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