2 * "$Id: usb-darwin.c 7460 2008-04-16 02:19:54Z mike $"
4 * Copyright 2005-2008 Apple Inc. All rights reserved.
6 * IMPORTANT: This Apple software is supplied to you by Apple Computer,
7 * Inc. ("Apple") in consideration of your agreement to the following
8 * terms, and your use, installation, modification or redistribution of
9 * this Apple software constitutes acceptance of these terms. If you do
10 * not agree with these terms, please do not use, install, modify or
11 * redistribute this Apple software.
13 * In consideration of your agreement to abide by the following terms, and
14 * subject to these terms, Apple grants you a personal, non-exclusive
15 * license, under Apple's copyrights in this original Apple software (the
16 * "Apple Software"), to use, reproduce, modify and redistribute the Apple
17 * Software, with or without modifications, in source and/or binary forms;
18 * provided that if you redistribute the Apple Software in its entirety and
19 * without modifications, you must retain this notice and the following
20 * text and disclaimers in all such redistributions of the Apple Software.
21 * Neither the name, trademarks, service marks or logos of Apple Computer,
22 * Inc. may be used to endorse or promote products derived from the Apple
23 * Software without specific prior written permission from Apple. Except
24 * as expressly stated in this notice, no other rights or licenses, express
25 * or implied, are granted by Apple herein, including but not limited to
26 * any patent rights that may be infringed by your derivative works or by
27 * other works in which the Apple Software may be incorporated.
29 * The Apple Software is provided by Apple on an "AS IS" basis. APPLE
30 * MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
31 * THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
32 * FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
33 * OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
35 * IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
36 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
37 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
38 * INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
39 * MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
40 * AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
41 * STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
42 * POSSIBILITY OF SUCH DAMAGE.
46 * list_devices() - List all USB devices.
47 * print_device() - Print a file to a USB device.
48 * sidechannel_thread() - Thread to handle side-channel requests.
49 * read_thread() - Thread to read the backchannel data on.
50 * list_device_cb() - list_device iterator callback.
51 * find_device_cb() - print_device iterator callback.
52 * status_timer_cb() - Status timer callback.
53 * iterate_printers() - Iterate over all the printers.
54 * device_added() - Device added notifier.
55 * copy_deviceinfo() - Copy strings from the 1284 device ID.
56 * release_deviceinfo() - Release deviceinfo strings.
57 * load_classdriver() - Load a classdriver.
58 * unload_classdriver() - Unload a classdriver.
59 * load_printerdriver() - Load vendor's classdriver.
60 * registry_open() - Open a connection to the printer.
61 * registry_close() - Close the connection to the printer.
62 * copy_deviceid() - Copy the 1284 device id string.
63 * copy_devicestring() - Copy the 1284 device id string.
64 * copy_value_for_key() - Copy value string associated with a key.
65 * cfstr_create_trim() - Create CFString and trim whitespace characters.
66 * parse_options() - Parse uri options.
67 * setup_cfLanguage() - Create AppleLanguages array from LANG environment var.
68 * run_ppc_backend() - Re-exec i386 backend as ppc.
69 * sigterm_handler() - SIGTERM handler.
70 * next_line() - Find the next line in a buffer.
71 * parse_pserror() - Scan the backchannel data for postscript errors.
72 * get_device_id() - Return IEEE-1284 device ID.
76 * Include necessary headers.
87 #include <sys/sysctl.h>
89 #include <mach/mach.h>
90 #include <mach/mach_error.h>
91 #include <mach/mach_time.h>
92 #include <cups/debug.h>
93 #include <cups/sidechannel.h>
94 #include <cups/i18n.h>
95 #include "backend-private.h"
97 #include <CoreFoundation/CoreFoundation.h>
98 #include <IOKit/usb/IOUSBLib.h>
99 #include <IOKit/IOCFPlugIn.h>
105 * WAIT_EOF_DELAY is number of seconds we'll wait for responses from
106 * the printer after we've finished sending all the data
108 #define WAIT_EOF_DELAY 7
109 #define WAIT_SIDE_DELAY 3
110 #define DEFAULT_TIMEOUT 5000L
112 #define USB_INTERFACE_KIND CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID190)
113 #define kUSBLanguageEnglish 0x409
115 #define PRINTER_POLLING_INTERVAL 5 /* seconds */
116 #define INITIAL_LOG_INTERVAL PRINTER_POLLING_INTERVAL
117 #define SUBSEQUENT_LOG_INTERVAL 3 * INITIAL_LOG_INTERVAL
119 #define kUSBPrinterClassTypeID CFUUIDGetConstantUUIDWithBytes(NULL, 0x06, 0x04, 0x7D, 0x16, 0x53, 0xA2, 0x11, 0xD6, 0x92, 0x06, 0x00, 0x30, 0x65, 0x52, 0x45, 0x92)
120 #define kUSBPrinterClassInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, 0x03, 0x34, 0x6D, 0x74, 0x53, 0xA3, 0x11, 0xD6, 0x9E, 0xA1, 0x76, 0x30, 0x65, 0x52, 0x45, 0x92)
122 #define kUSBClassDriverProperty CFSTR("USB Printing Class")
124 #define kUSBGenericTOPrinterClassDriver CFSTR("/System/Library/Printers/Libraries/USBGenericTOPrintingClass.plugin")
125 #define kUSBPrinterClassDeviceNotOpen -9664 /*kPMInvalidIOMContext*/
129 * Section 5.3 USB Printing Class spec
131 #define kUSBPrintingSubclass 1
132 #define kUSBPrintingProtocolNoOpen 0
133 #define kUSBPrintingProtocolUnidirectional 1
134 #define kUSBPrintingProtocolBidirectional 2
136 typedef IOUSBInterfaceInterface190
**printer_interface_t
;
138 typedef struct iodevice_request_s
/**** Device request ****/
146 } iodevice_request_t
;
148 typedef union /**** Centronics status byte ****/
153 unsigned reserved0
:2;
154 unsigned paperError
:1;
157 unsigned reserved1
:3;
159 } centronics_status_t
;
161 typedef struct classdriver_s
/**** g.classdriver context ****/
164 CFPlugInRef plugin
; /* release plugin */
165 IUnknownVTbl
**factory
; /* Factory */
166 void *vendorReference
; /* vendor class specific usage */
167 UInt32 location
; /* unique location in bus topology */
168 UInt8 interfaceNumber
; /* Interface number */
169 UInt16 vendorID
; /* Vendor id */
170 UInt16 productID
; /* Product id */
171 printer_interface_t interface
; /* identify the device to IOKit */
172 UInt8 outpipe
; /* mandatory bulkOut pipe */
173 UInt8 inpipe
; /* optional bulkIn pipe */
175 /* general class requests */
176 kern_return_t (*DeviceRequest
)(struct classdriver_s
**printer
, iodevice_request_t
*iorequest
, UInt16 timeout
);
177 kern_return_t (*GetString
)(struct classdriver_s
**printer
, UInt8 whichString
, UInt16 language
, UInt16 timeout
, CFStringRef
*result
);
179 /* standard printer class requests */
180 kern_return_t (*SoftReset
)(struct classdriver_s
**printer
, UInt16 timeout
);
181 kern_return_t (*GetCentronicsStatus
)(struct classdriver_s
**printer
, centronics_status_t
*result
, UInt16 timeout
);
182 kern_return_t (*GetDeviceID
)(struct classdriver_s
**printer
, CFStringRef
*devid
, UInt16 timeout
);
184 /* standard bulk device requests */
185 kern_return_t (*ReadPipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
);
186 kern_return_t (*WritePipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
, Boolean eoj
);
188 /* interface requests */
189 kern_return_t (*Open
)(struct classdriver_s
**printer
, UInt32 location
, UInt8 protocol
);
190 kern_return_t (*Abort
)(struct classdriver_s
**printer
);
191 kern_return_t (*Close
)(struct classdriver_s
**printer
);
193 /* initialize and terminate */
194 kern_return_t (*Initialize
)(struct classdriver_s
**printer
, struct classdriver_s
**baseclass
);
195 kern_return_t (*Terminate
)(struct classdriver_s
**printer
);
199 typedef Boolean (*iterator_callback_t
)(void *refcon
, io_service_t obj
);
201 typedef struct iterator_reference_s
/**** Iterator reference data */
203 iterator_callback_t callback
;
206 } iterator_reference_t
;
208 typedef struct globals_s
210 io_service_t printer_obj
;
211 classdriver_t
**classdriver
;
213 pthread_mutex_t read_thread_mutex
;
214 pthread_cond_t read_thread_cond
;
215 int read_thread_stop
;
216 int read_thread_done
;
218 pthread_mutex_t readwrite_lock_mutex
;
219 pthread_cond_t readwrite_lock_cond
;
228 CFRunLoopTimerRef status_timer
;
230 int print_fd
; /* File descriptor to print */
231 ssize_t print_bytes
; /* Print bytes read */
234 int drain_output
; /* Drain all pending output */
235 int bidi_flag
; /* 0=unidirectional, 1=bidirectional */
237 pthread_mutex_t sidechannel_thread_mutex
;
238 pthread_cond_t sidechannel_thread_cond
;
239 int sidechannel_thread_stop
;
240 int sidechannel_thread_done
;
248 globals_t g
= { 0 }; /* Globals */
255 static Boolean
find_device_cb(void *refcon
, io_service_t obj
);
256 static Boolean
list_device_cb(void *refcon
, io_service_t obj
);
257 static CFStringRef
cfstr_create_trim(const char *cstr
);
258 static CFStringRef
copy_value_for_key(CFStringRef deviceID
, CFStringRef
*keys
);
259 static kern_return_t
load_classdriver(CFStringRef driverPath
, printer_interface_t intf
, classdriver_t
***printerDriver
);
260 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
);
261 static kern_return_t
registry_close();
262 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
);
263 static kern_return_t
unload_classdriver();
264 static OSStatus
copy_deviceid(classdriver_t
**printer
, CFStringRef
*deviceID
);
265 static void *read_thread(void *reference
);
266 static void *sidechannel_thread(void *reference
);
267 static void copy_deviceinfo(CFStringRef deviceIDString
, CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
268 static void copy_devicestring(io_service_t usbInterface
, CFStringRef
*deviceID
, UInt32
*deviceLocation
, UInt8
*interfaceNum
);
269 static void device_added(void *userdata
, io_iterator_t iterator
);
270 static void get_device_id(cups_sc_status_t
*status
, char *data
, int *datalen
);
271 static void iterate_printers(iterator_callback_t callBack
, void *userdata
);
272 static void parse_options(char *options
, char *serial
, int serial_size
, UInt32
*location
, Boolean
*wait_eof
);
273 static void release_deviceinfo(CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
274 static void setup_cfLanguage(void);
275 static void soft_reset();
276 static void status_timer_cb(CFRunLoopTimerRef timer
, void *info
);
278 #if defined(__i386__)
279 static pid_t child_pid
; /* Child PID */
280 static void run_ppc_backend(int argc
, char *argv
[], int fd
); /* Starts child backend process running as a ppc executable */
281 static void sigterm_handler(int sig
); /* SIGTERM handler */
282 #endif /* __i386__ */
284 #ifdef PARSE_PS_ERRORS
285 static const char *next_line (const char *buffer
);
286 static void parse_pserror (char *sockBuffer
, int len
);
287 #endif /* PARSE_PS_ERRORS */
292 * 'list_devices()' - List all USB devices.
297 iterate_printers(list_device_cb
, NULL
);
302 * 'print_device()' - Print a file to a USB device.
305 int /* O - Exit status */
306 print_device(const char *uri
, /* I - Device URI */
307 const char *hostname
, /* I - Hostname/manufacturer */
308 const char *resource
, /* I - Resource/modelname */
309 char *options
, /* I - Device options/serial number */
310 int print_fd
, /* I - File descriptor to print */
311 int copies
, /* I - Copies to print */
312 int argc
, /* I - Number of command-line arguments (6 or 7) */
313 char *argv
[]) /* I - Command-line arguments */
315 char serial
[1024]; /* Serial number buffer */
316 OSStatus status
; /* Function results */
317 pthread_t read_thread_id
, /* Read thread */
318 sidechannel_thread_id
;/* Side-channel thread */
319 int have_sidechannel
= 0; /* Was the side-channel thread started? */
320 struct stat sidechannel_info
; /* Side-channel file descriptor info */
321 char print_buffer
[8192], /* Print data buffer */
322 *print_ptr
; /* Pointer into print data buffer */
323 UInt32 location
; /* Unique location in bus topology */
324 fd_set input_set
; /* Input set for select() */
325 CFStringRef driverBundlePath
; /* Class driver path */
326 int countdown
, /* Logging interval */
327 nfds
; /* Number of file descriptors */
328 ssize_t total_bytes
; /* Total bytes written */
329 UInt32 bytes
; /* Bytes written */
330 struct timeval
*timeout
, /* Timeout pointer */
331 stimeout
; /* Timeout for select() */
332 struct timespec cond_timeout
; /* pthread condition timeout */
336 * See if the side-channel descriptor is valid...
339 have_sidechannel
= !fstat(CUPS_SC_FD
, &sidechannel_info
) &&
340 S_ISSOCK(sidechannel_info
.st_mode
);
343 * Localize using CoreFoundation...
348 parse_options(options
, serial
, sizeof(serial
), &location
, &g
.wait_eof
);
350 if (resource
[0] == '/')
353 g
.print_fd
= print_fd
;
354 g
.make
= cfstr_create_trim(hostname
);
355 g
.model
= cfstr_create_trim(resource
);
356 g
.serial
= cfstr_create_trim(serial
);
357 g
.location
= location
;
359 if (!g
.make
|| !g
.model
)
361 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error!\n"));
364 fputs("DEBUG: USB make string is NULL!\n", stderr
);
366 fputs("DEBUG: USB model string is NULL!\n", stderr
);
368 return (CUPS_BACKEND_STOP
);
371 fputs("STATE: +connecting-to-device\n", stderr
);
373 countdown
= INITIAL_LOG_INTERVAL
;
379 IOObjectRelease(g
.printer_obj
);
380 unload_classdriver(&g
.classdriver
);
385 fprintf(stderr
, "DEBUG: Looking for '%s %s'\n", hostname
, resource
);
387 iterate_printers(find_device_cb
, NULL
);
389 fputs("DEBUG: Opening connection\n", stderr
);
391 driverBundlePath
= NULL
;
393 status
= registry_open(&driverBundlePath
);
395 #if defined(__i386__)
397 * If we were unable to load the class drivers for this printer it's probably because they're ppc-only.
398 * In this case try to fork & exec this backend as a ppc executable so we can use them...
402 run_ppc_backend(argc
, argv
, print_fd
);
403 /* Never returns here */
405 #endif /* __i386__ */
410 * If we still were unable to load the class drivers for this printer log
411 * the error and stop the queue...
414 if (driverBundlePath
== NULL
|| !CFStringGetCString(driverBundlePath
, print_buffer
, sizeof(print_buffer
), kCFStringEncodingUTF8
))
415 strlcpy(print_buffer
, "USB class driver", sizeof(print_buffer
));
417 fputs("STATE: +apple-missing-usbclassdriver-error\n", stderr
);
418 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error!\n"));
419 fprintf(stderr
, "DEBUG: Could not load %s\n", print_buffer
);
421 if (driverBundlePath
)
422 CFRelease(driverBundlePath
);
424 return (CUPS_BACKEND_STOP
);
427 if (driverBundlePath
)
428 CFRelease(driverBundlePath
);
432 sleep(PRINTER_POLLING_INTERVAL
);
433 countdown
-= PRINTER_POLLING_INTERVAL
;
436 _cupsLangPuts(stderr
,
437 _("INFO: Waiting for printer to become available...\n"));
438 fprintf(stderr
, "DEBUG: USB printer status: 0x%08x\n", (int)status
);
439 countdown
= SUBSEQUENT_LOG_INTERVAL
; /* subsequent log entries, every 15 seconds */
442 } while (status
!= noErr
);
444 fputs("STATE: -connecting-to-device\n", stderr
);
447 * Now that we are "connected" to the port, ignore SIGTERM so that we
448 * can finish out any page data the driver sends (e.g. to eject the
449 * current page... Only ignore SIGTERM if we are printing data from
450 * stdin (otherwise you can't cancel raw jobs...)
455 struct sigaction action
; /* POSIX signal action */
458 memset(&action
, 0, sizeof(action
));
460 sigemptyset(&action
.sa_mask
);
461 action
.sa_handler
= SIG_IGN
;
462 sigaction(SIGTERM
, &action
, NULL
);
466 * Start the side channel thread if the descriptor is valid...
469 pthread_mutex_init(&g
.readwrite_lock_mutex
, NULL
);
470 pthread_cond_init(&g
.readwrite_lock_cond
, NULL
);
471 g
.readwrite_lock
= 1;
473 if (have_sidechannel
)
475 g
.sidechannel_thread_stop
= 0;
476 g
.sidechannel_thread_done
= 0;
478 pthread_cond_init(&g
.sidechannel_thread_cond
, NULL
);
479 pthread_mutex_init(&g
.sidechannel_thread_mutex
, NULL
);
481 if (pthread_create(&sidechannel_thread_id
, NULL
, sidechannel_thread
, NULL
))
483 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error!\n"));
484 fputs("DEBUG: Couldn't create side-channel thread!\n", stderr
);
485 return (CUPS_BACKEND_STOP
);
490 * Get the read thread going...
493 g
.read_thread_stop
= 0;
494 g
.read_thread_done
= 0;
496 pthread_cond_init(&g
.read_thread_cond
, NULL
);
497 pthread_mutex_init(&g
.read_thread_mutex
, NULL
);
499 if (pthread_create(&read_thread_id
, NULL
, read_thread
, NULL
))
501 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error!\n"));
502 fputs("DEBUG: Couldn't create read thread!\n", stderr
);
503 return (CUPS_BACKEND_STOP
);
507 * The main thread sends the print file...
513 print_ptr
= print_buffer
;
515 while (status
== noErr
&& copies
-- > 0)
517 _cupsLangPuts(stderr
, _("INFO: Sending print data...\n"));
519 if (print_fd
!= STDIN_FILENO
)
521 fputs("PAGE: 1 1", stderr
);
522 lseek(print_fd
, 0, SEEK_SET
);
525 while (status
== noErr
)
530 FD_SET(print_fd
, &input_set
);
533 * Calculate select timeout...
534 * If we have data waiting to send timeout is 100ms.
535 * else if we're draining print_fd timeout is 0.
536 * else we're waiting forever...
542 stimeout
.tv_usec
= 100000; /* 100ms */
545 else if (g
.drain_output
)
548 stimeout
.tv_usec
= 0;
555 * I/O is unlocked around select...
558 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
559 g
.readwrite_lock
= 0;
560 pthread_cond_signal(&g
.readwrite_lock_cond
);
561 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
563 nfds
= select(print_fd
+ 1, &input_set
, NULL
, NULL
, timeout
);
566 * Reacquire the lock...
569 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
570 while (g
.readwrite_lock
)
571 pthread_cond_wait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
);
572 g
.readwrite_lock
= 1;
573 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
577 if (errno
== EINTR
&& total_bytes
== 0)
579 fputs("DEBUG: Received an interrupt before any bytes were "
580 "written, aborting!\n", stderr
);
583 else if (errno
!= EAGAIN
)
585 _cupsLangPuts(stderr
, _("ERROR: Unable to read print data!\n"));
586 perror("DEBUG: select");
587 return (CUPS_BACKEND_STOP
);
592 * If drain output has finished send a response...
595 if (g
.drain_output
&& !nfds
&& !g
.print_bytes
)
597 /* Send a response... */
598 cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
603 * Check if we have print data ready...
606 if (FD_ISSET(print_fd
, &input_set
))
608 g
.print_bytes
= read(print_fd
, print_buffer
, sizeof(print_buffer
));
610 if (g
.print_bytes
< 0)
613 * Read error - bail if we don't see EAGAIN or EINTR...
616 if (errno
!= EAGAIN
|| errno
!= EINTR
)
618 _cupsLangPuts(stderr
, _("ERROR: Unable to read print data!\n"));
619 perror("DEBUG: read");
620 return CUPS_BACKEND_STOP
;
625 else if (g
.print_bytes
== 0)
628 * End of file, break out of the loop...
634 print_ptr
= print_buffer
;
636 fprintf(stderr
, "DEBUG: Read %d bytes of print data...\n",
642 bytes
= g
.print_bytes
;
644 status
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
647 * Ignore timeout errors...
650 if (status
== kIOUSBTransactionTimeout
)
656 if (status
|| bytes
< 0)
659 * Write error - bail if we don't see an error we can retry...
662 OSStatus err
= (*g
.classdriver
)->Abort(g
.classdriver
);
663 _cupsLangPuts(stderr
, _("ERROR: Unable to send print data!\n"));
664 fprintf(stderr
, "DEBUG: USB class driver WritePipe returned %ld\n",
666 fprintf(stderr
, "DEBUG: USB class driver Abort returned %ld\n",
668 status
= CUPS_BACKEND_STOP
;
672 fprintf(stderr
, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes
);
674 g
.print_bytes
-= bytes
;
676 total_bytes
+= bytes
;
679 if (print_fd
!= 0 && status
== noErr
)
680 fprintf(stderr
, "DEBUG: Sending print file, %lld bytes...\n",
685 fprintf(stderr
, "DEBUG: Sent %lld bytes...\n", (off_t
)total_bytes
);
688 * Wait for the side channel thread to exit...
691 if (have_sidechannel
)
694 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
695 g
.readwrite_lock
= 0;
696 pthread_cond_signal(&g
.readwrite_lock_cond
);
697 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
699 g
.sidechannel_thread_stop
= 1;
700 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
701 if (!g
.sidechannel_thread_done
)
704 * Wait for the side-channel thread to exit...
707 cond_timeout
.tv_sec
= time(NULL
) + WAIT_SIDE_DELAY
;
708 cond_timeout
.tv_nsec
= 0;
709 if (pthread_cond_timedwait(&g
.sidechannel_thread_cond
,
710 &g
.sidechannel_thread_mutex
,
714 * Force the side-channel thread to exit...
717 pthread_kill(sidechannel_thread_id
, SIGTERM
);
720 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
722 pthread_join(sidechannel_thread_id
, NULL
);
724 pthread_cond_destroy(&g
.sidechannel_thread_cond
);
725 pthread_mutex_destroy(&g
.sidechannel_thread_mutex
);
728 pthread_cond_destroy(&g
.readwrite_lock_cond
);
729 pthread_mutex_destroy(&g
.readwrite_lock_mutex
);
732 * Signal the read thread to stop...
735 g
.read_thread_stop
= 1;
738 * Give the read thread WAIT_EOF_DELAY seconds to complete all the data. If
739 * we are not signaled in that time then force the thread to exit.
742 pthread_mutex_lock(&g
.read_thread_mutex
);
744 if (!g
.read_thread_done
)
746 cond_timeout
.tv_sec
= time(NULL
) + WAIT_EOF_DELAY
;
747 cond_timeout
.tv_nsec
= 0;
749 if (pthread_cond_timedwait(&g
.read_thread_cond
, &g
.read_thread_mutex
,
753 * Force the read thread to exit...
756 pthread_kill(read_thread_id
, SIGTERM
);
759 pthread_mutex_unlock(&g
.read_thread_mutex
);
761 pthread_join(read_thread_id
, NULL
); /* wait for the read thread to return */
763 pthread_cond_destroy(&g
.read_thread_cond
);
764 pthread_mutex_destroy(&g
.read_thread_mutex
);
767 * Close the connection and input file and general clean up...
772 if (print_fd
!= STDIN_FILENO
)
781 if (g
.serial
!= NULL
)
784 if (g
.printer_obj
!= 0x0)
785 IOObjectRelease(g
.printer_obj
);
792 * 'read_thread()' - Thread to read the backchannel data on.
795 static void *read_thread(void *reference
)
797 UInt8 readbuffer
[512];
799 kern_return_t readstatus
;
800 struct mach_timebase_info timeBaseInfo
;
804 /* Calculate what 250 milliSeconds are in mach absolute time...
806 mach_timebase_info(&timeBaseInfo
);
807 delay
= ((uint64_t)250000000 * (uint64_t)timeBaseInfo
.denom
) / (uint64_t)timeBaseInfo
.numer
;
812 * Remember when we started so we can throttle the loop after the read call...
815 start
= mach_absolute_time();
817 rbytes
= sizeof(readbuffer
);
818 readstatus
= (*g
.classdriver
)->ReadPipe(g
.classdriver
, readbuffer
, &rbytes
);
819 if (readstatus
== kIOReturnSuccess
&& rbytes
> 0)
821 cupsBackChannelWrite((char*)readbuffer
, rbytes
, 1.0);
823 /* cntrl-d is echoed by the printer.
825 * Xerox Phaser 6250D doesn't echo the cntrl-d.
826 * Xerox Phaser 6250D doesn't always send the product query.
828 if (g
.wait_eof
&& readbuffer
[rbytes
-1] == 0x4)
831 #ifdef PARSE_PS_ERRORS
832 parse_pserror(readbuffer
, rbytes
);
837 * Make sure this loop executes no more than once every 250 miliseconds...
840 if ((readstatus
!= kIOReturnSuccess
|| rbytes
== 0) && (g
.wait_eof
|| !g
.read_thread_stop
))
841 mach_wait_until(start
+ delay
);
843 } while (g
.wait_eof
|| !g
.read_thread_stop
); /* Abort from main thread tests error here */
846 * Let the main thread know that we have completed the read thread...
849 pthread_mutex_lock(&g
.read_thread_mutex
);
850 g
.read_thread_done
= 1;
851 pthread_cond_signal(&g
.read_thread_cond
);
852 pthread_mutex_unlock(&g
.read_thread_mutex
);
859 * 'sidechannel_thread()' - Handle side-channel requests.
863 sidechannel_thread(void *reference
)
865 cups_sc_command_t command
; /* Request command */
866 cups_sc_status_t status
; /* Request/response status */
867 char data
[2048]; /* Request/response data */
868 int datalen
; /* Request/response data size */
873 datalen
= sizeof(data
);
875 if (cupsSideChannelRead(&command
, &status
, data
, &datalen
, 1.0))
880 case CUPS_SC_CMD_SOFT_RESET
: /* Do a soft reset */
881 if ((*g
.classdriver
)->SoftReset
!= NULL
)
884 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
888 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
893 case CUPS_SC_CMD_DRAIN_OUTPUT
: /* Drain all pending output */
897 case CUPS_SC_CMD_GET_BIDI
: /* Is the connection bidirectional? */
898 data
[0] = g
.bidi_flag
;
899 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
902 case CUPS_SC_CMD_GET_DEVICE_ID
: /* Return IEEE-1284 device ID */
903 datalen
= sizeof(data
);
904 get_device_id(&status
, data
, &datalen
);
905 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, datalen
, 1.0);
908 case CUPS_SC_CMD_GET_STATE
: /* Return device state */
909 data
[0] = CUPS_SC_STATE_ONLINE
;
910 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
914 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
919 while (!g
.sidechannel_thread_stop
);
921 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
922 g
.sidechannel_thread_done
= 1;
923 pthread_cond_signal(&g
.sidechannel_thread_cond
);
924 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
932 * 'iterate_printers()' - Iterate over all the printers.
935 static void iterate_printers(iterator_callback_t callBack
,
938 mach_port_t masterPort
= 0x0;
939 kern_return_t kr
= IOMasterPort (bootstrap_port
, &masterPort
);
941 if (kr
== kIOReturnSuccess
&& masterPort
!= 0x0)
943 io_iterator_t addIterator
= 0x0;
945 iterator_reference_t reference
= { callBack
, userdata
, true };
946 IONotificationPortRef addNotification
= IONotificationPortCreate(masterPort
);
948 int klass
= kUSBPrintingClass
;
949 int subklass
= kUSBPrintingSubclass
;
951 CFNumberRef usb_klass
= CFNumberCreate(NULL
, kCFNumberIntType
, &klass
);
952 CFNumberRef usb_subklass
= CFNumberCreate(NULL
, kCFNumberIntType
, &subklass
);
953 CFMutableDictionaryRef usbPrinterMatchDictionary
= IOServiceMatching(kIOUSBInterfaceClassName
);
955 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceClass"), usb_klass
);
956 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceSubClass"), usb_subklass
);
958 CFRelease(usb_klass
);
959 CFRelease(usb_subklass
);
961 kr
= IOServiceAddMatchingNotification(addNotification
, kIOMatchedNotification
, usbPrinterMatchDictionary
, &device_added
, &reference
, &addIterator
);
962 if (addIterator
!= 0x0)
964 device_added (&reference
, addIterator
);
966 if (reference
.keepRunning
)
968 CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification
), kCFRunLoopDefaultMode
);
971 IOObjectRelease(addIterator
);
973 mach_port_deallocate(mach_task_self(), masterPort
);
979 * 'device_added()' - Device added notifier.
982 static void device_added(void *userdata
,
983 io_iterator_t iterator
)
985 iterator_reference_t
*reference
= userdata
;
988 while (reference
->keepRunning
&& (obj
= IOIteratorNext(iterator
)) != 0x0)
990 if (reference
->callback
!= NULL
)
991 reference
->keepRunning
= reference
->callback(reference
->userdata
, obj
);
993 IOObjectRelease(obj
);
996 /* One last call to the call back now that we are not longer have printers left to iterate...
998 if (reference
->keepRunning
)
999 reference
->keepRunning
= reference
->callback(reference
->userdata
, 0x0);
1001 if (!reference
->keepRunning
)
1002 CFRunLoopStop(CFRunLoopGetCurrent());
1007 * 'list_device_cb()' - list_device iterator callback.
1010 static Boolean
list_device_cb(void *refcon
,
1013 Boolean keepRunning
= (obj
!= 0x0);
1017 CFStringRef deviceIDString
= NULL
;
1018 UInt32 deviceLocation
= 0;
1019 UInt8 interfaceNum
= 0;
1021 copy_devicestring(obj
, &deviceIDString
, &deviceLocation
, &interfaceNum
);
1022 if (deviceIDString
!= NULL
)
1024 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1025 char uristr
[1024], makestr
[1024], modelstr
[1024], serialstr
[1024];
1026 char optionsstr
[1024], idstr
[1024], make_modelstr
[1024];
1028 copy_deviceinfo(deviceIDString
, &make
, &model
, &serial
);
1029 CFStringGetCString(deviceIDString
, idstr
, sizeof(idstr
),
1030 kCFStringEncodingUTF8
);
1031 backendGetMakeModel(idstr
, make_modelstr
, sizeof(make_modelstr
));
1035 if (!CFStringGetCString(make
, makestr
, sizeof(makestr
),
1036 kCFStringEncodingUTF8
))
1037 strcpy(makestr
, "Unknown");
1039 if (!CFStringGetCString(model
, &modelstr
[1], sizeof(modelstr
)-1,
1040 kCFStringEncodingUTF8
))
1041 strcpy(modelstr
+ 1, "Printer");
1043 optionsstr
[0] = '\0';
1046 CFStringGetCString(serial
, serialstr
, sizeof(serialstr
), kCFStringEncodingUTF8
);
1047 snprintf(optionsstr
, sizeof(optionsstr
), "?serial=%s", serialstr
);
1049 else if (deviceLocation
!= 0)
1050 snprintf(optionsstr
, sizeof(optionsstr
), "?location=%x", (unsigned)deviceLocation
);
1052 httpAssembleURI(HTTP_URI_CODING_ALL
, uristr
, sizeof(uristr
), "usb", NULL
, makestr
, 0, modelstr
);
1053 strncat(uristr
, optionsstr
, sizeof(uristr
));
1055 printf("direct %s \"%s\" \"%s USB\" \"%s\"\n", uristr
, make_modelstr
,
1056 make_modelstr
, idstr
);
1058 release_deviceinfo(&make
, &model
, &serial
);
1059 CFRelease(deviceIDString
);
1068 * 'find_device_cb()' - print_device iterator callback.
1071 static Boolean
find_device_cb(void *refcon
,
1074 Boolean keepLooking
= true;
1078 CFStringRef idString
= NULL
;
1079 UInt32 location
= -1;
1080 UInt8 interfaceNum
= 0;
1082 copy_devicestring(obj
, &idString
, &location
, &interfaceNum
);
1083 if (idString
!= NULL
)
1085 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1087 copy_deviceinfo(idString
, &make
, &model
, &serial
);
1088 if (make
&& CFStringCompare(make
, g
.make
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1090 if (model
&& CFStringCompare(model
, g
.model
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1092 if (g
.serial
!= NULL
&& CFStringGetLength(g
.serial
) > 0)
1094 if (serial
!= NULL
&& CFStringCompare(serial
, g
.serial
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1096 IOObjectRetain(obj
);
1097 g
.printer_obj
= obj
;
1098 keepLooking
= false;
1103 if (g
.printer_obj
!= 0)
1104 IOObjectRelease(g
.printer_obj
);
1106 g
.printer_obj
= obj
;
1107 IOObjectRetain(obj
);
1109 if (g
.location
== 0 || g
.location
== location
)
1110 keepLooking
= false;
1113 g
.interfaceNum
= interfaceNum
;
1117 release_deviceinfo(&make
, &model
, &serial
);
1118 CFRelease(idString
);
1123 keepLooking
= (g
.printer_obj
== 0);
1124 if (obj
== 0x0 && keepLooking
)
1126 CFRunLoopTimerContext context
= { 0, refcon
, NULL
, NULL
, NULL
};
1127 CFRunLoopTimerRef timer
= CFRunLoopTimerCreate(NULL
, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb
, &context
);
1130 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer
, kCFRunLoopDefaultMode
);
1131 g
.status_timer
= timer
;
1136 if (!keepLooking
&& g
.status_timer
!= NULL
)
1138 fputs("STATE: -offline-error\n", stderr
);
1139 _cupsLangPuts(stderr
, _("INFO: Printer is now online.\n"));
1140 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g
.status_timer
, kCFRunLoopDefaultMode
);
1141 CFRelease(g
.status_timer
);
1142 g
.status_timer
= NULL
;
1150 * 'status_timer_cb()' - Status timer callback.
1153 static void status_timer_cb(CFRunLoopTimerRef timer
,
1156 fputs("STATE: +offline-error\n", stderr
);
1157 _cupsLangPuts(stderr
, _("INFO: Printer is currently offline.\n"));
1159 if (getenv("CLASS") != NULL
)
1162 * If the CLASS environment variable is set, the job was submitted
1163 * to a class and not to a specific queue. In this case, we want
1164 * to abort immediately so that the job can be requeued on the next
1165 * available printer in the class.
1167 * Sleep 5 seconds to keep the job from requeuing too rapidly...
1172 exit(CUPS_BACKEND_FAILED
);
1179 * 'copy_deviceinfo()' - Copy strings from the 1284 device ID.
1182 static void copy_deviceinfo(CFStringRef deviceIDString
,
1185 CFStringRef
*serial
)
1187 CFStringRef modelKeys
[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL
};
1188 CFStringRef makeKeys
[] = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL
};
1189 CFStringRef serialKeys
[] = { CFSTR("SN:"), CFSTR("SERN:"), NULL
};
1193 if ((*make
= copy_value_for_key(deviceIDString
, makeKeys
)) == NULL
)
1194 *make
= CFStringCreateWithCString(kCFAllocatorDefault
, "Unknown",
1195 kCFStringEncodingUTF8
);
1200 if ((*model
= copy_value_for_key(deviceIDString
, modelKeys
)) == NULL
)
1201 *model
= CFStringCreateWithCString(kCFAllocatorDefault
, "Printer",
1202 kCFStringEncodingUTF8
);
1206 *serial
= copy_value_for_key(deviceIDString
, serialKeys
);
1211 * 'release_deviceinfo()' - Release deviceinfo strings.
1214 static void release_deviceinfo(CFStringRef
*make
,
1216 CFStringRef
*serial
)
1218 if (make
!= NULL
&& *make
!= NULL
)
1224 if (model
!= NULL
&& *model
!= NULL
)
1230 if (serial
!= NULL
&& *serial
!= NULL
)
1240 * 'load_classdriver()' - Load a classdriver.
1243 static kern_return_t
load_classdriver(CFStringRef driverPath
,
1244 printer_interface_t intf
,
1245 classdriver_t
***printerDriver
)
1247 kern_return_t kr
= kUSBPrinterClassDeviceNotOpen
;
1248 classdriver_t
**driver
= NULL
;
1249 CFStringRef bundle
= (driverPath
== NULL
? kUSBGenericTOPrinterClassDriver
: driverPath
);
1253 CFURLRef url
= CFURLCreateWithFileSystemPath(NULL
, bundle
, kCFURLPOSIXPathStyle
, true);
1254 CFPlugInRef plugin
= (url
!= NULL
? CFPlugInCreate(NULL
, url
) : NULL
);
1261 CFArrayRef factories
= CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID
, plugin
);
1262 if (factories
!= NULL
&& CFArrayGetCount(factories
) > 0)
1264 CFUUIDRef factoryID
= CFArrayGetValueAtIndex(factories
, 0);
1265 IUnknownVTbl
**iunknown
= CFPlugInInstanceCreate(NULL
, factoryID
, kUSBPrinterClassTypeID
);
1266 if (iunknown
!= NULL
)
1268 kr
= (*iunknown
)->QueryInterface(iunknown
, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID
), (LPVOID
*)&driver
);
1269 if (kr
== kIOReturnSuccess
&& driver
!= NULL
)
1271 classdriver_t
**genericDriver
= NULL
;
1272 if (driverPath
!= NULL
&& CFStringCompare(driverPath
, kUSBGenericTOPrinterClassDriver
, 0) != kCFCompareEqualTo
)
1273 kr
= load_classdriver(NULL
, intf
, &genericDriver
);
1275 if (kr
== kIOReturnSuccess
)
1277 (*driver
)->interface
= intf
;
1278 (*driver
)->Initialize(driver
, genericDriver
);
1280 (*driver
)->plugin
= plugin
;
1281 (*driver
)->interface
= intf
;
1282 *printerDriver
= driver
;
1285 (*iunknown
)->Release(iunknown
);
1287 CFRelease(factories
);
1293 char bundlestr
[1024];
1294 CFStringGetCString(bundle
, bundlestr
, sizeof(bundlestr
), kCFStringEncodingUTF8
);
1295 fprintf(stderr
, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr
, (int)kr
);
1303 * 'unload_classdriver()' - Unload a classdriver.
1306 static kern_return_t
unload_classdriver(classdriver_t
***classdriver
)
1308 if (*classdriver
!= NULL
)
1310 (**classdriver
)->Release(*classdriver
);
1311 *classdriver
= NULL
;
1314 return kIOReturnSuccess
;
1319 * 'load_printerdriver()' - Load vendor's classdriver.
1321 * If driverBundlePath is not NULL on return it is the callers responsbility to release it!
1324 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
)
1326 IOCFPlugInInterface
**iodev
= NULL
;
1329 printer_interface_t intf
;
1332 kr
= IOCreatePlugInInterfaceForService(g
.printer_obj
, kIOUSBInterfaceUserClientTypeID
, kIOCFPlugInInterfaceID
, &iodev
, &score
);
1333 if (kr
== kIOReturnSuccess
)
1335 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*) &intf
)) == noErr
)
1337 *driverBundlePath
= IORegistryEntryCreateCFProperty(g
.printer_obj
, kUSBClassDriverProperty
, NULL
, kNilOptions
);
1339 kr
= load_classdriver(*driverBundlePath
, intf
, &g
.classdriver
);
1341 if (kr
!= kIOReturnSuccess
)
1342 (*intf
)->Release(intf
);
1344 IODestroyPlugInInterface(iodev
);
1351 * 'registry_open()' - Open a connection to the printer.
1354 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
)
1356 g
.bidi_flag
= 0; /* 0=unidirectional */
1358 kern_return_t kr
= load_printerdriver(driverBundlePath
);
1359 if (kr
!= kIOReturnSuccess
)
1362 if (g
.classdriver
!= NULL
)
1364 (*g
.classdriver
)->interfaceNumber
= g
.interfaceNum
;
1365 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolBidirectional
);
1366 if (kr
!= kIOReturnSuccess
|| (*g
.classdriver
)->interface
== NULL
)
1368 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolUnidirectional
);
1369 if (kr
== kIOReturnSuccess
)
1371 if ((*g
.classdriver
)->interface
== NULL
)
1373 (*g
.classdriver
)->Close(g
.classdriver
);
1379 g
.bidi_flag
= 1; /* 1=bidirectional */
1382 if (kr
!= kIOReturnSuccess
)
1383 unload_classdriver(&g
.classdriver
);
1390 * 'registry_close()' - Close the connection to the printer.
1393 static kern_return_t
registry_close()
1395 if (g
.classdriver
!= NULL
)
1396 (*g
.classdriver
)->Close(g
.classdriver
);
1398 unload_classdriver(&g
.classdriver
);
1399 return kIOReturnSuccess
;
1404 * 'copy_deviceid()' - Copy the 1284 device id string.
1407 static OSStatus
copy_deviceid(classdriver_t
**classdriver
,
1408 CFStringRef
*deviceID
)
1410 CFStringRef devID
= NULL
,
1414 deviceSerial
= NULL
;
1416 OSStatus err
= (*classdriver
)->GetDeviceID(classdriver
, &devID
, DEFAULT_TIMEOUT
);
1418 copy_deviceinfo(devID
, &deviceMake
, &deviceModel
, &deviceSerial
);
1420 if (deviceMake
== NULL
|| deviceModel
== NULL
|| deviceSerial
== NULL
)
1422 IOUSBDeviceDescriptor desc
;
1423 iodevice_request_t request
;
1425 request
.requestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
1426 request
.request
= kUSBRqGetDescriptor
;
1427 request
.value
= (kUSBDeviceDesc
<< 8) | 0;
1429 request
.length
= sizeof(desc
);
1430 request
.buffer
= &desc
;
1431 err
= (*classdriver
)->DeviceRequest(classdriver
, &request
, DEFAULT_TIMEOUT
);
1432 if (err
== kIOReturnSuccess
)
1434 CFMutableStringRef newDevID
= CFStringCreateMutable(NULL
, 0);
1436 if (deviceMake
== NULL
)
1438 CFStringRef data
= NULL
;
1439 err
= (*classdriver
)->GetString(classdriver
, desc
.iManufacturer
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1442 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MFG:%@;"), data
);
1447 if (deviceModel
== NULL
)
1449 CFStringRef data
= NULL
;
1450 err
= (*classdriver
)->GetString(classdriver
, desc
.iProduct
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1453 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MDL:%@;"), data
);
1458 if (deviceSerial
== NULL
&& desc
.iSerialNumber
!= 0)
1460 CFStringRef data
= NULL
;
1461 err
= (*classdriver
)->GetString(classdriver
, desc
.iSerialNumber
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1464 CFStringAppendFormat(newDevID
, NULL
, CFSTR("SERN:%@;"), data
);
1471 CFStringAppend(newDevID
, devID
);
1475 *deviceID
= newDevID
;
1482 release_deviceinfo(&deviceMake
, &deviceModel
, &deviceSerial
);
1489 * 'copy_devicestring()' - Copy the 1284 device id string.
1492 static void copy_devicestring(io_service_t usbInterface
,
1493 CFStringRef
*deviceID
,
1494 UInt32
*deviceLocation
,
1495 UInt8
*interfaceNumber
)
1497 IOCFPlugInInterface
**iodev
= NULL
;
1500 printer_interface_t intf
;
1502 classdriver_t
**klassDriver
= NULL
;
1503 CFStringRef driverBundlePath
;
1505 if ((kr
= IOCreatePlugInInterfaceForService(usbInterface
,
1506 kIOUSBInterfaceUserClientTypeID
,
1507 kIOCFPlugInInterfaceID
,
1508 &iodev
, &score
)) == kIOReturnSuccess
)
1510 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*)
1513 (*intf
)->GetLocationID(intf
, deviceLocation
);
1514 (*intf
)->GetInterfaceNumber(intf
, interfaceNumber
);
1516 driverBundlePath
= IORegistryEntryCreateCFProperty(usbInterface
,
1517 kUSBClassDriverProperty
,
1520 kr
= load_classdriver(driverBundlePath
, intf
, &klassDriver
);
1522 if (kr
!= kIOReturnSuccess
&& driverBundlePath
!= NULL
)
1523 kr
= load_classdriver(NULL
, intf
, &klassDriver
);
1525 if (kr
== kIOReturnSuccess
&& klassDriver
!= NULL
)
1526 kr
= copy_deviceid(klassDriver
, deviceID
);
1528 unload_classdriver(&klassDriver
);
1530 if (driverBundlePath
!= NULL
)
1531 CFRelease(driverBundlePath
);
1533 /* (*intf)->Release(intf); */
1535 IODestroyPlugInInterface(iodev
);
1542 * 'copy_value_for_key()' - Copy value string associated with a key.
1545 static CFStringRef
copy_value_for_key(CFStringRef deviceID
,
1548 CFStringRef value
= NULL
;
1549 CFArrayRef kvPairs
= deviceID
!= NULL
? CFStringCreateArrayBySeparatingStrings(NULL
, deviceID
, CFSTR(";")) : NULL
;
1550 CFIndex max
= kvPairs
!= NULL
? CFArrayGetCount(kvPairs
) : 0;
1553 while (idx
< max
&& value
== NULL
)
1555 CFStringRef kvpair
= CFArrayGetValueAtIndex(kvPairs
, idx
);
1557 while (keys
[idxx
] != NULL
&& value
== NULL
)
1559 CFRange range
= CFStringFind(kvpair
, keys
[idxx
], kCFCompareCaseInsensitive
);
1560 if (range
.length
!= -1)
1562 if (range
.location
!= 0)
1564 CFMutableStringRef theString
= CFStringCreateMutableCopy(NULL
, 0, kvpair
);
1565 CFStringTrimWhitespace(theString
);
1566 range
= CFStringFind(theString
, keys
[idxx
], kCFCompareCaseInsensitive
);
1567 if (range
.location
== 0)
1568 value
= CFStringCreateWithSubstring(NULL
, theString
, CFRangeMake(range
.length
, CFStringGetLength(theString
) - range
.length
));
1570 CFRelease(theString
);
1574 CFStringRef theString
= CFStringCreateWithSubstring(NULL
, kvpair
, CFRangeMake(range
.length
, CFStringGetLength(kvpair
) - range
.length
));
1575 CFMutableStringRef theString2
= CFStringCreateMutableCopy(NULL
, 0, theString
);
1576 CFRelease(theString
);
1578 CFStringTrimWhitespace(theString2
);
1587 if (kvPairs
!= NULL
)
1594 * 'cfstr_create_trim()' - Create CFString and trim whitespace characters.
1597 CFStringRef
cfstr_create_trim(const char *cstr
)
1600 CFMutableStringRef cfmutablestr
= NULL
;
1602 if ((cfstr
= CFStringCreateWithCString(NULL
, cstr
, kCFStringEncodingUTF8
)) != NULL
)
1604 if ((cfmutablestr
= CFStringCreateMutableCopy(NULL
, 1024, cfstr
)) != NULL
)
1605 CFStringTrimWhitespace(cfmutablestr
);
1609 return (CFStringRef
) cfmutablestr
;
1615 * 'parse_options()' - Parse URI options.
1618 static void parse_options(char *options
,
1624 char sep
, /* Separator character */
1625 *name
, /* Name of option */
1626 *value
; /* Value of option */
1645 while (*options
&& *options
!= '=' && *options
!= '+' && *options
!= '&')
1648 if ((sep
= *options
) != '\0')
1659 while (*options
&& *options
!= '+' && *options
!= '&')
1669 * Process the option...
1672 if (!strcasecmp(name
, "waiteof"))
1674 if (!strcasecmp(value
, "on") ||
1675 !strcasecmp(value
, "yes") ||
1676 !strcasecmp(value
, "true"))
1678 else if (!strcasecmp(value
, "off") ||
1679 !strcasecmp(value
, "no") ||
1680 !strcasecmp(value
, "false"))
1683 _cupsLangPrintf(stderr
,
1684 _("WARNING: Boolean expected for waiteof option "
1685 "\"%s\"\n"), value
);
1687 else if (!strcasecmp(name
, "serial"))
1688 strlcpy(serial
, value
, serial_size
);
1689 else if (!strcasecmp(name
, "location") && location
)
1690 *location
= strtol(value
, NULL
, 16);
1696 * @function setup_cfLanguage
1697 * @abstract Convert the contents of the CUPS 'APPLE_LANGUAGE' environment
1698 * variable into a one element CF array of languages.
1700 * @discussion Each submitted job comes with a natural language. CUPS passes
1701 * that language in an environment variable. We take that language
1702 * and jam it into the AppleLanguages array so that CF will use
1703 * it when reading localized resources. We need to do this before
1704 * any CF code reads and caches the languages array, so this function
1705 * should be called early in main()
1707 static void setup_cfLanguage(void)
1709 CFStringRef lang
[1] = {NULL
};
1710 CFArrayRef langArray
= NULL
;
1711 const char *requestedLang
= NULL
;
1713 if ((requestedLang
= getenv("APPLE_LANGUAGE")) == NULL
)
1714 requestedLang
= getenv("LANG");
1716 if (requestedLang
!= NULL
)
1718 lang
[0] = CFStringCreateWithCString(kCFAllocatorDefault
, requestedLang
, kCFStringEncodingUTF8
);
1719 langArray
= CFArrayCreate(kCFAllocatorDefault
, (const void **)lang
, sizeof(lang
) / sizeof(lang
[0]), &kCFTypeArrayCallBacks
);
1721 CFPreferencesSetAppValue(CFSTR("AppleLanguages"), langArray
, kCFPreferencesCurrentApplication
);
1722 fprintf(stderr
, "DEBUG: usb: AppleLanguages=\"%s\"\n", requestedLang
);
1725 CFRelease(langArray
);
1728 fputs("DEBUG: usb: LANG and APPLE_LANGUAGE environment variables missing.\n", stderr
);
1732 #if defined(__i386__)
1734 * @function run_ppc_backend
1736 * @abstract Starts child backend process running as a ppc executable.
1738 * @result Never returns; always calls exit().
1742 static void run_ppc_backend(int argc
,
1749 pid_t waitpid_status
;
1751 char *usb_ppc_status
;
1754 * If we're running as i386 and couldn't load the class driver (because they'it's
1755 * ppc-only) then try to re-exec ourselves in ppc mode to try again. If we don't have
1756 * a ppc architecture we may be running i386 again so guard against this by setting
1757 * and testing an environment variable...
1759 usb_ppc_status
= getenv("USB_PPC_STATUS");
1761 if (usb_ppc_status
== NULL
)
1764 * Setup a SIGTERM handler then block it before forking...
1767 struct sigaction action
; /* POSIX signal action */
1768 sigset_t newmask
, /* New signal mask */
1769 oldmask
; /* Old signal mask */
1771 memset(&action
, 0, sizeof(action
));
1772 sigaddset(&action
.sa_mask
, SIGTERM
);
1773 action
.sa_handler
= sigterm_handler
;
1774 sigaction(SIGTERM
, &action
, NULL
);
1776 sigemptyset(&newmask
);
1777 sigaddset(&newmask
, SIGTERM
);
1778 sigprocmask(SIG_BLOCK
, &newmask
, &oldmask
);
1780 if ((child_pid
= fork()) == 0)
1783 * Child comes here...
1786 setenv("USB_PPC_STATUS", "1", false);
1789 * Unblock signals before doing the exec...
1792 memset(&action
, 0, sizeof(action
));
1793 sigemptyset(&action
.sa_mask
);
1794 action
.sa_handler
= SIG_DFL
;
1795 sigaction(SIGTERM
, &action
, NULL
);
1797 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
1800 * Tell the kernel the next exec call should favor the ppc architecture...
1803 int mib
[] = { CTL_KERN
, KERN_AFFINITY
, 1, 1 };
1805 sysctl(mib
, namelen
, NULL
, NULL
, NULL
, 0);
1808 * Set up the arguments and call exec...
1811 for (i
= 0; i
< argc
&& i
< (sizeof(my_argv
)/sizeof(my_argv
[0])) - 1; i
++)
1812 my_argv
[i
] = argv
[i
];
1816 execv("/usr/libexec/cups/backend/usb", my_argv
);
1818 _cupsLangPrintf(stderr
, _("Unable to use legacy USB class driver!\n"));
1819 perror("DEBUG: Unable to exec /usr/libexec/cups/backend/usb");
1822 else if (child_pid
< 0)
1825 * Error - couldn't fork a new process!
1828 _cupsLangPrintf(stderr
, _("Unable to use legacy USB class driver!\n"));
1829 perror("DEBUG: Unable to fork");
1834 * Unblock signals...
1837 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
1840 * Close the fds we won't be using then wait for the child backend to exit.
1846 fprintf(stderr
, "DEBUG: Started usb(legacy) backend (PID %d)\n",
1849 while ((waitpid_status
= waitpid(child_pid
, &childstatus
, 0)) == (pid_t
)-1 && errno
== EINTR
)
1852 if (WIFSIGNALED(childstatus
))
1854 exitstatus
= WTERMSIG(childstatus
);
1855 fprintf(stderr
, "DEBUG: usb(legacy) backend %d crashed on signal %d!\n",
1856 child_pid
, exitstatus
);
1860 if ((exitstatus
= WEXITSTATUS(childstatus
)) != 0)
1862 "DEBUG: usb(legacy) backend %d stopped with status %d!\n",
1863 child_pid
, exitstatus
);
1865 fprintf(stderr
, "DEBUG: usb(legacy) backend %d exited with no errors\n",
1871 fputs("DEBUG: usb(legacy) backend running native again\n", stderr
);
1872 exitstatus
= ENOENT
;
1879 * 'sigterm_handler()' - SIGTERM handler.
1882 static void sigterm_handler(int sig
)
1884 /* If we started a child process pass the signal on to it...
1887 kill(child_pid
, sig
);
1892 #endif /* __i386__ */
1895 #ifdef PARSE_PS_ERRORS
1897 * 'next_line()' - Find the next line in a buffer.
1900 static const char *next_line (const char *buffer
)
1902 const char *cptr
, *lptr
= NULL
;
1904 for (cptr
= buffer
; *cptr
&& lptr
== NULL
; cptr
++)
1905 if (*cptr
== '\n' || *cptr
== '\r')
1912 * 'parse_pserror()' - Scan the backchannel data for postscript errors.
1915 static void parse_pserror(char *sockBuffer
,
1918 static char gErrorBuffer
[1024] = "";
1919 static char *gErrorBufferPtr
= gErrorBuffer
;
1920 static char *gErrorBufferEndPtr
= gErrorBuffer
+ sizeof(gErrorBuffer
);
1922 char *pCommentBegin
, *pCommentEnd
, *pLineEnd
;
1927 if (gErrorBufferPtr
+ len
> gErrorBufferEndPtr
- 1)
1928 gErrorBufferPtr
= gErrorBuffer
;
1929 if (len
> sizeof(gErrorBuffer
) - 1)
1930 len
= sizeof(gErrorBuffer
) - 1;
1932 memcpy(gErrorBufferPtr
, (const void *)sockBuffer
, len
);
1933 gErrorBufferPtr
+= len
;
1934 *(gErrorBufferPtr
+ 1) = '\0';
1936 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
1937 while (pLineEnd
!= NULL
)
1941 pCommentBegin
= strstr(gErrorBuffer
,"%%[");
1942 pCommentEnd
= strstr(gErrorBuffer
, "]%%");
1943 if (pCommentBegin
!= gErrorBuffer
&& pCommentEnd
!= NULL
)
1945 pCommentEnd
+= 3; /* Skip past "]%%" */
1946 *pCommentEnd
= '\0'; /* There's always room for the nul */
1948 if (strncasecmp(pCommentBegin
, "%%[ Error:", 10) == 0)
1950 else if (strncasecmp(pCommentBegin
, "%%[ Flushing", 12) == 0)
1955 if ((logstrlen
= snprintf(logstr
, sizeof(logstr
), "%s: %s\n", logLevel
, pCommentBegin
)) >= sizeof(logstr
))
1957 /* If the string was trucnated make sure it has a linefeed before the nul */
1958 logstrlen
= sizeof(logstr
) - 1;
1959 logstr
[logstrlen
- 1] = '\n';
1961 write(STDERR_FILENO
, logstr
, logstrlen
);
1964 /* move everything over... */
1965 strcpy(gErrorBuffer
, pLineEnd
);
1966 gErrorBufferPtr
= gErrorBuffer
;
1967 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
1970 #endif /* PARSE_PS_ERRORS */
1974 * 'soft_reset()' - Send a soft reset to the device.
1977 static void soft_reset()
1979 fd_set input_set
; /* Input set for select() */
1980 struct timeval stimeout
; /* Timeout for select() */
1981 char buffer
[2048]; /* Buffer */
1982 struct timespec cond_timeout
; /* pthread condition timeout */
1985 * Send an abort once a second until the I/O lock is released by the main thread...
1988 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
1989 while (g
.readwrite_lock
)
1991 (*g
.classdriver
)->Abort(g
.classdriver
);
1993 cond_timeout
.tv_sec
= time(NULL
) + 1;
1994 cond_timeout
.tv_nsec
= 0;
1996 pthread_cond_timedwait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
, &cond_timeout
);
1999 g
.readwrite_lock
= 1;
2000 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2003 * Flush bytes waiting on print_fd...
2008 FD_ZERO(&input_set
);
2009 FD_SET(g
.print_fd
, &input_set
);
2011 stimeout
.tv_sec
= 0;
2012 stimeout
.tv_usec
= 0;
2014 while (select(g
.print_fd
+1, &input_set
, NULL
, NULL
, &stimeout
) > 0)
2015 if (read(g
.print_fd
, buffer
, sizeof(buffer
)) <= 0)
2022 (*g
.classdriver
)->SoftReset(g
.classdriver
, DEFAULT_TIMEOUT
);
2025 * Release the I/O lock...
2028 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2029 g
.readwrite_lock
= 0;
2030 pthread_cond_signal(&g
.readwrite_lock_cond
);
2031 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2036 * 'get_device_id()' - Return IEEE-1284 device ID.
2039 static void get_device_id(cups_sc_status_t
*status
,
2043 UInt32 deviceLocation
= 0;
2044 UInt8 interfaceNum
= 0;
2045 CFStringRef deviceIDString
= NULL
;
2048 copy_devicestring(g
.printer_obj
, &deviceIDString
, &deviceLocation
, &interfaceNum
);
2051 CFStringGetCString(deviceIDString
, data
, *datalen
, kCFStringEncodingUTF8
);
2052 *datalen
= strlen(data
);
2053 CFRelease(deviceIDString
);
2055 *status
= CUPS_SC_STATUS_OK
;
2060 * End of "$Id: usb-darwin.c 7460 2008-04-16 02:19:54Z mike $".