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