]> git.ipfire.org Git - thirdparty/cups.git/blob - backend/usb-darwin.c
Merge changes from CUPS 1.5svn-r9313.
[thirdparty/cups.git] / backend / usb-darwin.c
1 /*
2 * "$Id: usb-darwin.c 7953 2008-09-17 01:43:19Z mike $"
3 *
4 * Copyright 2005-2010 Apple Inc. All rights reserved.
5 *
6 * IMPORTANT: This Apple software is supplied to you by Apple Computer,
7 * Inc. ("Apple") in consideration of your agreement to the following
8 * terms, and your use, installation, modification or redistribution of
9 * this Apple software constitutes acceptance of these terms. If you do
10 * not agree with these terms, please do not use, install, modify or
11 * redistribute this Apple software.
12 *
13 * In consideration of your agreement to abide by the following terms, and
14 * subject to these terms, Apple grants you a personal, non-exclusive
15 * license, under Apple's copyrights in this original Apple software (the
16 * "Apple Software"), to use, reproduce, modify and redistribute the Apple
17 * Software, with or without modifications, in source and/or binary forms;
18 * provided that if you redistribute the Apple Software in its entirety and
19 * without modifications, you must retain this notice and the following
20 * text and disclaimers in all such redistributions of the Apple Software.
21 * Neither the name, trademarks, service marks or logos of Apple Computer,
22 * Inc. may be used to endorse or promote products derived from the Apple
23 * Software without specific prior written permission from Apple. Except
24 * as expressly stated in this notice, no other rights or licenses, express
25 * or implied, are granted by Apple herein, including but not limited to
26 * any patent rights that may be infringed by your derivative works or by
27 * other works in which the Apple Software may be incorporated.
28 *
29 * The Apple Software is provided by Apple on an "AS IS" basis. APPLE
30 * MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
31 * THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
32 * FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
33 * OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
34 *
35 * IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
36 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
37 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
38 * INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
39 * MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
40 * AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
41 * STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
42 * POSSIBILITY OF SUCH DAMAGE.
43 *
44 * Contents:
45 *
46 * list_devices() - List all USB devices.
47 * print_device() - Print a file to a USB device.
48 * sidechannel_thread() - Thread to handle side-channel requests.
49 * read_thread() - Thread to read the backchannel data on.
50 * list_device_cb() - list_device iterator callback.
51 * find_device_cb() - print_device iterator callback.
52 * status_timer_cb() - Status timer callback.
53 * iterate_printers() - Iterate over all the printers.
54 * device_added() - Device added notifier.
55 * copy_deviceinfo() - Copy strings from the 1284 device ID.
56 * release_deviceinfo() - Release deviceinfo strings.
57 * load_classdriver() - Load a classdriver.
58 * unload_classdriver() - Unload a classdriver.
59 * load_printerdriver() - Load vendor's classdriver.
60 * registry_open() - Open a connection to the printer.
61 * registry_close() - Close the connection to the printer.
62 * copy_deviceid() - Copy the 1284 device id string.
63 * copy_devicestring() - Copy the 1284 device id string.
64 * copy_value_for_key() - Copy value string associated with a key.
65 * cfstr_create_trim() - Create CFString and trim whitespace characters.
66 * parse_options() - Parse uri options.
67 * setup_cfLanguage() - Create AppleLanguages array from LANG environment var.
68 * run_legacy_backend() - Re-exec backend as ppc or i386.
69 * sigterm_handler() - SIGTERM handler.
70 * next_line() - Find the next line in a buffer.
71 * parse_pserror() - Scan the backchannel data for postscript errors.
72 * get_device_id() - Return IEEE-1284 device ID.
73 */
74
75 /*
76 * Include necessary headers.
77 */
78
79 #include <stdio.h>
80 #include <stdlib.h>
81 #include <errno.h>
82 #include <signal.h>
83 #include <fcntl.h>
84 #include <termios.h>
85 #include <unistd.h>
86 #include <sys/stat.h>
87 #include <sys/sysctl.h>
88 #include <libgen.h>
89 #include <mach/mach.h>
90 #include <mach/mach_error.h>
91 #include <mach/mach_time.h>
92 #include <cups/debug-private.h>
93 #include <cups/sidechannel.h>
94 #include <cups/language-private.h>
95 #include "backend-private.h"
96
97 #include <CoreFoundation/CoreFoundation.h>
98 #include <IOKit/usb/IOUSBLib.h>
99 #include <IOKit/IOCFPlugIn.h>
100
101 #include <spawn.h>
102 #include <pthread.h>
103
104 extern char **environ;
105
106
107 /*
108 * DEBUG_WRITES, if defined, causes the backend to write data to the printer in
109 * 512 byte increments, up to 8192 bytes, to make debugging with a USB bus
110 * analyzer easier.
111 */
112
113 #define DEBUG_WRITES 0
114
115 /*
116 * WAIT_EOF_DELAY is number of seconds we'll wait for responses from
117 * the printer after we've finished sending all the data
118 */
119 #define WAIT_EOF_DELAY 7
120 #define WAIT_SIDE_DELAY 3
121 #define DEFAULT_TIMEOUT 5000L
122
123 #define USB_INTERFACE_KIND CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID190)
124 #define kUSBLanguageEnglish 0x409
125
126 #define PRINTER_POLLING_INTERVAL 5 /* seconds */
127 #define INITIAL_LOG_INTERVAL PRINTER_POLLING_INTERVAL
128 #define SUBSEQUENT_LOG_INTERVAL 3 * INITIAL_LOG_INTERVAL
129
130 #define kUSBPrinterClassTypeID CFUUIDGetConstantUUIDWithBytes(NULL, 0x06, 0x04, 0x7D, 0x16, 0x53, 0xA2, 0x11, 0xD6, 0x92, 0x06, 0x00, 0x30, 0x65, 0x52, 0x45, 0x92)
131 #define kUSBPrinterClassInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, 0x03, 0x34, 0x6D, 0x74, 0x53, 0xA3, 0x11, 0xD6, 0x9E, 0xA1, 0x76, 0x30, 0x65, 0x52, 0x45, 0x92)
132
133 #define kUSBClassDriverProperty CFSTR("USB Printing Class")
134
135 #define kUSBGenericTOPrinterClassDriver CFSTR("/System/Library/Printers/Libraries/USBGenericTOPrintingClass.plugin")
136 #define kUSBPrinterClassDeviceNotOpen -9664 /*kPMInvalidIOMContext*/
137
138
139 /*
140 * Section 5.3 USB Printing Class spec
141 */
142 #define kUSBPrintingSubclass 1
143 #define kUSBPrintingProtocolNoOpen 0
144 #define kUSBPrintingProtocolUnidirectional 1
145 #define kUSBPrintingProtocolBidirectional 2
146
147 typedef IOUSBInterfaceInterface190 **printer_interface_t;
148
149 typedef struct iodevice_request_s /**** Device request ****/
150 {
151 UInt8 requestType;
152 UInt8 request;
153 UInt16 value;
154 UInt16 index;
155 UInt16 length;
156 void *buffer;
157 } iodevice_request_t;
158
159 typedef union /**** Centronics status byte ****/
160 {
161 char b;
162 struct
163 {
164 unsigned reserved0:2;
165 unsigned paperError:1;
166 unsigned select:1;
167 unsigned notError:1;
168 unsigned reserved1:3;
169 } status;
170 } centronics_status_t;
171
172 typedef struct classdriver_s /**** g.classdriver context ****/
173 {
174 IUNKNOWN_C_GUTS;
175 CFPlugInRef plugin; /* release plugin */
176 IUnknownVTbl **factory; /* Factory */
177 void *vendorReference; /* vendor class specific usage */
178 UInt32 location; /* unique location in bus topology */
179 UInt8 interfaceNumber; /* Interface number */
180 UInt16 vendorID; /* Vendor id */
181 UInt16 productID; /* Product id */
182 printer_interface_t interface; /* identify the device to IOKit */
183 UInt8 outpipe; /* mandatory bulkOut pipe */
184 UInt8 inpipe; /* optional bulkIn pipe */
185
186 /* general class requests */
187 kern_return_t (*DeviceRequest)(struct classdriver_s **printer, iodevice_request_t *iorequest, UInt16 timeout);
188 kern_return_t (*GetString)(struct classdriver_s **printer, UInt8 whichString, UInt16 language, UInt16 timeout, CFStringRef *result);
189
190 /* standard printer class requests */
191 kern_return_t (*SoftReset)(struct classdriver_s **printer, UInt16 timeout);
192 kern_return_t (*GetCentronicsStatus)(struct classdriver_s **printer, centronics_status_t *result, UInt16 timeout);
193 kern_return_t (*GetDeviceID)(struct classdriver_s **printer, CFStringRef *devid, UInt16 timeout);
194
195 /* standard bulk device requests */
196 kern_return_t (*ReadPipe)(struct classdriver_s **printer, UInt8 *buffer, UInt32 *count);
197 kern_return_t (*WritePipe)(struct classdriver_s **printer, UInt8 *buffer, UInt32 *count, Boolean eoj);
198
199 /* interface requests */
200 kern_return_t (*Open)(struct classdriver_s **printer, UInt32 location, UInt8 protocol);
201 kern_return_t (*Abort)(struct classdriver_s **printer);
202 kern_return_t (*Close)(struct classdriver_s **printer);
203
204 /* initialize and terminate */
205 kern_return_t (*Initialize)(struct classdriver_s **printer, struct classdriver_s **baseclass);
206 kern_return_t (*Terminate)(struct classdriver_s **printer);
207
208 } classdriver_t;
209
210 typedef Boolean (*iterator_callback_t)(void *refcon, io_service_t obj);
211
212 typedef struct iterator_reference_s /**** Iterator reference data */
213 {
214 iterator_callback_t callback;
215 void *userdata;
216 Boolean keepRunning;
217 } iterator_reference_t;
218
219 typedef struct globals_s
220 {
221 io_service_t printer_obj;
222 classdriver_t **classdriver;
223
224 pthread_mutex_t read_thread_mutex;
225 pthread_cond_t read_thread_cond;
226 int read_thread_stop;
227 int read_thread_done;
228
229 pthread_mutex_t readwrite_lock_mutex;
230 pthread_cond_t readwrite_lock_cond;
231 int readwrite_lock;
232
233 CFStringRef make;
234 CFStringRef model;
235 CFStringRef serial;
236 UInt32 location;
237 UInt8 interfaceNum;
238
239 CFRunLoopTimerRef status_timer;
240
241 int print_fd; /* File descriptor to print */
242 ssize_t print_bytes; /* Print bytes read */
243 #if DEBUG_WRITES
244 ssize_t debug_bytes; /* Current bytes to read */
245 #endif /* DEBUG_WRITES */
246
247 Boolean wait_eof;
248 int drain_output; /* Drain all pending output */
249 int bidi_flag; /* 0=unidirectional, 1=bidirectional */
250
251 pthread_mutex_t sidechannel_thread_mutex;
252 pthread_cond_t sidechannel_thread_cond;
253 int sidechannel_thread_stop;
254 int sidechannel_thread_done;
255 } globals_t;
256
257
258 /*
259 * Globals...
260 */
261
262 globals_t g = { 0 }; /* Globals */
263
264
265 /*
266 * Local functions...
267 */
268
269 static Boolean find_device_cb(void *refcon, io_service_t obj);
270 static Boolean list_device_cb(void *refcon, io_service_t obj);
271 static CFStringRef cfstr_create_trim(const char *cstr);
272 static CFStringRef copy_value_for_key(CFStringRef deviceID, CFStringRef *keys);
273 static kern_return_t load_classdriver(CFStringRef driverPath, printer_interface_t intf, classdriver_t ***printerDriver);
274 static kern_return_t load_printerdriver(CFStringRef *driverBundlePath);
275 static kern_return_t registry_close();
276 static kern_return_t registry_open(CFStringRef *driverBundlePath);
277 static kern_return_t unload_classdriver();
278 static OSStatus copy_deviceid(classdriver_t **printer, CFStringRef *deviceID);
279 static void *read_thread(void *reference);
280 static void *sidechannel_thread(void *reference);
281 static void copy_deviceinfo(CFStringRef deviceIDString, CFStringRef *make, CFStringRef *model, CFStringRef *serial);
282 static void copy_devicestring(io_service_t usbInterface, CFStringRef *deviceID, UInt32 *deviceLocation, UInt8 *interfaceNum);
283 static void device_added(void *userdata, io_iterator_t iterator);
284 static void get_device_id(cups_sc_status_t *status, char *data, int *datalen);
285 static void iterate_printers(iterator_callback_t callBack, void *userdata);
286 static void parse_options(char *options, char *serial, int serial_size, UInt32 *location, Boolean *wait_eof);
287 static void release_deviceinfo(CFStringRef *make, CFStringRef *model, CFStringRef *serial);
288 static void setup_cfLanguage(void);
289 static void soft_reset();
290 static void status_timer_cb(CFRunLoopTimerRef timer, void *info);
291
292 #if defined(__i386__) || defined(__x86_64__)
293 static pid_t child_pid; /* Child PID */
294 static void run_legacy_backend(int argc, char *argv[], int fd); /* Starts child backend process running as a ppc executable */
295 static void sigterm_handler(int sig); /* SIGTERM handler */
296 #endif /* __i386__ || __x86_64__ */
297
298 #ifdef PARSE_PS_ERRORS
299 static const char *next_line (const char *buffer);
300 static void parse_pserror (char *sockBuffer, int len);
301 #endif /* PARSE_PS_ERRORS */
302
303 #pragma mark -
304
305 /*
306 * 'list_devices()' - List all USB devices.
307 */
308
309 void list_devices()
310 {
311 iterate_printers(list_device_cb, NULL);
312 }
313
314
315 /*
316 * 'print_device()' - Print a file to a USB device.
317 */
318
319 int /* O - Exit status */
320 print_device(const char *uri, /* I - Device URI */
321 const char *hostname, /* I - Hostname/manufacturer */
322 const char *resource, /* I - Resource/modelname */
323 char *options, /* I - Device options/serial number */
324 int print_fd, /* I - File descriptor to print */
325 int copies, /* I - Copies to print */
326 int argc, /* I - Number of command-line arguments (6 or 7) */
327 char *argv[]) /* I - Command-line arguments */
328 {
329 char serial[1024]; /* Serial number buffer */
330 OSStatus status; /* Function results */
331 IOReturn iostatus; /* Current IO status */
332 pthread_t read_thread_id, /* Read thread */
333 sidechannel_thread_id;/* Side-channel thread */
334 int have_sidechannel = 0; /* Was the side-channel thread started? */
335 struct stat sidechannel_info; /* Side-channel file descriptor info */
336 char print_buffer[8192], /* Print data buffer */
337 *print_ptr; /* Pointer into print data buffer */
338 UInt32 location; /* Unique location in bus topology */
339 fd_set input_set; /* Input set for select() */
340 CFStringRef driverBundlePath; /* Class driver path */
341 int countdown, /* Logging interval */
342 nfds; /* Number of file descriptors */
343 ssize_t total_bytes; /* Total bytes written */
344 UInt32 bytes; /* Bytes written */
345 struct timeval *timeout, /* Timeout pointer */
346 stimeout; /* Timeout for select() */
347 struct timespec cond_timeout; /* pthread condition timeout */
348
349
350 /*
351 * See if the side-channel descriptor is valid...
352 */
353
354 have_sidechannel = !fstat(CUPS_SC_FD, &sidechannel_info) &&
355 S_ISSOCK(sidechannel_info.st_mode);
356
357 /*
358 * Localize using CoreFoundation...
359 */
360
361 setup_cfLanguage();
362
363 parse_options(options, serial, sizeof(serial), &location, &g.wait_eof);
364
365 if (resource[0] == '/')
366 resource++;
367
368 g.print_fd = print_fd;
369 g.make = cfstr_create_trim(hostname);
370 g.model = cfstr_create_trim(resource);
371 g.serial = cfstr_create_trim(serial);
372 g.location = location;
373
374 if (!g.make || !g.model)
375 {
376 fprintf(stderr, "DEBUG: Fatal USB error.\n");
377 _cupsLangPuts(stderr, _("ERROR: There was an unrecoverable USB error.\n"));
378
379 if (!g.make)
380 fputs("DEBUG: USB make string is NULL\n", stderr);
381 if (!g.model)
382 fputs("DEBUG: USB model string is NULL\n", stderr);
383
384 return (CUPS_BACKEND_STOP);
385 }
386
387 fputs("STATE: +connecting-to-device\n", stderr);
388
389 countdown = INITIAL_LOG_INTERVAL;
390
391 do
392 {
393 if (g.printer_obj)
394 {
395 IOObjectRelease(g.printer_obj);
396 unload_classdriver(&g.classdriver);
397 g.printer_obj = 0x0;
398 g.classdriver = 0x0;
399 }
400
401 fprintf(stderr, "DEBUG: Looking for '%s %s'\n", hostname, resource);
402
403 iterate_printers(find_device_cb, NULL);
404
405 fputs("DEBUG: Opening connection\n", stderr);
406
407 driverBundlePath = NULL;
408
409 status = registry_open(&driverBundlePath);
410
411 #if defined(__i386__) || defined(__x86_64__)
412 /*
413 * If we were unable to load the class drivers for this printer it's
414 * probably because they're ppc or i386. In this case try to run this
415 * backend as i386 or ppc executables so we can use them...
416 */
417 if (status == -2)
418 {
419 run_legacy_backend(argc, argv, print_fd);
420 /* Never returns here */
421 }
422 #endif /* __i386__ || __x86_64__ */
423
424 if (status == -2)
425 {
426 /*
427 * If we still were unable to load the class drivers for this printer log
428 * the error and stop the queue...
429 */
430
431 if (driverBundlePath == NULL || !CFStringGetCString(driverBundlePath, print_buffer, sizeof(print_buffer), kCFStringEncodingUTF8))
432 strlcpy(print_buffer, "USB class driver", sizeof(print_buffer));
433
434 fputs("STATE: +apple-missing-usbclassdriver-error\n", stderr);
435 _cupsLangPuts(stderr, _("ERROR: There was an unrecoverable USB error.\n"));
436 fprintf(stderr, "DEBUG: Could not load %s\n", print_buffer);
437
438 if (driverBundlePath)
439 CFRelease(driverBundlePath);
440
441 return (CUPS_BACKEND_STOP);
442 }
443
444 if (driverBundlePath)
445 CFRelease(driverBundlePath);
446
447 if (status != noErr)
448 {
449 sleep(PRINTER_POLLING_INTERVAL);
450 countdown -= PRINTER_POLLING_INTERVAL;
451 if (countdown <= 0)
452 {
453 _cupsLangPuts(stderr,
454 _("INFO: Waiting for printer to become available...\n"));
455 fprintf(stderr, "DEBUG: USB printer status: 0x%08x\n", (int)status);
456 countdown = SUBSEQUENT_LOG_INTERVAL; /* subsequent log entries, every 15 seconds */
457 }
458 }
459 } while (status != noErr);
460
461 fputs("STATE: -connecting-to-device\n", stderr);
462
463 /*
464 * Now that we are "connected" to the port, ignore SIGTERM so that we
465 * can finish out any page data the driver sends (e.g. to eject the
466 * current page... Only ignore SIGTERM if we are printing data from
467 * stdin (otherwise you can't cancel raw jobs...)
468 */
469
470 if (!print_fd)
471 {
472 struct sigaction action; /* POSIX signal action */
473
474
475 memset(&action, 0, sizeof(action));
476
477 sigemptyset(&action.sa_mask);
478 action.sa_handler = SIG_IGN;
479 sigaction(SIGTERM, &action, NULL);
480 }
481
482 /*
483 * Start the side channel thread if the descriptor is valid...
484 */
485
486 pthread_mutex_init(&g.readwrite_lock_mutex, NULL);
487 pthread_cond_init(&g.readwrite_lock_cond, NULL);
488 g.readwrite_lock = 1;
489
490 if (have_sidechannel)
491 {
492 g.sidechannel_thread_stop = 0;
493 g.sidechannel_thread_done = 0;
494
495 pthread_cond_init(&g.sidechannel_thread_cond, NULL);
496 pthread_mutex_init(&g.sidechannel_thread_mutex, NULL);
497
498 if (pthread_create(&sidechannel_thread_id, NULL, sidechannel_thread, NULL))
499 {
500 fprintf(stderr, "DEBUG: Fatal USB error.\n");
501 _cupsLangPuts(stderr, _("ERROR: There was an unrecoverable USB error.\n"));
502 fputs("DEBUG: Couldn't create side-channel thread\n", stderr);
503 registry_close();
504 return (CUPS_BACKEND_STOP);
505 }
506 }
507
508 /*
509 * Get the read thread going...
510 */
511
512 g.read_thread_stop = 0;
513 g.read_thread_done = 0;
514
515 pthread_cond_init(&g.read_thread_cond, NULL);
516 pthread_mutex_init(&g.read_thread_mutex, NULL);
517
518 if (pthread_create(&read_thread_id, NULL, read_thread, NULL))
519 {
520 fprintf(stderr, "DEBUG: Fatal USB error.\n");
521 _cupsLangPuts(stderr, _("ERROR: There was an unrecoverable USB error.\n"));
522 fputs("DEBUG: Couldn't create read thread\n", stderr);
523 registry_close();
524 return (CUPS_BACKEND_STOP);
525 }
526
527 /*
528 * The main thread sends the print file...
529 */
530
531 g.drain_output = 0;
532 g.print_bytes = 0;
533 total_bytes = 0;
534 print_ptr = print_buffer;
535
536 while (status == noErr && copies-- > 0)
537 {
538 _cupsLangPuts(stderr, _("INFO: Sending print data...\n"));
539
540 if (print_fd != STDIN_FILENO)
541 {
542 fputs("PAGE: 1 1\n", stderr);
543 lseek(print_fd, 0, SEEK_SET);
544 }
545
546 while (status == noErr)
547 {
548 FD_ZERO(&input_set);
549
550 if (!g.print_bytes)
551 FD_SET(print_fd, &input_set);
552
553 /*
554 * Calculate select timeout...
555 * If we have data waiting to send timeout is 100ms.
556 * else if we're draining print_fd timeout is 0.
557 * else we're waiting forever...
558 */
559
560 if (g.print_bytes)
561 {
562 stimeout.tv_sec = 0;
563 stimeout.tv_usec = 100000; /* 100ms */
564 timeout = &stimeout;
565 }
566 else if (g.drain_output)
567 {
568 stimeout.tv_sec = 0;
569 stimeout.tv_usec = 0;
570 timeout = &stimeout;
571 }
572 else
573 timeout = NULL;
574
575 /*
576 * I/O is unlocked around select...
577 */
578
579 pthread_mutex_lock(&g.readwrite_lock_mutex);
580 g.readwrite_lock = 0;
581 pthread_cond_signal(&g.readwrite_lock_cond);
582 pthread_mutex_unlock(&g.readwrite_lock_mutex);
583
584 nfds = select(print_fd + 1, &input_set, NULL, NULL, timeout);
585
586 /*
587 * Reacquire the lock...
588 */
589
590 pthread_mutex_lock(&g.readwrite_lock_mutex);
591 while (g.readwrite_lock)
592 pthread_cond_wait(&g.readwrite_lock_cond, &g.readwrite_lock_mutex);
593 g.readwrite_lock = 1;
594 pthread_mutex_unlock(&g.readwrite_lock_mutex);
595
596 if (nfds < 0)
597 {
598 if (errno == EINTR && total_bytes == 0)
599 {
600 fputs("DEBUG: Received an interrupt before any bytes were "
601 "written, aborting\n", stderr);
602 registry_close();
603 return (CUPS_BACKEND_OK);
604 }
605 else if (errno != EAGAIN && errno != EINTR)
606 {
607 _cupsLangPuts(stderr, _("ERROR: Unable to read print data.\n"));
608 perror("DEBUG: select");
609 registry_close();
610 return (CUPS_BACKEND_FAILED);
611 }
612 }
613
614 /*
615 * If drain output has finished send a response...
616 */
617
618 if (g.drain_output && !nfds && !g.print_bytes)
619 {
620 /* Send a response... */
621 cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT, CUPS_SC_STATUS_OK, NULL, 0, 1.0);
622 g.drain_output = 0;
623 }
624
625 /*
626 * Check if we have print data ready...
627 */
628
629 if (FD_ISSET(print_fd, &input_set))
630 {
631 #if DEBUG_WRITES
632 g.debug_bytes += 512;
633 if (g.debug_bytes > sizeof(print_buffer))
634 g.debug_bytes = 512;
635
636 g.print_bytes = read(print_fd, print_buffer, g.debug_bytes);
637
638 #else
639 g.print_bytes = read(print_fd, print_buffer, sizeof(print_buffer));
640 #endif /* DEBUG_WRITES */
641
642 if (g.print_bytes < 0)
643 {
644 /*
645 * Read error - bail if we don't see EAGAIN or EINTR...
646 */
647
648 if (errno != EAGAIN && errno != EINTR)
649 {
650 _cupsLangPuts(stderr, _("ERROR: Unable to read print data.\n"));
651 perror("DEBUG: read");
652 registry_close();
653 return (CUPS_BACKEND_FAILED);
654 }
655
656 g.print_bytes = 0;
657 }
658 else if (g.print_bytes == 0)
659 {
660 /*
661 * End of file, break out of the loop...
662 */
663
664 break;
665 }
666
667 print_ptr = print_buffer;
668
669 fprintf(stderr, "DEBUG: Read %d bytes of print data...\n",
670 (int)g.print_bytes);
671 }
672
673 if (g.print_bytes)
674 {
675 bytes = g.print_bytes;
676 iostatus = (*g.classdriver)->WritePipe(g.classdriver, (UInt8*)print_ptr, &bytes, 0);
677
678 /*
679 * Ignore timeout errors, but retain the number of bytes written to
680 * avoid sending duplicate data (<rdar://problem/6254911>)...
681 */
682
683 if (iostatus == kIOUSBTransactionTimeout)
684 {
685 fputs("DEBUG: Got USB transaction timeout during write\n", stderr);
686 iostatus = 0;
687 }
688
689 /*
690 * If we've stalled, retry the write...
691 */
692
693 else if (iostatus == kIOUSBPipeStalled)
694 {
695 fputs("DEBUG: Got USB pipe stalled during write\n", stderr);
696
697 bytes = g.print_bytes;
698 iostatus = (*g.classdriver)->WritePipe(g.classdriver, (UInt8*)print_ptr, &bytes, 0);
699 }
700
701 /*
702 * Retry a write after an aborted write since we probably just got
703 * SIGTERM (<rdar://problem/6860126>)...
704 */
705
706 else if (iostatus == kIOReturnAborted)
707 {
708 fputs("DEBUG: Got USB return aborted during write\n", stderr);
709
710 IOReturn err = (*g.classdriver)->Abort(g.classdriver);
711 fprintf(stderr, "DEBUG: USB class driver Abort returned %x\n", err);
712
713 #if DEBUG_WRITES
714 sleep(5);
715 #endif /* DEBUG_WRITES */
716
717 bytes = g.print_bytes;
718 iostatus = (*g.classdriver)->WritePipe(g.classdriver, (UInt8*)print_ptr, &bytes, 0);
719 }
720
721 if (iostatus || bytes < 0)
722 {
723 /*
724 * Write error - bail if we don't see an error we can retry...
725 */
726 _cupsLangPuts(stderr, _("ERROR: Unable to send print data to printer.\n"));
727 fprintf(stderr, "DEBUG: USB class driver WritePipe returned %x\n",
728 iostatus);
729
730 IOReturn err = (*g.classdriver)->Abort(g.classdriver);
731 fprintf(stderr, "DEBUG: USB class driver Abort returned %x\n",
732 err);
733
734 status = CUPS_BACKEND_FAILED;
735 break;
736 }
737 else if (bytes > 0)
738 {
739 fprintf(stderr, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes);
740
741 g.print_bytes -= bytes;
742 print_ptr += bytes;
743 total_bytes += bytes;
744 }
745 }
746
747 if (print_fd != 0 && status == noErr)
748 fprintf(stderr, "DEBUG: Sending print file, %lld bytes...\n",
749 (off_t)total_bytes);
750 }
751 }
752
753 fprintf(stderr, "DEBUG: Sent %lld bytes...\n", (off_t)total_bytes);
754
755 if (!print_fd)
756 {
757 /*
758 * Re-enable the SIGTERM handler so pthread_kill() will work...
759 */
760
761 struct sigaction action; /* POSIX signal action */
762
763 memset(&action, 0, sizeof(action));
764
765 sigemptyset(&action.sa_mask);
766 action.sa_handler = SIG_DFL;
767 sigaction(SIGTERM, &action, NULL);
768 }
769
770 /*
771 * Wait for the side channel thread to exit...
772 */
773
774 if (have_sidechannel)
775 {
776 close(CUPS_SC_FD);
777 pthread_mutex_lock(&g.readwrite_lock_mutex);
778 g.readwrite_lock = 0;
779 pthread_cond_signal(&g.readwrite_lock_cond);
780 pthread_mutex_unlock(&g.readwrite_lock_mutex);
781
782 g.sidechannel_thread_stop = 1;
783 pthread_mutex_lock(&g.sidechannel_thread_mutex);
784 if (!g.sidechannel_thread_done)
785 {
786 /*
787 * Wait for the side-channel thread to exit...
788 */
789
790 cond_timeout.tv_sec = time(NULL) + WAIT_SIDE_DELAY;
791 cond_timeout.tv_nsec = 0;
792 if (pthread_cond_timedwait(&g.sidechannel_thread_cond,
793 &g.sidechannel_thread_mutex,
794 &cond_timeout) != 0)
795 {
796 /*
797 * Force the side-channel thread to exit...
798 */
799
800 pthread_kill(sidechannel_thread_id, SIGTERM);
801 }
802 }
803 pthread_mutex_unlock(&g.sidechannel_thread_mutex);
804
805 pthread_join(sidechannel_thread_id, NULL);
806
807 pthread_cond_destroy(&g.sidechannel_thread_cond);
808 pthread_mutex_destroy(&g.sidechannel_thread_mutex);
809 }
810
811 pthread_cond_destroy(&g.readwrite_lock_cond);
812 pthread_mutex_destroy(&g.readwrite_lock_mutex);
813
814 /*
815 * Signal the read thread to stop...
816 */
817
818 g.read_thread_stop = 1;
819
820 /*
821 * Give the read thread WAIT_EOF_DELAY seconds to complete all the data. If
822 * we are not signaled in that time then force the thread to exit.
823 */
824
825 pthread_mutex_lock(&g.read_thread_mutex);
826
827 if (!g.read_thread_done)
828 {
829 cond_timeout.tv_sec = time(NULL) + WAIT_EOF_DELAY;
830 cond_timeout.tv_nsec = 0;
831
832 if (pthread_cond_timedwait(&g.read_thread_cond, &g.read_thread_mutex,
833 &cond_timeout) != 0)
834 {
835 /*
836 * Force the read thread to exit...
837 */
838
839 g.wait_eof = 0;
840 pthread_kill(read_thread_id, SIGTERM);
841 }
842 }
843 pthread_mutex_unlock(&g.read_thread_mutex);
844
845 pthread_join(read_thread_id, NULL); /* wait for the read thread to return */
846
847 pthread_cond_destroy(&g.read_thread_cond);
848 pthread_mutex_destroy(&g.read_thread_mutex);
849
850 /*
851 * Close the connection and input file and general clean up...
852 */
853
854 registry_close();
855
856 if (print_fd != STDIN_FILENO)
857 close(print_fd);
858
859 if (g.make != NULL)
860 CFRelease(g.make);
861
862 if (g.model != NULL)
863 CFRelease(g.model);
864
865 if (g.serial != NULL)
866 CFRelease(g.serial);
867
868 if (g.printer_obj != 0x0)
869 IOObjectRelease(g.printer_obj);
870
871 return status;
872 }
873
874
875 /*
876 * 'read_thread()' - Thread to read the backchannel data on.
877 */
878
879 static void *read_thread(void *reference)
880 {
881 UInt8 readbuffer[512];
882 UInt32 rbytes;
883 kern_return_t readstatus;
884 struct mach_timebase_info timeBaseInfo;
885 uint64_t start,
886 delay;
887
888 /* Calculate what 250 milliSeconds are in mach absolute time...
889 */
890 mach_timebase_info(&timeBaseInfo);
891 delay = ((uint64_t)250000000 * (uint64_t)timeBaseInfo.denom) / (uint64_t)timeBaseInfo.numer;
892
893 do
894 {
895 /*
896 * Remember when we started so we can throttle the loop after the read call...
897 */
898
899 start = mach_absolute_time();
900
901 rbytes = sizeof(readbuffer);
902 readstatus = (*g.classdriver)->ReadPipe(g.classdriver, readbuffer, &rbytes);
903 if (readstatus == kIOReturnSuccess && rbytes > 0)
904 {
905 fprintf(stderr, "DEBUG: Read %d bytes of back-channel data...\n",
906 (int)rbytes);
907 cupsBackChannelWrite((char*)readbuffer, rbytes, 1.0);
908
909 /* cntrl-d is echoed by the printer.
910 * NOTES:
911 * Xerox Phaser 6250D doesn't echo the cntrl-d.
912 * Xerox Phaser 6250D doesn't always send the product query.
913 */
914 if (g.wait_eof && readbuffer[rbytes-1] == 0x4)
915 break;
916
917 #ifdef PARSE_PS_ERRORS
918 parse_pserror(readbuffer, rbytes);
919 #endif
920 }
921 else if (readstatus == kIOUSBTransactionTimeout)
922 fputs("DEBUG: Got USB transaction timeout during read\n", stderr);
923 else if (readstatus == kIOUSBPipeStalled)
924 fputs("DEBUG: Got USB pipe stalled during read\n", stderr);
925 else if (readstatus == kIOReturnAborted)
926 fputs("DEBUG: Got USB return aborted during read\n", stderr);
927
928 /*
929 * Make sure this loop executes no more than once every 250 miliseconds...
930 */
931
932 if ((readstatus != kIOReturnSuccess || rbytes == 0) && (g.wait_eof || !g.read_thread_stop))
933 mach_wait_until(start + delay);
934
935 } while (g.wait_eof || !g.read_thread_stop); /* Abort from main thread tests error here */
936
937 /*
938 * Let the main thread know that we have completed the read thread...
939 */
940
941 pthread_mutex_lock(&g.read_thread_mutex);
942 g.read_thread_done = 1;
943 pthread_cond_signal(&g.read_thread_cond);
944 pthread_mutex_unlock(&g.read_thread_mutex);
945
946 return NULL;
947 }
948
949
950 /*
951 * 'sidechannel_thread()' - Handle side-channel requests.
952 */
953
954 static void*
955 sidechannel_thread(void *reference)
956 {
957 cups_sc_command_t command; /* Request command */
958 cups_sc_status_t status; /* Request/response status */
959 char data[2048]; /* Request/response data */
960 int datalen; /* Request/response data size */
961
962
963 do
964 {
965 datalen = sizeof(data);
966
967 if (cupsSideChannelRead(&command, &status, data, &datalen, 1.0))
968 {
969 if (status == CUPS_SC_STATUS_TIMEOUT)
970 continue;
971 else
972 break;
973 }
974
975 switch (command)
976 {
977 case CUPS_SC_CMD_SOFT_RESET: /* Do a soft reset */
978 fputs("DEBUG: CUPS_SC_CMD_SOFT_RESET received from driver...\n",
979 stderr);
980
981 if ((*g.classdriver)->SoftReset != NULL)
982 {
983 soft_reset();
984 cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, NULL, 0, 1.0);
985 fputs("DEBUG: Returning status CUPS_STATUS_OK with no bytes...\n",
986 stderr);
987 }
988 else
989 {
990 cupsSideChannelWrite(command, CUPS_SC_STATUS_NOT_IMPLEMENTED,
991 NULL, 0, 1.0);
992 fputs("DEBUG: Returning status CUPS_STATUS_NOT_IMPLEMENTED with "
993 "no bytes...\n", stderr);
994 }
995 break;
996
997 case CUPS_SC_CMD_DRAIN_OUTPUT: /* Drain all pending output */
998 fputs("DEBUG: CUPS_SC_CMD_DRAIN_OUTPUT received from driver...\n",
999 stderr);
1000
1001 g.drain_output = 1;
1002 break;
1003
1004 case CUPS_SC_CMD_GET_BIDI: /* Is the connection bidirectional? */
1005 fputs("DEBUG: CUPS_SC_CMD_GET_BIDI received from driver...\n",
1006 stderr);
1007
1008 data[0] = g.bidi_flag;
1009 cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, data, 1, 1.0);
1010
1011 fprintf(stderr,
1012 "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
1013 data[0]);
1014 break;
1015
1016 case CUPS_SC_CMD_GET_DEVICE_ID: /* Return IEEE-1284 device ID */
1017 fputs("DEBUG: CUPS_SC_CMD_GET_DEVICE_ID received from driver...\n",
1018 stderr);
1019
1020 datalen = sizeof(data);
1021 get_device_id(&status, data, &datalen);
1022 cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, data, datalen, 1.0);
1023
1024 if (datalen < sizeof(data))
1025 data[datalen] = '\0';
1026 else
1027 data[sizeof(data) - 1] = '\0';
1028
1029 fprintf(stderr,
1030 "DEBUG: Returning CUPS_SC_STATUS_OK with %d bytes (%s)...\n",
1031 datalen, data);
1032 break;
1033
1034 case CUPS_SC_CMD_GET_STATE: /* Return device state */
1035 fputs("DEBUG: CUPS_SC_CMD_GET_STATE received from driver...\n",
1036 stderr);
1037
1038 data[0] = CUPS_SC_STATE_ONLINE;
1039 cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, data, 1, 1.0);
1040
1041 fprintf(stderr,
1042 "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
1043 data[0]);
1044 break;
1045
1046 default:
1047 fprintf(stderr, "DEBUG: Unknown side-channel command (%d) received "
1048 "from driver...\n", command);
1049
1050 cupsSideChannelWrite(command, CUPS_SC_STATUS_NOT_IMPLEMENTED,
1051 NULL, 0, 1.0);
1052
1053 fputs("DEBUG: Returned CUPS_SC_STATUS_NOT_IMPLEMENTED with no bytes...\n",
1054 stderr);
1055 break;
1056 }
1057 }
1058 while (!g.sidechannel_thread_stop);
1059
1060 pthread_mutex_lock(&g.sidechannel_thread_mutex);
1061 g.sidechannel_thread_done = 1;
1062 pthread_cond_signal(&g.sidechannel_thread_cond);
1063 pthread_mutex_unlock(&g.sidechannel_thread_mutex);
1064
1065 return NULL;
1066 }
1067
1068
1069 #pragma mark -
1070 /*
1071 * 'iterate_printers()' - Iterate over all the printers.
1072 */
1073
1074 static void iterate_printers(iterator_callback_t callBack,
1075 void *userdata)
1076 {
1077 mach_port_t masterPort = 0x0;
1078 kern_return_t kr = IOMasterPort (bootstrap_port, &masterPort);
1079
1080 if (kr == kIOReturnSuccess && masterPort != 0x0)
1081 {
1082 io_iterator_t addIterator = 0x0;
1083
1084 iterator_reference_t reference = { callBack, userdata, true };
1085 IONotificationPortRef addNotification = IONotificationPortCreate(masterPort);
1086
1087 int klass = kUSBPrintingClass;
1088 int subklass = kUSBPrintingSubclass;
1089
1090 CFNumberRef usb_klass = CFNumberCreate(NULL, kCFNumberIntType, &klass);
1091 CFNumberRef usb_subklass = CFNumberCreate(NULL, kCFNumberIntType, &subklass);
1092 CFMutableDictionaryRef usbPrinterMatchDictionary = IOServiceMatching(kIOUSBInterfaceClassName);
1093
1094 CFDictionaryAddValue(usbPrinterMatchDictionary, CFSTR("bInterfaceClass"), usb_klass);
1095 CFDictionaryAddValue(usbPrinterMatchDictionary, CFSTR("bInterfaceSubClass"), usb_subklass);
1096
1097 CFRelease(usb_klass);
1098 CFRelease(usb_subklass);
1099
1100 kr = IOServiceAddMatchingNotification(addNotification, kIOMatchedNotification, usbPrinterMatchDictionary, &device_added, &reference, &addIterator);
1101 if (addIterator != 0x0)
1102 {
1103 device_added (&reference, addIterator);
1104
1105 if (reference.keepRunning)
1106 {
1107 CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification), kCFRunLoopDefaultMode);
1108 CFRunLoopRun();
1109 }
1110 IOObjectRelease(addIterator);
1111 }
1112 mach_port_deallocate(mach_task_self(), masterPort);
1113 }
1114 }
1115
1116
1117 /*
1118 * 'device_added()' - Device added notifier.
1119 */
1120
1121 static void device_added(void *userdata,
1122 io_iterator_t iterator)
1123 {
1124 iterator_reference_t *reference = userdata;
1125
1126 io_service_t obj;
1127 while (reference->keepRunning && (obj = IOIteratorNext(iterator)) != 0x0)
1128 {
1129 if (reference->callback != NULL)
1130 reference->keepRunning = reference->callback(reference->userdata, obj);
1131
1132 IOObjectRelease(obj);
1133 }
1134
1135 /* One last call to the call back now that we are not longer have printers left to iterate...
1136 */
1137 if (reference->keepRunning)
1138 reference->keepRunning = reference->callback(reference->userdata, 0x0);
1139
1140 if (!reference->keepRunning)
1141 CFRunLoopStop(CFRunLoopGetCurrent());
1142 }
1143
1144
1145 /*
1146 * 'list_device_cb()' - list_device iterator callback.
1147 */
1148
1149 static Boolean list_device_cb(void *refcon,
1150 io_service_t obj)
1151 {
1152 Boolean keepRunning = (obj != 0x0);
1153
1154 if (keepRunning)
1155 {
1156 CFStringRef deviceIDString = NULL;
1157 UInt32 deviceLocation = 0;
1158 UInt8 interfaceNum = 0;
1159
1160 copy_devicestring(obj, &deviceIDString, &deviceLocation, &interfaceNum);
1161 if (deviceIDString != NULL)
1162 {
1163 CFStringRef make = NULL, model = NULL, serial = NULL;
1164 char uristr[1024], makestr[1024], modelstr[1024], serialstr[1024];
1165 char optionsstr[1024], idstr[1024], make_modelstr[1024];
1166
1167 copy_deviceinfo(deviceIDString, &make, &model, &serial);
1168 CFStringGetCString(deviceIDString, idstr, sizeof(idstr),
1169 kCFStringEncodingUTF8);
1170 backendGetMakeModel(idstr, make_modelstr, sizeof(make_modelstr));
1171
1172 modelstr[0] = '/';
1173
1174 if (!make ||
1175 !CFStringGetCString(make, makestr, sizeof(makestr),
1176 kCFStringEncodingUTF8))
1177 strcpy(makestr, "Unknown");
1178
1179 if (!model ||
1180 !CFStringGetCString(model, &modelstr[1], sizeof(modelstr)-1,
1181 kCFStringEncodingUTF8))
1182 strcpy(modelstr + 1, "Printer");
1183
1184 optionsstr[0] = '\0';
1185 if (serial != NULL)
1186 {
1187 CFStringGetCString(serial, serialstr, sizeof(serialstr), kCFStringEncodingUTF8);
1188 snprintf(optionsstr, sizeof(optionsstr), "?serial=%s", serialstr);
1189 }
1190 else if (deviceLocation != 0)
1191 snprintf(optionsstr, sizeof(optionsstr), "?location=%x", (unsigned)deviceLocation);
1192
1193 httpAssembleURI(HTTP_URI_CODING_ALL, uristr, sizeof(uristr), "usb", NULL, makestr, 0, modelstr);
1194 strlcat(uristr, optionsstr, sizeof(uristr));
1195
1196 cupsBackendReport("direct", uristr, make_modelstr, make_modelstr, idstr,
1197 NULL);
1198
1199 release_deviceinfo(&make, &model, &serial);
1200 CFRelease(deviceIDString);
1201 }
1202 }
1203
1204 return keepRunning;
1205 }
1206
1207
1208 /*
1209 * 'find_device_cb()' - print_device iterator callback.
1210 */
1211
1212 static Boolean find_device_cb(void *refcon,
1213 io_service_t obj)
1214 {
1215 Boolean keepLooking = true;
1216
1217 if (obj != 0x0)
1218 {
1219 CFStringRef idString = NULL;
1220 UInt32 location = -1;
1221 UInt8 interfaceNum = 0;
1222
1223 copy_devicestring(obj, &idString, &location, &interfaceNum);
1224 if (idString != NULL)
1225 {
1226 CFStringRef make = NULL, model = NULL, serial = NULL;
1227
1228 copy_deviceinfo(idString, &make, &model, &serial);
1229 if (make && CFStringCompare(make, g.make, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
1230 {
1231 if (model && CFStringCompare(model, g.model, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
1232 {
1233 if (g.serial != NULL && CFStringGetLength(g.serial) > 0)
1234 {
1235 if (serial != NULL && CFStringCompare(serial, g.serial, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
1236 {
1237 IOObjectRetain(obj);
1238 g.printer_obj = obj;
1239 keepLooking = false;
1240 }
1241 }
1242 else
1243 {
1244 if (g.printer_obj != 0)
1245 IOObjectRelease(g.printer_obj);
1246
1247 g.printer_obj = obj;
1248 IOObjectRetain(obj);
1249
1250 if (g.location == 0 || g.location == location)
1251 keepLooking = false;
1252 }
1253 if ( !keepLooking )
1254 g.interfaceNum = interfaceNum;
1255 }
1256 }
1257
1258 release_deviceinfo(&make, &model, &serial);
1259 CFRelease(idString);
1260 }
1261 }
1262 else
1263 {
1264 keepLooking = (g.printer_obj == 0);
1265 if (obj == 0x0 && keepLooking)
1266 {
1267 CFRunLoopTimerContext context = { 0, refcon, NULL, NULL, NULL };
1268 CFRunLoopTimerRef timer = CFRunLoopTimerCreate(NULL, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb, &context);
1269 if (timer != NULL)
1270 {
1271 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode);
1272 g.status_timer = timer;
1273 }
1274 }
1275 }
1276
1277 if (!keepLooking && g.status_timer != NULL)
1278 {
1279 fputs("STATE: -offline-report\n", stderr);
1280 _cupsLangPuts(stderr, _("INFO: Printer is now online.\n"));
1281 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g.status_timer, kCFRunLoopDefaultMode);
1282 CFRelease(g.status_timer);
1283 g.status_timer = NULL;
1284 }
1285
1286 return keepLooking;
1287 }
1288
1289
1290 /*
1291 * 'status_timer_cb()' - Status timer callback.
1292 */
1293
1294 static void status_timer_cb(CFRunLoopTimerRef timer,
1295 void *info)
1296 {
1297 fputs("STATE: +offline-report\n", stderr);
1298 _cupsLangPuts(stderr, _("INFO: Printer is offline.\n"));
1299
1300 if (getenv("CLASS") != NULL)
1301 {
1302 /*
1303 * If the CLASS environment variable is set, the job was submitted
1304 * to a class and not to a specific queue. In this case, we want
1305 * to abort immediately so that the job can be requeued on the next
1306 * available printer in the class.
1307 *
1308 * Sleep 5 seconds to keep the job from requeuing too rapidly...
1309 */
1310
1311 sleep(5);
1312
1313 exit(CUPS_BACKEND_FAILED);
1314 }
1315 }
1316
1317
1318 #pragma mark -
1319 /*
1320 * 'copy_deviceinfo()' - Copy strings from the 1284 device ID.
1321 */
1322
1323 static void copy_deviceinfo(CFStringRef deviceIDString,
1324 CFStringRef *make,
1325 CFStringRef *model,
1326 CFStringRef *serial)
1327 {
1328 CFStringRef modelKeys[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL };
1329 CFStringRef makeKeys[] = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL };
1330 CFStringRef serialKeys[] = { CFSTR("SN:"), CFSTR("SERN:"), NULL };
1331
1332 if (make != NULL)
1333 *make = copy_value_for_key(deviceIDString, makeKeys);
1334
1335 if (model != NULL)
1336 *model = copy_value_for_key(deviceIDString, modelKeys);
1337
1338 if (serial != NULL)
1339 *serial = copy_value_for_key(deviceIDString, serialKeys);
1340 }
1341
1342
1343 /*
1344 * 'release_deviceinfo()' - Release deviceinfo strings.
1345 */
1346
1347 static void release_deviceinfo(CFStringRef *make,
1348 CFStringRef *model,
1349 CFStringRef *serial)
1350 {
1351 if (make != NULL && *make != NULL)
1352 {
1353 CFRelease(*make);
1354 *make = NULL;
1355 }
1356
1357 if (model != NULL && *model != NULL)
1358 {
1359 CFRelease(*model);
1360 *model = NULL;
1361 }
1362
1363 if (serial != NULL && *serial != NULL)
1364 {
1365 CFRelease(*serial);
1366 *serial = NULL;
1367 }
1368 }
1369
1370
1371 #pragma mark -
1372 /*
1373 * 'load_classdriver()' - Load a classdriver.
1374 */
1375
1376 static kern_return_t load_classdriver(CFStringRef driverPath,
1377 printer_interface_t intf,
1378 classdriver_t ***printerDriver)
1379 {
1380 kern_return_t kr = kUSBPrinterClassDeviceNotOpen;
1381 classdriver_t **driver = NULL;
1382 CFStringRef bundle = driverPath ? driverPath : kUSBGenericTOPrinterClassDriver;
1383 char bundlestr[1024]; /* Bundle path */
1384 struct stat bundleinfo; /* File information for bundle */
1385 CFURLRef url; /* URL for driver */
1386 CFPlugInRef plugin = NULL; /* Plug-in address */
1387
1388
1389 CFStringGetCString(bundle, bundlestr, sizeof(bundlestr), kCFStringEncodingUTF8);
1390
1391 /*
1392 * Validate permissions for the class driver...
1393 */
1394
1395 if (stat(bundlestr, &bundleinfo))
1396 {
1397 fprintf(stderr, "DEBUG: Unable to load class driver \"%s\": %s\n",
1398 bundlestr, strerror(errno));
1399 if (errno == ENOENT)
1400 return (load_classdriver(NULL, intf, printerDriver));
1401 else
1402 return (kr);
1403 }
1404 else if (bundleinfo.st_mode & S_IWOTH)
1405 {
1406 fprintf(stderr, "DEBUG: Unable to load class driver \"%s\": insecure file "
1407 "permissions (0%o)\n", bundlestr, bundleinfo.st_mode);
1408 return (kr);
1409 }
1410
1411 /*
1412 * Try loading the class driver...
1413 */
1414
1415 url = CFURLCreateWithFileSystemPath(NULL, bundle, kCFURLPOSIXPathStyle, true);
1416
1417 if (url)
1418 {
1419 plugin = CFPlugInCreate(NULL, url);
1420 CFRelease(url);
1421 }
1422 else
1423 plugin = NULL;
1424
1425 if (plugin)
1426 {
1427 CFArrayRef factories = CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID, plugin);
1428 if (factories != NULL && CFArrayGetCount(factories) > 0)
1429 {
1430 CFUUIDRef factoryID = CFArrayGetValueAtIndex(factories, 0);
1431 IUnknownVTbl **iunknown = CFPlugInInstanceCreate(NULL, factoryID, kUSBPrinterClassTypeID);
1432 if (iunknown != NULL)
1433 {
1434 kr = (*iunknown)->QueryInterface(iunknown, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID), (LPVOID *)&driver);
1435 if (kr == kIOReturnSuccess && driver != NULL)
1436 {
1437 classdriver_t **genericDriver = NULL;
1438 if (driverPath != NULL && CFStringCompare(driverPath, kUSBGenericTOPrinterClassDriver, 0) != kCFCompareEqualTo)
1439 kr = load_classdriver(NULL, intf, &genericDriver);
1440
1441 if (kr == kIOReturnSuccess)
1442 {
1443 (*driver)->interface = intf;
1444 (*driver)->Initialize(driver, genericDriver);
1445
1446 (*driver)->plugin = plugin;
1447 (*driver)->interface = intf;
1448 *printerDriver = driver;
1449 }
1450 }
1451 (*iunknown)->Release(iunknown);
1452 }
1453 CFRelease(factories);
1454 }
1455 }
1456
1457 fprintf(stderr, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr, (int)kr);
1458
1459 return (kr);
1460 }
1461
1462
1463 /*
1464 * 'unload_classdriver()' - Unload a classdriver.
1465 */
1466
1467 static kern_return_t unload_classdriver(classdriver_t ***classdriver)
1468 {
1469 if (*classdriver != NULL)
1470 {
1471 (**classdriver)->Release(*classdriver);
1472 *classdriver = NULL;
1473 }
1474
1475 return kIOReturnSuccess;
1476 }
1477
1478
1479 /*
1480 * 'load_printerdriver()' - Load vendor's classdriver.
1481 *
1482 * If driverBundlePath is not NULL on return it is the callers responsbility to release it!
1483 */
1484
1485 static kern_return_t load_printerdriver(CFStringRef *driverBundlePath)
1486 {
1487 IOCFPlugInInterface **iodev = NULL;
1488 SInt32 score;
1489 kern_return_t kr;
1490 printer_interface_t intf;
1491 HRESULT res;
1492
1493 kr = IOCreatePlugInInterfaceForService(g.printer_obj, kIOUSBInterfaceUserClientTypeID, kIOCFPlugInInterfaceID, &iodev, &score);
1494 if (kr == kIOReturnSuccess)
1495 {
1496 if ((res = (*iodev)->QueryInterface(iodev, USB_INTERFACE_KIND, (LPVOID *) &intf)) == noErr)
1497 {
1498 *driverBundlePath = IORegistryEntryCreateCFProperty(g.printer_obj, kUSBClassDriverProperty, NULL, kNilOptions);
1499
1500 kr = load_classdriver(*driverBundlePath, intf, &g.classdriver);
1501
1502 if (kr != kIOReturnSuccess)
1503 (*intf)->Release(intf);
1504 }
1505 IODestroyPlugInInterface(iodev);
1506 }
1507 return kr;
1508 }
1509
1510
1511 /*
1512 * 'registry_open()' - Open a connection to the printer.
1513 */
1514
1515 static kern_return_t registry_open(CFStringRef *driverBundlePath)
1516 {
1517 g.bidi_flag = 0; /* 0=unidirectional */
1518
1519 kern_return_t kr = load_printerdriver(driverBundlePath);
1520 if (kr != kIOReturnSuccess)
1521 kr = -2;
1522
1523 if (g.classdriver != NULL)
1524 {
1525 (*g.classdriver)->interfaceNumber = g.interfaceNum;
1526 kr = (*g.classdriver)->Open(g.classdriver, g.location, kUSBPrintingProtocolBidirectional);
1527 if (kr != kIOReturnSuccess || (*g.classdriver)->interface == NULL)
1528 {
1529 kr = (*g.classdriver)->Open(g.classdriver, g.location, kUSBPrintingProtocolUnidirectional);
1530 if (kr == kIOReturnSuccess)
1531 {
1532 if ((*g.classdriver)->interface == NULL)
1533 {
1534 (*g.classdriver)->Close(g.classdriver);
1535 kr = -1;
1536 }
1537 }
1538 }
1539 else
1540 g.bidi_flag = 1; /* 1=bidirectional */
1541 }
1542
1543 if (kr != kIOReturnSuccess)
1544 unload_classdriver(&g.classdriver);
1545
1546 return kr;
1547 }
1548
1549
1550 /*
1551 * 'registry_close()' - Close the connection to the printer.
1552 */
1553
1554 static kern_return_t registry_close()
1555 {
1556 if (g.classdriver != NULL)
1557 (*g.classdriver)->Close(g.classdriver);
1558
1559 unload_classdriver(&g.classdriver);
1560 return kIOReturnSuccess;
1561 }
1562
1563
1564 /*
1565 * 'copy_deviceid()' - Copy the 1284 device id string.
1566 */
1567
1568 static OSStatus copy_deviceid(classdriver_t **classdriver,
1569 CFStringRef *deviceID)
1570 {
1571 CFStringRef devID = NULL,
1572
1573 deviceMake = NULL,
1574 deviceModel = NULL,
1575 deviceSerial = NULL;
1576
1577 OSStatus err = (*classdriver)->GetDeviceID(classdriver, &devID, DEFAULT_TIMEOUT);
1578
1579 copy_deviceinfo(devID, &deviceMake, &deviceModel, &deviceSerial);
1580
1581 if (deviceMake == NULL || deviceModel == NULL || deviceSerial == NULL)
1582 {
1583 IOUSBDeviceDescriptor desc;
1584 iodevice_request_t request;
1585
1586 request.requestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
1587 request.request = kUSBRqGetDescriptor;
1588 request.value = (kUSBDeviceDesc << 8) | 0;
1589 request.index = 0;
1590 request.length = sizeof(desc);
1591 request.buffer = &desc;
1592 err = (*classdriver)->DeviceRequest(classdriver, &request, DEFAULT_TIMEOUT);
1593 if (err == kIOReturnSuccess)
1594 {
1595 CFMutableStringRef newDevID = CFStringCreateMutable(NULL, 0);
1596
1597 if (deviceMake == NULL)
1598 {
1599 CFStringRef data = NULL;
1600 err = (*classdriver)->GetString(classdriver, desc.iManufacturer, kUSBLanguageEnglish, DEFAULT_TIMEOUT, &data);
1601 if (data != NULL)
1602 {
1603 CFStringAppendFormat(newDevID, NULL, CFSTR("MFG:%@;"), data);
1604 CFRelease(data);
1605 }
1606 }
1607
1608 if (deviceModel == NULL)
1609 {
1610 CFStringRef data = NULL;
1611 err = (*classdriver)->GetString(classdriver, desc.iProduct, kUSBLanguageEnglish, DEFAULT_TIMEOUT, &data);
1612 if (data != NULL)
1613 {
1614 CFStringAppendFormat(newDevID, NULL, CFSTR("MDL:%@;"), data);
1615 CFRelease(data);
1616 }
1617 }
1618
1619 if (deviceSerial == NULL && desc.iSerialNumber != 0)
1620 {
1621 CFStringRef data = NULL;
1622 err = (*classdriver)->GetString(classdriver, desc.iSerialNumber, kUSBLanguageEnglish, DEFAULT_TIMEOUT, &data);
1623 if (data != NULL)
1624 {
1625 CFStringAppendFormat(newDevID, NULL, CFSTR("SERN:%@;"), data);
1626 CFRelease(data);
1627 }
1628 }
1629
1630 if (devID != NULL)
1631 {
1632 CFStringAppend(newDevID, devID);
1633 CFRelease(devID);
1634 }
1635
1636 *deviceID = newDevID;
1637 }
1638 }
1639 else
1640 {
1641 *deviceID = devID;
1642 }
1643 release_deviceinfo(&deviceMake, &deviceModel, &deviceSerial);
1644
1645 return err;
1646 }
1647
1648
1649 /*
1650 * 'copy_devicestring()' - Copy the 1284 device id string.
1651 */
1652
1653 static void copy_devicestring(io_service_t usbInterface,
1654 CFStringRef *deviceID,
1655 UInt32 *deviceLocation,
1656 UInt8 *interfaceNumber )
1657 {
1658 IOCFPlugInInterface **iodev = NULL;
1659 SInt32 score;
1660 kern_return_t kr;
1661 printer_interface_t intf;
1662 HRESULT res;
1663 classdriver_t **klassDriver = NULL;
1664 CFStringRef driverBundlePath;
1665
1666 if ((kr = IOCreatePlugInInterfaceForService(usbInterface,
1667 kIOUSBInterfaceUserClientTypeID,
1668 kIOCFPlugInInterfaceID,
1669 &iodev, &score)) == kIOReturnSuccess)
1670 {
1671 if ((res = (*iodev)->QueryInterface(iodev, USB_INTERFACE_KIND, (LPVOID *)
1672 &intf)) == noErr)
1673 {
1674 (*intf)->GetLocationID(intf, deviceLocation);
1675 (*intf)->GetInterfaceNumber(intf, interfaceNumber);
1676
1677 driverBundlePath = IORegistryEntryCreateCFProperty(usbInterface,
1678 kUSBClassDriverProperty,
1679 NULL, kNilOptions);
1680
1681 kr = load_classdriver(driverBundlePath, intf, &klassDriver);
1682
1683 if (kr != kIOReturnSuccess && driverBundlePath != NULL)
1684 kr = load_classdriver(NULL, intf, &klassDriver);
1685
1686 if (kr == kIOReturnSuccess && klassDriver != NULL)
1687 kr = copy_deviceid(klassDriver, deviceID);
1688
1689 unload_classdriver(&klassDriver);
1690
1691 if (driverBundlePath != NULL)
1692 CFRelease(driverBundlePath);
1693
1694 /* (*intf)->Release(intf); */
1695 }
1696 IODestroyPlugInInterface(iodev);
1697 }
1698 }
1699
1700
1701 #pragma mark -
1702 /*
1703 * 'copy_value_for_key()' - Copy value string associated with a key.
1704 */
1705
1706 static CFStringRef copy_value_for_key(CFStringRef deviceID,
1707 CFStringRef *keys)
1708 {
1709 CFStringRef value = NULL;
1710 CFArrayRef kvPairs = deviceID != NULL ? CFStringCreateArrayBySeparatingStrings(NULL, deviceID, CFSTR(";")) : NULL;
1711 CFIndex max = kvPairs != NULL ? CFArrayGetCount(kvPairs) : 0;
1712 CFIndex idx = 0;
1713
1714 while (idx < max && value == NULL)
1715 {
1716 CFStringRef kvpair = CFArrayGetValueAtIndex(kvPairs, idx);
1717 CFIndex idxx = 0;
1718 while (keys[idxx] != NULL && value == NULL)
1719 {
1720 CFRange range = CFStringFind(kvpair, keys[idxx], kCFCompareCaseInsensitive);
1721 if (range.length != -1)
1722 {
1723 if (range.location != 0)
1724 {
1725 CFMutableStringRef theString = CFStringCreateMutableCopy(NULL, 0, kvpair);
1726 CFStringTrimWhitespace(theString);
1727 range = CFStringFind(theString, keys[idxx], kCFCompareCaseInsensitive);
1728 if (range.location == 0)
1729 value = CFStringCreateWithSubstring(NULL, theString, CFRangeMake(range.length, CFStringGetLength(theString) - range.length));
1730
1731 CFRelease(theString);
1732 }
1733 else
1734 {
1735 CFStringRef theString = CFStringCreateWithSubstring(NULL, kvpair, CFRangeMake(range.length, CFStringGetLength(kvpair) - range.length));
1736 CFMutableStringRef theString2 = CFStringCreateMutableCopy(NULL, 0, theString);
1737 CFRelease(theString);
1738
1739 CFStringTrimWhitespace(theString2);
1740 value = theString2;
1741 }
1742 }
1743 idxx++;
1744 }
1745 idx++;
1746 }
1747
1748 if (kvPairs != NULL)
1749 CFRelease(kvPairs);
1750 return value;
1751 }
1752
1753
1754 /*
1755 * 'cfstr_create_trim()' - Create CFString and trim whitespace characters.
1756 */
1757
1758 CFStringRef cfstr_create_trim(const char *cstr)
1759 {
1760 CFStringRef cfstr;
1761 CFMutableStringRef cfmutablestr = NULL;
1762
1763 if ((cfstr = CFStringCreateWithCString(NULL, cstr, kCFStringEncodingUTF8)) != NULL)
1764 {
1765 if ((cfmutablestr = CFStringCreateMutableCopy(NULL, 1024, cfstr)) != NULL)
1766 CFStringTrimWhitespace(cfmutablestr);
1767
1768 CFRelease(cfstr);
1769 }
1770 return (CFStringRef) cfmutablestr;
1771 }
1772
1773
1774 #pragma mark -
1775 /*
1776 * 'parse_options()' - Parse URI options.
1777 */
1778
1779 static void parse_options(char *options,
1780 char *serial,
1781 int serial_size,
1782 UInt32 *location,
1783 Boolean *wait_eof)
1784 {
1785 char sep, /* Separator character */
1786 *name, /* Name of option */
1787 *value; /* Value of option */
1788
1789
1790 if (serial)
1791 *serial = '\0';
1792 if (location)
1793 *location = 0;
1794
1795 if (!options)
1796 return;
1797
1798 while (*options)
1799 {
1800 /*
1801 * Get the name...
1802 */
1803
1804 name = options;
1805
1806 while (*options && *options != '=' && *options != '+' && *options != '&')
1807 options ++;
1808
1809 if ((sep = *options) != '\0')
1810 *options++ = '\0';
1811
1812 if (sep == '=')
1813 {
1814 /*
1815 * Get the value...
1816 */
1817
1818 value = options;
1819
1820 while (*options && *options != '+' && *options != '&')
1821 options ++;
1822
1823 if (*options)
1824 *options++ = '\0';
1825 }
1826 else
1827 value = (char *)"";
1828
1829 /*
1830 * Process the option...
1831 */
1832
1833 if (!strcasecmp(name, "waiteof"))
1834 {
1835 if (!strcasecmp(value, "on") ||
1836 !strcasecmp(value, "yes") ||
1837 !strcasecmp(value, "true"))
1838 *wait_eof = true;
1839 else if (!strcasecmp(value, "off") ||
1840 !strcasecmp(value, "no") ||
1841 !strcasecmp(value, "false"))
1842 *wait_eof = false;
1843 else
1844 _cupsLangPrintf(stderr,
1845 _("WARNING: Boolean expected for waiteof option "
1846 "\"%s\"\n"), value);
1847 }
1848 else if (!strcasecmp(name, "serial"))
1849 strlcpy(serial, value, serial_size);
1850 else if (!strcasecmp(name, "location") && location)
1851 *location = strtol(value, NULL, 16);
1852 }
1853 }
1854
1855
1856 /*!
1857 * @function setup_cfLanguage
1858 * @abstract Convert the contents of the CUPS 'APPLE_LANGUAGE' environment
1859 * variable into a one element CF array of languages.
1860 *
1861 * @discussion Each submitted job comes with a natural language. CUPS passes
1862 * that language in an environment variable. We take that language
1863 * and jam it into the AppleLanguages array so that CF will use
1864 * it when reading localized resources. We need to do this before
1865 * any CF code reads and caches the languages array, so this function
1866 * should be called early in main()
1867 */
1868 static void setup_cfLanguage(void)
1869 {
1870 CFStringRef lang[1] = {NULL};
1871 CFArrayRef langArray = NULL;
1872 const char *requestedLang = NULL;
1873
1874 if ((requestedLang = getenv("APPLE_LANGUAGE")) == NULL)
1875 requestedLang = getenv("LANG");
1876
1877 if (requestedLang != NULL)
1878 {
1879 lang[0] = CFStringCreateWithCString(kCFAllocatorDefault, requestedLang, kCFStringEncodingUTF8);
1880 langArray = CFArrayCreate(kCFAllocatorDefault, (const void **)lang, sizeof(lang) / sizeof(lang[0]), &kCFTypeArrayCallBacks);
1881
1882 CFPreferencesSetValue(CFSTR("AppleLanguages"), langArray, kCFPreferencesCurrentApplication, kCFPreferencesAnyUser, kCFPreferencesAnyHost);
1883 fprintf(stderr, "DEBUG: usb: AppleLanguages=\"%s\"\n", requestedLang);
1884
1885 CFRelease(lang[0]);
1886 CFRelease(langArray);
1887 }
1888 else
1889 fputs("DEBUG: usb: LANG and APPLE_LANGUAGE environment variables missing.\n", stderr);
1890 }
1891
1892 #pragma mark -
1893 #if defined(__i386__) || defined(__x86_64__)
1894 /*!
1895 * @function run_legacy_backend
1896 *
1897 * @abstract Starts child backend process running as a ppc or i386 executable.
1898 *
1899 * @result Never returns; always calls exit().
1900 *
1901 * @discussion
1902 */
1903 static void run_legacy_backend(int argc,
1904 char *argv[],
1905 int fd)
1906 {
1907 int i;
1908 int exitstatus = 0;
1909 int childstatus;
1910 pid_t waitpid_status;
1911 char *my_argv[32];
1912 char *usb_legacy_status;
1913
1914 /*
1915 * If we're running as x86_64 or i386 and couldn't load the class driver
1916 * (because it's ppc or i386), then try to re-exec ourselves in ppc or i386
1917 * mode to try again. If we don't have a ppc or i386 architecture we may be
1918 * running with the same architecture again so guard against this by setting
1919 * and testing an environment variable...
1920 */
1921
1922 # ifdef __x86_64__
1923 usb_legacy_status = getenv("USB_I386_STATUS");
1924 # else
1925 usb_legacy_status = getenv("USB_PPC_STATUS");
1926 # endif /* __x86_64__ */
1927
1928 if (!usb_legacy_status)
1929 {
1930 /*
1931 * Setup a SIGTERM handler then block it before forking...
1932 */
1933
1934 int err; /* posix_spawn result */
1935 struct sigaction action; /* POSIX signal action */
1936 sigset_t newmask, /* New signal mask */
1937 oldmask; /* Old signal mask */
1938 char usbpath[1024]; /* Path to USB backend */
1939 const char *cups_serverbin;/* Path to CUPS binaries */
1940
1941
1942 memset(&action, 0, sizeof(action));
1943 sigaddset(&action.sa_mask, SIGTERM);
1944 action.sa_handler = sigterm_handler;
1945 sigaction(SIGTERM, &action, NULL);
1946
1947 sigemptyset(&newmask);
1948 sigaddset(&newmask, SIGTERM);
1949 sigprocmask(SIG_BLOCK, &newmask, &oldmask);
1950
1951 /*
1952 * Set the environment variable...
1953 */
1954
1955 # ifdef __x86_64__
1956 setenv("USB_I386_STATUS", "1", false);
1957 # else
1958 setenv("USB_PPC_STATUS", "1", false);
1959 # endif /* __x86_64__ */
1960
1961 /*
1962 * Tell the kernel to use the specified CPU architecture...
1963 */
1964
1965 # ifdef __x86_64__
1966 cpu_type_t cpu = CPU_TYPE_I386;
1967 # else
1968 cpu_type_t cpu = CPU_TYPE_POWERPC;
1969 # endif /* __x86_64__ */
1970 size_t ocount = 1;
1971 posix_spawnattr_t attrs;
1972
1973 if (!posix_spawnattr_init(&attrs))
1974 {
1975 posix_spawnattr_setsigdefault(&attrs, &oldmask);
1976 if (posix_spawnattr_setbinpref_np(&attrs, 1, &cpu, &ocount) || ocount != 1)
1977 {
1978 # ifdef __x86_64__
1979 perror("DEBUG: Unable to set binary preference to i386");
1980 # else
1981 perror("DEBUG: Unable to set binary preference to ppc");
1982 # endif /* __x86_64__ */
1983 _cupsLangPrintf(stderr, _("Unable to use legacy USB class driver\n"));
1984 exit(CUPS_BACKEND_STOP);
1985 }
1986 }
1987
1988 /*
1989 * Set up the arguments and call posix_spawn...
1990 */
1991
1992 if ((cups_serverbin = getenv("CUPS_SERVERBIN")) == NULL)
1993 cups_serverbin = CUPS_SERVERBIN;
1994 snprintf(usbpath, sizeof(usbpath), "%s/backend/usb", cups_serverbin);
1995
1996 for (i = 0; i < argc && i < (sizeof(my_argv) / sizeof(my_argv[0])) - 1; i ++)
1997 my_argv[i] = argv[i];
1998
1999 my_argv[i] = NULL;
2000
2001 if ((err = posix_spawn(&child_pid, usbpath, NULL, &attrs, my_argv,
2002 environ)) != 0)
2003 {
2004 fprintf(stderr, "DEBUG: Unable to exec %s: %s\n", usbpath,
2005 strerror(err));
2006 _cupsLangPrintf(stderr, _("Unable to use legacy USB class driver\n"));
2007 exit(CUPS_BACKEND_STOP);
2008 }
2009
2010 /*
2011 * Unblock signals...
2012 */
2013
2014 sigprocmask(SIG_SETMASK, &oldmask, NULL);
2015
2016 /*
2017 * Close the fds we won't be using then wait for the child backend to exit.
2018 */
2019
2020 close(fd);
2021 close(1);
2022
2023 fprintf(stderr, "DEBUG: Started usb(legacy) backend (PID %d)\n",
2024 (int)child_pid);
2025
2026 while ((waitpid_status = waitpid(child_pid, &childstatus, 0)) == (pid_t)-1 && errno == EINTR)
2027 usleep(1000);
2028
2029 if (WIFSIGNALED(childstatus))
2030 {
2031 exitstatus = CUPS_BACKEND_STOP;
2032 fprintf(stderr, "DEBUG: usb(legacy) backend %d crashed on signal %d\n",
2033 child_pid, WTERMSIG(childstatus));
2034 }
2035 else
2036 {
2037 if ((exitstatus = WEXITSTATUS(childstatus)) != 0)
2038 fprintf(stderr,
2039 "DEBUG: usb(legacy) backend %d stopped with status %d\n",
2040 child_pid, exitstatus);
2041 else
2042 fprintf(stderr, "DEBUG: usb(legacy) backend %d exited with no errors\n",
2043 child_pid);
2044 }
2045 }
2046 else
2047 {
2048 fputs("DEBUG: usb(legacy) backend running native again\n", stderr);
2049 exitstatus = CUPS_BACKEND_STOP;
2050 }
2051
2052 exit(exitstatus);
2053 }
2054
2055 /*
2056 * 'sigterm_handler()' - SIGTERM handler.
2057 */
2058
2059 static void
2060 sigterm_handler(int sig) /* I - Signal */
2061 {
2062 /* If we started a child process pass the signal on to it...
2063 */
2064 if (child_pid)
2065 {
2066 /*
2067 * If we started a child process pass the signal on to it...
2068 */
2069
2070 int status;
2071
2072 kill(child_pid, sig);
2073 while (waitpid(child_pid, &status, 0) < 0 && errno == EINTR);
2074
2075 if (WIFEXITED(status))
2076 exit(WEXITSTATUS(status));
2077 else if (status == SIGTERM || status == SIGKILL)
2078 exit(0);
2079 else
2080 {
2081 fprintf(stderr, "DEBUG: Child crashed on signal %d\n", status);
2082 exit(CUPS_BACKEND_STOP);
2083 }
2084 }
2085 }
2086
2087 #endif /* __i386__ || __x86_64__ */
2088
2089
2090 #ifdef PARSE_PS_ERRORS
2091 /*
2092 * 'next_line()' - Find the next line in a buffer.
2093 */
2094
2095 static const char *next_line (const char *buffer)
2096 {
2097 const char *cptr, *lptr = NULL;
2098
2099 for (cptr = buffer; *cptr && lptr == NULL; cptr++)
2100 if (*cptr == '\n' || *cptr == '\r')
2101 lptr = cptr;
2102 return lptr;
2103 }
2104
2105
2106 /*
2107 * 'parse_pserror()' - Scan the backchannel data for postscript errors.
2108 */
2109
2110 static void parse_pserror(char *sockBuffer,
2111 int len)
2112 {
2113 static char gErrorBuffer[1024] = "";
2114 static char *gErrorBufferPtr = gErrorBuffer;
2115 static char *gErrorBufferEndPtr = gErrorBuffer + sizeof(gErrorBuffer);
2116
2117 char *pCommentBegin, *pCommentEnd, *pLineEnd;
2118 char *logLevel;
2119 char logstr[1024];
2120 int logstrlen;
2121
2122 if (gErrorBufferPtr + len > gErrorBufferEndPtr - 1)
2123 gErrorBufferPtr = gErrorBuffer;
2124 if (len > sizeof(gErrorBuffer) - 1)
2125 len = sizeof(gErrorBuffer) - 1;
2126
2127 memcpy(gErrorBufferPtr, (const void *)sockBuffer, len);
2128 gErrorBufferPtr += len;
2129 *(gErrorBufferPtr + 1) = '\0';
2130
2131 pLineEnd = (char *)next_line((const char *)gErrorBuffer);
2132 while (pLineEnd != NULL)
2133 {
2134 *pLineEnd++ = '\0';
2135
2136 pCommentBegin = strstr(gErrorBuffer,"%%[");
2137 pCommentEnd = strstr(gErrorBuffer, "]%%");
2138 if (pCommentBegin != gErrorBuffer && pCommentEnd != NULL)
2139 {
2140 pCommentEnd += 3; /* Skip past "]%%" */
2141 *pCommentEnd = '\0'; /* There's always room for the nul */
2142
2143 if (strncasecmp(pCommentBegin, "%%[ Error:", 10) == 0)
2144 logLevel = "DEBUG";
2145 else if (strncasecmp(pCommentBegin, "%%[ Flushing", 12) == 0)
2146 logLevel = "DEBUG";
2147 else
2148 logLevel = "INFO";
2149
2150 if ((logstrlen = snprintf(logstr, sizeof(logstr), "%s: %s\n", logLevel, pCommentBegin)) >= sizeof(logstr))
2151 {
2152 /* If the string was trucnated make sure it has a linefeed before the nul */
2153 logstrlen = sizeof(logstr) - 1;
2154 logstr[logstrlen - 1] = '\n';
2155 }
2156 write(STDERR_FILENO, logstr, logstrlen);
2157 }
2158
2159 /* move everything over... */
2160 strcpy(gErrorBuffer, pLineEnd);
2161 gErrorBufferPtr = gErrorBuffer;
2162 pLineEnd = (char *)next_line((const char *)gErrorBuffer);
2163 }
2164 }
2165 #endif /* PARSE_PS_ERRORS */
2166
2167
2168 /*
2169 * 'soft_reset()' - Send a soft reset to the device.
2170 */
2171
2172 static void soft_reset()
2173 {
2174 fd_set input_set; /* Input set for select() */
2175 struct timeval stimeout; /* Timeout for select() */
2176 char buffer[2048]; /* Buffer */
2177 struct timespec cond_timeout; /* pthread condition timeout */
2178
2179 /*
2180 * Send an abort once a second until the I/O lock is released by the main thread...
2181 */
2182
2183 pthread_mutex_lock(&g.readwrite_lock_mutex);
2184 while (g.readwrite_lock)
2185 {
2186 (*g.classdriver)->Abort(g.classdriver);
2187
2188 cond_timeout.tv_sec = time(NULL) + 1;
2189 cond_timeout.tv_nsec = 0;
2190
2191 pthread_cond_timedwait(&g.readwrite_lock_cond, &g.readwrite_lock_mutex, &cond_timeout);
2192 }
2193
2194 g.readwrite_lock = 1;
2195 pthread_mutex_unlock(&g.readwrite_lock_mutex);
2196
2197 /*
2198 * Flush bytes waiting on print_fd...
2199 */
2200
2201 g.print_bytes = 0;
2202
2203 FD_ZERO(&input_set);
2204 FD_SET(g.print_fd, &input_set);
2205
2206 stimeout.tv_sec = 0;
2207 stimeout.tv_usec = 0;
2208
2209 while (select(g.print_fd+1, &input_set, NULL, NULL, &stimeout) > 0)
2210 if (read(g.print_fd, buffer, sizeof(buffer)) <= 0)
2211 break;
2212
2213 /*
2214 * Send the reset...
2215 */
2216
2217 (*g.classdriver)->SoftReset(g.classdriver, DEFAULT_TIMEOUT);
2218
2219 /*
2220 * Release the I/O lock...
2221 */
2222
2223 pthread_mutex_lock(&g.readwrite_lock_mutex);
2224 g.readwrite_lock = 0;
2225 pthread_cond_signal(&g.readwrite_lock_cond);
2226 pthread_mutex_unlock(&g.readwrite_lock_mutex);
2227 }
2228
2229
2230 /*
2231 * 'get_device_id()' - Return IEEE-1284 device ID.
2232 */
2233
2234 static void get_device_id(cups_sc_status_t *status,
2235 char *data,
2236 int *datalen)
2237 {
2238 CFStringRef deviceIDString = NULL;
2239
2240 /* GetDeviceID */
2241 copy_deviceid(g.classdriver, &deviceIDString);
2242
2243 if (deviceIDString)
2244 {
2245 CFStringGetCString(deviceIDString, data, *datalen, kCFStringEncodingUTF8);
2246 *datalen = strlen(data);
2247 CFRelease(deviceIDString);
2248 }
2249 *status = CUPS_SC_STATUS_OK;
2250 }
2251
2252
2253 /*
2254 * End of "$Id: usb-darwin.c 7953 2008-09-17 01:43:19Z mike $".
2255 */