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