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