summaryrefslogtreecommitdiffstats
path: root/backend_common.c
blob: 3cde463a3e10a0d14cf2fac3e003ab7c5071ee9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
/*
 *   CUPS Backend common code
 *
 *   Copyright (c) 2007-2020 Solomon Peachy <pizza@shaftnet.org>
 *
 *   The latest version of this program can be found at:
 *
 *     http://git.shaftnet.org/cgit/selphy_print.git
 *
 *   This program is free software; you can redistribute it and/or modify it
 *   under the terms of the GNU General Public License as published by the Free
 *   Software Foundation; either version 3 of the License, or (at your option)
 *   any later version.
 *
 *   This program is distributed in the hope that it will be useful, but
 *   WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 *   or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 *   for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, see <https://www.gnu.org/licenses/>.
 *
 *   SPDX-License-Identifier: GPL-3.0+
 *
 */

#include "backend_common.h"
#include <errno.h>
#include <signal.h>
#include <strings.h>  /* For strncasecmp */

#define BACKEND_VERSION "0.109"
#ifndef URI_PREFIX
#error "Must Define URI_PREFIX"
#endif

#ifndef CORRTABLE_PATH
#ifdef PACKAGE_DATA_DIR
#define CORRTABLE_PATH PACKAGE_DATA_DIR "/backend_data"
#else
#error "Must define CORRTABLE_PATH or PACKAGE_DATA_DIR!"
#endif
#endif

#define URB_XFER_SIZE  (64*1024)
#define XFER_TIMEOUT    15000

#define USB_SUBCLASS_PRINTER 0x1
#define USB_INTERFACE_PROTOCOL_BIDIR 0x2
#define USB_INTERFACE_PROTOCOL_IPP   0x4

/* Global Variables */
int dyesub_debug = 0;
int terminate = 0;
int fast_return = 0;
int extra_vid = -1;
int extra_pid = -1;
int extra_type = -1;
int ncopies = 1;
int collate = 0;
int test_mode = 0;
int quiet = 0;
FILE *logger;

const char *corrtable_path = CORRTABLE_PATH;
static int max_xfer_size = URB_XFER_SIZE;
static int xfer_timeout = XFER_TIMEOUT;
static int old_uri = 0;

/* Support Functions */
int backend_claim_interface(struct libusb_device_handle *dev, int iface,
			    int num_claim_attempts)
{
	int ret;
	do {
		ret = libusb_claim_interface(dev, iface);
		if (!ret)
			break;
		if (ret != LIBUSB_ERROR_BUSY)
			break;
		if (--num_claim_attempts == 0)
			break;
		sleep(1);
	} while (1);

	if (ret)
		ERROR("Failed to claim interface %d (%d)\n", iface, ret);

	return ret;
}

static int lookup_printer_type(struct dyesub_backend *backend, uint16_t idVendor, uint16_t idProduct)
{
	int i;
	int type = P_UNKNOWN;

	for (i = 0 ; backend->devices[i].vid ; i++) {
		if (extra_pid != -1 &&
		    extra_vid != -1 &&
		    extra_type != -1) {
			if (backend->devices[i].type == extra_type &&
			    extra_vid == idVendor &&
			    extra_pid == idProduct) {
				return extra_type;
			}
		}
		if (idVendor == backend->devices[i].vid &&
		    idProduct == backend->devices[i].pid) {
			return backend->devices[i].type;
		}
	}

	return type;
}

/* Interface **MUST** already be claimed! */
#define ID_BUF_SIZE 2048
char *get_device_id(struct libusb_device_handle *dev, int iface)
{
	int length;
	char *buf = malloc(ID_BUF_SIZE + 1);

	if (!buf) {
		ERROR("Memory allocation failure (%d bytes)\n", ID_BUF_SIZE+1);
		return NULL;
	}

	if (libusb_control_transfer(dev,
				    LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_ENDPOINT_IN |
				    LIBUSB_RECIPIENT_INTERFACE,
				    0, 0,
				    (iface << 8),
				    (unsigned char *)buf, ID_BUF_SIZE, 5000) < 0)
	{
		*buf = '\0';
		goto done;
	}

	/* length is the first two bytes, MSB first */
	length = (((unsigned)buf[0] & 255) << 8) |
		((unsigned)buf[1] & 255);

	/* Sanity checks */
	if (length > ID_BUF_SIZE || length < 14)
		length = (((unsigned)buf[1] & 255) << 8) |
			((unsigned)buf[0] & 255);

	if (length > ID_BUF_SIZE)
		length = ID_BUF_SIZE;

	if (length < 14) {
		*buf = '\0';
		goto done;
	}

	/* IEEE1284 length field includs the header! */
	length -= 2;

	/* Move, and terminate */
	memmove(buf, buf + 2, length);
	buf[length] = '\0';

done:
	return buf;
}

/* Used with the IEEE1284 deviceid string parsing */
int parse1284_data(const char *device_id, struct deviceid_dict* dict)
{
	char *ptr;
	char key[256];
	char val[256];
	int num = 0;

	if (!device_id)
		return CUPS_BACKEND_OK;

	//[whitespace]key[whitespace]:[whitespace]value[whitespace];
	while (*device_id && num < MAX_DICT) {
		/* Skip leading spaces */
		if (*device_id == ' ')
			device_id++;
		if (!*device_id)
			break;

		/* Work out key */
		for (ptr = key; *device_id && *device_id != ':'; device_id++)
			*ptr++ = *device_id;
		if (!*device_id)
			break;
		while (ptr > key && *(ptr-1) == ' ')
			ptr--;
		*ptr = 0;
		device_id++;
		if (!*device_id)
			break;

		/* Next up, value */
		for (ptr = val; *device_id && *device_id != ';'; device_id++)
			*ptr++ = *device_id;
		while (ptr > val && *(ptr-1) == ' ')
			ptr--;
		*ptr = 0;
		device_id++;

		/* Add it to the dictionary */
		dict[num].key = strdup(key);
		dict[num].val = strdup(val);
		num++;

		if (!*device_id)
			break;
	}
	return num;
}

char *dict_find(const char *key, int dlen, struct deviceid_dict* dict)
{
	while(dlen) {
		if (!strcmp(key, dict->key))
			return dict->val;
		dlen--;
		dict++;
	}
	return NULL;
}

/* I/O functions */

int read_data(struct dyesub_connection *conn, uint8_t *buf, int buflen, int *readlen)
{
	int ret;

	/* Clear buffer */
	memset(buf, 0, buflen);

	ret = libusb_bulk_transfer(conn->dev, conn->endp_up,
				   buf,
				   buflen,
				   readlen,
				   xfer_timeout);

	if (ret < 0) {
		ERROR("Failure to receive data from printer (libusb error %d: (%d/%d from 0x%02x))\n", ret, *readlen, buflen, conn->endp_up);
		goto done;
	}

	if (dyesub_debug) {
		DEBUG("Received %d bytes from printer\n", *readlen);
	}

	if ((dyesub_debug > 1 && buflen < 4096) ||
	    dyesub_debug > 2) {
		int i = *readlen;

		DEBUG("<- ");
		while(i > 0) {
			if ((*readlen-i) != 0 &&
			    (*readlen-i) % 16 == 0) {
				DEBUG2("\n");
				DEBUG("   ");
			}
			DEBUG2("%02x ", buf[*readlen-i]);
			i--;
		}
		DEBUG2("\n");
	}

done:
	return ret;
}

int send_data(struct dyesub_connection *conn, const uint8_t *buf, int len)
{
	int num = 0;

	if (dyesub_debug) {
		DEBUG("Sending %d bytes to printer\n", len);
	}

	while (len) {
		int len2 = (len > max_xfer_size) ? max_xfer_size: len;

		if ((dyesub_debug > 1 && len2 < 4096) ||
		    dyesub_debug > 2) {
			int i = len2;

			DEBUG("-> ");
			while(i > 0) {
				if ((len2-i) != 0 &&
				    (len2-i) % 16 == 0) {
					DEBUG2("\n");
					DEBUG("   ");
				}
				DEBUG2("%02x ", buf[len2-i]);
				i--;
			}
			DEBUG2("\n");
		}

		int ret = libusb_bulk_transfer(conn->dev, conn->endp_down,
					       (uint8_t*) buf, len2,
					       &num, xfer_timeout);

		if (ret < 0) {
			ERROR("Failure to send data to printer (libusb error %d: (%d/%d to 0x%02x))\n", ret, num, len2, conn->endp_down);
			return ret;
		}
		len -= num;
		buf += num;
	}

	return CUPS_BACKEND_OK;
}

/* More stuff */
#ifndef _WIN32
static void sigterm_handler(int signum) {
	UNUSED(signum);

	terminate = 1;
	INFO("Job Cancelled");
}
#endif

static char *sanitize_string(char *str) {
	int len = strlen(str);

	while(len && (str[len-1] <= 0x20)) {
		str[len-1] = 0;
		len--;
	}
	return str;
}

/*

   These functions are Public Domain code obtained from:

   http://www.geekhideout.com/urlcode.shtml

*/
#include <ctype.h>  /* for isalnum() */
static char to_hex(char code) {
	static const char hex[] = "0123456789abcdef";
	return hex[code & 15];
}
static char from_hex(char ch) {
	return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;
}
/* Note -- caller must free returned pointer! */
static char *url_encode(const char *str) {
	const char *pstr = str;
	char *buf = malloc(strlen(str) * 3 + 1);
	char *pbuf = buf;

	if (!buf) {
		ERROR("Memory allocation failure (%d bytes)\n", (int) strlen(str)*3 + 1);
		return NULL;
	}

	while (*pstr) {
		if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~')
			*pbuf++ = *pstr;
		else if (*pstr == ' ')
			*pbuf++ = '+';
		else
			*pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
		pstr++;
	}
	*pbuf = '\0';
	return buf;
}
static char *url_decode(char *str) {
	char *pstr = str, *buf = malloc(strlen(str) + 1), *pbuf = buf;

	if (!buf) {
		ERROR("Memory allocation failure (%d bytes)\n", (int) strlen(str) + 1);
		return NULL;
	}

	while (*pstr) {
		if (*pstr == '%') {
			if (pstr[1] && pstr[2]) {
				*pbuf++ = from_hex(pstr[1]) << 4 | from_hex(pstr[2]);
				pstr += 2;
			}
		} else if (*pstr == '+') {
			*pbuf++ = ' ';
		} else {
			*pbuf++ = *pstr;
		}
		pstr++;
	}
	*pbuf = '\0';
	return buf;
}

/* And now back to our regularly-scheduled programming */

static int probe_device(struct libusb_device *device,
			struct libusb_device_descriptor *desc,
			const char *make,
			const char *uri_prefix, const char *manuf_override,
			int found, int num_claim_attempts,
			int scan_only, const char *match_serno,
			struct dyesub_connection *conn,
			struct dyesub_backend *backend)
{
	struct libusb_device_handle *dev;
	char buf[256];
	char *product = NULL, *serial = NULL, *manuf = NULL, *descr = NULL;
	uint8_t iface, altset;
	struct libusb_config_descriptor *config = NULL;
	int dlen = 0;
	struct deviceid_dict dict[MAX_DICT];
	char *ieee_id = NULL;
	int i;
	uint8_t endp_up, endp_down;

	DEBUG("Probing VID: %04X PID: %04x\n", desc->idVendor, desc->idProduct);
	STATE("+connecting-to-device\n");

	if ((i = libusb_open(device, &dev))) {
#ifdef _WIN32
		if (i == LIBUSB_ERROR_NOT_SUPPORTED)
			ERROR("Could not open device %04x:%04x! (Genric USB driver missing, See README)\n", desc->idVendor, desc->idProduct);
		else
#endif
			ERROR("Could not open device %04x:%04x - %d (need to be root?)\n", desc->idVendor, desc->idProduct, i);
		found = -1;
		goto abort;
	}

#if 0
	/* XXX FIXME: Iterate through bNumConfigurations */

	/* Force reset of device configuration */
	{
		int cfgnum = -1;
		if (libusb_get_configuration(dev, &cfgnum)) {
			ERROR("Can't get config!");
		}
		INFO("Config %d\n", config);
		if (config < 1)
			cfgnum = 1;
		if (libusb_set_configuration(dev, cfgnum)) {
			ERROR("Can't set config\n");
		}
	}
#endif

	/* Get descriptor for active configuration */
	if (libusb_get_active_config_descriptor(device, &config)) {
		found  = -1;
		goto abort_close;
	}

	/* Loop through all interfaces and altsettings to find candidates */
	for (iface = 0 ; iface < config->bNumInterfaces ; iface ++) {
		for (altset = 0 ; altset < config->interface[iface].num_altsetting ; altset++) {
			/* Skip interfaces that don't have enough endpoints */
			if (config->interface[iface].altsetting[altset].bNumEndpoints < 2) {
				continue;
			}

#if 1
			/* Explicitly exclude IPP-over-USB interfaces */
			if (desc->bDeviceClass == LIBUSB_CLASS_PER_INTERFACE &&
			    config->interface[iface].altsetting[altset].bInterfaceClass == LIBUSB_CLASS_PRINTER &&
			    config->interface[iface].altsetting[altset].bInterfaceSubClass == USB_SUBCLASS_PRINTER &&
			    config->interface[iface].altsetting[altset].bInterfaceProtocol == USB_INTERFACE_PROTOCOL_IPP) {
				continue;
			}
#else
			// Make sure it's a printer class device that supports bidir comms  (XXX Is this necessarily true?)
			if (desc->bDeviceClass == LIBUSB_CLASS_PRINTER ||
			    (desc->bDeviceClass == LIBUSB_CLASS_PER_INTERFACE &&
			     config->interface[iface].altsetting[altset].bInterfaceClass == LIBUSB_CLASS_PRINTER &&
			     config->interface[iface].altsetting[altset].bInterfaceSubClass == USB_SUBCLASS_PRINTER &&
			     config->interface[iface].altsetting[altset].bInterfaceProtocol != USB_INTERFACE_PROTOCOL_BIDIR)) {
				continue;
			}
#endif

			/* Find the first set of endpoints! */
			endp_up = endp_down = 0;
			for (i = 0 ; i < config->interface[iface].altsetting[altset].bNumEndpoints ; i++) {
				if ((config->interface[iface].altsetting[altset].endpoint[i].bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) == LIBUSB_TRANSFER_TYPE_BULK) {
					if (config->interface[iface].altsetting[altset].endpoint[i].bEndpointAddress & LIBUSB_ENDPOINT_IN)
						endp_up = config->interface[iface].altsetting[altset].endpoint[i].bEndpointAddress;
					else
						endp_down = config->interface[iface].altsetting[altset].endpoint[i].bEndpointAddress;
				}
				if (endp_up && endp_down)
					goto candidate;
			}
		}
	}

	/* If we got here, we didn't find a match. */
	found = -1;
	goto abort_close;

candidate:

	/* We've now found an interface/altset we need to query in more detail */
	/* Detach the kernel driver */
	if (libusb_kernel_driver_active(dev, iface))
		libusb_detach_kernel_driver(dev, iface);

	/* Claim the interface so we can start querying things! */
	if (backend_claim_interface(dev, iface, num_claim_attempts)) {
		found = -1;
		goto abort_release;
	}

	/* Use the appropriate altesetting, but only if the
	   printer supports more than one.  Some printers don't like
	   us unconditionally setting this. */
	if (config->interface[iface].num_altsetting > 1) {
		if (libusb_set_interface_alt_setting(dev, iface, altset)) {
			ERROR("Failed to set alternative interface %d/%d\n", iface, altset);
			found = -1;
			goto abort_release;
		}
	}

	/* Query IEEE1284 info only if it's a PRINTER class */
	if (desc->bDeviceClass == LIBUSB_CLASS_PRINTER ||
	    (desc->bDeviceClass == LIBUSB_CLASS_PER_INTERFACE &&
	     config->interface[iface].altsetting[altset].bInterfaceClass == LIBUSB_CLASS_PRINTER &&
	     config->interface[iface].altsetting[altset].bInterfaceSubClass == USB_SUBCLASS_PRINTER)) {
		ieee_id = get_device_id(dev, iface);
		dlen = parse1284_data(ieee_id, dict);
	}

//	if (!old_uri) goto bypass;

	/* Look up mfg string. */
	if (manuf_override && strlen(manuf_override)) {
		manuf = url_encode(manuf_override);  /* Backend supplied */
	} else if ((manuf = dict_find("MANUFACTURER", dlen, dict))) {
		manuf = url_encode(manuf);
	} else if ((manuf = dict_find("MFG", dlen, dict))) {
		manuf = url_encode(manuf);
	} else if ((manuf = dict_find("MFR", dlen, dict))) {
		manuf = url_encode(manuf);
	} else if (desc->iManufacturer) { /* Get from USB descriptor */
		buf[0] = 0;
		libusb_get_string_descriptor_ascii(dev, desc->iManufacturer, (unsigned char*)buf, STR_LEN_MAX);
		sanitize_string(buf);
		manuf = url_encode(buf);
	}
	if (!manuf || !strlen(manuf)) {  /* Last-ditch */
		if (manuf) free(manuf);
		manuf = url_encode("Unknown"); // XXX use USB VID?
	}

	/* Look up model number */
	if ((product = dict_find("MODEL", dlen, dict))) {
		product = url_encode(product);
	} else if ((product = dict_find("MDL", dlen, dict))) {
		product = url_encode(product);
	} else if (desc->iProduct) {  /* Get from USB descriptor */
		buf[0] = 0;
		libusb_get_string_descriptor_ascii(dev, desc->iProduct, (unsigned char*)buf, STR_LEN_MAX);
		sanitize_string(buf);
		product = url_encode(buf);
	}

	if (!product || !strlen(product)) { /* Last-ditch */
		if (!product) free(product);
		product = url_encode("Unknown"); // XXX Use USB PID?
	}

	/* Look up description */
	if ((descr = dict_find("DESCRIPTION", dlen, dict))) {
		descr = strdup(descr);
	} else if ((descr = dict_find("DES", dlen, dict))) {
		descr = strdup(descr);
	}
	if (!descr || !strlen(descr)) { /* Last-ditch, generate */
		char *product2 = url_decode(product);
		char *manuf3 = url_decode(manuf);
		descr = malloc(514); /* 256 + 256 + 1 + 1 */
		if (!descr) {
			ERROR("Memory allocation failure (%d bytes)\n", 514);
			if (manuf3)
				free(manuf3);
			if (product2)
				free(product2);
			return -1;
		}

		snprintf(descr, 514, "%s %s", manuf3, product2);
		free(product2);
		free(manuf3);
	}

//bypass:

	/* Look up serial number */
	if ((serial = dict_find("SERIALNUMBER", dlen, dict))) {
		serial = url_encode(serial);
	} else if ((serial = dict_find("SN", dlen, dict))) {
		serial = url_encode(serial);
	} else if ((serial = dict_find("SER", dlen, dict))) {
		serial = url_encode(serial);
	} else if ((serial = dict_find("SERN", dlen, dict))) {
		serial = url_encode(serial);
	} else if (!(backend->flags & BACKEND_FLAG_BADISERIAL) &&
		   desc->iSerialNumber) {  /* Get from USB descriptor, if we can trust it.. */
		libusb_get_string_descriptor_ascii(dev, desc->iSerialNumber, (unsigned char*)buf, STR_LEN_MAX);
		sanitize_string(buf);
		serial = url_encode(buf);
	} else if (backend->query_serno) { /* Get from backend hook */
		struct dyesub_connection c2;
		c2.dev = dev;
		c2.iface = iface;
		c2.altset = altset;
		c2.endp_up = endp_up;
		c2.endp_down = endp_down;
		backend->query_serno(&c2, buf, STR_LEN_MAX);
		serial = url_encode(buf);
	}

	if (!serial || !strlen(serial)) {  /* Last-ditch */
		if (serial) free(serial);
		WARNING("**** THIS PRINTER DOES NOT REPORT A SERIAL NUMBER!\n");
		WARNING("**** If you intend to use multiple printers of this type, you\n");
		WARNING("**** must only plug one in at a time or unexpected behavior will occur!\n");
		serial = strdup("NONE_UNKNOWN");
	}

	if (scan_only) {
		if (!old_uri) {
			fprintf(stdout, "direct %s://%s/%s \"%s\" \"%s\" \"%s\" \"\"\n",
				uri_prefix, make, serial,
				descr, descr,
				ieee_id ? ieee_id : "");
		} else {
			int k = 0;

			/* URLify the manuf and model strings */
			strncpy(buf, manuf, sizeof(buf) - 2);
			k = strlen(buf);
			buf[k++] = '/';
			buf[k] = 0;

			strncpy(buf + k, product, sizeof(buf)-k);

			fprintf(stdout, "direct %s://%s?serial=%s&backend=%s \"%s\" \"%s\" \"%s\" \"\"\n",
				uri_prefix, buf, serial, make,
				descr, descr,
				ieee_id? ieee_id : "");
		}
	}

	/* If a serial number was passed down, use it. */
	if (match_serno && strcmp(match_serno, (char*)serial)) {
		found = -1;
	}

	if (dyesub_debug)
		DEBUG("VID: %04X PID: %04X Manuf: '%s' Product: '%s' Serial: '%s' found: %d\n",
		      desc->idVendor, desc->idProduct, manuf, product, serial, found);

	if (found != -1 && conn) {
		conn->iface = iface;
		conn->altset = altset;
		conn->endp_up = endp_up;
		conn->endp_down = endp_down;
	}

	/* Free things up */
	if(serial) free(serial);
	if(manuf) free(manuf);
	if(product) free(product);
	if(descr) free(descr);
	if(ieee_id) free(ieee_id);

abort_release:

	libusb_release_interface(dev, iface);

abort_close:

	libusb_close(dev);

abort:
	if (config) libusb_free_config_descriptor(config);

	/* Clean up the dictionary */
	while (dlen--) {
		free (dict[dlen].key);
		free (dict[dlen].val);
	}

	STATE("-connecting-to-device\n");

	return found;
}

void generic_teardown(void *vctx)
{
	if (!vctx)
		return;

	free(vctx);
}

extern struct dyesub_backend sonyupd_backend;
extern struct dyesub_backend sonyupdneo_backend;
extern struct dyesub_backend kodak6800_backend;
extern struct dyesub_backend kodak605_backend;
extern struct dyesub_backend kodak1400_backend;
extern struct dyesub_backend shinkos1245_backend;
extern struct dyesub_backend shinkos2145_backend;
extern struct dyesub_backend shinkos6145_backend;
extern struct dyesub_backend shinkos6245_backend;
extern struct dyesub_backend canonselphy_backend;
extern struct dyesub_backend canonselphyneo_backend;
extern struct dyesub_backend mitsu70x_backend;
extern struct dyesub_backend mitsu9550_backend;
extern struct dyesub_backend mitsup95d_backend;
extern struct dyesub_backend dnpds40_backend;
extern struct dyesub_backend magicard_backend;
extern struct dyesub_backend mitsud90_backend;
extern struct dyesub_backend hiti_backend;

static struct dyesub_backend *backends[] = {
	&canonselphy_backend,
	&canonselphyneo_backend,
	&kodak6800_backend,
	&kodak605_backend,
	&kodak1400_backend,
	&shinkos1245_backend,
	&shinkos2145_backend,
	&shinkos6145_backend,
	&shinkos6245_backend,
	&sonyupd_backend,
	&sonyupdneo_backend,
	&mitsu70x_backend,
	&mitsud90_backend,
	&mitsu9550_backend,
	&mitsup95d_backend,
	&dnpds40_backend,
	&magicard_backend,
	&hiti_backend,
	NULL,
};

static int find_and_enumerate(struct libusb_context *ctx,
			      struct libusb_device ***list,
			      const struct dyesub_backend *backend,
			      const char *match_serno,
			      const char *make,
			      int scan_only, int num_claim_attempts,
			      struct dyesub_connection *conn)
{
	int num;
	int i, j = 0, k;
	int found = -1;

	if (test_mode >= TEST_MODE_NOATTACH && conn) {
		found = 1;
		conn->endp_up = 0x82;
		conn->endp_down = 0x01;
		conn->iface = 0;
		conn->altset = 0;
		return found;
	}

	STATE("+org.gutenprint.searching-for-device\n");

	/* Enumerate and find suitable device */
	num = libusb_get_device_list(ctx, list);

	/* See if we can actually match on the supplied make! */
	if (backend && make) {
		int match = 0;
		for (j = 0 ; backend->devices[j].vid ; j++) {
			if (!strcmp(make,backend->devices[j].make)) {
				match = 1;
				break;
			}
		}
		/* If not, clear it */
		if (!match)
			make = NULL;
	} else {
		make = NULL; /* Explicitly clear it */
	}

	for (i = 0 ; i < num ; i++) {
		const char *foundmake = NULL;

		struct libusb_device_descriptor desc;
		libusb_get_device_descriptor((*list)[i], &desc);

		for (k = 0 ; backends[k] ; k++) {
			if (backend && backend != backends[k])
				continue;

			for (j = 0 ; backends[k]->devices[j].vid ; j++) {
				/* Try for extra pid/vid/type */
				// XXX nuke entire extra_??? concept?
				if (extra_pid != -1 &&
				    extra_vid != -1 &&
				    extra_type != -1) {
					if (backends[k]->devices[j].type == extra_type &&
					    extra_vid == desc.idVendor &&
					    extra_pid == desc.idProduct) {
						found = i;
						make = backends[k]->uri_prefixes[0];
						goto match;
					}
				}

				/* Match based on VID/PID (and prefix, if specified) */
				if (desc.idVendor == backends[k]->devices[j].vid &&
				    (desc.idProduct == backends[k]->devices[j].pid ||
				     desc.idProduct == 0xffff) &&
				    (!make || !strcmp(make,backends[k]->devices[j].make))) {
					    found = i;
					    foundmake = backends[k]->devices[j].make;
					    goto match;
				}
			}
		}

		continue;

	match:
		found = probe_device((*list)[i], &desc, (foundmake ? foundmake : make),
				     URI_PREFIX, backends[k]->devices[j].manuf_str,
				     found, num_claim_attempts,
				     scan_only, match_serno,
				     conn,
				     backends[k]);
		foundmake = NULL;
		if (found != -1 && !scan_only)
			break;
	}

	STATE("-org.gutenprint.searching-for-device\n");
	return found;
}

static struct dyesub_backend *find_backend(const char *uri_prefix)
{
	int i;

	if (!uri_prefix)
		return NULL;

	for (i = 0; ; i++) {
		struct dyesub_backend *backend = backends[i];
		const char **alias;
		int j;
		if (!backend)
			return NULL;
		for (alias = backend->uri_prefixes ; alias && *alias ; alias++) {
			if (!strcmp(uri_prefix, *alias))
				return backend;
		}
		for (j = 0 ; backend->devices[j].vid ; j++) {
			if (!strcmp(uri_prefix,backend->devices[j].make)) {
				return backend;
			}
		}
	}
	return NULL;
}

static int query_markers(const struct dyesub_backend *backend, void *ctx, int full)
{
	struct marker *markers = NULL;
	int marker_count = 0;
	int ret;

	if (!backend->query_markers)
		return CUPS_BACKEND_OK;

	if (test_mode >= TEST_MODE_NOPRINT)
		return CUPS_BACKEND_OK;

	ret = backend->query_markers(ctx, &markers, &marker_count);
	if (ret)
		return ret;

	dump_markers(markers, marker_count, full);

	return CUPS_BACKEND_OK;
}

static void dump_stats(struct dyesub_backend *backend, struct printerstats *stats, int json)
{
	int i;
	struct tm *tm;
	char tmbuf[64];
	tm = localtime(&stats->timestamp);

	strftime(tmbuf, sizeof(tmbuf), "%Y-%m-%d %H:%M:%S", tm);

	if (json) {
		fprintf(stdout, "{\n");
		fprintf(stdout, "\t\"backend\": \"%s\",\n", backend->name);
		fprintf(stdout, "\t\"version\": \"%s / %s\",\n", BACKEND_VERSION, backend->version);
		fprintf(stdout, "\t\"timestamp\": \"%s\",\n", tmbuf);
		if (stats->mfg)
			fprintf(stdout, "\t\"manufacturer\": \"%s\",\n", stats->mfg);
		if (stats->model)
			fprintf(stdout, "\t\"model\": \"%s\",\n", stats->model);
		if (stats->serial)
			fprintf(stdout, "\t\"serial\": \"%s\",\n", stats->serial);
		if (stats->fwver)
			fprintf(stdout, "\t\"firmware\": \"%s\",\n", stats->fwver);

		fprintf(stdout, "\t\"decks\": {\n");
		for (i = 0 ; i < stats->decks ; i++) {
			fprintf(stdout, "\t\t\"%s\": {\n", stats->name[i]);
			if (stats->status[i])
				fprintf(stdout, "\t\t\t\"status\": \"%s\",\n", stats->status[i]);
			fprintf(stdout, "\t\t\t\"mediatype\": \"%s\",\n", stats->mediatype[i]);
			switch (stats->levelnow[i]) {
			case CUPS_MARKER_UNKNOWN:
				fprintf(stdout, "\t\t\t\"medialevel\": \"Unknown\",\n");
				break;
			case CUPS_MARKER_UNAVAILABLE:
				fprintf(stdout, "\t\t\t\"medialevel\": \"Unavailable\",\n");
				break;
			case CUPS_MARKER_UNKNOWN_OK:
				fprintf(stdout, "\t\t\t\"medialevel\": \"OK\",\n");
				break;
			default:
				if (stats->levelnow[i] >= 0 && stats->levelmax[i] > 0) {
					fprintf(stdout, "\t\t\t\"medialevel\": \"OK\",\n");
					fprintf(stdout, "\t\t\t\"medialevelnow\": %d,\n", stats->levelnow[i]);
					fprintf(stdout, "\t\t\t\"medialevelmax\": %d,\n", stats->levelmax[i]);
				} else {
				fprintf(stdout, "\t\t\t\"medialevel\": \"Illegal value\",\n");
				}
				break;
			}
			fprintf(stdout, "\t\t\t\"counters\": {\n");
			if (stats->cnt_life[i] >= 0)
				fprintf(stdout, "\t\t\t\t\"lifetime\": %d\n", stats->cnt_life[i]);

			fprintf(stdout, "\t\t\t}\n");

			fprintf(stdout, "\t\t}%c\n", (i < (stats->decks -1) ? ',': ' '));
		}
		fprintf(stdout, "\t}\n");
		fprintf(stdout, "}\n");
	} else {
		fprintf(stdout, "Backend: %s\n", backend->name);
		fprintf(stdout, "Version: %s / %s\n", BACKEND_VERSION, backend->version);
		fprintf(stdout, "Timestamp: %s\n", tmbuf);
		if (stats->mfg)
			fprintf(stdout, "Manufacturer: %s\n", stats->mfg);
		if (stats->model)
			fprintf(stdout, "Model: %s\n", stats->model);
		if (stats->serial)
			fprintf(stdout, "Serial Number: %s\n", stats->serial);
		if (stats->fwver)
			fprintf(stdout, "Firmware Version: %s\n", stats->fwver);

		for (i = 0 ; i < stats->decks ; i++) {
			if (stats->status[i])
				fprintf(stdout, "%s Status: %s\n", stats->name[i], stats->status[i]);
			if (stats->cnt_life[i] >= 0)
				fprintf(stdout, "%s Lifetime Prints: %d\n", stats->name[i], stats->cnt_life[i]);
			fprintf(stdout, "%s Media Type: %s\n", stats->name[i], stats->mediatype[i]);
			if (stats->levelnow[i] == CUPS_MARKER_UNKNOWN_OK)
				fprintf(stdout, "%s Media Level: OK\n", stats->name[i]);
			else if (stats->levelnow[i] == CUPS_MARKER_UNKNOWN)
				fprintf(stdout, "%s Media Level: Unknown\n", stats->name[i]);
			else if (stats->levelnow[i] == CUPS_MARKER_UNAVAILABLE)
				fprintf(stdout, "%s Media Level: Unavailable\n", stats->name[i]);
			else if (stats->levelnow[i] >= 0 && stats->levelmax[i] > 0)
				fprintf(stdout, "%s Media Level: %d / %d\n", stats->name[i], stats->levelnow[i], stats->levelmax[i]);
		}
	}
}

void print_license_blurb(void)
{
	const char *license = "\n\
Copyright 2007-2020 Solomon Peachy <pizza AT shaftnet DOT org>\n\
\n\
This program is free software; you can redistribute it and/or modify it\n\
under the terms of the GNU General Public License as published by the Free\n\
Software Foundation; either version 3 of the License, or (at your option)\n\
any later version.\n\
\n\
This program is distributed in the hope that it will be useful, but\n\
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n\
or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n\
for more details.\n\
\n\
You should have received a copy of the GNU General Public License\n\
along with this program; if not, see <https://www.gnu.org/licenses/>.\n\n";

	fprintf(logger, "%s", license);
}

void print_help(const char *argv0, const struct dyesub_backend *backend)
{
	struct libusb_context *ctx = NULL;
	struct libusb_device **list = NULL;

	const char *ptr = getenv("BACKEND");
	if (!ptr)
		ptr = strrchr(argv0, '/');
	if (ptr)
		ptr++;
	else
		ptr = argv0;

	if (!backend)
		backend = find_backend(ptr);

	if (!backend) {
		int i;
		DEBUG("Environment variables:\n");
		DEBUG(" DYESUB_DEBUG EXTRA_PID EXTRA_VID EXTRA_TYPE BACKEND SERIAL OLD_URI_SCHEME BACKEND_QUIET\n");
		DEBUG("CUPS Usage:\n");
		DEBUG("\tDEVICE_URI=someuri %s job user title num-copies options [ filename ]\n", URI_PREFIX);
		DEBUG("\n");
		DEBUG("Standalone Usage:\n");
		DEBUG("\t%s\n", URI_PREFIX);
		DEBUG("  [ -D ] [ -G ] [ -f ] [ -v ]\n");
		DEBUG("  [ backend_specific_args ] \n");
		DEBUG("  [ -d copies ] \n");
		DEBUG("  [ - | infile ] \n");
		for (i = 0; ; i++) {
			const char **alias;

			backend = backends[i];
			if (!backend)
				break;
			DEBUG("\t# %s version %s\n",
			      backend->name, backend->version);
			DEBUG("  BACKEND=");
			for (alias = backend->uri_prefixes ; alias && *alias ; alias++)
				DEBUG2("%s ", *alias);
			DEBUG2("\n");

			if (backend->cmdline_usage)
				backend->cmdline_usage();
		}
	} else {
		const char **alias;
		int j;
		DEBUG("Standalone %s backend version %s\n",
		      backend->name, backend->version);
		DEBUG("\t supporting: ");
		for (alias = backend->uri_prefixes ; alias && *alias ; alias++)
			DEBUG2("%s ", *alias);
		for (j = 0 ; backend->devices[j].vid ; j++)
			DEBUG2("%s ", backend->devices[j].make);
		DEBUG2("\n");

		DEBUG("\t[ -D ] [ -G ] [ -f ]\n");
		if (backend->cmdline_usage)
			backend->cmdline_usage();
		DEBUG("\t[ -d copies ] [ infile | - ]\n");
	}

	/* Scan for all printers for the specified backend */
	find_and_enumerate(ctx, &list, backend, NULL, ptr, 1, 1, NULL);
	libusb_free_device_list(list, 1);
}

static int parse_cmdstream(struct dyesub_backend *backend, void *backend_ctx, int fd)
{
	FILE *fp = stdin;
	char line[128];
	char *lp;

	if (fd != fileno(stdin)) {
		fp = fdopen(fd, "r");
		if (!fp) {
			ERROR("Can't open data stream!\n");
			return CUPS_BACKEND_FAILED;
		}
	}
	while (fgets(line, sizeof(line), fp) != NULL) {
		/* Strip trailing newline */
		lp = line + strlen(line) - 1;
		if (*lp == '\n')
			*lp = '\0';
		/* And leading spaces */
		for (lp = line; isspace(*lp); lp++);
		/* And comments and blank lines */
		if (*lp == '#' || !*lp)
			continue;

		/* Parse command! */
		if (strncasecmp(lp, "ReportLevels", 12) == 0) {
			query_markers(backend, backend_ctx, 1);
/* XXX TODO: ReportStatus, AutoConfigure, PrintSelfTestPage?  What about others, eg reset or cancel job? */
		} else {
			WARNING("Invalid printer command \"%s\"!\n", lp);
		}
	}

	/* Clean up */
	if (fp != stdin)
		fclose(fp);

	return CUPS_BACKEND_OK;
}

static int handle_input(struct dyesub_backend *backend, void *backend_ctx,
			const char *fname, char *uri, char *type)
{
	int ret = CUPS_BACKEND_OK;
#ifndef _WIN32
	int i;
#endif
	const void *job;
	int data_fd = fileno(stdin);
	int read_page = 0, print_page = 0;
	struct dyesub_joblist *jlist = NULL;

	if (!fname) {
		if (uri && strlen(uri))
			ERROR("ERROR: No input file specified\n");
		ret = CUPS_BACKEND_FAILED;
		goto done;
	}

	if (ncopies < 1) {
		ERROR("ERROR: need to have at least 1 copy!\n");
		ret = CUPS_BACKEND_FAILED;
		goto done;
	}

	/* Open file if not STDIN */
	if (strcmp("-", fname)) {
		data_fd = open(fname, O_RDONLY);
		if (data_fd < 0) {
			perror("ERROR:Can't open input file");
			ret = CUPS_BACKEND_FAILED;
			goto done;
		}
	}

#ifndef _WIN32
	/* Ensure we're using BLOCKING I/O */
	i = fcntl(data_fd, F_GETFL, 0);
	if (i < 0) {
		perror("ERROR:Can't open input");
		ret = CUPS_BACKEND_FAILED;
		goto done;
	}
	i &= ~O_NONBLOCK;
	i = fcntl(data_fd, F_SETFL, i);
	if (i < 0) {
		perror("ERROR:Can't open input");
		ret = CUPS_BACKEND_FAILED;
		goto done;
	}

	/* Ignore SIGPIPE */
	signal(SIGPIPE, SIG_IGN);
	signal(SIGTERM, sigterm_handler);
#endif

	/* Time for the main processing loop */
	INFO("Printing started (%d copies)\n", ncopies);

	/* See if it's a CUPS command stream, and if yes, handle it! */
	if (type && !strcmp("application/vnd.cups-command", type))
	{
		ret = parse_cmdstream(backend, backend_ctx, data_fd);
		goto done;
	}

	/* Emit a verbose marker dump */
	ret = query_markers(backend, backend_ctx, 1);
	if (ret)
		goto done;

newpage:
	/* Read in data */
	job = NULL;
	if ((ret = backend->read_parse(backend_ctx, &job, data_fd, ncopies))) {
		if (read_page)
			goto done_multiple;
		else
			goto done;
	}

	if (!job) {
		WARNING("No job returned by backend read_parse?\n");
		goto newpage;
	}

	/* Create a joblist if needed */
	if (!jlist) {
		jlist = dyesub_joblist_create(backend, backend_ctx);
	}
	if (!jlist) {
		backend->cleanup_job(job);
		goto done;
	}

	/* Stick it onto the end of the list */
	dyesub_joblist_appendjob(jlist, job);
	read_page++;

	INFO("Parsed page %d (%d copies)\n", read_page, ncopies);

	/* If we get here, we can wait for another combined job, do so */
	if (dyesub_joblist_canwait(jlist))
		goto newpage;

print_list:
	/* Print the pagelist */
	ret = dyesub_joblist_print(jlist, &print_page);
	if (ret)
		goto done;

	dyesub_joblist_cleanup(jlist);
	jlist = NULL;

	/* Since we have no way of telling if there's more data remaining
	   to be read (without actually trying to read it), always assume
	   multiple print jobs. */
	goto newpage;

done_multiple:
	if (jlist)
		goto print_list;

	close(data_fd);

	ret = CUPS_BACKEND_OK;

done:
	if (jlist) dyesub_joblist_cleanup(jlist);

	return ret;
}

int main (int argc, char **argv)
{
	struct libusb_context *ctx = NULL;
	struct libusb_device **list = NULL;

	struct dyesub_backend *backend = NULL;
	void * backend_ctx = NULL;

	struct dyesub_connection conn;

	int ret = CUPS_BACKEND_OK;

	int found = -1;
	int jobid = 0;

	int stats_only = 0;
	char *uri;
	char *type;
	const char *fname = NULL;
	char *use_serno = NULL;
	const char *backend_str = NULL;

	logger = stderr;

	/* Handle environment variables  */
	if (getenv("BACKEND_QUIET"))
		quiet = atoi(getenv("BACKEND_QUIET"));
	if (getenv("BACKEND_STATS_ONLY"))
		stats_only = atoi(getenv("BACKEND_STATS_ONLY"));
	if (getenv("DYESUB_DEBUG"))
		dyesub_debug = atoi(getenv("DYESUB_DEBUG"));
	if (getenv("EXTRA_PID"))
		extra_pid = strtol(getenv("EXTRA_PID"), NULL, 16);
	if (getenv("EXTRA_VID"))
		extra_vid = strtol(getenv("EXTRA_VID"), NULL, 16);
	if (getenv("EXTRA_TYPE"))
		extra_type = atoi(getenv("EXTRA_TYPE"));
	if (getenv("BACKEND"))
		backend_str = getenv("BACKEND");
	if (getenv("FAST_RETURN"))
		fast_return++;
	if (getenv("MAX_XFER_SIZE"))
		max_xfer_size = atoi(getenv("MAX_XFER_SIZE"));
	if (getenv("XFER_TIMEOUT"))
		xfer_timeout = atoi(getenv("XFER_TIMEOUT"));
	if (getenv("TEST_MODE"))
		test_mode = atoi(getenv("TEST_MODE"));
	if (getenv("OLD_URI_SCHEME"))
		old_uri = atoi(getenv("OLD_URI_SCHEME"));
	if (getenv("CORRTABLE_PATH"))
		corrtable_path = getenv("CORRTABLE_PATH");

	if (test_mode >= TEST_MODE_NOATTACH && (extra_vid == -1 || extra_pid == -1)) {
		ERROR("Must specify EXTRA_VID, EXTRA_PID in test mode > 1!\n");
		exit(1);
	}

	if (stats_only)
		quiet = 1;

	DEBUG("Multi-Call Dye-sublimation CUPS Backend version %s\n",
	      BACKEND_VERSION);
	DEBUG("Copyright 2007-2020 Solomon Peachy\n");
	DEBUG("This free software comes with ABSOLUTELY NO WARRANTY! \n");
	DEBUG("Licensed under the GNU GPL.  Run with '-G' for more details.\n");
	DEBUG("\n");

	use_serno = getenv("SERIAL");
	uri = getenv("DEVICE_URI");  /* CUPS backend mode! */
	type = getenv("FINAL_CONTENT_TYPE"); /* CUPS content type -- ie raster or command */

	if (uri && strlen(uri)) {  /* CUPS backend mode */
		int base = optind; /* ie 1 */
		if (argc < 6) {
			ERROR("Insufficient arguments\n");
			exit(1);
		}
		if (argv[base])
			jobid = atoi(argv[base]);
		if (argv[base + 3])
			ncopies = atoi(argv[base + 3]);
		if (argc > 6)
			fname = argv[base + 5];
		else
			fname = "-";

		/* Figure out backend based on URI */
		{
			char *ptr2;
			backend_str = strstr(uri, "backend=");
			if (backend_str) { /* Original format */
				backend_str += 8;
				ptr2 = strchr(backend_str, '&');
				if (ptr2) {
					use_serno = strstr(ptr2, "serial=");
					*ptr2 = 0;
				}

				if (!use_serno)
					use_serno = strstr(uri, "serial=");

				if (!use_serno || !*(use_serno+7)) {
					ERROR("Invalid URI (%s)\n", uri);
					exit(1);
				}
				use_serno += 7;

			} else { /* New format */
				// prefix://backend/serno
				backend_str = strchr(uri, '/');
				backend_str += 2;
				use_serno = strchr(backend_str, '/');
				if (!use_serno || !*(use_serno+1)) {
					ERROR("Invalid URI (%s)\n", uri);
					exit(1);
				}
				*use_serno = 0;
				use_serno++;
			}

			if (use_serno) {
				ptr2 = strchr(use_serno, '&');
				if (ptr2)
					*ptr2 = 0;
			}
		}

		/* Always enable fast return in CUPS mode */
		fast_return++;

	} else {  /* Standalone mode */

		/* Try to guess backend from executable name */
		if (!backend_str) {
			backend_str = strrchr(argv[0], '/');
			if (backend_str)
				backend_str++;
			else
				backend_str = argv[0];
		}

		srand(getpid());
		jobid = rand();
	}

	/* Finally, look up the backend */
	backend = find_backend(backend_str);
	if (!backend) {
		if (uri && strlen(uri)) {
			ERROR("Invalid backend requested (%s)\n", backend_str);
			exit(1);
		}
		backend_str = NULL;
	}

#ifndef LIBUSB_PRE_1_0_10
	if (dyesub_debug) {
		const struct libusb_version *ver;
		ver = libusb_get_version();
		DEBUG(" ** running with libusb %d.%d.%d%s (%d)\n",
		      ver->major, ver->minor, ver->micro, (ver->rc? ver->rc : ""), ver->nano );
	}
#endif

	/* Libusb setup */
	ret = libusb_init(&ctx);
	if (ret) {
		ERROR("Failed to initialize libusb (%d)\n", ret);
		ret = CUPS_BACKEND_RETRY_CURRENT;
		goto done;
	}

	/* If we don't have a valid backend, print help and terminate */
	if (!backend && !stats_only) {
		print_help(argv[0], NULL); // probes all devices
		ret = CUPS_BACKEND_OK;
		goto done;
	}

	/* If we're in standalone mode, print help only if no args */
	if ((!uri || !strlen(uri)) && !stats_only) {
		if (argc < 2) {
			print_help(argv[0], backend); // probes all devices
			ret = CUPS_BACKEND_OK;
			goto done;
		}
	}

	/* Enumerate devices */
	found = find_and_enumerate(ctx, &list, backend, use_serno, backend_str, 0, NUM_CLAIM_ATTEMPTS, &conn);

	if (found == -1) {
		ERROR("Printer open failure (No matching printers found!)\n");
		ret = CUPS_BACKEND_RETRY;
		goto done;
	}

	if (test_mode) {
		WARNING("**** TEST MODE %d!\n", test_mode);
		if (test_mode >= TEST_MODE_NOATTACH)
			goto bypass;
	}

	/* Open an appropriate device */
	ret = libusb_open(list[found], &conn.dev);
	if (ret) {
		ERROR("Printer open failure (Need to be root?) (%d)\n", ret);
		ret = CUPS_BACKEND_RETRY_CURRENT;
		goto done;
	}

	/* Detach the kernel driver */
	if (libusb_kernel_driver_active(conn.dev, conn.iface)) {
		ret = libusb_detach_kernel_driver(conn.dev, conn.iface);
		if (ret && (ret != LIBUSB_ERROR_NOT_SUPPORTED)) {
			ERROR("Printer open failure (Could not detach printer from kernel) (%d)\n", ret);
			ret = CUPS_BACKEND_RETRY_CURRENT;
			goto done_close;
		}
	}

	/* Claim the interface so we can start using this! */
	ret = backend_claim_interface(conn.dev, conn.iface, NUM_CLAIM_ATTEMPTS);
	if (ret) {
		ERROR("Printer open failure (Unable to claim interface) (%d)\n", ret);
		ret = CUPS_BACKEND_RETRY;
		goto done_close;
	}

	/* Use the appropriate altesetting! */
	if (conn.altset != 0) {
		ret = libusb_set_interface_alt_setting(conn.dev, conn.iface, conn.altset);
		if (ret) {
			ERROR("Printer open failure (Unable to issue altsettinginterface) (%d)\n", ret);
			ret = CUPS_BACKEND_RETRY;
			goto done_claimed;
		}
	}

bypass:
	/* Initialize backend */
	DEBUG("Initializing '%s' backend (version %s)\n",
	      backend->name, backend->version);
	backend_ctx = backend->init();

	if (test_mode < TEST_MODE_NOATTACH) {
		struct libusb_device *device;
		struct libusb_device_descriptor desc;

		device = libusb_get_device(conn.dev);
		libusb_get_device_descriptor(device, &desc);

		conn.type = lookup_printer_type(backend,
						desc.idVendor, desc.idProduct);
	} else {
		conn.type = lookup_printer_type(backend,
						extra_vid, extra_pid);
	}

	if (conn.type <= P_UNKNOWN) {
		ERROR("Unable to lookup printer type\n");
		ret = CUPS_BACKEND_FAILED;
		goto done_claimed;
	}

	/* Attach backend to device */ // XXX pass backend_str?
	ret = backend->attach(backend_ctx, &conn, jobid);
	if (ret) {
		ERROR("Unable to attach to printer!\n");
		ret = CUPS_BACKEND_FAILED;
		goto done_claimed;
	}

//	STATE("+org.gutenprint.attached-to-device\n");

	/* Dump stats only */
	if (stats_only && backend->query_stats) {
		struct printerstats stats;
		memset(&stats, 0, sizeof(stats));

		stats.timestamp = time(NULL);
		ret = backend->query_stats(backend_ctx, &stats);
		if (ret)
			goto done_claimed;
		dump_stats(backend, &stats, stats_only -1);
		for (int i = 0 ; i < stats.decks ; i++) {
			if (stats.status[i])
				free(stats.status[i]); // the only dynamic member..
		}
		goto done_claimed;
	}

	if (!uri || !strlen(uri)) {
		if (backend->cmdline_arg(backend_ctx, argc, argv))
			goto done_claimed;

		/* Grab the filename */
		fname = argv[optind]; // XXX do this a smarter way?
	}

	/* Parse the file passed in */
	ret = handle_input(backend, backend_ctx, fname, uri, type);

done_claimed:
	if (test_mode < TEST_MODE_NOATTACH)
		libusb_release_interface(conn.dev, conn.iface);

done_close:
	if (test_mode < TEST_MODE_NOATTACH)
		libusb_close(conn.dev);
done:

	if (backend && backend_ctx) {
		if (backend->teardown)
			backend->teardown(backend_ctx);
		else
			generic_teardown(backend_ctx);
//		STATE("-org.gutenprint.attached-to-device");
	}

	if (list)
		libusb_free_device_list(list, 1);

	libusb_exit(ctx);

	return ret;
}

void dump_markers(const struct marker *markers, int marker_count, int full)
{
	int i;

	if (!full)
		goto minimal;

	ATTR("marker-colors=");
	for (i = 0 ; i < marker_count; i++) {
		DEBUG2("%s", markers[i].color);
		if ((i+1) < marker_count)
			DEBUG2(",");
	}
	DEBUG2("\n");

	ATTR("marker-high-levels=");
	for (i = 0 ; i < marker_count; i++) {
		DEBUG2("%d", 100);
		if ((i+1) < marker_count)
			DEBUG2(",");
	}
	DEBUG2("\n");

	ATTR("marker-low-levels=");
	for (i = 0 ; i < marker_count; i++) {
		DEBUG2("%d", 10);
		if ((i+1) < marker_count)
			DEBUG2(",");
	}
	DEBUG2("\n");

	ATTR("marker-names=");
	for (i = 0 ; i < marker_count; i++) {
		DEBUG2("'\"%s\"'", markers[i].name);
		if ((i+1) < marker_count)
			DEBUG2(",");
	}
	DEBUG2("\n");

	ATTR("marker-types=");
	for (i = 0 ; i < marker_count; i++) {
		DEBUG2("ribbonWax");
		if ((i+1) < marker_count)
			DEBUG2(",");
	}
	DEBUG2("\n");

minimal:
	ATTR("marker-levels=");
	for (i = 0 ; i < marker_count; i++) {
		int val;
		if (markers[i].levelmax <= 0 || markers[i].levelnow < 0)
			val = (markers[i].levelnow <= 0) ? markers[i].levelnow : CUPS_MARKER_UNAVAILABLE;
		else if (markers[i].levelmax == 100)
			val = markers[i].levelnow;
		else
			val = markers[i].levelnow * 100 / markers[i].levelmax;
		DEBUG2("%d", val);
		if ((i+1) < marker_count)
			DEBUG2(",");
	}
	DEBUG2("\n");

	/* Only dump a message if the marker is not a percentage */
	if (markers[0].levelmax != 100) {
		ATTR("marker-message=");
		for (i = 0 ; i < marker_count; i++) {
			switch (markers[i].levelnow) {
			case CUPS_MARKER_UNAVAILABLE:
				DEBUG2("'\"Unable to query remaining prints on %s media\"'", markers[i].name);
				break;
			case CUPS_MARKER_UNKNOWN:
				DEBUG2("'\"Unknown remaining prints on %s media\"'", markers[i].name);
				break;
			case CUPS_MARKER_UNKNOWN_OK:
				DEBUG2("'\"One or more remaining prints on %s media\"'", markers[i].name);
				break;
			default:
				DEBUG2("'\"%d native prints remaining on %s media\"'", markers[i].levelnow, markers[i].name);
				break;
			}
			if ((i+1) < marker_count)
				DEBUG2(",");
		}
		DEBUG2("\n");
	}

	if (markers[0].levelnow == 0)
		STATE("+media-empty\n");
	else if (markers[0].levelnow > 0 || markers[0].levelnow == CUPS_MARKER_UNKNOWN_OK)
		STATE("-media-empty\n");

	/* If we're running as a CUPS backend, report the media type */
	if (full && getenv("DEVICE_URI")) {
		for (i = 0 ; i < marker_count ; i++) {
			PPD("StpMediaID%d=%d\n", i, markers[i].numtype);
		}
	}
}

int dyesub_read_file(const char *filename, void *databuf, int datalen,
		     int *actual_len)
{
	int len;
	int fd = open(filename, O_RDONLY);

	if (fd < 0) {
		ERROR("Unable to open '%s'\n", filename);
		return CUPS_BACKEND_FAILED;
	}
	len = read(fd, databuf, datalen);
	if (len < 0) {
		ERROR("Bad Read! (%d/%d)\n", len, errno);
		close(fd);
		return CUPS_BACKEND_FAILED;
	}
	if (!actual_len && (datalen != len)) {
		ERROR("Read mismatch (%d vs %d)\n", len, datalen);
		close(fd);
		return CUPS_BACKEND_FAILED;
	}
	close(fd);

	if (actual_len)
		*actual_len = len;

	return CUPS_BACKEND_OK;
}

uint16_t uint16_to_packed_bcd(uint16_t val)
{
        uint16_t bcd;
        uint16_t i;

        /* Handle from 0-9999 */
        i = val % 10;
        bcd = i;
        val /= 10;
        i = val % 10;
        bcd |= (i << 4);
        val /= 10;
        i = val % 10;
        bcd |= (i << 8);
        val /= 10;
        i = val % 10;
        bcd |= (i << 12);

        return bcd;
}

uint32_t packed_bcd_to_uint32(const char *in, int len)
{
	uint32_t out = 0;

	while (len--) {
		out *= 10;
		out += ((*in >> 4) & 0xf);
		out *= 10;
		out += (*in & 0xf);
		in++;
	}
        return out;
}

/* Job list manipulation */
struct dyesub_joblist *dyesub_joblist_create(const struct dyesub_backend *backend, void *ctx)
{
	struct dyesub_joblist *list;

	list = malloc(sizeof(struct dyesub_joblist));
	if (!list) {
		ERROR("Memory allocation failure\n");
		return NULL;
	}
	list->backend = backend;
	list->ctx = ctx;
	list->num_entries = 0;

	if (collate)
		list->copies = ncopies;
	else
		list->copies = 1;

	return list;
}

void dyesub_joblist_cleanup(const struct dyesub_joblist *list)
{
	int i;
	for (i = 0; i < list->num_entries ; i++) {
		if (list->entries[i])
			list->backend->cleanup_job(list->entries[i]);
	}
	free((void*)list);
}

static int __dyesub_joblist_addjob(struct dyesub_joblist *list, const void *job)
{
	if (list->num_entries >= DYESUB_MAX_JOB_ENTRIES)
		return 1;

	list->entries[list->num_entries++] = job;

	return CUPS_BACKEND_OK;
}

static int __dyesub_append_job(struct dyesub_joblist *list, const void **vjob, int polarity)
{
	struct dyesub_job_common *job, *combined;
	const struct dyesub_job_common *oldjob;

	/* Create writable copy of the new job */
	job = malloc(((const struct dyesub_job_common *)*vjob)->jobsize);
	if (!job) {
		ERROR("Memory allocation failure!\n");
		return CUPS_BACKEND_RETRY_CURRENT;
	}
	memcpy(job, *vjob, ((const struct dyesub_job_common *)*vjob)->jobsize);

	/* If we can't combine the new job, don't bother doing anything else */
	if (!job->can_combine) {
		free(job);
		return CUPS_BACKEND_OK;
	}

	/* Get the old job */
	oldjob = dyesub_joblist_popjob(list);

	/* If we can't combine with it, carry on as before */
	if (oldjob && (oldjob->copies > 1 || !oldjob->can_combine)) {
		__dyesub_joblist_addjob(list, oldjob);
		oldjob = NULL;
	}

	if (oldjob) {
		/* Try to combine first copy with old job */
		combined = list->backend->combine_jobs(oldjob, job);
		if (combined) {
			INFO("Successfully combined two jobs\n");
			/* Success, add it to the list */
	                __dyesub_joblist_addjob(list, combined);
			combined = NULL;

			/* Clean up the old job */
			list->backend->cleanup_job(oldjob);

			/* Anything left in the new job? */
			job->copies--;
			if (job->copies == 0) {
				/* Nope, we're done */
				list->backend->cleanup_job(job);
			} else if (job->copies == 1) {
				/* Just one, shove it on the list */
				__dyesub_joblist_addjob(list, job);
			}

			goto done;
		} else {
			/* Failed to combine, restore old job and continue */
			__dyesub_joblist_addjob(list, oldjob);
		}

		polarity = 0;
	}

	/* If we have no work to do, just return */
	if (job->copies == 1) {
		free(job);
		return CUPS_BACKEND_OK;
	}

	/* Attempt to combine multiple copies! */
	combined = list->backend->combine_jobs(job, job);

	if (!combined) {
		/* Failed, so return */
		free(job);
		return CUPS_BACKEND_OK;
	}

	INFO("Successfully combined multiple copies\n");
	combined->copies = job->copies / 2;
	job->copies = job->copies % 2;

	/* Add the combined job at start if we can */
	if (!polarity) {
		__dyesub_joblist_addjob(list, combined);
	}

	/* Add the remainder, if any */
	if (job->copies) {
		__dyesub_joblist_addjob(list, job);
	} else {
		list->backend->cleanup_job(job);
	}

	/* Add combined job at end of we need to */
	if (polarity) {
		__dyesub_joblist_addjob(list, combined);
	}

done:
	/* Clean up */
	free((void*)*vjob);
	*vjob = NULL;

	return CUPS_BACKEND_OK;
}

int dyesub_joblist_appendjob(struct dyesub_joblist *list, const void *job)
{
	if (list->backend->combine_jobs) {
		int polarity = 0;
		if (list->backend->job_polarity)
			polarity = list->backend->job_polarity(list->ctx);
		__dyesub_append_job(list, &job, polarity);
	}

	if (job)
		__dyesub_joblist_addjob(list, job);

	return CUPS_BACKEND_OK;
}

const void *dyesub_joblist_popjob(struct dyesub_joblist *list)
{
	if (list->num_entries) {
		return list->entries[--list->num_entries];
	}

	return NULL;
}

int dyesub_joblist_canwait(struct dyesub_joblist *list)
{
	if (list->num_entries == DYESUB_MAX_JOB_ENTRIES)
		return 0;
	if (!list->num_entries)
		return 1;

	return ((const struct dyesub_job_common *)(list->entries[list->num_entries - 1]))->can_combine;
}

int dyesub_joblist_print(const struct dyesub_joblist *list, int *pagenum)
{
	int i, j;
	int ret;
//	int pages = 0;

	for (i = 0 ; i < list->copies ; i++) {
		for (j = 0 ; j < list->num_entries ; j++) {
			if (list->entries[j]) {
				int copies = ((const struct dyesub_job_common *)(list->entries[j]))->copies;

				INFO("Printing page %d (%d copies)\n", ++(*pagenum), copies);
				if (test_mode >= TEST_MODE_NOPRINT )
					WARNING("**** TEST MODE, bypassing printing!\n");

				/* Print this page */
				if (test_mode < TEST_MODE_NOPRINT ||
				    list->backend->flags & BACKEND_FLAG_DUMMYPRINT) {
					ret = list->backend->main_loop(list->ctx, list->entries[j]);
					if (ret)
						return ret;
				}

//				pages += copies;

				/* Dump a marker status update */
				ret = query_markers(list->backend, list->ctx, 0);
				if (ret)
					return ret;
#if 0
				/* Free up the job as we go along
				   if we're on the final copy */
				if (i + 1 == list->copies) {
					list->backend->cleanup_job(list->entries[j]);
					list->entries[j] = NULL;
				}
#endif
			}
		}
	}

//	INFO("Printed %d total pages/copies\n", pages);

	return CUPS_BACKEND_OK;
}