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