]> git.ipfire.org Git - thirdparty/cups.git/blame - backend/usb-darwin.c
Merge changes from CUPS 1.4svn-r8606.
[thirdparty/cups.git] / backend / usb-darwin.c
CommitLineData
ef416fc2 1/*
b19ccc9e 2* "$Id: usb-darwin.c 7953 2008-09-17 01:43:19Z mike $"
09a101d6 3*
bf3816c7 4* Copyright 2005-2009 Apple Inc. All rights reserved.
09a101d6 5*
6* IMPORTANT: This Apple software is supplied to you by Apple Computer,
7* Inc. ("Apple") in consideration of your agreement to the following
8* terms, and your use, installation, modification or redistribution of
9* this Apple software constitutes acceptance of these terms. If you do
10* not agree with these terms, please do not use, install, modify or
11* redistribute this Apple software.
12*
13* In consideration of your agreement to abide by the following terms, and
14* subject to these terms, Apple grants you a personal, non-exclusive
15* license, under Apple's copyrights in this original Apple software (the
16* "Apple Software"), to use, reproduce, modify and redistribute the Apple
17* Software, with or without modifications, in source and/or binary forms;
18* provided that if you redistribute the Apple Software in its entirety and
19* without modifications, you must retain this notice and the following
20* text and disclaimers in all such redistributions of the Apple Software.
21* Neither the name, trademarks, service marks or logos of Apple Computer,
22* Inc. may be used to endorse or promote products derived from the Apple
23* Software without specific prior written permission from Apple. Except
24* as expressly stated in this notice, no other rights or licenses, express
25* or implied, are granted by Apple herein, including but not limited to
26* any patent rights that may be infringed by your derivative works or by
27* other works in which the Apple Software may be incorporated.
28*
29* The Apple Software is provided by Apple on an "AS IS" basis. APPLE
30* MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
31* THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
32* FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
33* OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
34*
35* IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
36* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
37* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
38* INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
39* MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
40* AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
41* STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
42* POSSIBILITY OF SUCH DAMAGE.
43*
44* Contents:
45*
46* list_devices() - List all USB devices.
47* print_device() - Print a file to a USB device.
48* sidechannel_thread() - Thread to handle side-channel requests.
49* read_thread() - Thread to read the backchannel data on.
50* list_device_cb() - list_device iterator callback.
51* find_device_cb() - print_device iterator callback.
52* status_timer_cb() - Status timer callback.
53* iterate_printers() - Iterate over all the printers.
54* device_added() - Device added notifier.
55* copy_deviceinfo() - Copy strings from the 1284 device ID.
56* release_deviceinfo() - Release deviceinfo strings.
57* load_classdriver() - Load a classdriver.
58* unload_classdriver() - Unload a classdriver.
59* load_printerdriver() - Load vendor's classdriver.
60* registry_open() - Open a connection to the printer.
61* registry_close() - Close the connection to the printer.
62* copy_deviceid() - Copy the 1284 device id string.
63* copy_devicestring() - Copy the 1284 device id string.
64* copy_value_for_key() - Copy value string associated with a key.
65* cfstr_create_trim() - Create CFString and trim whitespace characters.
66* parse_options() - Parse uri options.
67* setup_cfLanguage() - Create AppleLanguages array from LANG environment var.
749b1e90 68* run_legacy_backend() - Re-exec backend as ppc or i386.
09a101d6 69* sigterm_handler() - SIGTERM handler.
70* next_line() - Find the next line in a buffer.
71* parse_pserror() - Scan the backchannel data for postscript errors.
72* get_device_id() - Return IEEE-1284 device ID.
73*/
ef416fc2 74
75/*
09a101d6 76 * Include necessary headers.
ef416fc2 77 */
09a101d6 78
ef416fc2 79#include <stdio.h>
80#include <stdlib.h>
81#include <errno.h>
82#include <signal.h>
83#include <fcntl.h>
84#include <termios.h>
85#include <unistd.h>
ac884b6a 86#include <sys/stat.h>
e53920b9 87#include <sys/sysctl.h>
88#include <libgen.h>
09a101d6 89#include <mach/mach.h>
e53920b9 90#include <mach/mach_error.h>
91#include <mach/mach_time.h>
92#include <cups/debug.h>
f7deaa1a 93#include <cups/sidechannel.h>
323c5de1 94#include <cups/i18n.h>
db0bd74a 95#include "backend-private.h"
ef416fc2 96
e53920b9 97#include <CoreFoundation/CoreFoundation.h>
98#include <IOKit/usb/IOUSBLib.h>
99#include <IOKit/IOCFPlugIn.h>
ef416fc2 100
749b1e90 101#include <spawn.h>
e53920b9 102#include <pthread.h>
ef416fc2 103
749b1e90
MS
104extern char **environ;
105
f7deaa1a 106
09a101d6 107/*
108 * WAIT_EOF_DELAY is number of seconds we'll wait for responses from
109 * the printer after we've finished sending all the data
ef416fc2 110 */
09a101d6 111#define WAIT_EOF_DELAY 7
bc44d920 112#define WAIT_SIDE_DELAY 3
7dfedb92 113#define DEFAULT_TIMEOUT 5000L
ef416fc2 114
e53920b9 115#define USB_INTERFACE_KIND CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID190)
116#define kUSBLanguageEnglish 0x409
ef416fc2 117
09a101d6 118#define PRINTER_POLLING_INTERVAL 5 /* seconds */
119#define INITIAL_LOG_INTERVAL PRINTER_POLLING_INTERVAL
120#define SUBSEQUENT_LOG_INTERVAL 3 * INITIAL_LOG_INTERVAL
ef416fc2 121
09a101d6 122#define kUSBPrinterClassTypeID CFUUIDGetConstantUUIDWithBytes(NULL, 0x06, 0x04, 0x7D, 0x16, 0x53, 0xA2, 0x11, 0xD6, 0x92, 0x06, 0x00, 0x30, 0x65, 0x52, 0x45, 0x92)
123#define kUSBPrinterClassInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, 0x03, 0x34, 0x6D, 0x74, 0x53, 0xA3, 0x11, 0xD6, 0x9E, 0xA1, 0x76, 0x30, 0x65, 0x52, 0x45, 0x92)
ef416fc2 124
125#define kUSBClassDriverProperty CFSTR("USB Printing Class")
ef416fc2 126
e53920b9 127#define kUSBGenericTOPrinterClassDriver CFSTR("/System/Library/Printers/Libraries/USBGenericTOPrintingClass.plugin")
128#define kUSBPrinterClassDeviceNotOpen -9664 /*kPMInvalidIOMContext*/
ef416fc2 129
ef416fc2 130
e53920b9 131/*
132 * Section 5.3 USB Printing Class spec
133 */
134#define kUSBPrintingSubclass 1
135#define kUSBPrintingProtocolNoOpen 0
136#define kUSBPrintingProtocolUnidirectional 1
137#define kUSBPrintingProtocolBidirectional 2
138
139typedef IOUSBInterfaceInterface190 **printer_interface_t;
ef416fc2 140
09a101d6 141typedef struct iodevice_request_s /**** Device request ****/
ef416fc2 142{
09a101d6 143 UInt8 requestType;
e53920b9 144 UInt8 request;
145 UInt16 value;
146 UInt16 index;
147 UInt16 length;
09a101d6 148 void *buffer;
e53920b9 149} iodevice_request_t;
150
09a101d6 151typedef union /**** Centronics status byte ****/
152{
e53920b9 153 char b;
09a101d6 154 struct
155 {
e53920b9 156 unsigned reserved0:2;
157 unsigned paperError:1;
158 unsigned select:1;
159 unsigned notError:1;
160 unsigned reserved1:3;
161 } status;
162} centronics_status_t;
163
09a101d6 164typedef struct classdriver_s /**** g.classdriver context ****/
ef416fc2 165{
166 IUNKNOWN_C_GUTS;
e53920b9 167 CFPlugInRef plugin; /* release plugin */
168 IUnknownVTbl **factory; /* Factory */
169 void *vendorReference; /* vendor class specific usage */
170 UInt32 location; /* unique location in bus topology */
171 UInt8 interfaceNumber; /* Interface number */
172 UInt16 vendorID; /* Vendor id */
173 UInt16 productID; /* Product id */
174 printer_interface_t interface; /* identify the device to IOKit */
175 UInt8 outpipe; /* mandatory bulkOut pipe */
176 UInt8 inpipe; /* optional bulkIn pipe */
ef416fc2 177
e53920b9 178 /* general class requests */
09a101d6 179 kern_return_t (*DeviceRequest)(struct classdriver_s **printer, iodevice_request_t *iorequest, UInt16 timeout);
180 kern_return_t (*GetString)(struct classdriver_s **printer, UInt8 whichString, UInt16 language, UInt16 timeout, CFStringRef *result);
ef416fc2 181
e53920b9 182 /* standard printer class requests */
09a101d6 183 kern_return_t (*SoftReset)(struct classdriver_s **printer, UInt16 timeout);
184 kern_return_t (*GetCentronicsStatus)(struct classdriver_s **printer, centronics_status_t *result, UInt16 timeout);
185 kern_return_t (*GetDeviceID)(struct classdriver_s **printer, CFStringRef *devid, UInt16 timeout);
ef416fc2 186
e53920b9 187 /* standard bulk device requests */
09a101d6 188 kern_return_t (*ReadPipe)(struct classdriver_s **printer, UInt8 *buffer, UInt32 *count);
189 kern_return_t (*WritePipe)(struct classdriver_s **printer, UInt8 *buffer, UInt32 *count, Boolean eoj);
ef416fc2 190
e53920b9 191 /* interface requests */
09a101d6 192 kern_return_t (*Open)(struct classdriver_s **printer, UInt32 location, UInt8 protocol);
193 kern_return_t (*Abort)(struct classdriver_s **printer);
194 kern_return_t (*Close)(struct classdriver_s **printer);
ef416fc2 195
e53920b9 196 /* initialize and terminate */
09a101d6 197 kern_return_t (*Initialize)(struct classdriver_s **printer, struct classdriver_s **baseclass);
198 kern_return_t (*Terminate)(struct classdriver_s **printer);
ef416fc2 199
09a101d6 200} classdriver_t;
ef416fc2 201
e53920b9 202typedef Boolean (*iterator_callback_t)(void *refcon, io_service_t obj);
ef416fc2 203
09a101d6 204typedef struct iterator_reference_s /**** Iterator reference data */
205{
e53920b9 206 iterator_callback_t callback;
207 void *userdata;
208 Boolean keepRunning;
209} iterator_reference_t;
ef416fc2 210
09a101d6 211typedef struct globals_s
212{
213 io_service_t printer_obj;
214 classdriver_t **classdriver;
215
216 pthread_mutex_t read_thread_mutex;
217 pthread_cond_t read_thread_cond;
218 int read_thread_stop;
219 int read_thread_done;
ef416fc2 220
09a101d6 221 pthread_mutex_t readwrite_lock_mutex;
222 pthread_cond_t readwrite_lock_cond;
223 int readwrite_lock;
ef416fc2 224
e53920b9 225 CFStringRef make;
226 CFStringRef model;
227 CFStringRef serial;
e53920b9 228 UInt32 location;
bc44d920 229 UInt8 interfaceNum;
09a101d6 230
231 CFRunLoopTimerRef status_timer;
232
233 int print_fd; /* File descriptor to print */
234 ssize_t print_bytes; /* Print bytes read */
235
236 Boolean wait_eof;
237 int drain_output; /* Drain all pending output */
238 int bidi_flag; /* 0=unidirectional, 1=bidirectional */
bc44d920 239
240 pthread_mutex_t sidechannel_thread_mutex;
241 pthread_cond_t sidechannel_thread_cond;
242 int sidechannel_thread_stop;
243 int sidechannel_thread_done;
09a101d6 244} globals_t;
245
246
247/*
248 * Globals...
249 */
250
251globals_t g = { 0 }; /* Globals */
ef416fc2 252
ef416fc2 253
e53920b9 254/*
255 * Local functions...
256 */
ef416fc2 257
09a101d6 258static Boolean find_device_cb(void *refcon, io_service_t obj);
259static Boolean list_device_cb(void *refcon, io_service_t obj);
260static CFStringRef cfstr_create_trim(const char *cstr);
261static CFStringRef copy_value_for_key(CFStringRef deviceID, CFStringRef *keys);
262static kern_return_t load_classdriver(CFStringRef driverPath, printer_interface_t intf, classdriver_t ***printerDriver);
263static kern_return_t load_printerdriver(CFStringRef *driverBundlePath);
264static kern_return_t registry_close();
265static kern_return_t registry_open(CFStringRef *driverBundlePath);
266static kern_return_t unload_classdriver();
267static OSStatus copy_deviceid(classdriver_t **printer, CFStringRef *deviceID);
268static void *read_thread(void *reference);
269static void *sidechannel_thread(void *reference);
e53920b9 270static void copy_deviceinfo(CFStringRef deviceIDString, CFStringRef *make, CFStringRef *model, CFStringRef *serial);
bc44d920 271static void copy_devicestring(io_service_t usbInterface, CFStringRef *deviceID, UInt32 *deviceLocation, UInt8 *interfaceNum);
09a101d6 272static void device_added(void *userdata, io_iterator_t iterator);
273static void get_device_id(cups_sc_status_t *status, char *data, int *datalen);
274static void iterate_printers(iterator_callback_t callBack, void *userdata);
db1f069b 275static void parse_options(char *options, char *serial, int serial_size, UInt32 *location, Boolean *wait_eof);
09a101d6 276static void release_deviceinfo(CFStringRef *make, CFStringRef *model, CFStringRef *serial);
e53920b9 277static void setup_cfLanguage(void);
09a101d6 278static void soft_reset();
279static void status_timer_cb(CFRunLoopTimerRef timer, void *info);
e53920b9 280
749b1e90 281#if defined(__i386__) || defined(__x86_64__)
f11a948a 282static pid_t child_pid; /* Child PID */
749b1e90 283static void run_legacy_backend(int argc, char *argv[], int fd); /* Starts child backend process running as a ppc executable */
749b1e90 284#endif /* __i386__ || __x86_64__ */
f11a948a
MS
285static int job_canceled = 0; /* Was the job canceled? */
286static void sigterm_handler(int sig); /* SIGTERM handler */
ef416fc2 287
e53920b9 288#ifdef PARSE_PS_ERRORS
289static const char *next_line (const char *buffer);
290static void parse_pserror (char *sockBuffer, int len);
291#endif /* PARSE_PS_ERRORS */
ef416fc2 292
e53920b9 293#pragma mark -
ef416fc2 294
e53920b9 295/*
296 * 'list_devices()' - List all USB devices.
297 */
ef416fc2 298
e53920b9 299void list_devices()
ef416fc2 300{
09a101d6 301 iterate_printers(list_device_cb, NULL);
ef416fc2 302}
303
ef416fc2 304
e53920b9 305/*
306 * 'print_device()' - Print a file to a USB device.
307 */
ef416fc2 308
e53920b9 309int /* O - Exit status */
310print_device(const char *uri, /* I - Device URI */
311 const char *hostname, /* I - Hostname/manufacturer */
312 const char *resource, /* I - Resource/modelname */
db1f069b 313 char *options, /* I - Device options/serial number */
09a101d6 314 int print_fd, /* I - File descriptor to print */
e53920b9 315 int copies, /* I - Copies to print */
316 int argc, /* I - Number of command-line arguments (6 or 7) */
317 char *argv[]) /* I - Command-line arguments */
ef416fc2 318{
09a101d6 319 char serial[1024]; /* Serial number buffer */
320 OSStatus status; /* Function results */
321 pthread_t read_thread_id, /* Read thread */
db1f069b 322 sidechannel_thread_id;/* Side-channel thread */
ac884b6a
MS
323 int have_sidechannel = 0; /* Was the side-channel thread started? */
324 struct stat sidechannel_info; /* Side-channel file descriptor info */
09a101d6 325 char print_buffer[8192], /* Print data buffer */
326 *print_ptr; /* Pointer into print data buffer */
327 UInt32 location; /* Unique location in bus topology */
328 fd_set input_set; /* Input set for select() */
329 CFStringRef driverBundlePath; /* Class driver path */
330 int countdown, /* Logging interval */
331 nfds; /* Number of file descriptors */
332 ssize_t total_bytes; /* Total bytes written */
333 UInt32 bytes; /* Bytes written */
334 struct timeval *timeout, /* Timeout pointer */
335 stimeout; /* Timeout for select() */
336 struct timespec cond_timeout; /* pthread condition timeout */
e53920b9 337
db1f069b 338
ac884b6a
MS
339 /*
340 * See if the side-channel descriptor is valid...
341 */
342
343 have_sidechannel = !fstat(CUPS_SC_FD, &sidechannel_info) &&
344 S_ISSOCK(sidechannel_info.st_mode);
345
346 /*
347 * Localize using CoreFoundation...
348 */
349
e53920b9 350 setup_cfLanguage();
09a101d6 351
76cd9e37 352 parse_options(options, serial, sizeof(serial), &location, &g.wait_eof);
e53920b9 353
354 if (resource[0] == '/')
355 resource++;
356
09a101d6 357 g.print_fd = print_fd;
358 g.make = cfstr_create_trim(hostname);
359 g.model = cfstr_create_trim(resource);
360 g.serial = cfstr_create_trim(serial);
361 g.location = location;
e53920b9 362
7dfedb92
MS
363 if (!g.make || !g.model)
364 {
005dd1eb
MS
365 _cupsLangPuts(stderr, _("ERROR: Fatal USB error!\n"));
366
367 if (!g.make)
368 fputs("DEBUG: USB make string is NULL!\n", stderr);
369 if (!g.model)
370 fputs("DEBUG: USB model string is NULL!\n", stderr);
371
372 return (CUPS_BACKEND_STOP);
7dfedb92
MS
373 }
374
e53920b9 375 fputs("STATE: +connecting-to-device\n", stderr);
376
09a101d6 377 countdown = INITIAL_LOG_INTERVAL;
378
379 do
380 {
381 if (g.printer_obj)
382 {
383 IOObjectRelease(g.printer_obj);
384 unload_classdriver(&g.classdriver);
385 g.printer_obj = 0x0;
386 g.classdriver = 0x0;
ef416fc2 387 }
ef416fc2 388
c0e1af83 389 fprintf(stderr, "DEBUG: Looking for '%s %s'\n", hostname, resource);
09a101d6 390
391 iterate_printers(find_device_cb, NULL);
e53920b9 392
c0e1af83 393 fputs("DEBUG: Opening connection\n", stderr);
411affcf 394
395 driverBundlePath = NULL;
09a101d6 396
397 status = registry_open(&driverBundlePath);
398
749b1e90 399#if defined(__i386__) || defined(__x86_64__)
e53920b9 400 /*
749b1e90
MS
401 * If we were unable to load the class drivers for this printer it's
402 * probably because they're ppc or i386. In this case try to run this
403 * backend as i386 or ppc executables so we can use them...
e53920b9 404 */
09a101d6 405 if (status == -2)
406 {
749b1e90 407 run_legacy_backend(argc, argv, print_fd);
e53920b9 408 /* Never returns here */
ef416fc2 409 }
749b1e90 410#endif /* __i386__ || __x86_64__ */
09a101d6 411
412 if (status == -2)
413 {
411affcf 414 /*
415 * If we still were unable to load the class drivers for this printer log
416 * the error and stop the queue...
417 */
418
09a101d6 419 if (driverBundlePath == NULL || !CFStringGetCString(driverBundlePath, print_buffer, sizeof(print_buffer), kCFStringEncodingUTF8))
420 strlcpy(print_buffer, "USB class driver", sizeof(print_buffer));
411affcf 421
c0e1af83 422 fputs("STATE: +apple-missing-usbclassdriver-error\n", stderr);
005dd1eb
MS
423 _cupsLangPuts(stderr, _("ERROR: Fatal USB error!\n"));
424 fprintf(stderr, "DEBUG: Could not load %s\n", print_buffer);
411affcf 425
426 if (driverBundlePath)
427 CFRelease(driverBundlePath);
428
005dd1eb 429 return (CUPS_BACKEND_STOP);
411affcf 430 }
431
432 if (driverBundlePath)
433 CFRelease(driverBundlePath);
e53920b9 434
09a101d6 435 if (status != noErr)
436 {
437 sleep(PRINTER_POLLING_INTERVAL);
e53920b9 438 countdown -= PRINTER_POLLING_INTERVAL;
09a101d6 439 if (countdown <= 0)
440 {
005dd1eb
MS
441 _cupsLangPuts(stderr,
442 _("INFO: Waiting for printer to become available...\n"));
443 fprintf(stderr, "DEBUG: USB printer status: 0x%08x\n", (int)status);
e53920b9 444 countdown = SUBSEQUENT_LOG_INTERVAL; /* subsequent log entries, every 15 seconds */
445 }
446 }
447 } while (status != noErr);
ef416fc2 448
e53920b9 449 fputs("STATE: -connecting-to-device\n", stderr);
ef416fc2 450
e53920b9 451 /*
f11a948a 452 * Now that we are "connected" to the port, catch SIGTERM so that we
e53920b9 453 * can finish out any page data the driver sends (e.g. to eject the
f11a948a 454 * current page... Only catch SIGTERM if we are printing data from
e53920b9 455 * stdin (otherwise you can't cancel raw jobs...)
456 */
ef416fc2 457
09a101d6 458 if (!print_fd)
459 {
bc44d920 460 struct sigaction action; /* POSIX signal action */
461
462
e53920b9 463 memset(&action, 0, sizeof(action));
ef416fc2 464
e53920b9 465 sigemptyset(&action.sa_mask);
f11a948a 466 action.sa_handler = sigterm_handler;
e53920b9 467 sigaction(SIGTERM, &action, NULL);
e53920b9 468 }
ef416fc2 469
09a101d6 470 /*
ac884b6a 471 * Start the side channel thread if the descriptor is valid...
09a101d6 472 */
ef416fc2 473
09a101d6 474 pthread_mutex_init(&g.readwrite_lock_mutex, NULL);
475 pthread_cond_init(&g.readwrite_lock_cond, NULL);
476 g.readwrite_lock = 1;
f7deaa1a 477
ac884b6a 478 if (have_sidechannel)
09a101d6 479 {
bc44d920 480 g.sidechannel_thread_stop = 0;
481 g.sidechannel_thread_done = 0;
482
483 pthread_cond_init(&g.sidechannel_thread_cond, NULL);
484 pthread_mutex_init(&g.sidechannel_thread_mutex, NULL);
485
09a101d6 486 if (pthread_create(&sidechannel_thread_id, NULL, sidechannel_thread, NULL))
487 {
005dd1eb
MS
488 _cupsLangPuts(stderr, _("ERROR: Fatal USB error!\n"));
489 fputs("DEBUG: Couldn't create side-channel thread!\n", stderr);
490 return (CUPS_BACKEND_STOP);
09a101d6 491 }
492 }
f7deaa1a 493
09a101d6 494 /*
495 * Get the read thread going...
496 */
f7deaa1a 497
09a101d6 498 g.read_thread_stop = 0;
499 g.read_thread_done = 0;
f7deaa1a 500
09a101d6 501 pthread_cond_init(&g.read_thread_cond, NULL);
502 pthread_mutex_init(&g.read_thread_mutex, NULL);
f7deaa1a 503
09a101d6 504 if (pthread_create(&read_thread_id, NULL, read_thread, NULL))
505 {
005dd1eb
MS
506 _cupsLangPuts(stderr, _("ERROR: Fatal USB error!\n"));
507 fputs("DEBUG: Couldn't create read thread!\n", stderr);
508 return (CUPS_BACKEND_STOP);
e53920b9 509 }
ef416fc2 510
09a101d6 511 /*
512 * The main thread sends the print file...
513 */
f7deaa1a 514
09a101d6 515 g.drain_output = 0;
516 g.print_bytes = 0;
517 total_bytes = 0;
518 print_ptr = print_buffer;
ef416fc2 519
09a101d6 520 while (status == noErr && copies-- > 0)
521 {
005dd1eb 522 _cupsLangPuts(stderr, _("INFO: Sending print data...\n"));
757d2cad 523
09a101d6 524 if (print_fd != STDIN_FILENO)
525 {
749b1e90 526 fputs("PAGE: 1 1\n", stderr);
09a101d6 527 lseek(print_fd, 0, SEEK_SET);
ef416fc2 528 }
529
09a101d6 530 while (status == noErr)
531 {
532 FD_ZERO(&input_set);
e53920b9 533
09a101d6 534 if (!g.print_bytes)
535 FD_SET(print_fd, &input_set);
f7deaa1a 536
09a101d6 537 /*
538 * Calculate select timeout...
539 * If we have data waiting to send timeout is 100ms.
540 * else if we're draining print_fd timeout is 0.
541 * else we're waiting forever...
542 */
543
544 if (g.print_bytes)
545 {
546 stimeout.tv_sec = 0;
547 stimeout.tv_usec = 100000; /* 100ms */
548 timeout = &stimeout;
549 }
550 else if (g.drain_output)
551 {
552 stimeout.tv_sec = 0;
553 stimeout.tv_usec = 0;
554 timeout = &stimeout;
555 }
556 else
557 timeout = NULL;
558
559 /*
560 * I/O is unlocked around select...
561 */
562
563 pthread_mutex_lock(&g.readwrite_lock_mutex);
564 g.readwrite_lock = 0;
565 pthread_cond_signal(&g.readwrite_lock_cond);
566 pthread_mutex_unlock(&g.readwrite_lock_mutex);
567
568 nfds = select(print_fd + 1, &input_set, NULL, NULL, timeout);
569
570 /*
571 * Reacquire the lock...
572 */
573
574 pthread_mutex_lock(&g.readwrite_lock_mutex);
575 while (g.readwrite_lock)
576 pthread_cond_wait(&g.readwrite_lock_cond, &g.readwrite_lock_mutex);
577 g.readwrite_lock = 1;
578 pthread_mutex_unlock(&g.readwrite_lock_mutex);
579
580 if (nfds < 0)
581 {
582 if (errno == EINTR && total_bytes == 0)
583 {
584 fputs("DEBUG: Received an interrupt before any bytes were "
585 "written, aborting!\n", stderr);
f11a948a 586 return (CUPS_BACKEND_OK);
09a101d6 587 }
588 else if (errno != EAGAIN)
589 {
005dd1eb
MS
590 _cupsLangPuts(stderr, _("ERROR: Unable to read print data!\n"));
591 perror("DEBUG: select");
f11a948a 592 return (CUPS_BACKEND_FAILED);
09a101d6 593 }
594 }
595
596 /*
597 * If drain output has finished send a response...
598 */
599
600 if (g.drain_output && !nfds && !g.print_bytes)
601 {
602 /* Send a response... */
603 cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT, CUPS_SC_STATUS_OK, NULL, 0, 1.0);
604 g.drain_output = 0;
605 }
606
607 /*
608 * Check if we have print data ready...
609 */
610
611 if (FD_ISSET(print_fd, &input_set))
612 {
613 g.print_bytes = read(print_fd, print_buffer, sizeof(print_buffer));
614
615 if (g.print_bytes < 0)
616 {
617 /*
618 * Read error - bail if we don't see EAGAIN or EINTR...
619 */
620
621 if (errno != EAGAIN || errno != EINTR)
622 {
005dd1eb
MS
623 _cupsLangPuts(stderr, _("ERROR: Unable to read print data!\n"));
624 perror("DEBUG: read");
f11a948a 625 return (CUPS_BACKEND_FAILED);
09a101d6 626 }
627
628 g.print_bytes = 0;
f7deaa1a 629 }
09a101d6 630 else if (g.print_bytes == 0)
631 {
632 /*
633 * End of file, break out of the loop...
634 */
f7deaa1a 635
e53920b9 636 break;
ef416fc2 637 }
638
09a101d6 639 print_ptr = print_buffer;
640
641 fprintf(stderr, "DEBUG: Read %d bytes of print data...\n",
642 (int)g.print_bytes);
e53920b9 643 }
ef416fc2 644
09a101d6 645 if (g.print_bytes)
646 {
647 bytes = g.print_bytes;
ef416fc2 648
09a101d6 649 status = (*g.classdriver)->WritePipe(g.classdriver, (UInt8*)print_ptr, &bytes, 0);
f7deaa1a 650
09a101d6 651 /*
58dc1933
MS
652 * Ignore timeout errors, but retain the number of bytes written to
653 * avoid sending duplicate data (<rdar://problem/6254911>)...
09a101d6 654 */
e53920b9 655
09a101d6 656 if (status == kIOUSBTransactionTimeout)
09a101d6 657 status = 0;
ef416fc2 658
09a101d6 659 if (status || bytes < 0)
660 {
661 /*
662 * Write error - bail if we don't see an error we can retry...
663 */
f7deaa1a 664
09a101d6 665 OSStatus err = (*g.classdriver)->Abort(g.classdriver);
005dd1eb
MS
666 _cupsLangPuts(stderr, _("ERROR: Unable to send print data!\n"));
667 fprintf(stderr, "DEBUG: USB class driver WritePipe returned %ld\n",
668 (long)status);
669 fprintf(stderr, "DEBUG: USB class driver Abort returned %ld\n",
670 (long)err);
f11a948a 671 status = job_canceled ? CUPS_BACKEND_FAILED : CUPS_BACKEND_STOP;
bc44d920 672 break;
09a101d6 673 }
674
675 fprintf(stderr, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes);
676
677 g.print_bytes -= bytes;
678 print_ptr += bytes;
679 total_bytes += bytes;
f7deaa1a 680 }
09a101d6 681
682 if (print_fd != 0 && status == noErr)
683 fprintf(stderr, "DEBUG: Sending print file, %lld bytes...\n",
684 (off_t)total_bytes);
f7deaa1a 685 }
f7deaa1a 686 }
687
09a101d6 688 fprintf(stderr, "DEBUG: Sent %lld bytes...\n", (off_t)total_bytes);
f7deaa1a 689
09a101d6 690 /*
691 * Wait for the side channel thread to exit...
692 */
693
ac884b6a 694 if (have_sidechannel)
bc44d920 695 {
db1f069b
MS
696 close(CUPS_SC_FD);
697 pthread_mutex_lock(&g.readwrite_lock_mutex);
698 g.readwrite_lock = 0;
699 pthread_cond_signal(&g.readwrite_lock_cond);
700 pthread_mutex_unlock(&g.readwrite_lock_mutex);
701
702 g.sidechannel_thread_stop = 1;
703 pthread_mutex_lock(&g.sidechannel_thread_mutex);
704 if (!g.sidechannel_thread_done)
705 {
706 /*
707 * Wait for the side-channel thread to exit...
708 */
bc44d920 709
db1f069b
MS
710 cond_timeout.tv_sec = time(NULL) + WAIT_SIDE_DELAY;
711 cond_timeout.tv_nsec = 0;
712 if (pthread_cond_timedwait(&g.sidechannel_thread_cond,
713 &g.sidechannel_thread_mutex,
714 &cond_timeout) != 0)
715 {
716 /*
717 * Force the side-channel thread to exit...
718 */
719
720 pthread_kill(sidechannel_thread_id, SIGTERM);
721 }
722 }
723 pthread_mutex_unlock(&g.sidechannel_thread_mutex);
09a101d6 724
db1f069b
MS
725 pthread_join(sidechannel_thread_id, NULL);
726
727 pthread_cond_destroy(&g.sidechannel_thread_cond);
728 pthread_mutex_destroy(&g.sidechannel_thread_mutex);
729 }
bc44d920 730
09a101d6 731 pthread_cond_destroy(&g.readwrite_lock_cond);
732 pthread_mutex_destroy(&g.readwrite_lock_mutex);
733
734 /*
735 * Signal the read thread to stop...
736 */
737
738 g.read_thread_stop = 1;
739
740 /*
741 * Give the read thread WAIT_EOF_DELAY seconds to complete all the data. If
db1f069b 742 * we are not signaled in that time then force the thread to exit.
09a101d6 743 */
744
745 pthread_mutex_lock(&g.read_thread_mutex);
ef416fc2 746
09a101d6 747 if (!g.read_thread_done)
748 {
749 cond_timeout.tv_sec = time(NULL) + WAIT_EOF_DELAY;
750 cond_timeout.tv_nsec = 0;
ef416fc2 751
bc44d920 752 if (pthread_cond_timedwait(&g.read_thread_cond, &g.read_thread_mutex,
753 &cond_timeout) != 0)
db1f069b
MS
754 {
755 /*
756 * Force the read thread to exit...
757 */
758
ed6e7faf 759 g.wait_eof = 0;
db1f069b
MS
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
0af14961
MS
1039 if (!make ||
1040 !CFStringGetCString(make, makestr, sizeof(makestr),
568fa3fa 1041 kCFStringEncodingUTF8))
f7deaa1a 1042 strcpy(makestr, "Unknown");
1043
0af14961
MS
1044 if (!model ||
1045 !CFStringGetCString(model, &modelstr[1], sizeof(modelstr)-1,
568fa3fa 1046 kCFStringEncodingUTF8))
f7deaa1a 1047 strcpy(modelstr + 1, "Printer");
e53920b9 1048
1049 optionsstr[0] = '\0';
1050 if (serial != NULL)
1051 {
1052 CFStringGetCString(serial, serialstr, sizeof(serialstr), kCFStringEncodingUTF8);
1053 snprintf(optionsstr, sizeof(optionsstr), "?serial=%s", serialstr);
1054 }
1055 else if (deviceLocation != 0)
09a101d6 1056 snprintf(optionsstr, sizeof(optionsstr), "?location=%x", (unsigned)deviceLocation);
e53920b9 1057
1058 httpAssembleURI(HTTP_URI_CODING_ALL, uristr, sizeof(uristr), "usb", NULL, makestr, 0, modelstr);
1059 strncat(uristr, optionsstr, sizeof(uristr));
1060
749b1e90
MS
1061 cupsBackendReport("direct", uristr, make_modelstr, make_modelstr, idstr,
1062 NULL);
e53920b9 1063
1064 release_deviceinfo(&make, &model, &serial);
1065 CFRelease(deviceIDString);
ef416fc2 1066 }
e53920b9 1067 }
1068
1069 return keepRunning;
ef416fc2 1070}
1071
1072
e53920b9 1073/*
09a101d6 1074 * 'find_device_cb()' - print_device iterator callback.
e53920b9 1075 */
ef416fc2 1076
09a101d6 1077static Boolean find_device_cb(void *refcon,
1078 io_service_t obj)
e53920b9 1079{
1080 Boolean keepLooking = true;
1081
09a101d6 1082 if (obj != 0x0)
1083 {
e53920b9 1084 CFStringRef idString = NULL;
1085 UInt32 location = -1;
bc44d920 1086 UInt8 interfaceNum = 0;
e53920b9 1087
bc44d920 1088 copy_devicestring(obj, &idString, &location, &interfaceNum);
09a101d6 1089 if (idString != NULL)
1090 {
e53920b9 1091 CFStringRef make = NULL, model = NULL, serial = NULL;
1092
1093 copy_deviceinfo(idString, &make, &model, &serial);
7dfedb92 1094 if (make && CFStringCompare(make, g.make, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
09a101d6 1095 {
7dfedb92 1096 if (model && CFStringCompare(model, g.model, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
09a101d6 1097 {
1098 if (g.serial != NULL && CFStringGetLength(g.serial) > 0)
1099 {
1100 if (serial != NULL && CFStringCompare(serial, g.serial, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
1101 {
e53920b9 1102 IOObjectRetain(obj);
09a101d6 1103 g.printer_obj = obj;
e53920b9 1104 keepLooking = false;
ef416fc2 1105 }
e53920b9 1106 }
09a101d6 1107 else
1108 {
1109 if (g.printer_obj != 0)
1110 IOObjectRelease(g.printer_obj);
1111
1112 g.printer_obj = obj;
e53920b9 1113 IOObjectRetain(obj);
1114
09a101d6 1115 if (g.location == 0 || g.location == location)
e53920b9 1116 keepLooking = false;
e53920b9 1117 }
bc44d920 1118 if ( !keepLooking )
1119 g.interfaceNum = interfaceNum;
ef416fc2 1120 }
e53920b9 1121 }
1122
1123 release_deviceinfo(&make, &model, &serial);
1124 CFRelease(idString);
ef416fc2 1125 }
e53920b9 1126 }
09a101d6 1127 else
1128 {
1129 keepLooking = (g.printer_obj == 0);
1130 if (obj == 0x0 && keepLooking)
1131 {
1132 CFRunLoopTimerContext context = { 0, refcon, NULL, NULL, NULL };
1133 CFRunLoopTimerRef timer = CFRunLoopTimerCreate(NULL, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb, &context);
1134 if (timer != NULL)
1135 {
7594b224 1136 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode);
09a101d6 1137 g.status_timer = timer;
7594b224 1138 }
1139 }
1140 }
09a101d6 1141
1142 if (!keepLooking && g.status_timer != NULL)
1143 {
c5571a1d 1144 fputs("STATE: -offline-report\n", stderr);
080811b1 1145 _cupsLangPuts(stderr, _("INFO: Printer is now online.\n"));
09a101d6 1146 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g.status_timer, kCFRunLoopDefaultMode);
1147 CFRelease(g.status_timer);
1148 g.status_timer = NULL;
e53920b9 1149 }
ef416fc2 1150
e53920b9 1151 return keepLooking;
ef416fc2 1152}
1153
1154
e53920b9 1155/*
09a101d6 1156 * 'status_timer_cb()' - Status timer callback.
ef416fc2 1157 */
e53920b9 1158
09a101d6 1159static void status_timer_cb(CFRunLoopTimerRef timer,
1160 void *info)
ef416fc2 1161{
c5571a1d 1162 fputs("STATE: +offline-report\n", stderr);
749b1e90 1163 _cupsLangPuts(stderr, _("INFO: Printer is offline.\n"));
0a682745
MS
1164
1165 if (getenv("CLASS") != NULL)
1166 {
1167 /*
1168 * If the CLASS environment variable is set, the job was submitted
1169 * to a class and not to a specific queue. In this case, we want
1170 * to abort immediately so that the job can be requeued on the next
1171 * available printer in the class.
1172 *
1173 * Sleep 5 seconds to keep the job from requeuing too rapidly...
1174 */
1175
1176 sleep(5);
1177
1178 exit(CUPS_BACKEND_FAILED);
1179 }
ef416fc2 1180}
1181
ef416fc2 1182
e53920b9 1183#pragma mark -
1184/*
1185 * 'copy_deviceinfo()' - Copy strings from the 1284 device ID.
1186 */
ef416fc2 1187
09a101d6 1188static void copy_deviceinfo(CFStringRef deviceIDString,
1189 CFStringRef *make,
1190 CFStringRef *model,
1191 CFStringRef *serial)
1192{
e53920b9 1193 CFStringRef modelKeys[] = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL };
1194 CFStringRef makeKeys[] = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL };
1195 CFStringRef serialKeys[] = { CFSTR("SN:"), CFSTR("SERN:"), NULL };
1196
1197 if (make != NULL)
0af14961 1198 *make = copy_value_for_key(deviceIDString, makeKeys);
568fa3fa 1199
e53920b9 1200 if (model != NULL)
0af14961 1201 *model = copy_value_for_key(deviceIDString, modelKeys);
568fa3fa 1202
e53920b9 1203 if (serial != NULL)
1204 *serial = copy_value_for_key(deviceIDString, serialKeys);
1205}
ef416fc2 1206
ef416fc2 1207
e53920b9 1208/*
1209 * 'release_deviceinfo()' - Release deviceinfo strings.
1210 */
ef416fc2 1211
09a101d6 1212static void release_deviceinfo(CFStringRef *make,
1213 CFStringRef *model,
1214 CFStringRef *serial)
ef416fc2 1215{
09a101d6 1216 if (make != NULL && *make != NULL)
1217 {
e53920b9 1218 CFRelease(*make);
1219 *make = NULL;
1220 }
1221
09a101d6 1222 if (model != NULL && *model != NULL)
1223 {
e53920b9 1224 CFRelease(*model);
1225 *model = NULL;
1226 }
1227
09a101d6 1228 if (serial != NULL && *serial != NULL)
1229 {
e53920b9 1230 CFRelease(*serial);
1231 *serial = NULL;
1232 }
1233}
1234
1235
1236#pragma mark -
1237/*
1238 * 'load_classdriver()' - Load a classdriver.
1239 */
1240
09a101d6 1241static kern_return_t load_classdriver(CFStringRef driverPath,
1242 printer_interface_t intf,
1243 classdriver_t ***printerDriver)
e53920b9 1244{
bf3816c7
MS
1245 kern_return_t kr = kUSBPrinterClassDeviceNotOpen;
1246 classdriver_t **driver = NULL;
1247 CFStringRef bundle = driverPath ? driverPath : kUSBGenericTOPrinterClassDriver;
1248 char bundlestr[1024]; /* Bundle path */
1249 struct stat bundleinfo; /* File information for bundle */
1250 CFURLRef url; /* URL for driver */
1251 CFPlugInRef plugin = NULL; /* Plug-in address */
e53920b9 1252
bf3816c7
MS
1253
1254 CFStringGetCString(bundle, bundlestr, sizeof(bundlestr), kCFStringEncodingUTF8);
1255
1256 /*
1257 * Validate permissions for the class driver...
1258 */
1259
1260 if (stat(bundlestr, &bundleinfo))
09a101d6 1261 {
bf3816c7
MS
1262 fprintf(stderr, "Unable to load class driver \"%s\": %s", bundlestr,
1263 strerror(errno));
1264 return (kr);
1265 }
1266 else if (bundleinfo.st_mode & S_IWOTH)
1267 {
1268 fprintf(stderr, "Unable to load class driver \"%s\": insecure file "
1269 "permissions (0%o)", bundlestr, bundleinfo.st_mode);
1270 return (kr);
1271 }
1272
1273 /*
1274 * Try loading the class driver...
1275 */
1276
1277 url = CFURLCreateWithFileSystemPath(NULL, bundle, kCFURLPOSIXPathStyle, true);
e53920b9 1278
bf3816c7
MS
1279 if (url)
1280 {
1281 plugin = CFPlugInCreate(NULL, url);
1282 CFRelease(url);
1283 }
1284 else
1285 plugin = NULL;
e53920b9 1286
bf3816c7
MS
1287 if (plugin)
1288 {
1289 CFArrayRef factories = CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID, plugin);
1290 if (factories != NULL && CFArrayGetCount(factories) > 0)
09a101d6 1291 {
bf3816c7
MS
1292 CFUUIDRef factoryID = CFArrayGetValueAtIndex(factories, 0);
1293 IUnknownVTbl **iunknown = CFPlugInInstanceCreate(NULL, factoryID, kUSBPrinterClassTypeID);
1294 if (iunknown != NULL)
09a101d6 1295 {
bf3816c7
MS
1296 kr = (*iunknown)->QueryInterface(iunknown, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID), (LPVOID *)&driver);
1297 if (kr == kIOReturnSuccess && driver != NULL)
09a101d6 1298 {
bf3816c7
MS
1299 classdriver_t **genericDriver = NULL;
1300 if (driverPath != NULL && CFStringCompare(driverPath, kUSBGenericTOPrinterClassDriver, 0) != kCFCompareEqualTo)
1301 kr = load_classdriver(NULL, intf, &genericDriver);
e53920b9 1302
bf3816c7
MS
1303 if (kr == kIOReturnSuccess)
1304 {
1305 (*driver)->interface = intf;
1306 (*driver)->Initialize(driver, genericDriver);
e53920b9 1307
bf3816c7
MS
1308 (*driver)->plugin = plugin;
1309 (*driver)->interface = intf;
1310 *printerDriver = driver;
e53920b9 1311 }
e53920b9 1312 }
bf3816c7 1313 (*iunknown)->Release(iunknown);
e53920b9 1314 }
bf3816c7 1315 CFRelease(factories);
ef416fc2 1316 }
e53920b9 1317 }
1318
c0e1af83 1319 fprintf(stderr, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr, (int)kr);
ef416fc2 1320
bf3816c7 1321 return (kr);
ef416fc2 1322}
1323
1324
e53920b9 1325/*
1326 * 'unload_classdriver()' - Unload a classdriver.
1327 */
ef416fc2 1328
09a101d6 1329static kern_return_t unload_classdriver(classdriver_t ***classdriver)
e53920b9 1330{
09a101d6 1331 if (*classdriver != NULL)
1332 {
1333 (**classdriver)->Release(*classdriver);
1334 *classdriver = NULL;
e53920b9 1335 }
ef416fc2 1336
e53920b9 1337 return kIOReturnSuccess;
1338}
ef416fc2 1339
ef416fc2 1340
e53920b9 1341/*
09a101d6 1342 * 'load_printerdriver()' - Load vendor's classdriver.
411affcf 1343 *
1344 * If driverBundlePath is not NULL on return it is the callers responsbility to release it!
e53920b9 1345 */
ef416fc2 1346
09a101d6 1347static kern_return_t load_printerdriver(CFStringRef *driverBundlePath)
ef416fc2 1348{
7594b224 1349 IOCFPlugInInterface **iodev = NULL;
1350 SInt32 score;
1351 kern_return_t kr;
1352 printer_interface_t intf;
1353 HRESULT res;
1354
09a101d6 1355 kr = IOCreatePlugInInterfaceForService(g.printer_obj, kIOUSBInterfaceUserClientTypeID, kIOCFPlugInInterfaceID, &iodev, &score);
7594b224 1356 if (kr == kIOReturnSuccess)
1357 {
1358 if ((res = (*iodev)->QueryInterface(iodev, USB_INTERFACE_KIND, (LPVOID *) &intf)) == noErr)
1359 {
09a101d6 1360 *driverBundlePath = IORegistryEntryCreateCFProperty(g.printer_obj, kUSBClassDriverProperty, NULL, kNilOptions);
e53920b9 1361
09a101d6 1362 kr = load_classdriver(*driverBundlePath, intf, &g.classdriver);
ef416fc2 1363
e53920b9 1364 if (kr != kIOReturnSuccess)
1365 (*intf)->Release(intf);
1366 }
1367 IODestroyPlugInInterface(iodev);
1368 }
1369 return kr;
ef416fc2 1370}
1371
1372
e53920b9 1373/*
1374 * 'registry_open()' - Open a connection to the printer.
1375 */
ef416fc2 1376
09a101d6 1377static kern_return_t registry_open(CFStringRef *driverBundlePath)
e53920b9 1378{
09a101d6 1379 g.bidi_flag = 0; /* 0=unidirectional */
f7deaa1a 1380
09a101d6 1381 kern_return_t kr = load_printerdriver(driverBundlePath);
1382 if (kr != kIOReturnSuccess)
e53920b9 1383 kr = -2;
ef416fc2 1384
09a101d6 1385 if (g.classdriver != NULL)
1386 {
bc44d920 1387 (*g.classdriver)->interfaceNumber = g.interfaceNum;
09a101d6 1388 kr = (*g.classdriver)->Open(g.classdriver, g.location, kUSBPrintingProtocolBidirectional);
1389 if (kr != kIOReturnSuccess || (*g.classdriver)->interface == NULL)
1390 {
1391 kr = (*g.classdriver)->Open(g.classdriver, g.location, kUSBPrintingProtocolUnidirectional);
1392 if (kr == kIOReturnSuccess)
1393 {
1394 if ((*g.classdriver)->interface == NULL)
1395 {
1396 (*g.classdriver)->Close(g.classdriver);
e53920b9 1397 kr = -1;
1398 }
1399 }
1400 }
09a101d6 1401 else
1402 g.bidi_flag = 1; /* 1=bidirectional */
e53920b9 1403 }
ef416fc2 1404
09a101d6 1405 if (kr != kIOReturnSuccess)
1406 unload_classdriver(&g.classdriver);
ef416fc2 1407
e53920b9 1408 return kr;
1409}
ef416fc2 1410
ef416fc2 1411
e53920b9 1412/*
1413 * 'registry_close()' - Close the connection to the printer.
1414 */
ef416fc2 1415
09a101d6 1416static kern_return_t registry_close()
ef416fc2 1417{
09a101d6 1418 if (g.classdriver != NULL)
1419 (*g.classdriver)->Close(g.classdriver);
1420
1421 unload_classdriver(&g.classdriver);
e53920b9 1422 return kIOReturnSuccess;
ef416fc2 1423}
1424
1425
e53920b9 1426/*
1427 * 'copy_deviceid()' - Copy the 1284 device id string.
1428 */
1429
09a101d6 1430static OSStatus copy_deviceid(classdriver_t **classdriver,
1431 CFStringRef *deviceID)
ef416fc2 1432{
e53920b9 1433 CFStringRef devID = NULL,
1434
1435 deviceMake = NULL,
1436 deviceModel = NULL,
1437 deviceSerial = NULL;
1438
09a101d6 1439 OSStatus err = (*classdriver)->GetDeviceID(classdriver, &devID, DEFAULT_TIMEOUT);
e53920b9 1440
1441 copy_deviceinfo(devID, &deviceMake, &deviceModel, &deviceSerial);
1442
09a101d6 1443 if (deviceMake == NULL || deviceModel == NULL || deviceSerial == NULL)
1444 {
e53920b9 1445 IOUSBDeviceDescriptor desc;
1446 iodevice_request_t request;
1447
09a101d6 1448 request.requestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
e53920b9 1449 request.request = kUSBRqGetDescriptor;
1450 request.value = (kUSBDeviceDesc << 8) | 0;
1451 request.index = 0;
1452 request.length = sizeof(desc);
1453 request.buffer = &desc;
09a101d6 1454 err = (*classdriver)->DeviceRequest(classdriver, &request, DEFAULT_TIMEOUT);
1455 if (err == kIOReturnSuccess)
1456 {
e53920b9 1457 CFMutableStringRef newDevID = CFStringCreateMutable(NULL, 0);
1458
09a101d6 1459 if (deviceMake == NULL)
1460 {
e53920b9 1461 CFStringRef data = NULL;
09a101d6 1462 err = (*classdriver)->GetString(classdriver, desc.iManufacturer, kUSBLanguageEnglish, DEFAULT_TIMEOUT, &data);
1463 if (data != NULL)
1464 {
e53920b9 1465 CFStringAppendFormat(newDevID, NULL, CFSTR("MFG:%@;"), data);
1466 CFRelease(data);
ef416fc2 1467 }
e53920b9 1468 }
1469
09a101d6 1470 if (deviceModel == NULL)
1471 {
e53920b9 1472 CFStringRef data = NULL;
09a101d6 1473 err = (*classdriver)->GetString(classdriver, desc.iProduct, kUSBLanguageEnglish, DEFAULT_TIMEOUT, &data);
1474 if (data != NULL)
1475 {
e53920b9 1476 CFStringAppendFormat(newDevID, NULL, CFSTR("MDL:%@;"), data);
1477 CFRelease(data);
ef416fc2 1478 }
e53920b9 1479 }
1480
09a101d6 1481 if (deviceSerial == NULL && desc.iSerialNumber != 0)
1482 {
e53920b9 1483 CFStringRef data = NULL;
09a101d6 1484 err = (*classdriver)->GetString(classdriver, desc.iSerialNumber, kUSBLanguageEnglish, DEFAULT_TIMEOUT, &data);
1485 if (data != NULL)
1486 {
e53920b9 1487 CFStringAppendFormat(newDevID, NULL, CFSTR("SERN:%@;"), data);
1488 CFRelease(data);
ef416fc2 1489 }
e53920b9 1490 }
ef416fc2 1491
09a101d6 1492 if (devID != NULL)
1493 {
e53920b9 1494 CFStringAppend(newDevID, devID);
1495 CFRelease(devID);
1496 }
ef416fc2 1497
e53920b9 1498 *deviceID = newDevID;
1499 }
1500 }
09a101d6 1501 else
1502 {
e53920b9 1503 *deviceID = devID;
1504 }
1505 release_deviceinfo(&deviceMake, &deviceModel, &deviceSerial);
ef416fc2 1506
e53920b9 1507 return err;
1508}
ef416fc2 1509
ef416fc2 1510
e53920b9 1511/*
1512 * 'copy_devicestring()' - Copy the 1284 device id string.
1513 */
ef416fc2 1514
09a101d6 1515static void copy_devicestring(io_service_t usbInterface,
1516 CFStringRef *deviceID,
bc44d920 1517 UInt32 *deviceLocation,
1518 UInt8 *interfaceNumber )
e53920b9 1519{
7594b224 1520 IOCFPlugInInterface **iodev = NULL;
1521 SInt32 score;
1522 kern_return_t kr;
1523 printer_interface_t intf;
1524 HRESULT res;
09a101d6 1525 classdriver_t **klassDriver = NULL;
7594b224 1526 CFStringRef driverBundlePath;
1527
09a101d6 1528 if ((kr = IOCreatePlugInInterfaceForService(usbInterface,
1529 kIOUSBInterfaceUserClientTypeID,
1530 kIOCFPlugInInterfaceID,
1531 &iodev, &score)) == kIOReturnSuccess)
7594b224 1532 {
09a101d6 1533 if ((res = (*iodev)->QueryInterface(iodev, USB_INTERFACE_KIND, (LPVOID *)
1534 &intf)) == noErr)
7594b224 1535 {
09a101d6 1536 (*intf)->GetLocationID(intf, deviceLocation);
bc44d920 1537 (*intf)->GetInterfaceNumber(intf, interfaceNumber);
e53920b9 1538
09a101d6 1539 driverBundlePath = IORegistryEntryCreateCFProperty(usbInterface,
1540 kUSBClassDriverProperty,
1541 NULL, kNilOptions);
e53920b9 1542
7594b224 1543 kr = load_classdriver(driverBundlePath, intf, &klassDriver);
ef416fc2 1544
7594b224 1545 if (kr != kIOReturnSuccess && driverBundlePath != NULL)
1546 kr = load_classdriver(NULL, intf, &klassDriver);
1547
09a101d6 1548 if (kr == kIOReturnSuccess && klassDriver != NULL)
1549 kr = copy_deviceid(klassDriver, deviceID);
ef416fc2 1550
7594b224 1551 unload_classdriver(&klassDriver);
1552
1553 if (driverBundlePath != NULL)
1554 CFRelease(driverBundlePath);
ef416fc2 1555
e53920b9 1556 /* (*intf)->Release(intf); */
09a101d6 1557 }
e53920b9 1558 IODestroyPlugInInterface(iodev);
1559 }
1560}
ef416fc2 1561
ef416fc2 1562
e53920b9 1563#pragma mark -
1564/*
1565 * 'copy_value_for_key()' - Copy value string associated with a key.
1566 */
ef416fc2 1567
09a101d6 1568static CFStringRef copy_value_for_key(CFStringRef deviceID,
1569 CFStringRef *keys)
ef416fc2 1570{
e53920b9 1571 CFStringRef value = NULL;
1572 CFArrayRef kvPairs = deviceID != NULL ? CFStringCreateArrayBySeparatingStrings(NULL, deviceID, CFSTR(";")) : NULL;
1573 CFIndex max = kvPairs != NULL ? CFArrayGetCount(kvPairs) : 0;
1574 CFIndex idx = 0;
1575
09a101d6 1576 while (idx < max && value == NULL)
1577 {
e53920b9 1578 CFStringRef kvpair = CFArrayGetValueAtIndex(kvPairs, idx);
1579 CFIndex idxx = 0;
09a101d6 1580 while (keys[idxx] != NULL && value == NULL)
1581 {
e53920b9 1582 CFRange range = CFStringFind(kvpair, keys[idxx], kCFCompareCaseInsensitive);
09a101d6 1583 if (range.length != -1)
1584 {
1585 if (range.location != 0)
1586 {
e53920b9 1587 CFMutableStringRef theString = CFStringCreateMutableCopy(NULL, 0, kvpair);
1588 CFStringTrimWhitespace(theString);
1589 range = CFStringFind(theString, keys[idxx], kCFCompareCaseInsensitive);
09a101d6 1590 if (range.location == 0)
e53920b9 1591 value = CFStringCreateWithSubstring(NULL, theString, CFRangeMake(range.length, CFStringGetLength(theString) - range.length));
09a101d6 1592
e53920b9 1593 CFRelease(theString);
1594 }
09a101d6 1595 else
1596 {
e53920b9 1597 CFStringRef theString = CFStringCreateWithSubstring(NULL, kvpair, CFRangeMake(range.length, CFStringGetLength(kvpair) - range.length));
1598 CFMutableStringRef theString2 = CFStringCreateMutableCopy(NULL, 0, theString);
1599 CFRelease(theString);
ef416fc2 1600
e53920b9 1601 CFStringTrimWhitespace(theString2);
1602 value = theString2;
ef416fc2 1603 }
e53920b9 1604 }
1605 idxx++;
ef416fc2 1606 }
e53920b9 1607 idx++;
1608 }
1609
1610 if (kvPairs != NULL)
09a101d6 1611 CFRelease(kvPairs);
e53920b9 1612 return value;
ef416fc2 1613}
1614
1615
411affcf 1616/*
09a101d6 1617 * 'cfstr_create_trim()' - Create CFString and trim whitespace characters.
411affcf 1618 */
1619
09a101d6 1620CFStringRef cfstr_create_trim(const char *cstr)
411affcf 1621{
1622 CFStringRef cfstr;
1623 CFMutableStringRef cfmutablestr = NULL;
09a101d6 1624
411affcf 1625 if ((cfstr = CFStringCreateWithCString(NULL, cstr, kCFStringEncodingUTF8)) != NULL)
1626 {
1627 if ((cfmutablestr = CFStringCreateMutableCopy(NULL, 1024, cfstr)) != NULL)
1628 CFStringTrimWhitespace(cfmutablestr);
1629
1630 CFRelease(cfstr);
1631 }
1632 return (CFStringRef) cfmutablestr;
1633}
1634
1635
e53920b9 1636#pragma mark -
1637/*
db1f069b 1638 * 'parse_options()' - Parse URI options.
e53920b9 1639 */
ef416fc2 1640
db1f069b 1641static void parse_options(char *options,
09a101d6 1642 char *serial,
76cd9e37 1643 int serial_size,
09a101d6 1644 UInt32 *location,
1645 Boolean *wait_eof)
e53920b9 1646{
db1f069b
MS
1647 char sep, /* Separator character */
1648 *name, /* Name of option */
1649 *value; /* Value of option */
1650
ef416fc2 1651
e53920b9 1652 if (serial)
1653 *serial = '\0';
1654 if (location)
1655 *location = 0;
ef416fc2 1656
e53920b9 1657 if (!options)
1658 return;
ef416fc2 1659
db1f069b 1660 while (*options)
09a101d6 1661 {
db1f069b
MS
1662 /*
1663 * Get the name...
1664 */
ef416fc2 1665
db1f069b 1666 name = options;
ef416fc2 1667
db1f069b 1668 while (*options && *options != '=' && *options != '+' && *options != '&')
e53920b9 1669 options ++;
ef416fc2 1670
db1f069b
MS
1671 if ((sep = *options) != '\0')
1672 *options++ = '\0';
ef416fc2 1673
db1f069b
MS
1674 if (sep == '=')
1675 {
1676 /*
1677 * Get the value...
1678 */
ef416fc2 1679
db1f069b
MS
1680 value = options;
1681
1682 while (*options && *options != '+' && *options != '&')
e53920b9 1683 options ++;
db1f069b
MS
1684
1685 if (*options)
1686 *options++ = '\0';
e53920b9 1687 }
db1f069b
MS
1688 else
1689 value = (char *)"";
ef416fc2 1690
db1f069b
MS
1691 /*
1692 * Process the option...
1693 */
1694
1695 if (!strcasecmp(name, "waiteof"))
09a101d6 1696 {
db1f069b
MS
1697 if (!strcasecmp(value, "on") ||
1698 !strcasecmp(value, "yes") ||
1699 !strcasecmp(value, "true"))
09a101d6 1700 *wait_eof = true;
db1f069b
MS
1701 else if (!strcasecmp(value, "off") ||
1702 !strcasecmp(value, "no") ||
1703 !strcasecmp(value, "false"))
09a101d6 1704 *wait_eof = false;
1705 else
db1f069b
MS
1706 _cupsLangPrintf(stderr,
1707 _("WARNING: Boolean expected for waiteof option "
1708 "\"%s\"\n"), value);
e53920b9 1709 }
db1f069b 1710 else if (!strcasecmp(name, "serial"))
76cd9e37 1711 strlcpy(serial, value, serial_size);
db1f069b 1712 else if (!strcasecmp(name, "location") && location)
e53920b9 1713 *location = strtol(value, NULL, 16);
e53920b9 1714 }
e53920b9 1715}
ef416fc2 1716
ef416fc2 1717
e53920b9 1718/*!
1719 * @function setup_cfLanguage
ac884b6a 1720 * @abstract Convert the contents of the CUPS 'APPLE_LANGUAGE' environment
e53920b9 1721 * variable into a one element CF array of languages.
1722 *
1723 * @discussion Each submitted job comes with a natural language. CUPS passes
1724 * that language in an environment variable. We take that language
1725 * and jam it into the AppleLanguages array so that CF will use
1726 * it when reading localized resources. We need to do this before
1727 * any CF code reads and caches the languages array, so this function
1728 * should be called early in main()
1729 */
1730static void setup_cfLanguage(void)
1731{
1732 CFStringRef lang[1] = {NULL};
1733 CFArrayRef langArray = NULL;
1734 const char *requestedLang = NULL;
1735
ac884b6a
MS
1736 if ((requestedLang = getenv("APPLE_LANGUAGE")) == NULL)
1737 requestedLang = getenv("LANG");
1738
09a101d6 1739 if (requestedLang != NULL)
1740 {
e53920b9 1741 lang[0] = CFStringCreateWithCString(kCFAllocatorDefault, requestedLang, kCFStringEncodingUTF8);
1742 langArray = CFArrayCreate(kCFAllocatorDefault, (const void **)lang, sizeof(lang) / sizeof(lang[0]), &kCFTypeArrayCallBacks);
1743
28b9d139 1744 CFPreferencesSetValue(CFSTR("AppleLanguages"), langArray, kCFPreferencesCurrentApplication, kCFPreferencesAnyUser, kCFPreferencesAnyHost);
005dd1eb 1745 fprintf(stderr, "DEBUG: usb: AppleLanguages=\"%s\"\n", requestedLang);
e53920b9 1746
1747 CFRelease(lang[0]);
1748 CFRelease(langArray);
e53920b9 1749 }
09a101d6 1750 else
ac884b6a 1751 fputs("DEBUG: usb: LANG and APPLE_LANGUAGE environment variables missing.\n", stderr);
e53920b9 1752}
ef416fc2 1753
e53920b9 1754#pragma mark -
749b1e90 1755#if defined(__i386__) || defined(__x86_64__)
e53920b9 1756/*!
749b1e90 1757 * @function run_legacy_backend
e53920b9 1758 *
749b1e90 1759 * @abstract Starts child backend process running as a ppc or i386 executable.
e53920b9 1760 *
1761 * @result Never returns; always calls exit().
1762 *
09a101d6 1763 * @discussion
e53920b9 1764 */
749b1e90
MS
1765static void run_legacy_backend(int argc,
1766 char *argv[],
1767 int fd)
e53920b9 1768{
1769 int i;
1770 int exitstatus = 0;
1771 int childstatus;
1772 pid_t waitpid_status;
1773 char *my_argv[32];
749b1e90 1774 char *usb_legacy_status;
ef416fc2 1775
749b1e90
MS
1776 /*
1777 * If we're running as x86_64 or i386 and couldn't load the class driver
1778 * (because it's ppc or i386), then try to re-exec ourselves in ppc or i386
1779 * mode to try again. If we don't have a ppc or i386 architecture we may be
1780 * running with the same architecture again so guard against this by setting
1781 * and testing an environment variable...
1782 */
e53920b9 1783
749b1e90
MS
1784# ifdef __x86_64__
1785 usb_legacy_status = getenv("USB_I386_STATUS");
1786# else
1787 usb_legacy_status = getenv("USB_PPC_STATUS");
1788# endif /* __x86_64__ */
1789
1790 if (!usb_legacy_status)
09a101d6 1791 {
bc44d920 1792 /*
1793 * Setup a SIGTERM handler then block it before forking...
1794 */
ef416fc2 1795
bc44d920 1796 struct sigaction action; /* POSIX signal action */
1797 sigset_t newmask, /* New signal mask */
1798 oldmask; /* Old signal mask */
58dc1933
MS
1799 char usbpath[1024]; /* Path to USB backend */
1800 const char *cups_serverbin;/* Path to CUPS binaries */
1801
bc44d920 1802
1803 memset(&action, 0, sizeof(action));
1804 sigaddset(&action.sa_mask, SIGTERM);
1805 action.sa_handler = sigterm_handler;
1806 sigaction(SIGTERM, &action, NULL);
1807
1808 sigemptyset(&newmask);
1809 sigaddset(&newmask, SIGTERM);
1810 sigprocmask(SIG_BLOCK, &newmask, &oldmask);
ef416fc2 1811
749b1e90
MS
1812 /*
1813 * Set the environment variable...
1814 */
bc44d920 1815
749b1e90
MS
1816# ifdef __x86_64__
1817 setenv("USB_I386_STATUS", "1", false);
1818# else
1819 setenv("USB_PPC_STATUS", "1", false);
1820# endif /* __x86_64__ */
bc44d920 1821
749b1e90
MS
1822 /*
1823 * Tell the kernel to use the specified CPU architecture...
1824 */
bc44d920 1825
749b1e90
MS
1826# ifdef __x86_64__
1827 cpu_type_t cpu = CPU_TYPE_I386;
1828# else
1829 cpu_type_t cpu = CPU_TYPE_POWERPC;
1830# endif /* __x86_64__ */
9a4f8274 1831 size_t ocount = 1;
749b1e90 1832 posix_spawnattr_t attrs;
ef416fc2 1833
749b1e90
MS
1834 if (!posix_spawnattr_init(&attrs))
1835 {
b19ccc9e
MS
1836 posix_spawnattr_setsigdefault(&attrs, &oldmask);
1837 if (posix_spawnattr_setbinpref_np(&attrs, 1, &cpu, &ocount) || ocount != 1)
9a4f8274
MS
1838 {
1839# ifdef __x86_64__
1840 perror("DEBUG: Unable to set binary preference to i386");
1841# else
1842 perror("DEBUG: Unable to set binary preference to ppc");
1843# endif /* __x86_64__ */
1844 _cupsLangPrintf(stderr, _("Unable to use legacy USB class driver!\n"));
1845 exit(CUPS_BACKEND_STOP);
1846 }
749b1e90 1847 }
bc44d920 1848
749b1e90
MS
1849 /*
1850 * Set up the arguments and call posix_spawn...
1851 */
ef416fc2 1852
58dc1933
MS
1853 if ((cups_serverbin = getenv("CUPS_SERVERBIN")) == NULL)
1854 cups_serverbin = CUPS_SERVERBIN;
1855 snprintf(usbpath, sizeof(usbpath), "%s/backend/usb", cups_serverbin);
1856
749b1e90
MS
1857 for (i = 0; i < argc && i < (sizeof(my_argv) / sizeof(my_argv[0])) - 1; i ++)
1858 my_argv[i] = argv[i];
ef416fc2 1859
749b1e90 1860 my_argv[i] = NULL;
ef416fc2 1861
58dc1933 1862 if (posix_spawn(&child_pid, usbpath, NULL, &attrs, my_argv, environ))
09a101d6 1863 {
58dc1933
MS
1864 fprintf(stderr, "DEBUG: Unable to exec %s: %s\n", usbpath,
1865 strerror(errno));
9a4f8274 1866 _cupsLangPrintf(stderr, _("Unable to use legacy USB class driver!\n"));
749b1e90 1867 exit(CUPS_BACKEND_STOP);
bc44d920 1868 }
e53920b9 1869
bc44d920 1870 /*
1871 * Unblock signals...
1872 */
e53920b9 1873
bc44d920 1874 sigprocmask(SIG_SETMASK, &oldmask, NULL);
e53920b9 1875
bc44d920 1876 /*
1877 * Close the fds we won't be using then wait for the child backend to exit.
1878 */
1879
1880 close(fd);
1881 close(1);
1882
005dd1eb
MS
1883 fprintf(stderr, "DEBUG: Started usb(legacy) backend (PID %d)\n",
1884 (int)child_pid);
bc44d920 1885
1886 while ((waitpid_status = waitpid(child_pid, &childstatus, 0)) == (pid_t)-1 && errno == EINTR)
1887 usleep(1000);
1888
1889 if (WIFSIGNALED(childstatus))
1890 {
749b1e90 1891 exitstatus = CUPS_BACKEND_STOP;
005dd1eb 1892 fprintf(stderr, "DEBUG: usb(legacy) backend %d crashed on signal %d!\n",
749b1e90 1893 child_pid, WTERMSIG(childstatus));
ef416fc2 1894 }
09a101d6 1895 else
1896 {
bc44d920 1897 if ((exitstatus = WEXITSTATUS(childstatus)) != 0)
005dd1eb
MS
1898 fprintf(stderr,
1899 "DEBUG: usb(legacy) backend %d stopped with status %d!\n",
1900 child_pid, exitstatus);
bc44d920 1901 else
005dd1eb
MS
1902 fprintf(stderr, "DEBUG: usb(legacy) backend %d exited with no errors\n",
1903 child_pid);
e53920b9 1904 }
1905 }
09a101d6 1906 else
1907 {
005dd1eb 1908 fputs("DEBUG: usb(legacy) backend running native again\n", stderr);
749b1e90 1909 exitstatus = CUPS_BACKEND_STOP;
e53920b9 1910 }
ef416fc2 1911
e53920b9 1912 exit(exitstatus);
1913}
f11a948a
MS
1914#endif /* __i386__ || __x86_64__ */
1915
ef416fc2 1916
e53920b9 1917/*
1918 * 'sigterm_handler()' - SIGTERM handler.
1919 */
ef416fc2 1920
f11a948a
MS
1921static void
1922sigterm_handler(int sig) /* I - Signal */
ef416fc2 1923{
f11a948a 1924#if defined(__i386__) || defined(__x86_64__)
e53920b9 1925 if (child_pid)
f11a948a
MS
1926 {
1927 /*
1928 * If we started a child process pass the signal on to it...
1929 */
e53920b9 1930
f11a948a
MS
1931 int status;
1932
1933 kill(child_pid, sig);
1934 while (waitpid(child_pid, &status, 0) < 0 && errno == EINTR);
ef416fc2 1935
f11a948a
MS
1936 if (WIFEXITED(status))
1937 exit(WEXITSTATUS(status));
1938 else if (status == SIGTERM || status == SIGKILL)
1939 exit(0);
1940 else
1941 {
1942 fprintf(stderr, "DEBUG: Child crashed on signal %d!\n", status);
1943 exit(CUPS_BACKEND_STOP);
1944 }
1945 }
749b1e90 1946#endif /* __i386__ || __x86_64__ */
ef416fc2 1947
f11a948a
MS
1948 /*
1949 * Otherwise just flag that the job has been canceled...
1950 */
1951
1952 job_canceled = 1;
1953}
1954
ef416fc2 1955
e53920b9 1956#ifdef PARSE_PS_ERRORS
1957/*
1958 * 'next_line()' - Find the next line in a buffer.
1959 */
ef416fc2 1960
e53920b9 1961static const char *next_line (const char *buffer)
ef416fc2 1962{
e53920b9 1963 const char *cptr, *lptr = NULL;
ef416fc2 1964
e53920b9 1965 for (cptr = buffer; *cptr && lptr == NULL; cptr++)
1966 if (*cptr == '\n' || *cptr == '\r')
1967 lptr = cptr;
1968 return lptr;
ef416fc2 1969}
1970
ef416fc2 1971
e53920b9 1972/*
1973 * 'parse_pserror()' - Scan the backchannel data for postscript errors.
1974 */
ef416fc2 1975
09a101d6 1976static void parse_pserror(char *sockBuffer,
1977 int len)
ef416fc2 1978{
e53920b9 1979 static char gErrorBuffer[1024] = "";
1980 static char *gErrorBufferPtr = gErrorBuffer;
1981 static char *gErrorBufferEndPtr = gErrorBuffer + sizeof(gErrorBuffer);
1982
1983 char *pCommentBegin, *pCommentEnd, *pLineEnd;
1984 char *logLevel;
1985 char logstr[1024];
1986 int logstrlen;
1987
1988 if (gErrorBufferPtr + len > gErrorBufferEndPtr - 1)
1989 gErrorBufferPtr = gErrorBuffer;
1990 if (len > sizeof(gErrorBuffer) - 1)
1991 len = sizeof(gErrorBuffer) - 1;
1992
1993 memcpy(gErrorBufferPtr, (const void *)sockBuffer, len);
1994 gErrorBufferPtr += len;
1995 *(gErrorBufferPtr + 1) = '\0';
1996
e53920b9 1997 pLineEnd = (char *)next_line((const char *)gErrorBuffer);
09a101d6 1998 while (pLineEnd != NULL)
1999 {
e53920b9 2000 *pLineEnd++ = '\0';
2001
2002 pCommentBegin = strstr(gErrorBuffer,"%%[");
2003 pCommentEnd = strstr(gErrorBuffer, "]%%");
09a101d6 2004 if (pCommentBegin != gErrorBuffer && pCommentEnd != NULL)
2005 {
e53920b9 2006 pCommentEnd += 3; /* Skip past "]%%" */
2007 *pCommentEnd = '\0'; /* There's always room for the nul */
2008
2009 if (strncasecmp(pCommentBegin, "%%[ Error:", 10) == 0)
2010 logLevel = "DEBUG";
2011 else if (strncasecmp(pCommentBegin, "%%[ Flushing", 12) == 0)
2012 logLevel = "DEBUG";
2013 else
2014 logLevel = "INFO";
2015
09a101d6 2016 if ((logstrlen = snprintf(logstr, sizeof(logstr), "%s: %s\n", logLevel, pCommentBegin)) >= sizeof(logstr))
2017 {
e53920b9 2018 /* If the string was trucnated make sure it has a linefeed before the nul */
2019 logstrlen = sizeof(logstr) - 1;
2020 logstr[logstrlen - 1] = '\n';
2021 }
2022 write(STDERR_FILENO, logstr, logstrlen);
ef416fc2 2023 }
ef416fc2 2024
e53920b9 2025 /* move everything over... */
2026 strcpy(gErrorBuffer, pLineEnd);
2027 gErrorBufferPtr = gErrorBuffer;
2028 pLineEnd = (char *)next_line((const char *)gErrorBuffer);
2029 }
ef416fc2 2030}
e53920b9 2031#endif /* PARSE_PS_ERRORS */
ef416fc2 2032
e53920b9 2033
2034/*
db1f069b 2035 * 'soft_reset()' - Send a soft reset to the device.
ef416fc2 2036 */
e53920b9 2037
09a101d6 2038static void soft_reset()
ef416fc2 2039{
09a101d6 2040 fd_set input_set; /* Input set for select() */
2041 struct timeval stimeout; /* Timeout for select() */
2042 char buffer[2048]; /* Buffer */
2043 struct timespec cond_timeout; /* pthread condition timeout */
e53920b9 2044
09a101d6 2045 /*
2046 * Send an abort once a second until the I/O lock is released by the main thread...
2047 */
e53920b9 2048
09a101d6 2049 pthread_mutex_lock(&g.readwrite_lock_mutex);
2050 while (g.readwrite_lock)
2051 {
2052 (*g.classdriver)->Abort(g.classdriver);
ef416fc2 2053
09a101d6 2054 cond_timeout.tv_sec = time(NULL) + 1;
2055 cond_timeout.tv_nsec = 0;
e53920b9 2056
09a101d6 2057 pthread_cond_timedwait(&g.readwrite_lock_cond, &g.readwrite_lock_mutex, &cond_timeout);
2058 }
f7deaa1a 2059
09a101d6 2060 g.readwrite_lock = 1;
2061 pthread_mutex_unlock(&g.readwrite_lock_mutex);
f7deaa1a 2062
09a101d6 2063 /*
2064 * Flush bytes waiting on print_fd...
2065 */
f7deaa1a 2066
09a101d6 2067 g.print_bytes = 0;
f7deaa1a 2068
09a101d6 2069 FD_ZERO(&input_set);
2070 FD_SET(g.print_fd, &input_set);
f7deaa1a 2071
09a101d6 2072 stimeout.tv_sec = 0;
2073 stimeout.tv_usec = 0;
f7deaa1a 2074
09a101d6 2075 while (select(g.print_fd+1, &input_set, NULL, NULL, &stimeout) > 0)
2076 if (read(g.print_fd, buffer, sizeof(buffer)) <= 0)
2077 break;
f7deaa1a 2078
09a101d6 2079 /*
2080 * Send the reset...
2081 */
f7deaa1a 2082
7dfedb92 2083 (*g.classdriver)->SoftReset(g.classdriver, DEFAULT_TIMEOUT);
f7deaa1a 2084
09a101d6 2085 /*
2086 * Release the I/O lock...
2087 */
f7deaa1a 2088
09a101d6 2089 pthread_mutex_lock(&g.readwrite_lock_mutex);
2090 g.readwrite_lock = 0;
2091 pthread_cond_signal(&g.readwrite_lock_cond);
2092 pthread_mutex_unlock(&g.readwrite_lock_mutex);
f7deaa1a 2093}
2094
f7deaa1a 2095
2096/*
09a101d6 2097 * 'get_device_id()' - Return IEEE-1284 device ID.
f7deaa1a 2098 */
f7deaa1a 2099
09a101d6 2100static void get_device_id(cups_sc_status_t *status,
2101 char *data,
2102 int *datalen)
2103{
f7deaa1a 2104 UInt32 deviceLocation = 0;
bc44d920 2105 UInt8 interfaceNum = 0;
f7deaa1a 2106 CFStringRef deviceIDString = NULL;
2107
2108 /* GetDeviceID */
bc44d920 2109 copy_devicestring(g.printer_obj, &deviceIDString, &deviceLocation, &interfaceNum);
09a101d6 2110 if (deviceIDString)
2111 {
2112 CFStringGetCString(deviceIDString, data, *datalen, kCFStringEncodingUTF8);
2113 *datalen = strlen(data);
2114 CFRelease(deviceIDString);
f7deaa1a 2115 }
09a101d6 2116 *status = CUPS_SC_STATUS_OK;
f7deaa1a 2117}
2118
f7deaa1a 2119
2120/*
b19ccc9e 2121 * End of "$Id: usb-darwin.c 7953 2008-09-17 01:43:19Z mike $".
ef416fc2 2122 */