2 * "$Id: usb-darwin.c 6993 2007-09-28 18:05:28Z mike $"
4 * Copyright � 2005-2007 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.
86 #include <sys/sysctl.h>
88 #include <mach/mach.h>
89 #include <mach/mach_error.h>
90 #include <mach/mach_time.h>
91 #include <cups/debug.h>
92 #include <cups/sidechannel.h>
93 #include <cups/i18n.h>
95 #include <CoreFoundation/CoreFoundation.h>
96 #include <IOKit/usb/IOUSBLib.h>
97 #include <IOKit/IOCFPlugIn.h>
103 * WAIT_EOF_DELAY is number of seconds we'll wait for responses from
104 * the printer after we've finished sending all the data
106 #define WAIT_EOF_DELAY 7
107 #define WAIT_SIDE_DELAY 3
108 #define DEFAULT_TIMEOUT 5000L
110 #define USB_INTERFACE_KIND CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID190)
111 #define kUSBLanguageEnglish 0x409
113 #define PRINTER_POLLING_INTERVAL 5 /* seconds */
114 #define INITIAL_LOG_INTERVAL PRINTER_POLLING_INTERVAL
115 #define SUBSEQUENT_LOG_INTERVAL 3 * INITIAL_LOG_INTERVAL
117 #define kUSBPrinterClassTypeID CFUUIDGetConstantUUIDWithBytes(NULL, 0x06, 0x04, 0x7D, 0x16, 0x53, 0xA2, 0x11, 0xD6, 0x92, 0x06, 0x00, 0x30, 0x65, 0x52, 0x45, 0x92)
118 #define kUSBPrinterClassInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, 0x03, 0x34, 0x6D, 0x74, 0x53, 0xA3, 0x11, 0xD6, 0x9E, 0xA1, 0x76, 0x30, 0x65, 0x52, 0x45, 0x92)
120 #define kUSBClassDriverProperty CFSTR("USB Printing Class")
122 #define kUSBGenericTOPrinterClassDriver CFSTR("/System/Library/Printers/Libraries/USBGenericTOPrintingClass.plugin")
123 #define kUSBPrinterClassDeviceNotOpen -9664 /*kPMInvalidIOMContext*/
127 * Section 5.3 USB Printing Class spec
129 #define kUSBPrintingSubclass 1
130 #define kUSBPrintingProtocolNoOpen 0
131 #define kUSBPrintingProtocolUnidirectional 1
132 #define kUSBPrintingProtocolBidirectional 2
134 typedef IOUSBInterfaceInterface190
**printer_interface_t
;
136 typedef struct iodevice_request_s
/**** Device request ****/
144 } iodevice_request_t
;
146 typedef union /**** Centronics status byte ****/
151 unsigned reserved0
:2;
152 unsigned paperError
:1;
155 unsigned reserved1
:3;
157 } centronics_status_t
;
159 typedef struct classdriver_s
/**** g.classdriver context ****/
162 CFPlugInRef plugin
; /* release plugin */
163 IUnknownVTbl
**factory
; /* Factory */
164 void *vendorReference
; /* vendor class specific usage */
165 UInt32 location
; /* unique location in bus topology */
166 UInt8 interfaceNumber
; /* Interface number */
167 UInt16 vendorID
; /* Vendor id */
168 UInt16 productID
; /* Product id */
169 printer_interface_t interface
; /* identify the device to IOKit */
170 UInt8 outpipe
; /* mandatory bulkOut pipe */
171 UInt8 inpipe
; /* optional bulkIn pipe */
173 /* general class requests */
174 kern_return_t (*DeviceRequest
)(struct classdriver_s
**printer
, iodevice_request_t
*iorequest
, UInt16 timeout
);
175 kern_return_t (*GetString
)(struct classdriver_s
**printer
, UInt8 whichString
, UInt16 language
, UInt16 timeout
, CFStringRef
*result
);
177 /* standard printer class requests */
178 kern_return_t (*SoftReset
)(struct classdriver_s
**printer
, UInt16 timeout
);
179 kern_return_t (*GetCentronicsStatus
)(struct classdriver_s
**printer
, centronics_status_t
*result
, UInt16 timeout
);
180 kern_return_t (*GetDeviceID
)(struct classdriver_s
**printer
, CFStringRef
*devid
, UInt16 timeout
);
182 /* standard bulk device requests */
183 kern_return_t (*ReadPipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
);
184 kern_return_t (*WritePipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
, Boolean eoj
);
186 /* interface requests */
187 kern_return_t (*Open
)(struct classdriver_s
**printer
, UInt32 location
, UInt8 protocol
);
188 kern_return_t (*Abort
)(struct classdriver_s
**printer
);
189 kern_return_t (*Close
)(struct classdriver_s
**printer
);
191 /* initialize and terminate */
192 kern_return_t (*Initialize
)(struct classdriver_s
**printer
, struct classdriver_s
**baseclass
);
193 kern_return_t (*Terminate
)(struct classdriver_s
**printer
);
197 typedef Boolean (*iterator_callback_t
)(void *refcon
, io_service_t obj
);
199 typedef struct iterator_reference_s
/**** Iterator reference data */
201 iterator_callback_t callback
;
204 } iterator_reference_t
;
206 typedef struct globals_s
208 io_service_t printer_obj
;
209 classdriver_t
**classdriver
;
211 pthread_mutex_t read_thread_mutex
;
212 pthread_cond_t read_thread_cond
;
213 int read_thread_stop
;
214 int read_thread_done
;
216 pthread_mutex_t readwrite_lock_mutex
;
217 pthread_cond_t readwrite_lock_cond
;
226 CFRunLoopTimerRef status_timer
;
228 int print_fd
; /* File descriptor to print */
229 ssize_t print_bytes
; /* Print bytes read */
232 int drain_output
; /* Drain all pending output */
233 int bidi_flag
; /* 0=unidirectional, 1=bidirectional */
235 pthread_mutex_t sidechannel_thread_mutex
;
236 pthread_cond_t sidechannel_thread_cond
;
237 int sidechannel_thread_stop
;
238 int sidechannel_thread_done
;
246 globals_t g
= { 0 }; /* Globals */
253 static Boolean
find_device_cb(void *refcon
, io_service_t obj
);
254 static Boolean
list_device_cb(void *refcon
, io_service_t obj
);
255 static CFStringRef
cfstr_create_trim(const char *cstr
);
256 static CFStringRef
copy_value_for_key(CFStringRef deviceID
, CFStringRef
*keys
);
257 static kern_return_t
load_classdriver(CFStringRef driverPath
, printer_interface_t intf
, classdriver_t
***printerDriver
);
258 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
);
259 static kern_return_t
registry_close();
260 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
);
261 static kern_return_t
unload_classdriver();
262 static OSStatus
copy_deviceid(classdriver_t
**printer
, CFStringRef
*deviceID
);
263 static void *read_thread(void *reference
);
264 static void *sidechannel_thread(void *reference
);
265 static void copy_deviceinfo(CFStringRef deviceIDString
, CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
266 static void copy_devicestring(io_service_t usbInterface
, CFStringRef
*deviceID
, UInt32
*deviceLocation
, UInt8
*interfaceNum
);
267 static void device_added(void *userdata
, io_iterator_t iterator
);
268 static void get_device_id(cups_sc_status_t
*status
, char *data
, int *datalen
);
269 static void iterate_printers(iterator_callback_t callBack
, void *userdata
);
270 static void parse_options(char *options
, char *serial
, int serial_size
, UInt32
*location
, Boolean
*wait_eof
);
271 static void release_deviceinfo(CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
272 static void setup_cfLanguage(void);
273 static void soft_reset();
274 static void status_timer_cb(CFRunLoopTimerRef timer
, void *info
);
276 #if defined(__i386__)
277 static pid_t child_pid
; /* Child PID */
278 static void run_ppc_backend(int argc
, char *argv
[], int fd
); /* Starts child backend process running as a ppc executable */
279 static void sigterm_handler(int sig
); /* SIGTERM handler */
280 #endif /* __i386__ */
282 #ifdef PARSE_PS_ERRORS
283 static const char *next_line (const char *buffer
);
284 static void parse_pserror (char *sockBuffer
, int len
);
285 #endif /* PARSE_PS_ERRORS */
290 * 'list_devices()' - List all USB devices.
295 iterate_printers(list_device_cb
, NULL
);
300 * 'print_device()' - Print a file to a USB device.
303 int /* O - Exit status */
304 print_device(const char *uri
, /* I - Device URI */
305 const char *hostname
, /* I - Hostname/manufacturer */
306 const char *resource
, /* I - Resource/modelname */
307 char *options
, /* I - Device options/serial number */
308 int print_fd
, /* I - File descriptor to print */
309 int copies
, /* I - Copies to print */
310 int argc
, /* I - Number of command-line arguments (6 or 7) */
311 char *argv
[]) /* I - Command-line arguments */
313 char serial
[1024]; /* Serial number buffer */
314 OSStatus status
; /* Function results */
315 pthread_t read_thread_id
, /* Read thread */
316 sidechannel_thread_id
;/* Side-channel thread */
317 int sidechannel_started
= 0;/* Was the side-channel thread started? */
318 char print_buffer
[8192], /* Print data buffer */
319 *print_ptr
; /* Pointer into print data buffer */
320 UInt32 location
; /* Unique location in bus topology */
321 fd_set input_set
; /* Input set for select() */
322 CFStringRef driverBundlePath
; /* Class driver path */
323 int countdown
, /* Logging interval */
324 nfds
; /* Number of file descriptors */
325 ssize_t total_bytes
; /* Total bytes written */
326 UInt32 bytes
; /* Bytes written */
327 struct timeval
*timeout
, /* Timeout pointer */
328 stimeout
; /* Timeout for select() */
329 struct timespec cond_timeout
; /* pthread condition timeout */
334 parse_options(options
, serial
, sizeof(serial
), &location
, &g
.wait_eof
);
336 if (resource
[0] == '/')
339 g
.print_fd
= print_fd
;
340 g
.make
= cfstr_create_trim(hostname
);
341 g
.model
= cfstr_create_trim(resource
);
342 g
.serial
= cfstr_create_trim(serial
);
343 g
.location
= location
;
345 if (!g
.make
|| !g
.model
)
347 _cupsLangPrintf(stderr
,
348 _("ERROR: Unable to create make and model strings\n"));
349 return CUPS_BACKEND_STOP
;
352 fputs("STATE: +connecting-to-device\n", stderr
);
354 countdown
= INITIAL_LOG_INTERVAL
;
360 IOObjectRelease(g
.printer_obj
);
361 unload_classdriver(&g
.classdriver
);
366 fprintf(stderr
, "DEBUG: Looking for '%s %s'\n", hostname
, resource
);
368 iterate_printers(find_device_cb
, NULL
);
370 fputs("DEBUG: Opening connection\n", stderr
);
372 driverBundlePath
= NULL
;
374 status
= registry_open(&driverBundlePath
);
376 #if defined(__i386__)
378 * If we were unable to load the class drivers for this printer it's probably because they're ppc-only.
379 * In this case try to fork & exec this backend as a ppc executable so we can use them...
383 run_ppc_backend(argc
, argv
, print_fd
);
384 /* Never returns here */
386 #endif /* __i386__ */
391 * If we still were unable to load the class drivers for this printer log
392 * the error and stop the queue...
395 if (driverBundlePath
== NULL
|| !CFStringGetCString(driverBundlePath
, print_buffer
, sizeof(print_buffer
), kCFStringEncodingUTF8
))
396 strlcpy(print_buffer
, "USB class driver", sizeof(print_buffer
));
398 fputs("STATE: +apple-missing-usbclassdriver-error\n", stderr
);
399 _cupsLangPrintf(stderr
, _("FATAL: Could not load %s\n"), print_buffer
);
401 if (driverBundlePath
)
402 CFRelease(driverBundlePath
);
404 return CUPS_BACKEND_STOP
;
407 if (driverBundlePath
)
408 CFRelease(driverBundlePath
);
412 sleep(PRINTER_POLLING_INTERVAL
);
413 countdown
-= PRINTER_POLLING_INTERVAL
;
416 _cupsLangPrintf(stderr
, _("INFO: Printer busy (status:0x%08x)\n"),
418 countdown
= SUBSEQUENT_LOG_INTERVAL
; /* subsequent log entries, every 15 seconds */
421 } while (status
!= noErr
);
423 fputs("STATE: -connecting-to-device\n", stderr
);
426 * Now that we are "connected" to the port, ignore SIGTERM so that we
427 * can finish out any page data the driver sends (e.g. to eject the
428 * current page... Only ignore SIGTERM if we are printing data from
429 * stdin (otherwise you can't cancel raw jobs...)
434 struct sigaction action
; /* POSIX signal action */
437 memset(&action
, 0, sizeof(action
));
439 sigemptyset(&action
.sa_mask
);
440 action
.sa_handler
= SIG_IGN
;
441 sigaction(SIGTERM
, &action
, NULL
);
445 * Start the side channel thread only if the descriptor is valid
446 * (i.e. it's not when the backend is used for auto-setup)...
449 pthread_mutex_init(&g
.readwrite_lock_mutex
, NULL
);
450 pthread_cond_init(&g
.readwrite_lock_cond
, NULL
);
451 g
.readwrite_lock
= 1;
454 FD_SET(CUPS_SC_FD
, &input_set
);
457 stimeout
.tv_usec
= 0;
459 if ((select(CUPS_SC_FD
+1, &input_set
, NULL
, NULL
, &stimeout
)) >= 0)
461 g
.sidechannel_thread_stop
= 0;
462 g
.sidechannel_thread_done
= 0;
464 pthread_cond_init(&g
.sidechannel_thread_cond
, NULL
);
465 pthread_mutex_init(&g
.sidechannel_thread_mutex
, NULL
);
467 if (pthread_create(&sidechannel_thread_id
, NULL
, sidechannel_thread
, NULL
))
469 _cupsLangPuts(stderr
, _("WARNING: Couldn't create side channel\n"));
470 return CUPS_BACKEND_STOP
;
473 sidechannel_started
= 1;
477 * Get the read thread going...
480 g
.read_thread_stop
= 0;
481 g
.read_thread_done
= 0;
483 pthread_cond_init(&g
.read_thread_cond
, NULL
);
484 pthread_mutex_init(&g
.read_thread_mutex
, NULL
);
486 if (pthread_create(&read_thread_id
, NULL
, read_thread
, NULL
))
488 _cupsLangPuts(stderr
, _("WARNING: Couldn't create read channel\n"));
489 return CUPS_BACKEND_STOP
;
493 * The main thread sends the print file...
499 print_ptr
= print_buffer
;
501 while (status
== noErr
&& copies
-- > 0)
503 _cupsLangPuts(stderr
, _("INFO: Sending data\n"));
505 if (print_fd
!= STDIN_FILENO
)
507 fputs("PAGE: 1 1", stderr
);
508 lseek(print_fd
, 0, SEEK_SET
);
511 while (status
== noErr
)
516 FD_SET(print_fd
, &input_set
);
519 * Calculate select timeout...
520 * If we have data waiting to send timeout is 100ms.
521 * else if we're draining print_fd timeout is 0.
522 * else we're waiting forever...
528 stimeout
.tv_usec
= 100000; /* 100ms */
531 else if (g
.drain_output
)
534 stimeout
.tv_usec
= 0;
541 * I/O is unlocked around select...
544 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
545 g
.readwrite_lock
= 0;
546 pthread_cond_signal(&g
.readwrite_lock_cond
);
547 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
549 nfds
= select(print_fd
+ 1, &input_set
, NULL
, NULL
, timeout
);
552 * Reacquire the lock...
555 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
556 while (g
.readwrite_lock
)
557 pthread_cond_wait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
);
558 g
.readwrite_lock
= 1;
559 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
563 if (errno
== EINTR
&& total_bytes
== 0)
565 fputs("DEBUG: Received an interrupt before any bytes were "
566 "written, aborting!\n", stderr
);
569 else if (errno
!= EAGAIN
)
571 _cupsLangPrintf(stderr
, _("ERROR: select() returned %d\n"), (int)errno
);
572 return CUPS_BACKEND_STOP
;
577 * If drain output has finished send a response...
580 if (g
.drain_output
&& !nfds
&& !g
.print_bytes
)
582 /* Send a response... */
583 cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
588 * Check if we have print data ready...
591 if (FD_ISSET(print_fd
, &input_set
))
593 g
.print_bytes
= read(print_fd
, print_buffer
, sizeof(print_buffer
));
595 if (g
.print_bytes
< 0)
598 * Read error - bail if we don't see EAGAIN or EINTR...
601 if (errno
!= EAGAIN
|| errno
!= EINTR
)
603 perror("ERROR: Unable to read print data");
604 return CUPS_BACKEND_STOP
;
609 else if (g
.print_bytes
== 0)
612 * End of file, break out of the loop...
618 print_ptr
= print_buffer
;
620 fprintf(stderr
, "DEBUG: Read %d bytes of print data...\n",
626 bytes
= g
.print_bytes
;
628 status
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
631 * Ignore timeout errors...
634 if (status
== kIOUSBTransactionTimeout
)
640 if (status
|| bytes
< 0)
643 * Write error - bail if we don't see an error we can retry...
646 OSStatus err
= (*g
.classdriver
)->Abort(g
.classdriver
);
647 _cupsLangPrintf(stderr
, _("ERROR: %ld: (canceled:%ld)\n"),
648 (long)status
, (long)err
);
649 status
= CUPS_BACKEND_STOP
;
653 fprintf(stderr
, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes
);
655 g
.print_bytes
-= bytes
;
657 total_bytes
+= bytes
;
660 if (print_fd
!= 0 && status
== noErr
)
661 fprintf(stderr
, "DEBUG: Sending print file, %lld bytes...\n",
666 fprintf(stderr
, "DEBUG: Sent %lld bytes...\n", (off_t
)total_bytes
);
669 * Wait for the side channel thread to exit...
672 if (sidechannel_started
)
675 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
676 g
.readwrite_lock
= 0;
677 pthread_cond_signal(&g
.readwrite_lock_cond
);
678 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
680 g
.sidechannel_thread_stop
= 1;
681 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
682 if (!g
.sidechannel_thread_done
)
685 * Wait for the side-channel thread to exit...
688 cond_timeout
.tv_sec
= time(NULL
) + WAIT_SIDE_DELAY
;
689 cond_timeout
.tv_nsec
= 0;
690 if (pthread_cond_timedwait(&g
.sidechannel_thread_cond
,
691 &g
.sidechannel_thread_mutex
,
695 * Force the side-channel thread to exit...
698 pthread_kill(sidechannel_thread_id
, SIGTERM
);
701 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
703 pthread_join(sidechannel_thread_id
, NULL
);
705 pthread_cond_destroy(&g
.sidechannel_thread_cond
);
706 pthread_mutex_destroy(&g
.sidechannel_thread_mutex
);
709 pthread_cond_destroy(&g
.readwrite_lock_cond
);
710 pthread_mutex_destroy(&g
.readwrite_lock_mutex
);
713 * Signal the read thread to stop...
716 g
.read_thread_stop
= 1;
719 * Give the read thread WAIT_EOF_DELAY seconds to complete all the data. If
720 * we are not signaled in that time then force the thread to exit.
723 pthread_mutex_lock(&g
.read_thread_mutex
);
725 if (!g
.read_thread_done
)
727 cond_timeout
.tv_sec
= time(NULL
) + WAIT_EOF_DELAY
;
728 cond_timeout
.tv_nsec
= 0;
730 if (pthread_cond_timedwait(&g
.read_thread_cond
, &g
.read_thread_mutex
,
734 * Force the read thread to exit...
737 pthread_kill(read_thread_id
, SIGTERM
);
740 pthread_mutex_unlock(&g
.read_thread_mutex
);
742 pthread_join(read_thread_id
, NULL
); /* wait for the read thread to return */
744 pthread_cond_destroy(&g
.read_thread_cond
);
745 pthread_mutex_destroy(&g
.read_thread_mutex
);
748 * Close the connection and input file and general clean up...
753 if (print_fd
!= STDIN_FILENO
)
762 if (g
.serial
!= NULL
)
765 if (g
.printer_obj
!= 0x0)
766 IOObjectRelease(g
.printer_obj
);
773 * 'read_thread()' - Thread to read the backchannel data on.
776 static void *read_thread(void *reference
)
778 UInt8 readbuffer
[512];
780 kern_return_t readstatus
;
781 struct mach_timebase_info timeBaseInfo
;
785 /* Calculate what 250 milliSeconds are in mach absolute time...
787 mach_timebase_info(&timeBaseInfo
);
788 delay
= ((uint64_t)250000000 * (uint64_t)timeBaseInfo
.denom
) / (uint64_t)timeBaseInfo
.numer
;
793 * Remember when we started so we can throttle the loop after the read call...
796 start
= mach_absolute_time();
798 rbytes
= sizeof(readbuffer
);
799 readstatus
= (*g
.classdriver
)->ReadPipe(g
.classdriver
, readbuffer
, &rbytes
);
800 if (readstatus
== kIOReturnSuccess
&& rbytes
> 0)
802 cupsBackChannelWrite((char*)readbuffer
, rbytes
, 1.0);
804 /* cntrl-d is echoed by the printer.
806 * Xerox Phaser 6250D doesn't echo the cntrl-d.
807 * Xerox Phaser 6250D doesn't always send the product query.
809 if (g
.wait_eof
&& readbuffer
[rbytes
-1] == 0x4)
812 #ifdef PARSE_PS_ERRORS
813 parse_pserror(readbuffer
, rbytes
);
818 * Make sure this loop executes no more than once every 250 miliseconds...
821 if ((readstatus
!= kIOReturnSuccess
|| rbytes
== 0) && (g
.wait_eof
|| !g
.read_thread_stop
))
822 mach_wait_until(start
+ delay
);
824 } while (g
.wait_eof
|| !g
.read_thread_stop
); /* Abort from main thread tests error here */
827 * Let the main thread know that we have completed the read thread...
830 pthread_mutex_lock(&g
.read_thread_mutex
);
831 g
.read_thread_done
= 1;
832 pthread_cond_signal(&g
.read_thread_cond
);
833 pthread_mutex_unlock(&g
.read_thread_mutex
);
840 * 'sidechannel_thread()' - Handle side-channel requests.
844 sidechannel_thread(void *reference
)
846 cups_sc_command_t command
; /* Request command */
847 cups_sc_status_t status
; /* Request/response status */
848 char data
[2048]; /* Request/response data */
849 int datalen
; /* Request/response data size */
854 datalen
= sizeof(data
);
856 if (cupsSideChannelRead(&command
, &status
, data
, &datalen
, 1.0))
861 case CUPS_SC_CMD_SOFT_RESET
: /* Do a soft reset */
862 if ((*g
.classdriver
)->SoftReset
!= NULL
)
865 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
869 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
874 case CUPS_SC_CMD_DRAIN_OUTPUT
: /* Drain all pending output */
878 case CUPS_SC_CMD_GET_BIDI
: /* Is the connection bidirectional? */
879 data
[0] = g
.bidi_flag
;
880 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
883 case CUPS_SC_CMD_GET_DEVICE_ID
: /* Return IEEE-1284 device ID */
884 datalen
= sizeof(data
);
885 get_device_id(&status
, data
, &datalen
);
886 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, datalen
, 1.0);
889 case CUPS_SC_CMD_GET_STATE
: /* Return device state */
890 data
[0] = CUPS_SC_STATE_ONLINE
;
891 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
895 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
900 while (!g
.sidechannel_thread_stop
);
902 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
903 g
.sidechannel_thread_done
= 1;
904 pthread_cond_signal(&g
.sidechannel_thread_cond
);
905 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
913 * 'iterate_printers()' - Iterate over all the printers.
916 static void iterate_printers(iterator_callback_t callBack
,
919 mach_port_t masterPort
= 0x0;
920 kern_return_t kr
= IOMasterPort (bootstrap_port
, &masterPort
);
922 if (kr
== kIOReturnSuccess
&& masterPort
!= 0x0)
924 io_iterator_t addIterator
= 0x0;
926 iterator_reference_t reference
= { callBack
, userdata
, true };
927 IONotificationPortRef addNotification
= IONotificationPortCreate(masterPort
);
929 int klass
= kUSBPrintingClass
;
930 int subklass
= kUSBPrintingSubclass
;
932 CFNumberRef usb_klass
= CFNumberCreate(NULL
, kCFNumberIntType
, &klass
);
933 CFNumberRef usb_subklass
= CFNumberCreate(NULL
, kCFNumberIntType
, &subklass
);
934 CFMutableDictionaryRef usbPrinterMatchDictionary
= IOServiceMatching(kIOUSBInterfaceClassName
);
936 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceClass"), usb_klass
);
937 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceSubClass"), usb_subklass
);
939 CFRelease(usb_klass
);
940 CFRelease(usb_subklass
);
942 kr
= IOServiceAddMatchingNotification(addNotification
, kIOMatchedNotification
, usbPrinterMatchDictionary
, &device_added
, &reference
, &addIterator
);
943 if (addIterator
!= 0x0)
945 device_added (&reference
, addIterator
);
947 if (reference
.keepRunning
)
949 CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification
), kCFRunLoopDefaultMode
);
952 IOObjectRelease(addIterator
);
954 mach_port_deallocate(mach_task_self(), masterPort
);
960 * 'device_added()' - Device added notifier.
963 static void device_added(void *userdata
,
964 io_iterator_t iterator
)
966 iterator_reference_t
*reference
= userdata
;
969 while (reference
->keepRunning
&& (obj
= IOIteratorNext(iterator
)) != 0x0)
971 if (reference
->callback
!= NULL
)
972 reference
->keepRunning
= reference
->callback(reference
->userdata
, obj
);
974 IOObjectRelease(obj
);
977 /* One last call to the call back now that we are not longer have printers left to iterate...
979 if (reference
->keepRunning
)
980 reference
->keepRunning
= reference
->callback(reference
->userdata
, 0x0);
982 if (!reference
->keepRunning
)
983 CFRunLoopStop(CFRunLoopGetCurrent());
988 * 'list_device_cb()' - list_device iterator callback.
991 static Boolean
list_device_cb(void *refcon
,
994 Boolean keepRunning
= (obj
!= 0x0);
998 CFStringRef deviceIDString
= NULL
;
999 UInt32 deviceLocation
= 0;
1000 UInt8 interfaceNum
= 0;
1002 copy_devicestring(obj
, &deviceIDString
, &deviceLocation
, &interfaceNum
);
1003 if (deviceIDString
!= NULL
)
1005 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1006 char uristr
[1024], makestr
[1024], modelstr
[1024], serialstr
[1024];
1007 char optionsstr
[1024], idstr
[1024];
1009 copy_deviceinfo(deviceIDString
, &make
, &model
, &serial
);
1013 CFStringGetCString(deviceIDString
, idstr
, sizeof(idstr
),
1014 kCFStringEncodingUTF8
);
1017 CFStringGetCString(make
, makestr
, sizeof(makestr
),
1018 kCFStringEncodingUTF8
);
1020 strcpy(makestr
, "Unknown");
1023 CFStringGetCString(model
, &modelstr
[1], sizeof(modelstr
)-1,
1024 kCFStringEncodingUTF8
);
1026 strcpy(modelstr
+ 1, "Printer");
1028 optionsstr
[0] = '\0';
1031 CFStringGetCString(serial
, serialstr
, sizeof(serialstr
), kCFStringEncodingUTF8
);
1032 snprintf(optionsstr
, sizeof(optionsstr
), "?serial=%s", serialstr
);
1034 else if (deviceLocation
!= 0)
1035 snprintf(optionsstr
, sizeof(optionsstr
), "?location=%x", (unsigned)deviceLocation
);
1037 httpAssembleURI(HTTP_URI_CODING_ALL
, uristr
, sizeof(uristr
), "usb", NULL
, makestr
, 0, modelstr
);
1038 strncat(uristr
, optionsstr
, sizeof(uristr
));
1041 * Fix common HP 1284 bug...
1044 if (!strcasecmp(makestr
, "Hewlett-Packard"))
1045 strcpy(makestr
, "HP");
1047 if (!strncasecmp(modelstr
+ 1, "hp ", 3))
1048 _cups_strcpy(modelstr
+ 1, modelstr
+ 4);
1050 printf("direct %s \"%s %s\" \"%s %s USB\" \"%s\"\n", uristr
, makestr
,
1051 &modelstr
[1], makestr
, &modelstr
[1], idstr
);
1053 release_deviceinfo(&make
, &model
, &serial
);
1054 CFRelease(deviceIDString
);
1063 * 'find_device_cb()' - print_device iterator callback.
1066 static Boolean
find_device_cb(void *refcon
,
1069 Boolean keepLooking
= true;
1073 CFStringRef idString
= NULL
;
1074 UInt32 location
= -1;
1075 UInt8 interfaceNum
= 0;
1077 copy_devicestring(obj
, &idString
, &location
, &interfaceNum
);
1078 if (idString
!= NULL
)
1080 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1082 copy_deviceinfo(idString
, &make
, &model
, &serial
);
1083 if (make
&& CFStringCompare(make
, g
.make
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1085 if (model
&& CFStringCompare(model
, g
.model
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1087 if (g
.serial
!= NULL
&& CFStringGetLength(g
.serial
) > 0)
1089 if (serial
!= NULL
&& CFStringCompare(serial
, g
.serial
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1091 IOObjectRetain(obj
);
1092 g
.printer_obj
= obj
;
1093 keepLooking
= false;
1098 if (g
.printer_obj
!= 0)
1099 IOObjectRelease(g
.printer_obj
);
1101 g
.printer_obj
= obj
;
1102 IOObjectRetain(obj
);
1104 if (g
.location
== 0 || g
.location
== location
)
1105 keepLooking
= false;
1108 g
.interfaceNum
= interfaceNum
;
1112 release_deviceinfo(&make
, &model
, &serial
);
1113 CFRelease(idString
);
1118 keepLooking
= (g
.printer_obj
== 0);
1119 if (obj
== 0x0 && keepLooking
)
1121 CFRunLoopTimerContext context
= { 0, refcon
, NULL
, NULL
, NULL
};
1122 CFRunLoopTimerRef timer
= CFRunLoopTimerCreate(NULL
, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb
, &context
);
1125 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer
, kCFRunLoopDefaultMode
);
1126 g
.status_timer
= timer
;
1131 if (!keepLooking
&& g
.status_timer
!= NULL
)
1133 fputs("STATE: -offline-error\n", stderr
);
1134 _cupsLangPuts(stderr
, _("INFO: Printer is now on-line.\n"));
1135 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g
.status_timer
, kCFRunLoopDefaultMode
);
1136 CFRelease(g
.status_timer
);
1137 g
.status_timer
= NULL
;
1145 * 'status_timer_cb()' - Status timer callback.
1148 static void status_timer_cb(CFRunLoopTimerRef timer
,
1151 fputs("STATE: +offline-error\n", stderr
);
1152 _cupsLangPuts(stderr
, _("INFO: Printer is currently off-line.\n"));
1158 * 'copy_deviceinfo()' - Copy strings from the 1284 device ID.
1161 static void copy_deviceinfo(CFStringRef deviceIDString
,
1164 CFStringRef
*serial
)
1166 CFStringRef modelKeys
[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL
};
1167 CFStringRef makeKeys
[] = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL
};
1168 CFStringRef serialKeys
[] = { CFSTR("SN:"), CFSTR("SERN:"), NULL
};
1171 *make
= copy_value_for_key(deviceIDString
, makeKeys
);
1173 *model
= copy_value_for_key(deviceIDString
, modelKeys
);
1175 *serial
= copy_value_for_key(deviceIDString
, serialKeys
);
1180 * 'release_deviceinfo()' - Release deviceinfo strings.
1183 static void release_deviceinfo(CFStringRef
*make
,
1185 CFStringRef
*serial
)
1187 if (make
!= NULL
&& *make
!= NULL
)
1193 if (model
!= NULL
&& *model
!= NULL
)
1199 if (serial
!= NULL
&& *serial
!= NULL
)
1209 * 'load_classdriver()' - Load a classdriver.
1212 static kern_return_t
load_classdriver(CFStringRef driverPath
,
1213 printer_interface_t intf
,
1214 classdriver_t
***printerDriver
)
1216 kern_return_t kr
= kUSBPrinterClassDeviceNotOpen
;
1217 classdriver_t
**driver
= NULL
;
1218 CFStringRef bundle
= (driverPath
== NULL
? kUSBGenericTOPrinterClassDriver
: driverPath
);
1222 CFURLRef url
= CFURLCreateWithFileSystemPath(NULL
, bundle
, kCFURLPOSIXPathStyle
, true);
1223 CFPlugInRef plugin
= (url
!= NULL
? CFPlugInCreate(NULL
, url
) : NULL
);
1230 CFArrayRef factories
= CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID
, plugin
);
1231 if (factories
!= NULL
&& CFArrayGetCount(factories
) > 0)
1233 CFUUIDRef factoryID
= CFArrayGetValueAtIndex(factories
, 0);
1234 IUnknownVTbl
**iunknown
= CFPlugInInstanceCreate(NULL
, factoryID
, kUSBPrinterClassTypeID
);
1235 if (iunknown
!= NULL
)
1237 kr
= (*iunknown
)->QueryInterface(iunknown
, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID
), (LPVOID
*)&driver
);
1238 if (kr
== kIOReturnSuccess
&& driver
!= NULL
)
1240 classdriver_t
**genericDriver
= NULL
;
1241 if (driverPath
!= NULL
&& CFStringCompare(driverPath
, kUSBGenericTOPrinterClassDriver
, 0) != kCFCompareEqualTo
)
1242 kr
= load_classdriver(NULL
, intf
, &genericDriver
);
1244 if (kr
== kIOReturnSuccess
)
1246 (*driver
)->interface
= intf
;
1247 (*driver
)->Initialize(driver
, genericDriver
);
1249 (*driver
)->plugin
= plugin
;
1250 (*driver
)->interface
= intf
;
1251 *printerDriver
= driver
;
1254 (*iunknown
)->Release(iunknown
);
1256 CFRelease(factories
);
1262 char bundlestr
[1024];
1263 CFStringGetCString(bundle
, bundlestr
, sizeof(bundlestr
), kCFStringEncodingUTF8
);
1264 fprintf(stderr
, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr
, (int)kr
);
1272 * 'unload_classdriver()' - Unload a classdriver.
1275 static kern_return_t
unload_classdriver(classdriver_t
***classdriver
)
1277 if (*classdriver
!= NULL
)
1279 (**classdriver
)->Release(*classdriver
);
1280 *classdriver
= NULL
;
1283 return kIOReturnSuccess
;
1288 * 'load_printerdriver()' - Load vendor's classdriver.
1290 * If driverBundlePath is not NULL on return it is the callers responsbility to release it!
1293 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
)
1295 IOCFPlugInInterface
**iodev
= NULL
;
1298 printer_interface_t intf
;
1301 kr
= IOCreatePlugInInterfaceForService(g
.printer_obj
, kIOUSBInterfaceUserClientTypeID
, kIOCFPlugInInterfaceID
, &iodev
, &score
);
1302 if (kr
== kIOReturnSuccess
)
1304 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*) &intf
)) == noErr
)
1306 *driverBundlePath
= IORegistryEntryCreateCFProperty(g
.printer_obj
, kUSBClassDriverProperty
, NULL
, kNilOptions
);
1308 kr
= load_classdriver(*driverBundlePath
, intf
, &g
.classdriver
);
1310 if (kr
!= kIOReturnSuccess
)
1311 (*intf
)->Release(intf
);
1313 IODestroyPlugInInterface(iodev
);
1320 * 'registry_open()' - Open a connection to the printer.
1323 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
)
1325 g
.bidi_flag
= 0; /* 0=unidirectional */
1327 kern_return_t kr
= load_printerdriver(driverBundlePath
);
1328 if (kr
!= kIOReturnSuccess
)
1331 if (g
.classdriver
!= NULL
)
1333 (*g
.classdriver
)->interfaceNumber
= g
.interfaceNum
;
1334 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolBidirectional
);
1335 if (kr
!= kIOReturnSuccess
|| (*g
.classdriver
)->interface
== NULL
)
1337 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolUnidirectional
);
1338 if (kr
== kIOReturnSuccess
)
1340 if ((*g
.classdriver
)->interface
== NULL
)
1342 (*g
.classdriver
)->Close(g
.classdriver
);
1348 g
.bidi_flag
= 1; /* 1=bidirectional */
1351 if (kr
!= kIOReturnSuccess
)
1352 unload_classdriver(&g
.classdriver
);
1359 * 'registry_close()' - Close the connection to the printer.
1362 static kern_return_t
registry_close()
1364 if (g
.classdriver
!= NULL
)
1365 (*g
.classdriver
)->Close(g
.classdriver
);
1367 unload_classdriver(&g
.classdriver
);
1368 return kIOReturnSuccess
;
1373 * 'copy_deviceid()' - Copy the 1284 device id string.
1376 static OSStatus
copy_deviceid(classdriver_t
**classdriver
,
1377 CFStringRef
*deviceID
)
1379 CFStringRef devID
= NULL
,
1383 deviceSerial
= NULL
;
1385 OSStatus err
= (*classdriver
)->GetDeviceID(classdriver
, &devID
, DEFAULT_TIMEOUT
);
1387 copy_deviceinfo(devID
, &deviceMake
, &deviceModel
, &deviceSerial
);
1389 if (deviceMake
== NULL
|| deviceModel
== NULL
|| deviceSerial
== NULL
)
1391 IOUSBDeviceDescriptor desc
;
1392 iodevice_request_t request
;
1394 request
.requestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
1395 request
.request
= kUSBRqGetDescriptor
;
1396 request
.value
= (kUSBDeviceDesc
<< 8) | 0;
1398 request
.length
= sizeof(desc
);
1399 request
.buffer
= &desc
;
1400 err
= (*classdriver
)->DeviceRequest(classdriver
, &request
, DEFAULT_TIMEOUT
);
1401 if (err
== kIOReturnSuccess
)
1403 CFMutableStringRef newDevID
= CFStringCreateMutable(NULL
, 0);
1405 if (deviceMake
== NULL
)
1407 CFStringRef data
= NULL
;
1408 err
= (*classdriver
)->GetString(classdriver
, desc
.iManufacturer
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1411 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MFG:%@;"), data
);
1416 if (deviceModel
== NULL
)
1418 CFStringRef data
= NULL
;
1419 err
= (*classdriver
)->GetString(classdriver
, desc
.iProduct
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1422 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MDL:%@;"), data
);
1427 if (deviceSerial
== NULL
&& desc
.iSerialNumber
!= 0)
1429 CFStringRef data
= NULL
;
1430 err
= (*classdriver
)->GetString(classdriver
, desc
.iSerialNumber
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1433 CFStringAppendFormat(newDevID
, NULL
, CFSTR("SERN:%@;"), data
);
1440 CFStringAppend(newDevID
, devID
);
1444 *deviceID
= newDevID
;
1451 release_deviceinfo(&deviceMake
, &deviceModel
, &deviceSerial
);
1458 * 'copy_devicestring()' - Copy the 1284 device id string.
1461 static void copy_devicestring(io_service_t usbInterface
,
1462 CFStringRef
*deviceID
,
1463 UInt32
*deviceLocation
,
1464 UInt8
*interfaceNumber
)
1466 IOCFPlugInInterface
**iodev
= NULL
;
1469 printer_interface_t intf
;
1471 classdriver_t
**klassDriver
= NULL
;
1472 CFStringRef driverBundlePath
;
1474 if ((kr
= IOCreatePlugInInterfaceForService(usbInterface
,
1475 kIOUSBInterfaceUserClientTypeID
,
1476 kIOCFPlugInInterfaceID
,
1477 &iodev
, &score
)) == kIOReturnSuccess
)
1479 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*)
1482 (*intf
)->GetLocationID(intf
, deviceLocation
);
1483 (*intf
)->GetInterfaceNumber(intf
, interfaceNumber
);
1485 driverBundlePath
= IORegistryEntryCreateCFProperty(usbInterface
,
1486 kUSBClassDriverProperty
,
1489 kr
= load_classdriver(driverBundlePath
, intf
, &klassDriver
);
1491 if (kr
!= kIOReturnSuccess
&& driverBundlePath
!= NULL
)
1492 kr
= load_classdriver(NULL
, intf
, &klassDriver
);
1494 if (kr
== kIOReturnSuccess
&& klassDriver
!= NULL
)
1495 kr
= copy_deviceid(klassDriver
, deviceID
);
1497 unload_classdriver(&klassDriver
);
1499 if (driverBundlePath
!= NULL
)
1500 CFRelease(driverBundlePath
);
1502 /* (*intf)->Release(intf); */
1504 IODestroyPlugInInterface(iodev
);
1511 * 'copy_value_for_key()' - Copy value string associated with a key.
1514 static CFStringRef
copy_value_for_key(CFStringRef deviceID
,
1517 CFStringRef value
= NULL
;
1518 CFArrayRef kvPairs
= deviceID
!= NULL
? CFStringCreateArrayBySeparatingStrings(NULL
, deviceID
, CFSTR(";")) : NULL
;
1519 CFIndex max
= kvPairs
!= NULL
? CFArrayGetCount(kvPairs
) : 0;
1522 while (idx
< max
&& value
== NULL
)
1524 CFStringRef kvpair
= CFArrayGetValueAtIndex(kvPairs
, idx
);
1526 while (keys
[idxx
] != NULL
&& value
== NULL
)
1528 CFRange range
= CFStringFind(kvpair
, keys
[idxx
], kCFCompareCaseInsensitive
);
1529 if (range
.length
!= -1)
1531 if (range
.location
!= 0)
1533 CFMutableStringRef theString
= CFStringCreateMutableCopy(NULL
, 0, kvpair
);
1534 CFStringTrimWhitespace(theString
);
1535 range
= CFStringFind(theString
, keys
[idxx
], kCFCompareCaseInsensitive
);
1536 if (range
.location
== 0)
1537 value
= CFStringCreateWithSubstring(NULL
, theString
, CFRangeMake(range
.length
, CFStringGetLength(theString
) - range
.length
));
1539 CFRelease(theString
);
1543 CFStringRef theString
= CFStringCreateWithSubstring(NULL
, kvpair
, CFRangeMake(range
.length
, CFStringGetLength(kvpair
) - range
.length
));
1544 CFMutableStringRef theString2
= CFStringCreateMutableCopy(NULL
, 0, theString
);
1545 CFRelease(theString
);
1547 CFStringTrimWhitespace(theString2
);
1556 if (kvPairs
!= NULL
)
1563 * 'cfstr_create_trim()' - Create CFString and trim whitespace characters.
1566 CFStringRef
cfstr_create_trim(const char *cstr
)
1569 CFMutableStringRef cfmutablestr
= NULL
;
1571 if ((cfstr
= CFStringCreateWithCString(NULL
, cstr
, kCFStringEncodingUTF8
)) != NULL
)
1573 if ((cfmutablestr
= CFStringCreateMutableCopy(NULL
, 1024, cfstr
)) != NULL
)
1574 CFStringTrimWhitespace(cfmutablestr
);
1578 return (CFStringRef
) cfmutablestr
;
1584 * 'parse_options()' - Parse URI options.
1587 static void parse_options(char *options
,
1593 char sep
, /* Separator character */
1594 *name
, /* Name of option */
1595 *value
; /* Value of option */
1614 while (*options
&& *options
!= '=' && *options
!= '+' && *options
!= '&')
1617 if ((sep
= *options
) != '\0')
1628 while (*options
&& *options
!= '+' && *options
!= '&')
1638 * Process the option...
1641 if (!strcasecmp(name
, "waiteof"))
1643 if (!strcasecmp(value
, "on") ||
1644 !strcasecmp(value
, "yes") ||
1645 !strcasecmp(value
, "true"))
1647 else if (!strcasecmp(value
, "off") ||
1648 !strcasecmp(value
, "no") ||
1649 !strcasecmp(value
, "false"))
1652 _cupsLangPrintf(stderr
,
1653 _("WARNING: Boolean expected for waiteof option "
1654 "\"%s\"\n"), value
);
1656 else if (!strcasecmp(name
, "serial"))
1657 strlcpy(serial
, value
, serial_size
);
1658 else if (!strcasecmp(name
, "location") && location
)
1659 *location
= strtol(value
, NULL
, 16);
1665 * @function setup_cfLanguage
1666 * @abstract Convert the contents of the CUPS 'LANG' environment
1667 * variable into a one element CF array of languages.
1669 * @discussion Each submitted job comes with a natural language. CUPS passes
1670 * that language in an environment variable. We take that language
1671 * and jam it into the AppleLanguages array so that CF will use
1672 * it when reading localized resources. We need to do this before
1673 * any CF code reads and caches the languages array, so this function
1674 * should be called early in main()
1676 static void setup_cfLanguage(void)
1678 CFStringRef lang
[1] = {NULL
};
1679 CFArrayRef langArray
= NULL
;
1680 const char *requestedLang
= NULL
;
1682 requestedLang
= getenv("LANG");
1683 if (requestedLang
!= NULL
)
1685 lang
[0] = CFStringCreateWithCString(kCFAllocatorDefault
, requestedLang
, kCFStringEncodingUTF8
);
1686 langArray
= CFArrayCreate(kCFAllocatorDefault
, (const void **)lang
, sizeof(lang
) / sizeof(lang
[0]), &kCFTypeArrayCallBacks
);
1688 CFPreferencesSetAppValue(CFSTR("AppleLanguages"), langArray
, kCFPreferencesCurrentApplication
);
1689 DEBUG_printf((stderr
, "DEBUG: usb: AppleLanguages = \"%s\"\n", requestedLang
));
1692 CFRelease(langArray
);
1695 fputs("DEBUG: usb: LANG environment variable missing.\n", stderr
);
1699 #if defined(__i386__)
1701 * @function run_ppc_backend
1703 * @abstract Starts child backend process running as a ppc executable.
1705 * @result Never returns; always calls exit().
1709 static void run_ppc_backend(int argc
,
1716 pid_t waitpid_status
;
1718 char *usb_ppc_status
;
1721 * If we're running as i386 and couldn't load the class driver (because they'it's
1722 * ppc-only) then try to re-exec ourselves in ppc mode to try again. If we don't have
1723 * a ppc architecture we may be running i386 again so guard against this by setting
1724 * and testing an environment variable...
1726 usb_ppc_status
= getenv("USB_PPC_STATUS");
1728 if (usb_ppc_status
== NULL
)
1731 * Setup a SIGTERM handler then block it before forking...
1734 struct sigaction action
; /* POSIX signal action */
1735 sigset_t newmask
, /* New signal mask */
1736 oldmask
; /* Old signal mask */
1738 memset(&action
, 0, sizeof(action
));
1739 sigaddset(&action
.sa_mask
, SIGTERM
);
1740 action
.sa_handler
= sigterm_handler
;
1741 sigaction(SIGTERM
, &action
, NULL
);
1743 sigemptyset(&newmask
);
1744 sigaddset(&newmask
, SIGTERM
);
1745 sigprocmask(SIG_BLOCK
, &newmask
, &oldmask
);
1747 if ((child_pid
= fork()) == 0)
1750 * Child comes here...
1753 setenv("USB_PPC_STATUS", "1", false);
1756 * Unblock signals before doing the exec...
1759 memset(&action
, 0, sizeof(action
));
1760 sigemptyset(&action
.sa_mask
);
1761 action
.sa_handler
= SIG_DFL
;
1762 sigaction(SIGTERM
, &action
, NULL
);
1764 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
1767 * Tell the kernel the next exec call should favor the ppc architecture...
1770 int mib
[] = { CTL_KERN
, KERN_AFFINITY
, 1, 1 };
1772 sysctl(mib
, namelen
, NULL
, NULL
, NULL
, 0);
1775 * Set up the arguments and call exec...
1778 for (i
= 0; i
< argc
&& i
< (sizeof(my_argv
)/sizeof(my_argv
[0])) - 1; i
++)
1779 my_argv
[i
] = argv
[i
];
1783 execv("/usr/libexec/cups/backend/usb", my_argv
);
1785 perror("/usr/libexec/cups/backend/usb");
1788 else if (child_pid
< 0)
1791 * Error - couldn't fork a new process!
1799 * Unblock signals...
1802 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
1805 * Close the fds we won't be using then wait for the child backend to exit.
1811 fprintf(stderr
, "DEBUG: Started usb(ppc) backend (PID %d)\n", (int)child_pid
);
1813 while ((waitpid_status
= waitpid(child_pid
, &childstatus
, 0)) == (pid_t
)-1 && errno
== EINTR
)
1816 if (WIFSIGNALED(childstatus
))
1818 exitstatus
= WTERMSIG(childstatus
);
1819 fprintf(stderr
, "DEBUG: usb(ppc) backend %d crashed on signal %d!\n", child_pid
, exitstatus
);
1823 if ((exitstatus
= WEXITSTATUS(childstatus
)) != 0)
1824 fprintf(stderr
, "DEBUG: usb(ppc) backend %d stopped with status %d!\n", child_pid
, exitstatus
);
1826 fprintf(stderr
, "DEBUG: PID %d exited with no errors\n", child_pid
);
1831 fputs("DEBUG: usb child running i386 again\n", stderr
);
1832 exitstatus
= ENOENT
;
1839 * 'sigterm_handler()' - SIGTERM handler.
1842 static void sigterm_handler(int sig
)
1844 /* If we started a child process pass the signal on to it...
1847 kill(child_pid
, sig
);
1852 #endif /* __i386__ */
1855 #ifdef PARSE_PS_ERRORS
1857 * 'next_line()' - Find the next line in a buffer.
1860 static const char *next_line (const char *buffer
)
1862 const char *cptr
, *lptr
= NULL
;
1864 for (cptr
= buffer
; *cptr
&& lptr
== NULL
; cptr
++)
1865 if (*cptr
== '\n' || *cptr
== '\r')
1872 * 'parse_pserror()' - Scan the backchannel data for postscript errors.
1875 static void parse_pserror(char *sockBuffer
,
1878 static char gErrorBuffer
[1024] = "";
1879 static char *gErrorBufferPtr
= gErrorBuffer
;
1880 static char *gErrorBufferEndPtr
= gErrorBuffer
+ sizeof(gErrorBuffer
);
1882 char *pCommentBegin
, *pCommentEnd
, *pLineEnd
;
1887 if (gErrorBufferPtr
+ len
> gErrorBufferEndPtr
- 1)
1888 gErrorBufferPtr
= gErrorBuffer
;
1889 if (len
> sizeof(gErrorBuffer
) - 1)
1890 len
= sizeof(gErrorBuffer
) - 1;
1892 memcpy(gErrorBufferPtr
, (const void *)sockBuffer
, len
);
1893 gErrorBufferPtr
+= len
;
1894 *(gErrorBufferPtr
+ 1) = '\0';
1896 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
1897 while (pLineEnd
!= NULL
)
1901 pCommentBegin
= strstr(gErrorBuffer
,"%%[");
1902 pCommentEnd
= strstr(gErrorBuffer
, "]%%");
1903 if (pCommentBegin
!= gErrorBuffer
&& pCommentEnd
!= NULL
)
1905 pCommentEnd
+= 3; /* Skip past "]%%" */
1906 *pCommentEnd
= '\0'; /* There's always room for the nul */
1908 if (strncasecmp(pCommentBegin
, "%%[ Error:", 10) == 0)
1910 else if (strncasecmp(pCommentBegin
, "%%[ Flushing", 12) == 0)
1915 if ((logstrlen
= snprintf(logstr
, sizeof(logstr
), "%s: %s\n", logLevel
, pCommentBegin
)) >= sizeof(logstr
))
1917 /* If the string was trucnated make sure it has a linefeed before the nul */
1918 logstrlen
= sizeof(logstr
) - 1;
1919 logstr
[logstrlen
- 1] = '\n';
1921 write(STDERR_FILENO
, logstr
, logstrlen
);
1924 /* move everything over... */
1925 strcpy(gErrorBuffer
, pLineEnd
);
1926 gErrorBufferPtr
= gErrorBuffer
;
1927 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
1930 #endif /* PARSE_PS_ERRORS */
1934 * 'soft_reset()' - Send a soft reset to the device.
1937 static void soft_reset()
1939 fd_set input_set
; /* Input set for select() */
1940 struct timeval stimeout
; /* Timeout for select() */
1941 char buffer
[2048]; /* Buffer */
1942 struct timespec cond_timeout
; /* pthread condition timeout */
1945 * Send an abort once a second until the I/O lock is released by the main thread...
1948 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
1949 while (g
.readwrite_lock
)
1951 (*g
.classdriver
)->Abort(g
.classdriver
);
1953 cond_timeout
.tv_sec
= time(NULL
) + 1;
1954 cond_timeout
.tv_nsec
= 0;
1956 pthread_cond_timedwait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
, &cond_timeout
);
1959 g
.readwrite_lock
= 1;
1960 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
1963 * Flush bytes waiting on print_fd...
1968 FD_ZERO(&input_set
);
1969 FD_SET(g
.print_fd
, &input_set
);
1971 stimeout
.tv_sec
= 0;
1972 stimeout
.tv_usec
= 0;
1974 while (select(g
.print_fd
+1, &input_set
, NULL
, NULL
, &stimeout
) > 0)
1975 if (read(g
.print_fd
, buffer
, sizeof(buffer
)) <= 0)
1982 (*g
.classdriver
)->SoftReset(g
.classdriver
, DEFAULT_TIMEOUT
);
1985 * Release the I/O lock...
1988 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
1989 g
.readwrite_lock
= 0;
1990 pthread_cond_signal(&g
.readwrite_lock_cond
);
1991 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
1996 * 'get_device_id()' - Return IEEE-1284 device ID.
1999 static void get_device_id(cups_sc_status_t
*status
,
2003 UInt32 deviceLocation
= 0;
2004 UInt8 interfaceNum
= 0;
2005 CFStringRef deviceIDString
= NULL
;
2008 copy_devicestring(g
.printer_obj
, &deviceIDString
, &deviceLocation
, &interfaceNum
);
2011 CFStringGetCString(deviceIDString
, data
, *datalen
, kCFStringEncodingUTF8
);
2012 *datalen
= strlen(data
);
2013 CFRelease(deviceIDString
);
2015 *status
= CUPS_SC_STATUS_OK
;
2020 * End of "$Id: usb-darwin.c 6993 2007-09-28 18:05:28Z mike $".