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