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