4 * Copyright 2005-2013 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 * Include necessary headers.
57 #include <sys/sysctl.h>
59 #include <mach/mach.h>
60 #include <mach/mach_error.h>
61 #include <mach/mach_time.h>
62 #include <cups/debug-private.h>
63 #include <cups/file-private.h>
64 #include <cups/sidechannel.h>
65 #include <cups/language-private.h>
66 #include "backend-private.h"
67 #include <CoreFoundation/CoreFoundation.h>
68 #include <IOKit/usb/IOUSBLib.h>
69 #include <IOKit/IOCFPlugIn.h>
75 extern char **environ
;
79 * DEBUG_WRITES, if defined, causes the backend to write data to the printer in
80 * 512 byte increments, up to 8192 bytes, to make debugging with a USB bus
84 #define DEBUG_WRITES 0
87 * WAIT_EOF_DELAY is number of seconds we'll wait for responses from
88 * the printer after we've finished sending all the data
90 #define WAIT_EOF_DELAY 7
91 #define WAIT_SIDE_DELAY 3
92 #define DEFAULT_TIMEOUT 5000L
94 #define USB_INTERFACE_KIND CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID190)
95 #define kUSBLanguageEnglish 0x409
97 #define PRINTER_POLLING_INTERVAL 5 /* seconds */
98 #define INITIAL_LOG_INTERVAL PRINTER_POLLING_INTERVAL
99 #define SUBSEQUENT_LOG_INTERVAL 3 * INITIAL_LOG_INTERVAL
101 #define kUSBPrinterClassTypeID CFUUIDGetConstantUUIDWithBytes(NULL, 0x06, 0x04, 0x7D, 0x16, 0x53, 0xA2, 0x11, 0xD6, 0x92, 0x06, 0x00, 0x30, 0x65, 0x52, 0x45, 0x92)
102 #define kUSBPrinterClassInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, 0x03, 0x34, 0x6D, 0x74, 0x53, 0xA3, 0x11, 0xD6, 0x9E, 0xA1, 0x76, 0x30, 0x65, 0x52, 0x45, 0x92)
104 #define kUSBClassDriverProperty CFSTR("USB Printing Class")
106 #define kUSBGenericTOPrinterClassDriver CFSTR("/System/Library/Printers/Libraries/USBGenericPrintingClass.plugin")
107 #define kUSBPrinterClassDeviceNotOpen -9664 /*kPMInvalidIOMContext*/
109 #define CRSetCrashLogMessage(m) _crc_make_setter(message, m)
110 #define _crc_make_setter(attr, arg) (gCRAnnotations.attr = (uint64_t)(unsigned long)(arg))
111 #define CRASH_REPORTER_CLIENT_HIDDEN __attribute__((visibility("hidden")))
112 #define CRASHREPORTER_ANNOTATIONS_VERSION 4
113 #define CRASHREPORTER_ANNOTATIONS_SECTION "__crash_info"
115 struct crashreporter_annotations_t
{
116 uint64_t version
; // unsigned long
117 uint64_t message
; // char *
118 uint64_t signature_string
; // char *
119 uint64_t backtrace
; // char *
120 uint64_t message2
; // char *
121 uint64_t thread
; // uint64_t
122 uint64_t dialog_mode
; // unsigned int
125 CRASH_REPORTER_CLIENT_HIDDEN
126 struct crashreporter_annotations_t gCRAnnotations
127 __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION
)))
128 = { CRASHREPORTER_ANNOTATIONS_VERSION
, 0, 0, 0, 0, 0, 0 };
131 * Section 5.3 USB Printing Class spec
133 #define kUSBPrintingSubclass 1
134 #define kUSBPrintingProtocolNoOpen 0
135 #define kUSBPrintingProtocolUnidirectional 1
136 #define kUSBPrintingProtocolBidirectional 2
138 typedef IOUSBInterfaceInterface190
**printer_interface_t
;
140 typedef struct iodevice_request_s
/**** Device request ****/
148 } iodevice_request_t
;
150 typedef union /**** Centronics status byte ****/
155 unsigned reserved0
:2;
156 unsigned paperError
:1;
159 unsigned reserved1
:3;
161 } centronics_status_t
;
163 typedef struct classdriver_s
/**** g.classdriver context ****/
166 CFPlugInRef plugin
; /* release plugin */
167 IUnknownVTbl
**factory
; /* Factory */
168 void *vendorReference
; /* vendor class specific usage */
169 UInt32 location
; /* unique location in bus topology */
170 UInt8 interfaceNumber
; /* Interface number */
171 UInt16 vendorID
; /* Vendor id */
172 UInt16 productID
; /* Product id */
173 printer_interface_t interface
; /* identify the device to IOKit */
174 UInt8 outpipe
; /* mandatory bulkOut pipe */
175 UInt8 inpipe
; /* optional bulkIn pipe */
177 /* general class requests */
178 kern_return_t (*DeviceRequest
)(struct classdriver_s
**printer
, iodevice_request_t
*iorequest
, UInt16 timeout
);
179 kern_return_t (*GetString
)(struct classdriver_s
**printer
, UInt8 whichString
, UInt16 language
, UInt16 timeout
, CFStringRef
*result
);
181 /* standard printer class requests */
182 kern_return_t (*SoftReset
)(struct classdriver_s
**printer
, UInt16 timeout
);
183 kern_return_t (*GetCentronicsStatus
)(struct classdriver_s
**printer
, centronics_status_t
*result
, UInt16 timeout
);
184 kern_return_t (*GetDeviceID
)(struct classdriver_s
**printer
, CFStringRef
*devid
, UInt16 timeout
);
186 /* standard bulk device requests */
187 kern_return_t (*ReadPipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
);
188 kern_return_t (*WritePipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
, Boolean eoj
);
190 /* interface requests */
191 kern_return_t (*Open
)(struct classdriver_s
**printer
, UInt32 location
, UInt8 protocol
);
192 kern_return_t (*Abort
)(struct classdriver_s
**printer
);
193 kern_return_t (*Close
)(struct classdriver_s
**printer
);
195 /* initialize and terminate */
196 kern_return_t (*Initialize
)(struct classdriver_s
**printer
, struct classdriver_s
**baseclass
);
197 kern_return_t (*Terminate
)(struct classdriver_s
**printer
);
201 typedef Boolean (*iterator_callback_t
)(void *refcon
, io_service_t obj
);
203 typedef struct iterator_reference_s
/**** Iterator reference data */
205 iterator_callback_t callback
;
208 } iterator_reference_t
;
210 typedef struct globals_s
212 io_service_t printer_obj
;
213 classdriver_t
**classdriver
;
215 pthread_mutex_t read_thread_mutex
;
216 pthread_cond_t read_thread_cond
;
217 int read_thread_stop
;
218 int read_thread_done
;
220 pthread_mutex_t readwrite_lock_mutex
;
221 pthread_cond_t readwrite_lock_cond
;
230 CFRunLoopTimerRef status_timer
;
232 int print_fd
; /* File descriptor to print */
233 ssize_t print_bytes
; /* Print bytes read */
235 ssize_t debug_bytes
; /* Current bytes to read */
236 #endif /* DEBUG_WRITES */
239 int drain_output
; /* Drain all pending output */
240 int bidi_flag
; /* 0=unidirectional, 1=bidirectional */
242 pthread_mutex_t sidechannel_thread_mutex
;
243 pthread_cond_t sidechannel_thread_cond
;
244 int sidechannel_thread_stop
;
245 int sidechannel_thread_done
;
253 globals_t g
= { 0 }; /* Globals */
254 int Iterating
= 0; /* Are we iterating the bus? */
261 static Boolean
find_device_cb(void *refcon
, io_service_t obj
);
262 static Boolean
list_device_cb(void *refcon
, io_service_t obj
);
263 static CFStringRef
cfstr_create_trim(const char *cstr
);
264 static CFStringRef
copy_value_for_key(CFStringRef deviceID
, CFStringRef
*keys
);
265 static kern_return_t
load_classdriver(CFStringRef driverPath
, printer_interface_t interface
, classdriver_t
***printerDriver
);
266 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
);
267 static kern_return_t
registry_close(void);
268 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
);
269 static kern_return_t
unload_classdriver(classdriver_t
***classdriver
);
270 static OSStatus
copy_deviceid(classdriver_t
**printer
, CFStringRef
*deviceID
);
271 static void *read_thread(void *reference
);
272 static void *sidechannel_thread(void *reference
);
273 static void copy_deviceinfo(CFStringRef deviceIDString
, CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
274 static void copy_devicestring(io_service_t usbInterface
, CFStringRef
*deviceID
, UInt32
*deviceLocation
, UInt8
*interfaceNum
);
275 static void device_added(void *userdata
, io_iterator_t iterator
);
276 static void get_device_id(cups_sc_status_t
*status
, char *data
, int *datalen
);
277 static void iterate_printers(iterator_callback_t callBack
, void *userdata
);
278 static void parse_options(char *options
, char *serial
, int serial_size
, UInt32
*location
, Boolean
*wait_eof
);
279 static void release_deviceinfo(CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
280 static void setup_cfLanguage(void);
281 static void soft_reset(void);
282 static void status_timer_cb(CFRunLoopTimerRef timer
, void *info
);
284 #if defined(__i386__) || defined(__x86_64__)
285 static pid_t child_pid
; /* Child PID */
286 static void run_legacy_backend(int argc
, char *argv
[], int fd
); /* Starts child backend process running as a ppc executable */
287 #endif /* __i386__ || __x86_64__ */
288 static void sigterm_handler(int sig
); /* SIGTERM handler */
289 static void sigquit_handler(int sig
, siginfo_t
*si
, void *unused
);
291 #ifdef PARSE_PS_ERRORS
292 static const char *next_line (const char *buffer
);
293 static void parse_pserror (char *sockBuffer
, int len
);
294 #endif /* PARSE_PS_ERRORS */
299 * 'list_devices()' - List all USB devices.
304 iterate_printers(list_device_cb
, NULL
);
309 * 'print_device()' - Print a file to a USB device.
312 int /* O - Exit status */
313 print_device(const char *uri
, /* I - Device URI */
314 const char *hostname
, /* I - Hostname/manufacturer */
315 const char *resource
, /* I - Resource/modelname */
316 char *options
, /* I - Device options/serial number */
317 int print_fd
, /* I - File descriptor to print */
318 int copies
, /* I - Copies to print */
319 int argc
, /* I - Number of command-line arguments (6 or 7) */
320 char *argv
[]) /* I - Command-line arguments */
322 char serial
[1024]; /* Serial number buffer */
323 OSStatus status
; /* Function results */
324 IOReturn iostatus
; /* Current IO status */
325 pthread_t read_thread_id
, /* Read thread */
326 sidechannel_thread_id
;/* Side-channel thread */
327 int have_sidechannel
= 0; /* Was the side-channel thread started? */
328 struct stat sidechannel_info
; /* Side-channel file descriptor info */
329 char print_buffer
[8192], /* Print data buffer */
330 *print_ptr
; /* Pointer into print data buffer */
331 UInt32 location
; /* Unique location in bus topology */
332 fd_set input_set
; /* Input set for select() */
333 CFStringRef driverBundlePath
; /* Class driver path */
334 int countdown
, /* Logging interval */
335 nfds
; /* Number of file descriptors */
336 ssize_t total_bytes
; /* Total bytes written */
337 UInt32 bytes
; /* Bytes written */
338 struct timeval
*timeout
, /* Timeout pointer */
340 struct timespec cond_timeout
; /* pthread condition timeout */
341 struct sigaction action
; /* Actions for POSIX signals */
347 * Catch SIGQUIT to determine who is sending it...
350 memset(&action
, 0, sizeof(action
));
351 action
.sa_sigaction
= sigquit_handler
;
352 action
.sa_flags
= SA_SIGINFO
;
353 sigaction(SIGQUIT
, &action
, NULL
);
356 * See if the side-channel descriptor is valid...
359 have_sidechannel
= !fstat(CUPS_SC_FD
, &sidechannel_info
) &&
360 S_ISSOCK(sidechannel_info
.st_mode
);
363 * Localize using CoreFoundation...
368 parse_options(options
, serial
, sizeof(serial
), &location
, &g
.wait_eof
);
370 if (resource
[0] == '/')
373 g
.print_fd
= print_fd
;
374 g
.make
= cfstr_create_trim(hostname
);
375 g
.model
= cfstr_create_trim(resource
);
376 g
.serial
= cfstr_create_trim(serial
);
377 g
.location
= location
;
379 if (!g
.make
|| !g
.model
)
381 fprintf(stderr
, "DEBUG: Fatal USB error.\n");
382 _cupsLangPrintFilter(stderr
, "ERROR",
383 _("There was an unrecoverable USB error."));
386 fputs("DEBUG: USB make string is NULL\n", stderr
);
388 fputs("DEBUG: USB model string is NULL\n", stderr
);
390 return (CUPS_BACKEND_STOP
);
393 fputs("STATE: +connecting-to-device\n", stderr
);
395 countdown
= INITIAL_LOG_INTERVAL
;
401 IOObjectRelease(g
.printer_obj
);
402 unload_classdriver(&g
.classdriver
);
407 fprintf(stderr
, "DEBUG: Looking for '%s %s'\n", hostname
, resource
);
409 iterate_printers(find_device_cb
, NULL
);
411 fputs("DEBUG: Opening connection\n", stderr
);
413 driverBundlePath
= NULL
;
415 status
= registry_open(&driverBundlePath
);
417 #if defined(__i386__) || defined(__x86_64__)
419 * If we were unable to load the class drivers for this printer it's
420 * probably because they're ppc or i386. In this case try to run this
421 * backend as i386 or ppc executables so we can use them...
425 run_legacy_backend(argc
, argv
, print_fd
);
426 /* Never returns here */
428 #endif /* __i386__ || __x86_64__ */
433 * If we still were unable to load the class drivers for this printer log
434 * the error and stop the queue...
437 if (driverBundlePath
== NULL
|| !CFStringGetCString(driverBundlePath
, print_buffer
, sizeof(print_buffer
), kCFStringEncodingUTF8
))
438 strlcpy(print_buffer
, "USB class driver", sizeof(print_buffer
));
440 fputs("STATE: +apple-missing-usbclassdriver-error\n", stderr
);
441 _cupsLangPrintFilter(stderr
, "ERROR",
442 _("There was an unrecoverable USB error."));
443 fprintf(stderr
, "DEBUG: Could not load %s\n", print_buffer
);
445 if (driverBundlePath
)
446 CFRelease(driverBundlePath
);
448 return (CUPS_BACKEND_STOP
);
451 if (driverBundlePath
)
452 CFRelease(driverBundlePath
);
456 sleep(PRINTER_POLLING_INTERVAL
);
457 countdown
-= PRINTER_POLLING_INTERVAL
;
460 _cupsLangPrintFilter(stderr
, "INFO",
461 _("Waiting for printer to become available."));
462 fprintf(stderr
, "DEBUG: USB printer status: 0x%08x\n", (int)status
);
463 countdown
= SUBSEQUENT_LOG_INTERVAL
; /* subsequent log entries, every 15 seconds */
466 } while (status
!= noErr
);
468 fputs("STATE: -connecting-to-device\n", stderr
);
471 * Now that we are "connected" to the port, ignore SIGTERM so that we
472 * can finish out any page data the driver sends (e.g. to eject the
473 * current page... Only ignore SIGTERM if we are printing data from
474 * stdin (otherwise you can't cancel raw jobs...)
479 memset(&action
, 0, sizeof(action
));
481 sigemptyset(&action
.sa_mask
);
482 action
.sa_handler
= SIG_IGN
;
483 sigaction(SIGTERM
, &action
, NULL
);
487 * Start the side channel thread if the descriptor is valid...
490 pthread_mutex_init(&g
.readwrite_lock_mutex
, NULL
);
491 pthread_cond_init(&g
.readwrite_lock_cond
, NULL
);
492 g
.readwrite_lock
= 1;
494 if (have_sidechannel
)
496 g
.sidechannel_thread_stop
= 0;
497 g
.sidechannel_thread_done
= 0;
499 pthread_cond_init(&g
.sidechannel_thread_cond
, NULL
);
500 pthread_mutex_init(&g
.sidechannel_thread_mutex
, NULL
);
502 if (pthread_create(&sidechannel_thread_id
, NULL
, sidechannel_thread
, NULL
))
504 fprintf(stderr
, "DEBUG: Fatal USB error.\n");
505 _cupsLangPrintFilter(stderr
, "ERROR",
506 _("There was an unrecoverable USB error."));
507 fputs("DEBUG: Couldn't create side-channel thread\n", stderr
);
509 return (CUPS_BACKEND_STOP
);
514 * Get the read thread going...
517 g
.read_thread_stop
= 0;
518 g
.read_thread_done
= 0;
520 pthread_cond_init(&g
.read_thread_cond
, NULL
);
521 pthread_mutex_init(&g
.read_thread_mutex
, NULL
);
523 if (pthread_create(&read_thread_id
, NULL
, read_thread
, NULL
))
525 fprintf(stderr
, "DEBUG: Fatal USB error.\n");
526 _cupsLangPrintFilter(stderr
, "ERROR",
527 _("There was an unrecoverable USB error."));
528 fputs("DEBUG: Couldn't create read thread\n", stderr
);
530 return (CUPS_BACKEND_STOP
);
534 * The main thread sends the print file...
540 print_ptr
= print_buffer
;
542 while (status
== noErr
&& copies
-- > 0)
544 _cupsLangPrintFilter(stderr
, "INFO", _("Sending data to printer."));
546 if (print_fd
!= STDIN_FILENO
)
548 fputs("PAGE: 1 1\n", stderr
);
549 lseek(print_fd
, 0, SEEK_SET
);
552 while (status
== noErr
)
557 FD_SET(print_fd
, &input_set
);
560 * Calculate select timeout...
561 * If we have data waiting to send timeout is 100ms.
562 * else if we're draining print_fd timeout is 0.
563 * else we're waiting forever...
569 tv
.tv_usec
= 100000; /* 100ms */
572 else if (g
.drain_output
)
582 * I/O is unlocked around select...
585 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
586 g
.readwrite_lock
= 0;
587 pthread_cond_signal(&g
.readwrite_lock_cond
);
588 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
590 nfds
= select(print_fd
+ 1, &input_set
, NULL
, NULL
, timeout
);
593 * Reacquire the lock...
596 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
597 while (g
.readwrite_lock
)
598 pthread_cond_wait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
);
599 g
.readwrite_lock
= 1;
600 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
604 if (errno
== EINTR
&& total_bytes
== 0)
606 fputs("DEBUG: Received an interrupt before any bytes were "
607 "written, aborting\n", stderr
);
609 return (CUPS_BACKEND_OK
);
611 else if (errno
!= EAGAIN
&& errno
!= EINTR
)
613 _cupsLangPrintFilter(stderr
, "ERROR",
614 _("Unable to read print data."));
615 perror("DEBUG: select");
617 return (CUPS_BACKEND_FAILED
);
622 * If drain output has finished send a response...
625 if (g
.drain_output
&& !nfds
&& !g
.print_bytes
)
627 /* Send a response... */
628 cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
633 * Check if we have print data ready...
636 if (FD_ISSET(print_fd
, &input_set
))
639 g
.debug_bytes
+= 512;
640 if (g
.debug_bytes
> sizeof(print_buffer
))
643 g
.print_bytes
= read(print_fd
, print_buffer
, g
.debug_bytes
);
646 g
.print_bytes
= read(print_fd
, print_buffer
, sizeof(print_buffer
));
647 #endif /* DEBUG_WRITES */
649 if (g
.print_bytes
< 0)
652 * Read error - bail if we don't see EAGAIN or EINTR...
655 if (errno
!= EAGAIN
&& errno
!= EINTR
)
657 _cupsLangPrintFilter(stderr
, "ERROR",
658 _("Unable to read print data."));
659 perror("DEBUG: read");
661 return (CUPS_BACKEND_FAILED
);
666 else if (g
.print_bytes
== 0)
669 * End of file, break out of the loop...
675 print_ptr
= print_buffer
;
677 fprintf(stderr
, "DEBUG: Read %d bytes of print data...\n",
683 bytes
= g
.print_bytes
;
684 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
687 * Ignore timeout errors, but retain the number of bytes written to
688 * avoid sending duplicate data...
691 if (iostatus
== kIOUSBTransactionTimeout
)
693 fputs("DEBUG: Got USB transaction timeout during write\n", stderr
);
698 * If we've stalled, retry the write...
701 else if (iostatus
== kIOUSBPipeStalled
)
703 fputs("DEBUG: Got USB pipe stalled during write\n", stderr
);
705 bytes
= g
.print_bytes
;
706 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
710 * Retry a write after an aborted write since we probably just got
714 else if (iostatus
== kIOReturnAborted
)
716 fputs("DEBUG: Got USB return aborted during write\n", stderr
);
718 IOReturn err
= (*g
.classdriver
)->Abort(g
.classdriver
);
719 fprintf(stderr
, "DEBUG: USB class driver Abort returned %x\n", err
);
723 #endif /* DEBUG_WRITES */
725 bytes
= g
.print_bytes
;
726 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
732 * Write error - bail if we don't see an error we can retry...
735 _cupsLangPrintFilter(stderr
, "ERROR",
736 _("Unable to send data to printer."));
737 fprintf(stderr
, "DEBUG: USB class driver WritePipe returned %x\n",
740 IOReturn err
= (*g
.classdriver
)->Abort(g
.classdriver
);
741 fprintf(stderr
, "DEBUG: USB class driver Abort returned %x\n",
744 status
= CUPS_BACKEND_FAILED
;
749 fprintf(stderr
, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes
);
751 g
.print_bytes
-= bytes
;
753 total_bytes
+= bytes
;
757 if (print_fd
!= 0 && status
== noErr
)
758 fprintf(stderr
, "DEBUG: Sending print file, %lld bytes...\n",
763 fprintf(stderr
, "DEBUG: Sent %lld bytes...\n", (off_t
)total_bytes
);
764 fputs("STATE: +cups-waiting-for-job-completed\n", stderr
);
767 * Signal the side channel thread to exit...
770 if (have_sidechannel
)
773 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
774 g
.readwrite_lock
= 0;
775 pthread_cond_signal(&g
.readwrite_lock_cond
);
776 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
778 g
.sidechannel_thread_stop
= 1;
779 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
781 if (!g
.sidechannel_thread_done
)
783 gettimeofday(&tv
, NULL
);
784 cond_timeout
.tv_sec
= tv
.tv_sec
+ WAIT_SIDE_DELAY
;
785 cond_timeout
.tv_nsec
= tv
.tv_usec
* 1000;
787 while (!g
.sidechannel_thread_done
)
789 if (pthread_cond_timedwait(&g
.sidechannel_thread_cond
,
790 &g
.sidechannel_thread_mutex
,
796 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
800 * Signal the read thread to exit then wait 7 seconds for it to complete...
803 g
.read_thread_stop
= 1;
805 pthread_mutex_lock(&g
.read_thread_mutex
);
807 if (!g
.read_thread_done
)
809 fputs("DEBUG: Waiting for read thread to exit...\n", stderr
);
811 gettimeofday(&tv
, NULL
);
812 cond_timeout
.tv_sec
= tv
.tv_sec
+ WAIT_EOF_DELAY
;
813 cond_timeout
.tv_nsec
= tv
.tv_usec
* 1000;
815 while (!g
.read_thread_done
)
817 if (pthread_cond_timedwait(&g
.read_thread_cond
, &g
.read_thread_mutex
,
823 * If it didn't exit abort the pending read and wait an additional second...
826 if (!g
.read_thread_done
)
828 fputs("DEBUG: Read thread still active, aborting the pending read...\n",
833 (*g
.classdriver
)->Abort(g
.classdriver
);
835 gettimeofday(&tv
, NULL
);
836 cond_timeout
.tv_sec
= tv
.tv_sec
+ 1;
837 cond_timeout
.tv_nsec
= tv
.tv_usec
* 1000;
839 while (!g
.read_thread_done
)
841 if (pthread_cond_timedwait(&g
.read_thread_cond
, &g
.read_thread_mutex
,
848 pthread_mutex_unlock(&g
.read_thread_mutex
);
851 * Close the connection and input file and general clean up...
856 if (print_fd
!= STDIN_FILENO
)
865 if (g
.serial
!= NULL
)
868 if (g
.printer_obj
!= 0x0)
869 IOObjectRelease(g
.printer_obj
);
876 * 'read_thread()' - Thread to read the backchannel data on.
879 static void *read_thread(void *reference
)
881 UInt8 readbuffer
[512];
883 kern_return_t readstatus
;
884 struct mach_timebase_info timeBaseInfo
;
891 /* Calculate what 250 milliSeconds are in mach absolute time...
893 mach_timebase_info(&timeBaseInfo
);
894 delay
= ((uint64_t)250000000 * (uint64_t)timeBaseInfo
.denom
) / (uint64_t)timeBaseInfo
.numer
;
899 * Remember when we started so we can throttle the loop after the read call...
902 start
= mach_absolute_time();
904 rbytes
= sizeof(readbuffer
);
905 readstatus
= (*g
.classdriver
)->ReadPipe(g
.classdriver
, readbuffer
, &rbytes
);
906 if (readstatus
== kIOReturnSuccess
&& rbytes
> 0)
908 fprintf(stderr
, "DEBUG: Read %d bytes of back-channel data...\n",
910 cupsBackChannelWrite((char*)readbuffer
, rbytes
, 1.0);
912 /* cntrl-d is echoed by the printer.
914 * Xerox Phaser 6250D doesn't echo the cntrl-d.
915 * Xerox Phaser 6250D doesn't always send the product query.
917 if (g
.wait_eof
&& readbuffer
[rbytes
-1] == 0x4)
920 #ifdef PARSE_PS_ERRORS
921 parse_pserror(readbuffer
, rbytes
);
924 else if (readstatus
== kIOUSBTransactionTimeout
)
925 fputs("DEBUG: Got USB transaction timeout during read\n", stderr
);
926 else if (readstatus
== kIOUSBPipeStalled
)
927 fputs("DEBUG: Got USB pipe stalled during read\n", stderr
);
928 else if (readstatus
== kIOReturnAborted
)
929 fputs("DEBUG: Got USB return aborted during read\n", stderr
);
932 * Make sure this loop executes no more than once every 250 miliseconds...
935 if ((readstatus
!= kIOReturnSuccess
|| rbytes
== 0) && (g
.wait_eof
|| !g
.read_thread_stop
))
936 mach_wait_until(start
+ delay
);
938 } while (g
.wait_eof
|| !g
.read_thread_stop
); /* Abort from main thread tests error here */
941 * Let the main thread know that we have completed the read thread...
944 pthread_mutex_lock(&g
.read_thread_mutex
);
945 g
.read_thread_done
= 1;
946 pthread_cond_signal(&g
.read_thread_cond
);
947 pthread_mutex_unlock(&g
.read_thread_mutex
);
954 * 'sidechannel_thread()' - Handle side-channel requests.
958 sidechannel_thread(void *reference
)
960 cups_sc_command_t command
; /* Request command */
961 cups_sc_status_t status
; /* Request/response status */
962 char data
[2048]; /* Request/response data */
963 int datalen
; /* Request/response data size */
970 datalen
= sizeof(data
);
972 if (cupsSideChannelRead(&command
, &status
, data
, &datalen
, 1.0))
974 if (status
== CUPS_SC_STATUS_TIMEOUT
)
982 case CUPS_SC_CMD_SOFT_RESET
: /* Do a soft reset */
983 fputs("DEBUG: CUPS_SC_CMD_SOFT_RESET received from driver...\n",
986 if ((*g
.classdriver
)->SoftReset
!= NULL
)
989 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
990 fputs("DEBUG: Returning status CUPS_STATUS_OK with no bytes...\n",
995 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
997 fputs("DEBUG: Returning status CUPS_STATUS_NOT_IMPLEMENTED with "
998 "no bytes...\n", stderr
);
1002 case CUPS_SC_CMD_DRAIN_OUTPUT
: /* Drain all pending output */
1003 fputs("DEBUG: CUPS_SC_CMD_DRAIN_OUTPUT received from driver...\n",
1009 case CUPS_SC_CMD_GET_BIDI
: /* Is the connection bidirectional? */
1010 fputs("DEBUG: CUPS_SC_CMD_GET_BIDI received from driver...\n",
1013 data
[0] = g
.bidi_flag
;
1014 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
1017 "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
1021 case CUPS_SC_CMD_GET_DEVICE_ID
: /* Return IEEE-1284 device ID */
1022 fputs("DEBUG: CUPS_SC_CMD_GET_DEVICE_ID received from driver...\n",
1025 datalen
= sizeof(data
);
1026 get_device_id(&status
, data
, &datalen
);
1027 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, datalen
, 1.0);
1029 if (datalen
< sizeof(data
))
1030 data
[datalen
] = '\0';
1032 data
[sizeof(data
) - 1] = '\0';
1035 "DEBUG: Returning CUPS_SC_STATUS_OK with %d bytes (%s)...\n",
1039 case CUPS_SC_CMD_GET_STATE
: /* Return device state */
1040 fputs("DEBUG: CUPS_SC_CMD_GET_STATE received from driver...\n",
1043 data
[0] = CUPS_SC_STATE_ONLINE
;
1044 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
1047 "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
1052 fprintf(stderr
, "DEBUG: Unknown side-channel command (%d) received "
1053 "from driver...\n", command
);
1055 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
1058 fputs("DEBUG: Returned CUPS_SC_STATUS_NOT_IMPLEMENTED with no bytes...\n",
1063 while (!g
.sidechannel_thread_stop
);
1065 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
1066 g
.sidechannel_thread_done
= 1;
1067 pthread_cond_signal(&g
.sidechannel_thread_cond
);
1068 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
1076 * 'iterate_printers()' - Iterate over all the printers.
1079 static void iterate_printers(iterator_callback_t callBack
,
1084 mach_port_t masterPort
= 0x0;
1085 kern_return_t kr
= IOMasterPort (bootstrap_port
, &masterPort
);
1087 if (kr
== kIOReturnSuccess
&& masterPort
!= 0x0)
1089 io_iterator_t addIterator
= 0x0;
1091 iterator_reference_t reference
= { callBack
, userdata
, true };
1092 IONotificationPortRef addNotification
= IONotificationPortCreate(masterPort
);
1094 int klass
= kUSBPrintingClass
;
1095 int subklass
= kUSBPrintingSubclass
;
1097 CFNumberRef usb_klass
= CFNumberCreate(NULL
, kCFNumberIntType
, &klass
);
1098 CFNumberRef usb_subklass
= CFNumberCreate(NULL
, kCFNumberIntType
, &subklass
);
1099 CFMutableDictionaryRef usbPrinterMatchDictionary
= IOServiceMatching(kIOUSBInterfaceClassName
);
1101 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceClass"), usb_klass
);
1102 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceSubClass"), usb_subklass
);
1104 CFRelease(usb_klass
);
1105 CFRelease(usb_subklass
);
1107 IOServiceAddMatchingNotification(addNotification
, kIOMatchedNotification
, usbPrinterMatchDictionary
, &device_added
, &reference
, &addIterator
);
1108 if (addIterator
!= 0x0)
1110 device_added (&reference
, addIterator
);
1112 if (reference
.keepRunning
)
1114 CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification
), kCFRunLoopDefaultMode
);
1117 IOObjectRelease(addIterator
);
1119 mach_port_deallocate(mach_task_self(), masterPort
);
1127 * 'device_added()' - Device added notifier.
1130 static void device_added(void *userdata
,
1131 io_iterator_t iterator
)
1133 iterator_reference_t
*reference
= userdata
;
1136 while (reference
->keepRunning
&& (obj
= IOIteratorNext(iterator
)) != 0x0)
1138 if (reference
->callback
!= NULL
)
1139 reference
->keepRunning
= reference
->callback(reference
->userdata
, obj
);
1141 IOObjectRelease(obj
);
1144 /* One last call to the call back now that we are not longer have printers left to iterate...
1146 if (reference
->keepRunning
&& reference
->callback
)
1147 reference
->keepRunning
= reference
->callback(reference
->userdata
, 0x0);
1149 if (!reference
->keepRunning
)
1150 CFRunLoopStop(CFRunLoopGetCurrent());
1155 * 'list_device_cb()' - list_device iterator callback.
1158 static Boolean
list_device_cb(void *refcon
,
1161 Boolean keepRunning
= (obj
!= 0x0);
1168 CFStringRef deviceIDString
= NULL
;
1169 UInt32 deviceLocation
= 0;
1170 UInt8 interfaceNum
= 0;
1172 copy_devicestring(obj
, &deviceIDString
, &deviceLocation
, &interfaceNum
);
1173 if (deviceIDString
!= NULL
)
1175 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1176 char uristr
[1024], makestr
[1024], modelstr
[1024], serialstr
[1024];
1177 char optionsstr
[1024], idstr
[1024], make_modelstr
[1024];
1179 copy_deviceinfo(deviceIDString
, &make
, &model
, &serial
);
1180 CFStringGetCString(deviceIDString
, idstr
, sizeof(idstr
),
1181 kCFStringEncodingUTF8
);
1182 backendGetMakeModel(idstr
, make_modelstr
, sizeof(make_modelstr
));
1187 !CFStringGetCString(make
, makestr
, sizeof(makestr
),
1188 kCFStringEncodingUTF8
))
1189 strlcpy(makestr
, "Unknown", sizeof(makestr
));
1192 !CFStringGetCString(model
, &modelstr
[1], sizeof(modelstr
)-1,
1193 kCFStringEncodingUTF8
))
1194 strlcpy(modelstr
+ 1, "Printer", sizeof(modelstr
) - 1);
1196 optionsstr
[0] = '\0';
1199 CFStringGetCString(serial
, serialstr
, sizeof(serialstr
), kCFStringEncodingUTF8
);
1200 snprintf(optionsstr
, sizeof(optionsstr
), "?serial=%s", serialstr
);
1202 else if (deviceLocation
!= 0)
1203 snprintf(optionsstr
, sizeof(optionsstr
), "?location=%x", (unsigned)deviceLocation
);
1205 httpAssembleURI(HTTP_URI_CODING_ALL
, uristr
, sizeof(uristr
), "usb", NULL
, makestr
, 0, modelstr
);
1206 strlcat(uristr
, optionsstr
, sizeof(uristr
));
1208 cupsBackendReport("direct", uristr
, make_modelstr
, make_modelstr
, idstr
,
1211 release_deviceinfo(&make
, &model
, &serial
);
1212 CFRelease(deviceIDString
);
1221 * 'find_device_cb()' - print_device iterator callback.
1224 static Boolean
find_device_cb(void *refcon
,
1227 Boolean keepLooking
= true;
1231 CFStringRef idString
= NULL
;
1232 UInt32 location
= -1;
1233 UInt8 interfaceNum
= 0;
1235 copy_devicestring(obj
, &idString
, &location
, &interfaceNum
);
1236 if (idString
!= NULL
)
1238 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1240 copy_deviceinfo(idString
, &make
, &model
, &serial
);
1241 if (make
&& CFStringCompare(make
, g
.make
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1243 if (model
&& CFStringCompare(model
, g
.model
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1245 if (g
.serial
!= NULL
&& CFStringGetLength(g
.serial
) > 0)
1247 if (serial
!= NULL
&& CFStringCompare(serial
, g
.serial
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1249 IOObjectRetain(obj
);
1250 g
.printer_obj
= obj
;
1251 keepLooking
= false;
1256 if (g
.printer_obj
!= 0)
1257 IOObjectRelease(g
.printer_obj
);
1259 g
.printer_obj
= obj
;
1260 IOObjectRetain(obj
);
1262 if (g
.location
== 0 || g
.location
== location
)
1263 keepLooking
= false;
1266 g
.interfaceNum
= interfaceNum
;
1270 release_deviceinfo(&make
, &model
, &serial
);
1271 CFRelease(idString
);
1276 keepLooking
= (g
.printer_obj
== 0);
1277 if (obj
== 0x0 && keepLooking
)
1279 CFRunLoopTimerContext context
= { 0, refcon
, NULL
, NULL
, NULL
};
1280 CFRunLoopTimerRef timer
= CFRunLoopTimerCreate(NULL
, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb
, &context
);
1283 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer
, kCFRunLoopDefaultMode
);
1284 g
.status_timer
= timer
;
1289 if (!keepLooking
&& g
.status_timer
!= NULL
)
1291 fputs("STATE: -offline-report\n", stderr
);
1292 _cupsLangPrintFilter(stderr
, "INFO", _("The printer is now online."));
1293 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g
.status_timer
, kCFRunLoopDefaultMode
);
1294 CFRelease(g
.status_timer
);
1295 g
.status_timer
= NULL
;
1303 * 'status_timer_cb()' - Status timer callback.
1306 static void status_timer_cb(CFRunLoopTimerRef timer
,
1312 fputs("STATE: +offline-report\n", stderr
);
1313 _cupsLangPrintFilter(stderr
, "INFO", _("The printer is offline."));
1315 if (getenv("CLASS") != NULL
)
1318 * If the CLASS environment variable is set, the job was submitted
1319 * to a class and not to a specific queue. In this case, we want
1320 * to abort immediately so that the job can be requeued on the next
1321 * available printer in the class.
1323 * Sleep 5 seconds to keep the job from requeuing too rapidly...
1328 exit(CUPS_BACKEND_FAILED
);
1335 * 'copy_deviceinfo()' - Copy strings from the 1284 device ID.
1338 static void copy_deviceinfo(CFStringRef deviceIDString
,
1341 CFStringRef
*serial
)
1343 CFStringRef modelKeys
[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL
};
1344 CFStringRef makeKeys
[] = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL
};
1345 CFStringRef serialKeys
[] = { CFSTR("SN:"), CFSTR("SERN:"), NULL
};
1348 *make
= copy_value_for_key(deviceIDString
, makeKeys
);
1351 *model
= copy_value_for_key(deviceIDString
, modelKeys
);
1354 *serial
= copy_value_for_key(deviceIDString
, serialKeys
);
1359 * 'release_deviceinfo()' - Release deviceinfo strings.
1362 static void release_deviceinfo(CFStringRef
*make
,
1364 CFStringRef
*serial
)
1366 if (make
!= NULL
&& *make
!= NULL
)
1372 if (model
!= NULL
&& *model
!= NULL
)
1378 if (serial
!= NULL
&& *serial
!= NULL
)
1388 * 'load_classdriver()' - Load a classdriver.
1391 static kern_return_t
load_classdriver(CFStringRef driverPath
,
1392 printer_interface_t interface
,
1393 classdriver_t
***printerDriver
)
1395 kern_return_t kr
= kUSBPrinterClassDeviceNotOpen
;
1396 classdriver_t
**driver
= NULL
;
1397 CFStringRef bundle
= driverPath
? driverPath
: kUSBGenericTOPrinterClassDriver
;
1398 char bundlestr
[1024]; /* Bundle path */
1399 CFURLRef url
; /* URL for driver */
1400 CFPlugInRef plugin
= NULL
; /* Plug-in address */
1403 CFStringGetCString(bundle
, bundlestr
, sizeof(bundlestr
), kCFStringEncodingUTF8
);
1406 * Validate permissions for the class driver...
1409 _cups_fc_result_t result
= _cupsFileCheck(bundlestr
,
1410 _CUPS_FILE_CHECK_DIRECTORY
, 1,
1411 Iterating
? NULL
: _cupsFileCheckFilter
, NULL
);
1413 if (result
&& driverPath
)
1414 return (load_classdriver(NULL
, interface
, printerDriver
));
1419 * Try loading the class driver...
1422 url
= CFURLCreateWithFileSystemPath(NULL
, bundle
, kCFURLPOSIXPathStyle
, true);
1426 plugin
= CFPlugInCreate(NULL
, url
);
1434 CFArrayRef factories
= CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID
, plugin
);
1435 if (factories
!= NULL
&& CFArrayGetCount(factories
) > 0)
1437 CFUUIDRef factoryID
= CFArrayGetValueAtIndex(factories
, 0);
1438 IUnknownVTbl
**iunknown
= CFPlugInInstanceCreate(NULL
, factoryID
, kUSBPrinterClassTypeID
);
1439 if (iunknown
!= NULL
)
1441 kr
= (*iunknown
)->QueryInterface(iunknown
, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID
), (LPVOID
*)&driver
);
1442 if (kr
== kIOReturnSuccess
&& driver
!= NULL
)
1444 classdriver_t
**genericDriver
= NULL
;
1445 if (driverPath
!= NULL
&& CFStringCompare(driverPath
, kUSBGenericTOPrinterClassDriver
, 0) != kCFCompareEqualTo
)
1446 kr
= load_classdriver(NULL
, interface
, &genericDriver
);
1448 if (kr
== kIOReturnSuccess
)
1450 (*driver
)->interface
= interface
;
1451 (*driver
)->Initialize(driver
, genericDriver
);
1453 (*driver
)->plugin
= plugin
;
1454 (*driver
)->interface
= interface
;
1455 *printerDriver
= driver
;
1458 (*iunknown
)->Release(iunknown
);
1460 CFRelease(factories
);
1464 fprintf(stderr
, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr
, (int)kr
);
1471 * 'unload_classdriver()' - Unload a classdriver.
1474 static kern_return_t
unload_classdriver(classdriver_t
***classdriver
)
1476 if (*classdriver
!= NULL
)
1478 (**classdriver
)->Release(*classdriver
);
1479 *classdriver
= NULL
;
1482 return kIOReturnSuccess
;
1487 * 'load_printerdriver()' - Load vendor's classdriver.
1489 * If driverBundlePath is not NULL on return it is the callers responsbility to release it!
1492 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
)
1494 IOCFPlugInInterface
**iodev
= NULL
;
1497 printer_interface_t interface
;
1500 kr
= IOCreatePlugInInterfaceForService(g
.printer_obj
, kIOUSBInterfaceUserClientTypeID
, kIOCFPlugInInterfaceID
, &iodev
, &score
);
1501 if (kr
== kIOReturnSuccess
)
1503 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*) &interface
)) == noErr
)
1505 *driverBundlePath
= IORegistryEntryCreateCFProperty(g
.printer_obj
, kUSBClassDriverProperty
, NULL
, kNilOptions
);
1507 kr
= load_classdriver(*driverBundlePath
, interface
, &g
.classdriver
);
1509 if (kr
!= kIOReturnSuccess
)
1510 (*interface
)->Release(interface
);
1512 IODestroyPlugInInterface(iodev
);
1519 * 'registry_open()' - Open a connection to the printer.
1522 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
)
1524 g
.bidi_flag
= 0; /* 0=unidirectional */
1526 kern_return_t kr
= load_printerdriver(driverBundlePath
);
1527 if (kr
!= kIOReturnSuccess
)
1530 if (g
.classdriver
!= NULL
)
1532 (*g
.classdriver
)->interfaceNumber
= g
.interfaceNum
;
1533 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolBidirectional
);
1534 if (kr
!= kIOReturnSuccess
|| (*g
.classdriver
)->interface
== NULL
)
1536 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolUnidirectional
);
1537 if (kr
== kIOReturnSuccess
)
1539 if ((*g
.classdriver
)->interface
== NULL
)
1541 (*g
.classdriver
)->Close(g
.classdriver
);
1547 g
.bidi_flag
= 1; /* 1=bidirectional */
1550 if (kr
!= kIOReturnSuccess
)
1551 unload_classdriver(&g
.classdriver
);
1558 * 'registry_close()' - Close the connection to the printer.
1561 static kern_return_t
registry_close(void)
1563 if (g
.classdriver
!= NULL
)
1564 (*g
.classdriver
)->Close(g
.classdriver
);
1566 unload_classdriver(&g
.classdriver
);
1567 return kIOReturnSuccess
;
1572 * 'copy_deviceid()' - Copy the 1284 device id string.
1575 static OSStatus
copy_deviceid(classdriver_t
**classdriver
,
1576 CFStringRef
*deviceID
)
1578 CFStringRef devID
= NULL
;
1579 CFStringRef deviceMake
= NULL
;
1580 CFStringRef deviceModel
= NULL
;
1581 CFStringRef deviceSerial
= NULL
;
1585 OSStatus err
= (*classdriver
)->GetDeviceID(classdriver
, &devID
, DEFAULT_TIMEOUT
);
1587 copy_deviceinfo(devID
, &deviceMake
, &deviceModel
, &deviceSerial
);
1589 if (deviceMake
== NULL
|| deviceModel
== NULL
|| deviceSerial
== NULL
)
1591 IOUSBDeviceDescriptor desc
;
1592 iodevice_request_t request
;
1594 request
.requestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
1595 request
.request
= kUSBRqGetDescriptor
;
1596 request
.value
= (kUSBDeviceDesc
<< 8) | 0;
1598 request
.length
= sizeof(desc
);
1599 request
.buffer
= &desc
;
1600 err
= (*classdriver
)->DeviceRequest(classdriver
, &request
, DEFAULT_TIMEOUT
);
1601 if (err
== kIOReturnSuccess
)
1603 CFMutableStringRef newDevID
= CFStringCreateMutable(NULL
, 0);
1605 if (deviceMake
== NULL
)
1607 CFStringRef data
= NULL
;
1608 err
= (*classdriver
)->GetString(classdriver
, desc
.iManufacturer
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1611 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MFG:%@;"), data
);
1616 if (deviceModel
== NULL
)
1618 CFStringRef data
= NULL
;
1619 err
= (*classdriver
)->GetString(classdriver
, desc
.iProduct
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1622 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MDL:%@;"), data
);
1627 if (deviceSerial
== NULL
&& desc
.iSerialNumber
!= 0)
1629 err
= (*classdriver
)->GetString(classdriver
, desc
.iSerialNumber
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &deviceSerial
);
1630 if (deviceSerial
!= NULL
)
1632 CFStringAppendFormat(newDevID
, NULL
, CFSTR("SERN:%@;"), deviceSerial
);
1638 CFStringAppend(newDevID
, devID
);
1642 *deviceID
= newDevID
;
1650 if (*deviceID
== NULL
)
1653 /* Remove special characters from the serial number */
1654 CFRange range
= (deviceSerial
!= NULL
? CFStringFind(deviceSerial
, CFSTR("+"), 0) : CFRangeMake(0, 0));
1655 if (range
.length
== 1) {
1656 range
= CFStringFind(*deviceID
, deviceSerial
, 0);
1658 CFMutableStringRef deviceIDString
= CFStringCreateMutableCopy(NULL
, 0, *deviceID
);
1659 CFStringFindAndReplace(deviceIDString
, CFSTR("+"), CFSTR(""), range
, 0);
1660 CFRelease(*deviceID
);
1661 *deviceID
= deviceIDString
;
1664 release_deviceinfo(&deviceMake
, &deviceModel
, &deviceSerial
);
1671 * 'copy_devicestring()' - Copy the 1284 device id string.
1674 static void copy_devicestring(io_service_t usbInterface
,
1675 CFStringRef
*deviceID
,
1676 UInt32
*deviceLocation
,
1677 UInt8
*interfaceNumber
)
1679 IOCFPlugInInterface
**iodev
= NULL
;
1682 printer_interface_t interface
;
1684 classdriver_t
**klassDriver
= NULL
;
1685 CFStringRef driverBundlePath
;
1687 if ((kr
= IOCreatePlugInInterfaceForService(usbInterface
,
1688 kIOUSBInterfaceUserClientTypeID
,
1689 kIOCFPlugInInterfaceID
,
1690 &iodev
, &score
)) == kIOReturnSuccess
)
1692 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*)
1693 &interface
)) == noErr
)
1695 (*interface
)->GetLocationID(interface
, deviceLocation
);
1696 (*interface
)->GetInterfaceNumber(interface
, interfaceNumber
);
1698 driverBundlePath
= IORegistryEntryCreateCFProperty(usbInterface
,
1699 kUSBClassDriverProperty
,
1702 kr
= load_classdriver(driverBundlePath
, interface
, &klassDriver
);
1704 if (kr
!= kIOReturnSuccess
&& driverBundlePath
!= NULL
)
1705 kr
= load_classdriver(NULL
, interface
, &klassDriver
);
1707 if (kr
== kIOReturnSuccess
&& klassDriver
!= NULL
)
1708 copy_deviceid(klassDriver
, deviceID
);
1710 unload_classdriver(&klassDriver
);
1712 if (driverBundlePath
!= NULL
)
1713 CFRelease(driverBundlePath
);
1715 /* (*interface)->Release(interface); */
1717 IODestroyPlugInInterface(iodev
);
1724 * 'copy_value_for_key()' - Copy value string associated with a key.
1727 static CFStringRef
copy_value_for_key(CFStringRef deviceID
,
1730 CFStringRef value
= NULL
;
1731 CFArrayRef kvPairs
= deviceID
!= NULL
? CFStringCreateArrayBySeparatingStrings(NULL
, deviceID
, CFSTR(";")) : NULL
;
1732 CFIndex max
= kvPairs
!= NULL
? CFArrayGetCount(kvPairs
) : 0;
1735 while (idx
< max
&& value
== NULL
)
1737 CFStringRef kvpair
= CFArrayGetValueAtIndex(kvPairs
, idx
);
1739 while (keys
[idxx
] != NULL
&& value
== NULL
)
1741 CFRange range
= CFStringFind(kvpair
, keys
[idxx
], kCFCompareCaseInsensitive
);
1742 if (range
.length
!= -1)
1744 if (range
.location
!= 0)
1746 CFMutableStringRef theString
= CFStringCreateMutableCopy(NULL
, 0, kvpair
);
1747 CFStringTrimWhitespace(theString
);
1748 range
= CFStringFind(theString
, keys
[idxx
], kCFCompareCaseInsensitive
);
1749 if (range
.location
== 0)
1750 value
= CFStringCreateWithSubstring(NULL
, theString
, CFRangeMake(range
.length
, CFStringGetLength(theString
) - range
.length
));
1752 CFRelease(theString
);
1756 CFStringRef theString
= CFStringCreateWithSubstring(NULL
, kvpair
, CFRangeMake(range
.length
, CFStringGetLength(kvpair
) - range
.length
));
1757 CFMutableStringRef theString2
= CFStringCreateMutableCopy(NULL
, 0, theString
);
1758 CFRelease(theString
);
1760 CFStringTrimWhitespace(theString2
);
1769 if (kvPairs
!= NULL
)
1776 * 'cfstr_create_trim()' - Create CFString and trim whitespace characters.
1779 CFStringRef
cfstr_create_trim(const char *cstr
)
1782 CFMutableStringRef cfmutablestr
= NULL
;
1784 if ((cfstr
= CFStringCreateWithCString(NULL
, cstr
, kCFStringEncodingUTF8
)) != NULL
)
1786 if ((cfmutablestr
= CFStringCreateMutableCopy(NULL
, 1024, cfstr
)) != NULL
)
1787 CFStringTrimWhitespace(cfmutablestr
);
1791 return (CFStringRef
) cfmutablestr
;
1797 * 'parse_options()' - Parse URI options.
1800 static void parse_options(char *options
,
1806 char sep
, /* Separator character */
1807 *name
, /* Name of option */
1808 *value
; /* Value of option */
1827 while (*options
&& *options
!= '=' && *options
!= '+' && *options
!= '&')
1830 if ((sep
= *options
) != '\0')
1841 while (*options
&& *options
!= '+' && *options
!= '&')
1851 * Process the option...
1854 if (!_cups_strcasecmp(name
, "waiteof"))
1856 if (!_cups_strcasecmp(value
, "on") ||
1857 !_cups_strcasecmp(value
, "yes") ||
1858 !_cups_strcasecmp(value
, "true"))
1860 else if (!_cups_strcasecmp(value
, "off") ||
1861 !_cups_strcasecmp(value
, "no") ||
1862 !_cups_strcasecmp(value
, "false"))
1865 _cupsLangPrintFilter(stderr
, "WARNING",
1866 _("Boolean expected for waiteof option \"%s\"."),
1869 else if (!_cups_strcasecmp(name
, "serial"))
1870 strlcpy(serial
, value
, serial_size
);
1871 else if (!_cups_strcasecmp(name
, "location") && location
)
1872 *location
= strtol(value
, NULL
, 16);
1878 * @function setup_cfLanguage
1879 * @abstract Convert the contents of the CUPS 'APPLE_LANGUAGE' environment
1880 * variable into a one element CF array of languages.
1882 * @discussion Each submitted job comes with a natural language. CUPS passes
1883 * that language in an environment variable. We take that language
1884 * and jam it into the AppleLanguages array so that CF will use
1885 * it when reading localized resources. We need to do this before
1886 * any CF code reads and caches the languages array, so this function
1887 * should be called early in main()
1889 static void setup_cfLanguage(void)
1891 CFStringRef lang
[1] = {NULL
};
1892 CFArrayRef langArray
= NULL
;
1893 const char *requestedLang
= NULL
;
1895 if ((requestedLang
= getenv("APPLE_LANGUAGE")) == NULL
)
1896 requestedLang
= getenv("LANG");
1898 if (requestedLang
!= NULL
)
1900 lang
[0] = CFStringCreateWithCString(kCFAllocatorDefault
, requestedLang
, kCFStringEncodingUTF8
);
1901 langArray
= CFArrayCreate(kCFAllocatorDefault
, (const void **)lang
, sizeof(lang
) / sizeof(lang
[0]), &kCFTypeArrayCallBacks
);
1903 CFPreferencesSetValue(CFSTR("AppleLanguages"), langArray
, kCFPreferencesCurrentApplication
, kCFPreferencesAnyUser
, kCFPreferencesAnyHost
);
1904 fprintf(stderr
, "DEBUG: usb: AppleLanguages=\"%s\"\n", requestedLang
);
1907 CFRelease(langArray
);
1910 fputs("DEBUG: usb: LANG and APPLE_LANGUAGE environment variables missing.\n", stderr
);
1914 #if defined(__i386__) || defined(__x86_64__)
1916 * @function run_legacy_backend
1918 * @abstract Starts child backend process running as a ppc or i386 executable.
1920 * @result Never returns; always calls exit().
1924 static void run_legacy_backend(int argc
,
1931 pid_t waitpid_status
;
1933 char *usb_legacy_status
;
1936 * If we're running as x86_64 or i386 and couldn't load the class driver
1937 * (because it's ppc or i386), then try to re-exec ourselves in ppc or i386
1938 * mode to try again. If we don't have a ppc or i386 architecture we may be
1939 * running with the same architecture again so guard against this by setting
1940 * and testing an environment variable...
1944 usb_legacy_status
= getenv("USB_I386_STATUS");
1946 usb_legacy_status
= getenv("USB_PPC_STATUS");
1947 # endif /* __x86_64__ */
1949 if (!usb_legacy_status
)
1952 * Setup a SIGTERM handler then block it before forking...
1955 int err
; /* posix_spawn result */
1956 struct sigaction action
; /* POSIX signal action */
1957 sigset_t newmask
, /* New signal mask */
1958 oldmask
; /* Old signal mask */
1959 char usbpath
[1024]; /* Path to USB backend */
1960 const char *cups_serverbin
;/* Path to CUPS binaries */
1963 memset(&action
, 0, sizeof(action
));
1964 sigaddset(&action
.sa_mask
, SIGTERM
);
1965 action
.sa_handler
= sigterm_handler
;
1966 sigaction(SIGTERM
, &action
, NULL
);
1968 sigemptyset(&newmask
);
1969 sigaddset(&newmask
, SIGTERM
);
1970 sigprocmask(SIG_BLOCK
, &newmask
, &oldmask
);
1973 * Set the environment variable...
1977 setenv("USB_I386_STATUS", "1", false);
1979 setenv("USB_PPC_STATUS", "1", false);
1980 # endif /* __x86_64__ */
1983 * Tell the kernel to use the specified CPU architecture...
1987 cpu_type_t cpu
= CPU_TYPE_I386
;
1989 cpu_type_t cpu
= CPU_TYPE_POWERPC
;
1990 # endif /* __x86_64__ */
1992 posix_spawnattr_t attrs
;
1994 if (!posix_spawnattr_init(&attrs
))
1996 posix_spawnattr_setsigdefault(&attrs
, &oldmask
);
1997 if (posix_spawnattr_setbinpref_np(&attrs
, 1, &cpu
, &ocount
) || ocount
!= 1)
2000 perror("DEBUG: Unable to set binary preference to i386");
2002 perror("DEBUG: Unable to set binary preference to ppc");
2003 # endif /* __x86_64__ */
2004 _cupsLangPrintFilter(stderr
, "ERROR",
2005 _("Unable to use legacy USB class driver."));
2006 exit(CUPS_BACKEND_STOP
);
2011 * Set up the arguments and call posix_spawn...
2014 if ((cups_serverbin
= getenv("CUPS_SERVERBIN")) == NULL
)
2015 cups_serverbin
= CUPS_SERVERBIN
;
2016 snprintf(usbpath
, sizeof(usbpath
), "%s/backend/usb", cups_serverbin
);
2018 for (i
= 0; i
< argc
&& i
< (sizeof(my_argv
) / sizeof(my_argv
[0])) - 1; i
++)
2019 my_argv
[i
] = argv
[i
];
2023 if ((err
= posix_spawn(&child_pid
, usbpath
, NULL
, &attrs
, my_argv
,
2026 fprintf(stderr
, "DEBUG: Unable to exec %s: %s\n", usbpath
,
2028 _cupsLangPrintFilter(stderr
, "ERROR",
2029 _("Unable to use legacy USB class driver."));
2030 exit(CUPS_BACKEND_STOP
);
2034 * Unblock signals...
2037 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
2040 * Close the fds we won't be using then wait for the child backend to exit.
2046 fprintf(stderr
, "DEBUG: Started usb(legacy) backend (PID %d)\n",
2049 while ((waitpid_status
= waitpid(child_pid
, &childstatus
, 0)) == (pid_t
)-1 && errno
== EINTR
)
2052 if (WIFSIGNALED(childstatus
))
2054 exitstatus
= CUPS_BACKEND_STOP
;
2055 fprintf(stderr
, "DEBUG: usb(legacy) backend %d crashed on signal %d\n",
2056 child_pid
, WTERMSIG(childstatus
));
2060 if ((exitstatus
= WEXITSTATUS(childstatus
)) != 0)
2062 "DEBUG: usb(legacy) backend %d stopped with status %d\n",
2063 child_pid
, exitstatus
);
2065 fprintf(stderr
, "DEBUG: usb(legacy) backend %d exited with no errors\n",
2071 fputs("DEBUG: usb(legacy) backend running native again\n", stderr
);
2072 exitstatus
= CUPS_BACKEND_STOP
;
2077 #endif /* __i386__ || __x86_64__ */
2081 * 'sigterm_handler()' - SIGTERM handler.
2085 sigterm_handler(int sig
) /* I - Signal */
2087 #if defined(__i386__) || defined(__x86_64__)
2089 * If we started a child process pass the signal on to it...
2095 * If we started a child process pass the signal on to it...
2100 kill(child_pid
, sig
);
2101 while (waitpid(child_pid
, &status
, 0) < 0 && errno
== EINTR
);
2103 if (WIFEXITED(status
))
2104 exit(WEXITSTATUS(status
));
2105 else if (status
== SIGTERM
|| status
== SIGKILL
)
2109 fprintf(stderr
, "DEBUG: Child crashed on signal %d\n", status
);
2110 exit(CUPS_BACKEND_STOP
);
2113 #endif /* __i386__ || __x86_64__ */
2118 * 'sigquit_handler()' - SIGQUIT handler.
2121 static void sigquit_handler(int sig
, siginfo_t
*si
, void *unused
)
2124 char pathbuf
[PROC_PIDPATHINFO_MAXSIZE
];
2125 static char msgbuf
[256] = "";
2131 if (proc_pidpath(si
->si_pid
, pathbuf
, sizeof(pathbuf
)) > 0 &&
2132 (path
= basename(pathbuf
)) != NULL
)
2133 snprintf(msgbuf
, sizeof(msgbuf
), "SIGQUIT sent by %s(%d)", path
, (int)si
->si_pid
);
2135 snprintf(msgbuf
, sizeof(msgbuf
), "SIGQUIT sent by PID %d", (int)si
->si_pid
);
2137 CRSetCrashLogMessage(msgbuf
);
2143 #ifdef PARSE_PS_ERRORS
2145 * 'next_line()' - Find the next line in a buffer.
2148 static const char *next_line (const char *buffer
)
2150 const char *cptr
, *lptr
= NULL
;
2152 for (cptr
= buffer
; *cptr
&& lptr
== NULL
; cptr
++)
2153 if (*cptr
== '\n' || *cptr
== '\r')
2160 * 'parse_pserror()' - Scan the backchannel data for postscript errors.
2163 static void parse_pserror(char *sockBuffer
,
2166 static char gErrorBuffer
[1024] = "";
2167 static char *gErrorBufferPtr
= gErrorBuffer
;
2168 static char *gErrorBufferEndPtr
= gErrorBuffer
+ sizeof(gErrorBuffer
);
2170 char *pCommentBegin
, *pCommentEnd
, *pLineEnd
;
2175 if (gErrorBufferPtr
+ len
> gErrorBufferEndPtr
- 1)
2176 gErrorBufferPtr
= gErrorBuffer
;
2177 if (len
> sizeof(gErrorBuffer
) - 1)
2178 len
= sizeof(gErrorBuffer
) - 1;
2180 memcpy(gErrorBufferPtr
, (const void *)sockBuffer
, len
);
2181 gErrorBufferPtr
+= len
;
2182 *(gErrorBufferPtr
+ 1) = '\0';
2184 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
2185 while (pLineEnd
!= NULL
)
2189 pCommentBegin
= strstr(gErrorBuffer
,"%%[");
2190 pCommentEnd
= strstr(gErrorBuffer
, "]%%");
2191 if (pCommentBegin
!= gErrorBuffer
&& pCommentEnd
!= NULL
)
2193 pCommentEnd
+= 3; /* Skip past "]%%" */
2194 *pCommentEnd
= '\0'; /* There's always room for the nul */
2196 if (_cups_strncasecmp(pCommentBegin
, "%%[ Error:", 10) == 0)
2198 else if (_cups_strncasecmp(pCommentBegin
, "%%[ Flushing", 12) == 0)
2203 if ((logstrlen
= snprintf(logstr
, sizeof(logstr
), "%s: %s\n", logLevel
, pCommentBegin
)) >= sizeof(logstr
))
2205 /* If the string was trucnated make sure it has a linefeed before the nul */
2206 logstrlen
= sizeof(logstr
) - 1;
2207 logstr
[logstrlen
- 1] = '\n';
2209 write(STDERR_FILENO
, logstr
, logstrlen
);
2212 /* move everything over... */
2213 strlcpy(gErrorBuffer
, pLineEnd
, sizeof(gErrorBuffer
));
2214 gErrorBufferPtr
= gErrorBuffer
;
2215 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
2218 #endif /* PARSE_PS_ERRORS */
2222 * 'soft_reset()' - Send a soft reset to the device.
2225 static void soft_reset(void)
2227 fd_set input_set
; /* Input set for select() */
2228 struct timeval tv
; /* Time value */
2229 char buffer
[2048]; /* Buffer */
2230 struct timespec cond_timeout
; /* pthread condition timeout */
2233 * Send an abort once a second until the I/O lock is released by the main thread...
2236 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2237 while (g
.readwrite_lock
)
2239 (*g
.classdriver
)->Abort(g
.classdriver
);
2241 gettimeofday(&tv
, NULL
);
2242 cond_timeout
.tv_sec
= tv
.tv_sec
+ 1;
2243 cond_timeout
.tv_nsec
= tv
.tv_usec
* 1000;
2245 while (g
.readwrite_lock
)
2247 if (pthread_cond_timedwait(&g
.readwrite_lock_cond
,
2248 &g
.readwrite_lock_mutex
,
2249 &cond_timeout
) != 0)
2254 g
.readwrite_lock
= 1;
2255 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2258 * Flush bytes waiting on print_fd...
2263 FD_ZERO(&input_set
);
2264 FD_SET(g
.print_fd
, &input_set
);
2269 while (select(g
.print_fd
+1, &input_set
, NULL
, NULL
, &tv
) > 0)
2270 if (read(g
.print_fd
, buffer
, sizeof(buffer
)) <= 0)
2277 (*g
.classdriver
)->SoftReset(g
.classdriver
, DEFAULT_TIMEOUT
);
2280 * Release the I/O lock...
2283 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2284 g
.readwrite_lock
= 0;
2285 pthread_cond_signal(&g
.readwrite_lock_cond
);
2286 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2291 * 'get_device_id()' - Return IEEE-1284 device ID.
2294 static void get_device_id(cups_sc_status_t
*status
,
2298 CFStringRef deviceIDString
= NULL
;
2301 copy_deviceid(g
.classdriver
, &deviceIDString
);
2305 CFStringGetCString(deviceIDString
, data
, *datalen
, kCFStringEncodingUTF8
);
2306 *datalen
= strlen(data
);
2307 CFRelease(deviceIDString
);
2309 *status
= CUPS_SC_STATUS_OK
;