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