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