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