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
116 * WAIT_EOF_DELAY is number of seconds we'll wait for responses from
117 * the printer after we've finished sending all the data
119 #define WAIT_EOF_DELAY 7
120 #define WAIT_SIDE_DELAY 3
121 #define DEFAULT_TIMEOUT 5000L
123 #define USB_INTERFACE_KIND CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID190)
124 #define kUSBLanguageEnglish 0x409
126 #define PRINTER_POLLING_INTERVAL 5 /* seconds */
127 #define INITIAL_LOG_INTERVAL PRINTER_POLLING_INTERVAL
128 #define SUBSEQUENT_LOG_INTERVAL 3 * INITIAL_LOG_INTERVAL
130 #define kUSBPrinterClassTypeID CFUUIDGetConstantUUIDWithBytes(NULL, 0x06, 0x04, 0x7D, 0x16, 0x53, 0xA2, 0x11, 0xD6, 0x92, 0x06, 0x00, 0x30, 0x65, 0x52, 0x45, 0x92)
131 #define kUSBPrinterClassInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, 0x03, 0x34, 0x6D, 0x74, 0x53, 0xA3, 0x11, 0xD6, 0x9E, 0xA1, 0x76, 0x30, 0x65, 0x52, 0x45, 0x92)
133 #define kUSBClassDriverProperty CFSTR("USB Printing Class")
135 #define kUSBGenericTOPrinterClassDriver CFSTR("/System/Library/Printers/Libraries/USBGenericTOPrintingClass.plugin")
136 #define kUSBPrinterClassDeviceNotOpen -9664 /*kPMInvalidIOMContext*/
140 * Section 5.3 USB Printing Class spec
142 #define kUSBPrintingSubclass 1
143 #define kUSBPrintingProtocolNoOpen 0
144 #define kUSBPrintingProtocolUnidirectional 1
145 #define kUSBPrintingProtocolBidirectional 2
147 typedef IOUSBInterfaceInterface190
**printer_interface_t
;
149 typedef struct iodevice_request_s
/**** Device request ****/
157 } iodevice_request_t
;
159 typedef union /**** Centronics status byte ****/
164 unsigned reserved0
:2;
165 unsigned paperError
:1;
168 unsigned reserved1
:3;
170 } centronics_status_t
;
172 typedef struct classdriver_s
/**** g.classdriver context ****/
175 CFPlugInRef plugin
; /* release plugin */
176 IUnknownVTbl
**factory
; /* Factory */
177 void *vendorReference
; /* vendor class specific usage */
178 UInt32 location
; /* unique location in bus topology */
179 UInt8 interfaceNumber
; /* Interface number */
180 UInt16 vendorID
; /* Vendor id */
181 UInt16 productID
; /* Product id */
182 printer_interface_t interface
; /* identify the device to IOKit */
183 UInt8 outpipe
; /* mandatory bulkOut pipe */
184 UInt8 inpipe
; /* optional bulkIn pipe */
186 /* general class requests */
187 kern_return_t (*DeviceRequest
)(struct classdriver_s
**printer
, iodevice_request_t
*iorequest
, UInt16 timeout
);
188 kern_return_t (*GetString
)(struct classdriver_s
**printer
, UInt8 whichString
, UInt16 language
, UInt16 timeout
, CFStringRef
*result
);
190 /* standard printer class requests */
191 kern_return_t (*SoftReset
)(struct classdriver_s
**printer
, UInt16 timeout
);
192 kern_return_t (*GetCentronicsStatus
)(struct classdriver_s
**printer
, centronics_status_t
*result
, UInt16 timeout
);
193 kern_return_t (*GetDeviceID
)(struct classdriver_s
**printer
, CFStringRef
*devid
, UInt16 timeout
);
195 /* standard bulk device requests */
196 kern_return_t (*ReadPipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
);
197 kern_return_t (*WritePipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
, Boolean eoj
);
199 /* interface requests */
200 kern_return_t (*Open
)(struct classdriver_s
**printer
, UInt32 location
, UInt8 protocol
);
201 kern_return_t (*Abort
)(struct classdriver_s
**printer
);
202 kern_return_t (*Close
)(struct classdriver_s
**printer
);
204 /* initialize and terminate */
205 kern_return_t (*Initialize
)(struct classdriver_s
**printer
, struct classdriver_s
**baseclass
);
206 kern_return_t (*Terminate
)(struct classdriver_s
**printer
);
210 typedef Boolean (*iterator_callback_t
)(void *refcon
, io_service_t obj
);
212 typedef struct iterator_reference_s
/**** Iterator reference data */
214 iterator_callback_t callback
;
217 } iterator_reference_t
;
219 typedef struct globals_s
221 io_service_t printer_obj
;
222 classdriver_t
**classdriver
;
224 pthread_mutex_t read_thread_mutex
;
225 pthread_cond_t read_thread_cond
;
226 int read_thread_stop
;
227 int read_thread_done
;
229 pthread_mutex_t readwrite_lock_mutex
;
230 pthread_cond_t readwrite_lock_cond
;
239 CFRunLoopTimerRef status_timer
;
241 int print_fd
; /* File descriptor to print */
242 ssize_t print_bytes
; /* Print bytes read */
244 ssize_t debug_bytes
; /* Current bytes to read */
245 #endif /* DEBUG_WRITES */
248 int drain_output
; /* Drain all pending output */
249 int bidi_flag
; /* 0=unidirectional, 1=bidirectional */
251 pthread_mutex_t sidechannel_thread_mutex
;
252 pthread_cond_t sidechannel_thread_cond
;
253 int sidechannel_thread_stop
;
254 int sidechannel_thread_done
;
262 globals_t g
= { 0 }; /* Globals */
269 static Boolean
find_device_cb(void *refcon
, io_service_t obj
);
270 static Boolean
list_device_cb(void *refcon
, io_service_t obj
);
271 static CFStringRef
cfstr_create_trim(const char *cstr
);
272 static CFStringRef
copy_value_for_key(CFStringRef deviceID
, CFStringRef
*keys
);
273 static kern_return_t
load_classdriver(CFStringRef driverPath
, printer_interface_t intf
, classdriver_t
***printerDriver
);
274 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
);
275 static kern_return_t
registry_close();
276 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
);
277 static kern_return_t
unload_classdriver();
278 static OSStatus
copy_deviceid(classdriver_t
**printer
, CFStringRef
*deviceID
);
279 static void *read_thread(void *reference
);
280 static void *sidechannel_thread(void *reference
);
281 static void copy_deviceinfo(CFStringRef deviceIDString
, CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
282 static void copy_devicestring(io_service_t usbInterface
, CFStringRef
*deviceID
, UInt32
*deviceLocation
, UInt8
*interfaceNum
);
283 static void device_added(void *userdata
, io_iterator_t iterator
);
284 static void get_device_id(cups_sc_status_t
*status
, char *data
, int *datalen
);
285 static void iterate_printers(iterator_callback_t callBack
, void *userdata
);
286 static void parse_options(char *options
, char *serial
, int serial_size
, UInt32
*location
, Boolean
*wait_eof
);
287 static void release_deviceinfo(CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
288 static void setup_cfLanguage(void);
289 static void soft_reset();
290 static void status_timer_cb(CFRunLoopTimerRef timer
, void *info
);
292 #if defined(__i386__) || defined(__x86_64__)
293 static pid_t child_pid
; /* Child PID */
294 static void run_legacy_backend(int argc
, char *argv
[], int fd
); /* Starts child backend process running as a ppc executable */
295 static void sigterm_handler(int sig
); /* SIGTERM handler */
296 #endif /* __i386__ || __x86_64__ */
298 #ifdef PARSE_PS_ERRORS
299 static const char *next_line (const char *buffer
);
300 static void parse_pserror (char *sockBuffer
, int len
);
301 #endif /* PARSE_PS_ERRORS */
306 * 'list_devices()' - List all USB devices.
311 iterate_printers(list_device_cb
, NULL
);
316 * 'print_device()' - Print a file to a USB device.
319 int /* O - Exit status */
320 print_device(const char *uri
, /* I - Device URI */
321 const char *hostname
, /* I - Hostname/manufacturer */
322 const char *resource
, /* I - Resource/modelname */
323 char *options
, /* I - Device options/serial number */
324 int print_fd
, /* I - File descriptor to print */
325 int copies
, /* I - Copies to print */
326 int argc
, /* I - Number of command-line arguments (6 or 7) */
327 char *argv
[]) /* I - Command-line arguments */
329 char serial
[1024]; /* Serial number buffer */
330 OSStatus status
; /* Function results */
331 IOReturn iostatus
; /* Current IO status */
332 pthread_t read_thread_id
, /* Read thread */
333 sidechannel_thread_id
;/* Side-channel thread */
334 int have_sidechannel
= 0; /* Was the side-channel thread started? */
335 struct stat sidechannel_info
; /* Side-channel file descriptor info */
336 char print_buffer
[8192], /* Print data buffer */
337 *print_ptr
; /* Pointer into print data buffer */
338 UInt32 location
; /* Unique location in bus topology */
339 fd_set input_set
; /* Input set for select() */
340 CFStringRef driverBundlePath
; /* Class driver path */
341 int countdown
, /* Logging interval */
342 nfds
; /* Number of file descriptors */
343 ssize_t total_bytes
; /* Total bytes written */
344 UInt32 bytes
; /* Bytes written */
345 struct timeval
*timeout
, /* Timeout pointer */
346 stimeout
; /* Timeout for select() */
347 struct timespec cond_timeout
; /* pthread condition timeout */
351 * See if the side-channel descriptor is valid...
354 have_sidechannel
= !fstat(CUPS_SC_FD
, &sidechannel_info
) &&
355 S_ISSOCK(sidechannel_info
.st_mode
);
358 * Localize using CoreFoundation...
363 parse_options(options
, serial
, sizeof(serial
), &location
, &g
.wait_eof
);
365 if (resource
[0] == '/')
368 g
.print_fd
= print_fd
;
369 g
.make
= cfstr_create_trim(hostname
);
370 g
.model
= cfstr_create_trim(resource
);
371 g
.serial
= cfstr_create_trim(serial
);
372 g
.location
= location
;
374 if (!g
.make
|| !g
.model
)
376 fprintf(stderr
, "DEBUG: Fatal USB error.\n");
377 _cupsLangPuts(stderr
, _("ERROR: There was an unrecoverable USB error.\n"));
380 fputs("DEBUG: USB make string is NULL\n", stderr
);
382 fputs("DEBUG: USB model string is NULL\n", stderr
);
384 return (CUPS_BACKEND_STOP
);
387 fputs("STATE: +connecting-to-device\n", stderr
);
389 countdown
= INITIAL_LOG_INTERVAL
;
395 IOObjectRelease(g
.printer_obj
);
396 unload_classdriver(&g
.classdriver
);
401 fprintf(stderr
, "DEBUG: Looking for '%s %s'\n", hostname
, resource
);
403 iterate_printers(find_device_cb
, NULL
);
405 fputs("DEBUG: Opening connection\n", stderr
);
407 driverBundlePath
= NULL
;
409 status
= registry_open(&driverBundlePath
);
411 #if defined(__i386__) || defined(__x86_64__)
413 * If we were unable to load the class drivers for this printer it's
414 * probably because they're ppc or i386. In this case try to run this
415 * backend as i386 or ppc executables so we can use them...
419 run_legacy_backend(argc
, argv
, print_fd
);
420 /* Never returns here */
422 #endif /* __i386__ || __x86_64__ */
427 * If we still were unable to load the class drivers for this printer log
428 * the error and stop the queue...
431 if (driverBundlePath
== NULL
|| !CFStringGetCString(driverBundlePath
, print_buffer
, sizeof(print_buffer
), kCFStringEncodingUTF8
))
432 strlcpy(print_buffer
, "USB class driver", sizeof(print_buffer
));
434 fputs("STATE: +apple-missing-usbclassdriver-error\n", stderr
);
435 _cupsLangPuts(stderr
, _("ERROR: There was an unrecoverable USB error.\n"));
436 fprintf(stderr
, "DEBUG: Could not load %s\n", print_buffer
);
438 if (driverBundlePath
)
439 CFRelease(driverBundlePath
);
441 return (CUPS_BACKEND_STOP
);
444 if (driverBundlePath
)
445 CFRelease(driverBundlePath
);
449 sleep(PRINTER_POLLING_INTERVAL
);
450 countdown
-= PRINTER_POLLING_INTERVAL
;
453 _cupsLangPuts(stderr
,
454 _("INFO: Waiting for printer to become available...\n"));
455 fprintf(stderr
, "DEBUG: USB printer status: 0x%08x\n", (int)status
);
456 countdown
= SUBSEQUENT_LOG_INTERVAL
; /* subsequent log entries, every 15 seconds */
459 } while (status
!= noErr
);
461 fputs("STATE: -connecting-to-device\n", stderr
);
464 * Now that we are "connected" to the port, ignore SIGTERM so that we
465 * can finish out any page data the driver sends (e.g. to eject the
466 * current page... Only ignore SIGTERM if we are printing data from
467 * stdin (otherwise you can't cancel raw jobs...)
472 struct sigaction action
; /* POSIX signal action */
475 memset(&action
, 0, sizeof(action
));
477 sigemptyset(&action
.sa_mask
);
478 action
.sa_handler
= SIG_IGN
;
479 sigaction(SIGTERM
, &action
, NULL
);
483 * Start the side channel thread if the descriptor is valid...
486 pthread_mutex_init(&g
.readwrite_lock_mutex
, NULL
);
487 pthread_cond_init(&g
.readwrite_lock_cond
, NULL
);
488 g
.readwrite_lock
= 1;
490 if (have_sidechannel
)
492 g
.sidechannel_thread_stop
= 0;
493 g
.sidechannel_thread_done
= 0;
495 pthread_cond_init(&g
.sidechannel_thread_cond
, NULL
);
496 pthread_mutex_init(&g
.sidechannel_thread_mutex
, NULL
);
498 if (pthread_create(&sidechannel_thread_id
, NULL
, sidechannel_thread
, NULL
))
500 fprintf(stderr
, "DEBUG: Fatal USB error.\n");
501 _cupsLangPuts(stderr
, _("ERROR: There was an unrecoverable USB error.\n"));
502 fputs("DEBUG: Couldn't create side-channel thread\n", stderr
);
504 return (CUPS_BACKEND_STOP
);
509 * Get the read thread going...
512 g
.read_thread_stop
= 0;
513 g
.read_thread_done
= 0;
515 pthread_cond_init(&g
.read_thread_cond
, NULL
);
516 pthread_mutex_init(&g
.read_thread_mutex
, NULL
);
518 if (pthread_create(&read_thread_id
, NULL
, read_thread
, NULL
))
520 fprintf(stderr
, "DEBUG: Fatal USB error.\n");
521 _cupsLangPuts(stderr
, _("ERROR: There was an unrecoverable USB error.\n"));
522 fputs("DEBUG: Couldn't create read thread\n", stderr
);
524 return (CUPS_BACKEND_STOP
);
528 * The main thread sends the print file...
534 print_ptr
= print_buffer
;
536 while (status
== noErr
&& copies
-- > 0)
538 _cupsLangPuts(stderr
, _("INFO: Sending print data...\n"));
540 if (print_fd
!= STDIN_FILENO
)
542 fputs("PAGE: 1 1\n", stderr
);
543 lseek(print_fd
, 0, SEEK_SET
);
546 while (status
== noErr
)
551 FD_SET(print_fd
, &input_set
);
554 * Calculate select timeout...
555 * If we have data waiting to send timeout is 100ms.
556 * else if we're draining print_fd timeout is 0.
557 * else we're waiting forever...
563 stimeout
.tv_usec
= 100000; /* 100ms */
566 else if (g
.drain_output
)
569 stimeout
.tv_usec
= 0;
576 * I/O is unlocked around select...
579 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
580 g
.readwrite_lock
= 0;
581 pthread_cond_signal(&g
.readwrite_lock_cond
);
582 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
584 nfds
= select(print_fd
+ 1, &input_set
, NULL
, NULL
, timeout
);
587 * Reacquire the lock...
590 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
591 while (g
.readwrite_lock
)
592 pthread_cond_wait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
);
593 g
.readwrite_lock
= 1;
594 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
598 if (errno
== EINTR
&& total_bytes
== 0)
600 fputs("DEBUG: Received an interrupt before any bytes were "
601 "written, aborting\n", stderr
);
603 return (CUPS_BACKEND_OK
);
605 else if (errno
!= EAGAIN
&& errno
!= EINTR
)
607 _cupsLangPuts(stderr
, _("ERROR: Unable to read print data.\n"));
608 perror("DEBUG: select");
610 return (CUPS_BACKEND_FAILED
);
615 * If drain output has finished send a response...
618 if (g
.drain_output
&& !nfds
&& !g
.print_bytes
)
620 /* Send a response... */
621 cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
626 * Check if we have print data ready...
629 if (FD_ISSET(print_fd
, &input_set
))
632 g
.debug_bytes
+= 512;
633 if (g
.debug_bytes
> sizeof(print_buffer
))
636 g
.print_bytes
= read(print_fd
, print_buffer
, g
.debug_bytes
);
639 g
.print_bytes
= read(print_fd
, print_buffer
, sizeof(print_buffer
));
640 #endif /* DEBUG_WRITES */
642 if (g
.print_bytes
< 0)
645 * Read error - bail if we don't see EAGAIN or EINTR...
648 if (errno
!= EAGAIN
&& errno
!= EINTR
)
650 _cupsLangPuts(stderr
, _("ERROR: Unable to read print data.\n"));
651 perror("DEBUG: read");
653 return (CUPS_BACKEND_FAILED
);
658 else if (g
.print_bytes
== 0)
661 * End of file, break out of the loop...
667 print_ptr
= print_buffer
;
669 fprintf(stderr
, "DEBUG: Read %d bytes of print data...\n",
675 bytes
= g
.print_bytes
;
676 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
679 * Ignore timeout errors, but retain the number of bytes written to
680 * avoid sending duplicate data (<rdar://problem/6254911>)...
683 if (iostatus
== kIOUSBTransactionTimeout
)
685 fputs("DEBUG: Got USB transaction timeout during write\n", stderr
);
690 * If we've stalled, retry the write...
693 else if (iostatus
== kIOUSBPipeStalled
)
695 fputs("DEBUG: Got USB pipe stalled during write\n", stderr
);
697 bytes
= g
.print_bytes
;
698 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
702 * Retry a write after an aborted write since we probably just got
703 * SIGTERM (<rdar://problem/6860126>)...
706 else if (iostatus
== kIOReturnAborted
)
708 fputs("DEBUG: Got USB return aborted during write\n", stderr
);
710 IOReturn err
= (*g
.classdriver
)->Abort(g
.classdriver
);
711 fprintf(stderr
, "DEBUG: USB class driver Abort returned %x\n", err
);
715 #endif /* DEBUG_WRITES */
717 bytes
= g
.print_bytes
;
718 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
721 if (iostatus
|| bytes
< 0)
724 * Write error - bail if we don't see an error we can retry...
726 _cupsLangPuts(stderr
, _("ERROR: Unable to send print data to printer.\n"));
727 fprintf(stderr
, "DEBUG: USB class driver WritePipe returned %x\n",
730 IOReturn err
= (*g
.classdriver
)->Abort(g
.classdriver
);
731 fprintf(stderr
, "DEBUG: USB class driver Abort returned %x\n",
734 status
= CUPS_BACKEND_FAILED
;
739 fprintf(stderr
, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes
);
741 g
.print_bytes
-= bytes
;
743 total_bytes
+= bytes
;
747 if (print_fd
!= 0 && status
== noErr
)
748 fprintf(stderr
, "DEBUG: Sending print file, %lld bytes...\n",
753 fprintf(stderr
, "DEBUG: Sent %lld bytes...\n", (off_t
)total_bytes
);
758 * Re-enable the SIGTERM handler so pthread_kill() will work...
761 struct sigaction action
; /* POSIX signal action */
763 memset(&action
, 0, sizeof(action
));
765 sigemptyset(&action
.sa_mask
);
766 action
.sa_handler
= SIG_DFL
;
767 sigaction(SIGTERM
, &action
, NULL
);
771 * Wait for the side channel thread to exit...
774 if (have_sidechannel
)
777 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
778 g
.readwrite_lock
= 0;
779 pthread_cond_signal(&g
.readwrite_lock_cond
);
780 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
782 g
.sidechannel_thread_stop
= 1;
783 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
784 if (!g
.sidechannel_thread_done
)
787 * Wait for the side-channel thread to exit...
790 cond_timeout
.tv_sec
= time(NULL
) + WAIT_SIDE_DELAY
;
791 cond_timeout
.tv_nsec
= 0;
792 if (pthread_cond_timedwait(&g
.sidechannel_thread_cond
,
793 &g
.sidechannel_thread_mutex
,
797 * Force the side-channel thread to exit...
800 pthread_kill(sidechannel_thread_id
, SIGTERM
);
803 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
805 pthread_join(sidechannel_thread_id
, NULL
);
807 pthread_cond_destroy(&g
.sidechannel_thread_cond
);
808 pthread_mutex_destroy(&g
.sidechannel_thread_mutex
);
811 pthread_cond_destroy(&g
.readwrite_lock_cond
);
812 pthread_mutex_destroy(&g
.readwrite_lock_mutex
);
815 * Signal the read thread to stop...
818 g
.read_thread_stop
= 1;
821 * Give the read thread WAIT_EOF_DELAY seconds to complete all the data. If
822 * we are not signaled in that time then force the thread to exit.
825 pthread_mutex_lock(&g
.read_thread_mutex
);
827 if (!g
.read_thread_done
)
829 cond_timeout
.tv_sec
= time(NULL
) + WAIT_EOF_DELAY
;
830 cond_timeout
.tv_nsec
= 0;
832 if (pthread_cond_timedwait(&g
.read_thread_cond
, &g
.read_thread_mutex
,
836 * Force the read thread to exit...
840 pthread_kill(read_thread_id
, SIGTERM
);
843 pthread_mutex_unlock(&g
.read_thread_mutex
);
845 pthread_join(read_thread_id
, NULL
); /* wait for the read thread to return */
847 pthread_cond_destroy(&g
.read_thread_cond
);
848 pthread_mutex_destroy(&g
.read_thread_mutex
);
851 * Close the connection and input file and general clean up...
856 if (print_fd
!= STDIN_FILENO
)
865 if (g
.serial
!= NULL
)
868 if (g
.printer_obj
!= 0x0)
869 IOObjectRelease(g
.printer_obj
);
876 * 'read_thread()' - Thread to read the backchannel data on.
879 static void *read_thread(void *reference
)
881 UInt8 readbuffer
[512];
883 kern_return_t readstatus
;
884 struct mach_timebase_info timeBaseInfo
;
888 /* Calculate what 250 milliSeconds are in mach absolute time...
890 mach_timebase_info(&timeBaseInfo
);
891 delay
= ((uint64_t)250000000 * (uint64_t)timeBaseInfo
.denom
) / (uint64_t)timeBaseInfo
.numer
;
896 * Remember when we started so we can throttle the loop after the read call...
899 start
= mach_absolute_time();
901 rbytes
= sizeof(readbuffer
);
902 readstatus
= (*g
.classdriver
)->ReadPipe(g
.classdriver
, readbuffer
, &rbytes
);
903 if (readstatus
== kIOReturnSuccess
&& rbytes
> 0)
905 fprintf(stderr
, "DEBUG: Read %d bytes of back-channel data...\n",
907 cupsBackChannelWrite((char*)readbuffer
, rbytes
, 1.0);
909 /* cntrl-d is echoed by the printer.
911 * Xerox Phaser 6250D doesn't echo the cntrl-d.
912 * Xerox Phaser 6250D doesn't always send the product query.
914 if (g
.wait_eof
&& readbuffer
[rbytes
-1] == 0x4)
917 #ifdef PARSE_PS_ERRORS
918 parse_pserror(readbuffer
, rbytes
);
921 else if (readstatus
== kIOUSBTransactionTimeout
)
922 fputs("DEBUG: Got USB transaction timeout during read\n", stderr
);
923 else if (readstatus
== kIOUSBPipeStalled
)
924 fputs("DEBUG: Got USB pipe stalled during read\n", stderr
);
925 else if (readstatus
== kIOReturnAborted
)
926 fputs("DEBUG: Got USB return aborted during read\n", stderr
);
929 * Make sure this loop executes no more than once every 250 miliseconds...
932 if ((readstatus
!= kIOReturnSuccess
|| rbytes
== 0) && (g
.wait_eof
|| !g
.read_thread_stop
))
933 mach_wait_until(start
+ delay
);
935 } while (g
.wait_eof
|| !g
.read_thread_stop
); /* Abort from main thread tests error here */
938 * Let the main thread know that we have completed the read thread...
941 pthread_mutex_lock(&g
.read_thread_mutex
);
942 g
.read_thread_done
= 1;
943 pthread_cond_signal(&g
.read_thread_cond
);
944 pthread_mutex_unlock(&g
.read_thread_mutex
);
951 * 'sidechannel_thread()' - Handle side-channel requests.
955 sidechannel_thread(void *reference
)
957 cups_sc_command_t command
; /* Request command */
958 cups_sc_status_t status
; /* Request/response status */
959 char data
[2048]; /* Request/response data */
960 int datalen
; /* Request/response data size */
965 datalen
= sizeof(data
);
967 if (cupsSideChannelRead(&command
, &status
, data
, &datalen
, 1.0))
969 if (status
== CUPS_SC_STATUS_TIMEOUT
)
977 case CUPS_SC_CMD_SOFT_RESET
: /* Do a soft reset */
978 fputs("DEBUG: CUPS_SC_CMD_SOFT_RESET received from driver...\n",
981 if ((*g
.classdriver
)->SoftReset
!= NULL
)
984 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
985 fputs("DEBUG: Returning status CUPS_STATUS_OK with no bytes...\n",
990 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
992 fputs("DEBUG: Returning status CUPS_STATUS_NOT_IMPLEMENTED with "
993 "no bytes...\n", stderr
);
997 case CUPS_SC_CMD_DRAIN_OUTPUT
: /* Drain all pending output */
998 fputs("DEBUG: CUPS_SC_CMD_DRAIN_OUTPUT received from driver...\n",
1004 case CUPS_SC_CMD_GET_BIDI
: /* Is the connection bidirectional? */
1005 fputs("DEBUG: CUPS_SC_CMD_GET_BIDI received from driver...\n",
1008 data
[0] = g
.bidi_flag
;
1009 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
1012 "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
1016 case CUPS_SC_CMD_GET_DEVICE_ID
: /* Return IEEE-1284 device ID */
1017 fputs("DEBUG: CUPS_SC_CMD_GET_DEVICE_ID received from driver...\n",
1020 datalen
= sizeof(data
);
1021 get_device_id(&status
, data
, &datalen
);
1022 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, datalen
, 1.0);
1024 if (datalen
< sizeof(data
))
1025 data
[datalen
] = '\0';
1027 data
[sizeof(data
) - 1] = '\0';
1030 "DEBUG: Returning CUPS_SC_STATUS_OK with %d bytes (%s)...\n",
1034 case CUPS_SC_CMD_GET_STATE
: /* Return device state */
1035 fputs("DEBUG: CUPS_SC_CMD_GET_STATE received from driver...\n",
1038 data
[0] = CUPS_SC_STATE_ONLINE
;
1039 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
1042 "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
1047 fprintf(stderr
, "DEBUG: Unknown side-channel command (%d) received "
1048 "from driver...\n", command
);
1050 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
1053 fputs("DEBUG: Returned CUPS_SC_STATUS_NOT_IMPLEMENTED with no bytes...\n",
1058 while (!g
.sidechannel_thread_stop
);
1060 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
1061 g
.sidechannel_thread_done
= 1;
1062 pthread_cond_signal(&g
.sidechannel_thread_cond
);
1063 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
1071 * 'iterate_printers()' - Iterate over all the printers.
1074 static void iterate_printers(iterator_callback_t callBack
,
1077 mach_port_t masterPort
= 0x0;
1078 kern_return_t kr
= IOMasterPort (bootstrap_port
, &masterPort
);
1080 if (kr
== kIOReturnSuccess
&& masterPort
!= 0x0)
1082 io_iterator_t addIterator
= 0x0;
1084 iterator_reference_t reference
= { callBack
, userdata
, true };
1085 IONotificationPortRef addNotification
= IONotificationPortCreate(masterPort
);
1087 int klass
= kUSBPrintingClass
;
1088 int subklass
= kUSBPrintingSubclass
;
1090 CFNumberRef usb_klass
= CFNumberCreate(NULL
, kCFNumberIntType
, &klass
);
1091 CFNumberRef usb_subklass
= CFNumberCreate(NULL
, kCFNumberIntType
, &subklass
);
1092 CFMutableDictionaryRef usbPrinterMatchDictionary
= IOServiceMatching(kIOUSBInterfaceClassName
);
1094 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceClass"), usb_klass
);
1095 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceSubClass"), usb_subklass
);
1097 CFRelease(usb_klass
);
1098 CFRelease(usb_subklass
);
1100 kr
= IOServiceAddMatchingNotification(addNotification
, kIOMatchedNotification
, usbPrinterMatchDictionary
, &device_added
, &reference
, &addIterator
);
1101 if (addIterator
!= 0x0)
1103 device_added (&reference
, addIterator
);
1105 if (reference
.keepRunning
)
1107 CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification
), kCFRunLoopDefaultMode
);
1110 IOObjectRelease(addIterator
);
1112 mach_port_deallocate(mach_task_self(), masterPort
);
1118 * 'device_added()' - Device added notifier.
1121 static void device_added(void *userdata
,
1122 io_iterator_t iterator
)
1124 iterator_reference_t
*reference
= userdata
;
1127 while (reference
->keepRunning
&& (obj
= IOIteratorNext(iterator
)) != 0x0)
1129 if (reference
->callback
!= NULL
)
1130 reference
->keepRunning
= reference
->callback(reference
->userdata
, obj
);
1132 IOObjectRelease(obj
);
1135 /* One last call to the call back now that we are not longer have printers left to iterate...
1137 if (reference
->keepRunning
)
1138 reference
->keepRunning
= reference
->callback(reference
->userdata
, 0x0);
1140 if (!reference
->keepRunning
)
1141 CFRunLoopStop(CFRunLoopGetCurrent());
1146 * 'list_device_cb()' - list_device iterator callback.
1149 static Boolean
list_device_cb(void *refcon
,
1152 Boolean keepRunning
= (obj
!= 0x0);
1156 CFStringRef deviceIDString
= NULL
;
1157 UInt32 deviceLocation
= 0;
1158 UInt8 interfaceNum
= 0;
1160 copy_devicestring(obj
, &deviceIDString
, &deviceLocation
, &interfaceNum
);
1161 if (deviceIDString
!= NULL
)
1163 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1164 char uristr
[1024], makestr
[1024], modelstr
[1024], serialstr
[1024];
1165 char optionsstr
[1024], idstr
[1024], make_modelstr
[1024];
1167 copy_deviceinfo(deviceIDString
, &make
, &model
, &serial
);
1168 CFStringGetCString(deviceIDString
, idstr
, sizeof(idstr
),
1169 kCFStringEncodingUTF8
);
1170 backendGetMakeModel(idstr
, make_modelstr
, sizeof(make_modelstr
));
1175 !CFStringGetCString(make
, makestr
, sizeof(makestr
),
1176 kCFStringEncodingUTF8
))
1177 strcpy(makestr
, "Unknown");
1180 !CFStringGetCString(model
, &modelstr
[1], sizeof(modelstr
)-1,
1181 kCFStringEncodingUTF8
))
1182 strcpy(modelstr
+ 1, "Printer");
1184 optionsstr
[0] = '\0';
1187 CFStringGetCString(serial
, serialstr
, sizeof(serialstr
), kCFStringEncodingUTF8
);
1188 snprintf(optionsstr
, sizeof(optionsstr
), "?serial=%s", serialstr
);
1190 else if (deviceLocation
!= 0)
1191 snprintf(optionsstr
, sizeof(optionsstr
), "?location=%x", (unsigned)deviceLocation
);
1193 httpAssembleURI(HTTP_URI_CODING_ALL
, uristr
, sizeof(uristr
), "usb", NULL
, makestr
, 0, modelstr
);
1194 strlcat(uristr
, optionsstr
, sizeof(uristr
));
1196 cupsBackendReport("direct", uristr
, make_modelstr
, make_modelstr
, idstr
,
1199 release_deviceinfo(&make
, &model
, &serial
);
1200 CFRelease(deviceIDString
);
1209 * 'find_device_cb()' - print_device iterator callback.
1212 static Boolean
find_device_cb(void *refcon
,
1215 Boolean keepLooking
= true;
1219 CFStringRef idString
= NULL
;
1220 UInt32 location
= -1;
1221 UInt8 interfaceNum
= 0;
1223 copy_devicestring(obj
, &idString
, &location
, &interfaceNum
);
1224 if (idString
!= NULL
)
1226 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1228 copy_deviceinfo(idString
, &make
, &model
, &serial
);
1229 if (make
&& CFStringCompare(make
, g
.make
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1231 if (model
&& CFStringCompare(model
, g
.model
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1233 if (g
.serial
!= NULL
&& CFStringGetLength(g
.serial
) > 0)
1235 if (serial
!= NULL
&& CFStringCompare(serial
, g
.serial
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1237 IOObjectRetain(obj
);
1238 g
.printer_obj
= obj
;
1239 keepLooking
= false;
1244 if (g
.printer_obj
!= 0)
1245 IOObjectRelease(g
.printer_obj
);
1247 g
.printer_obj
= obj
;
1248 IOObjectRetain(obj
);
1250 if (g
.location
== 0 || g
.location
== location
)
1251 keepLooking
= false;
1254 g
.interfaceNum
= interfaceNum
;
1258 release_deviceinfo(&make
, &model
, &serial
);
1259 CFRelease(idString
);
1264 keepLooking
= (g
.printer_obj
== 0);
1265 if (obj
== 0x0 && keepLooking
)
1267 CFRunLoopTimerContext context
= { 0, refcon
, NULL
, NULL
, NULL
};
1268 CFRunLoopTimerRef timer
= CFRunLoopTimerCreate(NULL
, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb
, &context
);
1271 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer
, kCFRunLoopDefaultMode
);
1272 g
.status_timer
= timer
;
1277 if (!keepLooking
&& g
.status_timer
!= NULL
)
1279 fputs("STATE: -offline-report\n", stderr
);
1280 _cupsLangPuts(stderr
, _("INFO: Printer is now online.\n"));
1281 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g
.status_timer
, kCFRunLoopDefaultMode
);
1282 CFRelease(g
.status_timer
);
1283 g
.status_timer
= NULL
;
1291 * 'status_timer_cb()' - Status timer callback.
1294 static void status_timer_cb(CFRunLoopTimerRef timer
,
1297 fputs("STATE: +offline-report\n", stderr
);
1298 _cupsLangPuts(stderr
, _("INFO: Printer is offline.\n"));
1300 if (getenv("CLASS") != NULL
)
1303 * If the CLASS environment variable is set, the job was submitted
1304 * to a class and not to a specific queue. In this case, we want
1305 * to abort immediately so that the job can be requeued on the next
1306 * available printer in the class.
1308 * Sleep 5 seconds to keep the job from requeuing too rapidly...
1313 exit(CUPS_BACKEND_FAILED
);
1320 * 'copy_deviceinfo()' - Copy strings from the 1284 device ID.
1323 static void copy_deviceinfo(CFStringRef deviceIDString
,
1326 CFStringRef
*serial
)
1328 CFStringRef modelKeys
[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL
};
1329 CFStringRef makeKeys
[] = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL
};
1330 CFStringRef serialKeys
[] = { CFSTR("SN:"), CFSTR("SERN:"), NULL
};
1333 *make
= copy_value_for_key(deviceIDString
, makeKeys
);
1336 *model
= copy_value_for_key(deviceIDString
, modelKeys
);
1339 *serial
= copy_value_for_key(deviceIDString
, serialKeys
);
1344 * 'release_deviceinfo()' - Release deviceinfo strings.
1347 static void release_deviceinfo(CFStringRef
*make
,
1349 CFStringRef
*serial
)
1351 if (make
!= NULL
&& *make
!= NULL
)
1357 if (model
!= NULL
&& *model
!= NULL
)
1363 if (serial
!= NULL
&& *serial
!= NULL
)
1373 * 'load_classdriver()' - Load a classdriver.
1376 static kern_return_t
load_classdriver(CFStringRef driverPath
,
1377 printer_interface_t intf
,
1378 classdriver_t
***printerDriver
)
1380 kern_return_t kr
= kUSBPrinterClassDeviceNotOpen
;
1381 classdriver_t
**driver
= NULL
;
1382 CFStringRef bundle
= driverPath
? driverPath
: kUSBGenericTOPrinterClassDriver
;
1383 char bundlestr
[1024]; /* Bundle path */
1384 struct stat bundleinfo
; /* File information for bundle */
1385 CFURLRef url
; /* URL for driver */
1386 CFPlugInRef plugin
= NULL
; /* Plug-in address */
1389 CFStringGetCString(bundle
, bundlestr
, sizeof(bundlestr
), kCFStringEncodingUTF8
);
1392 * Validate permissions for the class driver...
1395 if (stat(bundlestr
, &bundleinfo
))
1397 fprintf(stderr
, "DEBUG: Unable to load class driver \"%s\": %s\n",
1398 bundlestr
, strerror(errno
));
1399 if (errno
== ENOENT
)
1400 return (load_classdriver(NULL
, intf
, printerDriver
));
1404 else if (bundleinfo
.st_mode
& S_IWOTH
)
1406 fprintf(stderr
, "DEBUG: Unable to load class driver \"%s\": insecure file "
1407 "permissions (0%o)\n", bundlestr
, bundleinfo
.st_mode
);
1412 * Try loading the class driver...
1415 url
= CFURLCreateWithFileSystemPath(NULL
, bundle
, kCFURLPOSIXPathStyle
, true);
1419 plugin
= CFPlugInCreate(NULL
, url
);
1427 CFArrayRef factories
= CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID
, plugin
);
1428 if (factories
!= NULL
&& CFArrayGetCount(factories
) > 0)
1430 CFUUIDRef factoryID
= CFArrayGetValueAtIndex(factories
, 0);
1431 IUnknownVTbl
**iunknown
= CFPlugInInstanceCreate(NULL
, factoryID
, kUSBPrinterClassTypeID
);
1432 if (iunknown
!= NULL
)
1434 kr
= (*iunknown
)->QueryInterface(iunknown
, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID
), (LPVOID
*)&driver
);
1435 if (kr
== kIOReturnSuccess
&& driver
!= NULL
)
1437 classdriver_t
**genericDriver
= NULL
;
1438 if (driverPath
!= NULL
&& CFStringCompare(driverPath
, kUSBGenericTOPrinterClassDriver
, 0) != kCFCompareEqualTo
)
1439 kr
= load_classdriver(NULL
, intf
, &genericDriver
);
1441 if (kr
== kIOReturnSuccess
)
1443 (*driver
)->interface
= intf
;
1444 (*driver
)->Initialize(driver
, genericDriver
);
1446 (*driver
)->plugin
= plugin
;
1447 (*driver
)->interface
= intf
;
1448 *printerDriver
= driver
;
1451 (*iunknown
)->Release(iunknown
);
1453 CFRelease(factories
);
1457 fprintf(stderr
, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr
, (int)kr
);
1464 * 'unload_classdriver()' - Unload a classdriver.
1467 static kern_return_t
unload_classdriver(classdriver_t
***classdriver
)
1469 if (*classdriver
!= NULL
)
1471 (**classdriver
)->Release(*classdriver
);
1472 *classdriver
= NULL
;
1475 return kIOReturnSuccess
;
1480 * 'load_printerdriver()' - Load vendor's classdriver.
1482 * If driverBundlePath is not NULL on return it is the callers responsbility to release it!
1485 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
)
1487 IOCFPlugInInterface
**iodev
= NULL
;
1490 printer_interface_t intf
;
1493 kr
= IOCreatePlugInInterfaceForService(g
.printer_obj
, kIOUSBInterfaceUserClientTypeID
, kIOCFPlugInInterfaceID
, &iodev
, &score
);
1494 if (kr
== kIOReturnSuccess
)
1496 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*) &intf
)) == noErr
)
1498 *driverBundlePath
= IORegistryEntryCreateCFProperty(g
.printer_obj
, kUSBClassDriverProperty
, NULL
, kNilOptions
);
1500 kr
= load_classdriver(*driverBundlePath
, intf
, &g
.classdriver
);
1502 if (kr
!= kIOReturnSuccess
)
1503 (*intf
)->Release(intf
);
1505 IODestroyPlugInInterface(iodev
);
1512 * 'registry_open()' - Open a connection to the printer.
1515 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
)
1517 g
.bidi_flag
= 0; /* 0=unidirectional */
1519 kern_return_t kr
= load_printerdriver(driverBundlePath
);
1520 if (kr
!= kIOReturnSuccess
)
1523 if (g
.classdriver
!= NULL
)
1525 (*g
.classdriver
)->interfaceNumber
= g
.interfaceNum
;
1526 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolBidirectional
);
1527 if (kr
!= kIOReturnSuccess
|| (*g
.classdriver
)->interface
== NULL
)
1529 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolUnidirectional
);
1530 if (kr
== kIOReturnSuccess
)
1532 if ((*g
.classdriver
)->interface
== NULL
)
1534 (*g
.classdriver
)->Close(g
.classdriver
);
1540 g
.bidi_flag
= 1; /* 1=bidirectional */
1543 if (kr
!= kIOReturnSuccess
)
1544 unload_classdriver(&g
.classdriver
);
1551 * 'registry_close()' - Close the connection to the printer.
1554 static kern_return_t
registry_close()
1556 if (g
.classdriver
!= NULL
)
1557 (*g
.classdriver
)->Close(g
.classdriver
);
1559 unload_classdriver(&g
.classdriver
);
1560 return kIOReturnSuccess
;
1565 * 'copy_deviceid()' - Copy the 1284 device id string.
1568 static OSStatus
copy_deviceid(classdriver_t
**classdriver
,
1569 CFStringRef
*deviceID
)
1571 CFStringRef devID
= NULL
,
1575 deviceSerial
= NULL
;
1577 OSStatus err
= (*classdriver
)->GetDeviceID(classdriver
, &devID
, DEFAULT_TIMEOUT
);
1579 copy_deviceinfo(devID
, &deviceMake
, &deviceModel
, &deviceSerial
);
1581 if (deviceMake
== NULL
|| deviceModel
== NULL
|| deviceSerial
== NULL
)
1583 IOUSBDeviceDescriptor desc
;
1584 iodevice_request_t request
;
1586 request
.requestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
1587 request
.request
= kUSBRqGetDescriptor
;
1588 request
.value
= (kUSBDeviceDesc
<< 8) | 0;
1590 request
.length
= sizeof(desc
);
1591 request
.buffer
= &desc
;
1592 err
= (*classdriver
)->DeviceRequest(classdriver
, &request
, DEFAULT_TIMEOUT
);
1593 if (err
== kIOReturnSuccess
)
1595 CFMutableStringRef newDevID
= CFStringCreateMutable(NULL
, 0);
1597 if (deviceMake
== NULL
)
1599 CFStringRef data
= NULL
;
1600 err
= (*classdriver
)->GetString(classdriver
, desc
.iManufacturer
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1603 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MFG:%@;"), data
);
1608 if (deviceModel
== NULL
)
1610 CFStringRef data
= NULL
;
1611 err
= (*classdriver
)->GetString(classdriver
, desc
.iProduct
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1614 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MDL:%@;"), data
);
1619 if (deviceSerial
== NULL
&& desc
.iSerialNumber
!= 0)
1621 CFStringRef data
= NULL
;
1622 err
= (*classdriver
)->GetString(classdriver
, desc
.iSerialNumber
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1625 CFStringAppendFormat(newDevID
, NULL
, CFSTR("SERN:%@;"), data
);
1632 CFStringAppend(newDevID
, devID
);
1636 *deviceID
= newDevID
;
1643 release_deviceinfo(&deviceMake
, &deviceModel
, &deviceSerial
);
1650 * 'copy_devicestring()' - Copy the 1284 device id string.
1653 static void copy_devicestring(io_service_t usbInterface
,
1654 CFStringRef
*deviceID
,
1655 UInt32
*deviceLocation
,
1656 UInt8
*interfaceNumber
)
1658 IOCFPlugInInterface
**iodev
= NULL
;
1661 printer_interface_t intf
;
1663 classdriver_t
**klassDriver
= NULL
;
1664 CFStringRef driverBundlePath
;
1666 if ((kr
= IOCreatePlugInInterfaceForService(usbInterface
,
1667 kIOUSBInterfaceUserClientTypeID
,
1668 kIOCFPlugInInterfaceID
,
1669 &iodev
, &score
)) == kIOReturnSuccess
)
1671 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*)
1674 (*intf
)->GetLocationID(intf
, deviceLocation
);
1675 (*intf
)->GetInterfaceNumber(intf
, interfaceNumber
);
1677 driverBundlePath
= IORegistryEntryCreateCFProperty(usbInterface
,
1678 kUSBClassDriverProperty
,
1681 kr
= load_classdriver(driverBundlePath
, intf
, &klassDriver
);
1683 if (kr
!= kIOReturnSuccess
&& driverBundlePath
!= NULL
)
1684 kr
= load_classdriver(NULL
, intf
, &klassDriver
);
1686 if (kr
== kIOReturnSuccess
&& klassDriver
!= NULL
)
1687 kr
= copy_deviceid(klassDriver
, deviceID
);
1689 unload_classdriver(&klassDriver
);
1691 if (driverBundlePath
!= NULL
)
1692 CFRelease(driverBundlePath
);
1694 /* (*intf)->Release(intf); */
1696 IODestroyPlugInInterface(iodev
);
1703 * 'copy_value_for_key()' - Copy value string associated with a key.
1706 static CFStringRef
copy_value_for_key(CFStringRef deviceID
,
1709 CFStringRef value
= NULL
;
1710 CFArrayRef kvPairs
= deviceID
!= NULL
? CFStringCreateArrayBySeparatingStrings(NULL
, deviceID
, CFSTR(";")) : NULL
;
1711 CFIndex max
= kvPairs
!= NULL
? CFArrayGetCount(kvPairs
) : 0;
1714 while (idx
< max
&& value
== NULL
)
1716 CFStringRef kvpair
= CFArrayGetValueAtIndex(kvPairs
, idx
);
1718 while (keys
[idxx
] != NULL
&& value
== NULL
)
1720 CFRange range
= CFStringFind(kvpair
, keys
[idxx
], kCFCompareCaseInsensitive
);
1721 if (range
.length
!= -1)
1723 if (range
.location
!= 0)
1725 CFMutableStringRef theString
= CFStringCreateMutableCopy(NULL
, 0, kvpair
);
1726 CFStringTrimWhitespace(theString
);
1727 range
= CFStringFind(theString
, keys
[idxx
], kCFCompareCaseInsensitive
);
1728 if (range
.location
== 0)
1729 value
= CFStringCreateWithSubstring(NULL
, theString
, CFRangeMake(range
.length
, CFStringGetLength(theString
) - range
.length
));
1731 CFRelease(theString
);
1735 CFStringRef theString
= CFStringCreateWithSubstring(NULL
, kvpair
, CFRangeMake(range
.length
, CFStringGetLength(kvpair
) - range
.length
));
1736 CFMutableStringRef theString2
= CFStringCreateMutableCopy(NULL
, 0, theString
);
1737 CFRelease(theString
);
1739 CFStringTrimWhitespace(theString2
);
1748 if (kvPairs
!= NULL
)
1755 * 'cfstr_create_trim()' - Create CFString and trim whitespace characters.
1758 CFStringRef
cfstr_create_trim(const char *cstr
)
1761 CFMutableStringRef cfmutablestr
= NULL
;
1763 if ((cfstr
= CFStringCreateWithCString(NULL
, cstr
, kCFStringEncodingUTF8
)) != NULL
)
1765 if ((cfmutablestr
= CFStringCreateMutableCopy(NULL
, 1024, cfstr
)) != NULL
)
1766 CFStringTrimWhitespace(cfmutablestr
);
1770 return (CFStringRef
) cfmutablestr
;
1776 * 'parse_options()' - Parse URI options.
1779 static void parse_options(char *options
,
1785 char sep
, /* Separator character */
1786 *name
, /* Name of option */
1787 *value
; /* Value of option */
1806 while (*options
&& *options
!= '=' && *options
!= '+' && *options
!= '&')
1809 if ((sep
= *options
) != '\0')
1820 while (*options
&& *options
!= '+' && *options
!= '&')
1830 * Process the option...
1833 if (!strcasecmp(name
, "waiteof"))
1835 if (!strcasecmp(value
, "on") ||
1836 !strcasecmp(value
, "yes") ||
1837 !strcasecmp(value
, "true"))
1839 else if (!strcasecmp(value
, "off") ||
1840 !strcasecmp(value
, "no") ||
1841 !strcasecmp(value
, "false"))
1844 _cupsLangPrintf(stderr
,
1845 _("WARNING: Boolean expected for waiteof option "
1846 "\"%s\"\n"), value
);
1848 else if (!strcasecmp(name
, "serial"))
1849 strlcpy(serial
, value
, serial_size
);
1850 else if (!strcasecmp(name
, "location") && location
)
1851 *location
= strtol(value
, NULL
, 16);
1857 * @function setup_cfLanguage
1858 * @abstract Convert the contents of the CUPS 'APPLE_LANGUAGE' environment
1859 * variable into a one element CF array of languages.
1861 * @discussion Each submitted job comes with a natural language. CUPS passes
1862 * that language in an environment variable. We take that language
1863 * and jam it into the AppleLanguages array so that CF will use
1864 * it when reading localized resources. We need to do this before
1865 * any CF code reads and caches the languages array, so this function
1866 * should be called early in main()
1868 static void setup_cfLanguage(void)
1870 CFStringRef lang
[1] = {NULL
};
1871 CFArrayRef langArray
= NULL
;
1872 const char *requestedLang
= NULL
;
1874 if ((requestedLang
= getenv("APPLE_LANGUAGE")) == NULL
)
1875 requestedLang
= getenv("LANG");
1877 if (requestedLang
!= NULL
)
1879 lang
[0] = CFStringCreateWithCString(kCFAllocatorDefault
, requestedLang
, kCFStringEncodingUTF8
);
1880 langArray
= CFArrayCreate(kCFAllocatorDefault
, (const void **)lang
, sizeof(lang
) / sizeof(lang
[0]), &kCFTypeArrayCallBacks
);
1882 CFPreferencesSetValue(CFSTR("AppleLanguages"), langArray
, kCFPreferencesCurrentApplication
, kCFPreferencesAnyUser
, kCFPreferencesAnyHost
);
1883 fprintf(stderr
, "DEBUG: usb: AppleLanguages=\"%s\"\n", requestedLang
);
1886 CFRelease(langArray
);
1889 fputs("DEBUG: usb: LANG and APPLE_LANGUAGE environment variables missing.\n", stderr
);
1893 #if defined(__i386__) || defined(__x86_64__)
1895 * @function run_legacy_backend
1897 * @abstract Starts child backend process running as a ppc or i386 executable.
1899 * @result Never returns; always calls exit().
1903 static void run_legacy_backend(int argc
,
1910 pid_t waitpid_status
;
1912 char *usb_legacy_status
;
1915 * If we're running as x86_64 or i386 and couldn't load the class driver
1916 * (because it's ppc or i386), then try to re-exec ourselves in ppc or i386
1917 * mode to try again. If we don't have a ppc or i386 architecture we may be
1918 * running with the same architecture again so guard against this by setting
1919 * and testing an environment variable...
1923 usb_legacy_status
= getenv("USB_I386_STATUS");
1925 usb_legacy_status
= getenv("USB_PPC_STATUS");
1926 # endif /* __x86_64__ */
1928 if (!usb_legacy_status
)
1931 * Setup a SIGTERM handler then block it before forking...
1934 int err
; /* posix_spawn result */
1935 struct sigaction action
; /* POSIX signal action */
1936 sigset_t newmask
, /* New signal mask */
1937 oldmask
; /* Old signal mask */
1938 char usbpath
[1024]; /* Path to USB backend */
1939 const char *cups_serverbin
;/* Path to CUPS binaries */
1942 memset(&action
, 0, sizeof(action
));
1943 sigaddset(&action
.sa_mask
, SIGTERM
);
1944 action
.sa_handler
= sigterm_handler
;
1945 sigaction(SIGTERM
, &action
, NULL
);
1947 sigemptyset(&newmask
);
1948 sigaddset(&newmask
, SIGTERM
);
1949 sigprocmask(SIG_BLOCK
, &newmask
, &oldmask
);
1952 * Set the environment variable...
1956 setenv("USB_I386_STATUS", "1", false);
1958 setenv("USB_PPC_STATUS", "1", false);
1959 # endif /* __x86_64__ */
1962 * Tell the kernel to use the specified CPU architecture...
1966 cpu_type_t cpu
= CPU_TYPE_I386
;
1968 cpu_type_t cpu
= CPU_TYPE_POWERPC
;
1969 # endif /* __x86_64__ */
1971 posix_spawnattr_t attrs
;
1973 if (!posix_spawnattr_init(&attrs
))
1975 posix_spawnattr_setsigdefault(&attrs
, &oldmask
);
1976 if (posix_spawnattr_setbinpref_np(&attrs
, 1, &cpu
, &ocount
) || ocount
!= 1)
1979 perror("DEBUG: Unable to set binary preference to i386");
1981 perror("DEBUG: Unable to set binary preference to ppc");
1982 # endif /* __x86_64__ */
1983 _cupsLangPrintf(stderr
, _("Unable to use legacy USB class driver\n"));
1984 exit(CUPS_BACKEND_STOP
);
1989 * Set up the arguments and call posix_spawn...
1992 if ((cups_serverbin
= getenv("CUPS_SERVERBIN")) == NULL
)
1993 cups_serverbin
= CUPS_SERVERBIN
;
1994 snprintf(usbpath
, sizeof(usbpath
), "%s/backend/usb", cups_serverbin
);
1996 for (i
= 0; i
< argc
&& i
< (sizeof(my_argv
) / sizeof(my_argv
[0])) - 1; i
++)
1997 my_argv
[i
] = argv
[i
];
2001 if ((err
= posix_spawn(&child_pid
, usbpath
, NULL
, &attrs
, my_argv
,
2004 fprintf(stderr
, "DEBUG: Unable to exec %s: %s\n", usbpath
,
2006 _cupsLangPrintf(stderr
, _("Unable to use legacy USB class driver\n"));
2007 exit(CUPS_BACKEND_STOP
);
2011 * Unblock signals...
2014 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
2017 * Close the fds we won't be using then wait for the child backend to exit.
2023 fprintf(stderr
, "DEBUG: Started usb(legacy) backend (PID %d)\n",
2026 while ((waitpid_status
= waitpid(child_pid
, &childstatus
, 0)) == (pid_t
)-1 && errno
== EINTR
)
2029 if (WIFSIGNALED(childstatus
))
2031 exitstatus
= CUPS_BACKEND_STOP
;
2032 fprintf(stderr
, "DEBUG: usb(legacy) backend %d crashed on signal %d\n",
2033 child_pid
, WTERMSIG(childstatus
));
2037 if ((exitstatus
= WEXITSTATUS(childstatus
)) != 0)
2039 "DEBUG: usb(legacy) backend %d stopped with status %d\n",
2040 child_pid
, exitstatus
);
2042 fprintf(stderr
, "DEBUG: usb(legacy) backend %d exited with no errors\n",
2048 fputs("DEBUG: usb(legacy) backend running native again\n", stderr
);
2049 exitstatus
= CUPS_BACKEND_STOP
;
2056 * 'sigterm_handler()' - SIGTERM handler.
2060 sigterm_handler(int sig
) /* I - Signal */
2062 /* If we started a child process pass the signal on to it...
2067 * If we started a child process pass the signal on to it...
2072 kill(child_pid
, sig
);
2073 while (waitpid(child_pid
, &status
, 0) < 0 && errno
== EINTR
);
2075 if (WIFEXITED(status
))
2076 exit(WEXITSTATUS(status
));
2077 else if (status
== SIGTERM
|| status
== SIGKILL
)
2081 fprintf(stderr
, "DEBUG: Child crashed on signal %d\n", status
);
2082 exit(CUPS_BACKEND_STOP
);
2087 #endif /* __i386__ || __x86_64__ */
2090 #ifdef PARSE_PS_ERRORS
2092 * 'next_line()' - Find the next line in a buffer.
2095 static const char *next_line (const char *buffer
)
2097 const char *cptr
, *lptr
= NULL
;
2099 for (cptr
= buffer
; *cptr
&& lptr
== NULL
; cptr
++)
2100 if (*cptr
== '\n' || *cptr
== '\r')
2107 * 'parse_pserror()' - Scan the backchannel data for postscript errors.
2110 static void parse_pserror(char *sockBuffer
,
2113 static char gErrorBuffer
[1024] = "";
2114 static char *gErrorBufferPtr
= gErrorBuffer
;
2115 static char *gErrorBufferEndPtr
= gErrorBuffer
+ sizeof(gErrorBuffer
);
2117 char *pCommentBegin
, *pCommentEnd
, *pLineEnd
;
2122 if (gErrorBufferPtr
+ len
> gErrorBufferEndPtr
- 1)
2123 gErrorBufferPtr
= gErrorBuffer
;
2124 if (len
> sizeof(gErrorBuffer
) - 1)
2125 len
= sizeof(gErrorBuffer
) - 1;
2127 memcpy(gErrorBufferPtr
, (const void *)sockBuffer
, len
);
2128 gErrorBufferPtr
+= len
;
2129 *(gErrorBufferPtr
+ 1) = '\0';
2131 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
2132 while (pLineEnd
!= NULL
)
2136 pCommentBegin
= strstr(gErrorBuffer
,"%%[");
2137 pCommentEnd
= strstr(gErrorBuffer
, "]%%");
2138 if (pCommentBegin
!= gErrorBuffer
&& pCommentEnd
!= NULL
)
2140 pCommentEnd
+= 3; /* Skip past "]%%" */
2141 *pCommentEnd
= '\0'; /* There's always room for the nul */
2143 if (strncasecmp(pCommentBegin
, "%%[ Error:", 10) == 0)
2145 else if (strncasecmp(pCommentBegin
, "%%[ Flushing", 12) == 0)
2150 if ((logstrlen
= snprintf(logstr
, sizeof(logstr
), "%s: %s\n", logLevel
, pCommentBegin
)) >= sizeof(logstr
))
2152 /* If the string was trucnated make sure it has a linefeed before the nul */
2153 logstrlen
= sizeof(logstr
) - 1;
2154 logstr
[logstrlen
- 1] = '\n';
2156 write(STDERR_FILENO
, logstr
, logstrlen
);
2159 /* move everything over... */
2160 strcpy(gErrorBuffer
, pLineEnd
);
2161 gErrorBufferPtr
= gErrorBuffer
;
2162 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
2165 #endif /* PARSE_PS_ERRORS */
2169 * 'soft_reset()' - Send a soft reset to the device.
2172 static void soft_reset()
2174 fd_set input_set
; /* Input set for select() */
2175 struct timeval stimeout
; /* Timeout for select() */
2176 char buffer
[2048]; /* Buffer */
2177 struct timespec cond_timeout
; /* pthread condition timeout */
2180 * Send an abort once a second until the I/O lock is released by the main thread...
2183 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2184 while (g
.readwrite_lock
)
2186 (*g
.classdriver
)->Abort(g
.classdriver
);
2188 cond_timeout
.tv_sec
= time(NULL
) + 1;
2189 cond_timeout
.tv_nsec
= 0;
2191 pthread_cond_timedwait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
, &cond_timeout
);
2194 g
.readwrite_lock
= 1;
2195 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2198 * Flush bytes waiting on print_fd...
2203 FD_ZERO(&input_set
);
2204 FD_SET(g
.print_fd
, &input_set
);
2206 stimeout
.tv_sec
= 0;
2207 stimeout
.tv_usec
= 0;
2209 while (select(g
.print_fd
+1, &input_set
, NULL
, NULL
, &stimeout
) > 0)
2210 if (read(g
.print_fd
, buffer
, sizeof(buffer
)) <= 0)
2217 (*g
.classdriver
)->SoftReset(g
.classdriver
, DEFAULT_TIMEOUT
);
2220 * Release the I/O lock...
2223 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2224 g
.readwrite_lock
= 0;
2225 pthread_cond_signal(&g
.readwrite_lock_cond
);
2226 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2231 * 'get_device_id()' - Return IEEE-1284 device ID.
2234 static void get_device_id(cups_sc_status_t
*status
,
2238 CFStringRef deviceIDString
= NULL
;
2241 copy_deviceid(g
.classdriver
, &deviceIDString
);
2245 CFStringGetCString(deviceIDString
, data
, *datalen
, kCFStringEncodingUTF8
);
2246 *datalen
= strlen(data
);
2247 CFRelease(deviceIDString
);
2249 *status
= CUPS_SC_STATUS_OK
;
2254 * End of "$Id: usb-darwin.c 7953 2008-09-17 01:43:19Z mike $".