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