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