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