summaryrefslogtreecommitdiff
path: root/src/estream.c
blob: 17d599f64e3feec7982b2c451568e24ea02f6453 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
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
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
/* estream.c - Extended Stream I/O Library
 * Copyright (C) 2004, 2005, 2006, 2007, 2009, 2010, 2011,
 *               2014, 2015, 2016, 2017 g10 Code GmbH
 *
 * This file is part of Libestream.
 *
 * Libestream is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * Libestream is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Libestream; if not, see <https://www.gnu.org/licenses/>.
 *
 * ALTERNATIVELY, Libestream may be distributed under the terms of the
 * following license, in which case the provisions of this license are
 * required INSTEAD OF the GNU General Public License. If you wish to
 * allow use of your version of this file only under the terms of the
 * GNU General Public License, and not to allow others to use your
 * version of this file under the terms of the following license,
 * indicate your decision by deleting this paragraph and the license
 * below.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, and the entire permission notice in its entirety,
 *    including the disclaimer of warranties.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote
 *    products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifdef USE_ESTREAM_SUPPORT_H
# include <estream-support.h>
#endif

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#if defined(_WIN32) && !defined(HAVE_W32_SYSTEM)
# define HAVE_W32_SYSTEM 1
#endif

#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
#include <sys/types.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdarg.h>
#include <fcntl.h>
#include <errno.h>
#include <stddef.h>
#ifdef HAVE_W32_SYSTEM
# ifdef HAVE_WINSOCK2_H
#  include <winsock2.h>
# endif
# include <windows.h>
#else
# ifdef HAVE_POLL_H
#  include <poll.h>
# else
#  ifdef HAVE_SYS_SELECT_H
#   include <sys/select.h>
#  endif
# endif
#endif

/* Enable tracing.  The value is the module name to be printed.  */
/*#define ENABLE_TRACING "estream"*/

#include "gpgrt-int.h"
#include "estream-printf.h"
#include "thread.h"
#include "lock.h"


#ifndef O_BINARY
# define O_BINARY 0
#endif
#ifndef HAVE_DOSISH_SYSTEM
# ifdef HAVE_W32_SYSTEM
#  define HAVE_DOSISH_SYSTEM 1
# endif
#endif


#ifdef HAVE_W32_SYSTEM
# ifndef  S_IRGRP
#  define S_IRGRP S_IRUSR
# endif
# ifndef  S_IROTH
#  define S_IROTH S_IRUSR
# endif
# ifndef  S_IWGRP
#  define S_IWGRP S_IWUSR
# endif
# ifndef  S_IWOTH
#  define S_IWOTH S_IWUSR
# endif
# ifndef  S_IXGRP
#  define S_IXGRP S_IXUSR
# endif
# ifndef  S_IXOTH
#  define S_IXOTH S_IXUSR
# endif
#endif

#if !defined (EWOULDBLOCK) && defined (HAVE_W32_SYSTEM)
/* Compatibility with errno.h from mingw-2.0 */
# define EWOULDBLOCK 140
#endif

#ifndef EAGAIN
# define EAGAIN  EWOULDBLOCK
#endif


#define _set_errno(a)  do { errno = (a); } while (0)

#define IS_INVALID_FD(a)    ((a) == -1)

/* Calculate array dimension.  */
#ifndef DIM
#define DIM(array) (sizeof (array) / sizeof (*array))
#endif

/* A helper macro used to convert to a hex string.  */
#define tohex(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'A'))


/* Generally used types.  */

typedef void *(*func_realloc_t) (void *mem, size_t size);
typedef void (*func_free_t) (void *mem);




/*
 * A linked list to hold active stream objects.
 * Protected by ESTREAM_LIST_LOCK.
 */
struct estream_list_s
{
  struct estream_list_s *next;
  estream_t stream;  /* Entry is not used if NULL.  */
};
typedef struct estream_list_s *estream_list_t;
static estream_list_t estream_list;

/*
 * File descriptors registered for use as the standard file handles.
 * Protected by ESTREAM_LIST_LOCK.
 */
static int custom_std_fds[3];
static unsigned char custom_std_fds_valid[3];

/*
 * A lock object to protect ESTREAM LIST, CUSTOM_STD_FDS and
 * CUSTOM_STD_FDS_VALID.  Used by lock_list() and unlock_list().
 */
GPGRT_LOCK_DEFINE (estream_list_lock);


/*
 * Error code replacements.
 */
#ifndef EOPNOTSUPP
# define EOPNOTSUPP ENOSYS
#endif


/* Local prototypes.  */
static void fname_set_internal (estream_t stream, const char *fname, int quote);




/*
 * Memory allocation wrappers used in this file.
 */
static void *
mem_alloc (size_t n)
{
  return _gpgrt_malloc (n);
}

static void *
mem_realloc (void *p, size_t n)
{
  return _gpgrt_realloc (p, n);
}

static void
mem_free (void *p)
{
  if (p)
    _gpgrt_free (p);
}


/*
 * A Windows helper function to map a W32 API error code to a standard
 * system error code.  That actually belong into sysutils but to allow
 * standalone use of estream we keep it here.
 */
#ifdef HAVE_W32_SYSTEM
static int
map_w32_to_errno (DWORD w32_err)
{
  switch (w32_err)
    {
    case 0:
      return 0;

    case ERROR_FILE_NOT_FOUND:
      return ENOENT;

    case ERROR_PATH_NOT_FOUND:
      return ENOENT;

    case ERROR_ACCESS_DENIED:
      return EPERM;  /* ReactOS uses EACCES ("Permission denied") and
                      * is likely right because they used an
                      * undocumented function to associate the error
                      * codes.  However we have always used EPERM
                      * ("Operation not permitted", e.g. function is
                      * required to be called by root) and we better
                      * stick to that to avoid surprising bugs. */

    case ERROR_INVALID_HANDLE:
      return EBADF;

    case ERROR_INVALID_BLOCK:
      return ENOMEM;

    case ERROR_NOT_ENOUGH_MEMORY:
      return ENOMEM;

    case ERROR_NO_DATA:
      return EPIPE;

    case ERROR_ALREADY_EXISTS:
      return EEXIST;

      /* This mapping has been taken from reactOS.  */
    case ERROR_TOO_MANY_OPEN_FILES: return EMFILE;
    case ERROR_ARENA_TRASHED: return ENOMEM;
    case ERROR_BAD_ENVIRONMENT: return E2BIG;
    case ERROR_BAD_FORMAT: return ENOEXEC;
    case ERROR_INVALID_DRIVE: return ENOENT;
    case ERROR_CURRENT_DIRECTORY: return EACCES;
    case ERROR_NOT_SAME_DEVICE: return EXDEV;
    case ERROR_NO_MORE_FILES: return ENOENT;
    case ERROR_WRITE_PROTECT: return EACCES;
    case ERROR_BAD_UNIT: return EACCES;
    case ERROR_NOT_READY: return EACCES;
    case ERROR_BAD_COMMAND: return EACCES;
    case ERROR_CRC: return EACCES;
    case ERROR_BAD_LENGTH: return EACCES;
    case ERROR_SEEK: return EACCES;
    case ERROR_NOT_DOS_DISK: return EACCES;
    case ERROR_SECTOR_NOT_FOUND: return EACCES;
    case ERROR_OUT_OF_PAPER: return EACCES;
    case ERROR_WRITE_FAULT: return EACCES;
    case ERROR_READ_FAULT: return EACCES;
    case ERROR_GEN_FAILURE: return EACCES;
    case ERROR_SHARING_VIOLATION: return EACCES;
    case ERROR_LOCK_VIOLATION: return EACCES;
    case ERROR_WRONG_DISK: return EACCES;
    case ERROR_SHARING_BUFFER_EXCEEDED: return EACCES;
    case ERROR_BAD_NETPATH: return ENOENT;
    case ERROR_NETWORK_ACCESS_DENIED: return EACCES;
    case ERROR_BAD_NET_NAME: return ENOENT;
    case ERROR_FILE_EXISTS: return EEXIST;
    case ERROR_CANNOT_MAKE: return EACCES;
    case ERROR_FAIL_I24: return EACCES;
    case ERROR_NO_PROC_SLOTS: return EAGAIN;
    case ERROR_DRIVE_LOCKED: return EACCES;
    case ERROR_BROKEN_PIPE: return EPIPE;
    case ERROR_DISK_FULL: return ENOSPC;
    case ERROR_INVALID_TARGET_HANDLE: return EBADF;
    case ERROR_WAIT_NO_CHILDREN: return ECHILD;
    case ERROR_CHILD_NOT_COMPLETE: return ECHILD;
    case ERROR_DIRECT_ACCESS_HANDLE: return EBADF;
    case ERROR_SEEK_ON_DEVICE: return EACCES;
    case ERROR_DIR_NOT_EMPTY: return ENOTEMPTY;
    case ERROR_NOT_LOCKED: return EACCES;
    case ERROR_BAD_PATHNAME: return ENOENT;
    case ERROR_MAX_THRDS_REACHED: return EAGAIN;
    case ERROR_LOCK_FAILED: return EACCES;
    case ERROR_INVALID_STARTING_CODESEG: return ENOEXEC;
    case ERROR_INVALID_STACKSEG: return ENOEXEC;
    case ERROR_INVALID_MODULETYPE: return ENOEXEC;
    case ERROR_INVALID_EXE_SIGNATURE: return ENOEXEC;
    case ERROR_EXE_MARKED_INVALID: return ENOEXEC;
    case ERROR_BAD_EXE_FORMAT: return ENOEXEC;
    case ERROR_ITERATED_DATA_EXCEEDS_64k: return ENOEXEC;
    case ERROR_INVALID_MINALLOCSIZE: return ENOEXEC;
    case ERROR_DYNLINK_FROM_INVALID_RING: return ENOEXEC;
    case ERROR_IOPL_NOT_ENABLED: return ENOEXEC;
    case ERROR_INVALID_SEGDPL: return ENOEXEC;
    case ERROR_AUTODATASEG_EXCEEDS_64k: return ENOEXEC;
    case ERROR_RING2SEG_MUST_BE_MOVABLE: return ENOEXEC;
    case ERROR_RELOC_CHAIN_XEEDS_SEGLIM: return ENOEXEC;
    case ERROR_INFLOOP_IN_RELOC_CHAIN: return ENOEXEC;
    case ERROR_FILENAME_EXCED_RANGE: return ENOENT;
    case ERROR_NESTING_NOT_ALLOWED: return EAGAIN;
    case ERROR_NOT_ENOUGH_QUOTA: return ENOMEM;

    default:
      return EIO;
    }
}

/* Wrapper to be used by other modules to set ERRNO from the Windows
 * error.  EC may be -1 to get the last error.  */
void
_gpgrt_w32_set_errno (int ec)
{
  if (ec == -1)
    ec = GetLastError ();
  _set_errno (map_w32_to_errno (ec));
}


gpg_err_code_t
_gpgrt_w32_get_last_err_code (void)
{
  int ec = GetLastError ();
  errno = map_w32_to_errno (ec);
  return _gpg_err_code_from_errno (errno);
}


#endif /*HAVE_W32_SYSTEM*/

/*
 * Replacement for a missing memrchr.
 */
#ifndef HAVE_MEMRCHR
static void *
memrchr (const void *buffer, int c, size_t n)
{
  const unsigned char *p = buffer;

  for (p += n; n ; n--)
    if (*--p == c)
      return (void *)p;
  return NULL;
}
#endif /*HAVE_MEMRCHR*/



/*
 * Wrappers to lock a stream or the list of streams.
 */
#if 0
# define dbg_lock_0(f)        fprintf (stderr, "estream: " f);
# define dbg_lock_1(f, a)     fprintf (stderr, "estream: " f, (a));
# define dbg_lock_2(f, a, b)  fprintf (stderr, "estream: " f, (a), (b));
#else
# define dbg_lock_0(f)
# define dbg_lock_1(f, a)
# define dbg_lock_2(f, a, b)
#endif

static int
init_stream_lock (estream_t _GPGRT__RESTRICT stream)
{
  int rc;

  if (!stream->intern->samethread)
    {
      dbg_lock_1 ("enter init_stream_lock for %p\n", stream);
      memset (&stream->intern->lock, 0 , sizeof stream->intern->lock);
      rc = _gpgrt_lock_init (&stream->intern->lock);
      dbg_lock_2 ("leave init_stream_lock for %p: rc=%d\n", stream, rc);
    }
  else
    rc = 0;
  return rc;
}


static void
destroy_stream_lock (estream_t _GPGRT__RESTRICT stream)
{
  if (!stream->intern->samethread)
    {
      dbg_lock_1 ("enter destroy_stream_lock for %p\n", stream);
      _gpgrt_lock_destroy (&stream->intern->lock);
      dbg_lock_1 ("leave destroy_stream_lock for %p\n", stream);
    }
}


static void
lock_stream (estream_t _GPGRT__RESTRICT stream)
{
  if (!stream->intern->samethread)
    {
      dbg_lock_1 ("enter lock_stream for %p\n", stream);
      _gpgrt_lock_lock (&stream->intern->lock);
      dbg_lock_1 ("leave lock_stream for %p\n", stream);
    }
}


static int
trylock_stream (estream_t _GPGRT__RESTRICT stream)
{
  int rc;

  if (!stream->intern->samethread)
    {
      dbg_lock_1 ("enter trylock_stream for %p\n", stream);
      rc = _gpgrt_lock_trylock (&stream->intern->lock)? 0 : -1;
      dbg_lock_2 ("leave trylock_stream for %p: rc=%d\n", stream, rc);
    }
  else
    rc = 0;
  return rc;
}


static void
unlock_stream (estream_t _GPGRT__RESTRICT stream)
{
  if (!stream->intern->samethread)
    {
      dbg_lock_1 ("enter unlock_stream for %p\n", stream);
      _gpgrt_lock_unlock (&stream->intern->lock);
      dbg_lock_1 ("leave unlock_stream for %p\n", stream);
    }
}


static void
lock_list (void)
{
  dbg_lock_0 ("enter lock_list\n");
  _gpgrt_lock_lock (&estream_list_lock);
  dbg_lock_0 ("leave lock_list\n");
}


static void
unlock_list (void)
{
  dbg_lock_0 ("enter unlock_list\n");
  _gpgrt_lock_unlock (&estream_list_lock);
  dbg_lock_0 ("leave unlock_list\n");
}


#undef dbg_lock_0
#undef dbg_lock_1
#undef dbg_lock_2



/*
 * Manipulation of the list of stream.
 */

/*
 * Add STREAM to the list of registered stream objects.  If
 * WITH_LOCKED_LIST is true it is assumed that the list of streams is
 * already locked.  The implementation is straightforward: We first
 * look for an unused entry in the list and use that; if none is
 * available we put a new item at the head.  We drawback of the
 * strategy never to shorten the list is that a one time allocation of
 * many streams will lead to scanning unused entries later.  If that
 * turns out to be a problem, we may either free some items from the
 * list or append new entries at the end; or use a table.  Returns 0
 * on success; on error or non-zero is returned and ERRNO set.
 */
static int
do_list_add (estream_t stream, int with_locked_list)
{
  estream_list_t item;

  if (!with_locked_list)
    lock_list ();

  for (item = estream_list; item && item->stream; item = item->next)
    ;
  if (!item)
    {
      item = mem_alloc (sizeof *item);
      if (item)
        {
          item->next = estream_list;
          estream_list = item;
        }
    }
  if (item)
    item->stream = stream;

  if (!with_locked_list)
    unlock_list ();

  return item? 0 : -1;
}

/*
 * Remove STREAM from the list of registered stream objects.
 */
static void
do_list_remove (estream_t stream, int with_locked_list)
{
  estream_list_t item, item_prev = NULL;

  if (!with_locked_list)
    lock_list ();

  for (item = estream_list; item; item = item->next)
    if (item->stream == stream)
      break;
    else
      item_prev = item;

  if (item)
    {
      if (item_prev)
        item_prev->next = item->next;
      else
        estream_list = item->next;
      mem_free (item);
    }

  if (!with_locked_list)
    unlock_list ();
}



/*
 * The atexit handler for the entire gpgrt.
 */
static void
do_deinit (void)
{
  /* Flush all streams. */
  _gpgrt_fflush (NULL);

  /* We should release the estream_list.  However there is one
     problem: That list is also used to search for the standard
     estream file descriptors.  If we would remove the entire list,
     any use of es_foo in another atexit function may re-create the
     list and the streams with possible undesirable effects.  Given
     that we don't close the stream either, it should not matter that
     we keep the list and let the OS clean it up at process end.  */

  /* Reset the syscall clamp.  */
  _gpgrt_set_syscall_clamp (NULL, NULL);
}


/*
 * Initialization of the estream module.
 */
int
_gpgrt_estream_init (void)
{
  static int initialized;

  if (!initialized)
    {
      initialized = 1;
      atexit (do_deinit);
    }
  return 0;
}


/*
 * Implementation of memory based I/O.
 */

/* Cookie for memory objects.  */
typedef struct estream_cookie_mem
{
  unsigned int modeflags;	/* Open flags.  */
  unsigned char *memory;	/* Allocated data buffer.  */
  size_t memory_size;		/* Allocated size of MEMORY.  */
  size_t memory_limit;          /* Caller supplied maximum allowed
                                   allocation size or 0 for no limit.  */
  size_t offset;		/* Current offset in MEMORY.  */
  size_t data_len;		/* Used length of data in MEMORY.  */
  size_t block_size;		/* Block size.  */
  struct {
    unsigned int grow: 1;	/* MEMORY is allowed to grow.  */
  } flags;
  func_realloc_t func_realloc;
  func_free_t func_free;
} *estream_cookie_mem_t;


/*
 * Create function for memory objects.  DATA is either NULL or a user
 * supplied buffer with the initial conetnt of the memory buffer.  If
 * DATA is NULL, DATA_N and DATA_LEN need to be 0 as well.  If DATA is
 * not NULL, DATA_N gives the allocated size of DATA and DATA_LEN the
 * used length in DATA.  If this function succeeds DATA is now owned
 * by this function.  If GROW is false FUNC_REALLOC is not
 * required.
 */
static int
func_mem_create (void *_GPGRT__RESTRICT *_GPGRT__RESTRICT cookie,
                 unsigned char *_GPGRT__RESTRICT data, size_t data_n,
                 size_t data_len,
                 size_t block_size, unsigned int grow,
                 func_realloc_t func_realloc, func_free_t func_free,
                 unsigned int modeflags,
                 size_t memory_limit)
{
  estream_cookie_mem_t mem_cookie;
  int err;

  if (!data && (data_n || data_len))
    {
      _set_errno (EINVAL);
      return -1;
    }
  if (grow && func_free && !func_realloc)
    {
      _set_errno (EINVAL);
      return -1;
    }

  /* Round a memory limit up to the next block length.  */
  if (memory_limit && block_size)
    {
      memory_limit += block_size - 1;
      memory_limit /= block_size;
      memory_limit *= block_size;
    }

  mem_cookie = mem_alloc (sizeof (*mem_cookie));
  if (!mem_cookie)
    err = -1;
  else
    {
      mem_cookie->modeflags = modeflags;
      mem_cookie->memory = data;
      mem_cookie->memory_size = data_n;
      mem_cookie->memory_limit = memory_limit;
      mem_cookie->offset = 0;
      mem_cookie->data_len = data_len;
      mem_cookie->block_size = block_size;
      mem_cookie->flags.grow = !!grow;
      mem_cookie->func_realloc
        = grow? (func_realloc ? func_realloc : mem_realloc) : NULL;
      mem_cookie->func_free = func_free ? func_free : mem_free;
      *cookie = mem_cookie;
      err = 0;
    }

  return err;
}


/*
 * Read function for memory objects.
 */
static gpgrt_ssize_t
func_mem_read (void *cookie, void *buffer, size_t size)
{
  estream_cookie_mem_t mem_cookie = cookie;
  gpgrt_ssize_t ret;

  if (!size)  /* Just the pending data check.  */
    return (mem_cookie->data_len - mem_cookie->offset)? 0 : -1;

  if (size > mem_cookie->data_len - mem_cookie->offset)
    size = mem_cookie->data_len - mem_cookie->offset;

  if (size)
    {
      memcpy (buffer, mem_cookie->memory + mem_cookie->offset, size);
      mem_cookie->offset += size;
    }

  ret = size;
  return ret;
}


/*
 * Write function for memory objects.
 */
static gpgrt_ssize_t
func_mem_write (void *cookie, const void *buffer, size_t size)
{
  estream_cookie_mem_t mem_cookie = cookie;
  gpgrt_ssize_t ret;
  size_t nleft;

  if (!size)
    return 0;  /* A flush is a NOP for memory objects.  */

  if (mem_cookie->modeflags & O_APPEND)
    {
      /* Append to data.  */
      mem_cookie->offset = mem_cookie->data_len;
    }

  gpgrt_assert (mem_cookie->memory_size >= mem_cookie->offset);
  nleft = mem_cookie->memory_size - mem_cookie->offset;

  /* If we are not allowed to grow the buffer, limit the size to the
     left space.  */
  if (!mem_cookie->flags.grow && size > nleft)
    size = nleft;

  /* Enlarge the memory buffer if needed.  */
  if (size > nleft)
    {
      unsigned char *newbuf;
      size_t newsize;

      if (!mem_cookie->memory_size)
        newsize = size;  /* Not yet allocated.  */
      else
        newsize = mem_cookie->memory_size + (size - nleft);
      if (newsize < mem_cookie->offset)
        {
          _set_errno (EINVAL);
          return -1;
        }

      /* Round up to the next block length.  BLOCK_SIZE should always
         be set; we check anyway.  */
      if (mem_cookie->block_size)
        {
          newsize += mem_cookie->block_size - 1;
          if (newsize < mem_cookie->offset)
            {
              _set_errno (EINVAL);
              return -1;
            }
          newsize /= mem_cookie->block_size;
          newsize *= mem_cookie->block_size;
        }

      /* Check for a total limit.  */
      if (mem_cookie->memory_limit && newsize > mem_cookie->memory_limit)
        {
          _set_errno (ENOSPC);
          return -1;
        }

      gpgrt_assert (mem_cookie->func_realloc);
      newbuf = mem_cookie->func_realloc (mem_cookie->memory, newsize);
      if (!newbuf)
        return -1;

      mem_cookie->memory = newbuf;
      mem_cookie->memory_size = newsize;

      gpgrt_assert (mem_cookie->memory_size >= mem_cookie->offset);
      nleft = mem_cookie->memory_size - mem_cookie->offset;

      gpgrt_assert (size <= nleft);
    }

  memcpy (mem_cookie->memory + mem_cookie->offset, buffer, size);
  if (mem_cookie->offset + size > mem_cookie->data_len)
    mem_cookie->data_len = mem_cookie->offset + size;
  mem_cookie->offset += size;

  ret = size;
  return ret;
}


/*
 * Seek function for memory objects.
 */
static int
func_mem_seek (void *cookie, gpgrt_off_t *offset, int whence)
{
  estream_cookie_mem_t mem_cookie = cookie;
  gpgrt_off_t pos_new;

  switch (whence)
    {
    case SEEK_SET:
      pos_new = *offset;
      break;

    case SEEK_CUR:
      pos_new = mem_cookie->offset += *offset;
      break;

    case SEEK_END:
      pos_new = mem_cookie->data_len += *offset;
      break;

    default:
      _set_errno (EINVAL);
      return -1;
    }

  if (pos_new > mem_cookie->memory_size)
    {
      size_t newsize;
      void *newbuf;

      if (!mem_cookie->flags.grow)
	{
	  _set_errno (ENOSPC);
	  return -1;
        }

      newsize = pos_new + mem_cookie->block_size - 1;
      if (newsize < pos_new)
        {
          _set_errno (EINVAL);
          return -1;
        }
      newsize /= mem_cookie->block_size;
      newsize *= mem_cookie->block_size;

      if (mem_cookie->memory_limit && newsize > mem_cookie->memory_limit)
        {
          _set_errno (ENOSPC);
          return -1;
        }

      gpgrt_assert (mem_cookie->func_realloc);
      newbuf = mem_cookie->func_realloc (mem_cookie->memory, newsize);
      if (!newbuf)
        return -1;

      mem_cookie->memory = newbuf;
      mem_cookie->memory_size = newsize;
    }

  if (pos_new > mem_cookie->data_len)
    {
      /* Fill spare space with zeroes.  */
      memset (mem_cookie->memory + mem_cookie->data_len,
              0, pos_new - mem_cookie->data_len);
      mem_cookie->data_len = pos_new;
    }

  mem_cookie->offset = pos_new;
  *offset = pos_new;

  return 0;
}


/*
 * The IOCTL function for memory objects.
 */
static int
func_mem_ioctl (void *cookie, int cmd, void *ptr, size_t *len)
{
  estream_cookie_mem_t mem_cookie = cookie;
  int ret;

  if (cmd == COOKIE_IOCTL_SNATCH_BUFFER)
    {
      /* Return the internal buffer of the stream to the caller and
         invalidate it for the stream.  */
      *(void**)ptr = mem_cookie->memory;
      *len = mem_cookie->data_len;
      mem_cookie->memory = NULL;
      mem_cookie->memory_size = 0;
      mem_cookie->offset = 0;
      ret = 0;
    }
  else if (cmd == COOKIE_IOCTL_TRUNCATE)
    {
      gpgrt_off_t length = *(gpgrt_off_t *)ptr;

      ret = func_mem_seek (cookie, &length, SEEK_SET);
      if (ret != -1)
        mem_cookie->data_len = mem_cookie->offset;
    }
  else
    {
      _set_errno (EINVAL);
      ret = -1;
    }

  return ret;
}


/*
 * The destroy function for memory objects.
 */
static int
func_mem_destroy (void *cookie)
{
  estream_cookie_mem_t mem_cookie = cookie;

  if (cookie)
    {
      mem_cookie->func_free (mem_cookie->memory);
      mem_free (mem_cookie);
    }
  return 0;
}

/*
 * Access object for the memory functions.
 */
static struct cookie_io_functions_s estream_functions_mem =
  {
    {
      func_mem_read,
      func_mem_write,
      func_mem_seek,
      func_mem_destroy,
    },
    func_mem_ioctl,
  };



/*
 * Implementation of file descriptor based I/O.
 */

/* Cookie for fd objects.  */
typedef struct estream_cookie_fd
{
  int fd;        /* The file descriptor we are using for actual output.  */
  int no_close;  /* If set we won't close the file descriptor.  */
  int nonblock;  /* Non-blocking mode is enabled.  */
} *estream_cookie_fd_t;


/*
 * Create function for objects indentified by a libc file descriptor.
 */
static int
func_fd_create (void **cookie, int fd, unsigned int modeflags, int no_close)
{
  estream_cookie_fd_t fd_cookie;
  int err;

  trace (("enter: fd=%d mf=%x nc=%d", fd, modeflags, no_close));

  fd_cookie = mem_alloc (sizeof (*fd_cookie));
  if (! fd_cookie)
    err = -1;
  else
    {
#ifdef HAVE_DOSISH_SYSTEM
      /* Make sure it is in binary mode if requested.  */
      if ( (modeflags & O_BINARY) )
        setmode (fd, O_BINARY);
#endif
      fd_cookie->fd = fd;
      fd_cookie->no_close = no_close;
      fd_cookie->nonblock = !!(modeflags & O_NONBLOCK);
      *cookie = fd_cookie;
      err = 0;
    }

  trace_errno (err, ("leave: cookie=%p err=%d", *cookie, err));
  return err;
}


/*
 * Read function for fd objects.
 */
static gpgrt_ssize_t
func_fd_read (void *cookie, void *buffer, size_t size)

{
  estream_cookie_fd_t file_cookie = cookie;
  gpgrt_ssize_t bytes_read;

  trace (("enter: cookie=%p buffer=%p size=%d", cookie, buffer, (int)size));

  if (!size)
    bytes_read = -1; /* We don't know whether anything is pending.  */
  else if (IS_INVALID_FD (file_cookie->fd))
    {
      _gpgrt_yield ();
      bytes_read = 0;
    }
  else
    {
      _gpgrt_pre_syscall ();
      do
        {
          bytes_read = read (file_cookie->fd, buffer, size);
        }
      while (bytes_read == -1 && errno == EINTR);
      _gpgrt_post_syscall ();
    }

  trace_errno (bytes_read == -1, ("leave: bytes_read=%d", (int)bytes_read));
  return bytes_read;
}


/*
 * Write function for fd objects.
 */
static gpgrt_ssize_t
func_fd_write (void *cookie, const void *buffer, size_t size)
{
  estream_cookie_fd_t file_cookie = cookie;
  gpgrt_ssize_t bytes_written;

  trace (("enter: cookie=%p buffer=%p size=%d", cookie, buffer, (int)size));

  if (IS_INVALID_FD (file_cookie->fd))
    {
      _gpgrt_yield ();
      bytes_written = size; /* Yeah:  Success writing to the bit bucket.  */
    }
  else if (buffer)
    {
      _gpgrt_pre_syscall ();
      do
        {
          bytes_written = write (file_cookie->fd, buffer, size);
        }
      while (bytes_written == -1 && errno == EINTR);
      _gpgrt_post_syscall ();
    }
  else
    bytes_written = size; /* Note that for a flush SIZE should be 0.  */

  trace_errno (bytes_written == -1,
               ("leave: bytes_written=%d", (int)bytes_written));
  return bytes_written;
}


/*
 * Seek function for fd objects.
 */
static int
func_fd_seek (void *cookie, gpgrt_off_t *offset, int whence)
{
  estream_cookie_fd_t file_cookie = cookie;
  gpgrt_off_t offset_new;
  int err;

  if (IS_INVALID_FD (file_cookie->fd))
    {
      _set_errno (ESPIPE);
      err = -1;
    }
  else
    {
      _gpgrt_pre_syscall ();
      offset_new = lseek (file_cookie->fd, *offset, whence);
      _gpgrt_post_syscall ();
      if (offset_new == -1)
        err = -1;
      else
        {
          *offset = offset_new;
          err = 0;
        }
    }

  return err;
}


/*
 * The IOCTL function for fd objects.
 */
static int
func_fd_ioctl (void *cookie, int cmd, void *ptr, size_t *len)
{
  estream_cookie_fd_t fd_cookie = cookie;
  int ret;

  if (cmd == COOKIE_IOCTL_NONBLOCK && !len)
    {
      fd_cookie->nonblock = !!ptr;
      if (IS_INVALID_FD (fd_cookie->fd))
        {
          _set_errno (EINVAL);
          ret = -1;
        }
      else
        {
#ifdef _WIN32
          _set_errno (EOPNOTSUPP); /* FIXME: Implement for Windows.  */
          ret = -1;
#else
          _set_errno (0);
          ret = fcntl (fd_cookie->fd, F_GETFL, 0);
          if (ret == -1 && errno)
            ;
          else if (fd_cookie->nonblock)
            ret = fcntl (fd_cookie->fd, F_SETFL, (ret | O_NONBLOCK));
          else
            ret = fcntl (fd_cookie->fd, F_SETFL, (ret & ~O_NONBLOCK));
#endif
        }
    }
  else
    {
      _set_errno (EINVAL);
      ret = -1;
    }

  return ret;
}

/*
 * The destroy function for fd objects.
 */
static int
func_fd_destroy (void *cookie)
{
  estream_cookie_fd_t fd_cookie = cookie;
  int err;

  trace (("enter: cookie=%p", cookie));

  if (fd_cookie)
    {
      if (IS_INVALID_FD (fd_cookie->fd))
        err = 0;
      else
        err = fd_cookie->no_close? 0 : close (fd_cookie->fd);
      mem_free (fd_cookie);
    }
  else
    err = 0;

  trace_errno (err,("leave: err=%d", err));
  return err;
}


/*
 * Access object for the fd functions.
 */
static struct cookie_io_functions_s estream_functions_fd =
  {
    {
      func_fd_read,
      func_fd_write,
      func_fd_seek,
      func_fd_destroy,
    },
    func_fd_ioctl,
  };



#ifdef HAVE_W32_SYSTEM
/*
 * Implementation of SOCKET based I/O.
 */

/* Cookie for SOCKET objects.  */
typedef struct estream_cookie_sock
{
  SOCKET sock;   /* The SOCKET we are using for actual output.  */
  int no_close;  /* If set we won't close the file descriptor.  */
  int nonblock;  /* Non-blocking mode is enabled.  */
} *estream_cookie_sock_t;


/*
 * Create function for objects indentified by a libc file descriptor.
 */
static int
func_sock_create (void **cookie, SOCKET sock,
                  unsigned int modeflags, int no_close)
{
  estream_cookie_sock_t sock_cookie;
  int err;

  trace (("enter: sock=%d mf=%x nc=%d", (int)sock, modeflags, no_close));

  sock_cookie = mem_alloc (sizeof (*sock_cookie));
  if (! sock_cookie)
    err = -1;
  else
    {
      sock_cookie->sock = sock;
      sock_cookie->no_close = no_close;
      sock_cookie->nonblock = !!(modeflags & O_NONBLOCK);
      *cookie = sock_cookie;
      err = 0;
    }

  trace_errno (err, ("leave: cookie=%p err=%d", *cookie, err));
  return err;
}


/*
 * Read function for SOCKET objects.
 */
static gpgrt_ssize_t
func_sock_read (void *cookie, void *buffer, size_t size)

{
  estream_cookie_sock_t file_cookie = cookie;
  gpgrt_ssize_t bytes_read;

  trace (("enter: cookie=%p buffer=%p size=%d", cookie, buffer, (int)size));

  if (!size)
    bytes_read = -1; /* We don't know whether anything is pending.  */
  else if (IS_INVALID_FD (file_cookie->sock))
    {
      _gpgrt_yield ();
      bytes_read = 0;
    }
  else
    {
      _gpgrt_pre_syscall ();
      do
        {
          bytes_read = recv (file_cookie->sock, buffer, size, 0);
        }
      while (bytes_read == -1 && errno == EINTR);
      _gpgrt_post_syscall ();
    }

  trace_errno (bytes_read == -1, ("leave: bytes_read=%d", (int)bytes_read));
  return bytes_read;
}


/*
 * Write function for SOCKET objects.
 */
static gpgrt_ssize_t
func_sock_write (void *cookie, const void *buffer, size_t size)
{
  estream_cookie_sock_t file_cookie = cookie;
  gpgrt_ssize_t bytes_written;

  trace (("enter: cookie=%p buffer=%p size=%d", cookie, buffer, (int)size));

  if (IS_INVALID_FD (file_cookie->sock))
    {
      _gpgrt_yield ();
      bytes_written = size; /* Yeah:  Success writing to the bit bucket.  */
    }
  else if (buffer)
    {
      _gpgrt_pre_syscall ();
      do
        {
          bytes_written = send (file_cookie->sock, buffer, size, 0);
        }
      while (bytes_written == -1 && errno == EINTR);
      _gpgrt_post_syscall ();
    }
  else
    bytes_written = size; /* Note that for a flush SIZE should be 0.  */

  trace_errno (bytes_written == -1,
               ("leave: bytes_written=%d", (int)bytes_written));
  return bytes_written;
}


/*
 * Seek function for SOCKET objects.
 */
static int
func_sock_seek (void *cookie, gpgrt_off_t *offset, int whence)
{
  (void)cookie;
  (void)offset;
  (void)whence;
  _set_errno (ESPIPE);
  return -1;
}


/*
 * The IOCTL function for SOCKET objects.
 */
static int
func_sock_ioctl (void *cookie, int cmd, void *ptr, size_t *len)
{
  estream_cookie_sock_t sock_cookie = cookie;
  int ret;

  if (cmd == COOKIE_IOCTL_NONBLOCK && !len)
    {
      sock_cookie->nonblock = !!ptr;
      if (IS_INVALID_FD (sock_cookie->sock))
        {
          _set_errno (EINVAL);
          ret = -1;
        }
      else
        {
          u_long mode = 0;

          if (sock_cookie->nonblock)
            mode = 1;

          ret = ioctlsocket (sock_cookie->sock, FIONBIO, &mode);
        }
    }
  else
    {
      _set_errno (EINVAL);
      ret = -1;
    }

  return ret;
}

/*
 * The destroy function for SOCKET objects.
 */
static int
func_sock_destroy (void *cookie)
{
  estream_cookie_sock_t sock_cookie = cookie;
  int err;

  trace (("enter: cookie=%p", cookie));

  if (sock_cookie)
    {
      if (IS_INVALID_FD (sock_cookie->sock))
        err = 0;
      else
        err = sock_cookie->no_close? 0 : closesocket (sock_cookie->sock);
      mem_free (sock_cookie);
    }
  else
    err = 0;

  trace_errno (err,("leave: err=%d", err));
  return err;
}


/*
 * Access object for the fd functions.
 */
static struct cookie_io_functions_s estream_functions_sock =
  {
    {
      func_sock_read,
      func_sock_write,
      func_sock_seek,
      func_sock_destroy,
    },
    func_sock_ioctl,
  };

/*
 * Implementation of W32 handle based I/O.
 */

/* Cookie for fd objects.  */
typedef struct estream_cookie_w32
{
  HANDLE hd;     /* The handle we are using for actual output.  */
  int no_close;  /* If set we won't close the handle.  */
  int no_syscall_clamp; /* Do not use the syscall clamp. */
} *estream_cookie_w32_t;


/*
 * Create function for w32 handle objects.
 */
static int
func_w32_create (void **cookie, HANDLE hd,
                 unsigned int modeflags, int no_close, int no_syscall_clamp)
{
  estream_cookie_w32_t w32_cookie;
  int err;

  trace (("enter: hd=%p mf=%x nc=%d nsc=%d",
          hd, modeflags, no_close, no_syscall_clamp));
  w32_cookie = mem_alloc (sizeof (*w32_cookie));
  if (!w32_cookie)
    err = -1;
  else
    {
      /* CR/LF translations are not supported when using the bare W32
         API.  If that is really required we need to implemented that
         in the upper layer.  */
      (void)modeflags;

      w32_cookie->hd = hd;
      w32_cookie->no_close = no_close;
      w32_cookie->no_syscall_clamp = no_syscall_clamp;
      *cookie = w32_cookie;
      err = 0;
    }

  trace_errno (err, ("leave: cookie=%p err=%d", *cookie, err));
  return err;
}

/*
 * Read function for W32 handle objects.
 *
 * Note that this function may also be used by the reader thread of
 * w32-stream.  In that case the NO_SYSCALL_CLAMP is set.
 */
static gpgrt_ssize_t
func_w32_read (void *cookie, void *buffer, size_t size)
{
  estream_cookie_w32_t w32_cookie = cookie;
  gpgrt_ssize_t bytes_read;

  trace (("enter: cookie=%p buffer=%p size=%d", cookie, buffer, (int)size));

  if (!size)
    bytes_read = -1; /* We don't know whether anything is pending.  */
  else if (w32_cookie->hd == INVALID_HANDLE_VALUE)
    {
      _gpgrt_yield ();
      bytes_read = 0;
    }
  else
    {
      if (!w32_cookie->no_syscall_clamp)
        _gpgrt_pre_syscall ();
      do
        {
          DWORD nread, ec;

          trace (("cookie=%p calling ReadFile", cookie));
          if (!ReadFile (w32_cookie->hd, buffer, size, &nread, NULL))
            {
              ec = GetLastError ();
              trace (("cookie=%p ReadFile failed: ec=%ld", cookie,ec));
              if (ec == ERROR_BROKEN_PIPE)
                bytes_read = 0; /* Like our pth_read we handle this as EOF.  */
              else
                {
                  _set_errno (map_w32_to_errno (ec));
                  bytes_read = -1;
                }
            }
          else
            bytes_read = (int)nread;
        }
      while (bytes_read == -1 && errno == EINTR);
      if (!w32_cookie->no_syscall_clamp)
        _gpgrt_post_syscall ();
    }

  trace_errno (bytes_read==-1,("leave: bytes_read=%d", (int)bytes_read));
  return bytes_read;
}


/*
 * Write function for W32 handle objects.
 *
 * Note that this function may also be used by the writer thread of
 * w32-stream.  In that case the NO_SYSCALL_CLAMP is set.
 */
static gpgrt_ssize_t
func_w32_write (void *cookie, const void *buffer, size_t size)
{
  estream_cookie_w32_t w32_cookie = cookie;
  gpgrt_ssize_t bytes_written;

  trace (("enter: cookie=%p buffer=%p size=%d", cookie, buffer, (int)size));

  if (w32_cookie->hd == INVALID_HANDLE_VALUE)
    {
      _gpgrt_yield ();
      bytes_written = size; /* Yeah:  Success writing to the bit bucket.  */
    }
  else if (buffer)
    {
      if (!w32_cookie->no_syscall_clamp)
        _gpgrt_pre_syscall ();
      do
        {
          DWORD nwritten;

          trace (("cookie=%p calling WriteFile", cookie));
	  if (!WriteFile (w32_cookie->hd, buffer, size, &nwritten, NULL))
	    {
              DWORD ec = GetLastError ();
              trace (("cookie=%p WriteFile failed: ec=%ld", cookie, ec));
	      _set_errno (map_w32_to_errno (ec));
	      bytes_written = -1;
	    }
	  else
	    bytes_written = (int)nwritten;
        }
      while (bytes_written == -1 && errno == EINTR);
      if (!w32_cookie->no_syscall_clamp)
        _gpgrt_post_syscall ();
    }
  else
    bytes_written = size; /* Note that for a flush SIZE should be 0.  */

  trace_errno (bytes_written==-1,
               ("leave: bytes_written=%d", (int)bytes_written));
  return bytes_written;
}


/*
 * Seek function for W32 handle objects.
 */
static int
func_w32_seek (void *cookie, gpgrt_off_t *offset, int whence)
{
  estream_cookie_w32_t w32_cookie = cookie;
  DWORD method;
  LARGE_INTEGER distance, newoff;

  if (w32_cookie->hd == INVALID_HANDLE_VALUE)
    {
      _set_errno (ESPIPE);
      return -1;
    }

  if (GetFileType (w32_cookie->hd) == FILE_TYPE_PIPE)
    {
      _set_errno (ESPIPE);
      return -1;
    }

  if (whence == SEEK_SET)
    {
      method = FILE_BEGIN;
      distance.QuadPart = (unsigned long long)(*offset);
    }
  else if (whence == SEEK_CUR)
    {
      method = FILE_CURRENT;
      distance.QuadPart = (long long)(*offset);
    }
  else if (whence == SEEK_END)
    {
      method = FILE_END;
      distance.QuadPart = (long long)(*offset);
    }
  else
    {
      _set_errno (EINVAL);
      return -1;
    }
  if (!w32_cookie->no_syscall_clamp)
    _gpgrt_pre_syscall ();
  if (!SetFilePointerEx (w32_cookie->hd, distance, &newoff, method))
    {
      _set_errno (map_w32_to_errno (GetLastError ()));
      _gpgrt_post_syscall ();
      return -1;
    }
  if (!w32_cookie->no_syscall_clamp)
    _gpgrt_post_syscall ();
  /* Note that gpgrt_off_t is always 64 bit.  */
  *offset = (gpgrt_off_t)newoff.QuadPart;
  return 0;
}


/*
 * Destroy function for W32 handle objects.
 */
static int
func_w32_destroy (void *cookie)
{
  estream_cookie_w32_t w32_cookie = cookie;
  int err;

  trace (("enter: cookie=%p", cookie));

  if (w32_cookie)
    {
      if (w32_cookie->hd == INVALID_HANDLE_VALUE)
        err = 0;
      else if (w32_cookie->no_close)
        err = 0;
      else
        {
          trace (("cookie=%p closing handle %p", cookie, w32_cookie->hd));
          if (!CloseHandle (w32_cookie->hd))
            {
              DWORD ec = GetLastError ();
              trace (("cookie=%p CloseHandle failed: ec=%ld", cookie,ec));
	      _set_errno (map_w32_to_errno (ec));
              err = -1;
            }
          else
            err = 0;
        }
      mem_free (w32_cookie);
    }
  else
    err = 0;

  trace_errno (err, ("leave: err=%d", err));
  return err;
}


/*
 * Access object for the W32 handle based objects.
 */
static struct cookie_io_functions_s estream_functions_w32 =
  {
    {
      func_w32_read,
      func_w32_write,
      func_w32_seek,
      func_w32_destroy,
    },
    NULL,
  };
#endif /*HAVE_W32_SYSTEM*/




/*
 * Implementation of stdio based I/O.
 */

/* Cookie for fp objects.  */
typedef struct estream_cookie_fp
{
  FILE *fp;      /* The file pointer we are using for actual output.  */
  int no_close;  /* If set we won't close the file pointer.  */
} *estream_cookie_fp_t;


/*
 * Create function for stdio based objects.
 */
static int
func_fp_create (void **cookie, FILE *fp,
                unsigned int modeflags, int no_close)
{
  estream_cookie_fp_t fp_cookie;
  int err;

  fp_cookie = mem_alloc (sizeof *fp_cookie);
  if (!fp_cookie)
    err = -1;
  else
    {
#ifdef HAVE_DOSISH_SYSTEM
      /* Make sure it is in binary mode if requested.  */
      if ( (modeflags & O_BINARY) )
        setmode (fileno (fp), O_BINARY);
#else
      (void)modeflags;
#endif
      fp_cookie->fp = fp;
      fp_cookie->no_close = no_close;
      *cookie = fp_cookie;
      err = 0;
    }

  return err;
}


/*
 * Read function for stdio based objects.
 */
static gpgrt_ssize_t
func_fp_read (void *cookie, void *buffer, size_t size)

{
  estream_cookie_fp_t file_cookie = cookie;
  gpgrt_ssize_t bytes_read;

  if (!size)
    return -1; /* We don't know whether anything is pending.  */

  if (file_cookie->fp)
    {
      _gpgrt_pre_syscall ();
      bytes_read = fread (buffer, 1, size, file_cookie->fp);
      _gpgrt_post_syscall ();
    }
  else
    bytes_read = 0;
  if (!bytes_read && ferror (file_cookie->fp))
    return -1;
  return bytes_read;
}


/*
 * Write function for stdio bases objects.
 */
static gpgrt_ssize_t
func_fp_write (void *cookie, const void *buffer, size_t size)
{
  estream_cookie_fp_t file_cookie = cookie;
  size_t bytes_written;

  if (file_cookie->fp)
    {
      _gpgrt_pre_syscall ();
      if (buffer)
        {
#ifdef HAVE_W32_SYSTEM
          /* Using an fwrite to stdout connected to the console fails
             with the error "Not enough space" for an fwrite size of
             >= 52KB (tested on Windows XP SP2).  To solve this we
             always chunk the writes up into smaller blocks.  */
          bytes_written = 0;
          while (bytes_written < size)
            {
              size_t cnt = size - bytes_written;

              if (cnt > 32*1024)
                cnt = 32*1024;
              if (fwrite ((const char*)buffer + bytes_written,
                          cnt, 1, file_cookie->fp) != 1)
                break; /* Write error.  */
              bytes_written += cnt;
            }
#else
          bytes_written = fwrite (buffer, 1, size, file_cookie->fp);
#endif
        }
      else /* Only flush requested.  */
        bytes_written = size;

      fflush (file_cookie->fp);
      _gpgrt_post_syscall ();
    }
  else
    bytes_written = size; /* Successfully written to the bit bucket.  */

  if (bytes_written != size)
    return -1;
  return bytes_written;
}


/*
 * Seek function for stdio based objects.
 */
static int
func_fp_seek (void *cookie, gpgrt_off_t *offset, int whence)
{
  estream_cookie_fp_t file_cookie = cookie;
  long int offset_new;

  if (!file_cookie->fp)
    {
      _set_errno (ESPIPE);
      return -1;
    }

  _gpgrt_pre_syscall ();
  if ( fseek (file_cookie->fp, (long int)*offset, whence) )
    {
      /* fprintf (stderr, "\nfseek failed: errno=%d (%s)\n", */
      /*          errno,strerror (errno)); */
      _gpgrt_post_syscall ();
      return -1;
    }

  offset_new = ftell (file_cookie->fp);
  _gpgrt_post_syscall ();
  if (offset_new == -1)
    {
      /* fprintf (stderr, "\nftell failed: errno=%d (%s)\n",  */
      /*          errno,strerror (errno)); */
      return -1;
    }
  *offset = offset_new;
  return 0;
}


/*
 * Destroy function for stdio based objects.
 */
static int
func_fp_destroy (void *cookie)
{
  estream_cookie_fp_t fp_cookie = cookie;
  int err;

  if (fp_cookie)
    {
      if (fp_cookie->fp)
        {
          _gpgrt_pre_syscall ();
          fflush (fp_cookie->fp);
          _gpgrt_post_syscall ();
          err = fp_cookie->no_close? 0 : fclose (fp_cookie->fp);
        }
      else
        err = 0;
      mem_free (fp_cookie);
    }
  else
    err = 0;

  return err;
}


/*
 * Access object for stdio based objects.
 */
static struct cookie_io_functions_s estream_functions_fp =
  {
    {
      func_fp_read,
      func_fp_write,
      func_fp_seek,
      func_fp_destroy,
    },
    NULL,
  };




/*
 * Implementation of file name based I/O.
 *
 * Note that only a create function is required because the other
 * operations ares handled by file descriptor based I/O.
 */

#ifdef HAVE_W32_SYSTEM
static int
any8bitchar (const char *string)
{
  if (string)
    for ( ; *string; string++)
      if ((*string & 0x80))
        return 1;
  return 0;
}
#endif /*HAVE_W32_SYSTEM*/

/* Create function for objects identified by a file name.  */
static int
func_file_create (void **cookie, int *filedes,
                  const char *path, unsigned int modeflags, unsigned int cmode)
{
  estream_cookie_fd_t file_cookie;
  int err;
  int fd;

  err = 0;

  file_cookie = mem_alloc (sizeof (*file_cookie));
  if (! file_cookie)
    {
      err = -1;
      goto out;
    }

#ifdef HAVE_W32_SYSTEM
  if (any8bitchar (path))
    {
      wchar_t *wpath;

      wpath = _gpgrt_utf8_to_wchar (path);
      if (!wpath)
        fd = -1;
      else
        {
          fd = _wopen (wpath, modeflags, cmode);
          _gpgrt_free_wchar (wpath);
        }
    }
  else  /* Avoid unnecessary conversion.  */
    fd = open (path, modeflags, cmode);
#else
  fd = open (path, modeflags, cmode);
#endif
  if (fd == -1)
    {
      err = -1;
      goto out;
    }
#ifdef HAVE_DOSISH_SYSTEM
  /* Make sure it is in binary mode if requested.  */
  if ( (modeflags & O_BINARY) )
    setmode (fd, O_BINARY);
#endif

  file_cookie->fd = fd;
  file_cookie->no_close = 0;
  *cookie = file_cookie;
  *filedes = fd;

 out:

  if (err)
    mem_free (file_cookie);

  return err;
}


/* Create function for objects identified by a file name.  Windows
 * version to use CreateFile.  */
#ifdef HAVE_W32_SYSTEM
static int
func_file_create_w32 (void **cookie, HANDLE *rethd, const char *path,
                      unsigned int modeflags, unsigned int cmode)
{
  estream_cookie_w32_t hd_cookie;
  wchar_t *wpath = NULL;
  int err = 0;
  HANDLE hd;
  DWORD desired_access;
  DWORD share_mode;
  DWORD creation_distribution;

  (void)cmode;

  hd_cookie = mem_alloc (sizeof *hd_cookie);
  if (!hd_cookie)
    {
      err = -1;
      goto leave;
    }

  wpath = _gpgrt_fname_to_wchar (path);
  if (!wpath)
    {
      err = -1;
      goto leave;
    }

  if ((modeflags & O_WRONLY))
    {
      desired_access = GENERIC_WRITE;
      share_mode = FILE_SHARE_WRITE;
    }
  else if ((modeflags & O_RDWR))
    {
      desired_access = GENERIC_READ | GENERIC_WRITE;
      share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
    }
  else
    {
      desired_access = GENERIC_READ;
      share_mode = FILE_SHARE_READ;
    }


  creation_distribution = 0;
  if ((modeflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
     creation_distribution |= CREATE_NEW;
  else if ((modeflags & O_TRUNC) == O_TRUNC)
    {
      if ((modeflags & O_CREAT) == O_CREAT)
        creation_distribution |= CREATE_ALWAYS;
      else if ((modeflags & O_RDONLY) != O_RDONLY)
        creation_distribution |= TRUNCATE_EXISTING;
    }
  else if ((modeflags & O_APPEND) == O_APPEND)
    creation_distribution |= OPEN_EXISTING;
  else if ((modeflags & O_CREAT) == O_CREAT)
    creation_distribution |= OPEN_ALWAYS;
  else
    creation_distribution |= OPEN_EXISTING;

  hd = CreateFileW (wpath,
                    desired_access,
                    share_mode,
                    NULL,  /* security attributes */
                    creation_distribution,
                    0,     /* flags and attributes  */
                    NULL); /* template file  */
  if (hd == INVALID_HANDLE_VALUE)
    {
      _set_errno (map_w32_to_errno (GetLastError ()));
      err = -1;
      goto leave;
    }

  hd_cookie->hd = hd;
  hd_cookie->no_close = 0;
  hd_cookie->no_syscall_clamp = 0;
  *cookie = hd_cookie;
  *rethd = hd;

 leave:
  _gpgrt_free_wchar (wpath);
  if (err)
    mem_free (hd_cookie);
  return err;
}
#endif /*HAVE_W32_SYSTEM*/



/* Flags used by parse_mode and friends.  */
#define X_SAMETHREAD	(1 << 0)
#define X_SYSOPEN	(1 << 1)
#define X_POLLABLE	(1 << 2)

/* Parse the mode flags of fopen et al.  In addition to the POSIX
 * defined mode flags keyword parameters are supported.  These are
 * key/value pairs delimited by comma and optional white spaces.
 * Keywords and values may not contain a comma or white space; unknown
 * keywords are skipped. Supported keywords are:
 *
 * mode=<string>
 *
 *    Creates a file and gives the new file read and write permissions
 *    for the user and read permission for the group.  The format of
 *    the string is the same as shown by the -l option of the ls(1)
 *    command.  However the first letter must be a dash and it is
 *    allowed to leave out trailing dashes.  If this keyword parameter
 *    is not given the default mode for creating files is "-rw-rw-r--"
 *    (664).  Note that the system still applies the current umask to
 *    the mode when creating a file.  Example:
 *
 *       "wb,mode=-rw-r--"
 *
 * samethread
 *
 *    Assumes that the object is only used by the creating thread and
 *    disables any internal locking.  This keyword is also found on
 *    IBM systems.
 *
 * nonblock
 *
 *    The object is opened in non-blocking mode.  This is the same as
 *    calling gpgrt_set_nonblock on the file.
 *
 * sysopen
 *
 *    The object is opened in GPGRT_SYSHD_HANDLE mode.  On POSIX this
 *    is a NOP but under Windows the direct W32 API functions (HANDLE)
 *    are used instead of their libc counterparts (fd).  This flag
 *    also allows to use file names longer than MAXPATH.  Note that
 *    gpgrt_fileno does not not work for such a stream under Windows.
 *
 * pollable
 *
 *    The object is opened in a way suitable for use with es_poll.  On
 *    POSIX this is a NOP but under Windows we create up to two
 *    threads, one for reading and one for writing, do any I/O there,
 *    and synchronize with them in order to support es_poll.
 *
 * Note: R_CMODE is optional because is only required by functions
 * which are able to creat a file.
 */
static int
parse_mode (const char *modestr,
            unsigned int *modeflags,
            unsigned int *r_xmode,
            unsigned int *r_cmode)
{
  unsigned int omode, oflags, cmode;
  int got_cmode = 0;

  *r_xmode = 0;

  switch (*modestr)
    {
    case 'r':
      omode = O_RDONLY;
      oflags = 0;
      break;
    case 'w':
      omode = O_WRONLY;
      oflags = O_TRUNC | O_CREAT;
      break;
    case 'a':
      omode = O_WRONLY;
      oflags = O_APPEND | O_CREAT;
      break;
    default:
      _set_errno (EINVAL);
      return -1;
    }
  for (modestr++; *modestr; modestr++)
    {
      switch (*modestr)
        {
        case '+':
          omode = O_RDWR;
          break;
        case 'b':
          oflags |= O_BINARY;
          break;
        case 'x':
          oflags |= O_EXCL;
          break;
        case ',':
          goto keyvalue;
        default: /* Ignore unknown flags.  */
          break;
        }
    }

 keyvalue:
  /* Parse key/value pairs (similar to fopen on mainframes).  */
  for (cmode=0; *modestr == ','; modestr += strcspn (modestr, ","))
    {
      modestr++;
      modestr += strspn (modestr, " \t");
      if (!strncmp (modestr, "mode=", 5))
        {
          static struct {
            char letter;
            unsigned int value;
          } table[] = { { '-', 0 },
                        { 'r', S_IRUSR }, { 'w', S_IWUSR }, { 'x', S_IXUSR },
                        { 'r', S_IRGRP }, { 'w', S_IWGRP }, { 'x', S_IXGRP },
                        { 'r', S_IROTH }, { 'w', S_IWOTH }, { 'x', S_IXOTH }};
          int idx;

          got_cmode = 1;
          modestr += 5;
          /* For now we only support a string as used by ls(1) and no
             octal numbers.  The first character must be a dash.  */
          for (idx=0; idx < 10 && *modestr; idx++, modestr++)
            {
              if (*modestr == table[idx].letter)
                cmode |= table[idx].value;
              else if (*modestr != '-')
                break;
            }
          if (*modestr && !strchr (" \t,", *modestr))
            {
              _set_errno (EINVAL);
              return -1;
            }
        }
      else if (!strncmp (modestr, "samethread", 10))
        {
          modestr += 10;
          if (*modestr && !strchr (" \t,", *modestr))
            {
              _set_errno (EINVAL);
              return -1;
            }
          *r_xmode |= X_SAMETHREAD;
        }
      else if (!strncmp (modestr, "nonblock", 8))
        {
          modestr += 8;
          if (*modestr && !strchr (" \t,", *modestr))
            {
              _set_errno (EINVAL);
              return -1;
            }
          oflags |= O_NONBLOCK;
#if HAVE_W32_SYSTEM
          /* Currently, nonblock implies pollable on Windows.  */
          *r_xmode |= X_POLLABLE;
#endif
        }
      else if (!strncmp (modestr, "sysopen", 7))
        {
          modestr += 7;
          if (*modestr && !strchr (" \t,", *modestr))
            {
              _set_errno (EINVAL);
              return -1;
            }
          *r_xmode |= X_SYSOPEN;
        }
      else if (!strncmp (modestr, "pollable", 8))
        {
          modestr += 8;
          if (*modestr && !strchr (" \t,", *modestr))
            {
              _set_errno (EINVAL);
              return -1;
            }
          *r_xmode |= X_POLLABLE;
        }
    }
  if (!got_cmode)
    cmode = (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);

  *modeflags = (omode | oflags);
  if (r_cmode)
    *r_cmode = cmode;
  return 0;
}



/*
 * Low level stream functionality.
 */

static int
fill_stream (estream_t stream)
{
  size_t bytes_read = 0;
  int err;

  if (!stream->intern->func_read)
    {
      _set_errno (EOPNOTSUPP);
      err = -1;
    }
  else if (!stream->buffer_size)
    err = 0;
  else
    {
      gpgrt_cookie_read_function_t func_read = stream->intern->func_read;
      gpgrt_ssize_t ret;

      ret = (*func_read) (stream->intern->cookie,
			  stream->buffer, stream->buffer_size);
      if (ret == -1)
	{
	  bytes_read = 0;
	  err = -1;
#if EWOULDBLOCK != EAGAIN
          if (errno == EWOULDBLOCK)
            _set_errno (EAGAIN);
#endif
	}
      else
	{
	  bytes_read = ret;
	  err = 0;
	}
    }

  if (err)
    {
      if (errno != EAGAIN)
        {
          if (errno == EPIPE)
            stream->intern->indicators.hup = 1;
          stream->intern->indicators.err = 1;
        }
    }
  else if (!bytes_read)
    stream->intern->indicators.eof = 1;

  stream->intern->offset += stream->data_len;
  stream->data_len = bytes_read;
  stream->data_offset = 0;

  return err;
}

static int
flush_stream (estream_t stream)
{
  gpgrt_cookie_write_function_t func_write = stream->intern->func_write;
  int err;

  gpgrt_assert (stream->flags.writing);

  if (stream->data_offset)
    {
      size_t bytes_written;
      size_t data_flushed;
      gpgrt_ssize_t ret;

      if (! func_write)
	{
          _set_errno (EOPNOTSUPP);
          err = -1;
	  goto out;
	}

      /* Note: to prevent an endless loop caused by user-provided
	 write-functions that pretend to have written more bytes than
	 they were asked to write, we have to check for
	 "(stream->data_offset - data_flushed) > 0" instead of
	 "stream->data_offset - data_flushed".  */

      data_flushed = 0;
      err = 0;

      while ((((gpgrt_ssize_t) (stream->data_offset - data_flushed)) > 0)
             && !err)
	{
	  ret = (*func_write) (stream->intern->cookie,
			       stream->buffer + data_flushed,
			       stream->data_offset - data_flushed);
	  if (ret == -1)
	    {
	      bytes_written = 0;
	      err = -1;
#if EWOULDBLOCK != EAGAIN
              if (errno == EWOULDBLOCK)
                _set_errno (EAGAIN);
#endif
	    }
	  else
	    bytes_written = ret;

	  data_flushed += bytes_written;
	  if (err)
	    break;
	}

      stream->data_flushed += data_flushed;
      if (stream->data_offset == data_flushed)
	{
	  stream->intern->offset += stream->data_offset;
	  stream->data_offset = 0;
	  stream->data_flushed = 0;
	}
    }
  else
    err = 0;

  /* Always propagate flush event in case gpgrt_fflush was called
   * explictly to do flush buffers in caller's cookie functions.  */
  (*func_write) (stream->intern->cookie, NULL, 0);

 out:

  if (err && errno != EAGAIN)
    {
      if (errno == EPIPE)
        stream->intern->indicators.hup = 1;
      stream->intern->indicators.err = 1;
    }

  return err;
}


/*
 * Discard buffered data for STREAM.
 */
static void
es_empty (estream_t stream)
{
  gpgrt_assert (!stream->flags.writing);
  stream->data_len = 0;
  stream->data_offset = 0;
  stream->unread_data_len = 0;
}


/*
 * Initialize STREAM.
 */
static void
init_stream_obj (estream_t stream,
                 void *cookie, es_syshd_t *syshd,
                 gpgrt_stream_backend_kind_t kind,
                 struct cookie_io_functions_s functions,
                 unsigned int modeflags, unsigned int xmode)
{
  stream->intern->kind = kind;
  stream->intern->cookie = cookie;
  stream->intern->opaque = NULL;
  stream->intern->offset = 0;
  stream->intern->func_read = functions.public.func_read;
  stream->intern->func_write = functions.public.func_write;
  stream->intern->func_seek = functions.public.func_seek;
  stream->intern->func_ioctl = functions.func_ioctl;
  stream->intern->func_close = functions.public.func_close;
  stream->intern->strategy = _IOFBF;
  stream->intern->syshd = *syshd;
  stream->intern->print_ntotal = 0;
  stream->intern->indicators.err = 0;
  stream->intern->indicators.eof = 0;
  stream->intern->indicators.hup = 0;
  stream->intern->is_stdstream = 0;
  stream->intern->stdstream_fd = 0;
  stream->intern->deallocate_buffer = 0;
  stream->intern->printable_fname = NULL;
  stream->intern->printable_fname_inuse = 0;
  stream->intern->samethread = !! (xmode & X_SAMETHREAD);
  stream->intern->onclose = NULL;

  stream->data_len = 0;
  stream->data_offset = 0;
  stream->data_flushed = 0;
  stream->unread_data_len = 0;
  /* Depending on the modeflags we set whether we start in writing or
     reading mode.  This is required in case we are working on a
     stream which is not seeekable (like stdout).  Without this
     pre-initialization we would do a seek at the first write call and
     as this will fail no output will be delivered. */
  if ((modeflags & O_WRONLY) || (modeflags & O_RDWR) )
    stream->flags.writing = 1;
  else
    stream->flags.writing = 0;
}


/*
 * Deinitialize the STREAM object.  This does _not_ free the memory,
 * destroys the lock, or closes the underlying descriptor.
 */
static int
deinit_stream_obj (estream_t stream)
{
  gpgrt_cookie_close_function_t func_close;
  int err, tmp_err;

  trace (("enter: stream %p", stream));
  func_close = stream->intern->func_close;

  err = 0;
  if (stream->flags.writing)
    {
      tmp_err = flush_stream (stream);
      if (!err)
        err = tmp_err;
    }
  if (func_close)
    {
      trace (("stream %p calling func_close", stream));
      tmp_err = func_close (stream->intern->cookie);
      if (!err)
        err = tmp_err;
    }

  mem_free (stream->intern->printable_fname);
  stream->intern->printable_fname = NULL;
  stream->intern->printable_fname_inuse = 0;
  while (stream->intern->onclose)
    {
      notify_list_t tmp = stream->intern->onclose->next;
      mem_free (stream->intern->onclose);
      stream->intern->onclose = tmp;
    }

  trace_errno (err, ("leave: stream %p err=%d", stream, err));
  return err;
}


/*
 * Create a new stream and initialize it.  On success the new stream
 * handle is stored at R_STREAM.  On failure NULL is stored at
 * R_STREAM.
 */
static int
create_stream (estream_t *r_stream, void *cookie, es_syshd_t *syshd,
               gpgrt_stream_backend_kind_t kind,
               struct cookie_io_functions_s functions, unsigned int modeflags,
               unsigned int xmode, int with_locked_list)
{
  estream_internal_t stream_internal_new;
  estream_t stream_new;
  int err;
#if HAVE_W32_SYSTEM
  void *old_cookie = NULL;
#endif

  stream_new = NULL;
  stream_internal_new = NULL;

#if HAVE_W32_SYSTEM
  if ((xmode & X_POLLABLE) && kind != BACKEND_W32)
    {
      /* We require the W32 backend, because only that allows us to
       * write directly using the native W32 API and to disable the
       * system clamp.  Note that func_w32_create has already been
       * called with the flag to disable the system call clamp.  */
      _set_errno (EINVAL);
      err = -1;
      goto out;
    }
#endif /*HAVE_W32_SYSTEM*/

  stream_new = mem_alloc (sizeof (*stream_new));
  if (! stream_new)
    {
      err = -1;
      goto out;
    }

  stream_internal_new = mem_alloc (sizeof (*stream_internal_new));
  if (! stream_internal_new)
    {
      err = -1;
      goto out;
    }

  stream_new->buffer = stream_internal_new->buffer;
  stream_new->buffer_size = sizeof (stream_internal_new->buffer);
  stream_new->unread_buffer = stream_internal_new->unread_buffer;
  stream_new->unread_buffer_size = sizeof (stream_internal_new->unread_buffer);
  stream_new->intern = stream_internal_new;

#if HAVE_W32_SYSTEM
  if ((xmode & X_POLLABLE))
    {
      void *new_cookie;

      err = _gpgrt_w32_pollable_create (&new_cookie, modeflags,
                                        functions, cookie);
      if (err)
        goto out;

      modeflags &= ~O_NONBLOCK;
      old_cookie = cookie;
      cookie = new_cookie;
      kind = BACKEND_W32_POLLABLE;
      functions = _gpgrt_functions_w32_pollable;
    }
#endif /*HAVE_W32_SYSTEM*/

  init_stream_obj (stream_new, cookie, syshd, kind, functions, modeflags,
                   xmode);
  init_stream_lock (stream_new);

  err = do_list_add (stream_new, with_locked_list);
  if (err)
    goto out;

  *r_stream = stream_new;

 out:

  if (err)
    {
      trace_errno (err, ("leave: err=%d", err));
      if (stream_new)
	{
	  deinit_stream_obj (stream_new);
          destroy_stream_lock (stream_new);
	  mem_free (stream_new->intern);
	  mem_free (stream_new);
	}
    }
#if HAVE_W32_SYSTEM
  else if (old_cookie)
    trace (("leave: success stream=%p cookie=%p,%p",
            *r_stream, old_cookie, cookie));
#endif
  else
    trace (("leave: success stream=%p cookie=%p", *r_stream, cookie));

  return err;
}


/*
 * Deinitialize a stream object and destroy it.  With CANCEL_MODE set
 * try to cancel as much as possible (see _gpgrt_fcancel).
 */
static int
do_close (estream_t stream, int cancel_mode, int with_locked_list)
{
  int err;

  trace (("stream %p %s", stream, with_locked_list? "(with locked list)":""));

  if (stream)
    {
      do_list_remove (stream, with_locked_list);
      if (cancel_mode)
        {
          stream->flags.writing = 0;
          es_empty (stream);
        }
      while (stream->intern->onclose)
        {
          notify_list_t tmp = stream->intern->onclose->next;

          if (stream->intern->onclose->fnc)
            stream->intern->onclose->fnc (stream,
                                          stream->intern->onclose->fnc_value);
          mem_free (stream->intern->onclose);
          stream->intern->onclose = tmp;
        }
      err = deinit_stream_obj (stream);
      destroy_stream_lock (stream);
      if (stream->intern->deallocate_buffer)
        mem_free (stream->buffer);
      mem_free (stream->intern);
      mem_free (stream);
    }
  else
    err = 0;

  trace_errno (err, ("stream %p err=%d", stream, err));
  return err;
}


/*
 * The onclose worker function which is called with a locked
 * stream.
 */
static int
do_onclose (estream_t stream, int mode,
            void (*fnc) (estream_t, void*), void *fnc_value)
{
  notify_list_t item;

  if (!mode)
    {
      for (item = stream->intern->onclose; item; item = item->next)
        if (item->fnc && item->fnc == fnc && item->fnc_value == fnc_value)
          item->fnc = NULL; /* Disable this notification.  */
    }
  else
    {
      item = mem_alloc (sizeof *item);
      if (!item)
        return -1;
      item->fnc = fnc;
      item->fnc_value = fnc_value;
      item->next = stream->intern->onclose;
      stream->intern->onclose = item;
    }
  return 0;
}


/*
 * Try to read BYTES_TO_READ bytes from STREAM into BUFFER in
 * unbuffered-mode, storing the amount of bytes read at BYTES_READ.
 */
static int
do_read_nbf (estream_t _GPGRT__RESTRICT stream,
	     unsigned char *_GPGRT__RESTRICT buffer,
	     size_t bytes_to_read, size_t *_GPGRT__RESTRICT bytes_read)
{
  gpgrt_cookie_read_function_t func_read = stream->intern->func_read;
  size_t data_read;
  gpgrt_ssize_t ret;
  int err;

  data_read = 0;
  err = 0;

  while (bytes_to_read - data_read)
    {
      ret = (*func_read) (stream->intern->cookie,
			  buffer + data_read, bytes_to_read - data_read);
      if (ret == -1)
	{
	  err = -1;
#if EWOULDBLOCK != EAGAIN
          if (errno == EWOULDBLOCK)
            _set_errno (EAGAIN);
#endif
	  break;
	}
      else if (ret)
	data_read += ret;
      else
	break;
    }

  stream->intern->offset += data_read;
  *bytes_read = data_read;

  return err;
}


/*
 * Helper for check_pending.
 */
static int
check_pending_nbf (estream_t _GPGRT__RESTRICT stream)
{
  gpgrt_cookie_read_function_t func_read = stream->intern->func_read;
  char buffer[1];

  if (!(*func_read) (stream->intern->cookie, buffer, 0))
    return 1; /* Pending bytes.  */
  return 0; /* No pending bytes or error.  */
}


/*
 * Try to read BYTES_TO_READ bytes from STREAM into BUFFER in
 * fully-buffered-mode, storing the amount of bytes read at
 * BYTES_READ.
 */
static int
do_read_fbf (estream_t _GPGRT__RESTRICT stream,
	     unsigned char *_GPGRT__RESTRICT buffer,
	     size_t bytes_to_read, size_t *_GPGRT__RESTRICT bytes_read)
{
  size_t data_available;
  size_t data_to_read;
  size_t data_read;
  int err;

  data_read = 0;
  err = 0;

  while ((bytes_to_read - data_read) && (! err))
    {
      if (stream->data_offset == stream->data_len)
	{
	  /* Nothing more to read in current container, try to
	     fill container with new data.  */
	  err = fill_stream (stream);
	  if (! err)
	    if (! stream->data_len)
	      /* Filling did not result in any data read.  */
	      break;
	}

      if (! err)
	{
	  /* Filling resulted in some new data.  */

	  data_to_read = bytes_to_read - data_read;
	  data_available = stream->data_len - stream->data_offset;
	  if (data_to_read > data_available)
	    data_to_read = data_available;

	  memcpy (buffer + data_read,
		  stream->buffer + stream->data_offset, data_to_read);
	  stream->data_offset += data_to_read;
	  data_read += data_to_read;
	}
    }

  *bytes_read = data_read;

  return err;
}


/*
 * Helper for check_pending.
 */
static int
check_pending_fbf (estream_t _GPGRT__RESTRICT stream)
{
  gpgrt_cookie_read_function_t func_read = stream->intern->func_read;
  char buffer[1];

  if (stream->data_offset == stream->data_len)
    {
      /* Nothing more to read in current container, check whether it
         would be possible to fill the container with new data.  */
      if (!(*func_read) (stream->intern->cookie, buffer, 0))
        return 1; /* Pending bytes.  */
    }
  else
    return 1;
  return 0;
}


/*
 * Try to read BYTES_TO_READ bytes from STREAM into BUFFER in
 * line-buffered-mode, storing the amount of bytes read at BYTES_READ.
 */
static int
do_read_lbf (estream_t _GPGRT__RESTRICT stream,
	     unsigned char *_GPGRT__RESTRICT buffer,
	     size_t bytes_to_read, size_t *_GPGRT__RESTRICT bytes_read)
{
  int err;

  err = do_read_fbf (stream, buffer, bytes_to_read, bytes_read);

  return err;
}


/*
 * Try to read BYTES_TO_READ bytes from STREAM into BUFFER, storing
 * the amount of bytes read at BYTES_READ.
 */
static int
es_readn (estream_t _GPGRT__RESTRICT stream,
	  void *_GPGRT__RESTRICT buffer_arg,
	  size_t bytes_to_read, size_t *_GPGRT__RESTRICT bytes_read)
{
  unsigned char *buffer = (unsigned char *)buffer_arg;
  size_t data_read_unread, data_read;
  int err;

  data_read_unread = 0;
  data_read = 0;
  err = 0;

  if (stream->flags.writing)
    {
      /* Switching to reading mode -> flush output.  */
      err = flush_stream (stream);
      if (err)
	goto out;
      stream->flags.writing = 0;
    }

  /* Read unread data first.  */
  while ((bytes_to_read - data_read_unread) && stream->unread_data_len)
    {
      buffer[data_read_unread]
	= stream->unread_buffer[stream->unread_data_len - 1];
      stream->unread_data_len--;
      data_read_unread++;
    }

  switch (stream->intern->strategy)
    {
    case _IONBF:
      err = do_read_nbf (stream,
			 buffer + data_read_unread,
			 bytes_to_read - data_read_unread, &data_read);
      break;
    case _IOLBF:
      err = do_read_lbf (stream,
			 buffer + data_read_unread,
			 bytes_to_read - data_read_unread, &data_read);
      break;
    case _IOFBF:
      err = do_read_fbf (stream,
			 buffer + data_read_unread,
			 bytes_to_read - data_read_unread, &data_read);
      break;
    }

 out:

  if (bytes_read)
    *bytes_read = data_read_unread + data_read;

  return err;
}


/*
 * Return true if at least one byte is pending for read.  This is a
 * best effort check and it it possible that bytes are still pending
 * even if false is returned.  If the stream is in writing mode it is
 * switched to read mode.
 */
static int
check_pending (estream_t _GPGRT__RESTRICT stream)
{
  if (stream->flags.writing)
    {
      /* Switching to reading mode -> flush output.  */
      if (flush_stream (stream))
	return 0; /* Better return 0 on error.  */
      stream->flags.writing = 0;
    }

  /* Check unread data first.  */
  if (stream->unread_data_len)
    return 1;

  switch (stream->intern->strategy)
    {
    case _IONBF:
      return check_pending_nbf (stream);
    case _IOLBF:
    case _IOFBF:
      return check_pending_fbf (stream);
    }

  return 0;
}


/*
 * Try to unread DATA_N bytes from DATA into STREAM, storing the
 * amount of bytes successfully unread at BYTES_UNREAD.
 */
static void
es_unreadn (estream_t _GPGRT__RESTRICT stream,
	    const unsigned char *_GPGRT__RESTRICT data, size_t data_n,
	    size_t *_GPGRT__RESTRICT bytes_unread)
{
  size_t space_left;

  space_left = stream->unread_buffer_size - stream->unread_data_len;

  if (data_n > space_left)
    data_n = space_left;

  if (! data_n)
    goto out;

  memcpy (stream->unread_buffer + stream->unread_data_len, data, data_n);
  stream->unread_data_len += data_n;
  stream->intern->indicators.eof = 0;

 out:

  if (bytes_unread)
    *bytes_unread = data_n;
}


/*
 * Seek in STREAM.
 */
static int
es_seek (estream_t _GPGRT__RESTRICT stream, gpgrt_off_t offset, int whence,
	 gpgrt_off_t *_GPGRT__RESTRICT offset_new)
{
  gpgrt_cookie_seek_function_t func_seek = stream->intern->func_seek;
  int err, ret;
  gpgrt_off_t off;

  if (! func_seek)
    {
      _set_errno (EOPNOTSUPP);
      err = -1;
      goto out;
    }

  if (stream->flags.writing)
    {
      /* Flush data first in order to prevent flushing it to the wrong
	 offset.  */
      err = flush_stream (stream);
      if (err)
	goto out;
      stream->flags.writing = 0;
    }

  off = offset;
  if (whence == SEEK_CUR)
    {
      off = off - stream->data_len + stream->data_offset;
      off -= stream->unread_data_len;
    }

  ret = (*func_seek) (stream->intern->cookie, &off, whence);
  if (ret == -1)
    {
      err = -1;
#if EWOULDBLOCK != EAGAIN
      if (errno == EWOULDBLOCK)
        _set_errno (EAGAIN);
#endif
      goto out;
    }

  err = 0;
  es_empty (stream);

  if (offset_new)
    *offset_new = off;

  stream->intern->indicators.eof = 0;
  stream->intern->offset = off;

 out:

  if (err)
    {
      if (errno == EPIPE)
        stream->intern->indicators.hup = 1;
      stream->intern->indicators.err = 1;
    }

  return err;
}


/*
 * Write BYTES_TO_WRITE bytes from BUFFER into STREAM in
 * unbuffered-mode, storing the amount of bytes written at
 * BYTES_WRITTEN.
 */
static int
es_write_nbf (estream_t _GPGRT__RESTRICT stream,
	      const unsigned char *_GPGRT__RESTRICT buffer,
	      size_t bytes_to_write, size_t *_GPGRT__RESTRICT bytes_written)
{
  gpgrt_cookie_write_function_t func_write = stream->intern->func_write;
  size_t data_written;
  gpgrt_ssize_t ret;
  int err;

  if (bytes_to_write && (! func_write))
    {
      _set_errno (EOPNOTSUPP);
      err = -1;
      goto out;
    }

  data_written = 0;
  err = 0;

  while (bytes_to_write - data_written)
    {
      ret = (*func_write) (stream->intern->cookie,
			   buffer + data_written,
			   bytes_to_write - data_written);
      if (ret == -1)
	{
	  err = -1;
#if EWOULDBLOCK != EAGAIN
          if (errno == EWOULDBLOCK)
            _set_errno (EAGAIN);
#endif
	  break;
	}
      else
	data_written += ret;
    }

  stream->intern->offset += data_written;
  *bytes_written = data_written;

 out:

  return err;
}


/*
 * Write BYTES_TO_WRITE bytes from BUFFER into STREAM in
 * fully-buffered-mode, storing the amount of bytes written at
 * BYTES_WRITTEN.
 */
static int
es_write_fbf (estream_t _GPGRT__RESTRICT stream,
	      const unsigned char *_GPGRT__RESTRICT buffer,
	      size_t bytes_to_write, size_t *_GPGRT__RESTRICT bytes_written)
{
  size_t space_available;
  size_t data_to_write;
  size_t data_written;
  int err;

  data_written = 0;
  err = 0;

  while ((bytes_to_write - data_written) && (! err))
    {
      if (stream->data_offset == stream->buffer_size)
	/* Container full, flush buffer.  */
	err = flush_stream (stream);

      if (! err)
	{
	  /* Flushing resulted in empty container.  */

	  data_to_write = bytes_to_write - data_written;
	  space_available = stream->buffer_size - stream->data_offset;
	  if (data_to_write > space_available)
	    data_to_write = space_available;

	  memcpy (stream->buffer + stream->data_offset,
		  buffer + data_written, data_to_write);
	  stream->data_offset += data_to_write;
	  data_written += data_to_write;
	}
    }

  *bytes_written = data_written;

  return err;
}


/* Write BYTES_TO_WRITE bytes from BUFFER into STREAM in
   line-buffered-mode, storing the amount of bytes written in
   *BYTES_WRITTEN.  */
static int
es_write_lbf (estream_t _GPGRT__RESTRICT stream,
	      const unsigned char *_GPGRT__RESTRICT buffer,
	      size_t bytes_to_write, size_t *_GPGRT__RESTRICT bytes_written)
{
  size_t data_flushed = 0;
  size_t data_buffered = 0;
  unsigned char *nlp;
  int err = 0;

  nlp = memrchr (buffer, '\n', bytes_to_write);
  if (nlp)
    {
      /* Found a newline, directly write up to (including) this
	 character.  */
      err = flush_stream (stream);
      if (!err)
	err = es_write_nbf (stream, buffer, nlp - buffer + 1, &data_flushed);
    }

  if (!err)
    {
      /* Write remaining data fully buffered.  */
      err = es_write_fbf (stream, buffer + data_flushed,
			  bytes_to_write - data_flushed, &data_buffered);
    }

  *bytes_written = data_flushed + data_buffered;
  return err;
}


/* Write BYTES_TO_WRITE bytes from BUFFER into STREAM in, storing the
   amount of bytes written in BYTES_WRITTEN.  */
static int
es_writen (estream_t _GPGRT__RESTRICT stream,
	   const void *_GPGRT__RESTRICT buffer,
	   size_t bytes_to_write, size_t *_GPGRT__RESTRICT bytes_written)
{
  size_t data_written;
  int err;

  data_written = 0;
  err = 0;

  if (!stream->flags.writing)
    {
      /* Switching to writing mode -> discard input data and seek to
	 position at which reading has stopped.  We can do this only
	 if a seek function has been registered. */
      if (stream->intern->func_seek)
        {
          err = es_seek (stream, 0, SEEK_CUR, NULL);
          if (err)
            {
              if (errno == ESPIPE)
                err = 0;
              else
                goto out;
            }
          stream->flags.writing = 1;
        }
    }

  switch (stream->intern->strategy)
    {
    case _IONBF:
      err = es_write_nbf (stream, buffer, bytes_to_write, &data_written);
      break;

    case _IOLBF:
      err = es_write_lbf (stream, buffer, bytes_to_write, &data_written);
      break;

    case _IOFBF:
      err = es_write_fbf (stream, buffer, bytes_to_write, &data_written);
      break;
    }

 out:

  if (bytes_written)
    *bytes_written = data_written;

  return err;
}


static int
peek_stream (estream_t _GPGRT__RESTRICT stream,
             unsigned char **_GPGRT__RESTRICT data,
             size_t *_GPGRT__RESTRICT data_len)
{
  int err;

  if (stream->flags.writing)
    {
      /* Switching to reading mode -> flush output.  */
      err = flush_stream (stream);
      if (err)
	goto out;
      stream->flags.writing = 0;
    }

  if (stream->data_offset == stream->data_len)
    {
      /* Refill container.  */
      err = fill_stream (stream);
      if (err)
	goto out;
    }

  if (data)
    *data = stream->buffer + stream->data_offset;
  if (data_len)
    *data_len = stream->data_len - stream->data_offset;
  err = 0;

 out:

  return err;
}


/* Skip SIZE bytes of input data contained in buffer.  */
static int
skip_stream (estream_t stream, size_t size)
{
  int err;

  if (stream->data_offset + size > stream->data_len)
    {
      _set_errno (EINVAL);
      err = -1;
    }
  else
    {
      stream->data_offset += size;
      err = 0;
    }

  return err;
}


static int
doreadline (estream_t _GPGRT__RESTRICT stream, size_t max_length,
            char *_GPGRT__RESTRICT *_GPGRT__RESTRICT line,
            size_t *_GPGRT__RESTRICT line_length)
{
  size_t line_size;
  estream_t line_stream;
  char *line_new;
  void *line_stream_cookie;
  char *newline;
  unsigned char *data;
  size_t data_len;
  int err;
  es_syshd_t syshd;

  line_new = NULL;
  line_stream = NULL;
  line_stream_cookie = NULL;

  err = func_mem_create (&line_stream_cookie, NULL, 0, 0,
                         BUFFER_BLOCK_SIZE, 1,
                         mem_realloc, mem_free,
                         O_RDWR,
                         0);
  if (err)
    goto out;

  memset (&syshd, 0, sizeof syshd);
  err = create_stream (&line_stream, line_stream_cookie,
                       &syshd, BACKEND_MEM,
                       estream_functions_mem, O_RDWR, 1, 0);
  if (err)
    goto out;

  {
    size_t space_left = max_length;

    line_size = 0;
    for (;;)
      {
        if (max_length && (space_left == 1))
          break;

        err = peek_stream (stream, &data, &data_len);
        if (err || (! data_len))
          break;

        if (data_len > (space_left - 1))
          data_len = space_left - 1;

        newline = memchr (data, '\n', data_len);
        if (newline)
          {
            data_len = (newline - (char *) data) + 1;
            err = _gpgrt_write (line_stream, data, data_len, NULL);
            if (! err)
              {
                /* Not needed: space_left -= data_len */
                line_size += data_len;
                skip_stream (stream, data_len);
                break; /* endless loop */
              }
          }
        else
          {
            err = _gpgrt_write (line_stream, data, data_len, NULL);
            if (! err)
              {
                space_left -= data_len;
                line_size += data_len;
                skip_stream (stream, data_len);
              }
          }
        if (err)
          break;
      }
  }
  if (err)
    goto out;

  /* Complete line has been written to line_stream.  */

  if ((max_length > 1) && (! line_size))
    {
      stream->intern->indicators.eof = 1;
      goto out;
    }

  err = es_seek (line_stream, 0, SEEK_SET, NULL);
  if (err)
    goto out;

  if (! *line)
    {
      line_new = mem_alloc (line_size + 1);
      if (! line_new)
	{
	  err = -1;
	  goto out;
	}
    }
  else
    line_new = *line;

  err = _gpgrt_read (line_stream, line_new, line_size, NULL);
  if (err)
    goto out;

  line_new[line_size] = '\0';

  if (! *line)
    *line = line_new;
  if (line_length)
    *line_length = line_size;

 out:

  if (line_stream)
    do_close (line_stream, 0, 0);
  else if (line_stream_cookie)
    func_mem_destroy (line_stream_cookie);

  if (err)
    {
      if (! *line)
	mem_free (line_new);
      stream->intern->indicators.err = 1;
    }

  return err;
}


/* Output function used by estream_format.  */
static int
print_writer (void *outfncarg, const char *buf, size_t buflen)
{
  estream_t stream = outfncarg;
  size_t nwritten;
  int rc;

  nwritten = 0;
  rc = es_writen (stream, buf, buflen, &nwritten);
  stream->intern->print_ntotal += nwritten;
  return rc;
}


/* The core of our printf function.  This is called in locked state. */
static int
do_print_stream (estream_t _GPGRT__RESTRICT stream,
                 gpgrt_string_filter_t sf, void *sfvalue,
                 const char *_GPGRT__RESTRICT format, va_list ap)
{
  int rc;

  stream->intern->print_ntotal = 0;
  rc = _gpgrt_estream_format (print_writer, stream, sf, sfvalue, format, ap);
  if (rc)
    return -1;
  return (int)stream->intern->print_ntotal;
}


static int
es_set_buffering (estream_t _GPGRT__RESTRICT stream,
		  char *_GPGRT__RESTRICT buffer, int mode, size_t size)
{
  int err;

  /* Flush or empty buffer depending on mode.  */
  if (stream->flags.writing)
    {
      err = flush_stream (stream);
      if (err)
	goto out;
    }
  else
    es_empty (stream);

  stream->intern->indicators.eof = 0;

  /* Free old buffer in case that was allocated by this function.  */
  if (stream->intern->deallocate_buffer)
    {
      stream->intern->deallocate_buffer = 0;
      mem_free (stream->buffer);
      stream->buffer = NULL;
    }

  if (mode == _IONBF)
    stream->buffer_size = 0;
  else
    {
      void *buffer_new;

      if (buffer)
	buffer_new = buffer;
      else
	{
          if (!size)
            size = BUFSIZ;
	  buffer_new = mem_alloc (size);
	  if (! buffer_new)
	    {
	      err = -1;
	      goto out;
	    }
	}

      stream->buffer = buffer_new;
      stream->buffer_size = size;
      if (! buffer)
	stream->intern->deallocate_buffer = 1;
    }
  stream->intern->strategy = mode;
  err = 0;

 out:

  return err;
}


static gpgrt_off_t
es_offset_calculate (estream_t stream)
{
  gpgrt_off_t offset;

  offset = stream->intern->offset + stream->data_offset;
  if (offset < stream->unread_data_len)
    /* Offset undefined.  */
    offset = 0;
  else
    offset -= stream->unread_data_len;

  return offset;
}


static void
es_opaque_ctrl (estream_t _GPGRT__RESTRICT stream,
                void *_GPGRT__RESTRICT opaque_new,
		void **_GPGRT__RESTRICT opaque_old)
{
  if (opaque_old)
    *opaque_old = stream->intern->opaque;
  if (opaque_new)
    stream->intern->opaque = opaque_new;
}


/* API.  */

estream_t
_gpgrt_fopen (const char *_GPGRT__RESTRICT path,
              const char *_GPGRT__RESTRICT mode)
{
  unsigned int modeflags, cmode, xmode;
  int create_called = 0;
  estream_t stream = NULL;
  void *cookie = NULL;
  int err;
  struct cookie_io_functions_s *functions;
  es_syshd_t syshd;
  int kind;

  err = parse_mode (mode, &modeflags, &xmode, &cmode);
  if (err)
    goto leave;

  /* Convenience hack so that we can use /dev/null on Windows.  */
#ifdef HAVE_W32_SYSTEM
  if (path && !strcmp (path, "/dev/null"))
    path = "nul";
#endif

#ifdef HAVE_W32_SYSTEM
  if ((xmode & X_SYSOPEN))
    {
      kind = BACKEND_W32;
      functions = &estream_functions_w32;
      syshd.type = ES_SYSHD_HANDLE;
      err = func_file_create_w32 (&cookie, &syshd.u.handle,
                                  path, modeflags, cmode);
    }
  else
#endif /* W32 */
    {
      kind = BACKEND_FD;
      functions = &estream_functions_fd;
      syshd.type = ES_SYSHD_FD;
      err = func_file_create (&cookie, &syshd.u.fd,
                              path, modeflags, cmode);
    }
  if (err)
    goto leave;

  create_called = 1;
  err = create_stream (&stream, cookie, &syshd, kind,
                       *functions, modeflags, xmode, 0);
  if (err)
    goto leave;

  if (stream && path)
    fname_set_internal (stream, path, 1);

 leave:
  if (err && create_called)
    functions->public.func_close (cookie);

  return stream;
}



/* Create a new estream object in memory.  If DATA is not NULL this
   buffer will be used as the memory buffer; thus after this functions
   returns with the success the the memory at DATA belongs to the new
   estream.  The allocated length of DATA is given by DATA_LEN and its
   used length by DATA_N.  Usually this is malloced buffer; if a
   static buffer is provided, the caller must pass false for GROW and
   provide a dummy function for FUNC_FREE.  FUNC_FREE and FUNC_REALLOC
   allow the caller to provide custom functions for realloc and free
   to be used by the new estream object.  Note that the realloc
   function is also used for initial allocation.  If DATA is NULL a
   buffer is internally allocated; either using internal function or
   those provide by the caller.  It is an error to provide a realloc
   function but no free function.  Providing only a free function is
   allowed as long as GROW is false.  */
estream_t
_gpgrt_mopen (void *_GPGRT__RESTRICT data, size_t data_n, size_t data_len,
              unsigned int grow,
              func_realloc_t func_realloc, func_free_t func_free,
              const char *_GPGRT__RESTRICT mode)
{
  int create_called = 0;
  estream_t stream = NULL;
  void *cookie = NULL;
  unsigned int modeflags, xmode;
  int err;
  es_syshd_t syshd;

  err = parse_mode (mode, &modeflags, &xmode, NULL);
  if (err)
    goto out;

  err = func_mem_create (&cookie, data, data_n, data_len,
                         BUFFER_BLOCK_SIZE, grow,
                         func_realloc, func_free, modeflags, 0);
  if (err)
    goto out;

  memset (&syshd, 0, sizeof syshd);
  create_called = 1;
  err = create_stream (&stream, cookie, &syshd, BACKEND_MEM,
                       estream_functions_mem, modeflags, xmode, 0);

 out:

  if (err && create_called)
    (*estream_functions_mem.public.func_close) (cookie);

  return stream;
}



estream_t
_gpgrt_fopenmem (size_t memlimit, const char *_GPGRT__RESTRICT mode)
{
  unsigned int modeflags, xmode;
  estream_t stream = NULL;
  void *cookie = NULL;
  es_syshd_t syshd;

  /* Memory streams are always read/write.  We use MODE only to get
     the append flag.  */
  if (parse_mode (mode, &modeflags, &xmode, NULL))
    return NULL;
  modeflags |= O_RDWR;

  if (func_mem_create (&cookie, NULL, 0, 0,
                       BUFFER_BLOCK_SIZE, 1,
                       mem_realloc, mem_free, modeflags,
                       memlimit))
    return NULL;

  memset (&syshd, 0, sizeof syshd);
  if (create_stream (&stream, cookie, &syshd, BACKEND_MEM,
                     estream_functions_mem, modeflags, xmode, 0))
    (*estream_functions_mem.public.func_close) (cookie);

  return stream;
}


/* This is the same as es_fopenmem but intializes the memory with a
   copy of (DATA,DATALEN).  The stream is initially set to the
   beginning.  If MEMLIMIT is not 0 but shorter than DATALEN it
   DATALEN will be used as the value for MEMLIMIT.  */
estream_t
_gpgrt_fopenmem_init (size_t memlimit, const char *_GPGRT__RESTRICT mode,
                      const void *data, size_t datalen)
{
  estream_t stream;

  if (memlimit && memlimit < datalen)
    memlimit = datalen;

  stream = _gpgrt_fopenmem (memlimit, mode);
  if (stream && data && datalen)
    {
      if (es_writen (stream, data, datalen, NULL))
        {
          int saveerrno = errno;
          _gpgrt_fclose (stream);
          stream = NULL;
          _set_errno (saveerrno);
        }
      else
        {
          es_seek (stream, 0L, SEEK_SET, NULL);
          stream->intern->indicators.eof = 0;
          stream->intern->indicators.err = 0;
        }
    }
  return stream;
}



estream_t
_gpgrt_fopencookie (void *_GPGRT__RESTRICT cookie,
                    const char *_GPGRT__RESTRICT mode,
                    gpgrt_cookie_io_functions_t functions)
{
  unsigned int modeflags, xmode;
  estream_t stream;
  int err;
  es_syshd_t syshd;
  struct cookie_io_functions_s io_functions = { functions, NULL };

  stream = NULL;
  modeflags = 0;

  err = parse_mode (mode, &modeflags, &xmode, NULL);
  if (err)
    goto out;

  memset (&syshd, 0, sizeof syshd);
  err = create_stream (&stream, cookie, &syshd, BACKEND_USER, io_functions,
                       modeflags, xmode, 0);
  if (err)
    goto out;

 out:
  return stream;
}



static estream_t
do_fdopen (int filedes, const char *mode, int no_close, int with_locked_list)
{
  int create_called = 0;
  estream_t stream = NULL;
  void *cookie = NULL;
  unsigned int modeflags, xmode;
  int err;
  es_syshd_t syshd;

  err = parse_mode (mode, &modeflags, &xmode, NULL);
  if (err)
    goto out;
  if ((xmode & X_SYSOPEN))
    {
      /* Not allowed for fdopen.  */
      _set_errno (EINVAL);
      err = -1;
      goto out;
    }

  err = func_fd_create (&cookie, filedes, modeflags, no_close);
  if (err)
    goto out;

  syshd.type = ES_SYSHD_FD;
  syshd.u.fd = filedes;
  create_called = 1;
  err = create_stream (&stream, cookie, &syshd,
                       BACKEND_FD, estream_functions_fd,
                       modeflags, xmode, with_locked_list);

  if (!err && stream)
    {
      if ((modeflags & O_NONBLOCK))
        err = stream->intern->func_ioctl (cookie, COOKIE_IOCTL_NONBLOCK,
                                          "", NULL);
    }

 out:
  if (err && create_called)
    (*estream_functions_fd.public.func_close) (cookie);

  return stream;
}

estream_t
_gpgrt_fdopen (int filedes, const char *mode)
{
  return do_fdopen (filedes, mode, 0, 0);
}

/* A variant of es_fdopen which does not close FILEDES at the end.  */
estream_t
_gpgrt_fdopen_nc (int filedes, const char *mode)
{
  return do_fdopen (filedes, mode, 1, 0);
}



static estream_t
do_fpopen (FILE *fp, const char *mode, int no_close, int with_locked_list)
{
  unsigned int modeflags, cmode, xmode;
  int create_called = 0;
  estream_t stream = NULL;
  void *cookie = NULL;
  int err;
  es_syshd_t syshd;

  err = parse_mode (mode, &modeflags, &xmode, &cmode);
  if (err)
    goto out;
  if ((xmode & X_SYSOPEN))
    {
      /* Not allowed for fpopen.  */
      _set_errno (EINVAL);
      err = -1;
      goto out;
    }

  if (fp)
    fflush (fp);
  err = func_fp_create (&cookie, fp, modeflags, no_close);
  if (err)
    goto out;

  syshd.type = ES_SYSHD_FD;
  syshd.u.fd = fp? fileno (fp): -1;
  create_called = 1;
  err = create_stream (&stream, cookie, &syshd,
                       BACKEND_FP, estream_functions_fp,
                       modeflags, xmode, with_locked_list);

 out:
  if (err && create_called)
    (*estream_functions_fp.public.func_close) (cookie);

  return stream;
}


/* Create an estream from the stdio stream FP.  This mechanism is
   useful in case the stdio streams have special properties and may
   not be mixed with fd based functions.  This is for example the case
   under Windows where the 3 standard streams are associated with the
   console whereas a duped and fd-opened stream of one of this stream
   won't be associated with the console.  As this messes things up it
   is easier to keep on using the standard I/O stream as a backend for
   estream. */
estream_t
_gpgrt_fpopen (FILE *fp, const char *mode)
{
  return do_fpopen (fp, mode, 0, 0);
}


/* Same as es_fpopen but does not close  FP at the end.  */
estream_t
_gpgrt_fpopen_nc (FILE *fp, const char *mode)
{
  return do_fpopen (fp, mode, 1, 0);
}



#ifdef HAVE_W32_SYSTEM
static estream_t
do_sockopen (SOCKET sock, const char *mode, int no_close, int with_locked_list)
{
  int create_called = 0;
  estream_t stream = NULL;
  void *cookie = NULL;
  unsigned int modeflags, xmode;
  int err;
  es_syshd_t syshd;

  err = parse_mode (mode, &modeflags, &xmode, NULL);
  if (err)
    goto out;
  if ((xmode & X_SYSOPEN))
    {
      /* Not allowed for sockopen.  */
      _set_errno (EINVAL);
      err = -1;
      goto out;
    }

  err = func_sock_create (&cookie, sock, modeflags, no_close);
  if (err)
    goto out;

  syshd.type = ES_SYSHD_SOCK;
  syshd.u.sock = sock;
  create_called = 1;
  err = create_stream (&stream, cookie, &syshd,
                       BACKEND_SOCK, estream_functions_sock,
                       modeflags, xmode, with_locked_list);

  if (!err && stream)
    {
      if ((modeflags & O_NONBLOCK))
        err = stream->intern->func_ioctl (cookie, COOKIE_IOCTL_NONBLOCK,
                                          "", NULL);
    }

 out:
  if (err && create_called)
    (*estream_functions_sock.public.func_close) (cookie);

  return stream;
}


estream_t
do_w32open (HANDLE hd, const char *mode,
            int no_close, int with_locked_list)
{
  unsigned int modeflags, cmode, xmode;
  int create_called = 0;
  estream_t stream = NULL;
  void *cookie = NULL;
  int err;
  es_syshd_t syshd;

  /* For obvious reasons we ignore sysmode here.  */
  err = parse_mode (mode, &modeflags, &xmode, &cmode);
  if (err)
    goto leave;

  /* If we are pollable we create the function cookie with syscall
   * clamp disabled.  This is because functions are called from
   * separate reader and writer threads in w32-stream.  */
  err = func_w32_create (&cookie, hd, modeflags,
                         no_close, !!(xmode & X_POLLABLE));
  if (err)
    goto leave;

  syshd.type = ES_SYSHD_HANDLE;
  syshd.u.handle = hd;
  create_called = 1;
  err = create_stream (&stream, cookie, &syshd,
                       BACKEND_W32, estream_functions_w32,
                       modeflags, xmode, with_locked_list);

 leave:
  if (err && create_called)
    (*estream_functions_w32.public.func_close) (cookie);

  return stream;
}
#endif /*HAVE_W32_SYSTEM*/

static estream_t
do_sysopen (es_syshd_t *syshd, const char *mode, int no_close)
{
  estream_t stream;

  switch (syshd->type)
    {
    case ES_SYSHD_FD:
#ifndef HAVE_W32_SYSTEM
    case ES_SYSHD_SOCK:
#endif
      stream = do_fdopen (syshd->u.fd, mode, no_close, 0);
      break;

#ifdef HAVE_W32_SYSTEM
    case ES_SYSHD_SOCK:
      stream = do_sockopen (syshd->u.sock, mode, no_close, 0);
      break;
    case ES_SYSHD_HANDLE:
      stream = do_w32open (syshd->u.handle, mode, no_close, 0);
      break;
#endif

    /* FIXME: Support RVIDs under Wince?  */

    default:
      _set_errno (EINVAL);
      stream = NULL;
    }
  return stream;
}

/* On POSIX systems this function is an alias for es_fdopen.  Under
   Windows it uses the bare W32 API and thus a HANDLE instead of a
   file descriptor.  */
estream_t
_gpgrt_sysopen (es_syshd_t *syshd, const char *mode)
{
  return do_sysopen (syshd, mode, 0);
}

/* Same as es_sysopen but the handle/fd will not be closed by
   es_fclose.  */
estream_t
_gpgrt_sysopen_nc (es_syshd_t *syshd, const char *mode)
{
  return do_sysopen (syshd, mode, 1);
}



/* Set custom standard descriptors to be used for stdin, stdout and
   stderr.  This function needs to be called before any of the
   standard streams are accessed.  This internal version uses a double
   dash inside its name. */
void
_gpgrt__set_std_fd (int no, int fd)
{
  /* fprintf (stderr, "es_set_std_fd(%d, %d)\n", no, fd); */
  lock_list ();
  if (no >= 0 && no < 3 && !custom_std_fds_valid[no])
    {
      custom_std_fds[no] = fd;
      custom_std_fds_valid[no] = 1;
    }
  unlock_list ();
}


/* Return the stream used for stdin, stdout or stderr.
   This internal version uses a double dash inside its name. */
estream_t
_gpgrt__get_std_stream (int fd)
{
  estream_list_t list_obj;
  estream_t stream = NULL;

  fd %= 3; /* We only allow 0, 1 or 2 but we don't want to return an error. */

  lock_list ();

  for (list_obj = estream_list; list_obj; list_obj = list_obj->next)
    if (list_obj->stream && list_obj->stream->intern->is_stdstream
        && list_obj->stream->intern->stdstream_fd == fd)
      {
	stream = list_obj->stream;
	break;
      }
  if (!stream)
    {
      /* Standard stream not yet created.  We first try to create them
         from registered file descriptors.  */
      if (!fd && custom_std_fds_valid[0])
        stream = do_fdopen (custom_std_fds[0], "r", 1, 1);
      else if (fd == 1 && custom_std_fds_valid[1])
        stream = do_fdopen (custom_std_fds[1], "a", 1, 1);
      else if (custom_std_fds_valid[2])
        stream = do_fdopen (custom_std_fds[2], "a", 1, 1);

      if (!stream)
        {
          /* Second try is to use the standard C streams.  */
          if (!fd)
            stream = do_fpopen (stdin, "r", 1, 1);
          else if (fd == 1)
            stream = do_fpopen (stdout, "a", 1, 1);
          else
            stream = do_fpopen (stderr, "a", 1, 1);
        }

      if (!stream)
        {
          /* Last try: Create a bit bucket.  */
          stream = do_fpopen (NULL, fd? "a":"r", 0, 1);
          if (!stream)
            {
              fprintf (stderr, "fatal: error creating a dummy estream"
                       " for %d: %s\n", fd, strerror (errno));
              _gpgrt_abort();
            }
        }

      stream->intern->is_stdstream = 1;
      stream->intern->stdstream_fd = fd;
      if (fd == 2)
        es_set_buffering (stream, NULL, _IOLBF, 0);
      fname_set_internal (stream,
                          fd == 0? "[stdin]" :
                          fd == 1? "[stdout]" : "[stderr]", 0);
    }

  unlock_list ();
  return stream;
}

/* Note: A "samethread" keyword given in "mode" is ignored and the
 * value used by STREAM is used instead.  Note that this function is
 * the reasons why some of the init and deinit code is split up into
 * several functions.  */
estream_t
_gpgrt_freopen (const char *_GPGRT__RESTRICT path,
                const char *_GPGRT__RESTRICT mode,
                estream_t _GPGRT__RESTRICT stream)
{
  int err;

  if (path)
    {
      unsigned int modeflags, cmode, xmode, dummy;
      int create_called;
      void *cookie;
      int fd;
      es_syshd_t syshd;

      cookie = NULL;
      create_called = 0;

  /* Convenience hack so that we can use /dev/null on Windows.  */
#ifdef HAVE_W32_SYSTEM
      if (!strcmp (path, "/dev/null"))
        path = "nul";
#endif

      xmode = stream->intern->samethread ? X_SAMETHREAD : 0;

      lock_stream (stream);

      deinit_stream_obj (stream);

      err = parse_mode (mode, &modeflags, &dummy, &cmode);
      if (err)
	goto leave;
      (void)dummy;

      err = func_file_create (&cookie, &fd, path, modeflags, cmode);
      if (err)
	goto leave;

      syshd.type = ES_SYSHD_FD;
      syshd.u.fd = fd;
      create_called = 1;
      init_stream_obj (stream, cookie, &syshd, BACKEND_FD,
                       estream_functions_fd, modeflags, xmode);

    leave:

      if (err)
	{
	  if (create_called)
	    func_fd_destroy (cookie);

	  do_close (stream, 0, 0);
	  stream = NULL;
	}
      else
        {
          if (path)
            fname_set_internal (stream, path, 1);
          unlock_stream (stream);
        }
    }
  else
    {
      /* FIXME?  We don't support re-opening at the moment.  */
      _set_errno (EINVAL);
      deinit_stream_obj (stream);
      do_close (stream, 0, 0);
      stream = NULL;
    }

  return stream;
}


int
_gpgrt_fclose (estream_t stream)
{
  int err;

  err = do_close (stream, 0, 0);

  return err;
}


/* gpgrt_fcancel does the same as gpgrt_fclose but tries to avoid
 * flushing out any data still held in internal buffers.  It may or
 * may not remove a new file created for that stream by the open
 * function.  */
int
_gpgrt_fcancel (estream_t stream)
{
  int err;

  err = do_close (stream, 1, 0);

  return err;
}


/* This is a special version of es_fclose which can be used with
   es_fopenmem to return the memory buffer.  This is feature is useful
   to write to a memory buffer using estream.  Note that the function
   does not close the stream if the stream does not support snatching
   the buffer.  On error NULL is stored at R_BUFFER.  Note that if no
   write operation has happened, NULL may also be stored at BUFFER on
   success.  The caller needs to release the returned memory using
   gpgrt_free.  */
int
_gpgrt_fclose_snatch (estream_t stream, void **r_buffer, size_t *r_buflen)
{
  int err;

  /* Note: There is no need to lock the stream in a close call.  The
     object will be destroyed after the close and thus any other
     contender for the lock would work on a closed stream.  */

  if (r_buffer)
    {
      cookie_ioctl_function_t func_ioctl = stream->intern->func_ioctl;
      size_t buflen;

      *r_buffer = NULL;

      if (!func_ioctl)
        {
          _set_errno (EOPNOTSUPP);
          err = -1;
          goto leave;
        }

      if (stream->flags.writing)
        {
          err = flush_stream (stream);
          if (err)
            goto leave;
          stream->flags.writing = 0;
        }

      err = func_ioctl (stream->intern->cookie, COOKIE_IOCTL_SNATCH_BUFFER,
                        r_buffer, &buflen);
      if (err)
        goto leave;
      if (r_buflen)
        *r_buflen = buflen;
    }

  err = do_close (stream, 0, 0);

 leave:
  if (err && r_buffer)
    {
      mem_free (*r_buffer);
      *r_buffer = NULL;
    }
  return err;
}


/* Register or unregister a close notification function for STREAM.
   FNC is the function to call and FNC_VALUE the value passed as
   second argument.  To register the notification the value for MODE
   must be 1.  If mode is 0 the function tries to remove or disable an
   already registered notification; for this to work the value of FNC
   and FNC_VALUE must be the same as with the registration and
   FNC_VALUE must be a unique value.  No error will be returned if
   MODE is 0.

   FIXME: I think the next comment is not anymore correct:
   Unregister should only be used in the error case because it may not
   be able to remove memory internally allocated for the onclose
   handler.

   FIXME: Unregister is not thread safe.

   The notification will be called right before the stream is
   closed. If gpgrt_fcancel is used, the cancellation of internal
   buffers is done before the notifications.  The notification handler
   may not call any estream function for STREAM, neither direct nor
   indirectly. */
int
_gpgrt_onclose (estream_t stream, int mode,
                void (*fnc) (estream_t, void*), void *fnc_value)
{
  int err;

  lock_stream (stream);
  err = do_onclose (stream, mode, fnc, fnc_value);
  unlock_stream (stream);

  return err;
}


int
_gpgrt_fileno_unlocked (estream_t stream)
{
  es_syshd_t syshd;

  if (_gpgrt_syshd_unlocked (stream, &syshd))
    return -1;
  switch (syshd.type)
    {
    case ES_SYSHD_FD:   return syshd.u.fd;
    case ES_SYSHD_SOCK: return syshd.u.sock;
    default:
      _set_errno (EINVAL);
      return -1;
    }
}


/* Return the handle of a stream which has been opened by es_sysopen.
   The caller needs to pass a structure which will be filled with the
   sys handle.  Return 0 on success or true on error and sets errno.
   This is the unlocked version.  */
int
_gpgrt_syshd_unlocked (estream_t stream, es_syshd_t *syshd)
{
  if (!stream || !syshd || stream->intern->syshd.type == ES_SYSHD_NONE)
    {
      if (syshd)
        syshd->type = ES_SYSHD_NONE;
      _set_errno (EINVAL);
      return -1;
    }

  *syshd = stream->intern->syshd;
  return 0;
}


void
_gpgrt_flockfile (estream_t stream)
{
  lock_stream (stream);
}


int
_gpgrt_ftrylockfile (estream_t stream)
{
  return trylock_stream (stream);
}


void
_gpgrt_funlockfile (estream_t stream)
{
  unlock_stream (stream);
}


int
_gpgrt_fileno (estream_t stream)
{
  int ret;

  lock_stream (stream);
  ret = _gpgrt_fileno_unlocked (stream);
  unlock_stream (stream);

  return ret;
}


/* Return the handle of a stream which has been opened by es_sysopen.
   The caller needs to pass a structure which will be filled with the
   sys handle.  Return 0 on success or true on error and sets errno.
   This is the unlocked version.  */
int
_gpgrt_syshd (estream_t stream, es_syshd_t *syshd)
{
  int ret;

  lock_stream (stream);
  ret = _gpgrt_syshd_unlocked (stream, syshd);
  unlock_stream (stream);

  return ret;
}


int
_gpgrt__pending_unlocked (estream_t stream)
{
  return check_pending (stream);
}


/* Return true if there is at least one byte pending for read on
   STREAM.  This does only work if the backend supports checking for
   pending bytes and is thus mostly useful with cookie based backends.

   Note that if this function is used with cookie based functions, the
   read cookie may be called with 0 for the SIZE argument.  If bytes
   are pending the function is expected to return -1 in this case and
   thus deviates from the standard behavior of read(2).   */
int
_gpgrt__pending (estream_t stream)
{
  int ret;

  lock_stream (stream);
  ret = _gpgrt__pending_unlocked (stream);
  unlock_stream (stream);

  return ret;
}


int
_gpgrt_feof_unlocked (estream_t stream)
{
  return stream->intern->indicators.eof;
}


int
_gpgrt_feof (estream_t stream)
{
  int ret;

  lock_stream (stream);
  ret = _gpgrt_feof_unlocked (stream);
  unlock_stream (stream);

  return ret;
}


int
_gpgrt_ferror_unlocked (estream_t stream)
{
  return stream->intern->indicators.err;
}


int
_gpgrt_ferror (estream_t stream)
{
  int ret;

  lock_stream (stream);
  ret = _gpgrt_ferror_unlocked (stream);
  unlock_stream (stream);

  return ret;
}


void
_gpgrt_clearerr_unlocked (estream_t stream)
{
  stream->intern->indicators.eof = 0;
  stream->intern->indicators.err = 0;
  /* We do not reset the HUP indicator because there is no way to
     get out of this state.  */
}


void
_gpgrt_clearerr (estream_t stream)
{
  lock_stream (stream);
  _gpgrt_clearerr_unlocked (stream);
  unlock_stream (stream);
}


static int
do_fflush (estream_t stream)
{
  int err;

  if (stream->flags.writing)
    err = flush_stream (stream);
  else
    {
      es_empty (stream);
      err = 0;
    }

  return err;
}


int
_gpgrt_fflush (estream_t stream)
{
  int err;

  if (stream)
    {
      lock_stream (stream);
      err = do_fflush (stream);
      unlock_stream (stream);
    }
  else
    {
      estream_list_t item;

      err = 0;
      lock_list ();
      for (item = estream_list; item; item = item->next)
        if (item->stream)
          {
            lock_stream (item->stream);
            err |= do_fflush (item->stream);
            unlock_stream (item->stream);
          }
      unlock_list ();
    }
  return err ? EOF : 0;
}


int
_gpgrt_fseek (estream_t stream, long int offset, int whence)
{
  int err;

  lock_stream (stream);
  err = es_seek (stream, offset, whence, NULL);
  unlock_stream (stream);

  return err;
}


int
_gpgrt_fseeko (estream_t stream, gpgrt_off_t offset, int whence)
{
  int err;

  lock_stream (stream);
  err = es_seek (stream, offset, whence, NULL);
  unlock_stream (stream);

  return err;
}


long int
_gpgrt_ftell (estream_t stream)
{
  long int ret;

  lock_stream (stream);
  ret = es_offset_calculate (stream);
  unlock_stream (stream);

  return ret;
}


gpgrt_off_t
_gpgrt_ftello (estream_t stream)
{
  gpgrt_off_t ret = -1;

  lock_stream (stream);
  ret = es_offset_calculate (stream);
  unlock_stream (stream);

  return ret;
}


void
_gpgrt_rewind (estream_t stream)
{
  lock_stream (stream);
  es_seek (stream, 0L, SEEK_SET, NULL);
  /* Note that es_seek already cleared the EOF flag.  */
  stream->intern->indicators.err = 0;
  unlock_stream (stream);
}


int
_gpgrt_ftruncate (estream_t stream, gpgrt_off_t length)
{
  cookie_ioctl_function_t func_ioctl;
  int ret;

  lock_stream (stream);
  func_ioctl = stream->intern->func_ioctl;
  if (!func_ioctl)
    {
      _set_errno (EOPNOTSUPP);
      ret = -1;
    }
  else
    {
      ret = func_ioctl (stream->intern->cookie, COOKIE_IOCTL_TRUNCATE,
                        &length, NULL);
    }
  unlock_stream (stream);
  return ret;
}


int
_gpgrt__getc_underflow (estream_t stream)
{
  int err;
  unsigned char c;
  size_t bytes_read;

  err = es_readn (stream, &c, 1, &bytes_read);

  return (err || (! bytes_read)) ? EOF : c;
}


int
_gpgrt__putc_overflow (int c, estream_t stream)
{
  unsigned char d = c;
  int err;

  err = es_writen (stream, &d, 1, NULL);

  return err ? EOF : c;
}


int
_gpgrt_fgetc (estream_t stream)
{
  int ret;

  lock_stream (stream);
  ret = _gpgrt_getc_unlocked (stream);
  unlock_stream (stream);

  return ret;
}


int
_gpgrt_fputc (int c, estream_t stream)
{
  int ret;

  lock_stream (stream);
  ret = _gpgrt_putc_unlocked (c, stream);
  unlock_stream (stream);

  return ret;
}


int
_gpgrt_ungetc (int c, estream_t stream)
{
  unsigned char data = (unsigned char) c;
  size_t data_unread;

  lock_stream (stream);
  es_unreadn (stream, &data, 1, &data_unread);
  unlock_stream (stream);

  return data_unread ? c : EOF;
}


int
_gpgrt_read (estream_t _GPGRT__RESTRICT stream,
             void *_GPGRT__RESTRICT buffer, size_t bytes_to_read,
             size_t *_GPGRT__RESTRICT bytes_read)
{
  int err;

  if (bytes_to_read)
    {
      lock_stream (stream);
      err = es_readn (stream, buffer, bytes_to_read, bytes_read);
      unlock_stream (stream);
    }
  else
    err = 0;

  return err;
}


int
_gpgrt_write (estream_t _GPGRT__RESTRICT stream,
              const void *_GPGRT__RESTRICT buffer, size_t bytes_to_write,
              size_t *_GPGRT__RESTRICT bytes_written)
{
  int err;

  if (bytes_to_write)
    {
      lock_stream (stream);
      err = es_writen (stream, buffer, bytes_to_write, bytes_written);
      unlock_stream (stream);
    }
  else
    err = 0;

  return err;
}


size_t
_gpgrt_fread (void *_GPGRT__RESTRICT ptr, size_t size, size_t nitems,
              estream_t _GPGRT__RESTRICT stream)
{
  size_t ret, bytes;

  if (size && nitems)
    {
      lock_stream (stream);
      es_readn (stream, ptr, size * nitems, &bytes);
      unlock_stream (stream);

      ret = bytes / size;
    }
  else
    ret = 0;

  return ret;
}


size_t
_gpgrt_fwrite (const void *_GPGRT__RESTRICT ptr, size_t size, size_t nitems,
               estream_t _GPGRT__RESTRICT stream)
{
  size_t ret, bytes;

  if (size && nitems)
    {
      lock_stream (stream);
      es_writen (stream, ptr, size * nitems, &bytes);
      unlock_stream (stream);

      ret = bytes / size;
    }
  else
    ret = 0;

  return ret;
}


char *
_gpgrt_fgets (char *_GPGRT__RESTRICT buffer, int length,
              estream_t _GPGRT__RESTRICT stream)
{
  unsigned char *s = (unsigned char*)buffer;
  int c;

  if (!length)
    return NULL;

  c = EOF;
  lock_stream (stream);
  while (length > 1 && (c = _gpgrt_getc_unlocked (stream)) != EOF && c != '\n')
    {
      *s++ = c;
      length--;
    }
  unlock_stream (stream);

  if (c == EOF && s == (unsigned char*)buffer)
    return NULL; /* Nothing read.  */

  if (c != EOF && length > 1)
    *s++ = c;

  *s = 0;
  return buffer;
}


int
_gpgrt_fputs_unlocked (const char *_GPGRT__RESTRICT s,
                       estream_t _GPGRT__RESTRICT stream)
{
  size_t length;
  int err;

  length = strlen (s);
  err = es_writen (stream, s, length, NULL);
  return err ? EOF : 0;
}

int
_gpgrt_fputs (const char *_GPGRT__RESTRICT s, estream_t _GPGRT__RESTRICT stream)
{
  size_t length;
  int err;

  length = strlen (s);
  lock_stream (stream);
  err = es_writen (stream, s, length, NULL);
  unlock_stream (stream);

  return err ? EOF : 0;
}


gpgrt_ssize_t
_gpgrt_getline (char *_GPGRT__RESTRICT *_GPGRT__RESTRICT lineptr,
                size_t *_GPGRT__RESTRICT n, estream_t _GPGRT__RESTRICT stream)
{
  char *line = NULL;
  size_t line_n = 0;
  int err;

  lock_stream (stream);
  err = doreadline (stream, 0, &line, &line_n);
  unlock_stream (stream);
  if (err)
    goto out;

  if (*n)
    {
      /* Caller wants us to use his buffer.  */

      if (*n < (line_n + 1))
	{
	  /* Provided buffer is too small -> resize.  */

	  void *p;

	  p = mem_realloc (*lineptr, line_n + 1);
	  if (! p)
	    err = -1;
	  else
	    {
	      if (*lineptr != p)
		*lineptr = p;
	    }
	}

      if (! err)
	{
	  memcpy (*lineptr, line, line_n + 1);
	  if (*n != line_n)
	    *n = line_n;
	}
      mem_free (line);
    }
  else
    {
      /* Caller wants new buffers.  */
      *lineptr = line;
      *n = line_n;
    }

 out:

  return err ? err : (gpgrt_ssize_t)line_n;
}



/* Same as fgets() but if the provided buffer is too short a larger
   one will be allocated.  This is similar to getline. A line is
   considered a byte stream ending in a LF.

   If MAX_LENGTH is not NULL, it shall point to a value with the
   maximum allowed allocation.

   Returns the length of the line. EOF is indicated by a line of
   length zero. A truncated line is indicated my setting the value at
   MAX_LENGTH to 0.  If the returned value is less then 0 not enough
   memory was available or another error occurred; ERRNO is then set
   accordingly.

   If a line has been truncated, the file pointer is moved forward to
   the end of the line so that the next read starts with the next
   line.  Note that MAX_LENGTH must be re-initialized in this case.

   The caller initially needs to provide the address of a variable,
   initialized to NULL, at ADDR_OF_BUFFER and don't change this value
   anymore with the following invocations.  LENGTH_OF_BUFFER should be
   the address of a variable, initialized to 0, which is also
   maintained by this function.  Thus, both paramaters should be
   considered the state of this function.

   Note: The returned buffer is allocated with enough extra space to
   allow the caller to append a CR,LF,Nul.  The buffer should be
   released using gpgrt_free.
 */
gpgrt_ssize_t
_gpgrt_read_line (estream_t stream,
                  char **addr_of_buffer, size_t *length_of_buffer,
                  size_t *max_length)
{
  int c;
  char  *buffer = *addr_of_buffer;
  size_t length = *length_of_buffer;
  size_t nbytes = 0;
  size_t maxlen = max_length? *max_length : 0;
  char *p;

  if (!buffer)
    {
      /* No buffer given - allocate a new one. */
      length = 256;
      buffer = mem_alloc (length);
      *addr_of_buffer = buffer;
      if (!buffer)
        {
          *length_of_buffer = 0;
          if (max_length)
            *max_length = 0;
          return -1;
        }
      *length_of_buffer = length;
    }

  if (length < 4)
    {
      /* This should never happen. If it does, the function has been
         called with wrong arguments. */
      _set_errno (EINVAL);
      return -1;
    }
  length -= 3; /* Reserve 3 bytes for CR,LF,EOL. */

  lock_stream (stream);
  p = buffer;
  while  ((c = _gpgrt_getc_unlocked (stream)) != EOF)
    {
      if (nbytes == length)
        {
          /* Enlarge the buffer. */
          if (maxlen && length > maxlen)
            {
              /* We are beyond our limit: Skip the rest of the line. */
              while (c != '\n' && (c=_gpgrt_getc_unlocked (stream)) != EOF)
                ;
              *p++ = '\n'; /* Always append a LF (we reserved some space). */
              nbytes++;
              if (max_length)
                *max_length = 0; /* Indicate truncation. */
              break; /* the while loop. */
            }
          length += 3; /* Adjust for the reserved bytes. */
          length += length < 1024? 256 : 1024;
          *addr_of_buffer = mem_realloc (buffer, length);
          if (!*addr_of_buffer)
            {
              int save_errno = errno;
              mem_free (buffer);
              *length_of_buffer = 0;
              if (max_length)
                *max_length = 0;
              unlock_stream (stream);
              _set_errno (save_errno);
              return -1;
            }
          buffer = *addr_of_buffer;
          *length_of_buffer = length;
          length -= 3;
          p = buffer + nbytes;
	}
      *p++ = c;
      nbytes++;
      if (c == '\n')
        break;
    }
  *p = 0; /* Make sure the line is a string. */
  unlock_stream (stream);

  return nbytes;
}

/* Wrapper around free() to match the memory allocation system used by
   estream.  Should be used for all buffers returned to the caller by
   libestream.  If a custom allocation handler has been set with
   gpgrt_set_alloc_func that register function may be used
   instead.  This function has been moved to init.c.  */
/* void */
/* _gpgrt_free (void *a) */
/* { */
/*   mem_free (a); */
/* } */


int
_gpgrt_vfprintf_unlocked (estream_t _GPGRT__RESTRICT stream,
                          gpgrt_string_filter_t sf, void *sfvalue,
                          const char *_GPGRT__RESTRICT format,
                          va_list ap)
{
  return do_print_stream (stream, sf, sfvalue, format, ap);
}


int
_gpgrt_vfprintf (estream_t _GPGRT__RESTRICT stream,
                 gpgrt_string_filter_t sf, void *sfvalue,
                 const char *_GPGRT__RESTRICT format,
                 va_list ap)
{
  int ret;

  lock_stream (stream);
  ret = do_print_stream (stream, sf, sfvalue, format, ap);
  unlock_stream (stream);

  return ret;
}


int
_gpgrt_fprintf_unlocked (estream_t _GPGRT__RESTRICT stream,
                         const char *_GPGRT__RESTRICT format, ...)
{
  int ret;

  va_list ap;
  va_start (ap, format);
  ret = do_print_stream (stream, NULL, NULL, format, ap);
  va_end (ap);

  return ret;
}


int
_gpgrt_fprintf (estream_t _GPGRT__RESTRICT stream,
                const char *_GPGRT__RESTRICT format, ...)
{
  int ret;

  va_list ap;
  va_start (ap, format);
  lock_stream (stream);
  ret = do_print_stream (stream, NULL, NULL, format, ap);
  unlock_stream (stream);
  va_end (ap);

  return ret;
}


static int
tmpfd (void)
{
#ifdef HAVE_W32_SYSTEM
  int attempts, n;
  char buffer[MAX_PATH+9+12+1];
# define mystrlen(a) strlen (a)
  char *name, *p;
  HANDLE file;
  int pid = GetCurrentProcessId ();
  unsigned int value;
  int i;

  n = GetTempPath (MAX_PATH+1, buffer);
  if (!n || n > MAX_PATH || mystrlen (buffer) > MAX_PATH)
    {
      _set_errno (ENOENT);
      return -1;
    }
  p = buffer + mystrlen (buffer);
  strcpy (p, "_estream");
  p += 8;
  /* We try to create the directory but don't care about an error as
     it may already exist and the CreateFile would throw an error
     anyway.  */
  CreateDirectory (buffer, NULL);
  *p++ = '\\';
  name = p;
  for (attempts=0; attempts < 10; attempts++)
    {
      p = name;
      value = (GetTickCount () ^ ((pid<<16) & 0xffff0000));
      for (i=0; i < 8; i++)
        {
          *p++ = tohex (((value >> 28) & 0x0f));
          value <<= 4;
        }
      strcpy (p, ".tmp");
      file = CreateFile (buffer,
                         GENERIC_READ | GENERIC_WRITE,
                         0,
                         NULL,
                         CREATE_NEW,
                         FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
                         NULL);
      if (file != INVALID_HANDLE_VALUE)
        {
          int fd = _open_osfhandle ((intptr_t)file, 0);
          if (fd == -1)
            {
              CloseHandle (file);
              return -1;
            }
          return fd;
        }
      Sleep (1); /* One ms as this is the granularity of GetTickCount.  */
    }
  _set_errno (ENOENT);
  return -1;
#else /*!HAVE_W32_SYSTEM*/
  FILE *fp;
  int fp_fd;
  int fd;

  fp = NULL;
  fd = -1;

  fp = tmpfile ();
  if (! fp)
    goto out;

  fp_fd = fileno (fp);
  fd = dup (fp_fd);

 out:

  if (fp)
    fclose (fp);

  return fd;
#endif /*!HAVE_W32_SYSTEM*/
}

estream_t
_gpgrt_tmpfile (void)
{
  unsigned int modeflags;
  int create_called = 0;
  estream_t stream = NULL;
  void *cookie = NULL;
  int err;
  int fd;
  es_syshd_t syshd;

  modeflags = O_RDWR | O_TRUNC | O_CREAT;

  fd = tmpfd ();
  if (fd == -1)
    {
      err = -1;
      goto out;
    }

  err = func_fd_create (&cookie, fd, modeflags, 0);
  if (err)
    goto out;

  syshd.type = ES_SYSHD_FD;
  syshd.u.fd = fd;
  create_called = 1;
  err = create_stream (&stream, cookie, &syshd,
                       BACKEND_FD, estream_functions_fd,
                       modeflags, 0, 0);

 out:
  if (err)
    {
      if (create_called)
	func_fd_destroy (cookie);
      else if (fd != -1)
	close (fd);
      stream = NULL;
    }

  return stream;
}


int
_gpgrt_setvbuf (estream_t _GPGRT__RESTRICT stream,
                char *_GPGRT__RESTRICT buf, int type, size_t size)
{
  int err;

  if ((type == _IOFBF || type == _IOLBF || type == _IONBF)
      && (!buf || size || type == _IONBF))
    {
      lock_stream (stream);
      err = es_set_buffering (stream, buf, type, size);
      unlock_stream (stream);
    }
  else
    {
      _set_errno (EINVAL);
      err = -1;
    }

  return err;
}


/* Put a stream into binary mode.  This is only needed for the
   standard streams if they are to be used in a binary way.  On Unix
   systems it is never needed but MSDOS based systems require such a
   call.  It needs to be called before any I/O is done on STREAM.  */
void
_gpgrt_set_binary (estream_t stream)
{
  lock_stream (stream);
  if (!(stream->intern->modeflags & O_BINARY))
    {
      stream->intern->modeflags |= O_BINARY;
#ifdef HAVE_DOSISH_SYSTEM
      if (stream->intern->func_read == func_fd_read)
        {
          estream_cookie_fd_t fd_cookie = stream->intern->cookie;

          if (!IS_INVALID_FD (fd_cookie->fd))
            setmode (fd_cookie->fd, O_BINARY);
        }
      else if (stream->intern->func_read == func_fp_read)
        {
          estream_cookie_fp_t fp_cookie = stream->intern->cookie;

          if (fp_cookie->fp)
            setmode (fileno (fp_cookie->fp), O_BINARY);
        }
#endif
    }
  unlock_stream (stream);
}


/* Set non-blocking mode for STREAM.  Use true for ONOFF to enable and
   false to disable non-blocking mode.  Returns 0 on success or -1 on
   error and sets ERRNO.  Note that not all backends support
   non-blocking mode.

   In non-blocking mode a system call will not block but return an
   error and set errno to EAGAIN.  The estream API always uses EAGAIN
   and not EWOULDBLOCK.  If a buffered function like es_fgetc() or
   es_fgets() returns an error and both, feof() and ferror() return
   false the caller may assume that the error condition was EAGAIN.

   Switching back from non-blocking to blocking may raise problems
   with buffering, thus care should be taken.  Although read+write
   sockets are supported in theory, switching from write to read may
   result into problems because estream may first flush the write
   buffers and there is no way to handle that non-blocking (EAGAIN)
   case.  Explicit flushing should thus be done before before
   switching to read.  */
int
_gpgrt_set_nonblock (estream_t stream, int onoff)
{
  cookie_ioctl_function_t func_ioctl;
  int ret;

  lock_stream (stream);
  func_ioctl = stream->intern->func_ioctl;
  if (!func_ioctl)
    {
      _set_errno (EOPNOTSUPP);
      ret = -1;
    }
  else
    {
      unsigned int save_flags = stream->intern->modeflags;

      if (onoff)
        stream->intern->modeflags |= O_NONBLOCK;
      else
        stream->intern->modeflags &= ~O_NONBLOCK;

      ret = func_ioctl (stream->intern->cookie, COOKIE_IOCTL_NONBLOCK,
                        onoff?"":NULL, NULL);
      if (ret)
        stream->intern->modeflags = save_flags;
    }
  unlock_stream (stream);
  return ret;
}


/* Return true if STREAM is in non-blocking mode.  */
int
_gpgrt_get_nonblock (estream_t stream)
{
  int ret;

  lock_stream (stream);
  ret = !!(stream->intern->modeflags & O_NONBLOCK);
  unlock_stream (stream);
  return ret;
}


/* A version of poll(2) working on estream handles.  Note that not all
   estream types work with this function.  In contrast to the standard
   poll function the gpgrt_poll_t object uses a set of bit flags
   instead of the EVENTS and REVENTS members.  An item with the IGNORE
   flag set is entirely ignored.  The TIMEOUT values is given in
   milliseconds, a value of -1 waits indefinitely, and a value of 0
   returns immediately.

   A positive return value gives the number of fds with new
   information.  A return value of 0 indicates a timeout and -1
   indicates an error in which case ERRNO is set.  */
int
_gpgrt_poll (gpgrt_poll_t *fds, unsigned int nfds, int timeout)
{
  gpgrt_poll_t *item;
  int count = 0;
  int idx;
#ifndef HAVE_W32_SYSTEM
# ifdef HAVE_POLL_H
  struct pollfd *poll_fds = NULL;
  nfds_t poll_nfds;
# else
  fd_set readfds, writefds, exceptfds;
  int any_readfd, any_writefd, any_exceptfd;
  int max_fd;
#endif
  int fd, ret, any;
#endif /*HAVE_W32_SYSTEM*/

  trace (("enter: nfds=%u timeout=%d", nfds, timeout));

  if (!fds)
    {
      _set_errno (EINVAL);
      count = -1;
      goto leave;
    }

  /* Clear all response fields (even for ignored items).  */
  for (item = fds, idx = 0; idx < nfds; item++, idx++)
    {
      item->got_read = 0;
      item->got_write = 0;
      item->got_oob = 0;
      item->got_rdhup = 0;
      item->got_err = 0;
      item->got_hup = 0;
      item->got_nval = 0;
    }

  /* Check for pending reads.  */
  for (item = fds, idx = 0; idx < nfds; item++, idx++)
    {
      if (item->ignore)
        continue;
      if (!item->want_read)
        continue;
      if (_gpgrt__pending (item->stream))
        {
          item->got_read = 1;
          count++;
        }
    }

  /* Check for space in the write buffers.  */
  for (item = fds, idx = 0; idx < nfds; item++, idx++)
    {
      if (item->ignore)
        continue;
      if (!item->want_write)
        continue;
      /* FIXME */
    }

  if (count)
    goto leave;

  /* Now do the real select.  */
#ifdef HAVE_W32_SYSTEM

  _gpgrt_pre_syscall ();
  count = _gpgrt_w32_poll (fds, nfds, timeout);
  _gpgrt_post_syscall ();

#else /*!HAVE_W32_SYSTEM*/
# ifdef HAVE_POLL_H
  poll_fds = xtrymalloc (sizeof (*poll_fds)*nfds);
  if (!poll_fds)
    {
      count = -1;
      goto leave;
    }
  poll_nfds = 0;
  for (item = fds, idx = 0; idx < nfds; item++, idx++)
    {
      if (item->ignore)
        continue;
      fd = _gpgrt_fileno (item->stream);
      if (fd == -1)
        continue;  /* Stream does not support polling.  */

      if (item->want_read || item->want_write || item->want_oob)
        {
          poll_fds[poll_nfds].fd = fd;
          poll_fds[poll_nfds].events = ((item->want_read ? POLLIN : 0)
                                        |(item->want_write ? POLLOUT : 0)
                                        |(item->want_oob ? POLLPRI : 0));
          poll_fds[poll_nfds].revents = 0;
          poll_nfds++;
        }
    }

  _gpgrt_pre_syscall ();
  do
    ret = poll (poll_fds, poll_nfds, timeout);
  while (ret == -1 && (errno == EINTR || errno == EAGAIN));
  _gpgrt_post_syscall ();
# else /* !HAVE_POLL_H */
  any_readfd = any_writefd = any_exceptfd = 0;
  max_fd = 0;
  for (item = fds, idx = 0; idx < nfds; item++, idx++)
    {
      if (item->ignore)
        continue;
      fd = _gpgrt_fileno (item->stream);
      if (fd == -1)
        continue;  /* Stream does not support polling.  */

      if (item->want_read)
        {
          if (!any_readfd)
            {
              FD_ZERO (&readfds);
              any_readfd = 1;
            }
          FD_SET (fd, &readfds);
          if (fd > max_fd)
            max_fd = fd;
        }
      if (item->want_write)
        {
          if (!any_writefd)
            {
              FD_ZERO (&writefds);
              any_writefd = 1;
            }
          FD_SET (fd, &writefds);
          if (fd > max_fd)
            max_fd = fd;
        }
      if (item->want_oob)
        {
          if (!any_exceptfd)
            {
              FD_ZERO (&exceptfds);
              any_exceptfd = 1;
            }
          FD_SET (fd, &exceptfds);
          if (fd > max_fd)
            max_fd = fd;
        }
    }

  _gpgrt_pre_syscall ();
  do
    {
      struct timeval timeout_val;

      timeout_val.tv_sec = timeout / 1000;
      timeout_val.tv_usec = (timeout % 1000) * 1000;
      ret = select (max_fd+1,
                    any_readfd?   &readfds   : NULL,
                    any_writefd?  &writefds  : NULL,
                    any_exceptfd? &exceptfds : NULL,
                    timeout == -1 ? NULL : &timeout_val);
    }
  while (ret == -1 && errno == EINTR);
  _gpgrt_post_syscall ();
# endif

  if (ret == -1)
    {
# ifdef HAVE_POLL_H
      trace_errno (1, ("poll failed: "));
# else
      trace_errno (1, ("select failed: "));
# endif
      count = -1;
      goto leave;
    }
  if (!ret)
    {
      /* Timeout.  Note that in this case we can't return got_err for
       * an invalid stream.  */
      count = 0;
      goto leave;
    }

# ifdef HAVE_POLL_H
  poll_nfds = 0;
  for (item = fds, idx = 0; idx < nfds; item++, idx++)
    {
      if (item->ignore)
        continue;
      fd = _gpgrt_fileno (item->stream);
      if (fd == -1)
        {
          item->got_err = 1;  /* Stream does not support polling.  */
          count++;
          continue;
        }

      any = 0;
      if (item->stream->intern->indicators.hup)
        {
          item->got_hup = 1;
          any = 1;
        }
      if (item->want_read && (poll_fds[poll_nfds].revents & (POLLIN|POLLHUP)))
        {
          item->got_read = 1;
          any = 1;
        }
      if (item->want_write && (poll_fds[poll_nfds].revents & POLLOUT))
        {
          item->got_write = 1;
          any = 1;
        }
      if (item->want_oob && (poll_fds[poll_nfds].revents & ~(POLLIN|POLLOUT)))
        {
          item->got_oob = 1;
          any = 1;
        }

      if (item->want_read || item->want_write || item->want_oob)
        poll_nfds++;
      if (any)
        count++;
    }
# else
  for (item = fds, idx = 0; idx < nfds; item++, idx++)
    {
      if (item->ignore)
        continue;
      fd = _gpgrt_fileno (item->stream);
      if (fd == -1)
        {
          item->got_err = 1;  /* Stream does not support polling.  */
          count++;
          continue;
        }

      any = 0;
      if (item->stream->intern->indicators.hup)
        {
          item->got_hup = 1;
          any = 1;
        }
      if (item->want_read && FD_ISSET (fd, &readfds))
        {
          item->got_read = 1;
          any = 1;
        }
      if (item->want_write && FD_ISSET (fd, &writefds))
        {
          item->got_write = 1;
          any = 1;
        }
      if (item->want_oob && FD_ISSET (fd, &exceptfds))
        {
          item->got_oob = 1;
          any = 1;
        }

      if (any)
        count++;
    }
# endif
#endif /*!HAVE_W32_SYSTEM*/

 leave:
#ifndef HAVE_W32_SYSTEM
# ifdef HAVE_POLL_H
  xfree (poll_fds);
# endif
#endif
#ifdef ENABLE_TRACING
  trace (("leave: count=%d", count));
  if (count > 0)
    {
      for (item = fds, idx = 0; idx < nfds; item++, idx++)
        {
          trace (("     %3d  %c%c%c%c%c  %c%c%c%c%c%c%c",
                  idx,
                  fds[idx].want_read?  'r':'-',
                  fds[idx].want_write? 'w':'-',
                  fds[idx].want_oob?   'o':'-',
                  fds[idx].want_rdhup? 'h':'-',
                  fds[idx].ignore?     'i':'-',
                  fds[idx].got_read?   'r':'-',
                  fds[idx].got_write?  'w':'-',
                  fds[idx].got_oob?    'o':'-',
                  fds[idx].got_rdhup?  'h':'-',
                  fds[idx].got_hup?    'H':'-',
                  fds[idx].got_err?    'e':'-',
                  fds[idx].got_nval?   'n':'-'
                  ));
        }
    }
#endif /*ENABLE_TRACING*/
  return count;
}


void
_gpgrt_opaque_set (estream_t stream, void *opaque)
{
  lock_stream (stream);
  es_opaque_ctrl (stream, opaque, NULL);
  unlock_stream (stream);
}


void *
_gpgrt_opaque_get (estream_t stream)
{
  void *opaque;

  lock_stream (stream);
  es_opaque_ctrl (stream, NULL, &opaque);
  unlock_stream (stream);

  return opaque;
}


static void
fname_set_internal (estream_t stream, const char *fname, int quote)
{
  if (stream->intern->printable_fname
      && !stream->intern->printable_fname_inuse)
    {
      mem_free (stream->intern->printable_fname);
      stream->intern->printable_fname = NULL;
    }
  if (stream->intern->printable_fname)
    return; /* Can't change because it is in use.  */

  if (*fname != '[')
    quote = 0;
  else
    quote = !!quote;

  stream->intern->printable_fname = mem_alloc (strlen (fname) + quote + 1);
  if (quote)
    stream->intern->printable_fname[0] = '\\';
  strcpy (stream->intern->printable_fname+quote, fname);
}


/* Set the filename attribute of STREAM.  There is no error return.
   as long as STREAM is valid.  This function is called internally by
   functions which open a filename.  */
void
_gpgrt_fname_set (estream_t stream, const char *fname)
{
  if (fname)
    {
      lock_stream (stream);
      fname_set_internal (stream, fname, 1);
      unlock_stream (stream);
    }
}


/* Return the filename attribute of STREAM.  In case no filename has
   been set, "[?]" will be returned.  The returned file name is valid
   as long as STREAM is valid.  */
const char *
_gpgrt_fname_get (estream_t stream)
{
  const char *fname;

  lock_stream (stream);
  fname = stream->intern->printable_fname;
  if (fname)
    stream->intern->printable_fname_inuse = 1;
  unlock_stream (stream);
  if (!fname)
    fname = "[?]";
  return fname;
}



/* Print a BUFFER to STREAM while replacing all control characters and
   the characters in DELIMITERS by standard C escape sequences.
   Returns 0 on success or -1 on error.  If BYTES_WRITTEN is not NULL
   the number of bytes actually written are stored at this
   address.  */
int
_gpgrt_write_sanitized (estream_t _GPGRT__RESTRICT stream,
                        const void * _GPGRT__RESTRICT buffer, size_t length,
                        const char * delimiters,
                        size_t * _GPGRT__RESTRICT bytes_written)
{
  const unsigned char *p = buffer;
  size_t count = 0;
  int ret;

  lock_stream (stream);
  for (; length; length--, p++, count++)
    {
      if (*p < 0x20
          || *p == 0x7f
          || (delimiters
              && (strchr (delimiters, *p) || *p == '\\')))
        {
          _gpgrt_putc_unlocked ('\\', stream);
          count++;
          if (*p == '\n')
            {
              _gpgrt_putc_unlocked ('n', stream);
              count++;
            }
          else if (*p == '\r')
            {
              _gpgrt_putc_unlocked ('r', stream);
              count++;
            }
          else if (*p == '\f')
            {
              _gpgrt_putc_unlocked ('f', stream);
              count++;
            }
          else if (*p == '\v')
            {
              _gpgrt_putc_unlocked ('v', stream);
              count++;
            }
          else if (*p == '\b')
            {
              _gpgrt_putc_unlocked ('b', stream);
              count++;
            }
          else if (!*p)
            {
              _gpgrt_putc_unlocked('0', stream);
              count++;
            }
          else
            {
              _gpgrt_fprintf_unlocked (stream, "x%02x", *p);
              count += 3;
            }
	}
      else
        {
          _gpgrt_putc_unlocked (*p, stream);
          count++;
        }
    }

  if (bytes_written)
    *bytes_written = count;
  ret =  _gpgrt_ferror_unlocked (stream)? -1 : 0;
  unlock_stream (stream);

  return ret;
}


/* Write LENGTH bytes of BUFFER to STREAM as a hex encoded string.
   RESERVED must be 0.  Returns 0 on success or -1 on error.  If
   BYTES_WRITTEN is not NULL the number of bytes actually written are
   stored at this address.  */
int
_gpgrt_write_hexstring (estream_t _GPGRT__RESTRICT stream,
                        const void *_GPGRT__RESTRICT buffer, size_t length,
                        int reserved, size_t *_GPGRT__RESTRICT bytes_written )
{
  int ret;
  const unsigned char *s;
  size_t count = 0;

  (void)reserved;

#define tohex(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'A'))

  if (!length)
    return 0;

  lock_stream (stream);

  for (s = buffer; length; s++, length--)
    {
      _gpgrt_putc_unlocked ( tohex ((*s>>4)&15), stream);
      _gpgrt_putc_unlocked ( tohex (*s&15), stream);
      count += 2;
    }

  if (bytes_written)
    *bytes_written = count;
  ret = _gpgrt_ferror_unlocked (stream)? -1 : 0;

  unlock_stream (stream);

  return ret;

#undef tohex
}