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