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