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