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