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