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 "backend-private.h"
67 #include <CoreFoundation/CoreFoundation.h>
68 #include <IOKit/usb/IOUSBLib.h>
69 #include <IOKit/IOCFPlugIn.h>
76 * Include necessary headers.
79 extern char **environ
;
83 * DEBUG_WRITES, if defined, causes the backend to write data to the printer in
84 * 512 byte increments, up to 8192 bytes, to make debugging with a USB bus
88 #define DEBUG_WRITES 0
91 * WAIT_EOF_DELAY is number of seconds we'll wait for responses from
92 * the printer after we've finished sending all the data
94 #define WAIT_EOF_DELAY 7
95 #define WAIT_SIDE_DELAY 3
96 #define DEFAULT_TIMEOUT 5000L
98 #define USB_INTERFACE_KIND CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID245)
99 #define kUSBLanguageEnglish 0x409
101 #define PRINTER_POLLING_INTERVAL 5 /* seconds */
102 #define INITIAL_LOG_INTERVAL PRINTER_POLLING_INTERVAL
103 #define SUBSEQUENT_LOG_INTERVAL 3 * INITIAL_LOG_INTERVAL
105 #define kUSBPrinterClassTypeID CFUUIDGetConstantUUIDWithBytes(NULL, 0x06, 0x04, 0x7D, 0x16, 0x53, 0xA2, 0x11, 0xD6, 0x92, 0x06, 0x00, 0x30, 0x65, 0x52, 0x45, 0x92)
106 #define kUSBPrinterClassInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, 0x03, 0x34, 0x6D, 0x74, 0x53, 0xA3, 0x11, 0xD6, 0x9E, 0xA1, 0x76, 0x30, 0x65, 0x52, 0x45, 0x92)
108 #define kUSBClassDriverProperty CFSTR("USB Printing Class")
110 #define kUSBGenericTOPrinterClassDriver CFSTR("/System/Library/Printers/Libraries/USBGenericPrintingClass.plugin")
111 #define kUSBPrinterClassDeviceNotOpen -9664 /*kPMInvalidIOMContext*/
113 #define CRSetCrashLogMessage(m) _crc_make_setter(message, m)
114 #define _crc_make_setter(attr, arg) (gCRAnnotations.attr = (uint64_t)(unsigned long)(arg))
115 #define CRASH_REPORTER_CLIENT_HIDDEN __attribute__((visibility("hidden")))
116 #define CRASHREPORTER_ANNOTATIONS_VERSION 4
117 #define CRASHREPORTER_ANNOTATIONS_SECTION "__crash_info"
119 struct crashreporter_annotations_t
{
120 uint64_t version
; // unsigned long
121 uint64_t message
; // char *
122 uint64_t signature_string
; // char *
123 uint64_t backtrace
; // char *
124 uint64_t message2
; // char *
125 uint64_t thread
; // uint64_t
126 uint64_t dialog_mode
; // unsigned int
129 CRASH_REPORTER_CLIENT_HIDDEN
130 struct crashreporter_annotations_t gCRAnnotations
131 __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION
)))
132 = { CRASHREPORTER_ANNOTATIONS_VERSION
, 0, 0, 0, 0, 0, 0 };
135 * Section 5.3 USB Printing Class spec
137 #define kUSBPrintingSubclass 1
138 #define kUSBPrintingProtocolNoOpen 0
139 #define kUSBPrintingProtocolUnidirectional 1
140 #define kUSBPrintingProtocolBidirectional 2
141 #define kUSBPrintingProtocolIPP 4
143 typedef IOUSBInterfaceInterface245
**printer_interface_t
;
145 typedef struct iodevice_request_s
/**** Device request ****/
153 } iodevice_request_t
;
155 typedef union /**** Centronics status byte ****/
160 unsigned reserved0
:2;
161 unsigned paperError
:1;
164 unsigned reserved1
:3;
166 } centronics_status_t
;
168 typedef struct classdriver_s
/**** g.classdriver context ****/
171 CFPlugInRef plugin
; /* release plugin */
172 IUnknownVTbl
**factory
; /* Factory */
173 void *vendorReference
; /* vendor class specific usage */
174 UInt32 location
; /* unique location in bus topology */
175 UInt8 interfaceNumber
; /* Interface number */
176 UInt16 vendorID
; /* Vendor id */
177 UInt16 productID
; /* Product id */
178 printer_interface_t interface
; /* identify the device to IOKit */
179 UInt8 outpipe
; /* mandatory bulkOut pipe */
180 UInt8 inpipe
; /* optional bulkIn pipe */
182 /* general class requests */
183 kern_return_t (*DeviceRequest
)(struct classdriver_s
**printer
, iodevice_request_t
*iorequest
, UInt16 timeout
);
184 kern_return_t (*GetString
)(struct classdriver_s
**printer
, UInt8 whichString
, UInt16 language
, UInt16 timeout
, CFStringRef
*result
);
186 /* standard printer class requests */
187 kern_return_t (*SoftReset
)(struct classdriver_s
**printer
, UInt16 timeout
);
188 kern_return_t (*GetCentronicsStatus
)(struct classdriver_s
**printer
, centronics_status_t
*result
, UInt16 timeout
);
189 kern_return_t (*GetDeviceID
)(struct classdriver_s
**printer
, CFStringRef
*devid
, UInt16 timeout
);
191 /* standard bulk device requests */
192 kern_return_t (*ReadPipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
);
193 kern_return_t (*WritePipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
, Boolean eoj
);
195 /* interface requests */
196 kern_return_t (*Open
)(struct classdriver_s
**printer
, UInt32 location
, UInt8 protocol
);
197 kern_return_t (*Abort
)(struct classdriver_s
**printer
);
198 kern_return_t (*Close
)(struct classdriver_s
**printer
);
200 /* initialize and terminate */
201 kern_return_t (*Initialize
)(struct classdriver_s
**printer
, struct classdriver_s
**baseclass
);
202 kern_return_t (*Terminate
)(struct classdriver_s
**printer
);
206 typedef Boolean (*iterator_callback_t
)(void *refcon
, io_service_t obj
, CFStringRef deviceIDString
, UInt32 deviceLocation
, UInt8 interfaceNum
, UInt8 alternateSetting
);
208 typedef struct iterator_reference_s
/**** Iterator reference data */
210 iterator_callback_t callback
;
213 } iterator_reference_t
;
215 typedef struct globals_s
217 io_service_t printer_obj
;
218 classdriver_t
**classdriver
;
220 pthread_mutex_t read_thread_mutex
;
221 pthread_cond_t read_thread_cond
;
222 int read_thread_stop
;
223 int read_thread_done
;
225 pthread_mutex_t readwrite_lock_mutex
;
226 pthread_cond_t readwrite_lock_cond
;
234 UInt8 alternateSetting
;
236 CFRunLoopTimerRef status_timer
;
238 int print_fd
; /* File descriptor to print */
239 ssize_t print_bytes
; /* Print bytes read */
241 ssize_t debug_bytes
; /* Current bytes to read */
242 #endif /* DEBUG_WRITES */
244 Boolean use_generic_class_driver
;
246 int drain_output
; /* Drain all pending output */
247 int bidi_flag
; /* 0=unidirectional, 1=bidirectional */
249 pthread_mutex_t sidechannel_thread_mutex
;
250 pthread_cond_t sidechannel_thread_cond
;
251 int sidechannel_thread_stop
;
252 int sidechannel_thread_done
;
260 globals_t g
= { 0 }; /* Globals */
261 int Iterating
= 0; /* Are we iterating the bus? */
268 static Boolean
find_device_cb(void *refcon
, io_service_t obj
, CFStringRef deviceIDString
, UInt32 deviceLocation
, UInt8 interfaceNum
, UInt8 alternateSetting
);
269 static Boolean
list_device_cb(void *refcon
, io_service_t obj
, CFStringRef deviceIDString
, UInt32 deviceLocation
, UInt8 interfaceNum
, UInt8 alternateSetting
);
271 static CFStringRef
cfstr_create_trim(const char *cstr
);
272 static CFStringRef
copy_value_for_key(CFStringRef deviceID
, CFStringRef
*keys
);
273 static kern_return_t
load_classdriver(CFStringRef driverPath
, printer_interface_t interface
, classdriver_t
***printerDriver
);
274 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
);
275 static kern_return_t
registry_close(void);
276 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
);
277 static kern_return_t
unload_classdriver(classdriver_t
***classdriver
);
279 static void *read_thread(void *reference
);
280 static void *sidechannel_thread(void *reference
);
281 static void device_added(void *userdata
, io_iterator_t iterator
);
282 static void get_device_id(cups_sc_status_t
*status
, char *data
, int *datalen
);
283 static void iterate_printers(iterator_callback_t callBack
, void *userdata
);
284 static void parse_options(char *options
, char *serial
, int serial_size
, UInt32
*location
, Boolean
*wait_eof
);
285 static void setup_cfLanguage(void);
286 static void soft_reset(void);
287 static void status_timer_cb(CFRunLoopTimerRef timer
, void *info
);
288 static void log_usb_class_driver(int is_64bit
);
290 #define IS_NOT_64BIT 0
292 #if defined(__i386__) || defined(__x86_64__)
293 static pid_t child_pid
; /* Child PID */
294 static void run_legacy_backend(int argc
, char *argv
[], int fd
) __attribute__((noreturn
)); /* Starts child backend process running as a ppc executable */
295 #endif /* __i386__ || __x86_64__ */
296 static void sigterm_handler(int sig
); /* SIGTERM handler */
297 static void sigquit_handler(int sig
, siginfo_t
*si
, void *unused
) __attribute__((noreturn
));
299 #ifdef PARSE_PS_ERRORS
300 static const char *next_line (const char *buffer
);
301 static void parse_pserror (char *sockBuffer
, int len
);
302 #endif /* PARSE_PS_ERRORS */
304 static printer_interface_t
usb_printer_interface_interface(io_service_t usbClass
);
305 static IOUSBDeviceInterface
**usb_device_interface_for_device(io_service_t usbDevice
);
306 static CFStringRef
copy_printer_interface_deviceid(printer_interface_t printer
, UInt8 alternateSetting
);
307 static CFStringRef
copy_printer_interface_indexed_description(printer_interface_t printer
, UInt8 index
, UInt16 language
);
308 static CFStringRef
deviceIDCopyManufacturer(CFStringRef deviceID
);
309 static CFStringRef
deviceIDCopyModel(CFStringRef deviceID
);
310 static CFStringRef
deviceIDCopySerialNumber(CFStringRef deviceID
);
315 * 'list_devices()' - List all USB devices.
320 iterate_printers(list_device_cb
, NULL
);
325 * 'print_device()' - Print a file to a USB device.
328 int /* O - Exit status */
329 print_device(const char *uri
, /* I - Device URI */
330 const char *hostname
, /* I - Hostname/manufacturer */
331 const char *resource
, /* I - Resource/modelname */
332 char *options
, /* I - Device options/serial number */
333 int print_fd
, /* I - File descriptor to print */
334 int copies
, /* I - Copies to print */
335 int argc
, /* I - Number of command-line arguments (6 or 7) */
336 char *argv
[]) /* I - Command-line arguments */
338 char serial
[1024]; /* Serial number buffer */
339 OSStatus status
; /* Function results */
340 IOReturn iostatus
; /* Current IO status */
341 pthread_t read_thread_id
, /* Read thread */
342 sidechannel_thread_id
;/* Side-channel thread */
343 int have_sidechannel
= 0; /* Was the side-channel thread started? */
344 struct stat sidechannel_info
; /* Side-channel file descriptor info */
345 char print_buffer
[8192], /* Print data buffer */
346 *print_ptr
; /* Pointer into print data buffer */
347 UInt32 location
; /* Unique location in bus topology */
348 fd_set input_set
; /* Input set for select() */
349 CFStringRef driverBundlePath
; /* Class driver path */
350 int countdown
, /* Logging interval */
351 nfds
; /* Number of file descriptors */
352 ssize_t total_bytes
; /* Total bytes written */
353 UInt32 bytes
; /* Bytes written */
354 struct timeval
*timeout
, /* Timeout pointer */
356 struct timespec cond_timeout
; /* pthread condition timeout */
357 struct sigaction action
; /* Actions for POSIX signals */
363 * Catch SIGQUIT to determine who is sending it...
366 memset(&action
, 0, sizeof(action
));
367 action
.sa_sigaction
= sigquit_handler
;
368 action
.sa_flags
= SA_SIGINFO
;
369 sigaction(SIGQUIT
, &action
, NULL
);
372 * See if the side-channel descriptor is valid...
375 have_sidechannel
= !fstat(CUPS_SC_FD
, &sidechannel_info
) &&
376 S_ISSOCK(sidechannel_info
.st_mode
);
379 * Localize using CoreFoundation...
384 parse_options(options
, serial
, sizeof(serial
), &location
, &g
.wait_eof
);
386 if (resource
[0] == '/')
389 g
.print_fd
= print_fd
;
390 g
.make
= cfstr_create_trim(hostname
);
391 g
.model
= cfstr_create_trim(resource
);
392 g
.serial
= cfstr_create_trim(serial
);
393 g
.location
= location
;
395 if (!g
.make
|| !g
.model
)
397 fprintf(stderr
, "DEBUG: Fatal USB error.\n");
398 _cupsLangPrintFilter(stderr
, "ERROR",
399 _("There was an unrecoverable USB error."));
402 fputs("DEBUG: USB make string is NULL\n", stderr
);
404 fputs("DEBUG: USB model string is NULL\n", stderr
);
406 return (CUPS_BACKEND_STOP
);
409 fputs("STATE: +connecting-to-device\n", stderr
);
411 countdown
= INITIAL_LOG_INTERVAL
;
417 IOObjectRelease(g
.printer_obj
);
418 unload_classdriver(&g
.classdriver
);
423 fprintf(stderr
, "DEBUG: Looking for '%s %s'\n", hostname
, resource
);
425 iterate_printers(find_device_cb
, NULL
);
427 fputs("DEBUG: Opening connection\n", stderr
);
429 driverBundlePath
= NULL
;
431 status
= registry_open(&driverBundlePath
);
433 #if defined(__i386__) || defined(__x86_64__)
435 * If we were unable to load the class drivers for this printer it's
436 * probably because they're ppc or i386. In this case try to run this
437 * backend as i386 or ppc executables so we can use them...
441 run_legacy_backend(argc
, argv
, print_fd
);
442 /* Never returns here */
444 #endif /* __i386__ || __x86_64__ */
449 * If we still were unable to load the class drivers for this printer log
450 * the error and stop the queue...
453 if (driverBundlePath
== NULL
|| !CFStringGetCString(driverBundlePath
, print_buffer
, sizeof(print_buffer
), kCFStringEncodingUTF8
))
454 strlcpy(print_buffer
, "USB class driver", sizeof(print_buffer
));
456 fputs("STATE: +apple-missing-usbclassdriver-error\n", stderr
);
457 _cupsLangPrintFilter(stderr
, "ERROR",
458 _("There was an unrecoverable USB error."));
459 fprintf(stderr
, "DEBUG: Could not load %s\n", print_buffer
);
461 if (driverBundlePath
)
462 CFRelease(driverBundlePath
);
464 return (CUPS_BACKEND_STOP
);
468 if (status
== noErr
&& driverBundlePath
!= NULL
&& CFStringCompare(driverBundlePath
, kUSBGenericTOPrinterClassDriver
, 0) != kCFCompareEqualTo
)
469 log_usb_class_driver(IS_64BIT
);
470 #endif /* __x86_64__ */
472 if (driverBundlePath
)
473 CFRelease(driverBundlePath
);
477 sleep(PRINTER_POLLING_INTERVAL
);
478 countdown
-= PRINTER_POLLING_INTERVAL
;
481 _cupsLangPrintFilter(stderr
, "INFO",
482 _("Waiting for printer to become available."));
483 fprintf(stderr
, "DEBUG: USB printer status: 0x%08x\n", (int)status
);
484 countdown
= SUBSEQUENT_LOG_INTERVAL
; /* subsequent log entries, every 15 seconds */
487 } while (status
!= noErr
);
489 fputs("STATE: -connecting-to-device\n", stderr
);
492 * Now that we are "connected" to the port, ignore SIGTERM so that we
493 * can finish out any page data the driver sends (e.g. to eject the
494 * current page... Only ignore SIGTERM if we are printing data from
495 * stdin (otherwise you can't cancel raw jobs...)
500 memset(&action
, 0, sizeof(action
));
502 sigemptyset(&action
.sa_mask
);
503 action
.sa_handler
= SIG_IGN
;
504 sigaction(SIGTERM
, &action
, NULL
);
508 * Start the side channel thread if the descriptor is valid...
511 pthread_mutex_init(&g
.readwrite_lock_mutex
, NULL
);
512 pthread_cond_init(&g
.readwrite_lock_cond
, NULL
);
513 g
.readwrite_lock
= 1;
515 if (have_sidechannel
)
517 g
.sidechannel_thread_stop
= 0;
518 g
.sidechannel_thread_done
= 0;
520 pthread_cond_init(&g
.sidechannel_thread_cond
, NULL
);
521 pthread_mutex_init(&g
.sidechannel_thread_mutex
, NULL
);
523 if (pthread_create(&sidechannel_thread_id
, NULL
, sidechannel_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 side-channel thread\n", stderr
);
530 return (CUPS_BACKEND_STOP
);
535 * Get the read thread going...
538 g
.read_thread_stop
= 0;
539 g
.read_thread_done
= 0;
541 pthread_cond_init(&g
.read_thread_cond
, NULL
);
542 pthread_mutex_init(&g
.read_thread_mutex
, NULL
);
544 if (pthread_create(&read_thread_id
, NULL
, read_thread
, NULL
))
546 fprintf(stderr
, "DEBUG: Fatal USB error.\n");
547 _cupsLangPrintFilter(stderr
, "ERROR",
548 _("There was an unrecoverable USB error."));
549 fputs("DEBUG: Couldn't create read thread\n", stderr
);
551 return (CUPS_BACKEND_STOP
);
555 * The main thread sends the print file...
561 print_ptr
= print_buffer
;
563 while (status
== noErr
&& copies
-- > 0)
565 _cupsLangPrintFilter(stderr
, "INFO", _("Sending data to printer."));
567 if (print_fd
!= STDIN_FILENO
)
569 fputs("PAGE: 1 1\n", stderr
);
570 lseek(print_fd
, 0, SEEK_SET
);
573 while (status
== noErr
)
578 FD_SET(print_fd
, &input_set
);
581 * Calculate select timeout...
582 * If we have data waiting to send timeout is 100ms.
583 * else if we're draining print_fd timeout is 0.
584 * else we're waiting forever...
590 tv
.tv_usec
= 100000; /* 100ms */
593 else if (g
.drain_output
)
603 * I/O is unlocked around select...
606 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
607 g
.readwrite_lock
= 0;
608 pthread_cond_signal(&g
.readwrite_lock_cond
);
609 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
611 nfds
= select(print_fd
+ 1, &input_set
, NULL
, NULL
, timeout
);
614 * Reacquire the lock...
617 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
618 while (g
.readwrite_lock
)
619 pthread_cond_wait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
);
620 g
.readwrite_lock
= 1;
621 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
625 if (errno
== EINTR
&& total_bytes
== 0)
627 fputs("DEBUG: Received an interrupt before any bytes were "
628 "written, aborting\n", stderr
);
630 return (CUPS_BACKEND_OK
);
632 else if (errno
!= EAGAIN
&& errno
!= EINTR
)
634 _cupsLangPrintFilter(stderr
, "ERROR",
635 _("Unable to read print data."));
636 perror("DEBUG: select");
638 return (CUPS_BACKEND_FAILED
);
643 * If drain output has finished send a response...
646 if (g
.drain_output
&& !nfds
&& !g
.print_bytes
)
648 /* Send a response... */
649 cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
654 * Check if we have print data ready...
657 if (FD_ISSET(print_fd
, &input_set
))
660 g
.debug_bytes
+= 512;
661 if (g
.debug_bytes
> sizeof(print_buffer
))
664 g
.print_bytes
= read(print_fd
, print_buffer
, g
.debug_bytes
);
667 g
.print_bytes
= read(print_fd
, print_buffer
, sizeof(print_buffer
));
668 #endif /* DEBUG_WRITES */
670 if (g
.print_bytes
< 0)
673 * Read error - bail if we don't see EAGAIN or EINTR...
676 if (errno
!= EAGAIN
&& errno
!= EINTR
)
678 _cupsLangPrintFilter(stderr
, "ERROR",
679 _("Unable to read print data."));
680 perror("DEBUG: read");
682 return (CUPS_BACKEND_FAILED
);
687 else if (g
.print_bytes
== 0)
690 * End of file, break out of the loop...
696 print_ptr
= print_buffer
;
698 fprintf(stderr
, "DEBUG: Read %d bytes of print data...\n",
704 bytes
= (UInt32
)g
.print_bytes
;
705 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
708 * Ignore timeout errors, but retain the number of bytes written to
709 * avoid sending duplicate data...
712 if (iostatus
== kIOUSBTransactionTimeout
)
714 fputs("DEBUG: Got USB transaction timeout during write\n", stderr
);
719 * If we've stalled, retry the write...
722 else if (iostatus
== kIOUSBPipeStalled
)
724 fputs("DEBUG: Got USB pipe stalled during write\n", stderr
);
726 bytes
= (UInt32
)g
.print_bytes
;
727 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
731 * Retry a write after an aborted write since we probably just got
735 else if (iostatus
== kIOReturnAborted
)
737 fputs("DEBUG: Got USB return aborted during write\n", stderr
);
739 IOReturn err
= (*g
.classdriver
)->Abort(g
.classdriver
);
740 fprintf(stderr
, "DEBUG: USB class driver Abort returned %x\n", err
);
744 #endif /* DEBUG_WRITES */
746 bytes
= (UInt32
)g
.print_bytes
;
747 iostatus
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
753 * Write error - bail if we don't see an error we can retry...
756 _cupsLangPrintFilter(stderr
, "ERROR",
757 _("Unable to send data to printer."));
758 fprintf(stderr
, "DEBUG: USB class driver WritePipe returned %x\n",
761 IOReturn err
= (*g
.classdriver
)->Abort(g
.classdriver
);
762 fprintf(stderr
, "DEBUG: USB class driver Abort returned %x\n",
765 status
= CUPS_BACKEND_FAILED
;
770 fprintf(stderr
, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes
);
772 g
.print_bytes
-= bytes
;
774 total_bytes
+= bytes
;
778 if (print_fd
!= 0 && status
== noErr
)
779 fprintf(stderr
, "DEBUG: Sending print file, %lld bytes...\n",
784 fprintf(stderr
, "DEBUG: Sent %lld bytes...\n", (off_t
)total_bytes
);
785 fputs("STATE: +cups-waiting-for-job-completed\n", stderr
);
788 * Signal the side channel thread to exit...
791 if (have_sidechannel
)
794 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
795 g
.readwrite_lock
= 0;
796 pthread_cond_signal(&g
.readwrite_lock_cond
);
797 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
799 g
.sidechannel_thread_stop
= 1;
800 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
802 if (!g
.sidechannel_thread_done
)
804 gettimeofday(&tv
, NULL
);
805 cond_timeout
.tv_sec
= tv
.tv_sec
+ WAIT_SIDE_DELAY
;
806 cond_timeout
.tv_nsec
= tv
.tv_usec
* 1000;
808 while (!g
.sidechannel_thread_done
)
810 if (pthread_cond_timedwait(&g
.sidechannel_thread_cond
,
811 &g
.sidechannel_thread_mutex
,
817 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
821 * Signal the read thread to exit then wait 7 seconds for it to complete...
824 g
.read_thread_stop
= 1;
826 pthread_mutex_lock(&g
.read_thread_mutex
);
828 if (!g
.read_thread_done
)
830 fputs("DEBUG: Waiting for read thread to exit...\n", stderr
);
832 gettimeofday(&tv
, NULL
);
833 cond_timeout
.tv_sec
= tv
.tv_sec
+ WAIT_EOF_DELAY
;
834 cond_timeout
.tv_nsec
= tv
.tv_usec
* 1000;
836 while (!g
.read_thread_done
)
838 if (pthread_cond_timedwait(&g
.read_thread_cond
, &g
.read_thread_mutex
,
844 * If it didn't exit abort the pending read and wait an additional second...
847 if (!g
.read_thread_done
)
849 fputs("DEBUG: Read thread still active, aborting the pending read...\n",
854 (*g
.classdriver
)->Abort(g
.classdriver
);
856 gettimeofday(&tv
, NULL
);
857 cond_timeout
.tv_sec
= tv
.tv_sec
+ 1;
858 cond_timeout
.tv_nsec
= tv
.tv_usec
* 1000;
860 while (!g
.read_thread_done
)
862 if (pthread_cond_timedwait(&g
.read_thread_cond
, &g
.read_thread_mutex
,
869 pthread_mutex_unlock(&g
.read_thread_mutex
);
872 * Close the connection and input file and general clean up...
877 if (print_fd
!= STDIN_FILENO
)
886 if (g
.serial
!= NULL
)
889 if (g
.printer_obj
!= 0x0)
890 IOObjectRelease(g
.printer_obj
);
897 * 'read_thread()' - Thread to read the backchannel data on.
900 static void *read_thread(void *reference
)
902 UInt8 readbuffer
[512];
904 kern_return_t readstatus
;
905 struct mach_timebase_info timeBaseInfo
;
912 /* Calculate what 250 milliSeconds are in mach absolute time...
914 mach_timebase_info(&timeBaseInfo
);
915 delay
= ((uint64_t)250000000 * (uint64_t)timeBaseInfo
.denom
) / (uint64_t)timeBaseInfo
.numer
;
920 * Remember when we started so we can throttle the loop after the read call...
923 start
= mach_absolute_time();
925 rbytes
= sizeof(readbuffer
);
926 readstatus
= (*g
.classdriver
)->ReadPipe(g
.classdriver
, readbuffer
, &rbytes
);
927 if (readstatus
== kIOReturnSuccess
&& rbytes
> 0)
929 fprintf(stderr
, "DEBUG: Read %d bytes of back-channel data...\n",
931 cupsBackChannelWrite((char*)readbuffer
, rbytes
, 1.0);
933 /* cntrl-d is echoed by the printer.
935 * Xerox Phaser 6250D doesn't echo the cntrl-d.
936 * Xerox Phaser 6250D doesn't always send the product query.
938 if (g
.wait_eof
&& readbuffer
[rbytes
-1] == 0x4)
941 #ifdef PARSE_PS_ERRORS
942 parse_pserror(readbuffer
, rbytes
);
945 else if (readstatus
== kIOUSBTransactionTimeout
)
946 fputs("DEBUG: Got USB transaction timeout during read\n", stderr
);
947 else if (readstatus
== kIOUSBPipeStalled
)
948 fputs("DEBUG: Got USB pipe stalled during read\n", stderr
);
949 else if (readstatus
== kIOReturnAborted
)
950 fputs("DEBUG: Got USB return aborted during read\n", stderr
);
953 * Make sure this loop executes no more than once every 250 miliseconds...
956 if ((readstatus
!= kIOReturnSuccess
|| rbytes
== 0) && (g
.wait_eof
|| !g
.read_thread_stop
))
957 mach_wait_until(start
+ delay
);
959 } while (g
.wait_eof
|| !g
.read_thread_stop
); /* Abort from main thread tests error here */
961 /* Workaround for usb race condition. <rdar://problem/21882551> */
962 if (!g
.wait_eof
&& g
.use_generic_class_driver
)
964 const char *pdl
= getenv("FINAL_CONTENT_TYPE");
965 if (pdl
&& strcmp(pdl
, "application/vnd.cups-postscript") == 0)
967 while (readstatus
== kIOReturnSuccess
&& ((rbytes
> 0 && readbuffer
[rbytes
-1] != 0x4) || rbytes
== 0))
969 start
= mach_absolute_time();
971 rbytes
= sizeof(readbuffer
);
972 readstatus
= (*g
.classdriver
)->ReadPipe(g
.classdriver
, readbuffer
, &rbytes
);
973 if (readstatus
== kIOReturnSuccess
&& rbytes
> 0 && readbuffer
[rbytes
-1] == 0x4)
976 /* Make sure this loop executes no more than once every 250 miliseconds... */
977 mach_wait_until(start
+ delay
);
983 * Let the main thread know that we have completed the read thread...
986 pthread_mutex_lock(&g
.read_thread_mutex
);
987 g
.read_thread_done
= 1;
988 pthread_cond_signal(&g
.read_thread_cond
);
989 pthread_mutex_unlock(&g
.read_thread_mutex
);
996 * 'sidechannel_thread()' - Handle side-channel requests.
1000 sidechannel_thread(void *reference
)
1002 cups_sc_command_t command
; /* Request command */
1003 cups_sc_status_t status
; /* Request/response status */
1004 char data
[2048]; /* Request/response data */
1005 int datalen
; /* Request/response data size */
1012 datalen
= sizeof(data
);
1014 if (cupsSideChannelRead(&command
, &status
, data
, &datalen
, 1.0))
1016 if (status
== CUPS_SC_STATUS_TIMEOUT
)
1024 case CUPS_SC_CMD_SOFT_RESET
: /* Do a soft reset */
1025 fputs("DEBUG: CUPS_SC_CMD_SOFT_RESET received from driver...\n",
1028 if ((*g
.classdriver
)->SoftReset
!= NULL
)
1031 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
1032 fputs("DEBUG: Returning status CUPS_STATUS_OK with no bytes...\n",
1037 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
1039 fputs("DEBUG: Returning status CUPS_STATUS_NOT_IMPLEMENTED with "
1040 "no bytes...\n", stderr
);
1044 case CUPS_SC_CMD_DRAIN_OUTPUT
: /* Drain all pending output */
1045 fputs("DEBUG: CUPS_SC_CMD_DRAIN_OUTPUT received from driver...\n",
1051 case CUPS_SC_CMD_GET_BIDI
: /* Is the connection bidirectional? */
1052 fputs("DEBUG: CUPS_SC_CMD_GET_BIDI received from driver...\n",
1055 data
[0] = (char)g
.bidi_flag
;
1056 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
1059 "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
1063 case CUPS_SC_CMD_GET_DEVICE_ID
: /* Return IEEE-1284 device ID */
1064 fputs("DEBUG: CUPS_SC_CMD_GET_DEVICE_ID received from driver...\n",
1067 datalen
= sizeof(data
);
1068 get_device_id(&status
, data
, &datalen
);
1069 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, datalen
, 1.0);
1071 if ((size_t)datalen
< sizeof(data
))
1072 data
[datalen
] = '\0';
1074 data
[sizeof(data
) - 1] = '\0';
1077 "DEBUG: Returning CUPS_SC_STATUS_OK with %d bytes (%s)...\n",
1081 case CUPS_SC_CMD_GET_STATE
: /* Return device state */
1082 fputs("DEBUG: CUPS_SC_CMD_GET_STATE received from driver...\n",
1085 data
[0] = CUPS_SC_STATE_ONLINE
;
1086 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
1089 "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
1094 fprintf(stderr
, "DEBUG: Unknown side-channel command (%d) received "
1095 "from driver...\n", command
);
1097 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
1100 fputs("DEBUG: Returned CUPS_SC_STATUS_NOT_IMPLEMENTED with no bytes...\n",
1105 while (!g
.sidechannel_thread_stop
);
1107 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
1108 g
.sidechannel_thread_done
= 1;
1109 pthread_cond_signal(&g
.sidechannel_thread_cond
);
1110 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
1118 * 'iterate_printers()' - Iterate over all the printers.
1121 static void iterate_printers(iterator_callback_t callBack
, void *userdata
)
1125 mach_port_t masterPort
= 0x0;
1126 kern_return_t kr
= IOMasterPort (bootstrap_port
, &masterPort
);
1128 if (kr
== kIOReturnSuccess
&& masterPort
!= 0x0)
1130 iterator_reference_t reference
= { callBack
, userdata
, true };
1132 IONotificationPortRef addNotification
= IONotificationPortCreate(masterPort
);
1133 io_iterator_t addIterator
= IO_OBJECT_NULL
;
1135 kr
= IOServiceAddMatchingNotification(addNotification
, kIOFirstMatchNotification
, IOServiceMatching(kIOUSBDeviceClassName
),
1136 &device_added
, &reference
, &addIterator
);
1137 if (kr
== kIOReturnSuccess
&& addIterator
!= IO_OBJECT_NULL
)
1139 device_added(&reference
, addIterator
);
1140 if (reference
.keepRunning
)
1142 CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification
), kCFRunLoopDefaultMode
);
1145 IOObjectRelease(addIterator
);
1147 mach_port_deallocate(mach_task_self(), masterPort
);
1155 * 'device_added()' - Device added notifier.
1157 #define IsPrintingInterface(c,s,p) ((c) == kUSBPrintingInterfaceClass && (s) == kUSBPrintingSubclass && (p) != kUSBPrintingProtocolIPP)
1159 static void device_added(void *userdata
, io_iterator_t iterator
)
1161 iterator_reference_t
*reference
= userdata
;
1162 io_service_t device
;
1164 while (reference
->keepRunning
&& (device
= IOIteratorNext(iterator
)) != 0x0)
1166 UInt32 locationID
= 0;
1167 IOUSBDeviceInterface
**devIntf
= NULL
;
1168 io_iterator_t intfIterator
= IO_OBJECT_NULL
;
1169 io_object_t intf
= IO_OBJECT_NULL
;
1171 devIntf
= usb_device_interface_for_device(device
);
1172 if (devIntf
== NULL
)
1173 goto device_added_done
;
1175 UInt16 vendorUniqueID
;
1176 if ((*devIntf
)->GetDeviceVendor(devIntf
, &vendorUniqueID
) != kIOReturnSuccess
|| vendorUniqueID
== kAppleVendorID
|| vendorUniqueID
== 0x0A5C)
1177 goto device_added_done
;
1179 if ((*devIntf
)->GetLocationID(devIntf
, &locationID
) != kIOReturnSuccess
)
1180 goto device_added_done
;
1182 IOUSBFindInterfaceRequest req
= { kIOUSBFindInterfaceDontCare
, kIOUSBFindInterfaceDontCare
, kIOUSBFindInterfaceDontCare
, kIOUSBFindInterfaceDontCare
};
1183 if ((*devIntf
)->CreateInterfaceIterator(devIntf
, &req
, &intfIterator
) != kIOReturnSuccess
)
1184 goto device_added_done
;
1186 while (reference
->keepRunning
&& (intf
= IOIteratorNext(intfIterator
)))
1188 printer_interface_t printerIntf
= usb_printer_interface_interface(intf
);
1189 if (printerIntf
!= NULL
)
1191 UInt8 intfClass
= 0, intfSubclass
= 0, intfProtocol
= 0, intfNumber
= 0;
1193 (*printerIntf
)->GetInterfaceClass(printerIntf
, &intfClass
);
1194 (*printerIntf
)->GetInterfaceSubClass(printerIntf
, &intfSubclass
);
1195 (*printerIntf
)->GetInterfaceProtocol(printerIntf
, &intfProtocol
);
1196 (*printerIntf
)->GetInterfaceNumber(printerIntf
, &intfNumber
);
1198 if (IsPrintingInterface(intfClass
, intfSubclass
, intfProtocol
))
1200 CFStringRef deviceIDString
= copy_printer_interface_deviceid(printerIntf
, 0);
1201 if (deviceIDString
!= NULL
)
1203 reference
->keepRunning
= reference
->callback(userdata
, intf
, deviceIDString
, locationID
, intfNumber
, 0);
1204 CFRelease(deviceIDString
);
1208 IOUSBInterfaceDescriptor
*intfDesc
= NULL
;
1209 while (reference
->keepRunning
&& (intfDesc
= (IOUSBInterfaceDescriptor
*)(*printerIntf
)->FindNextAssociatedDescriptor(printerIntf
, intfDesc
, kUSBInterfaceDesc
)))
1211 intfClass
= intfDesc
->bInterfaceClass
;
1212 intfSubclass
= intfDesc
->bInterfaceSubClass
;
1213 intfProtocol
= intfDesc
->bInterfaceProtocol
;
1215 if ((IsPrintingInterface(intfClass
, intfSubclass
, intfProtocol
)))
1217 CFStringRef deviceIDString
= copy_printer_interface_deviceid(printerIntf
, intfDesc
->bAlternateSetting
);
1218 if (deviceIDString
!= NULL
)
1220 reference
->keepRunning
= reference
->callback(userdata
, intf
, deviceIDString
, locationID
, intfNumber
, intfDesc
->bAlternateSetting
);
1221 CFRelease(deviceIDString
);
1225 (*printerIntf
)->Release(printerIntf
);
1227 IOObjectRelease(intf
);
1231 if (devIntf
!= NULL
) (*devIntf
)->Release(devIntf
);
1232 if (intfIterator
!= IO_OBJECT_NULL
) IOObjectRelease(intfIterator
);
1234 IOObjectRelease(device
);
1237 /* One last call to the call back now that we are not longer have printers left to iterate...
1239 if (reference
->keepRunning
&& reference
->callback
)
1240 reference
->keepRunning
= reference
->callback(reference
->userdata
, IO_OBJECT_NULL
, NULL
, 0, 0, 0);
1242 if (!reference
->keepRunning
)
1243 CFRunLoopStop(CFRunLoopGetCurrent());
1247 * 'list_device_cb()' - list_device iterator callback.
1250 static Boolean
list_device_cb(void *refcon
, io_service_t obj
, CFStringRef deviceIDString
, UInt32 deviceLocation
, UInt8 interfaceNum
, UInt8 alternateSetting
)
1254 (void)alternateSetting
;
1256 if (obj
!= IO_OBJECT_NULL
)
1258 CFStringRef make
= deviceIDCopyManufacturer(deviceIDString
);
1259 CFStringRef model
= deviceIDCopyModel(deviceIDString
);
1260 CFStringRef serial
= deviceIDCopySerialNumber(deviceIDString
);
1262 char uristr
[1024], makestr
[1024], modelstr
[1024], serialstr
[1024];
1263 char optionsstr
[1024], idstr
[1024], make_modelstr
[1024];
1265 CFStringGetCString(deviceIDString
, idstr
, sizeof(idstr
), kCFStringEncodingUTF8
);
1266 backendGetMakeModel(idstr
, make_modelstr
, sizeof(make_modelstr
));
1270 if (make
== NULL
|| !CFStringGetCString(make
, makestr
, sizeof(makestr
), kCFStringEncodingUTF8
))
1271 strlcpy(makestr
, "Unknown", sizeof(makestr
));
1273 if (model
== NULL
|| !CFStringGetCString(model
, &modelstr
[1], sizeof(modelstr
)-1, kCFStringEncodingUTF8
))
1274 strlcpy(modelstr
+ 1, "Printer", sizeof(modelstr
) - 1);
1276 optionsstr
[0] = '\0';
1277 if (serial
!= NULL
&& CFStringGetCString(serial
, serialstr
, sizeof(serialstr
), kCFStringEncodingUTF8
))
1278 snprintf(optionsstr
, sizeof(optionsstr
), "?serial=%s", serialstr
);
1279 else if (deviceLocation
!= 0)
1280 snprintf(optionsstr
, sizeof(optionsstr
), "?location=%x", (unsigned)deviceLocation
);
1282 httpAssembleURI(HTTP_URI_CODING_ALL
, uristr
, sizeof(uristr
), "usb", NULL
, makestr
, 0, modelstr
);
1283 strlcat(uristr
, optionsstr
, sizeof(uristr
));
1285 cupsBackendReport("direct", uristr
, make_modelstr
, make_modelstr
, idstr
,
1288 if (make
!= NULL
) CFRelease(make
);
1289 if (model
!= NULL
) CFRelease(model
);
1290 if (serial
!= NULL
) CFRelease(serial
);
1293 return obj
!= IO_OBJECT_NULL
;
1297 * 'find_device_cb()' - print_device iterator callback.
1299 static Boolean
find_device_cb(void *refcon
, io_service_t obj
, CFStringRef deviceIDString
, UInt32 deviceLocation
, UInt8 interfaceNum
, UInt8 alternateSetting
)
1301 Boolean keepLooking
= true;
1303 if (obj
!= IO_OBJECT_NULL
)
1305 CFStringRef make
= deviceIDCopyManufacturer(deviceIDString
);
1306 CFStringRef model
= deviceIDCopyModel(deviceIDString
);
1307 CFStringRef serial
= deviceIDCopySerialNumber(deviceIDString
);
1309 if (make
&& CFStringCompare(make
, g
.make
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1311 if (model
&& CFStringCompare(model
, g
.model
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1313 if (g
.serial
!= NULL
&& CFStringGetLength(g
.serial
) > 0)
1315 if (serial
!= NULL
&& CFStringCompare(serial
, g
.serial
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1317 IOObjectRetain(obj
);
1318 g
.printer_obj
= obj
;
1319 g
.location
= deviceLocation
;
1320 g
.alternateSetting
= alternateSetting
;
1321 keepLooking
= false;
1326 if (g
.printer_obj
!= 0)
1327 IOObjectRelease(g
.printer_obj
);
1329 g
.alternateSetting
= alternateSetting
;
1330 g
.printer_obj
= obj
;
1331 IOObjectRetain(obj
);
1333 if (g
.location
== 0 || g
.location
== deviceLocation
)
1334 keepLooking
= false;
1338 g
.interfaceNum
= interfaceNum
;
1342 if (make
) CFRelease(make
);
1343 if (model
) CFRelease(model
);
1344 if (serial
) CFRelease(serial
);
1348 keepLooking
= (g
.printer_obj
== 0);
1349 if (obj
== IO_OBJECT_NULL
&& keepLooking
)
1351 CFRunLoopTimerContext context
= { 0, refcon
, NULL
, NULL
, NULL
};
1352 CFRunLoopTimerRef timer
= CFRunLoopTimerCreate(NULL
, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb
, &context
);
1355 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer
, kCFRunLoopDefaultMode
);
1356 g
.status_timer
= timer
;
1361 if (!keepLooking
&& g
.status_timer
!= NULL
)
1363 fputs("STATE: -offline-report\n", stderr
);
1364 _cupsLangPrintFilter(stderr
, "INFO", _("The printer is now online."));
1365 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g
.status_timer
, kCFRunLoopDefaultMode
);
1366 CFRelease(g
.status_timer
);
1367 g
.status_timer
= NULL
;
1373 static CFStringRef
deviceIDCopySerialNumber(CFStringRef deviceID
)
1375 CFStringRef serialKeys
[] = { CFSTR("SN:"), CFSTR("SERN:"), NULL
};
1377 return copy_value_for_key(deviceID
, serialKeys
);
1380 static CFStringRef
deviceIDCopyModel(CFStringRef deviceID
)
1382 CFStringRef modelKeys
[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL
};
1383 return copy_value_for_key(deviceID
, modelKeys
);
1386 static CFStringRef
deviceIDCopyManufacturer(CFStringRef deviceID
)
1388 CFStringRef makeKeys
[] = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL
};
1389 return copy_value_for_key(deviceID
, makeKeys
);
1393 * 'status_timer_cb()' - Status timer callback.
1396 static void status_timer_cb(CFRunLoopTimerRef timer
,
1402 fputs("STATE: +offline-report\n", stderr
);
1403 _cupsLangPrintFilter(stderr
, "INFO", _("The printer is offline."));
1405 if (getenv("CLASS") != NULL
)
1408 * If the CLASS environment variable is set, the job was submitted
1409 * to a class and not to a specific queue. In this case, we want
1410 * to abort immediately so that the job can be requeued on the next
1411 * available printer in the class.
1413 * Sleep 5 seconds to keep the job from requeuing too rapidly...
1418 exit(CUPS_BACKEND_FAILED
);
1425 * 'load_classdriver()' - Load a classdriver.
1428 static kern_return_t
load_classdriver(CFStringRef driverPath
,
1429 printer_interface_t interface
,
1430 classdriver_t
***printerDriver
)
1432 kern_return_t kr
= kUSBPrinterClassDeviceNotOpen
;
1433 classdriver_t
**driver
= NULL
;
1434 CFStringRef bundle
= driverPath
? driverPath
: kUSBGenericTOPrinterClassDriver
;
1435 char bundlestr
[1024]; /* Bundle path */
1436 CFURLRef url
; /* URL for driver */
1437 CFPlugInRef plugin
= NULL
; /* Plug-in address */
1440 CFStringGetCString(bundle
, bundlestr
, sizeof(bundlestr
), kCFStringEncodingUTF8
);
1443 * Validate permissions for the class driver...
1446 _cups_fc_result_t result
= _cupsFileCheck(bundlestr
,
1447 _CUPS_FILE_CHECK_DIRECTORY
, 1,
1448 Iterating
? NULL
: _cupsFileCheckFilter
, NULL
);
1450 if (result
&& driverPath
)
1451 return (load_classdriver(NULL
, interface
, printerDriver
));
1456 * Try loading the class driver...
1459 url
= CFURLCreateWithFileSystemPath(NULL
, bundle
, kCFURLPOSIXPathStyle
, true);
1463 plugin
= CFPlugInCreate(NULL
, url
);
1471 CFArrayRef factories
= CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID
, plugin
);
1472 if (factories
!= NULL
&& CFArrayGetCount(factories
) > 0)
1474 CFUUIDRef factoryID
= CFArrayGetValueAtIndex(factories
, 0);
1475 IUnknownVTbl
**iunknown
= CFPlugInInstanceCreate(NULL
, factoryID
, kUSBPrinterClassTypeID
);
1476 if (iunknown
!= NULL
)
1478 kr
= (*iunknown
)->QueryInterface(iunknown
, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID
), (LPVOID
*)&driver
);
1479 if (kr
== kIOReturnSuccess
&& driver
!= NULL
)
1481 classdriver_t
**genericDriver
= NULL
;
1482 if (driverPath
!= NULL
&& CFStringCompare(driverPath
, kUSBGenericTOPrinterClassDriver
, 0) != kCFCompareEqualTo
)
1483 kr
= load_classdriver(NULL
, interface
, &genericDriver
);
1485 if (kr
== kIOReturnSuccess
)
1487 (*driver
)->interface
= interface
;
1488 (*driver
)->Initialize(driver
, genericDriver
);
1490 (*driver
)->plugin
= plugin
;
1491 (*driver
)->interface
= interface
;
1492 *printerDriver
= driver
;
1495 (*iunknown
)->Release(iunknown
);
1497 CFRelease(factories
);
1501 fprintf(stderr
, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr
, (int)kr
);
1508 * 'unload_classdriver()' - Unload a classdriver.
1511 static kern_return_t
unload_classdriver(classdriver_t
***classdriver
)
1513 if (*classdriver
!= NULL
)
1515 (**classdriver
)->Release(*classdriver
);
1516 *classdriver
= NULL
;
1519 return kIOReturnSuccess
;
1524 * 'load_printerdriver()' - Load vendor's classdriver.
1526 * If driverBundlePath is not NULL on return it is the callers responsbility to release it!
1529 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
)
1531 IOCFPlugInInterface
**iodev
= NULL
;
1534 printer_interface_t interface
;
1537 kr
= IOCreatePlugInInterfaceForService(g
.printer_obj
, kIOUSBInterfaceUserClientTypeID
, kIOCFPlugInInterfaceID
, &iodev
, &score
);
1538 if (kr
== kIOReturnSuccess
)
1540 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*) &interface
)) == noErr
)
1542 *driverBundlePath
= IORegistryEntryCreateCFProperty(g
.printer_obj
, kUSBClassDriverProperty
, NULL
, kNilOptions
);
1544 g
.use_generic_class_driver
= (*driverBundlePath
== NULL
|| (CFStringCompare(*driverBundlePath
, kUSBGenericTOPrinterClassDriver
, 0x0) == kCFCompareEqualTo
));
1545 kr
= load_classdriver(*driverBundlePath
, interface
, &g
.classdriver
);
1547 if (kr
!= kIOReturnSuccess
)
1548 (*interface
)->Release(interface
);
1550 IODestroyPlugInInterface(iodev
);
1555 static printer_interface_t
usb_printer_interface_interface(io_service_t usbClass
)
1557 printer_interface_t intf
= NULL
;
1558 IOCFPlugInInterface
**plugin
= NULL
;
1560 int kr
= IOCreatePlugInInterfaceForService(usbClass
, kIOUSBInterfaceUserClientTypeID
, kIOCFPlugInInterfaceID
, &plugin
, &score
);
1561 if (kr
== kIOReturnSuccess
)
1563 (*plugin
)->QueryInterface(plugin
, USB_INTERFACE_KIND
, (LPVOID
*)&intf
);
1564 IODestroyPlugInInterface(plugin
);
1570 static IOUSBDeviceInterface
**usb_device_interface_for_device(io_service_t usbDevice
)
1572 IOUSBDeviceInterface
** intf
= NULL
;
1573 IOCFPlugInInterface
**plugin
= NULL
;
1576 int kr
= IOCreatePlugInInterfaceForService(usbDevice
, kIOUSBDeviceUserClientTypeID
, kIOCFPlugInInterfaceID
, &plugin
, &score
);
1577 if (kr
== kIOReturnSuccess
)
1579 (*plugin
)->QueryInterface(plugin
, CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID
), (LPVOID
*)&intf
);
1580 IODestroyPlugInInterface(plugin
);
1587 static CFStringRef
copy_printer_interface_deviceid(printer_interface_t printer
, UInt8 alternateSetting
)
1589 // I have tried to make this function as neat as I can, but the possibility of needing to resend
1590 // a request to get the entire string makes it hideous...
1592 // We package the job of sending a request up into the block (^sendRequest), which takes the size
1593 // it should allocate for the message buffer. It frees the current buffer if one is set and
1594 // allocates one of the specified size, then performs the request. We can then easily retry by
1595 // calling the block again if we fail to get the whole string the first time around.
1597 #define kUSBPrintClassGetDeviceID 0
1598 #define kDefaultNoDataTimeout 5000L
1599 #define pack_device_id_wIndex(intf, alt) ((UInt16)((((UInt16)(intf)) << 8) | ((UInt8)(alt))))
1601 if (printer
== NULL
)
1605 IOReturn err
= kIOReturnError
;
1606 UInt8 configurationIndex
= 0;
1607 UInt8 interfaceNumber
= 0;
1608 size_t bufferLength
= 256;
1609 CFStringRef ret
= NULL
;
1611 if ((*printer
)->GetConfigurationValue( printer
, &configurationIndex
) == kIOReturnSuccess
&&
1612 (*printer
)->GetInterfaceNumber( printer
, &interfaceNumber
) == kIOReturnSuccess
)
1614 __block IOUSBDevRequestTO request
;
1615 IOReturn (^sendRequest
)(size_t) = ^ (size_t size
)
1619 free(request
.pData
);
1620 request
.wLength
= 0;
1621 request
.pData
= NULL
;
1624 IOReturn berr
= kIOReturnError
;
1625 char *buffer
= malloc(size
);
1627 return kIOReturnNoMemory
;
1629 request
.wLength
= HostToUSBWord(size
);
1630 request
.pData
= buffer
;
1631 berr
= (*printer
)->ControlRequestTO(printer
, (UInt8
)0, &request
);
1635 /* This request takes the 0 based configuration index. IOKit returns a 1 based configuration index */
1636 configurationIndex
-= 1;
1638 bzero(&request
, sizeof(request
));
1640 request
.bmRequestType
= USBmakebmRequestType(kUSBIn
, kUSBClass
, kUSBInterface
);
1641 request
.bRequest
= kUSBPrintClassGetDeviceID
;
1642 request
.wValue
= HostToUSBWord(configurationIndex
);
1643 request
.wIndex
= HostToUSBWord(pack_device_id_wIndex(interfaceNumber
, alternateSetting
));
1644 request
.noDataTimeout
= kDefaultNoDataTimeout
;
1645 request
.completionTimeout
= 0; // Copying behavior from Generic Class Driver
1647 err
= sendRequest(bufferLength
);
1649 if (err
== kIOReturnSuccess
&& request
.wLenDone
> 1)
1651 UInt16 actualLength
= OSSwapBigToHostInt16(*((UInt16
*)request
.pData
));
1653 if (actualLength
> 2 && actualLength
<= bufferLength
- 2)
1655 ret
= CFStringCreateWithBytes(NULL
, (const UInt8
*) &request
.pData
[2], actualLength
- 2, kCFStringEncodingUTF8
, false);
1658 err
= sendRequest(actualLength
);
1659 if (err
== kIOReturnSuccess
&& request
.wLenDone
> 0)
1661 actualLength
= OSSwapBigToHostInt16(*((UInt16
*)request
.pData
));
1662 ret
= CFStringCreateWithBytes(NULL
, (const UInt8
*) &request
.pData
[2], actualLength
- 2, kCFStringEncodingUTF8
, false);
1668 free(request
.pData
);
1671 CFStringRef manufacturer
= deviceIDCopyManufacturer(ret
);
1672 CFStringRef model
= deviceIDCopyModel(ret
);
1673 CFStringRef serial
= deviceIDCopySerialNumber(ret
);
1675 if (manufacturer
== NULL
|| serial
== NULL
|| model
== NULL
)
1677 IOUSBDevRequestTO request
;
1678 IOUSBDeviceDescriptor desc
;
1680 bzero(&request
, sizeof(request
));
1682 request
.bmRequestType
= USBmakebmRequestType( kUSBIn
, kUSBStandard
, kUSBDevice
);
1683 request
.bRequest
= kUSBRqGetDescriptor
;
1684 request
.wValue
= kUSBDeviceDesc
<< 8;
1686 request
.wLength
= sizeof(desc
);
1687 request
.pData
= &desc
;
1688 request
.completionTimeout
= 0;
1689 request
.noDataTimeout
= 60L;
1691 err
= (*printer
)->ControlRequestTO(printer
, 0, &request
);
1692 if (err
== kIOReturnSuccess
)
1694 CFMutableStringRef extras
= CFStringCreateMutable(NULL
, 0);
1695 if (manufacturer
== NULL
)
1697 manufacturer
= copy_printer_interface_indexed_description(printer
, desc
.iManufacturer
, kUSBLanguageEnglish
);
1698 if (manufacturer
&& CFStringGetLength(manufacturer
) > 0)
1699 CFStringAppendFormat(extras
, NULL
, CFSTR("MFG:%@;"), manufacturer
);
1704 model
= copy_printer_interface_indexed_description(printer
, desc
.iProduct
, kUSBLanguageEnglish
);
1705 if (model
&& CFStringGetLength(model
) > 0)
1706 CFStringAppendFormat(extras
, NULL
, CFSTR("MDL:%@;"), model
);
1709 if (serial
== NULL
&& desc
.iSerialNumber
!= 0)
1711 serial
= copy_printer_interface_indexed_description(printer
, desc
.iSerialNumber
, kUSBLanguageEnglish
);
1712 if (serial
&& CFStringGetLength(serial
) > 0)
1713 CFStringAppendFormat(extras
, NULL
, CFSTR("SERN:%@;"), serial
);
1718 CFStringAppend(extras
, ret
);
1732 /* Remove special characters from the serial number */
1733 CFRange range
= (serial
!= NULL
? CFStringFind(serial
, CFSTR("+"), 0) : CFRangeMake(0, 0));
1734 if (range
.length
== 1)
1736 range
= CFStringFind(ret
, serial
, 0);
1738 CFMutableStringRef deviceIDString
= CFStringCreateMutableCopy(NULL
, 0, ret
);
1741 ret
= deviceIDString
;
1742 CFStringFindAndReplace(deviceIDString
, CFSTR("+"), CFSTR(""), range
, 0);
1746 if (manufacturer
!= NULL
)
1747 CFRelease(manufacturer
);
1755 if (ret
!= NULL
&& CFStringGetLength(ret
) == 0)
1764 static CFStringRef
copy_printer_interface_indexed_description(printer_interface_t printer
, UInt8 index
, UInt16 language
)
1767 UInt8 description
[256]; // Max possible descriptor length
1768 IOUSBDevRequestTO request
;
1770 bzero(description
, 2);
1772 request
.bmRequestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
1773 request
.bRequest
= kUSBRqGetDescriptor
;
1774 request
.wValue
= (kUSBStringDesc
<< 8) | index
;
1775 request
.wIndex
= language
;
1776 request
.wLength
= 2;
1777 request
.pData
= &description
;
1778 request
.completionTimeout
= 0;
1779 request
.noDataTimeout
= 60L;
1781 err
= (*printer
)->ControlRequestTO(printer
, 0, &request
);
1782 if (err
!= kIOReturnSuccess
&& err
!= kIOReturnOverrun
)
1784 bzero(description
, request
.wLength
);
1786 // Let's try again full length. Here's why:
1787 // On USB 2.0 controllers, we will not get an overrun error. We just get a "babble" error
1788 // and no valid data. So, if we ask for the max size, we will either get it, or we'll get an underrun.
1789 // It looks like we get it w/out an underrun
1791 request
.bmRequestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
1792 request
.bRequest
= kUSBRqGetDescriptor
;
1793 request
.wValue
= (kUSBStringDesc
<< 8) | index
;
1794 request
.wIndex
= language
;
1795 request
.wLength
= sizeof description
;
1796 request
.pData
= &description
;
1797 request
.completionTimeout
= 0;
1798 request
.noDataTimeout
= 60L;
1800 err
= (*printer
)->ControlRequestTO(printer
, 0, &request
);
1801 if (err
!= kIOReturnSuccess
&& err
!= kIOReturnUnderrun
)
1805 unsigned int length
= description
[0];
1807 return CFStringCreateWithCString(NULL
, "", kCFStringEncodingUTF8
);
1809 if (description
[1] != kUSBStringDesc
)
1812 request
.bmRequestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
1813 request
.bRequest
= kUSBRqGetDescriptor
;
1814 request
.wValue
= (kUSBStringDesc
<< 8) | index
;
1815 request
.wIndex
= language
;
1817 bzero(description
, length
);
1818 request
.wLength
= (UInt16
)length
;
1819 request
.pData
= &description
;
1820 request
.completionTimeout
= 0;
1821 request
.noDataTimeout
= 60L;
1823 err
= (*printer
)->ControlRequestTO(printer
, 0, &request
);
1824 if (err
!= kIOReturnSuccess
)
1827 if (description
[1] != kUSBStringDesc
)
1830 if ((description
[0] & 1) != 0)
1831 description
[0] &= 0xfe;
1833 char buffer
[258] = {};
1834 unsigned int maxLength
= sizeof buffer
;
1835 if (description
[0] > 1)
1837 length
= (description
[0]-2)/2;
1839 if (length
> maxLength
- 1)
1840 length
= maxLength
-1;
1842 for (unsigned i
= 0; i
< length
; i
++)
1843 buffer
[i
] = (char) description
[2*i
+2];
1848 return CFStringCreateWithCString(NULL
, buffer
, kCFStringEncodingUTF8
);
1852 * 'registry_open()' - Open a connection to the printer.
1855 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
)
1857 g
.bidi_flag
= 0; /* 0=unidirectional */
1859 kern_return_t kr
= load_printerdriver(driverBundlePath
);
1860 if (kr
!= kIOReturnSuccess
)
1863 if (g
.classdriver
!= NULL
)
1865 (*g
.classdriver
)->interfaceNumber
= g
.interfaceNum
;
1866 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolBidirectional
);
1867 if (kr
!= kIOReturnSuccess
|| (*g
.classdriver
)->interface
== NULL
)
1869 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolUnidirectional
);
1870 if (kr
== kIOReturnSuccess
)
1872 if ((*g
.classdriver
)->interface
== NULL
)
1874 (*g
.classdriver
)->Close(g
.classdriver
);
1880 g
.bidi_flag
= 1; /* 1=bidirectional */
1883 if (kr
!= kIOReturnSuccess
)
1884 unload_classdriver(&g
.classdriver
);
1891 * 'registry_close()' - Close the connection to the printer.
1894 static kern_return_t
registry_close(void)
1896 if (g
.classdriver
!= NULL
)
1897 (*g
.classdriver
)->Close(g
.classdriver
);
1899 unload_classdriver(&g
.classdriver
);
1900 return kIOReturnSuccess
;
1905 * 'copy_value_for_key()' - Copy value string associated with a key.
1908 static CFStringRef
copy_value_for_key(CFStringRef deviceID
,
1911 CFStringRef value
= NULL
;
1912 CFArrayRef kvPairs
= deviceID
!= NULL
? CFStringCreateArrayBySeparatingStrings(NULL
, deviceID
, CFSTR(";")) : NULL
;
1913 CFIndex max
= kvPairs
!= NULL
? CFArrayGetCount(kvPairs
) : 0;
1916 while (idx
< max
&& value
== NULL
)
1918 CFStringRef kvpair
= CFArrayGetValueAtIndex(kvPairs
, idx
);
1920 while (keys
[idxx
] != NULL
&& value
== NULL
)
1922 CFRange range
= CFStringFind(kvpair
, keys
[idxx
], kCFCompareCaseInsensitive
);
1923 if (range
.length
!= -1)
1925 if (range
.location
!= 0)
1927 CFMutableStringRef theString
= CFStringCreateMutableCopy(NULL
, 0, kvpair
);
1928 CFStringTrimWhitespace(theString
);
1929 range
= CFStringFind(theString
, keys
[idxx
], kCFCompareCaseInsensitive
);
1930 if (range
.location
== 0)
1931 value
= CFStringCreateWithSubstring(NULL
, theString
, CFRangeMake(range
.length
, CFStringGetLength(theString
) - range
.length
));
1933 CFRelease(theString
);
1937 CFStringRef theString
= CFStringCreateWithSubstring(NULL
, kvpair
, CFRangeMake(range
.length
, CFStringGetLength(kvpair
) - range
.length
));
1938 CFMutableStringRef theString2
= CFStringCreateMutableCopy(NULL
, 0, theString
);
1939 CFRelease(theString
);
1941 CFStringTrimWhitespace(theString2
);
1950 if (kvPairs
!= NULL
)
1957 * 'cfstr_create_trim()' - Create CFString and trim whitespace characters.
1960 CFStringRef
cfstr_create_trim(const char *cstr
)
1963 CFMutableStringRef cfmutablestr
= NULL
;
1965 if ((cfstr
= CFStringCreateWithCString(NULL
, cstr
, kCFStringEncodingUTF8
)) != NULL
)
1967 if ((cfmutablestr
= CFStringCreateMutableCopy(NULL
, 1024, cfstr
)) != NULL
)
1968 CFStringTrimWhitespace(cfmutablestr
);
1972 return (CFStringRef
) cfmutablestr
;
1978 * 'parse_options()' - Parse URI options.
1981 static void parse_options(char *options
,
1987 char sep
, /* Separator character */
1988 *name
, /* Name of option */
1989 *value
; /* Value of option */
2008 while (*options
&& *options
!= '=' && *options
!= '+' && *options
!= '&')
2011 if ((sep
= *options
) != '\0')
2022 while (*options
&& *options
!= '+' && *options
!= '&')
2032 * Process the option...
2035 if (!_cups_strcasecmp(name
, "waiteof"))
2037 if (!_cups_strcasecmp(value
, "on") ||
2038 !_cups_strcasecmp(value
, "yes") ||
2039 !_cups_strcasecmp(value
, "true"))
2041 else if (!_cups_strcasecmp(value
, "off") ||
2042 !_cups_strcasecmp(value
, "no") ||
2043 !_cups_strcasecmp(value
, "false"))
2046 _cupsLangPrintFilter(stderr
, "WARNING",
2047 _("Boolean expected for waiteof option \"%s\"."),
2050 else if (!_cups_strcasecmp(name
, "serial"))
2051 strlcpy(serial
, value
, serial_size
);
2052 else if (!_cups_strcasecmp(name
, "location") && location
)
2053 *location
= (UInt32
)strtoul(value
, NULL
, 16);
2059 * @function setup_cfLanguage
2060 * @abstract Convert the contents of the CUPS 'APPLE_LANGUAGE' environment
2061 * variable into a one element CF array of languages.
2063 * @discussion Each submitted job comes with a natural language. CUPS passes
2064 * that language in an environment variable. We take that language
2065 * and jam it into the AppleLanguages array so that CF will use
2066 * it when reading localized resources. We need to do this before
2067 * any CF code reads and caches the languages array, so this function
2068 * should be called early in main()
2070 static void setup_cfLanguage(void)
2072 CFStringRef lang
[1] = {NULL
};
2073 CFArrayRef langArray
= NULL
;
2074 const char *requestedLang
= NULL
;
2076 if ((requestedLang
= getenv("APPLE_LANGUAGE")) == NULL
)
2077 requestedLang
= getenv("LANG");
2079 if (requestedLang
!= NULL
)
2081 lang
[0] = CFStringCreateWithCString(kCFAllocatorDefault
, requestedLang
, kCFStringEncodingUTF8
);
2082 langArray
= CFArrayCreate(kCFAllocatorDefault
, (const void **)lang
, sizeof(lang
) / sizeof(lang
[0]), &kCFTypeArrayCallBacks
);
2084 CFPreferencesSetValue(CFSTR("AppleLanguages"), langArray
, kCFPreferencesCurrentApplication
, kCFPreferencesAnyUser
, kCFPreferencesAnyHost
);
2085 fprintf(stderr
, "DEBUG: usb: AppleLanguages=\"%s\"\n", requestedLang
);
2088 CFRelease(langArray
);
2091 fputs("DEBUG: usb: LANG and APPLE_LANGUAGE environment variables missing.\n", stderr
);
2095 #if defined(__i386__) || defined(__x86_64__)
2097 * @function run_legacy_backend
2099 * @abstract Starts child backend process running as a ppc or i386 executable.
2101 * @result Never returns; always calls exit().
2105 static void run_legacy_backend(int argc
,
2112 pid_t waitpid_status
;
2114 char *usb_legacy_status
;
2118 * If we're running as x86_64 or i386 and couldn't load the class driver
2119 * (because it's ppc or i386), then try to re-exec ourselves in ppc or i386
2120 * mode to try again. If we don't have a ppc or i386 architecture we may be
2121 * running with the same architecture again so guard against this by setting
2122 * and testing an environment variable...
2126 usb_legacy_status
= getenv("USB_I386_STATUS");
2128 usb_legacy_status
= getenv("USB_PPC_STATUS");
2129 # endif /* __x86_64__ */
2131 if (!usb_legacy_status
)
2133 log_usb_class_driver(IS_NOT_64BIT
);
2136 * Setup a SIGTERM handler then block it before forking...
2139 int err
; /* posix_spawn result */
2140 struct sigaction action
; /* POSIX signal action */
2141 sigset_t newmask
, /* New signal mask */
2142 oldmask
; /* Old signal mask */
2143 char usbpath
[1024]; /* Path to USB backend */
2144 const char *cups_serverbin
;/* Path to CUPS binaries */
2147 memset(&action
, 0, sizeof(action
));
2148 sigaddset(&action
.sa_mask
, SIGTERM
);
2149 action
.sa_handler
= sigterm_handler
;
2150 sigaction(SIGTERM
, &action
, NULL
);
2152 sigemptyset(&newmask
);
2153 sigaddset(&newmask
, SIGTERM
);
2154 sigprocmask(SIG_BLOCK
, &newmask
, &oldmask
);
2157 * Set the environment variable...
2161 setenv("USB_I386_STATUS", "1", false);
2163 setenv("USB_PPC_STATUS", "1", false);
2164 # endif /* __x86_64__ */
2167 * Tell the kernel to use the specified CPU architecture...
2171 cpu_type_t cpu
= CPU_TYPE_I386
;
2173 cpu_type_t cpu
= CPU_TYPE_POWERPC
;
2174 # endif /* __x86_64__ */
2176 posix_spawnattr_t attrs
;
2178 if (!posix_spawnattr_init(&attrs
))
2180 posix_spawnattr_setsigdefault(&attrs
, &oldmask
);
2181 if (posix_spawnattr_setbinpref_np(&attrs
, 1, &cpu
, &ocount
) || ocount
!= 1)
2184 perror("DEBUG: Unable to set binary preference to i386");
2186 perror("DEBUG: Unable to set binary preference to ppc");
2187 # endif /* __x86_64__ */
2188 _cupsLangPrintFilter(stderr
, "ERROR",
2189 _("Unable to use legacy USB class driver."));
2190 exit(CUPS_BACKEND_STOP
);
2195 * Set up the arguments and call posix_spawn...
2198 if ((cups_serverbin
= getenv("CUPS_SERVERBIN")) == NULL
)
2199 cups_serverbin
= CUPS_SERVERBIN
;
2200 snprintf(usbpath
, sizeof(usbpath
), "%s/backend/usb", cups_serverbin
);
2202 for (i
= 0; i
< argc
&& i
< (int)(sizeof(my_argv
) / sizeof(my_argv
[0])) - 1; i
++)
2203 my_argv
[i
] = argv
[i
];
2207 if ((err
= posix_spawn(&child_pid
, usbpath
, NULL
, &attrs
, my_argv
,
2210 fprintf(stderr
, "DEBUG: Unable to exec %s: %s\n", usbpath
,
2212 _cupsLangPrintFilter(stderr
, "ERROR",
2213 _("Unable to use legacy USB class driver."));
2214 exit(CUPS_BACKEND_STOP
);
2218 * Unblock signals...
2221 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
2224 * Close the fds we won't be using then wait for the child backend to exit.
2230 fprintf(stderr
, "DEBUG: Started usb(legacy) backend (PID %d)\n",
2233 while ((waitpid_status
= waitpid(child_pid
, &childstatus
, 0)) == (pid_t
)-1 && errno
== EINTR
)
2236 if (WIFSIGNALED(childstatus
))
2238 exitstatus
= CUPS_BACKEND_STOP
;
2239 fprintf(stderr
, "DEBUG: usb(legacy) backend %d crashed on signal %d\n",
2240 child_pid
, WTERMSIG(childstatus
));
2244 if ((exitstatus
= WEXITSTATUS(childstatus
)) != 0)
2246 "DEBUG: usb(legacy) backend %d stopped with status %d\n",
2247 child_pid
, exitstatus
);
2249 fprintf(stderr
, "DEBUG: usb(legacy) backend %d exited with no errors\n",
2255 fputs("DEBUG: usb(legacy) backend running native again\n", stderr
);
2256 exitstatus
= CUPS_BACKEND_STOP
;
2261 #endif /* __i386__ || __x86_64__ */
2265 * 'sigterm_handler()' - SIGTERM handler.
2269 sigterm_handler(int sig
) /* I - Signal */
2271 #if defined(__i386__) || defined(__x86_64__)
2273 * If we started a child process pass the signal on to it...
2279 * If we started a child process pass the signal on to it...
2284 kill(child_pid
, sig
);
2285 while (waitpid(child_pid
, &status
, 0) < 0 && errno
== EINTR
);
2287 if (WIFEXITED(status
))
2288 exit(WEXITSTATUS(status
));
2289 else if (status
== SIGTERM
|| status
== SIGKILL
)
2293 fprintf(stderr
, "DEBUG: Child crashed on signal %d\n", status
);
2294 exit(CUPS_BACKEND_STOP
);
2297 #endif /* __i386__ || __x86_64__ */
2302 * 'sigquit_handler()' - SIGQUIT handler.
2305 static void sigquit_handler(int sig
, siginfo_t
*si
, void *unused
)
2308 char pathbuf
[PROC_PIDPATHINFO_MAXSIZE
];
2309 static char msgbuf
[256] = "";
2315 if (proc_pidpath(si
->si_pid
, pathbuf
, sizeof(pathbuf
)) > 0 &&
2316 (path
= basename(pathbuf
)) != NULL
)
2317 snprintf(msgbuf
, sizeof(msgbuf
), "SIGQUIT sent by %s(%d)", path
, (int)si
->si_pid
);
2319 snprintf(msgbuf
, sizeof(msgbuf
), "SIGQUIT sent by PID %d", (int)si
->si_pid
);
2321 CRSetCrashLogMessage(msgbuf
);
2327 #ifdef PARSE_PS_ERRORS
2329 * 'next_line()' - Find the next line in a buffer.
2332 static const char *next_line (const char *buffer
)
2334 const char *cptr
, *lptr
= NULL
;
2336 for (cptr
= buffer
; *cptr
&& lptr
== NULL
; cptr
++)
2337 if (*cptr
== '\n' || *cptr
== '\r')
2344 * 'parse_pserror()' - Scan the backchannel data for postscript errors.
2347 static void parse_pserror(char *sockBuffer
,
2350 static char gErrorBuffer
[1024] = "";
2351 static char *gErrorBufferPtr
= gErrorBuffer
;
2352 static char *gErrorBufferEndPtr
= gErrorBuffer
+ sizeof(gErrorBuffer
);
2354 char *pCommentBegin
, *pCommentEnd
, *pLineEnd
;
2359 if (gErrorBufferPtr
+ len
> gErrorBufferEndPtr
- 1)
2360 gErrorBufferPtr
= gErrorBuffer
;
2361 if (len
> sizeof(gErrorBuffer
) - 1)
2362 len
= sizeof(gErrorBuffer
) - 1;
2364 memcpy(gErrorBufferPtr
, (const void *)sockBuffer
, len
);
2365 gErrorBufferPtr
+= len
;
2366 *(gErrorBufferPtr
+ 1) = '\0';
2368 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
2369 while (pLineEnd
!= NULL
)
2373 pCommentBegin
= strstr(gErrorBuffer
,"%%[");
2374 pCommentEnd
= strstr(gErrorBuffer
, "]%%");
2375 if (pCommentBegin
!= gErrorBuffer
&& pCommentEnd
!= NULL
)
2377 pCommentEnd
+= 3; /* Skip past "]%%" */
2378 *pCommentEnd
= '\0'; /* There's always room for the nul */
2380 if (_cups_strncasecmp(pCommentBegin
, "%%[ Error:", 10) == 0)
2382 else if (_cups_strncasecmp(pCommentBegin
, "%%[ Flushing", 12) == 0)
2387 if ((logstrlen
= snprintf(logstr
, sizeof(logstr
), "%s: %s\n", logLevel
, pCommentBegin
)) >= sizeof(logstr
))
2389 /* If the string was trucnated make sure it has a linefeed before the nul */
2390 logstrlen
= sizeof(logstr
) - 1;
2391 logstr
[logstrlen
- 1] = '\n';
2393 write(STDERR_FILENO
, logstr
, logstrlen
);
2396 /* move everything over... */
2397 strlcpy(gErrorBuffer
, pLineEnd
, sizeof(gErrorBuffer
));
2398 gErrorBufferPtr
= gErrorBuffer
;
2399 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
2402 #endif /* PARSE_PS_ERRORS */
2406 * 'soft_reset()' - Send a soft reset to the device.
2409 static void soft_reset(void)
2411 fd_set input_set
; /* Input set for select() */
2412 struct timeval tv
; /* Time value */
2413 char buffer
[2048]; /* Buffer */
2414 struct timespec cond_timeout
; /* pthread condition timeout */
2417 * Send an abort once a second until the I/O lock is released by the main thread...
2420 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2421 while (g
.readwrite_lock
)
2423 (*g
.classdriver
)->Abort(g
.classdriver
);
2425 gettimeofday(&tv
, NULL
);
2426 cond_timeout
.tv_sec
= tv
.tv_sec
+ 1;
2427 cond_timeout
.tv_nsec
= tv
.tv_usec
* 1000;
2429 while (g
.readwrite_lock
)
2431 if (pthread_cond_timedwait(&g
.readwrite_lock_cond
,
2432 &g
.readwrite_lock_mutex
,
2433 &cond_timeout
) != 0)
2438 g
.readwrite_lock
= 1;
2439 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2442 * Flush bytes waiting on print_fd...
2447 FD_ZERO(&input_set
);
2448 FD_SET(g
.print_fd
, &input_set
);
2453 while (select(g
.print_fd
+1, &input_set
, NULL
, NULL
, &tv
) > 0)
2454 if (read(g
.print_fd
, buffer
, sizeof(buffer
)) <= 0)
2461 (*g
.classdriver
)->SoftReset(g
.classdriver
, DEFAULT_TIMEOUT
);
2464 * Release the I/O lock...
2467 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2468 g
.readwrite_lock
= 0;
2469 pthread_cond_signal(&g
.readwrite_lock_cond
);
2470 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2475 * 'get_device_id()' - Return IEEE-1284 device ID.
2478 static void get_device_id(cups_sc_status_t
*status
,
2482 CFStringRef deviceIDString
= NULL
;
2484 if (g
.printer_obj
!= IO_OBJECT_NULL
)
2486 printer_interface_t printerIntf
= usb_printer_interface_interface(g
.printer_obj
);
2489 deviceIDString
= copy_printer_interface_deviceid(printerIntf
, g
.alternateSetting
);
2490 (*printerIntf
)->Release(printerIntf
);
2497 if (CFStringGetCString(deviceIDString
, data
, *datalen
, kCFStringEncodingUTF8
))
2498 *datalen
= (int)strlen(data
);
2502 CFRelease(deviceIDString
);
2509 *status
= CUPS_SC_STATUS_OK
;
2514 log_usb_class_driver(int is_64bit
) /* I - Is the USB class driver 64-bit? */
2517 * Report the usage of legacy USB class drivers to Apple if the user opts into providing
2518 * feedback to Apple...
2521 aslmsg aslm
= asl_new(ASL_TYPE_MSG
);
2524 ppd_file_t
*ppd
= ppdOpenFile(getenv("PPD"));
2525 const char *make_model
= ppd
? ppd
->nickname
: NULL
;
2526 ppd_attr_t
*version
= ppdFindAttr(ppd
, "FileVersion", "");
2528 asl_set(aslm
, "com.apple.message.domain", "com.apple.printing.usb.64bit");
2529 asl_set(aslm
, "com.apple.message.result", is_64bit
? "yes" : "no");
2530 asl_set(aslm
, "com.apple.message.signature", make_model
? make_model
: "Unknown");
2531 asl_set(aslm
, "com.apple.message.signature2", version
? version
->value
: "?.?");
2532 asl_set(aslm
, "com.apple.message.summarize", "YES");
2533 asl_log(NULL
, aslm
, ASL_LEVEL_NOTICE
, "");