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