Debian Codegraph @

src/cups/backend_common.c

raw symbols SCIP
1 /*
2 * CUPS Backend common code
3 *
4 * Copyright (c) 2007-2025 Solomon Peachy <[email protected]>
5 *
6 * The latest version of this program can be found at:
7 *
8 * https://git.shaftnet.org/gitea/slp/selphy_print.git
9 *
10 * This program is free software; you can redistribute it and/or modify it
11 * under the terms of the GNU General Public License as published by the Free
12 * Software Foundation; either version 2 of the License, or (at your option)
13 * any later version.
14 *
15 * This program is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
18 * for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, see <https://www.gnu.org/licenses/>.
22 *
23 * SPDX-License-Identifier: GPL-2.0+
24 *
25 */
26
27 #include "backend_common.h"
28 #include <errno.h>
29 #include <signal.h>
30 #include <strings.h> /* For strncasecmp */
31
32 #define BACKEND_VERSION "0.134G"
33
34 #ifndef CORRTABLE_PATH
35 #ifdef PACKAGE_DATA_DIR
36 #define CORRTABLE_PATH PACKAGE_DATA_DIR "/backend_data"
37 #else
38 #error "Must define CORRTABLE_PATH or PACKAGE_DATA_DIR!"
39 #endif
40 #endif
41
42 #define URB_XFER_SIZE (64*1024)
43 #define XFER_TIMEOUT 15000
44
45 #define USB_SUBCLASS_PRINTER 0x1
46 #define USB_INTERFACE_PROTOCOL_BIDIR 0x2
47 #define USB_INTERFACE_PROTOCOL_IPP 0x4
48
49 /* Global Variables */
50 int dyesub_debug = 0;
51 int terminate = 0;
52 int fast_return = 0;
53 int extra_vid = -1;
54 int extra_pid = -1;
55 int extra_type = -1;
56 int ncopies = 1;
57 int collate = 0;
58 int test_mode = 0;
59 int quiet = 0;
60 int stats_only = 0;
61 FILE *logger;
62
63 const char *corrtable_path = CORRTABLE_PATH;
64 static int max_xfer_size = URB_XFER_SIZE;
65 static int xfer_timeout = XFER_TIMEOUT;
66
67 #if defined(OLD_URI) && OLD_URI
68 static int old_uri = 1;
69 #else
70 static int old_uri = 0;
71 #endif
72
73 /* Support Functions */
74 int backend_claim_interface(struct libusb_device_handle *dev, int iface,
75 int num_claim_attempts)
76 {
77 int ret;
78 do {
79 ret = libusb_claim_interface(dev, iface);
80 if (!ret)
81 break;
82 if (ret != LIBUSB_ERROR_BUSY)
83 break;
84 if (--num_claim_attempts == 0)
85 break;
86 sleep(1);
87 } while (1);
88
89 if (ret)
90 ERROR("Failed to claim interface %d (%d)\n", iface, ret);
91
92 return ret;
93 }
94
95 static int lookup_printer_type(struct dyesub_backend *backend, uint16_t idVendor, uint16_t idProduct)
96 {
97 int i;
98 int type = P_UNKNOWN;
99
100 for (i = 0 ; backend->devices[i].vid ; i++) {
101 if (extra_pid != -1 &&
102 extra_vid != -1 &&
103 extra_type != -1) {
104 if (backend->devices[i].type == extra_type &&
105 extra_vid == idVendor &&
106 extra_pid == idProduct) {
107 return extra_type;
108 }
109 }
110 if (idVendor == backend->devices[i].vid &&
111 idProduct == backend->devices[i].pid) {
112 return backend->devices[i].type;
113 }
114 }
115
116 return type;
117 }
118
119 /* Interface **MUST** already be claimed! */
120 #define ID_BUF_SIZE 2048
121 char *get_device_id(struct libusb_device_handle *dev, int iface)
122 {
123 int length;
124 char *buf = malloc(ID_BUF_SIZE + 1);
125
126 if (!buf) {
127 ERROR("Memory allocation failure (%d bytes)\n", ID_BUF_SIZE+1);
128 return NULL;
129 }
130
131 if (libusb_control_transfer(dev,
132 LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_ENDPOINT_IN |
133 LIBUSB_RECIPIENT_INTERFACE,
134 0, 0,
135 (iface << 8),
136 (unsigned char *)buf, ID_BUF_SIZE, 5000) < 0)
137 {
138 *buf = '\0';
139 goto done;
140 }
141
142 /* length is the first two bytes, MSB first */
143 length = (((unsigned)buf[0] & 255) << 8) |
144 ((unsigned)buf[1] & 255);
145
146 /* Sanity checks */
147 if (length > ID_BUF_SIZE || length < 14)
148 length = (((unsigned)buf[1] & 255) << 8) |
149 ((unsigned)buf[0] & 255);
150
151 if (length > ID_BUF_SIZE)
152 length = ID_BUF_SIZE;
153
154 if (length < 14) {
155 *buf = '\0';
156 goto done;
157 }
158
159 /* IEEE1284 length field includs the header! */
160 length -= 2;
161
162 /* Move, and terminate */
163 memmove(buf, buf + 2, length);
164 buf[length] = '\0';
165
166 done:
167 return buf;
168 }
169
170 /* Used with the IEEE1284 deviceid string parsing */
171 int parse1284_data(const char *device_id, struct deviceid_dict* dict)
172 {
173 char *ptr;
174 char key[256];
175 char val[256];
176 int num = 0;
177
178 if (!device_id)
179 return CUPS_BACKEND_OK;
180
181 //[whitespace]key[whitespace]:[whitespace]value[whitespace];
182 while (*device_id && num < MAX_DICT) {
183 /* Skip leading spaces */
184 if (*device_id == ' ')
185 device_id++;
186 if (!*device_id)
187 break;
188
189 /* Work out key */
190 for (ptr = key; *device_id && *device_id != ':'; device_id++)
191 *ptr++ = *device_id;
192 if (!*device_id)
193 break;
194 while (ptr > key && *(ptr-1) == ' ')
195 ptr--;
196 *ptr = 0;
197 device_id++;
198 if (!*device_id)
199 break;
200
201 /* Next up, value */
202 for (ptr = val; *device_id && *device_id != ';'; device_id++)
203 *ptr++ = *device_id;
204 while (ptr > val && *(ptr-1) == ' ')
205 ptr--;
206 *ptr = 0;
207 device_id++;
208
209 if (!strlen(key) || !strlen(val))
210 continue;
211
212 /* Add it to the dictionary */
213 dict[num].key = strdup(key);
214 dict[num].val = strdup(val);
215 num++;
216
217 if (!*device_id)
218 break;
219 }
220 return num;
221 }
222
223 char *dict_find(const char *key, int dlen, struct deviceid_dict* dict)
224 {
225 while(dlen) {
226 if (!strcmp(key, dict->key))
227 return dict->val;
228 dlen--;
229 dict++;
230 }
231 return NULL;
232 }
233
234 /* I/O functions */
235
236 int read_data(struct dyesub_connection *conn, uint8_t *buf, int buflen, int *readlen)
237 {
238 int ret;
239
240 /* Clear buffer */
241 memset(buf, 0, buflen);
242
243 ret = libusb_bulk_transfer(conn->dev, conn->endp_up,
244 buf,
245 buflen,
246 readlen,
247 xfer_timeout);
248
249 if (ret < 0) {
250 ERROR("Failure to receive data from printer (libusb error %d: (%d/%d from 0x%02x))\n", ret, *readlen, buflen, conn->endp_up);
251 goto done;
252 }
253
254 if (dyesub_debug) {
255 DEBUG("Received %d bytes from printer\n", *readlen);
256 }
257
258 if ((dyesub_debug > 1 && *readlen < 4096) ||
259 dyesub_debug > 2) {
260 int i = *readlen;
261
262 DEBUG("<- ");
263 while(i > 0) {
264 if ((*readlen-i) != 0 &&
265 (*readlen-i) % 16 == 0) {
266 DEBUG2("\n");
267 DEBUG(" ");
268 }
269 DEBUG2("%02x ", buf[*readlen-i]);
270 i--;
271 }
272 DEBUG2("\n");
273 }
274
275 done:
276 return ret;
277 }
278
279 int send_data(struct dyesub_connection *conn, const uint8_t *buf, int len)
280 {
281 int num = 0;
282
283 if (dyesub_debug) {
284 DEBUG("Sending %d bytes to printer\n", len);
285 }
286
287 while (len) {
288 int len2 = (len > max_xfer_size) ? max_xfer_size: len;
289
290 if ((dyesub_debug > 1 && len2 < 4096) ||
291 dyesub_debug > 2) {
292 int i = len2;
293
294 DEBUG("-> ");
295 while(i > 0) {
296 if ((len2-i) != 0 &&
297 (len2-i) % 16 == 0) {
298 DEBUG2("\n");
299 DEBUG(" ");
300 }
301 DEBUG2("%02x ", buf[len2-i]);
302 i--;
303 }
304 DEBUG2("\n");
305 }
306
307 int ret = libusb_bulk_transfer(conn->dev, conn->endp_down,
308 (uint8_t*) buf, len2,
309 &num, xfer_timeout);
310
311 if (ret < 0) {
312 ERROR("Failure to send data to printer (libusb error %d: (%d/%d to 0x%02x))\n", ret, num, len2, conn->endp_down);
313 return ret;
314 }
315 len -= num;
316 buf += num;
317 }
318
319 return CUPS_BACKEND_OK;
320 }
321
322 /* More stuff */
323 #ifndef _WIN32
324 static void sigterm_handler(int signum) {
325 UNUSED(signum);
326
327 terminate = 1;
328 INFO("Job Cancelled");
329 }
330 #endif
331
332 static char *sanitize_string(char *str) {
333 int len = strlen(str);
334
335 while(len && (str[len-1] <= 0x20)) {
336 str[len-1] = 0;
337 len--;
338 }
339 return str;
340 }
341
342 /*
343
344 These functions are Public Domain code obtained from:
345
346 https://www.geekhideout.com/urlcode.shtml
347
348 */
349 #include <ctype.h> /* for isalnum() */
350 static char to_hex(char code) {
351 static const char hex[] = "0123456789abcdef";
352 return hex[code & 15];
353 }
354 static char from_hex(char ch) {
355 return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;
356 }
357 /* Note -- caller must free returned pointer! */
358 static char *url_encode(const char *str) {
359 const char *pstr = str;
360 char *buf = malloc(strlen(str) * 3 + 1);
361 char *pbuf = buf;
362
363 if (!buf) {
364 ERROR("Memory allocation failure (%d bytes)\n", (int) strlen(str)*3 + 1);
365 return NULL;
366 }
367
368 while (*pstr) {
369 if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~')
370 *pbuf++ = *pstr;
371 else if (*pstr == ' ')
372 *pbuf++ = '+';
373 else
374 *pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
375 pstr++;
376 }
377 *pbuf = '\0';
378 return buf;
379 }
380 static char *url_decode(char *str) {
381 char *pstr = str, *buf = malloc(strlen(str) + 1), *pbuf = buf;
382
383 if (!buf) {
384 ERROR("Memory allocation failure (%d bytes)\n", (int) strlen(str) + 1);
385 return NULL;
386 }
387
388 while (*pstr) {
389 if (*pstr == '%') {
390 if (pstr[1] && pstr[2]) {
391 *pbuf++ = from_hex(pstr[1]) << 4 | from_hex(pstr[2]);
392 pstr += 2;
393 }
394 } else if (*pstr == '+') {
395 *pbuf++ = ' ';
396 } else {
397 *pbuf++ = *pstr;
398 }
399 pstr++;
400 }
401 *pbuf = '\0';
402 return buf;
403 }
404
405 /* And now back to our regularly-scheduled programming */
406
407 static int probe_device(struct libusb_device *device,
408 struct libusb_device_descriptor *desc,
409 const char *make,
410 const char *uri_prefix, const char *manuf_override,
411 int found, int num_claim_attempts,
412 int scan_only, const char *match_serno,
413 struct dyesub_connection *conn,
414 struct dyesub_backend *backend)
415 {
416 struct libusb_device_handle *dev;
417 char buf[256];
418 char *product = NULL, *serial = NULL, *manuf = NULL, *descr = NULL;
419 uint8_t iface, altset;
420 struct libusb_config_descriptor *config = NULL;
421 int dlen = 0;
422 struct deviceid_dict dict[MAX_DICT];
423 char *ieee_id = NULL;
424 int i;
425 uint8_t endp_up, endp_down;
426
427 DEBUG("Probing VID: %04X PID: %04x\n", desc->idVendor, desc->idProduct);
428
429 if ((i = libusb_open(device, &dev))) {
430 #ifdef _WIN32
431 if (i == LIBUSB_ERROR_NOT_SUPPORTED)
432 ERROR("Could not open device %04x:%04x! (Genric USB driver missing, See README)\n", desc->idVendor, desc->idProduct);
433 else
434 #endif
435 ERROR("Could not open device %04x:%04x - %d (need to be root?)\n", desc->idVendor, desc->idProduct, i);
436 found = -1;
437 goto abort;
438 }
439
440 #if 0
441 /* XXX FIXME: Iterate through bNumConfigurations */
442
443 /* Force reset of device configuration */
444 {
445 int cfgnum = -1;
446 if (libusb_get_configuration(dev, &cfgnum)) {
447 ERROR("Can't get config!");
448 }
449 INFO("Config %d\n", config);
450 if (config < 1)
451 cfgnum = 1;
452 if (libusb_set_configuration(dev, cfgnum)) {
453 ERROR("Can't set config\n");
454 }
455 }
456 #endif
457
458 /* Get descriptor for active configuration */
459 if (libusb_get_active_config_descriptor(device, &config)) {
460 found = -1;
461 goto abort_close;
462 }
463
464 /* Loop through all interfaces and altsettings to find candidates */
465 for (iface = 0 ; iface < config->bNumInterfaces ; iface ++) {
466 for (altset = 0 ; altset < config->interface[iface].num_altsetting ; altset++) {
467 /* Skip interfaces that don't have enough endpoints */
468 if (config->interface[iface].altsetting[altset].bNumEndpoints < 2) {
469 continue;
470 }
471
472 /* Note we actually only match on explicit VID+PIDs so there's no need to filter based
473 on specific class/type */
474
475 /* Explicitly exclude IPP-over-USB interfaces */
476 if (desc->bDeviceClass == LIBUSB_CLASS_PER_INTERFACE &&
477 config->interface[iface].altsetting[altset].bInterfaceClass == LIBUSB_CLASS_PRINTER &&
478 config->interface[iface].altsetting[altset].bInterfaceSubClass == USB_SUBCLASS_PRINTER &&
479 config->interface[iface].altsetting[altset].bInterfaceProtocol == USB_INTERFACE_PROTOCOL_IPP) {
480 continue;
481 }
482
483 /* Find the first set of endpoints! */
484 endp_up = endp_down = 0;
485 for (i = 0 ; i < config->interface[iface].altsetting[altset].bNumEndpoints ; i++) {
486 if ((config->interface[iface].altsetting[altset].endpoint[i].bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) == LIBUSB_TRANSFER_TYPE_BULK) {
487 if (config->interface[iface].altsetting[altset].endpoint[i].bEndpointAddress & LIBUSB_ENDPOINT_IN)
488 endp_up = config->interface[iface].altsetting[altset].endpoint[i].bEndpointAddress;
489 else
490 endp_down = config->interface[iface].altsetting[altset].endpoint[i].bEndpointAddress;
491 }
492 if (endp_up && endp_down)
493 goto candidate;
494 }
495 }
496 }
497
498 /* If we got here, we didn't find a match. */
499 found = -1;
500 goto abort_close;
501
502 candidate:
503
504 /* We've now found an interface/altset we need to query in more detail */
505 /* Detach the kernel driver */
506 if (libusb_kernel_driver_active(dev, iface))
507 libusb_detach_kernel_driver(dev, iface);
508
509 /* Claim the interface so we can start querying things! */
510 if (backend_claim_interface(dev, iface, num_claim_attempts)) {
511 found = -1;
512 goto abort_release;
513 }
514
515 /* Use the appropriate altesetting, but only if the
516 printer supports more than one. Some printers don't like
517 us unconditionally setting this. */
518 if (config->interface[iface].num_altsetting > 1) {
519 if (libusb_set_interface_alt_setting(dev, iface, altset)) {
520 ERROR("Failed to set alternative interface %d/%d\n", iface, altset);
521 found = -1;
522 goto abort_release;
523 }
524 }
525
526 /* Query IEEE1284 info only if it's a PRINTER class */
527 if (desc->bDeviceClass == LIBUSB_CLASS_PRINTER ||
528 (desc->bDeviceClass == LIBUSB_CLASS_PER_INTERFACE &&
529 config->interface[iface].altsetting[altset].bInterfaceClass == LIBUSB_CLASS_PRINTER &&
530 config->interface[iface].altsetting[altset].bInterfaceSubClass == USB_SUBCLASS_PRINTER)) {
531 ieee_id = get_device_id(dev, iface);
532 dlen = parse1284_data(ieee_id, dict);
533 }
534
535 if (!old_uri && !scan_only && !dyesub_debug) goto skip_manuf_model;
536
537 /* Look up mfg string in IEEE1284 data */
538 if (manuf_override && strlen(manuf_override)) {
539 manuf = url_encode(manuf_override);
540 } else if ((manuf = dict_find("MANUFACTURER", dlen, dict))) {
541 manuf = url_encode(manuf);
542 } else if ((manuf = dict_find("MFG", dlen, dict))) {
543 manuf = url_encode(manuf);
544 } else if ((manuf = dict_find("MFR", dlen, dict))) {
545 manuf = url_encode(manuf);
546 }
547
548 /* If no manufacturer string, fall back to USB iManufacturer */
549 if ((!manuf || !strlen(manuf)) &&
550 desc->iManufacturer) {
551 buf[0] = 0;
552 libusb_get_string_descriptor_ascii(dev, desc->iManufacturer, (unsigned char*)buf, STR_LEN_MAX);
553 sanitize_string(buf);
554 manuf = url_encode(buf);
555 }
556
557 if (!manuf || !strlen(manuf)) { /* Last-ditch */
558 if (manuf) free(manuf);
559 WARNING("**** THIS PRINTER DOES NOT REPORT A VALID MANUFACTURER STRING!\n");
560 manuf = url_encode("Unknown"); // XXX use USB VID?
561 }
562
563 /* Look up model string in IEEE1284 data */
564 if ((product = dict_find("MODEL", dlen, dict))) {
565 product = url_encode(product);
566 } else if ((product = dict_find("MDL", dlen, dict))) {
567 product = url_encode(product);
568 }
569
570 /* If no manufacturer string, fall back to USB iProduct */
571 if ((!product || !strlen(product)) &&
572 desc->iProduct) {
573 buf[0] = 0;
574 libusb_get_string_descriptor_ascii(dev, desc->iProduct, (unsigned char*)buf, STR_LEN_MAX);
575 sanitize_string(buf);
576 product = url_encode(buf);
577 }
578
579 if (!product || !strlen(product)) { /* Last-ditch */
580 if (!product) free(product);
581 WARNING("**** THIS PRINTER DOES NOT REPORT A VALID MODEL STRING!\n");
582 product = url_encode("Unknown"); // XXX Use USB PID?
583 }
584
585 /* Look up decription string in IEEE1284 data */
586 if ((descr = dict_find("DESCRIPTION", dlen, dict))) {
587 descr = strdup(descr);
588 } else if ((descr = dict_find("DES", dlen, dict))) {
589 descr = strdup(descr);
590 }
591
592 if (!descr || !strlen(descr)) { /* Last-ditch, generate */
593 char *product2 = url_decode(product);
594 char *manuf3 = url_decode(manuf);
595 descr = malloc(514); /* 256 + 256 + 1 + 1 */
596 if (!descr) {
597 ERROR("Memory allocation failure (%d bytes)\n", 514);
598 if (manuf3)
599 free(manuf3);
600 if (product2)
601 free(product2);
602 return -1;
603 }
604
605 snprintf(descr, 514, "%s %s", manuf3, product2);
606 free(product2);
607 free(manuf3);
608 }
609
610 skip_manuf_model:
611
612 /* Prefer IEEE1284-reported serial number */
613 if ((serial = dict_find("SERIALNUMBER", dlen, dict))) {
614 serial = url_encode(serial);
615 } else if ((serial = dict_find("SN", dlen, dict))) {
616 serial = url_encode(serial);
617 } else if ((serial = dict_find("SER", dlen, dict))) {
618 serial = url_encode(serial);
619 } else if ((serial = dict_find("SERN", dlen, dict))) {
620 serial = url_encode(serial);
621 }
622
623 /* If it's not valid, fall back to USB iSerial */
624 if ((!serial || !strlen(serial)) &&
625 !(backend->flags & BACKEND_FLAG_BADISERIAL) &&
626 desc->iSerialNumber) {
627 libusb_get_string_descriptor_ascii(dev, desc->iSerialNumber, (unsigned char*)buf, STR_LEN_MAX);
628 sanitize_string(buf);
629 serial = url_encode(buf);
630 }
631
632 /* TODO: What about situations where iSerial does not match IEEE1284?
633 Or if the '1284 data is bogus? */
634
635 /* If still no serial, fall back to backend hook */
636 if ((!serial || !strlen(serial)) &&
637 backend->query_serno) { /* Get from backend hook */
638 struct dyesub_connection c2;
639 c2.dev = dev;
640 c2.iface = iface;
641 c2.altset = altset;
642 c2.endp_up = endp_up;
643 c2.endp_down = endp_down;
644 c2.type = lookup_printer_type(backend,
645 desc->idVendor, desc->idProduct);
646 backend->query_serno(&c2, buf, STR_LEN_MAX);
647 serial = url_encode(buf);
648 }
649
650 /* Last-ditch serial number fallback */
651 if (!serial || !strlen(serial)) {
652 if (serial) free(serial);
653 WARNING("**** THIS PRINTER DOES NOT REPORT A SERIAL NUMBER!\n");
654 WARNING("**** If you intend to use multiple printers of this type, you\n");
655 WARNING("**** must only plug one in at a time or unexpected behavior will occur!\n");
656 serial = strdup("NONE_UNKNOWN");
657 }
658
659 if (scan_only) {
660 if (!old_uri) {
661 fprintf(stdout, "direct %s://%s/%s \"%s\" \"%s\" \"%s\" \"\"\n",
662 uri_prefix, make, serial,
663 descr, descr,
664 ieee_id ? ieee_id : "");
665 } else {
666 int k = 0;
667
668 /* URLify the manuf and model strings */
669 strncpy(buf, manuf, sizeof(buf) - 2);
670 k = strlen(buf);
671 buf[k++] = '/';
672 buf[k] = 0;
673
674 strncpy(buf + k, product, sizeof(buf)-k);
675
676 fprintf(stdout, "direct %s://%s?serial=%s&backend=%s \"%s\" \"%s\" \"%s\" \"\"\n",
677 uri_prefix, buf, serial, make,
678 descr, descr,
679 ieee_id? ieee_id : "");
680 }
681 }
682
683 /* If a serial number was passed down, use it. */
684 if (match_serno && strcmp(match_serno, (char*)serial)) {
685 found = -1;
686 }
687
688 uint8_t bus_num = libusb_get_bus_number(device);
689 uint8_t port_num = libusb_get_port_number(device);
690
691 if (dyesub_debug)
692 DEBUG("VID/PID %04X/%04X @ bus/port %03d/%03d Manuf: '%s' Product: '%s' Serial: '%s' found: %d\n",
693 desc->idVendor, desc->idProduct, bus_num, port_num, manuf, product, serial, found);
694
695 if (found != -1 && conn) {
696 conn->iface = iface;
697 conn->altset = altset;
698 conn->endp_up = endp_up;
699 conn->endp_down = endp_down;
700 conn->bus_num = bus_num;
701 conn->port_num = port_num;
702 }
703
704 /* Free things up */
705 if(serial) free(serial);
706 if(manuf) free(manuf);
707 if(product) free(product);
708 if(descr) free(descr);
709 if(ieee_id) free(ieee_id);
710
711 abort_release:
712
713 libusb_release_interface(dev, iface);
714
715 abort_close:
716
717 libusb_close(dev);
718
719 abort:
720 if (config) libusb_free_config_descriptor(config);
721
722 /* Clean up the dictionary */
723 while (dlen--) {
724 free (dict[dlen].key);
725 free (dict[dlen].val);
726 }
727
728 return found;
729 }
730
731 void generic_teardown(void *vctx)
732 {
733 if (!vctx)
734 return;
735
736 free(vctx);
737 }
738
739 extern struct dyesub_backend sonyupd_backend;
740 extern struct dyesub_backend sonyupdneo_backend;
741 extern struct dyesub_backend kodak6800_backend;
742 extern struct dyesub_backend kodak605_backend;
743 extern struct dyesub_backend kodak1400_backend;
744 extern struct dyesub_backend kodak8800_backend;
745 extern struct dyesub_backend shinkos1245_backend;
746 extern struct dyesub_backend shinkos2145_backend;
747 extern struct dyesub_backend shinkos6145_backend;
748 extern struct dyesub_backend shinkos6245_backend;
749 extern struct dyesub_backend canonselphy_backend;
750 extern struct dyesub_backend canonselphyneo_backend;
751 extern struct dyesub_backend mitsu70x_backend;
752 extern struct dyesub_backend mitsu9550_backend;
753 extern struct dyesub_backend mitsup95d_backend;
754 extern struct dyesub_backend dnpds40_backend;
755 extern struct dyesub_backend magicard_backend;
756 extern struct dyesub_backend mitsud90_backend;
757 extern struct dyesub_backend hiti_backend;
758
759 static struct dyesub_backend *backends[] = {
760 &canonselphy_backend,
761 &canonselphyneo_backend,
762 &kodak6800_backend,
763 &kodak605_backend,
764 &kodak1400_backend,
765 &kodak8800_backend,
766 &shinkos1245_backend,
767 &shinkos2145_backend,
768 &shinkos6145_backend,
769 &shinkos6245_backend,
770 &sonyupd_backend,
771 &sonyupdneo_backend,
772 &mitsu70x_backend,
773 &mitsud90_backend,
774 &mitsu9550_backend,
775 &mitsup95d_backend,
776 &dnpds40_backend,
777 &magicard_backend,
778 &hiti_backend,
779 NULL,
780 };
781
782 static int find_and_enumerate(const char *argv0,
783 struct libusb_device ***list,
784 const struct dyesub_backend *backend,
785 const char *match_serno,
786 const char *make,
787 int scan_only, int num_claim_attempts,
788 struct dyesub_connection *conn)
789 {
790 int num;
791 int i, j = 0, k;
792 int found = -1;
793
794 if (test_mode >= TEST_MODE_NOATTACH && conn) {
795 found = 1;
796 conn->endp_up = 0x82;
797 conn->endp_down = 0x01;
798 conn->iface = 0;
799 conn->altset = 0;
800 return found;
801 }
802
803 STATE("+org.gutenprint.searching-for-device\n");
804
805 /* Enumerate and find suitable device */
806 num = libusb_get_device_list(NULL, list);
807
808 /* See if we can actually match on the supplied make! */
809 if (backend && make) {
810 int match = 0;
811 for (j = 0 ; backend->devices[j].vid ; j++) {
812 if (!strcmp(make,backend->devices[j].make)) {
813 match = 1;
814 break;
815 }
816 }
817 /* If not, clear it */
818 if (!match)
819 make = NULL;
820 } else {
821 make = NULL; /* Explicitly clear it */
822 }
823
824 for (i = 0 ; i < num ; i++) {
825 const char *foundmake = NULL;
826
827 struct libusb_device_descriptor desc;
828 libusb_get_device_descriptor((*list)[i], &desc);
829
830 for (k = 0 ; backends[k] ; k++) {
831 if (backend && backend != backends[k])
832 continue;
833
834 for (j = 0 ; backends[k]->devices[j].vid ; j++) {
835 /* Try for extra pid/vid/type */
836 // XXX nuke entire extra_??? concept?
837 if (extra_pid != -1 &&
838 extra_vid != -1 &&
839 extra_type != -1) {
840 if (backends[k]->devices[j].type == extra_type &&
841 extra_vid == desc.idVendor &&
842 extra_pid == desc.idProduct) {
843 found = i;
844 make = backends[k]->uri_prefixes[0];
845 goto match;
846 }
847 }
848
849 /* Match based on VID/PID (and prefix, if specified) */
850 if (desc.idVendor == backends[k]->devices[j].vid &&
851 (desc.idProduct == backends[k]->devices[j].pid ||
852 desc.idProduct == 0xffff) &&
853 (!make || !strcmp(make,backends[k]->devices[j].make))) {
854 found = i;
855 foundmake = backends[k]->devices[j].make;
856 goto match;
857 }
858 }
859 }
860
861 continue;
862
863 match:
864 found = probe_device((*list)[i], &desc, (foundmake ? foundmake : make),
865 argv0, backends[k]->devices[j].manuf_str,
866 found, num_claim_attempts,
867 scan_only, match_serno,
868 conn,
869 backends[k]);
870 foundmake = NULL;
871 if (found != -1 && !scan_only)
872 break;
873 }
874
875 STATE("-org.gutenprint.searching-for-device\n");
876 return found;
877 }
878
879 static struct dyesub_backend *find_backend(const char *uri_prefix)
880 {
881 int i;
882
883 if (!uri_prefix)
884 return NULL;
885
886 for (i = 0; ; i++) {
887 struct dyesub_backend *backend = backends[i];
888 const char **alias;
889 int j;
890 if (!backend)
891 return NULL;
892 for (alias = backend->uri_prefixes ; alias && *alias ; alias++) {
893 if (!strcmp(uri_prefix, *alias))
894 return backend;
895 }
896 for (j = 0 ; backend->devices[j].vid ; j++) {
897 if (!strcmp(uri_prefix,backend->devices[j].make)) {
898 return backend;
899 }
900 }
901 }
902 return NULL;
903 }
904
905 static int query_markers(const struct dyesub_backend *backend, void *ctx, int full)
906 {
907 struct marker *markers = NULL;
908 int marker_count = 0;
909 int ret;
910
911 if (!backend->query_markers)
912 return CUPS_BACKEND_OK;
913
914 if (test_mode >= TEST_MODE_NOATTACH)
915 return CUPS_BACKEND_OK;
916
917 ret = backend->query_markers(ctx, &markers, &marker_count);
918 if (ret)
919 return ret;
920
921 dump_markers(markers, marker_count, full);
922
923 return CUPS_BACKEND_OK;
924 }
925
926 static void dump_stats(struct dyesub_backend *backend, struct printerstats *stats, int json)
927 {
928 int i;
929 struct tm *tm;
930 char tmbuf[64];
931 tm = localtime(&stats->timestamp);
932
933 strftime(tmbuf, sizeof(tmbuf), "%Y-%m-%d %H:%M:%S", tm);
934
935 if (json) {
936 fprintf(stdout, "{\n");
937 fprintf(stdout, "\t\"backend\": \"%s\",\n", backend->name);
938 fprintf(stdout, "\t\"version\": \"%s / %s\",\n", BACKEND_VERSION, backend->version);
939 fprintf(stdout, "\t\"timestamp\": \"%s\",\n", tmbuf);
940 if (stats->mfg)
941 fprintf(stdout, "\t\"manufacturer\": \"%s\",\n", stats->mfg);
942 if (stats->model)
943 fprintf(stdout, "\t\"model\": \"%s\",\n", stats->model);
944 if (stats->serial)
945 fprintf(stdout, "\t\"serial\": \"%s\",\n", stats->serial);
946 if (stats->fwver)
947 fprintf(stdout, "\t\"firmware\": \"%s\",\n", stats->fwver);
948
949 fprintf(stdout, "\t\"decks\": {\n");
950 for (i = 0 ; i < stats->decks ; i++) {
951 fprintf(stdout, "\t\t\"%s\": {\n", stats->name[i]);
952 if (stats->status[i])
953 fprintf(stdout, "\t\t\t\"status\": \"%s\",\n", stats->status[i]);
954 fprintf(stdout, "\t\t\t\"mediatype\": \"%s\",\n", stats->mediatype[i]);
955 switch (stats->levelnow[i]) {
956 case CUPS_MARKER_UNKNOWN:
957 fprintf(stdout, "\t\t\t\"medialevel\": \"Unknown\",\n");
958 break;
959 case CUPS_MARKER_UNAVAILABLE:
960 fprintf(stdout, "\t\t\t\"medialevel\": \"Unavailable\",\n");
961 break;
962 case CUPS_MARKER_UNKNOWN_OK:
963 fprintf(stdout, "\t\t\t\"medialevel\": \"OK\",\n");
964 break;
965 default:
966 if (stats->levelnow[i] >= 0 && stats->levelmax[i] > 0) {
967 fprintf(stdout, "\t\t\t\"medialevel\": \"OK\",\n");
968 fprintf(stdout, "\t\t\t\"medialevelnow\": %d,\n", stats->levelnow[i]);
969 fprintf(stdout, "\t\t\t\"medialevelmax\": %d,\n", stats->levelmax[i]);
970 } else {
971 fprintf(stdout, "\t\t\t\"medialevel\": \"Illegal value\",\n");
972 }
973 break;
974 }
975 fprintf(stdout, "\t\t\t\"counters\": {\n");
976 if (stats->cnt_life[i] >= 0)
977 fprintf(stdout, "\t\t\t\t\"lifetime\": %d\n", stats->cnt_life[i]);
978
979 fprintf(stdout, "\t\t\t}\n");
980
981 fprintf(stdout, "\t\t}%c\n", (i < (stats->decks -1) ? ',': ' '));
982 }
983 fprintf(stdout, "\t}\n");
984 fprintf(stdout, "}\n");
985 } else {
986 fprintf(stdout, "Backend: %s\n", backend->name);
987 fprintf(stdout, "Version: %s / %s\n", BACKEND_VERSION, backend->version);
988 fprintf(stdout, "Timestamp: %s\n", tmbuf);
989 if (stats->mfg)
990 fprintf(stdout, "Manufacturer: %s\n", stats->mfg);
991 if (stats->model)
992 fprintf(stdout, "Model: %s\n", stats->model);
993 if (stats->serial)
994 fprintf(stdout, "Serial Number: %s\n", stats->serial);
995 if (stats->fwver)
996 fprintf(stdout, "Firmware Version: %s\n", stats->fwver);
997
998 for (i = 0 ; i < stats->decks ; i++) {
999 if (stats->status[i])
1000 fprintf(stdout, "%s Status: %s\n", stats->name[i], stats->status[i]);
1001 if (stats->cnt_life[i] >= 0)
1002 fprintf(stdout, "%s Lifetime Prints: %d\n", stats->name[i], stats->cnt_life[i]);
1003 fprintf(stdout, "%s Media Type: %s\n", stats->name[i], stats->mediatype[i]);
1004 if (stats->levelnow[i] == CUPS_MARKER_UNKNOWN_OK)
1005 fprintf(stdout, "%s Media Level: OK\n", stats->name[i]);
1006 else if (stats->levelnow[i] == CUPS_MARKER_UNKNOWN)
1007 fprintf(stdout, "%s Media Level: Unknown\n", stats->name[i]);
1008 else if (stats->levelnow[i] == CUPS_MARKER_UNAVAILABLE)
1009 fprintf(stdout, "%s Media Level: Unavailable\n", stats->name[i]);
1010 else if (stats->levelnow[i] >= 0 && stats->levelmax[i] > 0)
1011 fprintf(stdout, "%s Media Level: %d / %d\n", stats->name[i], stats->levelnow[i], stats->levelmax[i]);
1012 }
1013 }
1014 }
1015
1016 void print_license_blurb(void)
1017 {
1018 const char *license = "\n\
1019 Copyright 2007-2026 Solomon Peachy <pizza AT shaftnet DOT org>\n\
1020 \n\
1021 This program is free software; you can redistribute it and/or modify it\n\
1022 under the terms of the GNU General Public License as published by the Free\n\
1023 Software Foundation; either version 2 of the License, or (at your option)\n\
1024 any later version.\n\
1025 \n\
1026 This program is distributed in the hope that it will be useful, but\n\
1027 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n\
1028 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n\
1029 for more details.\n\
1030 \n\
1031 You should have received a copy of the GNU General Public License\n\
1032 along with this program; if not, see <https://www.gnu.org/licenses/>.\n\n";
1033
1034 fprintf(logger, "%s", license);
1035 }
1036
1037 void print_help(const char *argv0, const struct dyesub_backend *backend)
1038 {
1039 struct libusb_device **list = NULL;
1040
1041 const char *ptr = getenv("BACKEND");
1042 if (!ptr)
1043 ptr = getenv("DYESUB_BACKEND");
1044 if (!ptr)
1045 ptr = argv0;
1046
1047 if (!backend)
1048 backend = find_backend(ptr);
1049
1050 if (!backend) {
1051 int i;
1052 DEBUG("Environment variables:\n");
1053 DEBUG(" DYESUB_DEBUG EXTRA_PID EXTRA_VID EXTRA_TYPE BACKEND SERIAL OLD_URI_SCHEME BACKEND_QUIET\n");
1054 DEBUG("CUPS Usage:\n");
1055 DEBUG("\tDEVICE_URI=someuri %s job user title num-copies options [ filename ]\n", ptr);
1056 DEBUG("\n");
1057 DEBUG("Standalone Usage:\n");
1058 DEBUG("\t%s\n", ptr);
1059 DEBUG(" [ -D ] [ -G ] [ -f ] [ -v ]\n");
1060 DEBUG(" [ backend_specific_args ] \n");
1061 DEBUG(" [ -d copies ] \n");
1062 DEBUG(" [ - | infile ] \n");
1063 for (i = 0; ; i++) {
1064 const char **alias;
1065
1066 backend = backends[i];
1067 if (!backend)
1068 break;
1069 DEBUG("\t# %s version %s\n",
1070 backend->name, backend->version);
1071 DEBUG(" BACKEND=");
1072 for (alias = backend->uri_prefixes ; alias && *alias ; alias++)
1073 DEBUG2("%s ", *alias);
1074 DEBUG2("\n");
1075
1076 if (backend->cmdline_usage)
1077 backend->cmdline_usage();
1078 }
1079 } else {
1080 const char **alias;
1081 int j;
1082 DEBUG("Standalone %s backend version %s\n",
1083 backend->name, backend->version);
1084 DEBUG("\t supporting: ");
1085 for (alias = backend->uri_prefixes ; alias && *alias ; alias++)
1086 DEBUG2("%s ", *alias);
1087 for (j = 0 ; backend->devices[j].vid ; j++)
1088 DEBUG2("%s ", backend->devices[j].make);
1089 DEBUG2("\n");
1090
1091 DEBUG("\t[ -D ] [ -G ] [ -f ]\n");
1092 if (backend->cmdline_usage)
1093 backend->cmdline_usage();
1094 DEBUG("\t[ -d copies ] [ infile | - ]\n");
1095 }
1096
1097 /* Scan for all printers for the specified backend */
1098 find_and_enumerate(argv0, &list, backend, NULL, ptr, 1, 1, NULL);
1099 libusb_free_device_list(list, 1);
1100 }
1101
1102 static int parse_cmdstream(const struct dyesub_backend *backend, void *backend_ctx, int fd)
1103 {
1104 FILE *fp = stdin;
1105 char line[128];
1106 char *lp;
1107
1108 if (fd != fileno(stdin)) {
1109 fp = fdopen(fd, "r");
1110 if (!fp) {
1111 ERROR("Can't open data stream!\n");
1112 return CUPS_BACKEND_FAILED;
1113 }
1114 }
1115 while (fgets(line, sizeof(line), fp) != NULL) {
1116 /* Strip trailing newline */
1117 lp = line + strlen(line) - 1;
1118 if (*lp == '\n')
1119 *lp = '\0';
1120 /* And leading spaces */
1121 for (lp = line; isspace(*lp); lp++);
1122 /* And comments and blank lines */
1123 if (*lp == '#' || !*lp)
1124 continue;
1125
1126 /* Parse command! */
1127 if (strncasecmp(lp, "ReportLevels", 12) == 0) {
1128 query_markers(backend, backend_ctx, 1);
1129 /* XXX TODO: ReportStatus, AutoConfigure, PrintSelfTestPage? What about others, eg reset or cancel job? */
1130 } else {
1131 WARNING("Invalid printer command \"%s\"!\n", lp);
1132 }
1133 }
1134
1135 /* Clean up */
1136 if (fp != stdin)
1137 fclose(fp);
1138
1139 return CUPS_BACKEND_OK;
1140 }
1141
1142 static int handle_input(struct dyesub_backend *backend, void *backend_ctx,
1143 const char *fname, const char *uri, const char *type)
1144 {
1145 int ret = CUPS_BACKEND_OK;
1146 int i;
1147 const void *jobs[MAX_JOBS_FROM_READ_PARSE];
1148 int data_fd = fileno(stdin);
1149 int read_page = 0, print_page = 0;
1150 struct dyesub_joblist *jlist = NULL;
1151
1152 if (!fname) {
1153 if (uri && strlen(uri))
1154 ERROR("ERROR: No input file specified\n");
1155 ret = CUPS_BACKEND_FAILED;
1156 goto done;
1157 }
1158
1159 if (ncopies < 1) {
1160 ERROR("ERROR: need to have at least 1 copy!\n");
1161 ret = CUPS_BACKEND_FAILED;
1162 goto done;
1163 }
1164
1165 /* Open file if not STDIN */
1166 if (strcmp("-", fname)) {
1167 data_fd = open(fname, O_RDONLY);
1168 if (data_fd < 0) {
1169 perror("ERROR:Can't open input file");
1170 ret = CUPS_BACKEND_FAILED;
1171 goto done;
1172 }
1173 }
1174
1175 #ifndef _WIN32
1176 /* Ensure we're using BLOCKING I/O */
1177 i = fcntl(data_fd, F_GETFL, 0);
1178 if (i < 0) {
1179 perror("ERROR:Can't open input");
1180 ret = CUPS_BACKEND_FAILED;
1181 goto done;
1182 }
1183 i &= ~O_NONBLOCK;
1184 i = fcntl(data_fd, F_SETFL, i);
1185 if (i < 0) {
1186 perror("ERROR:Can't open input");
1187 ret = CUPS_BACKEND_FAILED;
1188 goto done;
1189 }
1190
1191 /* Ignore SIGPIPE */
1192 signal(SIGPIPE, SIG_IGN);
1193 signal(SIGTERM, sigterm_handler);
1194 #endif
1195
1196 /* See if it's a CUPS command stream, and if yes, handle it! */
1197 if (type && !strcmp("application/vnd.cups-command", type))
1198 {
1199 INFO("CUPS Command mode\n");
1200 ret = parse_cmdstream(backend, backend_ctx, data_fd);
1201 goto done;
1202 }
1203
1204 /* Time for the main processing loop */
1205 INFO("Printing started\n");
1206
1207 /* Emit a verbose marker dump */
1208 ret = query_markers(backend, backend_ctx, 1);
1209 if (ret)
1210 goto done;
1211
1212 newpage:
1213 /* Read in data */
1214 for (i = 0 ; i < MAX_JOBS_FROM_READ_PARSE ; i++)
1215 jobs[i] = NULL;
1216
1217 if ((ret = backend->read_parse(backend_ctx, jobs, data_fd, ncopies))) {
1218 if (read_page)
1219 goto done_multiple;
1220 else
1221 goto done;
1222 }
1223
1224 if (!jobs[0]) {
1225 WARNING("No job returned by backend read_parse?\n");
1226 goto newpage;
1227 }
1228
1229 /* Create a joblist if needed */
1230 if (!jlist) {
1231 jlist = dyesub_joblist_create(backend, backend_ctx);
1232 }
1233 if (!jlist) {
1234 for (i = 0 ; i < MAX_JOBS_FROM_READ_PARSE ; i++)
1235 backend->cleanup_job(jobs[i]);
1236 goto done;
1237 }
1238
1239 /* Stick jobs onto the end of the list */
1240 for (i = 0 ; i < MAX_JOBS_FROM_READ_PARSE ; i++) {
1241 if (jobs[i])
1242 dyesub_joblist_appendjob(jlist, jobs[i]);
1243 }
1244 read_page++;
1245
1246 INFO("Parsed page %d (%d copies)\n", read_page, ncopies);
1247
1248 /* If we get here, we can wait for another combined job, do so */
1249 if (dyesub_joblist_canwait(jlist))
1250 goto newpage;
1251
1252 print_list:
1253 /* Print the pagelist */
1254 ret = dyesub_joblist_print(jlist, &print_page);
1255 if (ret)
1256 goto done;
1257
1258 dyesub_joblist_cleanup(jlist);
1259 jlist = NULL;
1260
1261 /* Since we have no way of telling if there's more data remaining
1262 to be read (without actually trying to read it), always assume
1263 multiple print jobs. */
1264 goto newpage;
1265
1266 done_multiple:
1267 if (jlist)
1268 goto print_list;
1269
1270 close(data_fd);
1271
1272 ret = CUPS_BACKEND_OK;
1273
1274 done:
1275 if (jlist) dyesub_joblist_cleanup(jlist);
1276
1277 return ret;
1278 }
1279
1280 int main (int argc, char **argv)
1281 {
1282 struct libusb_device **list = NULL;
1283
1284 struct dyesub_backend *backend = NULL;
1285 void * backend_ctx = NULL;
1286
1287 struct dyesub_connection conn;
1288
1289 int ret = CUPS_BACKEND_OK;
1290
1291 int found = -1;
1292 int jobid = 0;
1293
1294 char *uri;
1295 char *type;
1296 const char *fname = NULL;
1297 char *use_serno = NULL;
1298 const char *backend_str = NULL;
1299 const char *argv0;
1300
1301 /* Work out path-less executable name */
1302 argv0 = strrchr(argv[0], '/');
1303 if (argv0)
1304 argv0++;
1305 else
1306 argv0 = argv[0];
1307
1308 logger = stderr;
1309
1310 /* Handle environment variables */
1311 if (getenv("BACKEND_QUIET"))
1312 quiet = atoi(getenv("BACKEND_QUIET"));
1313 if (getenv("BACKEND_STATS_ONLY"))
1314 stats_only = atoi(getenv("BACKEND_STATS_ONLY"));
1315 if (getenv("DYESUB_DEBUG"))
1316 dyesub_debug = atoi(getenv("DYESUB_DEBUG"));
1317 if (getenv("EXTRA_PID"))
1318 extra_pid = strtol(getenv("EXTRA_PID"), NULL, 16);
1319 if (getenv("EXTRA_VID"))
1320 extra_vid = strtol(getenv("EXTRA_VID"), NULL, 16);
1321 if (getenv("EXTRA_TYPE"))
1322 extra_type = atoi(getenv("EXTRA_TYPE"));
1323 if (getenv("BACKEND"))
1324 backend_str = getenv("BACKEND");
1325 else if (getenv("DYESUB_BACKEND"))
1326 backend_str = getenv("DYESUB_BACKEND");
1327 if (getenv("FAST_RETURN"))
1328 fast_return = atoi(getenv("FAST_RETURN"));
1329 if (getenv("MAX_XFER_SIZE"))
1330 max_xfer_size = atoi(getenv("MAX_XFER_SIZE"));
1331 if (getenv("XFER_TIMEOUT"))
1332 xfer_timeout = atoi(getenv("XFER_TIMEOUT"));
1333 if (getenv("TEST_MODE"))
1334 test_mode = atoi(getenv("TEST_MODE"));
1335 if (getenv("OLD_URI_SCHEME"))
1336 old_uri = atoi(getenv("OLD_URI_SCHEME"));
1337 if (getenv("CORRTABLE_PATH"))
1338 corrtable_path = getenv("CORRTABLE_PATH");
1339
1340 if (test_mode >= TEST_MODE_NOATTACH && (extra_vid == -1 || extra_pid == -1)) {
1341 ERROR("Must specify EXTRA_VID, EXTRA_PID in test mode > 1!\n");
1342 exit(1);
1343 }
1344
1345 if (stats_only && !dyesub_debug)
1346 quiet = 1;
1347
1348 DEBUG("Multi-Call Dye-sublimation CUPS Backend version %s\n",
1349 BACKEND_VERSION);
1350 DEBUG("Copyright 2007-2025 Solomon Peachy\n");
1351 DEBUG("This free software comes with ABSOLUTELY NO WARRANTY! \n");
1352 DEBUG("Licensed under the GNU GPL. Run with '-G' for more details.\n");
1353 DEBUG("\n");
1354
1355 use_serno = getenv("SERIAL");
1356 uri = getenv("DEVICE_URI"); /* CUPS backend mode! */
1357 type = getenv("CONTENT_TYPE"); /* CUPS content type -- ie raster or command */
1358
1359 if (uri && strlen(uri)) { /* CUPS backend mode */
1360 int base = optind; /* ie 1 */
1361 if (argc < 6) {
1362 ERROR("Insufficient arguments\n");
1363 exit(1);
1364 }
1365 if (argv[base])
1366 jobid = atoi(argv[base]);
1367 if (argc > 6) {
1368 fname = argv[base + 5];
1369 if (argv[base + 3])
1370 ncopies = atoi(argv[base + 3]);
1371 } else {
1372 fname = "-";
1373 }
1374
1375 /* Figure out backend based on URI */
1376 {
1377 char *ptr2;
1378 backend_str = strstr(uri, "backend=");
1379 if (backend_str) { /* Original format */
1380 backend_str += 8;
1381 ptr2 = strchr(backend_str, '&');
1382 if (ptr2) {
1383 use_serno = strstr(ptr2, "serial=");
1384 *ptr2 = 0;
1385 }
1386
1387 if (!use_serno)
1388 use_serno = strstr(uri, "serial=");
1389
1390 if (!use_serno || !*(use_serno+7)) {
1391 ERROR("Invalid URI (%s)\n", uri);
1392 exit(1);
1393 }
1394 use_serno += 7;
1395
1396 } else { /* New format */
1397 // prefix://backend/serno
1398 backend_str = strchr(uri, '/');
1399 backend_str += 2;
1400 use_serno = strchr(backend_str, '/');
1401 if (!use_serno || !*(use_serno+1)) {
1402 ERROR("Invalid URI (%s)\n", uri);
1403 exit(1);
1404 }
1405 *use_serno = 0;
1406 use_serno++;
1407 }
1408
1409 if (use_serno) {
1410 ptr2 = strchr(use_serno, '&');
1411 if (ptr2)
1412 *ptr2 = 0;
1413 }
1414 }
1415
1416 /* Enable fast return in CUPS if it's not supplied */
1417 if (!getenv("FAST_RETURN"))
1418 fast_return++;
1419
1420 } else { /* Standalone mode */
1421
1422 /* Try to guess backend from executable name */
1423 if (!backend_str)
1424 backend_str = argv0;
1425
1426 srand(getpid());
1427 jobid = rand();
1428 }
1429
1430 /* Finally, look up the backend */
1431 backend = find_backend(backend_str);
1432 if (!backend) {
1433 if (uri && strlen(uri)) {
1434 ERROR("Invalid backend requested (%s)\n", backend_str);
1435 exit(1);
1436 }
1437 backend_str = NULL;
1438 }
1439
1440 #ifndef LIBUSB_PRE_1_0_10
1441 if (dyesub_debug) {
1442 const struct libusb_version *ver;
1443 ver = libusb_get_version();
1444 DEBUG(" ** running with libusb %d.%d.%d%s (%d)\n",
1445 ver->major, ver->minor, ver->micro, (ver->rc? ver->rc : ""), ver->nano );
1446 }
1447 #endif
1448
1449 /* Libusb setup */
1450 ret = libusb_init(NULL);
1451 if (ret) {
1452 ERROR("Failed to initialize libusb (%d)\n", ret);
1453 ret = CUPS_BACKEND_RETRY_CURRENT;
1454 goto done;
1455 }
1456
1457 /* If we don't have a valid backend, print help and terminate */
1458 if (!backend && !stats_only) {
1459 print_help(argv0, NULL); // probes all devices
1460 ret = CUPS_BACKEND_OK;
1461 goto done;
1462 }
1463
1464 /* If we're in standalone mode, print help only if no args */
1465 if ((!uri || !strlen(uri)) && !stats_only) {
1466 if (argc < 2) {
1467 print_help(argv0, backend); // probes all devices
1468 ret = CUPS_BACKEND_OK;
1469 goto done;
1470 }
1471 }
1472
1473 /* Enumerate devices */
1474 STATE("+connecting-to-device\n");
1475
1476 found = find_and_enumerate(argv0, &list, backend, use_serno, backend_str, 0, NUM_CLAIM_ATTEMPTS, &conn);
1477
1478 if (found == -1) {
1479 ERROR("Printer open failure (No matching printers found!)\n");
1480 STATE("+offline-report\n");
1481 ret = CUPS_BACKEND_RETRY;
1482 goto done;
1483 }
1484 STATE("-offline-report\n");
1485
1486 if (test_mode) {
1487 WARNING("**** TEST MODE %d!\n", test_mode);
1488 if (test_mode >= TEST_MODE_NOATTACH)
1489 goto bypass;
1490 }
1491
1492 /* Open an appropriate device */
1493 ret = libusb_open(list[found], &conn.dev);
1494 if (ret) {
1495 ERROR("Printer open failure (Need to be root?) (%d)\n", ret);
1496 ret = CUPS_BACKEND_RETRY_CURRENT;
1497 goto done;
1498 }
1499
1500 /* Detach the kernel driver */
1501 if (libusb_kernel_driver_active(conn.dev, conn.iface)) {
1502 ret = libusb_detach_kernel_driver(conn.dev, conn.iface);
1503 if (ret && (ret != LIBUSB_ERROR_NOT_SUPPORTED)) {
1504 ERROR("Printer open failure (Could not detach printer from kernel) (%d)\n", ret);
1505 ret = CUPS_BACKEND_RETRY_CURRENT;
1506 goto done_close;
1507 }
1508 }
1509
1510 /* Claim the interface so we can start using this! */
1511 ret = backend_claim_interface(conn.dev, conn.iface, NUM_CLAIM_ATTEMPTS);
1512 if (ret) {
1513 ERROR("Printer open failure (Unable to claim interface) (%d)\n", ret);
1514 ret = CUPS_BACKEND_RETRY;
1515 goto done_close;
1516 }
1517
1518 /* Use the appropriate altesetting! */
1519 if (conn.altset != 0) {
1520 ret = libusb_set_interface_alt_setting(conn.dev, conn.iface, conn.altset);
1521 if (ret) {
1522 ERROR("Printer open failure (Unable to issue altsettinginterface) (%d)\n", ret);
1523 ret = CUPS_BACKEND_RETRY;
1524 goto done_claimed;
1525 }
1526 }
1527
1528 bypass:
1529 STATE("-connecting-to-device\n");
1530
1531 /* Initialize backend */
1532 DEBUG("Initializing '%s' backend (version %s)\n",
1533 backend->name, backend->version);
1534 backend_ctx = backend->init();
1535
1536 if (test_mode < TEST_MODE_NOATTACH) {
1537 struct libusb_device *device;
1538 struct libusb_device_descriptor desc;
1539
1540 device = libusb_get_device(conn.dev);
1541 libusb_get_device_descriptor(device, &desc);
1542
1543 conn.type = lookup_printer_type(backend,
1544 desc.idVendor, desc.idProduct);
1545 conn.usb_vid = desc.idVendor;
1546 conn.usb_pid = desc.idProduct;
1547 } else {
1548 conn.type = lookup_printer_type(backend,
1549 extra_vid, extra_pid);
1550 conn.usb_vid = extra_vid;
1551 conn.usb_pid = extra_pid;
1552 }
1553
1554 if (conn.type <= P_UNKNOWN) {
1555 ERROR("Unable to lookup printer type\n");
1556 ret = CUPS_BACKEND_FAILED;
1557 goto done_claimed;
1558 }
1559
1560 /* Attach backend to device */ // XXX pass backend_str?
1561 ret = backend->attach(backend_ctx, &conn, jobid);
1562 if (ret) {
1563 ERROR("Unable to attach to printer!\n");
1564 ret = CUPS_BACKEND_FAILED;
1565 goto done_claimed;
1566 }
1567
1568 /* Dump stats only */
1569 if (stats_only && backend->query_stats) {
1570 struct printerstats stats;
1571 memset(&stats, 0, sizeof(stats));
1572
1573 stats.timestamp = time(NULL);
1574 ret = backend->query_stats(backend_ctx, &stats);
1575 if (ret)
1576 goto done_claimed;
1577 dump_stats(backend, &stats, stats_only -1);
1578 for (int i = 0 ; i < stats.decks ; i++) {
1579 if (stats.status[i])
1580 free(stats.status[i]); // the only dynamic member..
1581 }
1582 goto done_claimed;
1583 }
1584
1585 PPD("StpUsbBackend=\"%s\"\n", backend_str ? backend_str : backend->name);
1586 PPD("StpUsbVid=%04x\n", conn.usb_vid);
1587 PPD("StpUsbPid=%04x\n", conn.usb_pid);
1588 if (test_mode < TEST_MODE_NOATTACH) {
1589 PPD("StpUsbBus=%03d\n", conn.bus_num);
1590 PPD("StpUsbPort=%03d\n", conn.port_num);
1591 }
1592
1593 if (!uri || !strlen(uri)) {
1594 if (backend->cmdline_arg(backend_ctx, argc, argv))
1595 goto done_claimed;
1596
1597 /* Grab the filename */
1598 fname = argv[optind]; // XXX do this a smarter way?
1599 }
1600
1601 /* Parse the file passed in */
1602 ret = handle_input(backend, backend_ctx, fname, uri, type);
1603
1604 done_claimed:
1605 if (test_mode < TEST_MODE_NOATTACH)
1606 libusb_release_interface(conn.dev, conn.iface);
1607
1608 done_close:
1609 if (test_mode < TEST_MODE_NOATTACH)
1610 libusb_close(conn.dev);
1611 done:
1612
1613 STATE("-connecting-to-device\n");
1614
1615 if (backend && backend_ctx) {
1616 if (backend->teardown)
1617 backend->teardown(backend_ctx);
1618 else
1619 generic_teardown(backend_ctx);
1620 }
1621
1622 if (list)
1623 libusb_free_device_list(list, 1);
1624
1625 libusb_exit(NULL);
1626
1627 return ret;
1628 }
1629
1630 void dump_markers(const struct marker *markers, int marker_count, int full)
1631 {
1632 int i;
1633
1634 if (!full)
1635 goto minimal;
1636
1637 ATTR("marker-colors=");
1638 for (i = 0 ; i < marker_count; i++) {
1639 DEBUG2("%s", markers[i].color);
1640 if ((i+1) < marker_count)
1641 DEBUG2(",");
1642 }
1643 DEBUG2("\n");
1644
1645 ATTR("marker-high-levels=");
1646 for (i = 0 ; i < marker_count; i++) {
1647 DEBUG2("%d", 100);
1648 if ((i+1) < marker_count)
1649 DEBUG2(",");
1650 }
1651 DEBUG2("\n");
1652
1653 ATTR("marker-low-levels=");
1654 for (i = 0 ; i < marker_count; i++) {
1655 DEBUG2("%d", 10);
1656 if ((i+1) < marker_count)
1657 DEBUG2(",");
1658 }
1659 DEBUG2("\n");
1660
1661 ATTR("marker-names=");
1662 for (i = 0 ; i < marker_count; i++) {
1663 DEBUG2("'\"%s\"'", markers[i].name);
1664 if ((i+1) < marker_count)
1665 DEBUG2(",");
1666 }
1667 DEBUG2("\n");
1668
1669 ATTR("marker-types=");
1670 for (i = 0 ; i < marker_count; i++) {
1671 DEBUG2("ribbonWax");
1672 if ((i+1) < marker_count)
1673 DEBUG2(",");
1674 }
1675 DEBUG2("\n");
1676
1677 minimal:
1678 ATTR("marker-levels=");
1679 for (i = 0 ; i < marker_count; i++) {
1680 int val;
1681 if (markers[i].levelmax <= 0 || markers[i].levelnow < 0)
1682 val = (markers[i].levelnow <= 0) ? markers[i].levelnow : CUPS_MARKER_UNAVAILABLE;
1683 else if (markers[i].levelmax == 100)
1684 val = markers[i].levelnow;
1685 else
1686 val = markers[i].levelnow * 100 / markers[i].levelmax;
1687 DEBUG2("%d", val);
1688 if ((i+1) < marker_count)
1689 DEBUG2(",");
1690 }
1691 DEBUG2("\n");
1692
1693 /* Only dump a message if the marker is not a percentage */
1694 if (markers[0].levelmax != 100) {
1695 ATTR("marker-message=");
1696 for (i = 0 ; i < marker_count; i++) {
1697 switch (markers[i].levelnow) {
1698 case CUPS_MARKER_UNAVAILABLE:
1699 DEBUG2("'\"Unable to query remaining prints on %s media\"'", markers[i].name);
1700 break;
1701 case CUPS_MARKER_UNKNOWN:
1702 DEBUG2("'\"Unknown remaining prints on %s media\"'", markers[i].name);
1703 break;
1704 case CUPS_MARKER_UNKNOWN_OK:
1705 DEBUG2("'\"One or more remaining prints on %s media\"'", markers[i].name);
1706 break;
1707 default:
1708 DEBUG2("'\"%d native prints remaining on %s media\"'", markers[i].levelnow, markers[i].name);
1709 break;
1710 }
1711 if ((i+1) < marker_count)
1712 DEBUG2(",");
1713 }
1714 DEBUG2("\n");
1715 }
1716
1717 if (markers[0].levelnow == 0)
1718 STATE("+media-empty\n");
1719 else if (markers[0].levelnow > 0 || markers[0].levelnow == CUPS_MARKER_UNKNOWN_OK)
1720 STATE("-media-empty\n");
1721
1722 /* If we're running as a CUPS backend, report the media type */
1723 if (full && getenv("DEVICE_URI")) {
1724 for (i = 0 ; i < marker_count ; i++) {
1725 PPD("StpMediaID%d=%d\n", i, markers[i].numtype);
1726 PPD("StpMediaName%d=\"%s\"\n", i, markers[i].name);
1727 }
1728 }
1729 }
1730
1731 int dyesub_read_file2(const char *filename, void *databuf, int datalen,
1732 int *actual_len, int fail_ok)
1733 {
1734 int len;
1735 int fd = open(filename, O_RDONLY);
1736
1737 if (fd < 0) {
1738 if (!fail_ok)
1739 ERROR("Unable to open '%s'\n", filename);
1740 return CUPS_BACKEND_FAILED;
1741 }
1742 len = read(fd, databuf, datalen);
1743 if (len < 0) {
1744 ERROR("Bad Read! (%d/%d)\n", len, errno);
1745 close(fd);
1746 return CUPS_BACKEND_FAILED;
1747 }
1748 if (!actual_len && (datalen != len)) {
1749 ERROR("Read mismatch (%d vs %d)\n", len, datalen);
1750 close(fd);
1751 return CUPS_BACKEND_FAILED;
1752 }
1753 close(fd);
1754
1755 if (actual_len)
1756 *actual_len = len;
1757
1758 return CUPS_BACKEND_OK;
1759 }
1760
1761 uint16_t uint16_to_packed_bcd(uint16_t val)
1762 {
1763 uint16_t bcd;
1764 uint16_t i;
1765
1766 /* Handle from 0-9999 */
1767 i = val % 10;
1768 bcd = i;
1769 val /= 10;
1770 i = val % 10;
1771 bcd |= (i << 4);
1772 val /= 10;
1773 i = val % 10;
1774 bcd |= (i << 8);
1775 val /= 10;
1776 i = val % 10;
1777 bcd |= (i << 12);
1778
1779 return bcd;
1780 }
1781
1782 uint32_t packed_bcd_to_uint32(const char *in, int len)
1783 {
1784 uint32_t out = 0;
1785
1786 while (len--) {
1787 out *= 10;
1788 out += ((*in >> 4) & 0xf);
1789 out *= 10;
1790 out += (*in & 0xf);
1791 in++;
1792 }
1793 return out;
1794 }
1795
1796 /* Job list manipulation */
1797 struct dyesub_joblist *dyesub_joblist_create(const struct dyesub_backend *backend, void *ctx)
1798 {
1799 struct dyesub_joblist *list;
1800
1801 list = malloc(sizeof(struct dyesub_joblist));
1802 if (!list) {
1803 ERROR("Memory allocation failure\n");
1804 return NULL;
1805 }
1806 list->backend = backend;
1807 list->ctx = ctx;
1808 list->num_entries = 0;
1809
1810 if (collate)
1811 list->copies = ncopies; // XXX
1812 else
1813 list->copies = 1;
1814
1815 return list;
1816 }
1817
1818 void dyesub_joblist_cleanup(const struct dyesub_joblist *list)
1819 {
1820 int i;
1821 for (i = 0; i < list->num_entries ; i++) {
1822 if (list->entries[i])
1823 list->backend->cleanup_job(list->entries[i]);
1824 }
1825 free((void*)list);
1826 }
1827
1828 static int __dyesub_joblist_addjob(struct dyesub_joblist *list, const void *job)
1829 {
1830 if (list->num_entries >= DYESUB_MAX_JOB_ENTRIES)
1831 return 1;
1832
1833 list->entries[list->num_entries++] = job;
1834
1835 return CUPS_BACKEND_OK;
1836 }
1837
1838 static int __dyesub_append_job(struct dyesub_joblist *list, const void **vjob, int polarity)
1839 {
1840 struct dyesub_job_common *job, *combined;
1841 const struct dyesub_job_common *oldjob;
1842
1843 /* Create writable copy of the new job */
1844 job = malloc(((const struct dyesub_job_common *)*vjob)->jobsize);
1845 if (!job) {
1846 ERROR("Memory allocation failure!\n");
1847 return CUPS_BACKEND_RETRY_CURRENT;
1848 }
1849 memcpy(job, *vjob, ((const struct dyesub_job_common *)*vjob)->jobsize);
1850
1851 /* If we can't combine the new job, don't bother doing anything else */
1852 if (!job->can_combine) {
1853 free(job);
1854 return CUPS_BACKEND_OK;
1855 }
1856
1857 /* Get the old job */
1858 oldjob = dyesub_joblist_popjob(list);
1859
1860 /* If we can't combine with it, carry on as before */
1861 if (oldjob && (oldjob->copies > 1 || !oldjob->can_combine)) {
1862 __dyesub_joblist_addjob(list, oldjob);
1863 oldjob = NULL;
1864 }
1865
1866 if (oldjob) {
1867 /* Try to combine first copy with old job */
1868 combined = list->backend->combine_jobs(oldjob, job);
1869 if (combined) {
1870 INFO("Successfully combined two jobs\n");
1871 /* Success, add it to the list */
1872 __dyesub_joblist_addjob(list, combined);
1873 combined = NULL;
1874
1875 /* Clean up the old job */
1876 list->backend->cleanup_job(oldjob);
1877
1878 /* Anything left in the new job? */
1879 job->copies--;
1880 if (job->copies == 0) {
1881 /* Nope, we're done */
1882 list->backend->cleanup_job(job);
1883 } else if (job->copies == 1) {
1884 /* Just one, shove it on the list */
1885 __dyesub_joblist_addjob(list, job);
1886 }
1887
1888 goto done;
1889 } else {
1890 /* Failed to combine, restore old job and continue */
1891 __dyesub_joblist_addjob(list, oldjob);
1892 }
1893
1894 polarity = 0;
1895 }
1896
1897 /* If we have no work to do, just return */
1898 if (job->copies == 1) {
1899 free(job);
1900 return CUPS_BACKEND_OK;
1901 }
1902
1903 /* Attempt to combine multiple copies! */
1904 combined = list->backend->combine_jobs(job, job);
1905
1906 if (!combined) {
1907 /* Failed, so return */
1908 free(job);
1909 return CUPS_BACKEND_OK;
1910 }
1911
1912 INFO("Successfully combined multiple copies\n");
1913 combined->copies = job->copies / 2;
1914 job->copies = job->copies % 2;
1915
1916 /* Add the combined job at start if we can */
1917 if (!polarity) {
1918 __dyesub_joblist_addjob(list, combined);
1919 }
1920
1921 /* Add the remainder, if any */
1922 if (job->copies) {
1923 __dyesub_joblist_addjob(list, job);
1924 } else {
1925 list->backend->cleanup_job(job);
1926 }
1927
1928 /* Add combined job at end of we need to */
1929 if (polarity) {
1930 __dyesub_joblist_addjob(list, combined);
1931 }
1932
1933 done:
1934 /* Clean up */
1935 free((void*)*vjob);
1936 *vjob = NULL;
1937
1938 return CUPS_BACKEND_OK;
1939 }
1940
1941 int dyesub_joblist_appendjob(struct dyesub_joblist *list, const void *job)
1942 {
1943 if (list->backend->combine_jobs) {
1944 int polarity = 0;
1945 if (list->backend->job_polarity)
1946 polarity = list->backend->job_polarity(list->ctx);
1947 __dyesub_append_job(list, &job, polarity);
1948 }
1949
1950 if (job)
1951 __dyesub_joblist_addjob(list, job);
1952
1953 return CUPS_BACKEND_OK;
1954 }
1955
1956 const void *dyesub_joblist_popjob(struct dyesub_joblist *list)
1957 {
1958 if (list->num_entries) {
1959 return list->entries[--list->num_entries];
1960 }
1961
1962 return NULL;
1963 }
1964
1965 #include "backend_panodata.h"
1966 #define PROCESS_PIXEL(__corr, __offset) \
1967 data[(r * cols * 3) + c + __offset] = 255 - ((255 - (double)data[(r * cols *3) + c +__offset]) * (__corr))
1968
1969 static void dyesub_pano_process_rgb8(const struct dnp_panodata *pano,
1970 uint8_t *data, int lh, int rh,
1971 uint16_t cols, uint16_t rows,
1972 uint16_t overlap, uint16_t pad_rows)
1973 {
1974 /* Skip over start margin in source */
1975 data += pad_rows * cols * 3;
1976
1977 for (int r = 0 ; r < rows ; r++) {
1978 if (rh && r < overlap) {
1979 const struct panodata_row *rhc;
1980 int i, c;
1981 int row = (overlap - r);
1982 for (i = 0 ; i < pano->elements-1 ; i++) {
1983 if (row >= pano->rows[i].start_row && row < pano->rows[i+1].start_row)
1984 break;
1985 }
1986 rhc = &pano->rows[i];
1987 for (c = 0 ; c < cols ; c++) {
1988 PROCESS_PIXEL(rhc->rhYMC[2],0); /* R/C */
1989 PROCESS_PIXEL(rhc->rhYMC[1],1); /* G/M */
1990 PROCESS_PIXEL(rhc->rhYMC[0],2); /* B/Y */
1991 }
1992 } else if (lh && (rows - r) < overlap) {
1993 const struct panodata_row *lhc;
1994 int i, c;
1995 int row = (rows -r);
1996 for (i = 0 ; i < pano->elements-1 ; i++) {
1997 if (row >= pano->rows[i].start_row && row < pano->rows[i+1].start_row)
1998 break;
1999 }
2000 lhc = &pano->rows[i];
2001 for (c = 0 ; c < cols ; c++) {
2002 PROCESS_PIXEL(lhc->rhYMC[2],0); /* R/C */
2003 PROCESS_PIXEL(lhc->rhYMC[1],1); /* G/M */
2004 PROCESS_PIXEL(lhc->rhYMC[0],2); /* B/Y */
2005 }
2006 }
2007 }
2008 }
2009
2010 void dyesub_pano_split_rgb8(const uint8_t *src, uint16_t cols, uint8_t numpanels,
2011 uint16_t overlap_rows, uint16_t pad_rows,
2012 uint16_t *panel_rows, uint8_t **panels)
2013 {
2014 int i = 0;
2015
2016 INFO("Splitting job into %d panel continuous panorama\n", numpanels);
2017
2018 /* Skip over start margin in source */
2019 src += pad_rows * cols * 3;
2020
2021 for (i = 0 ; i < numpanels ; i++) {
2022 int lh = (i < (numpanels -1));
2023 int rh = (i > 0);
2024 uint8_t *out = panels[i];
2025
2026 /* Fill start margin with white */
2027 if (pad_rows) {
2028 memset(out, 0xff, pad_rows * cols * 3);
2029 out += pad_rows * cols * 3;
2030 }
2031
2032 /* Copy over panel data */
2033 memcpy(out, src, panel_rows[i] * cols * 3);
2034 src += (panel_rows[i] - overlap_rows) * cols * 3; /* Factor in overlap */
2035 out += panel_rows[i] * cols * 3;
2036
2037 /* Fill end margin with white */
2038 if (pad_rows) {
2039 memset(out, 0xff, pad_rows * cols * 3);
2040 out += pad_rows * cols * 3;
2041 }
2042
2043 dyesub_pano_process_rgb8(&panodata, panels[i], lh, rh,
2044 cols, panel_rows[i],
2045 overlap_rows, pad_rows);
2046 }
2047 }
2048
2049 int dyesub_joblist_canwait(struct dyesub_joblist *list)
2050 {
2051 if (list->num_entries == DYESUB_MAX_JOB_ENTRIES)
2052 return 0;
2053 if (!list->num_entries)
2054 return 1;
2055
2056 return ((const struct dyesub_job_common *)(list->entries[list->num_entries - 1]))->can_combine;
2057 }
2058
2059 int dyesub_joblist_print(const struct dyesub_joblist *list, int *pagenum)
2060 {
2061 int i, j;
2062 int ret;
2063 // int pages = 0;
2064
2065 for (i = 0 ; i < list->copies ; i++) {
2066 for (j = 0 ; j < list->num_entries ; j++) {
2067 int wait_on_return = 0;
2068 if (i == (list->copies - 1) && j == (list->num_entries -1))
2069 wait_on_return = !fast_return; /* only wait on the final copy/page. */
2070
2071 if (list->entries[j]) {
2072 int copies = ((const struct dyesub_job_common *)(list->entries[j]))->copies;
2073
2074 INFO("Printing page %d (%d copies)\n", ++(*pagenum), copies);
2075 if (test_mode >= TEST_MODE_NOPRINT )
2076 WARNING("**** TEST MODE, bypassing printing!\n");
2077
2078 /* Print this page */
2079 if (test_mode < TEST_MODE_NOPRINT ||
2080 list->backend->flags & BACKEND_FLAG_DUMMYPRINT) {
2081 ret = list->backend->main_loop(list->ctx, list->entries[j], wait_on_return);
2082 if (ret)
2083 return ret;
2084 }
2085
2086 // pages += copies;
2087
2088 /* Dump a marker status update */
2089 ret = query_markers(list->backend, list->ctx, 0);
2090 if (ret)
2091 return ret;
2092 #if 0
2093 /* Free up the job as we go along
2094 if we're on the final copy */
2095 if (i + 1 == list->copies) {
2096 list->backend->cleanup_job(list->entries[j]);
2097 list->entries[j] = NULL;
2098 }
2099 #endif
2100 }
2101 }
2102 }
2103
2104 // INFO("Printed %d total pages/copies\n", pages);
2105
2106 return CUPS_BACKEND_OK;
2107 }