2 * "$Id: usb-darwin.c 7953 2008-09-17 01:43:19Z 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_legacy_backend() - Re-exec backend as ppc or i386.
69 * sigterm_handler() - SIGTERM handler.
70 * next_line() - Find the next line in a buffer.
71 * parse_pserror() - Scan the backchannel data for postscript errors.
72 * get_device_id() - Return IEEE-1284 device ID.
76 * Include necessary headers.
87 #include <sys/sysctl.h>
89 #include <mach/mach.h>
90 #include <mach/mach_error.h>
91 #include <mach/mach_time.h>
92 #include <cups/debug.h>
93 #include <cups/sidechannel.h>
94 #include <cups/i18n.h>
95 #include "backend-private.h"
97 #include <CoreFoundation/CoreFoundation.h>
98 #include <IOKit/usb/IOUSBLib.h>
99 #include <IOKit/IOCFPlugIn.h>
104 extern char **environ
;
108 * WAIT_EOF_DELAY is number of seconds we'll wait for responses from
109 * the printer after we've finished sending all the data
111 #define WAIT_EOF_DELAY 7
112 #define WAIT_SIDE_DELAY 3
113 #define DEFAULT_TIMEOUT 5000L
115 #define USB_INTERFACE_KIND CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID190)
116 #define kUSBLanguageEnglish 0x409
118 #define PRINTER_POLLING_INTERVAL 5 /* seconds */
119 #define INITIAL_LOG_INTERVAL PRINTER_POLLING_INTERVAL
120 #define SUBSEQUENT_LOG_INTERVAL 3 * INITIAL_LOG_INTERVAL
122 #define kUSBPrinterClassTypeID CFUUIDGetConstantUUIDWithBytes(NULL, 0x06, 0x04, 0x7D, 0x16, 0x53, 0xA2, 0x11, 0xD6, 0x92, 0x06, 0x00, 0x30, 0x65, 0x52, 0x45, 0x92)
123 #define kUSBPrinterClassInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, 0x03, 0x34, 0x6D, 0x74, 0x53, 0xA3, 0x11, 0xD6, 0x9E, 0xA1, 0x76, 0x30, 0x65, 0x52, 0x45, 0x92)
125 #define kUSBClassDriverProperty CFSTR("USB Printing Class")
127 #define kUSBGenericTOPrinterClassDriver CFSTR("/System/Library/Printers/Libraries/USBGenericTOPrintingClass.plugin")
128 #define kUSBPrinterClassDeviceNotOpen -9664 /*kPMInvalidIOMContext*/
132 * Section 5.3 USB Printing Class spec
134 #define kUSBPrintingSubclass 1
135 #define kUSBPrintingProtocolNoOpen 0
136 #define kUSBPrintingProtocolUnidirectional 1
137 #define kUSBPrintingProtocolBidirectional 2
139 typedef IOUSBInterfaceInterface190
**printer_interface_t
;
141 typedef struct iodevice_request_s
/**** Device request ****/
149 } iodevice_request_t
;
151 typedef union /**** Centronics status byte ****/
156 unsigned reserved0
:2;
157 unsigned paperError
:1;
160 unsigned reserved1
:3;
162 } centronics_status_t
;
164 typedef struct classdriver_s
/**** g.classdriver context ****/
167 CFPlugInRef plugin
; /* release plugin */
168 IUnknownVTbl
**factory
; /* Factory */
169 void *vendorReference
; /* vendor class specific usage */
170 UInt32 location
; /* unique location in bus topology */
171 UInt8 interfaceNumber
; /* Interface number */
172 UInt16 vendorID
; /* Vendor id */
173 UInt16 productID
; /* Product id */
174 printer_interface_t interface
; /* identify the device to IOKit */
175 UInt8 outpipe
; /* mandatory bulkOut pipe */
176 UInt8 inpipe
; /* optional bulkIn pipe */
178 /* general class requests */
179 kern_return_t (*DeviceRequest
)(struct classdriver_s
**printer
, iodevice_request_t
*iorequest
, UInt16 timeout
);
180 kern_return_t (*GetString
)(struct classdriver_s
**printer
, UInt8 whichString
, UInt16 language
, UInt16 timeout
, CFStringRef
*result
);
182 /* standard printer class requests */
183 kern_return_t (*SoftReset
)(struct classdriver_s
**printer
, UInt16 timeout
);
184 kern_return_t (*GetCentronicsStatus
)(struct classdriver_s
**printer
, centronics_status_t
*result
, UInt16 timeout
);
185 kern_return_t (*GetDeviceID
)(struct classdriver_s
**printer
, CFStringRef
*devid
, UInt16 timeout
);
187 /* standard bulk device requests */
188 kern_return_t (*ReadPipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
);
189 kern_return_t (*WritePipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
, Boolean eoj
);
191 /* interface requests */
192 kern_return_t (*Open
)(struct classdriver_s
**printer
, UInt32 location
, UInt8 protocol
);
193 kern_return_t (*Abort
)(struct classdriver_s
**printer
);
194 kern_return_t (*Close
)(struct classdriver_s
**printer
);
196 /* initialize and terminate */
197 kern_return_t (*Initialize
)(struct classdriver_s
**printer
, struct classdriver_s
**baseclass
);
198 kern_return_t (*Terminate
)(struct classdriver_s
**printer
);
202 typedef Boolean (*iterator_callback_t
)(void *refcon
, io_service_t obj
);
204 typedef struct iterator_reference_s
/**** Iterator reference data */
206 iterator_callback_t callback
;
209 } iterator_reference_t
;
211 typedef struct globals_s
213 io_service_t printer_obj
;
214 classdriver_t
**classdriver
;
216 pthread_mutex_t read_thread_mutex
;
217 pthread_cond_t read_thread_cond
;
218 int read_thread_stop
;
219 int read_thread_done
;
221 pthread_mutex_t readwrite_lock_mutex
;
222 pthread_cond_t readwrite_lock_cond
;
231 CFRunLoopTimerRef status_timer
;
233 int print_fd
; /* File descriptor to print */
234 ssize_t print_bytes
; /* Print bytes read */
237 int drain_output
; /* Drain all pending output */
238 int bidi_flag
; /* 0=unidirectional, 1=bidirectional */
240 pthread_mutex_t sidechannel_thread_mutex
;
241 pthread_cond_t sidechannel_thread_cond
;
242 int sidechannel_thread_stop
;
243 int sidechannel_thread_done
;
251 globals_t g
= { 0 }; /* Globals */
258 static Boolean
find_device_cb(void *refcon
, io_service_t obj
);
259 static Boolean
list_device_cb(void *refcon
, io_service_t obj
);
260 static CFStringRef
cfstr_create_trim(const char *cstr
);
261 static CFStringRef
copy_value_for_key(CFStringRef deviceID
, CFStringRef
*keys
);
262 static kern_return_t
load_classdriver(CFStringRef driverPath
, printer_interface_t intf
, classdriver_t
***printerDriver
);
263 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
);
264 static kern_return_t
registry_close();
265 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
);
266 static kern_return_t
unload_classdriver();
267 static OSStatus
copy_deviceid(classdriver_t
**printer
, CFStringRef
*deviceID
);
268 static void *read_thread(void *reference
);
269 static void *sidechannel_thread(void *reference
);
270 static void copy_deviceinfo(CFStringRef deviceIDString
, CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
271 static void copy_devicestring(io_service_t usbInterface
, CFStringRef
*deviceID
, UInt32
*deviceLocation
, UInt8
*interfaceNum
);
272 static void device_added(void *userdata
, io_iterator_t iterator
);
273 static void get_device_id(cups_sc_status_t
*status
, char *data
, int *datalen
);
274 static void iterate_printers(iterator_callback_t callBack
, void *userdata
);
275 static void parse_options(char *options
, char *serial
, int serial_size
, UInt32
*location
, Boolean
*wait_eof
);
276 static void release_deviceinfo(CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
277 static void setup_cfLanguage(void);
278 static void soft_reset();
279 static void status_timer_cb(CFRunLoopTimerRef timer
, void *info
);
281 #if defined(__i386__) || defined(__x86_64__)
282 static pid_t child_pid
; /* Child PID */
283 static void run_legacy_backend(int argc
, char *argv
[], int fd
); /* Starts child backend process running as a ppc executable */
284 static void sigterm_handler(int sig
); /* SIGTERM handler */
285 #endif /* __i386__ || __x86_64__ */
287 #ifdef PARSE_PS_ERRORS
288 static const char *next_line (const char *buffer
);
289 static void parse_pserror (char *sockBuffer
, int len
);
290 #endif /* PARSE_PS_ERRORS */
295 * 'list_devices()' - List all USB devices.
300 iterate_printers(list_device_cb
, NULL
);
305 * 'print_device()' - Print a file to a USB device.
308 int /* O - Exit status */
309 print_device(const char *uri
, /* I - Device URI */
310 const char *hostname
, /* I - Hostname/manufacturer */
311 const char *resource
, /* I - Resource/modelname */
312 char *options
, /* I - Device options/serial number */
313 int print_fd
, /* I - File descriptor to print */
314 int copies
, /* I - Copies to print */
315 int argc
, /* I - Number of command-line arguments (6 or 7) */
316 char *argv
[]) /* I - Command-line arguments */
318 char serial
[1024]; /* Serial number buffer */
319 OSStatus status
; /* Function results */
320 pthread_t read_thread_id
, /* Read thread */
321 sidechannel_thread_id
;/* Side-channel thread */
322 int have_sidechannel
= 0; /* Was the side-channel thread started? */
323 struct stat sidechannel_info
; /* Side-channel file descriptor info */
324 char print_buffer
[8192], /* Print data buffer */
325 *print_ptr
; /* Pointer into print data buffer */
326 UInt32 location
; /* Unique location in bus topology */
327 fd_set input_set
; /* Input set for select() */
328 CFStringRef driverBundlePath
; /* Class driver path */
329 int countdown
, /* Logging interval */
330 nfds
; /* Number of file descriptors */
331 ssize_t total_bytes
; /* Total bytes written */
332 UInt32 bytes
; /* Bytes written */
333 struct timeval
*timeout
, /* Timeout pointer */
334 stimeout
; /* Timeout for select() */
335 struct timespec cond_timeout
; /* pthread condition timeout */
339 * See if the side-channel descriptor is valid...
342 have_sidechannel
= !fstat(CUPS_SC_FD
, &sidechannel_info
) &&
343 S_ISSOCK(sidechannel_info
.st_mode
);
346 * Localize using CoreFoundation...
351 parse_options(options
, serial
, sizeof(serial
), &location
, &g
.wait_eof
);
353 if (resource
[0] == '/')
356 g
.print_fd
= print_fd
;
357 g
.make
= cfstr_create_trim(hostname
);
358 g
.model
= cfstr_create_trim(resource
);
359 g
.serial
= cfstr_create_trim(serial
);
360 g
.location
= location
;
362 if (!g
.make
|| !g
.model
)
364 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error!\n"));
367 fputs("DEBUG: USB make string is NULL!\n", stderr
);
369 fputs("DEBUG: USB model string is NULL!\n", stderr
);
371 return (CUPS_BACKEND_STOP
);
374 fputs("STATE: +connecting-to-device\n", stderr
);
376 countdown
= INITIAL_LOG_INTERVAL
;
382 IOObjectRelease(g
.printer_obj
);
383 unload_classdriver(&g
.classdriver
);
388 fprintf(stderr
, "DEBUG: Looking for '%s %s'\n", hostname
, resource
);
390 iterate_printers(find_device_cb
, NULL
);
392 fputs("DEBUG: Opening connection\n", stderr
);
394 driverBundlePath
= NULL
;
396 status
= registry_open(&driverBundlePath
);
398 #if defined(__i386__) || defined(__x86_64__)
400 * If we were unable to load the class drivers for this printer it's
401 * probably because they're ppc or i386. In this case try to run this
402 * backend as i386 or ppc executables so we can use them...
406 run_legacy_backend(argc
, argv
, print_fd
);
407 /* Never returns here */
409 #endif /* __i386__ || __x86_64__ */
414 * If we still were unable to load the class drivers for this printer log
415 * the error and stop the queue...
418 if (driverBundlePath
== NULL
|| !CFStringGetCString(driverBundlePath
, print_buffer
, sizeof(print_buffer
), kCFStringEncodingUTF8
))
419 strlcpy(print_buffer
, "USB class driver", sizeof(print_buffer
));
421 fputs("STATE: +apple-missing-usbclassdriver-error\n", stderr
);
422 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error!\n"));
423 fprintf(stderr
, "DEBUG: Could not load %s\n", print_buffer
);
425 if (driverBundlePath
)
426 CFRelease(driverBundlePath
);
428 return (CUPS_BACKEND_STOP
);
431 if (driverBundlePath
)
432 CFRelease(driverBundlePath
);
436 sleep(PRINTER_POLLING_INTERVAL
);
437 countdown
-= PRINTER_POLLING_INTERVAL
;
440 _cupsLangPuts(stderr
,
441 _("INFO: Waiting for printer to become available...\n"));
442 fprintf(stderr
, "DEBUG: USB printer status: 0x%08x\n", (int)status
);
443 countdown
= SUBSEQUENT_LOG_INTERVAL
; /* subsequent log entries, every 15 seconds */
446 } while (status
!= noErr
);
448 fputs("STATE: -connecting-to-device\n", stderr
);
451 * Now that we are "connected" to the port, ignore SIGTERM so that we
452 * can finish out any page data the driver sends (e.g. to eject the
453 * current page... Only ignore SIGTERM if we are printing data from
454 * stdin (otherwise you can't cancel raw jobs...)
459 struct sigaction action
; /* POSIX signal action */
462 memset(&action
, 0, sizeof(action
));
464 sigemptyset(&action
.sa_mask
);
465 action
.sa_handler
= SIG_IGN
;
466 sigaction(SIGTERM
, &action
, NULL
);
470 * Start the side channel thread if the descriptor is valid...
473 pthread_mutex_init(&g
.readwrite_lock_mutex
, NULL
);
474 pthread_cond_init(&g
.readwrite_lock_cond
, NULL
);
475 g
.readwrite_lock
= 1;
477 if (have_sidechannel
)
479 g
.sidechannel_thread_stop
= 0;
480 g
.sidechannel_thread_done
= 0;
482 pthread_cond_init(&g
.sidechannel_thread_cond
, NULL
);
483 pthread_mutex_init(&g
.sidechannel_thread_mutex
, NULL
);
485 if (pthread_create(&sidechannel_thread_id
, NULL
, sidechannel_thread
, NULL
))
487 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error!\n"));
488 fputs("DEBUG: Couldn't create side-channel thread!\n", stderr
);
489 return (CUPS_BACKEND_STOP
);
494 * Get the read thread going...
497 g
.read_thread_stop
= 0;
498 g
.read_thread_done
= 0;
500 pthread_cond_init(&g
.read_thread_cond
, NULL
);
501 pthread_mutex_init(&g
.read_thread_mutex
, NULL
);
503 if (pthread_create(&read_thread_id
, NULL
, read_thread
, NULL
))
505 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error!\n"));
506 fputs("DEBUG: Couldn't create read thread!\n", stderr
);
507 return (CUPS_BACKEND_STOP
);
511 * The main thread sends the print file...
517 print_ptr
= print_buffer
;
519 while (status
== noErr
&& copies
-- > 0)
521 _cupsLangPuts(stderr
, _("INFO: Sending print data...\n"));
523 if (print_fd
!= STDIN_FILENO
)
525 fputs("PAGE: 1 1\n", stderr
);
526 lseek(print_fd
, 0, SEEK_SET
);
529 while (status
== noErr
)
534 FD_SET(print_fd
, &input_set
);
537 * Calculate select timeout...
538 * If we have data waiting to send timeout is 100ms.
539 * else if we're draining print_fd timeout is 0.
540 * else we're waiting forever...
546 stimeout
.tv_usec
= 100000; /* 100ms */
549 else if (g
.drain_output
)
552 stimeout
.tv_usec
= 0;
559 * I/O is unlocked around select...
562 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
563 g
.readwrite_lock
= 0;
564 pthread_cond_signal(&g
.readwrite_lock_cond
);
565 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
567 nfds
= select(print_fd
+ 1, &input_set
, NULL
, NULL
, timeout
);
570 * Reacquire the lock...
573 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
574 while (g
.readwrite_lock
)
575 pthread_cond_wait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
);
576 g
.readwrite_lock
= 1;
577 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
581 if (errno
== EINTR
&& total_bytes
== 0)
583 fputs("DEBUG: Received an interrupt before any bytes were "
584 "written, aborting!\n", stderr
);
587 else if (errno
!= EAGAIN
)
589 _cupsLangPuts(stderr
, _("ERROR: Unable to read print data!\n"));
590 perror("DEBUG: select");
591 return (CUPS_BACKEND_STOP
);
596 * If drain output has finished send a response...
599 if (g
.drain_output
&& !nfds
&& !g
.print_bytes
)
601 /* Send a response... */
602 cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
607 * Check if we have print data ready...
610 if (FD_ISSET(print_fd
, &input_set
))
612 g
.print_bytes
= read(print_fd
, print_buffer
, sizeof(print_buffer
));
614 if (g
.print_bytes
< 0)
617 * Read error - bail if we don't see EAGAIN or EINTR...
620 if (errno
!= EAGAIN
|| errno
!= EINTR
)
622 _cupsLangPuts(stderr
, _("ERROR: Unable to read print data!\n"));
623 perror("DEBUG: read");
624 return CUPS_BACKEND_STOP
;
629 else if (g
.print_bytes
== 0)
632 * End of file, break out of the loop...
638 print_ptr
= print_buffer
;
640 fprintf(stderr
, "DEBUG: Read %d bytes of print data...\n",
646 bytes
= g
.print_bytes
;
648 status
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
651 * Ignore timeout errors, but retain the number of bytes written to
652 * avoid sending duplicate data (<rdar://problem/6254911>)...
655 if (status
== kIOUSBTransactionTimeout
)
658 if (status
|| bytes
< 0)
661 * Write error - bail if we don't see an error we can retry...
664 OSStatus err
= (*g
.classdriver
)->Abort(g
.classdriver
);
665 _cupsLangPuts(stderr
, _("ERROR: Unable to send print data!\n"));
666 fprintf(stderr
, "DEBUG: USB class driver WritePipe returned %ld\n",
668 fprintf(stderr
, "DEBUG: USB class driver Abort returned %ld\n",
670 status
= CUPS_BACKEND_STOP
;
674 fprintf(stderr
, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes
);
676 g
.print_bytes
-= bytes
;
678 total_bytes
+= bytes
;
681 if (print_fd
!= 0 && status
== noErr
)
682 fprintf(stderr
, "DEBUG: Sending print file, %lld bytes...\n",
687 fprintf(stderr
, "DEBUG: Sent %lld bytes...\n", (off_t
)total_bytes
);
690 * Wait for the side channel thread to exit...
693 if (have_sidechannel
)
696 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
697 g
.readwrite_lock
= 0;
698 pthread_cond_signal(&g
.readwrite_lock_cond
);
699 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
701 g
.sidechannel_thread_stop
= 1;
702 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
703 if (!g
.sidechannel_thread_done
)
706 * Wait for the side-channel thread to exit...
709 cond_timeout
.tv_sec
= time(NULL
) + WAIT_SIDE_DELAY
;
710 cond_timeout
.tv_nsec
= 0;
711 if (pthread_cond_timedwait(&g
.sidechannel_thread_cond
,
712 &g
.sidechannel_thread_mutex
,
716 * Force the side-channel thread to exit...
719 pthread_kill(sidechannel_thread_id
, SIGTERM
);
722 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
724 pthread_join(sidechannel_thread_id
, NULL
);
726 pthread_cond_destroy(&g
.sidechannel_thread_cond
);
727 pthread_mutex_destroy(&g
.sidechannel_thread_mutex
);
730 pthread_cond_destroy(&g
.readwrite_lock_cond
);
731 pthread_mutex_destroy(&g
.readwrite_lock_mutex
);
734 * Signal the read thread to stop...
737 g
.read_thread_stop
= 1;
740 * Give the read thread WAIT_EOF_DELAY seconds to complete all the data. If
741 * we are not signaled in that time then force the thread to exit.
744 pthread_mutex_lock(&g
.read_thread_mutex
);
746 if (!g
.read_thread_done
)
748 cond_timeout
.tv_sec
= time(NULL
) + WAIT_EOF_DELAY
;
749 cond_timeout
.tv_nsec
= 0;
751 if (pthread_cond_timedwait(&g
.read_thread_cond
, &g
.read_thread_mutex
,
755 * Force the read thread to exit...
759 pthread_kill(read_thread_id
, SIGTERM
);
762 pthread_mutex_unlock(&g
.read_thread_mutex
);
764 pthread_join(read_thread_id
, NULL
); /* wait for the read thread to return */
766 pthread_cond_destroy(&g
.read_thread_cond
);
767 pthread_mutex_destroy(&g
.read_thread_mutex
);
770 * Close the connection and input file and general clean up...
775 if (print_fd
!= STDIN_FILENO
)
784 if (g
.serial
!= NULL
)
787 if (g
.printer_obj
!= 0x0)
788 IOObjectRelease(g
.printer_obj
);
795 * 'read_thread()' - Thread to read the backchannel data on.
798 static void *read_thread(void *reference
)
800 UInt8 readbuffer
[512];
802 kern_return_t readstatus
;
803 struct mach_timebase_info timeBaseInfo
;
807 /* Calculate what 250 milliSeconds are in mach absolute time...
809 mach_timebase_info(&timeBaseInfo
);
810 delay
= ((uint64_t)250000000 * (uint64_t)timeBaseInfo
.denom
) / (uint64_t)timeBaseInfo
.numer
;
815 * Remember when we started so we can throttle the loop after the read call...
818 start
= mach_absolute_time();
820 rbytes
= sizeof(readbuffer
);
821 readstatus
= (*g
.classdriver
)->ReadPipe(g
.classdriver
, readbuffer
, &rbytes
);
822 if (readstatus
== kIOReturnSuccess
&& rbytes
> 0)
824 cupsBackChannelWrite((char*)readbuffer
, rbytes
, 1.0);
826 /* cntrl-d is echoed by the printer.
828 * Xerox Phaser 6250D doesn't echo the cntrl-d.
829 * Xerox Phaser 6250D doesn't always send the product query.
831 if (g
.wait_eof
&& readbuffer
[rbytes
-1] == 0x4)
834 #ifdef PARSE_PS_ERRORS
835 parse_pserror(readbuffer
, rbytes
);
840 * Make sure this loop executes no more than once every 250 miliseconds...
843 if ((readstatus
!= kIOReturnSuccess
|| rbytes
== 0) && (g
.wait_eof
|| !g
.read_thread_stop
))
844 mach_wait_until(start
+ delay
);
846 } while (g
.wait_eof
|| !g
.read_thread_stop
); /* Abort from main thread tests error here */
849 * Let the main thread know that we have completed the read thread...
852 pthread_mutex_lock(&g
.read_thread_mutex
);
853 g
.read_thread_done
= 1;
854 pthread_cond_signal(&g
.read_thread_cond
);
855 pthread_mutex_unlock(&g
.read_thread_mutex
);
862 * 'sidechannel_thread()' - Handle side-channel requests.
866 sidechannel_thread(void *reference
)
868 cups_sc_command_t command
; /* Request command */
869 cups_sc_status_t status
; /* Request/response status */
870 char data
[2048]; /* Request/response data */
871 int datalen
; /* Request/response data size */
876 datalen
= sizeof(data
);
878 if (cupsSideChannelRead(&command
, &status
, data
, &datalen
, 1.0))
883 case CUPS_SC_CMD_SOFT_RESET
: /* Do a soft reset */
884 if ((*g
.classdriver
)->SoftReset
!= NULL
)
887 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
891 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
896 case CUPS_SC_CMD_DRAIN_OUTPUT
: /* Drain all pending output */
900 case CUPS_SC_CMD_GET_BIDI
: /* Is the connection bidirectional? */
901 data
[0] = g
.bidi_flag
;
902 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
905 case CUPS_SC_CMD_GET_DEVICE_ID
: /* Return IEEE-1284 device ID */
906 datalen
= sizeof(data
);
907 get_device_id(&status
, data
, &datalen
);
908 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, datalen
, 1.0);
911 case CUPS_SC_CMD_GET_STATE
: /* Return device state */
912 data
[0] = CUPS_SC_STATE_ONLINE
;
913 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
917 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
922 while (!g
.sidechannel_thread_stop
);
924 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
925 g
.sidechannel_thread_done
= 1;
926 pthread_cond_signal(&g
.sidechannel_thread_cond
);
927 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
935 * 'iterate_printers()' - Iterate over all the printers.
938 static void iterate_printers(iterator_callback_t callBack
,
941 mach_port_t masterPort
= 0x0;
942 kern_return_t kr
= IOMasterPort (bootstrap_port
, &masterPort
);
944 if (kr
== kIOReturnSuccess
&& masterPort
!= 0x0)
946 io_iterator_t addIterator
= 0x0;
948 iterator_reference_t reference
= { callBack
, userdata
, true };
949 IONotificationPortRef addNotification
= IONotificationPortCreate(masterPort
);
951 int klass
= kUSBPrintingClass
;
952 int subklass
= kUSBPrintingSubclass
;
954 CFNumberRef usb_klass
= CFNumberCreate(NULL
, kCFNumberIntType
, &klass
);
955 CFNumberRef usb_subklass
= CFNumberCreate(NULL
, kCFNumberIntType
, &subklass
);
956 CFMutableDictionaryRef usbPrinterMatchDictionary
= IOServiceMatching(kIOUSBInterfaceClassName
);
958 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceClass"), usb_klass
);
959 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceSubClass"), usb_subklass
);
961 CFRelease(usb_klass
);
962 CFRelease(usb_subklass
);
964 kr
= IOServiceAddMatchingNotification(addNotification
, kIOMatchedNotification
, usbPrinterMatchDictionary
, &device_added
, &reference
, &addIterator
);
965 if (addIterator
!= 0x0)
967 device_added (&reference
, addIterator
);
969 if (reference
.keepRunning
)
971 CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification
), kCFRunLoopDefaultMode
);
974 IOObjectRelease(addIterator
);
976 mach_port_deallocate(mach_task_self(), masterPort
);
982 * 'device_added()' - Device added notifier.
985 static void device_added(void *userdata
,
986 io_iterator_t iterator
)
988 iterator_reference_t
*reference
= userdata
;
991 while (reference
->keepRunning
&& (obj
= IOIteratorNext(iterator
)) != 0x0)
993 if (reference
->callback
!= NULL
)
994 reference
->keepRunning
= reference
->callback(reference
->userdata
, obj
);
996 IOObjectRelease(obj
);
999 /* One last call to the call back now that we are not longer have printers left to iterate...
1001 if (reference
->keepRunning
)
1002 reference
->keepRunning
= reference
->callback(reference
->userdata
, 0x0);
1004 if (!reference
->keepRunning
)
1005 CFRunLoopStop(CFRunLoopGetCurrent());
1010 * 'list_device_cb()' - list_device iterator callback.
1013 static Boolean
list_device_cb(void *refcon
,
1016 Boolean keepRunning
= (obj
!= 0x0);
1020 CFStringRef deviceIDString
= NULL
;
1021 UInt32 deviceLocation
= 0;
1022 UInt8 interfaceNum
= 0;
1024 copy_devicestring(obj
, &deviceIDString
, &deviceLocation
, &interfaceNum
);
1025 if (deviceIDString
!= NULL
)
1027 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1028 char uristr
[1024], makestr
[1024], modelstr
[1024], serialstr
[1024];
1029 char optionsstr
[1024], idstr
[1024], make_modelstr
[1024];
1031 copy_deviceinfo(deviceIDString
, &make
, &model
, &serial
);
1032 CFStringGetCString(deviceIDString
, idstr
, sizeof(idstr
),
1033 kCFStringEncodingUTF8
);
1034 backendGetMakeModel(idstr
, make_modelstr
, sizeof(make_modelstr
));
1039 !CFStringGetCString(make
, makestr
, sizeof(makestr
),
1040 kCFStringEncodingUTF8
))
1041 strcpy(makestr
, "Unknown");
1044 !CFStringGetCString(model
, &modelstr
[1], sizeof(modelstr
)-1,
1045 kCFStringEncodingUTF8
))
1046 strcpy(modelstr
+ 1, "Printer");
1048 optionsstr
[0] = '\0';
1051 CFStringGetCString(serial
, serialstr
, sizeof(serialstr
), kCFStringEncodingUTF8
);
1052 snprintf(optionsstr
, sizeof(optionsstr
), "?serial=%s", serialstr
);
1054 else if (deviceLocation
!= 0)
1055 snprintf(optionsstr
, sizeof(optionsstr
), "?location=%x", (unsigned)deviceLocation
);
1057 httpAssembleURI(HTTP_URI_CODING_ALL
, uristr
, sizeof(uristr
), "usb", NULL
, makestr
, 0, modelstr
);
1058 strncat(uristr
, optionsstr
, sizeof(uristr
));
1060 cupsBackendReport("direct", uristr
, make_modelstr
, make_modelstr
, idstr
,
1063 release_deviceinfo(&make
, &model
, &serial
);
1064 CFRelease(deviceIDString
);
1073 * 'find_device_cb()' - print_device iterator callback.
1076 static Boolean
find_device_cb(void *refcon
,
1079 Boolean keepLooking
= true;
1083 CFStringRef idString
= NULL
;
1084 UInt32 location
= -1;
1085 UInt8 interfaceNum
= 0;
1087 copy_devicestring(obj
, &idString
, &location
, &interfaceNum
);
1088 if (idString
!= NULL
)
1090 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1092 copy_deviceinfo(idString
, &make
, &model
, &serial
);
1093 if (make
&& CFStringCompare(make
, g
.make
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1095 if (model
&& CFStringCompare(model
, g
.model
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1097 if (g
.serial
!= NULL
&& CFStringGetLength(g
.serial
) > 0)
1099 if (serial
!= NULL
&& CFStringCompare(serial
, g
.serial
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1101 IOObjectRetain(obj
);
1102 g
.printer_obj
= obj
;
1103 keepLooking
= false;
1108 if (g
.printer_obj
!= 0)
1109 IOObjectRelease(g
.printer_obj
);
1111 g
.printer_obj
= obj
;
1112 IOObjectRetain(obj
);
1114 if (g
.location
== 0 || g
.location
== location
)
1115 keepLooking
= false;
1118 g
.interfaceNum
= interfaceNum
;
1122 release_deviceinfo(&make
, &model
, &serial
);
1123 CFRelease(idString
);
1128 keepLooking
= (g
.printer_obj
== 0);
1129 if (obj
== 0x0 && keepLooking
)
1131 CFRunLoopTimerContext context
= { 0, refcon
, NULL
, NULL
, NULL
};
1132 CFRunLoopTimerRef timer
= CFRunLoopTimerCreate(NULL
, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb
, &context
);
1135 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer
, kCFRunLoopDefaultMode
);
1136 g
.status_timer
= timer
;
1141 if (!keepLooking
&& g
.status_timer
!= NULL
)
1143 fputs("STATE: -offline-report\n", stderr
);
1144 _cupsLangPuts(stderr
, _("INFO: Printer is now online.\n"));
1145 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g
.status_timer
, kCFRunLoopDefaultMode
);
1146 CFRelease(g
.status_timer
);
1147 g
.status_timer
= NULL
;
1155 * 'status_timer_cb()' - Status timer callback.
1158 static void status_timer_cb(CFRunLoopTimerRef timer
,
1161 fputs("STATE: +offline-report\n", stderr
);
1162 _cupsLangPuts(stderr
, _("INFO: Printer is offline.\n"));
1164 if (getenv("CLASS") != NULL
)
1167 * If the CLASS environment variable is set, the job was submitted
1168 * to a class and not to a specific queue. In this case, we want
1169 * to abort immediately so that the job can be requeued on the next
1170 * available printer in the class.
1172 * Sleep 5 seconds to keep the job from requeuing too rapidly...
1177 exit(CUPS_BACKEND_FAILED
);
1184 * 'copy_deviceinfo()' - Copy strings from the 1284 device ID.
1187 static void copy_deviceinfo(CFStringRef deviceIDString
,
1190 CFStringRef
*serial
)
1192 CFStringRef modelKeys
[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL
};
1193 CFStringRef makeKeys
[] = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL
};
1194 CFStringRef serialKeys
[] = { CFSTR("SN:"), CFSTR("SERN:"), NULL
};
1197 *make
= copy_value_for_key(deviceIDString
, makeKeys
);
1200 *model
= copy_value_for_key(deviceIDString
, modelKeys
);
1203 *serial
= copy_value_for_key(deviceIDString
, serialKeys
);
1208 * 'release_deviceinfo()' - Release deviceinfo strings.
1211 static void release_deviceinfo(CFStringRef
*make
,
1213 CFStringRef
*serial
)
1215 if (make
!= NULL
&& *make
!= NULL
)
1221 if (model
!= NULL
&& *model
!= NULL
)
1227 if (serial
!= NULL
&& *serial
!= NULL
)
1237 * 'load_classdriver()' - Load a classdriver.
1240 static kern_return_t
load_classdriver(CFStringRef driverPath
,
1241 printer_interface_t intf
,
1242 classdriver_t
***printerDriver
)
1244 kern_return_t kr
= kUSBPrinterClassDeviceNotOpen
;
1245 classdriver_t
**driver
= NULL
;
1246 CFStringRef bundle
= (driverPath
== NULL
? kUSBGenericTOPrinterClassDriver
: driverPath
);
1250 CFURLRef url
= CFURLCreateWithFileSystemPath(NULL
, bundle
, kCFURLPOSIXPathStyle
, true);
1251 CFPlugInRef plugin
= (url
!= NULL
? CFPlugInCreate(NULL
, url
) : NULL
);
1258 CFArrayRef factories
= CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID
, plugin
);
1259 if (factories
!= NULL
&& CFArrayGetCount(factories
) > 0)
1261 CFUUIDRef factoryID
= CFArrayGetValueAtIndex(factories
, 0);
1262 IUnknownVTbl
**iunknown
= CFPlugInInstanceCreate(NULL
, factoryID
, kUSBPrinterClassTypeID
);
1263 if (iunknown
!= NULL
)
1265 kr
= (*iunknown
)->QueryInterface(iunknown
, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID
), (LPVOID
*)&driver
);
1266 if (kr
== kIOReturnSuccess
&& driver
!= NULL
)
1268 classdriver_t
**genericDriver
= NULL
;
1269 if (driverPath
!= NULL
&& CFStringCompare(driverPath
, kUSBGenericTOPrinterClassDriver
, 0) != kCFCompareEqualTo
)
1270 kr
= load_classdriver(NULL
, intf
, &genericDriver
);
1272 if (kr
== kIOReturnSuccess
)
1274 (*driver
)->interface
= intf
;
1275 (*driver
)->Initialize(driver
, genericDriver
);
1277 (*driver
)->plugin
= plugin
;
1278 (*driver
)->interface
= intf
;
1279 *printerDriver
= driver
;
1282 (*iunknown
)->Release(iunknown
);
1284 CFRelease(factories
);
1289 char bundlestr
[1024];
1290 CFStringGetCString(bundle
, bundlestr
, sizeof(bundlestr
), kCFStringEncodingUTF8
);
1291 fprintf(stderr
, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr
, (int)kr
);
1298 * 'unload_classdriver()' - Unload a classdriver.
1301 static kern_return_t
unload_classdriver(classdriver_t
***classdriver
)
1303 if (*classdriver
!= NULL
)
1305 (**classdriver
)->Release(*classdriver
);
1306 *classdriver
= NULL
;
1309 return kIOReturnSuccess
;
1314 * 'load_printerdriver()' - Load vendor's classdriver.
1316 * If driverBundlePath is not NULL on return it is the callers responsbility to release it!
1319 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
)
1321 IOCFPlugInInterface
**iodev
= NULL
;
1324 printer_interface_t intf
;
1327 kr
= IOCreatePlugInInterfaceForService(g
.printer_obj
, kIOUSBInterfaceUserClientTypeID
, kIOCFPlugInInterfaceID
, &iodev
, &score
);
1328 if (kr
== kIOReturnSuccess
)
1330 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*) &intf
)) == noErr
)
1332 *driverBundlePath
= IORegistryEntryCreateCFProperty(g
.printer_obj
, kUSBClassDriverProperty
, NULL
, kNilOptions
);
1334 kr
= load_classdriver(*driverBundlePath
, intf
, &g
.classdriver
);
1336 if (kr
!= kIOReturnSuccess
)
1337 (*intf
)->Release(intf
);
1339 IODestroyPlugInInterface(iodev
);
1346 * 'registry_open()' - Open a connection to the printer.
1349 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
)
1351 g
.bidi_flag
= 0; /* 0=unidirectional */
1353 kern_return_t kr
= load_printerdriver(driverBundlePath
);
1354 if (kr
!= kIOReturnSuccess
)
1357 if (g
.classdriver
!= NULL
)
1359 (*g
.classdriver
)->interfaceNumber
= g
.interfaceNum
;
1360 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolBidirectional
);
1361 if (kr
!= kIOReturnSuccess
|| (*g
.classdriver
)->interface
== NULL
)
1363 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolUnidirectional
);
1364 if (kr
== kIOReturnSuccess
)
1366 if ((*g
.classdriver
)->interface
== NULL
)
1368 (*g
.classdriver
)->Close(g
.classdriver
);
1374 g
.bidi_flag
= 1; /* 1=bidirectional */
1377 if (kr
!= kIOReturnSuccess
)
1378 unload_classdriver(&g
.classdriver
);
1385 * 'registry_close()' - Close the connection to the printer.
1388 static kern_return_t
registry_close()
1390 if (g
.classdriver
!= NULL
)
1391 (*g
.classdriver
)->Close(g
.classdriver
);
1393 unload_classdriver(&g
.classdriver
);
1394 return kIOReturnSuccess
;
1399 * 'copy_deviceid()' - Copy the 1284 device id string.
1402 static OSStatus
copy_deviceid(classdriver_t
**classdriver
,
1403 CFStringRef
*deviceID
)
1405 CFStringRef devID
= NULL
,
1409 deviceSerial
= NULL
;
1411 OSStatus err
= (*classdriver
)->GetDeviceID(classdriver
, &devID
, DEFAULT_TIMEOUT
);
1413 copy_deviceinfo(devID
, &deviceMake
, &deviceModel
, &deviceSerial
);
1415 if (deviceMake
== NULL
|| deviceModel
== NULL
|| deviceSerial
== NULL
)
1417 IOUSBDeviceDescriptor desc
;
1418 iodevice_request_t request
;
1420 request
.requestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
1421 request
.request
= kUSBRqGetDescriptor
;
1422 request
.value
= (kUSBDeviceDesc
<< 8) | 0;
1424 request
.length
= sizeof(desc
);
1425 request
.buffer
= &desc
;
1426 err
= (*classdriver
)->DeviceRequest(classdriver
, &request
, DEFAULT_TIMEOUT
);
1427 if (err
== kIOReturnSuccess
)
1429 CFMutableStringRef newDevID
= CFStringCreateMutable(NULL
, 0);
1431 if (deviceMake
== NULL
)
1433 CFStringRef data
= NULL
;
1434 err
= (*classdriver
)->GetString(classdriver
, desc
.iManufacturer
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1437 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MFG:%@;"), data
);
1442 if (deviceModel
== NULL
)
1444 CFStringRef data
= NULL
;
1445 err
= (*classdriver
)->GetString(classdriver
, desc
.iProduct
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1448 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MDL:%@;"), data
);
1453 if (deviceSerial
== NULL
&& desc
.iSerialNumber
!= 0)
1455 CFStringRef data
= NULL
;
1456 err
= (*classdriver
)->GetString(classdriver
, desc
.iSerialNumber
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1459 CFStringAppendFormat(newDevID
, NULL
, CFSTR("SERN:%@;"), data
);
1466 CFStringAppend(newDevID
, devID
);
1470 *deviceID
= newDevID
;
1477 release_deviceinfo(&deviceMake
, &deviceModel
, &deviceSerial
);
1484 * 'copy_devicestring()' - Copy the 1284 device id string.
1487 static void copy_devicestring(io_service_t usbInterface
,
1488 CFStringRef
*deviceID
,
1489 UInt32
*deviceLocation
,
1490 UInt8
*interfaceNumber
)
1492 IOCFPlugInInterface
**iodev
= NULL
;
1495 printer_interface_t intf
;
1497 classdriver_t
**klassDriver
= NULL
;
1498 CFStringRef driverBundlePath
;
1500 if ((kr
= IOCreatePlugInInterfaceForService(usbInterface
,
1501 kIOUSBInterfaceUserClientTypeID
,
1502 kIOCFPlugInInterfaceID
,
1503 &iodev
, &score
)) == kIOReturnSuccess
)
1505 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*)
1508 (*intf
)->GetLocationID(intf
, deviceLocation
);
1509 (*intf
)->GetInterfaceNumber(intf
, interfaceNumber
);
1511 driverBundlePath
= IORegistryEntryCreateCFProperty(usbInterface
,
1512 kUSBClassDriverProperty
,
1515 kr
= load_classdriver(driverBundlePath
, intf
, &klassDriver
);
1517 if (kr
!= kIOReturnSuccess
&& driverBundlePath
!= NULL
)
1518 kr
= load_classdriver(NULL
, intf
, &klassDriver
);
1520 if (kr
== kIOReturnSuccess
&& klassDriver
!= NULL
)
1521 kr
= copy_deviceid(klassDriver
, deviceID
);
1523 unload_classdriver(&klassDriver
);
1525 if (driverBundlePath
!= NULL
)
1526 CFRelease(driverBundlePath
);
1528 /* (*intf)->Release(intf); */
1530 IODestroyPlugInInterface(iodev
);
1537 * 'copy_value_for_key()' - Copy value string associated with a key.
1540 static CFStringRef
copy_value_for_key(CFStringRef deviceID
,
1543 CFStringRef value
= NULL
;
1544 CFArrayRef kvPairs
= deviceID
!= NULL
? CFStringCreateArrayBySeparatingStrings(NULL
, deviceID
, CFSTR(";")) : NULL
;
1545 CFIndex max
= kvPairs
!= NULL
? CFArrayGetCount(kvPairs
) : 0;
1548 while (idx
< max
&& value
== NULL
)
1550 CFStringRef kvpair
= CFArrayGetValueAtIndex(kvPairs
, idx
);
1552 while (keys
[idxx
] != NULL
&& value
== NULL
)
1554 CFRange range
= CFStringFind(kvpair
, keys
[idxx
], kCFCompareCaseInsensitive
);
1555 if (range
.length
!= -1)
1557 if (range
.location
!= 0)
1559 CFMutableStringRef theString
= CFStringCreateMutableCopy(NULL
, 0, kvpair
);
1560 CFStringTrimWhitespace(theString
);
1561 range
= CFStringFind(theString
, keys
[idxx
], kCFCompareCaseInsensitive
);
1562 if (range
.location
== 0)
1563 value
= CFStringCreateWithSubstring(NULL
, theString
, CFRangeMake(range
.length
, CFStringGetLength(theString
) - range
.length
));
1565 CFRelease(theString
);
1569 CFStringRef theString
= CFStringCreateWithSubstring(NULL
, kvpair
, CFRangeMake(range
.length
, CFStringGetLength(kvpair
) - range
.length
));
1570 CFMutableStringRef theString2
= CFStringCreateMutableCopy(NULL
, 0, theString
);
1571 CFRelease(theString
);
1573 CFStringTrimWhitespace(theString2
);
1582 if (kvPairs
!= NULL
)
1589 * 'cfstr_create_trim()' - Create CFString and trim whitespace characters.
1592 CFStringRef
cfstr_create_trim(const char *cstr
)
1595 CFMutableStringRef cfmutablestr
= NULL
;
1597 if ((cfstr
= CFStringCreateWithCString(NULL
, cstr
, kCFStringEncodingUTF8
)) != NULL
)
1599 if ((cfmutablestr
= CFStringCreateMutableCopy(NULL
, 1024, cfstr
)) != NULL
)
1600 CFStringTrimWhitespace(cfmutablestr
);
1604 return (CFStringRef
) cfmutablestr
;
1610 * 'parse_options()' - Parse URI options.
1613 static void parse_options(char *options
,
1619 char sep
, /* Separator character */
1620 *name
, /* Name of option */
1621 *value
; /* Value of option */
1640 while (*options
&& *options
!= '=' && *options
!= '+' && *options
!= '&')
1643 if ((sep
= *options
) != '\0')
1654 while (*options
&& *options
!= '+' && *options
!= '&')
1664 * Process the option...
1667 if (!strcasecmp(name
, "waiteof"))
1669 if (!strcasecmp(value
, "on") ||
1670 !strcasecmp(value
, "yes") ||
1671 !strcasecmp(value
, "true"))
1673 else if (!strcasecmp(value
, "off") ||
1674 !strcasecmp(value
, "no") ||
1675 !strcasecmp(value
, "false"))
1678 _cupsLangPrintf(stderr
,
1679 _("WARNING: Boolean expected for waiteof option "
1680 "\"%s\"\n"), value
);
1682 else if (!strcasecmp(name
, "serial"))
1683 strlcpy(serial
, value
, serial_size
);
1684 else if (!strcasecmp(name
, "location") && location
)
1685 *location
= strtol(value
, NULL
, 16);
1691 * @function setup_cfLanguage
1692 * @abstract Convert the contents of the CUPS 'APPLE_LANGUAGE' environment
1693 * variable into a one element CF array of languages.
1695 * @discussion Each submitted job comes with a natural language. CUPS passes
1696 * that language in an environment variable. We take that language
1697 * and jam it into the AppleLanguages array so that CF will use
1698 * it when reading localized resources. We need to do this before
1699 * any CF code reads and caches the languages array, so this function
1700 * should be called early in main()
1702 static void setup_cfLanguage(void)
1704 CFStringRef lang
[1] = {NULL
};
1705 CFArrayRef langArray
= NULL
;
1706 const char *requestedLang
= NULL
;
1708 if ((requestedLang
= getenv("APPLE_LANGUAGE")) == NULL
)
1709 requestedLang
= getenv("LANG");
1711 if (requestedLang
!= NULL
)
1713 lang
[0] = CFStringCreateWithCString(kCFAllocatorDefault
, requestedLang
, kCFStringEncodingUTF8
);
1714 langArray
= CFArrayCreate(kCFAllocatorDefault
, (const void **)lang
, sizeof(lang
) / sizeof(lang
[0]), &kCFTypeArrayCallBacks
);
1716 CFPreferencesSetValue(CFSTR("AppleLanguages"), langArray
, kCFPreferencesCurrentApplication
, kCFPreferencesAnyUser
, kCFPreferencesAnyHost
);
1717 fprintf(stderr
, "DEBUG: usb: AppleLanguages=\"%s\"\n", requestedLang
);
1720 CFRelease(langArray
);
1723 fputs("DEBUG: usb: LANG and APPLE_LANGUAGE environment variables missing.\n", stderr
);
1727 #if defined(__i386__) || defined(__x86_64__)
1729 * @function run_legacy_backend
1731 * @abstract Starts child backend process running as a ppc or i386 executable.
1733 * @result Never returns; always calls exit().
1737 static void run_legacy_backend(int argc
,
1744 pid_t waitpid_status
;
1746 char *usb_legacy_status
;
1749 * If we're running as x86_64 or i386 and couldn't load the class driver
1750 * (because it's ppc or i386), then try to re-exec ourselves in ppc or i386
1751 * mode to try again. If we don't have a ppc or i386 architecture we may be
1752 * running with the same architecture again so guard against this by setting
1753 * and testing an environment variable...
1757 usb_legacy_status
= getenv("USB_I386_STATUS");
1759 usb_legacy_status
= getenv("USB_PPC_STATUS");
1760 # endif /* __x86_64__ */
1762 if (!usb_legacy_status
)
1765 * Setup a SIGTERM handler then block it before forking...
1768 struct sigaction action
; /* POSIX signal action */
1769 sigset_t newmask
, /* New signal mask */
1770 oldmask
; /* Old signal mask */
1771 char usbpath
[1024]; /* Path to USB backend */
1772 const char *cups_serverbin
;/* Path to CUPS binaries */
1775 memset(&action
, 0, sizeof(action
));
1776 sigaddset(&action
.sa_mask
, SIGTERM
);
1777 action
.sa_handler
= sigterm_handler
;
1778 sigaction(SIGTERM
, &action
, NULL
);
1780 sigemptyset(&newmask
);
1781 sigaddset(&newmask
, SIGTERM
);
1782 sigprocmask(SIG_BLOCK
, &newmask
, &oldmask
);
1785 * Set the environment variable...
1789 setenv("USB_I386_STATUS", "1", false);
1791 setenv("USB_PPC_STATUS", "1", false);
1792 # endif /* __x86_64__ */
1795 * Tell the kernel to use the specified CPU architecture...
1799 cpu_type_t cpu
= CPU_TYPE_I386
;
1801 cpu_type_t cpu
= CPU_TYPE_POWERPC
;
1802 # endif /* __x86_64__ */
1804 posix_spawnattr_t attrs
;
1806 if (!posix_spawnattr_init(&attrs
))
1808 posix_spawnattr_setsigdefault(&attrs
, &oldmask
);
1809 if (posix_spawnattr_setbinpref_np(&attrs
, 1, &cpu
, &ocount
) || ocount
!= 1)
1812 perror("DEBUG: Unable to set binary preference to i386");
1814 perror("DEBUG: Unable to set binary preference to ppc");
1815 # endif /* __x86_64__ */
1816 _cupsLangPrintf(stderr
, _("Unable to use legacy USB class driver!\n"));
1817 exit(CUPS_BACKEND_STOP
);
1822 * Set up the arguments and call posix_spawn...
1825 if ((cups_serverbin
= getenv("CUPS_SERVERBIN")) == NULL
)
1826 cups_serverbin
= CUPS_SERVERBIN
;
1827 snprintf(usbpath
, sizeof(usbpath
), "%s/backend/usb", cups_serverbin
);
1829 for (i
= 0; i
< argc
&& i
< (sizeof(my_argv
) / sizeof(my_argv
[0])) - 1; i
++)
1830 my_argv
[i
] = argv
[i
];
1834 if (posix_spawn(&child_pid
, usbpath
, NULL
, &attrs
, my_argv
, environ
))
1836 fprintf(stderr
, "DEBUG: Unable to exec %s: %s\n", usbpath
,
1838 _cupsLangPrintf(stderr
, _("Unable to use legacy USB class driver!\n"));
1839 exit(CUPS_BACKEND_STOP
);
1843 * Unblock signals...
1846 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
1849 * Close the fds we won't be using then wait for the child backend to exit.
1855 fprintf(stderr
, "DEBUG: Started usb(legacy) backend (PID %d)\n",
1858 while ((waitpid_status
= waitpid(child_pid
, &childstatus
, 0)) == (pid_t
)-1 && errno
== EINTR
)
1861 if (WIFSIGNALED(childstatus
))
1863 exitstatus
= CUPS_BACKEND_STOP
;
1864 fprintf(stderr
, "DEBUG: usb(legacy) backend %d crashed on signal %d!\n",
1865 child_pid
, WTERMSIG(childstatus
));
1869 if ((exitstatus
= WEXITSTATUS(childstatus
)) != 0)
1871 "DEBUG: usb(legacy) backend %d stopped with status %d!\n",
1872 child_pid
, exitstatus
);
1874 fprintf(stderr
, "DEBUG: usb(legacy) backend %d exited with no errors\n",
1880 fputs("DEBUG: usb(legacy) backend running native again\n", stderr
);
1881 exitstatus
= CUPS_BACKEND_STOP
;
1888 * 'sigterm_handler()' - SIGTERM handler.
1891 static void sigterm_handler(int sig
)
1893 /* If we started a child process pass the signal on to it...
1896 kill(child_pid
, sig
);
1901 #endif /* __i386__ || __x86_64__ */
1904 #ifdef PARSE_PS_ERRORS
1906 * 'next_line()' - Find the next line in a buffer.
1909 static const char *next_line (const char *buffer
)
1911 const char *cptr
, *lptr
= NULL
;
1913 for (cptr
= buffer
; *cptr
&& lptr
== NULL
; cptr
++)
1914 if (*cptr
== '\n' || *cptr
== '\r')
1921 * 'parse_pserror()' - Scan the backchannel data for postscript errors.
1924 static void parse_pserror(char *sockBuffer
,
1927 static char gErrorBuffer
[1024] = "";
1928 static char *gErrorBufferPtr
= gErrorBuffer
;
1929 static char *gErrorBufferEndPtr
= gErrorBuffer
+ sizeof(gErrorBuffer
);
1931 char *pCommentBegin
, *pCommentEnd
, *pLineEnd
;
1936 if (gErrorBufferPtr
+ len
> gErrorBufferEndPtr
- 1)
1937 gErrorBufferPtr
= gErrorBuffer
;
1938 if (len
> sizeof(gErrorBuffer
) - 1)
1939 len
= sizeof(gErrorBuffer
) - 1;
1941 memcpy(gErrorBufferPtr
, (const void *)sockBuffer
, len
);
1942 gErrorBufferPtr
+= len
;
1943 *(gErrorBufferPtr
+ 1) = '\0';
1945 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
1946 while (pLineEnd
!= NULL
)
1950 pCommentBegin
= strstr(gErrorBuffer
,"%%[");
1951 pCommentEnd
= strstr(gErrorBuffer
, "]%%");
1952 if (pCommentBegin
!= gErrorBuffer
&& pCommentEnd
!= NULL
)
1954 pCommentEnd
+= 3; /* Skip past "]%%" */
1955 *pCommentEnd
= '\0'; /* There's always room for the nul */
1957 if (strncasecmp(pCommentBegin
, "%%[ Error:", 10) == 0)
1959 else if (strncasecmp(pCommentBegin
, "%%[ Flushing", 12) == 0)
1964 if ((logstrlen
= snprintf(logstr
, sizeof(logstr
), "%s: %s\n", logLevel
, pCommentBegin
)) >= sizeof(logstr
))
1966 /* If the string was trucnated make sure it has a linefeed before the nul */
1967 logstrlen
= sizeof(logstr
) - 1;
1968 logstr
[logstrlen
- 1] = '\n';
1970 write(STDERR_FILENO
, logstr
, logstrlen
);
1973 /* move everything over... */
1974 strcpy(gErrorBuffer
, pLineEnd
);
1975 gErrorBufferPtr
= gErrorBuffer
;
1976 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
1979 #endif /* PARSE_PS_ERRORS */
1983 * 'soft_reset()' - Send a soft reset to the device.
1986 static void soft_reset()
1988 fd_set input_set
; /* Input set for select() */
1989 struct timeval stimeout
; /* Timeout for select() */
1990 char buffer
[2048]; /* Buffer */
1991 struct timespec cond_timeout
; /* pthread condition timeout */
1994 * Send an abort once a second until the I/O lock is released by the main thread...
1997 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
1998 while (g
.readwrite_lock
)
2000 (*g
.classdriver
)->Abort(g
.classdriver
);
2002 cond_timeout
.tv_sec
= time(NULL
) + 1;
2003 cond_timeout
.tv_nsec
= 0;
2005 pthread_cond_timedwait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
, &cond_timeout
);
2008 g
.readwrite_lock
= 1;
2009 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2012 * Flush bytes waiting on print_fd...
2017 FD_ZERO(&input_set
);
2018 FD_SET(g
.print_fd
, &input_set
);
2020 stimeout
.tv_sec
= 0;
2021 stimeout
.tv_usec
= 0;
2023 while (select(g
.print_fd
+1, &input_set
, NULL
, NULL
, &stimeout
) > 0)
2024 if (read(g
.print_fd
, buffer
, sizeof(buffer
)) <= 0)
2031 (*g
.classdriver
)->SoftReset(g
.classdriver
, DEFAULT_TIMEOUT
);
2034 * Release the I/O lock...
2037 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2038 g
.readwrite_lock
= 0;
2039 pthread_cond_signal(&g
.readwrite_lock_cond
);
2040 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2045 * 'get_device_id()' - Return IEEE-1284 device ID.
2048 static void get_device_id(cups_sc_status_t
*status
,
2052 UInt32 deviceLocation
= 0;
2053 UInt8 interfaceNum
= 0;
2054 CFStringRef deviceIDString
= NULL
;
2057 copy_devicestring(g
.printer_obj
, &deviceIDString
, &deviceLocation
, &interfaceNum
);
2060 CFStringGetCString(deviceIDString
, data
, *datalen
, kCFStringEncodingUTF8
);
2061 *datalen
= strlen(data
);
2062 CFRelease(deviceIDString
);
2064 *status
= CUPS_SC_STATUS_OK
;
2069 * End of "$Id: usb-darwin.c 7953 2008-09-17 01:43:19Z mike $".