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