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
  
1976
  
1977
  
1978
  
1979
  
1980
  
1981
  
1982
  
1983
  
1984
  
1985
  
1986
  
1987
  
1988
  
1989
  
1990
  
1991
  
1992
  
1993
  
1994
  
1995
  
1996
  
1997
  
1998
  
1999
  
2000
  
2001
  
2002
  
2003
  
2004
  
2005
  
2006
  
2007
  
2008
  
2009
  
2010
  
2011
  
2012
  
2013
  
2014
  
2015
  
2016
  
2017
  
2018
  
2019
  
2020
  
2021
  
2022
  
2023
  
2024
  
2025
  
2026
  
2027
  
2028
  
2029
  
2030
  
2031
  
2032
  
2033
  
2034
  
2035
  
2036
  
2037
  
2038
  
2039
  
2040
  
2041
  
2042
  
2043
  
2044
  
2045
  
2046
  
2047
  
2048
  
2049
  
2050
  
2051
  
2052
  
2053
  
2054
  
2055
  
2056
  
2057
  
2058
  
2059
  
2060
  
2061
  
2062
  
2063
  
2064
  
2065
  
2066
  
2067
  
2068
  
2069
  
2070
  
2071
  
2072
  
2073
  
2074
  
2075
  
2076
  
2077
  
2078
  
2079
  
2080
  
2081
  
2082
  
2083
  
2084
  
2085
  
2086
  
2087
  
2088
  
2089
  
2090
  
2091
  
2092
  
2093
  
2094
  
2095
  
2096
  
2097
  
2098
  
2099
  
2100
  
2101
  
2102
  
2103
  
2104
  
2105
  
2106
  
2107
  
2108
  
2109
  
2110
  
2111
  
2112
  
2113
  
2114
  
2115
  
2116
  
2117
  
2118
  
2119
  
2120
  
2121
  
2122
  
2123
  
2124
  
2125
  
2126
  
2127
  
2128
  
2129
  
2130
  
2131
  
2132
  
2133
  
2134
  
2135
  
2136
  
2137
  
2138
  
2139
  
2140
  
2141
  
2142
  
2143
  
2144
  
2145
  
2146
  
2147
  
2148
  
2149
  
2150
  
2151
  
2152
  
2153
  
2154
  
2155
  
2156
  
2157
  
2158
  
2159
  
2160
  
2161
  
2162
  
2163
  
2164
  
2165
  
2166
  
2167
  
2168
  
2169
  
2170
  
2171
  
2172
  
2173
  
2174
  
2175
  
2176
  
2177
  
2178
  
2179
  
2180
  
2181
  
2182
  
2183
  
2184
  
2185
  
2186
  
2187
  
2188
  
2189
  
2190
  
2191
  
2192
  
2193
  
2194
  
2195
  
2196
  
2197
  
2198
  
2199
  
2200
  
2201
  
2202
  
2203
  
2204
  
2205
  
2206
  
2207
  
2208
  
2209
  
2210
  
2211
  
2212
  
2213
  
2214
  
2215
  
2216
  
2217
  
2218
  
2219
  
2220
  
2221
  
2222
  
2223
  
2224
  
2225
  
2226
  
2227
  
2228
  
2229
  
2230
  
2231
  
2232
  
2233
  
2234
  
2235
  
2236
  
2237
  
2238
  
2239
  
2240
  
2241
  
2242
  
2243
  
2244
  
2245
  
2246
  
2247
  
2248
  
2249
  
2250
  
2251
  
2252
  
2253
  
2254
  
2255
  
2256
  
2257
  
2258
  
2259
  
2260
  
2261
  
2262
  
2263
  
2264
  
2265
  
2266
  
2267
  
2268
  
2269
  
2270
  
2271
  
2272
  
2273
  
2274
  
2275
  
2276
  
2277
  
2278
  
2279
  
2280
  
2281
  
2282
  
2283
  
2284
  
2285
  
2286
  
2287
  
2288
  
2289
  
2290
  
2291
  
2292
  
2293
  
2294
  
2295
  
2296
  
2297
  
2298
  
2299
  
2300
  
2301
  
2302
  
2303
  
2304
  
2305
  
2306
  
2307
  
2308
  
2309
  
2310
  
2311
  
2312
  
2313
  
2314
  
2315
  
2316
  
2317
  
2318
  
2319
  
2320
  
2321
  
2322
  
2323
  
2324
  
2325
  
2326
  
2327
  
2328
  
2329
  
2330
  
2331
  
2332
  
2333
  
2334
  
2335
  
2336
  
2337
  
2338
  
2339
  
2340
  
2341
  
2342
  
2343
  
2344
  
2345
  
2346
  
2347
  
2348
  
2349
  
2350
  
2351
  
2352
  
2353
  
2354
  
2355
  
2356
  
2357
  
2358
  
2359
  
2360
  
2361
  
2362
  
2363
  
2364
  
2365
  
2366
  
2367
  
2368
  
2369
  
2370
  
2371
  
2372
  
2373
  
2374
  
2375
  
2376
  
2377
  
2378
  
2379
  
2380
  
2381
  
2382
  
2383
  
2384
  
2385
  
2386
  
2387
  
2388
  
2389
  
2390
  
2391
  
2392
  
2393
  
2394
  
2395
  
2396
  
2397
  
2398
  
2399
  
2400
  
2401
  
2402
  
2403
  
2404
  
2405
  
2406
  
2407
  
2408
  
2409
  
2410
  
2411
  
2412
  
2413
  
2414
  
2415
  
2416
  
2417
  
2418
  
2419
  
2420
  
2421
  
2422
  
2423
  
2424
  
2425
  
2426
  
2427
  
2428
  
2429
  
2430
  
2431
  
2432
  
2433
  
2434
  
2435
  
2436
  
2437
  
2438
  
2439
  
2440
  
2441
  
2442
  
2443
  
2444
  
2445
  
2446
  
2447
  
2448
  
2449
  
2450
  
2451
  
2452
  
2453
  
2454
  
2455
  
2456
  
2457
  
2458
  
2459
  
2460
  
2461
  
2462
  
2463
  
2464
  
2465
  
2466
  
2467
  
2468
  
2469
  
2470
  
2471
  
2472
  
2473
  
2474
  
2475
  
2476
  
2477
  
2478
  
2479
  
2480
  
2481
  
2482
  
2483
  
2484
  
2485
  
2486
  
2487
  
2488
  
2489
  
2490
  
2491
  
2492
  
2493
  
2494
  
2495
  
2496
  
2497
  
2498
  
2499
  
2500
  
2501
  
2502
  
2503
  
2504
  
2505
  
2506
  
2507
  
2508
  
2509
  
2510
  
2511
  
2512
  
2513
  
2514
  
2515
  
2516
  
2517
  
2518
  
2519
  
2520
  
2521
  
2522
  
2523
  
2524
  
2525
  
2526
  
2527
  
2528
  
2529
  
2530
  
2531
  
2532
  
2533
  
2534
  
2535
  
2536
  
2537
  
2538
  
2539
  
2540
  
2541
  
2542
  
2543
  
2544
  
2545
  
2546
  
2547
  
2548
  
2549
  
2550
  
2551
  
2552
  
2553
  
2554
  
2555
  
2556
  
2557
  
2558
  
2559
  
2560
  
2561
  
2562
  
2563
  
2564
  
2565
  
2566
  
2567
  
2568
  
2569
  
2570
  
2571
  
2572
  
2573
  
2574
  
2575
  
2576
  
2577
  
2578
  
2579
  
2580
  
2581
  
2582
  
2583
  
2584
  
2585
  
2586
  
2587
  
2588
  
2589
  
2590
  
2591
  
2592
  
2593
  
2594
  
2595
  
2596
  
2597
  
2598
  
2599
  
2600
  
2601
  
2602
  
2603
  
2604
  
2605
  
2606
  
2607
  
2608
  
2609
  
2610
  
2611
  
2612
  
2613
  
2614
  
2615
  
2616
  
2617
  
2618
  
2619
  
2620
  
2621
  
2622
  
2623
  
2624
  
2625
  
2626
  
2627
  
2628
  
2629
  
2630
  
2631
  
2632
  
2633
  
2634
  
2635
  
2636
  
2637
  
2638
  
2639
  
2640
  
2641
  
2642
  
2643
  
2644
  
2645
  
2646
  
2647
  
2648
  
2649
  
2650
  
2651
  
2652
  
2653
  
2654
  
2655
  
2656
  
2657
  
2658
  
2659
  
2660
  
2661
  
2662
  
2663
  
2664
  
2665
  
2666
  
2667
  
2668
  
2669
  
2670
  
2671
  
2672
  
2673
  
2674
  
2675
  
2676
  
2677
  
2678
  
2679
  
2680
  
2681
  
2682
  
2683
  
2684
  
2685
  
2686
  
2687
  
2688
  
2689
  
2690
  
2691
  
2692
  
2693
  
2694
  
2695
  
2696
  
2697
  
2698
  
2699
  
2700
  
2701
  
2702
  
2703
  
2704
  
2705
  
2706
  
2707
  
2708
  
2709
  
2710
  
2711
  
2712
  
2713
  
2714
  
2715
  
2716
  
2717
  
2718
  
2719
  
2720
  
2721
  
2722
  
2723
  
2724
  
2725
  
2726
  
2727
  
2728
  
2729
  
2730
  
2731
  
2732
  
2733
  
2734
  
2735
  
2736
  
2737
  
2738
  
2739
  
2740
  
2741
  
2742
  
2743
  
2744
  
2745
  
2746
  
2747
  
2748
  
2749
  
2750
  
2751
  
2752
  
2753
  
2754
  
2755
  
2756
  
2757
  
2758
  
2759
  
2760
  
2761
  
2762
  
2763
  
2764
  
2765
  
2766
  
2767
  
2768
  
2769
  
2770
  
2771
  
2772
  
2773
  
2774
  
2775
  
2776
  
2777
  
2778
  
2779
  
2780
  
2781
  
2782
  
2783
  
2784
  
2785
  
2786
  
2787
  
2788
  
2789
  
2790
  
2791
  
2792
  
2793
  
2794
  
2795
  
2796
  
2797
  
2798
  
2799
  
2800
  
2801
  
2802
  
2803
  
2804
  
2805
  
2806
  
2807
  
2808
  
2809
  
2810
  
2811
  
2812
  
2813
  
2814
  
2815
  
2816
  
2817
  
2818
  
2819
  
2820
  
2821
  
2822
  
2823
  
2824
  
2825
  
2826
  
2827
  
2828
  
2829
  
2830
  
2831
  
2832
  
2833
  
2834
  
2835
  
2836
  
2837
  
2838
  
2839
  
2840
  
2841
  
2842
  
2843
  
2844
  
2845
  
2846
  
2847
  
2848
  
2849
  
2850
  
2851
  
2852
  
2853
  
2854
  
2855
  
2856
  
2857
  
2858
  
2859
  
2860
  
2861
  
2862
  
2863
  
2864
  
2865
  
2866
  
2867
  
2868
  
2869
  
2870
  
2871
  
2872
  
2873
  
2874
  
2875
  
2876
  
2877
  
2878
  
2879
  
2880
  
2881
  
2882
  
2883
  
2884
  
2885
  
2886
  
2887
  
2888
  
2889
  
2890
  
2891
  
2892
  
2893
  
2894
  
2895
  
2896
  
2897
  
2898
  
2899
  
2900
  
2901
  
2902
  
2903
  
2904
  
2905
  
2906
  
2907
  
2908
  
2909
  
2910
  
2911
  
2912
  
2913
  
2914
  
2915
  
2916
  
2917
  
2918
  
2919
  
2920
  
2921
  
2922
  
2923
  
2924
  
2925
  
2926
  
2927
  
2928
  
2929
  
2930
  
2931
  
2932
  
2933
  
2934
  
2935
  
2936
  
2937
  
2938
  
2939
  
2940
  
2941
  
2942
  
2943
  
2944
  
2945
  
2946
  
2947
  
2948
  
2949
  
2950
  
2951
  
2952
  
2953
  
2954
  
2955
  
2956
  
2957
  
2958
  
2959
  
2960
  
2961
  
2962
  
2963
  
2964
  
2965
  
2966
  
2967
  
2968
  
2969
  
2970
  
2971
  
2972
  
2973
  
2974
  
2975
  
2976
  
2977
  
2978
  
2979
  
2980
  
2981
  
2982
  
2983
  
2984
  
2985
  
2986
  
2987
  
2988
  
2989
  
2990
  
2991
  
2992
  
2993
  
2994
  
2995
  
2996
  
2997
  
2998
  
2999
  
3000
  
3001
  
3002
  
3003
  
3004
  
3005
  
3006
  
3007
  
3008
  
3009
  
3010
  
3011
  
3012
  
3013
  
3014
  
3015
  
3016
  
3017
  
3018
  
3019
  
3020
  
3021
  
3022
  
3023
  
3024
  
3025
  
3026
  
3027
  
3028
  
3029
  
3030
  
3031
  
3032
  
3033
  
3034
  
3035
  
3036
  
3037
  
3038
  
3039
  
3040
  
3041
  
3042
  
3043
  
3044
  
3045
  
3046
  
3047
  
3048
  
3049
  
3050
  
3051
  
3052
  
3053
  
3054
  
3055
  
3056
  
3057
  
3058
  
3059
  
3060
  
3061
  
3062
  
3063
  
3064
  
3065
  
3066
  
3067
  
3068
  
3069
  
3070
  
3071
  
3072
  
3073
  
3074
  
3075
  
3076
  
3077
  
3078
  
3079
  
3080
  
3081
  
3082
  
3083
  
3084
  
3085
  
3086
  
3087
  
3088
  
3089
  
3090
  
3091
  
3092
  
3093
  
3094
  
3095
  
3096
  
3097
  
3098
  
3099
  
3100
  
3101
  
3102
  
3103
  
3104
  
3105
  
3106
  
3107
  
3108
  
3109
  
3110
  
3111
  
3112
  
3113
  
3114
  
3115
  
3116
  
3117
  
3118
  
3119
  
3120
  
3121
  
3122
  
3123
  
3124
  
3125
  
3126
  
3127
  
3128
  
3129
  
3130
  
3131
  
3132
  
3133
  
3134
  
3135
  
3136
  
3137
  
3138
  
3139
  
3140
  
3141
  
3142
  
3143
  
3144
  
3145
  
3146
  
3147
  
3148
  
3149
  
3150
  
3151
  
3152
  
3153
  
3154
  
3155
  
3156
  
3157
  
3158
  
3159
  
3160
  
3161
  
3162
  
3163
  
3164
  
3165
  
3166
  
3167
  
3168
  
3169
  
3170
  
3171
  
3172
  
3173
  
3174
  
3175
  
3176
  
3177
  
3178
  
3179
  
3180
  
3181
  
3182
  
3183
  
3184
  
3185
  
3186
  
3187
  
3188
  
3189
  
3190
  
3191
  
3192
  
3193
  
3194
  
3195
  
3196
  
3197
  
3198
  
3199
  
3200
  
3201
  
3202
  
3203
  
3204
  
3205
  
3206
  
3207
  
3208
  
3209
  
3210
  
3211
  
3212
  
3213
  
3214
  
3215
  
3216
  
3217
  
3218
  
3219
  
3220
  
3221
  
3222
  
3223
  
3224
  
3225
  
3226
  
3227
  
3228
  
3229
  
3230
  
3231
  
3232
  
3233
  
3234
  
3235
  
3236
  
3237
  
3238
  
3239
  
3240
  
3241
  
3242
  
3243
  
3244
  
3245
  
3246
  
3247
  
3248
  
3249
  
3250
  
3251
  
3252
  
3253
  
3254
  
3255
  
3256
  
3257
  
3258
  
3259
  
3260
  
3261
  
3262
  
3263
  
3264
  
3265
  
3266
  
3267
  
3268
  
3269
  
3270
  
3271
  
3272
  
3273
  
3274
  
3275
  
3276
  
3277
  
3278
  
3279
  
3280
  
3281
  
3282
  
3283
  
3284
  
3285
  
3286
  
3287
  
3288
  
3289
  
3290
  
3291
  
3292
  
3293
  
3294
  
3295
  
3296
  
3297
  
3298
  
3299
  
3300
  
3301
  
3302
  
3303
  
3304
  
3305
  
3306
  
3307
  
3308
  
3309
  
3310
  
3311
  
3312
  
3313
  
3314
  
3315
  
3316
  
3317
  
3318
  
3319
  
3320
  
3321
  
3322
  
3323
  
3324
  
3325
  
3326
  
3327
  
3328
  
3329
  
3330
  
3331
  
3332
  
3333
  
3334
  
3335
  
3336
  
3337
  
3338
  
3339
  
3340
  
3341
  
3342
  
3343
  
3344
  
3345
  
3346
  
3347
  
3348
  
3349
  
3350
  
3351
  
3352
  
3353
  
3354
  
3355
  
3356
  
3357
  
3358
  
3359
  
3360
  
3361
  
3362
  
3363
  
3364
  
3365
  
3366
  
3367
  
3368
  
3369
  
3370
  
3371
  
3372
  
3373
  
3374
  
3375
  
3376
  
3377
  
3378
  
3379
  
3380
  
3381
  
3382
  
3383
  
3384
  
3385
  
3386
  
3387
  
3388
  
3389
  
3390
  
3391
  
3392
  
3393
  
3394
  
3395
  
3396
  
3397
  
3398
  
3399
  
3400
  
3401
  
3402
  
3403
  
3404
  
3405
  
3406
  
3407
  
3408
  
3409
  
3410
  
3411
  
3412
  
3413
  
3414
  
3415
  
3416
  
3417
  
3418
  
3419
  
3420
  
3421
  
3422
  
3423
  
3424
  
3425
  
3426
  
3427
  
3428
  
3429
  
3430
  
3431
  
3432
  
3433
  
3434
  
3435
  
3436
  
3437
  
3438
  
3439
  
3440
  
3441
  
3442
  
3443
  
3444
  
3445
  
3446
  
3447
  
3448
  
3449
  
3450
  
3451
  
3452
  
3453
  
3454
  
3455
  
3456
  
3457
  
3458
  
3459
  
3460
  
3461
  
3462
  
3463
  
3464
  
3465
  
3466
  
3467
  
3468
  
3469
  
3470
  
3471
  
3472
  
3473
  
3474
  
3475
  
3476
  
3477
  
3478
  
3479
  
3480
  
3481
  
3482
  
3483
  
3484
  
3485
  
3486
  
3487
  
3488
  
3489
  
3490
  
3491
  
3492
  
3493
  
3494
  
3495
  
3496
  
3497
  
3498
  
3499
  
3500
  
3501
  
3502
  
3503
  
3504
  
3505
  
3506
  
3507
  
3508
  
3509
  
3510
  
3511
  
3512
  
3513
  
3514
  
3515
  
3516
  
3517
  
3518
  
3519
  
3520
  
3521
  
3522
  
3523
  
3524
  
3525
  
3526
  
3527
  
3528
  
3529
  
3530
  
3531
  
3532
  
3533
  
3534
  
3535
  
3536
  
3537
  
3538
  
3539
  
3540
  
3541
  
3542
  
3543
  
3544
  
3545
  
3546
  
3547
  
3548
  
3549
  
3550
  
3551
  
3552
  
3553
  
3554
  
3555
  
3556
  
3557
  
3558
  
3559
  
3560
  
3561
  
3562
  
3563
  
3564
  
3565
  
3566
  
3567
  
3568
  
3569
  
3570
  
3571
  
3572
  
3573
  
3574
  
3575
  
3576
  
3577
  
3578
  
3579
  
3580
  
3581
  
3582
  
3583
  
3584
  
3585
  
3586
  
3587
  
3588
  
3589
  
3590
  
3591
  
3592
  
3593
  
3594
  
3595
  
3596
  
3597
  
3598
  
3599
  
3600
  
3601
  
3602
  
3603
  
3604
  
3605
  
3606
  
3607
  
3608
  
3609
  
3610
  
3611
  
3612
  
3613
  
3614
  
3615
  
3616
  
3617
  
3618
  
3619
  
3620
  
3621
  
3622
  
3623
  
3624
  
3625
  
3626
  
3627
  
3628
  
3629
  
3630
  
3631
  
3632
  
3633
  
3634
  
3635
  
3636
  
3637
  
3638
  
3639
  
3640
  
3641
  
3642
  
3643
  
3644
  
3645
  
3646
  
3647
  
3648
  
3649
  
3650
  
3651
  
3652
  
3653
  
3654
  
3655
  
3656
  
3657
  
3658
  
3659
  
3660
  
3661
  
3662
  
3663
  
3664
  
3665
  
3666
  
3667
  
3668
  
3669
  
3670
  
3671
  
3672
  
3673
  
3674
  
3675
  
3676
  
3677
  
3678
  
3679
  
3680
  
3681
  
3682
  
#pike __REAL_VERSION__ 
 
inherit _Stdio; 
 
#ifdef SENDFILE_DEBUG 
#define SF_WERR(X) werror("Stdio.sendfile(): %s\n", X) 
#else 
#define SF_WERR(X) 
#endif 
 
//#define BACKEND_DEBUG 
#ifdef BACKEND_DEBUG 
#define BE_WERR(X ...) werror("FD %O: %s\n", _fd, sprintf(X)) 
#else 
#define BE_WERR(X ...) 
#endif 
 
// TRACK_OPEN_FILES is a debug tool to track down where a file is 
// currently opened from (see report_file_open_places). It's used 
// primarily when debugging on NT since an opened file can't be 
// renamed or removed there. 
#ifndef TRACK_OPEN_FILES 
#define register_open_file(file, id, backtrace) 
#define register_close_file(id) 
#endif 
 
constant LineIterator = __builtin.file_line_iterator; 
 
final constant DATA_CHUNK_SIZE = 64 * 1024; 
//! Size used in various places to divide incoming or outgoing data 
//! into chunks. 
 
//! The Stdio.Stream API. 
//! 
//! This class exists purely for typing reasons. 
//! 
//! Use in types in place of @[Stdio.File] where only blocking 
//! stream-oriented I/O is done with the object. 
//! 
//! This class lists the minimum functionality guaranteed to exist in 
//! all Stream objects. 
//! 
//! @seealso 
//! @[NonblockingStream], @[BlockFile], @[File], @[FILE] 
//! 
class Stream 
{ 
  //! 
  string read(int nbytes); 
 
  //! 
  int write(string data); 
 
  //! 
  void close(); 
 
  //! 
  optional string read_oob(int nbytes); 
  optional int write_oob(string data); 
  optional mapping(string:int) tcgetattr(); 
  optional int tcsetattr(mapping(string:int) attr, string|void when); 
} 
 
//! Argument to @[Stdio.File()->tcsetattr()]. 
//! 
//! Change immediately. 
constant TCSANOW = "TCSANOW"; 
 
//! Argument to @[Stdio.File()->tcsetattr()]. 
//! 
//! Change after all output has been written. 
constant TCSADRAIN = "TCSADRAIN"; 
 
//! Argument to @[Stdio.File()->tcsetattr()]. 
//! 
//! Change after all output has been written, 
//! and empty the input buffers. 
constant TCSAFLUSH = "TCSAFLUSH"; 
 
//! The Stdio.NonblockingStream API. 
//! 
//! This class exists purely for typing reasons. 
//! 
//! Use in types in place of @[Stdio.File] where nonblocking and/or 
//! blocking stream-oriented I/O is done with the object. 
//! 
//! @seealso 
//! @[Stream], @[BlockFile], @[File], @[FILE] 
//! 
class NonblockingStream 
{ 
  inherit Stream; 
 
  //! 
  NonblockingStream set_read_callback( function f, mixed ... rest ); 
  NonblockingStream set_write_callback( function f, mixed ... rest ); 
  NonblockingStream set_close_callback( function f, mixed ... rest ); 
  NonblockingStream set_fs_event_callback( function f, int event_mask, mixed ... rest ); 
 
  //! 
  optional NonblockingStream set_read_oob_callback(function f, mixed ... rest) 
  { 
    error("OOB not implemented for this stream type\n"); 
  } 
  optional NonblockingStream set_write_oob_callback(function f, mixed ... rest) 
  { 
    error("OOB not implemented for this stream type\n"); 
  } 
 
  //! 
  void set_nonblocking( function a, function b, function c, 
                        function|void d, function|void e); 
 
  //! 
  void set_blocking(); 
} 
 
//! The Stdio.BlockFile API. 
//! 
//! This class exists purely for typing reasons. 
//! 
//! Use in types in place of @[Stdio.File] where only blocking 
//! I/O is done with the object. 
//! 
//! @seealso 
//! @[Stream], @[NonblockingStream], @[File], @[FILE] 
//! 
class BlockFile 
{ 
  inherit Stream; 
 
  //! 
  int seek(int to, string|void how); 
 
  //! 
  int tell(); 
} 
 
//! The various read_callback signatures. 
//! 
//! The string (or void) version is used when buffer mode (see 
//! @[set_buffer_mode]) has not been enabled for reading. 
//! 
//! The @[Buffer] version is used when a @[Buffer] has been enabled 
//! for reading. 
//! 
//! In both cases the data is the newly arrived data, but in buffered 
//! mode data you did not fully read in the last read callback is 
//! kept in the buffer. 
local typedef 
  function(mixed|void,string:int|void)| 
  function(mixed|void,Buffer:int|void)| 
  function(mixed|void:int|void) read_callback_t; 
 
//! The various write_callback signatures. 
//! 
//! The void version is used when buffer mode (see 
//! @[set_buffer_mode]) has not been enabled for writing. 
//! 
//! The @[Buffer] version is used when a @[Buffer] has been enabled 
//! for writing, add data to that buffer to send it. 
local typedef 
  function(mixed|void:int|void) | 
  function(mixed|void,Buffer:int|void) write_callback_t; 
 
 
//! This is the basic I/O object, it provides socket and pipe 
//! communication as well as file access. It does not buffer reads and 
//! writes by default, and provides no line-by-line reading, that is done 
//! with @[Stdio.FILE] object. 
//! 
//! @note 
//! The file or stream will normally be closed when this object is 
//! destructed (unless there are more objects that refer to the same 
//! file through use of @[assign] or @[dup]). Objects do not contain 
//! cyclic references in themselves, so they will be destructed timely 
//! when they run out of references. 
//! 
//! @seealso 
//! @[Stdio.FILE] 
class File 
{ 
  optional inherit Fd; 
 
  // This is needed in case we get overloaded by strange code 
  // (socktest.pike). 
  protected Fd fd_factory() 
  { 
    return File()->_fd; 
  } 
 
  protected Stdio.Buffer inbuffer, outbuffer; 
 
  //! Toggle the file to Buffer mode. 
  //! 
  //! In this mode reading and writing will be done via Buffer 
  //! objects, in the directions you included buffers. 
  //! 
  //! @param in 
  //!   Input buffer. If this buffer is non-empty, its contents 
  //!   will be returned after any already received data. 
  //! 
  //! @param out 
  //!   Output buffer. If this buffer is non-empty, its contents 
  //!   will be sent after any data already queued for sending. 
  //! 
  //! @note 
  //!  Normally you call @[write] to re-trigger the write callback if 
  //!  you do not output anything in it (which will stop it from 
  //!  re-occuring again). 
  //! 
  //!  This will work with buffered output mode as well, but simply 
  //!  adding more data to the output buffer will work as well. 
  //! 
  //! @seealso 
  //!  @[query_buffer_mode()] 
  void set_buffer_mode( Stdio.Buffer|int(0..0) in,Stdio.Buffer|int(0..0) out ) 
  { 
    if (in && inbuffer && sizeof(inbuffer)) { 
      // Behave as if any data in the new buffer was appended 
      // to the old input buffer. 
      in->add(inbuffer->read(), in->read()); 
    } 
    inbuffer = in; 
    if (outbuffer) { 
      outbuffer->__fd_set_output( 0 ); 
      if (out && sizeof(outbuffer)) { 
        // Behave as if any data in the new output buffer was 
        // appended to the old output buffer. 
        out->add(outbuffer->read(), out->read()); 
      } 
    } 
    if( outbuffer = out ) 
      outbuffer->__fd_set_output( ::write ); 
  } 
 
  //! Get the active input and output buffers that have been 
  //! set with @[set_buffer_mode()] (if any). 
  //! 
  //! @returns 
  //!   Returns an array with two elements: 
  //!   @array 
  //!     @elem Stdio.Buffer 0 
  //!       The current input buffer. 
  //!     @elem Stdio.Buffer 1 
  //!       The current output buffer. 
  //!   @endarray 
  //! 
  //! @seealso 
  //!   @[set_buffer_mode()] 
  array(Stdio.Buffer|int(0..0)) query_buffer_mode() 
  { 
    return ({ inbuffer, outbuffer }); 
  } 
 
#ifdef TRACK_OPEN_FILES 
  /*protected*/ int open_file_id = next_open_file_id++; 
#endif 
 
  // FIXME: Is this variable used for anything? 
  int is_file; 
 
  protected read_callback_t ___read_callback; 
  protected write_callback_t ___write_callback; 
  protected function(mixed|void:int) ___close_callback; 
  protected function(mixed|void,string|void:int) ___read_oob_callback; 
  protected function(mixed|void:int) ___write_oob_callback; 
  protected function(mixed|void,int:int) ___fs_event_callback; 
  protected mixed ___id; 
 
#ifdef __STDIO_DEBUG 
  protected string __closed_backtrace; 
#define CHECK_OPEN()  do {                                            \ 
    if(!is_open())                                                      \ 
    {                                                                   \ 
      error( "Stdio.File(): line "+__LINE__+" on closed file.\n" +      \ 
             (__closed_backtrace ?                                      \ 
              sprintf("File was closed from:\n"                         \ 
                      "    %-=200s\n",                                  \ 
                      __closed_backtrace) :                             \ 
              "This file has never been open.\n" ) );                   \ 
    }                                                                   \ 
  } while(0) 
#else 
#define CHECK_OPEN() 
#endif 
 
  //! Returns the error code for the last command on this file. 
  //! Error code is normally cleared when a command is successful. 
  //! 
  int errno() 
  { 
    return ::errno(); 
  } 
 
  protected string|int debug_file; 
  protected string debug_mode; 
  protected int debug_bits; 
 
  optional void _setup_debug( string f, string m, int|void b ) 
  { 
    debug_file = f; 
    debug_mode = m; 
    debug_bits = b; 
  } 
 
  protected string _sprintf( int type, mapping flags ) 
  { 
    if(type!='O') return 0; 
    return sprintf("%O(%O, %O, %o /* fd=%d */)", 
                   this_program, 
                   debug_file, debug_mode, 
                   debug_bits||0777, 
                   _fd && is_open() ? query_fd() : -1 ); 
  } 
 
  // @decl int open(int fd, string mode) 
  //! @decl int open(string filename, string mode) 
  //! @decl int open(string filename, string mode, int mask) 
  //! 
  //! Open a file for read, write or append. The parameter @[mode] should 
  //! contain one or more of the following letters: 
  //! @string 
  //!   @value "r" 
  //!   Open file for reading. 
  //!   @value "w" 
  //!   Open file for writing. 
  //!   @value "a" 
  //!   Open file for append (use with @expr{"w"@}). 
  //!   @value "t" 
  //!   Truncate file at open (use with @expr{"w"@}). 
  //!   @value "c" 
  //!   Create file if it doesn't exist (use with @expr{"w"@}). 
  //!   @value "x" 
  //!   Fail if file already exists (use with @expr{"c"@}). 
  //! @endstring 
  //! 
  //! @[mode] should always contain at least one of the letters 
  //! @expr{"r"@} or @expr{"w"@}. 
  //! 
  //! The parameter @[mask] is protection bits to use if the file is 
  //! created. Default is @expr{0666@} (read+write for all in octal 
  //! notation). 
  //! 
  //! @returns 
  //! This function returns @expr{1@} for success, @expr{0@} otherwise. 
  //! 
  //! @seealso 
  //! @[close()], @[create()] 
  //! 
  int open(string file, string mode, void|int bits) 
  { 
    is_file = 1; 
#ifdef __STDIO_DEBUG 
    __closed_backtrace=0; 
#endif 
    if (undefinedp(bits)) bits=0666; 
    debug_file = file;  debug_mode = mode; 
    debug_bits = bits; 
    if (::open(file,mode,bits)) { 
      register_open_file (file, open_file_id, backtrace()); 
      fix_internal_callbacks(); 
      return 1; 
    } 
    return 0; 
  } 
 
#if constant(_Stdio.__HAVE_OPENPT__) 
  //! @decl int openpt(string mode) 
  //! 
  //! Open the master end of a pseudo-terminal pair.  The parameter 
  //! @[mode] should contain one or more of the following letters: 
  //! @string 
  //!   @value "r" 
  //!   Open terminal for reading. 
  //!   @value "w" 
  //!   Open terminal for writing. 
  //! @endstring 
  //! 
  //! @[mode] should always contain at least one of the letters 
  //! @expr{"r"@} or @expr{"w"@}. 
  //! 
  //! @seealso 
  //! @[grantpt()] 
  //! 
  int openpt(string mode) 
  { 
    is_file = 0; 
#ifdef __STDIO_DEBUG 
    __closed_backtrace=0; 
#endif 
    debug_file = "pty master";  debug_mode = mode; debug_bits=0; 
    if (::openpt(mode)) { 
      register_open_file ("pty master", open_file_id, backtrace()); 
      fix_internal_callbacks(); 
      return 1; 
    } 
    return 0; 
  } 
#endif 
 
  //! This makes this file into a socket ready for connections. The reason 
  //! for this function is so that you can set the socket to nonblocking 
  //! or blocking (default is blocking) before you call @[connect()]. 
  //! 
  //! @param port 
  //!   If you give a port number to this function, the socket will be 
  //!   bound to this port locally before connecting anywhere. This is 
  //!   only useful for some silly protocols like @b{FTP@}. The port can 
  //!   also be specified as a string, giving the name of the service 
  //!   associated with the port. Pass -1 to not specify a port (eg to 
  //!   bind only to an address). 
  //! 
  //! @param address 
  //!   You may specify an address to bind to if your machine has many IP 
  //!   numbers. 
  //! 
  //! @param family_hint 
  //!   A protocol family for the socket can be specified. If no family is 
  //!   specified, one which is appropriate for the address is automatically 
  //!   selected. Thus, there is normally no need to specify it.  If you 
  //!   do not want to specify a bind address, you can provide the address 
  //!   as a hint here instead, to allow the automatic selection to work 
  //!   anyway. 
  //! 
  //! @returns 
  //! This function returns 1 for success, 0 otherwise. 
  //! 
  //! @seealso 
  //! @[connect()], @[set_nonblocking()], @[set_blocking()] 
  //! 
  int open_socket(int|string|void port, string|void address, 
                  int|string|void family_hint) 
  { 
    is_file = 0; 
#ifdef __STDIO_DEBUG 
    __closed_backtrace=0; 
#endif 
    debug_file="socket"; 
    debug_mode=0; debug_bits=0; 
    int ok; 
    switch(query_num_arg()) { 
    case 0: 
      ok = ::open_socket(); 
      break; 
    case 1: 
      ok = ::open_socket(port); 
      break; 
    case 2: 
      ok = ::open_socket(port, address); 
      break; 
    default: 
      ok = ::open_socket(port, address, family_hint); 
      break; 
    } 
    if (ok) { 
      register_open_file ("socket", open_file_id, backtrace()); 
      fix_internal_callbacks(); 
    } 
    return ok; 
  } 
 
  //! Open a TCP/IP connection to the specified destination. 
  //! 
  //! In nonblocking mode, success is indicated with the write-callback, 
  //! and failure with the close-callback or the read_oob-callback. 
  //! 
  //! The @[host] argument is the hostname or IP number of the remote 
  //! machine. 
  //! 
  //! A local IP and port can be explicitly bound by specifying 
  //! @[client] and @[client_port]. 
  //! 
  //! If the @[data] argument is included the socket will use 
  //! TCP_FAST_OPEN if posible. In this mode the the function will 
  //! return the part of the data that has not been sent to the remote 
  //! server yet instead of 1 (you will have to use @[write] to send 
  //! this data). 
  //! 
  //! Note that TCP_FAST_OPEN requires server support, the connection 
  //! might fail even though the remote server exists. It might be 
  //! advisable to retry without TCP_FAST_OPEN (and remember this 
  //! fact) 
  //! 
  //! @returns 
  //! This function returns 1 or the remaining @[data] for success, 0 
  //! otherwise. 
  //! 
  //! @note 
  //! 
  //! In nonblocking mode @expr{0@} (zero) may be returned and 
  //! @[errno()] set to @expr{EWOULDBLOCK@} or @expr{WSAEWOULDBLOCK@}. 
  //! 
  //! This should not be regarded as a 
  //! connection failure. In nonblocking mode you need to wait for a 
  //! write or close callback before you know if the connection failed 
  //! or not. 
  //! 
  //! @seealso 
  //! @[query_address()], @[async_connect()], @[connect_unix()] 
  //! 
  variant int connect(string host, int(0..)|string port) 
  { 
#ifdef __STDIO_DEBUG 
    __closed_backtrace=0; 
#endif 
    is_file = 0; 
    debug_file = "socket"; 
    debug_mode = host+":"+port; 
    debug_bits = 0; 
    if(::connect(host, port)) 
    { 
      register_open_file ("socket", open_file_id, backtrace()); 
      fix_internal_callbacks(); 
      return 1; 
    } 
    return 0; 
  } 
  variant int connect(string host, int(0..)|string port, 
                      string client, int(0..)|string client_port) 
  { 
#ifdef __STDIO_DEBUG 
    __closed_backtrace=0; 
#endif 
    is_file = 0; 
    debug_file = "socket"; 
    debug_mode = host+":"+port; 
    debug_bits = 0; 
    if (::connect(host, port, client, client_port)) 
    { 
      register_open_file ("socket", open_file_id, backtrace()); 
      fix_internal_callbacks(); 
      return 1; 
    } 
    return 0; 
  } 
  variant string connect(string host, int(0..)|string port, string data) 
  { 
    return connect(host,port,0,0,data); 
  } 
  variant string connect(string host, int(0..)|string port, 
                         int(0..0)|string client, int(0..)|string client_port, 
                         string data) 
  { 
#ifdef __STDIO_DEBUG 
    __closed_backtrace=0; 
#endif 
    is_file = 0; 
    debug_file = "socket"; 
    debug_mode = host+":"+port; 
    debug_bits = 0; 
    if( (data = ::connect(host, port, client, client_port, data)) ) 
    { 
      register_open_file ("socket", open_file_id, backtrace()); 
      fix_internal_callbacks(); 
      return data; 
    } 
    return 0; 
  } 
 
#if constant(_Stdio.__HAVE_CONNECT_UNIX__) 
  int connect_unix(string path) 
  //! Open a UNIX domain socket connection to the specified destination. 
  //! 
  //! @returns 
  //!  Returns @expr{1@} on success, and @expr{0@} on failure. 
  //! 
  //! @note 
  //!  Nonblocking mode is not supported while connecting 
  { 
#ifdef __STDIO_DEBUG 
    __closed_backtrace=0; 
#endif 
    is_file = 0; 
    debug_file = "unix_socket"; 
    debug_mode = path; 
    debug_bits = 0; 
    if (::connect_unix( path )) { 
      register_open_file ("unix_socket", open_file_id, backtrace()); 
      fix_internal_callbacks(); 
      return 1; 
    } 
    return 0; 
  } 
#endif 
 
  private function(int, mixed ...:void) _async_cb; 
  private array(mixed) _async_args; 
  private void _async_check_cb(mixed|void ignored) 
  { 
    // Copy the args to avoid races. 
    function(int, mixed ...:void) cb = _async_cb; 
    array(mixed) args = _async_args; 
    _async_cb = 0; 
    _async_args = 0; 
    set_callbacks (0,0,0,0,0); 
    if (cb) { 
      if (is_open() && query_address()) { 
        // Connection OK. 
        cb(1, @args); 
      } else { 
        // Connection failed. 
        // Make sure the state is reset. 
        close(); 
        cb(0, @args); 
      } 
    } 
  } 
 
  //! Read (optionally buffered) data from a file or a stream. 
  //! 
  //! Proxy function for @[Fd::read()], that adds support for 
  //! the buffering configured by @[set_buffer_mode()] 
  //! 
  //! @seealso 
  //!   @[read_function()], @[write()], @[Fd::read()] 
  string(8bit) read(int|void nbytes, int(0..1)|void not_all) 
  { 
    if (inbuffer) { 
      if (!nbytes) return ""; 
      if (!sizeof(inbuffer) || (!not_all && sizeof(inbuffer) < nbytes)) { 
        // Try filling the buffer with the remaining wanted bytes. 
        if ((inbuffer->input_from(this, nbytes - sizeof(inbuffer)) < 0) && 
            !sizeof(inbuffer)) { 
          // Read error and no data in the buffer. 
          // Propagate errno. 
          _errno = predef::errno(); 
          return 0; 
        } 
      } 
      return inbuffer->try_read(nbytes); 
    } 
    return ::read(nbytes, not_all); 
  } 
 
  function(:string) read_function(int nbytes) 
  //! Returns a function that when called will call @[read] with 
  //! nbytes as argument. Can be used to get various callback 
  //! functions, eg for the fourth argument to 
  //! @[String.SplitIterator]. 
  { 
    return lambda() 
    { 
      return read(nbytes); 
    }; 
  } 
 
  String.SplitIterator|LineIterator line_iterator( int|void trim ) 
  //! Returns an iterator that will loop over the lines in this file. 
  //! If trim is true, all @tt{'\r'@} characters will be removed from 
  //! the input. 
  { 
    if( trim ) 
      return String.SplitIterator( "",(<'\n','\r'>),1, 
                                   read_function(DATA_CHUNK_SIZE)); 
    // This one is about twice as fast, but it's way less flexible. 
    return LineIterator( read_function(DATA_CHUNK_SIZE) ); 
  } 
 
 
  //! Open a TCP/IP connection asynchronously. 
  //! 
  //! This function is similar to @[connect()], but works asynchronously. 
  //! 
  //! @param host 
  //!   Hostname or IP to connect to. 
  //! 
  //! @param port 
  //!   Port number or service name to connect to. 
  //! 
  //! @param callback 
  //!   Function to be called on completion. 
  //!   The first argument will be @expr{1@} if a connection was 
  //!   successfully established, and @expr{0@} (zero) on failure. 
  //!   The rest of the arguments to @[callback] are passed 
  //!   verbatim from @[args]. 
  //! 
  //! @param args 
  //!   Extra arguments to pass to @[callback]. 
  //! 
  //! @returns 
  //!   Returns @expr{0@} on failure to open a socket, and @expr{1@} 
  //!   if @[callback] will be used. 
  //! 
  //! @note 
  //!   The socket may be opened with @[open_socket()] ahead of 
  //!   the call to this function, but it is not required. 
  //! 
  //! @note 
  //!   This object is put in callback mode by this function. For 
  //!   @[callback] to be called, the backend must be active. See e.g. 
  //!   @[set_read_callback] for more details about backends and 
  //!   callback mode. 
  //! 
  //! @note 
  //!   The socket will be in nonblocking state if the connection is 
  //!   successful, and any callbacks will be cleared. 
  //! 
  //! @seealso 
  //!   @[connect()], @[open_socket()], @[set_nonblocking()] 
  int async_connect(string host, int|string port, 
                    function(int, mixed ...:void) callback, 
                    mixed ... args) 
  { 
    if (!is_open() || 
        !::stat()->issock || 
        catch { throw(query_address()); }) { 
      // Open a new socket if: 
      //   o We don't have an fd. 
      //   o The fd isn't a socket. 
      //   o query_address() returns non zero (ie connected). 
      //   o query_address() throws an error (eg delayed UDP error) [bug 2691]. 
      // 
      // This code is here to support the socket being opened (and locally 
      // bound) by the calling code, to support eg FTP. 
      if (!open_socket(-1, 0, host)) { 
        // Out of sockets? 
        return 0; 
      } 
    } 
 
    _async_cb = callback; 
    _async_args = args; 
    set_nonblocking(0, _async_check_cb, _async_check_cb, _async_check_cb, 0); 
    mixed err; 
    int res; 
    if (err = catch(res = connect(host, port))) { 
      // Illegal format. -- Bad hostname? 
      set_callbacks (0, 0, 0, 0, 0); 
      call_out(_async_check_cb, 0); 
    } else if (!res) { 
      // Connect failed. 
      set_callbacks (0, 0, 0, 0, 0); 
      call_out(_async_check_cb, 0); 
    } 
    return 1;       // OK so far. (Or rather the callback will be used). 
  } 
 
  //! This function creates a pipe between the object it was called in 
  //! and an object that is returned. 
  //! 
  //! @param required_properties 
  //!   Binary or (@[predef::`|()]) of required @expr{PROP_@} properties. 
  //!   @int 
  //!     @value PROP_IPC 
  //!       The resulting pipe may be used for inter process communication. 
  //!     @value PROP_NONBLOCK 
  //!       The resulting pipe supports nonblocking I/O. 
  //!     @value PROP_SHUTDOWN 
  //!       The resulting pipe supports shutting down transmission in either 
  //!       direction (see @[close()]). 
  //!     @value PROP_BUFFERED 
  //!       The resulting pipe is buffered (usually 4KB). 
  //!     @value PROP_BIDIRECTIONAL 
  //!       The resulting pipe is bi-directional. 
  //!     @value PROP_SEND_FD 
  //!       The resulting pipe might support sending of file descriptors 
  //!       (see @[send_fd()] and @[receive_fd()] for details). 
  //!     @value PROP_REVERSE 
  //!       The resulting pipe supports communication "backwards" (but 
  //!       not necessarily "forwards", see @[PROP_BIDIRECTIONAL]). 
  //!   @endint 
  //!   The default is @expr{PROP_NONBLOCK|PROP_BIDIRECTIONAL@}. 
  //! 
  //! If @[PROP_BIDIRECTIONAL] isn't specified, the read-end is this 
  //! object, and the write-end is the returned object (unless 
  //! @[PROP_REVERSE] has been specified, in which case it is the other 
  //! way around). 
  //! 
  //! The two ends of a bi-directional pipe are indistinguishable. 
  //! 
  //! If the File object this function is called in was open to begin with, 
  //! it will be closed before the pipe is created. 
  //! 
  //! @note 
  //!   Calling this function with an argument of @tt{0@} is not the 
  //!   same as calling it with no arguments. 
  //! 
  //! @seealso 
  //!   @[Process.create_process()], @[send_fd()], @[receive_fd()], 
  //!   @[PROP_IPC], @[PROP_NONBLOCK], @[PROP_SEND_FD], 
  //!   @[PROP_SHUTDOWN], @[PROP_BUFFERED], @[PROP_REVERSE], 
  //!   @[PROP_BIDIRECTIONAL] 
  //! 
  File pipe(void|int required_properties) 
  { 
#ifdef __STDIO_DEBUG 
    __closed_backtrace=0; 
#endif 
    is_file = 0; 
    if(query_num_arg()==0) 
      required_properties=PROP_NONBLOCK | PROP_BIDIRECTIONAL; 
    if(Fd fd = ::pipe(required_properties)) 
    { 
      File o = function_object(fd->read); 
      o->_setup_debug( "pipe", 0 ); 
      register_open_file ("pipe", open_file_id, backtrace()); 
      register_open_file ("pipe", o->open_file_id, backtrace()); 
      fix_internal_callbacks(); 
      return o; 
    } 
    return 0; 
  } 
 
#if constant(_Stdio.__HAVE_OPENAT__) 
  //! @decl File openat(string filename, string mode) 
  //! @decl File openat(string filename, string mode, int mask) 
  //! 
  //! Open a file relative to an open directory. 
  //! 
  //! @seealso 
  //!   @[File.statat()], @[File.unlinkat()] 
  File openat(string filename, string mode, int|void mask) 
  { 
    if(query_num_arg()<3) 
      mask = 0777; 
    if(Fd fd = ::openat(filename, mode, mask)) 
    { 
      File o = function_object(fd->read); 
      string path = combine_path(debug_file||"", filename); 
      o->_setup_debug(path, mode, mask); 
      register_open_file(path, o->open_file_id, backtrace()); 
      return o; 
    } 
    return 0; 
  } 
#endif 
 
#if constant(_Stdio.__HAVE_SEND_FD__) 
  //! 
  void send_fd(File|Fd file) 
  { 
    ::send_fd(file->_fd); 
  } 
#endif 
 
  //! @decl void create() 
  //! @decl void create(string filename) 
  //! @decl void create(string filename, string mode) 
  //! @decl void create(string filename, string mode, int mask) 
  //! @decl void create(string descriptorname) 
  //! @decl void create(int fd) 
  //! @decl void create(int fd, string mode) 
  //! 
  //! There are four basic ways to create a Stdio.File object. 
  //! The first is calling it without any arguments, in which case the you'd 
  //! have to call @[open()], @[connect()] or some other method which connects 
  //! the File object with a stream. 
  //! 
  //! The second way is calling it with a @[filename] and open @[mode]. This is 
  //! the same thing as cloning and then calling @[open()], except shorter and 
  //! faster. 
  //! 
  //! The third way is to call it with @[descriptorname] of @expr{"stdin"@}, 
  //! @expr{"stdout"@} or @expr{"stderr"@}. This will open the specified 
  //! standard stream. 
  //! 
  //! For the advanced users, you can use the file descriptors of the 
  //! systems (note: emulated by pike on some systems - like NT). This is 
  //! only useful for streaming purposes on unix systems. This is @b{not 
  //! recommended at all@} if you don't know what you're into. Default 
  //! @[mode] for this is @expr{"rw"@}. 
  //! 
  //! @note 
  //! Open mode will be filtered through the system UMASK. You 
  //! might need to use @[chmod()] later. 
  //! 
  //! @seealso 
  //! @[open()], @[connect()], @[Stdio.FILE], 
  protected void create(int|string|void file,void|string mode,void|int bits) 
  { 
    if (undefinedp(file)) 
      return; 
 
    debug_file = file; 
    debug_mode = mode; 
    debug_bits = bits; 
    switch(file) 
    { 
      case "stdin": 
        create(0, mode, bits); 
        break; 
 
      case "stdout": 
        create(1, mode, bits); 
        break; 
 
      case "stderr": 
        create(2, mode, bits); 
        break; 
 
      case 0..0x7fffffff: 
        if (!mode) mode="rw"; 
        ::create(file, mode); 
        register_open_file ("fd " + file, open_file_id, backtrace()); 
#ifdef __STDIO_DEBUG 
      __closed_backtrace=0; 
#endif 
      break; 
 
      default: 
        is_file = 1; 
#ifdef __STDIO_DEBUG 
      __closed_backtrace=0; 
#endif 
      if(query_num_arg()<3) bits=0666; 
        if(!mode) mode="r"; 
        if (!::open(file,mode,bits)) 
          error("Failed to open %O mode %O : %s.\n", file, mode, 
                strerror(errno())); 
        register_open_file (file, open_file_id, backtrace()); 
        break; 
    } 
  } 
 
  //! This function takes a clone of Stdio.File and assigns all 
  //! variables of this file from it. It can be used together with @[dup()] 
  //! to move files around. 
  //! 
  //! @seealso 
  //! @[dup()] 
  //! 
  int assign(File|Fd o) 
  { 
    BE_WERR("assign()\n"); 
    is_file = o->is_file; 
    o->dup2(_fd); 
    return 0; 
  } 
 
  //! This function returns a clone of Stdio.File with all variables 
  //! copied from this file. 
  //! 
  //! @note 
  //! All variables, even @tt{id@}, are copied. 
  //! 
  //! @seealso 
  //! @[assign()] 
  File dup() 
  { 
    BE_WERR("dup()\n"); 
    return function_object(::dup()->read); 
  } 
 
 
  //! @decl int close() 
  //! @decl int close(string direction) 
  //! 
  //! Close the file. Optionally, specify "r", "w" or "rw" to close just 
  //! the read, just the write or both read and write directions of the file 
  //! respectively. 
  //! 
  //! An exception is thrown if an I/O error occurs. 
  //! 
  //! @returns 
  //! Nonzero is returned if the file wasn't open in the specified 
  //! direction, zero otherwise. 
  //! 
  //! @note 
  //! This function will not call the @tt{close_callback@}. 
  //! 
  //! @seealso 
  //! @[open], @[open_socket] 
  //! 
  int close(void|string how) 
  { 
    if(::close(how||"rw")) 
    { 
      // Avoid cyclic refs. 
#define FREE_CB(X) _fd->_##X = 0 
      FREE_CB(read_callback); 
      FREE_CB(write_callback); 
      FREE_CB(read_oob_callback); 
      FREE_CB(write_oob_callback); 
 
      register_close_file (open_file_id); 
#ifdef __STDIO_DEBUG 
      __closed_backtrace=master()->describe_backtrace(backtrace()); 
#endif 
      return 1; 
    } 
    return 0; 
  } 
 
#ifdef STDIO_CALLBACK_TEST_MODE 
  // Test mode where we are nasty and never return a string longer 
  // than one byte in the read callbacks and never let nonblocking 
  // writes write more than one byte. Useful to test that the callback 
  // stuff really handles packets cut at odd positions. 
 
  int write (sprintf_format|array(string) s, sprintf_args... args) 
  { 
    if (!(::mode() & PROP_IS_NONBLOCKING)) { 
      if (outbuffer && sizeof(outbuffer)) { 
        outbuffer->__fd_set_output(0); 
 
        int actual_bytes = outbuffer->output_to(::write); 
 
        outbuffer->__fd_set_output(::write); 
        if (actual_bytes <= 0) { 
          if (actual_bytes) _errno = predef::errno(); 
          return actual_bytes; 
        } 
        if (sizeof(outbuffer)) return 0; 
      } 
      return ::write (s, @args); 
    } 
 
    if (outbuffer && sizeof(outbuffer)) { 
      outbuffer->__fd_set_output(0); 
 
      string byte = outbuffer->read(1); 
 
      int actual_bytes = ::write(byte); 
      outbuffer->__fd_set_output(::write); 
 
      if (actual_bytes <= 0) { 
        outbuffer->unread(sizeof(byte)); 
        return actual_bytes; 
      } 
      if (sizeof(outbuffer)) return 0; 
    } 
 
    if (arrayp (s)) s *= ""; 
    if (sizeof (args)) s = sprintf (s, @args); 
    return ::write (s[..0]); 
  } 
 
  int write_oob (string s, mixed... args) 
  { 
    if (!(::mode() & PROP_IS_NONBLOCKING)) 
      return ::write_oob (s, @args); 
 
    if (sizeof (args)) s = sprintf (s, @args); 
    return ::write_oob (s[..0]); 
  } 
 
#else /* !STDIO_CALLBACK_TEST_MODE */ 
 
  int write(sprintf_format|array(string)|object data_or_format, 
            sprintf_args ... args) 
  { 
    if (outbuffer) { 
      outbuffer->__fd_set_output(0); 
 
      if (sizeof(outbuffer)) { 
        // The write buffer isn't empty, so try to empty it. */ 
        int bytes = outbuffer->output_to( ::write ); 
        if (sizeof(outbuffer) && (bytes > 0)) { 
          // Not all was written. Probably EWOULDBLOCK. 
          // We propagate errno below. 
          bytes = 0; 
        } 
        if (bytes <= 0) { 
          if (bytes) { 
            // EWOULDBLOCK or other error. 
            _errno = predef::errno(); 
          } 
          outbuffer->__fd_set_output(::write); 
          return 0; 
        } 
      } 
 
      // NB: Invariant: outbuffer is empty here. 
 
      if (sizeof(args)) { 
        if (arrayp(data_or_format)) { 
          data_or_format = data_or_format * ""; 
        } 
        outbuffer->sprintf(data_or_format, args); 
      } else { 
        outbuffer->add(data_or_format); 
      } 
      int bytes = sizeof(outbuffer); 
 
      int actual_bytes = outbuffer->output_to( ::write ); 
      if (actual_bytes <= 0) { 
        // Write failure. Unwrite the outbuffer. 
        _errno = predef::errno(); 
        outbuffer->clear(); 
        return actual_bytes; 
      } 
 
      outbuffer->__fd_set_output(::write); 
 
      return bytes; 
    } 
    return ::write(data_or_format, @args); 
  } 
 
#endif /* !STDIO_CALLBACK_TEST_MODE */ 
 
  private int __read_callback_error() 
  { 
#if constant(System.EWOULDBLOCK) 
    if (errno() == System.EWOULDBLOCK) { 
      // Necessary to reregister since the callback is disabled 
      // until a successful read() has been done. 
      ::set_read_callback(__stdio_read_callback); 
      return 0; 
    } 
#endif 
    ::set_read_callback(0); 
    if (___close_callback) { 
      BE_WERR ("  calling close callback"); 
      return ___close_callback(___id||this); 
    } 
  } 
 
  // FIXME: No way to specify the maximum to read. 
  protected int __stdio_read_callback() 
  { 
    BE_WERR("__stdio_read_callback()"); 
 
    if (!___read_callback) { 
      if (___close_callback) { 
          return __stdio_close_callback(); 
      } 
      return 0; 
    } 
 
    if (!errno()) { 
      if( object buffer = inbuffer ) 
      { 
        buffer->allocate(DATA_CHUNK_SIZE); 
 
        int bytes = ::read(buffer); 
 
        if (bytes > 0) 
        { 
          buffer->advance(bytes); 
          return ___read_callback( ___id||this, buffer ); 
        } 
        else 
        { 
          return __read_callback_error(); 
        } 
      } 
      string s; 
#ifdef STDIO_CALLBACK_TEST_MODE 
      s = ::read (1, 1); 
#else 
      s = ::read(DATA_CHUNK_SIZE,1); 
#endif 
      if (s) { 
        if(sizeof(s)) 
        { 
          BE_WERR("  calling read callback with %O", s); 
          return ___read_callback(___id||this, s); 
        } 
        BE_WERR ("  got eof"); 
      } 
      else 
        BE_WERR ("  got error %s from read()", strerror(errno())); 
    } 
    else 
      BE_WERR ("  got error %s from backend", strerror(errno())); 
 
    return __read_callback_error(); 
  } 
 
  protected int __stdio_fs_event_callback(int event_mask) 
  { 
    BE_WERR ("__stdio_fs_event_callback()"); 
 
    if (!___fs_event_callback) return 0; 
 
        if(errno()) 
        BE_WERR ("  got error %s from read()", strerror(errno())); 
 
    return ___fs_event_callback(___id||this, event_mask); 
  } 
 
  protected int __stdio_close_callback() 
  { 
    BE_WERR ("__stdio_close_callback()"); 
#if 0 
    if (!(::mode() & PROP_IS_NONBLOCKING)) ::set_nonblocking(); 
#endif /* 0 */ 
 
    if (!___close_callback) return 0; 
 
    if (!errno()) { 
      // There's data to read... 
      // 
      // FIXME: This doesn't work well since the close callback might 
      // very well be called sometime later, due to an error if 
      // nothing else. What we really need is a special error callback 
      // from the backend. /mast 
      BE_WERR ("  WARNING: data to read - __stdio_close_callback deregistered"); 
      ::set_read_callback(0); 
      //___close_callback = 0; 
    } 
    else 
    { 
#ifdef BACKEND_DEBUG 
      if (errno()) 
        BE_WERR ("  got error %s from backend", strerror(errno())); 
      else 
        BE_WERR ("  got eof"); 
#endif 
      ::set_read_callback(0); 
      BE_WERR ("  calling close callback"); 
      return ___close_callback(___id||this); 
    } 
 
    return 0; 
  } 
 
  protected int __stdio_write_callback() 
  { 
    BE_WERR("__stdio_write_callback()"); 
 
    if (!errno()) { 
      if (!___write_callback) return 0; 
 
      BE_WERR ("  calling write callback"); 
      if( outbuffer ) 
      { 
        int res; 
        if( sizeof( outbuffer ) ) 
          res = outbuffer->output_to( ::write ); 
        else 
        { 
          outbuffer->__fd_set_output( 0 ); 
          res = ___write_callback(___id||this,outbuffer); 
          if( !this ) return res; 
          if( sizeof( outbuffer ) ) 
            outbuffer->output_to( ::write ); 
          outbuffer->__fd_set_output( ::write ); 
        } 
        return res; 
      } 
      return ___write_callback(___id||this); 
    } 
 
    BE_WERR ("  got error %s from backend", strerror(errno())); 
    // Don't need to report the error to ___close_callback here - we 
    // know it isn't installed. If it were, either 
    // __stdio_read_callback or __stdio_close_callback would be 
    // installed and would get the error first. 
    return 0; 
  } 
 
  protected int __stdio_read_oob_callback() 
  { 
    BE_WERR ("__stdio_read_oob_callback()"); 
 
    string s; 
    if (!___read_oob_callback) { 
      // The out of band callback was probably removed after the backend 
      // was started. Propagate the event to __stdio_read_callback(). 
      s = ""; 
    } else { 
#ifdef STDIO_CALLBACK_TEST_MODE 
      s = ::read_oob (1, 1); 
#else 
      s = ::read_oob(DATA_CHUNK_SIZE,1); 
#endif 
    } 
 
    if(s) 
    { 
      if (sizeof(s)) { 
        BE_WERR ("  calling read oob callback with %O", s); 
        return ___read_oob_callback(___id||this, s); 
      } 
 
      // If the backend doesn't support separate read oob events then 
      // we'll get here if there's normal data to read or a read eof, 
      // and due to the way file_read_oob in file.c currently clears 
      // both read events, it won't call __stdio_read_callback or 
      // __stdio_close_callback afterwards. Therefore we need to try a 
      // normal read here. 
      BE_WERR ("  no oob data - trying __stdio_read_callback"); 
      return __stdio_read_callback(); 
    } 
 
    else { 
      BE_WERR ("  got error %s from read_oob()", strerror(errno())); 
 
#if constant(System.EWOULDBLOCK) 
      if (errno() == System.EWOULDBLOCK) { 
        // Necessary to reregister since the callback is disabled 
        // until a successful read() has been done. 
        ::set_read_oob_callback(__stdio_read_oob_callback); 
        return 0; 
      } 
#endif 
 
      // In case the read fails (it shouldn't, but anyway..). 
      ::set_read_oob_callback(0); 
      if (___close_callback) { 
        BE_WERR ("  calling close callback"); 
        return ___close_callback(___id||this); 
      } 
    } 
 
    return 0; 
  } 
 
  protected int __stdio_write_oob_callback() 
  { 
    BE_WERR ("__stdio_write_oob_callback()"); 
    if (!___write_oob_callback) return 0; 
 
    BE_WERR ("  calling write oob callback"); 
    return ___write_oob_callback(___id||this); 
  } 
 
  //! @decl void set_read_callback(function(mixed,string:int) read_cb) 
  //! @decl void set_read_callback(function(mixed,Buffer:int) read_cb) 
  //! @decl void set_write_callback(function(mixed:int) write_cb) 
  //! @decl void set_write_callback(function(mixed,Buffer:int) write_cb) 
  //! @decl void set_read_oob_callback(function(mixed, string:int) read_oob_cb) 
  //! @decl void set_write_oob_callback(function(mixed:int) write_oob_cb) 
  //! @decl void set_close_callback(function(mixed:int) close_cb) 
  //! @decl void set_fs_event_callback(function(mixed,int:int) fs_event_cb, int event_mask) 
  //! 
  //! These functions set the various callbacks, which will be called 
  //! when various events occur on the stream. A zero as argument will 
  //! remove the callback. 
  //! 
  //! A @[Pike.Backend] object is responsible for calling the 
  //! callbacks. It requires a thread to be waiting in it to execute 
  //! the calls. That means that only one of the callbacks will be 
  //! running at a time, so you don't need mutexes between them. 
  //! 
  //! Unless you've specified otherwise with the @[set_backend] 
  //! function, the default backend @[Pike.DefaultBackend] will be 
  //! used. It's normally activated by returning @expr{-1@} from the 
  //! @tt{main@} function and will then execute in the main thread. 
  //! 
  //! @ul 
  //! @item 
  //!   When data arrives on the stream, @[read_cb] will be called with 
  //!   some or all of that data as the second argument. 
  //! 
  //!   If the file is in buffer mode, the second argument will be a Buffer. 
  //! 
  //!   This will always be the same buffer, so data you do not use in 
  //!   one read callback can be simply left in the buffer, when new 
  //!   data arrives it will be appended 
  //! 
  //! 
  //! @item 
  //!   When the stream has buffer space over for writing, @[write_cb] 
  //!   will be called so that you can write more data to it. 
  //! 
  //!   This callback is also called after the remote end of a socket 
  //!   connection has closed the write direction. An attempt to write 
  //!   data to it in that case will generate a @[System.EPIPE] errno. 
  //!   If the remote end has closed both directions simultaneously 
  //!   (the usual case), Pike will first attempt to call @[close_cb], 
  //!   then this callback (unless @[close_cb] has closed the stream). 
  //! 
  //!   If the file is in buffer mode, the second argument will be a Buffer. 
  //! 
  //!   You should add data to write to this buffer. 
  //! @item 
  //!   When out-of-band data arrives on the stream, @[read_oob_cb] 
  //!   will be called with some or all of that data as the second 
  //!   argument. 
  //! 
  //! @item 
  //!   When the stream allows out-of-band data to be sent, 
  //!   @[write_oob_cb] will be called so that you can write more 
  //!   out-of-band data to it. 
  //! 
  //!   If the OS doesn't separate the write events for normal and 
  //!   out-of-band data, Pike will try to call @[write_oob_cb] first. 
  //!   If it doesn't write anything, then @[write_cb] will be tried. 
  //!   This also means that @[write_oob_cb] might get called when the 
  //!   remote end of a connection has closed the write direction. 
  //! 
  //! @item 
  //!   When an error or an end-of-stream in the read direction 
  //!   occurs, @[close_cb] will be called. @[errno] will return the 
  //!   error, or zero in the case of an end-of-stream. 
  //! 
  //!   The name of this callback is rather unfortunate since it 
  //!   really has nothing to do with a close: The stream is still 
  //!   open when @[close_cb] is called (you might not be able to read 
  //!   and/or write to it, but you can still use things like 
  //!   @[query_address], and the underlying file descriptor is still 
  //!   allocated). Also, this callback will not be called for a local 
  //!   close, neither by a call to @[close] or by destructing this 
  //!   object. 
  //! 
  //!   Also, @[close_cb] will not be called if a remote close only 
  //!   occurs in the write direction; that is handled by @[write_cb] 
  //!   (or possibly @[write_oob_cb]). 
  //! 
  //!   Events to @[read_cb] and @[close_cb] will be automatically 
  //!   deregistered if an end-of-stream occurs, and all events in the 
  //!   case of an error. I.e. there won't be any more calls to the 
  //!   callbacks unless they are reinstalled. This doesn't affect the 
  //!   callback settings - @[query_read_callback] et al will still 
  //!   return the installed callbacks. 
  //! @endul 
  //! 
  //! If the stream is a socket performing a nonblocking connect (see 
  //! @[open_socket] and @[connect]), a connection failure will call 
  //! @[close_cb], and a successful connect will call either 
  //! @[read_cb] or @[write_cb] as above. 
  //! 
  //! All callbacks will receive the @tt{id@} set by @[set_id] as 
  //! first argument. 
  //! 
  //! If a callback returns @expr{-1@}, no other callback or call out 
  //! will be called by the backend in that round. I.e. the caller of 
  //! the backend will get control back right away. For the default 
  //! backend that means it will immediately start another round and 
  //! check files and call outs anew. 
  //! 
  //! @param event_mask 
  //!  An event mask specifing bitwise OR of one or more event types to 
  //!  monitor, selected from @[Stdio.NOTE_WRITE] and friends. 
  //! 
  //! @note 
  //!   These functions do not set the file nonblocking. 
  //! 
  //! @note 
  //!   Callbacks are also set by @[set_callbacks] and 
  //!   @[set_nonblocking()]. 
  //! 
  //! @note 
  //! After a callback has been called, it's disabled until it has 
  //! accessed the stream accordingly, i.e. the @[write_cb] callback 
  //! is disabled after it's been called until something has been 
  //! written with @[write], and the @[write_oob_cb] callback is 
  //! likewise disabled until something has been written with 
  //! @[write_oob]. Since the data already has been read when the read 
  //! callbacks are called, this effect is not noticeable for them. 
  //! 
  //! @note 
  //! Installing callbacks means that you will start doing I/O on the 
  //! stream from the thread running the backend. If you are running 
  //! these set functions from another thread you must be prepared 
  //! that the callbacks can be called immediately by the backend 
  //! thread, so it might not be safe to continue using the stream in 
  //! this thread. 
  //! 
  //! Because of that, it's useful to talk about "callback mode" when 
  //! any callback is installed. In callback mode the stream should be 
  //! seen as "bound" to the backend thread. For instance, it's only 
  //! the backend thread that reliably can end callback mode before 
  //! the stream is "handed over" to another thread. 
  //! 
  //! @note 
  //! Callback mode has nothing to do with nonblocking mode - although 
  //! the two often are used together they don't have to be. 
  //! 
  //! @note 
  //! The file object will stay referenced from the backend object as 
  //! long as there are callbacks that can receive events. 
  //! 
  //! @bugs 
  //! Setting a close callback without a read callback currently only 
  //! works when there's no risk of getting more data on the stream. 
  //! Otherwise the close callback will be silently deregistered if 
  //! data arrives. 
  //! 
  //! @note 
  //! fs_event callbacks only trigger on systems that support these events. 
  //! Currently, this includes systems that use kqueue, such as Mac OS X, 
  //! and various flavours of BSD. 
  //! 
  //! @seealso 
  //! @[set_callbacks], @[set_nonblocking()], @[set_id()], 
  //! @[set_backend], @[query_read_callback], @[query_write_callback], 
  //! @[query_read_oob_callback], @[query_write_oob_callback], 
  //! @[query_close_callback] 
 
#define SET(X,Y) ::set_##X ((___##X = (Y)) && __stdio_##X) 
#define _SET(X,Y) _fd->_##X=(___##X = (Y)) && __stdio_##X 
 
   void set_callbacks (read_callback_t|void read_cb, 
                       write_callback_t|void write_cb, 
                       void|function(mixed:int) close_cb, 
                       void|function(mixed, string:int) read_oob_cb, 
                       void|function(mixed:int) write_oob_cb) 
  //! Installs all the specified callbacks at once. Use @[UNDEFINED] 
  //! to keep the current setting for a callback. 
  //! 
  //! Like @[set_nonblocking], the callbacks are installed atomically. 
  //! As opposed to @[set_nonblocking], this function does not do 
  //! anything with the stream, and it doesn't even have to be open. 
  //! 
  //! @seealso 
  //! @[set_read_callback], @[set_write_callback], 
  //! @[set_read_oob_callback], @[set_write_oob_callback], 
  //! @[set_close_callback], @[query_callbacks] 
  { 
    ::_disable_callbacks(); 
 
    // Bypass the ::set_xxx_callback functions; we instead enable all 
    // the event bits at once through the _enable_callbacks call at the end. 
 
    if (!undefinedp (read_cb)) 
      _SET (read_callback, read_cb); 
    if (!undefinedp (write_cb)) 
      _SET (write_callback, write_cb); 
 
    if (!undefinedp (close_cb) && 
        (___close_callback = close_cb) && !___read_callback) 
      _fd->_read_callback = __stdio_close_callback; 
 
    if (!undefinedp (read_oob_cb)) 
      _SET (read_oob_callback, read_oob_cb); 
    if (!undefinedp (write_oob_cb)) 
      _SET (write_oob_callback, write_oob_cb); 
 
    ::_enable_callbacks(); 
  } 
 
  //! @decl read_callback_t query_read_callback() 
  //! @decl write_callback_t query_write_callback() 
  //! @decl function(mixed, string:int) query_read_oob_callback() 
  //! @decl function(mixed:int) query_write_oob_callback() 
  //! @decl function(mixed:int) query_close_callback() 
  //! @decl array(function(mixed,void|string:int)) query_callbacks() 
  //! 
  //! These functions return the currently installed callbacks for the 
  //! respective events. 
  //! 
  //! @[query_callbacks] returns the callbacks in the same order as 
  //! @[set_callbacks] and @[set_nonblocking] expect them. 
  //! 
  //! @seealso 
  //! @[set_nonblocking()], @[set_read_callback], 
  //! @[set_write_callback], @[set_read_oob_callback], 
  //! @[set_write_oob_callback], @[set_close_callback], 
  //! @[set_callbacks] 
 
  //! @ignore 
 
  void set_read_callback(read_callback_t read_cb) 
  { 
    BE_WERR("setting read_callback to %O\n", read_cb); 
    ::set_read_callback(((___read_callback = read_cb) && 
                         __stdio_read_callback) || 
                        (___close_callback && __stdio_close_callback)); 
  } 
 
  read_callback_t query_read_callback() 
  { 
    return ___read_callback; 
  } 
 
#define CBFUNC(TYPE, X)                                       \ 
  void set_##X (TYPE l##X)                              \ 
  {                                                     \ 
    BE_WERR("setting " #X " to %O\n", l##X);            \ 
    SET( X , l##X );                                    \ 
  }                                                     \ 
                                                        \ 
  TYPE query_##X ()                                     \ 
  {                                                     \ 
    return ___##X;                                      \ 
  } 
 
  CBFUNC(write_callback_t, write_callback) 
  CBFUNC(function(mixed|void,string|void:int), read_oob_callback) 
  CBFUNC(function(mixed|void:int), write_oob_callback) 
 
  void set_fs_event_callback(function(mixed|void,int:int) c, int event_mask) 
  { 
    ___fs_event_callback=c; 
    if(c) 
    { 
       ::set_fs_event_callback(__stdio_fs_event_callback, event_mask); 
    } 
    else 
    { 
      ::set_fs_event_callback(0, 0); 
    } 
  } 
 
  void set_close_callback(function(mixed|void:int) c)  { 
    ___close_callback=c; 
    if (!___read_callback) { 
      if (c) { 
        ::set_read_callback(__stdio_close_callback); 
      } else { 
        ::set_read_callback(0); 
      } 
    } 
  } 
 
  function(mixed|void:int) query_close_callback() { return ___close_callback; } 
 
  function(mixed|void,int:int) query_fs_event_callback() 
  { 
    return ___fs_event_callback; 
  } 
 
 
  // this getter is provided by Stdio.Fd. 
  // function(mixed|void:int) query_fs_event_callback() { return ___fs_event_callback; } 
 
  array(function(mixed,void|string|Buffer:int)) query_callbacks() 
  { 
    return ({ 
      ___read_callback, 
      ___write_callback, 
      ___close_callback, 
      ___read_oob_callback, 
      ___write_oob_callback, 
    }); 
  } 
 
  protected void fix_internal_callbacks() 
  { 
    BE_WERR("fix_internal_callbacks()\n"); 
    ::set_read_callback ((___read_callback && __stdio_read_callback) || 
                         (___close_callback && __stdio_close_callback)); 
    ::set_write_callback (___write_callback && __stdio_write_callback); 
    ::set_read_oob_callback (___read_oob_callback && __stdio_read_oob_callback); 
    ::set_write_oob_callback (___write_oob_callback && __stdio_write_oob_callback); 
  } 
 
  //! @endignore 
 
  //! This function sets the @tt{id@} of this file. The @tt{id@} is mainly 
  //! used as an identifier that is sent as the first argument to all 
  //! callbacks. The default @tt{id@} is @expr{0@} (zero). Another possible 
  //! use of the @tt{id@} is to hold all data related to this file in a 
  //! mapping or array. 
  //! 
  //! @seealso 
  //! @[query_id()] 
  //! 
  void set_id(mixed id) { ___id=id; } 
 
  //! This function returns the @tt{id@} that has been set with @[set_id()]. 
  //! 
  //! @seealso 
  //! @[set_id()] 
  //! 
  mixed query_id() { return ___id; } 
 
  //! @decl void set_nonblocking(read_callback_t read_callback, @ 
  //!                            write_callback_t write_callback, @ 
  //!                            function(mixed:int) close_callback) 
  //! @decl void set_nonblocking(read_callback_t read_callback, @ 
  //!                            write_callback_t write_callback, @ 
  //!                            function(mixed:int) close_callback, @ 
  //!                            function(mixed, string:int) read_oob_callback, @ 
  //!                            function(mixed:int) write_oob_callback) 
  //! @decl void set_nonblocking() 
  //! 
  //! This function sets a stream to nonblocking mode and installs the 
  //! specified callbacks. See the @expr{set_*_callback@} functions 
  //! for details about them. If no arguments are given, the callbacks 
  //! will be cleared. 
  //! 
  //! @note 
  //! As opposed to calling the set callback functions separately, 
  //! this function will set all the callbacks and nonblocking mode 
  //! atomically so that no callback gets called in between. That 
  //! avoids races in case the backend is executed by another thread. 
  //! 
  //! @note 
  //!   Out-of-band data was not be supported on Pike 0.5 and earlier, 
  //!   and not on Pike 0.6 through 7.4 if they were compiled with the 
  //!   option @tt{'--without-oob'@}. 
  //! 
  //! @seealso 
  //! @[set_blocking()], @[set_callbacks], @[set_read_callback()], 
  //! @[set_write_callback()], @[set_read_oob_callback()], 
  //! @[set_write_oob_callback()], @[set_close_callback()] 
  //! @[set_nonblocking_keep_callbacks()], 
  //! @[set_blocking_keep_callbacks()] 
  //! 
  void set_nonblocking(mixed|void rcb, 
                       mixed|void wcb, 
                       mixed|void ccb, 
                       mixed|void roobcb, 
                       mixed|void woobcb) 
  { 
    CHECK_OPEN(); 
    ::_disable_callbacks(); // Thread safing 
 
    // Bypass the ::set_xxx_callback functions; we instead enable all 
    // the event bits at once through the _enable_callbacks call at the end. 
 
    _SET(read_callback,rcb); 
    _SET(write_callback,wcb); 
    if ((___close_callback = ccb) && (!rcb)) { 
      _fd->_read_callback = __stdio_close_callback; 
    } 
 
    _SET(read_oob_callback,roobcb); 
    _SET(write_oob_callback,woobcb); 
 
#ifdef __STDIO_DEBUG 
    if(mixed x=catch { ::set_nonblocking(); }) 
    { 
      x[0]+=(__closed_backtrace ? 
           sprintf("File was closed from:\n    %-=200s\n",__closed_backtrace) : 
           "This file has never been open.\n" ); 
      throw(x); 
    } 
#else 
    ::set_nonblocking(); 
#endif 
 
    ::_enable_callbacks(); 
  } 
 
  //! This function clears all callbacks and sets a stream to blocking 
  //! mode. i.e. reading, writing and closing will wait until data has 
  //! been transferred before returning. 
  //! 
  //! @note 
  //! The callbacks are cleared and blocking mode is set in one atomic 
  //! operation, so no callback gets called in between if the backend 
  //! is running in another thread. 
  //! 
  //! Even so, if the stream is in callback mode (i.e. if any 
  //! callbacks are installed) then only the backend thread can use 
  //! this function reliably; it might otherwise already be running in 
  //! a callback which is about to call e.g. @[write] when the stream 
  //! becomes blocking. 
  //! 
  //! @seealso 
  //! @[set_nonblocking()], @[set_nonblocking_keep_callbacks()], 
  //! @[set_blocking_keep_callbacks()] 
  //! 
  void set_blocking() 
  { 
    CHECK_OPEN(); 
    ::_disable_callbacks(); // Thread safing 
    SET(read_callback,0); 
    SET(write_callback,0); 
    ___close_callback=0; 
    SET(read_oob_callback,0); 
    SET(write_oob_callback,0); 
    ::set_blocking(); 
    // NOTE: _enable_callbacks() can throw in only one case; 
    //       when callback operations aren't supported, which 
    //       we don't care about in this case, since we've 
    //       just cleared all the callbacks anyway. 
    catch { ::_enable_callbacks(); }; 
  } 
 
  //! @decl void set_nonblocking_keep_callbacks() 
  //! @decl void set_blocking_keep_callbacks() 
  //!    Toggle between blocking and nonblocking, 
  //!    without changing the callbacks. 
  //! 
  //! @seealso 
  //!   @[set_nonblocking()], @[set_blocking()] 
 
  void set_blocking_keep_callbacks() 
  { 
     CHECK_OPEN(); 
     ::set_blocking(); 
  } 
 
  void set_nonblocking_keep_callbacks() 
  { 
     CHECK_OPEN(); 
     ::set_nonblocking(); 
  } 
 
  protected void _destruct() 
  { 
    BE_WERR("_destruct()"); 
    register_close_file (open_file_id); 
  } 
} 
 
//! Handles listening to socket ports. Whenever you need a bound 
//! socket that is open and listens for connections you should 
//! use this program. 
class Port 
{ 
  inherit _port; 
 
  protected int|string debug_port; 
  protected string debug_ip; 
 
  protected string _sprintf( int f ) 
  { 
    return f=='O' && sprintf( "%O(%s:%O)", 
                              this_program, debug_ip||"", debug_port ); 
  } 
 
  //! Factory creating empty @[Fd] objects. 
  //! 
  //! This function is called by @[accept()] when it needs to create 
  //! a new file. 
  protected Fd fd_factory() 
  { 
    return File()->_fd; 
  } 
 
  //! @decl void create() 
  //! @decl void create(int|string port) 
  //! @decl void create(int|string port, function accept_callback) 
  //! @decl void create(int|string port, function accept_callback, string ip) 
  //! @decl void create("stdin") 
  //! @decl void create("stdin", function accept_callback) 
  //! 
  //! If the first argument is other than @expr{"stdin"@} the arguments will 
  //! be passed to @[bind()]. 
  //! 
  //! When create is called with @expr{"stdin"@} as the first argument, a 
  //! socket is created out of the file descriptor @expr{0@}. This is only 
  //! useful if it actually is a socket to begin with, and is equivalent to 
  //! creating a port and initializing it with @[listen_fd](0). 
  //! 
  //! @seealso 
  //! @[bind] 
  protected void create( string|int|void p, 
                      void|mixed cb, 
                      string|void ip ) 
  { 
    debug_ip = (ip||"ANY"); 
    debug_port = p; 
 
    if( cb || ip ) 
      if( ip ) 
        ::create( p, cb, ip ); 
      else 
        ::create( p, cb ); 
    else 
      ::create( p ); 
  } 
 
  int bind(int|string port, void|function accept_callback, void|string ip, int|void shared) { 
    // Needed to fix _sprintf(). 
    debug_ip = (ip||"ANY"); 
    debug_port = port; 
    return ::bind(port, accept_callback, ip, shared); 
  } 
 
  //! This function completes a connection made from a remote machine to 
  //! this port. It returns a two-way stream in the form of a clone of 
  //! @[Stdio.File]. The new file is by initially set to blocking mode. 
  //! 
  //! @seealso 
  //! @[Stdio.File] 
  //! 
  File accept() 
  { 
    if(object(Fd) x=::accept()) 
    { 
      File y = function_object(x->read); 
      y->_setup_debug( "socket", x->query_address() ); 
      return y; 
    } 
    return 0; 
  } 
} 
 
//! @[Stdio.FILE] is a buffered version of @[Stdio.File], it inherits 
//! @[Stdio.File] and has most of the functionality of @[Stdio.File]. 
//! However, it has an input buffer that allows line-by-line input. 
//! 
//! It also has support for automatic charset conversion for both input 
//! and output (see @[Stdio.FILE()->set_charset()]). 
//! 
//! @note 
//!   The output part of @[Stdio.FILE] is currently not buffered. 
class FILE 
{ 
  inherit File : file; 
 
  // This is needed since it was overloaded in File above. 
  protected Fd fd_factory() 
  { 
    return FILE()->_fd; 
  } 
 
  /* Private functions / buffers etc. */ 
 
  private string b=""; 
  private int bpos=0, lp; 
 
  // Contains a prefix of b splitted on "\n". 
  // Note that the last element of the array is a partial line, 
  // and should not be used. 
  private array(string) cached_lines = ({}); 
 
  private function(string:string) output_conversion, input_conversion; 
 
  protected string _sprintf( int type, mapping flags ) 
  { 
    return ::_sprintf( type, flags ); 
  } 
 
  inline private int low_get_data() 
  { 
    string s = file::read(DATA_CHUNK_SIZE,1); 
    if(s && strlen(s)) { 
      if( input_conversion ) { 
        s = input_conversion( s ); 
      } 
      b+=s; 
      return 1; 
    } 
    return 0; 
  } 
 
  inline private int get_data() 
  { 
    if( bpos ) 
    { 
      b = b[ bpos .. ]; 
      bpos=0; 
    } 
    return low_get_data(); 
  } 
 
  // Update cached_lines and lp 
  // Return 0 at end of file, 1 otherwise. 
  // At exit cached_lines contains at least one string, 
  // and lp is set to zero. 
  inline private int get_lines() 
  { 
    if( bpos ) 
    { 
      b = b[ bpos .. ]; 
      bpos=0; 
    } 
    int start = 0; 
    while ((search(b, "\n", start) == -1) && 
           ((start = sizeof(b)), low_get_data())) 
      ; 
 
    cached_lines = b/"\n"; 
    lp = 0; 
    return sizeof(cached_lines) > 1; 
  } 
 
  // NB: Caller is responsible for clearing cached_lines and lp. 
  inline private string extract(int bytes, int|void skip) 
  { 
    string s; 
    s=b[bpos..bpos+bytes-1]; 
    if ((bpos += bytes+skip) > sizeof(b)) { 
      bpos = 0; 
      b = ""; 
    } 
    return s; 
  } 
 
  /* Public functions. */ 
 
  void set_charset( string|void charset ) 
  //! Sets the input and output charset of this file to the specified 
  //! @[charset]. If @[charset] is 0 or not specified the environment 
  //! is used to try to detect a suitable charset. 
  //! 
  //! The default charset if this function is not called is 
  //! @tt{"ISO-8859-1"@}. 
  //! 
  //! @fixme 
  //!   Consider using one of 
  //!   ISO-IR-196 (@tt{"\e%G"@} - switch to UTF-8 with return) 
  //!   or ISO-IR-190 (@tt{"\e%/G"@} - switch to UTF-8 level 1 no return) 
  //!   or ISO-IR-191 (@tt{"\e%/H"@} - switch to UTF-8 level 2 no return) 
  //!   or ISO-IR-192 (@tt{"\e%/I"@} - switch to UTF-8 level 3 no return) 
  //!   or ISO-IR-193 (@tt{"\e%/J"@} - switch to UTF-16 level 1 no return) 
  //!   or ISO-IR-194 (@tt{"\e%/K"@} - switch to UTF-16 level 2 no return) 
  //!   or ISO-IR-195 (@tt{"\e%/L"@} - switch to UTF-16 level 3 no return) 
  //!   or ISO-IR-162 (@tt{"\e%/@@"@} - switch to UCS-2 level 1) 
  //!   or ISO-IR-163 (@tt{"\e%/A"@} - switch to UCS-4 level 1) 
  //!   or ISO-IR-174 (@tt{"\e%/C"@} - switch to UCS-2 level 2) 
  //!   or ISO-IR-175 (@tt{"\e%/D"@} - switch to UCS-4 level 2) 
  //!   or ISO-IR-176 (@tt{"\e%/E"@} - switch to UCS-2 level 3) 
  //!   or ISO-IR-177 (@tt{"\e%/F"@} - switch to UCS-4 level 3) 
  //!   or ISO-IR-178 (@tt{"\e%B"@} - switch to UTF-1) 
  //!   automatically to encode wide strings. 
  { 
    if( !charset ) // autodetect. 
    { 
      if( getenv("CHARSET") ) 
        charset = getenv("CHARSET"); 
      else if( getenv("LANG") ) 
        sscanf(getenv("LANG"), "%*s.%s", charset ); 
      if( !charset ) 
        return; 
    } 
 
    charset = lower_case( charset ); 
    if( charset != "iso-8859-1" && 
        charset != "ascii") 
    { 
      object in =  Pike.Lazy.Charset.decoder( charset ); 
      object out = Pike.Lazy.Charset.encoder( charset ); 
 
      input_conversion = 
        [function(string:string)]lambda( string s ) { 
          return in->feed( s )->drain(); 
        }; 
      output_conversion = 
        [function(string:string)]lambda( string s ) { 
          return out->feed( s )->drain(); 
        }; 
    } 
    else 
      input_conversion = output_conversion = 0; 
  } 
 
  //! Read one line of input with support for input conversion. 
  //! 
  //! @param not_all 
  //!   Set this parameter to ignore partial lines at EOF. This 
  //!   is useful for eg monitoring a growing logfile. 
  //! 
  //! @returns 
  //! This function returns the line read if successful, and @expr{0@} if 
  //! no more lines are available. 
  //! 
  //! @seealso 
  //!   @[ngets()], @[read()], @[line_iterator()], @[set_charset()] 
  //! 
  string gets(int(0..1)|void not_all) 
  { 
    string r; 
    if( (sizeof(cached_lines) <= lp+1) && 
        !get_lines()) { 
      // EOF 
 
      // NB: lp is always zero here. 
      if (sizeof(r = cached_lines[0]) && !not_all) { 
        cached_lines = ({}); 
        b = ""; 
        bpos = 0; 
        return r; 
      } 
      return 0; 
    } 
    bpos += sizeof(r = cached_lines[lp++]) + 1; 
    return r; 
  } 
 
  int seek(int pos, string|void how) 
  { 
    bpos=0;  b=""; cached_lines = ({}); lp=0; 
    if( how ) 
        return file::seek(pos,[string]how); 
    return file::seek(pos); 
  } 
 
  int(-1..1) peek(void|int|float timeout) 
  { 
    if(sizeof(b)-bpos) return 1; 
    return file::peek(timeout); 
  } 
 
  int tell() 
  { 
    return file::tell()-sizeof(b)+bpos; 
  } 
 
  int close(void|string mode) 
  { 
    bpos=0; b=""; 
    if(!mode) mode="rw"; 
    file::close(mode); 
  } 
 
  int open(string file, void|string mode) 
  { 
    bpos=0; b=""; 
    if(!mode) mode="rwc"; 
    return file::open(file,mode); 
  } 
 
  int open_socket(int|string|void port, string|void address, int|string|void family_hint) 
  { 
    bpos=0;  b=""; 
    if(undefinedp(port)) 
      return file::open_socket(); 
    return file::open_socket(port, address, family_hint); 
  } 
 
  //! Get @[n] lines. 
  //! 
  //! @param n 
  //!   Number of lines to get, or all remaining if zero. 
  //! 
  //! @param not_all 
  //!   Set this parameter to ignore partial lines at EOF. This 
  //!   is useful for eg monitoring a growing logfile. 
  array(string) ngets(void|int(1..) n, int(0..1)|void not_all) 
  { 
    array(string) res; 
    if (!n) 
    { 
       res=read()/"\n"; 
       if (res[-1]=="" || not_all) return res[..<1]; 
       return res; 
    } 
    if (n < 0) return ({}); 
    res = ({}); 
    do { 
      array(string) delta; 
      if (lp + n < sizeof(cached_lines)) { 
        delta = cached_lines[lp..(lp += n)-1]; 
        bpos += `+(@sizeof(delta[*]), sizeof(delta)); 
        return res + delta; 
      } 
      delta = cached_lines[lp..<1]; 
      bpos += `+(@sizeof(delta[*]), sizeof(delta)); 
      res += delta; 
      // NB: lp and cached_lines are reset by get_lines(). 
    } while(get_lines()); 
 
    // EOF, and we want more lines... 
 
    // NB: At this point lp is always zero, and 
    //     cached_lines contains a single string. 
    if (sizeof(cached_lines[0]) && !not_all) { 
      // Return the partial line too. 
      res += cached_lines; 
      b = ""; 
      bpos = 0; 
      cached_lines = ({}); 
    } 
    if (!sizeof(res)) return 0; 
    return res; 
  } 
 
  //! Same as @[Stdio.File()->pipe()], but returns an @[Stdio.FILE] 
  //! object. 
  //! 
  //! @seealso 
  //!   @[Stdio.File()->pipe()] 
  FILE pipe(void|int flags) 
  { 
    bpos=0; cached_lines=({}); lp=0; 
    b=""; 
    return query_num_arg() ? file::pipe(flags) : file::pipe(); 
  } 
 
#if constant(_Stdio.__HAVE_OPENAT__) 
  //! @decl FILE openat(string filename, string mode) 
  //! @decl FILE openat(string filename, string mode, int mask) 
  //! 
  //! Same as @[Stdio.File()->openat()], but returns an @[Stdio.FILE] 
  //! object. 
  //! 
  //! @seealso 
  //!   @[Stdio.File()->openat()] 
  FILE openat(string filename, string mode, int|void mask) 
  { 
    if(query_num_arg()<3) 
      mask = 0777; 
    if(Fd fd=[object(Fd)]_fd->openat(filename, mode, mask)) 
    { 
      FILE o = function_object(fd->read); 
      string path = combine_path(debug_file||"", filename); 
      o->_setup_debug(path, mode, mask); 
      register_open_file(path, o->open_file_id, backtrace()); 
      return o; 
    } 
    return 0; 
  } 
#endif 
 
  int assign(File|FILE foo) 
  { 
    bpos=0; cached_lines=({}); lp=0; 
    b=""; 
    return ::assign(foo); 
  } 
 
  FILE dup() 
  { 
    FILE o=FILE(); 
    o->assign(this); 
    return o; 
  } 
 
  void set_nonblocking() 
  { 
    error("Cannot use nonblocking IO with buffered files.\n"); 
  } 
 
  //! Write @[what] with support for output_conversion. 
  //! 
  //! @seealso 
  //!   @[Stdio.File()->write()] 
  int write( array(string)|string what, mixed ... fmt  ) 
  { 
    if( output_conversion ) 
    { 
      if( sizeof( fmt ) ) 
      { 
        if( arrayp( what ) ) 
          what *=""; 
        what = sprintf( [string]what, @fmt ); 
      } 
      if( arrayp( what ) ) 
        what = map( what, output_conversion ); 
      else 
        what = output_conversion( [string]what ); 
      return ::write( what ); 
    } 
    return ::write( what,@fmt ); 
  } 
 
  //! This function does approximately the same as: 
  //! @expr{@[write](@[sprintf](@[format],@@@[data]))@}. 
  //! 
  //! @seealso 
  //! @[write()], @[sprintf()] 
  //! 
  int printf(string format, mixed ... data) 
  { 
    return ::write(format,@data); 
  } 
 
  function(:string) read_function(int nbytes) 
  { 
    return lambda(){ 
             return read( nbytes); 
           }; 
  } 
 
  //! Returns an iterator that will loop over the lines in this file. 
  //! 
  //! @seealso 
  //!   @[line_iterator()] 
  protected object _get_iterator() 
  { 
    if( input_conversion ) 
      return String.SplitIterator( "",'\n',1,read_function(DATA_CHUNK_SIZE)); 
    // This one is about twice as fast, but it's way less flexible. 
    return __builtin.file_line_iterator( read_function(DATA_CHUNK_SIZE) ); 
  } 
 
  object line_iterator( int|void trim ) 
  //! Returns an iterator that will loop over the lines in this file. 
  //! If @[trim] is true, all @tt{'\r'@} characters will be removed 
  //! from the input. 
  //! 
  //! @note 
  //! It's not supported to call this method more than once 
  //! unless a call to @[seek] is done in advance. Also note that it's 
  //! not possible to intermingle calls to @[read], @[gets] or other 
  //! functions that read data with the line iterator, it will produce 
  //! unexpected results since the internal buffer in the iterator will not 
  //! contain sequential file-data in those cases. 
  //! 
  //! @seealso 
  //!   @[_get_iterator()] 
  { 
    if( trim ) 
      return String.SplitIterator( "",(<'\n','\r'>),1, 
                                   read_function(DATA_CHUNK_SIZE)); 
    return _get_iterator(); 
  } 
 
  //! Read @[bytes] (wide-) characters with buffering and support for 
  //! input conversion. 
  //! 
  //! @seealso 
  //!   @[Stdio.File()->read()], @[set_charset()], @[unread()] 
  string read(int|void bytes,void|int(0..1) now) 
  { 
    if (!query_num_arg()) { 
      bytes = 0x7fffffff; 
    } 
 
    /* Optimization - Hubbe */ 
    if(!sizeof(b) && bytes > DATA_CHUNK_SIZE) { 
      if (input_conversion) { 
        // NOTE: This may depending on the charset return less 
        //       characters than requested. 
        // FIXME: Does this handle EOF correctly? 
        return input_conversion(::read(bytes, now)); 
      } 
      return ::read(bytes, now); 
    } 
 
    cached_lines = ({}); lp = 0; 
    while(sizeof(b) - bpos < bytes) { 
      if(!get_data()) { 
        // EOF. 
        // NB: get_data() sets bpos to zero. 
        string res = b; 
        b = ""; 
        return res; 
      } 
      else if (now) break; 
    } 
 
    return extract(bytes); 
  } 
 
  //! This function puts a string back in the input buffer. The string 
  //! can then be read with eg @[read()], @[gets()] or @[getchar()]. 
  //! 
  //! @seealso 
  //! @[read()], @[gets()], @[getchar()], @[ungets()] 
  //! 
  void unread(string s) 
  { 
    cached_lines = ({}); 
    lp = 0; 
    b=s+b[bpos..]; 
    bpos=0; 
  } 
 
  //! This function puts a line back in the input buffer. The line 
  //! can then be read with eg @[read()], @[gets()] or @[getchar()]. 
  //! 
  //! @note 
  //!   The string is autoterminated by an extra line-feed. 
  //! 
  //! @seealso 
  //! @[read()], @[gets()], @[getchar()], @[unread()] 
  //! 
  void ungets(string s) 
  { 
    if(sizeof(cached_lines)>lp) 
      cached_lines = s/"\n" + cached_lines[lp..]; 
    else 
      cached_lines = ({}); 
    lp = 0; 
    b=s+"\n"+b[bpos..]; 
    bpos=0; 
  } 
 
  private protected final int getchar_get_data() 
  { 
    b = ""; 
    bpos=0; 
    return low_get_data(); 
  } 
 
  private protected final void getchar_updatelinecache() 
  { 
    if(sizeof(cached_lines)>lp+1 && sizeof(cached_lines[lp])) 
      cached_lines = ({cached_lines[lp][1..]}) + cached_lines[lp+1..]; 
    else 
      cached_lines = ({}); 
    lp=0; 
  } 
 
  //! This function returns one character from the input stream. 
  //! 
  //! @returns 
  //!   Returns the ISO-10646 (Unicode) value of the character. 
  //! 
  //! @note 
  //!   Returns an @expr{int@} and not a @expr{string@} of length 1. 
  //! 
  inline int getchar() 
  { 
    if(sizeof(b) - bpos <= 0 && !getchar_get_data()) 
      return -1; 
 
    if(sizeof(cached_lines)) 
      getchar_updatelinecache(); 
 
    return b[bpos++]; 
  } 
} 
 
//! An instance of @tt{FILE("stderr")@}, the standard error stream. Use this 
//! when you want to output error messages. 
//! 
//! @seealso 
//!   @[predef::werror()] 
FILE stderr=FILE("stderr"); 
 
//! An instance of @tt{FILE("stdout")@}, the standatd output stream. Use this 
//! when you want to write anything to the standard output. 
//! 
//! @seealso 
//!   @[predef::write()] 
FILE stdout=FILE("stdout"); 
 
//! An instance of @tt{FILE("stdin")@}, the standard input stream. Use this 
//! when you want to read anything from the standard input. 
//! This example will read lines from standard input for as long as there 
//! are more lines to read. Each line will then be written to stdout together 
//! with the line number. We could use @[Stdio.stdout.write()] instead 
//! of just @[write()], since they are the same function. 
//! 
//! @example 
//!  int main() 
//!  { 
//!    int line; 
//!    while(string s=Stdio.stdin.gets()) 
//!    write("%5d: %s\n", line++, s); 
//!  } 
FILE stdin=FILE("stdin"); 
 
#ifdef TRACK_OPEN_FILES 
protected mapping(string|int:array) open_files = ([]); 
protected mapping(string:int) registering_files = ([]); 
protected int next_open_file_id = 1; 
 
protected void register_open_file (string file, int id, array backtrace) 
{ 
  file = combine_path (getcwd(), file); 
  if (!registering_files[file]) { 
    // Avoid the recursion which might occur when the backtrace is formatted. 
    registering_files[file] = 1; 
    open_files[id] = 
      ({file, describe_backtrace (backtrace[..<1])}); 
    m_delete (registering_files, file); 
  } 
  else 
    open_files[id] = 
      ({file, "Cannot describe backtrace due to recursion.\n"}); 
  if (!open_files[file]) open_files[file] = ({id}); 
  else open_files[file] += ({id}); 
} 
 
protected void register_close_file (int id) 
{ 
  if (open_files[id]) { 
    string file = open_files[id][0]; 
    open_files[file] -= ({id}); 
    if (!sizeof (open_files[file])) m_delete (open_files, file); 
    m_delete (open_files, id); 
  } 
} 
 
array(string) file_open_places (string file) 
{ 
  file = combine_path (getcwd(), file); 
  if (array(int) ids = open_files[file]) 
    return map (ids, lambda (int id) { 
                       if (array ent = open_files[id]) 
                         return ent[1]; 
                     }) - ({0}); 
  return 0; 
} 
 
void report_file_open_places (string file) 
{ 
  array(string) places = file_open_places (file); 
  if (places) 
    werror ("File " + file + " is currently opened from:\n" + 
            map (places, 
                 lambda (string place) { 
                   return " * " + 
                     replace (place[..<1], "\n", "\n   "); 
                 }) * "\n\n" + "\n"); 
  else 
    werror ("File " + file + " is currently not opened from any known place.\n"); 
} 
#endif 
 
//! @decl string read_file(string filename) 
//! @decl string read_file(string filename, int start, int len) 
//! 
//! Read @[len] lines from a regular file @[filename] after skipping 
//! @[start] lines and return those lines as a string. If both 
//! @[start] and @[len] are omitted the whole file is read. 
//! 
//! @throws 
//!   Throws an error on any I/O error except when the file doesn't 
//!   exist. 
//! 
//! @returns 
//!   Returns @expr{0@} (zero) if the file doesn't exist or if 
//!   @[start] is beyond the end of it. 
//! 
//!   Returns a string with the requested data otherwise. 
//! 
//! @seealso 
//! @[read_bytes()], @[write_file()] 
//! 
string(0..255) read_file(string filename,void|int start,void|int len) 
{ 
  FILE f; 
  string ret; 
  f=FILE(); 
  if (!f->open(filename,"r")) { 
    if (f->errno() == System.ENOENT) 
      return 0; 
    else 
      error ("Failed to open %O: %s.\n", filename, strerror (f->errno())); 
  } 
 
  // Disallow devices and directories. 
  Stat st; 
  if ((st = f->stat()) && !st->isreg) { 
    error( "%O is not a regular file.\n", filename ); 
  } 
 
  switch(query_num_arg()) 
  { 
  case 1: 
    ret=f->read(); 
    if (!ret) 
      error ("Failed to read %O: %s.\n", filename, strerror (f->errno())); 
    break; 
 
  case 3: 
    if( len==0 ) 
      return ""; 
    // Fallthrough 
  case 2: 
    while(start--) { 
      if (!f->gets()) 
        if (int err = f->errno()) 
          error ("Failed to read %O: %s.\n", filename, strerror (err)); 
        else 
          return "";            // EOF reached. 
    } 
 
    if( len==0 ) 
    { 
      ret=f->read(); 
      break; 
    } 
 
    String.Buffer buf=String.Buffer(); 
    while(len--) 
    { 
      if (string tmp = f->gets()) 
        buf->add(tmp, "\n"); 
      else 
        if (int err = f->errno()) 
          error ("Failed to read %O: %s.\n", filename, strerror (err)); 
        else 
          break;            // EOF reached. 
    } 
    ret=buf->get(); 
    destruct(buf); 
  } 
  f->close(); 
 
  return ret; 
} 
 
//! @decl string read_bytes(string filename, int start, int len) 
//! @decl string read_bytes(string filename, int start) 
//! @decl string read_bytes(string filename) 
//! 
//! Read @[len] number of bytes from a regular file @[filename] 
//! starting at byte @[start], and return it as a string. 
//! 
//! If @[len] is omitted, the rest of the file will be returned. 
//! 
//! If @[start] is also omitted, the entire file will be returned. 
//! 
//! @throws 
//!   Throws an error on any I/O error except when the file doesn't 
//!   exist. 
//! 
//! @returns 
//!   Returns @expr{0@} (zero) if the file doesn't exist or if 
//!   @[start] is beyond the end of it. 
//! 
//!   Returns a string with the requested data otherwise. 
//! 
//! @seealso 
//! @[read_file], @[write_file()], @[append_file()] 
//! 
string(0..255) read_bytes(string filename, void|int start,void|int len) 
{ 
  string ret; 
  File f = File(); 
 
  if (!f->open(filename,"r")) { 
    if (f->errno() == System.ENOENT) 
      return 0; 
    else 
      error ("Failed to open %O: %s.\n", filename, strerror (f->errno())); 
  } 
 
  // Disallow devices and directories. 
  Stat st; 
  if ((st = f->stat()) && !st->isreg) { 
    error( "%O is not a regular file.\n", filename ); 
  } 
 
  switch(query_num_arg()) 
  { 
  case 3: 
    if( len==0 ) 
      return ""; 
    // Fallthrough 
  case 2: 
    if(start) 
      if (f->seek(start) < 0) 
        error ("Failed to seek in %O: %s.\n", filename, strerror(f->errno())); 
  } 
  ret = len ? f->read(len) : f->read(); 
  if (!ret) 
    error ("Failed to read %O: %s.\n", filename, strerror (f->errno())); 
  f->close(); 
  return ret; 
} 
 
//! Write the string @[str] onto the file @[filename]. Any existing 
//! data in the file is overwritten. 
//! 
//! For a description of @[access], see @[Stdio.File()->open()]. 
//! 
//! @throws 
//!   Throws an error if @[filename] couldn't be opened for writing. 
//! 
//! @returns 
//!   Returns the number of bytes written, i.e. @expr{sizeof(str)@}. 
//! 
//! @seealso 
//!   @[append_file()], @[read_bytes()], @[Stdio.File()->open()] 
//! 
int write_file(string filename, string str, int|void access) 
{ 
  int ret; 
  File f = File(); 
 
  if (undefinedp (access)) 
    access = 0666; 
 
  if(!f->open(filename, "twc", access)) 
    error("Couldn't open %O: %s.\n", filename, strerror(f->errno())); 
 
  while (ret < sizeof (str)) { 
    int bytes = f->write(str[ret..]); 
    if (bytes <= 0) { 
      error ("Couldn't write to %O: %s.\n", filename, strerror (f->errno())); 
    } 
    ret += bytes; 
  } 
 
  f->close(); 
  return ret; 
} 
 
//! Append the string @[str] onto the file @[filename]. 
//! 
//! For a description of @[access], see @[Stdio.File->open()]. 
//! 
//! @throws 
//!   Throws an error if @[filename] couldn't be opened for writing. 
//! 
//! @returns 
//!   Returns the number of bytes written, i.e. @expr{sizeof(str)@}. 
//! 
//! @seealso 
//!   @[write_file()], @[read_bytes()], @[Stdio.File()->open()] 
//! 
int append_file(string filename, string str, int|void access) 
{ 
  int ret; 
  File f = File(); 
 
  if (undefinedp (access)) 
    access = 0666; 
 
  if(!f->open(filename, "awc", access)) 
    error("Couldn't open %O: %s.\n", filename, strerror(f->errno())); 
 
  while (ret < sizeof (str)) { 
    int bytes = f->write(str[ret..]); 
    if (bytes <= 0) { 
      error ("Couldn't write to %O: %s.\n", filename, strerror (f->errno())); 
    } 
    ret += bytes; 
  } 
 
  f->close(); 
  return ret; 
} 
 
//! Give the size of a file. Size -1 indicates that the file either 
//! does not exist, or that it is not readable by you. Size -2 
//! indicates that it is a directory, -3 that it is a symlink and -4 
//! that it is a device. 
//! 
//! @seealso 
//! @[file_stat()], @[write_file()], @[read_bytes()] 
//! 
int file_size(string filename) 
{ 
  Stat stat; 
  stat = file_stat(filename); 
  if(!stat) return -1; 
  // Please note that stat->size is not always the same thing as stat[1]. /mast 
  return [int]stat[1]; 
} 
 
//! @decl string append_path(string absolute, string ... relative) 
//! @decl string append_path_unix(string absolute, string ... relative) 
//! @decl string append_path_nt(string absolute, string ... relative) 
//! 
//!   Append @[relative] paths to an @[absolute] path and remove any 
//!   @expr{"//"@}, @expr{"../"@} or @expr{"/."@} to produce a 
//!   straightforward absolute path as a result. 
//! 
//!   @expr{"../"@} is ignorded in the relative paths if it makes the 
//!   created path begin with something else than the absolute path 
//!   (or so far created path). 
//! 
//!   @[append_path_nt()] fixes drive letter issues in @[relative] 
//!   by removing the colon separator @expr{":"@} if it exists (k:/fnord appends 
//!   as k/fnord) 
//! 
//!   @[append_path_nt()] also makes sure that UNC path(s) in @[relative] is appended 
//!   correctly by removing any @expr{"\\"@} or @expr{"//"@} from the beginning. 
//! 
//!   @[append_path()] is equivalent to @[append_path_unix()] on UNIX-like 
//!   operating systems, and equivalent to @[append_path_nt()] on NT-like 
//!   operating systems. 
//! 
//!   @seealso 
//!   @[combine_path()] 
//! 
 
string append_path_unix(string absolute, string ... relative) 
{ 
  return combine_path_unix(absolute, 
                           @map(relative, lambda(string s) { 
                                            return combine_path_unix("/", s)[1..]; 
                                          })); 
} 
 
string append_path_nt(string absolute, string ... relative) 
{ 
  return combine_path_nt(absolute, 
                         @map(relative, lambda(string s) { 
                                          if(s[1..1] == ":") { 
                                            s = s[0..0] + s[2..]; 
                                          } 
                                          else if(s[0..1] == "\\\\" || s[0..1] == "//") { 
                                            s = s[2..]; 
                                          } 
                                          return combine_path_nt("/", s)[1..]; 
                                        })); 
} 
 
string append_path(string absolute, string ... relative) 
{ 
#ifdef __NT__ 
  return append_path_nt (absolute, @relative); 
#else 
  return append_path_unix (absolute, @relative); 
#endif 
} 
 
//! Returns a canonic representation of @[path] (without /./, /../, // 
//! and similar path segments). 
string simplify_path(string path) 
{ 
  if(has_prefix(path, "/")) 
    return combine_path("/", path); 
  return combine_path("/", path)[1..]; 
} 
 
//! This function prints a message to stderr along with a description 
//! of what went wrong if available. It uses the system errno to find 
//! out what went wrong, so it is only applicable to IO errors. 
//! 
//! @seealso 
//! @[werror()] 
//! 
void perror(string s) 
{ 
  stderr->write("%s: %s.\n", s, strerror(errno())); 
} 
 
/* 
 * Predicates. 
 */ 
 
//! Check if a @[path] is a file. 
//! 
//! @returns 
//! Returns true if the given path is a regular file, otherwise false. 
//! 
//! @seealso 
//! @[exist()], @[is_dir()], @[is_link()], @[file_stat()] 
//! 
int is_file(string path) 
{ 
  if (Stat s = file_stat (path)) return [int]s->isreg; 
  return 0; 
} 
 
//! Check if a @[path] is a directory. 
//! 
//! @returns 
//! Returns true if the given path is a directory, otherwise false. 
//! 
//! @seealso 
//! @[exist()], @[is_file()], @[is_link()], @[file_stat()] 
//! 
int is_dir(string path) 
{ 
  if (Stat s = file_stat (path)) return [int]s->isdir; 
  return 0; 
} 
 
//! Check if a @[path] is a symbolic link. 
//! 
//! @returns 
//! Returns true if the given path is a symbolic link, otherwise false. 
//! 
//! @seealso 
//! @[exist()], @[is_dir()], @[is_file()], @[file_stat()] 
//! 
int is_link(string path) 
{ 
  if (Stat s = file_stat (path, 1)) return [int]s->islnk; 
  return 0; 
} 
 
//! Check if a @[path] exists. 
//! 
//! @returns 
//! Returns true if the given path exists (is a directory or file), 
//! otherwise false. 
//! 
//! @note 
//!   May fail with eg @[errno()] @tt{EFBIG@} if the file exists, 
//!   but the filesystem doesn't support the file size. 
//! 
//! @seealso 
//! @[is_dir()], @[is_file()], @[is_link()], @[file_stat()] 
int exist(string path) 
{ 
  return !!file_stat(path); 
} 
 
//! Convert the mode_string string as returned by Stdio.Stat object 
//! to int suitable for chmod 
//! 
//! @param mode_string 
//!   The string as return from Stdio.Stat()->mode_string 
//! @returns 
//!   An int matching the permission of the mode_string string suitable for 
//!   chmod 
int convert_modestring2int(string mode_string) 
{ 
  constant user_permissions_letters2value = 
    ([ 
      "r": 0400, 
      "w": 0200, 
      "x": 0100, 
      "s": 4000, 
      "S": 2000, 
      "t": 1000 
    ]); 
  constant group_permissions_letters2value = 
    ([ 
      "r": 0040, 
      "w": 0020, 
      "x": 0010, 
      "s": 4000, 
      "S": 2000, 
      "t": 1000 
    ]); 
   constant other_permissions_letters2value = 
    ([ 
      "r": 0004, 
      "w": 0002, 
      "x": 0001, 
      "s": 4000, 
      "S": 2000, 
      "t": 1000 
    ]); 
  int result = 0; 
  array arr_mode = mode_string / ""; 
  if(sizeof(mode_string) != 10) 
  { 
    throw(({ "Invalid mode_string", backtrace() })); 
  } 
  for(int i = 1; i < 4; i++) 
  { 
    result += user_permissions_letters2value[arr_mode[i]]; 
  } 
  for(int i = 4; i < 7; i++) 
  { 
    result += group_permissions_letters2value[arr_mode[i]]; 
  } 
  for(int i = 7; i < 10; i++) 
  { 
    result += other_permissions_letters2value[arr_mode[i]]; 
  } 
  return result; 
} 
 
int cp(string from, string to) 
//! Copies the file @[from] to the new position @[to]. If there is 
//! no system function for cp, a new file will be created and the 
//! old one copied manually in chunks of @[DATA_CHUNK_SIZE] bytes. 
//! 
//! This function can also copy directories recursively. 
//! 
//! @returns 
//!  0 on error, 1 on success 
//! 
//! @note 
//!   This function keeps file and directory mode bits, unlike in Pike 
//!   7.6 and earlier. 
{ 
  Stat stat = file_stat(from, 1); 
  if( !stat ) 
     return 0; 
 
  if(stat->isdir) 
  { 
    // recursive copying of directories 
    if (has_prefix(combine_path(to, "./"), combine_path(from, "./"))) { 
      // to is a subdirectory of from. 
      // 
      // This is NOT a good idea, as it often will trigger an infinite loop. 
      return 0; 
    } 
    if(!mkdir(to)) 
      return 0; 
    array(string) sub_files = get_dir(from); 
    foreach(sub_files, string sub_file) 
    { 
      if(!cp(combine_path(from, sub_file), combine_path(to, sub_file))) 
        return 0; 
    } 
  } 
  else 
  { 
#if constant(System.cp) 
    if (!System.cp (from, to)) 
      return 0; 
#else 
    File f=File(), t; 
    if(!f->open(from,"r")) return 0; 
    function(int,int|void:string) r=f->read; 
    t=File(); 
    if(!t->open(to,"wct")) { 
      f->close(); 
      return 0; 
    } 
    string data; 
    function(string:int) w=t->write; 
    do 
    { 
      data=r(DATA_CHUNK_SIZE); 
      if(!data) return 0; 
      if(w(data)!=sizeof(data)) return 0; 
    }while(sizeof(data) == DATA_CHUNK_SIZE); 
 
    f->close(); 
    t->close(); 
#endif 
  } 
 
  chmod(to, convert_modestring2int([string]stat->mode_string)); 
  return 1; 
} 
 
int file_equal (string file_1, string file_2) 
//! Returns nonzero if the given paths are files with identical 
//! content, returns zero otherwise. Zero is also returned for any 
//! sort of I/O error. 
{ 
  File f1 = File(), f2 = File(); 
 
  if( file_1 == file_2 ) 
    return 1; 
 
  if (!f1->open (file_1, "r") || !f2->open (file_2, "r")) return 0; 
 
 
  // Some optimizations. 
  Stat s1 = f1->stat(), s2 = f2->stat(); 
 
  if( s1->size != s2->size ) 
    return 0; 
 
  // Detect sym- or hardlinks to the same file. 
  if( (s1->dev == s2->dev) && (s1->ino == s2->ino) ) 
    return 1; 
 
  function(int,int|void:string) f1_read = f1->read, f2_read = f2->read; 
  string d1, d2; 
  do { 
    d1 = f1_read (DATA_CHUNK_SIZE); 
    if (!d1) return 0; 
    d2 = f2_read (DATA_CHUNK_SIZE); 
    if (d1 != d2) return 0; 
  } while (sizeof (d1) == DATA_CHUNK_SIZE); 
  f1->close(); 
  f2->close(); 
  return 1; 
} 
 
protected void call_cp_cb(int len, 
                       function(int, mixed ...:void) cb, mixed ... args) 
{ 
  // FIXME: Check that the lengths are the same? 
  cb(1, @args); 
} 
 
//! Copy a file asynchronously. 
//! 
//! This function is similar to @[cp()], but works asynchronously. 
//! 
//! @param from 
//!   Name of file to copy. 
//! 
//! @param to 
//!   Name of file to create or replace with a copy of @[from]. 
//! 
//! @param callback 
//!   Function to be called on completion. 
//!   The first argument will be @expr{1@} on success, and @expr{0@} (zero) 
//!   otherwise. The rest of the arguments to @[callback] are passed 
//!   verbatim from @[args]. 
//! 
//! @param args 
//!   Extra arguments to pass to @[callback]. 
//! 
//! @note 
//!   For @[callback] to be called, the backend must be active (ie 
//!   @[main()] must have returned @expr{-1@}, or @[Pike.DefaultBackend] 
//!   get called in some other way). The actual copying may start 
//!   before the backend has activated. 
//! 
//! @bugs 
//!   Currently the file sizes are not compared, so the destination file 
//!   (@[to]) may be truncated. 
//! 
//! @seealso 
//!   @[cp()], @[sendfile()] 
void async_cp(string from, string to, 
              function(int, mixed...:void) callback, mixed ... args) 
{ 
  File from_file = File(); 
  File to_file = File(); 
 
  if ((!(from_file->open(from, "r"))) || 
      (!(to_file->open(to, "wct")))) { 
    call_out(callback, 0, 0, @args); 
    return; 
  } 
  sendfile(0, from_file, 0, -1, 0, to_file, call_cp_cb, callback, @args); 
} 
 
//! Creates zero or more directories to ensure that the given @[pathname] is 
//! a directory. 
//! 
//! If a @[mode] is given, it's used for the new directories after being &'ed 
//! with the current umask (on OS'es that support this). 
//! 
//! @returns 
//!   Returns zero on failure and nonzero on success. 
//! 
//! @seealso 
//! @[mkdir()] 
//! 
int mkdirhier (string pathname, void|int mode) 
{ 
  if (undefinedp (mode)) mode = 0777; // &'ed with umask anyway. 
  if (!sizeof(pathname)) return 0; 
  string path = ""; 
#ifdef __NT__ 
  pathname = replace(pathname, "\\", "/"); 
  if (pathname[1..2] == ":/" && `<=("A", upper_case(pathname[..0]), "Z")) 
    path = pathname[..2], pathname = pathname[3..]; 
#endif 
  array(string) segments = pathname/"/"; 
  if (segments[0] == "") { 
    path += "/"; 
    pathname = pathname[1..]; 
    segments = segments[1..]; 
  } 
  // FIXME: An alternative could be a binary search, 
  //        but since it is usually only the last few 
  //        segments of the path that are missing, we 
  //        just do a linear search from the end. 
  int i = sizeof(segments); 
  while (i--) { 
    if (file_stat(path + segments[..i]*"/")) break; 
  } 
  i++; 
  while (i < sizeof(segments)) { 
    if (!mkdir(path + segments[..i++] * "/", mode)) { 
      if (errno() != System.EEXIST) 
        return 0; 
    } 
  } 
  return is_dir(path + pathname); 
} 
 
//! Remove a file or a directory tree. 
//! 
//! @returns 
//! Returns 0 on failure, nonzero otherwise. 
//! 
//! @seealso 
//! @[rm] 
//! 
int recursive_rm (string path) 
{ 
  Stat a = file_stat(path, 1); 
  if(!a) 
    return 0; 
  if(a->isdir) 
    if (array(string) sub = get_dir (path)) 
      foreach( sub, string name ) 
        recursive_rm (combine_path(path, name)); 
  return rm (path); 
} 
 
//! Copy a file or a directory tree by copying and then 
//! removing. Mode bits are preserved in the copy. 
//! It's not the fastest but works on every OS and 
//! works well across different file systems. 
//! 
//! @returns 
//! Returns 0 on failure, nonzero otherwise. 
//! 
//! @seealso 
//! @[recursive_rm] @[cp] 
//! 
int recursive_mv(string from, string to) 
{ 
  if(!cp(from, to)) 
    return 0; 
  // NB: We rely on cp() above failing if to is a subdirectory of from. 
  return recursive_rm(from); 
} 
 
/* 
 * Asynchronous sending of files. 
 */ 
 
#define READER_RESTART 4 
#define READER_HALT 32 
 
// FIXME: Support for timeouts? 
protected class nb_sendfile 
{ 
  protected File from; 
  protected int len; 
  protected array(string) trailers; 
  protected File to; 
  protected Pike.Backend backend; 
  protected function(int, mixed ...:void) callback; 
  protected array(mixed) args; 
 
  // NOTE: Always modified from backend callbacks, so no need 
  // for locking. 
  // 
  // The strings in to_write are always split up into DATA_CHUNK_SIZE 
  // pieces to limit the size of the strings passed to to->write(). 
  // That way repeated operations like str=str[x..] are avoided on 
  // arbitrarily large strings. 
  protected array(string) to_write = ({}); 
  protected int sent; 
 
  protected int reader_awake; 
  protected int writer_awake; 
 
  protected int blocking_to; 
  protected int blocking_from; 
 
  /* Reader */ 
 
  protected string _sprintf( int f ) 
  { 
    switch( f ) 
    { 
     case 't': 
       return "Stdio.Sendfile"; 
     case 'O': 
       return sprintf( "%t()", this ); 
    } 
  } 
 
  protected void reader_done() 
  { 
    SF_WERR("Reader done."); 
 
    from->set_blocking(); 
    from = 0; 
    if (trailers) { 
      to_write += trailers; 
    } 
    if (blocking_to) { 
      while(sizeof(to_write)) { 
        if (!do_write()) { 
          // Connection closed or Disk full. 
          writer_done(); 
          return; 
        } 
      } 
      if (!from) { 
        writer_done(); 
        return; 
      } 
    } else { 
      if (sizeof(to_write)) { 
        start_writer(); 
      } else { 
        writer_done(); 
        return; 
      } 
    } 
  } 
 
  protected void close_cb(mixed ignored) 
  { 
    SF_WERR("Input EOF."); 
    reader_done(); 
  } 
 
  protected void do_read() 
  { 
    SF_WERR("Blocking read."); 
    if( sizeof( to_write ) > 2) 
      return; 
    string more_data = ""; 
    if ((len < 0) || (len > DATA_CHUNK_SIZE)) { 
      more_data = from->read(DATA_CHUNK_SIZE, 1); 
    } else if (len) { 
      more_data = from->read(len, 1); 
    } 
    if (!more_data) { 
      SF_WERR(sprintf("Blocking read failed with errno: %d\n", from->errno())); 
      more_data = ""; 
    } 
    if (more_data == "") { 
      // EOF. 
      SF_WERR("Blocking read got EOF."); 
 
      from = 0; 
      if (trailers) { 
        to_write += (trailers - ({ "" })); 
        trailers = 0; 
      } 
    } else { 
      if (len > 0) len -= sizeof(more_data); 
      to_write += ({ more_data }); 
    } 
  } 
 
  protected void read_cb(mixed ignored, string data) 
  { 
    SF_WERR("Read callback."); 
    if (len >= 0) { 
      if (sizeof(data) < len) { 
        len -= sizeof(data); 
        to_write += data / (float) DATA_CHUNK_SIZE; 
      } else { 
        to_write += data[..len-1] / (float) DATA_CHUNK_SIZE; 
        len = 0; 
        from->set_blocking(); 
        reader_done(); 
        return; 
      } 
    } else { 
      to_write += data / (float) DATA_CHUNK_SIZE; 
    } 
    if (blocking_to) { 
      while(sizeof(to_write)) { 
        if (!do_write()) { 
          // Connection closed or Disk full. 
          writer_done(); 
          return; 
        } 
      } 
      if (!from) { 
        writer_done(); 
        return; 
      } 
    } else { 
      if (sizeof(to_write) > READER_HALT) { 
        // Go to sleep. 
        from->set_blocking(); 
        reader_awake = 0; 
      } 
      start_writer(); 
    } 
  } 
 
  protected void start_reader() 
  { 
    SF_WERR("Starting the reader."); 
    if (!reader_awake) { 
      reader_awake = 1; 
      from->set_nonblocking(read_cb, from->query_write_callback(), close_cb); 
    } 
  } 
 
  /* Writer */ 
 
  protected void writer_done() 
  { 
    SF_WERR("Writer done."); 
 
    // Disable any reader. 
    if (from && !blocking_from && from->set_nonblocking) { 
      from->set_nonblocking(0, from->query_write_callback(), 0); 
    } 
 
    // Disable any writer. 
    if (to && !blocking_to && to->set_nonblocking) { 
      to->set_nonblocking(to->query_read_callback(), 0, 
                          to->query_close_callback()); 
    } 
 
    // Make sure we get rid of any references... 
    to_write = 0; 
    trailers = 0; 
    from = 0; 
    to = 0; 
    backend = 0; 
    array(mixed) a = args; 
    function(int, mixed ...:void) cb = callback; 
    args = 0; 
    callback = 0; 
    if (cb) { 
      cb(sent, @a); 
    } 
  } 
 
  protected int do_write() 
  { 
    SF_WERR("Blocking writer."); 
 
    int bytes = sizeof(to_write) && to->write(to_write); 
 
    if (bytes >= 0) { 
      SF_WERR(sprintf("Wrote %d bytes.", bytes)); 
      sent += bytes; 
 
      int n; 
      for (n = 0; n < sizeof(to_write); n++) { 
        if (bytes < sizeof(to_write[n])) { 
          to_write[n] = to_write[n][bytes..]; 
          to_write = to_write[n..]; 
 
          return 1; 
        } else { 
          bytes -= sizeof(to_write[n]); 
          if (!bytes) { 
            to_write = to_write[n+1..]; 
            return 1; 
          } 
        } 
      } 
 
      return 1; 
    } else { 
      SF_WERR("Blocking writer got EOF."); 
      // Premature end of file! 
      return 0; 
    } 
  } 
 
  protected void write_cb(mixed ignored) 
  { 
    SF_WERR("Write callback."); 
    if (do_write()) { 
      if (from) { 
        if (sizeof(to_write) < READER_RESTART) { 
          if (blocking_from) { 
            do_read(); 
            if (!sizeof(to_write)) { 
              // Done. 
              writer_done(); 
            } 
          } else { 
            if (!sizeof(to_write)) { 
              // Go to sleep. 
              to->set_nonblocking(to->query_read_callback(),0, 
                                  to->query_close_callback()); 
              writer_awake = 0; 
            } 
            start_reader(); 
          } 
        } 
      } else if (!sizeof(to_write)) { 
        // Done. 
        writer_done(); 
      } 
    } else { 
      // Premature end of file! 
      writer_done(); 
    } 
  } 
 
  protected void start_writer() 
  { 
    SF_WERR("Starting the writer."); 
 
    if (!writer_awake) { 
      writer_awake = 1; 
      to->set_nonblocking(to->query_read_callback(), write_cb, 
                          to->query_close_callback()); 
    } 
  } 
 
  /* Blocking */ 
  protected void do_blocking() 
  { 
    SF_WERR("Blocking I/O."); 
 
    if (from && (sizeof(to_write) < READER_RESTART)) { 
      do_read(); 
    } 
    if (sizeof(to_write) && do_write()) { 
      backend->call_out(do_blocking, 0); 
    } else { 
      SF_WERR("Blocking I/O done."); 
      // Done. 
      from = 0; 
      to = 0; 
      backend = 0; 
      writer_done(); 
    } 
  } 
 
#ifdef SENDFILE_DEBUG 
  protected void _destruct() 
  { 
    werror("Stdio.sendfile(): Destructed.\n"); 
  } 
#endif /* SENDFILE_DEBUG */ 
 
  /* Starter */ 
 
  protected void create(array(string) hd, 
                     File f, int off, int l, 
                     array(string) tr, 
                     File t, 
                     function(int, mixed ...:void)|void cb, 
                     mixed ... a) 
  { 
    backend = (t->query_backend && t->query_backend()) || 
      Pike.DefaultBackend; 
 
    if (!l || !f) { 
      // No need for from. 
      f = 0; 
 
      // No need to differentiate between headers and trailers. 
      if (tr) { 
        if (hd) { 
          hd += tr; 
        } else { 
          hd = tr; 
        } 
        tr = 0; 
      } 
    } 
 
    if (hd) 
      to_write = map (hd, lambda (string s) { 
                            return s / (float) DATA_CHUNK_SIZE; 
                          }) * ({}) - ({""}); 
    else 
      to_write = ({}); 
 
    from = f; 
    len = l; 
 
    if (tr) 
      trailers = map (tr, lambda (string s) { 
                            return s / (float) DATA_CHUNK_SIZE; 
                          }) * ({}) - ({""}); 
    else 
      trailers = ({}); 
 
    to = t; 
    callback = cb; 
    args = a; 
 
    blocking_to = to->is_file || 
      ((!to->set_nonblocking) || 
       (to->mode && !(to->mode() & PROP_NONBLOCK))); 
 
    if (blocking_to && to->set_blocking) { 
      SF_WERR("Blocking to."); 
      to->set_blocking(); 
    } 
 
    if (from) { 
      blocking_from = from->is_file || 
        ((!from->set_nonblocking) || 
         (from->mode && !(from->mode() & PROP_NONBLOCK))); 
 
      if (off >= 0) { 
        from->seek(off); 
      } 
      if (blocking_from) { 
        SF_WERR("Blocking from."); 
        if (from->set_blocking) { 
          from->set_blocking(); 
        } 
      } else { 
        SF_WERR("Starting reader."); 
        start_reader(); 
      } 
    } 
 
    if (blocking_to) { 
      if (!from || blocking_from) { 
        // Can't use the reader to push data. 
 
        // Could have a direct call to do_blocking here, 
        // but then the callback would be called from the wrong context. 
        SF_WERR("Using fully blocking I/O."); 
        backend->call_out(do_blocking, 0); 
      } 
    } else { 
      if (blocking_from) { 
        SF_WERR("Reading some data."); 
        do_read(); 
      } 
      if (!from || sizeof(to_write)) { 
        SF_WERR("Starting the writer."); 
        start_writer(); 
      } 
    } 
  } 
} 
 
//! @decl object sendfile(array(string) headers, @ 
//!                       File from, int offset, int len, @ 
//!                       array(string) trailers, @ 
//!                       File to) 
//! @decl object sendfile(array(string) headers, @ 
//!                       File from, int offset, int len, @ 
//!                       array(string) trailers, @ 
//!                       File to, @ 
//!                       function(int, mixed ...:void) callback, @ 
//!                       mixed ... args) 
//! 
//! Sends @[headers] followed by @[len] bytes starting at @[offset] 
//! from the file @[from] followed by @[trailers] to the file @[to]. 
//! When completed @[callback] will be called with the total number of 
//! bytes sent as the first argument, followed by @[args]. 
//! 
//! Any of @[headers], @[from] and @[trailers] may be left out 
//! by setting them to @expr{0@}. 
//! 
//! Setting @[offset] to @expr{-1@} means send from the current position in 
//! @[from]. 
//! 
//! Setting @[len] to @expr{-1@} means send until @[from]'s end of file is 
//! reached. 
//! 
//! @note 
//! The sending is performed asynchronously, and may complete 
//! both before and after the function returns. 
//! 
//! For @[callback] to be called, the backend must be active (ie 
//! @[main()] must have returned @expr{-1@}, or @[Pike.DefaultBackend] 
//! get called in some other way). 
//! 
//! In some cases, the backend must also be active for any sending to 
//! be performed at all. 
//! 
//! In Pike 7.4.496, Pike 7.6.120 and Pike 7.7 and later the backend 
//! associated with @[to] will be used rather than the default backend. 
//! Note that you usually will want @[from] to have the same backend as @[to]. 
//! 
//! @note 
//! The low-level sending may be performed with blocking I/O calls, and 
//! thus trigger the process being killed with @tt{SIGPIPE@} when the 
//! peer closes the other end. Add a call to @[signal()] to avoid this. 
//! 
//! @bugs 
//! FIXME: Support for timeouts? 
//! 
//! @seealso 
//! @[Stdio.File->set_nonblocking()] 
//! 
object sendfile(array(string) headers, 
                File from, int offset, int len, 
                array(string) trailers, 
                File to, 
                function(int, mixed ...:void)|void cb, 
                mixed ... args) 
{ 
#if !defined(DISABLE_FILES_SENDFILE) && constant(_Stdio.sendfile) 
  // Try using files.sendfile(). 
 
  mixed err = catch { 
    return _Stdio.sendfile(headers, from, offset, len, 
                           trailers, to, cb, @args); 
  }; 
 
#ifdef SENDFILE_DEBUG 
  werror("files.sendfile() failed:\n%s\n", describe_backtrace(err)); 
#endif /* SENDFILE_DEBUG */ 
 
#endif /* !DISABLE_FILES_SENDFILE && files.sendfile */ 
 
  // Use nb_sendfile instead. 
  return nb_sendfile(headers, from, offset, len, trailers, to, cb, @args); 
} 
 
//! UDP (User Datagram Protocol) handling. 
class UDP 
{ 
  inherit _Stdio.UDP; 
 
  private array extra=0; 
  private function(mapping,mixed...:void) callback=0; 
 
  //! @decl UDP set_nonblocking() 
  //! @decl UDP set_nonblocking(function(mapping(string:int|string), @ 
  //!                                    mixed ...:void) read_cb, @ 
  //!                           mixed ... extra_args) 
  //! 
  //! Set this object to nonblocking mode. 
  //! 
  //! If @[read_cb] and @[extra_args] are specified, they will be passed on 
  //! to @[set_read_callback()]. 
  //! 
  //! @returns 
  //! The called object. 
  //! 
  this_program set_nonblocking(void|function(mapping,mixed...:void) f, 
                               mixed ... stuff) 
  { 
    if(f) 
      set_read_callback(f,@stuff); 
    return _set_nonblocking(); 
  } 
 
  //! @decl UDP set_read_callback(function(mapping(string:int|string), @ 
  //!                                      mixed...) read_cb, @ 
  //!                             mixed ... extra_args); 
  //! 
  //! The @[read_cb] function will receive a mapping similar to the mapping 
  //! returned by @[read()]: 
  //! @mapping 
  //!   @member string "data" 
  //!     Received data. 
  //!   @member string "ip" 
  //!     Data was sent from this IP. 
  //!   @member int "port" 
  //!     Data was sent from this port. 
  //! @endmapping 
  //! 
  //! @returns 
  //! The called object. 
  //! 
  //! @seealso 
  //! @[read()] 
  //! 
  this_program set_read_callback(function(mapping,mixed ...:void) f, 
                                 mixed ...ext) 
  { 
    extra=ext; 
    _set_read_callback((callback = f) && _read_callback); 
    return this; 
  } 
 
  private void _read_callback() 
  { 
    mapping i; 
    if (i=read()) 
      callback(i,@extra); 
  } 
} 
 
//! @decl void werror(string s) 
//! 
//! Write a message to stderr. Stderr is normally the console, even if 
//! the process output has been redirected to a file or pipe. 
//! 
//! @note 
//!   This function is identical to @[predef::werror()]. 
//! 
//! @seealso 
//!   @[predef::werror()] 
 
constant werror=predef::werror;