2 * "$Id: usb-darwin.c 6591 2007-06-21 20:35: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 DEFAULT_TIMEOUT 60L
109 #define USB_INTERFACE_KIND CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID190)
110 #define kUSBLanguageEnglish 0x409
112 #define PRINTER_POLLING_INTERVAL 5 /* seconds */
113 #define INITIAL_LOG_INTERVAL PRINTER_POLLING_INTERVAL
114 #define SUBSEQUENT_LOG_INTERVAL 3 * INITIAL_LOG_INTERVAL
116 #define kUSBPrinterClassTypeID CFUUIDGetConstantUUIDWithBytes(NULL, 0x06, 0x04, 0x7D, 0x16, 0x53, 0xA2, 0x11, 0xD6, 0x92, 0x06, 0x00, 0x30, 0x65, 0x52, 0x45, 0x92)
117 #define kUSBPrinterClassInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, 0x03, 0x34, 0x6D, 0x74, 0x53, 0xA3, 0x11, 0xD6, 0x9E, 0xA1, 0x76, 0x30, 0x65, 0x52, 0x45, 0x92)
119 #define kUSBClassDriverProperty CFSTR("USB Printing Class")
121 #define kUSBGenericTOPrinterClassDriver CFSTR("/System/Library/Printers/Libraries/USBGenericTOPrintingClass.plugin")
122 #define kUSBPrinterClassDeviceNotOpen -9664 /*kPMInvalidIOMContext*/
126 * Section 5.3 USB Printing Class spec
128 #define kUSBPrintingSubclass 1
129 #define kUSBPrintingProtocolNoOpen 0
130 #define kUSBPrintingProtocolUnidirectional 1
131 #define kUSBPrintingProtocolBidirectional 2
133 typedef IOUSBInterfaceInterface190
**printer_interface_t
;
135 typedef struct iodevice_request_s
/**** Device request ****/
143 } iodevice_request_t
;
145 typedef union /**** Centronics status byte ****/
150 unsigned reserved0
:2;
151 unsigned paperError
:1;
154 unsigned reserved1
:3;
156 } centronics_status_t
;
158 typedef struct classdriver_s
/**** g.classdriver context ****/
161 CFPlugInRef plugin
; /* release plugin */
162 IUnknownVTbl
**factory
; /* Factory */
163 void *vendorReference
; /* vendor class specific usage */
164 UInt32 location
; /* unique location in bus topology */
165 UInt8 interfaceNumber
; /* Interface number */
166 UInt16 vendorID
; /* Vendor id */
167 UInt16 productID
; /* Product id */
168 printer_interface_t interface
; /* identify the device to IOKit */
169 UInt8 outpipe
; /* mandatory bulkOut pipe */
170 UInt8 inpipe
; /* optional bulkIn pipe */
172 /* general class requests */
173 kern_return_t (*DeviceRequest
)(struct classdriver_s
**printer
, iodevice_request_t
*iorequest
, UInt16 timeout
);
174 kern_return_t (*GetString
)(struct classdriver_s
**printer
, UInt8 whichString
, UInt16 language
, UInt16 timeout
, CFStringRef
*result
);
176 /* standard printer class requests */
177 kern_return_t (*SoftReset
)(struct classdriver_s
**printer
, UInt16 timeout
);
178 kern_return_t (*GetCentronicsStatus
)(struct classdriver_s
**printer
, centronics_status_t
*result
, UInt16 timeout
);
179 kern_return_t (*GetDeviceID
)(struct classdriver_s
**printer
, CFStringRef
*devid
, UInt16 timeout
);
181 /* standard bulk device requests */
182 kern_return_t (*ReadPipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
);
183 kern_return_t (*WritePipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
, Boolean eoj
);
185 /* interface requests */
186 kern_return_t (*Open
)(struct classdriver_s
**printer
, UInt32 location
, UInt8 protocol
);
187 kern_return_t (*Abort
)(struct classdriver_s
**printer
);
188 kern_return_t (*Close
)(struct classdriver_s
**printer
);
190 /* initialize and terminate */
191 kern_return_t (*Initialize
)(struct classdriver_s
**printer
, struct classdriver_s
**baseclass
);
192 kern_return_t (*Terminate
)(struct classdriver_s
**printer
);
196 typedef Boolean (*iterator_callback_t
)(void *refcon
, io_service_t obj
);
198 typedef struct iterator_reference_s
/**** Iterator reference data */
200 iterator_callback_t callback
;
203 } iterator_reference_t
;
205 typedef struct globals_s
207 io_service_t printer_obj
;
208 classdriver_t
**classdriver
;
210 pthread_mutex_t read_thread_mutex
;
211 pthread_cond_t read_thread_cond
;
212 int read_thread_stop
;
213 int read_thread_done
;
215 pthread_mutex_t readwrite_lock_mutex
;
216 pthread_cond_t readwrite_lock_cond
;
224 CFRunLoopTimerRef status_timer
;
226 int print_fd
; /* File descriptor to print */
227 ssize_t print_bytes
; /* Print bytes read */
230 int drain_output
; /* Drain all pending output */
231 int bidi_flag
; /* 0=unidirectional, 1=bidirectional */
239 globals_t g
= { 0 }; /* Globals */
246 static Boolean
find_device_cb(void *refcon
, io_service_t obj
);
247 static Boolean
list_device_cb(void *refcon
, io_service_t obj
);
248 static CFStringRef
cfstr_create_trim(const char *cstr
);
249 static CFStringRef
copy_value_for_key(CFStringRef deviceID
, CFStringRef
*keys
);
250 static kern_return_t
load_classdriver(CFStringRef driverPath
, printer_interface_t intf
, classdriver_t
***printerDriver
);
251 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
);
252 static kern_return_t
registry_close();
253 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
);
254 static kern_return_t
unload_classdriver();
255 static OSStatus
copy_deviceid(classdriver_t
**printer
, CFStringRef
*deviceID
);
256 static void *read_thread(void *reference
);
257 static void *sidechannel_thread(void *reference
);
258 static void copy_deviceinfo(CFStringRef deviceIDString
, CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
259 static void copy_devicestring(io_service_t usbInterface
, CFStringRef
*deviceID
, UInt32
*deviceLocation
);
260 static void device_added(void *userdata
, io_iterator_t iterator
);
261 static void get_device_id(cups_sc_status_t
*status
, char *data
, int *datalen
);
262 static void iterate_printers(iterator_callback_t callBack
, void *userdata
);
263 static void parse_options(const char *options
, char *serial
, UInt32
*location
, Boolean
*wait_eof
);
264 static void release_deviceinfo(CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
265 static void setup_cfLanguage(void);
266 static void soft_reset();
267 static void status_timer_cb(CFRunLoopTimerRef timer
, void *info
);
269 #if defined(__i386__)
270 static pid_t child_pid
; /* Child PID */
271 static void run_ppc_backend(int argc
, char *argv
[], int fd
); /* Starts child backend process running as a ppc executable */
272 static void sigterm_handler(int sig
); /* SIGTERM handler */
273 #endif /* __i386__ */
275 #ifdef PARSE_PS_ERRORS
276 static const char *next_line (const char *buffer
);
277 static void parse_pserror (char *sockBuffer
, int len
);
278 #endif /* PARSE_PS_ERRORS */
283 * 'list_devices()' - List all USB devices.
288 iterate_printers(list_device_cb
, NULL
);
293 * 'print_device()' - Print a file to a USB device.
296 int /* O - Exit status */
297 print_device(const char *uri
, /* I - Device URI */
298 const char *hostname
, /* I - Hostname/manufacturer */
299 const char *resource
, /* I - Resource/modelname */
300 const char *options
, /* I - Device options/serial number */
301 int print_fd
, /* I - File descriptor to print */
302 int copies
, /* I - Copies to print */
303 int argc
, /* I - Number of command-line arguments (6 or 7) */
304 char *argv
[]) /* I - Command-line arguments */
306 char serial
[1024]; /* Serial number buffer */
307 OSStatus status
; /* Function results */
308 pthread_t read_thread_id
, /* Read thread */
309 sidechannel_thread_id
;/* Side channel thread */
310 char print_buffer
[8192], /* Print data buffer */
311 *print_ptr
; /* Pointer into print data buffer */
312 UInt32 location
; /* Unique location in bus topology */
313 fd_set input_set
; /* Input set for select() */
314 CFStringRef driverBundlePath
; /* Class driver path */
315 int countdown
, /* Logging interval */
316 nfds
; /* Number of file descriptors */
317 ssize_t total_bytes
; /* Total bytes written */
318 UInt32 bytes
; /* Bytes written */
319 struct timeval
*timeout
, /* Timeout pointer */
320 stimeout
; /* Timeout for select() */
321 struct timespec cond_timeout
; /* pthread condition timeout */
325 parse_options(options
, serial
, &location
, &g
.wait_eof
);
327 if (resource
[0] == '/')
330 g
.print_fd
= print_fd
;
331 g
.make
= cfstr_create_trim(hostname
);
332 g
.model
= cfstr_create_trim(resource
);
333 g
.serial
= cfstr_create_trim(serial
);
334 g
.location
= location
;
336 fputs("STATE: +connecting-to-device\n", stderr
);
338 countdown
= INITIAL_LOG_INTERVAL
;
344 IOObjectRelease(g
.printer_obj
);
345 unload_classdriver(&g
.classdriver
);
350 fprintf(stderr
, "DEBUG: Looking for '%s %s'\n", hostname
, resource
);
352 iterate_printers(find_device_cb
, NULL
);
354 fputs("DEBUG: Opening connection\n", stderr
);
356 driverBundlePath
= NULL
;
358 status
= registry_open(&driverBundlePath
);
360 #if defined(__i386__)
362 * If we were unable to load the class drivers for this printer it's probably because they're ppc-only.
363 * In this case try to fork & exec this backend as a ppc executable so we can use them...
367 run_ppc_backend(argc
, argv
, print_fd
);
368 /* Never returns here */
370 #endif /* __i386__ */
375 * If we still were unable to load the class drivers for this printer log
376 * the error and stop the queue...
379 if (driverBundlePath
== NULL
|| !CFStringGetCString(driverBundlePath
, print_buffer
, sizeof(print_buffer
), kCFStringEncodingUTF8
))
380 strlcpy(print_buffer
, "USB class driver", sizeof(print_buffer
));
382 fputs("STATE: +apple-missing-usbclassdriver-error\n", stderr
);
383 fprintf(stderr
, _("FATAL: Could not load %s\n"), print_buffer
);
385 if (driverBundlePath
)
386 CFRelease(driverBundlePath
);
388 return CUPS_BACKEND_STOP
;
391 if (driverBundlePath
)
392 CFRelease(driverBundlePath
);
396 sleep(PRINTER_POLLING_INTERVAL
);
397 countdown
-= PRINTER_POLLING_INTERVAL
;
400 fprintf(stderr
, _("INFO: Printer busy (status:0x%08x)\n"), (int)status
);
401 countdown
= SUBSEQUENT_LOG_INTERVAL
; /* subsequent log entries, every 15 seconds */
404 } while (status
!= noErr
);
406 fputs("STATE: -connecting-to-device\n", stderr
);
409 * Now that we are "connected" to the port, ignore SIGTERM so that we
410 * can finish out any page data the driver sends (e.g. to eject the
411 * current page... Only ignore SIGTERM if we are printing data from
412 * stdin (otherwise you can't cancel raw jobs...)
417 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
418 sigset(SIGTERM
, SIG_IGN
);
419 #elif defined(HAVE_SIGACTION)
420 memset(&action
, 0, sizeof(action
));
422 sigemptyset(&action
.sa_mask
);
423 action
.sa_handler
= SIG_IGN
;
424 sigaction(SIGTERM
, &action
, NULL
);
426 signal(SIGTERM
, SIG_IGN
);
427 #endif /* HAVE_SIGSET */
431 * Start the side channel thread only if the descriptor is valid
432 * (i.e. it's not when the backend is used for auto-setup)...
435 pthread_mutex_init(&g
.readwrite_lock_mutex
, NULL
);
436 pthread_cond_init(&g
.readwrite_lock_cond
, NULL
);
437 g
.readwrite_lock
= 1;
440 FD_SET(CUPS_SC_FD
, &input_set
);
443 stimeout
.tv_usec
= 0;
445 if ((select(CUPS_SC_FD
+1, &input_set
, NULL
, NULL
, &stimeout
)) >= 0)
447 if (pthread_create(&sidechannel_thread_id
, NULL
, sidechannel_thread
, NULL
))
449 fputs(_("WARNING: Couldn't create side channel\n"), stderr
);
450 return CUPS_BACKEND_STOP
;
455 * Get the read thread going...
458 g
.read_thread_stop
= 0;
459 g
.read_thread_done
= 0;
461 pthread_cond_init(&g
.read_thread_cond
, NULL
);
462 pthread_mutex_init(&g
.read_thread_mutex
, NULL
);
464 if (pthread_create(&read_thread_id
, NULL
, read_thread
, NULL
))
466 fputs(_("WARNING: Couldn't create read channel\n"), stderr
);
467 return CUPS_BACKEND_STOP
;
471 * The main thread sends the print file...
477 print_ptr
= print_buffer
;
479 while (status
== noErr
&& copies
-- > 0)
481 fputs(_("INFO: Sending data\n"), stderr
);
483 if (print_fd
!= STDIN_FILENO
)
485 fputs("PAGE: 1 1", stderr
);
486 lseek(print_fd
, 0, SEEK_SET
);
489 while (status
== noErr
)
494 FD_SET(print_fd
, &input_set
);
497 * Calculate select timeout...
498 * If we have data waiting to send timeout is 100ms.
499 * else if we're draining print_fd timeout is 0.
500 * else we're waiting forever...
506 stimeout
.tv_usec
= 100000; /* 100ms */
509 else if (g
.drain_output
)
512 stimeout
.tv_usec
= 0;
519 * I/O is unlocked around select...
522 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
523 g
.readwrite_lock
= 0;
524 pthread_cond_signal(&g
.readwrite_lock_cond
);
525 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
527 nfds
= select(print_fd
+ 1, &input_set
, NULL
, NULL
, timeout
);
530 * Reacquire the lock...
533 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
534 while (g
.readwrite_lock
)
535 pthread_cond_wait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
);
536 g
.readwrite_lock
= 1;
537 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
541 if (errno
== EINTR
&& total_bytes
== 0)
543 fputs("DEBUG: Received an interrupt before any bytes were "
544 "written, aborting!\n", stderr
);
547 else if (errno
!= EAGAIN
)
549 fprintf(stderr
, _("ERROR: select() returned %d\n"), (int)errno
);
550 return CUPS_BACKEND_STOP
;
555 * If drain output has finished send a response...
558 if (g
.drain_output
&& !nfds
&& !g
.print_bytes
)
560 /* Send a response... */
561 cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
566 * Check if we have print data ready...
569 if (FD_ISSET(print_fd
, &input_set
))
571 g
.print_bytes
= read(print_fd
, print_buffer
, sizeof(print_buffer
));
573 if (g
.print_bytes
< 0)
576 * Read error - bail if we don't see EAGAIN or EINTR...
579 if (errno
!= EAGAIN
|| errno
!= EINTR
)
581 perror("ERROR: Unable to read print data");
582 return CUPS_BACKEND_STOP
;
587 else if (g
.print_bytes
== 0)
590 * End of file, break out of the loop...
596 print_ptr
= print_buffer
;
598 fprintf(stderr
, "DEBUG: Read %d bytes of print data...\n",
604 bytes
= g
.print_bytes
;
606 status
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
609 * Ignore timeout errors...
612 if (status
== kIOUSBTransactionTimeout
)
618 if (status
|| bytes
< 0)
621 * Write error - bail if we don't see an error we can retry...
624 OSStatus err
= (*g
.classdriver
)->Abort(g
.classdriver
);
625 fprintf(stderr
, _("ERROR: %ld: (canceled:%ld)\n"), (long)status
, (long)err
);
626 return CUPS_BACKEND_STOP
;
629 fprintf(stderr
, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes
);
631 g
.print_bytes
-= bytes
;
633 total_bytes
+= bytes
;
636 if (print_fd
!= 0 && status
== noErr
)
637 fprintf(stderr
, "DEBUG: Sending print file, %lld bytes...\n",
642 fprintf(stderr
, "DEBUG: Sent %lld bytes...\n", (off_t
)total_bytes
);
645 * Wait for the side channel thread to exit...
649 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
650 g
.readwrite_lock
= 0;
651 pthread_cond_signal(&g
.readwrite_lock_cond
);
652 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
654 pthread_join(sidechannel_thread_id
, NULL
);
656 pthread_cond_destroy(&g
.readwrite_lock_cond
);
657 pthread_mutex_destroy(&g
.readwrite_lock_mutex
);
660 * Signal the read thread to stop...
663 g
.read_thread_stop
= 1;
666 * Give the read thread WAIT_EOF_DELAY seconds to complete all the data. If
667 * we are not signaled in that time then force the thread to exit by setting
668 * the waiteof to be false. Plese note that this relies on us using the timeout
672 pthread_mutex_lock(&g
.read_thread_mutex
);
674 if (!g
.read_thread_done
)
676 cond_timeout
.tv_sec
= time(NULL
) + WAIT_EOF_DELAY
;
677 cond_timeout
.tv_nsec
= 0;
679 if (pthread_cond_timedwait(&g
.read_thread_cond
, &g
.read_thread_mutex
, &cond_timeout
) != 0)
682 pthread_mutex_unlock(&g
.read_thread_mutex
);
684 pthread_join(read_thread_id
, NULL
); /* wait for the read thread to return */
686 pthread_cond_destroy(&g
.read_thread_cond
);
687 pthread_mutex_destroy(&g
.read_thread_mutex
);
690 * Close the connection and input file and general clean up...
695 if (print_fd
!= STDIN_FILENO
)
704 if (g
.serial
!= NULL
)
707 if (g
.printer_obj
!= 0x0)
708 IOObjectRelease(g
.printer_obj
);
715 * 'read_thread()' - Thread to read the backchannel data on.
718 static void *read_thread(void *reference
)
720 UInt8 readbuffer
[512];
722 kern_return_t readstatus
;
723 struct mach_timebase_info timeBaseInfo
;
727 /* Calculate what 250 milliSeconds are in mach absolute time...
729 mach_timebase_info(&timeBaseInfo
);
730 delay
= ((uint64_t)250000000 * (uint64_t)timeBaseInfo
.denom
) / (uint64_t)timeBaseInfo
.numer
;
735 * Remember when we started so we can throttle the loop after the read call...
738 start
= mach_absolute_time();
740 rbytes
= sizeof(readbuffer
);
741 readstatus
= (*g
.classdriver
)->ReadPipe(g
.classdriver
, readbuffer
, &rbytes
);
742 if (readstatus
== kIOReturnSuccess
&& rbytes
> 0)
744 cupsBackChannelWrite((char*)readbuffer
, rbytes
, 1.0);
746 /* cntrl-d is echoed by the printer.
748 * Xerox Phaser 6250D doesn't echo the cntrl-d.
749 * Xerox Phaser 6250D doesn't always send the product query.
751 if (g
.wait_eof
&& readbuffer
[rbytes
-1] == 0x4)
754 #ifdef PARSE_PS_ERRORS
755 parse_pserror(readbuffer
, rbytes
);
760 * Make sure this loop executes no more than once every 250 miliseconds...
763 if ((readstatus
!= kIOReturnSuccess
|| rbytes
== 0) && (g
.wait_eof
|| !g
.read_thread_stop
))
764 mach_wait_until(start
+ delay
);
766 } while (g
.wait_eof
|| !g
.read_thread_stop
); /* Abort from main thread tests error here */
769 * Let the main thread know that we have completed the read thread...
772 pthread_mutex_lock(&g
.read_thread_mutex
);
773 g
.read_thread_done
= 1;
774 pthread_cond_signal(&g
.read_thread_cond
);
775 pthread_mutex_unlock(&g
.read_thread_mutex
);
782 * 'sidechannel_thread()' - Handle side-channel requests.
786 sidechannel_thread(void *reference
)
788 cups_sc_command_t command
; /* Request command */
789 cups_sc_status_t status
; /* Request/response status */
790 char data
[2048]; /* Request/response data */
791 int datalen
; /* Request/response data size */
795 datalen
= sizeof(data
);
797 if (cupsSideChannelRead(&command
, &status
, data
, &datalen
, 1.0))
802 case CUPS_SC_CMD_SOFT_RESET
: /* Do a soft reset */
804 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
807 case CUPS_SC_CMD_DRAIN_OUTPUT
: /* Drain all pending output */
811 case CUPS_SC_CMD_GET_BIDI
: /* Is the connection bidirectional? */
812 data
[0] = g
.bidi_flag
;
813 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
816 case CUPS_SC_CMD_GET_DEVICE_ID
: /* Return IEEE-1284 device ID */
817 datalen
= sizeof(data
);
818 get_device_id(&status
, data
, &datalen
);
819 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, datalen
, 1.0);
822 case CUPS_SC_CMD_GET_STATE
: /* Return device state */
823 data
[0] = CUPS_SC_STATE_ONLINE
;
824 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
828 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
839 * 'iterate_printers()' - Iterate over all the printers.
842 static void iterate_printers(iterator_callback_t callBack
,
845 mach_port_t masterPort
= 0x0;
846 kern_return_t kr
= IOMasterPort (bootstrap_port
, &masterPort
);
848 if (kr
== kIOReturnSuccess
&& masterPort
!= 0x0)
850 io_iterator_t addIterator
= 0x0;
852 iterator_reference_t reference
= { callBack
, userdata
, true };
853 IONotificationPortRef addNotification
= IONotificationPortCreate(masterPort
);
855 int klass
= kUSBPrintingClass
;
856 int subklass
= kUSBPrintingSubclass
;
858 CFNumberRef usb_klass
= CFNumberCreate(NULL
, kCFNumberIntType
, &klass
);
859 CFNumberRef usb_subklass
= CFNumberCreate(NULL
, kCFNumberIntType
, &subklass
);
860 CFMutableDictionaryRef usbPrinterMatchDictionary
= IOServiceMatching(kIOUSBInterfaceClassName
);
862 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceClass"), usb_klass
);
863 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceSubClass"), usb_subklass
);
865 CFRelease(usb_klass
);
866 CFRelease(usb_subklass
);
868 kr
= IOServiceAddMatchingNotification(addNotification
, kIOMatchedNotification
, usbPrinterMatchDictionary
, &device_added
, &reference
, &addIterator
);
869 if (addIterator
!= 0x0)
871 device_added (&reference
, addIterator
);
873 if (reference
.keepRunning
)
875 CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification
), kCFRunLoopDefaultMode
);
878 IOObjectRelease(addIterator
);
880 mach_port_deallocate(mach_task_self(), masterPort
);
886 * 'device_added()' - Device added notifier.
889 static void device_added(void *userdata
,
890 io_iterator_t iterator
)
892 iterator_reference_t
*reference
= userdata
;
895 while (reference
->keepRunning
&& (obj
= IOIteratorNext(iterator
)) != 0x0)
897 if (reference
->callback
!= NULL
)
898 reference
->keepRunning
= reference
->callback(reference
->userdata
, obj
);
900 IOObjectRelease(obj
);
903 /* One last call to the call back now that we are not longer have printers left to iterate...
905 if (reference
->keepRunning
)
906 reference
->keepRunning
= reference
->callback(reference
->userdata
, 0x0);
908 if (!reference
->keepRunning
)
909 CFRunLoopStop(CFRunLoopGetCurrent());
914 * 'list_device_cb()' - list_device iterator callback.
917 static Boolean
list_device_cb(void *refcon
,
920 Boolean keepRunning
= (obj
!= 0x0);
924 CFStringRef deviceIDString
= NULL
;
925 UInt32 deviceLocation
= 0;
927 copy_devicestring(obj
, &deviceIDString
, &deviceLocation
);
928 if (deviceIDString
!= NULL
)
930 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
931 char uristr
[1024], makestr
[1024], modelstr
[1024], serialstr
[1024];
932 char optionsstr
[1024], idstr
[1024];
934 copy_deviceinfo(deviceIDString
, &make
, &model
, &serial
);
938 CFStringGetCString(deviceIDString
, idstr
, sizeof(idstr
),
939 kCFStringEncodingUTF8
);
942 CFStringGetCString(make
, makestr
, sizeof(makestr
),
943 kCFStringEncodingUTF8
);
945 strcpy(makestr
, "Unknown");
948 CFStringGetCString(model
, &modelstr
[1], sizeof(modelstr
)-1,
949 kCFStringEncodingUTF8
);
951 strcpy(modelstr
+ 1, "Printer");
953 optionsstr
[0] = '\0';
956 CFStringGetCString(serial
, serialstr
, sizeof(serialstr
), kCFStringEncodingUTF8
);
957 snprintf(optionsstr
, sizeof(optionsstr
), "?serial=%s", serialstr
);
959 else if (deviceLocation
!= 0)
960 snprintf(optionsstr
, sizeof(optionsstr
), "?location=%x", (unsigned)deviceLocation
);
962 httpAssembleURI(HTTP_URI_CODING_ALL
, uristr
, sizeof(uristr
), "usb", NULL
, makestr
, 0, modelstr
);
963 strncat(uristr
, optionsstr
, sizeof(uristr
));
966 * Fix common HP 1284 bug...
969 if (!strcasecmp(makestr
, "Hewlett-Packard"))
970 strcpy(makestr
, "HP");
972 if (!strncasecmp(modelstr
+ 1, "hp ", 3))
973 _cups_strcpy(modelstr
+ 1, modelstr
+ 4);
975 printf("direct %s \"%s %s\" \"%s %s USB\" \"%s\"\n", uristr
, makestr
,
976 &modelstr
[1], makestr
, &modelstr
[1], idstr
);
978 release_deviceinfo(&make
, &model
, &serial
);
979 CFRelease(deviceIDString
);
988 * 'find_device_cb()' - print_device iterator callback.
991 static Boolean
find_device_cb(void *refcon
,
994 Boolean keepLooking
= true;
998 CFStringRef idString
= NULL
;
999 UInt32 location
= -1;
1001 copy_devicestring(obj
, &idString
, &location
);
1002 if (idString
!= NULL
)
1004 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1006 copy_deviceinfo(idString
, &make
, &model
, &serial
);
1007 if (CFStringCompare(make
, g
.make
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1009 if (CFStringCompare(model
, g
.model
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1011 if (g
.serial
!= NULL
&& CFStringGetLength(g
.serial
) > 0)
1013 if (serial
!= NULL
&& CFStringCompare(serial
, g
.serial
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1015 IOObjectRetain(obj
);
1016 g
.printer_obj
= obj
;
1017 keepLooking
= false;
1022 if (g
.printer_obj
!= 0)
1023 IOObjectRelease(g
.printer_obj
);
1025 g
.printer_obj
= obj
;
1026 IOObjectRetain(obj
);
1028 if (g
.location
== 0 || g
.location
== location
)
1029 keepLooking
= false;
1034 release_deviceinfo(&make
, &model
, &serial
);
1035 CFRelease(idString
);
1040 keepLooking
= (g
.printer_obj
== 0);
1041 if (obj
== 0x0 && keepLooking
)
1043 CFRunLoopTimerContext context
= { 0, refcon
, NULL
, NULL
, NULL
};
1044 CFRunLoopTimerRef timer
= CFRunLoopTimerCreate(NULL
, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb
, &context
);
1047 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer
, kCFRunLoopDefaultMode
);
1048 g
.status_timer
= timer
;
1053 if (!keepLooking
&& g
.status_timer
!= NULL
)
1055 fputs("STATE: -offline-error\n", stderr
);
1056 fputs(_("INFO: Printer is now on-line.\n"), stderr
);
1057 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g
.status_timer
, kCFRunLoopDefaultMode
);
1058 CFRelease(g
.status_timer
);
1059 g
.status_timer
= NULL
;
1067 * 'status_timer_cb()' - Status timer callback.
1070 static void status_timer_cb(CFRunLoopTimerRef timer
,
1073 fputs("STATE: +offline-error\n", stderr
);
1074 fputs(_("INFO: Printer is currently off-line.\n"), stderr
);
1080 * 'copy_deviceinfo()' - Copy strings from the 1284 device ID.
1083 static void copy_deviceinfo(CFStringRef deviceIDString
,
1086 CFStringRef
*serial
)
1088 CFStringRef modelKeys
[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL
};
1089 CFStringRef makeKeys
[] = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL
};
1090 CFStringRef serialKeys
[] = { CFSTR("SN:"), CFSTR("SERN:"), NULL
};
1093 *make
= copy_value_for_key(deviceIDString
, makeKeys
);
1095 *model
= copy_value_for_key(deviceIDString
, modelKeys
);
1097 *serial
= copy_value_for_key(deviceIDString
, serialKeys
);
1102 * 'release_deviceinfo()' - Release deviceinfo strings.
1105 static void release_deviceinfo(CFStringRef
*make
,
1107 CFStringRef
*serial
)
1109 if (make
!= NULL
&& *make
!= NULL
)
1115 if (model
!= NULL
&& *model
!= NULL
)
1121 if (serial
!= NULL
&& *serial
!= NULL
)
1131 * 'load_classdriver()' - Load a classdriver.
1134 static kern_return_t
load_classdriver(CFStringRef driverPath
,
1135 printer_interface_t intf
,
1136 classdriver_t
***printerDriver
)
1138 kern_return_t kr
= kUSBPrinterClassDeviceNotOpen
;
1139 classdriver_t
**driver
= NULL
;
1140 CFStringRef bundle
= (driverPath
== NULL
? kUSBGenericTOPrinterClassDriver
: driverPath
);
1144 CFURLRef url
= CFURLCreateWithFileSystemPath(NULL
, bundle
, kCFURLPOSIXPathStyle
, true);
1145 CFPlugInRef plugin
= (url
!= NULL
? CFPlugInCreate(NULL
, url
) : NULL
);
1152 CFArrayRef factories
= CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID
, plugin
);
1153 if (factories
!= NULL
&& CFArrayGetCount(factories
) > 0)
1155 CFUUIDRef factoryID
= CFArrayGetValueAtIndex(factories
, 0);
1156 IUnknownVTbl
**iunknown
= CFPlugInInstanceCreate(NULL
, factoryID
, kUSBPrinterClassTypeID
);
1157 if (iunknown
!= NULL
)
1159 kr
= (*iunknown
)->QueryInterface(iunknown
, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID
), (LPVOID
*)&driver
);
1160 if (kr
== kIOReturnSuccess
&& driver
!= NULL
)
1162 classdriver_t
**genericDriver
= NULL
;
1163 if (driverPath
!= NULL
&& CFStringCompare(driverPath
, kUSBGenericTOPrinterClassDriver
, 0) != kCFCompareEqualTo
)
1164 kr
= load_classdriver(NULL
, intf
, &genericDriver
);
1166 if (kr
== kIOReturnSuccess
)
1168 (*driver
)->interface
= intf
;
1169 (*driver
)->Initialize(driver
, genericDriver
);
1171 (*driver
)->plugin
= plugin
;
1172 (*driver
)->interface
= intf
;
1173 *printerDriver
= driver
;
1176 (*iunknown
)->Release(iunknown
);
1178 CFRelease(factories
);
1184 char bundlestr
[1024];
1185 CFStringGetCString(bundle
, bundlestr
, sizeof(bundlestr
), kCFStringEncodingUTF8
);
1186 fprintf(stderr
, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr
, (int)kr
);
1194 * 'unload_classdriver()' - Unload a classdriver.
1197 static kern_return_t
unload_classdriver(classdriver_t
***classdriver
)
1199 if (*classdriver
!= NULL
)
1201 (**classdriver
)->Release(*classdriver
);
1202 *classdriver
= NULL
;
1205 return kIOReturnSuccess
;
1210 * 'load_printerdriver()' - Load vendor's classdriver.
1212 * If driverBundlePath is not NULL on return it is the callers responsbility to release it!
1215 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
)
1217 IOCFPlugInInterface
**iodev
= NULL
;
1220 printer_interface_t intf
;
1223 kr
= IOCreatePlugInInterfaceForService(g
.printer_obj
, kIOUSBInterfaceUserClientTypeID
, kIOCFPlugInInterfaceID
, &iodev
, &score
);
1224 if (kr
== kIOReturnSuccess
)
1226 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*) &intf
)) == noErr
)
1228 *driverBundlePath
= IORegistryEntryCreateCFProperty(g
.printer_obj
, kUSBClassDriverProperty
, NULL
, kNilOptions
);
1230 kr
= load_classdriver(*driverBundlePath
, intf
, &g
.classdriver
);
1232 if (kr
!= kIOReturnSuccess
)
1233 (*intf
)->Release(intf
);
1235 IODestroyPlugInInterface(iodev
);
1242 * 'registry_open()' - Open a connection to the printer.
1245 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
)
1247 g
.bidi_flag
= 0; /* 0=unidirectional */
1249 kern_return_t kr
= load_printerdriver(driverBundlePath
);
1250 if (kr
!= kIOReturnSuccess
)
1253 if (g
.classdriver
!= NULL
)
1255 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolBidirectional
);
1256 if (kr
!= kIOReturnSuccess
|| (*g
.classdriver
)->interface
== NULL
)
1258 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolUnidirectional
);
1259 if (kr
== kIOReturnSuccess
)
1261 if ((*g
.classdriver
)->interface
== NULL
)
1263 (*g
.classdriver
)->Close(g
.classdriver
);
1269 g
.bidi_flag
= 1; /* 1=bidirectional */
1272 if (kr
!= kIOReturnSuccess
)
1273 unload_classdriver(&g
.classdriver
);
1280 * 'registry_close()' - Close the connection to the printer.
1283 static kern_return_t
registry_close()
1285 if (g
.classdriver
!= NULL
)
1286 (*g
.classdriver
)->Close(g
.classdriver
);
1288 unload_classdriver(&g
.classdriver
);
1289 return kIOReturnSuccess
;
1294 * 'copy_deviceid()' - Copy the 1284 device id string.
1297 static OSStatus
copy_deviceid(classdriver_t
**classdriver
,
1298 CFStringRef
*deviceID
)
1300 CFStringRef devID
= NULL
,
1304 deviceSerial
= NULL
;
1306 OSStatus err
= (*classdriver
)->GetDeviceID(classdriver
, &devID
, DEFAULT_TIMEOUT
);
1308 copy_deviceinfo(devID
, &deviceMake
, &deviceModel
, &deviceSerial
);
1310 if (deviceMake
== NULL
|| deviceModel
== NULL
|| deviceSerial
== NULL
)
1312 IOUSBDeviceDescriptor desc
;
1313 iodevice_request_t request
;
1315 request
.requestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
1316 request
.request
= kUSBRqGetDescriptor
;
1317 request
.value
= (kUSBDeviceDesc
<< 8) | 0;
1319 request
.length
= sizeof(desc
);
1320 request
.buffer
= &desc
;
1321 err
= (*classdriver
)->DeviceRequest(classdriver
, &request
, DEFAULT_TIMEOUT
);
1322 if (err
== kIOReturnSuccess
)
1324 CFMutableStringRef newDevID
= CFStringCreateMutable(NULL
, 0);
1326 if (deviceMake
== NULL
)
1328 CFStringRef data
= NULL
;
1329 err
= (*classdriver
)->GetString(classdriver
, desc
.iManufacturer
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1332 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MFG:%@;"), data
);
1337 if (deviceModel
== NULL
)
1339 CFStringRef data
= NULL
;
1340 err
= (*classdriver
)->GetString(classdriver
, desc
.iProduct
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1343 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MDL:%@;"), data
);
1348 if (deviceSerial
== NULL
&& desc
.iSerialNumber
!= 0)
1350 CFStringRef data
= NULL
;
1351 err
= (*classdriver
)->GetString(classdriver
, desc
.iSerialNumber
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1354 CFStringAppendFormat(newDevID
, NULL
, CFSTR("SERN:%@;"), data
);
1361 CFStringAppend(newDevID
, devID
);
1365 *deviceID
= newDevID
;
1372 release_deviceinfo(&deviceMake
, &deviceModel
, &deviceSerial
);
1379 * 'copy_devicestring()' - Copy the 1284 device id string.
1382 static void copy_devicestring(io_service_t usbInterface
,
1383 CFStringRef
*deviceID
,
1384 UInt32
*deviceLocation
)
1386 IOCFPlugInInterface
**iodev
= NULL
;
1389 printer_interface_t intf
;
1391 classdriver_t
**klassDriver
= NULL
;
1392 CFStringRef driverBundlePath
;
1394 if ((kr
= IOCreatePlugInInterfaceForService(usbInterface
,
1395 kIOUSBInterfaceUserClientTypeID
,
1396 kIOCFPlugInInterfaceID
,
1397 &iodev
, &score
)) == kIOReturnSuccess
)
1399 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*)
1402 (*intf
)->GetLocationID(intf
, deviceLocation
);
1404 driverBundlePath
= IORegistryEntryCreateCFProperty(usbInterface
,
1405 kUSBClassDriverProperty
,
1408 kr
= load_classdriver(driverBundlePath
, intf
, &klassDriver
);
1410 if (kr
!= kIOReturnSuccess
&& driverBundlePath
!= NULL
)
1411 kr
= load_classdriver(NULL
, intf
, &klassDriver
);
1413 if (kr
== kIOReturnSuccess
&& klassDriver
!= NULL
)
1414 kr
= copy_deviceid(klassDriver
, deviceID
);
1416 unload_classdriver(&klassDriver
);
1418 if (driverBundlePath
!= NULL
)
1419 CFRelease(driverBundlePath
);
1421 /* (*intf)->Release(intf); */
1423 IODestroyPlugInInterface(iodev
);
1430 * 'copy_value_for_key()' - Copy value string associated with a key.
1433 static CFStringRef
copy_value_for_key(CFStringRef deviceID
,
1436 CFStringRef value
= NULL
;
1437 CFArrayRef kvPairs
= deviceID
!= NULL
? CFStringCreateArrayBySeparatingStrings(NULL
, deviceID
, CFSTR(";")) : NULL
;
1438 CFIndex max
= kvPairs
!= NULL
? CFArrayGetCount(kvPairs
) : 0;
1441 while (idx
< max
&& value
== NULL
)
1443 CFStringRef kvpair
= CFArrayGetValueAtIndex(kvPairs
, idx
);
1445 while (keys
[idxx
] != NULL
&& value
== NULL
)
1447 CFRange range
= CFStringFind(kvpair
, keys
[idxx
], kCFCompareCaseInsensitive
);
1448 if (range
.length
!= -1)
1450 if (range
.location
!= 0)
1452 CFMutableStringRef theString
= CFStringCreateMutableCopy(NULL
, 0, kvpair
);
1453 CFStringTrimWhitespace(theString
);
1454 range
= CFStringFind(theString
, keys
[idxx
], kCFCompareCaseInsensitive
);
1455 if (range
.location
== 0)
1456 value
= CFStringCreateWithSubstring(NULL
, theString
, CFRangeMake(range
.length
, CFStringGetLength(theString
) - range
.length
));
1458 CFRelease(theString
);
1462 CFStringRef theString
= CFStringCreateWithSubstring(NULL
, kvpair
, CFRangeMake(range
.length
, CFStringGetLength(kvpair
) - range
.length
));
1463 CFMutableStringRef theString2
= CFStringCreateMutableCopy(NULL
, 0, theString
);
1464 CFRelease(theString
);
1466 CFStringTrimWhitespace(theString2
);
1475 if (kvPairs
!= NULL
)
1482 * 'cfstr_create_trim()' - Create CFString and trim whitespace characters.
1485 CFStringRef
cfstr_create_trim(const char *cstr
)
1488 CFMutableStringRef cfmutablestr
= NULL
;
1490 if ((cfstr
= CFStringCreateWithCString(NULL
, cstr
, kCFStringEncodingUTF8
)) != NULL
)
1492 if ((cfmutablestr
= CFStringCreateMutableCopy(NULL
, 1024, cfstr
)) != NULL
)
1493 CFStringTrimWhitespace(cfmutablestr
);
1497 return (CFStringRef
) cfmutablestr
;
1503 * 'parse_options()' - Parse uri options.
1506 static void parse_options(const char *options
,
1511 char *serialnumber
; /* ?serial=<serial> or ?location=<location> */
1512 char optionName
[255], /* Name of option */
1513 value
[255], /* Value of option */
1514 *ptr
; /* Pointer into name or value */
1524 serialnumber
= NULL
;
1526 while (*options
!= '\0')
1528 /* Get the name... */
1529 for (ptr
= optionName
; *options
&& *options
!= '=' && *options
!= '+';)
1530 *ptr
++ = *options
++;
1535 if (*options
== '=')
1537 /* Get the value... */
1540 for (ptr
= value
; *options
&& *options
!= '+';)
1541 *ptr
++ = *options
++;
1545 if (*options
== '+')
1548 else if (*options
== '+')
1552 * Process the option...
1554 if (strcasecmp(optionName
, "waiteof") == 0)
1556 if (strcasecmp(value
, "on") == 0 ||
1557 strcasecmp(value
, "yes") == 0 ||
1558 strcasecmp(value
, "true") == 0)
1560 else if (strcasecmp(value
, "off") == 0 ||
1561 strcasecmp(value
, "no") == 0 ||
1562 strcasecmp(value
, "false") == 0)
1565 fprintf(stderr
, _("WARNING: Boolean expected for waiteof option \"%s\"\n"), value
);
1567 else if (strcasecmp(optionName
, "serial") == 0)
1569 strcpy(serial
, value
);
1570 serialnumber
= serial
;
1572 else if (strcasecmp(optionName
, "location") == 0 && location
)
1573 *location
= strtol(value
, NULL
, 16);
1581 * @function setup_cfLanguage
1582 * @abstract Convert the contents of the CUPS 'LANG' environment
1583 * variable into a one element CF array of languages.
1585 * @discussion Each submitted job comes with a natural language. CUPS passes
1586 * that language in an environment variable. We take that language
1587 * and jam it into the AppleLanguages array so that CF will use
1588 * it when reading localized resources. We need to do this before
1589 * any CF code reads and caches the languages array, so this function
1590 * should be called early in main()
1592 static void setup_cfLanguage(void)
1594 CFStringRef lang
[1] = {NULL
};
1595 CFArrayRef langArray
= NULL
;
1596 const char *requestedLang
= NULL
;
1598 requestedLang
= getenv("LANG");
1599 if (requestedLang
!= NULL
)
1601 lang
[0] = CFStringCreateWithCString(kCFAllocatorDefault
, requestedLang
, kCFStringEncodingUTF8
);
1602 langArray
= CFArrayCreate(kCFAllocatorDefault
, (const void **)lang
, sizeof(lang
) / sizeof(lang
[0]), &kCFTypeArrayCallBacks
);
1604 CFPreferencesSetAppValue(CFSTR("AppleLanguages"), langArray
, kCFPreferencesCurrentApplication
);
1605 DEBUG_printf((stderr
, "DEBUG: usb: AppleLanguages = \"%s\"\n", requestedLang
));
1608 CFRelease(langArray
);
1611 fputs("DEBUG: usb: LANG environment variable missing.\n", stderr
);
1615 #if defined(__i386__)
1617 * @function run_ppc_backend
1619 * @abstract Starts child backend process running as a ppc executable.
1621 * @result Never returns; always calls exit().
1625 static void run_ppc_backend(int argc
,
1632 pid_t waitpid_status
;
1634 char *usb_ppc_status
;
1637 * If we're running as i386 and couldn't load the class driver (because they'it's
1638 * ppc-only) then try to re-exec ourselves in ppc mode to try again. If we don't have
1639 * a ppc architecture we may be running i386 again so guard against this by setting
1640 * and testing an environment variable...
1642 usb_ppc_status
= getenv("USB_PPC_STATUS");
1644 if (usb_ppc_status
== NULL
)
1646 /* Catch SIGTERM if we are _not_ printing data from
1647 * stdin (otherwise you can't cancel raw jobs...)
1652 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
1653 sigset(SIGTERM
, sigterm_handler
);
1654 #elif defined(HAVE_SIGACTION)
1655 struct sigaction action
; /* Actions for POSIX signals */
1656 memset(&action
, 0, sizeof(action
));
1657 sigaddset(&action
.sa_mask
, SIGTERM
);
1658 action
.sa_handler
= sigterm_handler
;
1659 sigaction(SIGTERM
, &action
, NULL
);
1661 signal(SIGTERM
, sigterm_handler
);
1662 #endif /* HAVE_SIGSET */
1665 if ((child_pid
= fork()) == 0)
1667 /* Child comes here. */
1668 setenv("USB_PPC_STATUS", "1", false);
1670 /* Tell the kernel we want the next exec call to favor the ppc architecture... */
1671 int mib
[] = { CTL_KERN
, KERN_AFFINITY
, 1, 1 };
1673 sysctl(mib
, namelen
, NULL
, NULL
, NULL
, 0);
1675 /* Set up the arguments and call exec... */
1676 for (i
= 0; i
< argc
&& i
< (sizeof(my_argv
)/sizeof(my_argv
[0])) - 1; i
++)
1677 my_argv
[i
] = argv
[i
];
1681 execv("/usr/libexec/cups/backend/usb", my_argv
);
1683 fprintf(stderr
, "DEBUG: execv: %s\n", strerror(errno
));
1686 else if (child_pid
> 0)
1688 /* Parent comes here.
1690 * Close the fds we won't be using then wait for the child backend to exit.
1695 fprintf(stderr
, "DEBUG: Started usb(ppc) backend (PID %d)\n", (int)child_pid
);
1697 while ((waitpid_status
= waitpid(child_pid
, &childstatus
, 0)) == (pid_t
)-1 && errno
== EINTR
)
1700 if (WIFSIGNALED(childstatus
))
1702 exitstatus
= WTERMSIG(childstatus
);
1703 fprintf(stderr
, "DEBUG: usb(ppc) backend %d crashed on signal %d!\n", child_pid
, exitstatus
);
1707 if ((exitstatus
= WEXITSTATUS(childstatus
)) != 0)
1708 fprintf(stderr
, "DEBUG: usb(ppc) backend %d stopped with status %d!\n", child_pid
, exitstatus
);
1710 fprintf(stderr
, "DEBUG: PID %d exited with no errors\n", child_pid
);
1716 fprintf(stderr
, "DEBUG: fork: %s\n", strerror(errno
));
1722 fputs("DEBUG: usb child running i386 again\n", stderr
);
1723 exitstatus
= ENOENT
;
1730 * 'sigterm_handler()' - SIGTERM handler.
1733 static void sigterm_handler(int sig
)
1735 /* If we started a child process pass the signal on to it...
1738 kill(child_pid
, sig
);
1743 #endif /* __i386__ */
1746 #ifdef PARSE_PS_ERRORS
1748 * 'next_line()' - Find the next line in a buffer.
1751 static const char *next_line (const char *buffer
)
1753 const char *cptr
, *lptr
= NULL
;
1755 for (cptr
= buffer
; *cptr
&& lptr
== NULL
; cptr
++)
1756 if (*cptr
== '\n' || *cptr
== '\r')
1763 * 'parse_pserror()' - Scan the backchannel data for postscript errors.
1766 static void parse_pserror(char *sockBuffer
,
1769 static char gErrorBuffer
[1024] = "";
1770 static char *gErrorBufferPtr
= gErrorBuffer
;
1771 static char *gErrorBufferEndPtr
= gErrorBuffer
+ sizeof(gErrorBuffer
);
1773 char *pCommentBegin
, *pCommentEnd
, *pLineEnd
;
1778 if (gErrorBufferPtr
+ len
> gErrorBufferEndPtr
- 1)
1779 gErrorBufferPtr
= gErrorBuffer
;
1780 if (len
> sizeof(gErrorBuffer
) - 1)
1781 len
= sizeof(gErrorBuffer
) - 1;
1783 memcpy(gErrorBufferPtr
, (const void *)sockBuffer
, len
);
1784 gErrorBufferPtr
+= len
;
1785 *(gErrorBufferPtr
+ 1) = '\0';
1787 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
1788 while (pLineEnd
!= NULL
)
1792 pCommentBegin
= strstr(gErrorBuffer
,"%%[");
1793 pCommentEnd
= strstr(gErrorBuffer
, "]%%");
1794 if (pCommentBegin
!= gErrorBuffer
&& pCommentEnd
!= NULL
)
1796 pCommentEnd
+= 3; /* Skip past "]%%" */
1797 *pCommentEnd
= '\0'; /* There's always room for the nul */
1799 if (strncasecmp(pCommentBegin
, "%%[ Error:", 10) == 0)
1801 else if (strncasecmp(pCommentBegin
, "%%[ Flushing", 12) == 0)
1806 if ((logstrlen
= snprintf(logstr
, sizeof(logstr
), "%s: %s\n", logLevel
, pCommentBegin
)) >= sizeof(logstr
))
1808 /* If the string was trucnated make sure it has a linefeed before the nul */
1809 logstrlen
= sizeof(logstr
) - 1;
1810 logstr
[logstrlen
- 1] = '\n';
1812 write(STDERR_FILENO
, logstr
, logstrlen
);
1815 /* move everything over... */
1816 strcpy(gErrorBuffer
, pLineEnd
);
1817 gErrorBufferPtr
= gErrorBuffer
;
1818 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
1821 #endif /* PARSE_PS_ERRORS */
1828 static void soft_reset()
1830 fd_set input_set
; /* Input set for select() */
1831 struct timeval stimeout
; /* Timeout for select() */
1832 char buffer
[2048]; /* Buffer */
1833 struct timespec cond_timeout
; /* pthread condition timeout */
1836 * Send an abort once a second until the I/O lock is released by the main thread...
1839 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
1840 while (g
.readwrite_lock
)
1842 (*g
.classdriver
)->Abort(g
.classdriver
);
1844 cond_timeout
.tv_sec
= time(NULL
) + 1;
1845 cond_timeout
.tv_nsec
= 0;
1847 pthread_cond_timedwait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
, &cond_timeout
);
1850 g
.readwrite_lock
= 1;
1851 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
1854 * Flush bytes waiting on print_fd...
1859 FD_ZERO(&input_set
);
1860 FD_SET(g
.print_fd
, &input_set
);
1862 stimeout
.tv_sec
= 0;
1863 stimeout
.tv_usec
= 0;
1865 while (select(g
.print_fd
+1, &input_set
, NULL
, NULL
, &stimeout
) > 0)
1866 if (read(g
.print_fd
, buffer
, sizeof(buffer
)) <= 0)
1873 (*g
.classdriver
)->SoftReset(g
.classdriver
, 0);
1876 * Release the I/O lock...
1879 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
1880 g
.readwrite_lock
= 0;
1881 pthread_cond_signal(&g
.readwrite_lock_cond
);
1882 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
1887 * 'get_device_id()' - Return IEEE-1284 device ID.
1890 static void get_device_id(cups_sc_status_t
*status
,
1894 UInt32 deviceLocation
= 0;
1895 CFStringRef deviceIDString
= NULL
;
1898 copy_devicestring(g
.printer_obj
, &deviceIDString
, &deviceLocation
);
1901 CFStringGetCString(deviceIDString
, data
, *datalen
, kCFStringEncodingUTF8
);
1902 *datalen
= strlen(data
);
1903 CFRelease(deviceIDString
);
1905 *status
= CUPS_SC_STATUS_OK
;
1910 * End of "$Id: usb-darwin.c 6591 2007-06-21 20:35:28Z mike $".