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