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