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