2 * "$Id: usb-darwin.c 7953 2008-09-17 01:43:19Z mike $"
4 * Copyright 2005-2009 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.h>
93 #include <cups/sidechannel.h>
94 #include <cups/i18n.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 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error\n"));
379 fputs("DEBUG: USB make string is NULL\n", stderr
);
381 fputs("DEBUG: USB model string is NULL\n", stderr
);
383 return (CUPS_BACKEND_STOP
);
386 fputs("STATE: +connecting-to-device\n", stderr
);
388 countdown
= INITIAL_LOG_INTERVAL
;
394 IOObjectRelease(g
.printer_obj
);
395 unload_classdriver(&g
.classdriver
);
400 fprintf(stderr
, "DEBUG: Looking for '%s %s'\n", hostname
, resource
);
402 iterate_printers(find_device_cb
, NULL
);
404 fputs("DEBUG: Opening connection\n", stderr
);
406 driverBundlePath
= NULL
;
408 status
= registry_open(&driverBundlePath
);
410 #if defined(__i386__) || defined(__x86_64__)
412 * If we were unable to load the class drivers for this printer it's
413 * probably because they're ppc or i386. In this case try to run this
414 * backend as i386 or ppc executables so we can use them...
418 run_legacy_backend(argc
, argv
, print_fd
);
419 /* Never returns here */
421 #endif /* __i386__ || __x86_64__ */
426 * If we still were unable to load the class drivers for this printer log
427 * the error and stop the queue...
430 if (driverBundlePath
== NULL
|| !CFStringGetCString(driverBundlePath
, print_buffer
, sizeof(print_buffer
), kCFStringEncodingUTF8
))
431 strlcpy(print_buffer
, "USB class driver", sizeof(print_buffer
));
433 fputs("STATE: +apple-missing-usbclassdriver-error\n", stderr
);
434 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error\n"));
435 fprintf(stderr
, "DEBUG: Could not load %s\n", print_buffer
);
437 if (driverBundlePath
)
438 CFRelease(driverBundlePath
);
440 return (CUPS_BACKEND_STOP
);
443 if (driverBundlePath
)
444 CFRelease(driverBundlePath
);
448 sleep(PRINTER_POLLING_INTERVAL
);
449 countdown
-= PRINTER_POLLING_INTERVAL
;
452 _cupsLangPuts(stderr
,
453 _("INFO: Waiting for printer to become available...\n"));
454 fprintf(stderr
, "DEBUG: USB printer status: 0x%08x\n", (int)status
);
455 countdown
= SUBSEQUENT_LOG_INTERVAL
; /* subsequent log entries, every 15 seconds */
458 } while (status
!= noErr
);
460 fputs("STATE: -connecting-to-device\n", stderr
);
463 * Now that we are "connected" to the port, ignore SIGTERM so that we
464 * can finish out any page data the driver sends (e.g. to eject the
465 * current page... Only ignore SIGTERM if we are printing data from
466 * stdin (otherwise you can't cancel raw jobs...)
471 struct sigaction action
; /* POSIX signal action */
474 memset(&action
, 0, sizeof(action
));
476 sigemptyset(&action
.sa_mask
);
477 action
.sa_handler
= SIG_IGN
;
478 sigaction(SIGTERM
, &action
, NULL
);
482 * Start the side channel thread if the descriptor is valid...
485 pthread_mutex_init(&g
.readwrite_lock_mutex
, NULL
);
486 pthread_cond_init(&g
.readwrite_lock_cond
, NULL
);
487 g
.readwrite_lock
= 1;
489 if (have_sidechannel
)
491 g
.sidechannel_thread_stop
= 0;
492 g
.sidechannel_thread_done
= 0;
494 pthread_cond_init(&g
.sidechannel_thread_cond
, NULL
);
495 pthread_mutex_init(&g
.sidechannel_thread_mutex
, NULL
);
497 if (pthread_create(&sidechannel_thread_id
, NULL
, sidechannel_thread
, NULL
))
499 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error\n"));
500 fputs("DEBUG: Couldn't create side-channel thread\n", stderr
);
502 return (CUPS_BACKEND_STOP
);
507 * Get the read thread going...
510 g
.read_thread_stop
= 0;
511 g
.read_thread_done
= 0;
513 pthread_cond_init(&g
.read_thread_cond
, NULL
);
514 pthread_mutex_init(&g
.read_thread_mutex
, NULL
);
516 if (pthread_create(&read_thread_id
, NULL
, read_thread
, NULL
))
518 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error\n"));
519 fputs("DEBUG: Couldn't create read thread\n", stderr
);
521 return (CUPS_BACKEND_STOP
);
525 * The main thread sends the print file...
531 print_ptr
= print_buffer
;
533 while (status
== noErr
&& copies
-- > 0)
535 _cupsLangPuts(stderr
, _("INFO: Sending print data...\n"));
537 if (print_fd
!= STDIN_FILENO
)
539 fputs("PAGE: 1 1\n", stderr
);
540 lseek(print_fd
, 0, SEEK_SET
);
543 while (status
== noErr
)
548 FD_SET(print_fd
, &input_set
);
551 * Calculate select timeout...
552 * If we have data waiting to send timeout is 100ms.
553 * else if we're draining print_fd timeout is 0.
554 * else we're waiting forever...
560 stimeout
.tv_usec
= 100000; /* 100ms */
563 else if (g
.drain_output
)
566 stimeout
.tv_usec
= 0;
573 * I/O is unlocked around select...
576 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
577 g
.readwrite_lock
= 0;
578 pthread_cond_signal(&g
.readwrite_lock_cond
);
579 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
581 nfds
= select(print_fd
+ 1, &input_set
, NULL
, NULL
, timeout
);
584 * Reacquire the lock...
587 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
588 while (g
.readwrite_lock
)
589 pthread_cond_wait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
);
590 g
.readwrite_lock
= 1;
591 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
595 if (errno
== EINTR
&& total_bytes
== 0)
597 fputs("DEBUG: Received an interrupt before any bytes were "
598 "written, aborting\n", stderr
);
600 return (CUPS_BACKEND_OK
);
602 else if (errno
!= EAGAIN
&& errno
!= EINTR
)
604 _cupsLangPuts(stderr
, _("ERROR: Unable to read print data\n"));
605 perror("DEBUG: select");
607 return (CUPS_BACKEND_FAILED
);
612 * If drain output has finished send a response...
615 if (g
.drain_output
&& !nfds
&& !g
.print_bytes
)
617 /* Send a response... */
618 cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
623 * Check if we have print data ready...
626 if (FD_ISSET(print_fd
, &input_set
))
629 g
.debug_bytes
+= 512;
630 if (g
.debug_bytes
> sizeof(print_buffer
))
633 g
.print_bytes
= read(print_fd
, print_buffer
, g
.debug_bytes
);
636 g
.print_bytes
= read(print_fd
, print_buffer
, sizeof(print_buffer
));
637 #endif /* DEBUG_WRITES */
639 if (g
.print_bytes
< 0)
642 * Read error - bail if we don't see EAGAIN or EINTR...
645 if (errno
!= EAGAIN
&& errno
!= EINTR
)
647 _cupsLangPuts(stderr
, _("ERROR: Unable to read print data\n"));
648 perror("DEBUG: read");
650 return (CUPS_BACKEND_FAILED
);
655 else if (g
.print_bytes
== 0)
658 * End of file, break out of the loop...
664 print_ptr
= print_buffer
;
666 fprintf(stderr
, "DEBUG: Read %d bytes of print data...\n",
672 bytes
= g
.print_bytes
;
673 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
676 * Ignore timeout errors, but retain the number of bytes written to
677 * avoid sending duplicate data (<rdar://problem/6254911>)...
680 if (iostatus
== kIOUSBTransactionTimeout
)
682 fputs("DEBUG: Got USB transaction timeout during write\n", stderr
);
687 * If we've stalled, retry the write...
690 else if (iostatus
== kIOUSBPipeStalled
)
692 fputs("DEBUG: Got USB pipe stalled during write\n", stderr
);
694 bytes
= g
.print_bytes
;
695 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
699 * Retry a write after an aborted write since we probably just got
700 * SIGTERM (<rdar://problem/6860126>)...
703 else if (iostatus
== kIOReturnAborted
)
705 fputs("DEBUG: Got USB return aborted during write\n", stderr
);
707 IOReturn err
= (*g
.classdriver
)->Abort(g
.classdriver
);
708 fprintf(stderr
, "DEBUG: USB class driver Abort returned %x\n", err
);
712 #endif /* DEBUG_WRITES */
714 bytes
= g
.print_bytes
;
715 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
718 if (iostatus
|| bytes
< 0)
721 * Write error - bail if we don't see an error we can retry...
724 _cupsLangPuts(stderr
, _("ERROR: Unable to send print data\n"));
725 fprintf(stderr
, "DEBUG: USB class driver WritePipe returned %x\n",
728 IOReturn err
= (*g
.classdriver
)->Abort(g
.classdriver
);
729 fprintf(stderr
, "DEBUG: USB class driver Abort returned %x\n",
732 status
= CUPS_BACKEND_FAILED
;
737 fprintf(stderr
, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes
);
739 g
.print_bytes
-= bytes
;
741 total_bytes
+= bytes
;
745 if (print_fd
!= 0 && status
== noErr
)
746 fprintf(stderr
, "DEBUG: Sending print file, %lld bytes...\n",
751 fprintf(stderr
, "DEBUG: Sent %lld bytes...\n", (off_t
)total_bytes
);
754 * Wait for the side channel thread to exit...
757 if (have_sidechannel
)
760 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
761 g
.readwrite_lock
= 0;
762 pthread_cond_signal(&g
.readwrite_lock_cond
);
763 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
765 g
.sidechannel_thread_stop
= 1;
766 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
767 if (!g
.sidechannel_thread_done
)
770 * Wait for the side-channel thread to exit...
773 cond_timeout
.tv_sec
= time(NULL
) + WAIT_SIDE_DELAY
;
774 cond_timeout
.tv_nsec
= 0;
775 if (pthread_cond_timedwait(&g
.sidechannel_thread_cond
,
776 &g
.sidechannel_thread_mutex
,
780 * Force the side-channel thread to exit...
783 pthread_kill(sidechannel_thread_id
, SIGTERM
);
786 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
788 pthread_join(sidechannel_thread_id
, NULL
);
790 pthread_cond_destroy(&g
.sidechannel_thread_cond
);
791 pthread_mutex_destroy(&g
.sidechannel_thread_mutex
);
794 pthread_cond_destroy(&g
.readwrite_lock_cond
);
795 pthread_mutex_destroy(&g
.readwrite_lock_mutex
);
798 * Signal the read thread to stop...
801 g
.read_thread_stop
= 1;
804 * Give the read thread WAIT_EOF_DELAY seconds to complete all the data. If
805 * we are not signaled in that time then force the thread to exit.
808 pthread_mutex_lock(&g
.read_thread_mutex
);
810 if (!g
.read_thread_done
)
812 cond_timeout
.tv_sec
= time(NULL
) + WAIT_EOF_DELAY
;
813 cond_timeout
.tv_nsec
= 0;
815 if (pthread_cond_timedwait(&g
.read_thread_cond
, &g
.read_thread_mutex
,
819 * Force the read thread to exit...
823 pthread_kill(read_thread_id
, SIGTERM
);
826 pthread_mutex_unlock(&g
.read_thread_mutex
);
828 pthread_join(read_thread_id
, NULL
); /* wait for the read thread to return */
830 pthread_cond_destroy(&g
.read_thread_cond
);
831 pthread_mutex_destroy(&g
.read_thread_mutex
);
834 * Close the connection and input file and general clean up...
839 if (print_fd
!= STDIN_FILENO
)
848 if (g
.serial
!= NULL
)
851 if (g
.printer_obj
!= 0x0)
852 IOObjectRelease(g
.printer_obj
);
859 * 'read_thread()' - Thread to read the backchannel data on.
862 static void *read_thread(void *reference
)
864 UInt8 readbuffer
[512];
866 kern_return_t readstatus
;
867 struct mach_timebase_info timeBaseInfo
;
871 /* Calculate what 250 milliSeconds are in mach absolute time...
873 mach_timebase_info(&timeBaseInfo
);
874 delay
= ((uint64_t)250000000 * (uint64_t)timeBaseInfo
.denom
) / (uint64_t)timeBaseInfo
.numer
;
879 * Remember when we started so we can throttle the loop after the read call...
882 start
= mach_absolute_time();
884 rbytes
= sizeof(readbuffer
);
885 readstatus
= (*g
.classdriver
)->ReadPipe(g
.classdriver
, readbuffer
, &rbytes
);
886 if (readstatus
== kIOReturnSuccess
&& rbytes
> 0)
888 fprintf(stderr
, "DEBUG: Read %d bytes of back-channel data...\n",
890 cupsBackChannelWrite((char*)readbuffer
, rbytes
, 1.0);
892 /* cntrl-d is echoed by the printer.
894 * Xerox Phaser 6250D doesn't echo the cntrl-d.
895 * Xerox Phaser 6250D doesn't always send the product query.
897 if (g
.wait_eof
&& readbuffer
[rbytes
-1] == 0x4)
900 #ifdef PARSE_PS_ERRORS
901 parse_pserror(readbuffer
, rbytes
);
904 else if (readstatus
== kIOUSBTransactionTimeout
)
905 fputs("DEBUG: Got USB transaction timeout during read\n", stderr
);
906 else if (readstatus
== kIOUSBPipeStalled
)
907 fputs("DEBUG: Got USB pipe stalled during read\n", stderr
);
908 else if (readstatus
== kIOReturnAborted
)
909 fputs("DEBUG: Got USB return aborted during read\n", stderr
);
912 * Make sure this loop executes no more than once every 250 miliseconds...
915 if ((readstatus
!= kIOReturnSuccess
|| rbytes
== 0) && (g
.wait_eof
|| !g
.read_thread_stop
))
916 mach_wait_until(start
+ delay
);
918 } while (g
.wait_eof
|| !g
.read_thread_stop
); /* Abort from main thread tests error here */
921 * Let the main thread know that we have completed the read thread...
924 pthread_mutex_lock(&g
.read_thread_mutex
);
925 g
.read_thread_done
= 1;
926 pthread_cond_signal(&g
.read_thread_cond
);
927 pthread_mutex_unlock(&g
.read_thread_mutex
);
934 * 'sidechannel_thread()' - Handle side-channel requests.
938 sidechannel_thread(void *reference
)
940 cups_sc_command_t command
; /* Request command */
941 cups_sc_status_t status
; /* Request/response status */
942 char data
[2048]; /* Request/response data */
943 int datalen
; /* Request/response data size */
948 datalen
= sizeof(data
);
950 if (cupsSideChannelRead(&command
, &status
, data
, &datalen
, 1.0))
952 if (status
== CUPS_SC_STATUS_TIMEOUT
)
960 case CUPS_SC_CMD_SOFT_RESET
: /* Do a soft reset */
961 fputs("DEBUG: CUPS_SC_CMD_SOFT_RESET received from driver...\n",
964 if ((*g
.classdriver
)->SoftReset
!= NULL
)
967 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
968 fputs("DEBUG: Returning status CUPS_STATUS_OK with no bytes...\n",
973 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
975 fputs("DEBUG: Returning status CUPS_STATUS_NOT_IMPLEMENTED with "
976 "no bytes...\n", stderr
);
980 case CUPS_SC_CMD_DRAIN_OUTPUT
: /* Drain all pending output */
981 fputs("DEBUG: CUPS_SC_CMD_DRAIN_OUTPUT received from driver...\n",
987 case CUPS_SC_CMD_GET_BIDI
: /* Is the connection bidirectional? */
988 fputs("DEBUG: CUPS_SC_CMD_GET_BIDI received from driver...\n",
991 data
[0] = g
.bidi_flag
;
992 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
995 "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
999 case CUPS_SC_CMD_GET_DEVICE_ID
: /* Return IEEE-1284 device ID */
1000 fputs("DEBUG: CUPS_SC_CMD_GET_DEVICE_ID received from driver...\n",
1003 datalen
= sizeof(data
);
1004 get_device_id(&status
, data
, &datalen
);
1005 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, datalen
, 1.0);
1007 if (datalen
< sizeof(data
))
1008 data
[datalen
] = '\0';
1010 data
[sizeof(data
) - 1] = '\0';
1013 "DEBUG: Returning CUPS_SC_STATUS_OK with %d bytes (%s)...\n",
1017 case CUPS_SC_CMD_GET_STATE
: /* Return device state */
1018 fputs("DEBUG: CUPS_SC_CMD_GET_STATE received from driver...\n",
1021 data
[0] = CUPS_SC_STATE_ONLINE
;
1022 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
1025 "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
1030 fprintf(stderr
, "DEBUG: Unknown side-channel command (%d) received "
1031 "from driver...\n", command
);
1033 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
1036 fputs("DEBUG: Returned CUPS_SC_STATUS_NOT_IMPLEMENTED with no bytes...\n",
1041 while (!g
.sidechannel_thread_stop
);
1043 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
1044 g
.sidechannel_thread_done
= 1;
1045 pthread_cond_signal(&g
.sidechannel_thread_cond
);
1046 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
1054 * 'iterate_printers()' - Iterate over all the printers.
1057 static void iterate_printers(iterator_callback_t callBack
,
1060 mach_port_t masterPort
= 0x0;
1061 kern_return_t kr
= IOMasterPort (bootstrap_port
, &masterPort
);
1063 if (kr
== kIOReturnSuccess
&& masterPort
!= 0x0)
1065 io_iterator_t addIterator
= 0x0;
1067 iterator_reference_t reference
= { callBack
, userdata
, true };
1068 IONotificationPortRef addNotification
= IONotificationPortCreate(masterPort
);
1070 int klass
= kUSBPrintingClass
;
1071 int subklass
= kUSBPrintingSubclass
;
1073 CFNumberRef usb_klass
= CFNumberCreate(NULL
, kCFNumberIntType
, &klass
);
1074 CFNumberRef usb_subklass
= CFNumberCreate(NULL
, kCFNumberIntType
, &subklass
);
1075 CFMutableDictionaryRef usbPrinterMatchDictionary
= IOServiceMatching(kIOUSBInterfaceClassName
);
1077 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceClass"), usb_klass
);
1078 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceSubClass"), usb_subklass
);
1080 CFRelease(usb_klass
);
1081 CFRelease(usb_subklass
);
1083 kr
= IOServiceAddMatchingNotification(addNotification
, kIOMatchedNotification
, usbPrinterMatchDictionary
, &device_added
, &reference
, &addIterator
);
1084 if (addIterator
!= 0x0)
1086 device_added (&reference
, addIterator
);
1088 if (reference
.keepRunning
)
1090 CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification
), kCFRunLoopDefaultMode
);
1093 IOObjectRelease(addIterator
);
1095 mach_port_deallocate(mach_task_self(), masterPort
);
1101 * 'device_added()' - Device added notifier.
1104 static void device_added(void *userdata
,
1105 io_iterator_t iterator
)
1107 iterator_reference_t
*reference
= userdata
;
1110 while (reference
->keepRunning
&& (obj
= IOIteratorNext(iterator
)) != 0x0)
1112 if (reference
->callback
!= NULL
)
1113 reference
->keepRunning
= reference
->callback(reference
->userdata
, obj
);
1115 IOObjectRelease(obj
);
1118 /* One last call to the call back now that we are not longer have printers left to iterate...
1120 if (reference
->keepRunning
)
1121 reference
->keepRunning
= reference
->callback(reference
->userdata
, 0x0);
1123 if (!reference
->keepRunning
)
1124 CFRunLoopStop(CFRunLoopGetCurrent());
1129 * 'list_device_cb()' - list_device iterator callback.
1132 static Boolean
list_device_cb(void *refcon
,
1135 Boolean keepRunning
= (obj
!= 0x0);
1139 CFStringRef deviceIDString
= NULL
;
1140 UInt32 deviceLocation
= 0;
1141 UInt8 interfaceNum
= 0;
1143 copy_devicestring(obj
, &deviceIDString
, &deviceLocation
, &interfaceNum
);
1144 if (deviceIDString
!= NULL
)
1146 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1147 char uristr
[1024], makestr
[1024], modelstr
[1024], serialstr
[1024];
1148 char optionsstr
[1024], idstr
[1024], make_modelstr
[1024];
1150 copy_deviceinfo(deviceIDString
, &make
, &model
, &serial
);
1151 CFStringGetCString(deviceIDString
, idstr
, sizeof(idstr
),
1152 kCFStringEncodingUTF8
);
1153 backendGetMakeModel(idstr
, make_modelstr
, sizeof(make_modelstr
));
1158 !CFStringGetCString(make
, makestr
, sizeof(makestr
),
1159 kCFStringEncodingUTF8
))
1160 strcpy(makestr
, "Unknown");
1163 !CFStringGetCString(model
, &modelstr
[1], sizeof(modelstr
)-1,
1164 kCFStringEncodingUTF8
))
1165 strcpy(modelstr
+ 1, "Printer");
1167 optionsstr
[0] = '\0';
1170 CFStringGetCString(serial
, serialstr
, sizeof(serialstr
), kCFStringEncodingUTF8
);
1171 snprintf(optionsstr
, sizeof(optionsstr
), "?serial=%s", serialstr
);
1173 else if (deviceLocation
!= 0)
1174 snprintf(optionsstr
, sizeof(optionsstr
), "?location=%x", (unsigned)deviceLocation
);
1176 httpAssembleURI(HTTP_URI_CODING_ALL
, uristr
, sizeof(uristr
), "usb", NULL
, makestr
, 0, modelstr
);
1177 strlcat(uristr
, optionsstr
, sizeof(uristr
));
1179 cupsBackendReport("direct", uristr
, make_modelstr
, make_modelstr
, idstr
,
1182 release_deviceinfo(&make
, &model
, &serial
);
1183 CFRelease(deviceIDString
);
1192 * 'find_device_cb()' - print_device iterator callback.
1195 static Boolean
find_device_cb(void *refcon
,
1198 Boolean keepLooking
= true;
1202 CFStringRef idString
= NULL
;
1203 UInt32 location
= -1;
1204 UInt8 interfaceNum
= 0;
1206 copy_devicestring(obj
, &idString
, &location
, &interfaceNum
);
1207 if (idString
!= NULL
)
1209 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1211 copy_deviceinfo(idString
, &make
, &model
, &serial
);
1212 if (make
&& CFStringCompare(make
, g
.make
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1214 if (model
&& CFStringCompare(model
, g
.model
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1216 if (g
.serial
!= NULL
&& CFStringGetLength(g
.serial
) > 0)
1218 if (serial
!= NULL
&& CFStringCompare(serial
, g
.serial
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1220 IOObjectRetain(obj
);
1221 g
.printer_obj
= obj
;
1222 keepLooking
= false;
1227 if (g
.printer_obj
!= 0)
1228 IOObjectRelease(g
.printer_obj
);
1230 g
.printer_obj
= obj
;
1231 IOObjectRetain(obj
);
1233 if (g
.location
== 0 || g
.location
== location
)
1234 keepLooking
= false;
1237 g
.interfaceNum
= interfaceNum
;
1241 release_deviceinfo(&make
, &model
, &serial
);
1242 CFRelease(idString
);
1247 keepLooking
= (g
.printer_obj
== 0);
1248 if (obj
== 0x0 && keepLooking
)
1250 CFRunLoopTimerContext context
= { 0, refcon
, NULL
, NULL
, NULL
};
1251 CFRunLoopTimerRef timer
= CFRunLoopTimerCreate(NULL
, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb
, &context
);
1254 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer
, kCFRunLoopDefaultMode
);
1255 g
.status_timer
= timer
;
1260 if (!keepLooking
&& g
.status_timer
!= NULL
)
1262 fputs("STATE: -offline-report\n", stderr
);
1263 _cupsLangPuts(stderr
, _("INFO: Printer is now online.\n"));
1264 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g
.status_timer
, kCFRunLoopDefaultMode
);
1265 CFRelease(g
.status_timer
);
1266 g
.status_timer
= NULL
;
1274 * 'status_timer_cb()' - Status timer callback.
1277 static void status_timer_cb(CFRunLoopTimerRef timer
,
1280 fputs("STATE: +offline-report\n", stderr
);
1281 _cupsLangPuts(stderr
, _("INFO: Printer is offline.\n"));
1283 if (getenv("CLASS") != NULL
)
1286 * If the CLASS environment variable is set, the job was submitted
1287 * to a class and not to a specific queue. In this case, we want
1288 * to abort immediately so that the job can be requeued on the next
1289 * available printer in the class.
1291 * Sleep 5 seconds to keep the job from requeuing too rapidly...
1296 exit(CUPS_BACKEND_FAILED
);
1303 * 'copy_deviceinfo()' - Copy strings from the 1284 device ID.
1306 static void copy_deviceinfo(CFStringRef deviceIDString
,
1309 CFStringRef
*serial
)
1311 CFStringRef modelKeys
[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL
};
1312 CFStringRef makeKeys
[] = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL
};
1313 CFStringRef serialKeys
[] = { CFSTR("SN:"), CFSTR("SERN:"), NULL
};
1316 *make
= copy_value_for_key(deviceIDString
, makeKeys
);
1319 *model
= copy_value_for_key(deviceIDString
, modelKeys
);
1322 *serial
= copy_value_for_key(deviceIDString
, serialKeys
);
1327 * 'release_deviceinfo()' - Release deviceinfo strings.
1330 static void release_deviceinfo(CFStringRef
*make
,
1332 CFStringRef
*serial
)
1334 if (make
!= NULL
&& *make
!= NULL
)
1340 if (model
!= NULL
&& *model
!= NULL
)
1346 if (serial
!= NULL
&& *serial
!= NULL
)
1356 * 'load_classdriver()' - Load a classdriver.
1359 static kern_return_t
load_classdriver(CFStringRef driverPath
,
1360 printer_interface_t intf
,
1361 classdriver_t
***printerDriver
)
1363 kern_return_t kr
= kUSBPrinterClassDeviceNotOpen
;
1364 classdriver_t
**driver
= NULL
;
1365 CFStringRef bundle
= driverPath
? driverPath
: kUSBGenericTOPrinterClassDriver
;
1366 char bundlestr
[1024]; /* Bundle path */
1367 struct stat bundleinfo
; /* File information for bundle */
1368 CFURLRef url
; /* URL for driver */
1369 CFPlugInRef plugin
= NULL
; /* Plug-in address */
1372 CFStringGetCString(bundle
, bundlestr
, sizeof(bundlestr
), kCFStringEncodingUTF8
);
1375 * Validate permissions for the class driver...
1378 if (stat(bundlestr
, &bundleinfo
))
1380 fprintf(stderr
, "DEBUG: Unable to load class driver \"%s\": %s\n",
1381 bundlestr
, strerror(errno
));
1384 else if (bundleinfo
.st_mode
& S_IWOTH
)
1386 fprintf(stderr
, "DEBUG: Unable to load class driver \"%s\": insecure file "
1387 "permissions (0%o)\n", bundlestr
, bundleinfo
.st_mode
);
1392 * Try loading the class driver...
1395 url
= CFURLCreateWithFileSystemPath(NULL
, bundle
, kCFURLPOSIXPathStyle
, true);
1399 plugin
= CFPlugInCreate(NULL
, url
);
1407 CFArrayRef factories
= CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID
, plugin
);
1408 if (factories
!= NULL
&& CFArrayGetCount(factories
) > 0)
1410 CFUUIDRef factoryID
= CFArrayGetValueAtIndex(factories
, 0);
1411 IUnknownVTbl
**iunknown
= CFPlugInInstanceCreate(NULL
, factoryID
, kUSBPrinterClassTypeID
);
1412 if (iunknown
!= NULL
)
1414 kr
= (*iunknown
)->QueryInterface(iunknown
, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID
), (LPVOID
*)&driver
);
1415 if (kr
== kIOReturnSuccess
&& driver
!= NULL
)
1417 classdriver_t
**genericDriver
= NULL
;
1418 if (driverPath
!= NULL
&& CFStringCompare(driverPath
, kUSBGenericTOPrinterClassDriver
, 0) != kCFCompareEqualTo
)
1419 kr
= load_classdriver(NULL
, intf
, &genericDriver
);
1421 if (kr
== kIOReturnSuccess
)
1423 (*driver
)->interface
= intf
;
1424 (*driver
)->Initialize(driver
, genericDriver
);
1426 (*driver
)->plugin
= plugin
;
1427 (*driver
)->interface
= intf
;
1428 *printerDriver
= driver
;
1431 (*iunknown
)->Release(iunknown
);
1433 CFRelease(factories
);
1437 fprintf(stderr
, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr
, (int)kr
);
1444 * 'unload_classdriver()' - Unload a classdriver.
1447 static kern_return_t
unload_classdriver(classdriver_t
***classdriver
)
1449 if (*classdriver
!= NULL
)
1451 (**classdriver
)->Release(*classdriver
);
1452 *classdriver
= NULL
;
1455 return kIOReturnSuccess
;
1460 * 'load_printerdriver()' - Load vendor's classdriver.
1462 * If driverBundlePath is not NULL on return it is the callers responsbility to release it!
1465 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
)
1467 IOCFPlugInInterface
**iodev
= NULL
;
1470 printer_interface_t intf
;
1473 kr
= IOCreatePlugInInterfaceForService(g
.printer_obj
, kIOUSBInterfaceUserClientTypeID
, kIOCFPlugInInterfaceID
, &iodev
, &score
);
1474 if (kr
== kIOReturnSuccess
)
1476 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*) &intf
)) == noErr
)
1478 *driverBundlePath
= IORegistryEntryCreateCFProperty(g
.printer_obj
, kUSBClassDriverProperty
, NULL
, kNilOptions
);
1480 kr
= load_classdriver(*driverBundlePath
, intf
, &g
.classdriver
);
1482 if (kr
!= kIOReturnSuccess
)
1483 (*intf
)->Release(intf
);
1485 IODestroyPlugInInterface(iodev
);
1492 * 'registry_open()' - Open a connection to the printer.
1495 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
)
1497 g
.bidi_flag
= 0; /* 0=unidirectional */
1499 kern_return_t kr
= load_printerdriver(driverBundlePath
);
1500 if (kr
!= kIOReturnSuccess
)
1503 if (g
.classdriver
!= NULL
)
1505 (*g
.classdriver
)->interfaceNumber
= g
.interfaceNum
;
1506 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolBidirectional
);
1507 if (kr
!= kIOReturnSuccess
|| (*g
.classdriver
)->interface
== NULL
)
1509 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolUnidirectional
);
1510 if (kr
== kIOReturnSuccess
)
1512 if ((*g
.classdriver
)->interface
== NULL
)
1514 (*g
.classdriver
)->Close(g
.classdriver
);
1520 g
.bidi_flag
= 1; /* 1=bidirectional */
1523 if (kr
!= kIOReturnSuccess
)
1524 unload_classdriver(&g
.classdriver
);
1531 * 'registry_close()' - Close the connection to the printer.
1534 static kern_return_t
registry_close()
1536 if (g
.classdriver
!= NULL
)
1537 (*g
.classdriver
)->Close(g
.classdriver
);
1539 unload_classdriver(&g
.classdriver
);
1540 return kIOReturnSuccess
;
1545 * 'copy_deviceid()' - Copy the 1284 device id string.
1548 static OSStatus
copy_deviceid(classdriver_t
**classdriver
,
1549 CFStringRef
*deviceID
)
1551 CFStringRef devID
= NULL
,
1555 deviceSerial
= NULL
;
1557 OSStatus err
= (*classdriver
)->GetDeviceID(classdriver
, &devID
, DEFAULT_TIMEOUT
);
1559 copy_deviceinfo(devID
, &deviceMake
, &deviceModel
, &deviceSerial
);
1561 if (deviceMake
== NULL
|| deviceModel
== NULL
|| deviceSerial
== NULL
)
1563 IOUSBDeviceDescriptor desc
;
1564 iodevice_request_t request
;
1566 request
.requestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
1567 request
.request
= kUSBRqGetDescriptor
;
1568 request
.value
= (kUSBDeviceDesc
<< 8) | 0;
1570 request
.length
= sizeof(desc
);
1571 request
.buffer
= &desc
;
1572 err
= (*classdriver
)->DeviceRequest(classdriver
, &request
, DEFAULT_TIMEOUT
);
1573 if (err
== kIOReturnSuccess
)
1575 CFMutableStringRef newDevID
= CFStringCreateMutable(NULL
, 0);
1577 if (deviceMake
== NULL
)
1579 CFStringRef data
= NULL
;
1580 err
= (*classdriver
)->GetString(classdriver
, desc
.iManufacturer
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1583 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MFG:%@;"), data
);
1588 if (deviceModel
== NULL
)
1590 CFStringRef data
= NULL
;
1591 err
= (*classdriver
)->GetString(classdriver
, desc
.iProduct
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1594 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MDL:%@;"), data
);
1599 if (deviceSerial
== NULL
&& desc
.iSerialNumber
!= 0)
1601 CFStringRef data
= NULL
;
1602 err
= (*classdriver
)->GetString(classdriver
, desc
.iSerialNumber
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1605 CFStringAppendFormat(newDevID
, NULL
, CFSTR("SERN:%@;"), data
);
1612 CFStringAppend(newDevID
, devID
);
1616 *deviceID
= newDevID
;
1623 release_deviceinfo(&deviceMake
, &deviceModel
, &deviceSerial
);
1630 * 'copy_devicestring()' - Copy the 1284 device id string.
1633 static void copy_devicestring(io_service_t usbInterface
,
1634 CFStringRef
*deviceID
,
1635 UInt32
*deviceLocation
,
1636 UInt8
*interfaceNumber
)
1638 IOCFPlugInInterface
**iodev
= NULL
;
1641 printer_interface_t intf
;
1643 classdriver_t
**klassDriver
= NULL
;
1644 CFStringRef driverBundlePath
;
1646 if ((kr
= IOCreatePlugInInterfaceForService(usbInterface
,
1647 kIOUSBInterfaceUserClientTypeID
,
1648 kIOCFPlugInInterfaceID
,
1649 &iodev
, &score
)) == kIOReturnSuccess
)
1651 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*)
1654 (*intf
)->GetLocationID(intf
, deviceLocation
);
1655 (*intf
)->GetInterfaceNumber(intf
, interfaceNumber
);
1657 driverBundlePath
= IORegistryEntryCreateCFProperty(usbInterface
,
1658 kUSBClassDriverProperty
,
1661 kr
= load_classdriver(driverBundlePath
, intf
, &klassDriver
);
1663 if (kr
!= kIOReturnSuccess
&& driverBundlePath
!= NULL
)
1664 kr
= load_classdriver(NULL
, intf
, &klassDriver
);
1666 if (kr
== kIOReturnSuccess
&& klassDriver
!= NULL
)
1667 kr
= copy_deviceid(klassDriver
, deviceID
);
1669 unload_classdriver(&klassDriver
);
1671 if (driverBundlePath
!= NULL
)
1672 CFRelease(driverBundlePath
);
1674 /* (*intf)->Release(intf); */
1676 IODestroyPlugInInterface(iodev
);
1683 * 'copy_value_for_key()' - Copy value string associated with a key.
1686 static CFStringRef
copy_value_for_key(CFStringRef deviceID
,
1689 CFStringRef value
= NULL
;
1690 CFArrayRef kvPairs
= deviceID
!= NULL
? CFStringCreateArrayBySeparatingStrings(NULL
, deviceID
, CFSTR(";")) : NULL
;
1691 CFIndex max
= kvPairs
!= NULL
? CFArrayGetCount(kvPairs
) : 0;
1694 while (idx
< max
&& value
== NULL
)
1696 CFStringRef kvpair
= CFArrayGetValueAtIndex(kvPairs
, idx
);
1698 while (keys
[idxx
] != NULL
&& value
== NULL
)
1700 CFRange range
= CFStringFind(kvpair
, keys
[idxx
], kCFCompareCaseInsensitive
);
1701 if (range
.length
!= -1)
1703 if (range
.location
!= 0)
1705 CFMutableStringRef theString
= CFStringCreateMutableCopy(NULL
, 0, kvpair
);
1706 CFStringTrimWhitespace(theString
);
1707 range
= CFStringFind(theString
, keys
[idxx
], kCFCompareCaseInsensitive
);
1708 if (range
.location
== 0)
1709 value
= CFStringCreateWithSubstring(NULL
, theString
, CFRangeMake(range
.length
, CFStringGetLength(theString
) - range
.length
));
1711 CFRelease(theString
);
1715 CFStringRef theString
= CFStringCreateWithSubstring(NULL
, kvpair
, CFRangeMake(range
.length
, CFStringGetLength(kvpair
) - range
.length
));
1716 CFMutableStringRef theString2
= CFStringCreateMutableCopy(NULL
, 0, theString
);
1717 CFRelease(theString
);
1719 CFStringTrimWhitespace(theString2
);
1728 if (kvPairs
!= NULL
)
1735 * 'cfstr_create_trim()' - Create CFString and trim whitespace characters.
1738 CFStringRef
cfstr_create_trim(const char *cstr
)
1741 CFMutableStringRef cfmutablestr
= NULL
;
1743 if ((cfstr
= CFStringCreateWithCString(NULL
, cstr
, kCFStringEncodingUTF8
)) != NULL
)
1745 if ((cfmutablestr
= CFStringCreateMutableCopy(NULL
, 1024, cfstr
)) != NULL
)
1746 CFStringTrimWhitespace(cfmutablestr
);
1750 return (CFStringRef
) cfmutablestr
;
1756 * 'parse_options()' - Parse URI options.
1759 static void parse_options(char *options
,
1765 char sep
, /* Separator character */
1766 *name
, /* Name of option */
1767 *value
; /* Value of option */
1786 while (*options
&& *options
!= '=' && *options
!= '+' && *options
!= '&')
1789 if ((sep
= *options
) != '\0')
1800 while (*options
&& *options
!= '+' && *options
!= '&')
1810 * Process the option...
1813 if (!strcasecmp(name
, "waiteof"))
1815 if (!strcasecmp(value
, "on") ||
1816 !strcasecmp(value
, "yes") ||
1817 !strcasecmp(value
, "true"))
1819 else if (!strcasecmp(value
, "off") ||
1820 !strcasecmp(value
, "no") ||
1821 !strcasecmp(value
, "false"))
1824 _cupsLangPrintf(stderr
,
1825 _("WARNING: Boolean expected for waiteof option "
1826 "\"%s\"\n"), value
);
1828 else if (!strcasecmp(name
, "serial"))
1829 strlcpy(serial
, value
, serial_size
);
1830 else if (!strcasecmp(name
, "location") && location
)
1831 *location
= strtol(value
, NULL
, 16);
1837 * @function setup_cfLanguage
1838 * @abstract Convert the contents of the CUPS 'APPLE_LANGUAGE' environment
1839 * variable into a one element CF array of languages.
1841 * @discussion Each submitted job comes with a natural language. CUPS passes
1842 * that language in an environment variable. We take that language
1843 * and jam it into the AppleLanguages array so that CF will use
1844 * it when reading localized resources. We need to do this before
1845 * any CF code reads and caches the languages array, so this function
1846 * should be called early in main()
1848 static void setup_cfLanguage(void)
1850 CFStringRef lang
[1] = {NULL
};
1851 CFArrayRef langArray
= NULL
;
1852 const char *requestedLang
= NULL
;
1854 if ((requestedLang
= getenv("APPLE_LANGUAGE")) == NULL
)
1855 requestedLang
= getenv("LANG");
1857 if (requestedLang
!= NULL
)
1859 lang
[0] = CFStringCreateWithCString(kCFAllocatorDefault
, requestedLang
, kCFStringEncodingUTF8
);
1860 langArray
= CFArrayCreate(kCFAllocatorDefault
, (const void **)lang
, sizeof(lang
) / sizeof(lang
[0]), &kCFTypeArrayCallBacks
);
1862 CFPreferencesSetValue(CFSTR("AppleLanguages"), langArray
, kCFPreferencesCurrentApplication
, kCFPreferencesAnyUser
, kCFPreferencesAnyHost
);
1863 fprintf(stderr
, "DEBUG: usb: AppleLanguages=\"%s\"\n", requestedLang
);
1866 CFRelease(langArray
);
1869 fputs("DEBUG: usb: LANG and APPLE_LANGUAGE environment variables missing.\n", stderr
);
1873 #if defined(__i386__) || defined(__x86_64__)
1875 * @function run_legacy_backend
1877 * @abstract Starts child backend process running as a ppc or i386 executable.
1879 * @result Never returns; always calls exit().
1883 static void run_legacy_backend(int argc
,
1890 pid_t waitpid_status
;
1892 char *usb_legacy_status
;
1895 * If we're running as x86_64 or i386 and couldn't load the class driver
1896 * (because it's ppc or i386), then try to re-exec ourselves in ppc or i386
1897 * mode to try again. If we don't have a ppc or i386 architecture we may be
1898 * running with the same architecture again so guard against this by setting
1899 * and testing an environment variable...
1903 usb_legacy_status
= getenv("USB_I386_STATUS");
1905 usb_legacy_status
= getenv("USB_PPC_STATUS");
1906 # endif /* __x86_64__ */
1908 if (!usb_legacy_status
)
1911 * Setup a SIGTERM handler then block it before forking...
1914 int err
; /* posix_spawn result */
1915 struct sigaction action
; /* POSIX signal action */
1916 sigset_t newmask
, /* New signal mask */
1917 oldmask
; /* Old signal mask */
1918 char usbpath
[1024]; /* Path to USB backend */
1919 const char *cups_serverbin
;/* Path to CUPS binaries */
1922 memset(&action
, 0, sizeof(action
));
1923 sigaddset(&action
.sa_mask
, SIGTERM
);
1924 action
.sa_handler
= sigterm_handler
;
1925 sigaction(SIGTERM
, &action
, NULL
);
1927 sigemptyset(&newmask
);
1928 sigaddset(&newmask
, SIGTERM
);
1929 sigprocmask(SIG_BLOCK
, &newmask
, &oldmask
);
1932 * Set the environment variable...
1936 setenv("USB_I386_STATUS", "1", false);
1938 setenv("USB_PPC_STATUS", "1", false);
1939 # endif /* __x86_64__ */
1942 * Tell the kernel to use the specified CPU architecture...
1946 cpu_type_t cpu
= CPU_TYPE_I386
;
1948 cpu_type_t cpu
= CPU_TYPE_POWERPC
;
1949 # endif /* __x86_64__ */
1951 posix_spawnattr_t attrs
;
1953 if (!posix_spawnattr_init(&attrs
))
1955 posix_spawnattr_setsigdefault(&attrs
, &oldmask
);
1956 if (posix_spawnattr_setbinpref_np(&attrs
, 1, &cpu
, &ocount
) || ocount
!= 1)
1959 perror("DEBUG: Unable to set binary preference to i386");
1961 perror("DEBUG: Unable to set binary preference to ppc");
1962 # endif /* __x86_64__ */
1963 _cupsLangPrintf(stderr
, _("Unable to use legacy USB class driver\n"));
1964 exit(CUPS_BACKEND_STOP
);
1969 * Set up the arguments and call posix_spawn...
1972 if ((cups_serverbin
= getenv("CUPS_SERVERBIN")) == NULL
)
1973 cups_serverbin
= CUPS_SERVERBIN
;
1974 snprintf(usbpath
, sizeof(usbpath
), "%s/backend/usb", cups_serverbin
);
1976 for (i
= 0; i
< argc
&& i
< (sizeof(my_argv
) / sizeof(my_argv
[0])) - 1; i
++)
1977 my_argv
[i
] = argv
[i
];
1981 if ((err
= posix_spawn(&child_pid
, usbpath
, NULL
, &attrs
, my_argv
,
1984 fprintf(stderr
, "DEBUG: Unable to exec %s: %s\n", usbpath
,
1986 _cupsLangPrintf(stderr
, _("Unable to use legacy USB class driver\n"));
1987 exit(CUPS_BACKEND_STOP
);
1991 * Unblock signals...
1994 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
1997 * Close the fds we won't be using then wait for the child backend to exit.
2003 fprintf(stderr
, "DEBUG: Started usb(legacy) backend (PID %d)\n",
2006 while ((waitpid_status
= waitpid(child_pid
, &childstatus
, 0)) == (pid_t
)-1 && errno
== EINTR
)
2009 if (WIFSIGNALED(childstatus
))
2011 exitstatus
= CUPS_BACKEND_STOP
;
2012 fprintf(stderr
, "DEBUG: usb(legacy) backend %d crashed on signal %d\n",
2013 child_pid
, WTERMSIG(childstatus
));
2017 if ((exitstatus
= WEXITSTATUS(childstatus
)) != 0)
2019 "DEBUG: usb(legacy) backend %d stopped with status %d\n",
2020 child_pid
, exitstatus
);
2022 fprintf(stderr
, "DEBUG: usb(legacy) backend %d exited with no errors\n",
2028 fputs("DEBUG: usb(legacy) backend running native again\n", stderr
);
2029 exitstatus
= CUPS_BACKEND_STOP
;
2036 * 'sigterm_handler()' - SIGTERM handler.
2040 sigterm_handler(int sig
) /* I - Signal */
2042 /* If we started a child process pass the signal on to it...
2047 * If we started a child process pass the signal on to it...
2052 kill(child_pid
, sig
);
2053 while (waitpid(child_pid
, &status
, 0) < 0 && errno
== EINTR
);
2055 if (WIFEXITED(status
))
2056 exit(WEXITSTATUS(status
));
2057 else if (status
== SIGTERM
|| status
== SIGKILL
)
2061 fprintf(stderr
, "DEBUG: Child crashed on signal %d\n", status
);
2062 exit(CUPS_BACKEND_STOP
);
2067 #endif /* __i386__ || __x86_64__ */
2070 #ifdef PARSE_PS_ERRORS
2072 * 'next_line()' - Find the next line in a buffer.
2075 static const char *next_line (const char *buffer
)
2077 const char *cptr
, *lptr
= NULL
;
2079 for (cptr
= buffer
; *cptr
&& lptr
== NULL
; cptr
++)
2080 if (*cptr
== '\n' || *cptr
== '\r')
2087 * 'parse_pserror()' - Scan the backchannel data for postscript errors.
2090 static void parse_pserror(char *sockBuffer
,
2093 static char gErrorBuffer
[1024] = "";
2094 static char *gErrorBufferPtr
= gErrorBuffer
;
2095 static char *gErrorBufferEndPtr
= gErrorBuffer
+ sizeof(gErrorBuffer
);
2097 char *pCommentBegin
, *pCommentEnd
, *pLineEnd
;
2102 if (gErrorBufferPtr
+ len
> gErrorBufferEndPtr
- 1)
2103 gErrorBufferPtr
= gErrorBuffer
;
2104 if (len
> sizeof(gErrorBuffer
) - 1)
2105 len
= sizeof(gErrorBuffer
) - 1;
2107 memcpy(gErrorBufferPtr
, (const void *)sockBuffer
, len
);
2108 gErrorBufferPtr
+= len
;
2109 *(gErrorBufferPtr
+ 1) = '\0';
2111 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
2112 while (pLineEnd
!= NULL
)
2116 pCommentBegin
= strstr(gErrorBuffer
,"%%[");
2117 pCommentEnd
= strstr(gErrorBuffer
, "]%%");
2118 if (pCommentBegin
!= gErrorBuffer
&& pCommentEnd
!= NULL
)
2120 pCommentEnd
+= 3; /* Skip past "]%%" */
2121 *pCommentEnd
= '\0'; /* There's always room for the nul */
2123 if (strncasecmp(pCommentBegin
, "%%[ Error:", 10) == 0)
2125 else if (strncasecmp(pCommentBegin
, "%%[ Flushing", 12) == 0)
2130 if ((logstrlen
= snprintf(logstr
, sizeof(logstr
), "%s: %s\n", logLevel
, pCommentBegin
)) >= sizeof(logstr
))
2132 /* If the string was trucnated make sure it has a linefeed before the nul */
2133 logstrlen
= sizeof(logstr
) - 1;
2134 logstr
[logstrlen
- 1] = '\n';
2136 write(STDERR_FILENO
, logstr
, logstrlen
);
2139 /* move everything over... */
2140 strcpy(gErrorBuffer
, pLineEnd
);
2141 gErrorBufferPtr
= gErrorBuffer
;
2142 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
2145 #endif /* PARSE_PS_ERRORS */
2149 * 'soft_reset()' - Send a soft reset to the device.
2152 static void soft_reset()
2154 fd_set input_set
; /* Input set for select() */
2155 struct timeval stimeout
; /* Timeout for select() */
2156 char buffer
[2048]; /* Buffer */
2157 struct timespec cond_timeout
; /* pthread condition timeout */
2160 * Send an abort once a second until the I/O lock is released by the main thread...
2163 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2164 while (g
.readwrite_lock
)
2166 (*g
.classdriver
)->Abort(g
.classdriver
);
2168 cond_timeout
.tv_sec
= time(NULL
) + 1;
2169 cond_timeout
.tv_nsec
= 0;
2171 pthread_cond_timedwait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
, &cond_timeout
);
2174 g
.readwrite_lock
= 1;
2175 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2178 * Flush bytes waiting on print_fd...
2183 FD_ZERO(&input_set
);
2184 FD_SET(g
.print_fd
, &input_set
);
2186 stimeout
.tv_sec
= 0;
2187 stimeout
.tv_usec
= 0;
2189 while (select(g
.print_fd
+1, &input_set
, NULL
, NULL
, &stimeout
) > 0)
2190 if (read(g
.print_fd
, buffer
, sizeof(buffer
)) <= 0)
2197 (*g
.classdriver
)->SoftReset(g
.classdriver
, DEFAULT_TIMEOUT
);
2200 * Release the I/O lock...
2203 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2204 g
.readwrite_lock
= 0;
2205 pthread_cond_signal(&g
.readwrite_lock_cond
);
2206 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2211 * 'get_device_id()' - Return IEEE-1284 device ID.
2214 static void get_device_id(cups_sc_status_t
*status
,
2218 CFStringRef deviceIDString
= NULL
;
2221 copy_deviceid(g
.classdriver
, &deviceIDString
);
2225 CFStringGetCString(deviceIDString
, data
, *datalen
, kCFStringEncodingUTF8
);
2226 *datalen
= strlen(data
);
2227 CFRelease(deviceIDString
);
2229 *status
= CUPS_SC_STATUS_OK
;
2234 * End of "$Id: usb-darwin.c 7953 2008-09-17 01:43:19Z mike $".