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