2 * "$Id: usb-darwin.c 7953 2008-09-17 01:43:19Z mike $"
4 * Copyright 2005-2009 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 #endif /* __i386__ || __x86_64__ */
285 static int job_canceled
= 0; /* Was the job canceled? */
286 static void sigterm_handler(int sig
); /* SIGTERM handler */
288 #ifdef PARSE_PS_ERRORS
289 static const char *next_line (const char *buffer
);
290 static void parse_pserror (char *sockBuffer
, int len
);
291 #endif /* PARSE_PS_ERRORS */
296 * 'list_devices()' - List all USB devices.
301 iterate_printers(list_device_cb
, NULL
);
306 * 'print_device()' - Print a file to a USB device.
309 int /* O - Exit status */
310 print_device(const char *uri
, /* I - Device URI */
311 const char *hostname
, /* I - Hostname/manufacturer */
312 const char *resource
, /* I - Resource/modelname */
313 char *options
, /* I - Device options/serial number */
314 int print_fd
, /* I - File descriptor to print */
315 int copies
, /* I - Copies to print */
316 int argc
, /* I - Number of command-line arguments (6 or 7) */
317 char *argv
[]) /* I - Command-line arguments */
319 char serial
[1024]; /* Serial number buffer */
320 OSStatus status
; /* Function results */
321 IOReturn iostatus
, /* Current IO status */
322 prev_iostatus
= 0; /* Previous IO status */
323 pthread_t read_thread_id
, /* Read thread */
324 sidechannel_thread_id
;/* Side-channel thread */
325 int have_sidechannel
= 0; /* Was the side-channel thread started? */
326 struct stat sidechannel_info
; /* Side-channel file descriptor info */
327 char print_buffer
[8192], /* Print data buffer */
328 *print_ptr
; /* Pointer into print data buffer */
329 UInt32 location
; /* Unique location in bus topology */
330 fd_set input_set
; /* Input set for select() */
331 CFStringRef driverBundlePath
; /* Class driver path */
332 int countdown
, /* Logging interval */
333 nfds
; /* Number of file descriptors */
334 ssize_t total_bytes
; /* Total bytes written */
335 UInt32 bytes
; /* Bytes written */
336 struct timeval
*timeout
, /* Timeout pointer */
337 stimeout
; /* Timeout for select() */
338 struct timespec cond_timeout
; /* pthread condition timeout */
342 * See if the side-channel descriptor is valid...
345 have_sidechannel
= !fstat(CUPS_SC_FD
, &sidechannel_info
) &&
346 S_ISSOCK(sidechannel_info
.st_mode
);
349 * Localize using CoreFoundation...
354 parse_options(options
, serial
, sizeof(serial
), &location
, &g
.wait_eof
);
356 if (resource
[0] == '/')
359 g
.print_fd
= print_fd
;
360 g
.make
= cfstr_create_trim(hostname
);
361 g
.model
= cfstr_create_trim(resource
);
362 g
.serial
= cfstr_create_trim(serial
);
363 g
.location
= location
;
365 if (!g
.make
|| !g
.model
)
367 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error!\n"));
370 fputs("DEBUG: USB make string is NULL!\n", stderr
);
372 fputs("DEBUG: USB model string is NULL!\n", stderr
);
374 return (CUPS_BACKEND_STOP
);
377 fputs("STATE: +connecting-to-device\n", stderr
);
379 countdown
= INITIAL_LOG_INTERVAL
;
385 IOObjectRelease(g
.printer_obj
);
386 unload_classdriver(&g
.classdriver
);
391 fprintf(stderr
, "DEBUG: Looking for '%s %s'\n", hostname
, resource
);
393 iterate_printers(find_device_cb
, NULL
);
395 fputs("DEBUG: Opening connection\n", stderr
);
397 driverBundlePath
= NULL
;
399 status
= registry_open(&driverBundlePath
);
401 #if defined(__i386__) || defined(__x86_64__)
403 * If we were unable to load the class drivers for this printer it's
404 * probably because they're ppc or i386. In this case try to run this
405 * backend as i386 or ppc executables so we can use them...
409 run_legacy_backend(argc
, argv
, print_fd
);
410 /* Never returns here */
412 #endif /* __i386__ || __x86_64__ */
417 * If we still were unable to load the class drivers for this printer log
418 * the error and stop the queue...
421 if (driverBundlePath
== NULL
|| !CFStringGetCString(driverBundlePath
, print_buffer
, sizeof(print_buffer
), kCFStringEncodingUTF8
))
422 strlcpy(print_buffer
, "USB class driver", sizeof(print_buffer
));
424 fputs("STATE: +apple-missing-usbclassdriver-error\n", stderr
);
425 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error!\n"));
426 fprintf(stderr
, "DEBUG: Could not load %s\n", print_buffer
);
428 if (driverBundlePath
)
429 CFRelease(driverBundlePath
);
431 return (CUPS_BACKEND_STOP
);
434 if (driverBundlePath
)
435 CFRelease(driverBundlePath
);
439 sleep(PRINTER_POLLING_INTERVAL
);
440 countdown
-= PRINTER_POLLING_INTERVAL
;
443 _cupsLangPuts(stderr
,
444 _("INFO: Waiting for printer to become available...\n"));
445 fprintf(stderr
, "DEBUG: USB printer status: 0x%08x\n", (int)status
);
446 countdown
= SUBSEQUENT_LOG_INTERVAL
; /* subsequent log entries, every 15 seconds */
449 } while (status
!= noErr
);
451 fputs("STATE: -connecting-to-device\n", stderr
);
454 * Now that we are "connected" to the port, catch SIGTERM so that we
455 * can finish out any page data the driver sends (e.g. to eject the
456 * current page... Only catch SIGTERM if we are printing data from
457 * stdin (otherwise you can't cancel raw jobs...)
462 struct sigaction action
; /* POSIX signal action */
465 memset(&action
, 0, sizeof(action
));
467 sigemptyset(&action
.sa_mask
);
468 action
.sa_handler
= sigterm_handler
;
469 sigaction(SIGTERM
, &action
, NULL
);
473 * Start the side channel thread if the descriptor is valid...
476 pthread_mutex_init(&g
.readwrite_lock_mutex
, NULL
);
477 pthread_cond_init(&g
.readwrite_lock_cond
, NULL
);
478 g
.readwrite_lock
= 1;
480 if (have_sidechannel
)
482 g
.sidechannel_thread_stop
= 0;
483 g
.sidechannel_thread_done
= 0;
485 pthread_cond_init(&g
.sidechannel_thread_cond
, NULL
);
486 pthread_mutex_init(&g
.sidechannel_thread_mutex
, NULL
);
488 if (pthread_create(&sidechannel_thread_id
, NULL
, sidechannel_thread
, NULL
))
490 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error!\n"));
491 fputs("DEBUG: Couldn't create side-channel thread!\n", stderr
);
492 return (CUPS_BACKEND_STOP
);
497 * Get the read thread going...
500 g
.read_thread_stop
= 0;
501 g
.read_thread_done
= 0;
503 pthread_cond_init(&g
.read_thread_cond
, NULL
);
504 pthread_mutex_init(&g
.read_thread_mutex
, NULL
);
506 if (pthread_create(&read_thread_id
, NULL
, read_thread
, NULL
))
508 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error!\n"));
509 fputs("DEBUG: Couldn't create read thread!\n", stderr
);
510 return (CUPS_BACKEND_STOP
);
514 * The main thread sends the print file...
520 print_ptr
= print_buffer
;
522 while (status
== noErr
&& copies
-- > 0)
524 _cupsLangPuts(stderr
, _("INFO: Sending print data...\n"));
526 if (print_fd
!= STDIN_FILENO
)
528 fputs("PAGE: 1 1\n", stderr
);
529 lseek(print_fd
, 0, SEEK_SET
);
532 while (status
== noErr
)
537 FD_SET(print_fd
, &input_set
);
540 * Calculate select timeout...
541 * If we have data waiting to send timeout is 100ms.
542 * else if we're draining print_fd timeout is 0.
543 * else we're waiting forever...
549 stimeout
.tv_usec
= 100000; /* 100ms */
552 else if (g
.drain_output
)
555 stimeout
.tv_usec
= 0;
562 * I/O is unlocked around select...
565 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
566 g
.readwrite_lock
= 0;
567 pthread_cond_signal(&g
.readwrite_lock_cond
);
568 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
570 nfds
= select(print_fd
+ 1, &input_set
, NULL
, NULL
, timeout
);
573 * Reacquire the lock...
576 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
577 while (g
.readwrite_lock
)
578 pthread_cond_wait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
);
579 g
.readwrite_lock
= 1;
580 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
584 if (errno
== EINTR
&& total_bytes
== 0)
586 fputs("DEBUG: Received an interrupt before any bytes were "
587 "written, aborting!\n", stderr
);
588 return (CUPS_BACKEND_OK
);
590 else if (errno
!= EAGAIN
)
592 _cupsLangPuts(stderr
, _("ERROR: Unable to read print data!\n"));
593 perror("DEBUG: select");
594 return (CUPS_BACKEND_FAILED
);
599 * If drain output has finished send a response...
602 if (g
.drain_output
&& !nfds
&& !g
.print_bytes
)
604 /* Send a response... */
605 cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
610 * Check if we have print data ready...
613 if (FD_ISSET(print_fd
, &input_set
))
615 g
.print_bytes
= read(print_fd
, print_buffer
, sizeof(print_buffer
));
617 if (g
.print_bytes
< 0)
620 * Read error - bail if we don't see EAGAIN or EINTR...
623 if (errno
!= EAGAIN
|| errno
!= EINTR
)
625 _cupsLangPuts(stderr
, _("ERROR: Unable to read print data!\n"));
626 perror("DEBUG: read");
627 return (CUPS_BACKEND_FAILED
);
632 else if (g
.print_bytes
== 0)
635 * End of file, break out of the loop...
641 print_ptr
= print_buffer
;
643 fprintf(stderr
, "DEBUG: Read %d bytes of print data...\n",
649 bytes
= g
.print_bytes
;
651 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
654 * Ignore timeout errors, but retain the number of bytes written to
655 * avoid sending duplicate data (<rdar://problem/6254911>)...
658 if (iostatus
== kIOUSBTransactionTimeout
)
662 * Ignore stall errors, since we clear any stalls in the class driver...
665 if (iostatus
== kIOUSBPipeStalled
)
669 * Ignore the first "aborted" status we get, since we might have
670 * received a signal (<rdar://problem/6860126>)...
673 if (iostatus
== kIOReturnAborted
&& prev_iostatus
!= kIOReturnAborted
)
675 prev_iostatus
= iostatus
;
679 prev_iostatus
= iostatus
;
681 if (iostatus
|| bytes
< 0)
684 * Write error - bail if we don't see an error we can retry...
687 IOReturn err
= (*g
.classdriver
)->Abort(g
.classdriver
);
688 _cupsLangPuts(stderr
, _("ERROR: Unable to send print data!\n"));
689 fprintf(stderr
, "DEBUG: USB class driver WritePipe returned %x\n",
691 fprintf(stderr
, "DEBUG: USB class driver Abort returned %x\n",
693 status
= job_canceled
? CUPS_BACKEND_FAILED
: CUPS_BACKEND_STOP
;
697 fprintf(stderr
, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes
);
699 g
.print_bytes
-= bytes
;
701 total_bytes
+= bytes
;
704 if (print_fd
!= 0 && status
== noErr
)
705 fprintf(stderr
, "DEBUG: Sending print file, %lld bytes...\n",
710 fprintf(stderr
, "DEBUG: Sent %lld bytes...\n", (off_t
)total_bytes
);
713 * Wait for the side channel thread to exit...
716 if (have_sidechannel
)
719 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
720 g
.readwrite_lock
= 0;
721 pthread_cond_signal(&g
.readwrite_lock_cond
);
722 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
724 g
.sidechannel_thread_stop
= 1;
725 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
726 if (!g
.sidechannel_thread_done
)
729 * Wait for the side-channel thread to exit...
732 cond_timeout
.tv_sec
= time(NULL
) + WAIT_SIDE_DELAY
;
733 cond_timeout
.tv_nsec
= 0;
734 if (pthread_cond_timedwait(&g
.sidechannel_thread_cond
,
735 &g
.sidechannel_thread_mutex
,
739 * Force the side-channel thread to exit...
742 pthread_kill(sidechannel_thread_id
, SIGTERM
);
745 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
747 pthread_join(sidechannel_thread_id
, NULL
);
749 pthread_cond_destroy(&g
.sidechannel_thread_cond
);
750 pthread_mutex_destroy(&g
.sidechannel_thread_mutex
);
753 pthread_cond_destroy(&g
.readwrite_lock_cond
);
754 pthread_mutex_destroy(&g
.readwrite_lock_mutex
);
757 * Signal the read thread to stop...
760 g
.read_thread_stop
= 1;
763 * Give the read thread WAIT_EOF_DELAY seconds to complete all the data. If
764 * we are not signaled in that time then force the thread to exit.
767 pthread_mutex_lock(&g
.read_thread_mutex
);
769 if (!g
.read_thread_done
)
771 cond_timeout
.tv_sec
= time(NULL
) + WAIT_EOF_DELAY
;
772 cond_timeout
.tv_nsec
= 0;
774 if (pthread_cond_timedwait(&g
.read_thread_cond
, &g
.read_thread_mutex
,
778 * Force the read thread to exit...
782 pthread_kill(read_thread_id
, SIGTERM
);
785 pthread_mutex_unlock(&g
.read_thread_mutex
);
787 pthread_join(read_thread_id
, NULL
); /* wait for the read thread to return */
789 pthread_cond_destroy(&g
.read_thread_cond
);
790 pthread_mutex_destroy(&g
.read_thread_mutex
);
793 * Close the connection and input file and general clean up...
798 if (print_fd
!= STDIN_FILENO
)
807 if (g
.serial
!= NULL
)
810 if (g
.printer_obj
!= 0x0)
811 IOObjectRelease(g
.printer_obj
);
818 * 'read_thread()' - Thread to read the backchannel data on.
821 static void *read_thread(void *reference
)
823 UInt8 readbuffer
[512];
825 kern_return_t readstatus
;
826 struct mach_timebase_info timeBaseInfo
;
830 /* Calculate what 250 milliSeconds are in mach absolute time...
832 mach_timebase_info(&timeBaseInfo
);
833 delay
= ((uint64_t)250000000 * (uint64_t)timeBaseInfo
.denom
) / (uint64_t)timeBaseInfo
.numer
;
838 * Remember when we started so we can throttle the loop after the read call...
841 start
= mach_absolute_time();
843 rbytes
= sizeof(readbuffer
);
844 readstatus
= (*g
.classdriver
)->ReadPipe(g
.classdriver
, readbuffer
, &rbytes
);
845 if (readstatus
== kIOReturnSuccess
&& rbytes
> 0)
847 cupsBackChannelWrite((char*)readbuffer
, rbytes
, 1.0);
849 /* cntrl-d is echoed by the printer.
851 * Xerox Phaser 6250D doesn't echo the cntrl-d.
852 * Xerox Phaser 6250D doesn't always send the product query.
854 if (g
.wait_eof
&& readbuffer
[rbytes
-1] == 0x4)
857 #ifdef PARSE_PS_ERRORS
858 parse_pserror(readbuffer
, rbytes
);
863 * Make sure this loop executes no more than once every 250 miliseconds...
866 if ((readstatus
!= kIOReturnSuccess
|| rbytes
== 0) && (g
.wait_eof
|| !g
.read_thread_stop
))
867 mach_wait_until(start
+ delay
);
869 } while (g
.wait_eof
|| !g
.read_thread_stop
); /* Abort from main thread tests error here */
872 * Let the main thread know that we have completed the read thread...
875 pthread_mutex_lock(&g
.read_thread_mutex
);
876 g
.read_thread_done
= 1;
877 pthread_cond_signal(&g
.read_thread_cond
);
878 pthread_mutex_unlock(&g
.read_thread_mutex
);
885 * 'sidechannel_thread()' - Handle side-channel requests.
889 sidechannel_thread(void *reference
)
891 cups_sc_command_t command
; /* Request command */
892 cups_sc_status_t status
; /* Request/response status */
893 char data
[2048]; /* Request/response data */
894 int datalen
; /* Request/response data size */
899 datalen
= sizeof(data
);
901 if (cupsSideChannelRead(&command
, &status
, data
, &datalen
, 1.0))
906 case CUPS_SC_CMD_SOFT_RESET
: /* Do a soft reset */
907 if ((*g
.classdriver
)->SoftReset
!= NULL
)
910 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
914 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
919 case CUPS_SC_CMD_DRAIN_OUTPUT
: /* Drain all pending output */
923 case CUPS_SC_CMD_GET_BIDI
: /* Is the connection bidirectional? */
924 data
[0] = g
.bidi_flag
;
925 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
928 case CUPS_SC_CMD_GET_DEVICE_ID
: /* Return IEEE-1284 device ID */
929 datalen
= sizeof(data
);
930 get_device_id(&status
, data
, &datalen
);
931 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, datalen
, 1.0);
934 case CUPS_SC_CMD_GET_STATE
: /* Return device state */
935 data
[0] = CUPS_SC_STATE_ONLINE
;
936 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
940 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
945 while (!g
.sidechannel_thread_stop
);
947 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
948 g
.sidechannel_thread_done
= 1;
949 pthread_cond_signal(&g
.sidechannel_thread_cond
);
950 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
958 * 'iterate_printers()' - Iterate over all the printers.
961 static void iterate_printers(iterator_callback_t callBack
,
964 mach_port_t masterPort
= 0x0;
965 kern_return_t kr
= IOMasterPort (bootstrap_port
, &masterPort
);
967 if (kr
== kIOReturnSuccess
&& masterPort
!= 0x0)
969 io_iterator_t addIterator
= 0x0;
971 iterator_reference_t reference
= { callBack
, userdata
, true };
972 IONotificationPortRef addNotification
= IONotificationPortCreate(masterPort
);
974 int klass
= kUSBPrintingClass
;
975 int subklass
= kUSBPrintingSubclass
;
977 CFNumberRef usb_klass
= CFNumberCreate(NULL
, kCFNumberIntType
, &klass
);
978 CFNumberRef usb_subklass
= CFNumberCreate(NULL
, kCFNumberIntType
, &subklass
);
979 CFMutableDictionaryRef usbPrinterMatchDictionary
= IOServiceMatching(kIOUSBInterfaceClassName
);
981 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceClass"), usb_klass
);
982 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceSubClass"), usb_subklass
);
984 CFRelease(usb_klass
);
985 CFRelease(usb_subklass
);
987 kr
= IOServiceAddMatchingNotification(addNotification
, kIOMatchedNotification
, usbPrinterMatchDictionary
, &device_added
, &reference
, &addIterator
);
988 if (addIterator
!= 0x0)
990 device_added (&reference
, addIterator
);
992 if (reference
.keepRunning
)
994 CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification
), kCFRunLoopDefaultMode
);
997 IOObjectRelease(addIterator
);
999 mach_port_deallocate(mach_task_self(), masterPort
);
1005 * 'device_added()' - Device added notifier.
1008 static void device_added(void *userdata
,
1009 io_iterator_t iterator
)
1011 iterator_reference_t
*reference
= userdata
;
1014 while (reference
->keepRunning
&& (obj
= IOIteratorNext(iterator
)) != 0x0)
1016 if (reference
->callback
!= NULL
)
1017 reference
->keepRunning
= reference
->callback(reference
->userdata
, obj
);
1019 IOObjectRelease(obj
);
1022 /* One last call to the call back now that we are not longer have printers left to iterate...
1024 if (reference
->keepRunning
)
1025 reference
->keepRunning
= reference
->callback(reference
->userdata
, 0x0);
1027 if (!reference
->keepRunning
)
1028 CFRunLoopStop(CFRunLoopGetCurrent());
1033 * 'list_device_cb()' - list_device iterator callback.
1036 static Boolean
list_device_cb(void *refcon
,
1039 Boolean keepRunning
= (obj
!= 0x0);
1043 CFStringRef deviceIDString
= NULL
;
1044 UInt32 deviceLocation
= 0;
1045 UInt8 interfaceNum
= 0;
1047 copy_devicestring(obj
, &deviceIDString
, &deviceLocation
, &interfaceNum
);
1048 if (deviceIDString
!= NULL
)
1050 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1051 char uristr
[1024], makestr
[1024], modelstr
[1024], serialstr
[1024];
1052 char optionsstr
[1024], idstr
[1024], make_modelstr
[1024];
1054 copy_deviceinfo(deviceIDString
, &make
, &model
, &serial
);
1055 CFStringGetCString(deviceIDString
, idstr
, sizeof(idstr
),
1056 kCFStringEncodingUTF8
);
1057 backendGetMakeModel(idstr
, make_modelstr
, sizeof(make_modelstr
));
1062 !CFStringGetCString(make
, makestr
, sizeof(makestr
),
1063 kCFStringEncodingUTF8
))
1064 strcpy(makestr
, "Unknown");
1067 !CFStringGetCString(model
, &modelstr
[1], sizeof(modelstr
)-1,
1068 kCFStringEncodingUTF8
))
1069 strcpy(modelstr
+ 1, "Printer");
1071 optionsstr
[0] = '\0';
1074 CFStringGetCString(serial
, serialstr
, sizeof(serialstr
), kCFStringEncodingUTF8
);
1075 snprintf(optionsstr
, sizeof(optionsstr
), "?serial=%s", serialstr
);
1077 else if (deviceLocation
!= 0)
1078 snprintf(optionsstr
, sizeof(optionsstr
), "?location=%x", (unsigned)deviceLocation
);
1080 httpAssembleURI(HTTP_URI_CODING_ALL
, uristr
, sizeof(uristr
), "usb", NULL
, makestr
, 0, modelstr
);
1081 strncat(uristr
, optionsstr
, sizeof(uristr
));
1083 cupsBackendReport("direct", uristr
, make_modelstr
, make_modelstr
, idstr
,
1086 release_deviceinfo(&make
, &model
, &serial
);
1087 CFRelease(deviceIDString
);
1096 * 'find_device_cb()' - print_device iterator callback.
1099 static Boolean
find_device_cb(void *refcon
,
1102 Boolean keepLooking
= true;
1106 CFStringRef idString
= NULL
;
1107 UInt32 location
= -1;
1108 UInt8 interfaceNum
= 0;
1110 copy_devicestring(obj
, &idString
, &location
, &interfaceNum
);
1111 if (idString
!= NULL
)
1113 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1115 copy_deviceinfo(idString
, &make
, &model
, &serial
);
1116 if (make
&& CFStringCompare(make
, g
.make
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1118 if (model
&& CFStringCompare(model
, g
.model
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1120 if (g
.serial
!= NULL
&& CFStringGetLength(g
.serial
) > 0)
1122 if (serial
!= NULL
&& CFStringCompare(serial
, g
.serial
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1124 IOObjectRetain(obj
);
1125 g
.printer_obj
= obj
;
1126 keepLooking
= false;
1131 if (g
.printer_obj
!= 0)
1132 IOObjectRelease(g
.printer_obj
);
1134 g
.printer_obj
= obj
;
1135 IOObjectRetain(obj
);
1137 if (g
.location
== 0 || g
.location
== location
)
1138 keepLooking
= false;
1141 g
.interfaceNum
= interfaceNum
;
1145 release_deviceinfo(&make
, &model
, &serial
);
1146 CFRelease(idString
);
1151 keepLooking
= (g
.printer_obj
== 0);
1152 if (obj
== 0x0 && keepLooking
)
1154 CFRunLoopTimerContext context
= { 0, refcon
, NULL
, NULL
, NULL
};
1155 CFRunLoopTimerRef timer
= CFRunLoopTimerCreate(NULL
, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb
, &context
);
1158 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer
, kCFRunLoopDefaultMode
);
1159 g
.status_timer
= timer
;
1164 if (!keepLooking
&& g
.status_timer
!= NULL
)
1166 fputs("STATE: -offline-report\n", stderr
);
1167 _cupsLangPuts(stderr
, _("INFO: Printer is now online.\n"));
1168 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g
.status_timer
, kCFRunLoopDefaultMode
);
1169 CFRelease(g
.status_timer
);
1170 g
.status_timer
= NULL
;
1178 * 'status_timer_cb()' - Status timer callback.
1181 static void status_timer_cb(CFRunLoopTimerRef timer
,
1184 fputs("STATE: +offline-report\n", stderr
);
1185 _cupsLangPuts(stderr
, _("INFO: Printer is offline.\n"));
1187 if (getenv("CLASS") != NULL
)
1190 * If the CLASS environment variable is set, the job was submitted
1191 * to a class and not to a specific queue. In this case, we want
1192 * to abort immediately so that the job can be requeued on the next
1193 * available printer in the class.
1195 * Sleep 5 seconds to keep the job from requeuing too rapidly...
1200 exit(CUPS_BACKEND_FAILED
);
1207 * 'copy_deviceinfo()' - Copy strings from the 1284 device ID.
1210 static void copy_deviceinfo(CFStringRef deviceIDString
,
1213 CFStringRef
*serial
)
1215 CFStringRef modelKeys
[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL
};
1216 CFStringRef makeKeys
[] = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL
};
1217 CFStringRef serialKeys
[] = { CFSTR("SN:"), CFSTR("SERN:"), NULL
};
1220 *make
= copy_value_for_key(deviceIDString
, makeKeys
);
1223 *model
= copy_value_for_key(deviceIDString
, modelKeys
);
1226 *serial
= copy_value_for_key(deviceIDString
, serialKeys
);
1231 * 'release_deviceinfo()' - Release deviceinfo strings.
1234 static void release_deviceinfo(CFStringRef
*make
,
1236 CFStringRef
*serial
)
1238 if (make
!= NULL
&& *make
!= NULL
)
1244 if (model
!= NULL
&& *model
!= NULL
)
1250 if (serial
!= NULL
&& *serial
!= NULL
)
1260 * 'load_classdriver()' - Load a classdriver.
1263 static kern_return_t
load_classdriver(CFStringRef driverPath
,
1264 printer_interface_t intf
,
1265 classdriver_t
***printerDriver
)
1267 kern_return_t kr
= kUSBPrinterClassDeviceNotOpen
;
1268 classdriver_t
**driver
= NULL
;
1269 CFStringRef bundle
= driverPath
? driverPath
: kUSBGenericTOPrinterClassDriver
;
1270 char bundlestr
[1024]; /* Bundle path */
1271 struct stat bundleinfo
; /* File information for bundle */
1272 CFURLRef url
; /* URL for driver */
1273 CFPlugInRef plugin
= NULL
; /* Plug-in address */
1276 CFStringGetCString(bundle
, bundlestr
, sizeof(bundlestr
), kCFStringEncodingUTF8
);
1279 * Validate permissions for the class driver...
1282 if (stat(bundlestr
, &bundleinfo
))
1284 fprintf(stderr
, "Unable to load class driver \"%s\": %s", bundlestr
,
1288 else if (bundleinfo
.st_mode
& S_IWOTH
)
1290 fprintf(stderr
, "Unable to load class driver \"%s\": insecure file "
1291 "permissions (0%o)", bundlestr
, bundleinfo
.st_mode
);
1296 * Try loading the class driver...
1299 url
= CFURLCreateWithFileSystemPath(NULL
, bundle
, kCFURLPOSIXPathStyle
, true);
1303 plugin
= CFPlugInCreate(NULL
, url
);
1311 CFArrayRef factories
= CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID
, plugin
);
1312 if (factories
!= NULL
&& CFArrayGetCount(factories
) > 0)
1314 CFUUIDRef factoryID
= CFArrayGetValueAtIndex(factories
, 0);
1315 IUnknownVTbl
**iunknown
= CFPlugInInstanceCreate(NULL
, factoryID
, kUSBPrinterClassTypeID
);
1316 if (iunknown
!= NULL
)
1318 kr
= (*iunknown
)->QueryInterface(iunknown
, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID
), (LPVOID
*)&driver
);
1319 if (kr
== kIOReturnSuccess
&& driver
!= NULL
)
1321 classdriver_t
**genericDriver
= NULL
;
1322 if (driverPath
!= NULL
&& CFStringCompare(driverPath
, kUSBGenericTOPrinterClassDriver
, 0) != kCFCompareEqualTo
)
1323 kr
= load_classdriver(NULL
, intf
, &genericDriver
);
1325 if (kr
== kIOReturnSuccess
)
1327 (*driver
)->interface
= intf
;
1328 (*driver
)->Initialize(driver
, genericDriver
);
1330 (*driver
)->plugin
= plugin
;
1331 (*driver
)->interface
= intf
;
1332 *printerDriver
= driver
;
1335 (*iunknown
)->Release(iunknown
);
1337 CFRelease(factories
);
1341 fprintf(stderr
, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr
, (int)kr
);
1348 * 'unload_classdriver()' - Unload a classdriver.
1351 static kern_return_t
unload_classdriver(classdriver_t
***classdriver
)
1353 if (*classdriver
!= NULL
)
1355 (**classdriver
)->Release(*classdriver
);
1356 *classdriver
= NULL
;
1359 return kIOReturnSuccess
;
1364 * 'load_printerdriver()' - Load vendor's classdriver.
1366 * If driverBundlePath is not NULL on return it is the callers responsbility to release it!
1369 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
)
1371 IOCFPlugInInterface
**iodev
= NULL
;
1374 printer_interface_t intf
;
1377 kr
= IOCreatePlugInInterfaceForService(g
.printer_obj
, kIOUSBInterfaceUserClientTypeID
, kIOCFPlugInInterfaceID
, &iodev
, &score
);
1378 if (kr
== kIOReturnSuccess
)
1380 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*) &intf
)) == noErr
)
1382 *driverBundlePath
= IORegistryEntryCreateCFProperty(g
.printer_obj
, kUSBClassDriverProperty
, NULL
, kNilOptions
);
1384 kr
= load_classdriver(*driverBundlePath
, intf
, &g
.classdriver
);
1386 if (kr
!= kIOReturnSuccess
)
1387 (*intf
)->Release(intf
);
1389 IODestroyPlugInInterface(iodev
);
1396 * 'registry_open()' - Open a connection to the printer.
1399 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
)
1401 g
.bidi_flag
= 0; /* 0=unidirectional */
1403 kern_return_t kr
= load_printerdriver(driverBundlePath
);
1404 if (kr
!= kIOReturnSuccess
)
1407 if (g
.classdriver
!= NULL
)
1409 (*g
.classdriver
)->interfaceNumber
= g
.interfaceNum
;
1410 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolBidirectional
);
1411 if (kr
!= kIOReturnSuccess
|| (*g
.classdriver
)->interface
== NULL
)
1413 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolUnidirectional
);
1414 if (kr
== kIOReturnSuccess
)
1416 if ((*g
.classdriver
)->interface
== NULL
)
1418 (*g
.classdriver
)->Close(g
.classdriver
);
1424 g
.bidi_flag
= 1; /* 1=bidirectional */
1427 if (kr
!= kIOReturnSuccess
)
1428 unload_classdriver(&g
.classdriver
);
1435 * 'registry_close()' - Close the connection to the printer.
1438 static kern_return_t
registry_close()
1440 if (g
.classdriver
!= NULL
)
1441 (*g
.classdriver
)->Close(g
.classdriver
);
1443 unload_classdriver(&g
.classdriver
);
1444 return kIOReturnSuccess
;
1449 * 'copy_deviceid()' - Copy the 1284 device id string.
1452 static OSStatus
copy_deviceid(classdriver_t
**classdriver
,
1453 CFStringRef
*deviceID
)
1455 CFStringRef devID
= NULL
,
1459 deviceSerial
= NULL
;
1461 OSStatus err
= (*classdriver
)->GetDeviceID(classdriver
, &devID
, DEFAULT_TIMEOUT
);
1463 copy_deviceinfo(devID
, &deviceMake
, &deviceModel
, &deviceSerial
);
1465 if (deviceMake
== NULL
|| deviceModel
== NULL
|| deviceSerial
== NULL
)
1467 IOUSBDeviceDescriptor desc
;
1468 iodevice_request_t request
;
1470 request
.requestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
1471 request
.request
= kUSBRqGetDescriptor
;
1472 request
.value
= (kUSBDeviceDesc
<< 8) | 0;
1474 request
.length
= sizeof(desc
);
1475 request
.buffer
= &desc
;
1476 err
= (*classdriver
)->DeviceRequest(classdriver
, &request
, DEFAULT_TIMEOUT
);
1477 if (err
== kIOReturnSuccess
)
1479 CFMutableStringRef newDevID
= CFStringCreateMutable(NULL
, 0);
1481 if (deviceMake
== NULL
)
1483 CFStringRef data
= NULL
;
1484 err
= (*classdriver
)->GetString(classdriver
, desc
.iManufacturer
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1487 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MFG:%@;"), data
);
1492 if (deviceModel
== NULL
)
1494 CFStringRef data
= NULL
;
1495 err
= (*classdriver
)->GetString(classdriver
, desc
.iProduct
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1498 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MDL:%@;"), data
);
1503 if (deviceSerial
== NULL
&& desc
.iSerialNumber
!= 0)
1505 CFStringRef data
= NULL
;
1506 err
= (*classdriver
)->GetString(classdriver
, desc
.iSerialNumber
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1509 CFStringAppendFormat(newDevID
, NULL
, CFSTR("SERN:%@;"), data
);
1516 CFStringAppend(newDevID
, devID
);
1520 *deviceID
= newDevID
;
1527 release_deviceinfo(&deviceMake
, &deviceModel
, &deviceSerial
);
1534 * 'copy_devicestring()' - Copy the 1284 device id string.
1537 static void copy_devicestring(io_service_t usbInterface
,
1538 CFStringRef
*deviceID
,
1539 UInt32
*deviceLocation
,
1540 UInt8
*interfaceNumber
)
1542 IOCFPlugInInterface
**iodev
= NULL
;
1545 printer_interface_t intf
;
1547 classdriver_t
**klassDriver
= NULL
;
1548 CFStringRef driverBundlePath
;
1550 if ((kr
= IOCreatePlugInInterfaceForService(usbInterface
,
1551 kIOUSBInterfaceUserClientTypeID
,
1552 kIOCFPlugInInterfaceID
,
1553 &iodev
, &score
)) == kIOReturnSuccess
)
1555 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*)
1558 (*intf
)->GetLocationID(intf
, deviceLocation
);
1559 (*intf
)->GetInterfaceNumber(intf
, interfaceNumber
);
1561 driverBundlePath
= IORegistryEntryCreateCFProperty(usbInterface
,
1562 kUSBClassDriverProperty
,
1565 kr
= load_classdriver(driverBundlePath
, intf
, &klassDriver
);
1567 if (kr
!= kIOReturnSuccess
&& driverBundlePath
!= NULL
)
1568 kr
= load_classdriver(NULL
, intf
, &klassDriver
);
1570 if (kr
== kIOReturnSuccess
&& klassDriver
!= NULL
)
1571 kr
= copy_deviceid(klassDriver
, deviceID
);
1573 unload_classdriver(&klassDriver
);
1575 if (driverBundlePath
!= NULL
)
1576 CFRelease(driverBundlePath
);
1578 /* (*intf)->Release(intf); */
1580 IODestroyPlugInInterface(iodev
);
1587 * 'copy_value_for_key()' - Copy value string associated with a key.
1590 static CFStringRef
copy_value_for_key(CFStringRef deviceID
,
1593 CFStringRef value
= NULL
;
1594 CFArrayRef kvPairs
= deviceID
!= NULL
? CFStringCreateArrayBySeparatingStrings(NULL
, deviceID
, CFSTR(";")) : NULL
;
1595 CFIndex max
= kvPairs
!= NULL
? CFArrayGetCount(kvPairs
) : 0;
1598 while (idx
< max
&& value
== NULL
)
1600 CFStringRef kvpair
= CFArrayGetValueAtIndex(kvPairs
, idx
);
1602 while (keys
[idxx
] != NULL
&& value
== NULL
)
1604 CFRange range
= CFStringFind(kvpair
, keys
[idxx
], kCFCompareCaseInsensitive
);
1605 if (range
.length
!= -1)
1607 if (range
.location
!= 0)
1609 CFMutableStringRef theString
= CFStringCreateMutableCopy(NULL
, 0, kvpair
);
1610 CFStringTrimWhitespace(theString
);
1611 range
= CFStringFind(theString
, keys
[idxx
], kCFCompareCaseInsensitive
);
1612 if (range
.location
== 0)
1613 value
= CFStringCreateWithSubstring(NULL
, theString
, CFRangeMake(range
.length
, CFStringGetLength(theString
) - range
.length
));
1615 CFRelease(theString
);
1619 CFStringRef theString
= CFStringCreateWithSubstring(NULL
, kvpair
, CFRangeMake(range
.length
, CFStringGetLength(kvpair
) - range
.length
));
1620 CFMutableStringRef theString2
= CFStringCreateMutableCopy(NULL
, 0, theString
);
1621 CFRelease(theString
);
1623 CFStringTrimWhitespace(theString2
);
1632 if (kvPairs
!= NULL
)
1639 * 'cfstr_create_trim()' - Create CFString and trim whitespace characters.
1642 CFStringRef
cfstr_create_trim(const char *cstr
)
1645 CFMutableStringRef cfmutablestr
= NULL
;
1647 if ((cfstr
= CFStringCreateWithCString(NULL
, cstr
, kCFStringEncodingUTF8
)) != NULL
)
1649 if ((cfmutablestr
= CFStringCreateMutableCopy(NULL
, 1024, cfstr
)) != NULL
)
1650 CFStringTrimWhitespace(cfmutablestr
);
1654 return (CFStringRef
) cfmutablestr
;
1660 * 'parse_options()' - Parse URI options.
1663 static void parse_options(char *options
,
1669 char sep
, /* Separator character */
1670 *name
, /* Name of option */
1671 *value
; /* Value of option */
1690 while (*options
&& *options
!= '=' && *options
!= '+' && *options
!= '&')
1693 if ((sep
= *options
) != '\0')
1704 while (*options
&& *options
!= '+' && *options
!= '&')
1714 * Process the option...
1717 if (!strcasecmp(name
, "waiteof"))
1719 if (!strcasecmp(value
, "on") ||
1720 !strcasecmp(value
, "yes") ||
1721 !strcasecmp(value
, "true"))
1723 else if (!strcasecmp(value
, "off") ||
1724 !strcasecmp(value
, "no") ||
1725 !strcasecmp(value
, "false"))
1728 _cupsLangPrintf(stderr
,
1729 _("WARNING: Boolean expected for waiteof option "
1730 "\"%s\"\n"), value
);
1732 else if (!strcasecmp(name
, "serial"))
1733 strlcpy(serial
, value
, serial_size
);
1734 else if (!strcasecmp(name
, "location") && location
)
1735 *location
= strtol(value
, NULL
, 16);
1741 * @function setup_cfLanguage
1742 * @abstract Convert the contents of the CUPS 'APPLE_LANGUAGE' environment
1743 * variable into a one element CF array of languages.
1745 * @discussion Each submitted job comes with a natural language. CUPS passes
1746 * that language in an environment variable. We take that language
1747 * and jam it into the AppleLanguages array so that CF will use
1748 * it when reading localized resources. We need to do this before
1749 * any CF code reads and caches the languages array, so this function
1750 * should be called early in main()
1752 static void setup_cfLanguage(void)
1754 CFStringRef lang
[1] = {NULL
};
1755 CFArrayRef langArray
= NULL
;
1756 const char *requestedLang
= NULL
;
1758 if ((requestedLang
= getenv("APPLE_LANGUAGE")) == NULL
)
1759 requestedLang
= getenv("LANG");
1761 if (requestedLang
!= NULL
)
1763 lang
[0] = CFStringCreateWithCString(kCFAllocatorDefault
, requestedLang
, kCFStringEncodingUTF8
);
1764 langArray
= CFArrayCreate(kCFAllocatorDefault
, (const void **)lang
, sizeof(lang
) / sizeof(lang
[0]), &kCFTypeArrayCallBacks
);
1766 CFPreferencesSetValue(CFSTR("AppleLanguages"), langArray
, kCFPreferencesCurrentApplication
, kCFPreferencesAnyUser
, kCFPreferencesAnyHost
);
1767 fprintf(stderr
, "DEBUG: usb: AppleLanguages=\"%s\"\n", requestedLang
);
1770 CFRelease(langArray
);
1773 fputs("DEBUG: usb: LANG and APPLE_LANGUAGE environment variables missing.\n", stderr
);
1777 #if defined(__i386__) || defined(__x86_64__)
1779 * @function run_legacy_backend
1781 * @abstract Starts child backend process running as a ppc or i386 executable.
1783 * @result Never returns; always calls exit().
1787 static void run_legacy_backend(int argc
,
1794 pid_t waitpid_status
;
1796 char *usb_legacy_status
;
1799 * If we're running as x86_64 or i386 and couldn't load the class driver
1800 * (because it's ppc or i386), then try to re-exec ourselves in ppc or i386
1801 * mode to try again. If we don't have a ppc or i386 architecture we may be
1802 * running with the same architecture again so guard against this by setting
1803 * and testing an environment variable...
1807 usb_legacy_status
= getenv("USB_I386_STATUS");
1809 usb_legacy_status
= getenv("USB_PPC_STATUS");
1810 # endif /* __x86_64__ */
1812 if (!usb_legacy_status
)
1815 * Setup a SIGTERM handler then block it before forking...
1818 struct sigaction action
; /* POSIX signal action */
1819 sigset_t newmask
, /* New signal mask */
1820 oldmask
; /* Old signal mask */
1821 char usbpath
[1024]; /* Path to USB backend */
1822 const char *cups_serverbin
;/* Path to CUPS binaries */
1825 memset(&action
, 0, sizeof(action
));
1826 sigaddset(&action
.sa_mask
, SIGTERM
);
1827 action
.sa_handler
= sigterm_handler
;
1828 sigaction(SIGTERM
, &action
, NULL
);
1830 sigemptyset(&newmask
);
1831 sigaddset(&newmask
, SIGTERM
);
1832 sigprocmask(SIG_BLOCK
, &newmask
, &oldmask
);
1835 * Set the environment variable...
1839 setenv("USB_I386_STATUS", "1", false);
1841 setenv("USB_PPC_STATUS", "1", false);
1842 # endif /* __x86_64__ */
1845 * Tell the kernel to use the specified CPU architecture...
1849 cpu_type_t cpu
= CPU_TYPE_I386
;
1851 cpu_type_t cpu
= CPU_TYPE_POWERPC
;
1852 # endif /* __x86_64__ */
1854 posix_spawnattr_t attrs
;
1856 if (!posix_spawnattr_init(&attrs
))
1858 posix_spawnattr_setsigdefault(&attrs
, &oldmask
);
1859 if (posix_spawnattr_setbinpref_np(&attrs
, 1, &cpu
, &ocount
) || ocount
!= 1)
1862 perror("DEBUG: Unable to set binary preference to i386");
1864 perror("DEBUG: Unable to set binary preference to ppc");
1865 # endif /* __x86_64__ */
1866 _cupsLangPrintf(stderr
, _("Unable to use legacy USB class driver!\n"));
1867 exit(CUPS_BACKEND_STOP
);
1872 * Set up the arguments and call posix_spawn...
1875 if ((cups_serverbin
= getenv("CUPS_SERVERBIN")) == NULL
)
1876 cups_serverbin
= CUPS_SERVERBIN
;
1877 snprintf(usbpath
, sizeof(usbpath
), "%s/backend/usb", cups_serverbin
);
1879 for (i
= 0; i
< argc
&& i
< (sizeof(my_argv
) / sizeof(my_argv
[0])) - 1; i
++)
1880 my_argv
[i
] = argv
[i
];
1884 if (posix_spawn(&child_pid
, usbpath
, NULL
, &attrs
, my_argv
, environ
))
1886 fprintf(stderr
, "DEBUG: Unable to exec %s: %s\n", usbpath
,
1888 _cupsLangPrintf(stderr
, _("Unable to use legacy USB class driver!\n"));
1889 exit(CUPS_BACKEND_STOP
);
1893 * Unblock signals...
1896 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
1899 * Close the fds we won't be using then wait for the child backend to exit.
1905 fprintf(stderr
, "DEBUG: Started usb(legacy) backend (PID %d)\n",
1908 while ((waitpid_status
= waitpid(child_pid
, &childstatus
, 0)) == (pid_t
)-1 && errno
== EINTR
)
1911 if (WIFSIGNALED(childstatus
))
1913 exitstatus
= CUPS_BACKEND_STOP
;
1914 fprintf(stderr
, "DEBUG: usb(legacy) backend %d crashed on signal %d!\n",
1915 child_pid
, WTERMSIG(childstatus
));
1919 if ((exitstatus
= WEXITSTATUS(childstatus
)) != 0)
1921 "DEBUG: usb(legacy) backend %d stopped with status %d!\n",
1922 child_pid
, exitstatus
);
1924 fprintf(stderr
, "DEBUG: usb(legacy) backend %d exited with no errors\n",
1930 fputs("DEBUG: usb(legacy) backend running native again\n", stderr
);
1931 exitstatus
= CUPS_BACKEND_STOP
;
1936 #endif /* __i386__ || __x86_64__ */
1940 * 'sigterm_handler()' - SIGTERM handler.
1944 sigterm_handler(int sig
) /* I - Signal */
1946 #if defined(__i386__) || defined(__x86_64__)
1950 * If we started a child process pass the signal on to it...
1955 kill(child_pid
, sig
);
1956 while (waitpid(child_pid
, &status
, 0) < 0 && errno
== EINTR
);
1958 if (WIFEXITED(status
))
1959 exit(WEXITSTATUS(status
));
1960 else if (status
== SIGTERM
|| status
== SIGKILL
)
1964 fprintf(stderr
, "DEBUG: Child crashed on signal %d!\n", status
);
1965 exit(CUPS_BACKEND_STOP
);
1968 #endif /* __i386__ || __x86_64__ */
1971 * Otherwise just flag that the job has been canceled...
1978 #ifdef PARSE_PS_ERRORS
1980 * 'next_line()' - Find the next line in a buffer.
1983 static const char *next_line (const char *buffer
)
1985 const char *cptr
, *lptr
= NULL
;
1987 for (cptr
= buffer
; *cptr
&& lptr
== NULL
; cptr
++)
1988 if (*cptr
== '\n' || *cptr
== '\r')
1995 * 'parse_pserror()' - Scan the backchannel data for postscript errors.
1998 static void parse_pserror(char *sockBuffer
,
2001 static char gErrorBuffer
[1024] = "";
2002 static char *gErrorBufferPtr
= gErrorBuffer
;
2003 static char *gErrorBufferEndPtr
= gErrorBuffer
+ sizeof(gErrorBuffer
);
2005 char *pCommentBegin
, *pCommentEnd
, *pLineEnd
;
2010 if (gErrorBufferPtr
+ len
> gErrorBufferEndPtr
- 1)
2011 gErrorBufferPtr
= gErrorBuffer
;
2012 if (len
> sizeof(gErrorBuffer
) - 1)
2013 len
= sizeof(gErrorBuffer
) - 1;
2015 memcpy(gErrorBufferPtr
, (const void *)sockBuffer
, len
);
2016 gErrorBufferPtr
+= len
;
2017 *(gErrorBufferPtr
+ 1) = '\0';
2019 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
2020 while (pLineEnd
!= NULL
)
2024 pCommentBegin
= strstr(gErrorBuffer
,"%%[");
2025 pCommentEnd
= strstr(gErrorBuffer
, "]%%");
2026 if (pCommentBegin
!= gErrorBuffer
&& pCommentEnd
!= NULL
)
2028 pCommentEnd
+= 3; /* Skip past "]%%" */
2029 *pCommentEnd
= '\0'; /* There's always room for the nul */
2031 if (strncasecmp(pCommentBegin
, "%%[ Error:", 10) == 0)
2033 else if (strncasecmp(pCommentBegin
, "%%[ Flushing", 12) == 0)
2038 if ((logstrlen
= snprintf(logstr
, sizeof(logstr
), "%s: %s\n", logLevel
, pCommentBegin
)) >= sizeof(logstr
))
2040 /* If the string was trucnated make sure it has a linefeed before the nul */
2041 logstrlen
= sizeof(logstr
) - 1;
2042 logstr
[logstrlen
- 1] = '\n';
2044 write(STDERR_FILENO
, logstr
, logstrlen
);
2047 /* move everything over... */
2048 strcpy(gErrorBuffer
, pLineEnd
);
2049 gErrorBufferPtr
= gErrorBuffer
;
2050 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
2053 #endif /* PARSE_PS_ERRORS */
2057 * 'soft_reset()' - Send a soft reset to the device.
2060 static void soft_reset()
2062 fd_set input_set
; /* Input set for select() */
2063 struct timeval stimeout
; /* Timeout for select() */
2064 char buffer
[2048]; /* Buffer */
2065 struct timespec cond_timeout
; /* pthread condition timeout */
2068 * Send an abort once a second until the I/O lock is released by the main thread...
2071 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2072 while (g
.readwrite_lock
)
2074 (*g
.classdriver
)->Abort(g
.classdriver
);
2076 cond_timeout
.tv_sec
= time(NULL
) + 1;
2077 cond_timeout
.tv_nsec
= 0;
2079 pthread_cond_timedwait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
, &cond_timeout
);
2082 g
.readwrite_lock
= 1;
2083 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2086 * Flush bytes waiting on print_fd...
2091 FD_ZERO(&input_set
);
2092 FD_SET(g
.print_fd
, &input_set
);
2094 stimeout
.tv_sec
= 0;
2095 stimeout
.tv_usec
= 0;
2097 while (select(g
.print_fd
+1, &input_set
, NULL
, NULL
, &stimeout
) > 0)
2098 if (read(g
.print_fd
, buffer
, sizeof(buffer
)) <= 0)
2105 (*g
.classdriver
)->SoftReset(g
.classdriver
, DEFAULT_TIMEOUT
);
2108 * Release the I/O lock...
2111 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2112 g
.readwrite_lock
= 0;
2113 pthread_cond_signal(&g
.readwrite_lock_cond
);
2114 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2119 * 'get_device_id()' - Return IEEE-1284 device ID.
2122 static void get_device_id(cups_sc_status_t
*status
,
2126 UInt32 deviceLocation
= 0;
2127 UInt8 interfaceNum
= 0;
2128 CFStringRef deviceIDString
= NULL
;
2131 copy_devicestring(g
.printer_obj
, &deviceIDString
, &deviceLocation
, &interfaceNum
);
2134 CFStringGetCString(deviceIDString
, data
, *datalen
, kCFStringEncodingUTF8
);
2135 *datalen
= strlen(data
);
2136 CFRelease(deviceIDString
);
2138 *status
= CUPS_SC_STATUS_OK
;
2143 * End of "$Id: usb-darwin.c 7953 2008-09-17 01:43:19Z mike $".