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 * read_thread() - Thread to read the backchannel data on.
49 * sidechannel_thread() - Handle side-channel requests.
50 * iterate_printers() - Iterate over all the printers.
51 * device_added() - Device added notifier.
52 * list_device_cb() - list_device iterator callback.
53 * find_device_cb() - print_device iterator callback.
54 * status_timer_cb() - Status timer callback.
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 * sigterm_handler() - SIGTERM handler.
68 * next_line() - Find the next line in a buffer.
69 * parse_pserror() - Scan the backchannel data for postscript errors.
70 * soft_reset() - Send a soft reset to the device.
71 * get_device_id() - Return IEEE-1284 device ID.
75 * Include necessary headers.
86 #include <sys/sysctl.h>
88 #include <mach/mach.h>
89 #include <mach/mach_error.h>
90 #include <mach/mach_time.h>
91 #include <cups/debug-private.h>
92 #include <cups/sidechannel.h>
93 #include <cups/language-private.h>
94 #include "backend-private.h"
96 #include <CoreFoundation/CoreFoundation.h>
97 #include <IOKit/usb/IOUSBLib.h>
98 #include <IOKit/IOCFPlugIn.h>
103 extern char **environ
;
107 * DEBUG_WRITES, if defined, causes the backend to write data to the printer in
108 * 512 byte increments, up to 8192 bytes, to make debugging with a USB bus
112 #define DEBUG_WRITES 0
115 * WAIT_EOF_DELAY is number of seconds we'll wait for responses from
116 * the printer after we've finished sending all the data
118 #define WAIT_EOF_DELAY 7
119 #define WAIT_SIDE_DELAY 3
120 #define DEFAULT_TIMEOUT 5000L
122 #define USB_INTERFACE_KIND CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID190)
123 #define kUSBLanguageEnglish 0x409
125 #define PRINTER_POLLING_INTERVAL 5 /* seconds */
126 #define INITIAL_LOG_INTERVAL PRINTER_POLLING_INTERVAL
127 #define SUBSEQUENT_LOG_INTERVAL 3 * INITIAL_LOG_INTERVAL
129 #define kUSBPrinterClassTypeID CFUUIDGetConstantUUIDWithBytes(NULL, 0x06, 0x04, 0x7D, 0x16, 0x53, 0xA2, 0x11, 0xD6, 0x92, 0x06, 0x00, 0x30, 0x65, 0x52, 0x45, 0x92)
130 #define kUSBPrinterClassInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, 0x03, 0x34, 0x6D, 0x74, 0x53, 0xA3, 0x11, 0xD6, 0x9E, 0xA1, 0x76, 0x30, 0x65, 0x52, 0x45, 0x92)
132 #define kUSBClassDriverProperty CFSTR("USB Printing Class")
134 #define kUSBGenericTOPrinterClassDriver CFSTR("/System/Library/Printers/Libraries/USBGenericPrintingClass.plugin")
135 #define kUSBPrinterClassDeviceNotOpen -9664 /*kPMInvalidIOMContext*/
139 * Section 5.3 USB Printing Class spec
141 #define kUSBPrintingSubclass 1
142 #define kUSBPrintingProtocolNoOpen 0
143 #define kUSBPrintingProtocolUnidirectional 1
144 #define kUSBPrintingProtocolBidirectional 2
146 typedef IOUSBInterfaceInterface190
**printer_interface_t
;
148 typedef struct iodevice_request_s
/**** Device request ****/
156 } iodevice_request_t
;
158 typedef union /**** Centronics status byte ****/
163 unsigned reserved0
:2;
164 unsigned paperError
:1;
167 unsigned reserved1
:3;
169 } centronics_status_t
;
171 typedef struct classdriver_s
/**** g.classdriver context ****/
174 CFPlugInRef plugin
; /* release plugin */
175 IUnknownVTbl
**factory
; /* Factory */
176 void *vendorReference
; /* vendor class specific usage */
177 UInt32 location
; /* unique location in bus topology */
178 UInt8 interfaceNumber
; /* Interface number */
179 UInt16 vendorID
; /* Vendor id */
180 UInt16 productID
; /* Product id */
181 printer_interface_t interface
; /* identify the device to IOKit */
182 UInt8 outpipe
; /* mandatory bulkOut pipe */
183 UInt8 inpipe
; /* optional bulkIn pipe */
185 /* general class requests */
186 kern_return_t (*DeviceRequest
)(struct classdriver_s
**printer
, iodevice_request_t
*iorequest
, UInt16 timeout
);
187 kern_return_t (*GetString
)(struct classdriver_s
**printer
, UInt8 whichString
, UInt16 language
, UInt16 timeout
, CFStringRef
*result
);
189 /* standard printer class requests */
190 kern_return_t (*SoftReset
)(struct classdriver_s
**printer
, UInt16 timeout
);
191 kern_return_t (*GetCentronicsStatus
)(struct classdriver_s
**printer
, centronics_status_t
*result
, UInt16 timeout
);
192 kern_return_t (*GetDeviceID
)(struct classdriver_s
**printer
, CFStringRef
*devid
, UInt16 timeout
);
194 /* standard bulk device requests */
195 kern_return_t (*ReadPipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
);
196 kern_return_t (*WritePipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
, Boolean eoj
);
198 /* interface requests */
199 kern_return_t (*Open
)(struct classdriver_s
**printer
, UInt32 location
, UInt8 protocol
);
200 kern_return_t (*Abort
)(struct classdriver_s
**printer
);
201 kern_return_t (*Close
)(struct classdriver_s
**printer
);
203 /* initialize and terminate */
204 kern_return_t (*Initialize
)(struct classdriver_s
**printer
, struct classdriver_s
**baseclass
);
205 kern_return_t (*Terminate
)(struct classdriver_s
**printer
);
209 typedef Boolean (*iterator_callback_t
)(void *refcon
, io_service_t obj
);
211 typedef struct iterator_reference_s
/**** Iterator reference data */
213 iterator_callback_t callback
;
216 } iterator_reference_t
;
218 typedef struct globals_s
220 io_service_t printer_obj
;
221 classdriver_t
**classdriver
;
223 pthread_mutex_t read_thread_mutex
;
224 pthread_cond_t read_thread_cond
;
225 int read_thread_stop
;
226 int read_thread_done
;
228 pthread_mutex_t readwrite_lock_mutex
;
229 pthread_cond_t readwrite_lock_cond
;
238 CFRunLoopTimerRef status_timer
;
240 int print_fd
; /* File descriptor to print */
241 ssize_t print_bytes
; /* Print bytes read */
243 ssize_t debug_bytes
; /* Current bytes to read */
244 #endif /* DEBUG_WRITES */
247 int drain_output
; /* Drain all pending output */
248 int bidi_flag
; /* 0=unidirectional, 1=bidirectional */
250 pthread_mutex_t sidechannel_thread_mutex
;
251 pthread_cond_t sidechannel_thread_cond
;
252 int sidechannel_thread_stop
;
253 int sidechannel_thread_done
;
261 globals_t g
= { 0 }; /* Globals */
268 static Boolean
find_device_cb(void *refcon
, io_service_t obj
);
269 static Boolean
list_device_cb(void *refcon
, io_service_t obj
);
270 static CFStringRef
cfstr_create_trim(const char *cstr
);
271 static CFStringRef
copy_value_for_key(CFStringRef deviceID
, CFStringRef
*keys
);
272 static kern_return_t
load_classdriver(CFStringRef driverPath
, printer_interface_t intf
, classdriver_t
***printerDriver
);
273 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
);
274 static kern_return_t
registry_close();
275 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
);
276 static kern_return_t
unload_classdriver();
277 static OSStatus
copy_deviceid(classdriver_t
**printer
, CFStringRef
*deviceID
);
278 static void *read_thread(void *reference
);
279 static void *sidechannel_thread(void *reference
);
280 static void copy_deviceinfo(CFStringRef deviceIDString
, CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
281 static void copy_devicestring(io_service_t usbInterface
, CFStringRef
*deviceID
, UInt32
*deviceLocation
, UInt8
*interfaceNum
);
282 static void device_added(void *userdata
, io_iterator_t iterator
);
283 static void get_device_id(cups_sc_status_t
*status
, char *data
, int *datalen
);
284 static void iterate_printers(iterator_callback_t callBack
, void *userdata
);
285 static void parse_options(char *options
, char *serial
, int serial_size
, UInt32
*location
, Boolean
*wait_eof
);
286 static void release_deviceinfo(CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
287 static void setup_cfLanguage(void);
288 static void soft_reset();
289 static void status_timer_cb(CFRunLoopTimerRef timer
, void *info
);
291 #if defined(__i386__) || defined(__x86_64__)
292 static pid_t child_pid
; /* Child PID */
293 static void run_legacy_backend(int argc
, char *argv
[], int fd
); /* Starts child backend process running as a ppc executable */
294 #endif /* __i386__ || __x86_64__ */
295 static void sigterm_handler(int sig
); /* SIGTERM handler */
297 #ifdef PARSE_PS_ERRORS
298 static const char *next_line (const char *buffer
);
299 static void parse_pserror (char *sockBuffer
, int len
);
300 #endif /* PARSE_PS_ERRORS */
305 * 'list_devices()' - List all USB devices.
310 iterate_printers(list_device_cb
, NULL
);
315 * 'print_device()' - Print a file to a USB device.
318 int /* O - Exit status */
319 print_device(const char *uri
, /* I - Device URI */
320 const char *hostname
, /* I - Hostname/manufacturer */
321 const char *resource
, /* I - Resource/modelname */
322 char *options
, /* I - Device options/serial number */
323 int print_fd
, /* I - File descriptor to print */
324 int copies
, /* I - Copies to print */
325 int argc
, /* I - Number of command-line arguments (6 or 7) */
326 char *argv
[]) /* I - Command-line arguments */
328 char serial
[1024]; /* Serial number buffer */
329 OSStatus status
; /* Function results */
330 IOReturn iostatus
; /* Current IO status */
331 pthread_t read_thread_id
, /* Read thread */
332 sidechannel_thread_id
;/* Side-channel thread */
333 int have_sidechannel
= 0; /* Was the side-channel thread started? */
334 struct stat sidechannel_info
; /* Side-channel file descriptor info */
335 char print_buffer
[8192], /* Print data buffer */
336 *print_ptr
; /* Pointer into print data buffer */
337 UInt32 location
; /* Unique location in bus topology */
338 fd_set input_set
; /* Input set for select() */
339 CFStringRef driverBundlePath
; /* Class driver path */
340 int countdown
, /* Logging interval */
341 nfds
; /* Number of file descriptors */
342 ssize_t total_bytes
; /* Total bytes written */
343 UInt32 bytes
; /* Bytes written */
344 struct timeval
*timeout
, /* Timeout pointer */
346 struct timespec cond_timeout
; /* pthread condition timeout */
350 * See if the side-channel descriptor is valid...
353 have_sidechannel
= !fstat(CUPS_SC_FD
, &sidechannel_info
) &&
354 S_ISSOCK(sidechannel_info
.st_mode
);
357 * Localize using CoreFoundation...
362 parse_options(options
, serial
, sizeof(serial
), &location
, &g
.wait_eof
);
364 if (resource
[0] == '/')
367 g
.print_fd
= print_fd
;
368 g
.make
= cfstr_create_trim(hostname
);
369 g
.model
= cfstr_create_trim(resource
);
370 g
.serial
= cfstr_create_trim(serial
);
371 g
.location
= location
;
373 if (!g
.make
|| !g
.model
)
375 fprintf(stderr
, "DEBUG: Fatal USB error.\n");
376 _cupsLangPrintFilter(stderr
, "ERROR",
377 _("There was an unrecoverable USB error."));
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 _cupsLangPrintFilter(stderr
, "ERROR",
436 _("There was an unrecoverable USB error."));
437 fprintf(stderr
, "DEBUG: Could not load %s\n", print_buffer
);
439 if (driverBundlePath
)
440 CFRelease(driverBundlePath
);
442 return (CUPS_BACKEND_STOP
);
445 if (driverBundlePath
)
446 CFRelease(driverBundlePath
);
450 sleep(PRINTER_POLLING_INTERVAL
);
451 countdown
-= PRINTER_POLLING_INTERVAL
;
454 _cupsLangPrintFilter(stderr
, "INFO",
455 _("Waiting for printer to become available."));
456 fprintf(stderr
, "DEBUG: USB printer status: 0x%08x\n", (int)status
);
457 countdown
= SUBSEQUENT_LOG_INTERVAL
; /* subsequent log entries, every 15 seconds */
460 } while (status
!= noErr
);
462 fputs("STATE: -connecting-to-device\n", stderr
);
465 * Now that we are "connected" to the port, ignore SIGTERM so that we
466 * can finish out any page data the driver sends (e.g. to eject the
467 * current page... Only ignore SIGTERM if we are printing data from
468 * stdin (otherwise you can't cancel raw jobs...)
473 struct sigaction action
; /* POSIX signal action */
476 memset(&action
, 0, sizeof(action
));
478 sigemptyset(&action
.sa_mask
);
479 action
.sa_handler
= SIG_IGN
;
480 sigaction(SIGTERM
, &action
, NULL
);
484 * Start the side channel thread if the descriptor is valid...
487 pthread_mutex_init(&g
.readwrite_lock_mutex
, NULL
);
488 pthread_cond_init(&g
.readwrite_lock_cond
, NULL
);
489 g
.readwrite_lock
= 1;
491 if (have_sidechannel
)
493 g
.sidechannel_thread_stop
= 0;
494 g
.sidechannel_thread_done
= 0;
496 pthread_cond_init(&g
.sidechannel_thread_cond
, NULL
);
497 pthread_mutex_init(&g
.sidechannel_thread_mutex
, NULL
);
499 if (pthread_create(&sidechannel_thread_id
, NULL
, sidechannel_thread
, NULL
))
501 fprintf(stderr
, "DEBUG: Fatal USB error.\n");
502 _cupsLangPrintFilter(stderr
, "ERROR",
503 _("There was an unrecoverable USB error."));
504 fputs("DEBUG: Couldn't create side-channel thread\n", stderr
);
506 return (CUPS_BACKEND_STOP
);
511 * Get the read thread going...
514 g
.read_thread_stop
= 0;
515 g
.read_thread_done
= 0;
517 pthread_cond_init(&g
.read_thread_cond
, NULL
);
518 pthread_mutex_init(&g
.read_thread_mutex
, NULL
);
520 if (pthread_create(&read_thread_id
, NULL
, read_thread
, NULL
))
522 fprintf(stderr
, "DEBUG: Fatal USB error.\n");
523 _cupsLangPrintFilter(stderr
, "ERROR",
524 _("There was an unrecoverable USB error."));
525 fputs("DEBUG: Couldn't create read thread\n", stderr
);
527 return (CUPS_BACKEND_STOP
);
531 * The main thread sends the print file...
537 print_ptr
= print_buffer
;
539 while (status
== noErr
&& copies
-- > 0)
541 _cupsLangPrintFilter(stderr
, "INFO", _("Sending data to printer."));
543 if (print_fd
!= STDIN_FILENO
)
545 fputs("PAGE: 1 1\n", stderr
);
546 lseek(print_fd
, 0, SEEK_SET
);
549 while (status
== noErr
)
554 FD_SET(print_fd
, &input_set
);
557 * Calculate select timeout...
558 * If we have data waiting to send timeout is 100ms.
559 * else if we're draining print_fd timeout is 0.
560 * else we're waiting forever...
566 tv
.tv_usec
= 100000; /* 100ms */
569 else if (g
.drain_output
)
579 * I/O is unlocked around select...
582 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
583 g
.readwrite_lock
= 0;
584 pthread_cond_signal(&g
.readwrite_lock_cond
);
585 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
587 nfds
= select(print_fd
+ 1, &input_set
, NULL
, NULL
, timeout
);
590 * Reacquire the lock...
593 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
594 while (g
.readwrite_lock
)
595 pthread_cond_wait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
);
596 g
.readwrite_lock
= 1;
597 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
601 if (errno
== EINTR
&& total_bytes
== 0)
603 fputs("DEBUG: Received an interrupt before any bytes were "
604 "written, aborting\n", stderr
);
606 return (CUPS_BACKEND_OK
);
608 else if (errno
!= EAGAIN
&& errno
!= EINTR
)
610 _cupsLangPrintFilter(stderr
, "ERROR",
611 _("Unable to read print data."));
612 perror("DEBUG: select");
614 return (CUPS_BACKEND_FAILED
);
619 * If drain output has finished send a response...
622 if (g
.drain_output
&& !nfds
&& !g
.print_bytes
)
624 /* Send a response... */
625 cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
630 * Check if we have print data ready...
633 if (FD_ISSET(print_fd
, &input_set
))
636 g
.debug_bytes
+= 512;
637 if (g
.debug_bytes
> sizeof(print_buffer
))
640 g
.print_bytes
= read(print_fd
, print_buffer
, g
.debug_bytes
);
643 g
.print_bytes
= read(print_fd
, print_buffer
, sizeof(print_buffer
));
644 #endif /* DEBUG_WRITES */
646 if (g
.print_bytes
< 0)
649 * Read error - bail if we don't see EAGAIN or EINTR...
652 if (errno
!= EAGAIN
&& errno
!= EINTR
)
654 _cupsLangPrintFilter(stderr
, "ERROR",
655 _("Unable to read print data."));
656 perror("DEBUG: read");
658 return (CUPS_BACKEND_FAILED
);
663 else if (g
.print_bytes
== 0)
666 * End of file, break out of the loop...
672 print_ptr
= print_buffer
;
674 fprintf(stderr
, "DEBUG: Read %d bytes of print data...\n",
680 bytes
= g
.print_bytes
;
681 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
684 * Ignore timeout errors, but retain the number of bytes written to
685 * avoid sending duplicate data (<rdar://problem/6254911>)...
688 if (iostatus
== kIOUSBTransactionTimeout
)
690 fputs("DEBUG: Got USB transaction timeout during write\n", stderr
);
695 * If we've stalled, retry the write...
698 else if (iostatus
== kIOUSBPipeStalled
)
700 fputs("DEBUG: Got USB pipe stalled during write\n", stderr
);
702 bytes
= g
.print_bytes
;
703 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
707 * Retry a write after an aborted write since we probably just got
708 * SIGTERM (<rdar://problem/6860126>)...
711 else if (iostatus
== kIOReturnAborted
)
713 fputs("DEBUG: Got USB return aborted during write\n", stderr
);
715 IOReturn err
= (*g
.classdriver
)->Abort(g
.classdriver
);
716 fprintf(stderr
, "DEBUG: USB class driver Abort returned %x\n", err
);
720 #endif /* DEBUG_WRITES */
722 bytes
= g
.print_bytes
;
723 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
729 * Write error - bail if we don't see an error we can retry...
732 _cupsLangPrintFilter(stderr
, "ERROR",
733 _("Unable to send data to printer."));
734 fprintf(stderr
, "DEBUG: USB class driver WritePipe returned %x\n",
737 IOReturn err
= (*g
.classdriver
)->Abort(g
.classdriver
);
738 fprintf(stderr
, "DEBUG: USB class driver Abort returned %x\n",
741 status
= CUPS_BACKEND_FAILED
;
746 fprintf(stderr
, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes
);
748 g
.print_bytes
-= bytes
;
750 total_bytes
+= bytes
;
754 if (print_fd
!= 0 && status
== noErr
)
755 fprintf(stderr
, "DEBUG: Sending print file, %lld bytes...\n",
760 fprintf(stderr
, "DEBUG: Sent %lld bytes...\n", (off_t
)total_bytes
);
765 * Re-enable the SIGTERM handler so pthread_kill() will work...
768 struct sigaction action
; /* POSIX signal action */
770 memset(&action
, 0, sizeof(action
));
772 sigemptyset(&action
.sa_mask
);
773 sigaddset(&action
.sa_mask
, SIGTERM
);
774 action
.sa_handler
= sigterm_handler
;
775 sigaction(SIGTERM
, &action
, NULL
);
779 * Wait for the side channel thread to exit...
782 if (have_sidechannel
)
785 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
786 g
.readwrite_lock
= 0;
787 pthread_cond_signal(&g
.readwrite_lock_cond
);
788 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
790 g
.sidechannel_thread_stop
= 1;
791 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
793 if (!g
.sidechannel_thread_done
)
795 gettimeofday(&tv
, NULL
);
796 cond_timeout
.tv_sec
= tv
.tv_sec
+ WAIT_SIDE_DELAY
;
797 cond_timeout
.tv_nsec
= tv
.tv_usec
* 1000;
799 while (!g
.sidechannel_thread_done
)
801 if (pthread_cond_timedwait(&g
.sidechannel_thread_cond
,
802 &g
.sidechannel_thread_mutex
,
807 if (!g
.sidechannel_thread_done
)
810 * Force the side-channel thread to exit...
813 fputs("DEBUG: Force the side-channel thread to exit...\n", stderr
);
814 pthread_kill(sidechannel_thread_id
, SIGTERM
);
818 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
820 pthread_join(sidechannel_thread_id
, NULL
);
822 pthread_cond_destroy(&g
.sidechannel_thread_cond
);
823 pthread_mutex_destroy(&g
.sidechannel_thread_mutex
);
826 pthread_cond_destroy(&g
.readwrite_lock_cond
);
827 pthread_mutex_destroy(&g
.readwrite_lock_mutex
);
830 * Signal the read thread to stop...
833 g
.read_thread_stop
= 1;
836 * Give the read thread WAIT_EOF_DELAY seconds to complete all the data. If
837 * we are not signaled in that time then force the thread to exit.
840 pthread_mutex_lock(&g
.read_thread_mutex
);
842 if (!g
.read_thread_done
)
844 gettimeofday(&tv
, NULL
);
845 cond_timeout
.tv_sec
= tv
.tv_sec
+ WAIT_EOF_DELAY
;
846 cond_timeout
.tv_nsec
= tv
.tv_usec
* 1000;
848 while (!g
.read_thread_done
)
850 if (pthread_cond_timedwait(&g
.read_thread_cond
, &g
.read_thread_mutex
,
855 if (!g
.read_thread_done
)
858 * Force the read thread to exit...
862 fputs("DEBUG: Force the read thread to exit...\n", stderr
);
863 pthread_kill(read_thread_id
, SIGTERM
);
867 pthread_mutex_unlock(&g
.read_thread_mutex
);
869 pthread_join(read_thread_id
, NULL
); /* wait for the read thread to return */
871 pthread_cond_destroy(&g
.read_thread_cond
);
872 pthread_mutex_destroy(&g
.read_thread_mutex
);
875 * Close the connection and input file and general clean up...
880 if (print_fd
!= STDIN_FILENO
)
889 if (g
.serial
!= NULL
)
892 if (g
.printer_obj
!= 0x0)
893 IOObjectRelease(g
.printer_obj
);
900 * 'read_thread()' - Thread to read the backchannel data on.
903 static void *read_thread(void *reference
)
905 UInt8 readbuffer
[512];
907 kern_return_t readstatus
;
908 struct mach_timebase_info timeBaseInfo
;
912 /* Calculate what 250 milliSeconds are in mach absolute time...
914 mach_timebase_info(&timeBaseInfo
);
915 delay
= ((uint64_t)250000000 * (uint64_t)timeBaseInfo
.denom
) / (uint64_t)timeBaseInfo
.numer
;
920 * Remember when we started so we can throttle the loop after the read call...
923 start
= mach_absolute_time();
925 rbytes
= sizeof(readbuffer
);
926 readstatus
= (*g
.classdriver
)->ReadPipe(g
.classdriver
, readbuffer
, &rbytes
);
927 if (readstatus
== kIOReturnSuccess
&& rbytes
> 0)
929 fprintf(stderr
, "DEBUG: Read %d bytes of back-channel data...\n",
931 cupsBackChannelWrite((char*)readbuffer
, rbytes
, 1.0);
933 /* cntrl-d is echoed by the printer.
935 * Xerox Phaser 6250D doesn't echo the cntrl-d.
936 * Xerox Phaser 6250D doesn't always send the product query.
938 if (g
.wait_eof
&& readbuffer
[rbytes
-1] == 0x4)
941 #ifdef PARSE_PS_ERRORS
942 parse_pserror(readbuffer
, rbytes
);
945 else if (readstatus
== kIOUSBTransactionTimeout
)
946 fputs("DEBUG: Got USB transaction timeout during read\n", stderr
);
947 else if (readstatus
== kIOUSBPipeStalled
)
948 fputs("DEBUG: Got USB pipe stalled during read\n", stderr
);
949 else if (readstatus
== kIOReturnAborted
)
950 fputs("DEBUG: Got USB return aborted during read\n", stderr
);
953 * Make sure this loop executes no more than once every 250 miliseconds...
956 if ((readstatus
!= kIOReturnSuccess
|| rbytes
== 0) && (g
.wait_eof
|| !g
.read_thread_stop
))
957 mach_wait_until(start
+ delay
);
959 } while (g
.wait_eof
|| !g
.read_thread_stop
); /* Abort from main thread tests error here */
962 * Let the main thread know that we have completed the read thread...
965 pthread_mutex_lock(&g
.read_thread_mutex
);
966 g
.read_thread_done
= 1;
967 pthread_cond_signal(&g
.read_thread_cond
);
968 pthread_mutex_unlock(&g
.read_thread_mutex
);
975 * 'sidechannel_thread()' - Handle side-channel requests.
979 sidechannel_thread(void *reference
)
981 cups_sc_command_t command
; /* Request command */
982 cups_sc_status_t status
; /* Request/response status */
983 char data
[2048]; /* Request/response data */
984 int datalen
; /* Request/response data size */
989 datalen
= sizeof(data
);
991 if (cupsSideChannelRead(&command
, &status
, data
, &datalen
, 1.0))
993 if (status
== CUPS_SC_STATUS_TIMEOUT
)
1001 case CUPS_SC_CMD_SOFT_RESET
: /* Do a soft reset */
1002 fputs("DEBUG: CUPS_SC_CMD_SOFT_RESET received from driver...\n",
1005 if ((*g
.classdriver
)->SoftReset
!= NULL
)
1008 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
1009 fputs("DEBUG: Returning status CUPS_STATUS_OK with no bytes...\n",
1014 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
1016 fputs("DEBUG: Returning status CUPS_STATUS_NOT_IMPLEMENTED with "
1017 "no bytes...\n", stderr
);
1021 case CUPS_SC_CMD_DRAIN_OUTPUT
: /* Drain all pending output */
1022 fputs("DEBUG: CUPS_SC_CMD_DRAIN_OUTPUT received from driver...\n",
1028 case CUPS_SC_CMD_GET_BIDI
: /* Is the connection bidirectional? */
1029 fputs("DEBUG: CUPS_SC_CMD_GET_BIDI received from driver...\n",
1032 data
[0] = g
.bidi_flag
;
1033 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
1036 "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
1040 case CUPS_SC_CMD_GET_DEVICE_ID
: /* Return IEEE-1284 device ID */
1041 fputs("DEBUG: CUPS_SC_CMD_GET_DEVICE_ID received from driver...\n",
1044 datalen
= sizeof(data
);
1045 get_device_id(&status
, data
, &datalen
);
1046 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, datalen
, 1.0);
1048 if (datalen
< sizeof(data
))
1049 data
[datalen
] = '\0';
1051 data
[sizeof(data
) - 1] = '\0';
1054 "DEBUG: Returning CUPS_SC_STATUS_OK with %d bytes (%s)...\n",
1058 case CUPS_SC_CMD_GET_STATE
: /* Return device state */
1059 fputs("DEBUG: CUPS_SC_CMD_GET_STATE received from driver...\n",
1062 data
[0] = CUPS_SC_STATE_ONLINE
;
1063 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
1066 "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
1071 fprintf(stderr
, "DEBUG: Unknown side-channel command (%d) received "
1072 "from driver...\n", command
);
1074 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
1077 fputs("DEBUG: Returned CUPS_SC_STATUS_NOT_IMPLEMENTED with no bytes...\n",
1082 while (!g
.sidechannel_thread_stop
);
1084 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
1085 g
.sidechannel_thread_done
= 1;
1086 pthread_cond_signal(&g
.sidechannel_thread_cond
);
1087 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
1095 * 'iterate_printers()' - Iterate over all the printers.
1098 static void iterate_printers(iterator_callback_t callBack
,
1101 mach_port_t masterPort
= 0x0;
1102 kern_return_t kr
= IOMasterPort (bootstrap_port
, &masterPort
);
1104 if (kr
== kIOReturnSuccess
&& masterPort
!= 0x0)
1106 io_iterator_t addIterator
= 0x0;
1108 iterator_reference_t reference
= { callBack
, userdata
, true };
1109 IONotificationPortRef addNotification
= IONotificationPortCreate(masterPort
);
1111 int klass
= kUSBPrintingClass
;
1112 int subklass
= kUSBPrintingSubclass
;
1114 CFNumberRef usb_klass
= CFNumberCreate(NULL
, kCFNumberIntType
, &klass
);
1115 CFNumberRef usb_subklass
= CFNumberCreate(NULL
, kCFNumberIntType
, &subklass
);
1116 CFMutableDictionaryRef usbPrinterMatchDictionary
= IOServiceMatching(kIOUSBInterfaceClassName
);
1118 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceClass"), usb_klass
);
1119 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceSubClass"), usb_subklass
);
1121 CFRelease(usb_klass
);
1122 CFRelease(usb_subklass
);
1124 kr
= IOServiceAddMatchingNotification(addNotification
, kIOMatchedNotification
, usbPrinterMatchDictionary
, &device_added
, &reference
, &addIterator
);
1125 if (addIterator
!= 0x0)
1127 device_added (&reference
, addIterator
);
1129 if (reference
.keepRunning
)
1131 CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification
), kCFRunLoopDefaultMode
);
1134 IOObjectRelease(addIterator
);
1136 mach_port_deallocate(mach_task_self(), masterPort
);
1142 * 'device_added()' - Device added notifier.
1145 static void device_added(void *userdata
,
1146 io_iterator_t iterator
)
1148 iterator_reference_t
*reference
= userdata
;
1151 while (reference
->keepRunning
&& (obj
= IOIteratorNext(iterator
)) != 0x0)
1153 if (reference
->callback
!= NULL
)
1154 reference
->keepRunning
= reference
->callback(reference
->userdata
, obj
);
1156 IOObjectRelease(obj
);
1159 /* One last call to the call back now that we are not longer have printers left to iterate...
1161 if (reference
->keepRunning
)
1162 reference
->keepRunning
= reference
->callback(reference
->userdata
, 0x0);
1164 if (!reference
->keepRunning
)
1165 CFRunLoopStop(CFRunLoopGetCurrent());
1170 * 'list_device_cb()' - list_device iterator callback.
1173 static Boolean
list_device_cb(void *refcon
,
1176 Boolean keepRunning
= (obj
!= 0x0);
1180 CFStringRef deviceIDString
= NULL
;
1181 UInt32 deviceLocation
= 0;
1182 UInt8 interfaceNum
= 0;
1184 copy_devicestring(obj
, &deviceIDString
, &deviceLocation
, &interfaceNum
);
1185 if (deviceIDString
!= NULL
)
1187 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1188 char uristr
[1024], makestr
[1024], modelstr
[1024], serialstr
[1024];
1189 char optionsstr
[1024], idstr
[1024], make_modelstr
[1024];
1191 copy_deviceinfo(deviceIDString
, &make
, &model
, &serial
);
1192 CFStringGetCString(deviceIDString
, idstr
, sizeof(idstr
),
1193 kCFStringEncodingUTF8
);
1194 backendGetMakeModel(idstr
, make_modelstr
, sizeof(make_modelstr
));
1199 !CFStringGetCString(make
, makestr
, sizeof(makestr
),
1200 kCFStringEncodingUTF8
))
1201 strcpy(makestr
, "Unknown");
1204 !CFStringGetCString(model
, &modelstr
[1], sizeof(modelstr
)-1,
1205 kCFStringEncodingUTF8
))
1206 strcpy(modelstr
+ 1, "Printer");
1208 optionsstr
[0] = '\0';
1211 CFStringGetCString(serial
, serialstr
, sizeof(serialstr
), kCFStringEncodingUTF8
);
1212 snprintf(optionsstr
, sizeof(optionsstr
), "?serial=%s", serialstr
);
1214 else if (deviceLocation
!= 0)
1215 snprintf(optionsstr
, sizeof(optionsstr
), "?location=%x", (unsigned)deviceLocation
);
1217 httpAssembleURI(HTTP_URI_CODING_ALL
, uristr
, sizeof(uristr
), "usb", NULL
, makestr
, 0, modelstr
);
1218 strlcat(uristr
, optionsstr
, sizeof(uristr
));
1220 cupsBackendReport("direct", uristr
, make_modelstr
, make_modelstr
, idstr
,
1223 release_deviceinfo(&make
, &model
, &serial
);
1224 CFRelease(deviceIDString
);
1233 * 'find_device_cb()' - print_device iterator callback.
1236 static Boolean
find_device_cb(void *refcon
,
1239 Boolean keepLooking
= true;
1243 CFStringRef idString
= NULL
;
1244 UInt32 location
= -1;
1245 UInt8 interfaceNum
= 0;
1247 copy_devicestring(obj
, &idString
, &location
, &interfaceNum
);
1248 if (idString
!= NULL
)
1250 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1252 copy_deviceinfo(idString
, &make
, &model
, &serial
);
1253 if (make
&& CFStringCompare(make
, g
.make
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1255 if (model
&& CFStringCompare(model
, g
.model
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1257 if (g
.serial
!= NULL
&& CFStringGetLength(g
.serial
) > 0)
1259 if (serial
!= NULL
&& CFStringCompare(serial
, g
.serial
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1261 IOObjectRetain(obj
);
1262 g
.printer_obj
= obj
;
1263 keepLooking
= false;
1268 if (g
.printer_obj
!= 0)
1269 IOObjectRelease(g
.printer_obj
);
1271 g
.printer_obj
= obj
;
1272 IOObjectRetain(obj
);
1274 if (g
.location
== 0 || g
.location
== location
)
1275 keepLooking
= false;
1278 g
.interfaceNum
= interfaceNum
;
1282 release_deviceinfo(&make
, &model
, &serial
);
1283 CFRelease(idString
);
1288 keepLooking
= (g
.printer_obj
== 0);
1289 if (obj
== 0x0 && keepLooking
)
1291 CFRunLoopTimerContext context
= { 0, refcon
, NULL
, NULL
, NULL
};
1292 CFRunLoopTimerRef timer
= CFRunLoopTimerCreate(NULL
, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb
, &context
);
1295 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer
, kCFRunLoopDefaultMode
);
1296 g
.status_timer
= timer
;
1301 if (!keepLooking
&& g
.status_timer
!= NULL
)
1303 fputs("STATE: -offline-report\n", stderr
);
1304 _cupsLangPrintFilter(stderr
, "INFO", _("Printer is now online."));
1305 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g
.status_timer
, kCFRunLoopDefaultMode
);
1306 CFRelease(g
.status_timer
);
1307 g
.status_timer
= NULL
;
1315 * 'status_timer_cb()' - Status timer callback.
1318 static void status_timer_cb(CFRunLoopTimerRef timer
,
1321 fputs("STATE: +offline-report\n", stderr
);
1322 _cupsLangPrintFilter(stderr
, "INFO", _("Printer is offline."));
1324 if (getenv("CLASS") != NULL
)
1327 * If the CLASS environment variable is set, the job was submitted
1328 * to a class and not to a specific queue. In this case, we want
1329 * to abort immediately so that the job can be requeued on the next
1330 * available printer in the class.
1332 * Sleep 5 seconds to keep the job from requeuing too rapidly...
1337 exit(CUPS_BACKEND_FAILED
);
1344 * 'copy_deviceinfo()' - Copy strings from the 1284 device ID.
1347 static void copy_deviceinfo(CFStringRef deviceIDString
,
1350 CFStringRef
*serial
)
1352 CFStringRef modelKeys
[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL
};
1353 CFStringRef makeKeys
[] = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL
};
1354 CFStringRef serialKeys
[] = { CFSTR("SN:"), CFSTR("SERN:"), NULL
};
1357 *make
= copy_value_for_key(deviceIDString
, makeKeys
);
1360 *model
= copy_value_for_key(deviceIDString
, modelKeys
);
1363 *serial
= copy_value_for_key(deviceIDString
, serialKeys
);
1368 * 'release_deviceinfo()' - Release deviceinfo strings.
1371 static void release_deviceinfo(CFStringRef
*make
,
1373 CFStringRef
*serial
)
1375 if (make
!= NULL
&& *make
!= NULL
)
1381 if (model
!= NULL
&& *model
!= NULL
)
1387 if (serial
!= NULL
&& *serial
!= NULL
)
1397 * 'load_classdriver()' - Load a classdriver.
1400 static kern_return_t
load_classdriver(CFStringRef driverPath
,
1401 printer_interface_t intf
,
1402 classdriver_t
***printerDriver
)
1404 kern_return_t kr
= kUSBPrinterClassDeviceNotOpen
;
1405 classdriver_t
**driver
= NULL
;
1406 CFStringRef bundle
= driverPath
? driverPath
: kUSBGenericTOPrinterClassDriver
;
1407 char bundlestr
[1024]; /* Bundle path */
1408 struct stat bundleinfo
; /* File information for bundle */
1409 CFURLRef url
; /* URL for driver */
1410 CFPlugInRef plugin
= NULL
; /* Plug-in address */
1413 CFStringGetCString(bundle
, bundlestr
, sizeof(bundlestr
), kCFStringEncodingUTF8
);
1416 * Validate permissions for the class driver...
1419 if (stat(bundlestr
, &bundleinfo
))
1421 fprintf(stderr
, "DEBUG: Class driver \"%s\" not available: %s\n",
1422 bundlestr
, strerror(errno
));
1423 fputs("STATE: +cups-missing-filter-warning\n", stderr
);
1425 if (errno
== ENOENT
&& driverPath
)
1426 return (load_classdriver(NULL
, intf
, printerDriver
));
1430 else if (bundleinfo
.st_uid
||
1431 (bundleinfo
.st_gid
&& (bundleinfo
.st_mode
& S_IWGRP
)) ||
1432 (bundleinfo
.st_mode
& S_IWOTH
))
1434 fprintf(stderr
, "DEBUG: Class driver \"%s\" has insecure file "
1435 "permissions (0%o/uid=%d/gid=%d).\n", bundlestr
,
1436 bundleinfo
.st_mode
, (int)bundleinfo
.st_uid
,
1437 (int)bundleinfo
.st_gid
);
1438 fputs("STATE: +cups-insecure-filter-warning\n", stderr
);
1440 if (bundleinfo
.st_uid
|| (bundleinfo
.st_mode
& S_IWOTH
))
1443 return (load_classdriver(NULL
, intf
, printerDriver
));
1450 * Try loading the class driver...
1453 url
= CFURLCreateWithFileSystemPath(NULL
, bundle
, kCFURLPOSIXPathStyle
, true);
1457 plugin
= CFPlugInCreate(NULL
, url
);
1465 CFArrayRef factories
= CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID
, plugin
);
1466 if (factories
!= NULL
&& CFArrayGetCount(factories
) > 0)
1468 CFUUIDRef factoryID
= CFArrayGetValueAtIndex(factories
, 0);
1469 IUnknownVTbl
**iunknown
= CFPlugInInstanceCreate(NULL
, factoryID
, kUSBPrinterClassTypeID
);
1470 if (iunknown
!= NULL
)
1472 kr
= (*iunknown
)->QueryInterface(iunknown
, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID
), (LPVOID
*)&driver
);
1473 if (kr
== kIOReturnSuccess
&& driver
!= NULL
)
1475 classdriver_t
**genericDriver
= NULL
;
1476 if (driverPath
!= NULL
&& CFStringCompare(driverPath
, kUSBGenericTOPrinterClassDriver
, 0) != kCFCompareEqualTo
)
1477 kr
= load_classdriver(NULL
, intf
, &genericDriver
);
1479 if (kr
== kIOReturnSuccess
)
1481 (*driver
)->interface
= intf
;
1482 (*driver
)->Initialize(driver
, genericDriver
);
1484 (*driver
)->plugin
= plugin
;
1485 (*driver
)->interface
= intf
;
1486 *printerDriver
= driver
;
1489 (*iunknown
)->Release(iunknown
);
1491 CFRelease(factories
);
1495 fprintf(stderr
, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr
, (int)kr
);
1502 * 'unload_classdriver()' - Unload a classdriver.
1505 static kern_return_t
unload_classdriver(classdriver_t
***classdriver
)
1507 if (*classdriver
!= NULL
)
1509 (**classdriver
)->Release(*classdriver
);
1510 *classdriver
= NULL
;
1513 return kIOReturnSuccess
;
1518 * 'load_printerdriver()' - Load vendor's classdriver.
1520 * If driverBundlePath is not NULL on return it is the callers responsbility to release it!
1523 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
)
1525 IOCFPlugInInterface
**iodev
= NULL
;
1528 printer_interface_t intf
;
1531 kr
= IOCreatePlugInInterfaceForService(g
.printer_obj
, kIOUSBInterfaceUserClientTypeID
, kIOCFPlugInInterfaceID
, &iodev
, &score
);
1532 if (kr
== kIOReturnSuccess
)
1534 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*) &intf
)) == noErr
)
1536 *driverBundlePath
= IORegistryEntryCreateCFProperty(g
.printer_obj
, kUSBClassDriverProperty
, NULL
, kNilOptions
);
1538 kr
= load_classdriver(*driverBundlePath
, intf
, &g
.classdriver
);
1540 if (kr
!= kIOReturnSuccess
)
1541 (*intf
)->Release(intf
);
1543 IODestroyPlugInInterface(iodev
);
1550 * 'registry_open()' - Open a connection to the printer.
1553 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
)
1555 g
.bidi_flag
= 0; /* 0=unidirectional */
1557 kern_return_t kr
= load_printerdriver(driverBundlePath
);
1558 if (kr
!= kIOReturnSuccess
)
1561 if (g
.classdriver
!= NULL
)
1563 (*g
.classdriver
)->interfaceNumber
= g
.interfaceNum
;
1564 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolBidirectional
);
1565 if (kr
!= kIOReturnSuccess
|| (*g
.classdriver
)->interface
== NULL
)
1567 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolUnidirectional
);
1568 if (kr
== kIOReturnSuccess
)
1570 if ((*g
.classdriver
)->interface
== NULL
)
1572 (*g
.classdriver
)->Close(g
.classdriver
);
1578 g
.bidi_flag
= 1; /* 1=bidirectional */
1581 if (kr
!= kIOReturnSuccess
)
1582 unload_classdriver(&g
.classdriver
);
1589 * 'registry_close()' - Close the connection to the printer.
1592 static kern_return_t
registry_close()
1594 if (g
.classdriver
!= NULL
)
1595 (*g
.classdriver
)->Close(g
.classdriver
);
1597 unload_classdriver(&g
.classdriver
);
1598 return kIOReturnSuccess
;
1603 * 'copy_deviceid()' - Copy the 1284 device id string.
1606 static OSStatus
copy_deviceid(classdriver_t
**classdriver
,
1607 CFStringRef
*deviceID
)
1609 CFStringRef devID
= NULL
,
1613 deviceSerial
= NULL
;
1615 OSStatus err
= (*classdriver
)->GetDeviceID(classdriver
, &devID
, DEFAULT_TIMEOUT
);
1617 copy_deviceinfo(devID
, &deviceMake
, &deviceModel
, &deviceSerial
);
1619 if (deviceMake
== NULL
|| deviceModel
== NULL
|| deviceSerial
== NULL
)
1621 IOUSBDeviceDescriptor desc
;
1622 iodevice_request_t request
;
1624 request
.requestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
1625 request
.request
= kUSBRqGetDescriptor
;
1626 request
.value
= (kUSBDeviceDesc
<< 8) | 0;
1628 request
.length
= sizeof(desc
);
1629 request
.buffer
= &desc
;
1630 err
= (*classdriver
)->DeviceRequest(classdriver
, &request
, DEFAULT_TIMEOUT
);
1631 if (err
== kIOReturnSuccess
)
1633 CFMutableStringRef newDevID
= CFStringCreateMutable(NULL
, 0);
1635 if (deviceMake
== NULL
)
1637 CFStringRef data
= NULL
;
1638 err
= (*classdriver
)->GetString(classdriver
, desc
.iManufacturer
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1641 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MFG:%@;"), data
);
1646 if (deviceModel
== NULL
)
1648 CFStringRef data
= NULL
;
1649 err
= (*classdriver
)->GetString(classdriver
, desc
.iProduct
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1652 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MDL:%@;"), data
);
1657 if (deviceSerial
== NULL
&& desc
.iSerialNumber
!= 0)
1659 CFStringRef data
= NULL
;
1660 err
= (*classdriver
)->GetString(classdriver
, desc
.iSerialNumber
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1663 CFStringAppendFormat(newDevID
, NULL
, CFSTR("SERN:%@;"), data
);
1670 CFStringAppend(newDevID
, devID
);
1674 *deviceID
= newDevID
;
1681 release_deviceinfo(&deviceMake
, &deviceModel
, &deviceSerial
);
1688 * 'copy_devicestring()' - Copy the 1284 device id string.
1691 static void copy_devicestring(io_service_t usbInterface
,
1692 CFStringRef
*deviceID
,
1693 UInt32
*deviceLocation
,
1694 UInt8
*interfaceNumber
)
1696 IOCFPlugInInterface
**iodev
= NULL
;
1699 printer_interface_t intf
;
1701 classdriver_t
**klassDriver
= NULL
;
1702 CFStringRef driverBundlePath
;
1704 if ((kr
= IOCreatePlugInInterfaceForService(usbInterface
,
1705 kIOUSBInterfaceUserClientTypeID
,
1706 kIOCFPlugInInterfaceID
,
1707 &iodev
, &score
)) == kIOReturnSuccess
)
1709 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*)
1712 (*intf
)->GetLocationID(intf
, deviceLocation
);
1713 (*intf
)->GetInterfaceNumber(intf
, interfaceNumber
);
1715 driverBundlePath
= IORegistryEntryCreateCFProperty(usbInterface
,
1716 kUSBClassDriverProperty
,
1719 kr
= load_classdriver(driverBundlePath
, intf
, &klassDriver
);
1721 if (kr
!= kIOReturnSuccess
&& driverBundlePath
!= NULL
)
1722 kr
= load_classdriver(NULL
, intf
, &klassDriver
);
1724 if (kr
== kIOReturnSuccess
&& klassDriver
!= NULL
)
1725 kr
= copy_deviceid(klassDriver
, deviceID
);
1727 unload_classdriver(&klassDriver
);
1729 if (driverBundlePath
!= NULL
)
1730 CFRelease(driverBundlePath
);
1732 /* (*intf)->Release(intf); */
1734 IODestroyPlugInInterface(iodev
);
1741 * 'copy_value_for_key()' - Copy value string associated with a key.
1744 static CFStringRef
copy_value_for_key(CFStringRef deviceID
,
1747 CFStringRef value
= NULL
;
1748 CFArrayRef kvPairs
= deviceID
!= NULL
? CFStringCreateArrayBySeparatingStrings(NULL
, deviceID
, CFSTR(";")) : NULL
;
1749 CFIndex max
= kvPairs
!= NULL
? CFArrayGetCount(kvPairs
) : 0;
1752 while (idx
< max
&& value
== NULL
)
1754 CFStringRef kvpair
= CFArrayGetValueAtIndex(kvPairs
, idx
);
1756 while (keys
[idxx
] != NULL
&& value
== NULL
)
1758 CFRange range
= CFStringFind(kvpair
, keys
[idxx
], kCFCompareCaseInsensitive
);
1759 if (range
.length
!= -1)
1761 if (range
.location
!= 0)
1763 CFMutableStringRef theString
= CFStringCreateMutableCopy(NULL
, 0, kvpair
);
1764 CFStringTrimWhitespace(theString
);
1765 range
= CFStringFind(theString
, keys
[idxx
], kCFCompareCaseInsensitive
);
1766 if (range
.location
== 0)
1767 value
= CFStringCreateWithSubstring(NULL
, theString
, CFRangeMake(range
.length
, CFStringGetLength(theString
) - range
.length
));
1769 CFRelease(theString
);
1773 CFStringRef theString
= CFStringCreateWithSubstring(NULL
, kvpair
, CFRangeMake(range
.length
, CFStringGetLength(kvpair
) - range
.length
));
1774 CFMutableStringRef theString2
= CFStringCreateMutableCopy(NULL
, 0, theString
);
1775 CFRelease(theString
);
1777 CFStringTrimWhitespace(theString2
);
1786 if (kvPairs
!= NULL
)
1793 * 'cfstr_create_trim()' - Create CFString and trim whitespace characters.
1796 CFStringRef
cfstr_create_trim(const char *cstr
)
1799 CFMutableStringRef cfmutablestr
= NULL
;
1801 if ((cfstr
= CFStringCreateWithCString(NULL
, cstr
, kCFStringEncodingUTF8
)) != NULL
)
1803 if ((cfmutablestr
= CFStringCreateMutableCopy(NULL
, 1024, cfstr
)) != NULL
)
1804 CFStringTrimWhitespace(cfmutablestr
);
1808 return (CFStringRef
) cfmutablestr
;
1814 * 'parse_options()' - Parse URI options.
1817 static void parse_options(char *options
,
1823 char sep
, /* Separator character */
1824 *name
, /* Name of option */
1825 *value
; /* Value of option */
1844 while (*options
&& *options
!= '=' && *options
!= '+' && *options
!= '&')
1847 if ((sep
= *options
) != '\0')
1858 while (*options
&& *options
!= '+' && *options
!= '&')
1868 * Process the option...
1871 if (!strcasecmp(name
, "waiteof"))
1873 if (!strcasecmp(value
, "on") ||
1874 !strcasecmp(value
, "yes") ||
1875 !strcasecmp(value
, "true"))
1877 else if (!strcasecmp(value
, "off") ||
1878 !strcasecmp(value
, "no") ||
1879 !strcasecmp(value
, "false"))
1882 _cupsLangPrintFilter(stderr
, "WARNING",
1883 _("Boolean expected for waiteof option \"%s\"."),
1886 else if (!strcasecmp(name
, "serial"))
1887 strlcpy(serial
, value
, serial_size
);
1888 else if (!strcasecmp(name
, "location") && location
)
1889 *location
= strtol(value
, NULL
, 16);
1895 * @function setup_cfLanguage
1896 * @abstract Convert the contents of the CUPS 'APPLE_LANGUAGE' environment
1897 * variable into a one element CF array of languages.
1899 * @discussion Each submitted job comes with a natural language. CUPS passes
1900 * that language in an environment variable. We take that language
1901 * and jam it into the AppleLanguages array so that CF will use
1902 * it when reading localized resources. We need to do this before
1903 * any CF code reads and caches the languages array, so this function
1904 * should be called early in main()
1906 static void setup_cfLanguage(void)
1908 CFStringRef lang
[1] = {NULL
};
1909 CFArrayRef langArray
= NULL
;
1910 const char *requestedLang
= NULL
;
1912 if ((requestedLang
= getenv("APPLE_LANGUAGE")) == NULL
)
1913 requestedLang
= getenv("LANG");
1915 if (requestedLang
!= NULL
)
1917 lang
[0] = CFStringCreateWithCString(kCFAllocatorDefault
, requestedLang
, kCFStringEncodingUTF8
);
1918 langArray
= CFArrayCreate(kCFAllocatorDefault
, (const void **)lang
, sizeof(lang
) / sizeof(lang
[0]), &kCFTypeArrayCallBacks
);
1920 CFPreferencesSetValue(CFSTR("AppleLanguages"), langArray
, kCFPreferencesCurrentApplication
, kCFPreferencesAnyUser
, kCFPreferencesAnyHost
);
1921 fprintf(stderr
, "DEBUG: usb: AppleLanguages=\"%s\"\n", requestedLang
);
1924 CFRelease(langArray
);
1927 fputs("DEBUG: usb: LANG and APPLE_LANGUAGE environment variables missing.\n", stderr
);
1931 #if defined(__i386__) || defined(__x86_64__)
1933 * @function run_legacy_backend
1935 * @abstract Starts child backend process running as a ppc or i386 executable.
1937 * @result Never returns; always calls exit().
1941 static void run_legacy_backend(int argc
,
1948 pid_t waitpid_status
;
1950 char *usb_legacy_status
;
1953 * If we're running as x86_64 or i386 and couldn't load the class driver
1954 * (because it's ppc or i386), then try to re-exec ourselves in ppc or i386
1955 * mode to try again. If we don't have a ppc or i386 architecture we may be
1956 * running with the same architecture again so guard against this by setting
1957 * and testing an environment variable...
1961 usb_legacy_status
= getenv("USB_I386_STATUS");
1963 usb_legacy_status
= getenv("USB_PPC_STATUS");
1964 # endif /* __x86_64__ */
1966 if (!usb_legacy_status
)
1969 * Setup a SIGTERM handler then block it before forking...
1972 int err
; /* posix_spawn result */
1973 struct sigaction action
; /* POSIX signal action */
1974 sigset_t newmask
, /* New signal mask */
1975 oldmask
; /* Old signal mask */
1976 char usbpath
[1024]; /* Path to USB backend */
1977 const char *cups_serverbin
;/* Path to CUPS binaries */
1980 memset(&action
, 0, sizeof(action
));
1981 sigaddset(&action
.sa_mask
, SIGTERM
);
1982 action
.sa_handler
= sigterm_handler
;
1983 sigaction(SIGTERM
, &action
, NULL
);
1985 sigemptyset(&newmask
);
1986 sigaddset(&newmask
, SIGTERM
);
1987 sigprocmask(SIG_BLOCK
, &newmask
, &oldmask
);
1990 * Set the environment variable...
1994 setenv("USB_I386_STATUS", "1", false);
1996 setenv("USB_PPC_STATUS", "1", false);
1997 # endif /* __x86_64__ */
2000 * Tell the kernel to use the specified CPU architecture...
2004 cpu_type_t cpu
= CPU_TYPE_I386
;
2006 cpu_type_t cpu
= CPU_TYPE_POWERPC
;
2007 # endif /* __x86_64__ */
2009 posix_spawnattr_t attrs
;
2011 if (!posix_spawnattr_init(&attrs
))
2013 posix_spawnattr_setsigdefault(&attrs
, &oldmask
);
2014 if (posix_spawnattr_setbinpref_np(&attrs
, 1, &cpu
, &ocount
) || ocount
!= 1)
2017 perror("DEBUG: Unable to set binary preference to i386");
2019 perror("DEBUG: Unable to set binary preference to ppc");
2020 # endif /* __x86_64__ */
2021 _cupsLangPrintFilter(stderr
, "ERROR",
2022 _("Unable to use legacy USB class driver."));
2023 exit(CUPS_BACKEND_STOP
);
2028 * Set up the arguments and call posix_spawn...
2031 if ((cups_serverbin
= getenv("CUPS_SERVERBIN")) == NULL
)
2032 cups_serverbin
= CUPS_SERVERBIN
;
2033 snprintf(usbpath
, sizeof(usbpath
), "%s/backend/usb", cups_serverbin
);
2035 for (i
= 0; i
< argc
&& i
< (sizeof(my_argv
) / sizeof(my_argv
[0])) - 1; i
++)
2036 my_argv
[i
] = argv
[i
];
2040 if ((err
= posix_spawn(&child_pid
, usbpath
, NULL
, &attrs
, my_argv
,
2043 fprintf(stderr
, "DEBUG: Unable to exec %s: %s\n", usbpath
,
2045 _cupsLangPrintFilter(stderr
, "ERROR",
2046 _("Unable to use legacy USB class driver."));
2047 exit(CUPS_BACKEND_STOP
);
2051 * Unblock signals...
2054 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
2057 * Close the fds we won't be using then wait for the child backend to exit.
2063 fprintf(stderr
, "DEBUG: Started usb(legacy) backend (PID %d)\n",
2066 while ((waitpid_status
= waitpid(child_pid
, &childstatus
, 0)) == (pid_t
)-1 && errno
== EINTR
)
2069 if (WIFSIGNALED(childstatus
))
2071 exitstatus
= CUPS_BACKEND_STOP
;
2072 fprintf(stderr
, "DEBUG: usb(legacy) backend %d crashed on signal %d\n",
2073 child_pid
, WTERMSIG(childstatus
));
2077 if ((exitstatus
= WEXITSTATUS(childstatus
)) != 0)
2079 "DEBUG: usb(legacy) backend %d stopped with status %d\n",
2080 child_pid
, exitstatus
);
2082 fprintf(stderr
, "DEBUG: usb(legacy) backend %d exited with no errors\n",
2088 fputs("DEBUG: usb(legacy) backend running native again\n", stderr
);
2089 exitstatus
= CUPS_BACKEND_STOP
;
2094 #endif /* __i386__ || __x86_64__ */
2098 * 'sigterm_handler()' - SIGTERM handler.
2102 sigterm_handler(int sig
) /* I - Signal */
2104 #if defined(__i386__) || defined(__x86_64__)
2106 * If we started a child process pass the signal on to it...
2112 * If we started a child process pass the signal on to it...
2117 kill(child_pid
, sig
);
2118 while (waitpid(child_pid
, &status
, 0) < 0 && errno
== EINTR
);
2120 if (WIFEXITED(status
))
2121 exit(WEXITSTATUS(status
));
2122 else if (status
== SIGTERM
|| status
== SIGKILL
)
2126 fprintf(stderr
, "DEBUG: Child crashed on signal %d\n", status
);
2127 exit(CUPS_BACKEND_STOP
);
2130 #endif /* __i386__ || __x86_64__ */
2134 #ifdef PARSE_PS_ERRORS
2136 * 'next_line()' - Find the next line in a buffer.
2139 static const char *next_line (const char *buffer
)
2141 const char *cptr
, *lptr
= NULL
;
2143 for (cptr
= buffer
; *cptr
&& lptr
== NULL
; cptr
++)
2144 if (*cptr
== '\n' || *cptr
== '\r')
2151 * 'parse_pserror()' - Scan the backchannel data for postscript errors.
2154 static void parse_pserror(char *sockBuffer
,
2157 static char gErrorBuffer
[1024] = "";
2158 static char *gErrorBufferPtr
= gErrorBuffer
;
2159 static char *gErrorBufferEndPtr
= gErrorBuffer
+ sizeof(gErrorBuffer
);
2161 char *pCommentBegin
, *pCommentEnd
, *pLineEnd
;
2166 if (gErrorBufferPtr
+ len
> gErrorBufferEndPtr
- 1)
2167 gErrorBufferPtr
= gErrorBuffer
;
2168 if (len
> sizeof(gErrorBuffer
) - 1)
2169 len
= sizeof(gErrorBuffer
) - 1;
2171 memcpy(gErrorBufferPtr
, (const void *)sockBuffer
, len
);
2172 gErrorBufferPtr
+= len
;
2173 *(gErrorBufferPtr
+ 1) = '\0';
2175 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
2176 while (pLineEnd
!= NULL
)
2180 pCommentBegin
= strstr(gErrorBuffer
,"%%[");
2181 pCommentEnd
= strstr(gErrorBuffer
, "]%%");
2182 if (pCommentBegin
!= gErrorBuffer
&& pCommentEnd
!= NULL
)
2184 pCommentEnd
+= 3; /* Skip past "]%%" */
2185 *pCommentEnd
= '\0'; /* There's always room for the nul */
2187 if (strncasecmp(pCommentBegin
, "%%[ Error:", 10) == 0)
2189 else if (strncasecmp(pCommentBegin
, "%%[ Flushing", 12) == 0)
2194 if ((logstrlen
= snprintf(logstr
, sizeof(logstr
), "%s: %s\n", logLevel
, pCommentBegin
)) >= sizeof(logstr
))
2196 /* If the string was trucnated make sure it has a linefeed before the nul */
2197 logstrlen
= sizeof(logstr
) - 1;
2198 logstr
[logstrlen
- 1] = '\n';
2200 write(STDERR_FILENO
, logstr
, logstrlen
);
2203 /* move everything over... */
2204 strcpy(gErrorBuffer
, pLineEnd
);
2205 gErrorBufferPtr
= gErrorBuffer
;
2206 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
2209 #endif /* PARSE_PS_ERRORS */
2213 * 'soft_reset()' - Send a soft reset to the device.
2216 static void soft_reset()
2218 fd_set input_set
; /* Input set for select() */
2219 struct timeval tv
; /* Time value */
2220 char buffer
[2048]; /* Buffer */
2221 struct timespec cond_timeout
; /* pthread condition timeout */
2224 * Send an abort once a second until the I/O lock is released by the main thread...
2227 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2228 while (g
.readwrite_lock
)
2230 (*g
.classdriver
)->Abort(g
.classdriver
);
2232 gettimeofday(&tv
, NULL
);
2233 cond_timeout
.tv_sec
= tv
.tv_sec
+ 1;
2234 cond_timeout
.tv_nsec
= tv
.tv_usec
* 1000;
2236 while (g
.readwrite_lock
)
2238 if (pthread_cond_timedwait(&g
.readwrite_lock_cond
,
2239 &g
.readwrite_lock_mutex
,
2240 &cond_timeout
) != 0)
2245 g
.readwrite_lock
= 1;
2246 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2249 * Flush bytes waiting on print_fd...
2254 FD_ZERO(&input_set
);
2255 FD_SET(g
.print_fd
, &input_set
);
2260 while (select(g
.print_fd
+1, &input_set
, NULL
, NULL
, &tv
) > 0)
2261 if (read(g
.print_fd
, buffer
, sizeof(buffer
)) <= 0)
2268 (*g
.classdriver
)->SoftReset(g
.classdriver
, DEFAULT_TIMEOUT
);
2271 * Release the I/O lock...
2274 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2275 g
.readwrite_lock
= 0;
2276 pthread_cond_signal(&g
.readwrite_lock_cond
);
2277 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2282 * 'get_device_id()' - Return IEEE-1284 device ID.
2285 static void get_device_id(cups_sc_status_t
*status
,
2289 CFStringRef deviceIDString
= NULL
;
2292 copy_deviceid(g
.classdriver
, &deviceIDString
);
2296 CFStringGetCString(deviceIDString
, data
, *datalen
, kCFStringEncodingUTF8
);
2297 *datalen
= strlen(data
);
2298 CFRelease(deviceIDString
);
2300 *status
= CUPS_SC_STATUS_OK
;
2305 * End of "$Id: usb-darwin.c 7953 2008-09-17 01:43:19Z mike $".