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