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