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