• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * AppSocket backend for CUPS.
3  *
4  * Copyright © 2020-2024 by OpenPrinting.
5  * Copyright © 2007-2018 by Apple Inc.
6  * Copyright © 1997-2007 by Easy Software Products, all rights reserved.
7  *
8  * Licensed under Apache License v2.0.  See the file "LICENSE" for more
9  * information.
10  */
11 
12 /*
13  * Include necessary headers.
14  */
15 
16 #include <cups/http-private.h>
17 #include "backend-private.h"
18 #include <stdarg.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 
22 #ifdef _WIN32
23 #  include <winsock.h>
24 #else
25 #  include <unistd.h>
26 #  include <fcntl.h>
27 #  include <sys/socket.h>
28 #  include <netinet/in.h>
29 #  include <arpa/inet.h>
30 #  include <netdb.h>
31 #endif /* _WIN32 */
32 
33 
34 /*
35  * Local functions...
36  */
37 
38 static ssize_t	wait_bc(int device_fd, int secs);
39 
40 
41 /*
42  * 'main()' - Send a file to the printer or server.
43  *
44  * Usage:
45  *
46  *    printer-uri job-id user title copies options [file]
47  */
48 
49 int					/* O - Exit status */
main(int argc,char * argv[])50 main(int  argc,				/* I - Number of command-line arguments (6 or 7) */
51      char *argv[])			/* I - Command-line arguments */
52 {
53   const char	*device_uri;		/* Device URI */
54   char		scheme[255],		/* Scheme in URI */
55 		hostname[1024],		/* Hostname */
56 		username[255],		/* Username info (not used) */
57 		resource[1024],		/* Resource info (not used) */
58 		*options,		/* Pointer to options */
59 		*name,			/* Name of option */
60 		*value,			/* Value of option */
61 		sep;			/* Option separator */
62   int		print_fd;		/* Print file */
63   int		copies;			/* Number of copies to print */
64   time_t	start_time;		/* Time of first connect */
65   int		contimeout;		/* Connection timeout */
66   int		waiteof;		/* Wait for end-of-file? */
67   int		port;			/* Port number */
68   int		delay;			/* Delay for retries... */
69   int		device_fd;		/* AppSocket */
70   int		error;			/* Error code (if any) */
71   http_addrlist_t *addrlist,		/* Address list */
72 		*addr;			/* Connected address */
73   char		addrname[256];		/* Address name */
74   int		snmp_enabled = 1;	/* Is SNMP enabled? */
75   int		snmp_fd,		/* SNMP socket */
76 		start_count,		/* Page count via SNMP at start */
77 		page_count,		/* Page count via SNMP */
78 		have_supplies;		/* Printer supports supply levels? */
79   ssize_t	bytes = 0,		/* Initial bytes read */
80 		tbytes;			/* Total number of bytes written */
81   char		buffer[1024];		/* Initial print buffer */
82 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
83   struct sigaction action;		/* Actions for POSIX signals */
84 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
85 
86 
87  /*
88   * Make sure status messages are not buffered...
89   */
90 
91   setbuf(stderr, NULL);
92 
93  /*
94   * Ignore SIGPIPE signals...
95   */
96 
97 #ifdef HAVE_SIGSET
98   sigset(SIGPIPE, SIG_IGN);
99 #elif defined(HAVE_SIGACTION)
100   memset(&action, 0, sizeof(action));
101   action.sa_handler = SIG_IGN;
102   sigaction(SIGPIPE, &action, NULL);
103 #else
104   signal(SIGPIPE, SIG_IGN);
105 #endif /* HAVE_SIGSET */
106 
107  /*
108   * Check command-line...
109   */
110 
111   if (argc == 1)
112   {
113     printf("network socket \"Unknown\" \"%s\"\n",
114            _cupsLangString(cupsLangDefault(), _("AppSocket/HP JetDirect")));
115     return (CUPS_BACKEND_OK);
116   }
117   else if (argc != 6 && argc != 7)
118   {
119     _cupsLangPrintf(stderr,
120                     _("Usage: %s job-id user title copies options [file]"),
121                     argv[0]);
122     return (CUPS_BACKEND_FAILED);
123   }
124 
125  /*
126   * If we have 7 arguments, print the file named on the command-line.
127   * Otherwise, send stdin instead...
128   */
129 
130   if (argc == 6)
131   {
132     print_fd = 0;
133     copies   = 1;
134   }
135   else
136   {
137    /*
138     * Try to open the print file...
139     */
140 
141     if ((print_fd = open(argv[6], O_RDONLY)) < 0)
142     {
143       _cupsLangPrintError("ERROR", _("Unable to open print file"));
144       return (CUPS_BACKEND_FAILED);
145     }
146 
147     copies = atoi(argv[4]);
148   }
149 
150  /*
151   * Extract the hostname and port number from the URI...
152   */
153 
154   while ((device_uri = cupsBackendDeviceURI(argv)) == NULL)
155   {
156     _cupsLangPrintFilter(stderr, "INFO", _("Unable to locate printer."));
157     sleep(10);
158 
159     if (getenv("CLASS") != NULL)
160       return (CUPS_BACKEND_FAILED);
161   }
162 
163   httpSeparateURI(HTTP_URI_CODING_ALL, device_uri, scheme, sizeof(scheme),
164                   username, sizeof(username), hostname, sizeof(hostname), &port,
165 		  resource, sizeof(resource));
166 
167   if (port == 0)
168     port = 9100;	/* Default to HP JetDirect/Tektronix PhaserShare */
169 
170  /*
171   * Get options, if any...
172   */
173 
174   waiteof    = 1;
175   contimeout = 7 * 24 * 60 * 60;
176 
177   if ((options = strchr(resource, '?')) != NULL)
178   {
179    /*
180     * Yup, terminate the device name string and move to the first
181     * character of the options...
182     */
183 
184     *options++ = '\0';
185 
186    /*
187     * Parse options...
188     */
189 
190     while (*options)
191     {
192      /*
193       * Get the name...
194       */
195 
196       name = options;
197 
198       while (*options && *options != '=' && *options != '+' && *options != '&')
199         options ++;
200 
201       if ((sep = *options) != '\0')
202         *options++ = '\0';
203 
204       if (sep == '=')
205       {
206        /*
207         * Get the value...
208 	*/
209 
210         value = options;
211 
212 	while (*options && *options != '+' && *options != '&')
213 	  options ++;
214 
215         if (*options)
216 	  *options++ = '\0';
217       }
218       else
219         value = (char *)"";
220 
221      /*
222       * Process the option...
223       */
224 
225       if (!_cups_strcasecmp(name, "waiteof"))
226       {
227        /*
228         * Set the wait-for-eof value...
229 	*/
230 
231         waiteof = !value[0] || !_cups_strcasecmp(value, "on") ||
232 		  !_cups_strcasecmp(value, "yes") || !_cups_strcasecmp(value, "true");
233       }
234       else if (!_cups_strcasecmp(name, "snmp"))
235       {
236         /*
237          * Enable/disable SNMP stuff...
238          */
239 
240          snmp_enabled = !value[0] || !_cups_strcasecmp(value, "on") ||
241                         !_cups_strcasecmp(value, "yes") ||
242                         !_cups_strcasecmp(value, "true");
243       }
244       else if (!_cups_strcasecmp(name, "contimeout"))
245       {
246        /*
247         * Set the connection timeout...
248 	*/
249 
250 	if (atoi(value) > 0)
251 	  contimeout = atoi(value);
252       }
253     }
254   }
255 
256  /*
257   * Then try finding the remote host...
258   */
259 
260   start_time = time(NULL);
261 
262   addrlist = backendLookup(hostname, port, NULL);
263 
264  /*
265   * See if the printer supports SNMP...
266   */
267 
268   if (snmp_enabled)
269     snmp_fd = _cupsSNMPOpen(addrlist->addr.addr.sa_family);
270   else
271     snmp_fd = -1;
272 
273   if (snmp_fd >= 0)
274     have_supplies = !backendSNMPSupplies(snmp_fd, &(addrlist->addr),
275                                          &start_count, NULL);
276   else
277     have_supplies = start_count = 0;
278 
279  /*
280   * Wait for data from the filter...
281   */
282 
283   if (print_fd == 0)
284   {
285     if (!backendWaitLoop(snmp_fd, &(addrlist->addr), 1, backendNetworkSideCB))
286       return (CUPS_BACKEND_OK);
287     else if ((bytes = read(0, buffer, sizeof(buffer))) <= 0)
288       return (CUPS_BACKEND_OK);
289   }
290 
291  /*
292   * Connect to the printer...
293   */
294 
295   fprintf(stderr, "DEBUG: Connecting to %s:%d\n", hostname, port);
296   _cupsLangPrintFilter(stderr, "INFO", _("Connecting to printer."));
297 
298   for (delay = 5;;)
299   {
300     if ((addr = httpAddrConnect(addrlist, &device_fd)) == NULL)
301     {
302       error     = errno;
303       device_fd = -1;
304 
305       if (getenv("CLASS") != NULL)
306       {
307        /*
308         * If the CLASS environment variable is set, the job was submitted
309 	* to a class and not to a specific queue.  In this case, we want
310 	* to abort immediately so that the job can be requeued on the next
311 	* available printer in the class.
312 	*/
313 
314         _cupsLangPrintFilter(stderr, "INFO",
315 			     _("Unable to contact printer, queuing on next "
316 			       "printer in class."));
317 
318        /*
319         * Sleep 5 seconds to keep the job from requeuing too rapidly...
320 	*/
321 
322 	sleep(5);
323 
324         return (CUPS_BACKEND_FAILED);
325       }
326 
327       fprintf(stderr, "DEBUG: Connection error: %s\n", strerror(error));
328 
329       if (errno == ECONNREFUSED || errno == EHOSTDOWN || errno == EHOSTUNREACH || errno == ETIMEDOUT || errno == ENOTCONN)
330       {
331         if (contimeout && (time(NULL) - start_time) > contimeout)
332 	{
333 	  _cupsLangPrintFilter(stderr, "ERROR",
334 	                       _("The printer is not responding."));
335 	  return (CUPS_BACKEND_FAILED);
336 	}
337 
338 	switch (error)
339 	{
340 	  case EHOSTDOWN :
341 	      _cupsLangPrintFilter(stderr, "WARNING",
342 				   _("The printer may not exist or "
343 				     "is unavailable at this time."));
344 	      break;
345 
346 	  case EHOSTUNREACH :
347 	  default :
348 	      _cupsLangPrintFilter(stderr, "WARNING",
349 				   _("The printer is unreachable at this "
350 				     "time."));
351 	      break;
352 
353 	  case ECONNREFUSED :
354 	      _cupsLangPrintFilter(stderr, "WARNING",
355 	                           _("The printer is in use."));
356 	      break;
357         }
358 
359 	sleep((unsigned)delay);
360 
361 	if (delay < 30)
362 	  delay += 5;
363       }
364       else
365       {
366 	_cupsLangPrintFilter(stderr, "ERROR",
367 	                     _("The printer is not responding."));
368 	sleep(30);
369       }
370     }
371     else
372       break;
373   }
374 
375   fputs("STATE: -connecting-to-device\n", stderr);
376   _cupsLangPrintFilter(stderr, "INFO", _("Connected to printer."));
377 
378   fprintf(stderr, "DEBUG: Connected to %s:%d...\n",
379 	  httpAddrString(&(addr->addr), addrname, sizeof(addrname)),
380 	  httpAddrPort(&(addr->addr)));
381 
382  /*
383   * Print everything...
384   */
385 
386   tbytes = 0;
387 
388   if (bytes > 0)
389     tbytes += write(device_fd, buffer, (size_t)bytes);
390 
391   while (copies > 0 && tbytes >= 0)
392   {
393     copies --;
394 
395     if (print_fd != 0)
396     {
397       fputs("PAGE: 1 1\n", stderr);
398       lseek(print_fd, 0, SEEK_SET);
399     }
400 
401     if ((bytes = backendRunLoop(print_fd, device_fd, snmp_fd, &(addrlist->addr), 1, 0, backendNetworkSideCB)) < 0)
402       tbytes = -1;
403     else
404       tbytes = bytes;
405 
406     if (print_fd != 0 && tbytes >= 0)
407       _cupsLangPrintFilter(stderr, "INFO", _("Print file sent."));
408   }
409 
410   fputs("STATE: +cups-waiting-for-job-completed\n", stderr);
411 
412   if (waiteof && tbytes >= 0)
413   {
414    /*
415     * Shutdown the socket and wait for the other end to finish...
416     */
417 
418     _cupsLangPrintFilter(stderr, "INFO", _("Waiting for printer to finish."));
419 
420     shutdown(device_fd, 1);
421 
422     while (wait_bc(device_fd, 90) > 0);
423   }
424 
425  /*
426   * Collect the final page count as needed...
427   */
428 
429   if (have_supplies &&
430       !backendSNMPSupplies(snmp_fd, &(addrlist->addr), &page_count, NULL) &&
431       page_count > start_count)
432     fprintf(stderr, "PAGE: total %d\n", page_count - start_count);
433 
434  /*
435   * Close the socket connection...
436   */
437 
438   close(device_fd);
439 
440   httpAddrFreeList(addrlist);
441 
442  /*
443   * Close the input file and return...
444   */
445 
446   if (print_fd != 0)
447     close(print_fd);
448 
449   return (tbytes >= 0 ? CUPS_BACKEND_OK : CUPS_BACKEND_FAILED);
450 }
451 
452 
453 /*
454  * 'wait_bc()' - Wait for back-channel data...
455  */
456 
457 static ssize_t				/* O - # bytes read or -1 on error */
wait_bc(int device_fd,int secs)458 wait_bc(int device_fd,			/* I - Socket */
459         int secs)			/* I - Seconds to wait */
460 {
461   struct timeval timeout;		/* Timeout for select() */
462   fd_set	input;			/* Input set for select() */
463   ssize_t	bytes;			/* Number of back-channel bytes read */
464   char		buffer[1024];		/* Back-channel buffer */
465 
466 
467  /*
468   * Wait up to "secs" seconds for backchannel data...
469   */
470 
471   timeout.tv_sec  = secs;
472   timeout.tv_usec = 0;
473 
474   FD_ZERO(&input);
475   FD_SET(device_fd, &input);
476 
477   if (select(device_fd + 1, &input, NULL, NULL, &timeout) > 0)
478   {
479    /*
480     * Grab the data coming back and spit it out to stderr...
481     */
482 
483     if ((bytes = read(device_fd, buffer, sizeof(buffer))) > 0)
484     {
485       fprintf(stderr, "DEBUG: Received %d bytes of back-channel data\n",
486 	      (int)bytes);
487       cupsBackChannelWrite(buffer, (size_t)bytes, 1.0);
488     }
489 
490     return (bytes);
491   }
492   else
493     return (-1);
494 }
495