2 * "$Id: usb-darwin.c 6993 2007-09-28 18:05:28Z mike $"
4 * Copyright 2005-2008 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_ppc_backend() - Re-exec i386 backend as ppc.
69 * sigterm_handler() - SIGTERM handler.
70 * next_line() - Find the next line in a buffer.
71 * parse_pserror() - Scan the backchannel data for postscript errors.
72 * get_device_id() - Return IEEE-1284 device ID.
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>
96 #include <CoreFoundation/CoreFoundation.h>
97 #include <IOKit/usb/IOUSBLib.h>
98 #include <IOKit/IOCFPlugIn.h>
104 * WAIT_EOF_DELAY is number of seconds we'll wait for responses from
105 * the printer after we've finished sending all the data
107 #define WAIT_EOF_DELAY 7
108 #define WAIT_SIDE_DELAY 3
109 #define DEFAULT_TIMEOUT 5000L
111 #define USB_INTERFACE_KIND CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID190)
112 #define kUSBLanguageEnglish 0x409
114 #define PRINTER_POLLING_INTERVAL 5 /* seconds */
115 #define INITIAL_LOG_INTERVAL PRINTER_POLLING_INTERVAL
116 #define SUBSEQUENT_LOG_INTERVAL 3 * INITIAL_LOG_INTERVAL
118 #define kUSBPrinterClassTypeID CFUUIDGetConstantUUIDWithBytes(NULL, 0x06, 0x04, 0x7D, 0x16, 0x53, 0xA2, 0x11, 0xD6, 0x92, 0x06, 0x00, 0x30, 0x65, 0x52, 0x45, 0x92)
119 #define kUSBPrinterClassInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, 0x03, 0x34, 0x6D, 0x74, 0x53, 0xA3, 0x11, 0xD6, 0x9E, 0xA1, 0x76, 0x30, 0x65, 0x52, 0x45, 0x92)
121 #define kUSBClassDriverProperty CFSTR("USB Printing Class")
123 #define kUSBGenericTOPrinterClassDriver CFSTR("/System/Library/Printers/Libraries/USBGenericTOPrintingClass.plugin")
124 #define kUSBPrinterClassDeviceNotOpen -9664 /*kPMInvalidIOMContext*/
128 * Section 5.3 USB Printing Class spec
130 #define kUSBPrintingSubclass 1
131 #define kUSBPrintingProtocolNoOpen 0
132 #define kUSBPrintingProtocolUnidirectional 1
133 #define kUSBPrintingProtocolBidirectional 2
135 typedef IOUSBInterfaceInterface190
**printer_interface_t
;
137 typedef struct iodevice_request_s
/**** Device request ****/
145 } iodevice_request_t
;
147 typedef union /**** Centronics status byte ****/
152 unsigned reserved0
:2;
153 unsigned paperError
:1;
156 unsigned reserved1
:3;
158 } centronics_status_t
;
160 typedef struct classdriver_s
/**** g.classdriver context ****/
163 CFPlugInRef plugin
; /* release plugin */
164 IUnknownVTbl
**factory
; /* Factory */
165 void *vendorReference
; /* vendor class specific usage */
166 UInt32 location
; /* unique location in bus topology */
167 UInt8 interfaceNumber
; /* Interface number */
168 UInt16 vendorID
; /* Vendor id */
169 UInt16 productID
; /* Product id */
170 printer_interface_t interface
; /* identify the device to IOKit */
171 UInt8 outpipe
; /* mandatory bulkOut pipe */
172 UInt8 inpipe
; /* optional bulkIn pipe */
174 /* general class requests */
175 kern_return_t (*DeviceRequest
)(struct classdriver_s
**printer
, iodevice_request_t
*iorequest
, UInt16 timeout
);
176 kern_return_t (*GetString
)(struct classdriver_s
**printer
, UInt8 whichString
, UInt16 language
, UInt16 timeout
, CFStringRef
*result
);
178 /* standard printer class requests */
179 kern_return_t (*SoftReset
)(struct classdriver_s
**printer
, UInt16 timeout
);
180 kern_return_t (*GetCentronicsStatus
)(struct classdriver_s
**printer
, centronics_status_t
*result
, UInt16 timeout
);
181 kern_return_t (*GetDeviceID
)(struct classdriver_s
**printer
, CFStringRef
*devid
, UInt16 timeout
);
183 /* standard bulk device requests */
184 kern_return_t (*ReadPipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
);
185 kern_return_t (*WritePipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
, Boolean eoj
);
187 /* interface requests */
188 kern_return_t (*Open
)(struct classdriver_s
**printer
, UInt32 location
, UInt8 protocol
);
189 kern_return_t (*Abort
)(struct classdriver_s
**printer
);
190 kern_return_t (*Close
)(struct classdriver_s
**printer
);
192 /* initialize and terminate */
193 kern_return_t (*Initialize
)(struct classdriver_s
**printer
, struct classdriver_s
**baseclass
);
194 kern_return_t (*Terminate
)(struct classdriver_s
**printer
);
198 typedef Boolean (*iterator_callback_t
)(void *refcon
, io_service_t obj
);
200 typedef struct iterator_reference_s
/**** Iterator reference data */
202 iterator_callback_t callback
;
205 } iterator_reference_t
;
207 typedef struct globals_s
209 io_service_t printer_obj
;
210 classdriver_t
**classdriver
;
212 pthread_mutex_t read_thread_mutex
;
213 pthread_cond_t read_thread_cond
;
214 int read_thread_stop
;
215 int read_thread_done
;
217 pthread_mutex_t readwrite_lock_mutex
;
218 pthread_cond_t readwrite_lock_cond
;
227 CFRunLoopTimerRef status_timer
;
229 int print_fd
; /* File descriptor to print */
230 ssize_t print_bytes
; /* Print bytes read */
233 int drain_output
; /* Drain all pending output */
234 int bidi_flag
; /* 0=unidirectional, 1=bidirectional */
236 pthread_mutex_t sidechannel_thread_mutex
;
237 pthread_cond_t sidechannel_thread_cond
;
238 int sidechannel_thread_stop
;
239 int sidechannel_thread_done
;
247 globals_t g
= { 0 }; /* Globals */
254 static Boolean
find_device_cb(void *refcon
, io_service_t obj
);
255 static Boolean
list_device_cb(void *refcon
, io_service_t obj
);
256 static CFStringRef
cfstr_create_trim(const char *cstr
);
257 static CFStringRef
copy_value_for_key(CFStringRef deviceID
, CFStringRef
*keys
);
258 static kern_return_t
load_classdriver(CFStringRef driverPath
, printer_interface_t intf
, classdriver_t
***printerDriver
);
259 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
);
260 static kern_return_t
registry_close();
261 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
);
262 static kern_return_t
unload_classdriver();
263 static OSStatus
copy_deviceid(classdriver_t
**printer
, CFStringRef
*deviceID
);
264 static void *read_thread(void *reference
);
265 static void *sidechannel_thread(void *reference
);
266 static void copy_deviceinfo(CFStringRef deviceIDString
, CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
267 static void copy_devicestring(io_service_t usbInterface
, CFStringRef
*deviceID
, UInt32
*deviceLocation
, UInt8
*interfaceNum
);
268 static void device_added(void *userdata
, io_iterator_t iterator
);
269 static void get_device_id(cups_sc_status_t
*status
, char *data
, int *datalen
);
270 static void iterate_printers(iterator_callback_t callBack
, void *userdata
);
271 static void parse_options(char *options
, char *serial
, int serial_size
, UInt32
*location
, Boolean
*wait_eof
);
272 static void release_deviceinfo(CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
273 static void setup_cfLanguage(void);
274 static void soft_reset();
275 static void status_timer_cb(CFRunLoopTimerRef timer
, void *info
);
277 #if defined(__i386__)
278 static pid_t child_pid
; /* Child PID */
279 static void run_ppc_backend(int argc
, char *argv
[], int fd
); /* Starts child backend process running as a ppc executable */
280 static void sigterm_handler(int sig
); /* SIGTERM handler */
281 #endif /* __i386__ */
283 #ifdef PARSE_PS_ERRORS
284 static const char *next_line (const char *buffer
);
285 static void parse_pserror (char *sockBuffer
, int len
);
286 #endif /* PARSE_PS_ERRORS */
291 * 'list_devices()' - List all USB devices.
296 iterate_printers(list_device_cb
, NULL
);
301 * 'print_device()' - Print a file to a USB device.
304 int /* O - Exit status */
305 print_device(const char *uri
, /* I - Device URI */
306 const char *hostname
, /* I - Hostname/manufacturer */
307 const char *resource
, /* I - Resource/modelname */
308 char *options
, /* I - Device options/serial number */
309 int print_fd
, /* I - File descriptor to print */
310 int copies
, /* I - Copies to print */
311 int argc
, /* I - Number of command-line arguments (6 or 7) */
312 char *argv
[]) /* I - Command-line arguments */
314 char serial
[1024]; /* Serial number buffer */
315 OSStatus status
; /* Function results */
316 pthread_t read_thread_id
, /* Read thread */
317 sidechannel_thread_id
;/* Side-channel thread */
318 int have_sidechannel
= 0; /* Was the side-channel thread started? */
319 struct stat sidechannel_info
; /* Side-channel file descriptor info */
320 char print_buffer
[8192], /* Print data buffer */
321 *print_ptr
; /* Pointer into print data buffer */
322 UInt32 location
; /* Unique location in bus topology */
323 fd_set input_set
; /* Input set for select() */
324 CFStringRef driverBundlePath
; /* Class driver path */
325 int countdown
, /* Logging interval */
326 nfds
; /* Number of file descriptors */
327 ssize_t total_bytes
; /* Total bytes written */
328 UInt32 bytes
; /* Bytes written */
329 struct timeval
*timeout
, /* Timeout pointer */
330 stimeout
; /* Timeout for select() */
331 struct timespec cond_timeout
; /* pthread condition timeout */
335 * See if the side-channel descriptor is valid...
338 have_sidechannel
= !fstat(CUPS_SC_FD
, &sidechannel_info
) &&
339 S_ISSOCK(sidechannel_info
.st_mode
);
342 * Localize using CoreFoundation...
347 parse_options(options
, serial
, sizeof(serial
), &location
, &g
.wait_eof
);
349 if (resource
[0] == '/')
352 g
.print_fd
= print_fd
;
353 g
.make
= cfstr_create_trim(hostname
);
354 g
.model
= cfstr_create_trim(resource
);
355 g
.serial
= cfstr_create_trim(serial
);
356 g
.location
= location
;
358 if (!g
.make
|| !g
.model
)
360 _cupsLangPrintf(stderr
,
361 _("ERROR: Unable to create make and model strings\n"));
362 return CUPS_BACKEND_STOP
;
365 fputs("STATE: +connecting-to-device\n", stderr
);
367 countdown
= INITIAL_LOG_INTERVAL
;
373 IOObjectRelease(g
.printer_obj
);
374 unload_classdriver(&g
.classdriver
);
379 fprintf(stderr
, "DEBUG: Looking for '%s %s'\n", hostname
, resource
);
381 iterate_printers(find_device_cb
, NULL
);
383 fputs("DEBUG: Opening connection\n", stderr
);
385 driverBundlePath
= NULL
;
387 status
= registry_open(&driverBundlePath
);
389 #if defined(__i386__)
391 * If we were unable to load the class drivers for this printer it's probably because they're ppc-only.
392 * In this case try to fork & exec this backend as a ppc executable so we can use them...
396 run_ppc_backend(argc
, argv
, print_fd
);
397 /* Never returns here */
399 #endif /* __i386__ */
404 * If we still were unable to load the class drivers for this printer log
405 * the error and stop the queue...
408 if (driverBundlePath
== NULL
|| !CFStringGetCString(driverBundlePath
, print_buffer
, sizeof(print_buffer
), kCFStringEncodingUTF8
))
409 strlcpy(print_buffer
, "USB class driver", sizeof(print_buffer
));
411 fputs("STATE: +apple-missing-usbclassdriver-error\n", stderr
);
412 _cupsLangPrintf(stderr
, _("FATAL: Could not load %s\n"), print_buffer
);
414 if (driverBundlePath
)
415 CFRelease(driverBundlePath
);
417 return CUPS_BACKEND_STOP
;
420 if (driverBundlePath
)
421 CFRelease(driverBundlePath
);
425 sleep(PRINTER_POLLING_INTERVAL
);
426 countdown
-= PRINTER_POLLING_INTERVAL
;
429 _cupsLangPrintf(stderr
, _("INFO: Printer busy (status:0x%08x)\n"),
431 countdown
= SUBSEQUENT_LOG_INTERVAL
; /* subsequent log entries, every 15 seconds */
434 } while (status
!= noErr
);
436 fputs("STATE: -connecting-to-device\n", stderr
);
439 * Now that we are "connected" to the port, ignore SIGTERM so that we
440 * can finish out any page data the driver sends (e.g. to eject the
441 * current page... Only ignore SIGTERM if we are printing data from
442 * stdin (otherwise you can't cancel raw jobs...)
447 struct sigaction action
; /* POSIX signal action */
450 memset(&action
, 0, sizeof(action
));
452 sigemptyset(&action
.sa_mask
);
453 action
.sa_handler
= SIG_IGN
;
454 sigaction(SIGTERM
, &action
, NULL
);
458 * Start the side channel thread if the descriptor is valid...
461 pthread_mutex_init(&g
.readwrite_lock_mutex
, NULL
);
462 pthread_cond_init(&g
.readwrite_lock_cond
, NULL
);
463 g
.readwrite_lock
= 1;
465 if (have_sidechannel
)
467 g
.sidechannel_thread_stop
= 0;
468 g
.sidechannel_thread_done
= 0;
470 pthread_cond_init(&g
.sidechannel_thread_cond
, NULL
);
471 pthread_mutex_init(&g
.sidechannel_thread_mutex
, NULL
);
473 if (pthread_create(&sidechannel_thread_id
, NULL
, sidechannel_thread
, NULL
))
475 _cupsLangPuts(stderr
, _("WARNING: Couldn't create side channel\n"));
476 return CUPS_BACKEND_STOP
;
481 * Get the read thread going...
484 g
.read_thread_stop
= 0;
485 g
.read_thread_done
= 0;
487 pthread_cond_init(&g
.read_thread_cond
, NULL
);
488 pthread_mutex_init(&g
.read_thread_mutex
, NULL
);
490 if (pthread_create(&read_thread_id
, NULL
, read_thread
, NULL
))
492 _cupsLangPuts(stderr
, _("WARNING: Couldn't create read channel\n"));
493 return CUPS_BACKEND_STOP
;
497 * The main thread sends the print file...
503 print_ptr
= print_buffer
;
505 while (status
== noErr
&& copies
-- > 0)
507 _cupsLangPuts(stderr
, _("INFO: Sending data\n"));
509 if (print_fd
!= STDIN_FILENO
)
511 fputs("PAGE: 1 1", stderr
);
512 lseek(print_fd
, 0, SEEK_SET
);
515 while (status
== noErr
)
520 FD_SET(print_fd
, &input_set
);
523 * Calculate select timeout...
524 * If we have data waiting to send timeout is 100ms.
525 * else if we're draining print_fd timeout is 0.
526 * else we're waiting forever...
532 stimeout
.tv_usec
= 100000; /* 100ms */
535 else if (g
.drain_output
)
538 stimeout
.tv_usec
= 0;
545 * I/O is unlocked around select...
548 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
549 g
.readwrite_lock
= 0;
550 pthread_cond_signal(&g
.readwrite_lock_cond
);
551 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
553 nfds
= select(print_fd
+ 1, &input_set
, NULL
, NULL
, timeout
);
556 * Reacquire the lock...
559 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
560 while (g
.readwrite_lock
)
561 pthread_cond_wait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
);
562 g
.readwrite_lock
= 1;
563 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
567 if (errno
== EINTR
&& total_bytes
== 0)
569 fputs("DEBUG: Received an interrupt before any bytes were "
570 "written, aborting!\n", stderr
);
573 else if (errno
!= EAGAIN
)
575 _cupsLangPrintf(stderr
, _("ERROR: select() returned %d\n"), (int)errno
);
576 return CUPS_BACKEND_STOP
;
581 * If drain output has finished send a response...
584 if (g
.drain_output
&& !nfds
&& !g
.print_bytes
)
586 /* Send a response... */
587 cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
592 * Check if we have print data ready...
595 if (FD_ISSET(print_fd
, &input_set
))
597 g
.print_bytes
= read(print_fd
, print_buffer
, sizeof(print_buffer
));
599 if (g
.print_bytes
< 0)
602 * Read error - bail if we don't see EAGAIN or EINTR...
605 if (errno
!= EAGAIN
|| errno
!= EINTR
)
607 _cupsLangPrintError(_("ERROR: Unable to read print data"));
608 return CUPS_BACKEND_STOP
;
613 else if (g
.print_bytes
== 0)
616 * End of file, break out of the loop...
622 print_ptr
= print_buffer
;
624 fprintf(stderr
, "DEBUG: Read %d bytes of print data...\n",
630 bytes
= g
.print_bytes
;
632 status
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
635 * Ignore timeout errors...
638 if (status
== kIOUSBTransactionTimeout
)
644 if (status
|| bytes
< 0)
647 * Write error - bail if we don't see an error we can retry...
650 OSStatus err
= (*g
.classdriver
)->Abort(g
.classdriver
);
651 _cupsLangPrintf(stderr
, _("ERROR: %ld: (canceled:%ld)\n"),
652 (long)status
, (long)err
);
653 status
= CUPS_BACKEND_STOP
;
657 fprintf(stderr
, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes
);
659 g
.print_bytes
-= bytes
;
661 total_bytes
+= bytes
;
664 if (print_fd
!= 0 && status
== noErr
)
665 fprintf(stderr
, "DEBUG: Sending print file, %lld bytes...\n",
670 fprintf(stderr
, "DEBUG: Sent %lld bytes...\n", (off_t
)total_bytes
);
673 * Wait for the side channel thread to exit...
676 if (have_sidechannel
)
679 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
680 g
.readwrite_lock
= 0;
681 pthread_cond_signal(&g
.readwrite_lock_cond
);
682 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
684 g
.sidechannel_thread_stop
= 1;
685 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
686 if (!g
.sidechannel_thread_done
)
689 * Wait for the side-channel thread to exit...
692 cond_timeout
.tv_sec
= time(NULL
) + WAIT_SIDE_DELAY
;
693 cond_timeout
.tv_nsec
= 0;
694 if (pthread_cond_timedwait(&g
.sidechannel_thread_cond
,
695 &g
.sidechannel_thread_mutex
,
699 * Force the side-channel thread to exit...
702 pthread_kill(sidechannel_thread_id
, SIGTERM
);
705 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
707 pthread_join(sidechannel_thread_id
, NULL
);
709 pthread_cond_destroy(&g
.sidechannel_thread_cond
);
710 pthread_mutex_destroy(&g
.sidechannel_thread_mutex
);
713 pthread_cond_destroy(&g
.readwrite_lock_cond
);
714 pthread_mutex_destroy(&g
.readwrite_lock_mutex
);
717 * Signal the read thread to stop...
720 g
.read_thread_stop
= 1;
723 * Give the read thread WAIT_EOF_DELAY seconds to complete all the data. If
724 * we are not signaled in that time then force the thread to exit.
727 pthread_mutex_lock(&g
.read_thread_mutex
);
729 if (!g
.read_thread_done
)
731 cond_timeout
.tv_sec
= time(NULL
) + WAIT_EOF_DELAY
;
732 cond_timeout
.tv_nsec
= 0;
734 if (pthread_cond_timedwait(&g
.read_thread_cond
, &g
.read_thread_mutex
,
738 * Force the read thread to exit...
741 pthread_kill(read_thread_id
, SIGTERM
);
744 pthread_mutex_unlock(&g
.read_thread_mutex
);
746 pthread_join(read_thread_id
, NULL
); /* wait for the read thread to return */
748 pthread_cond_destroy(&g
.read_thread_cond
);
749 pthread_mutex_destroy(&g
.read_thread_mutex
);
752 * Close the connection and input file and general clean up...
757 if (print_fd
!= STDIN_FILENO
)
766 if (g
.serial
!= NULL
)
769 if (g
.printer_obj
!= 0x0)
770 IOObjectRelease(g
.printer_obj
);
777 * 'read_thread()' - Thread to read the backchannel data on.
780 static void *read_thread(void *reference
)
782 UInt8 readbuffer
[512];
784 kern_return_t readstatus
;
785 struct mach_timebase_info timeBaseInfo
;
789 /* Calculate what 250 milliSeconds are in mach absolute time...
791 mach_timebase_info(&timeBaseInfo
);
792 delay
= ((uint64_t)250000000 * (uint64_t)timeBaseInfo
.denom
) / (uint64_t)timeBaseInfo
.numer
;
797 * Remember when we started so we can throttle the loop after the read call...
800 start
= mach_absolute_time();
802 rbytes
= sizeof(readbuffer
);
803 readstatus
= (*g
.classdriver
)->ReadPipe(g
.classdriver
, readbuffer
, &rbytes
);
804 if (readstatus
== kIOReturnSuccess
&& rbytes
> 0)
806 cupsBackChannelWrite((char*)readbuffer
, rbytes
, 1.0);
808 /* cntrl-d is echoed by the printer.
810 * Xerox Phaser 6250D doesn't echo the cntrl-d.
811 * Xerox Phaser 6250D doesn't always send the product query.
813 if (g
.wait_eof
&& readbuffer
[rbytes
-1] == 0x4)
816 #ifdef PARSE_PS_ERRORS
817 parse_pserror(readbuffer
, rbytes
);
822 * Make sure this loop executes no more than once every 250 miliseconds...
825 if ((readstatus
!= kIOReturnSuccess
|| rbytes
== 0) && (g
.wait_eof
|| !g
.read_thread_stop
))
826 mach_wait_until(start
+ delay
);
828 } while (g
.wait_eof
|| !g
.read_thread_stop
); /* Abort from main thread tests error here */
831 * Let the main thread know that we have completed the read thread...
834 pthread_mutex_lock(&g
.read_thread_mutex
);
835 g
.read_thread_done
= 1;
836 pthread_cond_signal(&g
.read_thread_cond
);
837 pthread_mutex_unlock(&g
.read_thread_mutex
);
844 * 'sidechannel_thread()' - Handle side-channel requests.
848 sidechannel_thread(void *reference
)
850 cups_sc_command_t command
; /* Request command */
851 cups_sc_status_t status
; /* Request/response status */
852 char data
[2048]; /* Request/response data */
853 int datalen
; /* Request/response data size */
858 datalen
= sizeof(data
);
860 if (cupsSideChannelRead(&command
, &status
, data
, &datalen
, 1.0))
865 case CUPS_SC_CMD_SOFT_RESET
: /* Do a soft reset */
866 if ((*g
.classdriver
)->SoftReset
!= NULL
)
869 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
873 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
878 case CUPS_SC_CMD_DRAIN_OUTPUT
: /* Drain all pending output */
882 case CUPS_SC_CMD_GET_BIDI
: /* Is the connection bidirectional? */
883 data
[0] = g
.bidi_flag
;
884 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
887 case CUPS_SC_CMD_GET_DEVICE_ID
: /* Return IEEE-1284 device ID */
888 datalen
= sizeof(data
);
889 get_device_id(&status
, data
, &datalen
);
890 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, datalen
, 1.0);
893 case CUPS_SC_CMD_GET_STATE
: /* Return device state */
894 data
[0] = CUPS_SC_STATE_ONLINE
;
895 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
899 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
904 while (!g
.sidechannel_thread_stop
);
906 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
907 g
.sidechannel_thread_done
= 1;
908 pthread_cond_signal(&g
.sidechannel_thread_cond
);
909 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
917 * 'iterate_printers()' - Iterate over all the printers.
920 static void iterate_printers(iterator_callback_t callBack
,
923 mach_port_t masterPort
= 0x0;
924 kern_return_t kr
= IOMasterPort (bootstrap_port
, &masterPort
);
926 if (kr
== kIOReturnSuccess
&& masterPort
!= 0x0)
928 io_iterator_t addIterator
= 0x0;
930 iterator_reference_t reference
= { callBack
, userdata
, true };
931 IONotificationPortRef addNotification
= IONotificationPortCreate(masterPort
);
933 int klass
= kUSBPrintingClass
;
934 int subklass
= kUSBPrintingSubclass
;
936 CFNumberRef usb_klass
= CFNumberCreate(NULL
, kCFNumberIntType
, &klass
);
937 CFNumberRef usb_subklass
= CFNumberCreate(NULL
, kCFNumberIntType
, &subklass
);
938 CFMutableDictionaryRef usbPrinterMatchDictionary
= IOServiceMatching(kIOUSBInterfaceClassName
);
940 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceClass"), usb_klass
);
941 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceSubClass"), usb_subklass
);
943 CFRelease(usb_klass
);
944 CFRelease(usb_subklass
);
946 kr
= IOServiceAddMatchingNotification(addNotification
, kIOMatchedNotification
, usbPrinterMatchDictionary
, &device_added
, &reference
, &addIterator
);
947 if (addIterator
!= 0x0)
949 device_added (&reference
, addIterator
);
951 if (reference
.keepRunning
)
953 CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification
), kCFRunLoopDefaultMode
);
956 IOObjectRelease(addIterator
);
958 mach_port_deallocate(mach_task_self(), masterPort
);
964 * 'device_added()' - Device added notifier.
967 static void device_added(void *userdata
,
968 io_iterator_t iterator
)
970 iterator_reference_t
*reference
= userdata
;
973 while (reference
->keepRunning
&& (obj
= IOIteratorNext(iterator
)) != 0x0)
975 if (reference
->callback
!= NULL
)
976 reference
->keepRunning
= reference
->callback(reference
->userdata
, obj
);
978 IOObjectRelease(obj
);
981 /* One last call to the call back now that we are not longer have printers left to iterate...
983 if (reference
->keepRunning
)
984 reference
->keepRunning
= reference
->callback(reference
->userdata
, 0x0);
986 if (!reference
->keepRunning
)
987 CFRunLoopStop(CFRunLoopGetCurrent());
992 * 'list_device_cb()' - list_device iterator callback.
995 static Boolean
list_device_cb(void *refcon
,
998 Boolean keepRunning
= (obj
!= 0x0);
1002 CFStringRef deviceIDString
= NULL
;
1003 UInt32 deviceLocation
= 0;
1004 UInt8 interfaceNum
= 0;
1006 copy_devicestring(obj
, &deviceIDString
, &deviceLocation
, &interfaceNum
);
1007 if (deviceIDString
!= NULL
)
1009 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1010 char uristr
[1024], makestr
[1024], modelstr
[1024], serialstr
[1024];
1011 char optionsstr
[1024], idstr
[1024];
1013 copy_deviceinfo(deviceIDString
, &make
, &model
, &serial
);
1017 CFStringGetCString(deviceIDString
, idstr
, sizeof(idstr
),
1018 kCFStringEncodingUTF8
);
1021 CFStringGetCString(make
, makestr
, sizeof(makestr
),
1022 kCFStringEncodingUTF8
);
1024 strcpy(makestr
, "Unknown");
1027 CFStringGetCString(model
, &modelstr
[1], sizeof(modelstr
)-1,
1028 kCFStringEncodingUTF8
);
1030 strcpy(modelstr
+ 1, "Printer");
1032 optionsstr
[0] = '\0';
1035 CFStringGetCString(serial
, serialstr
, sizeof(serialstr
), kCFStringEncodingUTF8
);
1036 snprintf(optionsstr
, sizeof(optionsstr
), "?serial=%s", serialstr
);
1038 else if (deviceLocation
!= 0)
1039 snprintf(optionsstr
, sizeof(optionsstr
), "?location=%x", (unsigned)deviceLocation
);
1041 httpAssembleURI(HTTP_URI_CODING_ALL
, uristr
, sizeof(uristr
), "usb", NULL
, makestr
, 0, modelstr
);
1042 strncat(uristr
, optionsstr
, sizeof(uristr
));
1045 * Fix common HP 1284 bug...
1048 if (!strcasecmp(makestr
, "Hewlett-Packard"))
1049 strcpy(makestr
, "HP");
1051 if (!strncasecmp(modelstr
+ 1, "hp ", 3))
1052 _cups_strcpy(modelstr
+ 1, modelstr
+ 4);
1054 printf("direct %s \"%s %s\" \"%s %s USB\" \"%s\"\n", uristr
, makestr
,
1055 &modelstr
[1], makestr
, &modelstr
[1], idstr
);
1057 release_deviceinfo(&make
, &model
, &serial
);
1058 CFRelease(deviceIDString
);
1067 * 'find_device_cb()' - print_device iterator callback.
1070 static Boolean
find_device_cb(void *refcon
,
1073 Boolean keepLooking
= true;
1077 CFStringRef idString
= NULL
;
1078 UInt32 location
= -1;
1079 UInt8 interfaceNum
= 0;
1081 copy_devicestring(obj
, &idString
, &location
, &interfaceNum
);
1082 if (idString
!= NULL
)
1084 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1086 copy_deviceinfo(idString
, &make
, &model
, &serial
);
1087 if (make
&& CFStringCompare(make
, g
.make
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1089 if (model
&& CFStringCompare(model
, g
.model
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1091 if (g
.serial
!= NULL
&& CFStringGetLength(g
.serial
) > 0)
1093 if (serial
!= NULL
&& CFStringCompare(serial
, g
.serial
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1095 IOObjectRetain(obj
);
1096 g
.printer_obj
= obj
;
1097 keepLooking
= false;
1102 if (g
.printer_obj
!= 0)
1103 IOObjectRelease(g
.printer_obj
);
1105 g
.printer_obj
= obj
;
1106 IOObjectRetain(obj
);
1108 if (g
.location
== 0 || g
.location
== location
)
1109 keepLooking
= false;
1112 g
.interfaceNum
= interfaceNum
;
1116 release_deviceinfo(&make
, &model
, &serial
);
1117 CFRelease(idString
);
1122 keepLooking
= (g
.printer_obj
== 0);
1123 if (obj
== 0x0 && keepLooking
)
1125 CFRunLoopTimerContext context
= { 0, refcon
, NULL
, NULL
, NULL
};
1126 CFRunLoopTimerRef timer
= CFRunLoopTimerCreate(NULL
, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb
, &context
);
1129 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer
, kCFRunLoopDefaultMode
);
1130 g
.status_timer
= timer
;
1135 if (!keepLooking
&& g
.status_timer
!= NULL
)
1137 fputs("STATE: -offline-error\n", stderr
);
1138 _cupsLangPuts(stderr
, _("INFO: Printer is now online.\n"));
1139 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g
.status_timer
, kCFRunLoopDefaultMode
);
1140 CFRelease(g
.status_timer
);
1141 g
.status_timer
= NULL
;
1149 * 'status_timer_cb()' - Status timer callback.
1152 static void status_timer_cb(CFRunLoopTimerRef timer
,
1155 fputs("STATE: +offline-error\n", stderr
);
1156 _cupsLangPuts(stderr
, _("INFO: Printer is currently offline.\n"));
1158 if (getenv("CLASS") != NULL
)
1161 * If the CLASS environment variable is set, the job was submitted
1162 * to a class and not to a specific queue. In this case, we want
1163 * to abort immediately so that the job can be requeued on the next
1164 * available printer in the class.
1166 * Sleep 5 seconds to keep the job from requeuing too rapidly...
1171 exit(CUPS_BACKEND_FAILED
);
1178 * 'copy_deviceinfo()' - Copy strings from the 1284 device ID.
1181 static void copy_deviceinfo(CFStringRef deviceIDString
,
1184 CFStringRef
*serial
)
1186 CFStringRef modelKeys
[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL
};
1187 CFStringRef makeKeys
[] = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL
};
1188 CFStringRef serialKeys
[] = { CFSTR("SN:"), CFSTR("SERN:"), NULL
};
1191 *make
= copy_value_for_key(deviceIDString
, makeKeys
);
1193 *model
= copy_value_for_key(deviceIDString
, modelKeys
);
1195 *serial
= copy_value_for_key(deviceIDString
, serialKeys
);
1200 * 'release_deviceinfo()' - Release deviceinfo strings.
1203 static void release_deviceinfo(CFStringRef
*make
,
1205 CFStringRef
*serial
)
1207 if (make
!= NULL
&& *make
!= NULL
)
1213 if (model
!= NULL
&& *model
!= NULL
)
1219 if (serial
!= NULL
&& *serial
!= NULL
)
1229 * 'load_classdriver()' - Load a classdriver.
1232 static kern_return_t
load_classdriver(CFStringRef driverPath
,
1233 printer_interface_t intf
,
1234 classdriver_t
***printerDriver
)
1236 kern_return_t kr
= kUSBPrinterClassDeviceNotOpen
;
1237 classdriver_t
**driver
= NULL
;
1238 CFStringRef bundle
= (driverPath
== NULL
? kUSBGenericTOPrinterClassDriver
: driverPath
);
1242 CFURLRef url
= CFURLCreateWithFileSystemPath(NULL
, bundle
, kCFURLPOSIXPathStyle
, true);
1243 CFPlugInRef plugin
= (url
!= NULL
? CFPlugInCreate(NULL
, url
) : NULL
);
1250 CFArrayRef factories
= CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID
, plugin
);
1251 if (factories
!= NULL
&& CFArrayGetCount(factories
) > 0)
1253 CFUUIDRef factoryID
= CFArrayGetValueAtIndex(factories
, 0);
1254 IUnknownVTbl
**iunknown
= CFPlugInInstanceCreate(NULL
, factoryID
, kUSBPrinterClassTypeID
);
1255 if (iunknown
!= NULL
)
1257 kr
= (*iunknown
)->QueryInterface(iunknown
, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID
), (LPVOID
*)&driver
);
1258 if (kr
== kIOReturnSuccess
&& driver
!= NULL
)
1260 classdriver_t
**genericDriver
= NULL
;
1261 if (driverPath
!= NULL
&& CFStringCompare(driverPath
, kUSBGenericTOPrinterClassDriver
, 0) != kCFCompareEqualTo
)
1262 kr
= load_classdriver(NULL
, intf
, &genericDriver
);
1264 if (kr
== kIOReturnSuccess
)
1266 (*driver
)->interface
= intf
;
1267 (*driver
)->Initialize(driver
, genericDriver
);
1269 (*driver
)->plugin
= plugin
;
1270 (*driver
)->interface
= intf
;
1271 *printerDriver
= driver
;
1274 (*iunknown
)->Release(iunknown
);
1276 CFRelease(factories
);
1282 char bundlestr
[1024];
1283 CFStringGetCString(bundle
, bundlestr
, sizeof(bundlestr
), kCFStringEncodingUTF8
);
1284 fprintf(stderr
, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr
, (int)kr
);
1292 * 'unload_classdriver()' - Unload a classdriver.
1295 static kern_return_t
unload_classdriver(classdriver_t
***classdriver
)
1297 if (*classdriver
!= NULL
)
1299 (**classdriver
)->Release(*classdriver
);
1300 *classdriver
= NULL
;
1303 return kIOReturnSuccess
;
1308 * 'load_printerdriver()' - Load vendor's classdriver.
1310 * If driverBundlePath is not NULL on return it is the callers responsbility to release it!
1313 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
)
1315 IOCFPlugInInterface
**iodev
= NULL
;
1318 printer_interface_t intf
;
1321 kr
= IOCreatePlugInInterfaceForService(g
.printer_obj
, kIOUSBInterfaceUserClientTypeID
, kIOCFPlugInInterfaceID
, &iodev
, &score
);
1322 if (kr
== kIOReturnSuccess
)
1324 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*) &intf
)) == noErr
)
1326 *driverBundlePath
= IORegistryEntryCreateCFProperty(g
.printer_obj
, kUSBClassDriverProperty
, NULL
, kNilOptions
);
1328 kr
= load_classdriver(*driverBundlePath
, intf
, &g
.classdriver
);
1330 if (kr
!= kIOReturnSuccess
)
1331 (*intf
)->Release(intf
);
1333 IODestroyPlugInInterface(iodev
);
1340 * 'registry_open()' - Open a connection to the printer.
1343 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
)
1345 g
.bidi_flag
= 0; /* 0=unidirectional */
1347 kern_return_t kr
= load_printerdriver(driverBundlePath
);
1348 if (kr
!= kIOReturnSuccess
)
1351 if (g
.classdriver
!= NULL
)
1353 (*g
.classdriver
)->interfaceNumber
= g
.interfaceNum
;
1354 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolBidirectional
);
1355 if (kr
!= kIOReturnSuccess
|| (*g
.classdriver
)->interface
== NULL
)
1357 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolUnidirectional
);
1358 if (kr
== kIOReturnSuccess
)
1360 if ((*g
.classdriver
)->interface
== NULL
)
1362 (*g
.classdriver
)->Close(g
.classdriver
);
1368 g
.bidi_flag
= 1; /* 1=bidirectional */
1371 if (kr
!= kIOReturnSuccess
)
1372 unload_classdriver(&g
.classdriver
);
1379 * 'registry_close()' - Close the connection to the printer.
1382 static kern_return_t
registry_close()
1384 if (g
.classdriver
!= NULL
)
1385 (*g
.classdriver
)->Close(g
.classdriver
);
1387 unload_classdriver(&g
.classdriver
);
1388 return kIOReturnSuccess
;
1393 * 'copy_deviceid()' - Copy the 1284 device id string.
1396 static OSStatus
copy_deviceid(classdriver_t
**classdriver
,
1397 CFStringRef
*deviceID
)
1399 CFStringRef devID
= NULL
,
1403 deviceSerial
= NULL
;
1405 OSStatus err
= (*classdriver
)->GetDeviceID(classdriver
, &devID
, DEFAULT_TIMEOUT
);
1407 copy_deviceinfo(devID
, &deviceMake
, &deviceModel
, &deviceSerial
);
1409 if (deviceMake
== NULL
|| deviceModel
== NULL
|| deviceSerial
== NULL
)
1411 IOUSBDeviceDescriptor desc
;
1412 iodevice_request_t request
;
1414 request
.requestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
1415 request
.request
= kUSBRqGetDescriptor
;
1416 request
.value
= (kUSBDeviceDesc
<< 8) | 0;
1418 request
.length
= sizeof(desc
);
1419 request
.buffer
= &desc
;
1420 err
= (*classdriver
)->DeviceRequest(classdriver
, &request
, DEFAULT_TIMEOUT
);
1421 if (err
== kIOReturnSuccess
)
1423 CFMutableStringRef newDevID
= CFStringCreateMutable(NULL
, 0);
1425 if (deviceMake
== NULL
)
1427 CFStringRef data
= NULL
;
1428 err
= (*classdriver
)->GetString(classdriver
, desc
.iManufacturer
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1431 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MFG:%@;"), data
);
1436 if (deviceModel
== NULL
)
1438 CFStringRef data
= NULL
;
1439 err
= (*classdriver
)->GetString(classdriver
, desc
.iProduct
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1442 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MDL:%@;"), data
);
1447 if (deviceSerial
== NULL
&& desc
.iSerialNumber
!= 0)
1449 CFStringRef data
= NULL
;
1450 err
= (*classdriver
)->GetString(classdriver
, desc
.iSerialNumber
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1453 CFStringAppendFormat(newDevID
, NULL
, CFSTR("SERN:%@;"), data
);
1460 CFStringAppend(newDevID
, devID
);
1464 *deviceID
= newDevID
;
1471 release_deviceinfo(&deviceMake
, &deviceModel
, &deviceSerial
);
1478 * 'copy_devicestring()' - Copy the 1284 device id string.
1481 static void copy_devicestring(io_service_t usbInterface
,
1482 CFStringRef
*deviceID
,
1483 UInt32
*deviceLocation
,
1484 UInt8
*interfaceNumber
)
1486 IOCFPlugInInterface
**iodev
= NULL
;
1489 printer_interface_t intf
;
1491 classdriver_t
**klassDriver
= NULL
;
1492 CFStringRef driverBundlePath
;
1494 if ((kr
= IOCreatePlugInInterfaceForService(usbInterface
,
1495 kIOUSBInterfaceUserClientTypeID
,
1496 kIOCFPlugInInterfaceID
,
1497 &iodev
, &score
)) == kIOReturnSuccess
)
1499 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*)
1502 (*intf
)->GetLocationID(intf
, deviceLocation
);
1503 (*intf
)->GetInterfaceNumber(intf
, interfaceNumber
);
1505 driverBundlePath
= IORegistryEntryCreateCFProperty(usbInterface
,
1506 kUSBClassDriverProperty
,
1509 kr
= load_classdriver(driverBundlePath
, intf
, &klassDriver
);
1511 if (kr
!= kIOReturnSuccess
&& driverBundlePath
!= NULL
)
1512 kr
= load_classdriver(NULL
, intf
, &klassDriver
);
1514 if (kr
== kIOReturnSuccess
&& klassDriver
!= NULL
)
1515 kr
= copy_deviceid(klassDriver
, deviceID
);
1517 unload_classdriver(&klassDriver
);
1519 if (driverBundlePath
!= NULL
)
1520 CFRelease(driverBundlePath
);
1522 /* (*intf)->Release(intf); */
1524 IODestroyPlugInInterface(iodev
);
1531 * 'copy_value_for_key()' - Copy value string associated with a key.
1534 static CFStringRef
copy_value_for_key(CFStringRef deviceID
,
1537 CFStringRef value
= NULL
;
1538 CFArrayRef kvPairs
= deviceID
!= NULL
? CFStringCreateArrayBySeparatingStrings(NULL
, deviceID
, CFSTR(";")) : NULL
;
1539 CFIndex max
= kvPairs
!= NULL
? CFArrayGetCount(kvPairs
) : 0;
1542 while (idx
< max
&& value
== NULL
)
1544 CFStringRef kvpair
= CFArrayGetValueAtIndex(kvPairs
, idx
);
1546 while (keys
[idxx
] != NULL
&& value
== NULL
)
1548 CFRange range
= CFStringFind(kvpair
, keys
[idxx
], kCFCompareCaseInsensitive
);
1549 if (range
.length
!= -1)
1551 if (range
.location
!= 0)
1553 CFMutableStringRef theString
= CFStringCreateMutableCopy(NULL
, 0, kvpair
);
1554 CFStringTrimWhitespace(theString
);
1555 range
= CFStringFind(theString
, keys
[idxx
], kCFCompareCaseInsensitive
);
1556 if (range
.location
== 0)
1557 value
= CFStringCreateWithSubstring(NULL
, theString
, CFRangeMake(range
.length
, CFStringGetLength(theString
) - range
.length
));
1559 CFRelease(theString
);
1563 CFStringRef theString
= CFStringCreateWithSubstring(NULL
, kvpair
, CFRangeMake(range
.length
, CFStringGetLength(kvpair
) - range
.length
));
1564 CFMutableStringRef theString2
= CFStringCreateMutableCopy(NULL
, 0, theString
);
1565 CFRelease(theString
);
1567 CFStringTrimWhitespace(theString2
);
1576 if (kvPairs
!= NULL
)
1583 * 'cfstr_create_trim()' - Create CFString and trim whitespace characters.
1586 CFStringRef
cfstr_create_trim(const char *cstr
)
1589 CFMutableStringRef cfmutablestr
= NULL
;
1591 if ((cfstr
= CFStringCreateWithCString(NULL
, cstr
, kCFStringEncodingUTF8
)) != NULL
)
1593 if ((cfmutablestr
= CFStringCreateMutableCopy(NULL
, 1024, cfstr
)) != NULL
)
1594 CFStringTrimWhitespace(cfmutablestr
);
1598 return (CFStringRef
) cfmutablestr
;
1604 * 'parse_options()' - Parse URI options.
1607 static void parse_options(char *options
,
1613 char sep
, /* Separator character */
1614 *name
, /* Name of option */
1615 *value
; /* Value of option */
1634 while (*options
&& *options
!= '=' && *options
!= '+' && *options
!= '&')
1637 if ((sep
= *options
) != '\0')
1648 while (*options
&& *options
!= '+' && *options
!= '&')
1658 * Process the option...
1661 if (!strcasecmp(name
, "waiteof"))
1663 if (!strcasecmp(value
, "on") ||
1664 !strcasecmp(value
, "yes") ||
1665 !strcasecmp(value
, "true"))
1667 else if (!strcasecmp(value
, "off") ||
1668 !strcasecmp(value
, "no") ||
1669 !strcasecmp(value
, "false"))
1672 _cupsLangPrintf(stderr
,
1673 _("WARNING: Boolean expected for waiteof option "
1674 "\"%s\"\n"), value
);
1676 else if (!strcasecmp(name
, "serial"))
1677 strlcpy(serial
, value
, serial_size
);
1678 else if (!strcasecmp(name
, "location") && location
)
1679 *location
= strtol(value
, NULL
, 16);
1685 * @function setup_cfLanguage
1686 * @abstract Convert the contents of the CUPS 'APPLE_LANGUAGE' environment
1687 * variable into a one element CF array of languages.
1689 * @discussion Each submitted job comes with a natural language. CUPS passes
1690 * that language in an environment variable. We take that language
1691 * and jam it into the AppleLanguages array so that CF will use
1692 * it when reading localized resources. We need to do this before
1693 * any CF code reads and caches the languages array, so this function
1694 * should be called early in main()
1696 static void setup_cfLanguage(void)
1698 CFStringRef lang
[1] = {NULL
};
1699 CFArrayRef langArray
= NULL
;
1700 const char *requestedLang
= NULL
;
1702 if ((requestedLang
= getenv("APPLE_LANGUAGE")) == NULL
)
1703 requestedLang
= getenv("LANG");
1705 if (requestedLang
!= NULL
)
1707 lang
[0] = CFStringCreateWithCString(kCFAllocatorDefault
, requestedLang
, kCFStringEncodingUTF8
);
1708 langArray
= CFArrayCreate(kCFAllocatorDefault
, (const void **)lang
, sizeof(lang
) / sizeof(lang
[0]), &kCFTypeArrayCallBacks
);
1710 CFPreferencesSetAppValue(CFSTR("AppleLanguages"), langArray
, kCFPreferencesCurrentApplication
);
1711 DEBUG_printf((stderr
, "DEBUG: usb: AppleLanguages = \"%s\"\n", requestedLang
));
1714 CFRelease(langArray
);
1717 fputs("DEBUG: usb: LANG and APPLE_LANGUAGE environment variables missing.\n", stderr
);
1721 #if defined(__i386__)
1723 * @function run_ppc_backend
1725 * @abstract Starts child backend process running as a ppc executable.
1727 * @result Never returns; always calls exit().
1731 static void run_ppc_backend(int argc
,
1738 pid_t waitpid_status
;
1740 char *usb_ppc_status
;
1743 * If we're running as i386 and couldn't load the class driver (because they'it's
1744 * ppc-only) then try to re-exec ourselves in ppc mode to try again. If we don't have
1745 * a ppc architecture we may be running i386 again so guard against this by setting
1746 * and testing an environment variable...
1748 usb_ppc_status
= getenv("USB_PPC_STATUS");
1750 if (usb_ppc_status
== NULL
)
1753 * Setup a SIGTERM handler then block it before forking...
1756 struct sigaction action
; /* POSIX signal action */
1757 sigset_t newmask
, /* New signal mask */
1758 oldmask
; /* Old signal mask */
1760 memset(&action
, 0, sizeof(action
));
1761 sigaddset(&action
.sa_mask
, SIGTERM
);
1762 action
.sa_handler
= sigterm_handler
;
1763 sigaction(SIGTERM
, &action
, NULL
);
1765 sigemptyset(&newmask
);
1766 sigaddset(&newmask
, SIGTERM
);
1767 sigprocmask(SIG_BLOCK
, &newmask
, &oldmask
);
1769 if ((child_pid
= fork()) == 0)
1772 * Child comes here...
1775 setenv("USB_PPC_STATUS", "1", false);
1778 * Unblock signals before doing the exec...
1781 memset(&action
, 0, sizeof(action
));
1782 sigemptyset(&action
.sa_mask
);
1783 action
.sa_handler
= SIG_DFL
;
1784 sigaction(SIGTERM
, &action
, NULL
);
1786 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
1789 * Tell the kernel the next exec call should favor the ppc architecture...
1792 int mib
[] = { CTL_KERN
, KERN_AFFINITY
, 1, 1 };
1794 sysctl(mib
, namelen
, NULL
, NULL
, NULL
, 0);
1797 * Set up the arguments and call exec...
1800 for (i
= 0; i
< argc
&& i
< (sizeof(my_argv
)/sizeof(my_argv
[0])) - 1; i
++)
1801 my_argv
[i
] = argv
[i
];
1805 execv("/usr/libexec/cups/backend/usb", my_argv
);
1807 _cupsLangPrintError(_("ERROR: Unable to exec /usr/libexec/cups/backend/usb"));
1810 else if (child_pid
< 0)
1813 * Error - couldn't fork a new process!
1816 _cupsLangPrintError(_("ERROR: Unable to fork"));
1821 * Unblock signals...
1824 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
1827 * Close the fds we won't be using then wait for the child backend to exit.
1833 fprintf(stderr
, "DEBUG: Started usb(ppc) backend (PID %d)\n", (int)child_pid
);
1835 while ((waitpid_status
= waitpid(child_pid
, &childstatus
, 0)) == (pid_t
)-1 && errno
== EINTR
)
1838 if (WIFSIGNALED(childstatus
))
1840 exitstatus
= WTERMSIG(childstatus
);
1841 fprintf(stderr
, "DEBUG: usb(ppc) backend %d crashed on signal %d!\n", child_pid
, exitstatus
);
1845 if ((exitstatus
= WEXITSTATUS(childstatus
)) != 0)
1846 fprintf(stderr
, "DEBUG: usb(ppc) backend %d stopped with status %d!\n", child_pid
, exitstatus
);
1848 fprintf(stderr
, "DEBUG: PID %d exited with no errors\n", child_pid
);
1853 fputs("DEBUG: usb child running i386 again\n", stderr
);
1854 exitstatus
= ENOENT
;
1861 * 'sigterm_handler()' - SIGTERM handler.
1864 static void sigterm_handler(int sig
)
1866 /* If we started a child process pass the signal on to it...
1869 kill(child_pid
, sig
);
1874 #endif /* __i386__ */
1877 #ifdef PARSE_PS_ERRORS
1879 * 'next_line()' - Find the next line in a buffer.
1882 static const char *next_line (const char *buffer
)
1884 const char *cptr
, *lptr
= NULL
;
1886 for (cptr
= buffer
; *cptr
&& lptr
== NULL
; cptr
++)
1887 if (*cptr
== '\n' || *cptr
== '\r')
1894 * 'parse_pserror()' - Scan the backchannel data for postscript errors.
1897 static void parse_pserror(char *sockBuffer
,
1900 static char gErrorBuffer
[1024] = "";
1901 static char *gErrorBufferPtr
= gErrorBuffer
;
1902 static char *gErrorBufferEndPtr
= gErrorBuffer
+ sizeof(gErrorBuffer
);
1904 char *pCommentBegin
, *pCommentEnd
, *pLineEnd
;
1909 if (gErrorBufferPtr
+ len
> gErrorBufferEndPtr
- 1)
1910 gErrorBufferPtr
= gErrorBuffer
;
1911 if (len
> sizeof(gErrorBuffer
) - 1)
1912 len
= sizeof(gErrorBuffer
) - 1;
1914 memcpy(gErrorBufferPtr
, (const void *)sockBuffer
, len
);
1915 gErrorBufferPtr
+= len
;
1916 *(gErrorBufferPtr
+ 1) = '\0';
1918 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
1919 while (pLineEnd
!= NULL
)
1923 pCommentBegin
= strstr(gErrorBuffer
,"%%[");
1924 pCommentEnd
= strstr(gErrorBuffer
, "]%%");
1925 if (pCommentBegin
!= gErrorBuffer
&& pCommentEnd
!= NULL
)
1927 pCommentEnd
+= 3; /* Skip past "]%%" */
1928 *pCommentEnd
= '\0'; /* There's always room for the nul */
1930 if (strncasecmp(pCommentBegin
, "%%[ Error:", 10) == 0)
1932 else if (strncasecmp(pCommentBegin
, "%%[ Flushing", 12) == 0)
1937 if ((logstrlen
= snprintf(logstr
, sizeof(logstr
), "%s: %s\n", logLevel
, pCommentBegin
)) >= sizeof(logstr
))
1939 /* If the string was trucnated make sure it has a linefeed before the nul */
1940 logstrlen
= sizeof(logstr
) - 1;
1941 logstr
[logstrlen
- 1] = '\n';
1943 write(STDERR_FILENO
, logstr
, logstrlen
);
1946 /* move everything over... */
1947 strcpy(gErrorBuffer
, pLineEnd
);
1948 gErrorBufferPtr
= gErrorBuffer
;
1949 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
1952 #endif /* PARSE_PS_ERRORS */
1956 * 'soft_reset()' - Send a soft reset to the device.
1959 static void soft_reset()
1961 fd_set input_set
; /* Input set for select() */
1962 struct timeval stimeout
; /* Timeout for select() */
1963 char buffer
[2048]; /* Buffer */
1964 struct timespec cond_timeout
; /* pthread condition timeout */
1967 * Send an abort once a second until the I/O lock is released by the main thread...
1970 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
1971 while (g
.readwrite_lock
)
1973 (*g
.classdriver
)->Abort(g
.classdriver
);
1975 cond_timeout
.tv_sec
= time(NULL
) + 1;
1976 cond_timeout
.tv_nsec
= 0;
1978 pthread_cond_timedwait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
, &cond_timeout
);
1981 g
.readwrite_lock
= 1;
1982 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
1985 * Flush bytes waiting on print_fd...
1990 FD_ZERO(&input_set
);
1991 FD_SET(g
.print_fd
, &input_set
);
1993 stimeout
.tv_sec
= 0;
1994 stimeout
.tv_usec
= 0;
1996 while (select(g
.print_fd
+1, &input_set
, NULL
, NULL
, &stimeout
) > 0)
1997 if (read(g
.print_fd
, buffer
, sizeof(buffer
)) <= 0)
2004 (*g
.classdriver
)->SoftReset(g
.classdriver
, DEFAULT_TIMEOUT
);
2007 * Release the I/O lock...
2010 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2011 g
.readwrite_lock
= 0;
2012 pthread_cond_signal(&g
.readwrite_lock_cond
);
2013 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2018 * 'get_device_id()' - Return IEEE-1284 device ID.
2021 static void get_device_id(cups_sc_status_t
*status
,
2025 UInt32 deviceLocation
= 0;
2026 UInt8 interfaceNum
= 0;
2027 CFStringRef deviceIDString
= NULL
;
2030 copy_devicestring(g
.printer_obj
, &deviceIDString
, &deviceLocation
, &interfaceNum
);
2033 CFStringGetCString(deviceIDString
, data
, *datalen
, kCFStringEncodingUTF8
);
2034 *datalen
= strlen(data
);
2035 CFRelease(deviceIDString
);
2037 *status
= CUPS_SC_STATUS_OK
;
2042 * End of "$Id: usb-darwin.c 6993 2007-09-28 18:05:28Z mike $".