]>
Commit | Line | Data |
---|---|---|
1 | /* | |
2 | * "$Id$" | |
3 | * | |
4 | * Copyright 2005-2015 Apple Inc. All rights reserved. | |
5 | * | |
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. | |
12 | * | |
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. | |
28 | * | |
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. | |
34 | * | |
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. | |
43 | */ | |
44 | ||
45 | /* | |
46 | * Include necessary headers. | |
47 | */ | |
48 | ||
49 | #include <stdio.h> | |
50 | #include <stdlib.h> | |
51 | #include <errno.h> | |
52 | #include <signal.h> | |
53 | #include <fcntl.h> | |
54 | #include <termios.h> | |
55 | #include <unistd.h> | |
56 | #include <sys/stat.h> | |
57 | #include <sys/sysctl.h> | |
58 | #include <libgen.h> | |
59 | #include <mach/mach.h> | |
60 | #include <mach/mach_error.h> | |
61 | #include <mach/mach_time.h> | |
62 | #include <cups/debug-private.h> | |
63 | #include <cups/file-private.h> | |
64 | #include <cups/sidechannel.h> | |
65 | #include <cups/language-private.h> | |
66 | #include <cups/ppd-private.h> | |
67 | #include "backend-private.h" | |
68 | #include <CoreFoundation/CoreFoundation.h> | |
69 | #include <IOKit/usb/IOUSBLib.h> | |
70 | #include <IOKit/IOCFPlugIn.h> | |
71 | #include <libproc.h> | |
72 | #include <asl.h> | |
73 | #include <spawn.h> | |
74 | #include <pthread.h> | |
75 | ||
76 | /* | |
77 | * Include necessary headers. | |
78 | */ | |
79 | ||
80 | extern char **environ; | |
81 | ||
82 | ||
83 | /* | |
84 | * DEBUG_WRITES, if defined, causes the backend to write data to the printer in | |
85 | * 512 byte increments, up to 8192 bytes, to make debugging with a USB bus | |
86 | * analyzer easier. | |
87 | */ | |
88 | ||
89 | #define DEBUG_WRITES 0 | |
90 | ||
91 | /* | |
92 | * WAIT_EOF_DELAY is number of seconds we'll wait for responses from | |
93 | * the printer after we've finished sending all the data | |
94 | */ | |
95 | #define WAIT_EOF_DELAY 7 | |
96 | #define WAIT_SIDE_DELAY 3 | |
97 | #define DEFAULT_TIMEOUT 5000L | |
98 | ||
99 | #define USB_INTERFACE_KIND CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID245) | |
100 | #define kUSBLanguageEnglish 0x409 | |
101 | ||
102 | #define PRINTER_POLLING_INTERVAL 5 /* seconds */ | |
103 | #define INITIAL_LOG_INTERVAL PRINTER_POLLING_INTERVAL | |
104 | #define SUBSEQUENT_LOG_INTERVAL 3 * INITIAL_LOG_INTERVAL | |
105 | ||
106 | #define kUSBPrinterClassTypeID CFUUIDGetConstantUUIDWithBytes(NULL, 0x06, 0x04, 0x7D, 0x16, 0x53, 0xA2, 0x11, 0xD6, 0x92, 0x06, 0x00, 0x30, 0x65, 0x52, 0x45, 0x92) | |
107 | #define kUSBPrinterClassInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, 0x03, 0x34, 0x6D, 0x74, 0x53, 0xA3, 0x11, 0xD6, 0x9E, 0xA1, 0x76, 0x30, 0x65, 0x52, 0x45, 0x92) | |
108 | ||
109 | #define kUSBClassDriverProperty CFSTR("USB Printing Class") | |
110 | ||
111 | #define kUSBGenericTOPrinterClassDriver CFSTR("/System/Library/Printers/Libraries/USBGenericPrintingClass.plugin") | |
112 | #define kUSBPrinterClassDeviceNotOpen -9664 /*kPMInvalidIOMContext*/ | |
113 | ||
114 | #define CRSetCrashLogMessage(m) _crc_make_setter(message, m) | |
115 | #define _crc_make_setter(attr, arg) (gCRAnnotations.attr = (uint64_t)(unsigned long)(arg)) | |
116 | #define CRASH_REPORTER_CLIENT_HIDDEN __attribute__((visibility("hidden"))) | |
117 | #define CRASHREPORTER_ANNOTATIONS_VERSION 4 | |
118 | #define CRASHREPORTER_ANNOTATIONS_SECTION "__crash_info" | |
119 | ||
120 | struct crashreporter_annotations_t { | |
121 | uint64_t version; // unsigned long | |
122 | uint64_t message; // char * | |
123 | uint64_t signature_string; // char * | |
124 | uint64_t backtrace; // char * | |
125 | uint64_t message2; // char * | |
126 | uint64_t thread; // uint64_t | |
127 | uint64_t dialog_mode; // unsigned int | |
128 | }; | |
129 | ||
130 | CRASH_REPORTER_CLIENT_HIDDEN | |
131 | struct crashreporter_annotations_t gCRAnnotations | |
132 | __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION))) | |
133 | = { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0 }; | |
134 | ||
135 | /* | |
136 | * Section 5.3 USB Printing Class spec | |
137 | */ | |
138 | #define kUSBPrintingSubclass 1 | |
139 | #define kUSBPrintingProtocolNoOpen 0 | |
140 | #define kUSBPrintingProtocolUnidirectional 1 | |
141 | #define kUSBPrintingProtocolBidirectional 2 | |
142 | #define kUSBPrintingProtocolIPP 4 | |
143 | ||
144 | typedef IOUSBInterfaceInterface245 **printer_interface_t; | |
145 | ||
146 | typedef struct iodevice_request_s /**** Device request ****/ | |
147 | { | |
148 | UInt8 requestType; | |
149 | UInt8 request; | |
150 | UInt16 value; | |
151 | UInt16 index; | |
152 | UInt16 length; | |
153 | void *buffer; | |
154 | } iodevice_request_t; | |
155 | ||
156 | typedef union /**** Centronics status byte ****/ | |
157 | { | |
158 | char b; | |
159 | struct | |
160 | { | |
161 | unsigned reserved0:2; | |
162 | unsigned paperError:1; | |
163 | unsigned select:1; | |
164 | unsigned notError:1; | |
165 | unsigned reserved1:3; | |
166 | } status; | |
167 | } centronics_status_t; | |
168 | ||
169 | typedef struct classdriver_s /**** g.classdriver context ****/ | |
170 | { | |
171 | IUNKNOWN_C_GUTS; | |
172 | CFPlugInRef plugin; /* release plugin */ | |
173 | IUnknownVTbl **factory; /* Factory */ | |
174 | void *vendorReference; /* vendor class specific usage */ | |
175 | UInt32 location; /* unique location in bus topology */ | |
176 | UInt8 interfaceNumber; /* Interface number */ | |
177 | UInt16 vendorID; /* Vendor id */ | |
178 | UInt16 productID; /* Product id */ | |
179 | printer_interface_t interface; /* identify the device to IOKit */ | |
180 | UInt8 outpipe; /* mandatory bulkOut pipe */ | |
181 | UInt8 inpipe; /* optional bulkIn pipe */ | |
182 | ||
183 | /* general class requests */ | |
184 | kern_return_t (*DeviceRequest)(struct classdriver_s **printer, iodevice_request_t *iorequest, UInt16 timeout); | |
185 | kern_return_t (*GetString)(struct classdriver_s **printer, UInt8 whichString, UInt16 language, UInt16 timeout, CFStringRef *result); | |
186 | ||
187 | /* standard printer class requests */ | |
188 | kern_return_t (*SoftReset)(struct classdriver_s **printer, UInt16 timeout); | |
189 | kern_return_t (*GetCentronicsStatus)(struct classdriver_s **printer, centronics_status_t *result, UInt16 timeout); | |
190 | kern_return_t (*GetDeviceID)(struct classdriver_s **printer, CFStringRef *devid, UInt16 timeout); | |
191 | ||
192 | /* standard bulk device requests */ | |
193 | kern_return_t (*ReadPipe)(struct classdriver_s **printer, UInt8 *buffer, UInt32 *count); | |
194 | kern_return_t (*WritePipe)(struct classdriver_s **printer, UInt8 *buffer, UInt32 *count, Boolean eoj); | |
195 | ||
196 | /* interface requests */ | |
197 | kern_return_t (*Open)(struct classdriver_s **printer, UInt32 location, UInt8 protocol); | |
198 | kern_return_t (*Abort)(struct classdriver_s **printer); | |
199 | kern_return_t (*Close)(struct classdriver_s **printer); | |
200 | ||
201 | /* initialize and terminate */ | |
202 | kern_return_t (*Initialize)(struct classdriver_s **printer, struct classdriver_s **baseclass); | |
203 | kern_return_t (*Terminate)(struct classdriver_s **printer); | |
204 | ||
205 | } classdriver_t; | |
206 | ||
207 | typedef Boolean (*iterator_callback_t)(void *refcon, io_service_t obj, CFStringRef deviceIDString, UInt32 deviceLocation, UInt8 interfaceNum, UInt8 alternateSetting); | |
208 | ||
209 | typedef struct iterator_reference_s /**** Iterator reference data */ | |
210 | { | |
211 | iterator_callback_t callback; | |
212 | void *userdata; | |
213 | Boolean keepRunning; | |
214 | } iterator_reference_t; | |
215 | ||
216 | typedef struct globals_s | |
217 | { | |
218 | io_service_t printer_obj; | |
219 | classdriver_t **classdriver; | |
220 | ||
221 | pthread_mutex_t read_thread_mutex; | |
222 | pthread_cond_t read_thread_cond; | |
223 | int read_thread_stop; | |
224 | int read_thread_done; | |
225 | ||
226 | pthread_mutex_t readwrite_lock_mutex; | |
227 | pthread_cond_t readwrite_lock_cond; | |
228 | int readwrite_lock; | |
229 | ||
230 | CFStringRef make; | |
231 | CFStringRef model; | |
232 | CFStringRef serial; | |
233 | UInt32 location; | |
234 | UInt8 interfaceNum; | |
235 | UInt8 alternateSetting; | |
236 | ||
237 | CFRunLoopTimerRef status_timer; | |
238 | ||
239 | int print_fd; /* File descriptor to print */ | |
240 | ssize_t print_bytes; /* Print bytes read */ | |
241 | #if DEBUG_WRITES | |
242 | ssize_t debug_bytes; /* Current bytes to read */ | |
243 | #endif /* DEBUG_WRITES */ | |
244 | ||
245 | Boolean use_generic_class_driver; | |
246 | Boolean wait_eof; | |
247 | int drain_output; /* Drain all pending output */ | |
248 | int bidi_flag; /* 0=unidirectional, 1=bidirectional */ | |
249 | ||
250 | pthread_mutex_t sidechannel_thread_mutex; | |
251 | pthread_cond_t sidechannel_thread_cond; | |
252 | int sidechannel_thread_stop; | |
253 | int sidechannel_thread_done; | |
254 | } globals_t; | |
255 | ||
256 | ||
257 | /* | |
258 | * Globals... | |
259 | */ | |
260 | ||
261 | globals_t g = { 0 }; /* Globals */ | |
262 | int Iterating = 0; /* Are we iterating the bus? */ | |
263 | ||
264 | ||
265 | /* | |
266 | * Local functions... | |
267 | */ | |
268 | ||
269 | static Boolean find_device_cb(void *refcon, io_service_t obj, CFStringRef deviceIDString, UInt32 deviceLocation, UInt8 interfaceNum, UInt8 alternateSetting); | |
270 | static Boolean list_device_cb(void *refcon, io_service_t obj, CFStringRef deviceIDString, UInt32 deviceLocation, UInt8 interfaceNum, UInt8 alternateSetting); | |
271 | ||
272 | static CFStringRef cfstr_create_trim(const char *cstr); | |
273 | static CFStringRef copy_value_for_key(CFStringRef deviceID, CFStringRef *keys); | |
274 | static kern_return_t load_classdriver(CFStringRef driverPath, printer_interface_t interface, classdriver_t ***printerDriver); | |
275 | static kern_return_t load_printerdriver(CFStringRef *driverBundlePath); | |
276 | static kern_return_t registry_close(void); | |
277 | static kern_return_t registry_open(CFStringRef *driverBundlePath); | |
278 | static kern_return_t unload_classdriver(classdriver_t ***classdriver); | |
279 | ||
280 | static void *read_thread(void *reference); | |
281 | static void *sidechannel_thread(void *reference); | |
282 | static void device_added(void *userdata, io_iterator_t iterator); | |
283 | static void get_device_id(cups_sc_status_t *status, char *data, int *datalen); | |
284 | static void iterate_printers(iterator_callback_t callBack, void *userdata); | |
285 | static void parse_options(char *options, char *serial, int serial_size, UInt32 *location, Boolean *wait_eof); | |
286 | static void setup_cfLanguage(void); | |
287 | static void soft_reset(void); | |
288 | static void status_timer_cb(CFRunLoopTimerRef timer, void *info); | |
289 | static void log_usb_class_driver(int is_64bit); | |
290 | #define IS_64BIT 1 | |
291 | #define IS_NOT_64BIT 0 | |
292 | ||
293 | #if defined(__i386__) || defined(__x86_64__) | |
294 | static pid_t child_pid; /* Child PID */ | |
295 | static void run_legacy_backend(int argc, char *argv[], int fd) __attribute__((noreturn)); /* Starts child backend process running as a ppc executable */ | |
296 | #endif /* __i386__ || __x86_64__ */ | |
297 | static void sigterm_handler(int sig); /* SIGTERM handler */ | |
298 | static void sigquit_handler(int sig, siginfo_t *si, void *unused) __attribute__((noreturn)); | |
299 | ||
300 | #ifdef PARSE_PS_ERRORS | |
301 | static const char *next_line (const char *buffer); | |
302 | static void parse_pserror (char *sockBuffer, int len); | |
303 | #endif /* PARSE_PS_ERRORS */ | |
304 | ||
305 | static printer_interface_t usb_printer_interface_interface(io_service_t usbClass); | |
306 | static IOUSBDeviceInterface **usb_device_interface_for_device(io_service_t usbDevice); | |
307 | static CFStringRef copy_printer_interface_deviceid(printer_interface_t printer, UInt8 alternateSetting); | |
308 | static CFStringRef copy_printer_interface_indexed_description(printer_interface_t printer, UInt8 index, UInt16 language); | |
309 | static CFStringRef deviceIDCopyManufacturer(CFStringRef deviceID); | |
310 | static CFStringRef deviceIDCopyModel(CFStringRef deviceID); | |
311 | static CFStringRef deviceIDCopySerialNumber(CFStringRef deviceID); | |
312 | ||
313 | #pragma mark - | |
314 | ||
315 | /* | |
316 | * 'list_devices()' - List all USB devices. | |
317 | */ | |
318 | ||
319 | void list_devices() | |
320 | { | |
321 | iterate_printers(list_device_cb, NULL); | |
322 | } | |
323 | ||
324 | ||
325 | /* | |
326 | * 'print_device()' - Print a file to a USB device. | |
327 | */ | |
328 | ||
329 | int /* O - Exit status */ | |
330 | print_device(const char *uri, /* I - Device URI */ | |
331 | const char *hostname, /* I - Hostname/manufacturer */ | |
332 | const char *resource, /* I - Resource/modelname */ | |
333 | char *options, /* I - Device options/serial number */ | |
334 | int print_fd, /* I - File descriptor to print */ | |
335 | int copies, /* I - Copies to print */ | |
336 | int argc, /* I - Number of command-line arguments (6 or 7) */ | |
337 | char *argv[]) /* I - Command-line arguments */ | |
338 | { | |
339 | char serial[1024]; /* Serial number buffer */ | |
340 | OSStatus status; /* Function results */ | |
341 | IOReturn iostatus; /* Current IO status */ | |
342 | pthread_t read_thread_id, /* Read thread */ | |
343 | sidechannel_thread_id;/* Side-channel thread */ | |
344 | int have_sidechannel = 0; /* Was the side-channel thread started? */ | |
345 | struct stat sidechannel_info; /* Side-channel file descriptor info */ | |
346 | char print_buffer[8192], /* Print data buffer */ | |
347 | *print_ptr; /* Pointer into print data buffer */ | |
348 | UInt32 location; /* Unique location in bus topology */ | |
349 | fd_set input_set; /* Input set for select() */ | |
350 | CFStringRef driverBundlePath; /* Class driver path */ | |
351 | int countdown, /* Logging interval */ | |
352 | nfds; /* Number of file descriptors */ | |
353 | ssize_t total_bytes; /* Total bytes written */ | |
354 | UInt32 bytes; /* Bytes written */ | |
355 | struct timeval *timeout, /* Timeout pointer */ | |
356 | tv; /* Time value */ | |
357 | struct timespec cond_timeout; /* pthread condition timeout */ | |
358 | struct sigaction action; /* Actions for POSIX signals */ | |
359 | ||
360 | ||
361 | (void)uri; | |
362 | ||
363 | /* | |
364 | * Catch SIGQUIT to determine who is sending it... | |
365 | */ | |
366 | ||
367 | memset(&action, 0, sizeof(action)); | |
368 | action.sa_sigaction = sigquit_handler; | |
369 | action.sa_flags = SA_SIGINFO; | |
370 | sigaction(SIGQUIT, &action, NULL); | |
371 | ||
372 | /* | |
373 | * See if the side-channel descriptor is valid... | |
374 | */ | |
375 | ||
376 | have_sidechannel = !fstat(CUPS_SC_FD, &sidechannel_info) && | |
377 | S_ISSOCK(sidechannel_info.st_mode); | |
378 | ||
379 | /* | |
380 | * Localize using CoreFoundation... | |
381 | */ | |
382 | ||
383 | setup_cfLanguage(); | |
384 | ||
385 | parse_options(options, serial, sizeof(serial), &location, &g.wait_eof); | |
386 | ||
387 | if (resource[0] == '/') | |
388 | resource++; | |
389 | ||
390 | g.print_fd = print_fd; | |
391 | g.make = cfstr_create_trim(hostname); | |
392 | g.model = cfstr_create_trim(resource); | |
393 | g.serial = cfstr_create_trim(serial); | |
394 | g.location = location; | |
395 | ||
396 | if (!g.make || !g.model) | |
397 | { | |
398 | fprintf(stderr, "DEBUG: Fatal USB error.\n"); | |
399 | _cupsLangPrintFilter(stderr, "ERROR", | |
400 | _("There was an unrecoverable USB error.")); | |
401 | ||
402 | if (!g.make) | |
403 | fputs("DEBUG: USB make string is NULL\n", stderr); | |
404 | if (!g.model) | |
405 | fputs("DEBUG: USB model string is NULL\n", stderr); | |
406 | ||
407 | return (CUPS_BACKEND_STOP); | |
408 | } | |
409 | ||
410 | fputs("STATE: +connecting-to-device\n", stderr); | |
411 | ||
412 | countdown = INITIAL_LOG_INTERVAL; | |
413 | ||
414 | do | |
415 | { | |
416 | if (g.printer_obj) | |
417 | { | |
418 | IOObjectRelease(g.printer_obj); | |
419 | unload_classdriver(&g.classdriver); | |
420 | g.printer_obj = 0x0; | |
421 | g.classdriver = 0x0; | |
422 | } | |
423 | ||
424 | fprintf(stderr, "DEBUG: Looking for '%s %s'\n", hostname, resource); | |
425 | ||
426 | iterate_printers(find_device_cb, NULL); | |
427 | ||
428 | fputs("DEBUG: Opening connection\n", stderr); | |
429 | ||
430 | driverBundlePath = NULL; | |
431 | ||
432 | status = registry_open(&driverBundlePath); | |
433 | ||
434 | #if defined(__i386__) || defined(__x86_64__) | |
435 | /* | |
436 | * If we were unable to load the class drivers for this printer it's | |
437 | * probably because they're ppc or i386. In this case try to run this | |
438 | * backend as i386 or ppc executables so we can use them... | |
439 | */ | |
440 | if (status == -2) | |
441 | { | |
442 | run_legacy_backend(argc, argv, print_fd); | |
443 | /* Never returns here */ | |
444 | } | |
445 | #endif /* __i386__ || __x86_64__ */ | |
446 | ||
447 | if (status == -2) | |
448 | { | |
449 | /* | |
450 | * If we still were unable to load the class drivers for this printer log | |
451 | * the error and stop the queue... | |
452 | */ | |
453 | ||
454 | if (driverBundlePath == NULL || !CFStringGetCString(driverBundlePath, print_buffer, sizeof(print_buffer), kCFStringEncodingUTF8)) | |
455 | strlcpy(print_buffer, "USB class driver", sizeof(print_buffer)); | |
456 | ||
457 | fputs("STATE: +apple-missing-usbclassdriver-error\n", stderr); | |
458 | _cupsLangPrintFilter(stderr, "ERROR", | |
459 | _("There was an unrecoverable USB error.")); | |
460 | fprintf(stderr, "DEBUG: Could not load %s\n", print_buffer); | |
461 | ||
462 | if (driverBundlePath) | |
463 | CFRelease(driverBundlePath); | |
464 | ||
465 | return (CUPS_BACKEND_STOP); | |
466 | } | |
467 | ||
468 | #ifdef __x86_64__ | |
469 | if (status == noErr && driverBundlePath != NULL && CFStringCompare(driverBundlePath, kUSBGenericTOPrinterClassDriver, 0) != kCFCompareEqualTo) | |
470 | log_usb_class_driver(IS_64BIT); | |
471 | #endif /* __x86_64__ */ | |
472 | ||
473 | if (driverBundlePath) | |
474 | CFRelease(driverBundlePath); | |
475 | ||
476 | if (status != noErr) | |
477 | { | |
478 | sleep(PRINTER_POLLING_INTERVAL); | |
479 | countdown -= PRINTER_POLLING_INTERVAL; | |
480 | if (countdown <= 0) | |
481 | { | |
482 | _cupsLangPrintFilter(stderr, "INFO", | |
483 | _("Waiting for printer to become available.")); | |
484 | fprintf(stderr, "DEBUG: USB printer status: 0x%08x\n", (int)status); | |
485 | countdown = SUBSEQUENT_LOG_INTERVAL; /* subsequent log entries, every 15 seconds */ | |
486 | } | |
487 | } | |
488 | } while (status != noErr); | |
489 | ||
490 | fputs("STATE: -connecting-to-device\n", stderr); | |
491 | ||
492 | /* | |
493 | * Now that we are "connected" to the port, ignore SIGTERM so that we | |
494 | * can finish out any page data the driver sends (e.g. to eject the | |
495 | * current page... Only ignore SIGTERM if we are printing data from | |
496 | * stdin (otherwise you can't cancel raw jobs...) | |
497 | */ | |
498 | ||
499 | if (!print_fd) | |
500 | { | |
501 | memset(&action, 0, sizeof(action)); | |
502 | ||
503 | sigemptyset(&action.sa_mask); | |
504 | action.sa_handler = SIG_IGN; | |
505 | sigaction(SIGTERM, &action, NULL); | |
506 | } | |
507 | ||
508 | /* | |
509 | * Start the side channel thread if the descriptor is valid... | |
510 | */ | |
511 | ||
512 | pthread_mutex_init(&g.readwrite_lock_mutex, NULL); | |
513 | pthread_cond_init(&g.readwrite_lock_cond, NULL); | |
514 | g.readwrite_lock = 1; | |
515 | ||
516 | if (have_sidechannel) | |
517 | { | |
518 | g.sidechannel_thread_stop = 0; | |
519 | g.sidechannel_thread_done = 0; | |
520 | ||
521 | pthread_cond_init(&g.sidechannel_thread_cond, NULL); | |
522 | pthread_mutex_init(&g.sidechannel_thread_mutex, NULL); | |
523 | ||
524 | if (pthread_create(&sidechannel_thread_id, NULL, sidechannel_thread, NULL)) | |
525 | { | |
526 | fprintf(stderr, "DEBUG: Fatal USB error.\n"); | |
527 | _cupsLangPrintFilter(stderr, "ERROR", | |
528 | _("There was an unrecoverable USB error.")); | |
529 | fputs("DEBUG: Couldn't create side-channel thread\n", stderr); | |
530 | registry_close(); | |
531 | return (CUPS_BACKEND_STOP); | |
532 | } | |
533 | } | |
534 | ||
535 | /* | |
536 | * Get the read thread going... | |
537 | */ | |
538 | ||
539 | g.read_thread_stop = 0; | |
540 | g.read_thread_done = 0; | |
541 | ||
542 | pthread_cond_init(&g.read_thread_cond, NULL); | |
543 | pthread_mutex_init(&g.read_thread_mutex, NULL); | |
544 | ||
545 | if (pthread_create(&read_thread_id, NULL, read_thread, NULL)) | |
546 | { | |
547 | fprintf(stderr, "DEBUG: Fatal USB error.\n"); | |
548 | _cupsLangPrintFilter(stderr, "ERROR", | |
549 | _("There was an unrecoverable USB error.")); | |
550 | fputs("DEBUG: Couldn't create read thread\n", stderr); | |
551 | registry_close(); | |
552 | return (CUPS_BACKEND_STOP); | |
553 | } | |
554 | ||
555 | /* | |
556 | * The main thread sends the print file... | |
557 | */ | |
558 | ||
559 | g.drain_output = 0; | |
560 | g.print_bytes = 0; | |
561 | total_bytes = 0; | |
562 | print_ptr = print_buffer; | |
563 | ||
564 | while (status == noErr && copies-- > 0) | |
565 | { | |
566 | _cupsLangPrintFilter(stderr, "INFO", _("Sending data to printer.")); | |
567 | ||
568 | if (print_fd != STDIN_FILENO) | |
569 | { | |
570 | fputs("PAGE: 1 1\n", stderr); | |
571 | lseek(print_fd, 0, SEEK_SET); | |
572 | } | |
573 | ||
574 | while (status == noErr) | |
575 | { | |
576 | FD_ZERO(&input_set); | |
577 | ||
578 | if (!g.print_bytes) | |
579 | FD_SET(print_fd, &input_set); | |
580 | ||
581 | /* | |
582 | * Calculate select timeout... | |
583 | * If we have data waiting to send timeout is 100ms. | |
584 | * else if we're draining print_fd timeout is 0. | |
585 | * else we're waiting forever... | |
586 | */ | |
587 | ||
588 | if (g.print_bytes) | |
589 | { | |
590 | tv.tv_sec = 0; | |
591 | tv.tv_usec = 100000; /* 100ms */ | |
592 | timeout = &tv; | |
593 | } | |
594 | else if (g.drain_output) | |
595 | { | |
596 | tv.tv_sec = 0; | |
597 | tv.tv_usec = 0; | |
598 | timeout = &tv; | |
599 | } | |
600 | else | |
601 | timeout = NULL; | |
602 | ||
603 | /* | |
604 | * I/O is unlocked around select... | |
605 | */ | |
606 | ||
607 | pthread_mutex_lock(&g.readwrite_lock_mutex); | |
608 | g.readwrite_lock = 0; | |
609 | pthread_cond_signal(&g.readwrite_lock_cond); | |
610 | pthread_mutex_unlock(&g.readwrite_lock_mutex); | |
611 | ||
612 | nfds = select(print_fd + 1, &input_set, NULL, NULL, timeout); | |
613 | ||
614 | /* | |
615 | * Reacquire the lock... | |
616 | */ | |
617 | ||
618 | pthread_mutex_lock(&g.readwrite_lock_mutex); | |
619 | while (g.readwrite_lock) | |
620 | pthread_cond_wait(&g.readwrite_lock_cond, &g.readwrite_lock_mutex); | |
621 | g.readwrite_lock = 1; | |
622 | pthread_mutex_unlock(&g.readwrite_lock_mutex); | |
623 | ||
624 | if (nfds < 0) | |
625 | { | |
626 | if (errno == EINTR && total_bytes == 0) | |
627 | { | |
628 | fputs("DEBUG: Received an interrupt before any bytes were " | |
629 | "written, aborting\n", stderr); | |
630 | registry_close(); | |
631 | return (CUPS_BACKEND_OK); | |
632 | } | |
633 | else if (errno != EAGAIN && errno != EINTR) | |
634 | { | |
635 | _cupsLangPrintFilter(stderr, "ERROR", | |
636 | _("Unable to read print data.")); | |
637 | perror("DEBUG: select"); | |
638 | registry_close(); | |
639 | return (CUPS_BACKEND_FAILED); | |
640 | } | |
641 | } | |
642 | ||
643 | /* | |
644 | * If drain output has finished send a response... | |
645 | */ | |
646 | ||
647 | if (g.drain_output && !nfds && !g.print_bytes) | |
648 | { | |
649 | /* Send a response... */ | |
650 | cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT, CUPS_SC_STATUS_OK, NULL, 0, 1.0); | |
651 | g.drain_output = 0; | |
652 | } | |
653 | ||
654 | /* | |
655 | * Check if we have print data ready... | |
656 | */ | |
657 | ||
658 | if (FD_ISSET(print_fd, &input_set)) | |
659 | { | |
660 | #if DEBUG_WRITES | |
661 | g.debug_bytes += 512; | |
662 | if (g.debug_bytes > sizeof(print_buffer)) | |
663 | g.debug_bytes = 512; | |
664 | ||
665 | g.print_bytes = read(print_fd, print_buffer, g.debug_bytes); | |
666 | ||
667 | #else | |
668 | g.print_bytes = read(print_fd, print_buffer, sizeof(print_buffer)); | |
669 | #endif /* DEBUG_WRITES */ | |
670 | ||
671 | if (g.print_bytes < 0) | |
672 | { | |
673 | /* | |
674 | * Read error - bail if we don't see EAGAIN or EINTR... | |
675 | */ | |
676 | ||
677 | if (errno != EAGAIN && errno != EINTR) | |
678 | { | |
679 | _cupsLangPrintFilter(stderr, "ERROR", | |
680 | _("Unable to read print data.")); | |
681 | perror("DEBUG: read"); | |
682 | registry_close(); | |
683 | return (CUPS_BACKEND_FAILED); | |
684 | } | |
685 | ||
686 | g.print_bytes = 0; | |
687 | } | |
688 | else if (g.print_bytes == 0) | |
689 | { | |
690 | /* | |
691 | * End of file, break out of the loop... | |
692 | */ | |
693 | ||
694 | break; | |
695 | } | |
696 | ||
697 | print_ptr = print_buffer; | |
698 | ||
699 | fprintf(stderr, "DEBUG: Read %d bytes of print data...\n", | |
700 | (int)g.print_bytes); | |
701 | } | |
702 | ||
703 | if (g.print_bytes) | |
704 | { | |
705 | bytes = (UInt32)g.print_bytes; | |
706 | iostatus = (*g.classdriver)->WritePipe(g.classdriver, (UInt8*)print_ptr, &bytes, 0); | |
707 | ||
708 | /* | |
709 | * Ignore timeout errors, but retain the number of bytes written to | |
710 | * avoid sending duplicate data... | |
711 | */ | |
712 | ||
713 | if (iostatus == kIOUSBTransactionTimeout) | |
714 | { | |
715 | fputs("DEBUG: Got USB transaction timeout during write\n", stderr); | |
716 | iostatus = 0; | |
717 | } | |
718 | ||
719 | /* | |
720 | * If we've stalled, retry the write... | |
721 | */ | |
722 | ||
723 | else if (iostatus == kIOUSBPipeStalled) | |
724 | { | |
725 | fputs("DEBUG: Got USB pipe stalled during write\n", stderr); | |
726 | ||
727 | bytes = (UInt32)g.print_bytes; | |
728 | iostatus = (*g.classdriver)->WritePipe(g.classdriver, (UInt8*)print_ptr, &bytes, 0); | |
729 | } | |
730 | ||
731 | /* | |
732 | * Retry a write after an aborted write since we probably just got | |
733 | * SIGTERM... | |
734 | */ | |
735 | ||
736 | else if (iostatus == kIOReturnAborted) | |
737 | { | |
738 | fputs("DEBUG: Got USB return aborted during write\n", stderr); | |
739 | ||
740 | IOReturn err = (*g.classdriver)->Abort(g.classdriver); | |
741 | fprintf(stderr, "DEBUG: USB class driver Abort returned %x\n", err); | |
742 | ||
743 | #if DEBUG_WRITES | |
744 | sleep(5); | |
745 | #endif /* DEBUG_WRITES */ | |
746 | ||
747 | bytes = (UInt32)g.print_bytes; | |
748 | iostatus = (*g.classdriver)->WritePipe(g.classdriver, (UInt8*)print_ptr, &bytes, 0); | |
749 | } | |
750 | ||
751 | if (iostatus) | |
752 | { | |
753 | /* | |
754 | * Write error - bail if we don't see an error we can retry... | |
755 | */ | |
756 | ||
757 | _cupsLangPrintFilter(stderr, "ERROR", | |
758 | _("Unable to send data to printer.")); | |
759 | fprintf(stderr, "DEBUG: USB class driver WritePipe returned %x\n", | |
760 | iostatus); | |
761 | ||
762 | IOReturn err = (*g.classdriver)->Abort(g.classdriver); | |
763 | fprintf(stderr, "DEBUG: USB class driver Abort returned %x\n", | |
764 | err); | |
765 | ||
766 | status = CUPS_BACKEND_FAILED; | |
767 | break; | |
768 | } | |
769 | else if (bytes > 0) | |
770 | { | |
771 | fprintf(stderr, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes); | |
772 | ||
773 | g.print_bytes -= bytes; | |
774 | print_ptr += bytes; | |
775 | total_bytes += bytes; | |
776 | } | |
777 | } | |
778 | ||
779 | if (print_fd != 0 && status == noErr) | |
780 | fprintf(stderr, "DEBUG: Sending print file, %lld bytes...\n", | |
781 | (off_t)total_bytes); | |
782 | } | |
783 | } | |
784 | ||
785 | fprintf(stderr, "DEBUG: Sent %lld bytes...\n", (off_t)total_bytes); | |
786 | fputs("STATE: +cups-waiting-for-job-completed\n", stderr); | |
787 | ||
788 | /* | |
789 | * Signal the side channel thread to exit... | |
790 | */ | |
791 | ||
792 | if (have_sidechannel) | |
793 | { | |
794 | close(CUPS_SC_FD); | |
795 | pthread_mutex_lock(&g.readwrite_lock_mutex); | |
796 | g.readwrite_lock = 0; | |
797 | pthread_cond_signal(&g.readwrite_lock_cond); | |
798 | pthread_mutex_unlock(&g.readwrite_lock_mutex); | |
799 | ||
800 | g.sidechannel_thread_stop = 1; | |
801 | pthread_mutex_lock(&g.sidechannel_thread_mutex); | |
802 | ||
803 | if (!g.sidechannel_thread_done) | |
804 | { | |
805 | gettimeofday(&tv, NULL); | |
806 | cond_timeout.tv_sec = tv.tv_sec + WAIT_SIDE_DELAY; | |
807 | cond_timeout.tv_nsec = tv.tv_usec * 1000; | |
808 | ||
809 | while (!g.sidechannel_thread_done) | |
810 | { | |
811 | if (pthread_cond_timedwait(&g.sidechannel_thread_cond, | |
812 | &g.sidechannel_thread_mutex, | |
813 | &cond_timeout) != 0) | |
814 | break; | |
815 | } | |
816 | } | |
817 | ||
818 | pthread_mutex_unlock(&g.sidechannel_thread_mutex); | |
819 | } | |
820 | ||
821 | /* | |
822 | * Signal the read thread to exit then wait 7 seconds for it to complete... | |
823 | */ | |
824 | ||
825 | g.read_thread_stop = 1; | |
826 | ||
827 | pthread_mutex_lock(&g.read_thread_mutex); | |
828 | ||
829 | if (!g.read_thread_done) | |
830 | { | |
831 | fputs("DEBUG: Waiting for read thread to exit...\n", stderr); | |
832 | ||
833 | gettimeofday(&tv, NULL); | |
834 | cond_timeout.tv_sec = tv.tv_sec + WAIT_EOF_DELAY; | |
835 | cond_timeout.tv_nsec = tv.tv_usec * 1000; | |
836 | ||
837 | while (!g.read_thread_done) | |
838 | { | |
839 | if (pthread_cond_timedwait(&g.read_thread_cond, &g.read_thread_mutex, | |
840 | &cond_timeout) != 0) | |
841 | break; | |
842 | } | |
843 | ||
844 | /* | |
845 | * If it didn't exit abort the pending read and wait an additional second... | |
846 | */ | |
847 | ||
848 | if (!g.read_thread_done) | |
849 | { | |
850 | fputs("DEBUG: Read thread still active, aborting the pending read...\n", | |
851 | stderr); | |
852 | ||
853 | g.wait_eof = 0; | |
854 | ||
855 | (*g.classdriver)->Abort(g.classdriver); | |
856 | ||
857 | gettimeofday(&tv, NULL); | |
858 | cond_timeout.tv_sec = tv.tv_sec + 1; | |
859 | cond_timeout.tv_nsec = tv.tv_usec * 1000; | |
860 | ||
861 | while (!g.read_thread_done) | |
862 | { | |
863 | if (pthread_cond_timedwait(&g.read_thread_cond, &g.read_thread_mutex, | |
864 | &cond_timeout) != 0) | |
865 | break; | |
866 | } | |
867 | } | |
868 | } | |
869 | ||
870 | pthread_mutex_unlock(&g.read_thread_mutex); | |
871 | ||
872 | /* | |
873 | * Close the connection and input file and general clean up... | |
874 | */ | |
875 | ||
876 | registry_close(); | |
877 | ||
878 | if (print_fd != STDIN_FILENO) | |
879 | close(print_fd); | |
880 | ||
881 | if (g.make != NULL) | |
882 | CFRelease(g.make); | |
883 | ||
884 | if (g.model != NULL) | |
885 | CFRelease(g.model); | |
886 | ||
887 | if (g.serial != NULL) | |
888 | CFRelease(g.serial); | |
889 | ||
890 | if (g.printer_obj != 0x0) | |
891 | IOObjectRelease(g.printer_obj); | |
892 | ||
893 | return status; | |
894 | } | |
895 | ||
896 | ||
897 | /* | |
898 | * 'read_thread()' - Thread to read the backchannel data on. | |
899 | */ | |
900 | ||
901 | static void *read_thread(void *reference) | |
902 | { | |
903 | UInt8 readbuffer[512]; | |
904 | UInt32 rbytes; | |
905 | kern_return_t readstatus; | |
906 | struct mach_timebase_info timeBaseInfo; | |
907 | uint64_t start, | |
908 | delay; | |
909 | ||
910 | ||
911 | (void)reference; | |
912 | ||
913 | /* Calculate what 250 milliSeconds are in mach absolute time... | |
914 | */ | |
915 | mach_timebase_info(&timeBaseInfo); | |
916 | delay = ((uint64_t)250000000 * (uint64_t)timeBaseInfo.denom) / (uint64_t)timeBaseInfo.numer; | |
917 | ||
918 | do | |
919 | { | |
920 | /* | |
921 | * Remember when we started so we can throttle the loop after the read call... | |
922 | */ | |
923 | ||
924 | start = mach_absolute_time(); | |
925 | ||
926 | rbytes = sizeof(readbuffer); | |
927 | readstatus = (*g.classdriver)->ReadPipe(g.classdriver, readbuffer, &rbytes); | |
928 | if (readstatus == kIOReturnSuccess && rbytes > 0) | |
929 | { | |
930 | fprintf(stderr, "DEBUG: Read %d bytes of back-channel data...\n", | |
931 | (int)rbytes); | |
932 | cupsBackChannelWrite((char*)readbuffer, rbytes, 1.0); | |
933 | ||
934 | /* cntrl-d is echoed by the printer. | |
935 | * NOTES: | |
936 | * Xerox Phaser 6250D doesn't echo the cntrl-d. | |
937 | * Xerox Phaser 6250D doesn't always send the product query. | |
938 | */ | |
939 | if (g.wait_eof && readbuffer[rbytes-1] == 0x4) | |
940 | break; | |
941 | ||
942 | #ifdef PARSE_PS_ERRORS | |
943 | parse_pserror(readbuffer, rbytes); | |
944 | #endif | |
945 | } | |
946 | else if (readstatus == kIOUSBTransactionTimeout) | |
947 | fputs("DEBUG: Got USB transaction timeout during read\n", stderr); | |
948 | else if (readstatus == kIOUSBPipeStalled) | |
949 | fputs("DEBUG: Got USB pipe stalled during read\n", stderr); | |
950 | else if (readstatus == kIOReturnAborted) | |
951 | fputs("DEBUG: Got USB return aborted during read\n", stderr); | |
952 | ||
953 | /* | |
954 | * Make sure this loop executes no more than once every 250 miliseconds... | |
955 | */ | |
956 | ||
957 | if ((readstatus != kIOReturnSuccess || rbytes == 0) && (g.wait_eof || !g.read_thread_stop)) | |
958 | mach_wait_until(start + delay); | |
959 | ||
960 | } while (g.wait_eof || !g.read_thread_stop); /* Abort from main thread tests error here */ | |
961 | ||
962 | /* Workaround for usb race condition. <rdar://problem/21882551> */ | |
963 | if (!g.wait_eof && g.use_generic_class_driver) | |
964 | { | |
965 | const char *pdl = getenv("FINAL_CONTENT_TYPE"); | |
966 | if (pdl && strcmp(pdl, "application/vnd.cups-postscript") == 0) | |
967 | { | |
968 | while (readstatus == kIOReturnSuccess && ((rbytes > 0 && readbuffer[rbytes-1] != 0x4) || rbytes == 0)) | |
969 | { | |
970 | start = mach_absolute_time(); | |
971 | ||
972 | rbytes = sizeof(readbuffer); | |
973 | readstatus = (*g.classdriver)->ReadPipe(g.classdriver, readbuffer, &rbytes); | |
974 | if (readstatus == kIOReturnSuccess && rbytes > 0 && readbuffer[rbytes-1] == 0x4) | |
975 | break; | |
976 | ||
977 | /* Make sure this loop executes no more than once every 250 miliseconds... */ | |
978 | mach_wait_until(start + delay); | |
979 | } | |
980 | } | |
981 | } | |
982 | ||
983 | /* | |
984 | * Let the main thread know that we have completed the read thread... | |
985 | */ | |
986 | ||
987 | pthread_mutex_lock(&g.read_thread_mutex); | |
988 | g.read_thread_done = 1; | |
989 | pthread_cond_signal(&g.read_thread_cond); | |
990 | pthread_mutex_unlock(&g.read_thread_mutex); | |
991 | ||
992 | return NULL; | |
993 | } | |
994 | ||
995 | ||
996 | /* | |
997 | * 'sidechannel_thread()' - Handle side-channel requests. | |
998 | */ | |
999 | ||
1000 | static void* | |
1001 | sidechannel_thread(void *reference) | |
1002 | { | |
1003 | cups_sc_command_t command; /* Request command */ | |
1004 | cups_sc_status_t status; /* Request/response status */ | |
1005 | char data[2048]; /* Request/response data */ | |
1006 | int datalen; /* Request/response data size */ | |
1007 | ||
1008 | ||
1009 | (void)reference; | |
1010 | ||
1011 | do | |
1012 | { | |
1013 | datalen = sizeof(data); | |
1014 | ||
1015 | if (cupsSideChannelRead(&command, &status, data, &datalen, 1.0)) | |
1016 | { | |
1017 | if (status == CUPS_SC_STATUS_TIMEOUT) | |
1018 | continue; | |
1019 | else | |
1020 | break; | |
1021 | } | |
1022 | ||
1023 | switch (command) | |
1024 | { | |
1025 | case CUPS_SC_CMD_SOFT_RESET: /* Do a soft reset */ | |
1026 | fputs("DEBUG: CUPS_SC_CMD_SOFT_RESET received from driver...\n", | |
1027 | stderr); | |
1028 | ||
1029 | if ((*g.classdriver)->SoftReset != NULL) | |
1030 | { | |
1031 | soft_reset(); | |
1032 | cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, NULL, 0, 1.0); | |
1033 | fputs("DEBUG: Returning status CUPS_STATUS_OK with no bytes...\n", | |
1034 | stderr); | |
1035 | } | |
1036 | else | |
1037 | { | |
1038 | cupsSideChannelWrite(command, CUPS_SC_STATUS_NOT_IMPLEMENTED, | |
1039 | NULL, 0, 1.0); | |
1040 | fputs("DEBUG: Returning status CUPS_STATUS_NOT_IMPLEMENTED with " | |
1041 | "no bytes...\n", stderr); | |
1042 | } | |
1043 | break; | |
1044 | ||
1045 | case CUPS_SC_CMD_DRAIN_OUTPUT: /* Drain all pending output */ | |
1046 | fputs("DEBUG: CUPS_SC_CMD_DRAIN_OUTPUT received from driver...\n", | |
1047 | stderr); | |
1048 | ||
1049 | g.drain_output = 1; | |
1050 | break; | |
1051 | ||
1052 | case CUPS_SC_CMD_GET_BIDI: /* Is the connection bidirectional? */ | |
1053 | fputs("DEBUG: CUPS_SC_CMD_GET_BIDI received from driver...\n", | |
1054 | stderr); | |
1055 | ||
1056 | data[0] = (char)g.bidi_flag; | |
1057 | cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, data, 1, 1.0); | |
1058 | ||
1059 | fprintf(stderr, | |
1060 | "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n", | |
1061 | data[0]); | |
1062 | break; | |
1063 | ||
1064 | case CUPS_SC_CMD_GET_DEVICE_ID: /* Return IEEE-1284 device ID */ | |
1065 | fputs("DEBUG: CUPS_SC_CMD_GET_DEVICE_ID received from driver...\n", | |
1066 | stderr); | |
1067 | ||
1068 | datalen = sizeof(data); | |
1069 | get_device_id(&status, data, &datalen); | |
1070 | cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, data, datalen, 1.0); | |
1071 | ||
1072 | if ((size_t)datalen < sizeof(data)) | |
1073 | data[datalen] = '\0'; | |
1074 | else | |
1075 | data[sizeof(data) - 1] = '\0'; | |
1076 | ||
1077 | fprintf(stderr, | |
1078 | "DEBUG: Returning CUPS_SC_STATUS_OK with %d bytes (%s)...\n", | |
1079 | datalen, data); | |
1080 | break; | |
1081 | ||
1082 | case CUPS_SC_CMD_GET_STATE: /* Return device state */ | |
1083 | fputs("DEBUG: CUPS_SC_CMD_GET_STATE received from driver...\n", | |
1084 | stderr); | |
1085 | ||
1086 | data[0] = CUPS_SC_STATE_ONLINE; | |
1087 | cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, data, 1, 1.0); | |
1088 | ||
1089 | fprintf(stderr, | |
1090 | "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n", | |
1091 | data[0]); | |
1092 | break; | |
1093 | ||
1094 | default: | |
1095 | fprintf(stderr, "DEBUG: Unknown side-channel command (%d) received " | |
1096 | "from driver...\n", command); | |
1097 | ||
1098 | cupsSideChannelWrite(command, CUPS_SC_STATUS_NOT_IMPLEMENTED, | |
1099 | NULL, 0, 1.0); | |
1100 | ||
1101 | fputs("DEBUG: Returned CUPS_SC_STATUS_NOT_IMPLEMENTED with no bytes...\n", | |
1102 | stderr); | |
1103 | break; | |
1104 | } | |
1105 | } | |
1106 | while (!g.sidechannel_thread_stop); | |
1107 | ||
1108 | pthread_mutex_lock(&g.sidechannel_thread_mutex); | |
1109 | g.sidechannel_thread_done = 1; | |
1110 | pthread_cond_signal(&g.sidechannel_thread_cond); | |
1111 | pthread_mutex_unlock(&g.sidechannel_thread_mutex); | |
1112 | ||
1113 | return NULL; | |
1114 | } | |
1115 | ||
1116 | ||
1117 | #pragma mark - | |
1118 | /* | |
1119 | * 'iterate_printers()' - Iterate over all the printers. | |
1120 | */ | |
1121 | ||
1122 | static void iterate_printers(iterator_callback_t callBack, void *userdata) | |
1123 | { | |
1124 | Iterating = 1; | |
1125 | ||
1126 | mach_port_t masterPort = 0x0; | |
1127 | kern_return_t kr = IOMasterPort (bootstrap_port, &masterPort); | |
1128 | ||
1129 | if (kr == kIOReturnSuccess && masterPort != 0x0) | |
1130 | { | |
1131 | iterator_reference_t reference = { callBack, userdata, true }; | |
1132 | ||
1133 | IONotificationPortRef addNotification = IONotificationPortCreate(masterPort); | |
1134 | io_iterator_t addIterator = IO_OBJECT_NULL; | |
1135 | ||
1136 | kr = IOServiceAddMatchingNotification(addNotification, kIOFirstMatchNotification, IOServiceMatching(kIOUSBDeviceClassName), | |
1137 | &device_added, &reference, &addIterator); | |
1138 | if (kr == kIOReturnSuccess && addIterator != IO_OBJECT_NULL) | |
1139 | { | |
1140 | device_added(&reference, addIterator); | |
1141 | if (reference.keepRunning) | |
1142 | { | |
1143 | CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification), kCFRunLoopDefaultMode); | |
1144 | CFRunLoopRun(); | |
1145 | } | |
1146 | IOObjectRelease(addIterator); | |
1147 | } | |
1148 | mach_port_deallocate(mach_task_self(), masterPort); | |
1149 | } | |
1150 | ||
1151 | Iterating = 0; | |
1152 | } | |
1153 | ||
1154 | ||
1155 | /* | |
1156 | * 'device_added()' - Device added notifier. | |
1157 | */ | |
1158 | #define IsPrintingInterface(c,s,p) ((c) == kUSBPrintingInterfaceClass && (s) == kUSBPrintingSubclass && (p) != kUSBPrintingProtocolIPP) | |
1159 | ||
1160 | static void device_added(void *userdata, io_iterator_t iterator) | |
1161 | { | |
1162 | iterator_reference_t *reference = userdata; | |
1163 | io_service_t device; | |
1164 | ||
1165 | while (reference->keepRunning && (device = IOIteratorNext(iterator)) != 0x0) | |
1166 | { | |
1167 | UInt32 locationID = 0; | |
1168 | IOUSBDeviceInterface **devIntf = NULL; | |
1169 | io_iterator_t intfIterator = IO_OBJECT_NULL; | |
1170 | io_object_t intf = IO_OBJECT_NULL; | |
1171 | ||
1172 | devIntf = usb_device_interface_for_device(device); | |
1173 | if (devIntf == NULL) | |
1174 | goto device_added_done; | |
1175 | ||
1176 | UInt16 vendorUniqueID; | |
1177 | if ((*devIntf)->GetDeviceVendor(devIntf, &vendorUniqueID) != kIOReturnSuccess || vendorUniqueID == kAppleVendorID || vendorUniqueID == 0x0A5C) | |
1178 | goto device_added_done; | |
1179 | ||
1180 | if ((*devIntf)->GetLocationID(devIntf, &locationID) != kIOReturnSuccess) | |
1181 | goto device_added_done; | |
1182 | ||
1183 | IOUSBFindInterfaceRequest req = { kIOUSBFindInterfaceDontCare, kIOUSBFindInterfaceDontCare, kIOUSBFindInterfaceDontCare, kIOUSBFindInterfaceDontCare }; | |
1184 | if ((*devIntf)->CreateInterfaceIterator(devIntf, &req, &intfIterator) != kIOReturnSuccess) | |
1185 | goto device_added_done; | |
1186 | ||
1187 | while (reference->keepRunning && (intf = IOIteratorNext(intfIterator))) | |
1188 | { | |
1189 | printer_interface_t printerIntf = usb_printer_interface_interface(intf); | |
1190 | if (printerIntf != NULL) | |
1191 | { | |
1192 | UInt8 intfClass = 0, intfSubclass = 0, intfProtocol = 0, intfNumber = 0; | |
1193 | ||
1194 | (*printerIntf)->GetInterfaceClass(printerIntf, &intfClass); | |
1195 | (*printerIntf)->GetInterfaceSubClass(printerIntf, &intfSubclass); | |
1196 | (*printerIntf)->GetInterfaceProtocol(printerIntf, &intfProtocol); | |
1197 | (*printerIntf)->GetInterfaceNumber(printerIntf, &intfNumber); | |
1198 | ||
1199 | if (IsPrintingInterface(intfClass, intfSubclass, intfProtocol)) | |
1200 | { | |
1201 | CFStringRef deviceIDString = copy_printer_interface_deviceid(printerIntf, 0); | |
1202 | if (deviceIDString != NULL) | |
1203 | { | |
1204 | reference->keepRunning = reference->callback(userdata, intf, deviceIDString, locationID, intfNumber, 0); | |
1205 | CFRelease(deviceIDString); | |
1206 | } | |
1207 | } | |
1208 | ||
1209 | IOUSBInterfaceDescriptor *intfDesc = NULL; | |
1210 | while (reference->keepRunning && (intfDesc = (IOUSBInterfaceDescriptor *)(*printerIntf)->FindNextAssociatedDescriptor(printerIntf, intfDesc, kUSBInterfaceDesc))) | |
1211 | { | |
1212 | intfClass = intfDesc->bInterfaceClass; | |
1213 | intfSubclass = intfDesc->bInterfaceSubClass; | |
1214 | intfProtocol = intfDesc->bInterfaceProtocol; | |
1215 | ||
1216 | if ((IsPrintingInterface(intfClass, intfSubclass, intfProtocol))) | |
1217 | { | |
1218 | CFStringRef deviceIDString = copy_printer_interface_deviceid(printerIntf, intfDesc->bAlternateSetting); | |
1219 | if (deviceIDString != NULL) | |
1220 | { | |
1221 | reference->keepRunning = reference->callback(userdata, intf, deviceIDString, locationID, intfNumber, intfDesc->bAlternateSetting); | |
1222 | CFRelease(deviceIDString); | |
1223 | } | |
1224 | } | |
1225 | } | |
1226 | (*printerIntf)->Release(printerIntf); | |
1227 | } | |
1228 | IOObjectRelease(intf); | |
1229 | } | |
1230 | ||
1231 | device_added_done: | |
1232 | if (devIntf != NULL) (*devIntf)->Release(devIntf); | |
1233 | if (intfIterator != IO_OBJECT_NULL) IOObjectRelease(intfIterator); | |
1234 | ||
1235 | IOObjectRelease(device); | |
1236 | } | |
1237 | ||
1238 | /* One last call to the call back now that we are not longer have printers left to iterate... | |
1239 | */ | |
1240 | if (reference->keepRunning && reference->callback) | |
1241 | reference->keepRunning = reference->callback(reference->userdata, IO_OBJECT_NULL, NULL, 0, 0, 0); | |
1242 | ||
1243 | if (!reference->keepRunning) | |
1244 | CFRunLoopStop(CFRunLoopGetCurrent()); | |
1245 | } | |
1246 | ||
1247 | /* | |
1248 | * 'list_device_cb()' - list_device iterator callback. | |
1249 | */ | |
1250 | ||
1251 | static Boolean list_device_cb(void *refcon, io_service_t obj, CFStringRef deviceIDString, UInt32 deviceLocation, UInt8 interfaceNum, UInt8 alternateSetting) | |
1252 | { | |
1253 | (void)refcon; | |
1254 | (void)interfaceNum; | |
1255 | (void)alternateSetting; | |
1256 | ||
1257 | if (obj != IO_OBJECT_NULL) | |
1258 | { | |
1259 | CFStringRef make = deviceIDCopyManufacturer(deviceIDString); | |
1260 | CFStringRef model = deviceIDCopyModel(deviceIDString); | |
1261 | CFStringRef serial = deviceIDCopySerialNumber(deviceIDString); | |
1262 | ||
1263 | char uristr[1024], makestr[1024], modelstr[1024], serialstr[1024]; | |
1264 | char optionsstr[1024], idstr[1024], make_modelstr[1024]; | |
1265 | ||
1266 | CFStringGetCString(deviceIDString, idstr, sizeof(idstr), kCFStringEncodingUTF8); | |
1267 | backendGetMakeModel(idstr, make_modelstr, sizeof(make_modelstr)); | |
1268 | ||
1269 | modelstr[0] = '/'; | |
1270 | ||
1271 | if (make == NULL || !CFStringGetCString(make, makestr, sizeof(makestr), kCFStringEncodingUTF8)) | |
1272 | strlcpy(makestr, "Unknown", sizeof(makestr)); | |
1273 | ||
1274 | if (model == NULL || !CFStringGetCString(model, &modelstr[1], sizeof(modelstr)-1, kCFStringEncodingUTF8)) | |
1275 | strlcpy(modelstr + 1, "Printer", sizeof(modelstr) - 1); | |
1276 | ||
1277 | optionsstr[0] = '\0'; | |
1278 | if (serial != NULL && CFStringGetCString(serial, serialstr, sizeof(serialstr), kCFStringEncodingUTF8)) | |
1279 | snprintf(optionsstr, sizeof(optionsstr), "?serial=%s", serialstr); | |
1280 | else if (deviceLocation != 0) | |
1281 | snprintf(optionsstr, sizeof(optionsstr), "?location=%x", (unsigned)deviceLocation); | |
1282 | ||
1283 | httpAssembleURI(HTTP_URI_CODING_ALL, uristr, sizeof(uristr), "usb", NULL, makestr, 0, modelstr); | |
1284 | strlcat(uristr, optionsstr, sizeof(uristr)); | |
1285 | ||
1286 | cupsBackendReport("direct", uristr, make_modelstr, make_modelstr, idstr, | |
1287 | NULL); | |
1288 | ||
1289 | if (make != NULL) CFRelease(make); | |
1290 | if (model != NULL) CFRelease(model); | |
1291 | if (serial != NULL) CFRelease(serial); | |
1292 | } | |
1293 | ||
1294 | return obj != IO_OBJECT_NULL; | |
1295 | } | |
1296 | ||
1297 | /* | |
1298 | * 'find_device_cb()' - print_device iterator callback. | |
1299 | */ | |
1300 | static Boolean find_device_cb(void *refcon, io_service_t obj, CFStringRef deviceIDString, UInt32 deviceLocation, UInt8 interfaceNum, UInt8 alternateSetting) | |
1301 | { | |
1302 | Boolean keepLooking = true; | |
1303 | ||
1304 | if (obj != IO_OBJECT_NULL) | |
1305 | { | |
1306 | CFStringRef make = deviceIDCopyManufacturer(deviceIDString); | |
1307 | CFStringRef model = deviceIDCopyModel(deviceIDString); | |
1308 | CFStringRef serial = deviceIDCopySerialNumber(deviceIDString); | |
1309 | ||
1310 | if (make && CFStringCompare(make, g.make, kCFCompareCaseInsensitive) == kCFCompareEqualTo) | |
1311 | { | |
1312 | if (model && CFStringCompare(model, g.model, kCFCompareCaseInsensitive) == kCFCompareEqualTo) | |
1313 | { | |
1314 | if (g.serial != NULL && CFStringGetLength(g.serial) > 0) | |
1315 | { | |
1316 | if (serial != NULL && CFStringCompare(serial, g.serial, kCFCompareCaseInsensitive) == kCFCompareEqualTo) | |
1317 | { | |
1318 | IOObjectRetain(obj); | |
1319 | g.printer_obj = obj; | |
1320 | g.location = deviceLocation; | |
1321 | g.alternateSetting = alternateSetting; | |
1322 | keepLooking = false; | |
1323 | } | |
1324 | } | |
1325 | else | |
1326 | { | |
1327 | if (g.printer_obj != 0) | |
1328 | IOObjectRelease(g.printer_obj); | |
1329 | ||
1330 | g.alternateSetting = alternateSetting; | |
1331 | g.printer_obj = obj; | |
1332 | IOObjectRetain(obj); | |
1333 | ||
1334 | if (g.location == 0 || g.location == deviceLocation) | |
1335 | keepLooking = false; | |
1336 | } | |
1337 | ||
1338 | if ( !keepLooking ) | |
1339 | g.interfaceNum = interfaceNum; | |
1340 | } | |
1341 | } | |
1342 | ||
1343 | if (make) CFRelease(make); | |
1344 | if (model) CFRelease(model); | |
1345 | if (serial) CFRelease(serial); | |
1346 | } | |
1347 | else | |
1348 | { | |
1349 | keepLooking = (g.printer_obj == 0); | |
1350 | if (obj == IO_OBJECT_NULL && keepLooking) | |
1351 | { | |
1352 | CFRunLoopTimerContext context = { 0, refcon, NULL, NULL, NULL }; | |
1353 | CFRunLoopTimerRef timer = CFRunLoopTimerCreate(NULL, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb, &context); | |
1354 | if (timer != NULL) | |
1355 | { | |
1356 | CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode); | |
1357 | g.status_timer = timer; | |
1358 | } | |
1359 | } | |
1360 | } | |
1361 | ||
1362 | if (!keepLooking && g.status_timer != NULL) | |
1363 | { | |
1364 | fputs("STATE: -offline-report\n", stderr); | |
1365 | _cupsLangPrintFilter(stderr, "INFO", _("The printer is now online.")); | |
1366 | CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g.status_timer, kCFRunLoopDefaultMode); | |
1367 | CFRelease(g.status_timer); | |
1368 | g.status_timer = NULL; | |
1369 | } | |
1370 | ||
1371 | return keepLooking; | |
1372 | } | |
1373 | ||
1374 | static CFStringRef deviceIDCopySerialNumber(CFStringRef deviceID) | |
1375 | { | |
1376 | CFStringRef serialKeys[] = { CFSTR("SN:"), CFSTR("SERN:"), NULL }; | |
1377 | ||
1378 | return copy_value_for_key(deviceID, serialKeys); | |
1379 | } | |
1380 | ||
1381 | static CFStringRef deviceIDCopyModel(CFStringRef deviceID) | |
1382 | { | |
1383 | CFStringRef modelKeys[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL }; | |
1384 | return copy_value_for_key(deviceID, modelKeys); | |
1385 | } | |
1386 | ||
1387 | static CFStringRef deviceIDCopyManufacturer(CFStringRef deviceID) | |
1388 | { | |
1389 | CFStringRef makeKeys[] = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL }; | |
1390 | return copy_value_for_key(deviceID, makeKeys); | |
1391 | } | |
1392 | ||
1393 | /* | |
1394 | * 'status_timer_cb()' - Status timer callback. | |
1395 | */ | |
1396 | ||
1397 | static void status_timer_cb(CFRunLoopTimerRef timer, | |
1398 | void *info) | |
1399 | { | |
1400 | (void)timer; | |
1401 | (void)info; | |
1402 | ||
1403 | fputs("STATE: +offline-report\n", stderr); | |
1404 | _cupsLangPrintFilter(stderr, "INFO", _("The printer is offline.")); | |
1405 | ||
1406 | if (getenv("CLASS") != NULL) | |
1407 | { | |
1408 | /* | |
1409 | * If the CLASS environment variable is set, the job was submitted | |
1410 | * to a class and not to a specific queue. In this case, we want | |
1411 | * to abort immediately so that the job can be requeued on the next | |
1412 | * available printer in the class. | |
1413 | * | |
1414 | * Sleep 5 seconds to keep the job from requeuing too rapidly... | |
1415 | */ | |
1416 | ||
1417 | sleep(5); | |
1418 | ||
1419 | exit(CUPS_BACKEND_FAILED); | |
1420 | } | |
1421 | } | |
1422 | ||
1423 | ||
1424 | #pragma mark - | |
1425 | /* | |
1426 | * 'load_classdriver()' - Load a classdriver. | |
1427 | */ | |
1428 | ||
1429 | static kern_return_t load_classdriver(CFStringRef driverPath, | |
1430 | printer_interface_t interface, | |
1431 | classdriver_t ***printerDriver) | |
1432 | { | |
1433 | kern_return_t kr = kUSBPrinterClassDeviceNotOpen; | |
1434 | classdriver_t **driver = NULL; | |
1435 | CFStringRef bundle = driverPath ? driverPath : kUSBGenericTOPrinterClassDriver; | |
1436 | char bundlestr[1024]; /* Bundle path */ | |
1437 | CFURLRef url; /* URL for driver */ | |
1438 | CFPlugInRef plugin = NULL; /* Plug-in address */ | |
1439 | ||
1440 | ||
1441 | CFStringGetCString(bundle, bundlestr, sizeof(bundlestr), kCFStringEncodingUTF8); | |
1442 | ||
1443 | /* | |
1444 | * Validate permissions for the class driver... | |
1445 | */ | |
1446 | ||
1447 | _cups_fc_result_t result = _cupsFileCheck(bundlestr, | |
1448 | _CUPS_FILE_CHECK_DIRECTORY, 1, | |
1449 | Iterating ? NULL : _cupsFileCheckFilter, NULL); | |
1450 | ||
1451 | if (result && driverPath) | |
1452 | return (load_classdriver(NULL, interface, printerDriver)); | |
1453 | else if (result) | |
1454 | return (kr); | |
1455 | ||
1456 | /* | |
1457 | * Try loading the class driver... | |
1458 | */ | |
1459 | ||
1460 | url = CFURLCreateWithFileSystemPath(NULL, bundle, kCFURLPOSIXPathStyle, true); | |
1461 | ||
1462 | if (url) | |
1463 | { | |
1464 | plugin = CFPlugInCreate(NULL, url); | |
1465 | CFRelease(url); | |
1466 | } | |
1467 | else | |
1468 | plugin = NULL; | |
1469 | ||
1470 | if (plugin) | |
1471 | { | |
1472 | CFArrayRef factories = CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID, plugin); | |
1473 | if (factories != NULL && CFArrayGetCount(factories) > 0) | |
1474 | { | |
1475 | CFUUIDRef factoryID = CFArrayGetValueAtIndex(factories, 0); | |
1476 | IUnknownVTbl **iunknown = CFPlugInInstanceCreate(NULL, factoryID, kUSBPrinterClassTypeID); | |
1477 | if (iunknown != NULL) | |
1478 | { | |
1479 | kr = (*iunknown)->QueryInterface(iunknown, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID), (LPVOID *)&driver); | |
1480 | if (kr == kIOReturnSuccess && driver != NULL) | |
1481 | { | |
1482 | classdriver_t **genericDriver = NULL; | |
1483 | if (driverPath != NULL && CFStringCompare(driverPath, kUSBGenericTOPrinterClassDriver, 0) != kCFCompareEqualTo) | |
1484 | kr = load_classdriver(NULL, interface, &genericDriver); | |
1485 | ||
1486 | if (kr == kIOReturnSuccess) | |
1487 | { | |
1488 | (*driver)->interface = interface; | |
1489 | (*driver)->Initialize(driver, genericDriver); | |
1490 | ||
1491 | (*driver)->plugin = plugin; | |
1492 | (*driver)->interface = interface; | |
1493 | *printerDriver = driver; | |
1494 | } | |
1495 | } | |
1496 | (*iunknown)->Release(iunknown); | |
1497 | } | |
1498 | CFRelease(factories); | |
1499 | } | |
1500 | } | |
1501 | ||
1502 | fprintf(stderr, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr, (int)kr); | |
1503 | ||
1504 | return (kr); | |
1505 | } | |
1506 | ||
1507 | ||
1508 | /* | |
1509 | * 'unload_classdriver()' - Unload a classdriver. | |
1510 | */ | |
1511 | ||
1512 | static kern_return_t unload_classdriver(classdriver_t ***classdriver) | |
1513 | { | |
1514 | if (*classdriver != NULL) | |
1515 | { | |
1516 | (**classdriver)->Release(*classdriver); | |
1517 | *classdriver = NULL; | |
1518 | } | |
1519 | ||
1520 | return kIOReturnSuccess; | |
1521 | } | |
1522 | ||
1523 | ||
1524 | /* | |
1525 | * 'load_printerdriver()' - Load vendor's classdriver. | |
1526 | * | |
1527 | * If driverBundlePath is not NULL on return it is the callers responsbility to release it! | |
1528 | */ | |
1529 | ||
1530 | static kern_return_t load_printerdriver(CFStringRef *driverBundlePath) | |
1531 | { | |
1532 | IOCFPlugInInterface **iodev = NULL; | |
1533 | SInt32 score; | |
1534 | kern_return_t kr; | |
1535 | printer_interface_t interface; | |
1536 | HRESULT res; | |
1537 | ||
1538 | kr = IOCreatePlugInInterfaceForService(g.printer_obj, kIOUSBInterfaceUserClientTypeID, kIOCFPlugInInterfaceID, &iodev, &score); | |
1539 | if (kr == kIOReturnSuccess) | |
1540 | { | |
1541 | if ((res = (*iodev)->QueryInterface(iodev, USB_INTERFACE_KIND, (LPVOID *) &interface)) == noErr) | |
1542 | { | |
1543 | *driverBundlePath = IORegistryEntryCreateCFProperty(g.printer_obj, kUSBClassDriverProperty, NULL, kNilOptions); | |
1544 | ||
1545 | g.use_generic_class_driver = (*driverBundlePath == NULL || (CFStringCompare(*driverBundlePath, kUSBGenericTOPrinterClassDriver, 0x0) == kCFCompareEqualTo)); | |
1546 | kr = load_classdriver(*driverBundlePath, interface, &g.classdriver); | |
1547 | ||
1548 | if (kr != kIOReturnSuccess) | |
1549 | (*interface)->Release(interface); | |
1550 | } | |
1551 | IODestroyPlugInInterface(iodev); | |
1552 | } | |
1553 | return kr; | |
1554 | } | |
1555 | ||
1556 | static printer_interface_t usb_printer_interface_interface(io_service_t usbClass) | |
1557 | { | |
1558 | printer_interface_t intf = NULL; | |
1559 | IOCFPlugInInterface **plugin = NULL; | |
1560 | SInt32 score; | |
1561 | int kr = IOCreatePlugInInterfaceForService(usbClass, kIOUSBInterfaceUserClientTypeID, kIOCFPlugInInterfaceID, &plugin, &score); | |
1562 | if (kr == kIOReturnSuccess) | |
1563 | { | |
1564 | (*plugin)->QueryInterface(plugin, USB_INTERFACE_KIND, (LPVOID *)&intf); | |
1565 | IODestroyPlugInInterface(plugin); | |
1566 | } | |
1567 | ||
1568 | return intf; | |
1569 | } | |
1570 | ||
1571 | static IOUSBDeviceInterface **usb_device_interface_for_device(io_service_t usbDevice) | |
1572 | { | |
1573 | IOUSBDeviceInterface ** intf = NULL; | |
1574 | IOCFPlugInInterface **plugin = NULL; | |
1575 | SInt32 score; | |
1576 | ||
1577 | int kr = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID, kIOCFPlugInInterfaceID, &plugin, &score); | |
1578 | if (kr == kIOReturnSuccess) | |
1579 | { | |
1580 | (*plugin)->QueryInterface(plugin, CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID), (LPVOID *)&intf); | |
1581 | IODestroyPlugInInterface(plugin); | |
1582 | } | |
1583 | ||
1584 | return intf; | |
1585 | } | |
1586 | ||
1587 | ||
1588 | static CFStringRef copy_printer_interface_deviceid(printer_interface_t printer, UInt8 alternateSetting) | |
1589 | { | |
1590 | // I have tried to make this function as neat as I can, but the possibility of needing to resend | |
1591 | // a request to get the entire string makes it hideous... | |
1592 | // | |
1593 | // We package the job of sending a request up into the block (^sendRequest), which takes the size | |
1594 | // it should allocate for the message buffer. It frees the current buffer if one is set and | |
1595 | // allocates one of the specified size, then performs the request. We can then easily retry by | |
1596 | // calling the block again if we fail to get the whole string the first time around. | |
1597 | ||
1598 | #define kUSBPrintClassGetDeviceID 0 | |
1599 | #define kDefaultNoDataTimeout 5000L | |
1600 | #define pack_device_id_wIndex(intf, alt) ((UInt16)((((UInt16)(intf)) << 8) | ((UInt8)(alt)))) | |
1601 | ||
1602 | if (printer == NULL) | |
1603 | return NULL; | |
1604 | ||
1605 | ||
1606 | IOReturn err = kIOReturnError; | |
1607 | UInt8 configurationIndex = 0; | |
1608 | UInt8 interfaceNumber = 0; | |
1609 | size_t bufferLength = 256; | |
1610 | CFStringRef ret = NULL; | |
1611 | ||
1612 | if ((*printer)->GetConfigurationValue( printer, &configurationIndex) == kIOReturnSuccess && | |
1613 | (*printer)->GetInterfaceNumber( printer, &interfaceNumber) == kIOReturnSuccess) | |
1614 | { | |
1615 | __block IOUSBDevRequestTO request; | |
1616 | IOReturn (^sendRequest)(size_t) = ^ (size_t size) | |
1617 | { | |
1618 | if (request.pData) | |
1619 | { | |
1620 | free(request.pData); | |
1621 | request.wLength = 0; | |
1622 | request.pData = NULL; | |
1623 | } | |
1624 | ||
1625 | IOReturn berr = kIOReturnError; | |
1626 | char *buffer = malloc(size); | |
1627 | if (buffer == NULL) | |
1628 | return kIOReturnNoMemory; | |
1629 | ||
1630 | request.wLength = HostToUSBWord(size); | |
1631 | request.pData = buffer; | |
1632 | berr = (*printer)->ControlRequestTO(printer, (UInt8)0, &request); | |
1633 | return berr; | |
1634 | }; | |
1635 | ||
1636 | /* This request takes the 0 based configuration index. IOKit returns a 1 based configuration index */ | |
1637 | configurationIndex -= 1; | |
1638 | ||
1639 | bzero(&request, sizeof(request)); | |
1640 | ||
1641 | request.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBClass, kUSBInterface); | |
1642 | request.bRequest = kUSBPrintClassGetDeviceID; | |
1643 | request.wValue = HostToUSBWord(configurationIndex); | |
1644 | request.wIndex = HostToUSBWord(pack_device_id_wIndex(interfaceNumber, alternateSetting)); | |
1645 | request.noDataTimeout = kDefaultNoDataTimeout; | |
1646 | request.completionTimeout = 0; // Copying behavior from Generic Class Driver | |
1647 | ||
1648 | err = sendRequest(bufferLength); | |
1649 | ||
1650 | if (err == kIOReturnSuccess && request.wLenDone > 1) | |
1651 | { | |
1652 | UInt16 actualLength = OSSwapBigToHostInt16(*((UInt16 *)request.pData)); | |
1653 | ||
1654 | if (actualLength > 2 && actualLength <= bufferLength - 2) | |
1655 | { | |
1656 | ret = CFStringCreateWithBytes(NULL, (const UInt8 *) &request.pData[2], actualLength - 2, kCFStringEncodingUTF8, false); | |
1657 | } | |
1658 | else if (actualLength > 2) { | |
1659 | err = sendRequest(actualLength); | |
1660 | if (err == kIOReturnSuccess && request.wLenDone > 0) | |
1661 | { | |
1662 | actualLength = OSSwapBigToHostInt16(*((UInt16 *)request.pData)); | |
1663 | ret = CFStringCreateWithBytes(NULL, (const UInt8 *) &request.pData[2], actualLength - 2, kCFStringEncodingUTF8, false); | |
1664 | } | |
1665 | } | |
1666 | } | |
1667 | ||
1668 | if (request.pData) | |
1669 | free(request.pData); | |
1670 | } | |
1671 | ||
1672 | CFStringRef manufacturer = deviceIDCopyManufacturer(ret); | |
1673 | CFStringRef model = deviceIDCopyModel(ret); | |
1674 | CFStringRef serial = deviceIDCopySerialNumber(ret); | |
1675 | ||
1676 | if (manufacturer == NULL || serial == NULL || model == NULL) | |
1677 | { | |
1678 | IOUSBDevRequestTO request; | |
1679 | IOUSBDeviceDescriptor desc; | |
1680 | ||
1681 | bzero(&request, sizeof(request)); | |
1682 | ||
1683 | request.bmRequestType = USBmakebmRequestType( kUSBIn, kUSBStandard, kUSBDevice ); | |
1684 | request.bRequest = kUSBRqGetDescriptor; | |
1685 | request.wValue = kUSBDeviceDesc << 8; | |
1686 | request.wIndex = 0; | |
1687 | request.wLength = sizeof(desc); | |
1688 | request.pData = &desc; | |
1689 | request.completionTimeout = 0; | |
1690 | request.noDataTimeout = 60L; | |
1691 | ||
1692 | err = (*printer)->ControlRequestTO(printer, 0, &request); | |
1693 | if (err == kIOReturnSuccess) | |
1694 | { | |
1695 | CFMutableStringRef extras = CFStringCreateMutable(NULL, 0); | |
1696 | if (manufacturer == NULL) | |
1697 | { | |
1698 | manufacturer = copy_printer_interface_indexed_description(printer, desc.iManufacturer, kUSBLanguageEnglish); | |
1699 | if (manufacturer && CFStringGetLength(manufacturer) > 0) | |
1700 | CFStringAppendFormat(extras, NULL, CFSTR("MFG:%@;"), manufacturer); | |
1701 | } | |
1702 | ||
1703 | if (model == NULL) | |
1704 | { | |
1705 | model = copy_printer_interface_indexed_description(printer, desc.iProduct, kUSBLanguageEnglish); | |
1706 | if (model && CFStringGetLength(model) > 0) | |
1707 | CFStringAppendFormat(extras, NULL, CFSTR("MDL:%@;"), model); | |
1708 | } | |
1709 | ||
1710 | if (serial == NULL && desc.iSerialNumber != 0) | |
1711 | { | |
1712 | serial = copy_printer_interface_indexed_description(printer, desc.iSerialNumber, kUSBLanguageEnglish); | |
1713 | if (serial && CFStringGetLength(serial) > 0) | |
1714 | CFStringAppendFormat(extras, NULL, CFSTR("SERN:%@;"), serial); | |
1715 | } | |
1716 | ||
1717 | if (ret != NULL) | |
1718 | { | |
1719 | CFStringAppend(extras, ret); | |
1720 | CFRelease(ret); | |
1721 | ||
1722 | ret = extras; | |
1723 | } | |
1724 | else | |
1725 | { | |
1726 | ret = extras; | |
1727 | } | |
1728 | } | |
1729 | } | |
1730 | ||
1731 | if (ret != NULL) | |
1732 | { | |
1733 | /* Remove special characters from the serial number */ | |
1734 | CFRange range = (serial != NULL ? CFStringFind(serial, CFSTR("+"), 0) : CFRangeMake(0, 0)); | |
1735 | if (range.length == 1) | |
1736 | { | |
1737 | range = CFStringFind(ret, serial, 0); | |
1738 | ||
1739 | CFMutableStringRef deviceIDString = CFStringCreateMutableCopy(NULL, 0, ret); | |
1740 | CFRelease(ret); | |
1741 | ||
1742 | ret = deviceIDString; | |
1743 | CFStringFindAndReplace(deviceIDString, CFSTR("+"), CFSTR(""), range, 0); | |
1744 | } | |
1745 | } | |
1746 | ||
1747 | if (manufacturer != NULL) | |
1748 | CFRelease(manufacturer); | |
1749 | ||
1750 | if (model != NULL) | |
1751 | CFRelease(model); | |
1752 | ||
1753 | if (serial != NULL) | |
1754 | CFRelease(serial); | |
1755 | ||
1756 | if (ret != NULL && CFStringGetLength(ret) == 0) | |
1757 | { | |
1758 | CFRelease(ret); | |
1759 | return NULL; | |
1760 | } | |
1761 | ||
1762 | return ret; | |
1763 | } | |
1764 | ||
1765 | static CFStringRef copy_printer_interface_indexed_description(printer_interface_t printer, UInt8 index, UInt16 language) | |
1766 | { | |
1767 | IOReturn err; | |
1768 | UInt8 description[256]; // Max possible descriptor length | |
1769 | IOUSBDevRequestTO request; | |
1770 | ||
1771 | bzero(description, 2); | |
1772 | ||
1773 | request.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice); | |
1774 | request.bRequest = kUSBRqGetDescriptor; | |
1775 | request.wValue = (kUSBStringDesc << 8) | index; | |
1776 | request.wIndex = language; | |
1777 | request.wLength = 2; | |
1778 | request.pData = &description; | |
1779 | request.completionTimeout = 0; | |
1780 | request.noDataTimeout = 60L; | |
1781 | ||
1782 | err = (*printer)->ControlRequestTO(printer, 0, &request); | |
1783 | if (err != kIOReturnSuccess && err != kIOReturnOverrun) | |
1784 | { | |
1785 | bzero(description, request.wLength); | |
1786 | ||
1787 | // Let's try again full length. Here's why: | |
1788 | // On USB 2.0 controllers, we will not get an overrun error. We just get a "babble" error | |
1789 | // and no valid data. So, if we ask for the max size, we will either get it, or we'll get an underrun. | |
1790 | // It looks like we get it w/out an underrun | |
1791 | ||
1792 | request.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice); | |
1793 | request.bRequest = kUSBRqGetDescriptor; | |
1794 | request.wValue = (kUSBStringDesc << 8) | index; | |
1795 | request.wIndex = language; | |
1796 | request.wLength = sizeof description; | |
1797 | request.pData = &description; | |
1798 | request.completionTimeout = 0; | |
1799 | request.noDataTimeout = 60L; | |
1800 | ||
1801 | err = (*printer)->ControlRequestTO(printer, 0, &request); | |
1802 | if (err != kIOReturnSuccess && err != kIOReturnUnderrun) | |
1803 | return NULL; | |
1804 | } | |
1805 | ||
1806 | unsigned int length = description[0]; | |
1807 | if (length == 0) | |
1808 | return CFStringCreateWithCString(NULL, "", kCFStringEncodingUTF8); | |
1809 | ||
1810 | if (description[1] != kUSBStringDesc) | |
1811 | return NULL; | |
1812 | ||
1813 | request.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice); | |
1814 | request.bRequest = kUSBRqGetDescriptor; | |
1815 | request.wValue = (kUSBStringDesc << 8) | index; | |
1816 | request.wIndex = language; | |
1817 | ||
1818 | bzero(description, length); | |
1819 | request.wLength = (UInt16)length; | |
1820 | request.pData = &description; | |
1821 | request.completionTimeout = 0; | |
1822 | request.noDataTimeout = 60L; | |
1823 | ||
1824 | err = (*printer)->ControlRequestTO(printer, 0, &request); | |
1825 | if (err != kIOReturnSuccess) | |
1826 | return NULL; | |
1827 | ||
1828 | if (description[1] != kUSBStringDesc) | |
1829 | return NULL; | |
1830 | ||
1831 | if ((description[0] & 1) != 0) | |
1832 | description[0] &= 0xfe; | |
1833 | ||
1834 | char buffer[258] = {}; | |
1835 | unsigned int maxLength = sizeof buffer; | |
1836 | if (description[0] > 1) | |
1837 | { | |
1838 | length = (description[0]-2)/2; | |
1839 | ||
1840 | if (length > maxLength - 1) | |
1841 | length = maxLength -1; | |
1842 | ||
1843 | for (unsigned i = 0; i < length; i++) | |
1844 | buffer[i] = (char) description[2*i+2]; | |
1845 | ||
1846 | buffer[length] = 0; | |
1847 | } | |
1848 | ||
1849 | return CFStringCreateWithCString(NULL, buffer, kCFStringEncodingUTF8); | |
1850 | } | |
1851 | ||
1852 | /* | |
1853 | * 'registry_open()' - Open a connection to the printer. | |
1854 | */ | |
1855 | ||
1856 | static kern_return_t registry_open(CFStringRef *driverBundlePath) | |
1857 | { | |
1858 | g.bidi_flag = 0; /* 0=unidirectional */ | |
1859 | ||
1860 | kern_return_t kr = load_printerdriver(driverBundlePath); | |
1861 | if (kr != kIOReturnSuccess) | |
1862 | kr = -2; | |
1863 | ||
1864 | if (g.classdriver != NULL) | |
1865 | { | |
1866 | (*g.classdriver)->interfaceNumber = g.interfaceNum; | |
1867 | kr = (*g.classdriver)->Open(g.classdriver, g.location, kUSBPrintingProtocolBidirectional); | |
1868 | if (kr != kIOReturnSuccess || (*g.classdriver)->interface == NULL) | |
1869 | { | |
1870 | kr = (*g.classdriver)->Open(g.classdriver, g.location, kUSBPrintingProtocolUnidirectional); | |
1871 | if (kr == kIOReturnSuccess) | |
1872 | { | |
1873 | if ((*g.classdriver)->interface == NULL) | |
1874 | { | |
1875 | (*g.classdriver)->Close(g.classdriver); | |
1876 | kr = -1; | |
1877 | } | |
1878 | } | |
1879 | } | |
1880 | else | |
1881 | g.bidi_flag = 1; /* 1=bidirectional */ | |
1882 | } | |
1883 | ||
1884 | if (kr != kIOReturnSuccess) | |
1885 | unload_classdriver(&g.classdriver); | |
1886 | ||
1887 | return kr; | |
1888 | } | |
1889 | ||
1890 | ||
1891 | /* | |
1892 | * 'registry_close()' - Close the connection to the printer. | |
1893 | */ | |
1894 | ||
1895 | static kern_return_t registry_close(void) | |
1896 | { | |
1897 | if (g.classdriver != NULL) | |
1898 | (*g.classdriver)->Close(g.classdriver); | |
1899 | ||
1900 | unload_classdriver(&g.classdriver); | |
1901 | return kIOReturnSuccess; | |
1902 | } | |
1903 | ||
1904 | #pragma mark - | |
1905 | /* | |
1906 | * 'copy_value_for_key()' - Copy value string associated with a key. | |
1907 | */ | |
1908 | ||
1909 | static CFStringRef copy_value_for_key(CFStringRef deviceID, | |
1910 | CFStringRef *keys) | |
1911 | { | |
1912 | CFStringRef value = NULL; | |
1913 | CFArrayRef kvPairs = deviceID != NULL ? CFStringCreateArrayBySeparatingStrings(NULL, deviceID, CFSTR(";")) : NULL; | |
1914 | CFIndex max = kvPairs != NULL ? CFArrayGetCount(kvPairs) : 0; | |
1915 | CFIndex idx = 0; | |
1916 | ||
1917 | while (idx < max && value == NULL) | |
1918 | { | |
1919 | CFStringRef kvpair = CFArrayGetValueAtIndex(kvPairs, idx); | |
1920 | CFIndex idxx = 0; | |
1921 | while (keys[idxx] != NULL && value == NULL) | |
1922 | { | |
1923 | CFRange range = CFStringFind(kvpair, keys[idxx], kCFCompareCaseInsensitive); | |
1924 | if (range.length != -1) | |
1925 | { | |
1926 | if (range.location != 0) | |
1927 | { | |
1928 | CFMutableStringRef theString = CFStringCreateMutableCopy(NULL, 0, kvpair); | |
1929 | CFStringTrimWhitespace(theString); | |
1930 | range = CFStringFind(theString, keys[idxx], kCFCompareCaseInsensitive); | |
1931 | if (range.location == 0) | |
1932 | value = CFStringCreateWithSubstring(NULL, theString, CFRangeMake(range.length, CFStringGetLength(theString) - range.length)); | |
1933 | ||
1934 | CFRelease(theString); | |
1935 | } | |
1936 | else | |
1937 | { | |
1938 | CFStringRef theString = CFStringCreateWithSubstring(NULL, kvpair, CFRangeMake(range.length, CFStringGetLength(kvpair) - range.length)); | |
1939 | CFMutableStringRef theString2 = CFStringCreateMutableCopy(NULL, 0, theString); | |
1940 | CFRelease(theString); | |
1941 | ||
1942 | CFStringTrimWhitespace(theString2); | |
1943 | value = theString2; | |
1944 | } | |
1945 | } | |
1946 | idxx++; | |
1947 | } | |
1948 | idx++; | |
1949 | } | |
1950 | ||
1951 | if (kvPairs != NULL) | |
1952 | CFRelease(kvPairs); | |
1953 | return value; | |
1954 | } | |
1955 | ||
1956 | ||
1957 | /* | |
1958 | * 'cfstr_create_trim()' - Create CFString and trim whitespace characters. | |
1959 | */ | |
1960 | ||
1961 | CFStringRef cfstr_create_trim(const char *cstr) | |
1962 | { | |
1963 | CFStringRef cfstr; | |
1964 | CFMutableStringRef cfmutablestr = NULL; | |
1965 | ||
1966 | if ((cfstr = CFStringCreateWithCString(NULL, cstr, kCFStringEncodingUTF8)) != NULL) | |
1967 | { | |
1968 | if ((cfmutablestr = CFStringCreateMutableCopy(NULL, 1024, cfstr)) != NULL) | |
1969 | CFStringTrimWhitespace(cfmutablestr); | |
1970 | ||
1971 | CFRelease(cfstr); | |
1972 | } | |
1973 | return (CFStringRef) cfmutablestr; | |
1974 | } | |
1975 | ||
1976 | ||
1977 | #pragma mark - | |
1978 | /* | |
1979 | * 'parse_options()' - Parse URI options. | |
1980 | */ | |
1981 | ||
1982 | static void parse_options(char *options, | |
1983 | char *serial, | |
1984 | int serial_size, | |
1985 | UInt32 *location, | |
1986 | Boolean *wait_eof) | |
1987 | { | |
1988 | char sep, /* Separator character */ | |
1989 | *name, /* Name of option */ | |
1990 | *value; /* Value of option */ | |
1991 | ||
1992 | ||
1993 | if (serial) | |
1994 | *serial = '\0'; | |
1995 | if (location) | |
1996 | *location = 0; | |
1997 | ||
1998 | if (!options) | |
1999 | return; | |
2000 | ||
2001 | while (*options) | |
2002 | { | |
2003 | /* | |
2004 | * Get the name... | |
2005 | */ | |
2006 | ||
2007 | name = options; | |
2008 | ||
2009 | while (*options && *options != '=' && *options != '+' && *options != '&') | |
2010 | options ++; | |
2011 | ||
2012 | if ((sep = *options) != '\0') | |
2013 | *options++ = '\0'; | |
2014 | ||
2015 | if (sep == '=') | |
2016 | { | |
2017 | /* | |
2018 | * Get the value... | |
2019 | */ | |
2020 | ||
2021 | value = options; | |
2022 | ||
2023 | while (*options && *options != '+' && *options != '&') | |
2024 | options ++; | |
2025 | ||
2026 | if (*options) | |
2027 | *options++ = '\0'; | |
2028 | } | |
2029 | else | |
2030 | value = (char *)""; | |
2031 | ||
2032 | /* | |
2033 | * Process the option... | |
2034 | */ | |
2035 | ||
2036 | if (!_cups_strcasecmp(name, "waiteof")) | |
2037 | { | |
2038 | if (!_cups_strcasecmp(value, "on") || | |
2039 | !_cups_strcasecmp(value, "yes") || | |
2040 | !_cups_strcasecmp(value, "true")) | |
2041 | *wait_eof = true; | |
2042 | else if (!_cups_strcasecmp(value, "off") || | |
2043 | !_cups_strcasecmp(value, "no") || | |
2044 | !_cups_strcasecmp(value, "false")) | |
2045 | *wait_eof = false; | |
2046 | else | |
2047 | _cupsLangPrintFilter(stderr, "WARNING", | |
2048 | _("Boolean expected for waiteof option \"%s\"."), | |
2049 | value); | |
2050 | } | |
2051 | else if (!_cups_strcasecmp(name, "serial")) | |
2052 | strlcpy(serial, value, serial_size); | |
2053 | else if (!_cups_strcasecmp(name, "location") && location) | |
2054 | *location = (UInt32)strtoul(value, NULL, 16); | |
2055 | } | |
2056 | } | |
2057 | ||
2058 | ||
2059 | /*! | |
2060 | * @function setup_cfLanguage | |
2061 | * @abstract Convert the contents of the CUPS 'APPLE_LANGUAGE' environment | |
2062 | * variable into a one element CF array of languages. | |
2063 | * | |
2064 | * @discussion Each submitted job comes with a natural language. CUPS passes | |
2065 | * that language in an environment variable. We take that language | |
2066 | * and jam it into the AppleLanguages array so that CF will use | |
2067 | * it when reading localized resources. We need to do this before | |
2068 | * any CF code reads and caches the languages array, so this function | |
2069 | * should be called early in main() | |
2070 | */ | |
2071 | static void setup_cfLanguage(void) | |
2072 | { | |
2073 | CFStringRef lang[1] = {NULL}; | |
2074 | CFArrayRef langArray = NULL; | |
2075 | const char *requestedLang = NULL; | |
2076 | ||
2077 | if ((requestedLang = getenv("APPLE_LANGUAGE")) == NULL) | |
2078 | requestedLang = getenv("LANG"); | |
2079 | ||
2080 | if (requestedLang != NULL) | |
2081 | { | |
2082 | lang[0] = CFStringCreateWithCString(kCFAllocatorDefault, requestedLang, kCFStringEncodingUTF8); | |
2083 | langArray = CFArrayCreate(kCFAllocatorDefault, (const void **)lang, sizeof(lang) / sizeof(lang[0]), &kCFTypeArrayCallBacks); | |
2084 | ||
2085 | CFPreferencesSetValue(CFSTR("AppleLanguages"), langArray, kCFPreferencesCurrentApplication, kCFPreferencesAnyUser, kCFPreferencesAnyHost); | |
2086 | fprintf(stderr, "DEBUG: usb: AppleLanguages=\"%s\"\n", requestedLang); | |
2087 | ||
2088 | CFRelease(lang[0]); | |
2089 | CFRelease(langArray); | |
2090 | } | |
2091 | else | |
2092 | fputs("DEBUG: usb: LANG and APPLE_LANGUAGE environment variables missing.\n", stderr); | |
2093 | } | |
2094 | ||
2095 | #pragma mark - | |
2096 | #if defined(__i386__) || defined(__x86_64__) | |
2097 | /*! | |
2098 | * @function run_legacy_backend | |
2099 | * | |
2100 | * @abstract Starts child backend process running as a ppc or i386 executable. | |
2101 | * | |
2102 | * @result Never returns; always calls exit(). | |
2103 | * | |
2104 | * @discussion | |
2105 | */ | |
2106 | static void run_legacy_backend(int argc, | |
2107 | char *argv[], | |
2108 | int fd) | |
2109 | { | |
2110 | int i; | |
2111 | int exitstatus = 0; | |
2112 | int childstatus; | |
2113 | pid_t waitpid_status; | |
2114 | char *my_argv[32]; | |
2115 | char *usb_legacy_status; | |
2116 | ||
2117 | ||
2118 | /* | |
2119 | * If we're running as x86_64 or i386 and couldn't load the class driver | |
2120 | * (because it's ppc or i386), then try to re-exec ourselves in ppc or i386 | |
2121 | * mode to try again. If we don't have a ppc or i386 architecture we may be | |
2122 | * running with the same architecture again so guard against this by setting | |
2123 | * and testing an environment variable... | |
2124 | */ | |
2125 | ||
2126 | # ifdef __x86_64__ | |
2127 | usb_legacy_status = getenv("USB_I386_STATUS"); | |
2128 | # else | |
2129 | usb_legacy_status = getenv("USB_PPC_STATUS"); | |
2130 | # endif /* __x86_64__ */ | |
2131 | ||
2132 | if (!usb_legacy_status) | |
2133 | { | |
2134 | log_usb_class_driver(IS_NOT_64BIT); | |
2135 | ||
2136 | /* | |
2137 | * Setup a SIGTERM handler then block it before forking... | |
2138 | */ | |
2139 | ||
2140 | int err; /* posix_spawn result */ | |
2141 | struct sigaction action; /* POSIX signal action */ | |
2142 | sigset_t newmask, /* New signal mask */ | |
2143 | oldmask; /* Old signal mask */ | |
2144 | char usbpath[1024]; /* Path to USB backend */ | |
2145 | const char *cups_serverbin;/* Path to CUPS binaries */ | |
2146 | ||
2147 | ||
2148 | memset(&action, 0, sizeof(action)); | |
2149 | sigaddset(&action.sa_mask, SIGTERM); | |
2150 | action.sa_handler = sigterm_handler; | |
2151 | sigaction(SIGTERM, &action, NULL); | |
2152 | ||
2153 | sigemptyset(&newmask); | |
2154 | sigaddset(&newmask, SIGTERM); | |
2155 | sigprocmask(SIG_BLOCK, &newmask, &oldmask); | |
2156 | ||
2157 | /* | |
2158 | * Set the environment variable... | |
2159 | */ | |
2160 | ||
2161 | # ifdef __x86_64__ | |
2162 | setenv("USB_I386_STATUS", "1", false); | |
2163 | # else | |
2164 | setenv("USB_PPC_STATUS", "1", false); | |
2165 | # endif /* __x86_64__ */ | |
2166 | ||
2167 | /* | |
2168 | * Tell the kernel to use the specified CPU architecture... | |
2169 | */ | |
2170 | ||
2171 | # ifdef __x86_64__ | |
2172 | cpu_type_t cpu = CPU_TYPE_I386; | |
2173 | # else | |
2174 | cpu_type_t cpu = CPU_TYPE_POWERPC; | |
2175 | # endif /* __x86_64__ */ | |
2176 | size_t ocount = 1; | |
2177 | posix_spawnattr_t attrs; | |
2178 | ||
2179 | if (!posix_spawnattr_init(&attrs)) | |
2180 | { | |
2181 | posix_spawnattr_setsigdefault(&attrs, &oldmask); | |
2182 | if (posix_spawnattr_setbinpref_np(&attrs, 1, &cpu, &ocount) || ocount != 1) | |
2183 | { | |
2184 | # ifdef __x86_64__ | |
2185 | perror("DEBUG: Unable to set binary preference to i386"); | |
2186 | # else | |
2187 | perror("DEBUG: Unable to set binary preference to ppc"); | |
2188 | # endif /* __x86_64__ */ | |
2189 | _cupsLangPrintFilter(stderr, "ERROR", | |
2190 | _("Unable to use legacy USB class driver.")); | |
2191 | exit(CUPS_BACKEND_STOP); | |
2192 | } | |
2193 | } | |
2194 | ||
2195 | /* | |
2196 | * Set up the arguments and call posix_spawn... | |
2197 | */ | |
2198 | ||
2199 | if ((cups_serverbin = getenv("CUPS_SERVERBIN")) == NULL) | |
2200 | cups_serverbin = CUPS_SERVERBIN; | |
2201 | snprintf(usbpath, sizeof(usbpath), "%s/backend/usb", cups_serverbin); | |
2202 | ||
2203 | for (i = 0; i < argc && i < (int)(sizeof(my_argv) / sizeof(my_argv[0])) - 1; i ++) | |
2204 | my_argv[i] = argv[i]; | |
2205 | ||
2206 | my_argv[i] = NULL; | |
2207 | ||
2208 | if ((err = posix_spawn(&child_pid, usbpath, NULL, &attrs, my_argv, | |
2209 | environ)) != 0) | |
2210 | { | |
2211 | fprintf(stderr, "DEBUG: Unable to exec %s: %s\n", usbpath, | |
2212 | strerror(err)); | |
2213 | _cupsLangPrintFilter(stderr, "ERROR", | |
2214 | _("Unable to use legacy USB class driver.")); | |
2215 | exit(CUPS_BACKEND_STOP); | |
2216 | } | |
2217 | ||
2218 | /* | |
2219 | * Unblock signals... | |
2220 | */ | |
2221 | ||
2222 | sigprocmask(SIG_SETMASK, &oldmask, NULL); | |
2223 | ||
2224 | /* | |
2225 | * Close the fds we won't be using then wait for the child backend to exit. | |
2226 | */ | |
2227 | ||
2228 | close(fd); | |
2229 | close(1); | |
2230 | ||
2231 | fprintf(stderr, "DEBUG: Started usb(legacy) backend (PID %d)\n", | |
2232 | (int)child_pid); | |
2233 | ||
2234 | while ((waitpid_status = waitpid(child_pid, &childstatus, 0)) == (pid_t)-1 && errno == EINTR) | |
2235 | usleep(1000); | |
2236 | ||
2237 | if (WIFSIGNALED(childstatus)) | |
2238 | { | |
2239 | exitstatus = CUPS_BACKEND_STOP; | |
2240 | fprintf(stderr, "DEBUG: usb(legacy) backend %d crashed on signal %d\n", | |
2241 | child_pid, WTERMSIG(childstatus)); | |
2242 | } | |
2243 | else | |
2244 | { | |
2245 | if ((exitstatus = WEXITSTATUS(childstatus)) != 0) | |
2246 | fprintf(stderr, | |
2247 | "DEBUG: usb(legacy) backend %d stopped with status %d\n", | |
2248 | child_pid, exitstatus); | |
2249 | else | |
2250 | fprintf(stderr, "DEBUG: usb(legacy) backend %d exited with no errors\n", | |
2251 | child_pid); | |
2252 | } | |
2253 | } | |
2254 | else | |
2255 | { | |
2256 | fputs("DEBUG: usb(legacy) backend running native again\n", stderr); | |
2257 | exitstatus = CUPS_BACKEND_STOP; | |
2258 | } | |
2259 | ||
2260 | exit(exitstatus); | |
2261 | } | |
2262 | #endif /* __i386__ || __x86_64__ */ | |
2263 | ||
2264 | ||
2265 | /* | |
2266 | * 'sigterm_handler()' - SIGTERM handler. | |
2267 | */ | |
2268 | ||
2269 | static void | |
2270 | sigterm_handler(int sig) /* I - Signal */ | |
2271 | { | |
2272 | #if defined(__i386__) || defined(__x86_64__) | |
2273 | /* | |
2274 | * If we started a child process pass the signal on to it... | |
2275 | */ | |
2276 | ||
2277 | if (child_pid) | |
2278 | { | |
2279 | /* | |
2280 | * If we started a child process pass the signal on to it... | |
2281 | */ | |
2282 | ||
2283 | int status; | |
2284 | ||
2285 | kill(child_pid, sig); | |
2286 | while (waitpid(child_pid, &status, 0) < 0 && errno == EINTR); | |
2287 | ||
2288 | if (WIFEXITED(status)) | |
2289 | _exit(WEXITSTATUS(status)); | |
2290 | else if (status == SIGTERM || status == SIGKILL) | |
2291 | _exit(0); | |
2292 | else | |
2293 | { | |
2294 | write(2, "DEBUG: Child crashed.\n", 22); | |
2295 | _exit(CUPS_BACKEND_STOP); | |
2296 | } | |
2297 | } | |
2298 | #endif /* __i386__ || __x86_64__ */ | |
2299 | } | |
2300 | ||
2301 | ||
2302 | /* | |
2303 | * 'sigquit_handler()' - SIGQUIT handler. | |
2304 | */ | |
2305 | ||
2306 | static void sigquit_handler(int sig, siginfo_t *si, void *unused) | |
2307 | { | |
2308 | char *path; | |
2309 | char pathbuf[PROC_PIDPATHINFO_MAXSIZE]; | |
2310 | static char msgbuf[256] = ""; | |
2311 | ||
2312 | ||
2313 | (void)sig; | |
2314 | (void)unused; | |
2315 | ||
2316 | if (proc_pidpath(si->si_pid, pathbuf, sizeof(pathbuf)) > 0 && | |
2317 | (path = basename(pathbuf)) != NULL) | |
2318 | snprintf(msgbuf, sizeof(msgbuf), "SIGQUIT sent by %s(%d)", path, (int)si->si_pid); | |
2319 | else | |
2320 | snprintf(msgbuf, sizeof(msgbuf), "SIGQUIT sent by PID %d", (int)si->si_pid); | |
2321 | ||
2322 | CRSetCrashLogMessage(msgbuf); | |
2323 | ||
2324 | abort(); | |
2325 | } | |
2326 | ||
2327 | ||
2328 | #ifdef PARSE_PS_ERRORS | |
2329 | /* | |
2330 | * 'next_line()' - Find the next line in a buffer. | |
2331 | */ | |
2332 | ||
2333 | static const char *next_line (const char *buffer) | |
2334 | { | |
2335 | const char *cptr, *lptr = NULL; | |
2336 | ||
2337 | for (cptr = buffer; *cptr && lptr == NULL; cptr++) | |
2338 | if (*cptr == '\n' || *cptr == '\r') | |
2339 | lptr = cptr; | |
2340 | return lptr; | |
2341 | } | |
2342 | ||
2343 | ||
2344 | /* | |
2345 | * 'parse_pserror()' - Scan the backchannel data for postscript errors. | |
2346 | */ | |
2347 | ||
2348 | static void parse_pserror(char *sockBuffer, | |
2349 | int len) | |
2350 | { | |
2351 | static char gErrorBuffer[1024] = ""; | |
2352 | static char *gErrorBufferPtr = gErrorBuffer; | |
2353 | static char *gErrorBufferEndPtr = gErrorBuffer + sizeof(gErrorBuffer); | |
2354 | ||
2355 | char *pCommentBegin, *pCommentEnd, *pLineEnd; | |
2356 | char *logLevel; | |
2357 | char logstr[1024]; | |
2358 | int logstrlen; | |
2359 | ||
2360 | if (gErrorBufferPtr + len > gErrorBufferEndPtr - 1) | |
2361 | gErrorBufferPtr = gErrorBuffer; | |
2362 | if (len > sizeof(gErrorBuffer) - 1) | |
2363 | len = sizeof(gErrorBuffer) - 1; | |
2364 | ||
2365 | memcpy(gErrorBufferPtr, (const void *)sockBuffer, len); | |
2366 | gErrorBufferPtr += len; | |
2367 | *(gErrorBufferPtr + 1) = '\0'; | |
2368 | ||
2369 | pLineEnd = (char *)next_line((const char *)gErrorBuffer); | |
2370 | while (pLineEnd != NULL) | |
2371 | { | |
2372 | *pLineEnd++ = '\0'; | |
2373 | ||
2374 | pCommentBegin = strstr(gErrorBuffer,"%%["); | |
2375 | pCommentEnd = strstr(gErrorBuffer, "]%%"); | |
2376 | if (pCommentBegin != gErrorBuffer && pCommentEnd != NULL) | |
2377 | { | |
2378 | pCommentEnd += 3; /* Skip past "]%%" */ | |
2379 | *pCommentEnd = '\0'; /* There's always room for the nul */ | |
2380 | ||
2381 | if (_cups_strncasecmp(pCommentBegin, "%%[ Error:", 10) == 0) | |
2382 | logLevel = "DEBUG"; | |
2383 | else if (_cups_strncasecmp(pCommentBegin, "%%[ Flushing", 12) == 0) | |
2384 | logLevel = "DEBUG"; | |
2385 | else | |
2386 | logLevel = "INFO"; | |
2387 | ||
2388 | if ((logstrlen = snprintf(logstr, sizeof(logstr), "%s: %s\n", logLevel, pCommentBegin)) >= sizeof(logstr)) | |
2389 | { | |
2390 | /* If the string was trucnated make sure it has a linefeed before the nul */ | |
2391 | logstrlen = sizeof(logstr) - 1; | |
2392 | logstr[logstrlen - 1] = '\n'; | |
2393 | } | |
2394 | write(STDERR_FILENO, logstr, logstrlen); | |
2395 | } | |
2396 | ||
2397 | /* move everything over... */ | |
2398 | strlcpy(gErrorBuffer, pLineEnd, sizeof(gErrorBuffer)); | |
2399 | gErrorBufferPtr = gErrorBuffer; | |
2400 | pLineEnd = (char *)next_line((const char *)gErrorBuffer); | |
2401 | } | |
2402 | } | |
2403 | #endif /* PARSE_PS_ERRORS */ | |
2404 | ||
2405 | ||
2406 | /* | |
2407 | * 'soft_reset()' - Send a soft reset to the device. | |
2408 | */ | |
2409 | ||
2410 | static void soft_reset(void) | |
2411 | { | |
2412 | fd_set input_set; /* Input set for select() */ | |
2413 | struct timeval tv; /* Time value */ | |
2414 | char buffer[2048]; /* Buffer */ | |
2415 | struct timespec cond_timeout; /* pthread condition timeout */ | |
2416 | ||
2417 | /* | |
2418 | * Send an abort once a second until the I/O lock is released by the main thread... | |
2419 | */ | |
2420 | ||
2421 | pthread_mutex_lock(&g.readwrite_lock_mutex); | |
2422 | while (g.readwrite_lock) | |
2423 | { | |
2424 | (*g.classdriver)->Abort(g.classdriver); | |
2425 | ||
2426 | gettimeofday(&tv, NULL); | |
2427 | cond_timeout.tv_sec = tv.tv_sec + 1; | |
2428 | cond_timeout.tv_nsec = tv.tv_usec * 1000; | |
2429 | ||
2430 | while (g.readwrite_lock) | |
2431 | { | |
2432 | if (pthread_cond_timedwait(&g.readwrite_lock_cond, | |
2433 | &g.readwrite_lock_mutex, | |
2434 | &cond_timeout) != 0) | |
2435 | break; | |
2436 | } | |
2437 | } | |
2438 | ||
2439 | g.readwrite_lock = 1; | |
2440 | pthread_mutex_unlock(&g.readwrite_lock_mutex); | |
2441 | ||
2442 | /* | |
2443 | * Flush bytes waiting on print_fd... | |
2444 | */ | |
2445 | ||
2446 | g.print_bytes = 0; | |
2447 | ||
2448 | FD_ZERO(&input_set); | |
2449 | FD_SET(g.print_fd, &input_set); | |
2450 | ||
2451 | tv.tv_sec = 0; | |
2452 | tv.tv_usec = 0; | |
2453 | ||
2454 | while (select(g.print_fd+1, &input_set, NULL, NULL, &tv) > 0) | |
2455 | if (read(g.print_fd, buffer, sizeof(buffer)) <= 0) | |
2456 | break; | |
2457 | ||
2458 | /* | |
2459 | * Send the reset... | |
2460 | */ | |
2461 | ||
2462 | (*g.classdriver)->SoftReset(g.classdriver, DEFAULT_TIMEOUT); | |
2463 | ||
2464 | /* | |
2465 | * Release the I/O lock... | |
2466 | */ | |
2467 | ||
2468 | pthread_mutex_lock(&g.readwrite_lock_mutex); | |
2469 | g.readwrite_lock = 0; | |
2470 | pthread_cond_signal(&g.readwrite_lock_cond); | |
2471 | pthread_mutex_unlock(&g.readwrite_lock_mutex); | |
2472 | } | |
2473 | ||
2474 | ||
2475 | /* | |
2476 | * 'get_device_id()' - Return IEEE-1284 device ID. | |
2477 | */ | |
2478 | ||
2479 | static void get_device_id(cups_sc_status_t *status, | |
2480 | char *data, | |
2481 | int *datalen) | |
2482 | { | |
2483 | CFStringRef deviceIDString = NULL; | |
2484 | ||
2485 | if (g.printer_obj != IO_OBJECT_NULL) | |
2486 | { | |
2487 | printer_interface_t printerIntf = usb_printer_interface_interface(g.printer_obj); | |
2488 | if (printerIntf) | |
2489 | { | |
2490 | deviceIDString = copy_printer_interface_deviceid(printerIntf, g.alternateSetting); | |
2491 | (*printerIntf)->Release(printerIntf); | |
2492 | } | |
2493 | } | |
2494 | ||
2495 | ||
2496 | if (deviceIDString) | |
2497 | { | |
2498 | if (CFStringGetCString(deviceIDString, data, *datalen, kCFStringEncodingUTF8)) | |
2499 | *datalen = (int)strlen(data); | |
2500 | else | |
2501 | *datalen = 0; | |
2502 | ||
2503 | CFRelease(deviceIDString); | |
2504 | } | |
2505 | else | |
2506 | { | |
2507 | *datalen = 0; | |
2508 | } | |
2509 | ||
2510 | *status = CUPS_SC_STATUS_OK; | |
2511 | } | |
2512 | ||
2513 | ||
2514 | static void | |
2515 | log_usb_class_driver(int is_64bit) /* I - Is the USB class driver 64-bit? */ | |
2516 | { | |
2517 | /* | |
2518 | * Report the usage of legacy USB class drivers to Apple if the user opts into providing | |
2519 | * feedback to Apple... | |
2520 | */ | |
2521 | ||
2522 | aslmsg aslm = asl_new(ASL_TYPE_MSG); | |
2523 | if (aslm) | |
2524 | { | |
2525 | ppd_file_t *ppd = ppdOpenFile(getenv("PPD")); | |
2526 | const char *make_model = ppd ? ppd->nickname : NULL; | |
2527 | ppd_attr_t *version = ppdFindAttr(ppd, "FileVersion", ""); | |
2528 | ||
2529 | asl_set(aslm, "com.apple.message.domain", "com.apple.printing.usb.64bit"); | |
2530 | asl_set(aslm, "com.apple.message.result", is_64bit ? "yes" : "no"); | |
2531 | asl_set(aslm, "com.apple.message.signature", make_model ? make_model : "Unknown"); | |
2532 | asl_set(aslm, "com.apple.message.signature2", version ? version->value : "?.?"); | |
2533 | asl_set(aslm, "com.apple.message.summarize", "YES"); | |
2534 | asl_log(NULL, aslm, ASL_LEVEL_NOTICE, ""); | |
2535 | asl_free(aslm); | |
2536 | } | |
2537 | } | |
2538 | ||
2539 | ||
2540 | /* | |
2541 | * End of "$Id$". | |
2542 | */ |