]> git.ipfire.org Git - thirdparty/cups.git/blame - backend/usb-darwin.c
Really fix it.
[thirdparty/cups.git] / backend / usb-darwin.c
CommitLineData
ef416fc2 1/*
581dae2d
MS
2 * "$Id$"
3 *
7530b13a 4 * Copyright 2005-2015 Apple Inc. All rights reserved.
581dae2d
MS
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 */
ef416fc2 44
45/*
09a101d6 46 * Include necessary headers.
ef416fc2 47 */
09a101d6 48
ef416fc2 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>
ac884b6a 56#include <sys/stat.h>
e53920b9 57#include <sys/sysctl.h>
58#include <libgen.h>
09a101d6 59#include <mach/mach.h>
e53920b9 60#include <mach/mach_error.h>
61#include <mach/mach_time.h>
71e16022 62#include <cups/debug-private.h>
22c9029b 63#include <cups/file-private.h>
f7deaa1a 64#include <cups/sidechannel.h>
71e16022 65#include <cups/language-private.h>
db0bd74a 66#include "backend-private.h"
e53920b9 67#include <CoreFoundation/CoreFoundation.h>
68#include <IOKit/usb/IOUSBLib.h>
69#include <IOKit/IOCFPlugIn.h>
a469f8a5 70#include <libproc.h>
9fb65b89 71#include <asl.h>
749b1e90 72#include <spawn.h>
e53920b9 73#include <pthread.h>
ef416fc2 74
fe750b86
MS
75/*
76 * Include necessary headers.
77 */
78
749b1e90
MS
79extern char **environ;
80
f7deaa1a 81
acb056cb
MS
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
7cf5915e
MS
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
7dfedb92 96#define DEFAULT_TIMEOUT 5000L
ef416fc2 97
f1ebe30e 98#define USB_INTERFACE_KIND CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID245)
e53920b9 99#define kUSBLanguageEnglish 0x409
ef416fc2 100
09a101d6 101#define PRINTER_POLLING_INTERVAL 5 /* seconds */
102#define INITIAL_LOG_INTERVAL PRINTER_POLLING_INTERVAL
103#define SUBSEQUENT_LOG_INTERVAL 3 * INITIAL_LOG_INTERVAL
ef416fc2 104
09a101d6 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)
ef416fc2 107
108#define kUSBClassDriverProperty CFSTR("USB Printing Class")
ef416fc2 109
84315f46 110#define kUSBGenericTOPrinterClassDriver CFSTR("/System/Library/Printers/Libraries/USBGenericPrintingClass.plugin")
e53920b9 111#define kUSBPrinterClassDeviceNotOpen -9664 /*kPMInvalidIOMContext*/
ef416fc2 112
a469f8a5
MS
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
119struct 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
0fa6c7fa
MS
129CRASH_REPORTER_CLIENT_HIDDEN
130struct crashreporter_annotations_t gCRAnnotations
131 __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION)))
a469f8a5 132 = { CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0 };
ef416fc2 133
e53920b9 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
fe750b86 141#define kUSBPrintingProtocolIPP 4
e53920b9 142
f1ebe30e 143typedef IOUSBInterfaceInterface245 **printer_interface_t;
ef416fc2 144
09a101d6 145typedef struct iodevice_request_s /**** Device request ****/
ef416fc2 146{
09a101d6 147 UInt8 requestType;
e53920b9 148 UInt8 request;
149 UInt16 value;
150 UInt16 index;
151 UInt16 length;
09a101d6 152 void *buffer;
e53920b9 153} iodevice_request_t;
154
09a101d6 155typedef union /**** Centronics status byte ****/
156{
e53920b9 157 char b;
09a101d6 158 struct
159 {
e53920b9 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
09a101d6 168typedef struct classdriver_s /**** g.classdriver context ****/
ef416fc2 169{
170 IUNKNOWN_C_GUTS;
e53920b9 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 */
a469f8a5 179 UInt8 outpipe; /* mandatory bulkOut pipe */
e53920b9 180 UInt8 inpipe; /* optional bulkIn pipe */
ef416fc2 181
e53920b9 182 /* general class requests */
09a101d6 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);
ef416fc2 185
e53920b9 186 /* standard printer class requests */
09a101d6 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);
ef416fc2 190
e53920b9 191 /* standard bulk device requests */
09a101d6 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);
ef416fc2 194
e53920b9 195 /* interface requests */
09a101d6 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);
ef416fc2 199
e53920b9 200 /* initialize and terminate */
09a101d6 201 kern_return_t (*Initialize)(struct classdriver_s **printer, struct classdriver_s **baseclass);
202 kern_return_t (*Terminate)(struct classdriver_s **printer);
ef416fc2 203
09a101d6 204} classdriver_t;
ef416fc2 205
fe750b86 206typedef Boolean (*iterator_callback_t)(void *refcon, io_service_t obj, CFStringRef deviceIDString, UInt32 deviceLocation, UInt8 interfaceNum, UInt8 alternateSetting);
ef416fc2 207
09a101d6 208typedef struct iterator_reference_s /**** Iterator reference data */
209{
e53920b9 210 iterator_callback_t callback;
211 void *userdata;
212 Boolean keepRunning;
213} iterator_reference_t;
ef416fc2 214
09a101d6 215typedef 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;
ef416fc2 224
09a101d6 225 pthread_mutex_t readwrite_lock_mutex;
226 pthread_cond_t readwrite_lock_cond;
227 int readwrite_lock;
ef416fc2 228
e53920b9 229 CFStringRef make;
230 CFStringRef model;
231 CFStringRef serial;
e53920b9 232 UInt32 location;
bc44d920 233 UInt8 interfaceNum;
fe750b86 234 UInt8 alternateSetting;
09a101d6 235
236 CFRunLoopTimerRef status_timer;
237
238 int print_fd; /* File descriptor to print */
239 ssize_t print_bytes; /* Print bytes read */
acb056cb
MS
240#if DEBUG_WRITES
241 ssize_t debug_bytes; /* Current bytes to read */
242#endif /* DEBUG_WRITES */
09a101d6 243
7530b13a 244 Boolean use_generic_class_driver;
09a101d6 245 Boolean wait_eof;
246 int drain_output; /* Drain all pending output */
247 int bidi_flag; /* 0=unidirectional, 1=bidirectional */
7cf5915e
MS
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;
09a101d6 253} globals_t;
254
255
256/*
257 * Globals...
258 */
259
260globals_t g = { 0 }; /* Globals */
0fa6c7fa 261int Iterating = 0; /* Are we iterating the bus? */
ef416fc2 262
ef416fc2 263
e53920b9 264/*
265 * Local functions...
266 */
ef416fc2 267
fe750b86
MS
268static Boolean find_device_cb(void *refcon, io_service_t obj, CFStringRef deviceIDString, UInt32 deviceLocation, UInt8 interfaceNum, UInt8 alternateSetting);
269static Boolean list_device_cb(void *refcon, io_service_t obj, CFStringRef deviceIDString, UInt32 deviceLocation, UInt8 interfaceNum, UInt8 alternateSetting);
270
09a101d6 271static CFStringRef cfstr_create_trim(const char *cstr);
272static CFStringRef copy_value_for_key(CFStringRef deviceID, CFStringRef *keys);
321d8d57 273static kern_return_t load_classdriver(CFStringRef driverPath, printer_interface_t interface, classdriver_t ***printerDriver);
09a101d6 274static kern_return_t load_printerdriver(CFStringRef *driverBundlePath);
eac3a0a0 275static kern_return_t registry_close(void);
09a101d6 276static kern_return_t registry_open(CFStringRef *driverBundlePath);
eac3a0a0 277static kern_return_t unload_classdriver(classdriver_t ***classdriver);
fe750b86 278
09a101d6 279static void *read_thread(void *reference);
280static void *sidechannel_thread(void *reference);
09a101d6 281static void device_added(void *userdata, io_iterator_t iterator);
282static void get_device_id(cups_sc_status_t *status, char *data, int *datalen);
283static void iterate_printers(iterator_callback_t callBack, void *userdata);
db1f069b 284static void parse_options(char *options, char *serial, int serial_size, UInt32 *location, Boolean *wait_eof);
e53920b9 285static void setup_cfLanguage(void);
eac3a0a0 286static void soft_reset(void);
09a101d6 287static void status_timer_cb(CFRunLoopTimerRef timer, void *info);
9fb65b89
MS
288static void log_usb_class_driver(int is_64bit);
289#define IS_64BIT 1
290#define IS_NOT_64BIT 0
e53920b9 291
749b1e90 292#if defined(__i386__) || defined(__x86_64__)
f11a948a 293static pid_t child_pid; /* Child PID */
7e86f2f6 294static void run_legacy_backend(int argc, char *argv[], int fd) __attribute__((noreturn)); /* Starts child backend process running as a ppc executable */
18ecb428 295#endif /* __i386__ || __x86_64__ */
6c48a6ca 296static void sigterm_handler(int sig); /* SIGTERM handler */
7e86f2f6 297static void sigquit_handler(int sig, siginfo_t *si, void *unused) __attribute__((noreturn));
ef416fc2 298
e53920b9 299#ifdef PARSE_PS_ERRORS
300static const char *next_line (const char *buffer);
301static void parse_pserror (char *sockBuffer, int len);
302#endif /* PARSE_PS_ERRORS */
ef416fc2 303
f1ebe30e 304static printer_interface_t usb_printer_interface_interface(io_service_t usbClass);
fe750b86 305static IOUSBDeviceInterface **usb_device_interface_for_device(io_service_t usbDevice);
f1ebe30e
MS
306static CFStringRef copy_printer_interface_deviceid(printer_interface_t printer, UInt8 alternateSetting);
307static CFStringRef copy_printer_interface_indexed_description(printer_interface_t printer, UInt8 index, UInt16 language);
fe750b86
MS
308static CFStringRef deviceIDCopyManufacturer(CFStringRef deviceID);
309static CFStringRef deviceIDCopyModel(CFStringRef deviceID);
310static CFStringRef deviceIDCopySerialNumber(CFStringRef deviceID);
311
e53920b9 312#pragma mark -
ef416fc2 313
e53920b9 314/*
315 * 'list_devices()' - List all USB devices.
316 */
ef416fc2 317
e53920b9 318void list_devices()
ef416fc2 319{
09a101d6 320 iterate_printers(list_device_cb, NULL);
ef416fc2 321}
322
ef416fc2 323
e53920b9 324/*
325 * 'print_device()' - Print a file to a USB device.
326 */
ef416fc2 327
e53920b9 328int /* O - Exit status */
329print_device(const char *uri, /* I - Device URI */
330 const char *hostname, /* I - Hostname/manufacturer */
331 const char *resource, /* I - Resource/modelname */
db1f069b 332 char *options, /* I - Device options/serial number */
09a101d6 333 int print_fd, /* I - File descriptor to print */
e53920b9 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 */
ef416fc2 337{
09a101d6 338 char serial[1024]; /* Serial number buffer */
339 OSStatus status; /* Function results */
acb056cb 340 IOReturn iostatus; /* Current IO status */
09a101d6 341 pthread_t read_thread_id, /* Read thread */
db1f069b 342 sidechannel_thread_id;/* Side-channel thread */
ac884b6a
MS
343 int have_sidechannel = 0; /* Was the side-channel thread started? */
344 struct stat sidechannel_info; /* Side-channel file descriptor info */
09a101d6 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 */
84315f46 355 tv; /* Time value */
7cf5915e 356 struct timespec cond_timeout; /* pthread condition timeout */
a469f8a5 357 struct sigaction action; /* Actions for POSIX signals */
e53920b9 358
db1f069b 359
321d8d57
MS
360 (void)uri;
361
a469f8a5
MS
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
ac884b6a
MS
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
e53920b9 382 setup_cfLanguage();
09a101d6 383
76cd9e37 384 parse_options(options, serial, sizeof(serial), &location, &g.wait_eof);
e53920b9 385
386 if (resource[0] == '/')
387 resource++;
388
09a101d6 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;
e53920b9 394
7dfedb92
MS
395 if (!g.make || !g.model)
396 {
c7017ecc 397 fprintf(stderr, "DEBUG: Fatal USB error.\n");
0837b7e8
MS
398 _cupsLangPrintFilter(stderr, "ERROR",
399 _("There was an unrecoverable USB error."));
005dd1eb
MS
400
401 if (!g.make)
4d301e69 402 fputs("DEBUG: USB make string is NULL\n", stderr);
005dd1eb 403 if (!g.model)
4d301e69 404 fputs("DEBUG: USB model string is NULL\n", stderr);
005dd1eb
MS
405
406 return (CUPS_BACKEND_STOP);
7dfedb92
MS
407 }
408
e53920b9 409 fputs("STATE: +connecting-to-device\n", stderr);
410
09a101d6 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;
ef416fc2 421 }
ef416fc2 422
c0e1af83 423 fprintf(stderr, "DEBUG: Looking for '%s %s'\n", hostname, resource);
09a101d6 424
425 iterate_printers(find_device_cb, NULL);
e53920b9 426
c0e1af83 427 fputs("DEBUG: Opening connection\n", stderr);
411affcf 428
429 driverBundlePath = NULL;
09a101d6 430
431 status = registry_open(&driverBundlePath);
432
749b1e90 433#if defined(__i386__) || defined(__x86_64__)
e53920b9 434 /*
749b1e90
MS
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...
e53920b9 438 */
09a101d6 439 if (status == -2)
440 {
749b1e90 441 run_legacy_backend(argc, argv, print_fd);
e53920b9 442 /* Never returns here */
ef416fc2 443 }
749b1e90 444#endif /* __i386__ || __x86_64__ */
09a101d6 445
446 if (status == -2)
447 {
411affcf 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
09a101d6 453 if (driverBundlePath == NULL || !CFStringGetCString(driverBundlePath, print_buffer, sizeof(print_buffer), kCFStringEncodingUTF8))
454 strlcpy(print_buffer, "USB class driver", sizeof(print_buffer));
411affcf 455
c0e1af83 456 fputs("STATE: +apple-missing-usbclassdriver-error\n", stderr);
0837b7e8
MS
457 _cupsLangPrintFilter(stderr, "ERROR",
458 _("There was an unrecoverable USB error."));
005dd1eb 459 fprintf(stderr, "DEBUG: Could not load %s\n", print_buffer);
411affcf 460
461 if (driverBundlePath)
462 CFRelease(driverBundlePath);
463
005dd1eb 464 return (CUPS_BACKEND_STOP);
411affcf 465 }
466
3b3a130a
MS
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
411affcf 472 if (driverBundlePath)
473 CFRelease(driverBundlePath);
e53920b9 474
09a101d6 475 if (status != noErr)
476 {
477 sleep(PRINTER_POLLING_INTERVAL);
e53920b9 478 countdown -= PRINTER_POLLING_INTERVAL;
09a101d6 479 if (countdown <= 0)
480 {
0837b7e8
MS
481 _cupsLangPrintFilter(stderr, "INFO",
482 _("Waiting for printer to become available."));
005dd1eb 483 fprintf(stderr, "DEBUG: USB printer status: 0x%08x\n", (int)status);
e53920b9 484 countdown = SUBSEQUENT_LOG_INTERVAL; /* subsequent log entries, every 15 seconds */
485 }
486 }
487 } while (status != noErr);
ef416fc2 488
e53920b9 489 fputs("STATE: -connecting-to-device\n", stderr);
ef416fc2 490
e53920b9 491 /*
18ecb428 492 * Now that we are "connected" to the port, ignore SIGTERM so that we
e53920b9 493 * can finish out any page data the driver sends (e.g. to eject the
18ecb428 494 * current page... Only ignore SIGTERM if we are printing data from
e53920b9 495 * stdin (otherwise you can't cancel raw jobs...)
496 */
ef416fc2 497
09a101d6 498 if (!print_fd)
499 {
e53920b9 500 memset(&action, 0, sizeof(action));
ef416fc2 501
e53920b9 502 sigemptyset(&action.sa_mask);
18ecb428 503 action.sa_handler = SIG_IGN;
e53920b9 504 sigaction(SIGTERM, &action, NULL);
e53920b9 505 }
ef416fc2 506
09a101d6 507 /*
ac884b6a 508 * Start the side channel thread if the descriptor is valid...
09a101d6 509 */
ef416fc2 510
09a101d6 511 pthread_mutex_init(&g.readwrite_lock_mutex, NULL);
512 pthread_cond_init(&g.readwrite_lock_cond, NULL);
513 g.readwrite_lock = 1;
f7deaa1a 514
ac884b6a 515 if (have_sidechannel)
09a101d6 516 {
7cf5915e
MS
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
09a101d6 523 if (pthread_create(&sidechannel_thread_id, NULL, sidechannel_thread, NULL))
524 {
c7017ecc 525 fprintf(stderr, "DEBUG: Fatal USB error.\n");
0837b7e8
MS
526 _cupsLangPrintFilter(stderr, "ERROR",
527 _("There was an unrecoverable USB error."));
4d301e69 528 fputs("DEBUG: Couldn't create side-channel thread\n", stderr);
ef55b745 529 registry_close();
005dd1eb 530 return (CUPS_BACKEND_STOP);
09a101d6 531 }
532 }
f7deaa1a 533
09a101d6 534 /*
535 * Get the read thread going...
536 */
f7deaa1a 537
09a101d6 538 g.read_thread_stop = 0;
539 g.read_thread_done = 0;
f7deaa1a 540
09a101d6 541 pthread_cond_init(&g.read_thread_cond, NULL);
542 pthread_mutex_init(&g.read_thread_mutex, NULL);
f7deaa1a 543
09a101d6 544 if (pthread_create(&read_thread_id, NULL, read_thread, NULL))
545 {
c7017ecc 546 fprintf(stderr, "DEBUG: Fatal USB error.\n");
0837b7e8
MS
547 _cupsLangPrintFilter(stderr, "ERROR",
548 _("There was an unrecoverable USB error."));
4d301e69 549 fputs("DEBUG: Couldn't create read thread\n", stderr);
ef55b745 550 registry_close();
005dd1eb 551 return (CUPS_BACKEND_STOP);
e53920b9 552 }
ef416fc2 553
09a101d6 554 /*
555 * The main thread sends the print file...
556 */
f7deaa1a 557
09a101d6 558 g.drain_output = 0;
559 g.print_bytes = 0;
560 total_bytes = 0;
561 print_ptr = print_buffer;
ef416fc2 562
09a101d6 563 while (status == noErr && copies-- > 0)
564 {
0837b7e8 565 _cupsLangPrintFilter(stderr, "INFO", _("Sending data to printer."));
757d2cad 566
09a101d6 567 if (print_fd != STDIN_FILENO)
568 {
749b1e90 569 fputs("PAGE: 1 1\n", stderr);
09a101d6 570 lseek(print_fd, 0, SEEK_SET);
ef416fc2 571 }
572
09a101d6 573 while (status == noErr)
574 {
575 FD_ZERO(&input_set);
e53920b9 576
09a101d6 577 if (!g.print_bytes)
578 FD_SET(print_fd, &input_set);
f7deaa1a 579
09a101d6 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 {
84315f46
MS
589 tv.tv_sec = 0;
590 tv.tv_usec = 100000; /* 100ms */
591 timeout = &tv;
09a101d6 592 }
593 else if (g.drain_output)
594 {
84315f46
MS
595 tv.tv_sec = 0;
596 tv.tv_usec = 0;
597 timeout = &tv;
09a101d6 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 "
4d301e69 628 "written, aborting\n", stderr);
ef55b745 629 registry_close();
f11a948a 630 return (CUPS_BACKEND_OK);
09a101d6 631 }
536bc2c6 632 else if (errno != EAGAIN && errno != EINTR)
09a101d6 633 {
0837b7e8
MS
634 _cupsLangPrintFilter(stderr, "ERROR",
635 _("Unable to read print data."));
005dd1eb 636 perror("DEBUG: select");
ef55b745
MS
637 registry_close();
638 return (CUPS_BACKEND_FAILED);
09a101d6 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 {
acb056cb
MS
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
09a101d6 667 g.print_bytes = read(print_fd, print_buffer, sizeof(print_buffer));
acb056cb 668#endif /* DEBUG_WRITES */
09a101d6 669
670 if (g.print_bytes < 0)
671 {
672 /*
673 * Read error - bail if we don't see EAGAIN or EINTR...
674 */
675
536bc2c6 676 if (errno != EAGAIN && errno != EINTR)
09a101d6 677 {
0837b7e8
MS
678 _cupsLangPrintFilter(stderr, "ERROR",
679 _("Unable to read print data."));
005dd1eb 680 perror("DEBUG: read");
ef55b745 681 registry_close();
f11a948a 682 return (CUPS_BACKEND_FAILED);
09a101d6 683 }
684
685 g.print_bytes = 0;
f7deaa1a 686 }
09a101d6 687 else if (g.print_bytes == 0)
688 {
689 /*
690 * End of file, break out of the loop...
691 */
f7deaa1a 692
e53920b9 693 break;
ef416fc2 694 }
695
09a101d6 696 print_ptr = print_buffer;
697
698 fprintf(stderr, "DEBUG: Read %d bytes of print data...\n",
699 (int)g.print_bytes);
e53920b9 700 }
ef416fc2 701
09a101d6 702 if (g.print_bytes)
703 {
7e86f2f6 704 bytes = (UInt32)g.print_bytes;
178cb736 705 iostatus = (*g.classdriver)->WritePipe(g.classdriver, (UInt8*)print_ptr, &bytes, 0);
f7deaa1a 706
09a101d6 707 /*
58dc1933 708 * Ignore timeout errors, but retain the number of bytes written to
5a9febac 709 * avoid sending duplicate data...
09a101d6 710 */
e53920b9 711
178cb736 712 if (iostatus == kIOUSBTransactionTimeout)
b0f6947b 713 {
4d301e69 714 fputs("DEBUG: Got USB transaction timeout during write\n", stderr);
178cb736 715 iostatus = 0;
b0f6947b 716 }
ef416fc2 717
178cb736 718 /*
acb056cb 719 * If we've stalled, retry the write...
178cb736
MS
720 */
721
b0f6947b
MS
722 else if (iostatus == kIOUSBPipeStalled)
723 {
4d301e69 724 fputs("DEBUG: Got USB pipe stalled during write\n", stderr);
b0f6947b 725
7e86f2f6 726 bytes = (UInt32)g.print_bytes;
acb056cb 727 iostatus = (*g.classdriver)->WritePipe(g.classdriver, (UInt8*)print_ptr, &bytes, 0);
b0f6947b 728 }
178cb736
MS
729
730 /*
acb056cb 731 * Retry a write after an aborted write since we probably just got
5a9febac 732 * SIGTERM...
178cb736
MS
733 */
734
b0f6947b 735 else if (iostatus == kIOReturnAborted)
178cb736 736 {
3fb9c47e 737 fputs("DEBUG: Got USB return aborted during write\n", stderr);
b0f6947b
MS
738
739 IOReturn err = (*g.classdriver)->Abort(g.classdriver);
740 fprintf(stderr, "DEBUG: USB class driver Abort returned %x\n", err);
741
acb056cb
MS
742#if DEBUG_WRITES
743 sleep(5);
744#endif /* DEBUG_WRITES */
b0f6947b 745
7e86f2f6 746 bytes = (UInt32)g.print_bytes;
acb056cb 747 iostatus = (*g.classdriver)->WritePipe(g.classdriver, (UInt8*)print_ptr, &bytes, 0);
b0f6947b 748 }
178cb736 749
82f97232 750 if (iostatus)
09a101d6 751 {
752 /*
753 * Write error - bail if we don't see an error we can retry...
754 */
84315f46 755
0837b7e8
MS
756 _cupsLangPrintFilter(stderr, "ERROR",
757 _("Unable to send data to printer."));
178cb736
MS
758 fprintf(stderr, "DEBUG: USB class driver WritePipe returned %x\n",
759 iostatus);
b0f6947b
MS
760
761 IOReturn err = (*g.classdriver)->Abort(g.classdriver);
178cb736
MS
762 fprintf(stderr, "DEBUG: USB class driver Abort returned %x\n",
763 err);
b0f6947b 764
18ecb428 765 status = CUPS_BACKEND_FAILED;
bc44d920 766 break;
09a101d6 767 }
b0f6947b
MS
768 else if (bytes > 0)
769 {
770 fprintf(stderr, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes);
09a101d6 771
b0f6947b
MS
772 g.print_bytes -= bytes;
773 print_ptr += bytes;
774 total_bytes += bytes;
775 }
f7deaa1a 776 }
09a101d6 777
778 if (print_fd != 0 && status == noErr)
779 fprintf(stderr, "DEBUG: Sending print file, %lld bytes...\n",
780 (off_t)total_bytes);
f7deaa1a 781 }
f7deaa1a 782 }
783
09a101d6 784 fprintf(stderr, "DEBUG: Sent %lld bytes...\n", (off_t)total_bytes);
1e3e80bb 785 fputs("STATE: +cups-waiting-for-job-completed\n", stderr);
f7deaa1a 786
7cf5915e 787 /*
a4845881 788 * Signal the side channel thread to exit...
7cf5915e
MS
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);
84315f46 801
7cf5915e
MS
802 if (!g.sidechannel_thread_done)
803 {
84315f46
MS
804 gettimeofday(&tv, NULL);
805 cond_timeout.tv_sec = tv.tv_sec + WAIT_SIDE_DELAY;
806 cond_timeout.tv_nsec = tv.tv_usec * 1000;
7cf5915e 807
84315f46
MS
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 }
7cf5915e 815 }
84315f46 816
7cf5915e 817 pthread_mutex_unlock(&g.sidechannel_thread_mutex);
7cf5915e
MS
818 }
819
7cf5915e 820 /*
a4845881 821 * Signal the read thread to exit then wait 7 seconds for it to complete...
7cf5915e
MS
822 */
823
824 g.read_thread_stop = 1;
825
7cf5915e
MS
826 pthread_mutex_lock(&g.read_thread_mutex);
827
828 if (!g.read_thread_done)
829 {
a4845881
MS
830 fputs("DEBUG: Waiting for read thread to exit...\n", stderr);
831
84315f46
MS
832 gettimeofday(&tv, NULL);
833 cond_timeout.tv_sec = tv.tv_sec + WAIT_EOF_DELAY;
834 cond_timeout.tv_nsec = tv.tv_usec * 1000;
7cf5915e 835
84315f46
MS
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
a4845881
MS
843 /*
844 * If it didn't exit abort the pending read and wait an additional second...
845 */
f3c17241 846
84315f46 847 if (!g.read_thread_done)
7cf5915e 848 {
f3c17241 849 fputs("DEBUG: Read thread still active, aborting the pending read...\n",
a4845881 850 stderr);
7cf5915e
MS
851
852 g.wait_eof = 0;
a4845881
MS
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;
f3c17241 859
a4845881
MS
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 }
7cf5915e
MS
866 }
867 }
84315f46 868
7cf5915e
MS
869 pthread_mutex_unlock(&g.read_thread_mutex);
870
09a101d6 871 /*
872 * Close the connection and input file and general clean up...
873 */
f7deaa1a 874
09a101d6 875 registry_close();
f7deaa1a 876
09a101d6 877 if (print_fd != STDIN_FILENO)
878 close(print_fd);
f7deaa1a 879
09a101d6 880 if (g.make != NULL)
881 CFRelease(g.make);
e53920b9 882
09a101d6 883 if (g.model != NULL)
884 CFRelease(g.model);
e53920b9 885
09a101d6 886 if (g.serial != NULL)
887 CFRelease(g.serial);
e53920b9 888
09a101d6 889 if (g.printer_obj != 0x0)
890 IOObjectRelease(g.printer_obj);
e53920b9 891
892 return status;
ef416fc2 893}
894
09a101d6 895
896/*
897 * 'read_thread()' - Thread to read the backchannel data on.
898 */
899
900static 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
321d8d57
MS
909
910 (void)reference;
911
09a101d6 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 {
b0f6947b
MS
929 fprintf(stderr, "DEBUG: Read %d bytes of back-channel data...\n",
930 (int)rbytes);
09a101d6 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 }
b0f6947b 945 else if (readstatus == kIOUSBTransactionTimeout)
3fb9c47e 946 fputs("DEBUG: Got USB transaction timeout during read\n", stderr);
b0f6947b 947 else if (readstatus == kIOUSBPipeStalled)
4d301e69 948 fputs("DEBUG: Got USB pipe stalled during read\n", stderr);
b0f6947b 949 else if (readstatus == kIOReturnAborted)
3fb9c47e 950 fputs("DEBUG: Got USB return aborted during read\n", stderr);
09a101d6 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
7530b13a
MS
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
09a101d6 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
999static void*
1000sidechannel_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
bc44d920 1007
321d8d57
MS
1008 (void)reference;
1009
bc44d920 1010 do
09a101d6 1011 {
1012 datalen = sizeof(data);
1013
1014 if (cupsSideChannelRead(&command, &status, data, &datalen, 1.0))
ef55b745
MS
1015 {
1016 if (status == CUPS_SC_STATUS_TIMEOUT)
1017 continue;
1018 else
1019 break;
1020 }
09a101d6 1021
1022 switch (command)
1023 {
1024 case CUPS_SC_CMD_SOFT_RESET: /* Do a soft reset */
b0f6947b
MS
1025 fputs("DEBUG: CUPS_SC_CMD_SOFT_RESET received from driver...\n",
1026 stderr);
1027
db1f069b
MS
1028 if ((*g.classdriver)->SoftReset != NULL)
1029 {
1030 soft_reset();
1031 cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, NULL, 0, 1.0);
b0f6947b
MS
1032 fputs("DEBUG: Returning status CUPS_STATUS_OK with no bytes...\n",
1033 stderr);
db1f069b
MS
1034 }
1035 else
1036 {
1037 cupsSideChannelWrite(command, CUPS_SC_STATUS_NOT_IMPLEMENTED,
1038 NULL, 0, 1.0);
b0f6947b
MS
1039 fputs("DEBUG: Returning status CUPS_STATUS_NOT_IMPLEMENTED with "
1040 "no bytes...\n", stderr);
db1f069b 1041 }
09a101d6 1042 break;
1043
1044 case CUPS_SC_CMD_DRAIN_OUTPUT: /* Drain all pending output */
b0f6947b
MS
1045 fputs("DEBUG: CUPS_SC_CMD_DRAIN_OUTPUT received from driver...\n",
1046 stderr);
1047
09a101d6 1048 g.drain_output = 1;
1049 break;
1050
1051 case CUPS_SC_CMD_GET_BIDI: /* Is the connection bidirectional? */
b0f6947b
MS
1052 fputs("DEBUG: CUPS_SC_CMD_GET_BIDI received from driver...\n",
1053 stderr);
1054
7e86f2f6 1055 data[0] = (char)g.bidi_flag;
09a101d6 1056 cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, data, 1, 1.0);
b0f6947b
MS
1057
1058 fprintf(stderr,
1059 "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
1060 data[0]);
09a101d6 1061 break;
1062
1063 case CUPS_SC_CMD_GET_DEVICE_ID: /* Return IEEE-1284 device ID */
b0f6947b
MS
1064 fputs("DEBUG: CUPS_SC_CMD_GET_DEVICE_ID received from driver...\n",
1065 stderr);
1066
09a101d6 1067 datalen = sizeof(data);
1068 get_device_id(&status, data, &datalen);
1069 cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, data, datalen, 1.0);
b0f6947b 1070
7e86f2f6 1071 if ((size_t)datalen < sizeof(data))
b0f6947b
MS
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);
09a101d6 1079 break;
1080
1081 case CUPS_SC_CMD_GET_STATE: /* Return device state */
b0f6947b
MS
1082 fputs("DEBUG: CUPS_SC_CMD_GET_STATE received from driver...\n",
1083 stderr);
1084
09a101d6 1085 data[0] = CUPS_SC_STATE_ONLINE;
1086 cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, data, 1, 1.0);
b0f6947b
MS
1087
1088 fprintf(stderr,
1089 "DEBUG: Returned CUPS_SC_STATUS_OK with 1 byte (%02X)...\n",
1090 data[0]);
09a101d6 1091 break;
1092
1093 default:
b0f6947b
MS
1094 fprintf(stderr, "DEBUG: Unknown side-channel command (%d) received "
1095 "from driver...\n", command);
1096
09a101d6 1097 cupsSideChannelWrite(command, CUPS_SC_STATUS_NOT_IMPLEMENTED,
1098 NULL, 0, 1.0);
b0f6947b
MS
1099
1100 fputs("DEBUG: Returned CUPS_SC_STATUS_NOT_IMPLEMENTED with no bytes...\n",
1101 stderr);
09a101d6 1102 break;
1103 }
1104 }
7cf5915e
MS
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);
bc44d920 1111
09a101d6 1112 return NULL;
1113}
1114
1115
e53920b9 1116#pragma mark -
ef416fc2 1117/*
09a101d6 1118 * 'iterate_printers()' - Iterate over all the printers.
1119 */
1120
fe750b86 1121static void iterate_printers(iterator_callback_t callBack, void *userdata)
09a101d6 1122{
fe750b86 1123 Iterating = 1;
de3edeba 1124
fe750b86
MS
1125 mach_port_t masterPort = 0x0;
1126 kern_return_t kr = IOMasterPort (bootstrap_port, &masterPort);
de3edeba 1127
fe750b86 1128 if (kr == kIOReturnSuccess && masterPort != 0x0)
09a101d6 1129 {
fe750b86 1130 iterator_reference_t reference = { callBack, userdata, true };
de3edeba 1131
fe750b86
MS
1132 IONotificationPortRef addNotification = IONotificationPortCreate(masterPort);
1133 io_iterator_t addIterator = IO_OBJECT_NULL;
de3edeba 1134
fe750b86
MS
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);
09a101d6 1148 }
de3edeba 1149
fe750b86 1150 Iterating = 0;
09a101d6 1151}
1152
1153
1154/*
1155 * 'device_added()' - Device added notifier.
e53920b9 1156 */
fe750b86 1157#define IsPrintingInterface(c,s,p) ((c) == kUSBPrintingInterfaceClass && (s) == kUSBPrintingSubclass && (p) != kUSBPrintingProtocolIPP)
e53920b9 1158
fe750b86 1159static void device_added(void *userdata, io_iterator_t iterator)
09a101d6 1160{
fe750b86
MS
1161 iterator_reference_t *reference = userdata;
1162 io_service_t device;
de3edeba 1163
fe750b86
MS
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 {
f1ebe30e
MS
1188 printer_interface_t printerIntf = usb_printer_interface_interface(intf);
1189 if (printerIntf != NULL)
fe750b86
MS
1190 {
1191 UInt8 intfClass = 0, intfSubclass = 0, intfProtocol = 0, intfNumber = 0;
1192
f1ebe30e
MS
1193 (*printerIntf)->GetInterfaceClass(printerIntf, &intfClass);
1194 (*printerIntf)->GetInterfaceSubClass(printerIntf, &intfSubclass);
1195 (*printerIntf)->GetInterfaceProtocol(printerIntf, &intfProtocol);
1196 (*printerIntf)->GetInterfaceNumber(printerIntf, &intfNumber);
fe750b86
MS
1197
1198 if (IsPrintingInterface(intfClass, intfSubclass, intfProtocol))
1199 {
f1ebe30e 1200 CFStringRef deviceIDString = copy_printer_interface_deviceid(printerIntf, 0);
fe750b86
MS
1201 if (deviceIDString != NULL)
1202 {
1203 reference->keepRunning = reference->callback(userdata, intf, deviceIDString, locationID, intfNumber, 0);
1204 CFRelease(deviceIDString);
1205 }
1206 }
1207
de3edeba 1208 IOUSBInterfaceDescriptor *intfDesc = NULL;
f1ebe30e 1209 while (reference->keepRunning && (intfDesc = (IOUSBInterfaceDescriptor *)(*printerIntf)->FindNextAssociatedDescriptor(printerIntf, intfDesc, kUSBInterfaceDesc)))
fe750b86
MS
1210 {
1211 intfClass = intfDesc->bInterfaceClass;
1212 intfSubclass = intfDesc->bInterfaceSubClass;
1213 intfProtocol = intfDesc->bInterfaceProtocol;
1214
1215 if ((IsPrintingInterface(intfClass, intfSubclass, intfProtocol)))
1216 {
f1ebe30e 1217 CFStringRef deviceIDString = copy_printer_interface_deviceid(printerIntf, intfDesc->bAlternateSetting);
fe750b86
MS
1218 if (deviceIDString != NULL)
1219 {
1220 reference->keepRunning = reference->callback(userdata, intf, deviceIDString, locationID, intfNumber, intfDesc->bAlternateSetting);
1221 CFRelease(deviceIDString);
1222 }
1223 }
1224 }
f1ebe30e 1225 (*printerIntf)->Release(printerIntf);
fe750b86 1226 }
de3edeba 1227 IOObjectRelease(intf);
fe750b86 1228 }
09a101d6 1229
fe750b86
MS
1230 device_added_done:
1231 if (devIntf != NULL) (*devIntf)->Release(devIntf);
1232 if (intfIterator != IO_OBJECT_NULL) IOObjectRelease(intfIterator);
09a101d6 1233
fe750b86
MS
1234 IOObjectRelease(device);
1235 }
de3edeba 1236
fe750b86
MS
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);
de3edeba 1241
fe750b86
MS
1242 if (!reference->keepRunning)
1243 CFRunLoopStop(CFRunLoopGetCurrent());
09a101d6 1244}
1245
09a101d6 1246/*
1247 * 'list_device_cb()' - list_device iterator callback.
1248 */
1249
fe750b86 1250static Boolean list_device_cb(void *refcon, io_service_t obj, CFStringRef deviceIDString, UInt32 deviceLocation, UInt8 interfaceNum, UInt8 alternateSetting)
ef416fc2 1251{
f8f7636e 1252 (void)refcon;
fe750b86
MS
1253 (void)interfaceNum;
1254 (void)alternateSetting;
321d8d57 1255
fe750b86 1256 if (obj != IO_OBJECT_NULL)
09a101d6 1257 {
de3edeba
MS
1258 CFStringRef make = deviceIDCopyManufacturer(deviceIDString);
1259 CFStringRef model = deviceIDCopyModel(deviceIDString);
1260 CFStringRef serial = deviceIDCopySerialNumber(deviceIDString);
1261
fe750b86
MS
1262 char uristr[1024], makestr[1024], modelstr[1024], serialstr[1024];
1263 char optionsstr[1024], idstr[1024], make_modelstr[1024];
de3edeba 1264
fe750b86
MS
1265 CFStringGetCString(deviceIDString, idstr, sizeof(idstr), kCFStringEncodingUTF8);
1266 backendGetMakeModel(idstr, make_modelstr, sizeof(make_modelstr));
de3edeba 1267
fe750b86 1268 modelstr[0] = '/';
de3edeba 1269
fe750b86
MS
1270 if (make == NULL || !CFStringGetCString(make, makestr, sizeof(makestr), kCFStringEncodingUTF8))
1271 strlcpy(makestr, "Unknown", sizeof(makestr));
de3edeba 1272
fe750b86
MS
1273 if (model == NULL || !CFStringGetCString(model, &modelstr[1], sizeof(modelstr)-1, kCFStringEncodingUTF8))
1274 strlcpy(modelstr + 1, "Printer", sizeof(modelstr) - 1);
de3edeba 1275
fe750b86
MS
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);
de3edeba 1281
fe750b86
MS
1282 httpAssembleURI(HTTP_URI_CODING_ALL, uristr, sizeof(uristr), "usb", NULL, makestr, 0, modelstr);
1283 strlcat(uristr, optionsstr, sizeof(uristr));
de3edeba 1284
fe750b86
MS
1285 cupsBackendReport("direct", uristr, make_modelstr, make_modelstr, idstr,
1286 NULL);
7530b13a 1287
de3edeba
MS
1288 if (make != NULL) CFRelease(make);
1289 if (model != NULL) CFRelease(model);
1290 if (serial != NULL) CFRelease(serial);
1291 }
1292
fe750b86 1293 return obj != IO_OBJECT_NULL;
ef416fc2 1294}
1295
e53920b9 1296/*
09a101d6 1297 * 'find_device_cb()' - print_device iterator callback.
e53920b9 1298 */
fe750b86 1299static Boolean find_device_cb(void *refcon, io_service_t obj, CFStringRef deviceIDString, UInt32 deviceLocation, UInt8 interfaceNum, UInt8 alternateSetting)
e53920b9 1300{
fe750b86 1301 Boolean keepLooking = true;
de3edeba 1302
fe750b86 1303 if (obj != IO_OBJECT_NULL)
09a101d6 1304 {
fe750b86
MS
1305 CFStringRef make = deviceIDCopyManufacturer(deviceIDString);
1306 CFStringRef model = deviceIDCopyModel(deviceIDString);
1307 CFStringRef serial = deviceIDCopySerialNumber(deviceIDString);
de3edeba 1308
fe750b86
MS
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;
de3edeba 1319 g.location = deviceLocation;
fe750b86
MS
1320 g.alternateSetting = alternateSetting;
1321 keepLooking = false;
1322 }
1323 }
1324 else
1325 {
1326 if (g.printer_obj != 0)
1327 IOObjectRelease(g.printer_obj);
de3edeba 1328
fe750b86
MS
1329 g.alternateSetting = alternateSetting;
1330 g.printer_obj = obj;
1331 IOObjectRetain(obj);
de3edeba 1332
fe750b86
MS
1333 if (g.location == 0 || g.location == deviceLocation)
1334 keepLooking = false;
1335 }
de3edeba 1336
fe750b86
MS
1337 if ( !keepLooking )
1338 g.interfaceNum = interfaceNum;
1339 }
1340 }
de3edeba 1341
fe750b86
MS
1342 if (make) CFRelease(make);
1343 if (model) CFRelease(model);
1344 if (serial) CFRelease(serial);
ef416fc2 1345 }
fe750b86 1346 else
09a101d6 1347 {
fe750b86
MS
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 }
7594b224 1359 }
de3edeba 1360
fe750b86
MS
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 }
de3edeba 1369
fe750b86
MS
1370 return keepLooking;
1371}
09a101d6 1372
fe750b86
MS
1373static CFStringRef deviceIDCopySerialNumber(CFStringRef deviceID)
1374{
1375 CFStringRef serialKeys[] = { CFSTR("SN:"), CFSTR("SERN:"), NULL };
de3edeba 1376
fe750b86
MS
1377 return copy_value_for_key(deviceID, serialKeys);
1378}
ef416fc2 1379
fe750b86
MS
1380static CFStringRef deviceIDCopyModel(CFStringRef deviceID)
1381{
1382 CFStringRef modelKeys[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL };
1383 return copy_value_for_key(deviceID, modelKeys);
ef416fc2 1384}
1385
fe750b86
MS
1386static CFStringRef deviceIDCopyManufacturer(CFStringRef deviceID)
1387{
1388 CFStringRef makeKeys[] = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL };
1389 return copy_value_for_key(deviceID, makeKeys);
1390}
ef416fc2 1391
e53920b9 1392/*
09a101d6 1393 * 'status_timer_cb()' - Status timer callback.
ef416fc2 1394 */
e53920b9 1395
09a101d6 1396static void status_timer_cb(CFRunLoopTimerRef timer,
1397 void *info)
ef416fc2 1398{
321d8d57
MS
1399 (void)timer;
1400 (void)info;
1401
c5571a1d 1402 fputs("STATE: +offline-report\n", stderr);
f3c17241 1403 _cupsLangPrintFilter(stderr, "INFO", _("The printer is offline."));
0a682745
MS
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 }
ef416fc2 1420}
1421
ef416fc2 1422
e53920b9 1423#pragma mark -
1424/*
1425 * 'load_classdriver()' - Load a classdriver.
1426 */
1427
09a101d6 1428static kern_return_t load_classdriver(CFStringRef driverPath,
321d8d57 1429 printer_interface_t interface,
09a101d6 1430 classdriver_t ***printerDriver)
e53920b9 1431{
bf3816c7
MS
1432 kern_return_t kr = kUSBPrinterClassDeviceNotOpen;
1433 classdriver_t **driver = NULL;
1434 CFStringRef bundle = driverPath ? driverPath : kUSBGenericTOPrinterClassDriver;
1435 char bundlestr[1024]; /* Bundle path */
bf3816c7
MS
1436 CFURLRef url; /* URL for driver */
1437 CFPlugInRef plugin = NULL; /* Plug-in address */
e53920b9 1438
bf3816c7
MS
1439
1440 CFStringGetCString(bundle, bundlestr, sizeof(bundlestr), kCFStringEncodingUTF8);
1441
1442 /*
1443 * Validate permissions for the class driver...
1444 */
1445
22c9029b
MS
1446 _cups_fc_result_t result = _cupsFileCheck(bundlestr,
1447 _CUPS_FILE_CHECK_DIRECTORY, 1,
0fa6c7fa 1448 Iterating ? NULL : _cupsFileCheckFilter, NULL);
22c9029b
MS
1449
1450 if (result && driverPath)
321d8d57 1451 return (load_classdriver(NULL, interface, printerDriver));
22c9029b
MS
1452 else if (result)
1453 return (kr);
bf3816c7
MS
1454
1455 /*
1456 * Try loading the class driver...
1457 */
1458
1459 url = CFURLCreateWithFileSystemPath(NULL, bundle, kCFURLPOSIXPathStyle, true);
e53920b9 1460
bf3816c7
MS
1461 if (url)
1462 {
1463 plugin = CFPlugInCreate(NULL, url);
1464 CFRelease(url);
1465 }
1466 else
1467 plugin = NULL;
e53920b9 1468
bf3816c7
MS
1469 if (plugin)
1470 {
1471 CFArrayRef factories = CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID, plugin);
1472 if (factories != NULL && CFArrayGetCount(factories) > 0)
09a101d6 1473 {
bf3816c7
MS
1474 CFUUIDRef factoryID = CFArrayGetValueAtIndex(factories, 0);
1475 IUnknownVTbl **iunknown = CFPlugInInstanceCreate(NULL, factoryID, kUSBPrinterClassTypeID);
1476 if (iunknown != NULL)
09a101d6 1477 {
bf3816c7
MS
1478 kr = (*iunknown)->QueryInterface(iunknown, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID), (LPVOID *)&driver);
1479 if (kr == kIOReturnSuccess && driver != NULL)
09a101d6 1480 {
bf3816c7
MS
1481 classdriver_t **genericDriver = NULL;
1482 if (driverPath != NULL && CFStringCompare(driverPath, kUSBGenericTOPrinterClassDriver, 0) != kCFCompareEqualTo)
321d8d57 1483 kr = load_classdriver(NULL, interface, &genericDriver);
e53920b9 1484
bf3816c7
MS
1485 if (kr == kIOReturnSuccess)
1486 {
321d8d57 1487 (*driver)->interface = interface;
bf3816c7 1488 (*driver)->Initialize(driver, genericDriver);
e53920b9 1489
bf3816c7 1490 (*driver)->plugin = plugin;
321d8d57 1491 (*driver)->interface = interface;
bf3816c7 1492 *printerDriver = driver;
e53920b9 1493 }
e53920b9 1494 }
bf3816c7 1495 (*iunknown)->Release(iunknown);
e53920b9 1496 }
bf3816c7 1497 CFRelease(factories);
ef416fc2 1498 }
e53920b9 1499 }
1500
c0e1af83 1501 fprintf(stderr, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr, (int)kr);
ef416fc2 1502
bf3816c7 1503 return (kr);
ef416fc2 1504}
1505
1506
e53920b9 1507/*
1508 * 'unload_classdriver()' - Unload a classdriver.
1509 */
ef416fc2 1510
09a101d6 1511static kern_return_t unload_classdriver(classdriver_t ***classdriver)
e53920b9 1512{
09a101d6 1513 if (*classdriver != NULL)
1514 {
1515 (**classdriver)->Release(*classdriver);
1516 *classdriver = NULL;
e53920b9 1517 }
ef416fc2 1518
e53920b9 1519 return kIOReturnSuccess;
1520}
ef416fc2 1521
ef416fc2 1522
e53920b9 1523/*
09a101d6 1524 * 'load_printerdriver()' - Load vendor's classdriver.
411affcf 1525 *
1526 * If driverBundlePath is not NULL on return it is the callers responsbility to release it!
e53920b9 1527 */
ef416fc2 1528
09a101d6 1529static kern_return_t load_printerdriver(CFStringRef *driverBundlePath)
ef416fc2 1530{
7594b224 1531 IOCFPlugInInterface **iodev = NULL;
1532 SInt32 score;
1533 kern_return_t kr;
321d8d57 1534 printer_interface_t interface;
7594b224 1535 HRESULT res;
1536
09a101d6 1537 kr = IOCreatePlugInInterfaceForService(g.printer_obj, kIOUSBInterfaceUserClientTypeID, kIOCFPlugInInterfaceID, &iodev, &score);
7594b224 1538 if (kr == kIOReturnSuccess)
1539 {
321d8d57 1540 if ((res = (*iodev)->QueryInterface(iodev, USB_INTERFACE_KIND, (LPVOID *) &interface)) == noErr)
7594b224 1541 {
09a101d6 1542 *driverBundlePath = IORegistryEntryCreateCFProperty(g.printer_obj, kUSBClassDriverProperty, NULL, kNilOptions);
e53920b9 1543
7530b13a 1544 g.use_generic_class_driver = (*driverBundlePath == NULL || (CFStringCompare(*driverBundlePath, kUSBGenericTOPrinterClassDriver, 0x0) == kCFCompareEqualTo));
321d8d57 1545 kr = load_classdriver(*driverBundlePath, interface, &g.classdriver);
ef416fc2 1546
e53920b9 1547 if (kr != kIOReturnSuccess)
321d8d57 1548 (*interface)->Release(interface);
e53920b9 1549 }
1550 IODestroyPlugInInterface(iodev);
1551 }
1552 return kr;
ef416fc2 1553}
1554
f1ebe30e 1555static printer_interface_t usb_printer_interface_interface(io_service_t usbClass)
fe750b86 1556{
f1ebe30e 1557 printer_interface_t intf = NULL;
fe750b86
MS
1558 IOCFPlugInInterface **plugin = NULL;
1559 SInt32 score;
1560 int kr = IOCreatePlugInInterfaceForService(usbClass, kIOUSBInterfaceUserClientTypeID, kIOCFPlugInInterfaceID, &plugin, &score);
1561 if (kr == kIOReturnSuccess)
1562 {
f1ebe30e 1563 (*plugin)->QueryInterface(plugin, USB_INTERFACE_KIND, (LPVOID *)&intf);
fe750b86
MS
1564 IODestroyPlugInInterface(plugin);
1565 }
1566
1567 return intf;
1568}
1569
1570static 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
f1ebe30e 1587static CFStringRef copy_printer_interface_deviceid(printer_interface_t printer, UInt8 alternateSetting)
fe750b86
MS
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
de3edeba
MS
1601 if (printer == NULL)
1602 return NULL;
fe750b86
MS
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
f8f7636e 1624 IOReturn berr = kIOReturnError;
fe750b86
MS
1625 char *buffer = malloc(size);
1626 if (buffer == NULL)
1627 return kIOReturnNoMemory;
1628
1629 request.wLength = HostToUSBWord(size);
1630 request.pData = buffer;
f8f7636e
MS
1631 berr = (*printer)->ControlRequestTO(printer, (UInt8)0, &request);
1632 return berr;
fe750b86
MS
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 {
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);
de3edeba 1672 CFStringRef model = deviceIDCopyModel(ret);
fe750b86
MS
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 {
de3edeba
MS
1697 manufacturer = copy_printer_interface_indexed_description(printer, desc.iManufacturer, kUSBLanguageEnglish);
1698 if (manufacturer && CFStringGetLength(manufacturer) > 0)
fe750b86
MS
1699 CFStringAppendFormat(extras, NULL, CFSTR("MFG:%@;"), manufacturer);
1700 }
1701
1702 if (model == NULL)
1703 {
de3edeba
MS
1704 model = copy_printer_interface_indexed_description(printer, desc.iProduct, kUSBLanguageEnglish);
1705 if (model && CFStringGetLength(model) > 0)
1706 CFStringAppendFormat(extras, NULL, CFSTR("MDL:%@;"), model);
fe750b86
MS
1707 }
1708
1709 if (serial == NULL && desc.iSerialNumber != 0)
1710 {
de3edeba
MS
1711 serial = copy_printer_interface_indexed_description(printer, desc.iSerialNumber, kUSBLanguageEnglish);
1712 if (serial && CFStringGetLength(serial) > 0)
fe750b86
MS
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
de3edeba
MS
1730 if (ret != NULL)
1731 {
fe750b86
MS
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 }
de3edeba
MS
1744 }
1745
1746 if (manufacturer != NULL)
1747 CFRelease(manufacturer);
7530b13a 1748
de3edeba
MS
1749 if (model != NULL)
1750 CFRelease(model);
7530b13a 1751
de3edeba
MS
1752 if (serial != NULL)
1753 CFRelease(serial);
fe750b86 1754
de3edeba
MS
1755 if (ret != NULL && CFStringGetLength(ret) == 0)
1756 {
1757 CFRelease(ret);
1758 return NULL;
1759 }
7530b13a 1760
de3edeba 1761 return ret;
fe750b86
MS
1762}
1763
f1ebe30e 1764static CFStringRef copy_printer_interface_indexed_description(printer_interface_t printer, UInt8 index, UInt16 language)
fe750b86
MS
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)
de3edeba 1802 return NULL;
fe750b86
MS
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);
f8f7636e 1818 request.wLength = (UInt16)length;
fe750b86
MS
1819 request.pData = &description;
1820 request.completionTimeout = 0;
1821 request.noDataTimeout = 60L;
1822
1823 err = (*printer)->ControlRequestTO(printer, 0, &request);
1824 if (err != kIOReturnSuccess)
de3edeba 1825 return NULL;
fe750b86
MS
1826
1827 if (description[1] != kUSBStringDesc)
de3edeba 1828 return NULL;
fe750b86
MS
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
f8f7636e 1842 for (unsigned i = 0; i < length; i++)
fe750b86
MS
1843 buffer[i] = (char) description[2*i+2];
1844
1845 buffer[length] = 0;
1846 }
1847
1848 return CFStringCreateWithCString(NULL, buffer, kCFStringEncodingUTF8);
1849}
ef416fc2 1850
e53920b9 1851/*
1852 * 'registry_open()' - Open a connection to the printer.
1853 */
ef416fc2 1854
09a101d6 1855static kern_return_t registry_open(CFStringRef *driverBundlePath)
e53920b9 1856{
09a101d6 1857 g.bidi_flag = 0; /* 0=unidirectional */
f7deaa1a 1858
09a101d6 1859 kern_return_t kr = load_printerdriver(driverBundlePath);
1860 if (kr != kIOReturnSuccess)
e53920b9 1861 kr = -2;
ef416fc2 1862
09a101d6 1863 if (g.classdriver != NULL)
1864 {
bc44d920 1865 (*g.classdriver)->interfaceNumber = g.interfaceNum;
09a101d6 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);
e53920b9 1875 kr = -1;
1876 }
1877 }
1878 }
09a101d6 1879 else
1880 g.bidi_flag = 1; /* 1=bidirectional */
e53920b9 1881 }
ef416fc2 1882
09a101d6 1883 if (kr != kIOReturnSuccess)
1884 unload_classdriver(&g.classdriver);
ef416fc2 1885
e53920b9 1886 return kr;
1887}
ef416fc2 1888
ef416fc2 1889
e53920b9 1890/*
1891 * 'registry_close()' - Close the connection to the printer.
1892 */
ef416fc2 1893
eac3a0a0 1894static kern_return_t registry_close(void)
ef416fc2 1895{
09a101d6 1896 if (g.classdriver != NULL)
1897 (*g.classdriver)->Close(g.classdriver);
1898
1899 unload_classdriver(&g.classdriver);
e53920b9 1900 return kIOReturnSuccess;
ef416fc2 1901}
1902
e53920b9 1903#pragma mark -
1904/*
1905 * 'copy_value_for_key()' - Copy value string associated with a key.
1906 */
ef416fc2 1907
09a101d6 1908static CFStringRef copy_value_for_key(CFStringRef deviceID,
1909 CFStringRef *keys)
ef416fc2 1910{
e53920b9 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
09a101d6 1916 while (idx < max && value == NULL)
1917 {
e53920b9 1918 CFStringRef kvpair = CFArrayGetValueAtIndex(kvPairs, idx);
1919 CFIndex idxx = 0;
09a101d6 1920 while (keys[idxx] != NULL && value == NULL)
1921 {
e53920b9 1922 CFRange range = CFStringFind(kvpair, keys[idxx], kCFCompareCaseInsensitive);
09a101d6 1923 if (range.length != -1)
1924 {
1925 if (range.location != 0)
1926 {
e53920b9 1927 CFMutableStringRef theString = CFStringCreateMutableCopy(NULL, 0, kvpair);
1928 CFStringTrimWhitespace(theString);
1929 range = CFStringFind(theString, keys[idxx], kCFCompareCaseInsensitive);
09a101d6 1930 if (range.location == 0)
e53920b9 1931 value = CFStringCreateWithSubstring(NULL, theString, CFRangeMake(range.length, CFStringGetLength(theString) - range.length));
09a101d6 1932
e53920b9 1933 CFRelease(theString);
1934 }
09a101d6 1935 else
1936 {
e53920b9 1937 CFStringRef theString = CFStringCreateWithSubstring(NULL, kvpair, CFRangeMake(range.length, CFStringGetLength(kvpair) - range.length));
1938 CFMutableStringRef theString2 = CFStringCreateMutableCopy(NULL, 0, theString);
1939 CFRelease(theString);
ef416fc2 1940
e53920b9 1941 CFStringTrimWhitespace(theString2);
1942 value = theString2;
ef416fc2 1943 }
e53920b9 1944 }
1945 idxx++;
ef416fc2 1946 }
e53920b9 1947 idx++;
1948 }
1949
1950 if (kvPairs != NULL)
09a101d6 1951 CFRelease(kvPairs);
e53920b9 1952 return value;
ef416fc2 1953}
1954
1955
411affcf 1956/*
09a101d6 1957 * 'cfstr_create_trim()' - Create CFString and trim whitespace characters.
411affcf 1958 */
1959
09a101d6 1960CFStringRef cfstr_create_trim(const char *cstr)
411affcf 1961{
1962 CFStringRef cfstr;
1963 CFMutableStringRef cfmutablestr = NULL;
09a101d6 1964
411affcf 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
e53920b9 1976#pragma mark -
1977/*
db1f069b 1978 * 'parse_options()' - Parse URI options.
e53920b9 1979 */
ef416fc2 1980
db1f069b 1981static void parse_options(char *options,
09a101d6 1982 char *serial,
76cd9e37 1983 int serial_size,
09a101d6 1984 UInt32 *location,
1985 Boolean *wait_eof)
e53920b9 1986{
db1f069b
MS
1987 char sep, /* Separator character */
1988 *name, /* Name of option */
1989 *value; /* Value of option */
1990
ef416fc2 1991
e53920b9 1992 if (serial)
1993 *serial = '\0';
1994 if (location)
1995 *location = 0;
ef416fc2 1996
e53920b9 1997 if (!options)
1998 return;
ef416fc2 1999
db1f069b 2000 while (*options)
09a101d6 2001 {
db1f069b
MS
2002 /*
2003 * Get the name...
2004 */
ef416fc2 2005
db1f069b 2006 name = options;
ef416fc2 2007
db1f069b 2008 while (*options && *options != '=' && *options != '+' && *options != '&')
e53920b9 2009 options ++;
ef416fc2 2010
db1f069b
MS
2011 if ((sep = *options) != '\0')
2012 *options++ = '\0';
ef416fc2 2013
db1f069b
MS
2014 if (sep == '=')
2015 {
2016 /*
2017 * Get the value...
2018 */
ef416fc2 2019
db1f069b
MS
2020 value = options;
2021
2022 while (*options && *options != '+' && *options != '&')
e53920b9 2023 options ++;
db1f069b
MS
2024
2025 if (*options)
2026 *options++ = '\0';
e53920b9 2027 }
db1f069b
MS
2028 else
2029 value = (char *)"";
ef416fc2 2030
db1f069b
MS
2031 /*
2032 * Process the option...
2033 */
2034
88f9aafc 2035 if (!_cups_strcasecmp(name, "waiteof"))
09a101d6 2036 {
88f9aafc
MS
2037 if (!_cups_strcasecmp(value, "on") ||
2038 !_cups_strcasecmp(value, "yes") ||
2039 !_cups_strcasecmp(value, "true"))
09a101d6 2040 *wait_eof = true;
88f9aafc
MS
2041 else if (!_cups_strcasecmp(value, "off") ||
2042 !_cups_strcasecmp(value, "no") ||
2043 !_cups_strcasecmp(value, "false"))
09a101d6 2044 *wait_eof = false;
2045 else
0837b7e8
MS
2046 _cupsLangPrintFilter(stderr, "WARNING",
2047 _("Boolean expected for waiteof option \"%s\"."),
2048 value);
e53920b9 2049 }
88f9aafc 2050 else if (!_cups_strcasecmp(name, "serial"))
76cd9e37 2051 strlcpy(serial, value, serial_size);
88f9aafc 2052 else if (!_cups_strcasecmp(name, "location") && location)
7e86f2f6 2053 *location = (UInt32)strtoul(value, NULL, 16);
e53920b9 2054 }
e53920b9 2055}
ef416fc2 2056
ef416fc2 2057
e53920b9 2058/*!
2059 * @function setup_cfLanguage
ac884b6a 2060 * @abstract Convert the contents of the CUPS 'APPLE_LANGUAGE' environment
e53920b9 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 */
2070static void setup_cfLanguage(void)
2071{
2072 CFStringRef lang[1] = {NULL};
2073 CFArrayRef langArray = NULL;
2074 const char *requestedLang = NULL;
2075
ac884b6a
MS
2076 if ((requestedLang = getenv("APPLE_LANGUAGE")) == NULL)
2077 requestedLang = getenv("LANG");
2078
09a101d6 2079 if (requestedLang != NULL)
2080 {
e53920b9 2081 lang[0] = CFStringCreateWithCString(kCFAllocatorDefault, requestedLang, kCFStringEncodingUTF8);
2082 langArray = CFArrayCreate(kCFAllocatorDefault, (const void **)lang, sizeof(lang) / sizeof(lang[0]), &kCFTypeArrayCallBacks);
2083
28b9d139 2084 CFPreferencesSetValue(CFSTR("AppleLanguages"), langArray, kCFPreferencesCurrentApplication, kCFPreferencesAnyUser, kCFPreferencesAnyHost);
005dd1eb 2085 fprintf(stderr, "DEBUG: usb: AppleLanguages=\"%s\"\n", requestedLang);
e53920b9 2086
2087 CFRelease(lang[0]);
2088 CFRelease(langArray);
e53920b9 2089 }
09a101d6 2090 else
ac884b6a 2091 fputs("DEBUG: usb: LANG and APPLE_LANGUAGE environment variables missing.\n", stderr);
e53920b9 2092}
ef416fc2 2093
e53920b9 2094#pragma mark -
749b1e90 2095#if defined(__i386__) || defined(__x86_64__)
e53920b9 2096/*!
749b1e90 2097 * @function run_legacy_backend
e53920b9 2098 *
749b1e90 2099 * @abstract Starts child backend process running as a ppc or i386 executable.
e53920b9 2100 *
2101 * @result Never returns; always calls exit().
2102 *
09a101d6 2103 * @discussion
e53920b9 2104 */
749b1e90
MS
2105static void run_legacy_backend(int argc,
2106 char *argv[],
2107 int fd)
e53920b9 2108{
2109 int i;
2110 int exitstatus = 0;
2111 int childstatus;
2112 pid_t waitpid_status;
2113 char *my_argv[32];
749b1e90 2114 char *usb_legacy_status;
ef416fc2 2115
7e86f2f6 2116
749b1e90
MS
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 */
e53920b9 2124
749b1e90
MS
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)
09a101d6 2132 {
9fb65b89
MS
2133 log_usb_class_driver(IS_NOT_64BIT);
2134
bc44d920 2135 /*
2136 * Setup a SIGTERM handler then block it before forking...
2137 */
ef416fc2 2138
ef55b745 2139 int err; /* posix_spawn result */
bc44d920 2140 struct sigaction action; /* POSIX signal action */
2141 sigset_t newmask, /* New signal mask */
2142 oldmask; /* Old signal mask */
58dc1933
MS
2143 char usbpath[1024]; /* Path to USB backend */
2144 const char *cups_serverbin;/* Path to CUPS binaries */
2145
bc44d920 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);
ef416fc2 2155
749b1e90
MS
2156 /*
2157 * Set the environment variable...
2158 */
bc44d920 2159
749b1e90
MS
2160# ifdef __x86_64__
2161 setenv("USB_I386_STATUS", "1", false);
2162# else
2163 setenv("USB_PPC_STATUS", "1", false);
2164# endif /* __x86_64__ */
bc44d920 2165
749b1e90
MS
2166 /*
2167 * Tell the kernel to use the specified CPU architecture...
2168 */
bc44d920 2169
749b1e90
MS
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__ */
9a4f8274 2175 size_t ocount = 1;
749b1e90 2176 posix_spawnattr_t attrs;
ef416fc2 2177
749b1e90
MS
2178 if (!posix_spawnattr_init(&attrs))
2179 {
b19ccc9e
MS
2180 posix_spawnattr_setsigdefault(&attrs, &oldmask);
2181 if (posix_spawnattr_setbinpref_np(&attrs, 1, &cpu, &ocount) || ocount != 1)
9a4f8274
MS
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__ */
0837b7e8
MS
2188 _cupsLangPrintFilter(stderr, "ERROR",
2189 _("Unable to use legacy USB class driver."));
9a4f8274
MS
2190 exit(CUPS_BACKEND_STOP);
2191 }
749b1e90 2192 }
bc44d920 2193
749b1e90
MS
2194 /*
2195 * Set up the arguments and call posix_spawn...
2196 */
ef416fc2 2197
58dc1933
MS
2198 if ((cups_serverbin = getenv("CUPS_SERVERBIN")) == NULL)
2199 cups_serverbin = CUPS_SERVERBIN;
2200 snprintf(usbpath, sizeof(usbpath), "%s/backend/usb", cups_serverbin);
2201
7e86f2f6 2202 for (i = 0; i < argc && i < (int)(sizeof(my_argv) / sizeof(my_argv[0])) - 1; i ++)
749b1e90 2203 my_argv[i] = argv[i];
ef416fc2 2204
749b1e90 2205 my_argv[i] = NULL;
ef416fc2 2206
ef55b745
MS
2207 if ((err = posix_spawn(&child_pid, usbpath, NULL, &attrs, my_argv,
2208 environ)) != 0)
09a101d6 2209 {
58dc1933 2210 fprintf(stderr, "DEBUG: Unable to exec %s: %s\n", usbpath,
ef55b745 2211 strerror(err));
0837b7e8
MS
2212 _cupsLangPrintFilter(stderr, "ERROR",
2213 _("Unable to use legacy USB class driver."));
749b1e90 2214 exit(CUPS_BACKEND_STOP);
bc44d920 2215 }
e53920b9 2216
bc44d920 2217 /*
2218 * Unblock signals...
2219 */
e53920b9 2220
bc44d920 2221 sigprocmask(SIG_SETMASK, &oldmask, NULL);
e53920b9 2222
bc44d920 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
005dd1eb
MS
2230 fprintf(stderr, "DEBUG: Started usb(legacy) backend (PID %d)\n",
2231 (int)child_pid);
bc44d920 2232
2233 while ((waitpid_status = waitpid(child_pid, &childstatus, 0)) == (pid_t)-1 && errno == EINTR)
2234 usleep(1000);
2235
2236 if (WIFSIGNALED(childstatus))
2237 {
749b1e90 2238 exitstatus = CUPS_BACKEND_STOP;
4d301e69 2239 fprintf(stderr, "DEBUG: usb(legacy) backend %d crashed on signal %d\n",
749b1e90 2240 child_pid, WTERMSIG(childstatus));
ef416fc2 2241 }
09a101d6 2242 else
2243 {
bc44d920 2244 if ((exitstatus = WEXITSTATUS(childstatus)) != 0)
005dd1eb 2245 fprintf(stderr,
4d301e69 2246 "DEBUG: usb(legacy) backend %d stopped with status %d\n",
005dd1eb 2247 child_pid, exitstatus);
bc44d920 2248 else
005dd1eb
MS
2249 fprintf(stderr, "DEBUG: usb(legacy) backend %d exited with no errors\n",
2250 child_pid);
e53920b9 2251 }
2252 }
09a101d6 2253 else
2254 {
005dd1eb 2255 fputs("DEBUG: usb(legacy) backend running native again\n", stderr);
749b1e90 2256 exitstatus = CUPS_BACKEND_STOP;
e53920b9 2257 }
ef416fc2 2258
e53920b9 2259 exit(exitstatus);
2260}
6c48a6ca
MS
2261#endif /* __i386__ || __x86_64__ */
2262
ef416fc2 2263
e53920b9 2264/*
2265 * 'sigterm_handler()' - SIGTERM handler.
2266 */
ef416fc2 2267
f11a948a
MS
2268static void
2269sigterm_handler(int sig) /* I - Signal */
ef416fc2 2270{
6c48a6ca
MS
2271#if defined(__i386__) || defined(__x86_64__)
2272 /*
2273 * If we started a child process pass the signal on to it...
2274 */
2275
e53920b9 2276 if (child_pid)
f11a948a
MS
2277 {
2278 /*
2279 * If we started a child process pass the signal on to it...
2280 */
e53920b9 2281
f11a948a
MS
2282 int status;
2283
2284 kill(child_pid, sig);
2285 while (waitpid(child_pid, &status, 0) < 0 && errno == EINTR);
ef416fc2 2286
f11a948a 2287 if (WIFEXITED(status))
c1de66f9 2288 _exit(WEXITSTATUS(status));
f11a948a 2289 else if (status == SIGTERM || status == SIGKILL)
c1de66f9 2290 _exit(0);
f11a948a
MS
2291 else
2292 {
c1de66f9
MS
2293 write(2, "DEBUG: Child crashed.\n", 22);
2294 _exit(CUPS_BACKEND_STOP);
f11a948a
MS
2295 }
2296 }
18ecb428 2297#endif /* __i386__ || __x86_64__ */
6c48a6ca 2298}
18ecb428 2299
ef416fc2 2300
a469f8a5
MS
2301/*
2302 * 'sigquit_handler()' - SIGQUIT handler.
2303 */
2304
2305static 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
e53920b9 2327#ifdef PARSE_PS_ERRORS
2328/*
2329 * 'next_line()' - Find the next line in a buffer.
2330 */
ef416fc2 2331
e53920b9 2332static const char *next_line (const char *buffer)
ef416fc2 2333{
e53920b9 2334 const char *cptr, *lptr = NULL;
ef416fc2 2335
e53920b9 2336 for (cptr = buffer; *cptr && lptr == NULL; cptr++)
2337 if (*cptr == '\n' || *cptr == '\r')
2338 lptr = cptr;
2339 return lptr;
ef416fc2 2340}
2341
ef416fc2 2342
e53920b9 2343/*
2344 * 'parse_pserror()' - Scan the backchannel data for postscript errors.
2345 */
ef416fc2 2346
09a101d6 2347static void parse_pserror(char *sockBuffer,
2348 int len)
ef416fc2 2349{
e53920b9 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
e53920b9 2368 pLineEnd = (char *)next_line((const char *)gErrorBuffer);
09a101d6 2369 while (pLineEnd != NULL)
2370 {
e53920b9 2371 *pLineEnd++ = '\0';
2372
2373 pCommentBegin = strstr(gErrorBuffer,"%%[");
2374 pCommentEnd = strstr(gErrorBuffer, "]%%");
09a101d6 2375 if (pCommentBegin != gErrorBuffer && pCommentEnd != NULL)
2376 {
e53920b9 2377 pCommentEnd += 3; /* Skip past "]%%" */
2378 *pCommentEnd = '\0'; /* There's always room for the nul */
2379
88f9aafc 2380 if (_cups_strncasecmp(pCommentBegin, "%%[ Error:", 10) == 0)
e53920b9 2381 logLevel = "DEBUG";
88f9aafc 2382 else if (_cups_strncasecmp(pCommentBegin, "%%[ Flushing", 12) == 0)
e53920b9 2383 logLevel = "DEBUG";
2384 else
2385 logLevel = "INFO";
2386
09a101d6 2387 if ((logstrlen = snprintf(logstr, sizeof(logstr), "%s: %s\n", logLevel, pCommentBegin)) >= sizeof(logstr))
2388 {
e53920b9 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);
ef416fc2 2394 }
ef416fc2 2395
e53920b9 2396 /* move everything over... */
5a9febac 2397 strlcpy(gErrorBuffer, pLineEnd, sizeof(gErrorBuffer));
e53920b9 2398 gErrorBufferPtr = gErrorBuffer;
2399 pLineEnd = (char *)next_line((const char *)gErrorBuffer);
2400 }
ef416fc2 2401}
e53920b9 2402#endif /* PARSE_PS_ERRORS */
ef416fc2 2403
e53920b9 2404
2405/*
db1f069b 2406 * 'soft_reset()' - Send a soft reset to the device.
ef416fc2 2407 */
e53920b9 2408
eac3a0a0 2409static void soft_reset(void)
ef416fc2 2410{
09a101d6 2411 fd_set input_set; /* Input set for select() */
84315f46 2412 struct timeval tv; /* Time value */
09a101d6 2413 char buffer[2048]; /* Buffer */
2414 struct timespec cond_timeout; /* pthread condition timeout */
e53920b9 2415
09a101d6 2416 /*
2417 * Send an abort once a second until the I/O lock is released by the main thread...
2418 */
e53920b9 2419
09a101d6 2420 pthread_mutex_lock(&g.readwrite_lock_mutex);
2421 while (g.readwrite_lock)
2422 {
2423 (*g.classdriver)->Abort(g.classdriver);
ef416fc2 2424
84315f46
MS
2425 gettimeofday(&tv, NULL);
2426 cond_timeout.tv_sec = tv.tv_sec + 1;
2427 cond_timeout.tv_nsec = tv.tv_usec * 1000;
e53920b9 2428
84315f46
MS
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 }
09a101d6 2436 }
f7deaa1a 2437
09a101d6 2438 g.readwrite_lock = 1;
2439 pthread_mutex_unlock(&g.readwrite_lock_mutex);
f7deaa1a 2440
09a101d6 2441 /*
2442 * Flush bytes waiting on print_fd...
2443 */
f7deaa1a 2444
09a101d6 2445 g.print_bytes = 0;
f7deaa1a 2446
09a101d6 2447 FD_ZERO(&input_set);
2448 FD_SET(g.print_fd, &input_set);
f7deaa1a 2449
84315f46
MS
2450 tv.tv_sec = 0;
2451 tv.tv_usec = 0;
f7deaa1a 2452
84315f46 2453 while (select(g.print_fd+1, &input_set, NULL, NULL, &tv) > 0)
09a101d6 2454 if (read(g.print_fd, buffer, sizeof(buffer)) <= 0)
2455 break;
f7deaa1a 2456
09a101d6 2457 /*
2458 * Send the reset...
2459 */
f7deaa1a 2460
7dfedb92 2461 (*g.classdriver)->SoftReset(g.classdriver, DEFAULT_TIMEOUT);
f7deaa1a 2462
09a101d6 2463 /*
2464 * Release the I/O lock...
2465 */
f7deaa1a 2466
09a101d6 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);
f7deaa1a 2471}
2472
f7deaa1a 2473
2474/*
09a101d6 2475 * 'get_device_id()' - Return IEEE-1284 device ID.
f7deaa1a 2476 */
f7deaa1a 2477
09a101d6 2478static void get_device_id(cups_sc_status_t *status,
2479 char *data,
2480 int *datalen)
2481{
f7deaa1a 2482 CFStringRef deviceIDString = NULL;
2483
fe750b86
MS
2484 if (g.printer_obj != IO_OBJECT_NULL)
2485 {
f1ebe30e
MS
2486 printer_interface_t printerIntf = usb_printer_interface_interface(g.printer_obj);
2487 if (printerIntf)
fe750b86 2488 {
f1ebe30e
MS
2489 deviceIDString = copy_printer_interface_deviceid(printerIntf, g.alternateSetting);
2490 (*printerIntf)->Release(printerIntf);
fe750b86
MS
2491 }
2492 }
2493
e38f5e9c 2494
09a101d6 2495 if (deviceIDString)
2496 {
fe750b86
MS
2497 if (CFStringGetCString(deviceIDString, data, *datalen, kCFStringEncodingUTF8))
2498 *datalen = (int)strlen(data);
2499 else
2500 *datalen = 0;
de3edeba 2501
09a101d6 2502 CFRelease(deviceIDString);
f7deaa1a 2503 }
fe750b86
MS
2504 else
2505 {
2506 *datalen = 0;
2507 }
2508
09a101d6 2509 *status = CUPS_SC_STATUS_OK;
f7deaa1a 2510}
2511
f7deaa1a 2512
9fb65b89
MS
2513static void
2514log_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");
b846cf01 2533 asl_log(NULL, aslm, ASL_LEVEL_NOTICE, "");
9fb65b89
MS
2534 asl_free(aslm);
2535 }
2536}
2537
2538
f7deaa1a 2539/*
f2d18633 2540 * End of "$Id$".
ef416fc2 2541 */