4 * Copyright 2005-2015 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 <cups/ppd-private.h>
67 #include "backend-private.h"
68 #include <CoreFoundation/CoreFoundation.h>
69 #include <IOKit/usb/IOUSBLib.h>
70 #include <IOKit/IOCFPlugIn.h>
77 * Include necessary headers.
80 extern char **environ
;
84 * DEBUG_WRITES, if defined, causes the backend to write data to the printer in
85 * 512 byte increments, up to 8192 bytes, to make debugging with a USB bus
89 #define DEBUG_WRITES 0
92 * WAIT_EOF_DELAY is number of seconds we'll wait for responses from
93 * the printer after we've finished sending all the data
95 #define WAIT_EOF_DELAY 7
96 #define WAIT_SIDE_DELAY 3
97 #define DEFAULT_TIMEOUT 5000L
99 #define USB_INTERFACE_KIND CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID245)
100 #define kUSBLanguageEnglish 0x409
102 #define PRINTER_POLLING_INTERVAL 5 /* seconds */
103 #define INITIAL_LOG_INTERVAL PRINTER_POLLING_INTERVAL
104 #define SUBSEQUENT_LOG_INTERVAL 3 * INITIAL_LOG_INTERVAL
106 #define kUSBPrinterClassTypeID CFUUIDGetConstantUUIDWithBytes(NULL, 0x06, 0x04, 0x7D, 0x16, 0x53, 0xA2, 0x11, 0xD6, 0x92, 0x06, 0x00, 0x30, 0x65, 0x52, 0x45, 0x92)
107 #define kUSBPrinterClassInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, 0x03, 0x34, 0x6D, 0x74, 0x53, 0xA3, 0x11, 0xD6, 0x9E, 0xA1, 0x76, 0x30, 0x65, 0x52, 0x45, 0x92)
109 #define kUSBClassDriverProperty CFSTR("USB Printing Class")
111 #define kUSBGenericTOPrinterClassDriver CFSTR("/System/Library/Printers/Libraries/USBGenericPrintingClass.plugin")
112 #define kUSBPrinterClassDeviceNotOpen -9664 /*kPMInvalidIOMContext*/
114 #define CRSetCrashLogMessage(m) _crc_make_setter(message, m)
115 #define _crc_make_setter(attr, arg) (gCRAnnotations.attr = (uint64_t)(unsigned long)(arg))
116 #define CRASH_REPORTER_CLIENT_HIDDEN __attribute__((visibility("hidden")))
117 #define CRASHREPORTER_ANNOTATIONS_VERSION 4
118 #define CRASHREPORTER_ANNOTATIONS_SECTION "__crash_info"
120 struct crashreporter_annotations_t
{
121 uint64_t version
; // unsigned long
122 uint64_t message
; // char *
123 uint64_t signature_string
; // char *
124 uint64_t backtrace
; // char *
125 uint64_t message2
; // char *
126 uint64_t thread
; // uint64_t
127 uint64_t dialog_mode
; // unsigned int
130 CRASH_REPORTER_CLIENT_HIDDEN
131 struct crashreporter_annotations_t gCRAnnotations
132 __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION
)))
133 = { CRASHREPORTER_ANNOTATIONS_VERSION
, 0, 0, 0, 0, 0, 0 };
136 * Section 5.3 USB Printing Class spec
138 #define kUSBPrintingSubclass 1
139 #define kUSBPrintingProtocolNoOpen 0
140 #define kUSBPrintingProtocolUnidirectional 1
141 #define kUSBPrintingProtocolBidirectional 2
142 #define kUSBPrintingProtocolIPP 4
144 typedef IOUSBInterfaceInterface245
**printer_interface_t
;
146 typedef struct iodevice_request_s
/**** Device request ****/
154 } iodevice_request_t
;
156 typedef union /**** Centronics status byte ****/
161 unsigned reserved0
:2;
162 unsigned paperError
:1;
165 unsigned reserved1
:3;
167 } centronics_status_t
;
169 typedef struct classdriver_s
/**** g.classdriver context ****/
172 CFPlugInRef plugin
; /* release plugin */
173 IUnknownVTbl
**factory
; /* Factory */
174 void *vendorReference
; /* vendor class specific usage */
175 UInt32 location
; /* unique location in bus topology */
176 UInt8 interfaceNumber
; /* Interface number */
177 UInt16 vendorID
; /* Vendor id */
178 UInt16 productID
; /* Product id */
179 printer_interface_t interface
; /* identify the device to IOKit */
180 UInt8 outpipe
; /* mandatory bulkOut pipe */
181 UInt8 inpipe
; /* optional bulkIn pipe */
183 /* general class requests */
184 kern_return_t (*DeviceRequest
)(struct classdriver_s
**printer
, iodevice_request_t
*iorequest
, UInt16 timeout
);
185 kern_return_t (*GetString
)(struct classdriver_s
**printer
, UInt8 whichString
, UInt16 language
, UInt16 timeout
, CFStringRef
*result
);
187 /* standard printer class requests */
188 kern_return_t (*SoftReset
)(struct classdriver_s
**printer
, UInt16 timeout
);
189 kern_return_t (*GetCentronicsStatus
)(struct classdriver_s
**printer
, centronics_status_t
*result
, UInt16 timeout
);
190 kern_return_t (*GetDeviceID
)(struct classdriver_s
**printer
, CFStringRef
*devid
, UInt16 timeout
);
192 /* standard bulk device requests */
193 kern_return_t (*ReadPipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
);
194 kern_return_t (*WritePipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
, Boolean eoj
);
196 /* interface requests */
197 kern_return_t (*Open
)(struct classdriver_s
**printer
, UInt32 location
, UInt8 protocol
);
198 kern_return_t (*Abort
)(struct classdriver_s
**printer
);
199 kern_return_t (*Close
)(struct classdriver_s
**printer
);
201 /* initialize and terminate */
202 kern_return_t (*Initialize
)(struct classdriver_s
**printer
, struct classdriver_s
**baseclass
);
203 kern_return_t (*Terminate
)(struct classdriver_s
**printer
);
207 typedef Boolean (*iterator_callback_t
)(void *refcon
, io_service_t obj
, CFStringRef deviceIDString
, UInt32 deviceLocation
, UInt8 interfaceNum
, UInt8 alternateSetting
);
209 typedef struct iterator_reference_s
/**** Iterator reference data */
211 iterator_callback_t callback
;
214 } iterator_reference_t
;
216 typedef struct globals_s
218 io_service_t printer_obj
;
219 classdriver_t
**classdriver
;
221 pthread_mutex_t read_thread_mutex
;
222 pthread_cond_t read_thread_cond
;
223 int read_thread_stop
;
224 int read_thread_done
;
226 pthread_mutex_t readwrite_lock_mutex
;
227 pthread_cond_t readwrite_lock_cond
;
235 UInt8 alternateSetting
;
237 CFRunLoopTimerRef status_timer
;
239 int print_fd
; /* File descriptor to print */
240 ssize_t print_bytes
; /* Print bytes read */
242 ssize_t debug_bytes
; /* Current bytes to read */
243 #endif /* DEBUG_WRITES */
245 Boolean use_generic_class_driver
;
247 int drain_output
; /* Drain all pending output */
248 int bidi_flag
; /* 0=unidirectional, 1=bidirectional */
250 pthread_mutex_t sidechannel_thread_mutex
;
251 pthread_cond_t sidechannel_thread_cond
;
252 int sidechannel_thread_stop
;
253 int sidechannel_thread_done
;
261 globals_t g
= { 0 }; /* Globals */
262 int Iterating
= 0; /* Are we iterating the bus? */
269 static Boolean
find_device_cb(void *refcon
, io_service_t obj
, CFStringRef deviceIDString
, UInt32 deviceLocation
, UInt8 interfaceNum
, UInt8 alternateSetting
);
270 static Boolean
list_device_cb(void *refcon
, io_service_t obj
, CFStringRef deviceIDString
, UInt32 deviceLocation
, UInt8 interfaceNum
, UInt8 alternateSetting
);
272 static CFStringRef
cfstr_create_trim(const char *cstr
);
273 static CFStringRef
copy_value_for_key(CFStringRef deviceID
, CFStringRef
*keys
);
274 static kern_return_t
load_classdriver(CFStringRef driverPath
, printer_interface_t interface
, classdriver_t
***printerDriver
);
275 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
);
276 static kern_return_t
registry_close(void);
277 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
);
278 static kern_return_t
unload_classdriver(classdriver_t
***classdriver
);
280 static void *read_thread(void *reference
);
281 static void *sidechannel_thread(void *reference
);
282 static void device_added(void *userdata
, io_iterator_t iterator
);
283 static void get_device_id(cups_sc_status_t
*status
, char *data
, int *datalen
);
284 static void iterate_printers(iterator_callback_t callBack
, void *userdata
);
285 static void parse_options(char *options
, char *serial
, int serial_size
, UInt32
*location
, Boolean
*wait_eof
);
286 static void setup_cfLanguage(void);
287 static void soft_reset(void);
288 static void status_timer_cb(CFRunLoopTimerRef timer
, void *info
);
289 static void log_usb_class_driver(int is_64bit
);
291 #define IS_NOT_64BIT 0
293 #if defined(__i386__) || defined(__x86_64__)
294 static pid_t child_pid
; /* Child PID */
295 static void run_legacy_backend(int argc
, char *argv
[], int fd
) __attribute__((noreturn
)); /* Starts child backend process running as a ppc executable */
296 #endif /* __i386__ || __x86_64__ */
297 static void sigterm_handler(int sig
); /* SIGTERM handler */
298 static void sigquit_handler(int sig
, siginfo_t
*si
, void *unused
) __attribute__((noreturn
));
300 #ifdef PARSE_PS_ERRORS
301 static const char *next_line (const char *buffer
);
302 static void parse_pserror (char *sockBuffer
, int len
);
303 #endif /* PARSE_PS_ERRORS */
305 static printer_interface_t
usb_printer_interface_interface(io_service_t usbClass
);
306 static IOUSBDeviceInterface
**usb_device_interface_for_device(io_service_t usbDevice
);
307 static CFStringRef
copy_printer_interface_deviceid(printer_interface_t printer
, UInt8 alternateSetting
);
308 static CFStringRef
copy_printer_interface_indexed_description(printer_interface_t printer
, UInt8 index
, UInt16 language
);
309 static CFStringRef
deviceIDCopyManufacturer(CFStringRef deviceID
);
310 static CFStringRef
deviceIDCopyModel(CFStringRef deviceID
);
311 static CFStringRef
deviceIDCopySerialNumber(CFStringRef deviceID
);
316 * 'list_devices()' - List all USB devices.
321 iterate_printers(list_device_cb
, NULL
);
326 * 'print_device()' - Print a file to a USB device.
329 int /* O - Exit status */
330 print_device(const char *uri
, /* I - Device URI */
331 const char *hostname
, /* I - Hostname/manufacturer */
332 const char *resource
, /* I - Resource/modelname */
333 char *options
, /* I - Device options/serial number */
334 int print_fd
, /* I - File descriptor to print */
335 int copies
, /* I - Copies to print */
336 int argc
, /* I - Number of command-line arguments (6 or 7) */
337 char *argv
[]) /* I - Command-line arguments */
339 char serial
[1024]; /* Serial number buffer */
340 OSStatus status
; /* Function results */
341 IOReturn iostatus
; /* Current IO status */
342 pthread_t read_thread_id
, /* Read thread */
343 sidechannel_thread_id
;/* Side-channel thread */
344 int have_sidechannel
= 0; /* Was the side-channel thread started? */
345 struct stat sidechannel_info
; /* Side-channel file descriptor info */
346 char print_buffer
[8192], /* Print data buffer */
347 *print_ptr
; /* Pointer into print data buffer */
348 UInt32 location
; /* Unique location in bus topology */
349 fd_set input_set
; /* Input set for select() */
350 CFStringRef driverBundlePath
; /* Class driver path */
351 int countdown
, /* Logging interval */
352 nfds
; /* Number of file descriptors */
353 ssize_t total_bytes
; /* Total bytes written */
354 UInt32 bytes
; /* Bytes written */
355 struct timeval
*timeout
, /* Timeout pointer */
357 struct timespec cond_timeout
; /* pthread condition timeout */
358 struct sigaction action
; /* Actions for POSIX signals */
364 * Catch SIGQUIT to determine who is sending it...
367 memset(&action
, 0, sizeof(action
));
368 action
.sa_sigaction
= sigquit_handler
;
369 action
.sa_flags
= SA_SIGINFO
;
370 sigaction(SIGQUIT
, &action
, NULL
);
373 * See if the side-channel descriptor is valid...
376 have_sidechannel
= !fstat(CUPS_SC_FD
, &sidechannel_info
) &&
377 S_ISSOCK(sidechannel_info
.st_mode
);
380 * Localize using CoreFoundation...
385 parse_options(options
, serial
, sizeof(serial
), &location
, &g
.wait_eof
);
387 if (resource
[0] == '/')
390 g
.print_fd
= print_fd
;
391 g
.make
= cfstr_create_trim(hostname
);
392 g
.model
= cfstr_create_trim(resource
);
393 g
.serial
= cfstr_create_trim(serial
);
394 g
.location
= location
;
396 if (!g
.make
|| !g
.model
)
398 fprintf(stderr
, "DEBUG: Fatal USB error.\n");
399 _cupsLangPrintFilter(stderr
, "ERROR",
400 _("There was an unrecoverable USB error."));
403 fputs("DEBUG: USB make string is NULL\n", stderr
);
405 fputs("DEBUG: USB model string is NULL\n", stderr
);
407 return (CUPS_BACKEND_STOP
);
410 fputs("STATE: +connecting-to-device\n", stderr
);
412 countdown
= INITIAL_LOG_INTERVAL
;
418 IOObjectRelease(g
.printer_obj
);
419 unload_classdriver(&g
.classdriver
);
424 fprintf(stderr
, "DEBUG: Looking for '%s %s'\n", hostname
, resource
);
426 iterate_printers(find_device_cb
, NULL
);
428 fputs("DEBUG: Opening connection\n", stderr
);
430 driverBundlePath
= NULL
;
432 status
= registry_open(&driverBundlePath
);
434 #if defined(__i386__) || defined(__x86_64__)
436 * If we were unable to load the class drivers for this printer it's
437 * probably because they're ppc or i386. In this case try to run this
438 * backend as i386 or ppc executables so we can use them...
442 run_legacy_backend(argc
, argv
, print_fd
);
443 /* Never returns here */
445 #endif /* __i386__ || __x86_64__ */
450 * If we still were unable to load the class drivers for this printer log
451 * the error and stop the queue...
454 if (driverBundlePath
== NULL
|| !CFStringGetCString(driverBundlePath
, print_buffer
, sizeof(print_buffer
), kCFStringEncodingUTF8
))
455 strlcpy(print_buffer
, "USB class driver", sizeof(print_buffer
));
457 fputs("STATE: +apple-missing-usbclassdriver-error\n", stderr
);
458 _cupsLangPrintFilter(stderr
, "ERROR",
459 _("There was an unrecoverable USB error."));
460 fprintf(stderr
, "DEBUG: Could not load %s\n", print_buffer
);
462 if (driverBundlePath
)
463 CFRelease(driverBundlePath
);
465 return (CUPS_BACKEND_STOP
);
469 if (status
== noErr
&& driverBundlePath
!= NULL
&& CFStringCompare(driverBundlePath
, kUSBGenericTOPrinterClassDriver
, 0) != kCFCompareEqualTo
)
470 log_usb_class_driver(IS_64BIT
);
471 #endif /* __x86_64__ */
473 if (driverBundlePath
)
474 CFRelease(driverBundlePath
);
478 sleep(PRINTER_POLLING_INTERVAL
);
479 countdown
-= PRINTER_POLLING_INTERVAL
;
482 _cupsLangPrintFilter(stderr
, "INFO",
483 _("Waiting for printer to become available."));
484 fprintf(stderr
, "DEBUG: USB printer status: 0x%08x\n", (int)status
);
485 countdown
= SUBSEQUENT_LOG_INTERVAL
; /* subsequent log entries, every 15 seconds */
488 } while (status
!= noErr
);
490 fputs("STATE: -connecting-to-device\n", stderr
);
493 * Now that we are "connected" to the port, ignore SIGTERM so that we
494 * can finish out any page data the driver sends (e.g. to eject the
495 * current page... Only ignore SIGTERM if we are printing data from
496 * stdin (otherwise you can't cancel raw jobs...)
501 memset(&action
, 0, sizeof(action
));
503 sigemptyset(&action
.sa_mask
);
504 action
.sa_handler
= SIG_IGN
;
505 sigaction(SIGTERM
, &action
, NULL
);
509 * Start the side channel thread if the descriptor is valid...
512 pthread_mutex_init(&g
.readwrite_lock_mutex
, NULL
);
513 pthread_cond_init(&g
.readwrite_lock_cond
, NULL
);
514 g
.readwrite_lock
= 1;
516 if (have_sidechannel
)
518 g
.sidechannel_thread_stop
= 0;
519 g
.sidechannel_thread_done
= 0;
521 pthread_cond_init(&g
.sidechannel_thread_cond
, NULL
);
522 pthread_mutex_init(&g
.sidechannel_thread_mutex
, NULL
);
524 if (pthread_create(&sidechannel_thread_id
, NULL
, sidechannel_thread
, NULL
))
526 fprintf(stderr
, "DEBUG: Fatal USB error.\n");
527 _cupsLangPrintFilter(stderr
, "ERROR",
528 _("There was an unrecoverable USB error."));
529 fputs("DEBUG: Couldn't create side-channel thread\n", stderr
);
531 return (CUPS_BACKEND_STOP
);
536 * Get the read thread going...
539 g
.read_thread_stop
= 0;
540 g
.read_thread_done
= 0;
542 pthread_cond_init(&g
.read_thread_cond
, NULL
);
543 pthread_mutex_init(&g
.read_thread_mutex
, NULL
);
545 if (pthread_create(&read_thread_id
, NULL
, read_thread
, NULL
))
547 fprintf(stderr
, "DEBUG: Fatal USB error.\n");
548 _cupsLangPrintFilter(stderr
, "ERROR",
549 _("There was an unrecoverable USB error."));
550 fputs("DEBUG: Couldn't create read thread\n", stderr
);
552 return (CUPS_BACKEND_STOP
);
556 * The main thread sends the print file...
562 print_ptr
= print_buffer
;
564 while (status
== noErr
&& copies
-- > 0)
566 _cupsLangPrintFilter(stderr
, "INFO", _("Sending data to printer."));
568 if (print_fd
!= STDIN_FILENO
)
570 fputs("PAGE: 1 1\n", stderr
);
571 lseek(print_fd
, 0, SEEK_SET
);
574 while (status
== noErr
)
579 FD_SET(print_fd
, &input_set
);
582 * Calculate select timeout...
583 * If we have data waiting to send timeout is 100ms.
584 * else if we're draining print_fd timeout is 0.
585 * else we're waiting forever...
591 tv
.tv_usec
= 100000; /* 100ms */
594 else if (g
.drain_output
)
604 * I/O is unlocked around select...
607 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
608 g
.readwrite_lock
= 0;
609 pthread_cond_signal(&g
.readwrite_lock_cond
);
610 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
612 nfds
= select(print_fd
+ 1, &input_set
, NULL
, NULL
, timeout
);
615 * Reacquire the lock...
618 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
619 while (g
.readwrite_lock
)
620 pthread_cond_wait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
);
621 g
.readwrite_lock
= 1;
622 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
626 if (errno
== EINTR
&& total_bytes
== 0)
628 fputs("DEBUG: Received an interrupt before any bytes were "
629 "written, aborting\n", stderr
);
631 return (CUPS_BACKEND_OK
);
633 else if (errno
!= EAGAIN
&& errno
!= EINTR
)
635 _cupsLangPrintFilter(stderr
, "ERROR",
636 _("Unable to read print data."));
637 perror("DEBUG: select");
639 return (CUPS_BACKEND_FAILED
);
644 * If drain output has finished send a response...
647 if (g
.drain_output
&& !nfds
&& !g
.print_bytes
)
649 /* Send a response... */
650 cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
655 * Check if we have print data ready...
658 if (FD_ISSET(print_fd
, &input_set
))
661 g
.debug_bytes
+= 512;
662 if (g
.debug_bytes
> sizeof(print_buffer
))
665 g
.print_bytes
= read(print_fd
, print_buffer
, g
.debug_bytes
);
668 g
.print_bytes
= read(print_fd
, print_buffer
, sizeof(print_buffer
));
669 #endif /* DEBUG_WRITES */
671 if (g
.print_bytes
< 0)
674 * Read error - bail if we don't see EAGAIN or EINTR...
677 if (errno
!= EAGAIN
&& errno
!= EINTR
)
679 _cupsLangPrintFilter(stderr
, "ERROR",
680 _("Unable to read print data."));
681 perror("DEBUG: read");
683 return (CUPS_BACKEND_FAILED
);
688 else if (g
.print_bytes
== 0)
691 * End of file, break out of the loop...
697 print_ptr
= print_buffer
;
699 fprintf(stderr
, "DEBUG: Read %d bytes of print data...\n",
705 bytes
= (UInt32
)g
.print_bytes
;
706 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
709 * Ignore timeout errors, but retain the number of bytes written to
710 * avoid sending duplicate data...
713 if (iostatus
== kIOUSBTransactionTimeout
)
715 fputs("DEBUG: Got USB transaction timeout during write\n", stderr
);
720 * If we've stalled, retry the write...
723 else if (iostatus
== kIOUSBPipeStalled
)
725 fputs("DEBUG: Got USB pipe stalled during write\n", stderr
);
727 bytes
= (UInt32
)g
.print_bytes
;
728 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
732 * Retry a write after an aborted write since we probably just got
736 else if (iostatus
== kIOReturnAborted
)
738 fputs("DEBUG: Got USB return aborted during write\n", stderr
);
740 IOReturn err
= (*g
.classdriver
)->Abort(g
.classdriver
);
741 fprintf(stderr
, "DEBUG: USB class driver Abort returned %x\n", err
);
745 #endif /* DEBUG_WRITES */
747 bytes
= (UInt32
)g
.print_bytes
;
748 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
754 * Write error - bail if we don't see an error we can retry...
757 _cupsLangPrintFilter(stderr
, "ERROR",
758 _("Unable to send data to printer."));
759 fprintf(stderr
, "DEBUG: USB class driver WritePipe returned %x\n",
762 IOReturn err
= (*g
.classdriver
)->Abort(g
.classdriver
);
763 fprintf(stderr
, "DEBUG: USB class driver Abort returned %x\n",
766 status
= CUPS_BACKEND_FAILED
;
771 fprintf(stderr
, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes
);
773 g
.print_bytes
-= bytes
;
775 total_bytes
+= bytes
;
779 if (print_fd
!= 0 && status
== noErr
)
780 fprintf(stderr
, "DEBUG: Sending print file, %lld bytes...\n",
785 fprintf(stderr
, "DEBUG: Sent %lld bytes...\n", (off_t
)total_bytes
);
786 fputs("STATE: +cups-waiting-for-job-completed\n", stderr
);
789 * Signal the side channel thread to exit...
792 if (have_sidechannel
)
795 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
796 g
.readwrite_lock
= 0;
797 pthread_cond_signal(&g
.readwrite_lock_cond
);
798 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
800 g
.sidechannel_thread_stop
= 1;
801 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
803 if (!g
.sidechannel_thread_done
)
805 gettimeofday(&tv
, NULL
);
806 cond_timeout
.tv_sec
= tv
.tv_sec
+ WAIT_SIDE_DELAY
;
807 cond_timeout
.tv_nsec
= tv
.tv_usec
* 1000;
809 while (!g
.sidechannel_thread_done
)
811 if (pthread_cond_timedwait(&g
.sidechannel_thread_cond
,
812 &g
.sidechannel_thread_mutex
,
818 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
822 * Signal the read thread to exit then wait 7 seconds for it to complete...
825 g
.read_thread_stop
= 1;
827 pthread_mutex_lock(&g
.read_thread_mutex
);
829 if (!g
.read_thread_done
)
831 fputs("DEBUG: Waiting for read thread to exit...\n", stderr
);
833 gettimeofday(&tv
, NULL
);
834 cond_timeout
.tv_sec
= tv
.tv_sec
+ WAIT_EOF_DELAY
;
835 cond_timeout
.tv_nsec
= tv
.tv_usec
* 1000;
837 while (!g
.read_thread_done
)
839 if (pthread_cond_timedwait(&g
.read_thread_cond
, &g
.read_thread_mutex
,
845 * If it didn't exit abort the pending read and wait an additional second...
848 if (!g
.read_thread_done
)
850 fputs("DEBUG: Read thread still active, aborting the pending read...\n",
855 (*g
.classdriver
)->Abort(g
.classdriver
);
857 gettimeofday(&tv
, NULL
);
858 cond_timeout
.tv_sec
= tv
.tv_sec
+ 1;
859 cond_timeout
.tv_nsec
= tv
.tv_usec
* 1000;
861 while (!g
.read_thread_done
)
863 if (pthread_cond_timedwait(&g
.read_thread_cond
, &g
.read_thread_mutex
,
870 pthread_mutex_unlock(&g
.read_thread_mutex
);
873 * Close the connection and input file and general clean up...
878 if (print_fd
!= STDIN_FILENO
)
887 if (g
.serial
!= NULL
)
890 if (g
.printer_obj
!= 0x0)
891 IOObjectRelease(g
.printer_obj
);
898 * 'read_thread()' - Thread to read the backchannel data on.
901 static void *read_thread(void *reference
)
903 UInt8 readbuffer
[512];
905 kern_return_t readstatus
;
906 struct mach_timebase_info timeBaseInfo
;
913 /* Calculate what 250 milliSeconds are in mach absolute time...
915 mach_timebase_info(&timeBaseInfo
);
916 delay
= ((uint64_t)250000000 * (uint64_t)timeBaseInfo
.denom
) / (uint64_t)timeBaseInfo
.numer
;
921 * Remember when we started so we can throttle the loop after the read call...
924 start
= mach_absolute_time();
926 rbytes
= sizeof(readbuffer
);
927 readstatus
= (*g
.classdriver
)->ReadPipe(g
.classdriver
, readbuffer
, &rbytes
);
928 if (readstatus
== kIOReturnSuccess
&& rbytes
> 0)
930 fprintf(stderr
, "DEBUG: Read %d bytes of back-channel data...\n",
932 cupsBackChannelWrite((char*)readbuffer
, rbytes
, 1.0);
934 /* cntrl-d is echoed by the printer.
936 * Xerox Phaser 6250D doesn't echo the cntrl-d.
937 * Xerox Phaser 6250D doesn't always send the product query.
939 if (g
.wait_eof
&& readbuffer
[rbytes
-1] == 0x4)
942 #ifdef PARSE_PS_ERRORS
943 parse_pserror(readbuffer
, rbytes
);
946 else if (readstatus
== kIOUSBTransactionTimeout
)
947 fputs("DEBUG: Got USB transaction timeout during read\n", stderr
);
948 else if (readstatus
== kIOUSBPipeStalled
)
949 fputs("DEBUG: Got USB pipe stalled during read\n", stderr
);
950 else if (readstatus
== kIOReturnAborted
)
951 fputs("DEBUG: Got USB return aborted during read\n", stderr
);
954 * Make sure this loop executes no more than once every 250 miliseconds...
957 if ((readstatus
!= kIOReturnSuccess
|| rbytes
== 0) && (g
.wait_eof
|| !g
.read_thread_stop
))
958 mach_wait_until(start
+ delay
);
960 } while (g
.wait_eof
|| !g
.read_thread_stop
); /* Abort from main thread tests error here */
962 /* Workaround for usb race condition. <rdar://problem/21882551> */
963 if (!g
.wait_eof
&& g
.use_generic_class_driver
)
965 const char *pdl
= getenv("FINAL_CONTENT_TYPE");
966 if (pdl
&& strcmp(pdl
, "application/vnd.cups-postscript") == 0)
968 while (readstatus
== kIOReturnSuccess
&& ((rbytes
> 0 && readbuffer
[rbytes
-1] != 0x4) || rbytes
== 0))
970 start
= mach_absolute_time();
972 rbytes
= sizeof(readbuffer
);
973 readstatus
= (*g
.classdriver
)->ReadPipe(g
.classdriver
, readbuffer
, &rbytes
);
974 if (readstatus
== kIOReturnSuccess
&& rbytes
> 0 && readbuffer
[rbytes
-1] == 0x4)
977 /* Make sure this loop executes no more than once every 250 miliseconds... */
978 mach_wait_until(start
+ delay
);
984 * Let the main thread know that we have completed the read thread...
987 pthread_mutex_lock(&g
.read_thread_mutex
);
988 g
.read_thread_done
= 1;
989 pthread_cond_signal(&g
.read_thread_cond
);
990 pthread_mutex_unlock(&g
.read_thread_mutex
);
997 * 'sidechannel_thread()' - Handle side-channel requests.
1001 sidechannel_thread(void *reference
)
1003 cups_sc_command_t command
; /* Request command */
1004 cups_sc_status_t status
; /* Request/response status */
1005 char data
[2048]; /* Request/response data */
1006 int datalen
; /* Request/response data size */
1013 datalen
= sizeof(data
);
1015 if (cupsSideChannelRead(&command
, &status
, data
, &datalen
, 1.0))
1017 if (status
== CUPS_SC_STATUS_TIMEOUT
)
1025 case CUPS_SC_CMD_SOFT_RESET
: /* Do a soft reset */
1026 fputs("DEBUG: CUPS_SC_CMD_SOFT_RESET received from driver...\n",
1029 if ((*g
.classdriver
)->SoftReset
!= NULL
)
1032 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
1033 fputs("DEBUG: Returning status CUPS_STATUS_OK with no bytes...\n",
1038 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
1040 fputs("DEBUG: Returning status CUPS_STATUS_NOT_IMPLEMENTED with "
1041 "no bytes...\n", stderr
);
1045 case CUPS_SC_CMD_DRAIN_OUTPUT
: /* Drain all pending output */
1046 fputs("DEBUG: CUPS_SC_CMD_DRAIN_OUTPUT received from driver...\n",
1052 case CUPS_SC_CMD_GET_BIDI
: /* Is the connection bidirectional? */
1053 fputs("DEBUG: CUPS_SC_CMD_GET_BIDI received from driver...\n",
1056 data
[0] = (char)g
.bidi_flag
;
1057 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
1060 "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
1064 case CUPS_SC_CMD_GET_DEVICE_ID
: /* Return IEEE-1284 device ID */
1065 fputs("DEBUG: CUPS_SC_CMD_GET_DEVICE_ID received from driver...\n",
1068 datalen
= sizeof(data
);
1069 get_device_id(&status
, data
, &datalen
);
1070 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, datalen
, 1.0);
1072 if ((size_t)datalen
< sizeof(data
))
1073 data
[datalen
] = '\0';
1075 data
[sizeof(data
) - 1] = '\0';
1078 "DEBUG: Returning CUPS_SC_STATUS_OK with %d bytes (%s)...\n",
1082 case CUPS_SC_CMD_GET_STATE
: /* Return device state */
1083 fputs("DEBUG: CUPS_SC_CMD_GET_STATE received from driver...\n",
1086 data
[0] = CUPS_SC_STATE_ONLINE
;
1087 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
1090 "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
1095 fprintf(stderr
, "DEBUG: Unknown side-channel command (%d) received "
1096 "from driver...\n", command
);
1098 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
1101 fputs("DEBUG: Returned CUPS_SC_STATUS_NOT_IMPLEMENTED with no bytes...\n",
1106 while (!g
.sidechannel_thread_stop
);
1108 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
1109 g
.sidechannel_thread_done
= 1;
1110 pthread_cond_signal(&g
.sidechannel_thread_cond
);
1111 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
1119 * 'iterate_printers()' - Iterate over all the printers.
1122 static void iterate_printers(iterator_callback_t callBack
, void *userdata
)
1126 mach_port_t masterPort
= 0x0;
1127 kern_return_t kr
= IOMasterPort (bootstrap_port
, &masterPort
);
1129 if (kr
== kIOReturnSuccess
&& masterPort
!= 0x0)
1131 iterator_reference_t reference
= { callBack
, userdata
, true };
1133 IONotificationPortRef addNotification
= IONotificationPortCreate(masterPort
);
1134 io_iterator_t addIterator
= IO_OBJECT_NULL
;
1136 kr
= IOServiceAddMatchingNotification(addNotification
, kIOFirstMatchNotification
, IOServiceMatching(kIOUSBDeviceClassName
),
1137 &device_added
, &reference
, &addIterator
);
1138 if (kr
== kIOReturnSuccess
&& addIterator
!= IO_OBJECT_NULL
)
1140 device_added(&reference
, addIterator
);
1141 if (reference
.keepRunning
)
1143 CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification
), kCFRunLoopDefaultMode
);
1146 IOObjectRelease(addIterator
);
1148 mach_port_deallocate(mach_task_self(), masterPort
);
1156 * 'device_added()' - Device added notifier.
1158 #define IsPrintingInterface(c,s,p) ((c) == kUSBPrintingInterfaceClass && (s) == kUSBPrintingSubclass && (p) != kUSBPrintingProtocolIPP)
1160 static void device_added(void *userdata
, io_iterator_t iterator
)
1162 iterator_reference_t
*reference
= userdata
;
1163 io_service_t device
;
1165 while (reference
->keepRunning
&& (device
= IOIteratorNext(iterator
)) != 0x0)
1167 UInt32 locationID
= 0;
1168 IOUSBDeviceInterface
**devIntf
= NULL
;
1169 io_iterator_t intfIterator
= IO_OBJECT_NULL
;
1170 io_object_t intf
= IO_OBJECT_NULL
;
1172 devIntf
= usb_device_interface_for_device(device
);
1173 if (devIntf
== NULL
)
1174 goto device_added_done
;
1176 UInt16 vendorUniqueID
;
1177 if ((*devIntf
)->GetDeviceVendor(devIntf
, &vendorUniqueID
) != kIOReturnSuccess
|| vendorUniqueID
== kAppleVendorID
|| vendorUniqueID
== 0x0A5C)
1178 goto device_added_done
;
1180 if ((*devIntf
)->GetLocationID(devIntf
, &locationID
) != kIOReturnSuccess
)
1181 goto device_added_done
;
1183 IOUSBFindInterfaceRequest req
= { kIOUSBFindInterfaceDontCare
, kIOUSBFindInterfaceDontCare
, kIOUSBFindInterfaceDontCare
, kIOUSBFindInterfaceDontCare
};
1184 if ((*devIntf
)->CreateInterfaceIterator(devIntf
, &req
, &intfIterator
) != kIOReturnSuccess
)
1185 goto device_added_done
;
1187 while (reference
->keepRunning
&& (intf
= IOIteratorNext(intfIterator
)))
1189 printer_interface_t printerIntf
= usb_printer_interface_interface(intf
);
1190 if (printerIntf
!= NULL
)
1192 UInt8 intfClass
= 0, intfSubclass
= 0, intfProtocol
= 0, intfNumber
= 0;
1194 (*printerIntf
)->GetInterfaceClass(printerIntf
, &intfClass
);
1195 (*printerIntf
)->GetInterfaceSubClass(printerIntf
, &intfSubclass
);
1196 (*printerIntf
)->GetInterfaceProtocol(printerIntf
, &intfProtocol
);
1197 (*printerIntf
)->GetInterfaceNumber(printerIntf
, &intfNumber
);
1199 if (IsPrintingInterface(intfClass
, intfSubclass
, intfProtocol
))
1201 CFStringRef deviceIDString
= copy_printer_interface_deviceid(printerIntf
, 0);
1202 if (deviceIDString
!= NULL
)
1204 reference
->keepRunning
= reference
->callback(userdata
, intf
, deviceIDString
, locationID
, intfNumber
, 0);
1205 CFRelease(deviceIDString
);
1209 IOUSBInterfaceDescriptor
*intfDesc
= NULL
;
1210 while (reference
->keepRunning
&& (intfDesc
= (IOUSBInterfaceDescriptor
*)(*printerIntf
)->FindNextAssociatedDescriptor(printerIntf
, intfDesc
, kUSBInterfaceDesc
)))
1212 intfClass
= intfDesc
->bInterfaceClass
;
1213 intfSubclass
= intfDesc
->bInterfaceSubClass
;
1214 intfProtocol
= intfDesc
->bInterfaceProtocol
;
1216 if ((IsPrintingInterface(intfClass
, intfSubclass
, intfProtocol
)))
1218 CFStringRef deviceIDString
= copy_printer_interface_deviceid(printerIntf
, intfDesc
->bAlternateSetting
);
1219 if (deviceIDString
!= NULL
)
1221 reference
->keepRunning
= reference
->callback(userdata
, intf
, deviceIDString
, locationID
, intfNumber
, intfDesc
->bAlternateSetting
);
1222 CFRelease(deviceIDString
);
1226 (*printerIntf
)->Release(printerIntf
);
1228 IOObjectRelease(intf
);
1232 if (devIntf
!= NULL
) (*devIntf
)->Release(devIntf
);
1233 if (intfIterator
!= IO_OBJECT_NULL
) IOObjectRelease(intfIterator
);
1235 IOObjectRelease(device
);
1238 /* One last call to the call back now that we are not longer have printers left to iterate...
1240 if (reference
->keepRunning
&& reference
->callback
)
1241 reference
->keepRunning
= reference
->callback(reference
->userdata
, IO_OBJECT_NULL
, NULL
, 0, 0, 0);
1243 if (!reference
->keepRunning
)
1244 CFRunLoopStop(CFRunLoopGetCurrent());
1248 * 'list_device_cb()' - list_device iterator callback.
1251 static Boolean
list_device_cb(void *refcon
, io_service_t obj
, CFStringRef deviceIDString
, UInt32 deviceLocation
, UInt8 interfaceNum
, UInt8 alternateSetting
)
1255 (void)alternateSetting
;
1257 if (obj
!= IO_OBJECT_NULL
)
1259 CFStringRef make
= deviceIDCopyManufacturer(deviceIDString
);
1260 CFStringRef model
= deviceIDCopyModel(deviceIDString
);
1261 CFStringRef serial
= deviceIDCopySerialNumber(deviceIDString
);
1263 char uristr
[1024], makestr
[1024], modelstr
[1024], serialstr
[1024];
1264 char optionsstr
[1024], idstr
[1024], make_modelstr
[1024];
1266 CFStringGetCString(deviceIDString
, idstr
, sizeof(idstr
), kCFStringEncodingUTF8
);
1267 backendGetMakeModel(idstr
, make_modelstr
, sizeof(make_modelstr
));
1271 if (make
== NULL
|| !CFStringGetCString(make
, makestr
, sizeof(makestr
), kCFStringEncodingUTF8
))
1272 strlcpy(makestr
, "Unknown", sizeof(makestr
));
1274 if (model
== NULL
|| !CFStringGetCString(model
, &modelstr
[1], sizeof(modelstr
)-1, kCFStringEncodingUTF8
))
1275 strlcpy(modelstr
+ 1, "Printer", sizeof(modelstr
) - 1);
1277 optionsstr
[0] = '\0';
1278 if (serial
!= NULL
&& CFStringGetCString(serial
, serialstr
, sizeof(serialstr
), kCFStringEncodingUTF8
))
1279 snprintf(optionsstr
, sizeof(optionsstr
), "?serial=%s", serialstr
);
1280 else if (deviceLocation
!= 0)
1281 snprintf(optionsstr
, sizeof(optionsstr
), "?location=%x", (unsigned)deviceLocation
);
1283 httpAssembleURI(HTTP_URI_CODING_ALL
, uristr
, sizeof(uristr
), "usb", NULL
, makestr
, 0, modelstr
);
1284 strlcat(uristr
, optionsstr
, sizeof(uristr
));
1286 cupsBackendReport("direct", uristr
, make_modelstr
, make_modelstr
, idstr
,
1289 if (make
!= NULL
) CFRelease(make
);
1290 if (model
!= NULL
) CFRelease(model
);
1291 if (serial
!= NULL
) CFRelease(serial
);
1294 return obj
!= IO_OBJECT_NULL
;
1298 * 'find_device_cb()' - print_device iterator callback.
1300 static Boolean
find_device_cb(void *refcon
, io_service_t obj
, CFStringRef deviceIDString
, UInt32 deviceLocation
, UInt8 interfaceNum
, UInt8 alternateSetting
)
1302 Boolean keepLooking
= true;
1304 if (obj
!= IO_OBJECT_NULL
)
1306 CFStringRef make
= deviceIDCopyManufacturer(deviceIDString
);
1307 CFStringRef model
= deviceIDCopyModel(deviceIDString
);
1308 CFStringRef serial
= deviceIDCopySerialNumber(deviceIDString
);
1310 if (make
&& CFStringCompare(make
, g
.make
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1312 if (model
&& CFStringCompare(model
, g
.model
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1314 if (g
.serial
!= NULL
&& CFStringGetLength(g
.serial
) > 0)
1316 if (serial
!= NULL
&& CFStringCompare(serial
, g
.serial
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1318 IOObjectRetain(obj
);
1319 g
.printer_obj
= obj
;
1320 g
.location
= deviceLocation
;
1321 g
.alternateSetting
= alternateSetting
;
1322 keepLooking
= false;
1327 if (g
.printer_obj
!= 0)
1328 IOObjectRelease(g
.printer_obj
);
1330 g
.alternateSetting
= alternateSetting
;
1331 g
.printer_obj
= obj
;
1332 IOObjectRetain(obj
);
1334 if (g
.location
== 0 || g
.location
== deviceLocation
)
1335 keepLooking
= false;
1339 g
.interfaceNum
= interfaceNum
;
1343 if (make
) CFRelease(make
);
1344 if (model
) CFRelease(model
);
1345 if (serial
) CFRelease(serial
);
1349 keepLooking
= (g
.printer_obj
== 0);
1350 if (obj
== IO_OBJECT_NULL
&& keepLooking
)
1352 CFRunLoopTimerContext context
= { 0, refcon
, NULL
, NULL
, NULL
};
1353 CFRunLoopTimerRef timer
= CFRunLoopTimerCreate(NULL
, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb
, &context
);
1356 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer
, kCFRunLoopDefaultMode
);
1357 g
.status_timer
= timer
;
1362 if (!keepLooking
&& g
.status_timer
!= NULL
)
1364 fputs("STATE: -offline-report\n", stderr
);
1365 _cupsLangPrintFilter(stderr
, "INFO", _("The printer is now online."));
1366 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g
.status_timer
, kCFRunLoopDefaultMode
);
1367 CFRelease(g
.status_timer
);
1368 g
.status_timer
= NULL
;
1374 static CFStringRef
deviceIDCopySerialNumber(CFStringRef deviceID
)
1376 CFStringRef serialKeys
[] = { CFSTR("SN:"), CFSTR("SERN:"), NULL
};
1378 return copy_value_for_key(deviceID
, serialKeys
);
1381 static CFStringRef
deviceIDCopyModel(CFStringRef deviceID
)
1383 CFStringRef modelKeys
[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL
};
1384 return copy_value_for_key(deviceID
, modelKeys
);
1387 static CFStringRef
deviceIDCopyManufacturer(CFStringRef deviceID
)
1389 CFStringRef makeKeys
[] = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL
};
1390 return copy_value_for_key(deviceID
, makeKeys
);
1394 * 'status_timer_cb()' - Status timer callback.
1397 static void status_timer_cb(CFRunLoopTimerRef timer
,
1403 fputs("STATE: +offline-report\n", stderr
);
1404 _cupsLangPrintFilter(stderr
, "INFO", _("The printer is offline."));
1406 if (getenv("CLASS") != NULL
)
1409 * If the CLASS environment variable is set, the job was submitted
1410 * to a class and not to a specific queue. In this case, we want
1411 * to abort immediately so that the job can be requeued on the next
1412 * available printer in the class.
1414 * Sleep 5 seconds to keep the job from requeuing too rapidly...
1419 exit(CUPS_BACKEND_FAILED
);
1426 * 'load_classdriver()' - Load a classdriver.
1429 static kern_return_t
load_classdriver(CFStringRef driverPath
,
1430 printer_interface_t interface
,
1431 classdriver_t
***printerDriver
)
1433 kern_return_t kr
= kUSBPrinterClassDeviceNotOpen
;
1434 classdriver_t
**driver
= NULL
;
1435 CFStringRef bundle
= driverPath
? driverPath
: kUSBGenericTOPrinterClassDriver
;
1436 char bundlestr
[1024]; /* Bundle path */
1437 CFURLRef url
; /* URL for driver */
1438 CFPlugInRef plugin
= NULL
; /* Plug-in address */
1441 CFStringGetCString(bundle
, bundlestr
, sizeof(bundlestr
), kCFStringEncodingUTF8
);
1444 * Validate permissions for the class driver...
1447 _cups_fc_result_t result
= _cupsFileCheck(bundlestr
,
1448 _CUPS_FILE_CHECK_DIRECTORY
, 1,
1449 Iterating
? NULL
: _cupsFileCheckFilter
, NULL
);
1451 if (result
&& driverPath
)
1452 return (load_classdriver(NULL
, interface
, printerDriver
));
1457 * Try loading the class driver...
1460 url
= CFURLCreateWithFileSystemPath(NULL
, bundle
, kCFURLPOSIXPathStyle
, true);
1464 plugin
= CFPlugInCreate(NULL
, url
);
1472 CFArrayRef factories
= CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID
, plugin
);
1473 if (factories
!= NULL
&& CFArrayGetCount(factories
) > 0)
1475 CFUUIDRef factoryID
= CFArrayGetValueAtIndex(factories
, 0);
1476 IUnknownVTbl
**iunknown
= CFPlugInInstanceCreate(NULL
, factoryID
, kUSBPrinterClassTypeID
);
1477 if (iunknown
!= NULL
)
1479 kr
= (*iunknown
)->QueryInterface(iunknown
, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID
), (LPVOID
*)&driver
);
1480 if (kr
== kIOReturnSuccess
&& driver
!= NULL
)
1482 classdriver_t
**genericDriver
= NULL
;
1483 if (driverPath
!= NULL
&& CFStringCompare(driverPath
, kUSBGenericTOPrinterClassDriver
, 0) != kCFCompareEqualTo
)
1484 kr
= load_classdriver(NULL
, interface
, &genericDriver
);
1486 if (kr
== kIOReturnSuccess
)
1488 (*driver
)->interface
= interface
;
1489 (*driver
)->Initialize(driver
, genericDriver
);
1491 (*driver
)->plugin
= plugin
;
1492 (*driver
)->interface
= interface
;
1493 *printerDriver
= driver
;
1496 (*iunknown
)->Release(iunknown
);
1498 CFRelease(factories
);
1502 fprintf(stderr
, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr
, (int)kr
);
1509 * 'unload_classdriver()' - Unload a classdriver.
1512 static kern_return_t
unload_classdriver(classdriver_t
***classdriver
)
1514 if (*classdriver
!= NULL
)
1516 (**classdriver
)->Release(*classdriver
);
1517 *classdriver
= NULL
;
1520 return kIOReturnSuccess
;
1525 * 'load_printerdriver()' - Load vendor's classdriver.
1527 * If driverBundlePath is not NULL on return it is the callers responsbility to release it!
1530 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
)
1532 IOCFPlugInInterface
**iodev
= NULL
;
1535 printer_interface_t interface
;
1538 kr
= IOCreatePlugInInterfaceForService(g
.printer_obj
, kIOUSBInterfaceUserClientTypeID
, kIOCFPlugInInterfaceID
, &iodev
, &score
);
1539 if (kr
== kIOReturnSuccess
)
1541 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*) &interface
)) == noErr
)
1543 *driverBundlePath
= IORegistryEntryCreateCFProperty(g
.printer_obj
, kUSBClassDriverProperty
, NULL
, kNilOptions
);
1545 g
.use_generic_class_driver
= (*driverBundlePath
== NULL
|| (CFStringCompare(*driverBundlePath
, kUSBGenericTOPrinterClassDriver
, 0x0) == kCFCompareEqualTo
));
1546 kr
= load_classdriver(*driverBundlePath
, interface
, &g
.classdriver
);
1548 if (kr
!= kIOReturnSuccess
)
1549 (*interface
)->Release(interface
);
1551 IODestroyPlugInInterface(iodev
);
1556 static printer_interface_t
usb_printer_interface_interface(io_service_t usbClass
)
1558 printer_interface_t intf
= NULL
;
1559 IOCFPlugInInterface
**plugin
= NULL
;
1561 int kr
= IOCreatePlugInInterfaceForService(usbClass
, kIOUSBInterfaceUserClientTypeID
, kIOCFPlugInInterfaceID
, &plugin
, &score
);
1562 if (kr
== kIOReturnSuccess
)
1564 (*plugin
)->QueryInterface(plugin
, USB_INTERFACE_KIND
, (LPVOID
*)&intf
);
1565 IODestroyPlugInInterface(plugin
);
1571 static IOUSBDeviceInterface
**usb_device_interface_for_device(io_service_t usbDevice
)
1573 IOUSBDeviceInterface
** intf
= NULL
;
1574 IOCFPlugInInterface
**plugin
= NULL
;
1577 int kr
= IOCreatePlugInInterfaceForService(usbDevice
, kIOUSBDeviceUserClientTypeID
, kIOCFPlugInInterfaceID
, &plugin
, &score
);
1578 if (kr
== kIOReturnSuccess
)
1580 (*plugin
)->QueryInterface(plugin
, CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID
), (LPVOID
*)&intf
);
1581 IODestroyPlugInInterface(plugin
);
1588 static CFStringRef
copy_printer_interface_deviceid(printer_interface_t printer
, UInt8 alternateSetting
)
1590 // I have tried to make this function as neat as I can, but the possibility of needing to resend
1591 // a request to get the entire string makes it hideous...
1593 // We package the job of sending a request up into the block (^sendRequest), which takes the size
1594 // it should allocate for the message buffer. It frees the current buffer if one is set and
1595 // allocates one of the specified size, then performs the request. We can then easily retry by
1596 // calling the block again if we fail to get the whole string the first time around.
1598 #define kUSBPrintClassGetDeviceID 0
1599 #define kDefaultNoDataTimeout 5000L
1600 #define pack_device_id_wIndex(intf, alt) ((UInt16)((((UInt16)(intf)) << 8) | ((UInt8)(alt))))
1602 if (printer
== NULL
)
1606 IOReturn err
= kIOReturnError
;
1607 UInt8 configurationIndex
= 0;
1608 UInt8 interfaceNumber
= 0;
1609 size_t bufferLength
= 256;
1610 CFStringRef ret
= NULL
;
1612 if ((*printer
)->GetConfigurationValue( printer
, &configurationIndex
) == kIOReturnSuccess
&&
1613 (*printer
)->GetInterfaceNumber( printer
, &interfaceNumber
) == kIOReturnSuccess
)
1615 __block IOUSBDevRequestTO request
;
1616 IOReturn (^sendRequest
)(size_t) = ^ (size_t size
)
1620 free(request
.pData
);
1621 request
.wLength
= 0;
1622 request
.pData
= NULL
;
1625 IOReturn berr
= kIOReturnError
;
1626 char *buffer
= malloc(size
);
1628 return kIOReturnNoMemory
;
1630 request
.wLength
= HostToUSBWord(size
);
1631 request
.pData
= buffer
;
1632 berr
= (*printer
)->ControlRequestTO(printer
, (UInt8
)0, &request
);
1636 /* This request takes the 0 based configuration index. IOKit returns a 1 based configuration index */
1637 configurationIndex
-= 1;
1639 bzero(&request
, sizeof(request
));
1641 request
.bmRequestType
= USBmakebmRequestType(kUSBIn
, kUSBClass
, kUSBInterface
);
1642 request
.bRequest
= kUSBPrintClassGetDeviceID
;
1643 request
.wValue
= HostToUSBWord(configurationIndex
);
1644 request
.wIndex
= HostToUSBWord(pack_device_id_wIndex(interfaceNumber
, alternateSetting
));
1645 request
.noDataTimeout
= kDefaultNoDataTimeout
;
1646 request
.completionTimeout
= 0; // Copying behavior from Generic Class Driver
1648 err
= sendRequest(bufferLength
);
1650 if (err
== kIOReturnSuccess
&& request
.wLenDone
> 1)
1652 UInt16 actualLength
= OSSwapBigToHostInt16(*((UInt16
*)request
.pData
));
1654 if (actualLength
> 2 && actualLength
<= bufferLength
- 2)
1656 ret
= CFStringCreateWithBytes(NULL
, (const UInt8
*) &request
.pData
[2], actualLength
- 2, kCFStringEncodingUTF8
, false);
1658 else if (actualLength
> 2) {
1659 err
= sendRequest(actualLength
);
1660 if (err
== kIOReturnSuccess
&& request
.wLenDone
> 0)
1662 actualLength
= OSSwapBigToHostInt16(*((UInt16
*)request
.pData
));
1663 ret
= CFStringCreateWithBytes(NULL
, (const UInt8
*) &request
.pData
[2], actualLength
- 2, kCFStringEncodingUTF8
, false);
1669 free(request
.pData
);
1672 CFStringRef manufacturer
= deviceIDCopyManufacturer(ret
);
1673 CFStringRef model
= deviceIDCopyModel(ret
);
1674 CFStringRef serial
= deviceIDCopySerialNumber(ret
);
1676 if (manufacturer
== NULL
|| serial
== NULL
|| model
== NULL
)
1678 IOUSBDevRequestTO request
;
1679 IOUSBDeviceDescriptor desc
;
1681 bzero(&request
, sizeof(request
));
1683 request
.bmRequestType
= USBmakebmRequestType( kUSBIn
, kUSBStandard
, kUSBDevice
);
1684 request
.bRequest
= kUSBRqGetDescriptor
;
1685 request
.wValue
= kUSBDeviceDesc
<< 8;
1687 request
.wLength
= sizeof(desc
);
1688 request
.pData
= &desc
;
1689 request
.completionTimeout
= 0;
1690 request
.noDataTimeout
= 60L;
1692 err
= (*printer
)->ControlRequestTO(printer
, 0, &request
);
1693 if (err
== kIOReturnSuccess
)
1695 CFMutableStringRef extras
= CFStringCreateMutable(NULL
, 0);
1696 if (manufacturer
== NULL
)
1698 manufacturer
= copy_printer_interface_indexed_description(printer
, desc
.iManufacturer
, kUSBLanguageEnglish
);
1699 if (manufacturer
&& CFStringGetLength(manufacturer
) > 0)
1700 CFStringAppendFormat(extras
, NULL
, CFSTR("MFG:%@;"), manufacturer
);
1705 model
= copy_printer_interface_indexed_description(printer
, desc
.iProduct
, kUSBLanguageEnglish
);
1706 if (model
&& CFStringGetLength(model
) > 0)
1707 CFStringAppendFormat(extras
, NULL
, CFSTR("MDL:%@;"), model
);
1710 if (serial
== NULL
&& desc
.iSerialNumber
!= 0)
1712 serial
= copy_printer_interface_indexed_description(printer
, desc
.iSerialNumber
, kUSBLanguageEnglish
);
1713 if (serial
&& CFStringGetLength(serial
) > 0)
1714 CFStringAppendFormat(extras
, NULL
, CFSTR("SERN:%@;"), serial
);
1719 CFStringAppend(extras
, ret
);
1733 /* Remove special characters from the serial number */
1734 CFRange range
= (serial
!= NULL
? CFStringFind(serial
, CFSTR("+"), 0) : CFRangeMake(0, 0));
1735 if (range
.length
== 1)
1737 range
= CFStringFind(ret
, serial
, 0);
1739 CFMutableStringRef deviceIDString
= CFStringCreateMutableCopy(NULL
, 0, ret
);
1742 ret
= deviceIDString
;
1743 CFStringFindAndReplace(deviceIDString
, CFSTR("+"), CFSTR(""), range
, 0);
1747 if (manufacturer
!= NULL
)
1748 CFRelease(manufacturer
);
1756 if (ret
!= NULL
&& CFStringGetLength(ret
) == 0)
1765 static CFStringRef
copy_printer_interface_indexed_description(printer_interface_t printer
, UInt8 index
, UInt16 language
)
1768 UInt8 description
[256]; // Max possible descriptor length
1769 IOUSBDevRequestTO request
;
1771 bzero(description
, 2);
1773 request
.bmRequestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
1774 request
.bRequest
= kUSBRqGetDescriptor
;
1775 request
.wValue
= (kUSBStringDesc
<< 8) | index
;
1776 request
.wIndex
= language
;
1777 request
.wLength
= 2;
1778 request
.pData
= &description
;
1779 request
.completionTimeout
= 0;
1780 request
.noDataTimeout
= 60L;
1782 err
= (*printer
)->ControlRequestTO(printer
, 0, &request
);
1783 if (err
!= kIOReturnSuccess
&& err
!= kIOReturnOverrun
)
1785 bzero(description
, request
.wLength
);
1787 // Let's try again full length. Here's why:
1788 // On USB 2.0 controllers, we will not get an overrun error. We just get a "babble" error
1789 // and no valid data. So, if we ask for the max size, we will either get it, or we'll get an underrun.
1790 // It looks like we get it w/out an underrun
1792 request
.bmRequestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
1793 request
.bRequest
= kUSBRqGetDescriptor
;
1794 request
.wValue
= (kUSBStringDesc
<< 8) | index
;
1795 request
.wIndex
= language
;
1796 request
.wLength
= sizeof description
;
1797 request
.pData
= &description
;
1798 request
.completionTimeout
= 0;
1799 request
.noDataTimeout
= 60L;
1801 err
= (*printer
)->ControlRequestTO(printer
, 0, &request
);
1802 if (err
!= kIOReturnSuccess
&& err
!= kIOReturnUnderrun
)
1806 unsigned int length
= description
[0];
1808 return CFStringCreateWithCString(NULL
, "", kCFStringEncodingUTF8
);
1810 if (description
[1] != kUSBStringDesc
)
1813 request
.bmRequestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
1814 request
.bRequest
= kUSBRqGetDescriptor
;
1815 request
.wValue
= (kUSBStringDesc
<< 8) | index
;
1816 request
.wIndex
= language
;
1818 bzero(description
, length
);
1819 request
.wLength
= (UInt16
)length
;
1820 request
.pData
= &description
;
1821 request
.completionTimeout
= 0;
1822 request
.noDataTimeout
= 60L;
1824 err
= (*printer
)->ControlRequestTO(printer
, 0, &request
);
1825 if (err
!= kIOReturnSuccess
)
1828 if (description
[1] != kUSBStringDesc
)
1831 if ((description
[0] & 1) != 0)
1832 description
[0] &= 0xfe;
1834 char buffer
[258] = {};
1835 unsigned int maxLength
= sizeof buffer
;
1836 if (description
[0] > 1)
1838 length
= (description
[0]-2)/2;
1840 if (length
> maxLength
- 1)
1841 length
= maxLength
-1;
1843 for (unsigned i
= 0; i
< length
; i
++)
1844 buffer
[i
] = (char) description
[2*i
+2];
1849 return CFStringCreateWithCString(NULL
, buffer
, kCFStringEncodingUTF8
);
1853 * 'registry_open()' - Open a connection to the printer.
1856 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
)
1858 g
.bidi_flag
= 0; /* 0=unidirectional */
1860 kern_return_t kr
= load_printerdriver(driverBundlePath
);
1861 if (kr
!= kIOReturnSuccess
)
1864 if (g
.classdriver
!= NULL
)
1866 (*g
.classdriver
)->interfaceNumber
= g
.interfaceNum
;
1867 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolBidirectional
);
1868 if (kr
!= kIOReturnSuccess
|| (*g
.classdriver
)->interface
== NULL
)
1870 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolUnidirectional
);
1871 if (kr
== kIOReturnSuccess
)
1873 if ((*g
.classdriver
)->interface
== NULL
)
1875 (*g
.classdriver
)->Close(g
.classdriver
);
1881 g
.bidi_flag
= 1; /* 1=bidirectional */
1884 if (kr
!= kIOReturnSuccess
)
1885 unload_classdriver(&g
.classdriver
);
1892 * 'registry_close()' - Close the connection to the printer.
1895 static kern_return_t
registry_close(void)
1897 if (g
.classdriver
!= NULL
)
1898 (*g
.classdriver
)->Close(g
.classdriver
);
1900 unload_classdriver(&g
.classdriver
);
1901 return kIOReturnSuccess
;
1906 * 'copy_value_for_key()' - Copy value string associated with a key.
1909 static CFStringRef
copy_value_for_key(CFStringRef deviceID
,
1912 CFStringRef value
= NULL
;
1913 CFArrayRef kvPairs
= deviceID
!= NULL
? CFStringCreateArrayBySeparatingStrings(NULL
, deviceID
, CFSTR(";")) : NULL
;
1914 CFIndex max
= kvPairs
!= NULL
? CFArrayGetCount(kvPairs
) : 0;
1917 while (idx
< max
&& value
== NULL
)
1919 CFStringRef kvpair
= CFArrayGetValueAtIndex(kvPairs
, idx
);
1921 while (keys
[idxx
] != NULL
&& value
== NULL
)
1923 CFRange range
= CFStringFind(kvpair
, keys
[idxx
], kCFCompareCaseInsensitive
);
1924 if (range
.length
!= -1)
1926 if (range
.location
!= 0)
1928 CFMutableStringRef theString
= CFStringCreateMutableCopy(NULL
, 0, kvpair
);
1929 CFStringTrimWhitespace(theString
);
1930 range
= CFStringFind(theString
, keys
[idxx
], kCFCompareCaseInsensitive
);
1931 if (range
.location
== 0)
1932 value
= CFStringCreateWithSubstring(NULL
, theString
, CFRangeMake(range
.length
, CFStringGetLength(theString
) - range
.length
));
1934 CFRelease(theString
);
1938 CFStringRef theString
= CFStringCreateWithSubstring(NULL
, kvpair
, CFRangeMake(range
.length
, CFStringGetLength(kvpair
) - range
.length
));
1939 CFMutableStringRef theString2
= CFStringCreateMutableCopy(NULL
, 0, theString
);
1940 CFRelease(theString
);
1942 CFStringTrimWhitespace(theString2
);
1951 if (kvPairs
!= NULL
)
1958 * 'cfstr_create_trim()' - Create CFString and trim whitespace characters.
1961 CFStringRef
cfstr_create_trim(const char *cstr
)
1964 CFMutableStringRef cfmutablestr
= NULL
;
1966 if ((cfstr
= CFStringCreateWithCString(NULL
, cstr
, kCFStringEncodingUTF8
)) != NULL
)
1968 if ((cfmutablestr
= CFStringCreateMutableCopy(NULL
, 1024, cfstr
)) != NULL
)
1969 CFStringTrimWhitespace(cfmutablestr
);
1973 return (CFStringRef
) cfmutablestr
;
1979 * 'parse_options()' - Parse URI options.
1982 static void parse_options(char *options
,
1988 char sep
, /* Separator character */
1989 *name
, /* Name of option */
1990 *value
; /* Value of option */
2009 while (*options
&& *options
!= '=' && *options
!= '+' && *options
!= '&')
2012 if ((sep
= *options
) != '\0')
2023 while (*options
&& *options
!= '+' && *options
!= '&')
2033 * Process the option...
2036 if (!_cups_strcasecmp(name
, "waiteof"))
2038 if (!_cups_strcasecmp(value
, "on") ||
2039 !_cups_strcasecmp(value
, "yes") ||
2040 !_cups_strcasecmp(value
, "true"))
2042 else if (!_cups_strcasecmp(value
, "off") ||
2043 !_cups_strcasecmp(value
, "no") ||
2044 !_cups_strcasecmp(value
, "false"))
2047 _cupsLangPrintFilter(stderr
, "WARNING",
2048 _("Boolean expected for waiteof option \"%s\"."),
2051 else if (!_cups_strcasecmp(name
, "serial"))
2052 strlcpy(serial
, value
, serial_size
);
2053 else if (!_cups_strcasecmp(name
, "location") && location
)
2054 *location
= (UInt32
)strtoul(value
, NULL
, 16);
2060 * @function setup_cfLanguage
2061 * @abstract Convert the contents of the CUPS 'APPLE_LANGUAGE' environment
2062 * variable into a one element CF array of languages.
2064 * @discussion Each submitted job comes with a natural language. CUPS passes
2065 * that language in an environment variable. We take that language
2066 * and jam it into the AppleLanguages array so that CF will use
2067 * it when reading localized resources. We need to do this before
2068 * any CF code reads and caches the languages array, so this function
2069 * should be called early in main()
2071 static void setup_cfLanguage(void)
2073 CFStringRef lang
[1] = {NULL
};
2074 CFArrayRef langArray
= NULL
;
2075 const char *requestedLang
= NULL
;
2077 if ((requestedLang
= getenv("APPLE_LANGUAGE")) == NULL
)
2078 requestedLang
= getenv("LANG");
2080 if (requestedLang
!= NULL
)
2082 lang
[0] = CFStringCreateWithCString(kCFAllocatorDefault
, requestedLang
, kCFStringEncodingUTF8
);
2083 langArray
= CFArrayCreate(kCFAllocatorDefault
, (const void **)lang
, sizeof(lang
) / sizeof(lang
[0]), &kCFTypeArrayCallBacks
);
2085 CFPreferencesSetValue(CFSTR("AppleLanguages"), langArray
, kCFPreferencesCurrentApplication
, kCFPreferencesAnyUser
, kCFPreferencesAnyHost
);
2086 fprintf(stderr
, "DEBUG: usb: AppleLanguages=\"%s\"\n", requestedLang
);
2089 CFRelease(langArray
);
2092 fputs("DEBUG: usb: LANG and APPLE_LANGUAGE environment variables missing.\n", stderr
);
2096 #if defined(__i386__) || defined(__x86_64__)
2098 * @function run_legacy_backend
2100 * @abstract Starts child backend process running as a ppc or i386 executable.
2102 * @result Never returns; always calls exit().
2106 static void run_legacy_backend(int argc
,
2113 pid_t waitpid_status
;
2115 char *usb_legacy_status
;
2119 * If we're running as x86_64 or i386 and couldn't load the class driver
2120 * (because it's ppc or i386), then try to re-exec ourselves in ppc or i386
2121 * mode to try again. If we don't have a ppc or i386 architecture we may be
2122 * running with the same architecture again so guard against this by setting
2123 * and testing an environment variable...
2127 usb_legacy_status
= getenv("USB_I386_STATUS");
2129 usb_legacy_status
= getenv("USB_PPC_STATUS");
2130 # endif /* __x86_64__ */
2132 if (!usb_legacy_status
)
2134 log_usb_class_driver(IS_NOT_64BIT
);
2137 * Setup a SIGTERM handler then block it before forking...
2140 int err
; /* posix_spawn result */
2141 struct sigaction action
; /* POSIX signal action */
2142 sigset_t newmask
, /* New signal mask */
2143 oldmask
; /* Old signal mask */
2144 char usbpath
[1024]; /* Path to USB backend */
2145 const char *cups_serverbin
;/* Path to CUPS binaries */
2148 memset(&action
, 0, sizeof(action
));
2149 sigaddset(&action
.sa_mask
, SIGTERM
);
2150 action
.sa_handler
= sigterm_handler
;
2151 sigaction(SIGTERM
, &action
, NULL
);
2153 sigemptyset(&newmask
);
2154 sigaddset(&newmask
, SIGTERM
);
2155 sigprocmask(SIG_BLOCK
, &newmask
, &oldmask
);
2158 * Set the environment variable...
2162 setenv("USB_I386_STATUS", "1", false);
2164 setenv("USB_PPC_STATUS", "1", false);
2165 # endif /* __x86_64__ */
2168 * Tell the kernel to use the specified CPU architecture...
2172 cpu_type_t cpu
= CPU_TYPE_I386
;
2174 cpu_type_t cpu
= CPU_TYPE_POWERPC
;
2175 # endif /* __x86_64__ */
2177 posix_spawnattr_t attrs
;
2179 if (!posix_spawnattr_init(&attrs
))
2181 posix_spawnattr_setsigdefault(&attrs
, &oldmask
);
2182 if (posix_spawnattr_setbinpref_np(&attrs
, 1, &cpu
, &ocount
) || ocount
!= 1)
2185 perror("DEBUG: Unable to set binary preference to i386");
2187 perror("DEBUG: Unable to set binary preference to ppc");
2188 # endif /* __x86_64__ */
2189 _cupsLangPrintFilter(stderr
, "ERROR",
2190 _("Unable to use legacy USB class driver."));
2191 exit(CUPS_BACKEND_STOP
);
2196 * Set up the arguments and call posix_spawn...
2199 if ((cups_serverbin
= getenv("CUPS_SERVERBIN")) == NULL
)
2200 cups_serverbin
= CUPS_SERVERBIN
;
2201 snprintf(usbpath
, sizeof(usbpath
), "%s/backend/usb", cups_serverbin
);
2203 for (i
= 0; i
< argc
&& i
< (int)(sizeof(my_argv
) / sizeof(my_argv
[0])) - 1; i
++)
2204 my_argv
[i
] = argv
[i
];
2208 if ((err
= posix_spawn(&child_pid
, usbpath
, NULL
, &attrs
, my_argv
,
2211 fprintf(stderr
, "DEBUG: Unable to exec %s: %s\n", usbpath
,
2213 _cupsLangPrintFilter(stderr
, "ERROR",
2214 _("Unable to use legacy USB class driver."));
2215 exit(CUPS_BACKEND_STOP
);
2219 * Unblock signals...
2222 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
2225 * Close the fds we won't be using then wait for the child backend to exit.
2231 fprintf(stderr
, "DEBUG: Started usb(legacy) backend (PID %d)\n",
2234 while ((waitpid_status
= waitpid(child_pid
, &childstatus
, 0)) == (pid_t
)-1 && errno
== EINTR
)
2237 if (WIFSIGNALED(childstatus
))
2239 exitstatus
= CUPS_BACKEND_STOP
;
2240 fprintf(stderr
, "DEBUG: usb(legacy) backend %d crashed on signal %d\n",
2241 child_pid
, WTERMSIG(childstatus
));
2245 if ((exitstatus
= WEXITSTATUS(childstatus
)) != 0)
2247 "DEBUG: usb(legacy) backend %d stopped with status %d\n",
2248 child_pid
, exitstatus
);
2250 fprintf(stderr
, "DEBUG: usb(legacy) backend %d exited with no errors\n",
2256 fputs("DEBUG: usb(legacy) backend running native again\n", stderr
);
2257 exitstatus
= CUPS_BACKEND_STOP
;
2262 #endif /* __i386__ || __x86_64__ */
2266 * 'sigterm_handler()' - SIGTERM handler.
2270 sigterm_handler(int sig
) /* I - Signal */
2272 #if defined(__i386__) || defined(__x86_64__)
2274 * If we started a child process pass the signal on to it...
2280 * If we started a child process pass the signal on to it...
2285 kill(child_pid
, sig
);
2286 while (waitpid(child_pid
, &status
, 0) < 0 && errno
== EINTR
);
2288 if (WIFEXITED(status
))
2289 _exit(WEXITSTATUS(status
));
2290 else if (status
== SIGTERM
|| status
== SIGKILL
)
2294 write(2, "DEBUG: Child crashed.\n", 22);
2295 _exit(CUPS_BACKEND_STOP
);
2298 #endif /* __i386__ || __x86_64__ */
2303 * 'sigquit_handler()' - SIGQUIT handler.
2306 static void sigquit_handler(int sig
, siginfo_t
*si
, void *unused
)
2309 char pathbuf
[PROC_PIDPATHINFO_MAXSIZE
];
2310 static char msgbuf
[256] = "";
2316 if (proc_pidpath(si
->si_pid
, pathbuf
, sizeof(pathbuf
)) > 0 &&
2317 (path
= basename(pathbuf
)) != NULL
)
2318 snprintf(msgbuf
, sizeof(msgbuf
), "SIGQUIT sent by %s(%d)", path
, (int)si
->si_pid
);
2320 snprintf(msgbuf
, sizeof(msgbuf
), "SIGQUIT sent by PID %d", (int)si
->si_pid
);
2322 CRSetCrashLogMessage(msgbuf
);
2328 #ifdef PARSE_PS_ERRORS
2330 * 'next_line()' - Find the next line in a buffer.
2333 static const char *next_line (const char *buffer
)
2335 const char *cptr
, *lptr
= NULL
;
2337 for (cptr
= buffer
; *cptr
&& lptr
== NULL
; cptr
++)
2338 if (*cptr
== '\n' || *cptr
== '\r')
2345 * 'parse_pserror()' - Scan the backchannel data for postscript errors.
2348 static void parse_pserror(char *sockBuffer
,
2351 static char gErrorBuffer
[1024] = "";
2352 static char *gErrorBufferPtr
= gErrorBuffer
;
2353 static char *gErrorBufferEndPtr
= gErrorBuffer
+ sizeof(gErrorBuffer
);
2355 char *pCommentBegin
, *pCommentEnd
, *pLineEnd
;
2360 if (gErrorBufferPtr
+ len
> gErrorBufferEndPtr
- 1)
2361 gErrorBufferPtr
= gErrorBuffer
;
2362 if (len
> sizeof(gErrorBuffer
) - 1)
2363 len
= sizeof(gErrorBuffer
) - 1;
2365 memcpy(gErrorBufferPtr
, (const void *)sockBuffer
, len
);
2366 gErrorBufferPtr
+= len
;
2367 *(gErrorBufferPtr
+ 1) = '\0';
2369 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
2370 while (pLineEnd
!= NULL
)
2374 pCommentBegin
= strstr(gErrorBuffer
,"%%[");
2375 pCommentEnd
= strstr(gErrorBuffer
, "]%%");
2376 if (pCommentBegin
!= gErrorBuffer
&& pCommentEnd
!= NULL
)
2378 pCommentEnd
+= 3; /* Skip past "]%%" */
2379 *pCommentEnd
= '\0'; /* There's always room for the nul */
2381 if (_cups_strncasecmp(pCommentBegin
, "%%[ Error:", 10) == 0)
2383 else if (_cups_strncasecmp(pCommentBegin
, "%%[ Flushing", 12) == 0)
2388 if ((logstrlen
= snprintf(logstr
, sizeof(logstr
), "%s: %s\n", logLevel
, pCommentBegin
)) >= sizeof(logstr
))
2390 /* If the string was trucnated make sure it has a linefeed before the nul */
2391 logstrlen
= sizeof(logstr
) - 1;
2392 logstr
[logstrlen
- 1] = '\n';
2394 write(STDERR_FILENO
, logstr
, logstrlen
);
2397 /* move everything over... */
2398 strlcpy(gErrorBuffer
, pLineEnd
, sizeof(gErrorBuffer
));
2399 gErrorBufferPtr
= gErrorBuffer
;
2400 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
2403 #endif /* PARSE_PS_ERRORS */
2407 * 'soft_reset()' - Send a soft reset to the device.
2410 static void soft_reset(void)
2412 fd_set input_set
; /* Input set for select() */
2413 struct timeval tv
; /* Time value */
2414 char buffer
[2048]; /* Buffer */
2415 struct timespec cond_timeout
; /* pthread condition timeout */
2418 * Send an abort once a second until the I/O lock is released by the main thread...
2421 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2422 while (g
.readwrite_lock
)
2424 (*g
.classdriver
)->Abort(g
.classdriver
);
2426 gettimeofday(&tv
, NULL
);
2427 cond_timeout
.tv_sec
= tv
.tv_sec
+ 1;
2428 cond_timeout
.tv_nsec
= tv
.tv_usec
* 1000;
2430 while (g
.readwrite_lock
)
2432 if (pthread_cond_timedwait(&g
.readwrite_lock_cond
,
2433 &g
.readwrite_lock_mutex
,
2434 &cond_timeout
) != 0)
2439 g
.readwrite_lock
= 1;
2440 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2443 * Flush bytes waiting on print_fd...
2448 FD_ZERO(&input_set
);
2449 FD_SET(g
.print_fd
, &input_set
);
2454 while (select(g
.print_fd
+1, &input_set
, NULL
, NULL
, &tv
) > 0)
2455 if (read(g
.print_fd
, buffer
, sizeof(buffer
)) <= 0)
2462 (*g
.classdriver
)->SoftReset(g
.classdriver
, DEFAULT_TIMEOUT
);
2465 * Release the I/O lock...
2468 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2469 g
.readwrite_lock
= 0;
2470 pthread_cond_signal(&g
.readwrite_lock_cond
);
2471 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2476 * 'get_device_id()' - Return IEEE-1284 device ID.
2479 static void get_device_id(cups_sc_status_t
*status
,
2483 CFStringRef deviceIDString
= NULL
;
2485 if (g
.printer_obj
!= IO_OBJECT_NULL
)
2487 printer_interface_t printerIntf
= usb_printer_interface_interface(g
.printer_obj
);
2490 deviceIDString
= copy_printer_interface_deviceid(printerIntf
, g
.alternateSetting
);
2491 (*printerIntf
)->Release(printerIntf
);
2498 if (CFStringGetCString(deviceIDString
, data
, *datalen
, kCFStringEncodingUTF8
))
2499 *datalen
= (int)strlen(data
);
2503 CFRelease(deviceIDString
);
2510 *status
= CUPS_SC_STATUS_OK
;
2515 log_usb_class_driver(int is_64bit
) /* I - Is the USB class driver 64-bit? */
2518 * Report the usage of legacy USB class drivers to Apple if the user opts into providing
2519 * feedback to Apple...
2522 aslmsg aslm
= asl_new(ASL_TYPE_MSG
);
2525 ppd_file_t
*ppd
= ppdOpenFile(getenv("PPD"));
2526 const char *make_model
= ppd
? ppd
->nickname
: NULL
;
2527 ppd_attr_t
*version
= ppdFindAttr(ppd
, "FileVersion", "");
2529 asl_set(aslm
, "com.apple.message.domain", "com.apple.printing.usb.64bit");
2530 asl_set(aslm
, "com.apple.message.result", is_64bit
? "yes" : "no");
2531 asl_set(aslm
, "com.apple.message.signature", make_model
? make_model
: "Unknown");
2532 asl_set(aslm
, "com.apple.message.signature2", version
? version
->value
: "?.?");
2533 asl_set(aslm
, "com.apple.message.summarize", "YES");
2534 asl_log(NULL
, aslm
, ASL_LEVEL_NOTICE
, "");