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