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