]> git.ipfire.org Git - thirdparty/cups.git/blame - backend/usb-libusb.c
Merge changes from CUPS 1.4svn-r7791.
[thirdparty/cups.git] / backend / usb-libusb.c
CommitLineData
75bd9771
MS
1/*
2 * "$Id$"
3 *
4 * Libusb interface code for the Common UNIX Printing System (CUPS).
5 *
6 * Copyright 2007-2008 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 *
005dd1eb
MS
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 * side_cb() - Handle side-channel requests.
75bd9771
MS
26 */
27
28/*
29 * Include necessary headers...
30 */
31
32#include <usb.h>
005dd1eb 33#include <poll.h>
75bd9771
MS
34
35
36/*
37 * Local types...
38 */
39
40typedef struct usb_printer_s /**** USB Printer Data ****/
41{
42 struct usb_device *device; /* Device info */
43 int conf, /* Configuration */
44 iface, /* Interface */
45 altset, /* Alternate setting */
46 write_endp, /* Write endpoint */
47 read_endp; /* Read endpoint */
48 struct usb_dev_handle *handle; /* Open handle to device */
49} usb_printer_t;
50
51typedef int (*usb_cb_t)(usb_printer_t *, const char *, const char *,
52 const void *);
53
54
55/*
56 * Local functions...
57 */
58
59static int close_device(usb_printer_t *printer);
60static usb_printer_t *find_device(usb_cb_t cb, const void *data);
61static int get_device_id(usb_printer_t *printer, char *buffer,
62 size_t bufsize);
63static int list_cb(usb_printer_t *printer, const char *device_uri,
64 const char *device_id, const void *data);
65static char *make_device_uri(usb_printer_t *printer,
66 const char *device_id,
67 char *uri, size_t uri_size);
68static int open_device(usb_printer_t *printer, int verbose);
69static int print_cb(usb_printer_t *printer, const char *device_uri,
70 const char *device_id, const void *data);
005dd1eb 71static ssize_t side_cb(usb_printer_t *printer, int print_fd);
75bd9771
MS
72
73
74/*
75 * 'list_devices()' - List the available printers.
76 */
77
78void
79list_devices(void)
80{
81 fputs("DEBUG: list_devices\n", stderr);
82 find_device(list_cb, NULL);
83}
84
85
86/*
87 * 'print_device()' - Print a file to a USB device.
88 */
89
90int /* O - Exit status */
91print_device(const char *uri, /* I - Device URI */
92 const char *hostname, /* I - Hostname/manufacturer */
93 const char *resource, /* I - Resource/modelname */
94 char *options, /* I - Device options/serial number */
95 int print_fd, /* I - File descriptor to print */
96 int copies, /* I - Copies to print */
97 int argc, /* I - Number of command-line arguments (6 or 7) */
98 char *argv[]) /* I - Command-line arguments */
99{
100 usb_printer_t *printer; /* Printer */
101 ssize_t bytes, /* Bytes read/written */
102 tbytes; /* Total bytes written */
103 char buffer[8192]; /* Print data buffer */
104 struct sigaction action; /* Actions for POSIX signals */
005dd1eb 105 struct pollfd pfds[2]; /* Poll descriptors */
75bd9771
MS
106
107
108 fputs("DEBUG: print_device\n", stderr);
109
110 /*
111 * Connect to the printer...
112 */
113
114 while ((printer = find_device(print_cb, uri)) == NULL)
115 {
116 _cupsLangPuts(stderr,
117 _("INFO: Waiting for printer to become available...\n"));
118 sleep(5);
119 }
120
75bd9771
MS
121
122 /*
123 * If we are printing data from a print driver on stdin, ignore SIGTERM
124 * so that the driver can finish out any page data, e.g. to eject the
125 * current page. We only do this for stdin printing as otherwise there
126 * is no way to cancel a raw print job...
127 */
128
129 if (!print_fd)
130 {
131 memset(&action, 0, sizeof(action));
132
133 sigemptyset(&action.sa_mask);
134 action.sa_handler = SIG_IGN;
135 sigaction(SIGTERM, &action, NULL);
136 }
137
138 tbytes = 0;
139
005dd1eb
MS
140 pfds[0].fd = print_fd;
141 pfds[0].events = POLLIN;
142 pfds[1].fd = CUPS_SC_FD;
143 pfds[1].events = POLLIN;
144
75bd9771
MS
145 while (copies > 0 && tbytes >= 0)
146 {
147 copies --;
148
149 if (print_fd != 0)
150 {
151 fputs("PAGE: 1 1\n", stderr);
152 lseek(print_fd, 0, SEEK_SET);
153 }
154
155 /*
005dd1eb 156 * TODO: Add back-channel support, along with better write error handling.
75bd9771
MS
157 */
158
005dd1eb 159 if (poll(pfds, 2, -1) > 0)
75bd9771 160 {
005dd1eb 161 if (pfds[0].revents & POLLIN)
75bd9771 162 {
005dd1eb
MS
163 if ((bytes = read(print_fd, buffer, sizeof(buffer))) > 0)
164 {
165 while (usb_bulk_write(printer->handle, printer->write_endp, buffer,
166 bytes, 5000) < 0)
167 {
168 _cupsLangPrintf(stderr,
169 _("ERROR: Unable to write %d bytes to printer!\n"),
170 (int)bytes);
171 tbytes = -1;
172 break;
173 }
174
175 tbytes += bytes;
176 }
177 else if (bytes < 0 && errno != EAGAIN && errno != EINTR)
178 break;
75bd9771
MS
179 }
180
005dd1eb
MS
181 if (pfds[1].revents & POLLIN)
182 tbytes += side_cb(printer, print_fd);
75bd9771
MS
183 }
184 }
185
186 /*
187 * Close our connection and return...
188 */
189
190 close_device(printer);
191
192 return (CUPS_BACKEND_OK);
193}
194
195
196/*
197 * 'close_device()' - Close the connection to the USB printer.
198 */
199
200static int /* I - 0 on success, -1 on failure */
201close_device(usb_printer_t *printer) /* I - Printer */
202{
203 if (printer->handle)
204 {
205 usb_close(printer->handle);
206 printer->handle = NULL;
207 }
208
209 return (0);
210}
211
212
213/*
214 * 'find_device()' - Find or enumerate USB printers.
215 */
216
217static usb_printer_t * /* O - Found printer */
218find_device(usb_cb_t cb, /* I - Callback function */
219 const void *data) /* I - User data for callback */
220{
221 struct usb_bus *bus; /* Current bus */
222 struct usb_device *device; /* Current device */
223 struct usb_config_descriptor *confptr;/* Pointer to current configuration */
224 struct usb_interface *ifaceptr; /* Pointer to current interface */
225 struct usb_interface_descriptor *altptr;
226 /* Pointer to current alternate setting */
227 struct usb_endpoint_descriptor *endpptr;
228 /* Pointer to current endpoint */
229 int conf, /* Current configuration */
230 iface, /* Current interface */
231 altset, /* Current alternate setting */
232 protocol, /* Current protocol */
233 endp, /* Current endpoint */
234 read_endp, /* Current read endpoint */
235 write_endp; /* Current write endpoint */
236 char device_id[1024],/* IEEE-1284 device ID */
237 device_uri[1024];
238 /* Device URI */
239 static usb_printer_t printer; /* Current printer */
240
241
242 /*
243 * Initialize libusb...
244 */
245
246 usb_init();
247 fprintf(stderr, "DEBUG: usb_find_busses=%d\n", usb_find_busses());
248 fprintf(stderr, "DEBUG: usb_find_devices=%d\n", usb_find_devices());
249
250 /*
251 * Then loop through the devices it found...
252 */
253
254 for (bus = usb_get_busses(); bus; bus = bus->next)
255 for (device = bus->devices; device; device = device->next)
256 {
257 /*
258 * Ignore devices with no configuration data and anything that is not
259 * a printer...
260 */
261
262 if (!device->config || !device->descriptor.idVendor ||
263 !device->descriptor.idProduct)
264 continue;
265
266 for (conf = 0, confptr = device->config;
267 conf < device->descriptor.bNumConfigurations;
268 conf ++, confptr ++)
269 for (iface = 0, ifaceptr = confptr->interface;
270 iface < confptr->bNumInterfaces;
271 iface ++, ifaceptr ++)
272 {
273 /*
274 * Some printers offer multiple interfaces...
275 */
276
277 protocol = 0;
278
279 for (altset = 0, altptr = ifaceptr->altsetting;
280 altset < ifaceptr->num_altsetting;
281 altset ++, altptr ++)
282 {
283 /*
284 * Currently we only support unidirectional and bidirectional
285 * printers. Future versions of this code will support the
286 * 1284.4 (packet mode) protocol as well.
287 */
288
289 if (altptr->bInterfaceClass != USB_CLASS_PRINTER ||
290 altptr->bInterfaceSubClass != 1 ||
291 (altptr->bInterfaceProtocol != 1 && /* Unidirectional */
292 altptr->bInterfaceProtocol != 2) || /* Bidirectional */
293 altptr->bInterfaceProtocol < protocol)
294 continue;
295
296 read_endp = -1;
297 write_endp = -1;
298
299 for (endp = 0, endpptr = altptr->endpoint;
300 endp < altptr->bNumEndpoints;
301 endp ++, endpptr ++)
302 if ((endpptr->bmAttributes & USB_ENDPOINT_TYPE_MASK) ==
303 USB_ENDPOINT_TYPE_BULK)
304 {
305 if (endpptr->bEndpointAddress & USB_ENDPOINT_DIR_MASK)
306 read_endp = endp;
307 else
308 write_endp = endp;
309 }
310
311 if (write_endp >= 0)
312 {
313 /*
314 * Save the best match so far...
315 */
316
317 protocol = altptr->bInterfaceProtocol;
318 printer.altset = altset;
319 printer.write_endp = write_endp;
320 printer.read_endp = read_endp;
321 }
322 }
323
324 if (protocol > 0)
325 {
326 printer.device = device;
327 printer.conf = conf;
328 printer.iface = iface;
329 printer.handle = NULL;
330
331 if (!open_device(&printer, data != NULL))
332 {
333 if (!get_device_id(&printer, device_id, sizeof(device_id)))
334 {
335 make_device_uri(&printer, device_id, device_uri,
336 sizeof(device_uri));
337
338 if ((*cb)(&printer, device_uri, device_id, data))
005dd1eb
MS
339 {
340 printer.read_endp = printer.device->config[printer.conf].
341 interface[printer.iface].
342 altsetting[printer.altset].
343 endpoint[printer.read_endp].
344 bEndpointAddress;
345 printer.write_endp = printer.device->config[printer.conf].
346 interface[printer.iface].
347 altsetting[printer.altset].
348 endpoint[printer.write_endp].
349 bEndpointAddress;
75bd9771 350 return (&printer);
005dd1eb 351 }
75bd9771
MS
352 }
353
354 close_device(&printer);
355 }
356 }
357 }
358 }
359
360 /*
361 * If we get this far without returning, then we haven't found a printer
362 * to print to...
363 */
364
365 return (NULL);
366}
367
368
369/*
370 * 'get_device_id()' - Get the IEEE-1284 device ID for the printer.
371 */
372
373static int /* O - 0 on success, -1 on error */
374get_device_id(usb_printer_t *printer, /* I - Printer */
375 char *buffer, /* I - String buffer */
376 size_t bufsize) /* I - Number of bytes in buffer */
377{
378 int length; /* Length of device ID */
379
380
381 if (usb_control_msg(printer->handle,
382 USB_TYPE_CLASS | USB_ENDPOINT_IN | USB_RECIP_INTERFACE,
383 0, 0,
384 (printer->iface << 8) |
385 printer->device->config[printer->conf].
386 interface[printer->iface].
387 altsetting[printer->altset].bAlternateSetting,
388 buffer, bufsize, 5000) < 0)
389 {
390 *buffer = '\0';
391 return (-1);
392 }
393
394 /*
395 * Extract the length of the device ID string from the first two
396 * bytes. The 1284 spec says the length is stored MSB first...
397 */
398
399 length = (((unsigned)buffer[0] & 255) << 8) +
400 ((unsigned)buffer[1] & 255);
401
402 /*
403 * Check to see if the length is larger than our buffer; first
404 * assume that the vendor incorrectly implemented the 1284 spec,
405 * and then limit the length to the size of our buffer...
406 */
407
408 if (length > (bufsize - 2))
409 length = (((unsigned)buffer[1] & 255) << 8) +
410 ((unsigned)buffer[0] & 255);
411
412 if (length > (bufsize - 2))
413 length = bufsize - 2;
414
415 /*
416 * Copy the device ID text to the beginning of the buffer and
417 * nul-terminate.
418 */
419
420 memmove(buffer, buffer + 2, length);
421 buffer[length] = '\0';
422
423 return (0);
424}
425
426
427/*
428 * 'list_cb()' - List USB printers for discovery.
429 */
430
431static int /* O - 0 to continue, 1 to stop */
432list_cb(usb_printer_t *printer, /* I - Printer */
433 const char *device_uri, /* I - Device URI */
434 const char *device_id, /* I - IEEE-1284 device ID */
435 const void *data) /* I - User data (not used) */
436{
437 char make_model[1024]; /* Make and model */
438
439
440 /*
441 * Get the device URI and make/model strings...
442 */
443
444 backendGetMakeModel(device_id, make_model, sizeof(make_model));
445
446 /*
447 * Report the printer...
448 */
449
450 printf("direct %s \"%s\" \"%s USB\" \"%s\"\n", device_uri, make_model,
451 make_model, device_id);
452 fflush(stdout);
453
454 /*
455 * Keep going...
456 */
457
458 return (0);
459}
460
461
462/*
463 * 'make_device_uri()' - Create a device URI for a USB printer.
464 */
465
466static char * /* O - Device URI */
467make_device_uri(
468 usb_printer_t *printer, /* I - Printer */
469 const char *device_id, /* I - IEEE-1284 device ID */
470 char *uri, /* I - Device URI buffer */
471 size_t uri_size) /* I - Size of device URI buffer */
472{
473 char options[1024]; /* Device URI options */
474 int num_values; /* Number of 1284 parameters */
475 cups_option_t *values; /* 1284 parameters */
476 const char *mfg, /* Manufacturer */
477 *mdl, /* Model */
478 *des, /* Description */
479 *sern; /* Serial number */
480 char tempmfg[256], /* Temporary manufacturer string */
481 tempsern[256], /* Temporary serial number string */
482 *tempptr; /* Pointer into temp string */
483
484
485 /*
486 * Get the make, model, and serial numbers...
487 */
488
489 num_values = _ppdGet1284Values(device_id, &values);
490
491 if ((sern = cupsGetOption("SERIALNUMBER", num_values, values)) == NULL)
492 if ((sern = cupsGetOption("SERN", num_values, values)) == NULL)
493 if ((sern = cupsGetOption("SN", num_values, values)) == NULL)
494 {
495 /*
496 * Try getting the serial number from the device itself...
497 */
498
499 int length = usb_get_string_simple(printer->handle,
500 printer->device->descriptor.
501 iSerialNumber,
502 tempsern, sizeof(tempsern) - 1);
503 if (length > 0)
504 {
505 tempsern[length] = '\0';
506 sern = tempsern;
507 }
508 }
509
510 if ((mfg = cupsGetOption("MANUFACTURER", num_values, values)) == NULL)
511 mfg = cupsGetOption("MFG", num_values, values);
512
513 if ((mdl = cupsGetOption("MODEL", num_values, values)) == NULL)
514 mdl = cupsGetOption("MDL", num_values, values);
515
516#ifdef __APPLE__
517 /*
518 * To maintain compatibility with the original IOKit-based backend on Mac OS X,
519 * don't map manufacturer names...
520 */
521
522 if (!mfg)
523
524#else
525 /*
526 * To maintain compatibility with the original character device backend on
527 * Linux and *BSD, map manufacturer names...
528 */
529
530 if (mfg)
531 {
532 if (!strcasecmp(mfg, "Hewlett-Packard"))
533 mfg = "HP";
534 else if (!strcasecmp(mfg, "Lexmark International"))
535 mfg = "Lexmark";
536 }
537 else
538#endif /* __APPLE__ */
539 {
540 /*
541 * No manufacturer? Use the model string or description...
542 */
543
544 if (mdl)
545 _ppdNormalizeMakeAndModel(mdl, tempmfg, sizeof(tempmfg));
546 else if ((des = cupsGetOption("DESCRIPTION", num_values, values)) != NULL ||
547 (des = cupsGetOption("DES", num_values, values)) != NULL)
548 _ppdNormalizeMakeAndModel(des, tempmfg, sizeof(tempmfg));
549 else
550 strlcpy(tempmfg, "Unknown", sizeof(tempmfg));
551
552 if ((tempptr = strchr(tempmfg, ' ')) != NULL)
553 *tempptr = '\0';
554
555 mfg = tempmfg;
556 }
557
558 /*
559 * Generate the device URI from the manufacturer, model, serial number,
560 * and interface number...
561 */
562
563 if (sern)
564 {
565 if (printer->iface > 0)
566 snprintf(options, sizeof(options), "?serial=%s&interface=%d", sern,
567 printer->iface);
568 else
569 snprintf(options, sizeof(options), "?serial=%s", sern);
570 }
571 else if (printer->iface > 0)
572 snprintf(options, sizeof(options), "?interface=%d", printer->iface);
573 else
574 options[0] = '\0';
575
576 httpAssembleURIf(HTTP_URI_CODING_ALL, uri, uri_size, "usb", NULL, mfg, 0,
577 "/%s%s", mdl, options);
578
579 cupsFreeOptions(num_values, values);
580
581 return (uri);
582}
583
584
585/*
586 * 'open_device()' - Open a connection to the USB printer.
587 */
588
589static int /* O - 0 on success, -1 on error */
590open_device(usb_printer_t *printer, /* I - Printer */
591 int verbose) /* I - Update connecting-to-device state? */
592{
593 int number; /* Configuration/interface/altset numbers */
594
595
596 /*
597 * Return immediately if we are already connected...
598 */
599
600 if (printer->handle)
601 return (0);
602
603 /*
604 * Try opening the printer...
605 */
606
607 if ((printer->handle = usb_open(printer->device)) == NULL)
608 return (-1);
609
610 /*
611 * Then set the desired configuration...
612 */
613
614 if (verbose)
615 fputs("STATE: +connecting-to-device\n", stderr);
616
617 number = printer->device->config[printer->conf].bConfigurationValue;
618 while (usb_set_configuration(printer->handle, number) < 0)
619 {
620 if (errno != EBUSY)
621 fprintf(stderr, "DEBUG: Failed to set configuration %d for %04x:%04x\n",
622 number, printer->device->descriptor.idVendor,
623 printer->device->descriptor.idProduct);
624
625 goto error;
626 }
627
628 /*
629 * Claim interfaces as needed...
630 */
631
632 number = printer->device->config[printer->conf].interface[printer->iface].
633 altsetting[printer->altset].bInterfaceNumber;
634 while (usb_claim_interface(printer->handle, number) < 0)
635 {
636 if (errno != EBUSY)
637 fprintf(stderr, "DEBUG: Failed to claim interface %d for %04x:%04x\n",
638 number, printer->device->descriptor.idVendor,
639 printer->device->descriptor.idProduct);
640
641 goto error;
642 }
643
644 if (number != 0)
645 while (usb_claim_interface(printer->handle, 0) < 0)
646 {
647 if (errno != EBUSY)
648 fprintf(stderr, "DEBUG: Failed to claim interface 0 for %04x:%04x\n",
649 printer->device->descriptor.idVendor,
650 printer->device->descriptor.idProduct);
651
652 goto error;
653 }
654
655 /*
656 * Set alternate setting...
657 */
658
659 number = printer->device->config[printer->conf].interface[printer->iface].
660 altsetting[printer->altset].bAlternateSetting;
661 while (usb_set_altinterface(printer->handle, number) < 0)
662 {
663 if (errno != EBUSY)
664 fprintf(stderr,
665 "DEBUG: Failed to set alternate interface %d for %04x:%04x\n",
666 number, printer->device->descriptor.idVendor,
667 printer->device->descriptor.idProduct);
668
669 goto error;
670 }
671
672 if (verbose)
673 fputs("STATE: -connecting-to-device\n", stderr);
674
675 return (0);
676
677 /*
678 * If we get here, there was a hard error...
679 */
680
681 error:
682
683 if (verbose)
684 fputs("STATE: -connecting-to-device\n", stderr);
685
686 usb_close(printer->handle);
687 printer->handle = NULL;
688
689 return (-1);
690}
691
692
693/*
694 * 'print_cb()' - Find a USB printer for printing.
695 */
696
697static int /* O - 0 to continue, 1 to stop (found) */
698print_cb(usb_printer_t *printer, /* I - Printer */
699 const char *device_uri, /* I - Device URI */
700 const char *device_id, /* I - IEEE-1284 device ID */
701 const void *data) /* I - User data (make, model, S/N) */
702{
703 return (!strcmp((char *)data, device_uri));
704}
705
706
005dd1eb
MS
707/*
708 * 'side_cb()' - Handle side-channel requests.
709 */
710
711static ssize_t /* O - Number of bytes written */
712side_cb(usb_printer_t *printer, /* I - Printer */
713 int print_fd) /* I - File to print */
714{
715 ssize_t bytes, /* Bytes read/written */
716 tbytes; /* Total bytes written */
717 char buffer[8192]; /* Print data buffer */
718 struct pollfd pfd; /* Poll descriptor */
719 cups_sc_command_t command; /* Request command */
720 cups_sc_status_t status; /* Request/response status */
721 char data[2048]; /* Request/response data */
722 int datalen; /* Request/response data size */
723
724
725 tbytes = 0;
726 datalen = sizeof(data);
727
728 if (cupsSideChannelRead(&command, &status, data, &datalen, 1.0))
729 {
730 _cupsLangPuts(stderr, _("WARNING: Failed to read side-channel request!\n"));
731 return (0);
732 }
733
734 switch (command)
735 {
736 case CUPS_SC_CMD_DRAIN_OUTPUT :
737 pfd.fd = print_fd;
738 pfd.events = POLLIN;
739
740 while (poll(&pfd, 1, 1000) > 0)
741 {
742 if ((bytes = read(print_fd, buffer, sizeof(buffer))) > 0)
743 {
744 while (usb_bulk_write(printer->handle, printer->write_endp, buffer,
745 bytes, 5000) < 0)
746 {
747 _cupsLangPrintf(stderr,
748 _("ERROR: Unable to write %d bytes to printer!\n"),
749 (int)bytes);
750 tbytes = -1;
751 break;
752 }
753
754 tbytes += bytes;
755 }
756 else if (bytes < 0 && errno != EAGAIN && errno != EINTR)
757 break;
758 }
759
760 if (tbytes < 0)
761 status = CUPS_SC_STATUS_IO_ERROR;
762 else
763 status = CUPS_SC_STATUS_OK;
764
765 datalen = 0;
766 break;
767
768 case CUPS_SC_CMD_GET_BIDI :
769 data[0] = 0; /* TODO: Change to 1 when read supported */
770 datalen = 1;
771 break;
772
773 case CUPS_SC_CMD_GET_DEVICE_ID :
774 if (get_device_id(printer, data, sizeof(data)))
775 {
776 status = CUPS_SC_STATUS_IO_ERROR;
777 datalen = 0;
778 }
779 else
780 {
781 status = CUPS_SC_STATUS_OK;
782 datalen = strlen(data);
783 }
784 break;
785
786 default :
787 status = CUPS_SC_STATUS_NOT_IMPLEMENTED;
788 datalen = 0;
789 break;
790 }
791
792 cupsSideChannelWrite(command, status, data, datalen, 1.0);
793
794 return (tbytes);
795}
796
797
75bd9771
MS
798/*
799 * End of "$Id$".
800 */
801