• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * LIBUSB interface code for CUPS.
3  *
4  * Copyright © 2020-2024 by OpenPrinting.
5  * Copyright © 2007-2019 by Apple Inc.
6  *
7  * Licensed under Apache License v2.0.  See the file "LICENSE" for more
8  * information.
9  */
10 
11 /*
12  * Include necessary headers...
13  */
14 
15 #include <libusb.h>
16 #include <cups/cups-private.h>
17 #include <cups/ppd-private.h>
18 #include <cups/dir.h>
19 #include <pthread.h>
20 #include <sys/select.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/time.h>
24 #include <unistd.h>
25 
26 
27 /*
28  * WAIT_EOF_DELAY is number of seconds we'll wait for responses from
29  * the printer after we've finished sending all the data
30  */
31 
32 #define WAIT_EOF			0
33 #define WAIT_EOF_DELAY			7
34 #define WAIT_SIDE_DELAY			3
35 #define DEFAULT_TIMEOUT			5000L
36 
37 
38 /*
39  * Local types...
40  */
41 
42 typedef struct usb_printer_s		/**** USB Printer Data ****/
43 {
44   struct libusb_device	*device;	/* Device info */
45   int			conf,		/* Configuration */
46 			origconf,	/* Original configuration */
47 			iface,		/* Interface */
48 			altset,		/* Alternate setting */
49 			write_endp,	/* Write endpoint */
50 			read_endp,	/* Read endpoint */
51 			protocol,	/* Protocol: 1 = Uni-di, 2 = Bi-di. */
52 			usblp_attached,	/* "usblp" kernel module attached? */
53 			reset_after_job;/* Set to 1 by print_device() */
54   unsigned		quirks;		/* Quirks flags */
55   struct libusb_device_handle *handle;	/* Open handle to device */
56 } usb_printer_t;
57 
58 typedef int (*usb_cb_t)(usb_printer_t *, const char *, const char *,
59                         const void *);
60 
61 typedef struct usb_globals_s		/* Global USB printer information */
62 {
63   usb_printer_t		*printer;	/* Printer */
64 
65   pthread_mutex_t	read_thread_mutex;
66   pthread_cond_t	read_thread_cond;
67   int			read_thread_stop;
68   int			read_thread_done;
69 
70   pthread_mutex_t	readwrite_lock_mutex;
71   pthread_cond_t	readwrite_lock_cond;
72   int			readwrite_lock;
73 
74   int			print_fd;	/* File descriptor to print */
75   ssize_t		print_bytes;	/* Print bytes read */
76 
77   int			wait_eof;
78   int			drain_output;	/* Drain all pending output */
79   int			bidi_flag;	/* 0=unidirectional, 1=bidirectional */
80 
81   pthread_mutex_t	sidechannel_thread_mutex;
82   pthread_cond_t	sidechannel_thread_cond;
83   int			sidechannel_thread_stop;
84   int			sidechannel_thread_done;
85 } usb_globals_t;
86 
87 /*
88  * Quirks: various printer quirks are handled by this structure and its flags.
89  *
90  * The quirks table used to be compiled into the backend but is now loaded from
91  * one or more files in the /usr/share/cups/usb directory.
92  */
93 
94 #define USB_QUIRK_BLACKLIST	0x0001	/* Does not conform to the spec */
95 #define USB_QUIRK_NO_REATTACH	0x0002	/* After printing we cannot re-attach
96 					   the usblp kernel module */
97 #define USB_QUIRK_SOFT_RESET	0x0004	/* After printing do a soft reset
98 					   for clean-up */
99 #define USB_QUIRK_UNIDIR	0x0008	/* Requires unidirectional mode */
100 #define USB_QUIRK_USB_INIT	0x0010	/* Needs vendor USB init string */
101 #define USB_QUIRK_VENDOR_CLASS	0x0020	/* Descriptor uses vendor-specific
102 					   Class or SubClass */
103 #define USB_QUIRK_DELAY_CLOSE	0x0040	/* Delay close */
104 #define USB_QUIRK_WHITELIST	0x0000	/* no quirks */
105 
106 
107 typedef struct usb_quirk_s		/* USB "quirk" information */
108 {
109   int		vendor_id,		/* Affected vendor ID */
110 		product_id;		/* Affected product ID or 0 for all */
111   unsigned	quirks;			/* Quirks bitfield */
112 } usb_quirk_t;
113 
114 
115 
116 
117 /*
118  * Globals...
119  */
120 
121 cups_array_t		*all_quirks;	/* Array of printer quirks */
122 usb_globals_t		g = { 0 };	/* Globals */
123 libusb_device		**all_list;	/* List of connected USB devices */
124 
125 
126 /*
127  * Local functions...
128  */
129 
130 static int		close_device(usb_printer_t *printer);
131 static int		compare_quirks(usb_quirk_t *a, usb_quirk_t *b);
132 static usb_printer_t	*find_device(usb_cb_t cb, const void *data);
133 static unsigned		find_quirks(int vendor_id, int product_id);
134 static int		get_device_id(usb_printer_t *printer, char *buffer,
135 			              size_t bufsize);
136 static int		list_cb(usb_printer_t *printer, const char *device_uri,
137 			        const char *device_id, const void *data);
138 static void		load_quirks(void);
139 static char		*make_device_uri(usb_printer_t *printer,
140 			                 const char *device_id,
141 					 char *uri, size_t uri_size);
142 static int		open_device(usb_printer_t *printer, int verbose);
143 static int		print_cb(usb_printer_t *printer, const char *device_uri,
144 			         const char *device_id, const void *data);
145 static void		*read_thread(void *reference);
146 static void		*sidechannel_thread(void *reference);
147 static void		soft_reset(void);
148 static int		soft_reset_printer(usb_printer_t *printer);
149 
150 
151 /*
152  * 'list_devices()' - List the available printers.
153  */
154 
155 void
list_devices(void)156 list_devices(void)
157 {
158   load_quirks();
159 
160   fputs("DEBUG: list_devices\n", stderr);
161   find_device(list_cb, NULL);
162 }
163 
164 
165 /*
166  * 'print_device()' - Print a file to a USB device.
167  */
168 
169 int					/* O - Exit status */
print_device(const char * uri,const char * hostname,const char * resource,char * options,int print_fd,int copies,int argc,char * argv[])170 print_device(const char *uri,		/* I - Device URI */
171              const char *hostname,	/* I - Hostname/manufacturer */
172              const char *resource,	/* I - Resource/modelname */
173 	     char       *options,	/* I - Device options/serial number */
174 	     int        print_fd,	/* I - File descriptor to print */
175 	     int        copies,		/* I - Copies to print */
176 	     int	argc,		/* I - Number of command-line arguments (6 or 7) */
177 	     char	*argv[])	/* I - Command-line arguments */
178 {
179   int	        bytes;			/* Bytes written */
180   ssize_t	total_bytes;		/* Total bytes written */
181   struct sigaction action;		/* Actions for POSIX signals */
182   int		status = CUPS_BACKEND_OK,
183 					/* Function results */
184 		iostatus;		/* Current IO status */
185   pthread_t	read_thread_id,		/* Read thread */
186 		sidechannel_thread_id;	/* Side-channel thread */
187   int		have_sidechannel = 0,	/* Was the side-channel thread started? */
188 		have_backchannel = 0;   /* Do we have a back channel? */
189   struct stat   sidechannel_info;	/* Side-channel file descriptor info */
190   unsigned char	print_buffer[8192],	/* Print data buffer */
191 		*print_ptr;		/* Pointer into print data buffer */
192   fd_set	input_set;		/* Input set for select() */
193   int		nfds;			/* Number of file descriptors */
194   struct timeval *timeout,		/* Timeout pointer */
195 		tv;			/* Time value */
196   struct timespec cond_timeout;		/* pthread condition timeout */
197   int		num_opts;		/* Number of options */
198   cups_option_t	*opts;			/* Options */
199   const char	*val;			/* Option value */
200 
201 
202   load_quirks();
203 
204  /*
205   * See if the side-channel descriptor is valid...
206   */
207 
208   have_sidechannel = !fstat(CUPS_SC_FD, &sidechannel_info) &&
209                      S_ISSOCK(sidechannel_info.st_mode);
210 
211   g.wait_eof = WAIT_EOF;
212 
213  /*
214   * Connect to the printer...
215   */
216 
217   fprintf(stderr, "DEBUG: Printing on printer with URI: %s\n", uri);
218   while ((g.printer = find_device(print_cb, uri)) == NULL)
219   {
220     _cupsLangPrintFilter(stderr, "INFO",
221 			 _("Waiting for printer to become available."));
222     sleep(5);
223   }
224 
225   g.print_fd = print_fd;
226 
227  /*
228   * Some devices need a reset after finishing a job, these devices are
229   * marked with the USB_QUIRK_SOFT_RESET quirk.
230   */
231   g.printer->reset_after_job = (g.printer->quirks & USB_QUIRK_SOFT_RESET ? 1 : 0);
232 
233  /*
234   * If we are printing data from a print driver on stdin, ignore SIGTERM
235   * so that the driver can finish out any page data, e.g. to eject the
236   * current page.  We only do this for stdin printing as otherwise there
237   * is no way to cancel a raw print job...
238   */
239 
240   if (!print_fd)
241   {
242     memset(&action, 0, sizeof(action));
243 
244     sigemptyset(&action.sa_mask);
245     action.sa_handler = SIG_IGN;
246     sigaction(SIGTERM, &action, NULL);
247   }
248 
249  /*
250   * Start the side channel thread if the descriptor is valid...
251   */
252 
253   pthread_mutex_init(&g.readwrite_lock_mutex, NULL);
254   pthread_cond_init(&g.readwrite_lock_cond, NULL);
255   g.readwrite_lock = 1;
256 
257   if (have_sidechannel)
258   {
259     g.sidechannel_thread_stop = 0;
260     g.sidechannel_thread_done = 0;
261 
262     pthread_cond_init(&g.sidechannel_thread_cond, NULL);
263     pthread_mutex_init(&g.sidechannel_thread_mutex, NULL);
264 
265     if (pthread_create(&sidechannel_thread_id, NULL, sidechannel_thread, NULL))
266     {
267       fprintf(stderr, "DEBUG: Fatal USB error.\n");
268       _cupsLangPrintFilter(stderr, "ERROR",
269 			   _("There was an unrecoverable USB error."));
270       fputs("DEBUG: Couldn't create side-channel thread.\n", stderr);
271       close_device(g.printer);
272       return (CUPS_BACKEND_STOP);
273     }
274   }
275 
276  /*
277   * Debug mode: If option "usb-unidir" is given, always deactivate
278   * backchannel
279   */
280 
281   num_opts = cupsParseOptions(argv[5], 0, &opts);
282   val = cupsGetOption("usb-unidir", num_opts, opts);
283   if (val && strcasecmp(val, "no") && strcasecmp(val, "off") &&
284       strcasecmp(val, "false"))
285   {
286     g.printer->read_endp = -1;
287     fprintf(stderr, "DEBUG: Forced uni-directional communication "
288 	    "via \"usb-unidir\" option.\n");
289   }
290 
291  /*
292   * Debug mode: If option "usb-no-reattach" is given, do not re-attach
293   * the usblp kernel module after the job has completed.
294   */
295 
296   val = cupsGetOption("usb-no-reattach", num_opts, opts);
297   if (val && strcasecmp(val, "no") && strcasecmp(val, "off") &&
298       strcasecmp(val, "false"))
299   {
300     g.printer->usblp_attached = 0;
301     fprintf(stderr, "DEBUG: Forced not re-attaching the usblp kernel module "
302 	    "after the job via \"usb-no-reattach\" option.\n");
303   }
304 
305  /*
306   * Get the read thread going...
307   */
308 
309   if (g.printer->read_endp != -1)
310   {
311     have_backchannel = 1;
312 
313     g.read_thread_stop = 0;
314     g.read_thread_done = 0;
315 
316     pthread_cond_init(&g.read_thread_cond, NULL);
317     pthread_mutex_init(&g.read_thread_mutex, NULL);
318 
319     if (pthread_create(&read_thread_id, NULL, read_thread, NULL))
320     {
321       fprintf(stderr, "DEBUG: Fatal USB error.\n");
322       _cupsLangPrintFilter(stderr, "ERROR",
323 			   _("There was an unrecoverable USB error."));
324       fputs("DEBUG: Couldn't create read thread.\n", stderr);
325       close_device(g.printer);
326       return (CUPS_BACKEND_STOP);
327     }
328   }
329   else
330     fprintf(stderr, "DEBUG: Uni-directional device/mode, back channel "
331 	    "deactivated.\n");
332 
333  /*
334   * The main thread sends the print file...
335   */
336 
337   g.drain_output = 0;
338   g.print_bytes	 = 0;
339   total_bytes	 = 0;
340   print_ptr	 = print_buffer;
341 
342   while (status == CUPS_BACKEND_OK && copies-- > 0)
343   {
344     _cupsLangPrintFilter(stderr, "INFO", _("Sending data to printer."));
345 
346     if (print_fd != STDIN_FILENO)
347     {
348       fputs("PAGE: 1 1\n", stderr);
349       lseek(print_fd, 0, SEEK_SET);
350     }
351 
352     while (status == CUPS_BACKEND_OK)
353     {
354       FD_ZERO(&input_set);
355 
356       if (!g.print_bytes)
357 	FD_SET(print_fd, &input_set);
358 
359      /*
360       * Calculate select timeout...
361       *   If we have data waiting to send timeout is 100ms.
362       *   else if we're draining print_fd timeout is 0.
363       *   else we're waiting forever...
364       */
365 
366       if (g.print_bytes)
367       {
368 	tv.tv_sec  = 0;
369 	tv.tv_usec = 100000;		/* 100ms */
370 	timeout    = &tv;
371       }
372       else if (g.drain_output)
373       {
374 	tv.tv_sec  = 0;
375 	tv.tv_usec = 0;
376 	timeout    = &tv;
377       }
378       else
379 	timeout = NULL;
380 
381      /*
382       * I/O is unlocked around select...
383       */
384 
385       pthread_mutex_lock(&g.readwrite_lock_mutex);
386       g.readwrite_lock = 0;
387       pthread_cond_signal(&g.readwrite_lock_cond);
388       pthread_mutex_unlock(&g.readwrite_lock_mutex);
389 
390       nfds = select(print_fd + 1, &input_set, NULL, NULL, timeout);
391 
392      /*
393       * Reacquire the lock...
394       */
395 
396       pthread_mutex_lock(&g.readwrite_lock_mutex);
397       while (g.readwrite_lock)
398 	pthread_cond_wait(&g.readwrite_lock_cond, &g.readwrite_lock_mutex);
399       g.readwrite_lock = 1;
400       pthread_mutex_unlock(&g.readwrite_lock_mutex);
401 
402       if (nfds < 0)
403       {
404 	if (errno == EINTR && total_bytes == 0)
405 	{
406 	  fputs("DEBUG: Received an interrupt before any bytes were "
407 	        "written, aborting.\n", stderr);
408 	  close_device(g.printer);
409           return (CUPS_BACKEND_OK);
410 	}
411 	else if (errno != EAGAIN && errno != EINTR)
412 	{
413 	  _cupsLangPrintFilter(stderr, "ERROR",
414 	                       _("Unable to read print data."));
415 	  perror("DEBUG: select");
416 	  close_device(g.printer);
417           return (CUPS_BACKEND_FAILED);
418 	}
419       }
420 
421      /*
422       * If drain output has finished send a response...
423       */
424 
425       if (g.drain_output && !nfds && !g.print_bytes)
426       {
427 	/* Send a response... */
428 	cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT, CUPS_SC_STATUS_OK, NULL, 0, 1.0);
429 	g.drain_output = 0;
430       }
431 
432      /*
433       * Check if we have print data ready...
434       */
435 
436       if (FD_ISSET(print_fd, &input_set))
437       {
438 	g.print_bytes = read(print_fd, print_buffer, sizeof(print_buffer));
439 
440 	if (g.print_bytes < 0)
441 	{
442 	 /*
443 	  * Read error - bail if we don't see EAGAIN or EINTR...
444 	  */
445 
446 	  if (errno != EAGAIN && errno != EINTR)
447 	  {
448 	    _cupsLangPrintFilter(stderr, "ERROR",
449 				 _("Unable to read print data."));
450 	    perror("DEBUG: read");
451 	    close_device(g.printer);
452 	    return (CUPS_BACKEND_FAILED);
453 	  }
454 
455 	  g.print_bytes = 0;
456 	}
457 	else if (g.print_bytes == 0)
458 	{
459 	 /*
460 	  * End of file, break out of the loop...
461 	  */
462 
463 	  break;
464 	}
465 
466 	print_ptr = print_buffer;
467 
468 	fprintf(stderr, "DEBUG: Read %d bytes of print data...\n",
469 		(int)g.print_bytes);
470       }
471 
472       if (g.print_bytes)
473       {
474 	iostatus = libusb_bulk_transfer(g.printer->handle,
475 					g.printer->write_endp,
476 					print_ptr, g.print_bytes,
477 					&bytes, 0);
478        /*
479 	* Ignore timeout errors, but retain the number of bytes written to
480 	* avoid sending duplicate data...
481 	*/
482 
483 	if (iostatus == LIBUSB_ERROR_TIMEOUT)
484 	{
485 	  fputs("DEBUG: Got USB transaction timeout during write.\n", stderr);
486 	  iostatus = 0;
487 	}
488 
489        /*
490         * If we've stalled, retry the write...
491 	*/
492 
493 	else if (iostatus == LIBUSB_ERROR_PIPE)
494 	{
495 	  fputs("DEBUG: Got USB pipe stalled during write.\n", stderr);
496 
497 	  iostatus = libusb_bulk_transfer(g.printer->handle,
498 					  g.printer->write_endp,
499 					  print_ptr, g.print_bytes,
500 					  &bytes, 0);
501 	}
502 
503        /*
504 	* Retry a write after an aborted write since we probably just got
505 	* SIGTERM...
506 	*/
507 
508 	else if (iostatus == LIBUSB_ERROR_INTERRUPTED)
509 	{
510 	  fputs("DEBUG: Got USB return aborted during write.\n", stderr);
511 
512 	  iostatus = libusb_bulk_transfer(g.printer->handle,
513 					  g.printer->write_endp,
514 					  print_ptr, g.print_bytes,
515 					  &bytes, 0);
516         }
517 
518 	if (iostatus)
519 	{
520 	 /*
521 	  * Write error - bail if we don't see an error we can retry...
522 	  */
523 
524 	  _cupsLangPrintFilter(stderr, "ERROR",
525 	                       _("Unable to send data to printer."));
526 	  fprintf(stderr, "DEBUG: libusb write operation returned %x.\n",
527 	          iostatus);
528 
529 	  status = CUPS_BACKEND_FAILED;
530 	  break;
531 	}
532 	else if (bytes > 0)
533 	{
534 	  fprintf(stderr, "DEBUG: Wrote %d bytes of print data...\n",
535 	          (int)bytes);
536 
537 	  g.print_bytes -= bytes;
538 	  print_ptr   += bytes;
539 	  total_bytes += bytes;
540 	}
541       }
542 
543       if (print_fd != 0 && status == CUPS_BACKEND_OK)
544 	fprintf(stderr, "DEBUG: Sending print file, " CUPS_LLFMT " bytes...\n",
545 		CUPS_LLCAST total_bytes);
546     }
547   }
548 
549   fprintf(stderr, "DEBUG: Sent " CUPS_LLFMT " bytes...\n",
550           CUPS_LLCAST total_bytes);
551 
552  /*
553   * Signal the side channel thread to exit...
554   */
555 
556   if (have_sidechannel)
557   {
558     close(CUPS_SC_FD);
559     pthread_mutex_lock(&g.readwrite_lock_mutex);
560     g.readwrite_lock = 0;
561     pthread_cond_signal(&g.readwrite_lock_cond);
562     pthread_mutex_unlock(&g.readwrite_lock_mutex);
563 
564     g.sidechannel_thread_stop = 1;
565     pthread_mutex_lock(&g.sidechannel_thread_mutex);
566 
567     if (!g.sidechannel_thread_done)
568     {
569       gettimeofday(&tv, NULL);
570       cond_timeout.tv_sec  = tv.tv_sec + WAIT_SIDE_DELAY;
571       cond_timeout.tv_nsec = tv.tv_usec * 1000;
572 
573       while (!g.sidechannel_thread_done)
574       {
575 	if (pthread_cond_timedwait(&g.sidechannel_thread_cond,
576 				   &g.sidechannel_thread_mutex,
577 				   &cond_timeout) != 0)
578 	  break;
579       }
580     }
581 
582     pthread_mutex_unlock(&g.sidechannel_thread_mutex);
583   }
584 
585  /*
586   * Signal the read thread to exit then wait 7 seconds for it to complete...
587   */
588 
589   if (have_backchannel)
590   {
591     g.read_thread_stop = 1;
592 
593     pthread_mutex_lock(&g.read_thread_mutex);
594 
595     if (!g.read_thread_done)
596     {
597       fputs("DEBUG: Waiting for read thread to exit...\n", stderr);
598 
599       gettimeofday(&tv, NULL);
600       cond_timeout.tv_sec  = tv.tv_sec + WAIT_EOF_DELAY;
601       cond_timeout.tv_nsec = tv.tv_usec * 1000;
602 
603       while (!g.read_thread_done)
604       {
605 	if (pthread_cond_timedwait(&g.read_thread_cond, &g.read_thread_mutex,
606 				   &cond_timeout) != 0)
607 	  break;
608       }
609 
610       /*
611        * If it didn't exit abort the pending read and wait an additional
612        * second...
613        */
614 
615       if (!g.read_thread_done)
616       {
617 	fputs("DEBUG: Read thread still active, aborting the pending read...\n",
618 	      stderr);
619 
620 	g.wait_eof = 0;
621 
622 	gettimeofday(&tv, NULL);
623 	cond_timeout.tv_sec  = tv.tv_sec + 1;
624 	cond_timeout.tv_nsec = tv.tv_usec * 1000;
625 
626 	while (!g.read_thread_done)
627 	{
628 	  if (pthread_cond_timedwait(&g.read_thread_cond, &g.read_thread_mutex,
629 				     &cond_timeout) != 0)
630 	    break;
631 	}
632       }
633     }
634 
635     pthread_mutex_unlock(&g.read_thread_mutex);
636   }
637 
638  /*
639   * Close the connection and input file and general clean up...
640   */
641 
642   if (g.printer->quirks & USB_QUIRK_DELAY_CLOSE)
643     sleep(1);
644 
645   close_device(g.printer);
646 
647  /*
648   * Clean up ....
649   */
650 
651   libusb_free_device_list(all_list, 1);
652   libusb_exit(NULL);
653 
654   return (status);
655 }
656 
657 
658 /*
659  * 'close_device()' - Close the connection to the USB printer.
660  */
661 
662 static int				/* I - 0 on success, -1 on failure */
close_device(usb_printer_t * printer)663 close_device(usb_printer_t *printer)	/* I - Printer */
664 {
665   struct libusb_device_descriptor devdesc;
666                                         /* Current device descriptor */
667   struct libusb_config_descriptor *confptr;
668                                         /* Pointer to current configuration */
669 
670 
671   if (printer->handle)
672   {
673    /*
674     * Release interfaces before closing so that we know all data is written
675     * to the device...
676     */
677 
678     int errcode;			/* Return value of libusb function */
679     int number1,			/* Interface number */
680 	number2;			/* Configuration number */
681 
682     errcode =
683       libusb_get_config_descriptor(printer->device, printer->conf, &confptr);
684     if (errcode >= 0)
685     {
686       number1 = confptr->interface[printer->iface].
687 	altsetting[printer->altset].bInterfaceNumber;
688       libusb_release_interface(printer->handle, number1);
689 
690       number2 = confptr->bConfigurationValue;
691 
692       libusb_free_config_descriptor(confptr);
693 
694      /*
695       * If we have changed the configuration from one valid configuration
696       * to another, restore the old one
697       */
698       if (printer->origconf > 0 && printer->origconf != number2)
699       {
700 	fprintf(stderr, "DEBUG: Restoring USB device configuration: %d -> %d\n",
701 		number2, printer->origconf);
702 	if ((errcode = libusb_set_configuration(printer->handle,
703 						printer->origconf)) < 0)
704 	{
705 	  if (errcode != LIBUSB_ERROR_BUSY)
706 	  {
707 	    errcode =
708 	      libusb_get_device_descriptor (printer->device, &devdesc);
709 	    if (errcode < 0)
710 	      fprintf(stderr,
711 		      "DEBUG: Failed to set configuration %d\n",
712 		      printer->origconf);
713 	    else
714 	      fprintf(stderr,
715 		      "DEBUG: Failed to set configuration %d for %04x:%04x\n",
716 		      printer->origconf, devdesc.idVendor, devdesc.idProduct);
717 	  }
718 	}
719       }
720 
721      /*
722       * Re-attach "usblp" kernel module if it was attached before using this
723       * device
724       */
725       if (printer->usblp_attached == 1)
726 	if (libusb_attach_kernel_driver(printer->handle, number1) < 0)
727 	{
728 	  errcode = libusb_get_device_descriptor (printer->device, &devdesc);
729 	  if (errcode < 0)
730 	    fprintf(stderr,
731 		    "DEBUG: Failed to re-attach \"usblp\" kernel module\n");
732 	  else
733 	    fprintf(stderr,
734 		    "DEBUG: Failed to re-attach \"usblp\" kernel module to "
735 		    "%04x:%04x\n", devdesc.idVendor, devdesc.idProduct);
736 	}
737     }
738     else
739       fprintf(stderr,
740 	      "DEBUG: Failed to get configuration descriptor %d\n",
741 	      printer->conf);
742 
743    /*
744     * Reset the device to clean up after the job
745     */
746 
747     if (printer->reset_after_job == 1)
748     {
749       if ((errcode = libusb_reset_device(printer->handle)) < 0)
750 	fprintf(stderr,
751 		"DEBUG: Device reset failed, error code: %d\n",
752 		errcode);
753       else
754 	fprintf(stderr,
755 		"DEBUG: Resetting printer.\n");
756     }
757 
758    /*
759     * Close the interface and return...
760     */
761 
762     libusb_close(printer->handle);
763     printer->handle = NULL;
764   }
765 
766   return (0);
767 }
768 
769 
770 /*
771  * 'compare_quirks()' - Compare two quirks entries.
772  */
773 
774 static int				/* O - Result of comparison */
compare_quirks(usb_quirk_t * a,usb_quirk_t * b)775 compare_quirks(usb_quirk_t *a,		/* I - First quirk entry */
776                usb_quirk_t *b)		/* I - Second quirk entry */
777 {
778   int result;				/* Result of comparison */
779 
780   if ((result = b->vendor_id - a->vendor_id) == 0)
781     result = b->product_id - a->product_id;
782 
783   return (result);
784 }
785 
786 
787 /*
788  * 'find_device()' - Find or enumerate USB printers.
789  */
790 
791 static usb_printer_t *			/* O - Found printer */
find_device(usb_cb_t cb,const void * data)792 find_device(usb_cb_t   cb,		/* I - Callback function */
793             const void *data)		/* I - User data for callback */
794 {
795   libusb_device         **list;         /* List of connected USB devices */
796   libusb_device         *device = NULL;	/* Current device */
797   struct libusb_device_descriptor devdesc;
798                                         /* Current device descriptor */
799   struct libusb_config_descriptor *confptr = NULL;
800                                         /* Pointer to current configuration */
801   const struct libusb_interface *ifaceptr = NULL;
802                                         /* Pointer to current interface */
803   const struct libusb_interface_descriptor *altptr = NULL;
804 					/* Pointer to current alternate setting */
805   const struct libusb_endpoint_descriptor *endpptr = NULL;
806 					/* Pointer to current endpoint */
807   ssize_t               err = 0,	/* Error code */
808                         numdevs,        /* number of connected devices */
809                         i = 0;
810   uint8_t		conf,		/* Current configuration */
811 			iface,		/* Current interface */
812 			altset,		/* Current alternate setting */
813 			protocol,	/* Current protocol */
814 			endp,		/* Current endpoint */
815 			read_endp,	/* Current read endpoint */
816 			write_endp;	/* Current write endpoint */
817   char			device_id[1024],/* IEEE-1284 device ID */
818 			device_uri[1024];
819 					/* Device URI */
820   static usb_printer_t	printer;	/* Current printer */
821 
822 
823  /*
824   * Initialize libusb...
825   */
826 
827   err = libusb_init(NULL);
828   if (err)
829   {
830     fprintf(stderr, "ERROR: Unable to initialize USB access via libusb, libusb error %i (%s)\n", (int)err, libusb_strerror((int)err));
831     return (NULL);
832   }
833 
834   numdevs = libusb_get_device_list(NULL, &list);
835   fprintf(stderr, "DEBUG: libusb_get_device_list=%d\n", (int)numdevs);
836 
837  /*
838   * Then loop through the devices it found...
839   */
840 
841   if (numdevs > 0)
842     for (i = 0; i < numdevs; i++)
843     {
844       device = list[i];
845 
846      /*
847       * Ignore devices with no configuration data and anything that is not
848       * a printer...
849       */
850 
851       if (libusb_get_device_descriptor(device, &devdesc) < 0)
852 	continue;
853 
854       if (!devdesc.bNumConfigurations || !devdesc.idVendor ||
855           !devdesc.idProduct)
856 	continue;
857 
858       printer.quirks = find_quirks(devdesc.idVendor, devdesc.idProduct);
859 
860      /*
861       * Ignore blacklisted printers...
862       */
863 
864       if (printer.quirks & USB_QUIRK_BLACKLIST)
865         continue;
866 
867       for (conf = 0; conf < devdesc.bNumConfigurations; conf ++)
868       {
869 	if (libusb_get_config_descriptor(device, conf, &confptr) < 0)
870 	  continue;
871         for (iface = 0, ifaceptr = confptr->interface;
872 	     iface < confptr->bNumInterfaces;
873 	     iface ++, ifaceptr ++)
874         {
875 	 /*
876 	  * Some printers offer multiple interfaces...
877 	  */
878 
879           protocol   = 0;
880 
881 	  for (altset = 0, altptr = ifaceptr->altsetting;
882 	       altset < ifaceptr->num_altsetting; // lgtm [cpp/comparison-with-wider-type]
883 	       altset ++, altptr ++)
884           {
885 	   /*
886 	    * Currently we only support unidirectional and bidirectional
887 	    * printers.  Future versions of this code will support the
888 	    * 1284.4 (packet mode) protocol as well.
889 	    */
890 
891 	    if (((altptr->bInterfaceClass != LIBUSB_CLASS_PRINTER ||
892 		  altptr->bInterfaceSubClass != 1) &&
893 		 ((printer.quirks & USB_QUIRK_VENDOR_CLASS) == 0)) ||
894 		(altptr->bInterfaceProtocol != 1 &&	/* Unidirectional */
895 		 altptr->bInterfaceProtocol != 2) ||	/* Bidirectional */
896 		altptr->bInterfaceProtocol < protocol)
897 	      continue;
898 
899 	    if (printer.quirks & USB_QUIRK_VENDOR_CLASS)
900 	      fprintf(stderr, "DEBUG: Printer does not report class 7 and/or "
901 		      "subclass 1 but works as a printer anyway\n");
902 
903 	    read_endp  = 0xff;
904 	    write_endp = 0xff;
905 
906 	    for (endp = 0, endpptr = altptr->endpoint;
907 	         endp < altptr->bNumEndpoints;
908 		 endp ++, endpptr ++)
909               if ((endpptr->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) ==
910 	              LIBUSB_TRANSFER_TYPE_BULK)
911 	      {
912 	        if (endpptr->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
913 		  read_endp = endp;
914 		else
915 		  write_endp = endp;
916 	      }
917 
918             if (write_endp != 0xff)
919 	    {
920 	     /*
921 	      * Save the best match so far...
922 	      */
923 
924               protocol           = altptr->bInterfaceProtocol;
925 	      printer.altset     = altset;
926 	      printer.write_endp = write_endp;
927 	      if (protocol > 1)
928 		printer.read_endp = read_endp;
929 	      else
930 		printer.read_endp = -1;
931 	    }
932 	  }
933 
934 	  if (protocol > 0)
935 	  {
936 	    printer.device   = device;
937 	    printer.conf     = conf;
938 	    printer.iface    = iface;
939 	    printer.protocol = protocol;
940 	    printer.handle   = NULL;
941 
942             if (!open_device(&printer, data != NULL))
943 	    {
944 	      get_device_id(&printer, device_id, sizeof(device_id));
945 	      make_device_uri(&printer, device_id, device_uri,
946 			      sizeof(device_uri));
947 
948 	      fprintf(stderr, "DEBUG2: Printer found with device ID: %s "
949 		      "Device URI: %s\n",
950 		      device_id, device_uri);
951 
952 	      if ((*cb)(&printer, device_uri, device_id, data))
953 	      {
954 		fprintf(stderr, "DEBUG: Device protocol: %d\n",
955 			printer.protocol);
956 		if (printer.quirks & USB_QUIRK_UNIDIR)
957 		{
958 		  printer.read_endp = -1;
959 		  fprintf(stderr, "DEBUG: Printer reports bi-di support "
960 			  "but in reality works only uni-directionally\n");
961 		}
962 		if (printer.read_endp != -1)
963 		{
964 		  printer.read_endp = confptr->interface[printer.iface].
965 					    altsetting[printer.altset].
966 					    endpoint[printer.read_endp].
967 					    bEndpointAddress;
968 		}
969 		else
970 		  fprintf(stderr, "DEBUG: Uni-directional USB communication "
971 			  "only!\n");
972 		printer.write_endp = confptr->interface[printer.iface].
973 					   altsetting[printer.altset].
974 					   endpoint[printer.write_endp].
975 					   bEndpointAddress;
976 		if (printer.quirks & USB_QUIRK_NO_REATTACH)
977 		{
978 		  printer.usblp_attached = 0;
979 		  fprintf(stderr, "DEBUG: Printer does not like usblp "
980 			  "kernel module to be re-attached after job\n");
981 		}
982 		libusb_free_config_descriptor(confptr);
983 		return (&printer);
984               }
985 
986               close_device(&printer);
987 	    }
988 	  }
989 	}
990 	libusb_free_config_descriptor(confptr);
991       }
992     }
993 
994  /*
995   * If we get this far without returning, then we haven't found a printer
996   * to print to...
997   */
998 
999  /*
1000   * Clean up ....
1001   */
1002 
1003   if (numdevs >= 0)
1004     libusb_free_device_list(list, 1);
1005   libusb_exit(NULL);
1006 
1007   return (NULL);
1008 }
1009 
1010 
1011 /*
1012  * 'find_quirks()' - Find the quirks for the given printer, if any.
1013  *
1014  * First looks for an exact match, then looks for the vendor ID wildcard match.
1015  */
1016 
1017 static unsigned				/* O - Quirks flags */
find_quirks(int vendor_id,int product_id)1018 find_quirks(int vendor_id,		/* I - Vendor ID */
1019             int product_id)		/* I - Product ID */
1020 {
1021   usb_quirk_t	key,			/* Search key */
1022 		*match;			/* Matching quirk entry */
1023 
1024 
1025   key.vendor_id  = vendor_id;
1026   key.product_id = product_id;
1027 
1028   if ((match = cupsArrayFind(all_quirks, &key)) != NULL)
1029     return (match->quirks);
1030 
1031   key.product_id = 0;
1032 
1033   if ((match = cupsArrayFind(all_quirks, &key)) != NULL)
1034     return (match->quirks);
1035 
1036   return (USB_QUIRK_WHITELIST);
1037 }
1038 
1039 
1040 /*
1041  * 'get_device_id()' - Get the IEEE-1284 device ID for the printer.
1042  */
1043 
1044 static int				/* O - 0 on success, -1 on error */
get_device_id(usb_printer_t * printer,char * buffer,size_t bufsize)1045 get_device_id(usb_printer_t *printer,	/* I - Printer */
1046               char          *buffer,	/* I - String buffer */
1047               size_t        bufsize)	/* I - Number of bytes in buffer */
1048 {
1049   size_t	length;				/* Length of device ID */
1050 
1051 
1052   if (libusb_control_transfer(printer->handle,
1053 			      LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_ENDPOINT_IN |
1054 			      LIBUSB_RECIPIENT_INTERFACE,
1055 			      0, printer->conf,
1056 			      (printer->iface << 8) | printer->altset,
1057 			      (unsigned char *)buffer, bufsize, 5000) < 0)
1058   {
1059     *buffer = '\0';
1060     return (-1);
1061   }
1062 
1063  /*
1064   * Extract the length of the device ID string from the first two
1065   * bytes.  The 1284 spec says the length is stored MSB first...
1066   */
1067 
1068   length = (((unsigned)buffer[0] & 255) << 8) | ((unsigned)buffer[1] & 255);
1069 
1070  /*
1071   * Check to see if the length is larger than our buffer or less than 14 bytes
1072   * (the minimum valid device ID is "MFG:x;MDL:y;" with 2 bytes for the length).
1073   *
1074   * If the length is out-of-range, assume that the vendor incorrectly
1075   * implemented the 1284 spec and re-read the length as LSB first,..
1076   */
1077 
1078   if (length > bufsize || length < 14)
1079     length = (((unsigned)buffer[1] & 255) << 8) | ((unsigned)buffer[0] & 255);
1080 
1081   if (length > bufsize)
1082     length = bufsize;
1083 
1084   if (length < 14)
1085   {
1086    /*
1087     * Invalid device ID, clear it!
1088     */
1089 
1090     *buffer = '\0';
1091     return (-1);
1092   }
1093 
1094   length -= 2;
1095 
1096  /*
1097   * Copy the device ID text to the beginning of the buffer and
1098   * nul-terminate.
1099   */
1100 
1101   memmove(buffer, buffer + 2, length);
1102   buffer[length] = '\0';
1103 
1104   return (0);
1105 }
1106 
1107 
1108 /*
1109  * 'list_cb()' - List USB printers for discovery.
1110  */
1111 
1112 static int				/* O - 0 to continue, 1 to stop */
list_cb(usb_printer_t * printer,const char * device_uri,const char * device_id,const void * data)1113 list_cb(usb_printer_t *printer,		/* I - Printer */
1114         const char    *device_uri,	/* I - Device URI */
1115         const char    *device_id,	/* I - IEEE-1284 device ID */
1116         const void    *data)		/* I - User data (not used) */
1117 {
1118   char	make_model[1024];		/* Make and model */
1119 
1120 
1121  /*
1122   * Get the device URI and make/model strings...
1123   */
1124 
1125   if (backendGetMakeModel(device_id, make_model, sizeof(make_model)))
1126     strlcpy(make_model, "Unknown", sizeof(make_model));
1127 
1128  /*
1129   * Report the printer...
1130   */
1131 
1132   cupsBackendReport("direct", device_uri, make_model, make_model, device_id,
1133                     NULL);
1134 
1135  /*
1136   * Keep going...
1137   */
1138 
1139   return (0);
1140 }
1141 
1142 
1143 /*
1144  * 'load_quirks()' - Load all quirks files in the /usr/share/cups/usb directory.
1145  */
1146 
1147 static void
load_quirks(void)1148 load_quirks(void)
1149 {
1150   const char	*datadir;		/* CUPS_DATADIR environment variable */
1151   char		filename[1024],		/* Filename */
1152 		line[1024];		/* Line from file */
1153   cups_dir_t	*dir;			/* Directory */
1154   cups_dentry_t	*dent;			/* Directory entry */
1155   cups_file_t	*fp;			/* Quirks file */
1156   usb_quirk_t	*quirk;			/* New quirk */
1157 
1158 
1159   all_quirks = cupsArrayNew((cups_array_func_t)compare_quirks, NULL);
1160 
1161   if ((datadir = getenv("CUPS_DATADIR")) == NULL)
1162     datadir = CUPS_DATADIR;
1163 
1164   snprintf(filename, sizeof(filename), "%s/usb", datadir);
1165   if ((dir = cupsDirOpen(filename)) == NULL)
1166   {
1167     perror(filename);
1168     return;
1169   }
1170 
1171   fprintf(stderr, "DEBUG: Loading USB quirks from \"%s\".\n", filename);
1172 
1173   while ((dent = cupsDirRead(dir)) != NULL)
1174   {
1175     if (!S_ISREG(dent->fileinfo.st_mode))
1176       continue;
1177 
1178     snprintf(filename, sizeof(filename), "%s/usb/%s", datadir, dent->filename);
1179     if ((fp = cupsFileOpen(filename, "r")) == NULL)
1180     {
1181       perror(filename);
1182       continue;
1183     }
1184 
1185     while (cupsFileGets(fp, line, sizeof(line)))
1186     {
1187      /*
1188       * Skip blank and comment lines...
1189       */
1190 
1191       if (line[0] == '#' || !line[0])
1192         continue;
1193 
1194      /*
1195       * Add a quirk...
1196       */
1197 
1198       if ((quirk = calloc(1, sizeof(usb_quirk_t))) == NULL)
1199       {
1200         perror("DEBUG: Unable to allocate memory for quirk");
1201         break;
1202       }
1203 
1204       if (sscanf(line, "%x%x", &quirk->vendor_id, &quirk->product_id) < 1)
1205       {
1206         fprintf(stderr, "DEBUG: Bad line: %s\n", line);
1207         free(quirk);
1208         continue;
1209       }
1210 
1211       if (strstr(line, " blacklist"))
1212         quirk->quirks |= USB_QUIRK_BLACKLIST;
1213 
1214       if (strstr(line, " delay-close"))
1215         quirk->quirks |= USB_QUIRK_DELAY_CLOSE;
1216 
1217       if (strstr(line, " no-reattach"))
1218         quirk->quirks |= USB_QUIRK_NO_REATTACH;
1219 
1220       if (strstr(line, " soft-reset"))
1221         quirk->quirks |= USB_QUIRK_SOFT_RESET;
1222 
1223       if (strstr(line, " unidir"))
1224         quirk->quirks |= USB_QUIRK_UNIDIR;
1225 
1226       if (strstr(line, " usb-init"))
1227         quirk->quirks |= USB_QUIRK_USB_INIT;
1228 
1229       if (strstr(line, " vendor-class"))
1230         quirk->quirks |= USB_QUIRK_VENDOR_CLASS;
1231 
1232       cupsArrayAdd(all_quirks, quirk);
1233     }
1234 
1235     cupsFileClose(fp);
1236   }
1237 
1238   fprintf(stderr, "DEBUG: Loaded %d quirks.\n", cupsArrayCount(all_quirks));
1239 
1240   cupsDirClose(dir);
1241 }
1242 
1243 
1244 /*
1245  * 'make_device_uri()' - Create a device URI for a USB printer.
1246  */
1247 
1248 static char *				/* O - Device URI */
make_device_uri(usb_printer_t * printer,const char * device_id,char * uri,size_t uri_size)1249 make_device_uri(
1250     usb_printer_t *printer,		/* I - Printer */
1251     const char    *device_id,		/* I - IEEE-1284 device ID */
1252     char          *uri,			/* I - Device URI buffer */
1253     size_t        uri_size)		/* I - Size of device URI buffer */
1254 {
1255   struct libusb_device_descriptor devdesc;
1256                                         /* Current device descriptor */
1257   char		options[1024];		/* Device URI options */
1258   int		num_values;		/* Number of 1284 parameters */
1259   cups_option_t	*values;		/* 1284 parameters */
1260   const char	*mfg,			/* Manufacturer */
1261 		*mdl,			/* Model */
1262 		*des = NULL,		/* Description */
1263 		*sern = NULL;		/* Serial number */
1264   size_t	mfglen;			/* Length of manufacturer string */
1265   char		tempmdl[256],		/* Temporary model string */
1266 		tempmfg[256],		/* Temporary manufacturer string */
1267 		tempsern[256],		/* Temporary serial number string */
1268 		*tempptr;		/* Pointer into temp string */
1269 
1270 
1271  /*
1272   * Get the make, model, and serial numbers...
1273   */
1274 
1275   num_values = _cupsGet1284Values(device_id, &values);
1276 
1277   memset(&devdesc, 0, sizeof(devdesc));
1278 
1279   if (libusb_get_device_descriptor(printer->device, &devdesc) >= 0 && devdesc.iSerialNumber)
1280   {
1281     // Try getting the serial number from the device itself...
1282     int length = libusb_get_string_descriptor_ascii(printer->handle, devdesc.iSerialNumber, (unsigned char *)tempsern, sizeof(tempsern) - 1);
1283     if (length > 0)
1284     {
1285       tempsern[length] = '\0';
1286       sern             = tempsern;
1287 
1288       fprintf(stderr, "DEBUG2: iSerialNumber=\"%s\"\n", tempsern);
1289     }
1290     else
1291       fputs("DEBUG2: iSerialNumber could not be read.\n", stderr);
1292   }
1293   else
1294     fputs("DEBUG2: iSerialNumber is not present.\n", stderr);
1295 
1296 #if 0
1297   if (!sern)
1298   {
1299     // Fall back on serial number from IEEE-1284 device ID, which on some
1300     // printers (Issue #170) is a bogus hardcoded number.
1301     if ((sern = cupsGetOption("SERIALNUMBER", num_values, values)) == NULL)
1302       if ((sern = cupsGetOption("SERN", num_values, values)) == NULL)
1303 	sern = cupsGetOption("SN", num_values, values);
1304   }
1305 #endif // 0
1306 
1307   if ((mfg = cupsGetOption("MANUFACTURER", num_values, values)) == NULL)
1308   {
1309     if ((mfg = cupsGetOption("MFG", num_values, values)) == NULL && devdesc.iManufacturer)
1310     {
1311       int length = libusb_get_string_descriptor_ascii(printer->handle, devdesc.iManufacturer, (unsigned char *)tempmfg, sizeof(tempmfg) - 1);
1312       if (length > 0)
1313       {
1314 	tempmfg[length] = '\0';
1315 	mfg             = tempmfg;
1316       }
1317     }
1318   }
1319 
1320   if ((mdl = cupsGetOption("MODEL", num_values, values)) == NULL)
1321   {
1322     if ((mdl = cupsGetOption("MDL", num_values, values)) == NULL && devdesc.iProduct)
1323     {
1324       int length = libusb_get_string_descriptor_ascii(printer->handle, devdesc.iProduct, (unsigned char *)tempmdl, sizeof(tempmdl) - 1);
1325       if (length > 0)
1326       {
1327 	tempmdl[length] = '\0';
1328 	mdl             = tempmdl;
1329       }
1330     }
1331   }
1332 
1333  /*
1334   * To maintain compatibility with the original character device backend on
1335   * Linux and *BSD, map manufacturer names...
1336   */
1337 
1338   if (mfg)
1339   {
1340     if (!_cups_strcasecmp(mfg, "Hewlett-Packard"))
1341       mfg = "HP";
1342     else if (!_cups_strcasecmp(mfg, "Lexmark International"))
1343       mfg = "Lexmark";
1344   }
1345   else
1346   {
1347    /*
1348     * No manufacturer?  Use the model string or description...
1349     */
1350 
1351     if (mdl)
1352       _ppdNormalizeMakeAndModel(mdl, tempmfg, sizeof(tempmfg));
1353     else if ((des = cupsGetOption("DESCRIPTION", num_values, values)) != NULL ||
1354              (des = cupsGetOption("DES", num_values, values)) != NULL)
1355       _ppdNormalizeMakeAndModel(des, tempmfg, sizeof(tempmfg));
1356     else
1357       strlcpy(tempmfg, "Unknown", sizeof(tempmfg));
1358 
1359     if ((tempptr = strchr(tempmfg, ' ')) != NULL)
1360       *tempptr = '\0';
1361 
1362     mfg = tempmfg;
1363   }
1364 
1365   if (!mdl)
1366   {
1367    /*
1368     * No model?  Use description...
1369     */
1370     if (des)
1371       mdl = des; /* We remove the manufacturer name below */
1372     else if (!strncasecmp(mfg, "Unknown", 7))
1373       mdl = "Printer";
1374     else
1375       mdl = "Unknown Model";
1376   }
1377 
1378   mfglen = strlen(mfg);
1379 
1380   if (!strncasecmp(mdl, mfg, mfglen) && _cups_isspace(mdl[mfglen]))
1381   {
1382     mdl += mfglen + 1;
1383 
1384     while (_cups_isspace(*mdl))
1385       mdl ++;
1386   }
1387 
1388  /*
1389   * Generate the device URI from the manufacturer, model, serial number,
1390   * and interface number...
1391   */
1392 
1393   if (sern)
1394   {
1395     if (printer->iface > 0)
1396       snprintf(options, sizeof(options), "?serial=%s&interface=%d", sern,
1397                printer->iface);
1398     else
1399       snprintf(options, sizeof(options), "?serial=%s", sern);
1400   }
1401   else if (printer->iface > 0)
1402     snprintf(options, sizeof(options), "?interface=%d", printer->iface);
1403   else
1404     options[0] = '\0';
1405 
1406   httpAssembleURIf(HTTP_URI_CODING_ALL, uri, uri_size, "usb", NULL, mfg, 0,
1407 		   "/%s%s", mdl, options);
1408 
1409   cupsFreeOptions(num_values, values);
1410 
1411   return (uri);
1412 }
1413 
1414 
1415 /*
1416  * 'open_device()' - Open a connection to the USB printer.
1417  */
1418 
1419 static int				/* O - 0 on success, -1 on error */
open_device(usb_printer_t * printer,int verbose)1420 open_device(usb_printer_t *printer,	/* I - Printer */
1421             int           verbose)	/* I - Update connecting-to-device state? */
1422 {
1423   struct libusb_device_descriptor devdesc;
1424                                         /* Current device descriptor */
1425   struct libusb_config_descriptor *confptr = NULL;
1426                                         /* Pointer to current configuration */
1427   int	number1 = -1,			/* Configuration/interface/altset */
1428         number2 = -1,			/* numbers */
1429         errcode = 0;
1430   unsigned char	current;			/* Current configuration */
1431 
1432 
1433  /*
1434   * Return immediately if we are already connected...
1435   */
1436 
1437   if (printer->handle)
1438     return (0);
1439 
1440  /*
1441   * Try opening the printer...
1442   */
1443 
1444   if ((errcode = libusb_open(printer->device, &printer->handle)) < 0)
1445   {
1446     fprintf(stderr, "DEBUG: Failed to open device, code: %d\n",
1447 	    errcode);
1448     return (-1);
1449   }
1450 
1451   printer->usblp_attached = 0;
1452   printer->reset_after_job = 0;
1453 
1454   if (verbose)
1455     fputs("STATE: +connecting-to-device\n", stderr);
1456 
1457   if ((errcode = libusb_get_device_descriptor(printer->device, &devdesc)) < 0)
1458   {
1459     fprintf(stderr, "DEBUG: Failed to get device descriptor, code: %d\n",
1460 	    errcode);
1461     goto error;
1462   }
1463 
1464  /*
1465   * Get the "usblp" kernel module out of the way. This backend only
1466   * works without the module attached.
1467   */
1468 
1469   errcode = libusb_kernel_driver_active(printer->handle, printer->iface);
1470   if (errcode == 0)
1471     printer->usblp_attached = 0;
1472   else if (errcode == 1)
1473   {
1474     printer->usblp_attached = 1;
1475     if ((errcode =
1476 	 libusb_detach_kernel_driver(printer->handle, printer->iface)) < 0)
1477     {
1478       fprintf(stderr, "DEBUG: Failed to detach \"usblp\" module from %04x:%04x\n",
1479 	      devdesc.idVendor, devdesc.idProduct);
1480       goto error;
1481     }
1482   }
1483   else
1484   {
1485     printer->usblp_attached = 0;
1486 
1487     if (errcode != LIBUSB_ERROR_NOT_SUPPORTED)
1488     {
1489       fprintf(stderr,
1490               "DEBUG: Failed to check whether %04x:%04x has the \"usblp\" "
1491               "kernel module attached\n", devdesc.idVendor, devdesc.idProduct);
1492       goto error;
1493     }
1494   }
1495 
1496  /*
1497   * Set the desired configuration, but only if it needs changing. Some
1498   * printers (e.g., Samsung) don't like libusb_set_configuration. It will
1499   * succeed, but the following print job is sometimes silently lost by the
1500   * printer.
1501   */
1502 
1503   if (libusb_control_transfer(printer->handle,
1504                 LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_ENDPOINT_IN |
1505 		LIBUSB_RECIPIENT_DEVICE,
1506 		8, /* GET_CONFIGURATION */
1507 		0, 0, &current, 1, 5000) < 0)
1508     current = 0;			/* Assume not configured */
1509 
1510   printer->origconf = current;
1511 
1512   if ((errcode =
1513        libusb_get_config_descriptor (printer->device, printer->conf, &confptr))
1514       < 0)
1515   {
1516     fprintf(stderr, "DEBUG: Failed to get config descriptor for %04x:%04x\n",
1517 	    devdesc.idVendor, devdesc.idProduct);
1518     goto error;
1519   }
1520   number1 = confptr->bConfigurationValue;
1521 
1522   if (number1 != current)
1523   {
1524     fprintf(stderr, "DEBUG: Switching USB device configuration: %d -> %d\n",
1525 	    current, number1);
1526     if ((errcode = libusb_set_configuration(printer->handle, number1)) < 0)
1527     {
1528      /*
1529       * If the set fails, chances are that the printer only supports a
1530       * single configuration.  Technically these printers don't conform to
1531       * the USB printer specification, but otherwise they'll work...
1532       */
1533 
1534       if (errcode != LIBUSB_ERROR_BUSY)
1535         fprintf(stderr, "DEBUG: Failed to set configuration %d for %04x:%04x\n",
1536 		number1, devdesc.idVendor, devdesc.idProduct);
1537     }
1538   }
1539 
1540  /*
1541   * Claim interfaces as needed...
1542   */
1543 
1544   number1 = confptr->interface[printer->iface].
1545     altsetting[printer->altset].bInterfaceNumber;
1546 
1547   while ((errcode = libusb_claim_interface(printer->handle, number1)) < 0)
1548   {
1549     if (errcode != LIBUSB_ERROR_BUSY)
1550     {
1551       fprintf(stderr,
1552               "DEBUG: Failed to claim interface %d for %04x:%04x: %s\n",
1553               number1, devdesc.idVendor, devdesc.idProduct, strerror(errno));
1554 
1555       goto error;
1556     }
1557     else if ((errcode = libusb_detach_kernel_driver(printer->handle, printer->iface)) < 0)
1558     {
1559       fprintf(stderr,
1560               "DEBUG: Failed to detach \"usblp\" module from %04x:%04x\n",
1561               devdesc.idVendor, devdesc.idProduct);
1562 
1563       goto error;
1564     }
1565 
1566     sleep (1);
1567   }
1568 
1569  /*
1570   * Set alternate setting, but only if there is more than one option.  Some
1571   * printers (e.g., Samsung) don't like usb_set_altinterface.
1572   */
1573 
1574   if (confptr->interface[printer->iface].num_altsetting > 1)
1575   {
1576     number1 = confptr->interface[printer->iface].
1577                  altsetting[printer->altset].bInterfaceNumber;
1578     number2 = confptr->interface[printer->iface].
1579                  altsetting[printer->altset].bAlternateSetting;
1580 
1581     while ((errcode =
1582 	    libusb_set_interface_alt_setting(printer->handle, number1, number2))
1583 	   < 0)
1584     {
1585       if (errcode != LIBUSB_ERROR_BUSY)
1586       {
1587         fprintf(stderr,
1588                 "DEBUG: Failed to set alternate interface %d for %04x:%04x: "
1589                 "%s\n",
1590                 number2, devdesc.idVendor, devdesc.idProduct, strerror(errno));
1591 
1592 	goto error;
1593       }
1594     }
1595   }
1596 
1597   libusb_free_config_descriptor(confptr);
1598 
1599   if (verbose)
1600     fputs("STATE: -connecting-to-device\n", stderr);
1601 
1602   return (0);
1603 
1604  /*
1605   * If we get here, there was a hard error...
1606   */
1607 
1608   error:
1609 
1610   if (verbose)
1611     fputs("STATE: -connecting-to-device\n", stderr);
1612 
1613   libusb_close(printer->handle);
1614   printer->handle = NULL;
1615 
1616   return (-1);
1617 }
1618 
1619 
1620 /*
1621  * 'print_cb()' - Find a USB printer for printing.
1622  */
1623 
1624 static int				/* O - 0 to continue, 1 to stop (found) */
print_cb(usb_printer_t * printer,const char * device_uri,const char * device_id,const void * data)1625 print_cb(usb_printer_t *printer,	/* I - Printer */
1626          const char    *device_uri,	/* I - Device URI */
1627          const char    *device_id,	/* I - IEEE-1284 device ID */
1628          const void    *data)		/* I - User data (make, model, S/N) */
1629 {
1630   char	requested_uri[1024],		/* Requested URI */
1631 	*requested_ptr,			/* Pointer into requested URI */
1632 	detected_uri[1024],		/* Detected URI */
1633 	*detected_ptr;			/* Pointer into detected URI */
1634 
1635 
1636  /*
1637   * If we have an exact match, stop now...
1638   */
1639 
1640   if (!strcmp((char *)data, device_uri))
1641     return (1);
1642 
1643  /*
1644   * Work on copies of the URIs...
1645   */
1646 
1647   strlcpy(requested_uri, (char *)data, sizeof(requested_uri));
1648   strlcpy(detected_uri, device_uri, sizeof(detected_uri));
1649 
1650  /*
1651   * libusb-discovered URIs can have an "interface" specification and this
1652   * never happens for usblp-discovered URIs, so remove the "interface"
1653   * specification from the URI which we are checking currently. This way a
1654   * queue for a usblp-discovered printer can now be accessed via libusb.
1655   *
1656   * Similarly, strip "?serial=NNN...NNN" as needed.
1657   */
1658 
1659   if ((requested_ptr = strstr(requested_uri, "?interface=")) == NULL)
1660     requested_ptr = strstr(requested_uri, "&interface=");
1661   if ((detected_ptr = strstr(detected_uri, "?interface=")) == NULL)
1662     detected_ptr = strstr(detected_uri, "&interface=");
1663 
1664   if (!requested_ptr && detected_ptr)
1665   {
1666    /*
1667     * Strip "[?&]interface=nnn" from the detected printer.
1668     */
1669 
1670     *detected_ptr = '\0';
1671   }
1672   else if (requested_ptr && !detected_ptr)
1673   {
1674    /*
1675     * Strip "[?&]interface=nnn" from the requested printer.
1676     */
1677 
1678     *requested_ptr = '\0';
1679   }
1680 
1681   if ((requested_ptr = strstr(requested_uri, "?serial=?")) != NULL)
1682   {
1683    /*
1684     * Strip "?serial=?" from the requested printer.  This is a special
1685     * case, as "?serial=?" means no serial number and not the serial
1686     * number '?'.  This is not covered by the checks below...
1687     */
1688 
1689     *requested_ptr = '\0';
1690   }
1691 
1692   if ((requested_ptr = strstr(requested_uri, "?serial=")) == NULL &&
1693       (detected_ptr = strstr(detected_uri, "?serial=")) != NULL)
1694   {
1695    /*
1696     * Strip "?serial=nnn" from the detected printer.
1697     */
1698 
1699     *detected_ptr = '\0';
1700   }
1701   else if (requested_ptr && !detected_ptr)
1702   {
1703    /*
1704     * Strip "?serial=nnn" from the requested printer.
1705     */
1706 
1707     *requested_ptr = '\0';
1708   }
1709 
1710   return (!strcmp(requested_uri, detected_uri));
1711 }
1712 
1713 
1714 /*
1715  * 'read_thread()' - Thread to read the backchannel data on.
1716  */
1717 
read_thread(void * reference)1718 static void *read_thread(void *reference)
1719 {
1720   unsigned char		readbuffer[512];
1721   int			rbytes;
1722   int			readstatus;
1723 
1724 
1725   (void)reference;
1726 
1727   do
1728   {
1729    /*
1730     * Try reading from the OUT (to host) endpoint...
1731     */
1732 
1733     rbytes     = sizeof(readbuffer);
1734     readstatus = libusb_bulk_transfer(g.printer->handle,
1735 				      g.printer->read_endp,
1736 				      readbuffer, rbytes,
1737 				      &rbytes, 60000);
1738     if (readstatus == LIBUSB_SUCCESS && rbytes > 0)
1739     {
1740       fprintf(stderr, "DEBUG: Read %d bytes of back-channel data...\n", (int)rbytes);
1741       cupsBackChannelWrite((const char *)readbuffer, (size_t)rbytes, 1.0);
1742     }
1743     else if (readstatus == LIBUSB_ERROR_TIMEOUT)
1744       fputs("DEBUG: Got USB transaction timeout during read.\n", stderr);
1745     else if (readstatus == LIBUSB_ERROR_PIPE)
1746       fputs("DEBUG: Got USB pipe stalled during read.\n", stderr);
1747     else if (readstatus == LIBUSB_ERROR_INTERRUPTED)
1748       fputs("DEBUG: Got USB return aborted during read.\n", stderr);
1749 
1750    /*
1751     * Make sure this loop executes no more than once every 250 milliseconds...
1752     */
1753 
1754     if ((readstatus != LIBUSB_SUCCESS || rbytes == 0) &&
1755 	 (g.wait_eof || !g.read_thread_stop))
1756       usleep(250000);
1757   }
1758   while (g.wait_eof || !g.read_thread_stop);
1759 
1760  /*
1761   * Let the main thread know that we have completed the read thread...
1762   */
1763 
1764   pthread_mutex_lock(&g.read_thread_mutex);
1765   g.read_thread_done = 1;
1766   pthread_cond_signal(&g.read_thread_cond);
1767   pthread_mutex_unlock(&g.read_thread_mutex);
1768 
1769   return (NULL);
1770 }
1771 
1772 
1773 /*
1774  * 'sidechannel_thread()' - Handle side-channel requests.
1775  */
1776 
1777 static void*
sidechannel_thread(void * reference)1778 sidechannel_thread(void *reference)
1779 {
1780   cups_sc_command_t	command;	/* Request command */
1781   cups_sc_status_t	status;		/* Request/response status */
1782   char			data[2048];	/* Request/response data */
1783   int			datalen;	/* Request/response data size */
1784 
1785 
1786   (void)reference;
1787 
1788   do
1789   {
1790     datalen = sizeof(data);
1791 
1792     if (cupsSideChannelRead(&command, &status, data, &datalen, 1.0))
1793     {
1794       if (status == CUPS_SC_STATUS_TIMEOUT)
1795 	continue;
1796       else
1797 	break;
1798     }
1799 
1800     switch (command)
1801     {
1802       case CUPS_SC_CMD_SOFT_RESET:	/* Do a soft reset */
1803 	  fputs("DEBUG: CUPS_SC_CMD_SOFT_RESET received from driver...\n",
1804 		stderr);
1805 
1806 	  soft_reset();
1807 	  cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, NULL, 0, 1.0);
1808 	  fputs("DEBUG: Returning status CUPS_STATUS_OK with no bytes...\n",
1809 		stderr);
1810 	  break;
1811 
1812       case CUPS_SC_CMD_DRAIN_OUTPUT:	/* Drain all pending output */
1813 	  fputs("DEBUG: CUPS_SC_CMD_DRAIN_OUTPUT received from driver...\n",
1814 		stderr);
1815 
1816 	  g.drain_output = 1;
1817 	  break;
1818 
1819       case CUPS_SC_CMD_GET_BIDI:	/* Is the connection bidirectional? */
1820 	  fputs("DEBUG: CUPS_SC_CMD_GET_BIDI received from driver...\n",
1821 		stderr);
1822 
1823 	  data[0] = (g.printer->protocol >= 2 ? 1 : 0);
1824 	  cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, data, 1, 1.0);
1825 
1826 	  fprintf(stderr,
1827 	          "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
1828 		  data[0]);
1829 	  break;
1830 
1831       case CUPS_SC_CMD_GET_DEVICE_ID:	/* Return IEEE-1284 device ID */
1832 	  fputs("DEBUG: CUPS_SC_CMD_GET_DEVICE_ID received from driver...\n",
1833 		stderr);
1834 
1835 	  datalen = sizeof(data);
1836 	  if (get_device_id(g.printer, data, sizeof(data)))
1837 	  {
1838 	    status  = CUPS_SC_STATUS_IO_ERROR;
1839 	    datalen = 0;
1840 	  }
1841 	  else
1842 	  {
1843 	    status  = CUPS_SC_STATUS_OK;
1844 	    datalen = strlen(data);
1845 	  }
1846 	  cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, data, datalen, 1.0);
1847 
1848           if (datalen < sizeof(data))
1849 	    data[datalen] = '\0';
1850 	  else
1851 	    data[sizeof(data) - 1] = '\0';
1852 
1853 	  fprintf(stderr,
1854 	          "DEBUG: Returning CUPS_SC_STATUS_OK with %d bytes (%s)...\n",
1855 		  datalen, data);
1856 	  break;
1857 
1858       case CUPS_SC_CMD_GET_STATE:	/* Return device state */
1859 	  fputs("DEBUG: CUPS_SC_CMD_GET_STATE received from driver...\n",
1860 		stderr);
1861 
1862 	  data[0] = CUPS_SC_STATE_ONLINE;
1863 	  cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, data, 1, 1.0);
1864 
1865 	  fprintf(stderr,
1866 	          "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
1867 		  data[0]);
1868 	  break;
1869 
1870       case CUPS_SC_CMD_GET_CONNECTED:	/* Return whether device is
1871 					   connected */
1872 	  fputs("DEBUG: CUPS_SC_CMD_GET_CONNECTED received from driver...\n",
1873 		stderr);
1874 
1875 	  data[0] = (g.printer->handle ? 1 : 0);
1876 	  cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, data, 1, 1.0);
1877 
1878 	  fprintf(stderr,
1879 	          "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
1880 		  data[0]);
1881 	  break;
1882 
1883       default:
1884 	  fprintf(stderr, "DEBUG: Unknown side-channel command (%d) received "
1885 			  "from driver...\n", command);
1886 
1887 	  cupsSideChannelWrite(command, CUPS_SC_STATUS_NOT_IMPLEMENTED,
1888 			       NULL, 0, 1.0);
1889 
1890 	  fputs("DEBUG: Returned CUPS_SC_STATUS_NOT_IMPLEMENTED with no bytes...\n",
1891 		stderr);
1892 	  break;
1893     }
1894   }
1895   while (!g.sidechannel_thread_stop);
1896 
1897   pthread_mutex_lock(&g.sidechannel_thread_mutex);
1898   g.sidechannel_thread_done = 1;
1899   pthread_cond_signal(&g.sidechannel_thread_cond);
1900   pthread_mutex_unlock(&g.sidechannel_thread_mutex);
1901 
1902   return (NULL);
1903 }
1904 
1905 
1906 /*
1907  * 'soft_reset()' - Send a soft reset to the device.
1908  */
1909 
1910 static void
soft_reset(void)1911 soft_reset(void)
1912 {
1913   fd_set	  input_set;		/* Input set for select() */
1914   struct timeval  tv;			/* Time value */
1915   char		  buffer[2048];		/* Buffer */
1916   struct timespec cond_timeout;		/* pthread condition timeout */
1917 
1918 
1919  /*
1920   * Send an abort once a second until the I/O lock is released by the main
1921   * thread...
1922   */
1923 
1924   pthread_mutex_lock(&g.readwrite_lock_mutex);
1925   while (g.readwrite_lock)
1926   {
1927     gettimeofday(&tv, NULL);
1928     cond_timeout.tv_sec  = tv.tv_sec + 1;
1929     cond_timeout.tv_nsec = tv.tv_usec * 1000;
1930 
1931     while (g.readwrite_lock)
1932     {
1933       if (pthread_cond_timedwait(&g.readwrite_lock_cond,
1934 				 &g.readwrite_lock_mutex,
1935 				 &cond_timeout) != 0)
1936 	break;
1937     }
1938   }
1939 
1940   g.readwrite_lock = 1;
1941   pthread_mutex_unlock(&g.readwrite_lock_mutex);
1942 
1943  /*
1944   * Flush bytes waiting on print_fd...
1945   */
1946 
1947   g.print_bytes = 0;
1948 
1949   FD_ZERO(&input_set);
1950   FD_SET(g.print_fd, &input_set);
1951 
1952   tv.tv_sec  = 0;
1953   tv.tv_usec = 0;
1954 
1955   while (select(g.print_fd+1, &input_set, NULL, NULL, &tv) > 0)
1956     if (read(g.print_fd, buffer, sizeof(buffer)) <= 0)
1957       break;
1958 
1959  /*
1960   * Send the reset...
1961   */
1962 
1963   soft_reset_printer(g.printer);
1964 
1965  /*
1966   * Release the I/O lock...
1967   */
1968 
1969   pthread_mutex_lock(&g.readwrite_lock_mutex);
1970   g.readwrite_lock = 0;
1971   pthread_cond_signal(&g.readwrite_lock_cond);
1972   pthread_mutex_unlock(&g.readwrite_lock_mutex);
1973 }
1974 
1975 
1976 /*
1977  * 'soft_reset_printer()' - Do the soft reset request specific to printers
1978  *
1979  * This soft reset is specific to the printer device class and is much less
1980  * invasive than the general USB reset libusb_reset_device(). Especially it
1981  * does never happen that the USB addressing and configuration changes. What
1982  * is actually done is that all buffers get flushed and the bulk IN and OUT
1983  * pipes get reset to their default states. This clears all stall conditions.
1984  * See http://cholla.mmto.org/computers/linux/usb/usbprint11.pdf
1985  */
1986 
1987 static int				/* O - 0 on success, < 0 on error */
soft_reset_printer(usb_printer_t * printer)1988 soft_reset_printer(
1989     usb_printer_t *printer)		/* I - Printer */
1990 {
1991   struct libusb_config_descriptor *confptr = NULL;
1992                                         /* Pointer to current configuration */
1993   int interface,			/* Interface to reset */
1994       errcode;				/* Error code */
1995 
1996 
1997   if (libusb_get_config_descriptor(printer->device, printer->conf,
1998                                    &confptr) < 0)
1999     interface = printer->iface;
2000   else
2001     interface = confptr->interface[printer->iface].
2002                          altsetting[printer->altset].bInterfaceNumber;
2003 
2004   libusb_free_config_descriptor(confptr);
2005 
2006   if ((errcode = libusb_control_transfer(printer->handle,
2007 					 LIBUSB_REQUEST_TYPE_CLASS |
2008 					 LIBUSB_ENDPOINT_OUT |
2009 					 LIBUSB_RECIPIENT_OTHER,
2010 					 2, 0, interface, NULL, 0, 5000)) < 0)
2011     errcode = libusb_control_transfer(printer->handle,
2012 				      LIBUSB_REQUEST_TYPE_CLASS |
2013 				      LIBUSB_ENDPOINT_OUT |
2014 				      LIBUSB_RECIPIENT_INTERFACE,
2015 				      2, 0, interface, NULL, 0, 5000);
2016 
2017   return (errcode);
2018 }
2019