summaryrefslogtreecommitdiff
path: root/backend/usb-darwin.c
blob: dc628fea316d9d7dc7e8ed78af26b3f40e5de79c (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
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
/*
* "$Id: usb-darwin.c 6680 2007-07-16 18:46:16Z mike $"
*
* Copyright © 2005-2007 Apple Inc. All rights reserved.
*
* IMPORTANT:  This Apple software is supplied to you by Apple Computer,
* Inc. ("Apple") in consideration of your agreement to the following
* terms, and your use, installation, modification or redistribution of
* this Apple software constitutes acceptance of these terms.  If you do
* not agree with these terms, please do not use, install, modify or
* redistribute this Apple software.
*
* In consideration of your agreement to abide by the following terms, and
* subject to these terms, Apple grants you a personal, non-exclusive
* license, under Apple's copyrights in this original Apple software (the
* "Apple Software"), to use, reproduce, modify and redistribute the Apple
* Software, with or without modifications, in source and/or binary forms;
* provided that if you redistribute the Apple Software in its entirety and
* without modifications, you must retain this notice and the following
* text and disclaimers in all such redistributions of the Apple Software.
* Neither the name, trademarks, service marks or logos of Apple Computer,
* Inc. may be used to endorse or promote products derived from the Apple
* Software without specific prior written permission from Apple.  Except
* as expressly stated in this notice, no other rights or licenses, express
* or implied, are granted by Apple herein, including but not limited to
* any patent rights that may be infringed by your derivative works or by
* other works in which the Apple Software may be incorporated.
*
* The Apple Software is provided by Apple on an "AS IS" basis.  APPLE
* MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
* THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
* OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
*
* IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
* MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
* AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
* STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Contents:
*
*  list_devices()	- List all USB devices.
*  print_device()	- Print a file to a USB device.
*  sidechannel_thread() - Thread to handle side-channel requests.
*  read_thread()	- Thread to read the backchannel data on.
*  list_device_cb()	- list_device iterator callback.
*  find_device_cb()	- print_device iterator callback.
*  status_timer_cb()	- Status timer callback.
*  iterate_printers()	- Iterate over all the printers.
*  device_added()	- Device added notifier.
*  copy_deviceinfo()	- Copy strings from the 1284 device ID.
*  release_deviceinfo()	- Release deviceinfo strings.
*  load_classdriver()	- Load a classdriver.
*  unload_classdriver()	- Unload a classdriver.
*  load_printerdriver()	- Load vendor's classdriver.
*  registry_open()	- Open a connection to the printer.
*  registry_close()	- Close the connection to the printer.
*  copy_deviceid()	- Copy the 1284 device id string.
*  copy_devicestring()	- Copy the 1284 device id string.
*  copy_value_for_key()	- Copy value string associated with a key.
*  cfstr_create_trim()	- Create CFString and trim whitespace characters.
*  parse_options()	- Parse uri options.
*  setup_cfLanguage()	- Create AppleLanguages array from LANG environment var.
*  run_ppc_backend()	- Re-exec i386 backend as ppc.
*  sigterm_handler()	- SIGTERM handler.
*  next_line()		- Find the next line in a buffer.
*  parse_pserror()	- Scan the backchannel data for postscript errors.
*  get_device_id()	- Return IEEE-1284 device ID.
*/

/*
 * Include necessary headers.
 */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <sys/sysctl.h>
#include <libgen.h>
#include <mach/mach.h>
#include <mach/mach_error.h>
#include <mach/mach_time.h>
#include <cups/debug.h>
#include <cups/sidechannel.h>
#include <cups/i18n.h>

#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/usb/IOUSBLib.h>
#include <IOKit/IOCFPlugIn.h>

#include <pthread.h>


/*
 * WAIT_EOF_DELAY is number of seconds we'll wait for responses from
 * the printer after we've finished sending all the data
 */
#define WAIT_EOF_DELAY			7
#define WAIT_SIDE_DELAY			3
#define DEFAULT_TIMEOUT			60L

#define	USB_INTERFACE_KIND		CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID190)
#define kUSBLanguageEnglish		0x409

#define PRINTER_POLLING_INTERVAL	5			/* seconds */
#define INITIAL_LOG_INTERVAL		PRINTER_POLLING_INTERVAL
#define SUBSEQUENT_LOG_INTERVAL		3 * INITIAL_LOG_INTERVAL

#define kUSBPrinterClassTypeID		CFUUIDGetConstantUUIDWithBytes(NULL, 0x06, 0x04, 0x7D, 0x16, 0x53, 0xA2, 0x11, 0xD6, 0x92, 0x06, 0x00, 0x30, 0x65, 0x52, 0x45, 0x92)
#define	kUSBPrinterClassInterfaceID	CFUUIDGetConstantUUIDWithBytes(NULL, 0x03, 0x34, 0x6D, 0x74, 0x53, 0xA3, 0x11, 0xD6, 0x9E, 0xA1, 0x76, 0x30, 0x65, 0x52, 0x45, 0x92)

#define kUSBClassDriverProperty		CFSTR("USB Printing Class")

#define kUSBGenericTOPrinterClassDriver	CFSTR("/System/Library/Printers/Libraries/USBGenericTOPrintingClass.plugin")
#define kUSBPrinterClassDeviceNotOpen	-9664	/*kPMInvalidIOMContext*/


/*
 * Section 5.3 USB Printing Class spec
 */
#define kUSBPrintingSubclass			1
#define kUSBPrintingProtocolNoOpen		0
#define kUSBPrintingProtocolUnidirectional	1
#define kUSBPrintingProtocolBidirectional	2

typedef IOUSBInterfaceInterface190	**printer_interface_t;

typedef struct iodevice_request_s	/**** Device request ****/
{
  UInt8		requestType;
  UInt8		request;
  UInt16	value;
  UInt16	index;
  UInt16	length;
  void		*buffer;
} iodevice_request_t;

typedef union				/**** Centronics status byte ****/
{
  char		b;
  struct
  {
    unsigned	reserved0:2;
    unsigned	paperError:1;
    unsigned	select:1;
    unsigned	notError:1;
    unsigned	reserved1:3;
  } status;
} centronics_status_t;

typedef struct classdriver_s		/**** g.classdriver context ****/
{
  IUNKNOWN_C_GUTS;
  CFPlugInRef		plugin;			/* release plugin */
  IUnknownVTbl		**factory;		/* Factory */
  void			*vendorReference;	/* vendor class specific usage */
  UInt32		location;		/* unique location in bus topology */
  UInt8			interfaceNumber;	/* Interface number */
  UInt16		vendorID;		/* Vendor id */
  UInt16		productID;		/* Product id */
  printer_interface_t	interface;		/* identify the device to IOKit */
  UInt8		  	outpipe;		/* mandatory bulkOut pipe */
  UInt8			inpipe;			/* optional bulkIn pipe */

  /* general class requests */
  kern_return_t (*DeviceRequest)(struct classdriver_s **printer, iodevice_request_t *iorequest, UInt16 timeout);
  kern_return_t	(*GetString)(struct classdriver_s **printer, UInt8 whichString, UInt16 language, UInt16 timeout, CFStringRef *result);

  /* standard printer class requests */
  kern_return_t	(*SoftReset)(struct classdriver_s **printer, UInt16 timeout);
  kern_return_t	(*GetCentronicsStatus)(struct classdriver_s **printer, centronics_status_t *result, UInt16 timeout);
  kern_return_t	(*GetDeviceID)(struct classdriver_s **printer, CFStringRef *devid, UInt16 timeout);

  /* standard bulk device requests */
  kern_return_t (*ReadPipe)(struct classdriver_s **printer, UInt8 *buffer, UInt32 *count);
  kern_return_t (*WritePipe)(struct classdriver_s **printer, UInt8 *buffer, UInt32 *count, Boolean eoj);

  /* interface requests */
  kern_return_t (*Open)(struct classdriver_s **printer, UInt32 location, UInt8 protocol);
  kern_return_t (*Abort)(struct classdriver_s **printer);
  kern_return_t (*Close)(struct classdriver_s **printer);

  /* initialize and terminate */
  kern_return_t (*Initialize)(struct classdriver_s **printer, struct classdriver_s **baseclass);
  kern_return_t (*Terminate)(struct classdriver_s **printer);

} classdriver_t;

typedef Boolean (*iterator_callback_t)(void *refcon, io_service_t obj);

typedef struct iterator_reference_s	/**** Iterator reference data */
{
  iterator_callback_t callback;
  void		*userdata;
  Boolean	keepRunning;
} iterator_reference_t;

typedef struct globals_s
{
  io_service_t		printer_obj;
  classdriver_t		**classdriver;

  pthread_mutex_t	read_thread_mutex;
  pthread_cond_t	read_thread_cond;
  int			read_thread_stop;
  int			read_thread_done;

  pthread_mutex_t	readwrite_lock_mutex;
  pthread_cond_t	readwrite_lock_cond;
  int			readwrite_lock;

  CFStringRef		make;
  CFStringRef		model;
  CFStringRef		serial;
  UInt32		location;
  UInt8			interfaceNum;

  CFRunLoopTimerRef 	status_timer;

  int			print_fd;	/* File descriptor to print */
  ssize_t		print_bytes;	/* Print bytes read */

  Boolean		wait_eof;
  int			drain_output;	/* Drain all pending output */
  int			bidi_flag;	/* 0=unidirectional, 1=bidirectional */

  pthread_mutex_t	sidechannel_thread_mutex;
  pthread_cond_t	sidechannel_thread_cond;
  int			sidechannel_thread_stop;
  int			sidechannel_thread_done;
} globals_t;


/*
 * Globals...
 */

globals_t g = { 0 };			/* Globals */


/*
 * Local functions...
 */

static Boolean find_device_cb(void *refcon, io_service_t obj);
static Boolean list_device_cb(void *refcon, io_service_t obj);
static CFStringRef cfstr_create_trim(const char *cstr);
static CFStringRef copy_value_for_key(CFStringRef deviceID, CFStringRef *keys);
static kern_return_t load_classdriver(CFStringRef driverPath, printer_interface_t intf, classdriver_t ***printerDriver);
static kern_return_t load_printerdriver(CFStringRef *driverBundlePath);
static kern_return_t registry_close();
static kern_return_t registry_open(CFStringRef *driverBundlePath);
static kern_return_t unload_classdriver();
static OSStatus copy_deviceid(classdriver_t **printer, CFStringRef *deviceID);
static void *read_thread(void *reference);
static void *sidechannel_thread(void *reference);
static void copy_deviceinfo(CFStringRef deviceIDString, CFStringRef *make, CFStringRef *model, CFStringRef *serial);
static void copy_devicestring(io_service_t usbInterface, CFStringRef *deviceID, UInt32 *deviceLocation, UInt8 *interfaceNum);
static void device_added(void *userdata, io_iterator_t iterator);
static void get_device_id(cups_sc_status_t *status, char *data, int *datalen);
static void iterate_printers(iterator_callback_t callBack, void *userdata);
static void parse_options(const char *options, char *serial, int serial_size, UInt32 *location, Boolean *wait_eof);
static void release_deviceinfo(CFStringRef *make, CFStringRef *model, CFStringRef *serial);
static void setup_cfLanguage(void);
static void soft_reset();
static void status_timer_cb(CFRunLoopTimerRef timer, void *info);

#if defined(__i386__)
static pid_t	child_pid;					/* Child PID */
static void run_ppc_backend(int argc, char *argv[], int fd);	/* Starts child backend process running as a ppc executable */
static void sigterm_handler(int sig);				/* SIGTERM handler */
#endif /* __i386__ */

#ifdef PARSE_PS_ERRORS
static const char *next_line (const char *buffer);
static void parse_pserror (char *sockBuffer, int len);
#endif /* PARSE_PS_ERRORS */

#pragma mark -

/*
 * 'list_devices()' - List all USB devices.
 */

void list_devices()
{
  iterate_printers(list_device_cb, NULL);
}


/*
 * 'print_device()' - Print a file to a USB device.
 */

int					/* O - Exit status */
print_device(const char *uri,		/* I - Device URI */
             const char *hostname,	/* I - Hostname/manufacturer */
             const char *resource,	/* I - Resource/modelname */
	     const char *options,	/* I - Device options/serial number */
	     int        print_fd,	/* I - File descriptor to print */
	     int        copies,		/* I - Copies to print */
	     int	argc,		/* I - Number of command-line arguments (6 or 7) */
	     char	*argv[])	/* I - Command-line arguments */
{
  char		  serial[1024];		/* Serial number buffer */
  OSStatus	  status;		/* Function results */
  pthread_t	  read_thread_id,	/* Read thread */
		  sidechannel_thread_id;/* Side channel thread */
  char		  print_buffer[8192],	/* Print data buffer */
		  *print_ptr;		/* Pointer into print data buffer */
  UInt32	  location;		/* Unique location in bus topology */
  fd_set	  input_set;		/* Input set for select() */
  CFStringRef	  driverBundlePath;	/* Class driver path */
  int		  countdown,		/* Logging interval */
		  nfds;			/* Number of file descriptors */
  ssize_t	  total_bytes;		/* Total bytes written */
  UInt32	  bytes;		/* Bytes written */
  struct timeval  *timeout,		/* Timeout pointer */
		  stimeout;		/* Timeout for select() */
  struct timespec cond_timeout;		/* pthread condition timeout */

  setup_cfLanguage();

  parse_options(options, serial, sizeof(serial), &location, &g.wait_eof);

  if (resource[0] == '/')
    resource++;

  g.print_fd	= print_fd;
  g.make	= cfstr_create_trim(hostname);
  g.model	= cfstr_create_trim(resource);
  g.serial	= cfstr_create_trim(serial);
  g.location	= location;

  fputs("STATE: +connecting-to-device\n", stderr);

  countdown = INITIAL_LOG_INTERVAL;

  do
  {
    if (g.printer_obj)
    {
      IOObjectRelease(g.printer_obj);
      unload_classdriver(&g.classdriver);
      g.printer_obj = 0x0;
      g.classdriver = 0x0;
    }

    fprintf(stderr, "DEBUG: Looking for '%s %s'\n", hostname, resource);

    iterate_printers(find_device_cb, NULL);

    fputs("DEBUG: Opening connection\n", stderr);

    driverBundlePath = NULL;

    status = registry_open(&driverBundlePath);

#if defined(__i386__)
    /*
     * If we were unable to load the class drivers for this printer it's probably because they're ppc-only.
     * In this case try to fork & exec this backend as a ppc executable so we can use them...
     */
    if (status == -2)
    {
      run_ppc_backend(argc, argv, print_fd);
      /* Never returns here */
    }
#endif /* __i386__ */

    if (status ==  -2)
    {
     /*
      * If we still were unable to load the class drivers for this printer log
      * the error and stop the queue...
      */

      if (driverBundlePath == NULL || !CFStringGetCString(driverBundlePath, print_buffer, sizeof(print_buffer), kCFStringEncodingUTF8))
        strlcpy(print_buffer, "USB class driver", sizeof(print_buffer));

      fputs("STATE: +apple-missing-usbclassdriver-error\n", stderr);
      fprintf(stderr, _("FATAL: Could not load %s\n"), print_buffer);

      if (driverBundlePath)
	CFRelease(driverBundlePath);

      return CUPS_BACKEND_STOP;
    }

    if (driverBundlePath)
      CFRelease(driverBundlePath);

    if (status != noErr)
    {
      sleep(PRINTER_POLLING_INTERVAL);
      countdown -= PRINTER_POLLING_INTERVAL;
      if (countdown <= 0)
      {
	fprintf(stderr, _("INFO: Printer busy (status:0x%08x)\n"), (int)status);
	countdown = SUBSEQUENT_LOG_INTERVAL;	/* subsequent log entries, every 15 seconds */
      }
    }
  } while (status != noErr);

  fputs("STATE: -connecting-to-device\n", stderr);

  /*
   * Now that we are "connected" to the port, ignore SIGTERM so that we
   * can finish out any page data the driver sends (e.g. to eject the
   * current page...  Only ignore SIGTERM if we are printing data from
   * stdin (otherwise you can't cancel raw jobs...)
   */

  if (!print_fd)
  {
    struct sigaction	action;		/* POSIX signal action */


    memset(&action, 0, sizeof(action));

    sigemptyset(&action.sa_mask);
    action.sa_handler = SIG_IGN;
    sigaction(SIGTERM, &action, NULL);
  }

 /*
  * Start the side channel thread only if the descriptor is valid
  * (i.e. it's not when the backend is used for auto-setup)...
  */

  pthread_mutex_init(&g.readwrite_lock_mutex, NULL);
  pthread_cond_init(&g.readwrite_lock_cond, NULL);
  g.readwrite_lock = 1;

  FD_ZERO(&input_set);
  FD_SET(CUPS_SC_FD, &input_set);

  stimeout.tv_sec  = 0;
  stimeout.tv_usec = 0;

  if ((select(CUPS_SC_FD+1, &input_set, NULL, NULL, &stimeout)) >= 0)
  {
    g.sidechannel_thread_stop = 0;
    g.sidechannel_thread_done = 0;

    pthread_cond_init(&g.sidechannel_thread_cond, NULL);
    pthread_mutex_init(&g.sidechannel_thread_mutex, NULL);

    if (pthread_create(&sidechannel_thread_id, NULL, sidechannel_thread, NULL))
    {
      fputs(_("WARNING: Couldn't create side channel\n"), stderr);
      return CUPS_BACKEND_STOP;
    }
  }

 /*
  * Get the read thread going...
  */

  g.read_thread_stop = 0;
  g.read_thread_done = 0;

  pthread_cond_init(&g.read_thread_cond, NULL);
  pthread_mutex_init(&g.read_thread_mutex, NULL);

  if (pthread_create(&read_thread_id, NULL, read_thread, NULL))
  {
    fputs(_("WARNING: Couldn't create read channel\n"), stderr);
    return CUPS_BACKEND_STOP;
  }

 /*
  * The main thread sends the print file...
  */

  g.drain_output = 0;
  g.print_bytes	 = 0;
  total_bytes	 = 0;
  print_ptr	 = print_buffer;

  while (status == noErr && copies-- > 0)
  {
    fputs(_("INFO: Sending data\n"), stderr);

    if (print_fd != STDIN_FILENO)
    {
      fputs("PAGE: 1 1", stderr);
      lseek(print_fd, 0, SEEK_SET);
    }

    while (status == noErr)
    {
      FD_ZERO(&input_set);

      if (!g.print_bytes)
	FD_SET(print_fd, &input_set);

     /*
      * Calculate select timeout...
      *   If we have data waiting to send timeout is 100ms.
      *   else if we're draining print_fd timeout is 0.
      *   else we're waiting forever...
      */

      if (g.print_bytes)
      {
	stimeout.tv_sec  = 0;
	stimeout.tv_usec = 100000;		/* 100ms */
	timeout = &stimeout;
      }
      else if (g.drain_output)
      {
	stimeout.tv_sec  = 0;
	stimeout.tv_usec = 0;
	timeout = &stimeout;
      }
      else
	timeout = NULL;

     /*
      * I/O is unlocked around select...
      */

      pthread_mutex_lock(&g.readwrite_lock_mutex);
      g.readwrite_lock = 0;
      pthread_cond_signal(&g.readwrite_lock_cond);
      pthread_mutex_unlock(&g.readwrite_lock_mutex);

      nfds = select(print_fd + 1, &input_set, NULL, NULL, timeout);

     /*
      * Reacquire the lock...
      */

      pthread_mutex_lock(&g.readwrite_lock_mutex);
      while (g.readwrite_lock)
	pthread_cond_wait(&g.readwrite_lock_cond, &g.readwrite_lock_mutex);
      g.readwrite_lock = 1;
      pthread_mutex_unlock(&g.readwrite_lock_mutex);

      if (nfds < 0)
      {
	if (errno == EINTR && total_bytes == 0)
	{
	  fputs("DEBUG: Received an interrupt before any bytes were "
	        "written, aborting!\n", stderr);
          return (0);
	}
	else if (errno != EAGAIN)
	{
	 fprintf(stderr, _("ERROR: select() returned %d\n"), (int)errno);
	 return CUPS_BACKEND_STOP;
	}
      }

     /*
      * If drain output has finished send a response...
      */

      if (g.drain_output && !nfds && !g.print_bytes)
      {
	/* Send a response... */
	cupsSideChannelWrite(CUPS_SC_CMD_DRAIN_OUTPUT, CUPS_SC_STATUS_OK, NULL, 0, 1.0);
	g.drain_output = 0;
      }

     /*
      * Check if we have print data ready...
      */

      if (FD_ISSET(print_fd, &input_set))
      {
	g.print_bytes = read(print_fd, print_buffer, sizeof(print_buffer));

	if (g.print_bytes < 0)
	{
	 /*
	  * Read error - bail if we don't see EAGAIN or EINTR...
	  */

	  if (errno != EAGAIN || errno != EINTR)
	  {
	    perror("ERROR: Unable to read print data");
	    return CUPS_BACKEND_STOP;
	  }

	  g.print_bytes = 0;
	}
	else if (g.print_bytes == 0)
	{
	 /*
	  * End of file, break out of the loop...
	  */

	  break;
	}

	print_ptr = print_buffer;

	fprintf(stderr, "DEBUG: Read %d bytes of print data...\n",
		(int)g.print_bytes);
      }

      if (g.print_bytes)
      {
	bytes = g.print_bytes;

	status = (*g.classdriver)->WritePipe(g.classdriver, (UInt8*)print_ptr, &bytes, 0);

       /*
	* Ignore timeout errors...
	*/

	if (status == kIOUSBTransactionTimeout)
	{
	  status = 0;
	  bytes = 0;
	}

	if (status || bytes < 0)
	{
	 /*
	  * Write error - bail if we don't see an error we can retry...
	  */

	  OSStatus err = (*g.classdriver)->Abort(g.classdriver);
	  fprintf(stderr, _("ERROR: %ld: (canceled:%ld)\n"), (long)status, (long)err);
	  status = CUPS_BACKEND_STOP;
	  break;
	}

        fprintf(stderr, "DEBUG: Wrote %d bytes of print data...\n", (int)bytes);

        g.print_bytes -= bytes;
	print_ptr   += bytes;
	total_bytes += bytes;
      }

      if (print_fd != 0 && status == noErr)
	fprintf(stderr, "DEBUG: Sending print file, %lld bytes...\n",
		(off_t)total_bytes);
    }
  }

  fprintf(stderr, "DEBUG: Sent %lld bytes...\n", (off_t)total_bytes);

 /*
  * Wait for the side channel thread to exit...
  */

  close(CUPS_SC_FD);
  pthread_mutex_lock(&g.readwrite_lock_mutex);
  g.readwrite_lock = 0;
  pthread_cond_signal(&g.readwrite_lock_cond);
  pthread_mutex_unlock(&g.readwrite_lock_mutex);

  g.sidechannel_thread_stop = 1;
  pthread_mutex_lock(&g.sidechannel_thread_mutex);
  if (!g.sidechannel_thread_done)
  {
    cond_timeout.tv_sec  = time(NULL) + WAIT_SIDE_DELAY;
    cond_timeout.tv_nsec = 0;
    pthread_cond_timedwait(&g.sidechannel_thread_cond,
                           &g.sidechannel_thread_mutex, &cond_timeout);
  }
  pthread_mutex_unlock(&g.sidechannel_thread_mutex);

  pthread_join(sidechannel_thread_id, NULL);

  pthread_cond_destroy(&g.sidechannel_thread_cond);
  pthread_mutex_destroy(&g.sidechannel_thread_mutex);

  pthread_cond_destroy(&g.readwrite_lock_cond);
  pthread_mutex_destroy(&g.readwrite_lock_mutex);

 /*
  * Signal the read thread to stop...
  */

  g.read_thread_stop = 1;

 /*
  * Give the read thread WAIT_EOF_DELAY seconds to complete all the data. If
  * we are not signaled in that time then force the thread to exit by setting
  * the waiteof to be false. Plese note that this relies on us using the timeout
  * class driver.
  */

  pthread_mutex_lock(&g.read_thread_mutex);

  if (!g.read_thread_done)
  {
    cond_timeout.tv_sec = time(NULL) + WAIT_EOF_DELAY;
    cond_timeout.tv_nsec = 0;

    if (pthread_cond_timedwait(&g.read_thread_cond, &g.read_thread_mutex,
                               &cond_timeout) != 0)
      g.wait_eof = false;
  }
  pthread_mutex_unlock(&g.read_thread_mutex);

  pthread_join(read_thread_id, NULL);	/* wait for the read thread to return */

  pthread_cond_destroy(&g.read_thread_cond);
  pthread_mutex_destroy(&g.read_thread_mutex);

 /*
  * Close the connection and input file and general clean up...
  */

  registry_close();

  if (print_fd != STDIN_FILENO)
    close(print_fd);

  if (g.make != NULL)
    CFRelease(g.make);

  if (g.model != NULL)
    CFRelease(g.model);

  if (g.serial != NULL)
    CFRelease(g.serial);

  if (g.printer_obj != 0x0)
    IOObjectRelease(g.printer_obj);

  return status;
}


/*
 * 'read_thread()' - Thread to read the backchannel data on.
 */

static void *read_thread(void *reference)
{
  UInt8				readbuffer[512];
  UInt32			rbytes;
  kern_return_t			readstatus;
  struct mach_timebase_info	timeBaseInfo;
  uint64_t			start,
				delay;

  /* Calculate what 250 milliSeconds are in mach absolute time...
   */
  mach_timebase_info(&timeBaseInfo);
  delay = ((uint64_t)250000000 * (uint64_t)timeBaseInfo.denom) / (uint64_t)timeBaseInfo.numer;

  do
  {
   /*
    * Remember when we started so we can throttle the loop after the read call...
    */

    start = mach_absolute_time();

    rbytes = sizeof(readbuffer);
    readstatus = (*g.classdriver)->ReadPipe(g.classdriver, readbuffer, &rbytes);
    if (readstatus == kIOReturnSuccess && rbytes > 0)
    {
      cupsBackChannelWrite((char*)readbuffer, rbytes, 1.0);

      /* cntrl-d is echoed by the printer.
       * NOTES:
       *   Xerox Phaser 6250D doesn't echo the cntrl-d.
       *   Xerox Phaser 6250D doesn't always send the product query.
       */
      if (g.wait_eof && readbuffer[rbytes-1] == 0x4)
	break;

#ifdef PARSE_PS_ERRORS
      parse_pserror(readbuffer, rbytes);
#endif
    }

   /*
    * Make sure this loop executes no more than once every 250 miliseconds...
    */

    if ((readstatus != kIOReturnSuccess || rbytes == 0) && (g.wait_eof || !g.read_thread_stop))
      mach_wait_until(start + delay);

  } while (g.wait_eof || !g.read_thread_stop);	/* Abort from main thread tests error here */

 /*
  * Let the main thread know that we have completed the read thread...
  */

  pthread_mutex_lock(&g.read_thread_mutex);
  g.read_thread_done = 1;
  pthread_cond_signal(&g.read_thread_cond);
  pthread_mutex_unlock(&g.read_thread_mutex);

  return NULL;
}


/*
 * 'sidechannel_thread()' - Handle side-channel requests.
 */

static void*
sidechannel_thread(void *reference)
{
  cups_sc_command_t	command;	/* Request command */
  cups_sc_status_t	status;		/* Request/response status */
  char			data[2048];	/* Request/response data */
  int			datalen;	/* Request/response data size */


  do
  {
    datalen = sizeof(data);

    if (cupsSideChannelRead(&command, &status, data, &datalen, 1.0))
      continue;

    switch (command)
    {
      case CUPS_SC_CMD_SOFT_RESET:	/* Do a soft reset */
	  soft_reset();
	  cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, NULL, 0, 1.0);
	  break;

      case CUPS_SC_CMD_DRAIN_OUTPUT:	/* Drain all pending output */
	  g.drain_output = 1;
	  break;

      case CUPS_SC_CMD_GET_BIDI:		/* Is the connection bidirectional? */
	  data[0] = g.bidi_flag;
	  cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, data, 1, 1.0);
	  break;

      case CUPS_SC_CMD_GET_DEVICE_ID:	/* Return IEEE-1284 device ID */
	  datalen = sizeof(data);
	  get_device_id(&status, data, &datalen);
	  cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, data, datalen, 1.0);
	  break;

      case CUPS_SC_CMD_GET_STATE:		/* Return device state */
	  data[0] = CUPS_SC_STATE_ONLINE;
	  cupsSideChannelWrite(command, CUPS_SC_STATUS_OK, data, 1, 1.0);
	  break;

      default:
	  cupsSideChannelWrite(command, CUPS_SC_STATUS_NOT_IMPLEMENTED,
			       NULL, 0, 1.0);
	  break;
    }
  }
  while (!g.sidechannel_thread_stop);

  pthread_mutex_lock(&g.sidechannel_thread_mutex);
  g.sidechannel_thread_done = 1;
  pthread_cond_signal(&g.sidechannel_thread_cond);
  pthread_mutex_unlock(&g.sidechannel_thread_mutex);

  return NULL;
}


#pragma mark -
/*
 * 'iterate_printers()' - Iterate over all the printers.
 */

static void iterate_printers(iterator_callback_t callBack,
			     void *userdata)
{
  mach_port_t	masterPort = 0x0;
  kern_return_t kr = IOMasterPort (bootstrap_port, &masterPort);

  if (kr == kIOReturnSuccess && masterPort != 0x0)
  {
    io_iterator_t addIterator = 0x0;

    iterator_reference_t reference = { callBack, userdata, true };
    IONotificationPortRef addNotification = IONotificationPortCreate(masterPort);

    int klass = kUSBPrintingClass;
    int subklass = kUSBPrintingSubclass;

    CFNumberRef usb_klass = CFNumberCreate(NULL, kCFNumberIntType, &klass);
    CFNumberRef usb_subklass = CFNumberCreate(NULL, kCFNumberIntType, &subklass);
    CFMutableDictionaryRef usbPrinterMatchDictionary = IOServiceMatching(kIOUSBInterfaceClassName);

    CFDictionaryAddValue(usbPrinterMatchDictionary, CFSTR("bInterfaceClass"), usb_klass);
    CFDictionaryAddValue(usbPrinterMatchDictionary, CFSTR("bInterfaceSubClass"), usb_subklass);

    CFRelease(usb_klass);
    CFRelease(usb_subklass);

    kr = IOServiceAddMatchingNotification(addNotification, kIOMatchedNotification, usbPrinterMatchDictionary, &device_added, &reference, &addIterator);
    if (addIterator != 0x0)
    {
      device_added (&reference, addIterator);

      if (reference.keepRunning)
      {
	CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(addNotification), kCFRunLoopDefaultMode);
	CFRunLoopRun();
      }
      IOObjectRelease(addIterator);
    }
    mach_port_deallocate(mach_task_self(), masterPort);
  }
}


/*
 * 'device_added()' - Device added notifier.
 */

static void device_added(void *userdata,
			 io_iterator_t iterator)
{
  iterator_reference_t *reference = userdata;

  io_service_t obj;
  while (reference->keepRunning && (obj = IOIteratorNext(iterator)) != 0x0)
  {
    if (reference->callback != NULL)
      reference->keepRunning = reference->callback(reference->userdata, obj);

    IOObjectRelease(obj);
  }

  /* One last call to the call back now that we are not longer have printers left to iterate...
   */
  if (reference->keepRunning)
    reference->keepRunning = reference->callback(reference->userdata, 0x0);

  if (!reference->keepRunning)
    CFRunLoopStop(CFRunLoopGetCurrent());
}


/*
 * 'list_device_cb()' - list_device iterator callback.
 */

static Boolean list_device_cb(void *refcon,
			      io_service_t obj)
{
  Boolean keepRunning = (obj != 0x0);

  if (keepRunning)
  {
    CFStringRef deviceIDString = NULL;
    UInt32 deviceLocation = 0;
    UInt8	interfaceNum = 0;

    copy_devicestring(obj, &deviceIDString, &deviceLocation, &interfaceNum);
    if (deviceIDString != NULL)
    {
      CFStringRef make = NULL,  model = NULL, serial = NULL;
      char uristr[1024], makestr[1024], modelstr[1024], serialstr[1024];
      char optionsstr[1024], idstr[1024];

      copy_deviceinfo(deviceIDString, &make, &model, &serial);

      modelstr[0] = '/';

      CFStringGetCString(deviceIDString, idstr, sizeof(idstr),
                         kCFStringEncodingUTF8);

      if (make)
        CFStringGetCString(make, makestr, sizeof(makestr),
	                   kCFStringEncodingUTF8);
      else
        strcpy(makestr, "Unknown");

      if (model)
	CFStringGetCString(model, &modelstr[1], sizeof(modelstr)-1,
      			   kCFStringEncodingUTF8);
      else
        strcpy(modelstr + 1, "Printer");

      optionsstr[0] = '\0';
      if (serial != NULL)
      {
        CFStringGetCString(serial, serialstr, sizeof(serialstr), kCFStringEncodingUTF8);
	snprintf(optionsstr, sizeof(optionsstr), "?serial=%s", serialstr);
      }
      else if (deviceLocation != 0)
	snprintf(optionsstr, sizeof(optionsstr), "?location=%x", (unsigned)deviceLocation);

      httpAssembleURI(HTTP_URI_CODING_ALL, uristr, sizeof(uristr), "usb", NULL, makestr, 0, modelstr);
      strncat(uristr, optionsstr, sizeof(uristr));

     /*
      * Fix common HP 1284 bug...
      */

      if (!strcasecmp(makestr, "Hewlett-Packard"))
        strcpy(makestr, "HP");

      if (!strncasecmp(modelstr + 1, "hp ", 3))
        _cups_strcpy(modelstr + 1, modelstr + 4);

      printf("direct %s \"%s %s\" \"%s %s USB\" \"%s\"\n", uristr, makestr,
             &modelstr[1], makestr, &modelstr[1], idstr);

      release_deviceinfo(&make, &model, &serial);
      CFRelease(deviceIDString);
    }
  }

  return keepRunning;
}


/*
 * 'find_device_cb()' - print_device iterator callback.
 */

static Boolean find_device_cb(void *refcon,
			      io_service_t obj)
{
  Boolean keepLooking = true;

  if (obj != 0x0)
  {
    CFStringRef idString = NULL;
    UInt32 location = -1;
    UInt8	interfaceNum = 0;

    copy_devicestring(obj, &idString, &location, &interfaceNum);
    if (idString != NULL)
    {
      CFStringRef make = NULL,  model = NULL, serial = NULL;

      copy_deviceinfo(idString, &make, &model, &serial);
      if (CFStringCompare(make, g.make, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
      {
	if (CFStringCompare(model, g.model, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
	{
	  if (g.serial != NULL && CFStringGetLength(g.serial) > 0)
	  {
	    if (serial != NULL && CFStringCompare(serial, g.serial, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
	    {
	      IOObjectRetain(obj);
	      g.printer_obj = obj;
	      keepLooking = false;
	    }
	  }
	  else
	  {
	    if (g.printer_obj != 0)
	      IOObjectRelease(g.printer_obj);

	    g.printer_obj = obj;
	    IOObjectRetain(obj);

	    if (g.location == 0 || g.location == location)
	      keepLooking = false;
	  }
	  if ( !keepLooking )
		g.interfaceNum = interfaceNum;
	}
      }

      release_deviceinfo(&make, &model, &serial);
      CFRelease(idString);
    }
  }
  else
  {
    keepLooking = (g.printer_obj == 0);
    if (obj == 0x0 && keepLooking)
    {
      CFRunLoopTimerContext context = { 0, refcon, NULL, NULL, NULL };
      CFRunLoopTimerRef timer = CFRunLoopTimerCreate(NULL, CFAbsoluteTimeGetCurrent() + 1.0, 10, 0x0, 0x0, status_timer_cb, &context);
      if (timer != NULL)
      {
	CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode);
	g.status_timer = timer;
      }
    }
  }

  if (!keepLooking && g.status_timer != NULL)
  {
    fputs("STATE: -offline-error\n", stderr);
    fputs(_("INFO: Printer is now on-line.\n"), stderr);
    CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), g.status_timer, kCFRunLoopDefaultMode);
    CFRelease(g.status_timer);
    g.status_timer = NULL;
  }

  return keepLooking;
}


/*
 * 'status_timer_cb()' - Status timer callback.
 */

static void status_timer_cb(CFRunLoopTimerRef timer,
			    void *info)
{
  fputs("STATE: +offline-error\n", stderr);
  fputs(_("INFO: Printer is currently off-line.\n"), stderr);
}


#pragma mark -
/*
 * 'copy_deviceinfo()' - Copy strings from the 1284 device ID.
 */

static void copy_deviceinfo(CFStringRef deviceIDString,
			    CFStringRef *make,
			    CFStringRef *model,
			    CFStringRef *serial)
{
  CFStringRef modelKeys[]  = { CFSTR("MDL:"), CFSTR("MODEL:"), NULL };
  CFStringRef makeKeys[]   = { CFSTR("MFG:"), CFSTR("MANUFACTURER:"), NULL };
  CFStringRef serialKeys[] = { CFSTR("SN:"),  CFSTR("SERN:"), NULL };

  if (make != NULL)
    *make = copy_value_for_key(deviceIDString, makeKeys);
  if (model != NULL)
    *model = copy_value_for_key(deviceIDString, modelKeys);
  if (serial != NULL)
    *serial = copy_value_for_key(deviceIDString, serialKeys);
}


/*
 * 'release_deviceinfo()' - Release deviceinfo strings.
 */

static void release_deviceinfo(CFStringRef *make,
			       CFStringRef *model,
			       CFStringRef *serial)
{
  if (make != NULL && *make != NULL)
  {
    CFRelease(*make);
    *make = NULL;
  }

  if (model != NULL && *model != NULL)
  {
    CFRelease(*model);
    *model = NULL;
  }

  if (serial != NULL && *serial != NULL)
  {
    CFRelease(*serial);
    *serial = NULL;
  }
}


#pragma mark -
/*
 * 'load_classdriver()' - Load a classdriver.
 */

static kern_return_t load_classdriver(CFStringRef	    driverPath,
				      printer_interface_t   intf,
				      classdriver_t	    ***printerDriver)
{
  kern_return_t kr = kUSBPrinterClassDeviceNotOpen;
  classdriver_t **driver = NULL;
  CFStringRef bundle = (driverPath == NULL ? kUSBGenericTOPrinterClassDriver : driverPath);

  if (bundle != NULL)
  {
    CFURLRef url = CFURLCreateWithFileSystemPath(NULL, bundle, kCFURLPOSIXPathStyle, true);
    CFPlugInRef plugin = (url != NULL ? CFPlugInCreate(NULL, url) : NULL);

    if (url != NULL)
      CFRelease(url);

    if (plugin != NULL)
    {
      CFArrayRef factories = CFPlugInFindFactoriesForPlugInTypeInPlugIn(kUSBPrinterClassTypeID, plugin);
      if (factories != NULL && CFArrayGetCount(factories) > 0)
      {
	CFUUIDRef factoryID = CFArrayGetValueAtIndex(factories, 0);
	IUnknownVTbl **iunknown = CFPlugInInstanceCreate(NULL, factoryID, kUSBPrinterClassTypeID);
	if (iunknown != NULL)
	{
	  kr = (*iunknown)->QueryInterface(iunknown, CFUUIDGetUUIDBytes(kUSBPrinterClassInterfaceID), (LPVOID *)&driver);
	  if (kr == kIOReturnSuccess && driver != NULL)
	  {
	    classdriver_t **genericDriver = NULL;
	    if (driverPath != NULL && CFStringCompare(driverPath, kUSBGenericTOPrinterClassDriver, 0) != kCFCompareEqualTo)
	      kr = load_classdriver(NULL, intf, &genericDriver);

	    if (kr == kIOReturnSuccess)
	    {
	      (*driver)->interface = intf;
	      (*driver)->Initialize(driver, genericDriver);

	      (*driver)->plugin = plugin;
	      (*driver)->interface = intf;
	      *printerDriver = driver;
	    }
	  }
	  (*iunknown)->Release(iunknown);
	}
	CFRelease(factories);
      }
    }
  }

#ifdef DEBUG
  char bundlestr[1024];
  CFStringGetCString(bundle, bundlestr, sizeof(bundlestr), kCFStringEncodingUTF8);
  fprintf(stderr, "DEBUG: load_classdriver(%s) (kr:0x%08x)\n", bundlestr, (int)kr);
#endif /* DEBUG */

  return kr;
}


/*
 * 'unload_classdriver()' - Unload a classdriver.
 */

static kern_return_t unload_classdriver(classdriver_t ***classdriver)
{
  if (*classdriver != NULL)
  {
    (**classdriver)->Release(*classdriver);
    *classdriver = NULL;
  }

  return kIOReturnSuccess;
}


/*
 * 'load_printerdriver()' - Load vendor's classdriver.
 *
 * If driverBundlePath is not NULL on return it is the callers responsbility to release it!
 */

static kern_return_t load_printerdriver(CFStringRef *driverBundlePath)
{
  IOCFPlugInInterface	**iodev = NULL;
  SInt32		score;
  kern_return_t		kr;
  printer_interface_t	intf;
  HRESULT		res;

  kr = IOCreatePlugInInterfaceForService(g.printer_obj, kIOUSBInterfaceUserClientTypeID, kIOCFPlugInInterfaceID, &iodev, &score);
  if (kr == kIOReturnSuccess)
  {
    if ((res = (*iodev)->QueryInterface(iodev, USB_INTERFACE_KIND, (LPVOID *) &intf)) == noErr)
    {
      *driverBundlePath = IORegistryEntryCreateCFProperty(g.printer_obj, kUSBClassDriverProperty, NULL, kNilOptions);

      kr = load_classdriver(*driverBundlePath, intf, &g.classdriver);

      if (kr != kIOReturnSuccess)
	(*intf)->Release(intf);
    }
    IODestroyPlugInInterface(iodev);
  }
  return kr;
}


/*
 * 'registry_open()' - Open a connection to the printer.
 */

static kern_return_t registry_open(CFStringRef *driverBundlePath)
{
  g.bidi_flag = 0;	/* 0=unidirectional */

  kern_return_t kr = load_printerdriver(driverBundlePath);
  if (kr != kIOReturnSuccess)
    kr = -2;

  if (g.classdriver != NULL)
  {
  	(*g.classdriver)->interfaceNumber = g.interfaceNum;
    kr = (*g.classdriver)->Open(g.classdriver, g.location, kUSBPrintingProtocolBidirectional);
    if (kr != kIOReturnSuccess || (*g.classdriver)->interface == NULL)
    {
      kr = (*g.classdriver)->Open(g.classdriver, g.location, kUSBPrintingProtocolUnidirectional);
      if (kr == kIOReturnSuccess)
      {
	if ((*g.classdriver)->interface == NULL)
	{
	  (*g.classdriver)->Close(g.classdriver);
	  kr = -1;
	}
      }
    }
    else
      g.bidi_flag = 1;	/* 1=bidirectional */
  }

  if (kr != kIOReturnSuccess)
    unload_classdriver(&g.classdriver);

  return kr;
}


/*
 * 'registry_close()' - Close the connection to the printer.
 */

static kern_return_t registry_close()
{
  if (g.classdriver != NULL)
    (*g.classdriver)->Close(g.classdriver);

  unload_classdriver(&g.classdriver);
  return kIOReturnSuccess;
}


/*
 * 'copy_deviceid()' - Copy the 1284 device id string.
 */

static OSStatus copy_deviceid(classdriver_t **classdriver,
			      CFStringRef *deviceID)
{
  CFStringRef devID = NULL,

  deviceMake = NULL,
  deviceModel = NULL,
  deviceSerial = NULL;

  OSStatus err = (*classdriver)->GetDeviceID(classdriver, &devID, DEFAULT_TIMEOUT);

  copy_deviceinfo(devID, &deviceMake, &deviceModel, &deviceSerial);

  if (deviceMake == NULL || deviceModel == NULL || deviceSerial == NULL)
  {
    IOUSBDeviceDescriptor	desc;
    iodevice_request_t		request;

    request.requestType = USBmakebmRequestType(kUSBIn,  kUSBStandard, kUSBDevice);
    request.request = kUSBRqGetDescriptor;
    request.value = (kUSBDeviceDesc << 8) | 0;
    request.index = 0;
    request.length = sizeof(desc);
    request.buffer = &desc;
    err = (*classdriver)->DeviceRequest(classdriver, &request, DEFAULT_TIMEOUT);
    if (err == kIOReturnSuccess)
    {
      CFMutableStringRef newDevID = CFStringCreateMutable(NULL, 0);

      if (deviceMake == NULL)
      {
	CFStringRef data = NULL;
	err = (*classdriver)->GetString(classdriver, desc.iManufacturer, kUSBLanguageEnglish, DEFAULT_TIMEOUT, &data);
	if (data != NULL)
	{
	  CFStringAppendFormat(newDevID, NULL, CFSTR("MFG:%@;"), data);
	  CFRelease(data);
	}
      }

      if (deviceModel == NULL)
      {
	CFStringRef data = NULL;
	err = (*classdriver)->GetString(classdriver, desc.iProduct, kUSBLanguageEnglish, DEFAULT_TIMEOUT, &data);
	if (data != NULL)
	{
	  CFStringAppendFormat(newDevID, NULL, CFSTR("MDL:%@;"), data);
	  CFRelease(data);
	}
      }

      if (deviceSerial == NULL && desc.iSerialNumber != 0)
      {
	CFStringRef data = NULL;
	err = (*classdriver)->GetString(classdriver, desc.iSerialNumber, kUSBLanguageEnglish, DEFAULT_TIMEOUT, &data);
	if (data != NULL)
	{
	  CFStringAppendFormat(newDevID, NULL, CFSTR("SERN:%@;"), data);
	  CFRelease(data);
	}
      }

      if (devID != NULL)
      {
	CFStringAppend(newDevID, devID);
	CFRelease(devID);
      }

      *deviceID = newDevID;
    }
  }
  else
  {
    *deviceID = devID;
  }
  release_deviceinfo(&deviceMake, &deviceModel, &deviceSerial);

  return err;
}


/*
 * 'copy_devicestring()' - Copy the 1284 device id string.
 */

static void copy_devicestring(io_service_t usbInterface,
			      CFStringRef *deviceID,
			      UInt32 *deviceLocation,
			      UInt8	*interfaceNumber )
{
  IOCFPlugInInterface	**iodev = NULL;
  SInt32		score;
  kern_return_t		kr;
  printer_interface_t	intf;
  HRESULT		res;
  classdriver_t	**klassDriver = NULL;
  CFStringRef		driverBundlePath;

  if ((kr = IOCreatePlugInInterfaceForService(usbInterface,
					 kIOUSBInterfaceUserClientTypeID,
					 kIOCFPlugInInterfaceID,
					 &iodev, &score)) == kIOReturnSuccess)
  {
    if ((res = (*iodev)->QueryInterface(iodev, USB_INTERFACE_KIND, (LPVOID *)
					&intf)) == noErr)
    {
      (*intf)->GetLocationID(intf, deviceLocation);
      (*intf)->GetInterfaceNumber(intf, interfaceNumber);

      driverBundlePath = IORegistryEntryCreateCFProperty(usbInterface,
							 kUSBClassDriverProperty,
							 NULL, kNilOptions);

      kr = load_classdriver(driverBundlePath, intf, &klassDriver);

      if (kr != kIOReturnSuccess && driverBundlePath != NULL)
	kr = load_classdriver(NULL, intf, &klassDriver);

      if (kr == kIOReturnSuccess && klassDriver != NULL)
	  kr = copy_deviceid(klassDriver, deviceID);

      unload_classdriver(&klassDriver);

      if (driverBundlePath != NULL)
	CFRelease(driverBundlePath);

      /* (*intf)->Release(intf); */
    }
    IODestroyPlugInInterface(iodev);
  }
}


#pragma mark -
/*
 * 'copy_value_for_key()' - Copy value string associated with a key.
 */

static CFStringRef copy_value_for_key(CFStringRef deviceID,
				      CFStringRef *keys)
{
  CFStringRef	value = NULL;
  CFArrayRef	kvPairs = deviceID != NULL ? CFStringCreateArrayBySeparatingStrings(NULL, deviceID, CFSTR(";")) : NULL;
  CFIndex	max = kvPairs != NULL ? CFArrayGetCount(kvPairs) : 0;
  CFIndex	idx = 0;

  while (idx < max && value == NULL)
  {
    CFStringRef kvpair = CFArrayGetValueAtIndex(kvPairs, idx);
    CFIndex idxx = 0;
    while (keys[idxx] != NULL && value == NULL)
    {
      CFRange range = CFStringFind(kvpair, keys[idxx], kCFCompareCaseInsensitive);
      if (range.length != -1)
      {
	if (range.location != 0)
	{
	  CFMutableStringRef theString = CFStringCreateMutableCopy(NULL, 0, kvpair);
	  CFStringTrimWhitespace(theString);
	  range = CFStringFind(theString, keys[idxx], kCFCompareCaseInsensitive);
	  if (range.location == 0)
	    value = CFStringCreateWithSubstring(NULL, theString, CFRangeMake(range.length, CFStringGetLength(theString) - range.length));

	  CFRelease(theString);
	}
	else
	{
	  CFStringRef theString = CFStringCreateWithSubstring(NULL, kvpair, CFRangeMake(range.length, CFStringGetLength(kvpair) - range.length));
	  CFMutableStringRef theString2 = CFStringCreateMutableCopy(NULL, 0, theString);
	  CFRelease(theString);

	  CFStringTrimWhitespace(theString2);
	  value = theString2;
	}
      }
      idxx++;
    }
    idx++;
  }

  if (kvPairs != NULL)
    CFRelease(kvPairs);
  return value;
}


/*
 * 'cfstr_create_trim()' - Create CFString and trim whitespace characters.
 */

CFStringRef cfstr_create_trim(const char *cstr)
{
  CFStringRef		cfstr;
  CFMutableStringRef	cfmutablestr = NULL;

  if ((cfstr = CFStringCreateWithCString(NULL, cstr, kCFStringEncodingUTF8)) != NULL)
  {
    if ((cfmutablestr = CFStringCreateMutableCopy(NULL, 1024, cfstr)) != NULL)
      CFStringTrimWhitespace(cfmutablestr);

    CFRelease(cfstr);
  }
  return (CFStringRef) cfmutablestr;
}


#pragma mark -
/*
 * 'parse_options()' - Parse uri options.
 */

static void parse_options(const char *options,
			  char *serial,
			  int serial_size,
			  UInt32 *location,
			  Boolean *wait_eof)
{
  char	optionName[255],	/* Name of option */
	value[255],		/* Value of option */
	*ptr;			/* Pointer into name or value */

  if (serial)
    *serial = '\0';
  if (location)
    *location = 0;

  if (!options)
    return;

  while (*options != '\0')
  {
    /* Get the name... */
    for (ptr = optionName; *options && *options != '=' && *options != '+';)
      *ptr++ = *options++;

    *ptr = '\0';
    value[0] = '\0';

    if (*options == '=')
    {
      /* Get the value... */
      options ++;

      for (ptr = value; *options && *options != '+';)
	*ptr++ = *options++;

      *ptr = '\0';

      if (*options == '+')
	options ++;
    }
    else if (*options == '+')
      options ++;

    /*
     * Process the option...
     */
    if (strcasecmp(optionName, "waiteof") == 0)
    {
      if (strcasecmp(value, "on") == 0 ||
	  strcasecmp(value, "yes") == 0 ||
	  strcasecmp(value, "true") == 0)
	*wait_eof = true;
      else if (strcasecmp(value, "off")   == 0 ||
	       strcasecmp(value, "no")    == 0 ||
	       strcasecmp(value, "false") == 0)
	*wait_eof = false;
      else
	fprintf(stderr, _("WARNING: Boolean expected for waiteof option \"%s\"\n"), value);
    }
    else if (strcasecmp(optionName, "serial") == 0)
    {
      strlcpy(serial, value, serial_size);
    }
    else if (strcasecmp(optionName, "location") == 0 && location)
      *location = strtol(value, NULL, 16);
  }

  return;
}


/*!
 * @function	setup_cfLanguage
 * @abstract	Convert the contents of the CUPS 'LANG' environment
 *		variable into a one element CF array of languages.
 *
 * @discussion	Each submitted job comes with a natural language. CUPS passes
 * 		that language in an environment variable. We take that language
 * 		and jam it into the AppleLanguages array so that CF will use
 * 		it when reading localized resources. We need to do this before
 * 		any CF code reads and caches the languages array, so this function
 *		should be called early in main()
 */
static void setup_cfLanguage(void)
{
  CFStringRef	lang[1] = {NULL};
  CFArrayRef	langArray = NULL;
  const char	*requestedLang = NULL;

  requestedLang = getenv("LANG");
  if (requestedLang != NULL)
  {
    lang[0] = CFStringCreateWithCString(kCFAllocatorDefault, requestedLang, kCFStringEncodingUTF8);
    langArray = CFArrayCreate(kCFAllocatorDefault, (const void **)lang, sizeof(lang) / sizeof(lang[0]), &kCFTypeArrayCallBacks);

    CFPreferencesSetAppValue(CFSTR("AppleLanguages"), langArray, kCFPreferencesCurrentApplication);
    DEBUG_printf((stderr, "DEBUG: usb: AppleLanguages = \"%s\"\n", requestedLang));

    CFRelease(lang[0]);
    CFRelease(langArray);
  }
  else
    fputs("DEBUG: usb: LANG environment variable missing.\n", stderr);
}

#pragma mark -
#if defined(__i386__)
/*!
 * @function	run_ppc_backend
 *
 * @abstract	Starts child backend process running as a ppc executable.
 *
 * @result	Never returns; always calls exit().
 *
 * @discussion
 */
static void run_ppc_backend(int argc,
			    char *argv[],
			    int fd)
{
  int	i;
  int	exitstatus = 0;
  int	childstatus;
  pid_t	waitpid_status;
  char	*my_argv[32];
  char	*usb_ppc_status;

  /*
   * If we're running as i386 and couldn't load the class driver (because they'it's
   * ppc-only) then try to re-exec ourselves in ppc mode to try again. If we don't have
   * a ppc architecture we may be running i386 again so guard against this by setting
   * and testing an environment variable...
   */
  usb_ppc_status = getenv("USB_PPC_STATUS");

  if (usb_ppc_status == NULL)
  {
   /*
    * Setup a SIGTERM handler then block it before forking...
    */

    struct sigaction	action;		/* POSIX signal action */
    sigset_t		newmask,	/* New signal mask */
			oldmask;	/* Old signal mask */

    memset(&action, 0, sizeof(action));
    sigaddset(&action.sa_mask, SIGTERM);
    action.sa_handler = sigterm_handler;
    sigaction(SIGTERM, &action, NULL);

    sigemptyset(&newmask);
    sigaddset(&newmask, SIGTERM);
    sigprocmask(SIG_BLOCK, &newmask, &oldmask);

    if ((child_pid = fork()) == 0)
    {
     /*
      * Child comes here...
      */

      setenv("USB_PPC_STATUS", "1", false);

     /*
      * Unblock signals before doing the exec...
      */

      memset(&action, 0, sizeof(action));
      sigemptyset(&action.sa_mask);
      action.sa_handler = SIG_DFL;
      sigaction(SIGTERM, &action, NULL);

      sigprocmask(SIG_SETMASK, &oldmask, NULL);

     /*
      * Tell the kernel the next exec call should favor the ppc architecture...
      */

      int mib[] = { CTL_KERN, KERN_AFFINITY, 1, 1 };
      int namelen = 4;
      sysctl(mib, namelen, NULL, NULL, NULL, 0);

     /*
      * Set up the arguments and call exec...
      */

      for (i = 0; i < argc && i < (sizeof(my_argv)/sizeof(my_argv[0])) - 1; i++)
	my_argv[i] = argv[i];

      my_argv[i] = NULL;

      execv("/usr/libexec/cups/backend/usb", my_argv);

      perror("/usr/libexec/cups/backend/usb");
      exit(errno);
    }
    else if (child_pid < 0)
    {
     /*
      * Error - couldn't fork a new process!
      */

      perror("fork");
      exit(errno);
    }

   /*
    * Unblock signals...
    */

    sigprocmask(SIG_SETMASK, &oldmask, NULL);

   /*
    * Close the fds we won't be using then wait for the child backend to exit.
    */

    close(fd);
    close(1);

    fprintf(stderr, "DEBUG: Started usb(ppc) backend (PID %d)\n", (int)child_pid);

    while ((waitpid_status = waitpid(child_pid, &childstatus, 0)) == (pid_t)-1 && errno == EINTR)
      usleep(1000);

    if (WIFSIGNALED(childstatus))
    {
      exitstatus = WTERMSIG(childstatus);
      fprintf(stderr, "DEBUG: usb(ppc) backend %d crashed on signal %d!\n", child_pid, exitstatus);
    }
    else
    {
      if ((exitstatus = WEXITSTATUS(childstatus)) != 0)
	fprintf(stderr, "DEBUG: usb(ppc) backend %d stopped with status %d!\n", child_pid, exitstatus);
      else
	fprintf(stderr, "DEBUG: PID %d exited with no errors\n", child_pid);
    }
  }
  else
  {
    fputs("DEBUG: usb child running i386 again\n", stderr);
    exitstatus = ENOENT;
  }

  exit(exitstatus);
}

/*
 * 'sigterm_handler()' - SIGTERM handler.
 */

static void sigterm_handler(int sig)
{
  /* If we started a child process pass the signal on to it...
   */
  if (child_pid)
    kill(child_pid, sig);

  exit(1);
}

#endif /* __i386__ */


#ifdef PARSE_PS_ERRORS
/*
 * 'next_line()' - Find the next line in a buffer.
 */

static const char *next_line (const char *buffer)
{
  const char *cptr, *lptr = NULL;

  for (cptr = buffer; *cptr && lptr == NULL; cptr++)
    if (*cptr == '\n' || *cptr == '\r')
      lptr = cptr;
  return lptr;
}


/*
 * 'parse_pserror()' - Scan the backchannel data for postscript errors.
 */

static void parse_pserror(char *sockBuffer,
			  int len)
{
  static char  gErrorBuffer[1024] = "";
  static char *gErrorBufferPtr = gErrorBuffer;
  static char *gErrorBufferEndPtr = gErrorBuffer + sizeof(gErrorBuffer);

  char *pCommentBegin, *pCommentEnd, *pLineEnd;
  char *logLevel;
  char logstr[1024];
  int  logstrlen;

  if (gErrorBufferPtr + len > gErrorBufferEndPtr - 1)
    gErrorBufferPtr = gErrorBuffer;
  if (len > sizeof(gErrorBuffer) - 1)
    len = sizeof(gErrorBuffer) - 1;

  memcpy(gErrorBufferPtr, (const void *)sockBuffer, len);
  gErrorBufferPtr += len;
  *(gErrorBufferPtr + 1) = '\0';

  pLineEnd = (char *)next_line((const char *)gErrorBuffer);
  while (pLineEnd != NULL)
  {
    *pLineEnd++ = '\0';

    pCommentBegin = strstr(gErrorBuffer,"%%[");
    pCommentEnd = strstr(gErrorBuffer, "]%%");
    if (pCommentBegin != gErrorBuffer && pCommentEnd != NULL)
    {
      pCommentEnd += 3;            /* Skip past "]%%" */
      *pCommentEnd = '\0';         /* There's always room for the nul */

      if (strncasecmp(pCommentBegin, "%%[ Error:", 10) == 0)
	logLevel = "DEBUG";
      else if (strncasecmp(pCommentBegin, "%%[ Flushing", 12) == 0)
	logLevel = "DEBUG";
      else
	logLevel = "INFO";

      if ((logstrlen = snprintf(logstr, sizeof(logstr), "%s: %s\n", logLevel, pCommentBegin)) >= sizeof(logstr))
      {
	/* If the string was trucnated make sure it has a linefeed before the nul */
	logstrlen = sizeof(logstr) - 1;
	logstr[logstrlen - 1] = '\n';
      }
      write(STDERR_FILENO, logstr, logstrlen);
    }

    /* move everything over... */
    strcpy(gErrorBuffer, pLineEnd);
    gErrorBufferPtr = gErrorBuffer;
    pLineEnd = (char *)next_line((const char *)gErrorBuffer);
  }
}
#endif /* PARSE_PS_ERRORS */


/*
 * 'soft_reset'
 */

static void soft_reset()
{
  fd_set	  input_set;		/* Input set for select() */
  struct timeval  stimeout;		/* Timeout for select() */
  char		  buffer[2048];		/* Buffer */
  struct timespec cond_timeout;		/* pthread condition timeout */

 /*
  * Send an abort once a second until the I/O lock is released by the main thread...
  */

  pthread_mutex_lock(&g.readwrite_lock_mutex);
  while (g.readwrite_lock)
  {
    (*g.classdriver)->Abort(g.classdriver);

    cond_timeout.tv_sec = time(NULL) + 1;
    cond_timeout.tv_nsec = 0;

    pthread_cond_timedwait(&g.readwrite_lock_cond, &g.readwrite_lock_mutex, &cond_timeout);
  }

  g.readwrite_lock = 1;
  pthread_mutex_unlock(&g.readwrite_lock_mutex);

 /*
  * Flush bytes waiting on print_fd...
  */

  g.print_bytes = 0;

  FD_ZERO(&input_set);
  FD_SET(g.print_fd, &input_set);

  stimeout.tv_sec  = 0;
  stimeout.tv_usec = 0;

  while (select(g.print_fd+1, &input_set, NULL, NULL, &stimeout) > 0)
    if (read(g.print_fd, buffer, sizeof(buffer)) <= 0)
      break;

 /*
  * Send the reset...
  */

  (*g.classdriver)->SoftReset(g.classdriver, 0);

 /*
  * Release the I/O lock...
  */

  pthread_mutex_lock(&g.readwrite_lock_mutex);
  g.readwrite_lock = 0;
  pthread_cond_signal(&g.readwrite_lock_cond);
  pthread_mutex_unlock(&g.readwrite_lock_mutex);
}


/*
 * 'get_device_id()' - Return IEEE-1284 device ID.
 */

static void get_device_id(cups_sc_status_t *status,
			  char *data,
			  int *datalen)
{
  UInt32 deviceLocation = 0;
  UInt8	interfaceNum = 0;
  CFStringRef deviceIDString = NULL;

  /* GetDeviceID */
  copy_devicestring(g.printer_obj, &deviceIDString, &deviceLocation, &interfaceNum);
  if (deviceIDString)
  {
    CFStringGetCString(deviceIDString, data, *datalen, kCFStringEncodingUTF8);
    *datalen = strlen(data);
    CFRelease(deviceIDString);
  }
  *status  = CUPS_SC_STATUS_OK;
}


/*
 * End of "$Id: usb-darwin.c 6680 2007-07-16 18:46:16Z mike $".
 */