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