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