2 * "$Id: usb-darwin.c 7953 2008-09-17 01:43:19Z mike $"
4 * Copyright 2005-2009 Apple Inc. All rights reserved.
6 * IMPORTANT: This Apple software is supplied to you by Apple Computer,
7 * Inc. ("Apple") in consideration of your agreement to the following
8 * terms, and your use, installation, modification or redistribution of
9 * this Apple software constitutes acceptance of these terms. If you do
10 * not agree with these terms, please do not use, install, modify or
11 * redistribute this Apple software.
13 * In consideration of your agreement to abide by the following terms, and
14 * subject to these terms, Apple grants you a personal, non-exclusive
15 * license, under Apple's copyrights in this original Apple software (the
16 * "Apple Software"), to use, reproduce, modify and redistribute the Apple
17 * Software, with or without modifications, in source and/or binary forms;
18 * provided that if you redistribute the Apple Software in its entirety and
19 * without modifications, you must retain this notice and the following
20 * text and disclaimers in all such redistributions of the Apple Software.
21 * Neither the name, trademarks, service marks or logos of Apple Computer,
22 * Inc. may be used to endorse or promote products derived from the Apple
23 * Software without specific prior written permission from Apple. Except
24 * as expressly stated in this notice, no other rights or licenses, express
25 * or implied, are granted by Apple herein, including but not limited to
26 * any patent rights that may be infringed by your derivative works or by
27 * other works in which the Apple Software may be incorporated.
29 * The Apple Software is provided by Apple on an "AS IS" basis. APPLE
30 * MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
31 * THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
32 * FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
33 * OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
35 * IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
36 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
37 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
38 * INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
39 * MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
40 * AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
41 * STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
42 * POSSIBILITY OF SUCH DAMAGE.
46 * list_devices() - List all USB devices.
47 * print_device() - Print a file to a USB device.
48 * sidechannel_thread() - Thread to handle side-channel requests.
49 * read_thread() - Thread to read the backchannel data on.
50 * list_device_cb() - list_device iterator callback.
51 * find_device_cb() - print_device iterator callback.
52 * status_timer_cb() - Status timer callback.
53 * iterate_printers() - Iterate over all the printers.
54 * device_added() - Device added notifier.
55 * copy_deviceinfo() - Copy strings from the 1284 device ID.
56 * release_deviceinfo() - Release deviceinfo strings.
57 * load_classdriver() - Load a classdriver.
58 * unload_classdriver() - Unload a classdriver.
59 * load_printerdriver() - Load vendor's classdriver.
60 * registry_open() - Open a connection to the printer.
61 * registry_close() - Close the connection to the printer.
62 * copy_deviceid() - Copy the 1284 device id string.
63 * copy_devicestring() - Copy the 1284 device id string.
64 * copy_value_for_key() - Copy value string associated with a key.
65 * cfstr_create_trim() - Create CFString and trim whitespace characters.
66 * parse_options() - Parse uri options.
67 * setup_cfLanguage() - Create AppleLanguages array from LANG environment var.
68 * run_legacy_backend() - Re-exec backend as ppc or i386.
69 * sigterm_handler() - SIGTERM handler.
70 * next_line() - Find the next line in a buffer.
71 * parse_pserror() - Scan the backchannel data for postscript errors.
72 * get_device_id() - Return IEEE-1284 device ID.
76 * Include necessary headers.
87 #include <sys/sysctl.h>
89 #include <mach/mach.h>
90 #include <mach/mach_error.h>
91 #include <mach/mach_time.h>
92 #include <cups/debug.h>
93 #include <cups/sidechannel.h>
94 #include <cups/i18n.h>
95 #include "backend-private.h"
97 #include <CoreFoundation/CoreFoundation.h>
98 #include <IOKit/usb/IOUSBLib.h>
99 #include <IOKit/IOCFPlugIn.h>
104 extern char **environ
;
108 * WAIT_EOF_DELAY is number of seconds we'll wait for responses from
109 * the printer after we've finished sending all the data
111 #define WAIT_EOF_DELAY 7
112 #define WAIT_SIDE_DELAY 3
113 #define DEFAULT_TIMEOUT 5000L
115 #define USB_INTERFACE_KIND CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID190)
116 #define kUSBLanguageEnglish 0x409
118 #define PRINTER_POLLING_INTERVAL 5 /* seconds */
119 #define INITIAL_LOG_INTERVAL PRINTER_POLLING_INTERVAL
120 #define SUBSEQUENT_LOG_INTERVAL 3 * INITIAL_LOG_INTERVAL
122 #define kUSBPrinterClassTypeID CFUUIDGetConstantUUIDWithBytes(NULL, 0x06, 0x04, 0x7D, 0x16, 0x53, 0xA2, 0x11, 0xD6, 0x92, 0x06, 0x00, 0x30, 0x65, 0x52, 0x45, 0x92)
123 #define kUSBPrinterClassInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, 0x03, 0x34, 0x6D, 0x74, 0x53, 0xA3, 0x11, 0xD6, 0x9E, 0xA1, 0x76, 0x30, 0x65, 0x52, 0x45, 0x92)
125 #define kUSBClassDriverProperty CFSTR("USB Printing Class")
127 #define kUSBGenericTOPrinterClassDriver CFSTR("/System/Library/Printers/Libraries/USBGenericTOPrintingClass.plugin")
128 #define kUSBPrinterClassDeviceNotOpen -9664 /*kPMInvalidIOMContext*/
132 * Section 5.3 USB Printing Class spec
134 #define kUSBPrintingSubclass 1
135 #define kUSBPrintingProtocolNoOpen 0
136 #define kUSBPrintingProtocolUnidirectional 1
137 #define kUSBPrintingProtocolBidirectional 2
139 typedef IOUSBInterfaceInterface190
**printer_interface_t
;
141 typedef struct iodevice_request_s
/**** Device request ****/
149 } iodevice_request_t
;
151 typedef union /**** Centronics status byte ****/
156 unsigned reserved0
:2;
157 unsigned paperError
:1;
160 unsigned reserved1
:3;
162 } centronics_status_t
;
164 typedef struct classdriver_s
/**** g.classdriver context ****/
167 CFPlugInRef plugin
; /* release plugin */
168 IUnknownVTbl
**factory
; /* Factory */
169 void *vendorReference
; /* vendor class specific usage */
170 UInt32 location
; /* unique location in bus topology */
171 UInt8 interfaceNumber
; /* Interface number */
172 UInt16 vendorID
; /* Vendor id */
173 UInt16 productID
; /* Product id */
174 printer_interface_t interface
; /* identify the device to IOKit */
175 UInt8 outpipe
; /* mandatory bulkOut pipe */
176 UInt8 inpipe
; /* optional bulkIn pipe */
178 /* general class requests */
179 kern_return_t (*DeviceRequest
)(struct classdriver_s
**printer
, iodevice_request_t
*iorequest
, UInt16 timeout
);
180 kern_return_t (*GetString
)(struct classdriver_s
**printer
, UInt8 whichString
, UInt16 language
, UInt16 timeout
, CFStringRef
*result
);
182 /* standard printer class requests */
183 kern_return_t (*SoftReset
)(struct classdriver_s
**printer
, UInt16 timeout
);
184 kern_return_t (*GetCentronicsStatus
)(struct classdriver_s
**printer
, centronics_status_t
*result
, UInt16 timeout
);
185 kern_return_t (*GetDeviceID
)(struct classdriver_s
**printer
, CFStringRef
*devid
, UInt16 timeout
);
187 /* standard bulk device requests */
188 kern_return_t (*ReadPipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
);
189 kern_return_t (*WritePipe
)(struct classdriver_s
**printer
, UInt8
*buffer
, UInt32
*count
, Boolean eoj
);
191 /* interface requests */
192 kern_return_t (*Open
)(struct classdriver_s
**printer
, UInt32 location
, UInt8 protocol
);
193 kern_return_t (*Abort
)(struct classdriver_s
**printer
);
194 kern_return_t (*Close
)(struct classdriver_s
**printer
);
196 /* initialize and terminate */
197 kern_return_t (*Initialize
)(struct classdriver_s
**printer
, struct classdriver_s
**baseclass
);
198 kern_return_t (*Terminate
)(struct classdriver_s
**printer
);
202 typedef Boolean (*iterator_callback_t
)(void *refcon
, io_service_t obj
);
204 typedef struct iterator_reference_s
/**** Iterator reference data */
206 iterator_callback_t callback
;
209 } iterator_reference_t
;
211 typedef struct globals_s
213 io_service_t printer_obj
;
214 classdriver_t
**classdriver
;
216 pthread_mutex_t read_thread_mutex
;
217 pthread_cond_t read_thread_cond
;
218 int read_thread_stop
;
219 int read_thread_done
;
221 pthread_mutex_t readwrite_lock_mutex
;
222 pthread_cond_t readwrite_lock_cond
;
231 CFRunLoopTimerRef status_timer
;
233 int print_fd
; /* File descriptor to print */
234 ssize_t print_bytes
; /* Print bytes read */
237 int drain_output
; /* Drain all pending output */
238 int bidi_flag
; /* 0=unidirectional, 1=bidirectional */
240 pthread_mutex_t sidechannel_thread_mutex
;
241 pthread_cond_t sidechannel_thread_cond
;
242 int sidechannel_thread_stop
;
243 int sidechannel_thread_done
;
251 globals_t g
= { 0 }; /* Globals */
258 static Boolean
find_device_cb(void *refcon
, io_service_t obj
);
259 static Boolean
list_device_cb(void *refcon
, io_service_t obj
);
260 static CFStringRef
cfstr_create_trim(const char *cstr
);
261 static CFStringRef
copy_value_for_key(CFStringRef deviceID
, CFStringRef
*keys
);
262 static kern_return_t
load_classdriver(CFStringRef driverPath
, printer_interface_t intf
, classdriver_t
***printerDriver
);
263 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
);
264 static kern_return_t
registry_close();
265 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
);
266 static kern_return_t
unload_classdriver();
267 static OSStatus
copy_deviceid(classdriver_t
**printer
, CFStringRef
*deviceID
);
268 static void *read_thread(void *reference
);
269 static void *sidechannel_thread(void *reference
);
270 static void copy_deviceinfo(CFStringRef deviceIDString
, CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
271 static void copy_devicestring(io_service_t usbInterface
, CFStringRef
*deviceID
, UInt32
*deviceLocation
, UInt8
*interfaceNum
);
272 static void device_added(void *userdata
, io_iterator_t iterator
);
273 static void get_device_id(cups_sc_status_t
*status
, char *data
, int *datalen
);
274 static void iterate_printers(iterator_callback_t callBack
, void *userdata
);
275 static void parse_options(char *options
, char *serial
, int serial_size
, UInt32
*location
, Boolean
*wait_eof
);
276 static void release_deviceinfo(CFStringRef
*make
, CFStringRef
*model
, CFStringRef
*serial
);
277 static void setup_cfLanguage(void);
278 static void soft_reset();
279 static void status_timer_cb(CFRunLoopTimerRef timer
, void *info
);
281 #if defined(__i386__) || defined(__x86_64__)
282 static pid_t child_pid
; /* Child PID */
283 static void run_legacy_backend(int argc
, char *argv
[], int fd
); /* Starts child backend process running as a ppc executable */
284 #endif /* __i386__ || __x86_64__ */
285 static int job_canceled
= 0; /* Was the job canceled? */
286 static void sigterm_handler(int sig
); /* SIGTERM handler */
288 #ifdef PARSE_PS_ERRORS
289 static const char *next_line (const char *buffer
);
290 static void parse_pserror (char *sockBuffer
, int len
);
291 #endif /* PARSE_PS_ERRORS */
296 * 'list_devices()' - List all USB devices.
301 iterate_printers(list_device_cb
, NULL
);
306 * 'print_device()' - Print a file to a USB device.
309 int /* O - Exit status */
310 print_device(const char *uri
, /* I - Device URI */
311 const char *hostname
, /* I - Hostname/manufacturer */
312 const char *resource
, /* I - Resource/modelname */
313 char *options
, /* I - Device options/serial number */
314 int print_fd
, /* I - File descriptor to print */
315 int copies
, /* I - Copies to print */
316 int argc
, /* I - Number of command-line arguments (6 or 7) */
317 char *argv
[]) /* I - Command-line arguments */
319 char serial
[1024]; /* Serial number buffer */
320 OSStatus status
; /* Function results */
321 pthread_t read_thread_id
, /* Read thread */
322 sidechannel_thread_id
;/* Side-channel thread */
323 int have_sidechannel
= 0; /* Was the side-channel thread started? */
324 struct stat sidechannel_info
; /* Side-channel file descriptor info */
325 char print_buffer
[8192], /* Print data buffer */
326 *print_ptr
; /* Pointer into print data buffer */
327 UInt32 location
; /* Unique location in bus topology */
328 fd_set input_set
; /* Input set for select() */
329 CFStringRef driverBundlePath
; /* Class driver path */
330 int countdown
, /* Logging interval */
331 nfds
; /* Number of file descriptors */
332 ssize_t total_bytes
; /* Total bytes written */
333 UInt32 bytes
; /* Bytes written */
334 struct timeval
*timeout
, /* Timeout pointer */
335 stimeout
; /* Timeout for select() */
336 struct timespec cond_timeout
; /* pthread condition timeout */
340 * See if the side-channel descriptor is valid...
343 have_sidechannel
= !fstat(CUPS_SC_FD
, &sidechannel_info
) &&
344 S_ISSOCK(sidechannel_info
.st_mode
);
347 * Localize using CoreFoundation...
352 parse_options(options
, serial
, sizeof(serial
), &location
, &g
.wait_eof
);
354 if (resource
[0] == '/')
357 g
.print_fd
= print_fd
;
358 g
.make
= cfstr_create_trim(hostname
);
359 g
.model
= cfstr_create_trim(resource
);
360 g
.serial
= cfstr_create_trim(serial
);
361 g
.location
= location
;
363 if (!g
.make
|| !g
.model
)
365 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error!\n"));
368 fputs("DEBUG: USB make string is NULL!\n", stderr
);
370 fputs("DEBUG: USB model string is NULL!\n", stderr
);
372 return (CUPS_BACKEND_STOP
);
375 fputs("STATE: +connecting-to-device\n", stderr
);
377 countdown
= INITIAL_LOG_INTERVAL
;
383 IOObjectRelease(g
.printer_obj
);
384 unload_classdriver(&g
.classdriver
);
389 fprintf(stderr
, "DEBUG: Looking for '%s %s'\n", hostname
, resource
);
391 iterate_printers(find_device_cb
, NULL
);
393 fputs("DEBUG: Opening connection\n", stderr
);
395 driverBundlePath
= NULL
;
397 status
= registry_open(&driverBundlePath
);
399 #if defined(__i386__) || defined(__x86_64__)
401 * If we were unable to load the class drivers for this printer it's
402 * probably because they're ppc or i386. In this case try to run this
403 * backend as i386 or ppc executables so we can use them...
407 run_legacy_backend(argc
, argv
, print_fd
);
408 /* Never returns here */
410 #endif /* __i386__ || __x86_64__ */
415 * If we still were unable to load the class drivers for this printer log
416 * the error and stop the queue...
419 if (driverBundlePath
== NULL
|| !CFStringGetCString(driverBundlePath
, print_buffer
, sizeof(print_buffer
), kCFStringEncodingUTF8
))
420 strlcpy(print_buffer
, "USB class driver", sizeof(print_buffer
));
422 fputs("STATE: +apple-missing-usbclassdriver-error\n", stderr
);
423 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error!\n"));
424 fprintf(stderr
, "DEBUG: Could not load %s\n", print_buffer
);
426 if (driverBundlePath
)
427 CFRelease(driverBundlePath
);
429 return (CUPS_BACKEND_STOP
);
432 if (driverBundlePath
)
433 CFRelease(driverBundlePath
);
437 sleep(PRINTER_POLLING_INTERVAL
);
438 countdown
-= PRINTER_POLLING_INTERVAL
;
441 _cupsLangPuts(stderr
,
442 _("INFO: Waiting for printer to become available...\n"));
443 fprintf(stderr
, "DEBUG: USB printer status: 0x%08x\n", (int)status
);
444 countdown
= SUBSEQUENT_LOG_INTERVAL
; /* subsequent log entries, every 15 seconds */
447 } while (status
!= noErr
);
449 fputs("STATE: -connecting-to-device\n", stderr
);
452 * Now that we are "connected" to the port, catch SIGTERM so that we
453 * can finish out any page data the driver sends (e.g. to eject the
454 * current page... Only catch SIGTERM if we are printing data from
455 * stdin (otherwise you can't cancel raw jobs...)
460 struct sigaction action
; /* POSIX signal action */
463 memset(&action
, 0, sizeof(action
));
465 sigemptyset(&action
.sa_mask
);
466 action
.sa_handler
= sigterm_handler
;
467 sigaction(SIGTERM
, &action
, NULL
);
471 * Start the side channel thread if the descriptor is valid...
474 pthread_mutex_init(&g
.readwrite_lock_mutex
, NULL
);
475 pthread_cond_init(&g
.readwrite_lock_cond
, NULL
);
476 g
.readwrite_lock
= 1;
478 if (have_sidechannel
)
480 g
.sidechannel_thread_stop
= 0;
481 g
.sidechannel_thread_done
= 0;
483 pthread_cond_init(&g
.sidechannel_thread_cond
, NULL
);
484 pthread_mutex_init(&g
.sidechannel_thread_mutex
, NULL
);
486 if (pthread_create(&sidechannel_thread_id
, NULL
, sidechannel_thread
, NULL
))
488 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error!\n"));
489 fputs("DEBUG: Couldn't create side-channel thread!\n", stderr
);
490 return (CUPS_BACKEND_STOP
);
495 * Get the read thread going...
498 g
.read_thread_stop
= 0;
499 g
.read_thread_done
= 0;
501 pthread_cond_init(&g
.read_thread_cond
, NULL
);
502 pthread_mutex_init(&g
.read_thread_mutex
, NULL
);
504 if (pthread_create(&read_thread_id
, NULL
, read_thread
, NULL
))
506 _cupsLangPuts(stderr
, _("ERROR: Fatal USB error!\n"));
507 fputs("DEBUG: Couldn't create read thread!\n", stderr
);
508 return (CUPS_BACKEND_STOP
);
512 * The main thread sends the print file...
518 print_ptr
= print_buffer
;
520 while (status
== noErr
&& copies
-- > 0)
522 _cupsLangPuts(stderr
, _("INFO: Sending print data...\n"));
524 if (print_fd
!= STDIN_FILENO
)
526 fputs("PAGE: 1 1\n", stderr
);
527 lseek(print_fd
, 0, SEEK_SET
);
530 while (status
== noErr
)
535 FD_SET(print_fd
, &input_set
);
538 * Calculate select timeout...
539 * If we have data waiting to send timeout is 100ms.
540 * else if we're draining print_fd timeout is 0.
541 * else we're waiting forever...
547 stimeout
.tv_usec
= 100000; /* 100ms */
550 else if (g
.drain_output
)
553 stimeout
.tv_usec
= 0;
560 * I/O is unlocked around select...
563 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
564 g
.readwrite_lock
= 0;
565 pthread_cond_signal(&g
.readwrite_lock_cond
);
566 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
568 nfds
= select(print_fd
+ 1, &input_set
, NULL
, NULL
, timeout
);
571 * Reacquire the lock...
574 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
575 while (g
.readwrite_lock
)
576 pthread_cond_wait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
);
577 g
.readwrite_lock
= 1;
578 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
582 if (errno
== EINTR
&& total_bytes
== 0)
584 fputs("DEBUG: Received an interrupt before any bytes were "
585 "written, aborting!\n", stderr
);
586 return (CUPS_BACKEND_OK
);
588 else if (errno
!= EAGAIN
)
590 _cupsLangPuts(stderr
, _("ERROR: Unable to read print data!\n"));
591 perror("DEBUG: select");
592 return (CUPS_BACKEND_FAILED
);
597 * If drain output has finished send a response...
600 if (g
.drain_output
&& !nfds
&& !g
.print_bytes
)
602 /* Send a response... */
603 cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
608 * Check if we have print data ready...
611 if (FD_ISSET(print_fd
, &input_set
))
613 g
.print_bytes
= read(print_fd
, print_buffer
, sizeof(print_buffer
));
615 if (g
.print_bytes
< 0)
618 * Read error - bail if we don't see EAGAIN or EINTR...
621 if (errno
!= EAGAIN
|| errno
!= EINTR
)
623 _cupsLangPuts(stderr
, _("ERROR: Unable to read print data!\n"));
624 perror("DEBUG: read");
625 return (CUPS_BACKEND_FAILED
);
630 else if (g
.print_bytes
== 0)
633 * End of file, break out of the loop...
639 print_ptr
= print_buffer
;
641 fprintf(stderr
, "DEBUG: Read %d bytes of print data...\n",
647 bytes
= g
.print_bytes
;
649 status
= (*g
.classdriver
)->WritePipe(g
.classdriver
, (UInt8
*)print_ptr
, &bytes
, 0);
652 * Ignore timeout errors, but retain the number of bytes written to
653 * avoid sending duplicate data (<rdar://problem/6254911>)...
656 if (status
== kIOUSBTransactionTimeout
)
659 if (status
|| bytes
< 0)
662 * Write error - bail if we don't see an error we can retry...
665 OSStatus err
= (*g
.classdriver
)->Abort(g
.classdriver
);
666 _cupsLangPuts(stderr
, _("ERROR: Unable to send print data!\n"));
667 fprintf(stderr
, "DEBUG: USB class driver WritePipe returned %ld\n",
669 fprintf(stderr
, "DEBUG: USB class driver Abort returned %ld\n",
671 status
= job_canceled
? CUPS_BACKEND_FAILED
: CUPS_BACKEND_STOP
;
675 fprintf(stderr
, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes
);
677 g
.print_bytes
-= bytes
;
679 total_bytes
+= bytes
;
682 if (print_fd
!= 0 && status
== noErr
)
683 fprintf(stderr
, "DEBUG: Sending print file, %lld bytes...\n",
688 fprintf(stderr
, "DEBUG: Sent %lld bytes...\n", (off_t
)total_bytes
);
691 * Wait for the side channel thread to exit...
694 if (have_sidechannel
)
697 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
698 g
.readwrite_lock
= 0;
699 pthread_cond_signal(&g
.readwrite_lock_cond
);
700 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
702 g
.sidechannel_thread_stop
= 1;
703 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
704 if (!g
.sidechannel_thread_done
)
707 * Wait for the side-channel thread to exit...
710 cond_timeout
.tv_sec
= time(NULL
) + WAIT_SIDE_DELAY
;
711 cond_timeout
.tv_nsec
= 0;
712 if (pthread_cond_timedwait(&g
.sidechannel_thread_cond
,
713 &g
.sidechannel_thread_mutex
,
717 * Force the side-channel thread to exit...
720 pthread_kill(sidechannel_thread_id
, SIGTERM
);
723 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
725 pthread_join(sidechannel_thread_id
, NULL
);
727 pthread_cond_destroy(&g
.sidechannel_thread_cond
);
728 pthread_mutex_destroy(&g
.sidechannel_thread_mutex
);
731 pthread_cond_destroy(&g
.readwrite_lock_cond
);
732 pthread_mutex_destroy(&g
.readwrite_lock_mutex
);
735 * Signal the read thread to stop...
738 g
.read_thread_stop
= 1;
741 * Give the read thread WAIT_EOF_DELAY seconds to complete all the data. If
742 * we are not signaled in that time then force the thread to exit.
745 pthread_mutex_lock(&g
.read_thread_mutex
);
747 if (!g
.read_thread_done
)
749 cond_timeout
.tv_sec
= time(NULL
) + WAIT_EOF_DELAY
;
750 cond_timeout
.tv_nsec
= 0;
752 if (pthread_cond_timedwait(&g
.read_thread_cond
, &g
.read_thread_mutex
,
756 * Force the read thread to exit...
760 pthread_kill(read_thread_id
, SIGTERM
);
763 pthread_mutex_unlock(&g
.read_thread_mutex
);
765 pthread_join(read_thread_id
, NULL
); /* wait for the read thread to return */
767 pthread_cond_destroy(&g
.read_thread_cond
);
768 pthread_mutex_destroy(&g
.read_thread_mutex
);
771 * Close the connection and input file and general clean up...
776 if (print_fd
!= STDIN_FILENO
)
785 if (g
.serial
!= NULL
)
788 if (g
.printer_obj
!= 0x0)
789 IOObjectRelease(g
.printer_obj
);
796 * 'read_thread()' - Thread to read the backchannel data on.
799 static void *read_thread(void *reference
)
801 UInt8 readbuffer
[512];
803 kern_return_t readstatus
;
804 struct mach_timebase_info timeBaseInfo
;
808 /* Calculate what 250 milliSeconds are in mach absolute time...
810 mach_timebase_info(&timeBaseInfo
);
811 delay
= ((uint64_t)250000000 * (uint64_t)timeBaseInfo
.denom
) / (uint64_t)timeBaseInfo
.numer
;
816 * Remember when we started so we can throttle the loop after the read call...
819 start
= mach_absolute_time();
821 rbytes
= sizeof(readbuffer
);
822 readstatus
= (*g
.classdriver
)->ReadPipe(g
.classdriver
, readbuffer
, &rbytes
);
823 if (readstatus
== kIOReturnSuccess
&& rbytes
> 0)
825 cupsBackChannelWrite((char*)readbuffer
, rbytes
, 1.0);
827 /* cntrl-d is echoed by the printer.
829 * Xerox Phaser 6250D doesn't echo the cntrl-d.
830 * Xerox Phaser 6250D doesn't always send the product query.
832 if (g
.wait_eof
&& readbuffer
[rbytes
-1] == 0x4)
835 #ifdef PARSE_PS_ERRORS
836 parse_pserror(readbuffer
, rbytes
);
841 * Make sure this loop executes no more than once every 250 miliseconds...
844 if ((readstatus
!= kIOReturnSuccess
|| rbytes
== 0) && (g
.wait_eof
|| !g
.read_thread_stop
))
845 mach_wait_until(start
+ delay
);
847 } while (g
.wait_eof
|| !g
.read_thread_stop
); /* Abort from main thread tests error here */
850 * Let the main thread know that we have completed the read thread...
853 pthread_mutex_lock(&g
.read_thread_mutex
);
854 g
.read_thread_done
= 1;
855 pthread_cond_signal(&g
.read_thread_cond
);
856 pthread_mutex_unlock(&g
.read_thread_mutex
);
863 * 'sidechannel_thread()' - Handle side-channel requests.
867 sidechannel_thread(void *reference
)
869 cups_sc_command_t command
; /* Request command */
870 cups_sc_status_t status
; /* Request/response status */
871 char data
[2048]; /* Request/response data */
872 int datalen
; /* Request/response data size */
877 datalen
= sizeof(data
);
879 if (cupsSideChannelRead(&command
, &status
, data
, &datalen
, 1.0))
884 case CUPS_SC_CMD_SOFT_RESET
: /* Do a soft reset */
885 if ((*g
.classdriver
)->SoftReset
!= NULL
)
888 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, NULL
, 0, 1.0);
892 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
897 case CUPS_SC_CMD_DRAIN_OUTPUT
: /* Drain all pending output */
901 case CUPS_SC_CMD_GET_BIDI
: /* Is the connection bidirectional? */
902 data
[0] = g
.bidi_flag
;
903 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
906 case CUPS_SC_CMD_GET_DEVICE_ID
: /* Return IEEE-1284 device ID */
907 datalen
= sizeof(data
);
908 get_device_id(&status
, data
, &datalen
);
909 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, datalen
, 1.0);
912 case CUPS_SC_CMD_GET_STATE
: /* Return device state */
913 data
[0] = CUPS_SC_STATE_ONLINE
;
914 cupsSideChannelWrite(command
, CUPS_SC_STATUS_OK
, data
, 1, 1.0);
918 cupsSideChannelWrite(command
, CUPS_SC_STATUS_NOT_IMPLEMENTED
,
923 while (!g
.sidechannel_thread_stop
);
925 pthread_mutex_lock(&g
.sidechannel_thread_mutex
);
926 g
.sidechannel_thread_done
= 1;
927 pthread_cond_signal(&g
.sidechannel_thread_cond
);
928 pthread_mutex_unlock(&g
.sidechannel_thread_mutex
);
936 * 'iterate_printers()' - Iterate over all the printers.
939 static void iterate_printers(iterator_callback_t callBack
,
942 mach_port_t masterPort
= 0x0;
943 kern_return_t kr
= IOMasterPort (bootstrap_port
, &masterPort
);
945 if (kr
== kIOReturnSuccess
&& masterPort
!= 0x0)
947 io_iterator_t addIterator
= 0x0;
949 iterator_reference_t reference
= { callBack
, userdata
, true };
950 IONotificationPortRef addNotification
= IONotificationPortCreate(masterPort
);
952 int klass
= kUSBPrintingClass
;
953 int subklass
= kUSBPrintingSubclass
;
955 CFNumberRef usb_klass
= CFNumberCreate(NULL
, kCFNumberIntType
, &klass
);
956 CFNumberRef usb_subklass
= CFNumberCreate(NULL
, kCFNumberIntType
, &subklass
);
957 CFMutableDictionaryRef usbPrinterMatchDictionary
= IOServiceMatching(kIOUSBInterfaceClassName
);
959 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceClass"), usb_klass
);
960 CFDictionaryAddValue(usbPrinterMatchDictionary
, CFSTR("bInterfaceSubClass"), usb_subklass
);
962 CFRelease(usb_klass
);
963 CFRelease(usb_subklass
);
965 kr
= IOServiceAddMatchingNotification(addNotification
, kIOMatchedNotification
, usbPrinterMatchDictionary
, &device_added
, &reference
, &addIterator
);
966 if (addIterator
!= 0x0)
968 device_added (&reference
, addIterator
);
970 if (reference
.keepRunning
)
972 CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification
), kCFRunLoopDefaultMode
);
975 IOObjectRelease(addIterator
);
977 mach_port_deallocate(mach_task_self(), masterPort
);
983 * 'device_added()' - Device added notifier.
986 static void device_added(void *userdata
,
987 io_iterator_t iterator
)
989 iterator_reference_t
*reference
= userdata
;
992 while (reference
->keepRunning
&& (obj
= IOIteratorNext(iterator
)) != 0x0)
994 if (reference
->callback
!= NULL
)
995 reference
->keepRunning
= reference
->callback(reference
->userdata
, obj
);
997 IOObjectRelease(obj
);
1000 /* One last call to the call back now that we are not longer have printers left to iterate...
1002 if (reference
->keepRunning
)
1003 reference
->keepRunning
= reference
->callback(reference
->userdata
, 0x0);
1005 if (!reference
->keepRunning
)
1006 CFRunLoopStop(CFRunLoopGetCurrent());
1011 * 'list_device_cb()' - list_device iterator callback.
1014 static Boolean
list_device_cb(void *refcon
,
1017 Boolean keepRunning
= (obj
!= 0x0);
1021 CFStringRef deviceIDString
= NULL
;
1022 UInt32 deviceLocation
= 0;
1023 UInt8 interfaceNum
= 0;
1025 copy_devicestring(obj
, &deviceIDString
, &deviceLocation
, &interfaceNum
);
1026 if (deviceIDString
!= NULL
)
1028 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1029 char uristr
[1024], makestr
[1024], modelstr
[1024], serialstr
[1024];
1030 char optionsstr
[1024], idstr
[1024], make_modelstr
[1024];
1032 copy_deviceinfo(deviceIDString
, &make
, &model
, &serial
);
1033 CFStringGetCString(deviceIDString
, idstr
, sizeof(idstr
),
1034 kCFStringEncodingUTF8
);
1035 backendGetMakeModel(idstr
, make_modelstr
, sizeof(make_modelstr
));
1040 !CFStringGetCString(make
, makestr
, sizeof(makestr
),
1041 kCFStringEncodingUTF8
))
1042 strcpy(makestr
, "Unknown");
1045 !CFStringGetCString(model
, &modelstr
[1], sizeof(modelstr
)-1,
1046 kCFStringEncodingUTF8
))
1047 strcpy(modelstr
+ 1, "Printer");
1049 optionsstr
[0] = '\0';
1052 CFStringGetCString(serial
, serialstr
, sizeof(serialstr
), kCFStringEncodingUTF8
);
1053 snprintf(optionsstr
, sizeof(optionsstr
), "?serial=%s", serialstr
);
1055 else if (deviceLocation
!= 0)
1056 snprintf(optionsstr
, sizeof(optionsstr
), "?location=%x", (unsigned)deviceLocation
);
1058 httpAssembleURI(HTTP_URI_CODING_ALL
, uristr
, sizeof(uristr
), "usb", NULL
, makestr
, 0, modelstr
);
1059 strncat(uristr
, optionsstr
, sizeof(uristr
));
1061 cupsBackendReport("direct", uristr
, make_modelstr
, make_modelstr
, idstr
,
1064 release_deviceinfo(&make
, &model
, &serial
);
1065 CFRelease(deviceIDString
);
1074 * 'find_device_cb()' - print_device iterator callback.
1077 static Boolean
find_device_cb(void *refcon
,
1080 Boolean keepLooking
= true;
1084 CFStringRef idString
= NULL
;
1085 UInt32 location
= -1;
1086 UInt8 interfaceNum
= 0;
1088 copy_devicestring(obj
, &idString
, &location
, &interfaceNum
);
1089 if (idString
!= NULL
)
1091 CFStringRef make
= NULL
, model
= NULL
, serial
= NULL
;
1093 copy_deviceinfo(idString
, &make
, &model
, &serial
);
1094 if (make
&& CFStringCompare(make
, g
.make
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1096 if (model
&& CFStringCompare(model
, g
.model
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1098 if (g
.serial
!= NULL
&& CFStringGetLength(g
.serial
) > 0)
1100 if (serial
!= NULL
&& CFStringCompare(serial
, g
.serial
, kCFCompareCaseInsensitive
) == kCFCompareEqualTo
)
1102 IOObjectRetain(obj
);
1103 g
.printer_obj
= obj
;
1104 keepLooking
= false;
1109 if (g
.printer_obj
!= 0)
1110 IOObjectRelease(g
.printer_obj
);
1112 g
.printer_obj
= obj
;
1113 IOObjectRetain(obj
);
1115 if (g
.location
== 0 || g
.location
== location
)
1116 keepLooking
= false;
1119 g
.interfaceNum
= interfaceNum
;
1123 release_deviceinfo(&make
, &model
, &serial
);
1124 CFRelease(idString
);
1129 keepLooking
= (g
.printer_obj
== 0);
1130 if (obj
== 0x0 && keepLooking
)
1132 CFRunLoopTimerContext context
= { 0, refcon
, NULL
, NULL
, NULL
};
1133 CFRunLoopTimerRef timer
= CFRunLoopTimerCreate(NULL
, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb
, &context
);
1136 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer
, kCFRunLoopDefaultMode
);
1137 g
.status_timer
= timer
;
1142 if (!keepLooking
&& g
.status_timer
!= NULL
)
1144 fputs("STATE: -offline-report\n", stderr
);
1145 _cupsLangPuts(stderr
, _("INFO: Printer is now online.\n"));
1146 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g
.status_timer
, kCFRunLoopDefaultMode
);
1147 CFRelease(g
.status_timer
);
1148 g
.status_timer
= NULL
;
1156 * 'status_timer_cb()' - Status timer callback.
1159 static void status_timer_cb(CFRunLoopTimerRef timer
,
1162 fputs("STATE: +offline-report\n", stderr
);
1163 _cupsLangPuts(stderr
, _("INFO: Printer is offline.\n"));
1165 if (getenv("CLASS") != NULL
)
1168 * If the CLASS environment variable is set, the job was submitted
1169 * to a class and not to a specific queue. In this case, we want
1170 * to abort immediately so that the job can be requeued on the next
1171 * available printer in the class.
1173 * Sleep 5 seconds to keep the job from requeuing too rapidly...
1178 exit(CUPS_BACKEND_FAILED
);
1185 * 'copy_deviceinfo()' - Copy strings from the 1284 device ID.
1188 static void copy_deviceinfo(CFStringRef deviceIDString
,
1191 CFStringRef
*serial
)
1193 CFStringRef modelKeys
[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL
};
1194 CFStringRef makeKeys
[] = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL
};
1195 CFStringRef serialKeys
[] = { CFSTR("SN:"), CFSTR("SERN:"), NULL
};
1198 *make
= copy_value_for_key(deviceIDString
, makeKeys
);
1201 *model
= copy_value_for_key(deviceIDString
, modelKeys
);
1204 *serial
= copy_value_for_key(deviceIDString
, serialKeys
);
1209 * 'release_deviceinfo()' - Release deviceinfo strings.
1212 static void release_deviceinfo(CFStringRef
*make
,
1214 CFStringRef
*serial
)
1216 if (make
!= NULL
&& *make
!= NULL
)
1222 if (model
!= NULL
&& *model
!= NULL
)
1228 if (serial
!= NULL
&& *serial
!= NULL
)
1238 * 'load_classdriver()' - Load a classdriver.
1241 static kern_return_t
load_classdriver(CFStringRef driverPath
,
1242 printer_interface_t intf
,
1243 classdriver_t
***printerDriver
)
1245 kern_return_t kr
= kUSBPrinterClassDeviceNotOpen
;
1246 classdriver_t
**driver
= NULL
;
1247 CFStringRef bundle
= driverPath
? driverPath
: kUSBGenericTOPrinterClassDriver
;
1248 char bundlestr
[1024]; /* Bundle path */
1249 struct stat bundleinfo
; /* File information for bundle */
1250 CFURLRef url
; /* URL for driver */
1251 CFPlugInRef plugin
= NULL
; /* Plug-in address */
1254 CFStringGetCString(bundle
, bundlestr
, sizeof(bundlestr
), kCFStringEncodingUTF8
);
1257 * Validate permissions for the class driver...
1260 if (stat(bundlestr
, &bundleinfo
))
1262 fprintf(stderr
, "Unable to load class driver \"%s\": %s", bundlestr
,
1266 else if (bundleinfo
.st_mode
& S_IWOTH
)
1268 fprintf(stderr
, "Unable to load class driver \"%s\": insecure file "
1269 "permissions (0%o)", bundlestr
, bundleinfo
.st_mode
);
1274 * Try loading the class driver...
1277 url
= CFURLCreateWithFileSystemPath(NULL
, bundle
, kCFURLPOSIXPathStyle
, true);
1281 plugin
= CFPlugInCreate(NULL
, url
);
1289 CFArrayRef factories
= CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID
, plugin
);
1290 if (factories
!= NULL
&& CFArrayGetCount(factories
) > 0)
1292 CFUUIDRef factoryID
= CFArrayGetValueAtIndex(factories
, 0);
1293 IUnknownVTbl
**iunknown
= CFPlugInInstanceCreate(NULL
, factoryID
, kUSBPrinterClassTypeID
);
1294 if (iunknown
!= NULL
)
1296 kr
= (*iunknown
)->QueryInterface(iunknown
, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID
), (LPVOID
*)&driver
);
1297 if (kr
== kIOReturnSuccess
&& driver
!= NULL
)
1299 classdriver_t
**genericDriver
= NULL
;
1300 if (driverPath
!= NULL
&& CFStringCompare(driverPath
, kUSBGenericTOPrinterClassDriver
, 0) != kCFCompareEqualTo
)
1301 kr
= load_classdriver(NULL
, intf
, &genericDriver
);
1303 if (kr
== kIOReturnSuccess
)
1305 (*driver
)->interface
= intf
;
1306 (*driver
)->Initialize(driver
, genericDriver
);
1308 (*driver
)->plugin
= plugin
;
1309 (*driver
)->interface
= intf
;
1310 *printerDriver
= driver
;
1313 (*iunknown
)->Release(iunknown
);
1315 CFRelease(factories
);
1319 fprintf(stderr
, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr
, (int)kr
);
1326 * 'unload_classdriver()' - Unload a classdriver.
1329 static kern_return_t
unload_classdriver(classdriver_t
***classdriver
)
1331 if (*classdriver
!= NULL
)
1333 (**classdriver
)->Release(*classdriver
);
1334 *classdriver
= NULL
;
1337 return kIOReturnSuccess
;
1342 * 'load_printerdriver()' - Load vendor's classdriver.
1344 * If driverBundlePath is not NULL on return it is the callers responsbility to release it!
1347 static kern_return_t
load_printerdriver(CFStringRef
*driverBundlePath
)
1349 IOCFPlugInInterface
**iodev
= NULL
;
1352 printer_interface_t intf
;
1355 kr
= IOCreatePlugInInterfaceForService(g
.printer_obj
, kIOUSBInterfaceUserClientTypeID
, kIOCFPlugInInterfaceID
, &iodev
, &score
);
1356 if (kr
== kIOReturnSuccess
)
1358 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*) &intf
)) == noErr
)
1360 *driverBundlePath
= IORegistryEntryCreateCFProperty(g
.printer_obj
, kUSBClassDriverProperty
, NULL
, kNilOptions
);
1362 kr
= load_classdriver(*driverBundlePath
, intf
, &g
.classdriver
);
1364 if (kr
!= kIOReturnSuccess
)
1365 (*intf
)->Release(intf
);
1367 IODestroyPlugInInterface(iodev
);
1374 * 'registry_open()' - Open a connection to the printer.
1377 static kern_return_t
registry_open(CFStringRef
*driverBundlePath
)
1379 g
.bidi_flag
= 0; /* 0=unidirectional */
1381 kern_return_t kr
= load_printerdriver(driverBundlePath
);
1382 if (kr
!= kIOReturnSuccess
)
1385 if (g
.classdriver
!= NULL
)
1387 (*g
.classdriver
)->interfaceNumber
= g
.interfaceNum
;
1388 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolBidirectional
);
1389 if (kr
!= kIOReturnSuccess
|| (*g
.classdriver
)->interface
== NULL
)
1391 kr
= (*g
.classdriver
)->Open(g
.classdriver
, g
.location
, kUSBPrintingProtocolUnidirectional
);
1392 if (kr
== kIOReturnSuccess
)
1394 if ((*g
.classdriver
)->interface
== NULL
)
1396 (*g
.classdriver
)->Close(g
.classdriver
);
1402 g
.bidi_flag
= 1; /* 1=bidirectional */
1405 if (kr
!= kIOReturnSuccess
)
1406 unload_classdriver(&g
.classdriver
);
1413 * 'registry_close()' - Close the connection to the printer.
1416 static kern_return_t
registry_close()
1418 if (g
.classdriver
!= NULL
)
1419 (*g
.classdriver
)->Close(g
.classdriver
);
1421 unload_classdriver(&g
.classdriver
);
1422 return kIOReturnSuccess
;
1427 * 'copy_deviceid()' - Copy the 1284 device id string.
1430 static OSStatus
copy_deviceid(classdriver_t
**classdriver
,
1431 CFStringRef
*deviceID
)
1433 CFStringRef devID
= NULL
,
1437 deviceSerial
= NULL
;
1439 OSStatus err
= (*classdriver
)->GetDeviceID(classdriver
, &devID
, DEFAULT_TIMEOUT
);
1441 copy_deviceinfo(devID
, &deviceMake
, &deviceModel
, &deviceSerial
);
1443 if (deviceMake
== NULL
|| deviceModel
== NULL
|| deviceSerial
== NULL
)
1445 IOUSBDeviceDescriptor desc
;
1446 iodevice_request_t request
;
1448 request
.requestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
1449 request
.request
= kUSBRqGetDescriptor
;
1450 request
.value
= (kUSBDeviceDesc
<< 8) | 0;
1452 request
.length
= sizeof(desc
);
1453 request
.buffer
= &desc
;
1454 err
= (*classdriver
)->DeviceRequest(classdriver
, &request
, DEFAULT_TIMEOUT
);
1455 if (err
== kIOReturnSuccess
)
1457 CFMutableStringRef newDevID
= CFStringCreateMutable(NULL
, 0);
1459 if (deviceMake
== NULL
)
1461 CFStringRef data
= NULL
;
1462 err
= (*classdriver
)->GetString(classdriver
, desc
.iManufacturer
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1465 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MFG:%@;"), data
);
1470 if (deviceModel
== NULL
)
1472 CFStringRef data
= NULL
;
1473 err
= (*classdriver
)->GetString(classdriver
, desc
.iProduct
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1476 CFStringAppendFormat(newDevID
, NULL
, CFSTR("MDL:%@;"), data
);
1481 if (deviceSerial
== NULL
&& desc
.iSerialNumber
!= 0)
1483 CFStringRef data
= NULL
;
1484 err
= (*classdriver
)->GetString(classdriver
, desc
.iSerialNumber
, kUSBLanguageEnglish
, DEFAULT_TIMEOUT
, &data
);
1487 CFStringAppendFormat(newDevID
, NULL
, CFSTR("SERN:%@;"), data
);
1494 CFStringAppend(newDevID
, devID
);
1498 *deviceID
= newDevID
;
1505 release_deviceinfo(&deviceMake
, &deviceModel
, &deviceSerial
);
1512 * 'copy_devicestring()' - Copy the 1284 device id string.
1515 static void copy_devicestring(io_service_t usbInterface
,
1516 CFStringRef
*deviceID
,
1517 UInt32
*deviceLocation
,
1518 UInt8
*interfaceNumber
)
1520 IOCFPlugInInterface
**iodev
= NULL
;
1523 printer_interface_t intf
;
1525 classdriver_t
**klassDriver
= NULL
;
1526 CFStringRef driverBundlePath
;
1528 if ((kr
= IOCreatePlugInInterfaceForService(usbInterface
,
1529 kIOUSBInterfaceUserClientTypeID
,
1530 kIOCFPlugInInterfaceID
,
1531 &iodev
, &score
)) == kIOReturnSuccess
)
1533 if ((res
= (*iodev
)->QueryInterface(iodev
, USB_INTERFACE_KIND
, (LPVOID
*)
1536 (*intf
)->GetLocationID(intf
, deviceLocation
);
1537 (*intf
)->GetInterfaceNumber(intf
, interfaceNumber
);
1539 driverBundlePath
= IORegistryEntryCreateCFProperty(usbInterface
,
1540 kUSBClassDriverProperty
,
1543 kr
= load_classdriver(driverBundlePath
, intf
, &klassDriver
);
1545 if (kr
!= kIOReturnSuccess
&& driverBundlePath
!= NULL
)
1546 kr
= load_classdriver(NULL
, intf
, &klassDriver
);
1548 if (kr
== kIOReturnSuccess
&& klassDriver
!= NULL
)
1549 kr
= copy_deviceid(klassDriver
, deviceID
);
1551 unload_classdriver(&klassDriver
);
1553 if (driverBundlePath
!= NULL
)
1554 CFRelease(driverBundlePath
);
1556 /* (*intf)->Release(intf); */
1558 IODestroyPlugInInterface(iodev
);
1565 * 'copy_value_for_key()' - Copy value string associated with a key.
1568 static CFStringRef
copy_value_for_key(CFStringRef deviceID
,
1571 CFStringRef value
= NULL
;
1572 CFArrayRef kvPairs
= deviceID
!= NULL
? CFStringCreateArrayBySeparatingStrings(NULL
, deviceID
, CFSTR(";")) : NULL
;
1573 CFIndex max
= kvPairs
!= NULL
? CFArrayGetCount(kvPairs
) : 0;
1576 while (idx
< max
&& value
== NULL
)
1578 CFStringRef kvpair
= CFArrayGetValueAtIndex(kvPairs
, idx
);
1580 while (keys
[idxx
] != NULL
&& value
== NULL
)
1582 CFRange range
= CFStringFind(kvpair
, keys
[idxx
], kCFCompareCaseInsensitive
);
1583 if (range
.length
!= -1)
1585 if (range
.location
!= 0)
1587 CFMutableStringRef theString
= CFStringCreateMutableCopy(NULL
, 0, kvpair
);
1588 CFStringTrimWhitespace(theString
);
1589 range
= CFStringFind(theString
, keys
[idxx
], kCFCompareCaseInsensitive
);
1590 if (range
.location
== 0)
1591 value
= CFStringCreateWithSubstring(NULL
, theString
, CFRangeMake(range
.length
, CFStringGetLength(theString
) - range
.length
));
1593 CFRelease(theString
);
1597 CFStringRef theString
= CFStringCreateWithSubstring(NULL
, kvpair
, CFRangeMake(range
.length
, CFStringGetLength(kvpair
) - range
.length
));
1598 CFMutableStringRef theString2
= CFStringCreateMutableCopy(NULL
, 0, theString
);
1599 CFRelease(theString
);
1601 CFStringTrimWhitespace(theString2
);
1610 if (kvPairs
!= NULL
)
1617 * 'cfstr_create_trim()' - Create CFString and trim whitespace characters.
1620 CFStringRef
cfstr_create_trim(const char *cstr
)
1623 CFMutableStringRef cfmutablestr
= NULL
;
1625 if ((cfstr
= CFStringCreateWithCString(NULL
, cstr
, kCFStringEncodingUTF8
)) != NULL
)
1627 if ((cfmutablestr
= CFStringCreateMutableCopy(NULL
, 1024, cfstr
)) != NULL
)
1628 CFStringTrimWhitespace(cfmutablestr
);
1632 return (CFStringRef
) cfmutablestr
;
1638 * 'parse_options()' - Parse URI options.
1641 static void parse_options(char *options
,
1647 char sep
, /* Separator character */
1648 *name
, /* Name of option */
1649 *value
; /* Value of option */
1668 while (*options
&& *options
!= '=' && *options
!= '+' && *options
!= '&')
1671 if ((sep
= *options
) != '\0')
1682 while (*options
&& *options
!= '+' && *options
!= '&')
1692 * Process the option...
1695 if (!strcasecmp(name
, "waiteof"))
1697 if (!strcasecmp(value
, "on") ||
1698 !strcasecmp(value
, "yes") ||
1699 !strcasecmp(value
, "true"))
1701 else if (!strcasecmp(value
, "off") ||
1702 !strcasecmp(value
, "no") ||
1703 !strcasecmp(value
, "false"))
1706 _cupsLangPrintf(stderr
,
1707 _("WARNING: Boolean expected for waiteof option "
1708 "\"%s\"\n"), value
);
1710 else if (!strcasecmp(name
, "serial"))
1711 strlcpy(serial
, value
, serial_size
);
1712 else if (!strcasecmp(name
, "location") && location
)
1713 *location
= strtol(value
, NULL
, 16);
1719 * @function setup_cfLanguage
1720 * @abstract Convert the contents of the CUPS 'APPLE_LANGUAGE' environment
1721 * variable into a one element CF array of languages.
1723 * @discussion Each submitted job comes with a natural language. CUPS passes
1724 * that language in an environment variable. We take that language
1725 * and jam it into the AppleLanguages array so that CF will use
1726 * it when reading localized resources. We need to do this before
1727 * any CF code reads and caches the languages array, so this function
1728 * should be called early in main()
1730 static void setup_cfLanguage(void)
1732 CFStringRef lang
[1] = {NULL
};
1733 CFArrayRef langArray
= NULL
;
1734 const char *requestedLang
= NULL
;
1736 if ((requestedLang
= getenv("APPLE_LANGUAGE")) == NULL
)
1737 requestedLang
= getenv("LANG");
1739 if (requestedLang
!= NULL
)
1741 lang
[0] = CFStringCreateWithCString(kCFAllocatorDefault
, requestedLang
, kCFStringEncodingUTF8
);
1742 langArray
= CFArrayCreate(kCFAllocatorDefault
, (const void **)lang
, sizeof(lang
) / sizeof(lang
[0]), &kCFTypeArrayCallBacks
);
1744 CFPreferencesSetValue(CFSTR("AppleLanguages"), langArray
, kCFPreferencesCurrentApplication
, kCFPreferencesAnyUser
, kCFPreferencesAnyHost
);
1745 fprintf(stderr
, "DEBUG: usb: AppleLanguages=\"%s\"\n", requestedLang
);
1748 CFRelease(langArray
);
1751 fputs("DEBUG: usb: LANG and APPLE_LANGUAGE environment variables missing.\n", stderr
);
1755 #if defined(__i386__) || defined(__x86_64__)
1757 * @function run_legacy_backend
1759 * @abstract Starts child backend process running as a ppc or i386 executable.
1761 * @result Never returns; always calls exit().
1765 static void run_legacy_backend(int argc
,
1772 pid_t waitpid_status
;
1774 char *usb_legacy_status
;
1777 * If we're running as x86_64 or i386 and couldn't load the class driver
1778 * (because it's ppc or i386), then try to re-exec ourselves in ppc or i386
1779 * mode to try again. If we don't have a ppc or i386 architecture we may be
1780 * running with the same architecture again so guard against this by setting
1781 * and testing an environment variable...
1785 usb_legacy_status
= getenv("USB_I386_STATUS");
1787 usb_legacy_status
= getenv("USB_PPC_STATUS");
1788 # endif /* __x86_64__ */
1790 if (!usb_legacy_status
)
1793 * Setup a SIGTERM handler then block it before forking...
1796 struct sigaction action
; /* POSIX signal action */
1797 sigset_t newmask
, /* New signal mask */
1798 oldmask
; /* Old signal mask */
1799 char usbpath
[1024]; /* Path to USB backend */
1800 const char *cups_serverbin
;/* Path to CUPS binaries */
1803 memset(&action
, 0, sizeof(action
));
1804 sigaddset(&action
.sa_mask
, SIGTERM
);
1805 action
.sa_handler
= sigterm_handler
;
1806 sigaction(SIGTERM
, &action
, NULL
);
1808 sigemptyset(&newmask
);
1809 sigaddset(&newmask
, SIGTERM
);
1810 sigprocmask(SIG_BLOCK
, &newmask
, &oldmask
);
1813 * Set the environment variable...
1817 setenv("USB_I386_STATUS", "1", false);
1819 setenv("USB_PPC_STATUS", "1", false);
1820 # endif /* __x86_64__ */
1823 * Tell the kernel to use the specified CPU architecture...
1827 cpu_type_t cpu
= CPU_TYPE_I386
;
1829 cpu_type_t cpu
= CPU_TYPE_POWERPC
;
1830 # endif /* __x86_64__ */
1832 posix_spawnattr_t attrs
;
1834 if (!posix_spawnattr_init(&attrs
))
1836 posix_spawnattr_setsigdefault(&attrs
, &oldmask
);
1837 if (posix_spawnattr_setbinpref_np(&attrs
, 1, &cpu
, &ocount
) || ocount
!= 1)
1840 perror("DEBUG: Unable to set binary preference to i386");
1842 perror("DEBUG: Unable to set binary preference to ppc");
1843 # endif /* __x86_64__ */
1844 _cupsLangPrintf(stderr
, _("Unable to use legacy USB class driver!\n"));
1845 exit(CUPS_BACKEND_STOP
);
1850 * Set up the arguments and call posix_spawn...
1853 if ((cups_serverbin
= getenv("CUPS_SERVERBIN")) == NULL
)
1854 cups_serverbin
= CUPS_SERVERBIN
;
1855 snprintf(usbpath
, sizeof(usbpath
), "%s/backend/usb", cups_serverbin
);
1857 for (i
= 0; i
< argc
&& i
< (sizeof(my_argv
) / sizeof(my_argv
[0])) - 1; i
++)
1858 my_argv
[i
] = argv
[i
];
1862 if (posix_spawn(&child_pid
, usbpath
, NULL
, &attrs
, my_argv
, environ
))
1864 fprintf(stderr
, "DEBUG: Unable to exec %s: %s\n", usbpath
,
1866 _cupsLangPrintf(stderr
, _("Unable to use legacy USB class driver!\n"));
1867 exit(CUPS_BACKEND_STOP
);
1871 * Unblock signals...
1874 sigprocmask(SIG_SETMASK
, &oldmask
, NULL
);
1877 * Close the fds we won't be using then wait for the child backend to exit.
1883 fprintf(stderr
, "DEBUG: Started usb(legacy) backend (PID %d)\n",
1886 while ((waitpid_status
= waitpid(child_pid
, &childstatus
, 0)) == (pid_t
)-1 && errno
== EINTR
)
1889 if (WIFSIGNALED(childstatus
))
1891 exitstatus
= CUPS_BACKEND_STOP
;
1892 fprintf(stderr
, "DEBUG: usb(legacy) backend %d crashed on signal %d!\n",
1893 child_pid
, WTERMSIG(childstatus
));
1897 if ((exitstatus
= WEXITSTATUS(childstatus
)) != 0)
1899 "DEBUG: usb(legacy) backend %d stopped with status %d!\n",
1900 child_pid
, exitstatus
);
1902 fprintf(stderr
, "DEBUG: usb(legacy) backend %d exited with no errors\n",
1908 fputs("DEBUG: usb(legacy) backend running native again\n", stderr
);
1909 exitstatus
= CUPS_BACKEND_STOP
;
1914 #endif /* __i386__ || __x86_64__ */
1918 * 'sigterm_handler()' - SIGTERM handler.
1922 sigterm_handler(int sig
) /* I - Signal */
1924 #if defined(__i386__) || defined(__x86_64__)
1928 * If we started a child process pass the signal on to it...
1933 kill(child_pid
, sig
);
1934 while (waitpid(child_pid
, &status
, 0) < 0 && errno
== EINTR
);
1936 if (WIFEXITED(status
))
1937 exit(WEXITSTATUS(status
));
1938 else if (status
== SIGTERM
|| status
== SIGKILL
)
1942 fprintf(stderr
, "DEBUG: Child crashed on signal %d!\n", status
);
1943 exit(CUPS_BACKEND_STOP
);
1946 #endif /* __i386__ || __x86_64__ */
1949 * Otherwise just flag that the job has been canceled...
1956 #ifdef PARSE_PS_ERRORS
1958 * 'next_line()' - Find the next line in a buffer.
1961 static const char *next_line (const char *buffer
)
1963 const char *cptr
, *lptr
= NULL
;
1965 for (cptr
= buffer
; *cptr
&& lptr
== NULL
; cptr
++)
1966 if (*cptr
== '\n' || *cptr
== '\r')
1973 * 'parse_pserror()' - Scan the backchannel data for postscript errors.
1976 static void parse_pserror(char *sockBuffer
,
1979 static char gErrorBuffer
[1024] = "";
1980 static char *gErrorBufferPtr
= gErrorBuffer
;
1981 static char *gErrorBufferEndPtr
= gErrorBuffer
+ sizeof(gErrorBuffer
);
1983 char *pCommentBegin
, *pCommentEnd
, *pLineEnd
;
1988 if (gErrorBufferPtr
+ len
> gErrorBufferEndPtr
- 1)
1989 gErrorBufferPtr
= gErrorBuffer
;
1990 if (len
> sizeof(gErrorBuffer
) - 1)
1991 len
= sizeof(gErrorBuffer
) - 1;
1993 memcpy(gErrorBufferPtr
, (const void *)sockBuffer
, len
);
1994 gErrorBufferPtr
+= len
;
1995 *(gErrorBufferPtr
+ 1) = '\0';
1997 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
1998 while (pLineEnd
!= NULL
)
2002 pCommentBegin
= strstr(gErrorBuffer
,"%%[");
2003 pCommentEnd
= strstr(gErrorBuffer
, "]%%");
2004 if (pCommentBegin
!= gErrorBuffer
&& pCommentEnd
!= NULL
)
2006 pCommentEnd
+= 3; /* Skip past "]%%" */
2007 *pCommentEnd
= '\0'; /* There's always room for the nul */
2009 if (strncasecmp(pCommentBegin
, "%%[ Error:", 10) == 0)
2011 else if (strncasecmp(pCommentBegin
, "%%[ Flushing", 12) == 0)
2016 if ((logstrlen
= snprintf(logstr
, sizeof(logstr
), "%s: %s\n", logLevel
, pCommentBegin
)) >= sizeof(logstr
))
2018 /* If the string was trucnated make sure it has a linefeed before the nul */
2019 logstrlen
= sizeof(logstr
) - 1;
2020 logstr
[logstrlen
- 1] = '\n';
2022 write(STDERR_FILENO
, logstr
, logstrlen
);
2025 /* move everything over... */
2026 strcpy(gErrorBuffer
, pLineEnd
);
2027 gErrorBufferPtr
= gErrorBuffer
;
2028 pLineEnd
= (char *)next_line((const char *)gErrorBuffer
);
2031 #endif /* PARSE_PS_ERRORS */
2035 * 'soft_reset()' - Send a soft reset to the device.
2038 static void soft_reset()
2040 fd_set input_set
; /* Input set for select() */
2041 struct timeval stimeout
; /* Timeout for select() */
2042 char buffer
[2048]; /* Buffer */
2043 struct timespec cond_timeout
; /* pthread condition timeout */
2046 * Send an abort once a second until the I/O lock is released by the main thread...
2049 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2050 while (g
.readwrite_lock
)
2052 (*g
.classdriver
)->Abort(g
.classdriver
);
2054 cond_timeout
.tv_sec
= time(NULL
) + 1;
2055 cond_timeout
.tv_nsec
= 0;
2057 pthread_cond_timedwait(&g
.readwrite_lock_cond
, &g
.readwrite_lock_mutex
, &cond_timeout
);
2060 g
.readwrite_lock
= 1;
2061 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2064 * Flush bytes waiting on print_fd...
2069 FD_ZERO(&input_set
);
2070 FD_SET(g
.print_fd
, &input_set
);
2072 stimeout
.tv_sec
= 0;
2073 stimeout
.tv_usec
= 0;
2075 while (select(g
.print_fd
+1, &input_set
, NULL
, NULL
, &stimeout
) > 0)
2076 if (read(g
.print_fd
, buffer
, sizeof(buffer
)) <= 0)
2083 (*g
.classdriver
)->SoftReset(g
.classdriver
, DEFAULT_TIMEOUT
);
2086 * Release the I/O lock...
2089 pthread_mutex_lock(&g
.readwrite_lock_mutex
);
2090 g
.readwrite_lock
= 0;
2091 pthread_cond_signal(&g
.readwrite_lock_cond
);
2092 pthread_mutex_unlock(&g
.readwrite_lock_mutex
);
2097 * 'get_device_id()' - Return IEEE-1284 device ID.
2100 static void get_device_id(cups_sc_status_t
*status
,
2104 UInt32 deviceLocation
= 0;
2105 UInt8 interfaceNum
= 0;
2106 CFStringRef deviceIDString
= NULL
;
2109 copy_devicestring(g
.printer_obj
, &deviceIDString
, &deviceLocation
, &interfaceNum
);
2112 CFStringGetCString(deviceIDString
, data
, *datalen
, kCFStringEncodingUTF8
);
2113 *datalen
= strlen(data
);
2114 CFRelease(deviceIDString
);
2116 *status
= CUPS_SC_STATUS_OK
;
2121 * End of "$Id: usb-darwin.c 7953 2008-09-17 01:43:19Z mike $".