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