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