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