2 * "$Id: usb-darwin.c 7953 2008-09-17 01:43:19Z mike $"
4 * Copyright 2005-2010 Apple Inc. All rights reserved.
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.
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.
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.
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.
46 * list_devices() - List all USB devices.
47 * print_device() - Print a file to a USB device.
48 * sidechannel_thread() - Thread to handle side-channel requests.
49 * read_thread() - Thread to read the backchannel data on.
50 * list_device_cb() - list_device iterator callback.
51 * find_device_cb() - print_device iterator callback.
52 * status_timer_cb() - Status timer callback.
53 * iterate_printers() - Iterate over all the printers.
54 * device_added() - Device added notifier.
55 * copy_deviceinfo() - Copy strings from the 1284 device ID.
56 * release_deviceinfo() - Release deviceinfo strings.
57 * load_classdriver() - Load a classdriver.
58 * unload_classdriver() - Unload a classdriver.
59 * load_printerdriver() - Load vendor's classdriver.
60 * registry_open() - Open a connection to the printer.
61 * registry_close() - Close the connection to the printer.
62 * copy_deviceid() - Copy the 1284 device id string.
63 * copy_devicestring() - Copy the 1284 device id string.
64 * copy_value_for_key() - Copy value string associated with a key.
65 * cfstr_create_trim() - Create CFString and trim whitespace characters.
66 * parse_options() - Parse uri options.
67 * setup_cfLanguage() - Create AppleLanguages array from LANG environment var.
68 * run_legacy_backend() - Re-exec backend as ppc or i386.
69 * sigterm_handler() - SIGTERM handler.
70 * next_line() - Find the next line in a buffer.
71 * parse_pserror() - Scan the backchannel data for postscript errors.
72 * get_device_id() - Return IEEE-1284 device ID.
76 * Include necessary headers.
87 #include <sys/sysctl.h>
89 #include <mach/mach.h>
90 #include <mach/mach_error.h>
91 #include <mach/mach_time.h>
92 #include <cups/debug-private.h>
93 #include <cups/sidechannel.h>
94 #include <cups/language-private.h>
95 #include "backend-private.h"
97 #include <CoreFoundation/CoreFoundation.h>
98 #include <IOKit/usb/IOUSBLib.h>
99 #include <IOKit/IOCFPlugIn.h>
104 extern char **environ
;
108 * DEBUG_WRITES, if defined, causes the backend to write data to the printer in
109 * 512 byte increments, up to 8192 bytes, to make debugging with a USB bus
113 #define DEBUG_WRITES 0
115 #define DEFAULT_TIMEOUT 5000L
117 #define USB_INTERFACE_KIND CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID190)
118 #define kUSBLanguageEnglish 0x409
120 #define PRINTER_POLLING_INTERVAL 5 /* seconds */
121 #define INITIAL_LOG_INTERVAL PRINTER_POLLING_INTERVAL
122 #define SUBSEQUENT_LOG_INTERVAL 3 * INITIAL_LOG_INTERVAL
124 #define kUSBPrinterClassTypeID CFUUIDGetConstantUUIDWithBytes(NULL, 0x06, 0x04, 0x7D, 0x16, 0x53, 0xA2, 0x11, 0xD6, 0x92, 0x06, 0x00, 0x30, 0x65, 0x52, 0x45, 0x92)
125 #define kUSBPrinterClassInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, 0x03, 0x34, 0x6D, 0x74, 0x53, 0xA3, 0x11, 0xD6, 0x9E, 0xA1, 0x76, 0x30, 0x65, 0x52, 0x45, 0x92)
127 #define kUSBClassDriverProperty CFSTR("USB Printing Class")
129 #define kUSBGenericTOPrinterClassDriver CFSTR("/System/Library/Printers/Libraries/USBGenericTOPrintingClass.plugin")
130 #define kUSBPrinterClassDeviceNotOpen -9664 /*kPMInvalidIOMContext*/
134 * Section 5.3 USB Printing Class spec
136 #define kUSBPrintingSubclass 1
137 #define kUSBPrintingProtocolNoOpen 0
138 #define kUSBPrintingProtocolUnidirectional 1
139 #define kUSBPrintingProtocolBidirectional 2
141 typedef IOUSBInterfaceInterface190
**printer_interface_t
;
143 typedef struct iodevice_request_s
/**** Device request ****/
151 } iodevice_request_t
;
153 typedef union /**** Centronics status byte ****/
158 unsigned reserved0
:2;
159 unsigned paperError
:1;
162 unsigned reserved1
:3;
164 } centronics_status_t
;
166 typedef struct classdriver_s
/**** g.classdriver context ****/
169 CFPlugInRef plugin
; /* release plugin */
170 IUnknownVTbl
**factory
; /* Factory */
171 void *vendorReference
; /* vendor class specific usage */
172 UInt32 location
; /* unique location in bus topology */
173 UInt8 interfaceNumber
; /* Interface number */
174 UInt16 vendorID
; /* Vendor id */
175 UInt16 productID
; /* Product id */
176 printer_interface_t interface
; /* identify the device to IOKit */
177 UInt8 outpipe
; /* mandatory bulkOut pipe */
178 UInt8 inpipe
; /* optional bulkIn pipe */
180 /* general class requests */
181 kern_return_t (*DeviceRequest
)(struct classdriver_s
**printer
, iodevice_request_t
*iorequest
, UInt16 timeout
);
182 kern_return_t (*GetString
)(struct classdriver_s
**printer
, UInt8 whichString
, UInt16 language
, UInt16 timeout
, CFStringRef
*result
);
184 /* standard printer class requests */
185 kern_return_t (*SoftReset
)(struct classdriver_s
**printer
, UInt16 timeout
);
186 kern_return_t (*GetCentronicsStatus
)(struct classdriver_s
**printer
, centronics_status_t
*result
, UInt16 timeout
);
187 kern_return_t (*GetDeviceID
)(struct classdriver_s
**printer
, CFStringRef
*devid
, UInt16 timeout
);
189 /* standard bulk device requests */
190 kern_return_t (*ReadPipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
);
191 kern_return_t (*WritePipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
, Boolean eoj
);
193 /* interface requests */
194 kern_return_t (*Open
)(struct classdriver_s
**printer
, UInt32 location
, UInt8 protocol
);
195 kern_return_t (*Abort
)(struct classdriver_s
**printer
);
196 kern_return_t (*Close
)(struct classdriver_s
**printer
);
198 /* initialize and terminate */
199 kern_return_t (*Initialize
)(struct classdriver_s
**printer
, struct classdriver_s
**baseclass
);
200 kern_return_t (*Terminate
)(struct classdriver_s
**printer
);
204 typedef Boolean (*iterator_callback_t
)(void *refcon
, io_service_t obj
);
206 typedef struct iterator_reference_s
/**** Iterator reference data */
208 iterator_callback_t callback
;
211 } iterator_reference_t
;
213 typedef struct globals_s
215 io_service_t printer_obj
;
216 classdriver_t
**classdriver
;
218 pthread_mutex_t read_thread_mutex
;
219 pthread_cond_t read_thread_cond
;
220 int read_thread_stop
;
221 int read_thread_done
;
223 pthread_mutex_t readwrite_lock_mutex
;
224 pthread_cond_t readwrite_lock_cond
;
233 CFRunLoopTimerRef status_timer
;
235 int print_fd
; /* File descriptor to print */
236 ssize_t print_bytes
; /* Print bytes read */
238 ssize_t debug_bytes
; /* Current bytes to read */
239 #endif /* DEBUG_WRITES */
242 int drain_output
; /* Drain all pending output */
243 int bidi_flag
; /* 0=unidirectional, 1=bidirectional */
251 globals_t g
= { 0 }; /* Globals */
258 static Boolean
find_device_cb(void *refcon
, io_service_t obj
);
259 static Boolean
list_device_cb(void *refcon
, io_service_t obj
);
260 static CFStringRef
cfstr_create_trim(const char *cstr
);
261 static CFStringRef
copy_value_for_key(CFStringRef deviceID
, CFStringRef
*keys
);
262 static kern_return_t
load_classdriver(CFStringRef driverPath
, printer_interface_t intf
, classdriver_t
***printerDriver
);
263 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
);
264 static kern_return_t
registry_close();
265 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
);
266 static kern_return_t
unload_classdriver();
267 static OSStatus
copy_deviceid(classdriver_t
**printer
, CFStringRef
*deviceID
);
268 static void *read_thread(void *reference
);
269 static void *sidechannel_thread(void *reference
);
270 static void copy_deviceinfo(CFStringRef deviceIDString
, CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
271 static void copy_devicestring(io_service_t usbInterface
, CFStringRef
*deviceID
, UInt32
*deviceLocation
, UInt8
*interfaceNum
);
272 static void device_added(void *userdata
, io_iterator_t iterator
);
273 static void get_device_id(cups_sc_status_t
*status
, char *data
, int *datalen
);
274 static void iterate_printers(iterator_callback_t callBack
, void *userdata
);
275 static void parse_options(char *options
, char *serial
, int serial_size
, UInt32
*location
, Boolean
*wait_eof
);
276 static void release_deviceinfo(CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
277 static void setup_cfLanguage(void);
278 static void soft_reset();
279 static void status_timer_cb(CFRunLoopTimerRef timer
, void *info
);
281 #if defined(__i386__) || defined(__x86_64__)
282 static pid_t child_pid
; /* Child PID */
283 static void run_legacy_backend(int argc
, char *argv
[], int fd
); /* Starts child backend process running as a ppc executable */
284 static void sigterm_handler(int sig
); /* SIGTERM handler */
285 #endif /* __i386__ || __x86_64__ */
287 #ifdef PARSE_PS_ERRORS
288 static const char *next_line (const char *buffer
);
289 static void parse_pserror (char *sockBuffer
, int len
);
290 #endif /* PARSE_PS_ERRORS */
295 * 'list_devices()' - List all USB devices.
300 iterate_printers(list_device_cb
, NULL
);
305 * 'print_device()' - Print a file to a USB device.
308 int /* O - Exit status */
309 print_device(const char *uri
, /* I - Device URI */
310 const char *hostname
, /* I - Hostname/manufacturer */
311 const char *resource
, /* I - Resource/modelname */
312 char *options
, /* I - Device options/serial number */
313 int print_fd
, /* I - File descriptor to print */
314 int copies
, /* I - Copies to print */
315 int argc
, /* I - Number of command-line arguments (6 or 7) */
316 char *argv
[]) /* I - Command-line arguments */
318 char serial
[1024]; /* Serial number buffer */
319 OSStatus status
; /* Function results */
320 IOReturn iostatus
; /* Current IO status */
321 pthread_t read_thread_id
, /* Read thread */
322 sidechannel_thread_id
;/* Side-channel thread */
323 int have_sidechannel
= 0; /* Was the side-channel thread started? */
324 struct stat sidechannel_info
; /* Side-channel file descriptor info */
325 char print_buffer
[8192], /* Print data buffer */
326 *print_ptr
; /* Pointer into print data buffer */
327 UInt32 location
; /* Unique location in bus topology */
328 fd_set input_set
; /* Input set for select() */
329 CFStringRef driverBundlePath
; /* Class driver path */
330 int countdown
, /* Logging interval */
331 nfds
; /* Number of file descriptors */
332 ssize_t total_bytes
; /* Total bytes written */
333 UInt32 bytes
; /* Bytes written */
334 struct timeval
*timeout
, /* Timeout pointer */
335 stimeout
; /* Timeout for select() */
339 * See if the side-channel descriptor is valid...
342 have_sidechannel
= !fstat(CUPS_SC_FD
, &sidechannel_info
) &&
343 S_ISSOCK(sidechannel_info
.st_mode
);
346 * Localize using CoreFoundation...
351 parse_options(options
, serial
, sizeof(serial
), &location
, &g
.wait_eof
);
353 if (resource
[0] == '/')
356 g
.print_fd
= print_fd
;
357 g
.make
= cfstr_create_trim(hostname
);
358 g
.model
= cfstr_create_trim(resource
);
359 g
.serial
= cfstr_create_trim(serial
);
360 g
.location
= location
;
362 if (!g
.make
|| !g
.model
)
364 fprintf(stderr
, "DEBUG: Fatal USB error.\n");
365 _cupsLangPuts(stderr
, _("ERROR: There was an unrecoverable USB error.\n"));
368 fputs("DEBUG: USB make string is NULL\n", stderr
);
370 fputs("DEBUG: USB model string is NULL\n", stderr
);
372 return (CUPS_BACKEND_STOP
);
375 fputs("STATE: +connecting-to-device\n", stderr
);
377 countdown
= INITIAL_LOG_INTERVAL
;
383 IOObjectRelease(g
.printer_obj
);
384 unload_classdriver(&g
.classdriver
);
389 fprintf(stderr
, "DEBUG: Looking for '%s %s'\n", hostname
, resource
);
391 iterate_printers(find_device_cb
, NULL
);
393 fputs("DEBUG: Opening connection\n", stderr
);
395 driverBundlePath
= NULL
;
397 status
= registry_open(&driverBundlePath
);
399 #if defined(__i386__) || defined(__x86_64__)
401 * If we were unable to load the class drivers for this printer it's
402 * probably because they're ppc or i386. In this case try to run this
403 * backend as i386 or ppc executables so we can use them...
407 run_legacy_backend(argc
, argv
, print_fd
);
408 /* Never returns here */
410 #endif /* __i386__ || __x86_64__ */
415 * If we still were unable to load the class drivers for this printer log
416 * the error and stop the queue...
419 if (driverBundlePath
== NULL
|| !CFStringGetCString(driverBundlePath
, print_buffer
, sizeof(print_buffer
), kCFStringEncodingUTF8
))
420 strlcpy(print_buffer
, "USB class driver", sizeof(print_buffer
));
422 fputs("STATE: +apple-missing-usbclassdriver-error\n", stderr
);
423 _cupsLangPuts(stderr
, _("ERROR: There was an unrecoverable USB error.\n"));
424 fprintf(stderr
, "DEBUG: Could not load %s\n", print_buffer
);
426 if (driverBundlePath
)
427 CFRelease(driverBundlePath
);
429 return (CUPS_BACKEND_STOP
);
432 if (driverBundlePath
)
433 CFRelease(driverBundlePath
);
437 sleep(PRINTER_POLLING_INTERVAL
);
438 countdown
-= PRINTER_POLLING_INTERVAL
;
441 _cupsLangPuts(stderr
,
442 _("INFO: Waiting for printer to become available...\n"));
443 fprintf(stderr
, "DEBUG: USB printer status: 0x%08x\n", (int)status
);
444 countdown
= SUBSEQUENT_LOG_INTERVAL
; /* subsequent log entries, every 15 seconds */
447 } while (status
!= noErr
);
449 fputs("STATE: -connecting-to-device\n", stderr
);
452 * Now that we are "connected" to the port, ignore SIGTERM so that we
453 * can finish out any page data the driver sends (e.g. to eject the
454 * current page... Only ignore SIGTERM if we are printing data from
455 * stdin (otherwise you can't cancel raw jobs...)
460 struct sigaction action
; /* POSIX signal action */
463 memset(&action
, 0, sizeof(action
));
465 sigemptyset(&action
.sa_mask
);
466 action
.sa_handler
= SIG_IGN
;
467 sigaction(SIGTERM
, &action
, NULL
);
471 * Start the side channel thread if the descriptor is valid...
474 pthread_mutex_init(&g
.readwrite_lock_mutex
, NULL
);
475 pthread_cond_init(&g
.readwrite_lock_cond
, NULL
);
476 g
.readwrite_lock
= 1;
478 if (have_sidechannel
)
480 if (pthread_create(&sidechannel_thread_id
, NULL
, sidechannel_thread
, NULL
))
482 fprintf(stderr
, "DEBUG: Fatal USB error.\n");
483 _cupsLangPuts(stderr
, _("ERROR: There was an unrecoverable USB error.\n"));
484 fputs("DEBUG: Couldn't create side-channel thread\n", stderr
);
486 return (CUPS_BACKEND_STOP
);
491 * Get the read thread going...
494 g
.read_thread_stop
= 0;
495 g
.read_thread_done
= 0;
497 pthread_cond_init(&g
.read_thread_cond
, NULL
);
498 pthread_mutex_init(&g
.read_thread_mutex
, NULL
);
500 if (pthread_create(&read_thread_id
, NULL
, read_thread
, NULL
))
502 fprintf(stderr
, "DEBUG: Fatal USB error.\n");
503 _cupsLangPuts(stderr
, _("ERROR: There was an unrecoverable USB error.\n"));
504 fputs("DEBUG: Couldn't create read thread\n", stderr
);
506 return (CUPS_BACKEND_STOP
);
510 * The main thread sends the print file...
516 print_ptr
= print_buffer
;
518 while (status
== noErr
&& copies
-- > 0)
520 _cupsLangPuts(stderr
, _("INFO: Sending print data...\n"));
522 if (print_fd
!= STDIN_FILENO
)
524 fputs("PAGE: 1 1\n", stderr
);
525 lseek(print_fd
, 0, SEEK_SET
);
528 while (status
== noErr
)
533 FD_SET(print_fd
, &input_set
);
536 * Calculate select timeout...
537 * If we have data waiting to send timeout is 100ms.
538 * else if we're draining print_fd timeout is 0.
539 * else we're waiting forever...
545 stimeout
.tv_usec
= 100000; /* 100ms */
548 else if (g
.drain_output
)
551 stimeout
.tv_usec
= 0;
558 * I/O is unlocked around select...
561 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
562 g
.readwrite_lock
= 0;
563 pthread_cond_signal(&g
.readwrite_lock_cond
);
564 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
566 nfds
= select(print_fd
+ 1, &input_set
, NULL
, NULL
, timeout
);
569 * Reacquire the lock...
572 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
573 while (g
.readwrite_lock
)
574 pthread_cond_wait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
);
575 g
.readwrite_lock
= 1;
576 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
580 if (errno
== EINTR
&& total_bytes
== 0)
582 fputs("DEBUG: Received an interrupt before any bytes were "
583 "written, aborting\n", stderr
);
585 return (CUPS_BACKEND_OK
);
587 else if (errno
!= EAGAIN
&& errno
!= EINTR
)
589 _cupsLangPuts(stderr
, _("ERROR: Unable to read print data.\n"));
590 perror("DEBUG: select");
592 return (CUPS_BACKEND_FAILED
);
597 * If drain output has finished send a response...
600 if (g
.drain_output
&& !nfds
&& !g
.print_bytes
)
602 /* Send a response... */
603 cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
608 * Check if we have print data ready...
611 if (FD_ISSET(print_fd
, &input_set
))
614 g
.debug_bytes
+= 512;
615 if (g
.debug_bytes
> sizeof(print_buffer
))
618 g
.print_bytes
= read(print_fd
, print_buffer
, g
.debug_bytes
);
621 g
.print_bytes
= read(print_fd
, print_buffer
, sizeof(print_buffer
));
622 #endif /* DEBUG_WRITES */
624 if (g
.print_bytes
< 0)
627 * Read error - bail if we don't see EAGAIN or EINTR...
630 if (errno
!= EAGAIN
&& errno
!= EINTR
)
632 _cupsLangPuts(stderr
, _("ERROR: Unable to read print data.\n"));
633 perror("DEBUG: read");
635 return (CUPS_BACKEND_FAILED
);
640 else if (g
.print_bytes
== 0)
643 * End of file, break out of the loop...
649 print_ptr
= print_buffer
;
651 fprintf(stderr
, "DEBUG: Read %d bytes of print data...\n",
657 bytes
= g
.print_bytes
;
658 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
661 * Ignore timeout errors, but retain the number of bytes written to
662 * avoid sending duplicate data (<rdar://problem/6254911>)...
665 if (iostatus
== kIOUSBTransactionTimeout
)
667 fputs("DEBUG: Got USB transaction timeout during write\n", stderr
);
672 * If we've stalled, retry the write...
675 else if (iostatus
== kIOUSBPipeStalled
)
677 fputs("DEBUG: Got USB pipe stalled during write\n", stderr
);
679 bytes
= g
.print_bytes
;
680 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
684 * Retry a write after an aborted write since we probably just got
685 * SIGTERM (<rdar://problem/6860126>)...
688 else if (iostatus
== kIOReturnAborted
)
690 fputs("DEBUG: Got USB return aborted during write\n", stderr
);
692 IOReturn err
= (*g
.classdriver
)->Abort(g
.classdriver
);
693 fprintf(stderr
, "DEBUG: USB class driver Abort returned %x\n", err
);
697 #endif /* DEBUG_WRITES */
699 bytes
= g
.print_bytes
;
700 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
703 if (iostatus
|| bytes
< 0)
706 * Write error - bail if we don't see an error we can retry...
708 _cupsLangPuts(stderr
, _("ERROR: Unable to send print data to printer.\n"));
709 fprintf(stderr
, "DEBUG: USB class driver WritePipe returned %x\n",
712 IOReturn err
= (*g
.classdriver
)->Abort(g
.classdriver
);
713 fprintf(stderr
, "DEBUG: USB class driver Abort returned %x\n",
716 status
= CUPS_BACKEND_FAILED
;
721 fprintf(stderr
, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes
);
723 g
.print_bytes
-= bytes
;
725 total_bytes
+= bytes
;
729 if (print_fd
!= 0 && status
== noErr
)
730 fprintf(stderr
, "DEBUG: Sending print file, %lld bytes...\n",
735 fprintf(stderr
, "DEBUG: Sent %lld bytes...\n", (off_t
)total_bytes
);
738 * Close the connection and input file and general clean up...
743 if (print_fd
!= STDIN_FILENO
)
752 if (g
.serial
!= NULL
)
755 if (g
.printer_obj
!= 0x0)
756 IOObjectRelease(g
.printer_obj
);
763 * 'read_thread()' - Thread to read the backchannel data on.
766 static void *read_thread(void *reference
)
768 UInt8 readbuffer
[512];
770 kern_return_t readstatus
;
771 struct mach_timebase_info timeBaseInfo
;
775 /* Calculate what 250 milliSeconds are in mach absolute time...
777 mach_timebase_info(&timeBaseInfo
);
778 delay
= ((uint64_t)250000000 * (uint64_t)timeBaseInfo
.denom
) / (uint64_t)timeBaseInfo
.numer
;
783 * Remember when we started so we can throttle the loop after the read call...
786 start
= mach_absolute_time();
788 rbytes
= sizeof(readbuffer
);
789 readstatus
= (*g
.classdriver
)->ReadPipe(g
.classdriver
, readbuffer
, &rbytes
);
790 if (readstatus
== kIOReturnSuccess
&& rbytes
> 0)
792 fprintf(stderr
, "DEBUG: Read %d bytes of back-channel data...\n",
794 cupsBackChannelWrite((char*)readbuffer
, rbytes
, 1.0);
796 /* cntrl-d is echoed by the printer.
798 * Xerox Phaser 6250D doesn't echo the cntrl-d.
799 * Xerox Phaser 6250D doesn't always send the product query.
801 if (g
.wait_eof
&& readbuffer
[rbytes
-1] == 0x4)
804 #ifdef PARSE_PS_ERRORS
805 parse_pserror(readbuffer
, rbytes
);
808 else if (readstatus
== kIOUSBTransactionTimeout
)
809 fputs("DEBUG: Got USB transaction timeout during read\n", stderr
);
810 else if (readstatus
== kIOUSBPipeStalled
)
811 fputs("DEBUG: Got USB pipe stalled during read\n", stderr
);
812 else if (readstatus
== kIOReturnAborted
)
813 fputs("DEBUG: Got USB return aborted during read\n", stderr
);
816 * Make sure this loop executes no more than once every 250 miliseconds...
819 if ((readstatus
!= kIOReturnSuccess
|| rbytes
== 0) && (g
.wait_eof
|| !g
.read_thread_stop
))
820 mach_wait_until(start
+ delay
);
822 } while (g
.wait_eof
|| !g
.read_thread_stop
); /* Abort from main thread tests error here */
825 * Let the main thread know that we have completed the read thread...
828 pthread_mutex_lock(&g
.read_thread_mutex
);
829 g
.read_thread_done
= 1;
830 pthread_cond_signal(&g
.read_thread_cond
);
831 pthread_mutex_unlock(&g
.read_thread_mutex
);
838 * 'sidechannel_thread()' - Handle side-channel requests.
842 sidechannel_thread(void *reference
)
844 cups_sc_command_t command
; /* Request command */
845 cups_sc_status_t status
; /* Request/response status */
846 char data
[2048]; /* Request/response data */
847 int datalen
; /* Request/response data size */
852 datalen
= sizeof(data
);
854 if (cupsSideChannelRead(&command
, &status
, data
, &datalen
, 1.0))
856 if (status
== CUPS_SC_STATUS_TIMEOUT
)
864 case CUPS_SC_CMD_SOFT_RESET
: /* Do a soft reset */
865 fputs("DEBUG: CUPS_SC_CMD_SOFT_RESET received from driver...\n",
868 if ((*g
.classdriver
)->SoftReset
!= NULL
)
871 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
872 fputs("DEBUG: Returning status CUPS_STATUS_OK with no bytes...\n",
877 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
879 fputs("DEBUG: Returning status CUPS_STATUS_NOT_IMPLEMENTED with "
880 "no bytes...\n", stderr
);
884 case CUPS_SC_CMD_DRAIN_OUTPUT
: /* Drain all pending output */
885 fputs("DEBUG: CUPS_SC_CMD_DRAIN_OUTPUT received from driver...\n",
891 case CUPS_SC_CMD_GET_BIDI
: /* Is the connection bidirectional? */
892 fputs("DEBUG: CUPS_SC_CMD_GET_BIDI received from driver...\n",
895 data
[0] = g
.bidi_flag
;
896 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
899 "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
903 case CUPS_SC_CMD_GET_DEVICE_ID
: /* Return IEEE-1284 device ID */
904 fputs("DEBUG: CUPS_SC_CMD_GET_DEVICE_ID received from driver...\n",
907 datalen
= sizeof(data
);
908 get_device_id(&status
, data
, &datalen
);
909 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, datalen
, 1.0);
911 if (datalen
< sizeof(data
))
912 data
[datalen
] = '\0';
914 data
[sizeof(data
) - 1] = '\0';
917 "DEBUG: Returning CUPS_SC_STATUS_OK with %d bytes (%s)...\n",
921 case CUPS_SC_CMD_GET_STATE
: /* Return device state */
922 fputs("DEBUG: CUPS_SC_CMD_GET_STATE received from driver...\n",
925 data
[0] = CUPS_SC_STATE_ONLINE
;
926 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
929 "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
934 fprintf(stderr
, "DEBUG: Unknown side-channel command (%d) received "
935 "from driver...\n", command
);
937 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
940 fputs("DEBUG: Returned CUPS_SC_STATUS_NOT_IMPLEMENTED with no bytes...\n",
953 * 'iterate_printers()' - Iterate over all the printers.
956 static void iterate_printers(iterator_callback_t callBack
,
959 mach_port_t masterPort
= 0x0;
960 kern_return_t kr
= IOMasterPort (bootstrap_port
, &masterPort
);
962 if (kr
== kIOReturnSuccess
&& masterPort
!= 0x0)
964 io_iterator_t addIterator
= 0x0;
966 iterator_reference_t reference
= { callBack
, userdata
, true };
967 IONotificationPortRef addNotification
= IONotificationPortCreate(masterPort
);
969 int klass
= kUSBPrintingClass
;
970 int subklass
= kUSBPrintingSubclass
;
972 CFNumberRef usb_klass
= CFNumberCreate(NULL
, kCFNumberIntType
, &klass
);
973 CFNumberRef usb_subklass
= CFNumberCreate(NULL
, kCFNumberIntType
, &subklass
);
974 CFMutableDictionaryRef usbPrinterMatchDictionary
= IOServiceMatching(kIOUSBInterfaceClassName
);
976 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceClass"), usb_klass
);
977 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceSubClass"), usb_subklass
);
979 CFRelease(usb_klass
);
980 CFRelease(usb_subklass
);
982 kr
= IOServiceAddMatchingNotification(addNotification
, kIOMatchedNotification
, usbPrinterMatchDictionary
, &device_added
, &reference
, &addIterator
);
983 if (addIterator
!= 0x0)
985 device_added (&reference
, addIterator
);
987 if (reference
.keepRunning
)
989 CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification
), kCFRunLoopDefaultMode
);
992 IOObjectRelease(addIterator
);
994 mach_port_deallocate(mach_task_self(), masterPort
);
1000 * 'device_added()' - Device added notifier.
1003 static void device_added(void *userdata
,
1004 io_iterator_t iterator
)
1006 iterator_reference_t
*reference
= userdata
;
1009 while (reference
->keepRunning
&& (obj
= IOIteratorNext(iterator
)) != 0x0)
1011 if (reference
->callback
!= NULL
)
1012 reference
->keepRunning
= reference
->callback(reference
->userdata
, obj
);
1014 IOObjectRelease(obj
);
1017 /* One last call to the call back now that we are not longer have printers left to iterate...
1019 if (reference
->keepRunning
)
1020 reference
->keepRunning
= reference
->callback(reference
->userdata
, 0x0);
1022 if (!reference
->keepRunning
)
1023 CFRunLoopStop(CFRunLoopGetCurrent());
1028 * 'list_device_cb()' - list_device iterator callback.
1031 static Boolean
list_device_cb(void *refcon
,
1034 Boolean keepRunning
= (obj
!= 0x0);
1038 CFStringRef deviceIDString
= NULL
;
1039 UInt32 deviceLocation
= 0;
1040 UInt8 interfaceNum
= 0;
1042 copy_devicestring(obj
, &deviceIDString
, &deviceLocation
, &interfaceNum
);
1043 if (deviceIDString
!= NULL
)
1045 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1046 char uristr
[1024], makestr
[1024], modelstr
[1024], serialstr
[1024];
1047 char optionsstr
[1024], idstr
[1024], make_modelstr
[1024];
1049 copy_deviceinfo(deviceIDString
, &make
, &model
, &serial
);
1050 CFStringGetCString(deviceIDString
, idstr
, sizeof(idstr
),
1051 kCFStringEncodingUTF8
);
1052 backendGetMakeModel(idstr
, make_modelstr
, sizeof(make_modelstr
));
1057 !CFStringGetCString(make
, makestr
, sizeof(makestr
),
1058 kCFStringEncodingUTF8
))
1059 strcpy(makestr
, "Unknown");
1062 !CFStringGetCString(model
, &modelstr
[1], sizeof(modelstr
)-1,
1063 kCFStringEncodingUTF8
))
1064 strcpy(modelstr
+ 1, "Printer");
1066 optionsstr
[0] = '\0';
1069 CFStringGetCString(serial
, serialstr
, sizeof(serialstr
), kCFStringEncodingUTF8
);
1070 snprintf(optionsstr
, sizeof(optionsstr
), "?serial=%s", serialstr
);
1072 else if (deviceLocation
!= 0)
1073 snprintf(optionsstr
, sizeof(optionsstr
), "?location=%x", (unsigned)deviceLocation
);
1075 httpAssembleURI(HTTP_URI_CODING_ALL
, uristr
, sizeof(uristr
), "usb", NULL
, makestr
, 0, modelstr
);
1076 strlcat(uristr
, optionsstr
, sizeof(uristr
));
1078 cupsBackendReport("direct", uristr
, make_modelstr
, make_modelstr
, idstr
,
1081 release_deviceinfo(&make
, &model
, &serial
);
1082 CFRelease(deviceIDString
);
1091 * 'find_device_cb()' - print_device iterator callback.
1094 static Boolean
find_device_cb(void *refcon
,
1097 Boolean keepLooking
= true;
1101 CFStringRef idString
= NULL
;
1102 UInt32 location
= -1;
1103 UInt8 interfaceNum
= 0;
1105 copy_devicestring(obj
, &idString
, &location
, &interfaceNum
);
1106 if (idString
!= NULL
)
1108 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1110 copy_deviceinfo(idString
, &make
, &model
, &serial
);
1111 if (make
&& CFStringCompare(make
, g
.make
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1113 if (model
&& CFStringCompare(model
, g
.model
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1115 if (g
.serial
!= NULL
&& CFStringGetLength(g
.serial
) > 0)
1117 if (serial
!= NULL
&& CFStringCompare(serial
, g
.serial
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1119 IOObjectRetain(obj
);
1120 g
.printer_obj
= obj
;
1121 keepLooking
= false;
1126 if (g
.printer_obj
!= 0)
1127 IOObjectRelease(g
.printer_obj
);
1129 g
.printer_obj
= obj
;
1130 IOObjectRetain(obj
);
1132 if (g
.location
== 0 || g
.location
== location
)
1133 keepLooking
= false;
1136 g
.interfaceNum
= interfaceNum
;
1140 release_deviceinfo(&make
, &model
, &serial
);
1141 CFRelease(idString
);
1146 keepLooking
= (g
.printer_obj
== 0);
1147 if (obj
== 0x0 && keepLooking
)
1149 CFRunLoopTimerContext context
= { 0, refcon
, NULL
, NULL
, NULL
};
1150 CFRunLoopTimerRef timer
= CFRunLoopTimerCreate(NULL
, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb
, &context
);
1153 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer
, kCFRunLoopDefaultMode
);
1154 g
.status_timer
= timer
;
1159 if (!keepLooking
&& g
.status_timer
!= NULL
)
1161 fputs("STATE: -offline-report\n", stderr
);
1162 _cupsLangPuts(stderr
, _("INFO: Printer is now online.\n"));
1163 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g
.status_timer
, kCFRunLoopDefaultMode
);
1164 CFRelease(g
.status_timer
);
1165 g
.status_timer
= NULL
;
1173 * 'status_timer_cb()' - Status timer callback.
1176 static void status_timer_cb(CFRunLoopTimerRef timer
,
1179 fputs("STATE: +offline-report\n", stderr
);
1180 _cupsLangPuts(stderr
, _("INFO: Printer is offline.\n"));
1182 if (getenv("CLASS") != NULL
)
1185 * If the CLASS environment variable is set, the job was submitted
1186 * to a class and not to a specific queue. In this case, we want
1187 * to abort immediately so that the job can be requeued on the next
1188 * available printer in the class.
1190 * Sleep 5 seconds to keep the job from requeuing too rapidly...
1195 exit(CUPS_BACKEND_FAILED
);
1202 * 'copy_deviceinfo()' - Copy strings from the 1284 device ID.
1205 static void copy_deviceinfo(CFStringRef deviceIDString
,
1208 CFStringRef
*serial
)
1210 CFStringRef modelKeys
[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL
};
1211 CFStringRef makeKeys
[] = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL
};
1212 CFStringRef serialKeys
[] = { CFSTR("SN:"), CFSTR("SERN:"), NULL
};
1215 *make
= copy_value_for_key(deviceIDString
, makeKeys
);
1218 *model
= copy_value_for_key(deviceIDString
, modelKeys
);
1221 *serial
= copy_value_for_key(deviceIDString
, serialKeys
);
1226 * 'release_deviceinfo()' - Release deviceinfo strings.
1229 static void release_deviceinfo(CFStringRef
*make
,
1231 CFStringRef
*serial
)
1233 if (make
!= NULL
&& *make
!= NULL
)
1239 if (model
!= NULL
&& *model
!= NULL
)
1245 if (serial
!= NULL
&& *serial
!= NULL
)
1255 * 'load_classdriver()' - Load a classdriver.
1258 static kern_return_t
load_classdriver(CFStringRef driverPath
,
1259 printer_interface_t intf
,
1260 classdriver_t
***printerDriver
)
1262 kern_return_t kr
= kUSBPrinterClassDeviceNotOpen
;
1263 classdriver_t
**driver
= NULL
;
1264 CFStringRef bundle
= driverPath
? driverPath
: kUSBGenericTOPrinterClassDriver
;
1265 char bundlestr
[1024]; /* Bundle path */
1266 struct stat bundleinfo
; /* File information for bundle */
1267 CFURLRef url
; /* URL for driver */
1268 CFPlugInRef plugin
= NULL
; /* Plug-in address */
1271 CFStringGetCString(bundle
, bundlestr
, sizeof(bundlestr
), kCFStringEncodingUTF8
);
1274 * Validate permissions for the class driver...
1277 if (stat(bundlestr
, &bundleinfo
))
1279 fprintf(stderr
, "DEBUG: Unable to load class driver \"%s\": %s\n",
1280 bundlestr
, strerror(errno
));
1283 else if (bundleinfo
.st_mode
& S_IWOTH
)
1285 fprintf(stderr
, "DEBUG: Unable to load class driver \"%s\": insecure file "
1286 "permissions (0%o)\n", bundlestr
, bundleinfo
.st_mode
);
1291 * Try loading the class driver...
1294 url
= CFURLCreateWithFileSystemPath(NULL
, bundle
, kCFURLPOSIXPathStyle
, true);
1298 plugin
= CFPlugInCreate(NULL
, url
);
1306 CFArrayRef factories
= CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID
, plugin
);
1307 if (factories
!= NULL
&& CFArrayGetCount(factories
) > 0)
1309 CFUUIDRef factoryID
= CFArrayGetValueAtIndex(factories
, 0);
1310 IUnknownVTbl
**iunknown
= CFPlugInInstanceCreate(NULL
, factoryID
, kUSBPrinterClassTypeID
);
1311 if (iunknown
!= NULL
)
1313 kr
= (*iunknown
)->QueryInterface(iunknown
, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID
), (LPVOID
*)&driver
);
1314 if (kr
== kIOReturnSuccess
&& driver
!= NULL
)
1316 classdriver_t
**genericDriver
= NULL
;
1317 if (driverPath
!= NULL
&& CFStringCompare(driverPath
, kUSBGenericTOPrinterClassDriver
, 0) != kCFCompareEqualTo
)
1318 kr
= load_classdriver(NULL
, intf
, &genericDriver
);
1320 if (kr
== kIOReturnSuccess
)
1322 (*driver
)->interface
= intf
;
1323 (*driver
)->Initialize(driver
, genericDriver
);
1325 (*driver
)->plugin
= plugin
;
1326 (*driver
)->interface
= intf
;
1327 *printerDriver
= driver
;
1330 (*iunknown
)->Release(iunknown
);
1332 CFRelease(factories
);
1336 fprintf(stderr
, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr
, (int)kr
);
1343 * 'unload_classdriver()' - Unload a classdriver.
1346 static kern_return_t
unload_classdriver(classdriver_t
***classdriver
)
1348 if (*classdriver
!= NULL
)
1350 (**classdriver
)->Release(*classdriver
);
1351 *classdriver
= NULL
;
1354 return kIOReturnSuccess
;
1359 * 'load_printerdriver()' - Load vendor's classdriver.
1361 * If driverBundlePath is not NULL on return it is the callers responsbility to release it!
1364 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
)
1366 IOCFPlugInInterface
**iodev
= NULL
;
1369 printer_interface_t intf
;
1372 kr
= IOCreatePlugInInterfaceForService(g
.printer_obj
, kIOUSBInterfaceUserClientTypeID
, kIOCFPlugInInterfaceID
, &iodev
, &score
);
1373 if (kr
== kIOReturnSuccess
)
1375 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*) &intf
)) == noErr
)
1377 *driverBundlePath
= IORegistryEntryCreateCFProperty(g
.printer_obj
, kUSBClassDriverProperty
, NULL
, kNilOptions
);
1379 kr
= load_classdriver(*driverBundlePath
, intf
, &g
.classdriver
);
1381 if (kr
!= kIOReturnSuccess
)
1382 (*intf
)->Release(intf
);
1384 IODestroyPlugInInterface(iodev
);
1391 * 'registry_open()' - Open a connection to the printer.
1394 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
)
1396 g
.bidi_flag
= 0; /* 0=unidirectional */
1398 kern_return_t kr
= load_printerdriver(driverBundlePath
);
1399 if (kr
!= kIOReturnSuccess
)
1402 if (g
.classdriver
!= NULL
)
1404 (*g
.classdriver
)->interfaceNumber
= g
.interfaceNum
;
1405 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolBidirectional
);
1406 if (kr
!= kIOReturnSuccess
|| (*g
.classdriver
)->interface
== NULL
)
1408 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolUnidirectional
);
1409 if (kr
== kIOReturnSuccess
)
1411 if ((*g
.classdriver
)->interface
== NULL
)
1413 (*g
.classdriver
)->Close(g
.classdriver
);
1419 g
.bidi_flag
= 1; /* 1=bidirectional */
1422 if (kr
!= kIOReturnSuccess
)
1423 unload_classdriver(&g
.classdriver
);
1430 * 'registry_close()' - Close the connection to the printer.
1433 static kern_return_t
registry_close()
1435 if (g
.classdriver
!= NULL
)
1436 (*g
.classdriver
)->Close(g
.classdriver
);
1438 unload_classdriver(&g
.classdriver
);
1439 return kIOReturnSuccess
;
1444 * 'copy_deviceid()' - Copy the 1284 device id string.
1447 static OSStatus
copy_deviceid(classdriver_t
**classdriver
,
1448 CFStringRef
*deviceID
)
1450 CFStringRef devID
= NULL
,
1454 deviceSerial
= NULL
;
1456 OSStatus err
= (*classdriver
)->GetDeviceID(classdriver
, &devID
, DEFAULT_TIMEOUT
);
1458 copy_deviceinfo(devID
, &deviceMake
, &deviceModel
, &deviceSerial
);
1460 if (deviceMake
== NULL
|| deviceModel
== NULL
|| deviceSerial
== NULL
)
1462 IOUSBDeviceDescriptor desc
;
1463 iodevice_request_t request
;
1465 request
.requestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
1466 request
.request
= kUSBRqGetDescriptor
;
1467 request
.value
= (kUSBDeviceDesc
<< 8) | 0;
1469 request
.length
= sizeof(desc
);
1470 request
.buffer
= &desc
;
1471 err
= (*classdriver
)->DeviceRequest(classdriver
, &request
, DEFAULT_TIMEOUT
);
1472 if (err
== kIOReturnSuccess
)
1474 CFMutableStringRef newDevID
= CFStringCreateMutable(NULL
, 0);
1476 if (deviceMake
== NULL
)
1478 CFStringRef data
= NULL
;
1479 err
= (*classdriver
)->GetString(classdriver
, desc
.iManufacturer
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1482 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MFG:%@;"), data
);
1487 if (deviceModel
== NULL
)
1489 CFStringRef data
= NULL
;
1490 err
= (*classdriver
)->GetString(classdriver
, desc
.iProduct
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1493 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MDL:%@;"), data
);
1498 if (deviceSerial
== NULL
&& desc
.iSerialNumber
!= 0)
1500 CFStringRef data
= NULL
;
1501 err
= (*classdriver
)->GetString(classdriver
, desc
.iSerialNumber
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1504 CFStringAppendFormat(newDevID
, NULL
, CFSTR("SERN:%@;"), data
);
1511 CFStringAppend(newDevID
, devID
);
1515 *deviceID
= newDevID
;
1522 release_deviceinfo(&deviceMake
, &deviceModel
, &deviceSerial
);
1529 * 'copy_devicestring()' - Copy the 1284 device id string.
1532 static void copy_devicestring(io_service_t usbInterface
,
1533 CFStringRef
*deviceID
,
1534 UInt32
*deviceLocation
,
1535 UInt8
*interfaceNumber
)
1537 IOCFPlugInInterface
**iodev
= NULL
;
1540 printer_interface_t intf
;
1542 classdriver_t
**klassDriver
= NULL
;
1543 CFStringRef driverBundlePath
;
1545 if ((kr
= IOCreatePlugInInterfaceForService(usbInterface
,
1546 kIOUSBInterfaceUserClientTypeID
,
1547 kIOCFPlugInInterfaceID
,
1548 &iodev
, &score
)) == kIOReturnSuccess
)
1550 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*)
1553 (*intf
)->GetLocationID(intf
, deviceLocation
);
1554 (*intf
)->GetInterfaceNumber(intf
, interfaceNumber
);
1556 driverBundlePath
= IORegistryEntryCreateCFProperty(usbInterface
,
1557 kUSBClassDriverProperty
,
1560 kr
= load_classdriver(driverBundlePath
, intf
, &klassDriver
);
1562 if (kr
!= kIOReturnSuccess
&& driverBundlePath
!= NULL
)
1563 kr
= load_classdriver(NULL
, intf
, &klassDriver
);
1565 if (kr
== kIOReturnSuccess
&& klassDriver
!= NULL
)
1566 kr
= copy_deviceid(klassDriver
, deviceID
);
1568 unload_classdriver(&klassDriver
);
1570 if (driverBundlePath
!= NULL
)
1571 CFRelease(driverBundlePath
);
1573 /* (*intf)->Release(intf); */
1575 IODestroyPlugInInterface(iodev
);
1582 * 'copy_value_for_key()' - Copy value string associated with a key.
1585 static CFStringRef
copy_value_for_key(CFStringRef deviceID
,
1588 CFStringRef value
= NULL
;
1589 CFArrayRef kvPairs
= deviceID
!= NULL
? CFStringCreateArrayBySeparatingStrings(NULL
, deviceID
, CFSTR(";")) : NULL
;
1590 CFIndex max
= kvPairs
!= NULL
? CFArrayGetCount(kvPairs
) : 0;
1593 while (idx
< max
&& value
== NULL
)
1595 CFStringRef kvpair
= CFArrayGetValueAtIndex(kvPairs
, idx
);
1597 while (keys
[idxx
] != NULL
&& value
== NULL
)
1599 CFRange range
= CFStringFind(kvpair
, keys
[idxx
], kCFCompareCaseInsensitive
);
1600 if (range
.length
!= -1)
1602 if (range
.location
!= 0)
1604 CFMutableStringRef theString
= CFStringCreateMutableCopy(NULL
, 0, kvpair
);
1605 CFStringTrimWhitespace(theString
);
1606 range
= CFStringFind(theString
, keys
[idxx
], kCFCompareCaseInsensitive
);
1607 if (range
.location
== 0)
1608 value
= CFStringCreateWithSubstring(NULL
, theString
, CFRangeMake(range
.length
, CFStringGetLength(theString
) - range
.length
));
1610 CFRelease(theString
);
1614 CFStringRef theString
= CFStringCreateWithSubstring(NULL
, kvpair
, CFRangeMake(range
.length
, CFStringGetLength(kvpair
) - range
.length
));
1615 CFMutableStringRef theString2
= CFStringCreateMutableCopy(NULL
, 0, theString
);
1616 CFRelease(theString
);
1618 CFStringTrimWhitespace(theString2
);
1627 if (kvPairs
!= NULL
)
1634 * 'cfstr_create_trim()' - Create CFString and trim whitespace characters.
1637 CFStringRef
cfstr_create_trim(const char *cstr
)
1640 CFMutableStringRef cfmutablestr
= NULL
;
1642 if ((cfstr
= CFStringCreateWithCString(NULL
, cstr
, kCFStringEncodingUTF8
)) != NULL
)
1644 if ((cfmutablestr
= CFStringCreateMutableCopy(NULL
, 1024, cfstr
)) != NULL
)
1645 CFStringTrimWhitespace(cfmutablestr
);
1649 return (CFStringRef
) cfmutablestr
;
1655 * 'parse_options()' - Parse URI options.
1658 static void parse_options(char *options
,
1664 char sep
, /* Separator character */
1665 *name
, /* Name of option */
1666 *value
; /* Value of option */
1685 while (*options
&& *options
!= '=' && *options
!= '+' && *options
!= '&')
1688 if ((sep
= *options
) != '\0')
1699 while (*options
&& *options
!= '+' && *options
!= '&')
1709 * Process the option...
1712 if (!strcasecmp(name
, "waiteof"))
1714 if (!strcasecmp(value
, "on") ||
1715 !strcasecmp(value
, "yes") ||
1716 !strcasecmp(value
, "true"))
1718 else if (!strcasecmp(value
, "off") ||
1719 !strcasecmp(value
, "no") ||
1720 !strcasecmp(value
, "false"))
1723 _cupsLangPrintf(stderr
,
1724 _("WARNING: Boolean expected for waiteof option "
1725 "\"%s\"\n"), value
);
1727 else if (!strcasecmp(name
, "serial"))
1728 strlcpy(serial
, value
, serial_size
);
1729 else if (!strcasecmp(name
, "location") && location
)
1730 *location
= strtol(value
, NULL
, 16);
1736 * @function setup_cfLanguage
1737 * @abstract Convert the contents of the CUPS 'APPLE_LANGUAGE' environment
1738 * variable into a one element CF array of languages.
1740 * @discussion Each submitted job comes with a natural language. CUPS passes
1741 * that language in an environment variable. We take that language
1742 * and jam it into the AppleLanguages array so that CF will use
1743 * it when reading localized resources. We need to do this before
1744 * any CF code reads and caches the languages array, so this function
1745 * should be called early in main()
1747 static void setup_cfLanguage(void)
1749 CFStringRef lang
[1] = {NULL
};
1750 CFArrayRef langArray
= NULL
;
1751 const char *requestedLang
= NULL
;
1753 if ((requestedLang
= getenv("APPLE_LANGUAGE")) == NULL
)
1754 requestedLang
= getenv("LANG");
1756 if (requestedLang
!= NULL
)
1758 lang
[0] = CFStringCreateWithCString(kCFAllocatorDefault
, requestedLang
, kCFStringEncodingUTF8
);
1759 langArray
= CFArrayCreate(kCFAllocatorDefault
, (const void **)lang
, sizeof(lang
) / sizeof(lang
[0]), &kCFTypeArrayCallBacks
);
1761 CFPreferencesSetValue(CFSTR("AppleLanguages"), langArray
, kCFPreferencesCurrentApplication
, kCFPreferencesAnyUser
, kCFPreferencesAnyHost
);
1762 fprintf(stderr
, "DEBUG: usb: AppleLanguages=\"%s\"\n", requestedLang
);
1765 CFRelease(langArray
);
1768 fputs("DEBUG: usb: LANG and APPLE_LANGUAGE environment variables missing.\n", stderr
);
1772 #if defined(__i386__) || defined(__x86_64__)
1774 * @function run_legacy_backend
1776 * @abstract Starts child backend process running as a ppc or i386 executable.
1778 * @result Never returns; always calls exit().
1782 static void run_legacy_backend(int argc
,
1789 pid_t waitpid_status
;
1791 char *usb_legacy_status
;
1794 * If we're running as x86_64 or i386 and couldn't load the class driver
1795 * (because it's ppc or i386), then try to re-exec ourselves in ppc or i386
1796 * mode to try again. If we don't have a ppc or i386 architecture we may be
1797 * running with the same architecture again so guard against this by setting
1798 * and testing an environment variable...
1802 usb_legacy_status
= getenv("USB_I386_STATUS");
1804 usb_legacy_status
= getenv("USB_PPC_STATUS");
1805 # endif /* __x86_64__ */
1807 if (!usb_legacy_status
)
1810 * Setup a SIGTERM handler then block it before forking...
1813 int err
; /* posix_spawn result */
1814 struct sigaction action
; /* POSIX signal action */
1815 sigset_t newmask
, /* New signal mask */
1816 oldmask
; /* Old signal mask */
1817 char usbpath
[1024]; /* Path to USB backend */
1818 const char *cups_serverbin
;/* Path to CUPS binaries */
1821 memset(&action
, 0, sizeof(action
));
1822 sigaddset(&action
.sa_mask
, SIGTERM
);
1823 action
.sa_handler
= sigterm_handler
;
1824 sigaction(SIGTERM
, &action
, NULL
);
1826 sigemptyset(&newmask
);
1827 sigaddset(&newmask
, SIGTERM
);
1828 sigprocmask(SIG_BLOCK
, &newmask
, &oldmask
);
1831 * Set the environment variable...
1835 setenv("USB_I386_STATUS", "1", false);
1837 setenv("USB_PPC_STATUS", "1", false);
1838 # endif /* __x86_64__ */
1841 * Tell the kernel to use the specified CPU architecture...
1845 cpu_type_t cpu
= CPU_TYPE_I386
;
1847 cpu_type_t cpu
= CPU_TYPE_POWERPC
;
1848 # endif /* __x86_64__ */
1850 posix_spawnattr_t attrs
;
1852 if (!posix_spawnattr_init(&attrs
))
1854 posix_spawnattr_setsigdefault(&attrs
, &oldmask
);
1855 if (posix_spawnattr_setbinpref_np(&attrs
, 1, &cpu
, &ocount
) || ocount
!= 1)
1858 perror("DEBUG: Unable to set binary preference to i386");
1860 perror("DEBUG: Unable to set binary preference to ppc");
1861 # endif /* __x86_64__ */
1862 _cupsLangPrintf(stderr
, _("Unable to use legacy USB class driver\n"));
1863 exit(CUPS_BACKEND_STOP
);
1868 * Set up the arguments and call posix_spawn...
1871 if ((cups_serverbin
= getenv("CUPS_SERVERBIN")) == NULL
)
1872 cups_serverbin
= CUPS_SERVERBIN
;
1873 snprintf(usbpath
, sizeof(usbpath
), "%s/backend/usb", cups_serverbin
);
1875 for (i
= 0; i
< argc
&& i
< (sizeof(my_argv
) / sizeof(my_argv
[0])) - 1; i
++)
1876 my_argv
[i
] = argv
[i
];
1880 if ((err
= posix_spawn(&child_pid
, usbpath
, NULL
, &attrs
, my_argv
,
1883 fprintf(stderr
, "DEBUG: Unable to exec %s: %s\n", usbpath
,
1885 _cupsLangPrintf(stderr
, _("Unable to use legacy USB class driver\n"));
1886 exit(CUPS_BACKEND_STOP
);
1890 * Unblock signals...
1893 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
1896 * Close the fds we won't be using then wait for the child backend to exit.
1902 fprintf(stderr
, "DEBUG: Started usb(legacy) backend (PID %d)\n",
1905 while ((waitpid_status
= waitpid(child_pid
, &childstatus
, 0)) == (pid_t
)-1 && errno
== EINTR
)
1908 if (WIFSIGNALED(childstatus
))
1910 exitstatus
= CUPS_BACKEND_STOP
;
1911 fprintf(stderr
, "DEBUG: usb(legacy) backend %d crashed on signal %d\n",
1912 child_pid
, WTERMSIG(childstatus
));
1916 if ((exitstatus
= WEXITSTATUS(childstatus
)) != 0)
1918 "DEBUG: usb(legacy) backend %d stopped with status %d\n",
1919 child_pid
, exitstatus
);
1921 fprintf(stderr
, "DEBUG: usb(legacy) backend %d exited with no errors\n",
1927 fputs("DEBUG: usb(legacy) backend running native again\n", stderr
);
1928 exitstatus
= CUPS_BACKEND_STOP
;
1935 * 'sigterm_handler()' - SIGTERM handler.
1939 sigterm_handler(int sig
) /* I - Signal */
1941 /* If we started a child process pass the signal on to it...
1946 * If we started a child process pass the signal on to it...
1951 kill(child_pid
, sig
);
1952 while (waitpid(child_pid
, &status
, 0) < 0 && errno
== EINTR
);
1954 if (WIFEXITED(status
))
1955 exit(WEXITSTATUS(status
));
1956 else if (status
== SIGTERM
|| status
== SIGKILL
)
1960 fprintf(stderr
, "DEBUG: Child crashed on signal %d\n", status
);
1961 exit(CUPS_BACKEND_STOP
);
1966 #endif /* __i386__ || __x86_64__ */
1969 #ifdef PARSE_PS_ERRORS
1971 * 'next_line()' - Find the next line in a buffer.
1974 static const char *next_line (const char *buffer
)
1976 const char *cptr
, *lptr
= NULL
;
1978 for (cptr
= buffer
; *cptr
&& lptr
== NULL
; cptr
++)
1979 if (*cptr
== '\n' || *cptr
== '\r')
1986 * 'parse_pserror()' - Scan the backchannel data for postscript errors.
1989 static void parse_pserror(char *sockBuffer
,
1992 static char gErrorBuffer
[1024] = "";
1993 static char *gErrorBufferPtr
= gErrorBuffer
;
1994 static char *gErrorBufferEndPtr
= gErrorBuffer
+ sizeof(gErrorBuffer
);
1996 char *pCommentBegin
, *pCommentEnd
, *pLineEnd
;
2001 if (gErrorBufferPtr
+ len
> gErrorBufferEndPtr
- 1)
2002 gErrorBufferPtr
= gErrorBuffer
;
2003 if (len
> sizeof(gErrorBuffer
) - 1)
2004 len
= sizeof(gErrorBuffer
) - 1;
2006 memcpy(gErrorBufferPtr
, (const void *)sockBuffer
, len
);
2007 gErrorBufferPtr
+= len
;
2008 *(gErrorBufferPtr
+ 1) = '\0';
2010 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
2011 while (pLineEnd
!= NULL
)
2015 pCommentBegin
= strstr(gErrorBuffer
,"%%[");
2016 pCommentEnd
= strstr(gErrorBuffer
, "]%%");
2017 if (pCommentBegin
!= gErrorBuffer
&& pCommentEnd
!= NULL
)
2019 pCommentEnd
+= 3; /* Skip past "]%%" */
2020 *pCommentEnd
= '\0'; /* There's always room for the nul */
2022 if (strncasecmp(pCommentBegin
, "%%[ Error:", 10) == 0)
2024 else if (strncasecmp(pCommentBegin
, "%%[ Flushing", 12) == 0)
2029 if ((logstrlen
= snprintf(logstr
, sizeof(logstr
), "%s: %s\n", logLevel
, pCommentBegin
)) >= sizeof(logstr
))
2031 /* If the string was trucnated make sure it has a linefeed before the nul */
2032 logstrlen
= sizeof(logstr
) - 1;
2033 logstr
[logstrlen
- 1] = '\n';
2035 write(STDERR_FILENO
, logstr
, logstrlen
);
2038 /* move everything over... */
2039 strcpy(gErrorBuffer
, pLineEnd
);
2040 gErrorBufferPtr
= gErrorBuffer
;
2041 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
2044 #endif /* PARSE_PS_ERRORS */
2048 * 'soft_reset()' - Send a soft reset to the device.
2051 static void soft_reset()
2053 fd_set input_set
; /* Input set for select() */
2054 struct timeval stimeout
; /* Timeout for select() */
2055 char buffer
[2048]; /* Buffer */
2056 struct timespec cond_timeout
; /* pthread condition timeout */
2059 * Send an abort once a second until the I/O lock is released by the main thread...
2062 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2063 while (g
.readwrite_lock
)
2065 (*g
.classdriver
)->Abort(g
.classdriver
);
2067 cond_timeout
.tv_sec
= time(NULL
) + 1;
2068 cond_timeout
.tv_nsec
= 0;
2070 pthread_cond_timedwait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
, &cond_timeout
);
2073 g
.readwrite_lock
= 1;
2074 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2077 * Flush bytes waiting on print_fd...
2082 FD_ZERO(&input_set
);
2083 FD_SET(g
.print_fd
, &input_set
);
2085 stimeout
.tv_sec
= 0;
2086 stimeout
.tv_usec
= 0;
2088 while (select(g
.print_fd
+1, &input_set
, NULL
, NULL
, &stimeout
) > 0)
2089 if (read(g
.print_fd
, buffer
, sizeof(buffer
)) <= 0)
2096 (*g
.classdriver
)->SoftReset(g
.classdriver
, DEFAULT_TIMEOUT
);
2099 * Release the I/O lock...
2102 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2103 g
.readwrite_lock
= 0;
2104 pthread_cond_signal(&g
.readwrite_lock_cond
);
2105 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2110 * 'get_device_id()' - Return IEEE-1284 device ID.
2113 static void get_device_id(cups_sc_status_t
*status
,
2117 CFStringRef deviceIDString
= NULL
;
2120 copy_deviceid(g
.classdriver
, &deviceIDString
);
2124 CFStringGetCString(deviceIDString
, data
, *datalen
, kCFStringEncodingUTF8
);
2125 *datalen
= strlen(data
);
2126 CFRelease(deviceIDString
);
2128 *status
= CUPS_SC_STATUS_OK
;
2133 * End of "$Id: usb-darwin.c 7953 2008-09-17 01:43:19Z mike $".