File: ckcnet.c

package info (click to toggle)
ckermit 302-5.3%2Bdeb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 14,824 kB
  • sloc: ansic: 296,410; makefile: 10,037; sh: 66
file content (14447 lines) | stat: -rw-r--r-- 449,352 bytes parent folder | download | duplicates (4)
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
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
char *cknetv = "Network support, 9.0.297, 14 Jul 2011";

/*  C K C N E T  --  Network support  */

/*
  Copyright (C) 1985, 2011,
    Trustees of Columbia University in the City of New York.
    All rights reserved.  See the C-Kermit COPYING.TXT file or the
    copyright text in the ckcmai.c module for disclaimer and permissions.
*/

/*
  REMINDER: Any changes made to this file that other modules depend must
  also be made to cklnet.c (for VOS) until such time as cklnet.c and this
  module are merged back together.

  NOTE TO CONTRIBUTORS: This file, and all the other shared (ckc and cku)
  C-Kermit source files, must be compatible with C preprocessors that support
  only #ifdef, #else, #endif, #define, and #undef.  Please do not use #if,
  logical operators, or other preprocessor features in this module.  Also,
  don't use any ANSI C constructs except within #ifdef CK_ANSIC..#endif.

  Authors:

  Frank da Cruz (fdc@columbia.edu),
    Columbia University Academic Information Systems, New York City.
  Jeffrey E Altman (jaltman@secure-endpoints.com) -- Primary 
    maintainer/developer since about 1996.
  netopen() routine for TCP/IP originally by Ken Yap, Rochester University
    (ken@cs.rochester.edu) (no longer at that address).
  Missing pieces for Excelan sockets library from William Bader.
  Telnet protocol by Frank da Cruz and Jeffrey Altman.
  Rlogin protocol by Jeffrey E Altman.
  SSL support adapted by Jeffrey E Altman from work done by
    Tim Hudson <tjh@cryptosoft.com> +61 7 32781581
  TLS support by Jeffrey E Altman.
  HTTP support by Jeffrey E Altman.
  TGV MultiNet code by Frank da Cruz.
  MultiNet code adapted to WIN/TCP by Ray Hunter of TWG.
  MultiNet code adapted to DEC TCP/IP by Lee Tibbert of DEC and Frank da Cruz.
  TCP/IP support adapted to IBM TCP/IP 1.2.1,2.0 for OS/2 by Kai Uwe Rommel.
  CMU-OpenVMS/IP modifications by Mike O'Malley, Digital (DEC).
  X.25 support by Marcello Frutig, Catholic University,
    Rio de Janeiro, Brazil (frutig@rnp.impa.br) with fixes from
    Stefaan Eeckels, Eurokom, Luxembourg.
    David Lane added support for Stratus VOS X.25 1996.
    Stephen Riehm added support for IBM AIX X.25 in April 1998.
  Other contributions as indicated in the code.
*/
#define CKCNET_C
#include "ckcsym.h"
#include "ckcdeb.h"
#include "ckcker.h"
#include "ckcasc.h"
#ifdef I386IX                           /* Has to come before ckcnet.h in */
#include <errno.h>                      /* this version, but after in others */
#endif /* I386IX */
#include "ckcnet.h"                     /* which includes ckctel.h */
#ifdef CK_SSL
#include "ck_ssl.h"
#endif /* CK_SSL */

#ifdef CK_DNS_SRV
#ifdef OS2
#ifdef NT
#include <wshelper.h>
#else /* NT */
/* !Error OS/2 does not support DNS Service Records. */
#endif /* NT */
#else /* OS2 */
#include <arpa/inet.h>
#ifdef USE_NAMESER_COMPAT
#include <arpa/nameser_compat.h>
#endif	/* USE_NAMESER_COMPAT */

#ifdef MINIX3
#include <net/gen/resolv.h>
#include <net/gen/nameser.h>
#else
#include <arpa/nameser.h>
#include <resolv.h>
#endif /* MINIX 3 */

#ifndef PS2AIX10
#ifndef BSD4
#ifndef I386IX
#ifndef RTAIX
#include <netdb.h>
#endif /* RTAIX */
#endif /* I386IX */
#endif /* BSD4 */
#endif /* PS2AIX10 */
#endif /* OS2 */
#ifndef T_SRV
#define T_SRV 33
#endif /* T_SRV */
#ifndef T_TXT
#define T_TXT 16
#endif /* T_TXT */

/* for old Unixes and friends ... */
#ifndef MAXHOSTNAMELEN
#define MAXHOSTNAMELEN 64
#endif /* MAXHOSTNAMELEN */

#define MAX_DNS_NAMELEN (15*(MAXHOSTNAMELEN + 1)+1)
#endif /* CK_DNS_SRV */

#ifdef NONET
#ifdef TCPIPLIB
#undef TCPIPLIB
#endif /* TCPIPLIB */
#endif /* NONET */

#ifndef NOMHHOST
#ifdef datageneral
#define NOMHHOST
#else
#ifdef HPUX5WINTCP
#define NOMHHOST
#endif /* HPUX5WINTCP */
#endif /* datageneral */
#endif /* NOMHHOST */

#ifdef INADDRX
  struct in_addr inaddrx;
#endif /* INADDRX */

int ttnet = NET_NONE;                   /* Network type */
int ttnproto = NP_DEFAULT;              /* Network virtual terminal protocol */

/* 0 = don't lowercase username for Rlogin/Telnet protocol */
/* nonzero = do lowercase it.  Add a SET command if necessary... */
#ifdef VMS
int ck_lcname = 1;
#else
int ck_lcname = 0;
#endif /* VMS */

extern int                              /* External variables */
  duplex, debses, seslog, sessft, wasclosed,
  ttyfd, quiet, msgflg, what, nettype, ttmdm;
#ifdef IKSD
extern int inserver;
#endif /* IKSD */

char myipaddr[20] = { '\0' };           /* Global copy of my IP address */
char hostipaddr[64] = { '\0' };		/* Global copy of remote IP address */

#ifdef NETCONN
/* Don't need any of this if there is no network support. */

#ifndef OS2
/* Current fd-swapping hack is not thread-safe */
#define HTTP_BUFFERING
#endif	/* OS2 */

#ifdef HTTP_BUFFERING
#define HTTP_INBUFLEN 8192
static char http_inbuf[HTTP_INBUFLEN];
static int http_bufp = 0, http_count;
#endif	/* HTTP_BUFFERING */

/*
  NETLEBUF is (must be) defined for those platforms that call this
  module to do network i/o (e.g. netinc(), nettchk(), etc) rather
  than doing it themselves (ttinc(), ttchk(), etc).  In this case
  the Telnet local-echo buffers and routines are defined and referenced
  here, rather than in the ck?tio.c module.
*/
#ifdef NETLEBUF
#define LEBUFSIZ 4096
int ttpush = -1, le_data = 0;           /* These are seen from outside */
static CHAR le_buf[LEBUFSIZ];           /* These are used internally */
static int le_start = 0, le_end = 0;
int tt_push_inited = 0;
#endif /* NETLEBUF */

#ifdef CK_SOCKS                         /* SOCKS Internet relay package */
#ifdef CK_SOCKS5                        /* SOCKS 5 */
#define accept  SOCKSaccept
#define bind    SOCKSbind
#define connect SOCKSconnect
#define getsockname SOCKSgetsockname
#define listen SOCKSlisten
#else  /* Not SOCKS 5 */
#define accept  Raccept
#define bind    Rbind
#define connect Rconnect
#define getsockname Rgetsockname
#define listen Rlisten
#endif /* CK_SOCKS5 */
#endif /* CK_SOCKS */

#ifdef DEC_TCPIP
#include <time.h>
#include <inet.h>
#endif /* DEC_TCPIP */

/* Also see ckcnet.h -- hmmm, why don't we always include inet.h? */

#ifdef HPUX
#ifndef HPUX7                           /* HPUX 7.00 doesn't have it */
#ifndef HPUX6                           /* HPUX 6.00 doesn't have it */
#include <arpa/inet.h>                  /* For inet_ntoa() prototype */
#endif /* HPUX6 */
#endif /* HPUX7 */
#endif /* HPUX */

#ifdef CMU_TCPIP
#include <time.h>
#endif /* CMU_TCPIP */

#ifndef NODCLTIMEVAL
#ifdef DCLTIMEVAL                       /* UnixWare 7 */
struct timeval {                        /* And define these ourselves. */
    long tv_sec;                        /* (see comments in ckutio.c) */
    long tv_usec;
};
struct timezone {
    int tz_minuteswest;
    int tz_dsttime;
};
#endif /* DCLTIMEVAL */
#endif /* NODCLTIMEVAL */

#ifdef WINTCP

#include <setjmp.h>
#include <signal.h>
#include <sys/time.h>
/*
  The WIN/TCP code path is the same as that for MultiNet.
  Only the routine names have changed ...
*/
#define socket_read     netread
#define socket_ioctl    ioctl
#define socket_write    netwrite
#define socket_close    netclose

#ifdef OLD_TWG                         /* some routines have evolved */
        extern int vmserrno, uerrno;
#define socket_errno    uerrno
#define socket_perror   perror         /* which uses errno, not uerrno! */
#else
#define socket_errno    errno
#define socket_perror   win$perror
#endif /* OLD_TWG */

#else /* Not WINTCP */

#ifdef OSF13
#ifdef CK_ANSIC
#ifdef _NO_PROTO
#undef _NO_PROTO
#endif /* _NO_PROTO */
#endif /* CK_ANSIC */
#endif /* OSF13 */

#ifndef I386IX
#ifndef HPUXPRE65
#include <errno.h>			/* Error number symbols */
#else
#ifndef ERRNO_INCLUDED
#include <errno.h>			/* Error number symbols */
#endif	/* ERRNO_INCLUDED */
#endif	/* HPUXPRE65 */
#endif /* I386IX */

#include <signal.h>                     /* Everybody needs this */

#ifdef ZILOG                            /* Zilog has different name for this */
#include <setret.h>
#else
#include <setjmp.h>
#endif /* ZILOG */

#endif /* WINTCP */

#ifdef datageneral                      /* Data General AOS/VS */
#include <:usr:include:vs_tcp_errno.h>
#include <:usr:include:sys:vs_tcp_types.h>
#ifdef SELECT
/*
  NOTE: This can be compiled and linked OK with SELECT defined
  but it doesn't work at all.  Anybody who cares and knows how
  to fix it, feel free.
*/
#include <:usr:include:sys:vs_tcp_time.h>
#endif /* SELECT */
#include <:usr:include:sys:socket.h>
#include <:usr:include:netinet:in.h>
#include <:usr:include:netdb.h>
#endif /* datageneral */

#ifndef socket_errno
#define socket_errno errno
#endif /* socket_errno */

#ifdef TNCODE
extern int tn_deb;
#endif /* TNCODE */

int tcp_rdns =                          /* Reverse DNS lookup */
#ifdef DEC_TCPIP_OLD
    SET_OFF                             /* Doesn't seem to work in UCX */
#else
     SET_AUTO
#endif /* DEC_TCPIP */
      ;
#ifdef CK_DNS_SRV
int tcp_dns_srv = SET_OFF;
#endif /* CK_DNS_SRV */

_PROTOTYP( char * cmcvtdate, (char *, int) );

#ifdef RLOGCODE
_PROTOTYP( int rlog_ctrl, (CHAR *, int) );
_PROTOTYP( static int rlog_oob, (CHAR *, int) );
#ifndef TCPIPLIB
_PROTOTYP( static SIGTYP rlogoobh, ( int ) );
#endif /* TCPIPLIB */
_PROTOTYP( static int rlog_ini, (CHAR *, int,
                                 struct sockaddr_in *,
                                 struct sockaddr_in *) );
int rlog_mode = RL_COOKED;
int rlog_stopped = 0;
int rlog_inband = 0;
#endif /* RLOGCODE */

#ifndef NOICP
extern int doconx;                      /* CONNECT-class command active */
#endif /* NOICP */

#ifdef IBMX25
/* This variable should probably be generalised for true client/server
 * support - ie: the fd of the listening server, accepted calls should
 * be forked or at least handled via a second fd (for IBM's X.25 -
 * ttyfd always holds the active fd - ie the server becomes inactive
 * as long as a client is connected, and becomes active again when the
 * connection is closed)
 */
int x25serverfd = 0;            /* extern in ckcnet.h */
int x25seqno = 0;               /* Connection sequence number */
int x25lastmsg = -1;            /* A cheapskate's state table */

#define X25_CLOSED      0       /* Default state: no connection, no STREAM */
#define X25_SETUP       1       /* X.25 has been set up (no connection) */
#define X25_CONNECTED   2       /* X.25 connection has been established */
int x25_state = X25_CLOSED;     /* Default state */
#endif /* IBMX25 */

#ifndef DEBUG
#define deblog 0
#endif /* DEBUG */

#ifdef CK_NAWS                          /* Negotiate About Window Size */
#ifdef RLOGCODE
_PROTOTYP( int rlog_naws, (void) );
#endif /* RLOGCODE */
#endif /* CK_NAWS */

#ifdef OS2                              /* For terminal type name string */
#include "ckuusr.h"
#ifndef NT
#include <os2.h>
#undef COMMENT
#endif /* NT */
#include "ckocon.h"
extern int tt_type, max_tt;
extern struct tt_info_rec tt_info[];
extern char ttname[];
#else
#ifdef CK_AUTHENTICATION
#include "ckuusr.h"
#endif /* CK_AUTHENTICATION */
#endif /* OS2 */

#ifdef NT
extern int winsock_version;
#endif /* NT */

#ifdef CK_AUTHENTICATION
#include "ckuath.h"
#endif /* CK_AUTHENTICATION */

#include "ckcsig.h"

#ifndef OS2                             /* For timeout longjumps */
static ckjmpbuf njbuf;
#endif /* OS2 */

#define NAMECPYL 1024                   /* Local copy of hostname */
char namecopy[NAMECPYL];                /* Referenced by ckctel.c */
char namecopy2[NAMECPYL];		/* Referenced by ckctel.c */
#ifndef NOHTTP
char http_host_port[NAMECPYL];          /* orig host/port necessary for http */
char http_ip[20] = { '\0' };            /* ip address of host */
char http_port = 0;
int  http_ssl = 0;
char * http_agent = 0;
int  httpfd = -1;                       /* socket for http connections */
int  http_code = 0;
#define HTTPBUFLEN  1024
char http_reply_str[HTTPBUFLEN] = "";
#endif /* NOHTTP */

char ipaddr[20] = { '\0' };             /* Global copy of IP address */
unsigned long myxipaddr = 0L;           /* Ditto as a number */
#endif /* NETCONN */

char *tcp_address = NULL;               /* Preferred IP Address */
extern char uidbuf[];                   /* User ID buffer */
extern char pwbuf[];                    /* Password buffer */

#ifndef NOHTTP
char * tcp_http_proxy = NULL;           /* Name[:port] of http proxy server */
int    tcp_http_proxy_errno = 0;
char * tcp_http_proxy_user = NULL;
char * tcp_http_proxy_pwd  = NULL;
char * tcp_http_proxy_agent = NULL;
#define HTTPCPYL 1024
static char proxycopy[HTTPCPYL];
#endif /* NOHTTP */

#ifdef OS2
extern int tt_rows[], tt_cols[];
extern int tt_status[VNUM];
#else /* OS2 */
extern int tt_rows, tt_cols;            /* Everybody has this */
#endif /* OS2 */

extern int cmd_cols, cmd_rows;

#ifdef STREAMING                        /* Use blocking writes for streaming */
extern int streaming;
#endif /* STREAMING */

#ifdef NT
extern int WSASafeToCancel;
int win95selectbug = 0;                 /* For TCP/IP stacks whose select() */
/* always fails on write requests such as Cisco and Quarterdeck */
#define stricmp _stricmp
#endif /* NT */

#ifndef NOTCPOPTS

/* Skip all this if NOTCPOPTS specified. */

#ifdef SOL_SOCKET

#ifdef TCP_NODELAY
int tcp_nodelay = 0;                    /* Nagle algorithm TCP_NODELAY */
#endif /* TCP_NODELAY */

#ifdef SO_DONTROUTE
int tcp_dontroute = 0;
#endif /* SO_DONTROUTE */

#ifdef SO_LINGER
int tcp_linger  = 0;                    /* SO_LINGER */
int tcp_linger_tmo = 0;                 /* SO_LINGER timeout */
#endif /* SO_LINGER */

#ifdef HPUX                             /* But the data structures */
#ifndef HPUX8                           /* needed for linger are not */
#ifndef HPUX9                           /* defined in HP-UX versions */
#ifndef HPUX10                          /* prior to 8.00. */
#ifdef SO_LINGER
#undef SO_LINGER
#endif /* SO_LINGER */
#endif /* HPUX10 */
#endif /* HPUX9 */
#endif /* HPUX8 */
#endif /* HPUX */

#ifndef SO_OOBINLINE                    /* Hopefully only HP-UX 7.0 */
#define SO_OOBINLINE 0x0100
#endif /* SO_OOBINLINE */

#ifndef TCPSNDBUFSIZ
#ifdef VMS
#ifdef __alpha
#define TCPSNDBUFSIZ 16384
#endif /* __alpha */
#endif /* VMS */
#endif /* TCPSNDBUFSIZ */

#ifndef TCPSNDBUFSIZ
#define TCPSNDBUFSIZ -1
#endif /* TCPSNDBUFSIZ */

#ifdef SO_SNDBUF
int tcp_sendbuf = TCPSNDBUFSIZ;
#endif /* SO_SNDBUF */

#ifdef SO_RCVBUF
int tcp_recvbuf = -1;
#endif /* SO_RCVBUF */

#ifdef SO_KEEPALIVE
int tcp_keepalive = 1;
#endif /* SO_KEEPALIVE */

#endif /* SOL_SOCKET */
#endif /* NOTCPOPTS */

#ifndef NETCONN
/*
  Network support not defined.
  Dummy functions here in case #ifdef's forgotten elsewhere.
*/
int                                     /* Open network connection */
netopen(name, lcl, nett) char *name; int *lcl, nett; {
    return(-1);
}
int                                     /* Close network connection */
netclos() {
    return(-1);
}
int                                     /* Check network input buffer */
nettchk() {
    return(-1);
}
int                                     /* Flush network input buffer */
netflui() {
    return(-1);
}
int                                     /* Send network BREAK */
netbreak() {
    return(-1);
}
int                                     /* Input character from network */
netinc(timo) int timo; {
    return(-1);
}
int                                     /* Output character to network */
#ifdef CK_ANSIC
nettoc(CHAR c)
#else
nettoc(c) CHAR c;
#endif /* CK_ANSIC */
/* nettoc */ {
    return(-1);
}
int
nettol(s,n) CHAR *s; int n; {
    return(-1);
}

#else /* NETCONN is defined (much of this module...) */

#ifdef NETLEBUF
VOID
le_init() {                             /* LocalEchoInit() */
    int i;
    for (i = 0; i < LEBUFSIZ; i++)
      le_buf[i] = '\0';
    le_start = 0;
    le_end = 0;
    le_data = 0;
    tt_push_inited = 1;
}

VOID
le_clean() {                            /* LocalEchoCleanup() */
    le_init();
    return;
}

int
le_inbuf() {
    int rc = 0;
    if (le_start != le_end) {
        rc = (le_end -
              le_start +
              LEBUFSIZ) % LEBUFSIZ;
    }
    return(rc);
}

int
#ifdef CK_ANSIC
le_putchar(CHAR ch)
#else
le_putchar(ch) CHAR ch;
#endif /* CK_ANSIC */
/* le_putchar */ {
    if ((le_start - le_end + LEBUFSIZ)%LEBUFSIZ == 1) {
        debug(F110,"le_putchar","buffer is full",0);
        return(-1);
    }
    le_buf[le_end++] = ch;
    if (le_end == LEBUFSIZ)
      le_end = 0;
    le_data = 1;
    return(0);
}

int
#ifdef CK_ANSIC
le_puts(CHAR * s, int n)
#else
le_puts(s,n) CHAR * s; int n;
#endif /* CK_ANSIC */
/* le_puts */ {
    int rc = 0;
    int i = 0;
    CHAR * p = (CHAR *)"le_puts";
    ckhexdump(p,s,n);
    for (i = 0; i < n; i++)
      rc = le_putchar((char)s[i]);
    debug(F101,"le_puts","",rc);
    return(rc);
}

int
#ifdef CK_ANSIC
le_putstr(CHAR * s)
#else
le_putstr(s) CHAR * s;
#endif /* CK_ANSIC */
/* le_puts */ {
    CHAR * p;
    int rc = 0;
    p = (CHAR *)"le_putstr";
    ckhexdump(p,s,(int)strlen((char *)s));
    for (p = s; *p && !rc; p++)
      rc = le_putchar(*p);
    return(rc);
}

int
#ifdef CK_ANSIC
le_getchar(CHAR * pch)
#else /* CK_ANSIC */
le_getchar(pch) CHAR * pch;
#endif /* CK_ANSIC */
/* le_gatchar */ {
    int rc = 0;
    if (le_start != le_end) {
        *pch = le_buf[le_start];
        le_buf[le_start] = 0;
        le_start++;

        if (le_start == LEBUFSIZ)
          le_start = 0;

        if (le_start == le_end) {
            le_data = 0;
        }
        rc++;
    } else {
        *pch = 0;
    }
    return(rc);
}
#endif /* NETLEBUF */

#ifdef VMS
/*
  In edit 190, we moved tn_ini() to be called from within netopen().
  But tn_ini() calls ttol(), and ttol() checks to see if it's a net
  connection, but the flag for that isn't set until after netopen()
  is finished.  Since, in this module, we are always doing network
  output anyway, we just call nettol() directly, instead of going thru
  ttol().  Only needed for VMS, since UNIX, AOS/VS, and VOS can handle
  net connections just like regular connections in ttol(), and OS/2
  has a special routine for this.
*/
#define ttol nettol
#endif /* VMS */

int tcpsrfd = -1;

#ifdef CK_KERBEROS

char * krb5_d_principal = NULL;         /* Default principal */
char * krb5_d_instance = NULL;          /* Default instance */
char * krb5_d_realm = NULL;             /* Default realm */
char * krb5_d_cc = NULL;                /* Default credentials cache */
char * krb5_d_srv   = NULL;             /* Default Service */
int    krb5_d_lifetime = 600;           /* Default lifetime (10 hours) */
int    krb5_d_forwardable = 0;          /* creds not forwardable */
int    krb5_d_proxiable = 0;            /* creds not proxiable */
int    krb5_d_renewable = 0;            /* creds not renewable (0 min) */
int    krb5_autoget = 1;                /* Autoget TGTs */
int    krb5_autodel = 0;                /* Auto delete TGTs */
int    krb5_d_getk4 = 0;                /* K5 Kinit gets K4 TGTs */
int    krb5_checkaddrs = 1;             /* Check TGT Addrs */
int    krb5_d_no_addresses = 0;         /* Do not include IP Addresses */
char * krb5_d_addrs[KRB5_NUM_OF_ADDRS+1]={NULL,NULL}; /* Addrs to include */
int    krb5_errno = 0;                  /* Last K5 errno */
char * krb5_errmsg = NULL;              /* Last K5 errmsg */
char * k5_keytab = NULL;

char * krb4_d_principal = NULL;         /* Default principal */
char * krb4_d_realm = NULL;             /* Default realm */
char * krb4_d_srv   = NULL;             /* Default Service */
int    krb4_d_lifetime = 600;           /* Default lifetime (10 hours) */
int    krb4_d_preauth = 1;              /* Use preauth requests */
char * krb4_d_instance = NULL;          /* Default instance */
int    krb4_autoget = 1;                /* Autoget TGTs */
int    krb4_autodel = 0;                /* Auto delete TGTs */
int    krb4_checkaddrs = 1;             /* Check TGT Addrs */
char * k4_keytab = NULL;

int    krb4_errno = 0;                  /* Last K4 errno */
char * krb4_errmsg = NULL;              /* Last K4 errmsg */

struct krb_op_data krb_op = {           /* Operational data structure */
    0, NULL                             /* (version, cachefile) */
};

struct krb4_init_data krb4_init = {     /* Kerberos 4 INIT data structure */
    0, NULL, NULL, NULL, NULL
};

struct krb5_init_data krb5_init = {     /* Kerberos 5 INIT data structure */
    0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0,
    { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
      NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL },
    0
};

struct krb5_list_cred_data krb5_lc = {  /* List Credentials data structure */
    0, 0, 0
};

int krb_action = -1;                    /* Kerberos action to perform */

#ifndef CK_AUTHENTICATION
char *
ck_krb4_getrealm() {
    return("");
}
char *
ck_krb5_getrealm(cc) char * cc; {
    return("");
}
char *
ck_krb4_getprincipal() {
    return("");
}
char *
ck_krb5_getprincipal(cc) char * cc; {
    return("");
}
#endif /* CK_AUTHENTICATION */

/*  I N I _ K E R B  --  Initialize Kerberos data  */

VOID
ini_kerb() {
    int i;

    krb_action = -1;                    /* No action specified */

    krb_op.version = 0;                 /* Kerberos version (none) */
    krb_op.cache = NULL;                /* Cache file (none) */

/* Kerberos 5 */

    krb5_init.forwardable = krb5_d_forwardable; /* Init switch values... */
    krb5_init.proxiable   = krb5_d_proxiable;
    krb5_init.lifetime    = krb5_d_lifetime;
    krb5_init.renew       = 0;
    krb5_init.renewable   = krb5_d_renewable;
    krb5_init.validate    = 0;
    krb5_init.no_addresses = krb5_d_no_addresses;
    krb5_init.getk4       = krb5_d_getk4;
    if (krb5_init.postdate) {
        free(krb5_init.postdate);
        krb5_init.postdate = NULL;
    }
    if (krb5_init.service) {
        free(krb5_init.service);
        krb5_init.service = NULL;
    }
    if (!krb5_d_cc || !krb5_d_cc[0]) {  /* Set default cache */
        char * p;
        p = ck_krb5_get_cc_name();
        makestr(&krb5_d_cc,(p && p[0]) ? p : NULL);
    }
    if (!krb5_d_realm || !krb5_d_realm[0]) { /* Set default realm */
        char * p;
        p = ck_krb5_getrealm(krb5_d_cc);
        makestr(&krb5_d_realm,(p && p[0]) ? p : NULL);
    }
    makestr(&krb5_init.instance,krb5_d_instance);
    makestr(&krb5_init.realm,krb5_d_realm); /* Set realm from default */
    if (krb5_init.password) {
        memset(krb5_init.password,0xFF,strlen(krb5_init.password));
        free(krb5_init.password);
        krb5_init.password = NULL;
    }
    if (!krb5_d_principal) {            /* Default principal */
        /* a Null principal indicates the user should be prompted */
        char * p = ck_krb5_getprincipal(krb5_d_cc);
        if (!p || !(*p))
          p = (char *)uidbuf;           /* Principal = user */
                makestr(&krb5_d_principal,(p && p[0]) ? p : NULL);
    }
    makestr(&krb5_init.principal,krb5_d_principal);
    for (i = 0; i <= KRB5_NUM_OF_ADDRS; i++) {
        if (krb5_init.addrs[i])
          free(krb5_init.addrs[i]);
        krb5_init.addrs[i] = NULL;
    }
    for (i = 0; i <= KRB5_NUM_OF_ADDRS && krb5_d_addrs[i]; i++) {
        makestr(&krb5_init.addrs[i],krb5_d_addrs[i]);
    }

    /* Kerberos 4 */

    krb4_init.lifetime = krb4_d_lifetime;
    krb4_init.preauth  = krb4_d_preauth;
    makestr(&krb4_init.instance,krb4_d_instance);
    if (!krb4_d_realm || !krb4_d_realm[0]) {/* Set default realm */
        char * p;
        p = ck_krb4_getrealm();
                makestr(&krb4_d_realm,(p && p[0]) ? p : NULL);
    }
    makestr(&krb4_init.realm,krb4_d_realm);
    if (krb4_init.password) {
        memset(krb4_init.password,0xFF,strlen(krb4_init.password));
        free(krb4_init.password);
        krb4_init.password = NULL;
    }
    if (!krb4_d_principal) {            /* Default principal */
        /* a Null principal indicates the user should be prompted */
        char * p = ck_krb4_getprincipal();
        if (!p || !(*p))
          p = (char *)uidbuf;           /* Principal = user */
        makestr(&(krb4_d_principal),(p && p[0]) ? p : NULL);
    }
    makestr(&(krb4_init.principal),krb4_d_principal);
}

/*  D O A U T H  --  AUTHENTICATE action routine  */

int
doauth(cx) int cx; {                    /* AUTHENTICATE action routine */
    int rc = 0;                         /* Return code */

#ifdef CK_AUTHENTICATION
#ifdef OS2
    if (!ck_security_loaddll())         /* Load various DLLs */
      return(rc);
#endif /* OS2 */
    if (krb_op.version == 4) {          /* Version = 4 */
#ifdef COMMENT
        sho_auth(AUTHTYPE_KERBEROS_V4);
#endif /* COMMENT */
        if (!ck_krb4_is_installed()) {
            printf("?Kerberos 4 is not installed\n");
            return(0);
        }
        switch (krb_action) {           /* Perform V4 functions */
          case KRB_A_IN:                /* INIT */
            rc |= !(ck_krb4_initTGT(&krb_op,&krb4_init) < 0);
            break;
          case KRB_A_DE:                /* DESTROY */
            rc |= !(ck_krb4_destroy(&krb_op) < 0);
            break;
          case KRB_A_LC:                /* LIST-CREDENTIALS */
            rc |= !(ck_krb4_list_creds(&krb_op) < 0);
            break;
        }
    }
    if (krb_op.version == 5) {          /* V5 functions */
#ifdef COMMENT
        sho_auth(AUTHTYPE_KERBEROS_V5);
#endif /* COMMENT */
        if (!ck_krb5_is_installed()) {
            printf("?Kerberos 5 is not installed\n");
            return(0);
        }
        switch (krb_action) {
          case KRB_A_IN:                /* INIT */
            rc |= !(ck_krb5_initTGT(&krb_op,&krb5_init,
                                     krb5_init.getk4 ? &krb4_init : 0) < 0);
            break;
          case KRB_A_DE:                /* DESTROY */
            rc |= !(ck_krb5_destroy(&krb_op) < 0);
            break;
          case KRB_A_LC:                /* LIST-CREDENTIALS */
            if (krb_op.version == 0)
              printf("\n");
            rc |= !(ck_krb5_list_creds(&krb_op,&krb5_lc) < 0);
            break;
        }
    }
#else
#ifndef NOICP
#ifndef NOSHOW
    rc = sho_auth(0);                   /* Show all */
#endif /* NOSHOW */
#endif /* NOICP */
#endif /* CK_AUTHENTICATION */
    return(rc);
}
#endif /* CK_KERBEROS */

#ifdef TCPSOCKET
#ifndef OS2
#ifndef NOLISTEN                        /* For incoming connections */

#ifndef INADDR_ANY
#define INADDR_ANY 0
#endif /* INADDR_ANY */

_PROTOTYP( int ttbufr, ( VOID ) );
_PROTOTYP( int tcpsrv_open, (char *, int *, int, int ) );

static unsigned short tcpsrv_port = 0;

#endif /* NOLISTEN */
#endif /* OS2 */

static char svcbuf[80];                 /* TCP service string */
static int svcnum = 0;                  /* TCP port number */

#endif /* TCPSOCKET */

/*
  TCPIPLIB means use separate socket calls for i/o, while on UNIX the
  normal file system calls are used for TCP/IP sockets too.
  Means "DEC_TCPIP or MULTINET or WINTCP or OS2 or BEBOX" (see ckcnet.h),
*/

#ifdef TCPIPLIB

/* For buffered network reads... */
/*
  If the buffering code is written right, it shouldn't matter
  how long this buffer is.
*/
#ifdef OS2
#ifdef NT
#define TTIBUFL 64240                   /* 44 * 1460 (MSS) */
#else
#define TTIBUFL 32120                   /* 22 * 1460 (MSS) */
#endif /* NT */
#else /* OS2 */
#define TTIBUFL 8191                    /* Let's use 8K. */
#endif /* OS2 */

CHAR ttibuf[TTIBUFL+1];

/*
  select() is used in preference to alarm()/signal(), but different systems
  use different forms of select()...
*/
#ifndef NOSELECT         /* Option to override BSDSELECT */
#ifdef BELLV10
/*
  Note: Although BELLV10 does have TCP/IP support, and does use the unique
  form of select() that is evident in this module (and in ckutio.c), it does
  not have a sockets library and so we can't build Kermit TCP/IP support for
  it.  For this, somebody would have to write TCP/IP streams code.
*/
#define BELLSELECT
#ifndef FD_SETSIZE
#define FD_SETSIZE 128
#endif /* FD_SETSIZE */
#else
#ifdef WINTCP                           /* VMS with Wollongong WIN/TCP */
#ifndef OLD_TWG                         /* TWG 3.2 has only select(read) */
#define BSDSELECT
#endif /* OLD_TWG */
#else
#ifdef CMU_TCPIP                        /* LIBCMU can do select */
#define BSDSELECT
#else
#ifdef DEC_TCPIP
#define BSDSELECT
#else
#ifdef OS2                              /* OS/2 with TCP/IP */
#ifdef NT
#define BSDSELECT
#else /* NT */
#define IBMSELECT
#endif /* NT */
#endif /* OS2 */
#endif /* DEC_TCPIP */
#endif /* CMU_TCPIP */
#endif /* WINTCP */
#endif /* BELLV10 */
#endif /* NOSELECT */
/*
  Others (TGV, TCPware, ...) use alarm()/signal().  The BSDSELECT case does not
  compile at all; the IBMSELECT case compiles and links but crashes at runtime.
  NOTE: If any of these can be converted to select(), they should be for two
  reasons: (1) It's a lot faster; (2) certain sockets libraries do not like
  their socket_read() calls to be interrupted; subsequent socket_read()'s tend
  to fail with EBUSY.  This happened in the UCX case before it was converted
  to use select().
*/
#ifndef OS2
#ifndef VMS
static                                  /* These are used in CKVTIO.C */
#endif /* VMS */                        /* And in CKONET.C            */
#endif /* OS2 */
int
  ttibp = 0,
  ttibn = 0;
/*
  Read bytes from network into internal buffer ttibuf[].
  To be called when input buffer is empty, i.e. when ttibn == 0.

  Other network reading routines, like ttinc, ttinl, ttxin, should check the
  internal buffer first, and call this routine for a refill if necessary.

  Returns -1 on error, 0 if nothing happens.  When data is read successfully,
  returns number of bytes read, and sets global ttibn to that number and
  ttibp (the buffer pointer) to zero.
*/
_PROTOTYP( int ttbufr, ( VOID ) );
int
ttbufr() {                              /* TT Buffer Read */
    int count;

    if (ttnet != NET_TCPB)              /* First make sure current net is */
      return(-1);                       /* TCP/IP; if not, do nothing. */

#ifdef OS2
    RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
#endif /* OS2 */

    if (ttibn > 0) {                    /* Our internal buffer is not empty, */
#ifdef OS2
        ReleaseTCPIPMutex();
#endif /* OS2 */
        return(ttibn);                  /* so keep using it. */
    }

    if (ttyfd == -1) {                  /* No connection, error */
#ifdef OS2
        ReleaseTCPIPMutex();
#endif /* OS2 */
        return(-2);
    }

    ttibp = 0;                          /* Else reset pointer to beginning */

#ifdef WINTCP
    count = 512;                        /* This works for WIN/TCP */
#else
#ifdef DEC_TCPIP
    count = 512;                        /* UCX */
#else
#ifdef OS2
    count = TTIBUFL;
#else                                   /* Multinet, etc. */
    count = ttchk();                    /* Check network input buffer, */
    if (ttibn > 0) {                    /* which can put a char there! */
        debug(F111,"ttbufr","ttchk() returns",count);
#ifdef OS2
        ReleaseTCPIPMutex();
#endif /* OS2 */
        return(ttibn);
    }
    if (count < 0) {                     /* Read error - connection closed */
#ifdef OS2
        ReleaseTCPIPMutex();
#endif /* OS2 */
        return(-2);
    }
    else if (count > TTIBUFL)           /* Too many to read */
      count = TTIBUFL;
    else if (count == 0)                /* None, so force blocking read */
      count = 1;
#endif /* OS2 */
#endif /* DEC_TCPIP */
#endif /* WINTCP */
    debug(F101,"ttbufr count 1","",count);

#ifdef CK_SSL
    if (ssl_active_flag || tls_active_flag) {
        int error;
      ssl_read:
        if (ssl_active_flag)
          count = SSL_read(ssl_con, ttibuf, count);
        else
          count = SSL_read(tls_con, ttibuf, count);
        error = SSL_get_error(ssl_active_flag?ssl_con:tls_con,count);
        switch (error) {
          case SSL_ERROR_NONE:
            debug(F111,"ttbufr SSL_ERROR_NONE","count",count);
            if (count > 0) {
                ttibp = 0;              /* Reset buffer pointer. */
                ttibn = count;
#ifdef OS2
                ReleaseTCPIPMutex();
#endif /* OS2 */
                return(ttibn);          /* Return buffer count. */
            } else if (count < 0) {
#ifdef OS2
                ReleaseTCPIPMutex();
#endif /* OS2 */
                return(-1);
            } else {
                netclos();
#ifdef OS2
                ReleaseTCPIPMutex();
#endif /* OS2 */
                return(-2);
            }
          case SSL_ERROR_WANT_WRITE:
            debug(F100,"ttbufr SSL_ERROR_WANT_WRITE","",0);
#ifdef OS2
              ReleaseTCPIPMutex();
#endif /* OS2 */
            return(-1);
          case SSL_ERROR_WANT_READ:
            debug(F100,"ttbufr SSL_ERROR_WANT_READ","",0);
#ifdef OS2
            ReleaseTCPIPMutex();
#endif /* OS2 */
            return(-1);
          case SSL_ERROR_SYSCALL:
              if ( count == 0 ) { /* EOF */
                  netclos();
#ifdef OS2
                  ReleaseTCPIPMutex();
#endif /* OS2 */
                  return(-2);
              } else {
                  int rc = -1;
#ifdef NT
                  int gle = GetLastError();
                  debug(F111,"ttbufr SSL_ERROR_SYSCALL",
                         "GetLastError()",gle);
                  rc = os2socketerror(gle);
                  if (rc == -1)
                      rc = -2;
                  else if ( rc == -2 )
                      rc = -1;
#endif /* NT */
#ifdef OS2
                  ReleaseTCPIPMutex();
#endif /* OS2 */
                  return(rc);
              }
          case SSL_ERROR_WANT_X509_LOOKUP:
            debug(F100,"ttbufr SSL_ERROR_WANT_X509_LOOKUP","",0);
            netclos();
#ifdef OS2
              ReleaseTCPIPMutex();
#endif /* OS2 */
            return(-2);
          case SSL_ERROR_SSL:
              if (bio_err!=NULL) {
                  int len;
                  extern char ssl_err[];
                  BIO_printf(bio_err,"ttbufr SSL_ERROR_SSL\n");
                  ERR_print_errors(bio_err);
                  len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
                  ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
                  debug(F110,"ttbufr SSL_ERROR_SSL",ssl_err,0);
                  if (ssl_debug_flag)                  
                      printf(ssl_err);
              } else if (ssl_debug_flag) {
                  debug(F100,"ttbufr SSL_ERROR_SSL","",0);
                  fflush(stderr);
                  fprintf(stderr,"ttbufr SSL_ERROR_SSL\n");
                  ERR_print_errors_fp(stderr);
              }
#ifdef COMMENT
	      netclos();
#endif /* COMMENT */
#ifdef OS2
              ReleaseTCPIPMutex();
#endif /* OS2 */
            return(-2);
          case SSL_ERROR_ZERO_RETURN:
            debug(F100,"ttbufr SSL_ERROR_ZERO_RETURN","",0);
            netclos();
#ifdef OS2
              ReleaseTCPIPMutex();
#endif /* OS2 */
            return(-2);
          default:
              debug(F100,"ttbufr SSL_ERROR_?????","",0);
              netclos();
#ifdef OS2
              ReleaseTCPIPMutex();
#endif /* OS2 */
              return(-2);
          }
    }
#endif /* CK_SSL */

#ifdef COMMENT
/*
 This is for nonblocking reads, which we don't do any more.  This code didn't
 work anyway, in the sense that a broken connection was never sensed.
*/
    if ((count = socket_read(ttyfd,&ttibuf[ttibp+ttibn],count)) < 1) {
        if (count == -1 && socket_errno == EWOULDBLOCK) {
            debug(F100,"ttbufr finds nothing","",0);
#ifdef OS2
            ReleaseTCPIPMutex();
#endif /* OS2 */
            return(0);
        } else {
            debug(F101,"ttbufr socket_read error","",socket_errno);
#ifdef OS2
            ReleaseTCPIPMutex();
#endif /* OS2 */
            return(-1);
        }

    } else if (count == 0) {
        debug(F100,"ttbufr socket eof","",0);
#ifdef OS2
        ReleaseTCPIPMutex();
#endif /* OS2 */
        return(-1);
    }
#else /* COMMENT */

/* This is for blocking reads */

#ifndef VMS
#ifdef SO_OOBINLINE
    {
        int outofband = 0;
#ifdef BELLSELECT
        if (select(128, NULL, NULL, efds, 0) > 0 && FD_ISSET(ttyfd, efds))
          outofband = 1;
#else
#ifdef BSDSELECT
        fd_set efds;
        struct timeval tv;
        FD_ZERO(&efds);
        FD_SET(ttyfd, &efds);
        tv.tv_sec  = tv.tv_usec = 0L;
        debug(F100,"Out-of-Band BSDSELECT","",0);
#ifdef NT
        WSASafeToCancel = 1;
#endif /* NT */
        if (select(FD_SETSIZE, NULL, NULL, &efds, &tv) > 0 &&
            FD_ISSET(ttyfd, &efds))
          outofband = 1;
#ifdef NT
        WSASafeToCancel = 0;
#endif /* NT */
#else /* !BSDSELECT */
#ifdef IBMSELECT
/* Is used by OS/2 ... */
/* ... and it came in handy!  For our TCP/IP layer, it avoids all the fd_set */
/* and timeval stuff since this is the only place where it is used. */
        int socket = ttyfd;
        debug(F100,"Out-of-Band IBMSELECT","",0);
        if ((select(&socket, 0, 0, 1, 0L) == 1) && (socket == ttyfd))
          outofband = 1;
#else /* !IBMSELECT */
/*
  If we can't use select(), then we use the regular alarm()/signal()
  timeout mechanism.
*/
      debug(F101,"Out-of-Band data not supported","",0);
      outofband = 0;

#endif /* IBMSELECT */
#endif /* BSDSELECT */
#endif /* BELLSELECT */
      if (outofband) {
         /* Get the Urgent Data */
         /* if OOBINLINE is disabled this should be only a single byte      */
         /* MS Winsock has a bug in Windows 95.  Extra bytes are delivered  */
         /* That were never sent.                                           */
#ifdef OS2
          RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
#endif /* OS2 */
          count = socket_recv(ttyfd,&ttibuf[ttibp+ttibn],count,MSG_OOB);
#ifdef OS2
          ReleaseTCPIPMutex();
#endif /* OS2 */
          if (count <= 0) {
              int s_errno = socket_errno;
              debug(F101, "ttbufr socket_recv MSG_OOB","",count);
              debug(F101, "ttbufr socket_errno","",s_errno);
#ifdef OS2ONLY
              if (count < 0 && (s_errno == 0 || s_errno == 23)) {
                  /* These appear in OS/2 - don't know why   */
                  /* ignore it and read as normal data       */
                  /* and break, then we will attempt to read */
                  /* the port using normal read() techniques */
                  debug(F100,"ttbufr handing as in-band data","",0);
                  count = 1;
              } else {
                  netclos();                    /* *** *** */
#ifdef OS2
                  ReleaseTCPIPMutex();
#endif /* OS2 */
                  return(-2);
              }
#else /* OS2ONLY */
              netclos();                        /* *** *** */
#ifdef OS2
              ReleaseTCPIPMutex();
#endif /* OS2 */
              return(-2);
#endif /* OS2ONLY */
          } else {                      /* we got out-of-band data */
              ckhexdump("ttbufr out-of-band chars",&ttibuf[ttibp+ttibn],count);
#ifdef BETADEBUG
              bleep(BP_NOTE);
#endif /* BETADEBUG */
#ifdef RLOGCODE                         /* blah */
              if (ttnproto == NP_RLOGIN  ||
                  ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN ||
                  ((ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN) && 
                  !rlog_inband)
                   )
              {
                  /*
                    When urgent data is read with MSG_OOB and not OOBINLINE
                    then urgent data and normal data are not mixed.  So
                    treat the entire buffer as urgent data.
                  */
                  rlog_oob(&ttibuf[ttibp+ttibn], count);
#ifdef OS2
                  ReleaseTCPIPMutex();
#endif /* OS2 */
                  return ttbufr();
              } else
#endif /* RLOGCODE */ /* blah */
#ifdef COMMENT
            /*
               I haven't written this yet, nor do I know what it should do
             */
                if (ttnproto == NP_TELNET) {
                    tn_oob();
#ifdef OS2
                    ReleaseTCPIPMutex();
#endif /* OS2 */
                    return 0;
              } else
#endif /* COMMENT */
              {
                  /* For any protocols we don't have a special out-of-band  */
                  /* handler for, just put the bytes in the normal buffer   */
                  /* and return                                             */

                  ttibp += 0;       /* Reset buffer pointer. */
                  ttibn += count;
#ifdef DEBUG
                  /* Got some bytes. */
                  debug(F101,"ttbufr count 2","",count);
                  if (count > 0)
                      ttibuf[ttibp+ttibn] = '\0';
                  debug(F111,"ttbufr ttibuf",ttibuf,ttibp);
#endif /* DEBUG */
#ifdef OS2
                  ReleaseTCPIPMutex();
#endif /* OS2 */
                  return(ttibn);    /* Return buffer count. */
              }
          }
      }
    }
#endif /* SO_OOBINLINE */
#endif /* VMS */

    count = socket_read(ttyfd,&ttibuf[ttibp+ttibn],count);
    if (count <= 0) {
        int s_errno = socket_errno;
        debug(F101,"ttbufr socket_read","",count);
        debug(F101,"ttbufr socket_errno","",s_errno);
#ifdef OS2
        if (count == 0 || os2socketerror(s_errno) < 0) {
            netclos();
            ReleaseTCPIPMutex();
            return(-2);
        }
        ReleaseTCPIPMutex();
        return(-1);
#else /* OS2 */
        netclos();                      /* *** *** */
        return(-2);
#endif /* OS2 */
    }
#endif /* COMMENT */ /* (blocking vs nonblock reads...) */
    else {
        ttibp = 0;                      /* Reset buffer pointer. */
        ttibn += count;
#ifdef DEBUG
        debug(F101,"ttbufr count 2","",count); /* Got some bytes. */
        if (count > 0)
          ttibuf[ttibp+ttibn] = '\0';
        debug(F111,"ttbufr ttibuf",&ttibuf[ttibp],ttibn);
#endif /* DEBUG */

#ifdef OS2
        ReleaseTCPIPMutex();
#endif /* OS2 */
        return(ttibn);                  /* Return buffer count. */
    }
}
#endif /* TCPIPLIB */

#ifndef IBMSELECT
#ifndef BELLSELECT
#ifndef BSDSELECT               /* Non-TCPIPLIB case */
#ifdef SELECT
#define BSDSELECT
#endif /* SELECT */
#endif /* BSDSELECT */
#endif /* BELLSELECT */
#endif /* IBMSELECT */

#define TELNET_PORT 23          /* Should do lookup, but it won't change */
#define RLOGIN_PORT 513
#define KERMIT_PORT 1649
#define KLOGIN_PORT 543
#define EKLOGIN_PORT 2105

#ifndef NONET
/*
  C-Kermit network open/close functions for BSD-sockets.
  Much of this code shared by SunLink X.25, which also uses the socket library.
*/

/*  N E T O P N  --  Open a network connection.  */
/*
  Call with:
    name of host (or host:service),
    lcl - local-mode flag to be set if this function succeeds,
    network type - value defined in ckunet.h.
*/
#ifdef TCPSOCKET
struct hostent *
#ifdef CK_ANSIC
ck_copyhostent(struct hostent * h)
#else /* CK_ANSIC */
ck_copyhostent(h) struct hostent * h;
#endif /* CK_ANSIC */
{
    /*
     *  The hostent structure is dynamic in nature.
     *  struct  hostent {
     *  char    * h_name;
     *  char    * * h_aliases;
     *  short   h_addrtype;
     *  short   h_length;
     *  char    * * h_addr_list;
     *  #define h_addr  h_addr_list[0]
     */
#define HOSTENTCNT 5
    static struct hostent hosts[HOSTENTCNT] = {{NULL,NULL,0,0,NULL},
                                               {NULL,NULL,0,0,NULL},
                                               {NULL,NULL,0,0,NULL},
                                               {NULL,NULL,0,0,NULL},
                                               {NULL,NULL,0,0,NULL}};
    static int    next = 0;
    int    i,cnt;
    char ** pp;

    if ( h == NULL )
        return(NULL);

    if (next == HOSTENTCNT)
        next = 0;

    if ( hosts[next].h_name ) {
        free(hosts[next].h_name);
        hosts[next].h_name = NULL;
    }
    if ( hosts[next].h_aliases ) {
        pp = hosts[next].h_aliases;
        while ( *pp ) {
            free(*pp);
            pp++;
        }
        free(hosts[next].h_aliases);
    }
#ifdef HADDRLIST
    if ( hosts[next].h_addr_list ) {
        pp = hosts[next].h_addr_list;
        while ( *pp ) {
            free(*pp);
            pp++;
        }
        free(hosts[next].h_addr_list);
    }
#endif /* HADDRLIST */

    makestr(&hosts[next].h_name,h->h_name);
    if (h->h_aliases) {
        for ( cnt=0,pp=h->h_aliases; pp && *pp; pp++,cnt++) ;
        /* The following can give warnings in non-ANSI builds */
        hosts[next].h_aliases = (char **) malloc(sizeof(char *) * (cnt+1));
        for ( i=0; i<cnt; i++) {
            hosts[next].h_aliases[i] = NULL;
            makestr(&hosts[next].h_aliases[i],h->h_aliases[i]);
        }
        hosts[next].h_aliases[i] = NULL;
    } else
        hosts[next].h_aliases = NULL;

    hosts[next].h_addrtype = h->h_addrtype;
    hosts[next].h_length = h->h_length;

#ifdef HADDRLIST
#ifdef h_addr
    if (h->h_addr_list) {
        for ( cnt=0,pp=h->h_addr_list; pp && *pp; pp++,cnt++) ;
        /* The following can give warnings non-ANSI builds */
        hosts[next].h_addr_list = (char **) malloc(sizeof(char *) * (cnt+1));
        for ( i=0; i<cnt; i++) {
            hosts[next].h_addr_list[i] = malloc(h->h_length);
            bcopy(h->h_addr_list[i],hosts[next].h_addr_list[i],h->h_length);
        }
        hosts[next].h_addr_list[i] = NULL;
    } else
        hosts[next].h_addr_list = NULL;
#else
    bcopy(h->h_addr, &hosts[next].h_addr, h->h_length);
#endif /* h_addr */
#else /* HADDRLIST */
    bcopy(h->h_addr, &hosts[next].h_addr, h->h_length);
#endif /* HADDRLIST */

    return(&hosts[next++]);
}

#ifdef EXCELAN
/*
  Most other BSD sockets implementations define these in header files
  and libraries.
*/
struct servent {
    unsigned short s_port;
};

struct hostent {
    short h_addrtype;
    struct in_addr h_addr;
    int h_length;
};

struct servent *
getservbyname(service, connection) char *service,*connection; {
    static struct servent servrec;
    int port;

    port = 0;
    if (strcmp(service, "telnet") == 0) port = 23;
    else if (strcmp(service, "smtp") == 0) port = 25;
    else port = atoi(service);

    debug(F101,"getservbyname return port ","",port);

    if (port > 0) {
        servrec.s_port = htons(port);
        return(&servrec);
    }
    return((struct servent *) NULL);
}

struct hostent *
gethostbyname(hostname) char *hostname; {
    return((struct hostent *) NULL);
}

unsigned long
inet_addr(name) char *name; {
    unsigned long addr;

    addr = rhost(&name);
    debug(F111,"inet_addr ",name,(int)addr);
    return(addr);
}

char *
inet_ntoa(in) struct in_addr in; {
    static char name[80];
    ckmakxmsg(name, ckuitoa(in.s_net),".",ckuitoa(in.s_host),".",
               ckuitoa(in.s_lh),".", ckuitoa(in.s_impno));
    return(name);
}
#else
#ifdef DEC_TCPIP                        /* UCX */

int ucx_port_bug = 0;                   /* Explained below */

#ifdef OLDIP				/* Very old VAXC or GCC */
/*
  Note that my oldest VAX C (V3.1-051) does not need (or want) OLDIP,
  hence the "Very old" in the comment - SMS, 2010/03/15.
*/
#define getservbyname my_getservbyname

#ifdef CK_ANSIC
globalref int (*C$$GA_UCX_GETSERVBYNAME)();
extern void C$$TRANSLATE();
extern void C$$SOCK_TRANSLATE();
#else
globalref int (*C$$GA_UCX_GETSERVBYNAME)();
extern VOID C$$TRANSLATE();
extern VOID C$$SOCK_TRANSLATE();
#endif /* CK_ANSIC */

struct servent *
my_getservbyname (service, proto) char *service, *proto; {
    static struct servent sent;
    struct iosb {
        union {
            unsigned long status;
            unsigned short st[2];
        } sb;
        unsigned long spare;
    } s;
    struct {
        struct iosb *s;
        char *serv;
        char *prot;
    } par;
    unsigned long e;
    char sbuf[30], pbuf[30];
    char *p;

    debug(F111,"UCX getservbyname",service,(int)C$$GA_UCX_GETSERVBYNAME);

    p = sbuf;
    ckstrncpy(p, service, 29);
    while (*p = toupper(*p), *p++) {}
    p = pbuf;
    ckstrncpy(p, proto, 29);
    while (*p = toupper(*p), *p++) {}

    par.s = &s;

    par.serv = "";
    par.prot = "";
    /* reset file pointer or something like that!?!? */
    e = (*C$$GA_UCX_GETSERVBYNAME)(&par, &sent, par.s);
    par.serv = sbuf;
    par.prot = pbuf;            /* that is don't care */
    e = (*C$$GA_UCX_GETSERVBYNAME)(&par, &sent, par.s);
    if ((long)e == -1L)
      return NULL;
    if ((e & 1) == 0L) {
        C$$TRANSLATE(e);
        return NULL;
    }
    if ((s.sb.st[0] & 1) == 0) {
        C$$SOCK_TRANSLATE(&s.sb.st[0]);
        return NULL;
    }
/*
  sent.s_port is supposed to be returned by UCX in network byte order.
  However, UCX 2.0 through 2.0C did not do this; 2.0D and later do it.
  But there is no way of knowing which UCX version, so we have a user-settable
  runtime variable.  Note: UCX 2.0 was only for the VAX.
*/
    debug(F101,"UCX getservbyname port","",sent.s_port);
    debug(F101,"UCX getservbyname ntohs(port)","",ntohs(sent.s_port));
    if (ucx_port_bug) {
        sent.s_port = htons(sent.s_port);
        debug(F100,"UCX-PORT-BUG ON: swapping bytes","",0);
        debug(F101,"UCX swapped port","",sent.s_port);
        debug(F101,"UCX swapped ntohs(port)","",ntohs(sent.s_port));
    }
    return &sent;
}
#endif /* def OLDIP */
#endif /* DEC_TCPIP */
#endif /* EXCELAN */

int
gettcpport() {
    return(svcnum);
}

#endif /* TCPSOCKET */

#ifndef NOTCPOPTS
#ifndef datageneral
int
ck_linger(sock, onoff, timo) int sock; int onoff; int timo; {
/*
  The following, from William Bader, turns off the socket linger parameter,
  which makes a close() block until all data is sent.  "I don't think that
  disabling linger can ever cause kermit to lose data, but you telnet to a
  flaky server (or to our modem server when the modem is in use), disabling
  linger prevents kermit from hanging on the close if you try to exit."

  Modified by Jeff Altman to be generally useful.
*/
#ifdef SOL_SOCKET
#ifdef SO_LINGER
    struct linger set_linger_opt;
    struct linger get_linger_opt;
    SOCKOPT_T x;

#ifdef IKSD
    if (!inserver)
#endif /* IKSD */
      if (sock == -1 ||
        nettype != NET_TCPA && nettype != NET_TCPB &&
        nettype != NET_SSH || ttmdm >= 0) {
        tcp_linger = onoff;
        tcp_linger_tmo = timo;
        return(1);
    }
    x = sizeof(get_linger_opt);
    if (getsockopt(sock, SOL_SOCKET, SO_LINGER,
                    (char *)&get_linger_opt, &x)) {
        debug(F111,"TCP ck_linger can't get SO_LINGER",ck_errstr(),errno);
    } else if (x != sizeof(get_linger_opt)) {
#ifdef OS2
        struct _linger16 {
            short s_linger;
            short s_onoff;
        } get_linger_opt16, set_linger_opt16;
        if ( x == sizeof(get_linger_opt16) ) {
            debug(F111,"TCP setlinger warning: SO_LINGER","len is 16-bit",x);
            if (getsockopt(sock,
                           SOL_SOCKET, SO_LINGER,
                           (char *)&get_linger_opt16, &x)
                ) {
                debug(F111,
                      "TCP ck_linger can't get SO_LINGER",ck_errstr(),errno);
            } else if (get_linger_opt16.s_onoff != onoff ||
                       get_linger_opt16.s_linger != timo)
            {
                set_linger_opt16.s_onoff  = onoff;
                set_linger_opt16.s_linger = timo;
                if (setsockopt(sock,
                               SOL_SOCKET,
                               SO_LINGER,
                               (char *)&set_linger_opt16,
                               sizeof(set_linger_opt16))
                    ) {
                    debug(F111,
                          "TCP ck_linger can't set SO_LINGER",
                          ck_errstr(),
                          errno
                          );
                    tcp_linger = get_linger_opt16.s_onoff;
                    tcp_linger_tmo = get_linger_opt16.s_linger;
                } else {
                    debug(F101,
                          "TCP ck_linger new SO_LINGER","",
                          set_linger_opt16.s_onoff);
                    tcp_linger = set_linger_opt16.s_onoff;
                    tcp_linger_tmo = set_linger_opt16.s_linger;
                    return 1;
                }
            } else {
                debug(F101,"TCP ck_linger SO_LINGER unchanged","",
                       get_linger_opt16.s_onoff);
                tcp_linger = get_linger_opt16.s_onoff;
                tcp_linger_tmo = get_linger_opt16.s_linger;
                return 1;
            }
            return(0);
        }
#endif /* OS2 */
        debug(F111,"TCP ck_linger error: SO_LINGER","len",x);
        debug(F111,"TCP ck_linger SO_LINGER",
              "expected len",sizeof(get_linger_opt));
        debug(F111,"TCP ck_linger SO_LINGER","linger_opt.l_onoff",
              get_linger_opt.l_onoff);
        debug(F111,"TCP linger SO_LINGER","linger_opt.l_linger",
               get_linger_opt.l_linger);
    } else if (get_linger_opt.l_onoff != onoff ||
               get_linger_opt.l_linger != timo) {
        set_linger_opt.l_onoff  = onoff;
        set_linger_opt.l_linger = timo;
        if (setsockopt(sock,
                       SOL_SOCKET,
                       SO_LINGER,
                       (char *)&set_linger_opt,
                       sizeof(set_linger_opt))) {
            debug(F111,"TCP ck_linger can't set SO_LINGER",ck_errstr(),errno);
            tcp_linger = get_linger_opt.l_onoff;
            tcp_linger_tmo = get_linger_opt.l_linger;
         } else {
             debug(F101,
                   "TCP ck_linger new SO_LINGER",
                   "",
                   set_linger_opt.l_onoff
                   );
             tcp_linger = set_linger_opt.l_onoff;
             tcp_linger_tmo = set_linger_opt.l_linger;
             return 1;
         }
    } else {
        debug(F101,"TCP ck_linger SO_LINGER unchanged","",
              get_linger_opt.l_onoff);
        tcp_linger = get_linger_opt.l_onoff;
        tcp_linger_tmo = get_linger_opt.l_linger;
        return 1;
    }
#else
    debug(F100,"TCP ck_linger SO_LINGER not defined","",0);
#endif /* SO_LINGER */
#else
    debug(F100,"TCP ck_linger SO_SOCKET not defined","",0);
#endif /* SOL_SOCKET */
    return(0);
}

int
sendbuf(sock,size) int sock; int size; {
/*
  The following, from William Bader, allows changing of socket buffer sizes,
  in case that might affect performance.

  Modified by Jeff Altman to be generally useful.
*/
#ifdef SOL_SOCKET
#ifdef SO_SNDBUF
    int i, j;
    SOCKOPT_T x;

#ifdef IKSD
    if (!inserver)
#endif /* IKSD */
      if (sock == -1 ||
        nettype != NET_TCPA && nettype != NET_TCPB && nettype != NET_SSH
                || ttmdm >= 0) {
        tcp_sendbuf = size;
        return 1;
    }
    x = sizeof(i);
    if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&i, &x)) {
        debug(F111,"TCP sendbuf can't get SO_SNDBUF",ck_errstr(),errno);
    } else if (x != sizeof(i)) {
#ifdef OS2
        short i16,j16;
        if (x == sizeof(i16)) {
            debug(F111,"TCP sendbuf warning: SO_SNDBUF","len is 16-bit",x);
            if (getsockopt(sock,
                           SOL_SOCKET, SO_SNDBUF,
                           (char *)&i16, &x)
                ) {
                debug(F111,"TCP sendbuf can't get SO_SNDBUF",
                      ck_errstr(),errno);
            } else if (size <= 0) {
                tcp_sendbuf = i16;
                debug(F101,"TCP sendbuf SO_SNDBUF retrieved","",i16);
                return 1;
            } else if (i16 != size) {
                j16 = size;
                if (setsockopt(sock,
                               SOL_SOCKET,
                               SO_SNDBUF,
                               (char *)&j16,
                               sizeof(j16))
                    ) {
                    debug(F111,"TCP sendbuf can't set SO_SNDBUF",
                          ck_errstr(),errno);
                } else {
                    debug(F101,"TCP sendbuf old SO_SNDBUF","",i16);
                    debug(F101,"TCP sendbuf new SO_SNDBUF","",j16);
                    tcp_sendbuf = size;
                    return 1;
                }
            } else {
                debug(F101,"TCP sendbuf SO_SNDBUF unchanged","",i16);
                tcp_sendbuf = size;
                return 1;
            }
            return(0);
        }
#endif /* OS2 */
        debug(F111,"TCP sendbuf error: SO_SNDBUF","len",x);
        debug(F111,"TCP sendbuf SO_SNDBUF","expected len",sizeof(i));
        debug(F111,"TCP sendbuf SO_SNDBUF","i",i);
    } else if (size <= 0) {
        tcp_sendbuf = i;
        debug(F101,"TCP sendbuf SO_SNDBUF retrieved","",i);
        return 1;
    } else if (i != size) {
        j = size;
        if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&j, sizeof(j))) {
            debug(F111,"TCP sendbuf can't set SO_SNDBUF",ck_errstr(),errno);
            tcp_sendbuf = i;
        } else {
            debug(F101,"TCP sendbuf old SO_SNDBUF","",i);
            debug(F101,"TCP sendbuf new SO_SNDBUF","",j);
            tcp_sendbuf = size;
            return 1;
        }
    } else {
        debug(F101,"TCP sendbuf SO_SNDBUF unchanged","",i);
        tcp_sendbuf = size;
        return 1;
    }
#else
    debug(F100,"TCP sendbuf SO_SNDBUF not defined","",0);
#endif /* SO_SNDBUF */
#else
    debug(F100,"TCP sendbuf SO_SOCKET not defined","",0);
#endif /* SOL_SOCKET */
    return(0);
}

int
recvbuf(sock,size) int sock; int size; {
/*
  The following, from William Bader, allows changing of socket buffer sizes,
  in case that might affect performance.

  Modified by Jeff Altman to be generally useful.
*/
#ifdef SOL_SOCKET
#ifdef SO_RCVBUF
    int i, j;
    SOCKOPT_T x;

#ifdef IKSD
    if (!inserver)
#endif /* IKSD */
      if (sock == -1 ||
	  nettype != NET_TCPA && nettype != NET_TCPB &&
	  nettype != NET_SSH || ttmdm >= 0) {
        tcp_recvbuf = size;
        return(1);
    }
    x = sizeof(i);
    if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&i, &x)) {
        debug(F111,"TCP recvbuf can't get SO_RCVBUF",ck_errstr(),errno);
    } else if (x != sizeof(i)) {
#ifdef OS2
        short i16,j16;
        if ( x == sizeof(i16) ) {
            debug(F111,"TCP recvbuf warning: SO_RCVBUF","len is 16-bit",x);
            if (getsockopt(sock,
                           SOL_SOCKET, SO_RCVBUF,
                           (char *)&i16, &x)
                ) {
                debug(F111,"TCP recvbuf can't get SO_RCVBUF",
                      ck_errstr(),errno);
            } else if (size <= 0) {
                tcp_recvbuf = i16;
                debug(F101,"TCP recvbuf SO_RCVBUF retrieved","",i16);
                return 1;
            } else if (i16 != size) {
                j16 = size;
                if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&j16,
                               sizeof(j16))) {
                    debug(F111,"TCP recvbuf can' set SO_RCVBUF",
                          ck_errstr(),errno);
                } else {
                    debug(F101,"TCP recvbuf old SO_RCVBUF","",i16);
                    debug(F101,"TCP recvbuf new SO_RCVBUF","",j16);
                    tcp_recvbuf = size;
                    return 1;
                }
            } else {
                debug(F101,"TCP recvbuf SO_RCVBUF unchanged","",i16);
                tcp_recvbuf = size;
                return 1;
            }
            return(0);
        }
#endif /* OS2 */
        debug(F111,"TCP recvbuf error: SO_RCVBUF","len",x);
        debug(F111,"TCP recvbuf SO_RCVBUF","expected len",sizeof(i));
        debug(F111,"TCP recvbuf SO_RCVBUF","i",i);
    } else if (size <= 0) {
        tcp_recvbuf = i;
        debug(F101,"TCP recvbuf SO_RCVBUF retrieved","",i);
        return 1;
    } else if (i != size) {
        j = size;
        if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&j, sizeof(j))) {
            debug(F111,"TCP recvbuf can't set SO_RCVBUF",ck_errstr(),errno);
            tcp_recvbuf = i;
        } else {
            debug(F101,"TCP recvbuf old SO_RCVBUF","",i);
            debug(F101,"TCP recvbuf new SO_RCVBUF","",j);
            tcp_recvbuf = size;
            return 1;
        }
    } else {
        debug(F101,"TCP recvbuf SO_RCVBUF unchanged","",i);
        tcp_recvbuf = size;
        return 1;
    }
#else
    debug(F100,"TCP recvbuf SO_RCVBUF not defined","",0);
#endif /* SO_RCVBUF */
#else
    debug(F100,"TCP recvbuf SO_SOCKET not defined","",0);
#endif /* SOL_SOCKET */
    return 0;
}

int
keepalive(sock,onoff) int sock; int onoff; {
#ifdef SOL_SOCKET
#ifdef SO_KEEPALIVE
    int get_keepalive_opt;
    int set_keepalive_opt;
    SOCKOPT_T x;

    debug(F111,"TCP keepalive","sock",sock);
    debug(F111,"TCP keepalive","nettype",nettype);
    debug(F111,"TCP keepalive","ttmdm",ttmdm);

#ifdef IKSD
    if (!inserver)
#endif /* IKSD */
      if (sock == -1 ||
        nettype != NET_TCPA && nettype != NET_TCPB && nettype != NET_SSH
                || ttmdm >= 0) {
        tcp_keepalive = onoff;
        return 1;
    }
    x = sizeof(get_keepalive_opt);
    if (getsockopt(sock,
                   SOL_SOCKET, SO_KEEPALIVE, (char *)&get_keepalive_opt, &x)) {
        debug(F111,"TCP keepalive can't get SO_KEEPALIVE",ck_errstr(),errno);
    } else if (x != sizeof(get_keepalive_opt)) {
#ifdef OS2
        short get_keepalive_opt16;
        short set_keepalive_opt16;
        if (x == sizeof(get_keepalive_opt16)) {
            debug(F111,"TCP keepalive warning: SO_KEEPALIVE",
                  "len is 16-bit",x);
            if (getsockopt(sock,
                           SOL_SOCKET, SO_KEEPALIVE,
                           (char *)&get_keepalive_opt16, &x)
                ) {
                debug(F111,
                      "TCP keepalive can't get SO_KEEPALIVE",
                      ck_errstr(),
                      errno
                      );
            } else if (get_keepalive_opt16 != onoff) {
                set_keepalive_opt16 = onoff;
                if (setsockopt(sock,
                               SOL_SOCKET,
                               SO_KEEPALIVE,
                               (char *)&set_keepalive_opt16,
                               sizeof(set_keepalive_opt16))
                    ) {
                    debug(F111,
                          "TCP keepalive can't clear SO_KEEPALIVE",
                          ck_errstr(),
                          errno
                          );
                    tcp_keepalive = get_keepalive_opt16;
                } else {
                    debug(F101,
                          "TCP keepalive new SO_KEEPALIVE","",
                          set_keepalive_opt16);
                    tcp_keepalive = set_keepalive_opt16;
                    return 1;
                }
            } else {
                debug(F101,"TCP keepalive SO_KEEPALIVE unchanged","",
                      get_keepalive_opt16);
                tcp_keepalive = onoff;
                return 1;
            }
            return(0);
        }
#endif /* OS2 */
        debug(F111,"TCP keepalive error: SO_KEEPALIVE","len",x);
        debug(F111,
              "TCP keepalive SO_KEEPALIVE",
              "expected len",
              sizeof(get_keepalive_opt)
              );
        debug(F111,
              "TCP keepalive SO_KEEPALIVE",
              "keepalive_opt",
              get_keepalive_opt
              );
    } else if (get_keepalive_opt != onoff) {
            set_keepalive_opt = onoff;
            if (setsockopt(sock,
                            SOL_SOCKET,
                            SO_KEEPALIVE,
                            (char *)&set_keepalive_opt,
                            sizeof(set_keepalive_opt))
                ) {
                debug(F111,
                      "TCP keepalive can't clear SO_KEEPALIVE",
                      ck_errstr(),
                      errno
                      );
                tcp_keepalive = get_keepalive_opt;
            } else {
                debug(F101,
                      "TCP keepalive new SO_KEEPALIVE",
                      "",
                      set_keepalive_opt
                      );
                tcp_keepalive = onoff;
                return 1;
            }
        } else {
            debug(F101,"TCP keepalive SO_KEEPALIVE unchanged",
                  "",
                  get_keepalive_opt
                  );
            tcp_keepalive = onoff;
            return 1;
    }
#else
    debug(F100,"TCP keepalive SO_KEEPALIVE not defined","",0);
#endif /* SO_KEEPALIVE */
#else
    debug(F100,"TCP keepalive SO_SOCKET not defined","",0);
#endif /* SOL_SOCKET */
    return(0);
}

int
dontroute(sock,onoff) int sock; int onoff; {
#ifdef SOL_SOCKET
#ifdef SO_DONTROUTE
    int get_dontroute_opt;
    int set_dontroute_opt;
    SOCKOPT_T x;

#ifdef IKSD
    if (!inserver)
#endif /* IKSD */
      if (sock == -1 ||
        nettype != NET_TCPA && nettype != NET_TCPB && nettype != NET_SSH
                || ttmdm >= 0) {
        tcp_dontroute = onoff;
        return 1;
    }
    x = sizeof(get_dontroute_opt);
    if (getsockopt(sock,
                   SOL_SOCKET, SO_DONTROUTE, (char *)&get_dontroute_opt, &x)) {
        debug(F111,"TCP dontroute can't get SO_DONTROUTE",ck_errstr(),errno);
    } else if (x != sizeof(get_dontroute_opt)) {
#ifdef OS2
        short get_dontroute_opt16;
        short set_dontroute_opt16;
        if (x == sizeof(get_dontroute_opt16)) {
            debug(F111,"TCP dontroute warning: SO_DONTROUTE",
                  "len is 16-bit",x);
            if (getsockopt(sock,
                           SOL_SOCKET, SO_DONTROUTE,
                           (char *)&get_dontroute_opt16, &x)
                ) {
                debug(F111,
                      "TCP dontroute can't get SO_DONTROUTE",
                      ck_errstr(),
                      errno
                      );
            } else if (get_dontroute_opt16 != onoff) {
                set_dontroute_opt16 = onoff;
                if (setsockopt(sock,
                               SOL_SOCKET,
                               SO_DONTROUTE,
                               (char *)&set_dontroute_opt16,
                               sizeof(set_dontroute_opt16))
                    ) {
                    debug(F111,
                          "TCP dontroute can't clear SO_DONTROUTE",
                          ck_errstr(),
                          errno
                          );
                    tcp_dontroute = get_dontroute_opt16;
                } else {
                    debug(F101,
                          "TCP dontroute new SO_DONTROUTE","",
                          set_dontroute_opt16);
                    tcp_dontroute = set_dontroute_opt16;
                    return 1;
                }
            } else {
                debug(F101,"TCP dontroute SO_DONTROUTE unchanged","",
                      get_dontroute_opt16);
                tcp_dontroute = onoff;
                return 1;
            }
            return(0);
        }
#endif /* OS2 */
        debug(F111,"TCP dontroute error: SO_DONTROUTE","len",x);
        debug(F111,
              "TCP dontroute SO_DONTROUTE",
              "expected len",
              sizeof(get_dontroute_opt)
              );
        debug(F111,
              "TCP dontroute SO_DONTROUTE",
              "dontroute_opt",
              get_dontroute_opt
              );
    } else if (get_dontroute_opt != onoff) {
            set_dontroute_opt = onoff;
            if (setsockopt(sock,
                            SOL_SOCKET,
                            SO_DONTROUTE,
                            (char *)&set_dontroute_opt,
                            sizeof(set_dontroute_opt))
                ) {
                debug(F111,
                      "TCP dontroute can't clear SO_DONTROUTE",
                      ck_errstr(),
                      errno
                      );
                tcp_dontroute = get_dontroute_opt;
            } else {
                debug(F101,
                      "TCP dontroute new SO_DONTROUTE",
                      "",
                      set_dontroute_opt
                      );
                tcp_dontroute = onoff;
                return 1;
            }
        } else {
            debug(F101,"TCP dontroute SO_DONTROUTE unchanged",
                  "",
                  get_dontroute_opt
                  );
            tcp_dontroute = onoff;
            return 1;
    }
#else
    debug(F100,"TCP dontroute SO_DONTROUTE not defined","",0);
#endif /* SO_DONTROUTE */
#else
    debug(F100,"TCP dontroute SO_SOCKET not defined","",0);
#endif /* SOL_SOCKET */
    return(0);
}

int
no_delay(sock,onoff)  int sock; int onoff; {
#ifdef SOL_SOCKET
#ifdef TCP_NODELAY
    int get_nodelay_opt;
    int set_nodelay_opt;
    SOCKOPT_T x;

#ifdef IKSD
    if (!inserver)
#endif /* IKSD */
      if (sock == -1 ||
        nettype != NET_TCPA && nettype != NET_TCPB && nettype != NET_SSH
                || ttmdm >= 0) {
        tcp_nodelay = onoff;
        return(1);
    }
    x = sizeof(get_nodelay_opt);
    if (getsockopt(sock,IPPROTO_TCP,TCP_NODELAY,
                   (char *)&get_nodelay_opt,&x)) {
        debug(F111,
              "TCP no_delay can't get TCP_NODELAY",
              ck_errstr(),
              errno);
    } else if (x != sizeof(get_nodelay_opt)) {
#ifdef OS2
        short get_nodelay_opt16;
        short set_nodelay_opt16;
        if (x == sizeof(get_nodelay_opt16)) {
            debug(F111,"TCP no_delay warning: TCP_NODELAY","len is 16-bit",x);
            if (getsockopt(sock,
                           IPPROTO_TCP, TCP_NODELAY,
                           (char *)&get_nodelay_opt16, &x)
                ) {
                debug(F111,
                      "TCP no_delay can't get TCP_NODELAY",
                      ck_errstr(),
                      errno);
            } else if (get_nodelay_opt16 != onoff) {
                set_nodelay_opt16 = onoff;
                if (setsockopt(sock,
                               IPPROTO_TCP,
                               TCP_NODELAY,
                               (char *)&set_nodelay_opt16,
                               sizeof(set_nodelay_opt16))
                    ) {
                    debug(F111,
                          "TCP no_delay can't clear TCP_NODELAY",
                          ck_errstr(),
                          errno);
                    tcp_nodelay = get_nodelay_opt16;
                } else {
                    debug(F101,
                          "TCP no_delay new TCP_NODELAY",
                          "",
                          set_nodelay_opt16);
                    tcp_nodelay = onoff;
                    return 1;
                }
            } else {
                debug(F101,"TCP no_delay TCP_NODELAY unchanged","",
                      get_nodelay_opt16);
                tcp_nodelay = onoff;
                return 1;
            }
            return(0);
        }
#endif /* OS2 */
        debug(F111,"TCP no_delay error: TCP_NODELAY","len",x);
        debug(F111,"TCP no_delay TCP_NODELAY","expected len",
              sizeof(get_nodelay_opt));
        debug(F111,"TCP no_delay TCP_NODELAY","nodelay_opt",get_nodelay_opt);
    } else if (get_nodelay_opt != onoff) {
        set_nodelay_opt = onoff;
        if (setsockopt(sock,
                       IPPROTO_TCP,
                       TCP_NODELAY,
                       (char *)&set_nodelay_opt,
                       sizeof(set_nodelay_opt))) {
            debug(F111,
                  "TCP no_delay can't clear TCP_NODELAY",
                  ck_errstr(),
                  errno
                  );
            tcp_nodelay = get_nodelay_opt;
        } else {
            debug(F101,"TCP no_delay new TCP_NODELAY","",set_nodelay_opt);
            tcp_nodelay = onoff;
            return 1;
        }
    } else {
        debug(F101,"TCP no_delay TCP_NODELAY unchanged","",get_nodelay_opt);
        tcp_nodelay = onoff;
        return(1);
    }
#else
    debug(F100,"TCP no_delay TCP_NODELAY not defined","",0);
#endif /* TCP_NODELAY */
#else
    debug(F100,"TCP no_delay SO_SOCKET not defined","",0);
#endif /* SOL_SOCKET */
    return 0;
}
#endif /* datageneral */
#endif /* NOTCPOPTS */

#ifdef SUNX25
#ifndef X25_WR_FACILITY
/* For Solaris 2.3 / SunLink 8.x - see comments in ckcnet.h */
void
bzero(s,n) char *s; int n; {
    memset(s,0,n);
}
#endif /* X25_WR_FACILITY */
#endif /* SUNX25 */

#ifdef TCPSOCKET
#ifndef OS2
#ifndef NOLISTEN

#ifdef BSDSELECT
#ifndef VMS
#ifndef BELLV10
#ifndef datageneral
#ifdef hp9000s500                       /* HP-9000/500 HP-U 5.21 */
#include <time.h>
#else

/****** THIS SECTION ADDED BY STEVE RANCE - OS9 NETWORK SERVER
*       ------------------------------------------------------
*
*       Due to OS9's Lack of a select() call, the following seems to be
*       enough to fool the rest of the code into compiling. The only
*       effect that I can see is using control L to refresh the status
*       display gets qued up until some network packets arrive.
*
*       This solution is by no means elegant but works enough to be
*       a (the) solution.
*
*       Also with the defines I had specified in my makefile I had to
*       have an #endif right at the end of the file when compiling.
*       I did not bother speding time to find out why.
*
*       COPTS   = -to=osk -d=OSK -d=TCPSOCKET -d=SELECT -d=VOID=void -d=SIG_V \
*          -d=DYNAMIC -d=PARSENSE -d=KANJI -d=MYCURSES -d=ZFCDAT \
*          -d=CK_APC -d=CK_REDIR -d=RENAME -d=CK_TTYFD -d=NOOLDMODEMS \
*          -d=CK_ANSIC -d=CK_XYZ -tp=68040d -l=netdb.l -l=socklib.l \
*          -l=termlib.l -l=math.l -l=sys_clib.l
*
*       stever@ozemail.com.au
*/

#ifdef  OSK
#define BSDSELECT                       /* switch on BSD select code */
#define FD_SETSIZE 32                   /* Max # of paths in OS9 */
#define FD_ZERO(p)                      ((*p)=0)
#define FD_SET(n,b)                     ((*b)|=(1<<(n)))
#define FD_ISSET(n,b)           1       /* always say data is ready */
#define select(a,b,c,d,e)       1       /* always say 1 path has data */
typedef int     fd_set;                 /* keep BSD Code Happy */
struct timeval {int tv_sec,tv_usec;};   /* keep BSD Code Happy */

/****** END OF OS9 MODS FROM STEVE RANCE **************************/
#endif /* OSK */

#include <sys/time.h>
#endif /* hp9000s500 */
#endif /* datageneral */
#endif /* BELLV10 */
#endif /* VMS */
#ifdef SELECT_H
#include <sys/select.h>
#endif /* SELECT_H */
#endif /* BSDSELECT */

#ifdef SELECT
#ifdef CK_SCOV5
#include <sys/select.h>
#endif /* CK_SCOV5 */
#endif /* SELECT */

#ifdef NOTUSED
/* T C P S O C K E T _ O P E N -- Open a preexisting socket number */

int
tcpsocket_open(name,lcl,nett,timo) char * name; int * lcl; int nett; int timo {
    int on = 1;
    static struct servent *service, servrec;
    static struct hostent *host;
    static struct sockaddr_in saddr;
    static
#ifdef UCX50
      unsigned
#endif /* UCX50 */
      int saddrlen;
#ifdef BSDSELECT
    fd_set rfds;
    struct timeval tv;
#else
#ifdef BELLSELECT
    fd_set rfds;
#else
    fd_set rfds;
    fd_set rfds;
    struct timeval {
        long tv_sec;
        long tv_usec;
    } tv;
#endif /* BELLSELECT */
#endif /* BSDSELECT */

    debug(F101,"tcpsocket_open nett","",nett);
    *ipaddr = '\0';

    if (nett != NET_TCPB)
      return(-1);                       /* BSD socket support */

    netclos();                          /* Close any previous connection. */
    ckstrncpy(namecopy, name, NAMECPYL); /* Copy the hostname. */
#ifdef COMMENT
    /* Jeff's version from 30 Dec 2005 doesn't inhibit Telnet */
    if (ttnproto != NP_TCPRAW &&
	ttnproto != NP_SSL_RAW &&
	ttnproto != NP_TLS_RAW)
      ttnproto = NP_NONE;               /* No protocol selected yet. */
#else
    /* fdc's version from 4 Dec 2005 works ok */
    if (ttnproto != NP_TCPRAW)
      ttnproto = NP_NONE;               /* No protocol selected yet. */
#endif	/* COMMENT */
    debug(F110,"tcpsocket_open namecopy",namecopy,0);

    /* Assign the socket number to ttyfd and then fill in tcp structures */
    ttyfd = atoi(&name[1]);
    debug(F111,"tcpsocket_open","ttyfd",ttyfd);

#ifndef NOTCPOPTS
#ifdef SOL_SOCKET
    setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);

#ifndef datageneral
#ifdef TCP_NODELAY
    no_delay(ttyfd,tcp_nodelay);
#endif /* TCP_NODELAY */
#ifdef SO_KEEPALIVE
    keepalive(ttyfd,tcp_keepalive);
#endif /* SO_KEEPALIVE */
#ifdef SO_LINGER
    ck_linger(ttyfd,tcp_linger, tcp_linger_tmo);
#endif /* SO_LINGER */
#ifdef SO_SNDBUF
    sendbuf(ttyfd,tcp_sendbuf);
#endif /* SO_SNDBUF */
#ifdef SO_RCVBUF
    recvbuf(ttyfd,tcp_recvbuf);
#endif /* SO_RCVBUF */
#endif /* datageneral */
#endif /* SOL_SOCKET */
#endif /* NOTCPOPTS */

#ifdef NT_TCP_OVERLAPPED
    OverlappedWriteInit();
    OverlappedReadInit();
#endif /* NT_TCP_OVERLAPPED */


    /* Get the name of the host we are connected to */

    saddrlen = sizeof(saddr);
    getpeername(ttyfd,(struct sockaddr *)&saddr,&saddrlen);

    ckstrncpy(ipaddr,(char *)inet_ntoa(saddr.sin_addr),20);

    if (tcp_rdns == SET_ON
#ifdef CK_KERBEROS
        || tcp_rdns == SET_AUTO &&
         (ck_krb5_is_installed() || ck_krb4_is_installed())
#endif /* CK_KERBEROS */
#ifndef NOHTTP
          && (tcp_http_proxy == NULL)
#endif /* NOHTTP */
#ifdef CK_SSL
          && !(ssl_only_flag || tls_only_flag)
#endif /* CK_SSL */
         ) {                            /* Reverse DNS */
        if (!quiet) {
            printf(" Reverse DNS Lookup... ");
            fflush(stdout);
        }
        host = gethostbyaddr((char *)&saddr.sin_addr,4,PF_INET);
        debug(F110,"tcpsocket_open gethostbyaddr",host ? "OK" : "FAILED",0);
        if (host) {
            host = ck_copyhostent(host);
            debug(F100,"tcpsocket_open gethostbyaddr != NULL","",0);
            if (!quiet) {
                printf("(OK)\n");
                fflush(stdout);
            }
            ckstrncpy(name, host->h_name, 80);
            ckstrncat(name, ":", 80);
            ckstrncat(name,ckuitoa(ntohs(saddr.sin_port)), 80);
            if (!quiet
#ifndef NOICP
                && !doconx
#endif /* NOICP */
                )
              printf("%s connected on port %d\n",
                   host->h_name,
                   ntohs(saddr.sin_port)
                   );
        } else if (!quiet)
          printf("Failed\n");
    } else if (!quiet)
      printf("(OK)\n");

    if (tcp_rdns != SET_ON || !host) {
        ckstrncpy(name,ipaddr,80);
        ckstrncat(name,":",80);
        ckstrncat(name,ckuitoa(ntohs(saddr.sin_port)),80);
        if (!quiet
#ifdef NOICP
            && !doconx
#endif /* NOICP */
            )
          printf("%s connected on port %d\n",ipaddr,ntohs(saddr.sin_port));
    }
    if (!quiet) fflush(stdout);
    ttnet = nett;                       /* TCP/IP (sockets) network */

#ifdef RLOGCODE
    if (ntohs(saddr.sin_port) == 513)
        ttnproto = NP_LOGIN;
    else
#endif /* RLOGCODE */
    /* Assume the service is TELNET. */
#ifdef COMMENT
      /* Jeff's code from 2005/12/30 */
      if (ttnproto != NP_TCP_RAW &&
	  ttnproto != NP_SSL_RAW &&
	  ttnproto != NP_TLS_RAW)
#else
      /* fdc's code from 2005/12/04 */
      if (ttnproto != NP_TCPRAW)
#endif	/* COMMENT */
	ttnproto = NP_TELNET;		/* Yes, set global flag. */
#ifdef CK_SECURITY
    /* Before Initialization Telnet/Rlogin Negotiations Init Kerberos */
    ck_auth_init((tcp_rdns && host && host->h_name && host->h_name[0]) ?
                host->h_name : ipaddr,
                ipaddr,
                uidbuf,
                ttyfd
                );
#endif /* CK_SECURITY */
    if (tn_ini() < 0)                   /* Start/Reset TELNET negotiations */
      if (ttchk() < 0)                  /* Did it fail due to connect loss? */
        return(-1);

    if (*lcl < 0) *lcl = 1;             /* Local mode. */

    return(0);                          /* Done. */
}
#endif /* NOTUSED */

/*  T C P S R V _ O P E N  --  Open a TCP/IP Server connection  */
/*
  Calling conventions same as ttopen(), except third argument is network
  type rather than modem type.
*/
int
tcpsrv_open(name,lcl,nett,timo) char * name; int * lcl; int nett; int timo; {
    char *p;
    int i, x;
    SOCKOPT_T on = 1;
    int ready_to_accept = 0;
    static struct servent *service, *service2, servrec;
    static struct hostent *host;
    static struct sockaddr_in saddr;
    struct sockaddr_in l_addr;
    GSOCKNAME_T l_slen;
#ifdef UCX50
    static u_int saddrlen;
#else
    static SOCKOPT_T saddrlen;
#endif /* UCX50 */

#ifdef BSDSELECT
    fd_set rfds;
    struct timeval tv;
#else
#ifdef BELLSELCT
    fd_set rfds;
#else
    fd_set rfds;
    struct timeval {
        long tv_sec;
        long tv_usec;
    } tv;
#endif /* BELLSELECT */
#endif /* BSDSELECT */
#ifdef CK_SSL
    int ssl_failed = 0;
#endif /* CK_SSL */

    debug(F101,"tcpsrv_open nett","",nett);
    *ipaddr = '\0';

    if (nett != NET_TCPB)
      return(-1);                       /* BSD socket support */

    netclos();                          /* Close any previous connection. */
    ckstrncpy(namecopy, name, NAMECPYL); /* Copy the hostname. */
    /* Don't do this. */
#ifdef COMMENT
    /* fdc */
    if (ttnproto != NP_TCPRAW)
      ttnproto = NP_NONE;               /* No protocol selected yet. */
#endif	/* COMMENT */
#ifdef COMMENT
    /* Jeff */
    if (ttnproto != NP_TCP_RAW &&
	ttnproto != NP_SSL_RAW &&
	ttnproto != NP_TLS_RAW)
      ttnproto = NP_NONE;               /* No protocol selected yet. */
#endif /* COMMENT */
    debug(F110,"tcpsrv_open namecopy",namecopy,0);

    p = namecopy;                       /* Was a service requested? */
    while (*p != '\0' && *p != ':')
      p++; /* Look for colon */
    if (*p == ':') {                    /* Have a colon */
        *p++ = '\0';                    /* Get service name or number */
    } else {                            /* Otherwise use kermit */
        p = "kermit";
    }
    debug(F110,"tcpsrv_open service requested",p,0);
    if (isdigit(*p)) {                  /* Use socket number without lookup */
        service = &servrec;
        service->s_port = htons((unsigned short)atoi(p));
    } else {                            /* Otherwise lookup the service name */
        service = getservbyname(p, "tcp");
    }
    if (!service && !strcmp("kermit",p)) { /* Use Kermit service port */
        service = &servrec;
        service->s_port = htons(1649);
    }
#ifdef RLOGCODE
    if (service && !strcmp("login",p) && service->s_port != htons(513)) {
        fprintf(stderr,
                "  Warning: login service on port %d instead of port 513\n",
                 ntohs(service->s_port));
        fprintf(stderr, "  Edit SERVICES file if RLOGIN fails to connect.\n");
        debug(F101,"tcpsrv_open login on port","",ntohs(service->s_port));
    }
#endif /* RLOGCODE */
    if (!service) {
        fprintf(stderr, "Cannot find port for service: %s\n", p);
        debug(F111,"tcpsrv_open can't get service",p,errno);
        errno = 0;                      /* rather than mislead */
        return(-1);
    }

    /* If we currently have a listen active but port has changed then close */

    debug(F101,"tcpsrv_open checking previous connection","",tcpsrfd);
    debug(F101,"tcpsrv_open previous tcpsrv_port","",tcpsrv_port);
    if (tcpsrfd != -1 &&
        tcpsrv_port != ntohs((unsigned short)service->s_port)) {
        debug(F100,"tcpsrv_open closing previous connection","",0);
#ifdef TCPIPLIB
        socket_close(tcpsrfd);
#else
        close(tcpsrfd);
#endif /* TCPIPLIB */
        tcpsrfd = -1;
    }
    debug(F100,"tcpsrv_open tcpsrfd","",tcpsrfd);
    if (tcpsrfd == -1) {

        /* Set up socket structure and get host address */

        bzero((char *)&saddr, sizeof(saddr));
        debug(F100,"tcpsrv_open bzero ok","",0);
        saddr.sin_family = AF_INET;
        if (tcp_address) {
#ifdef INADDRX
            inaddrx = inet_addr(tcp_address);
            saddr.sin_addr.s_addr = *(unsigned long *)&inaddrx;
#else
            saddr.sin_addr.s_addr = inet_addr(tcp_address);
#endif /* INADDRX */
        } else
          saddr.sin_addr.s_addr = INADDR_ANY;

        /* Get a file descriptor for the connection. */

        saddr.sin_port = service->s_port;
        ipaddr[0] = '\0';

        debug(F100,"tcpsrv_open calling socket","",0);
        if ((tcpsrfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
            perror("TCP socket error");
            debug(F101,"tcpsrv_open socket error","",errno);
            return (-1);
        }
        errno = 0;

        /* Specify the Port may be reused */

        debug(F100,"tcpsrv_open calling setsockopt","",0);
        x = setsockopt(tcpsrfd,
                       SOL_SOCKET,SO_REUSEADDR,(char *)&on,sizeof on);
        debug(F101,"tcpsrv_open setsockopt","",x);

       /* Now bind to the socket */
        printf("\nBinding socket to port %d ...\n",
               ntohs((unsigned short)service->s_port));
        if (bind(tcpsrfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
            i = errno;                  /* Save error code */
#ifdef TCPIPLIB
            socket_close(tcpsrfd);
#else /* TCPIPLIB */
            close(tcpsrfd);
#endif /* TCPIPLIB */
            tcpsrfd = -1;
            tcpsrv_port = 0;
            ttyfd = -1;
            wasclosed = 1;
            errno = i;                  /* and report this error */
            debug(F101,"tcpsrv_open bind errno","",errno);
            printf("?Unable to bind to socket (errno = %d)\n",errno);
            return(-1);
        }
        debug(F100,"tcpsrv_open bind OK","",0);
        printf("Listening ...\n");
        if (listen(tcpsrfd, 15) < 0) {
            i = errno;                  /* Save error code */
#ifdef TCPIPLIB
            socket_close(tcpsrfd);
#else /* TCPIPLIB */
            close(tcpsrfd);
#endif /* TCPIPLIB */
            tcpsrfd = -1;
            tcpsrv_port = 0;
            ttyfd = -1;
            wasclosed = 1;
            errno = i;                  /* And report this error */
            debug(F101,"tcpsrv_open listen errno","",errno);
            return(-1);
        }
        debug(F100,"tcpsrv_open listen OK","",0);
        tcpsrv_port = ntohs((unsigned short)service->s_port);
    }

#ifdef CK_SSL
    if (ck_ssleay_is_installed()) {
        if (!ssl_tn_init(SSL_SERVER)) {
            ssl_failed = 1;
            if (bio_err!=NULL) {
                BIO_printf(bio_err,"do_ssleay_init() failed\n");
                ERR_print_errors(bio_err);
            } else {
                fflush(stderr);
                fprintf(stderr,"do_ssleay_init() failed\n");
                ERR_print_errors_fp(stderr);
            }
            if (tls_only_flag || ssl_only_flag) {
#ifdef TCPIPLIB
                socket_close(ttyfd);
                socket_close(tcpsrfd);
#else /* TCPIPLIB */
                close(ttyfd);
                close(tcpsrfd);
#endif /* TCPIPLIB */
                ttyfd = -1;
                wasclosed = 1;
                tcpsrfd = -1;
                tcpsrv_port = 0;
                return(-1);
            }
            /* we will continue to accept the connection   */
            /* without SSL or TLS support unless required. */
            if ( TELOPT_DEF_S_ME_MODE(TELOPT_START_TLS) != TN_NG_MU )
                TELOPT_DEF_S_ME_MODE(TELOPT_START_TLS) = TN_NG_RF;
            if ( TELOPT_DEF_S_U_MODE(TELOPT_START_TLS) != TN_NG_MU )
                TELOPT_DEF_S_U_MODE(TELOPT_START_TLS) = TN_NG_RF;
            if ( TELOPT_DEF_C_ME_MODE(TELOPT_START_TLS) != TN_NG_MU )
                TELOPT_DEF_C_ME_MODE(TELOPT_START_TLS) = TN_NG_RF;
            if ( TELOPT_DEF_C_U_MODE(TELOPT_START_TLS) != TN_NG_MU )
                TELOPT_DEF_C_U_MODE(TELOPT_START_TLS) = TN_NG_RF;
        }
    }
#endif /* CK_SSL */

    printf("\nWaiting to Accept a TCP/IP connection on port %d ...\n",
           ntohs((unsigned short)service->s_port));
    saddrlen = sizeof(saddr);

#ifdef BSDSELECT
    tv.tv_sec  = tv.tv_usec = 0L;
    if (timo < 0)
      tv.tv_usec = (long) -timo * 10000L;
    else
      tv.tv_sec = timo;
    debug(F101,"tcpsrv_open BSDSELECT","",timo);
#else
    debug(F101,"tcpsrv_open not BSDSELECT","",timo);
#endif /* BSDSELECT */

    if (timo) {
        while (!ready_to_accept) {
#ifdef BSDSELECT
            FD_ZERO(&rfds);
            FD_SET(tcpsrfd, &rfds);
            ready_to_accept =
              ((select(FD_SETSIZE,
#ifdef HPUX
#ifdef HPUX1010
                       (fd_set *)
#else

                       (int *)
#endif /* HPUX1010 */
#else
#ifdef __DECC
#ifdef INTSELECT
                       (int *)
#else /* def INTSELECT */
                       (fd_set *)
#endif /* def INTSELECT [else] */
#endif /* __DECC */
#endif /* HPUX */
                       &rfds, NULL, NULL, &tv) > 0) &&
               FD_ISSET(tcpsrfd, &rfds));
#else /* BSDSELECT */
#ifdef IBMSELECT
#define ck_sleepint 250
            ready_to_accept =
              (select(&tcpsrfd, 1, 0, 0,
                      timo < 0 ? -timo :
                      (timo > 0 ? timo * 1000L : ck_sleepint)) == 1
               );
#else
#ifdef BELLSELECT
            FD_ZERO(rfds);
            FD_SET(tcpsrfd, rfds);
            ready_to_accept =
              ((select(128, rfds, NULL, NULL, timo < 0 ? -timo :
                      (timo > 0 ? timo * 1000L)) > 0) &&
               FD_ISSET(tcpsrfd, rfds));
#else
/* Try this - what's the worst that can happen... */

            FD_ZERO(&rfds);
            FD_SET(tcpsrfd, &rfds);
            ready_to_accept =
              ((select(FD_SETSIZE,
                       (fd_set *) &rfds, NULL, NULL, &tv) > 0) &&
               FD_ISSET(tcpsrfd, &rfds));

#endif /* BELLSELECT */
#endif /* IBMSELECT */
#endif /* BSDSELECT */
        }
    }
    if (ready_to_accept || timo == 0) {
        if ((ttyfd = accept(tcpsrfd,
                            (struct sockaddr *)&saddr,&saddrlen)) < 0) {
            i = errno;                  /* save error code */
#ifdef TCPIPLIB
            socket_close(tcpsrfd);
#else /* TCPIPLIB */
            close(tcpsrfd);
#endif /* TCPIPLIB */
            ttyfd = -1;
            wasclosed = 1;
            tcpsrfd = -1;
            tcpsrv_port = 0;
            errno = i;                  /* and report this error */
            debug(F101,"tcpsrv_open accept errno","",errno);
            return(-1);
        }
        setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);

#ifndef NOTCPOPTS
#ifndef datageneral
#ifdef SOL_SOCKET
#ifdef TCP_NODELAY
        no_delay(ttyfd,tcp_nodelay);
        debug(F101,"tcpsrv_open no_delay","",tcp_nodelay);
#endif /* TCP_NODELAY */
#ifdef SO_KEEPALIVE
        keepalive(ttyfd,tcp_keepalive);
        debug(F101,"tcpsrv_open keepalive","",tcp_keepalive);
#endif /* SO_KEEPALIVE */
#ifdef SO_LINGER
        ck_linger(ttyfd,tcp_linger, tcp_linger_tmo);
        debug(F101,"tcpsrv_open linger","",tcp_linger_tmo);
#endif /* SO_LINGER */
#ifdef SO_SNDBUF
        sendbuf(ttyfd,tcp_sendbuf);
#endif /* SO_SNDBUF */
#ifdef SO_RCVBUF
        recvbuf(ttyfd,tcp_recvbuf);
#endif /* SO_RCVBUF */
#endif /* SOL_SOCKET */
#endif /* datageneral */
#endif /* NOTCPOPTS */

        ttnet = nett;                   /* TCP/IP (sockets) network */
        tcp_incoming = 1;               /* This is an incoming connection */
        sstelnet = 1;                   /* Do server-side Telnet protocol */

        /* See if the service is TELNET. */
        x = (unsigned short)service->s_port;
        service2 = getservbyname("telnet", "tcp");
        if (service2 && x == service2->s_port) {
#ifdef COMMENT
	    /* Jeff 2005/12/30 */
	    if (ttnproto != NP_TCPRAW && /* Yes... */
		 ttnproto != NP_SSL_RAW &&
		 ttnproto != NP_TLS_RAW) /* and if raw port not requested */
#else
	    /* fdc 2005/12/04 */
            if (ttnproto != NP_TCPRAW)  /* Yes and if raw port not requested */
#endif	/*  */
              ttnproto = NP_TELNET;	/* set protocol to TELNET. */
        }
        ckstrncpy(ipaddr,(char *)inet_ntoa(saddr.sin_addr),20);
        if (tcp_rdns) {
            if (!quiet) {
                printf(" Reverse DNS Lookup... ");
                fflush(stdout);
            }
            if (host = gethostbyaddr((char *)&saddr.sin_addr,4,PF_INET)) {
                host = ck_copyhostent(host);
                debug(F100,"tcpsrv_open gethostbyaddr != NULL","",0);
                if (!quiet) {
                    printf("(OK)\n");
                    fflush(stdout);
                }
                name[0] = '*';
                ckstrncpy(&name[1],host->h_name,78);
                ckstrncat(name,":",80-strlen(name));
                ckstrncat(name,p,80-strlen(name));
                if (!quiet
#ifndef NOICP
                    && !doconx
#endif /* NOICP */
                    )
                  printf("%s connected on port %s\n",host->h_name,p);
            } else {
                if (!quiet) printf("Failed.\n");
            }
        } else if (!quiet) printf("(OK)\n");

        if (!tcp_rdns || !host) {
            ckstrncpy(name,ipaddr,80);
            ckstrncat(name,":",80);
            ckstrncat(name,ckuitoa(ntohs(saddr.sin_port)),80);
            if (!quiet
#ifndef NOICP
                && !doconx
#endif /* NOICP */
                )
              printf("%s connected on port %d\n",ipaddr,ntohs(saddr.sin_port));
        }
        if (!quiet) fflush(stdout);

#ifdef CK_SECURITY
        /* Before Initialization Telnet/Rlogin Negotiations Init Kerberos */
        ck_auth_init((tcp_rdns && host && host->h_name && host->h_name[0]) ?
                     (char *)host->h_name : ipaddr,
                     ipaddr,
                     uidbuf,
                     ttyfd
                     );
#endif /* CK_SECURITY */

#ifdef CK_SSL
        if (ck_ssleay_is_installed() && !ssl_failed) {
            if (ck_ssl_incoming(ttyfd) < 0) {
#ifdef TCPIPLIB
                    socket_close(ttyfd);
                    socket_close(tcpsrfd);
#else /* TCPIPLIB */
                    close(ttyfd);
                    close(tcpsrfd);
#endif /* TCPIPLIB */
                    ttyfd = -1;
                    wasclosed = 1;
                    tcpsrfd = -1;
                    tcpsrv_port = 0;
                    return(-1);
            }
        }
#endif /* CK_SSL */

#ifndef datageneral
        /* Find out our own IP address. */
        l_slen = sizeof(l_addr);
        bzero((char *)&l_addr, l_slen);
#ifndef EXCELAN
        if (!getsockname(ttyfd, (struct sockaddr *)&l_addr, &l_slen)) {
            char * s = (char *)inet_ntoa(l_addr.sin_addr);
            ckstrncpy(myipaddr, s,20);
            debug(F110,"getsockname",myipaddr,0);
        }
#endif /* EXCELAN */
#endif /* datageneral */

        if (tn_ini() < 0)               /* Start TELNET negotiations. */
          if (ttchk() < 0) {            /* Disconnected? */
              i = errno;                /* save error code */
#ifdef TCPIPLIB
              socket_close(tcpsrfd);
#else /* TCPIPLIB */
              close(tcpsrfd);
#endif /* TCPIPLIB */
              ttyfd = -1;
              wasclosed = 1;
              tcpsrfd = -1;
              tcpsrv_port = 0;
              errno = i;                /* and report this error */
              debug(F101,"tcpsrv_open accept errno","",errno);
              return(-1);
          }
        debug(F101,"tcpsrv_open service","",x);
        if (*lcl < 0)                   /* Set local mode. */
          *lcl = 1;

#ifdef CK_KERBEROS
#ifdef KRB5_U2U
        if ( ttnproto == NP_K5U2U ) {
            if (k5_user_to_user_server_auth() != 0) {
                i = errno;                /* save error code */
#ifdef TCPIPLIB
                socket_close(tcpsrfd);
#else /* TCPIPLIB */
                close(tcpsrfd);
#endif /* TCPIPLIB */
                ttyfd = -1;
                wasclosed = 1;
                tcpsrfd = -1;
                tcpsrv_port = 0;
                errno = i;                /* and report this error */
                debug(F101,"tcpsrv_open accept errno","",errno);
                return(-1);
            }
        }
#endif /* KRB5_U2U */
#endif /* CK_KERBEROS */
        return(0);                      /* Done. */
    } else {
        i = errno;                      /* save error code */
#ifdef TCPIPLIB
        socket_close(tcpsrfd);
#else /* TCPIPLIB */
        close(tcpsrfd);
#endif /* TCPIPLIB */
        ttyfd = -1;
        wasclosed = 1;
        tcpsrfd = -1;
        tcpsrv_port = 0;
        errno = i;                      /* and report this error */
        debug(F101,"tcpsrv_open accept errno","",errno);
        return(-1);
    }
}
#endif /* NOLISTEN */
#endif /* OS2 */
#endif /* TCPSOCKET */
#endif /* NONET */

#ifdef TCPSOCKET
char *
ckname2addr(name) char * name;
{
#ifdef HPUX5
    return("");
#else
    struct hostent *host;

    if (name == NULL || *name == '\0')
        return("");

    host = gethostbyname(name);
    if ( host ) {
        host = ck_copyhostent(host);
        return(inet_ntoa(*((struct in_addr *) host->h_addr)));
    }
    return("");
#endif /* HPUX5 */
}

char *
ckaddr2name(addr) char * addr;
{
#ifdef HPUX5
    return("");
#else
    struct hostent *host;
    struct in_addr sin_addr;

    if (addr == NULL || *addr == '\0')
        return("");

    sin_addr.s_addr = inet_addr(addr);
    host = gethostbyaddr((char *)&sin_addr,4,AF_INET);
    if (host) {
        host = ck_copyhostent(host);
        return((char *)host->h_name);
    }
    return("");
#endif /* HPUX5 */
}
#endif /* TCPSOCKET */

unsigned long peerxipaddr = 0L;

char *
ckgetpeer() {
#ifdef TCPSOCKET
    static char namebuf[256];
    static struct hostent *host;
    static struct sockaddr_in saddr;
#ifdef GPEERNAME_T
    static GPEERNAME_T saddrlen;
#else
#ifdef PTX
    static size_t saddrlen;
#else
#ifdef AIX42
    /* It's size_t in 4.2 but int in 4.1 and earlier. */
    /* Note: the 4.2 man page lies; believe socket.h. */
    static size_t saddrlen;
#else
#ifdef UNIXWARE
    static size_t saddrlen;
#else  /* UNIXWARE */
#ifdef DEC_TCPIP
/* 2010-03-08 SMS.
 * Coincidentally, the condition for integer arguments in select(),
 * which is actually "defined( _DECC_V4_SOURCE)", works for an integer
 * argument in getpeername().  Sadly, due to a lack of foresight,
 * "defined( _DECC_V4_SOURCE)" doesn't work with DEC C V4.0, so the
 * user-specified INTSELECT is used instead.  Most likely, "size_t"
 * should be used instead of "unsigned int", but I'm a coward.
 */
#ifdef INTSELECT
    static int saddrlen;
#else /* def INTSELECT */
    static unsigned int saddrlen;
#endif /* def INTSELECT [else] */
#else
#ifdef MACOSX10
    static unsigned int saddrlen;
#else
#ifdef CK_64BIT
    static socklen_t saddrlen;
#else
    static int saddrlen;
#endif	/* CK_64BIT */
#endif /* MACOSX10 */
#endif /* DEC_TCPIP */
#endif /* UNIXWARE */
#endif /* AIX42 */
#endif /* PTX */
#endif	/* GPEERNAME_T */
    saddrlen = sizeof(saddr);
    if (getpeername(ttyfd,(struct sockaddr *)&saddr,&saddrlen) < 0) {
        debug(F111,"ckgetpeer failure",ckitoa(ttyfd),errno);
        return(NULL);
    }
    host = gethostbyaddr((char *)&saddr.sin_addr,4,AF_INET);
    if (host) {
        host = ck_copyhostent(host);
        ckstrncpy(namebuf,(char *)host->h_name,80);
    } else {
        ckstrncpy(namebuf,(char *)inet_ntoa(saddr.sin_addr),80);
    }
    peerxipaddr = ntohl(saddr.sin_addr.s_addr);
    debug(F111,"ckgetpeer",namebuf,peerxipaddr);
    return(namebuf);
#else
    return(NULL);
#endif /* TCPSOCKET */
}

/* Get fully qualified IP hostname */

#ifndef NONET
char *
#ifdef CK_ANSIC
ckgetfqhostname(char * name)
#else
ckgetfqhostname(name) char * name;
#endif /* CK_ANSIC */
{
#ifdef NOCKGETFQHOST

    return(name);

#else /* If the following code dumps core, define NOCKGETFQHOST and rebuild. */

    static char namebuf[256];
    struct hostent *host=NULL;
    struct sockaddr_in r_addr;
    int i;

    debug(F110,"ckgetfqhn()",name,0);

    ckstrncpy(namebuf,name,256);
    namebuf[255] = '\0';
    i = ckindex(":",namebuf,0,0,0);
    if (i)
      namebuf[i-1] = '\0';

    bzero((char *)&r_addr, sizeof(r_addr));

    host = gethostbyname(namebuf);
    if (host) {
        host = ck_copyhostent(host);
        debug(F100,"ckgetfqhn() gethostbyname != NULL","",0);
        r_addr.sin_family = host->h_addrtype;
#ifdef HADDRLIST
#ifdef h_addr
        /* This is for trying multiple IP addresses - see <netdb.h> */
        if (!(host->h_addr_list))
          goto exit_func;
        bcopy(host->h_addr_list[0],
              (caddr_t)&r_addr.sin_addr,
              host->h_length
              );
#else
        bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
#endif /* h_addr */
#else  /* HADDRLIST */
        bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
#endif /* HADDRLIST */
#ifdef COMMENT
#ifndef EXCELAN
        debug(F111,"BCOPY","host->h_addr",host->h_addr);
#endif /* EXCELAN */
        debug(F111,"BCOPY"," (caddr_t)&r_addr.sin_addr",
              (caddr_t)&r_addr.sin_addr);
#endif	/* COMMENT */
        debug(F111,"BCOPY","host->h_length",host->h_length);

#ifdef NT
        /* Windows 95/98 requires a 1 second wait between calls to Microsoft */
        /* provided DNS functions.  Otherwise, the TTL of the DNS response */
        /* is ignored. */
        if (isWin95())
          sleep(1);
#endif /* NT */
        host = gethostbyaddr((char *)&r_addr.sin_addr,4,PF_INET);
        if (host) {
            host = ck_copyhostent(host);
            debug(F100,"ckgetfqhn() gethostbyaddr != NULL","",0);
            ckstrncpy(namebuf, host->h_name, 256);
        }
    }

#ifdef HADDRLIST
#ifdef h_addr
  exit_func:
#endif /* h_addr */
#endif /* HADDRLIST */

    if (i > 0)
      ckstrncat(namebuf,&name[i-1],256-strlen(namebuf)-strlen(&name[i-1]));
    debug(F110,"ckgetfqhn()",namebuf,0);
    return(namebuf);
#endif /* NOCKGETFQHOST */
}

VOID
#ifdef CK_ANSIC
setnproto(char * p)
#else
setnproto(p) char * p;
#endif /* CK_ANSIC */
{
    if (!isdigit(*p)) {
        if (!strcmp("kermit",p))
          ttnproto = NP_KERMIT;
        else if (!strcmp("telnet",p))
          ttnproto = NP_TELNET;
        else if (!strcmp("http",p))
          ttnproto = NP_TCPRAW;
#ifdef RLOGCODE
        else if (!strcmp("login",p))
          ttnproto = NP_RLOGIN;
#endif /* RLOGCODE */
#ifdef CK_SSL
        /* Commonly used SSL ports (might not be in services file) */
        else if (!strcmp("https",p)) {
          ttnproto = NP_SSL_RAW;
          ssl_only_flag = 1;
        } else if (!strcmp("ssl-telnet",p)) {
          ttnproto = NP_TELNET;
          ssl_only_flag = 1;
        } else if (!strcmp("telnets",p)) {
          ttnproto = NP_TELNET;
          ssl_only_flag = 1;
        }
#endif /* CK_SSL */
#ifdef CK_KERBEROS
#ifdef RLOGCODE
        else if (!strcmp("klogin",p)) {
            if (ck_krb5_is_installed())
              ttnproto = NP_K5LOGIN;
            else if (ck_krb4_is_installed())
              ttnproto = NP_K4LOGIN;
            else
              ttnproto = NP_RLOGIN;
        } else if (!strcmp("eklogin",p)) {
            if (ck_krb5_is_installed())
              ttnproto = NP_EK5LOGIN;
            else if (ck_krb4_is_installed())
              ttnproto = NP_EK4LOGIN;
            else
              ttnproto = NP_RLOGIN;
        }
#endif /* RLOGCODE */
#endif /* CK_KERBEROS */
        else
          ttnproto = NP_NONE;
    } else {
        switch (atoi(p)) {
          case 23:                      /* Telnet */
            ttnproto = NP_TELNET;
            break;
          case 513:
            ttnproto = NP_RLOGIN;
            break;
          case 1649:
            ttnproto = NP_KERMIT;
            break;
#ifdef CK_SSL
          case 443:
#ifdef COMMENT
	    /* Jeff 2005/12/30 */
            ttnproto = NP_SSL_RAW;
#else
	    /* fdc 2005/12/04 */
            ttnproto = NP_SSL;
#endif	/* COMMENT */
            ssl_only_flag = 1;
            break;
          case 151:
          case 992:
            ttnproto = NP_TELNET;
            ssl_only_flag = 1;
            break;
#endif /* CK_SSL */
#ifdef CK_KERBEROS
          case 543:
            if (ck_krb5_is_installed())
              ttnproto = NP_K5LOGIN;
            else if (ck_krb4_is_installed())
              ttnproto = NP_K4LOGIN;
            else
              ttnproto = NP_RLOGIN;
            break;
          case 2105:
            if (ck_krb5_is_installed())
              ttnproto = NP_EK5LOGIN;
            else if (ck_krb4_is_installed())
              ttnproto = NP_EK4LOGIN;
            else
              ttnproto = NP_RLOGIN;
            break;
#endif /* CK_KERBEROS */
          case 80:                      /* HTTP */
            ttnproto = NP_TCPRAW;
            break;
          default:
            ttnproto = NP_NONE;
            break;
        }
    }
}

/* ckgetservice() is used to determine the port number for a given */
/* service taking into account the use of DNS SRV records.         */

static struct servent servrec;
static struct servent *
ckgetservice(hostname, servicename, ip, iplen)
    char *hostname; char * servicename; char * ip; int iplen;
{
    struct servent * service = NULL;
#ifdef CK_DNS_SRV
    struct sockaddr * dns_addrs = NULL;
    int dns_naddrs = 0;
#endif /* CK_DNS_SRV */

    if (isdigit(*servicename)) {        /* Use socket number without lookup */
        service = &servrec;
        service->s_port = htons((unsigned short)atoi(servicename));
    } else {                            /* Otherwise lookup the service name */
#ifdef CK_DNS_SRV
        if (tcp_dns_srv && !quiet) {
            printf(" DNS SRV Lookup... ");
            fflush(stdout);
        }
        if (tcp_dns_srv &&
            locate_srv_dns(hostname,
                           servicename,
                           "tcp",
                           &dns_addrs,
                           &dns_naddrs
                           )
            ) {
            /* Use the first one.  Eventually we should cycle through all */
            /* the returned IP addresses and port numbers. */
            struct sockaddr_in *sin = NULL;
#ifdef BETADEBUG
            int i;
            printf("\r\n");
            for ( i=0;i<dns_naddrs;i++ ) {
                sin = (struct sockaddr_in *) &dns_addrs[i];
                printf("dns_addrs[%d] = %s %d\r\n", i,
                        (char *)inet_ntoa(sin->sin_addr),
                        ntohs(sin->sin_port));
            }
#endif /* BETADEBUG */
            sin = (struct sockaddr_in *) &dns_addrs[0];
            if ( ip && iplen > 0 )
                ckstrncpy(ip,(char *)inet_ntoa(sin->sin_addr),iplen);
            service = &servrec;
            service->s_port = sin->sin_port;

            free(dns_addrs);
            dns_addrs = NULL;
            dns_naddrs = 0;
        } else
#endif /* CK_DNS_SRV */
            service = getservbyname(servicename, "tcp");
    }
    if (!service) {
        if (!ckstrcmp("kermit",servicename,-1,0)) { /* Kermit service port */
            service = &servrec;
            service->s_port = htons(1649);
        } else if (!ckstrcmp("telnet",servicename,-1,0)) { /* Telnet port */
            service = &servrec;
            service->s_port = htons(23);
        } else if (!ckstrcmp("http",servicename,-1,0)) {
            service = &servrec;
            service->s_port = htons(80);
        }
#ifdef RLOGCODE
        else if (!ckstrcmp("login",servicename,-1,0)) {
            service = &servrec;
            service->s_port = htons(513);
        }
#endif /* RLOGCODE */
#ifdef CK_SSL
        /* Commonly used SSL ports (might not be in services file) */
        else if (!ckstrcmp("https",servicename,-1,0)) {
            service = &servrec;
            service->s_port = htons(443);
        } else if (!ckstrcmp("ssl-telnet",servicename,-1,0)) {
            service = &servrec;
            service->s_port = htons(151);
        } else if (!ckstrcmp("telnets",servicename,-1,0)) {
            service = &servrec;
            service->s_port = htons(992);
        }
#endif /* CK_SSL */
#ifdef CK_KERBEROS
#ifdef RLOGCODE
        else if (!ckstrcmp("klogin",servicename,-1,0)) {
            service = &servrec;
            service->s_port = htons(543);
        } else if (!ckstrcmp("eklogin",servicename,-1,0)) {
            service = &servrec;
            service->s_port = htons(2105);
        }
#endif /* RLOGCODE */
#endif /* CK_KERBEROS */
    }
    return(service);
}

/*  N E T O P E N  --  Open a network connection  */
/*
  Calling conventions same as ttopen(), except third argument is network
  type rather than modem type.  Designed to be called from within ttopen.
*/

#define XXNAMELEN 256
static char xxname[XXNAMELEN];

int
netopen(name, lcl, nett) char *name; int *lcl, nett; {
    char *p;
    int i, x, rc_inet_addr = 0, dns = 0;
#ifdef TCPSOCKET
    int isconnect = 0;
#ifdef SO_OOBINLINE
    int on = 1;
#endif /* SO_OOBINLINE */
    struct servent *service=NULL;
    struct hostent *host=NULL;
    struct sockaddr_in r_addr;
    struct sockaddr_in sin;
    struct sockaddr_in l_addr;
    GSOCKNAME_T l_slen;
#ifdef EXCELAN
    struct sockaddr_in send_socket;
#endif /* EXCELAN */

#ifdef INADDRX
/* inet_addr() is of type struct in_addr */
#ifdef datageneral
    extern struct in_addr inet_addr();
#else
#ifdef HPUX5WINTCP
    extern struct in_addr inet_addr();
#endif /* HPUX5WINTCP */
#endif /* datageneral */
    struct in_addr iax;
#else
#ifdef INADDR_NONE
    struct in_addr iax;
#else /* INADDR_NONE */
    long iax;
#endif /* INADDR_NONE */
#endif /* INADDRX */
#endif /* TCPSOCKET */

#ifdef COMMENT
/* This causes big trouble */
#ifndef INADDR_NONE
#define INADDR_NONE 0xffffffff
#endif /* INADDR_NONE */
#endif /* COMMENT */

#ifdef SUNX25                           /* Code for SunLink X.25 support */
#define X29PID 1                        /* X.29 Protocol ID */
_PROTOTYP(SIGTYP x25oobh, (int) );
    CONN_DB x25host;
#ifndef X25_WR_FACILITY
    FACILITY x25facil;
#else
    FACILITY_DB x25facil;
#endif /* X25_WR_FACILITY */
    static int needh = 1;
    PID_T pid;
    extern int linkid, lcn, x25ver;
#endif /* SUNX25 */
#ifdef ANYX25
    extern int revcall, closgr, cudata;
    extern char udata[];
#endif /* ANYX25 */

#ifdef IBMX25                           /* Variables for IBM X25 */
    extern int x25port;                 /* Logical port to use */
    extern x25addr_t local_nua;         /* Local X.25 address */
    extern x25addr_t remote_nua;        /* Remote X.25 address */
    extern char x25name[];              /* X25 device name (sx25a0) */
    extern char x25dev[];               /* X25 device file /dev/x25pkt */
    ulong bind_flags = 0;               /* Flags for binding the X25 stream */
    ulong token = 0;                    /* Temporary return code */
#endif /* IBMX25 */

    debug(F101,"netopen nett","",nett);
    *ipaddr = '\0';                     /* Initialize IP address string */

#ifdef SUNX25
    if (nett == NET_SX25) {             /* If network type is X.25 */
        netclos();                      /* Close any previous net connection */
        ttnproto = NP_NONE;             /* No protocol selected yet */

        /* Set up host structure */
        bzero((char *)&x25host,sizeof(x25host));
        if ((x25host.hostlen = pkx121(name,x25host.host)) < 0) {
            fprintf (stderr,"Invalid X.121 host address %s\n",name);
            errno = 0;
            return (-1);
        }
        x25host.datalen = X29PIDLEN;
        x25host.data[0] = X29PID;

        /* Set call user data if specified */
        if (cudata) {
            ckstrncpy((char *)x25host.data+X29PIDLEN,udata,(int)strlen(udata));
            x25host.datalen += (int)strlen(udata);
        }

        /* Open SunLink X.25 socket */
        if (!quiet && *name) {
            printf(" Trying %s... ", name);
            fflush(stdout);
        }
        if ((ttyfd = socket(AF_X25, SOCK_STREAM, 0)) < 0) {
            debug(F101,"netopen socket error","",errno);
            perror ("X.25 socket error");
            return (-1);
        }

        /* Setting X.25 out-of-band data handler */
        pid = getpid();
        if (ioctl(ttyfd,SIOCSPGRP,&pid)) {
            perror("X.25 set process group id error");
            return(-1);
        }
        (VOID) signal(SIGURG,x25oobh);

        /* Set reverse charge call and closed user group if requested */
        bzero ((char *)&x25facil,sizeof(x25facil));

#ifndef X25_WR_FACILITY
/*  New SunLink (7.0 or 8.0, not sure which)... */
        x25facil.type = T_REVERSE_CHARGE; /* Reverse Charge */
        x25facil.f_reverse_charge = revcall ? 1 : 0;
        if (ioctl(ttyfd,X25_SET_FACILITY,&x25facil) < 0) {
            perror ("Setting X.25 reverse charge");
            return (-1);
        }
        if (closgr > -1) {              /* Closed User Group (Outgoing) */
            bzero ((char *)&x25facil,sizeof(x25facil));
            x25facil.type = T_CUG;
            x25facil.f_cug_req = CUG_REQ_ACS;
            x25facil.f_cug_index = closgr;
            if (ioctl(ttyfd,X25_SET_FACILITY,&x25facil) < 0) {
                perror ("Setting X.25 closed user group");
                return (-1);
            }
        }
#else
/*  Old SunLink 6.0 (or 7.0?)... */
        if (revcall) x25facil.reverse_charge = revcall;
        if (closgr > -1) {
            x25facil.cug_req = 1;
            x25facil.cug_index = closgr;
        }
        if (ioctl(ttyfd,X25_WR_FACILITY,&x25facil) < 0) {
            perror ("Setting X.25 facilities");
            return (-1);
        }
#endif /* X25_WR_FACILITY */

        /*  Need X.25 header with bits Q and M */
        if (ioctl (ttyfd,X25_HEADER,&needh) < 0) {
            perror ("Setting X.25 header");
            return (-1);
        }

        /* Connects to remote host via SunLink X.25 */
        if (connect(ttyfd,(struct sockaddr *)&x25host,sizeof(x25host)) < 0) {
            i = errno;
            debug(F101,"netopen connect errno","",i);
            if (i) {
                perror("netopen x25 connect");
                x25diag();
            }
            (VOID) netclos();
            ttyfd = -1;
            wasclosed = 1;
            ttnproto = NP_NONE;
            errno = i;
            return (-1);
        }

        /* Get X.25 link identification used for the connection */
        if (ioctl(ttyfd,X25_GET_LINK,&linkid) < 0) {
            perror ("Getting X.25 link id");
            return (-1);
        }

        /* Get X.25 logical channel number used for the connection */
        if (ioctl(ttyfd,X25_RD_LCGN,&lcn) < 0) {
            perror ("Getting X.25 lcn");
            return (-1);
        }

        /* Get SunLink X.25 version */
        if (ioctl(ttyfd,X25_VERSION,&x25ver) < 0) {
            perror ("Getting SunLink X.25 version");
            return (-1);
        }
        ttnet = nett;                   /* Sunlink X.25 network */
        ttnproto = NP_X3;               /* PAD X.3, X.28, X.29 protocol */
        if (lcl) if (*lcl < 0) *lcl = 1; /* Local mode */
        return(0);
    } else /* Note that SUNX25 support can coexist with TCP/IP support. */
#endif /* SUNX25 */

#ifdef IBMX25
    /* riehm */
    if (nett == NET_IX25) {             /* IBM AIX X.25 */
        netclos();                      /* Close any previous net connection */
        ttnproto = NP_NONE;             /* No protocol selected yet */

        /* find out who we are - this is not so easy on AIX */
        /* riehm: need to write the code that finds this out
         * automatically, or at least allow it to be configured
         * somehow
         */
        if (!local_nua[0] && !x25local_nua(local_nua)) {
            return(-1);
        }

        /* Initialise the X25 API (once per process? once per connection?) */

        debug(F110, "Opening ", x25dev, 0 );
        /* set O_NDELAY to allow polling? */
        if ((ttyfd = open(x25dev, O_RDWR)) < 0) {
            perror ("X.25 device open error");
            debug(F101,"netopen: device open error","",errno);
            return (-1);
        }

        /* push the NPI onto the STREAM */
        if (ioctl(ttyfd,I_PUSH,"npi") < 0 ) {
            close(ttyfd);
            ttyfd = -1;
            wasclosed = 1;
            perror( "kermit: netopen(): couldn't push npi on the X25 stream" );
            debug(F101,"netopen: can't push npi on the X25 stream","",errno);
            return (-1);
        }

        /* set up server mode - bind the x25 port and wait for
         * incoming connections
         */
        if (name[0] == '*') {           /* Server */
            /* set up a server - see the warning in x25bind() */
            bind_flags |= TOKEN_REQUEST;

            /* bind kermit to the local X25 address */
            token = x25bind(ttyfd,
                            local_nua,
                            udata,
                            (int)strlen( udata ),
                            1,
                            x25port,
                            bind_flags
                            );
            if (token < 0) {
                debug(F100,"netopen: couldn't bind to local X25 address","",0);
                netclos();
                return(-1);
            }
            /* Currently not connected to a remote host */

            remote_nua[0] = '\0';

            /* store the fd so that incoming calls can have their own fd
             * This is almost support for a true server (ie: a'la ftpd)
             * but we're not quite there yet.
             * used in netclos()
             */
            x25serverfd = ttyfd;
            /*
             * wait for an incoming call
             * this should happen in the "server" command and not in
             * the "set host *" command.
             */
            if ((ttyfd = x25getcall(ttyfd)) < 0) {
                netclos();
                return(-1);
            }
        } else {                        /* Client */
            /* Bind kermit to the local X25 address */
            token = x25bind(
                            ttyfd,
                            local_nua,
                            (char *)NULL,
                            0,
                            0,
                            x25port,
                            bind_flags
                            );
            if (token < 0) {
                debug(F100,"netopen: couldn't bind to local X25 address","",0);
                netclos();
                return(-1);
            }
/* riehm: this should be done via the CONNECT command, not HOST! */
            {
                x25serverfd = 0;
                /* call the remote host */
                /* name == address of remote host as char* */
                if (x25call(ttyfd, name, udata) < 0 ) {
                    debug(F100,
                          "netopen: couldn't connect to remote X25 address",
                          "", 0);
                    netclos();
                    return(-1);
                }
                strcpy(remote_nua, name);
            }
        }
        ttnet = nett;                   /* AIX X.25 network */
        if (lcl) if (*lcl < 0) *lcl = 1; /* Local mode */
        return(0);

    } else /* Note that IBMX25 support can coexist with TCP/IP support. */
#endif /* IBMX25 */

/*   Add support for other networks here. */

      if (nett != NET_TCPB) return(-1); /* BSD socket support */

#ifdef TCPSOCKET
    netclos();                          /* Close any previous connection. */
    ckstrncpy(namecopy, name, NAMECPYL);        /* Copy the hostname. */
    debug(F110,"netopen namecopy",namecopy,0);

#ifndef NOLISTEN
    if (name[0] == '*')
      return(tcpsrv_open(name, lcl, nett, 0));
#endif /* NOLISTEN */

    p = namecopy;                       /* Was a service requested? */
    while (*p != '\0' && *p != ':') p++; /* Look for colon */
    if (*p == ':') {                    /* Have a colon */
        debug(F110,"netopen name has colon",namecopy,0);
        *p++ = '\0';                    /* Get service name or number */
#ifdef CK_URL
        /*
           Here we have to check for various popular syntaxes:
           host:port (our original syntax)
           URL such as telnet:host or telnet://host/
           Or even telnet://user:password@host:port/path/
           Or a malformed URL such as generated by Netscape 4.0 like:
           telnet:telnet or telnet::host.
        */

        /*
         * REPLACE THIS CODE WITH urlparse() but not on the day of the
         * C-Kermit 8.0 RELEASE.
         */

        if (*p == ':')                  /* a second colon */
          *p++ = '\0';                  /* get rid of that one too */
        while (*p == '/') *p++ = '\0';  /* and slashes */
        x = strlen(p);                  /* Length of remainder */
        if (p[x-1] == '/')              /* If there is a trailing slash */
          p[x-1] = '\0';                /* remove it. */
        debug(F110,"netopen namecopy after stripping",namecopy,0);
        debug(F110,"netopen p after stripping",p,0);
        service = getservbyname(namecopy,"tcp");
        if (service ||
#ifdef RLOGCODE
            !ckstrcmp("rlogin",namecopy,NAMECPYL,0) ||
#endif /* RLOGCODE */
#ifdef CK_SSL
            !ckstrcmp("telnets",namecopy,NAMECPYL,0) ||
#endif /* CK_SSL */
            !ckstrcmp("iksd",namecopy,NAMECPYL,0)
            ) {
            char temphost[256], tempservice[80], temppath[256];
            char * q = p, *r = p, *w = p;
            int uidfound=0;
            extern char pwbuf[];
            extern int pwflg, pwcrypt;

            if (ttnproto == NP_DEFAULT)
              setnproto(namecopy);

            /* Check for userid and possibly password */
            while (*p != '\0' && *p != '@')
                p++; /* look for @ */
            if (*p == '@') {
                /* found username and perhaps password */
                debug(F110,"netopen namecopy found @","",0);
                *p = '\0';
                p++;
                while (*w != '\0' && *w != ':')
                  w++;
                if (*w == ':')
                  *w++ = '\0';
                /* r now points to username, save it and the password */
                debug(F110,"netopen namecopy username",r,0);
                debug(F110,"netopen namecopy password",w,0);
                uidfound=1;
                if ( strcmp(uidbuf,r) || *w )
                    ckstrncpy(pwbuf,w,PWBUFL+1);
                ckstrncpy(uidbuf,r,UIDBUFLEN);
                pwflg = 1;
                pwcrypt = 0;
                q = p;                  /* Host after user and pwd */
            } else {
                p = q;                  /* No username or password */
            }
            /* Now we must look for the optional port. */
            debug(F110,"netopen x p",p,0);
            debug(F110,"netopen x q",q,0);

            /* Look for the port/service or a file/directory path */
            while (*p != '\0' && *p != ':' && *p != '/')
              p++;
            if (*p == ':') {
                debug(F110,"netopen found port",q,0);
                *p++ = '\0';            /* Found a port name or number */
                r = p;

                /* Look for the end of port/service or a file/directory path */
                while (*p != '\0' && *p != '/')
                    p++;
                if (*p == '/')
                    *p++ = '\0';

                debug(F110,"netopen port",r,0);
                ckstrncpy(tempservice,r,80);
                ckstrncpy(temphost,q,256);
                ckstrncpy(temppath,p,256);
                ckstrncpy(namecopy,temphost,NAMECPYL);
                debug(F110,"netopen tempservice",tempservice,0);
                debug(F110,"netopen temphost",temphost,0);
                debug(F110,"netopen temppath",temppath,0);

                /* move port/service to a buffer that won't go away */
                x = strlen(namecopy);
                p = namecopy + x + 1;
                ckstrncpy(p, tempservice, NAMECPYL - x);
            } else {
                /* Handle a path if we found one */
                if (*p == '/')
                    *p++ = '\0';
                ckstrncpy(temppath,p,256);

                /* We didn't find another port, but if q is a service */
                /* then assume that namecopy is actually a host.      */
                if (getservbyname(q,"tcp")) {
                    p = q;
                } else {
#ifdef RLOGCODE
                    /* rlogin is not a valid service */
                    if (!ckstrcmp("rlogin",namecopy,6,0)) {
                        ckstrncpy(namecopy,"login",NAMECPYL);
                    }
#endif /* RLOGCODE */
                    /* iksd is not a valid service */
                    if (!ckstrcmp("iksd",namecopy,6,0)) {
                        ckstrncpy(namecopy,"kermit",NAMECPYL);
                    }
                    /* Reconstruct namecopy */
                    ckstrncpy(tempservice,namecopy,80);
                    ckstrncpy(temphost,q,256);
                    ckstrncpy(namecopy,temphost,NAMECPYL);
                    debug(F110,"netopen tempservice",tempservice,0);
                    debug(F110,"netopen temphost",temphost,0);
                    debug(F110,"netopen temppath",temppath,0);

                    /* move port/service to a buffer that won't go away */
                    x = strlen(namecopy);
                    p = namecopy + x + 1;
                    ckstrncpy(p, tempservice, NAMECPYL - x - 1);
                }
            }
            debug(F110,"netopen URL result: host",namecopy,0);
            debug(F110,"netopen URL result: service",p,0);
            debug(F110,"netopen URL result: path",temppath,0);

#ifdef IKS_GET
            /* If we have set a path specified, we need to try to GET it */
            /* But we have another problem, we have to login first.  How */
            /* do we specify that a login must be done before the GET?   */
            /* The user's name if specified is in 'userid' and the       */
            /* password if any is in 'pwbuf'.                            */
            if ( temppath[0] ) {
                extern int action;
                extern char * cmarg;

                if ( !uidfound ) {
                    /* If no userid was specified as part of the URL but
                     * a path was specified, then we
                     * set the user name to anonymous and the password
                     * to the current userid.
                     */
                    ckstrncpy(pwbuf,uidbuf,PWBUFL);
                    ckstrncat(pwbuf,"@",PWBUFL);
                    pwflg = 1;
                    pwcrypt = 0;
                    ckstrncpy(uidbuf,"anonymous",UIDBUFLEN);
                }

                /*
                 * If a file path was specified we perform the GET
                 * operation and then terminate the connection.
                 *
                 * If a directory was given instead of a file, then
                 * we should REMOTE CD to the directory and list its
                 * contents.  But how do we tell the difference?
                 */
                makestr(&cmarg,temppath);
                action = 'r';
            }
#endif /* IKS_GET */
        }
#endif /* CK_URL */
    } else {                            /* Otherwise use telnet */
        p = "telnet";
    }
/*
  By the time we get here, namecopy[] should hold the null-terminated
  hostname or address, and p should point to the service name or number.
*/
    debug(F110,"netopen host",namecopy,0);
    debug(F110,"netopen service requested",p,0);

   /* Use the service port to set the default protocol type if necessary */
    if (ttnproto == NP_DEFAULT)
       setnproto(p);

    ckstrncpy(namecopy2,namecopy,NAMECPYL);
    service = ckgetservice(namecopy,p,namecopy,NAMECPYL);
    if (!service) {
        fprintf(stderr, "Can't find port for service %s\n", p);
#ifdef TGVORWIN
        debug(F101,"netopen can't get service","",socket_errno);
#else
        debug(F101,"netopen can't get service","",errno);
#endif /* TGVORWIN */
        errno = 0;                  /* (rather than mislead) */
        return(-1);
    } else {
        if (!ckstrcmp(namecopy,namecopy2,-1,0))
	  namecopy2[0] = '\0';
        ckstrncpy(svcbuf,ckuitoa(ntohs(service->s_port)),sizeof(svcbuf));
        debug(F110,"netopen service ok",svcbuf,0);
    }

#ifdef RLOGCODE
    if (service && !strcmp("login",p) && service->s_port != htons(513)) {
        fprintf(stderr,
                "  Warning: login service on port %d instead of port 513\n",
                 ntohs(service->s_port)
                );
        fprintf(stderr, "  Edit SERVICES file if RLOGIN fails to connect.\n");
        debug(F101,"tcpsrv_open login on port","",ntohs(service->s_port));
    }
#endif /* RLOGCODE */

#ifndef NOHTTP
   /* For HTTP connections we must preserve the original hostname and */
   /* service requested so we can include them in the Host header.    */
    ckmakmsg(http_host_port,sizeof(http_host_port),namecopy,":",
              ckitoa(ntohs(service->s_port)),NULL);

    /* 'namecopy' contains the name of the host to which we want to connect */
    /* 'svcbuf'   contains the service name                                 */
    /* 'service->s_port' contains the port number in network byte order     */

    /* If we are using an http proxy, we need to create a buffer containing */
    /*   hostname:port-number                                               */
    /* to pass to the http_connect() function.  Then we need to replace     */
    /* 'namecopy' with the name of the proxy server and the service->s_port */
    /* with the port number of the proxy (default port 80).                 */

    if ( tcp_http_proxy ) {
        ckmakmsg(proxycopy,sizeof(proxycopy),namecopy,":",
                 ckuitoa(ntohs(service->s_port)),NULL);
        ckstrncpy(namecopy,tcp_http_proxy,NAMECPYL);

        p = namecopy;                       /* Was a service requested? */
        while (*p != '\0' && *p != ':') p++; /* Look for colon */
        if (*p == ':') {                    /* Have a colon */
            debug(F110,"netopen name has colon",namecopy,0);
            *p++ = '\0';                    /* Get service name or number */
        } else {
            strcpy(++p,"http");
        }

        service = ckgetservice(namecopy,p,namecopy,NAMECPYL);
        if (!service) {
            fprintf(stderr, "Can't find port for service %s\n", p);
#ifdef TGVORWIN
            debug(F101,"netopen can't get service for proxy","",socket_errno);
#else
            debug(F101,"netopen can't get service for proxy","",errno);
#endif /* TGVORWIN */
            errno = 0;                  /* (rather than mislead) */
            return(-1);
        }
        ckstrncpy(p,ckuitoa(ntohs(service->s_port)),NAMECPYL-(p-namecopy));

    }
#endif /* NOHTTP */

    /* Set up socket structure and get host address */

    bzero((char *)&r_addr, sizeof(r_addr));
    debug(F100,"netopen bzero ok","",0);
/*
   NOTE: Originally the inet_addr() check was #ifdef NT, but is enabled for
   all as of 20 Sep 97, to allow people to "set host" to a specific numeric IP
   address without going through the multihomed host sequence and winding up
   at a different place than the one requested.
*/
#ifdef INADDR_NONE
    debug(F101,"netopen INADDR_NONE defined","",INADDR_NONE);
#else /* INADDR_NONE */
    debug(F100,"netopen INADDR_NONE not defined","",0);
#endif /* INADDR_NONE */
#ifdef INADDRX
    debug(F100,"netopen INADDRX defined","",0);
#else /* INADDRX */
    debug(F100,"netopen INADDRX not defined","",0);
#endif /* INADDRX */

#ifndef NOMHHOST
#ifdef INADDRX
    iax = inet_addr(namecopy);
    debug(F111,"netopen inet_addr",namecopy,iax.s_addr);
#else /* INADDRX */
#ifdef INADDR_NONE
    iax.s_addr = inet_addr(namecopy);
    debug(F111,"netopen inet_addr",namecopy,iax.s_addr);
#else /* INADDR_NONE */
#ifdef SOLARIS
    /* In Solaris inet_addr() is of type in_addr_t which is uint32_t */
    /* (unsigned) yet it returns -1 (signed) on failure. */
    /* It makes a difference in 64-bit builds. */
    rc_inet_addr = inet_addr(namecopy);	/* Assign return code to an int */
    iax = (unsigned) rc_inet_addr;	/* and from there to whatever.. */
#else
#ifndef datageneral
    iax = (unsigned int) inet_addr(namecopy);
#else
    iax = -1L;
#endif /* datageneral */
#endif /* SOLARIS */
    debug(F111,"netopen rc_inet_addr",namecopy,rc_inet_addr);
    debug(F111,"netopen inet_addr",namecopy,iax);
#endif /* INADDR_NONE */
#endif /* INADDRX */

    dns = 0;
    if (
/* This might give warnings on 64-bit platforms but they should be harmless */
/* because INADDR_NONE should be all 1's anyway, thus the OR part is */
/* probably superfluous -- not sure why it's even there, maybe it should be */
/* removed. */
#ifdef SOLARIS
	rc_inet_addr == -1
#else
#ifdef INADDR_NONE
        iax.s_addr == INADDR_NONE /* || iax.s_addr == (unsigned long) -1L */
#else /* INADDR_NONE */
        iax < 0
#endif /* INADDR_NONE */
#endif /* SOLARIS */
        ) {
        if (!quiet) {
            printf(" DNS Lookup... ");
            fflush(stdout);
        }
        if ((host = gethostbyname(namecopy)) != NULL) {
            debug(F110,"netopen gethostbyname != NULL",namecopy,0);
            host = ck_copyhostent(host);
            dns = 1;                    /* Remember we performed dns lookup */
            r_addr.sin_family = host->h_addrtype;
            if (tcp_rdns && host->h_name && host->h_name[0]
#ifndef NOHTTP
                 && (tcp_http_proxy == NULL)
#endif /* NOHTTP */
		) {
#ifdef COMMENT
                ckstrncpy(xxname,host->h_name,XXNAMELEN);
		debug(F110,"netopen xxname[1]",xxname,0);
                if ((XXNAMELEN - (int)strlen(name)) > ((int)strlen(svcbuf)+1)){
                    ckstrncat(xxname,":",XXNAMELEN - (int)strlen(xxname));
                    ckstrncat(xxname,svcbuf,XXNAMELEN - (int)strlen(xxname));
		    debug(F110,"netopen xxname[2]",xxname,0);
                }
		name = (char *)xxname;
#else
                ckstrncpy(name,host->h_name,80);  /* Bad Bad Bad */
                if ( (80-strlen(name)) > (strlen(svcbuf)+1) ) {
                    ckstrncat(name,":",80-strlen(name));
                    ckstrncat(name,svcbuf,80-strlen(name));
                }
#endif	/* COMMENT */
            }
	    debug(F110,"netopen name after lookup",name,0);

#ifdef HADDRLIST
#ifdef h_addr
            /* This is for trying multiple IP addresses - see <netdb.h> */
            if (!(host->h_addr_list))
              return(-1);
            bcopy(host->h_addr_list[0],
                  (caddr_t)&r_addr.sin_addr,
                  host->h_length
                  );
#else
            bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
#endif /* h_addr */
#else  /* HADDRLIST */
#ifdef HPUX6
	    r_addr.sin_addr.s_addr = (u_long)host->h_addr;
#else  /* HPUX6 */
            bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
#endif	/* HPUX6 */
#endif /* HADDRLIST */

#ifndef HPUX6
            debug(F111,"BCOPY","host->h_length",host->h_length);
#endif	/* HPUX6 */
        }
    }
#endif /* NOMHHOST */

    debug(F101,"netopen dns","",dns);

    if (!dns) {
#ifdef INADDRX
/* inet_addr() is of type struct in_addr */
        struct in_addr ina;
        unsigned long uu;
        debug(F100,"netopen gethostbyname == NULL: INADDRX","",0);
        ina = inet_addr(namecopy);
        uu = *(unsigned int *)&ina;
#else /* Not INADDRX */
/* inet_addr() is unsigned long */
        unsigned long uu;
        debug(F100,"netopen gethostbyname == NULL: Not INADDRX","",0);
        uu = inet_addr(namecopy);
#endif /* INADDRX */
        debug(F101,"netopen uu","",uu);
        if (
#ifdef INADDR_NONE
            !(uu == INADDR_NONE || uu == (unsigned int) -1L)
#else   /* INADDR_NONE */
            uu != ((unsigned long)-1)
#endif /* INADDR_NONE */
            ) {
            r_addr.sin_addr.s_addr = uu;
            r_addr.sin_family = AF_INET;
        } else {
#ifdef VMS
            fprintf(stdout, "\r\n");    /* complete any previous message */
#endif /* VMS */
            fprintf(stderr, "Can't get address for %s\n", namecopy);
#ifdef TGVORWIN
            debug(F101,"netopen can't get address","",socket_errno);
#else
            debug(F101,"netopen can't get address","",errno);
#endif /* TGVORWIN */
            errno = 0;                  /* Rather than mislead */
            return(-1);
        }
    }

    /* Get a file descriptor for the connection. */

    r_addr.sin_port = service->s_port;
    ckstrncpy(ipaddr,(char *)inet_ntoa(r_addr.sin_addr),20);
    debug(F110,"netopen trying",ipaddr,0);
    if (!quiet && *ipaddr) {
        printf(" Trying %s... ", ipaddr);
        fflush(stdout);
    }

    /* Loop to try additional IP addresses, if any. */

    do {
#ifdef EXCELAN
        send_socket.sin_family = AF_INET;
        send_socket.sin_addr.s_addr = 0;
        send_socket.sin_port = 0;
        if ((ttyfd = socket(SOCK_STREAM, (struct sockproto *)0,
                            &send_socket, SO_REUSEADDR)) < 0)
#else  /* EXCELAN */
#ifdef NT
#ifdef COMMENT_X
       /*
         Must make sure that all sockets are opened in
         Non-overlapped mode since we use the standard
         C RTL functions to read and write data.
         But it doesn't seem to work as planned.
       */
          {
              int optionValue = SO_SYNCHRONOUS_NONALERT;
              if (setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
                             (char *) &optionValue, sizeof(optionValue))
                  != NO_ERROR)
                return(-1);
          }
#endif /* COMMENT */
#endif /* NT */

        if ((ttyfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
#endif /* EXCELAN */
            {
#ifdef EXCELAN
                experror("TCP socket error");
#else
#ifdef VMS
                fprintf(stdout, "\r\n"); /* complete any previous stdout */
#endif /* VMS */
#ifdef TGVORWIN
#ifdef OLD_TWG
                errno = socket_errno;
#endif /* OLD_TWG */
                socket_perror("TCP socket error");
                debug(F101,"netopen socket error","",socket_errno);
#else
                perror("TCP socket error");
                debug(F101,"netopen socket error","",errno);
#endif /* TGVORWIN */
#endif /* EXCELAN */
                return (-1);
            }
        errno = 0;

#ifdef RLOGCODE
       /* Not part of the RLOGIN RFC, but the BSD implementation     */
       /* requires that the client port be a priviliged port (<1024) */
       /* on a Unix system this would require SuperUser permissions  */
       /* thereby saying that the root of the Unix system has given  */
       /* permission for this connection to be created               */
       if (service->s_port == htons((unsigned short)RLOGIN_PORT)) {
           static unsigned short lport = 1024;  /* max reserved port */
#ifdef OS2
           int s_errno;
#endif /* OS2 */

           lport--;                     /* Make sure we do not reuse a port */
           if (lport == 512)
             lport = 1023;

           sin.sin_family = AF_INET;
           if (tcp_address) {
#ifdef INADDRX
               inaddrx = inet_addr(tcp_address);
               sin.sin_addr.s_addr = *(unsigned long *)&inaddrx;
#else
               sin.sin_addr.s_addr = inet_addr(tcp_address);
#endif /* INADDRX */
           } else
             sin.sin_addr.s_addr = INADDR_ANY;
           while (1) {
               sin.sin_port = htons(lport);
               if (bind(ttyfd, (struct sockaddr *)&sin, sizeof(sin)) >= 0)
                 break;
#ifdef OS2
               s_errno = socket_errno;
               if (s_errno && /* OS2 bind fails with 0, if already in use */
#ifdef NT
                   s_errno != WSAEADDRINUSE
#else
                   s_errno != SOCEADDRINUSE &&
                   s_errno != (SOCEADDRINUSE - SOCBASEERR)
#endif /* NT */
                   )
#else /* OS2 */
#ifdef TGVORWIN
                 if (socket_errno != EADDRINUSE)
#else
                 if (errno != EADDRINUSE)
#endif /* TGVORWIN */
#endif /* OS2 */
                   {
#ifdef COMMENT
                       printf("\nBind failed with errno %d  for port %d.\n",
#ifdef OS2
                              s_errno
#else
#ifdef TGVORWIN
                              socket_errno
#else
                              errno
#endif /* TGVORWIN */
#endif /* OS2 */
                              , lport
                              );
#ifdef OS2
                       debug(F101,"rlogin bind failed","",s_errno);
#else
#ifdef TGVORWIN
                       debug(F101,"rlogin bind failed","",socket_errno);
#ifdef OLD_TWG
                       errno = socket_errno;
#endif /* OLD_TWG */
                       socket_perror("rlogin bind");
#else
                       debug(F101,"rlogin bind failed","",errno);
                       perror("rlogin bind");
#endif /* TGVORWIN */
#endif /* OS2 */
#else  /* COMMENT */
#ifdef OS2
                       debug(F101,"rlogin bind s_errno","",s_errno);
                       perror("rlogin bind");
#else
#ifdef VMS
                       printf("\r\n");  /* complete any previous message */
#endif /* VMS */
#ifdef TGVORWIN
                       debug(F101,"rlogin bind socket_errno","",socket_errno);
#ifdef OLD_TWG
                       errno = socket_errno;
#endif /* OLD_TWG */
                       socket_perror("rlogin bind");
#else
                       debug(F101,"rlogin bind errno","",errno);
                       perror("rlogin bind");
#endif /* TGVORWIN */
#endif /* OS2 */
                       debug(F101,"rlogin local port","",lport);
#endif /* COMMENT */
                       netclos();
                       return -1;
                   }
               lport--;
               if (lport == 512 /* lowest reserved port to use */ ) {
                   printf("\nNo reserved ports available.\n");
                   netclos();
                   return -1;
               }
           }
           debug(F101,"rlogin lport","",lport);
           ttnproto = NP_RLOGIN;
       } else
#endif /* RLOGCODE  */

       /* If a specific TCP address on the local host is desired we */
       /* must bind it to the socket.                               */
#ifndef datageneral
         if (tcp_address) {
             int s_errno;

             debug(F110,"netopen binding socket to",tcp_address,0);
             bzero((char *)&sin,sizeof(sin));
             sin.sin_family = AF_INET;
#ifdef INADDRX
             inaddrx = inet_addr(tcp_address);
             sin.sin_addr.s_addr = *(unsigned long *)&inaddrx;
#else
             sin.sin_addr.s_addr = inet_addr(tcp_address);
#endif /* INADDRX */
             sin.sin_port = 0;
             if (bind(ttyfd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
                 s_errno = socket_errno; /* Save error code */
#ifdef TCPIPLIB
                 socket_close(ttyfd);
#else /* TCPIPLIB */
                 close(ttyfd);
#endif /* TCPIPLIB */
                 ttyfd = -1;
                 wasclosed = 1;
                 errno = s_errno;       /* and report this error */
                 debug(F101,"netopen bind errno","",errno);
                 return(-1);
             }
         }
#endif /* datageneral */

/* Now connect to the socket on the other end. */

#ifdef EXCELAN
        if (connect(ttyfd, &r_addr) < 0)
#else
#ifdef NT
          WSASafeToCancel = 1;
#endif /* NT */
        if (connect(ttyfd, (struct sockaddr *)&r_addr, sizeof(r_addr)) < 0)
#endif /* EXCELAN */
          {
#ifdef NT
              WSASafeToCancel = 0;
#endif /* NT */
#ifdef OS2
              i = socket_errno;
#else /* OS2 */
#ifdef TGVORWIN
              i = socket_errno;
#else
              i = errno;                /* Save error code */
#endif /* TGVORWIN */
#endif /* OS2 */
#ifdef RLOGCODE
              if (
#ifdef OS2
                 i && /* OS2 bind fails with 0, if already in use */
#ifdef NT
                 i == WSAEADDRINUSE
#else
                 (i == SOCEADDRINUSE ||
                 i == (SOCEADDRINUSE - SOCBASEERR))
#endif /* NT */
#else /* OS2 */
#ifdef TGVORWIN
                  socket_errno == EADDRINUSE
#else
                  errno == EADDRINUSE
#endif /* TGVORWIN */
#endif /* OS2 */
                  && ttnproto == NP_RLOGIN) {
#ifdef TCPIPLIB
                   socket_close(ttyfd); /* Close it. */
#else
                   close(ttyfd);
#endif /* TCPIPLIB */
                   continue;            /* Try a different lport */
               }
#endif /* RLOGCODE */
#ifdef HADDRLIST
#ifdef h_addr
              if (host && host->h_addr_list && host->h_addr_list[1]) {
                  perror("");
                  host->h_addr_list++;
                  bcopy(host->h_addr_list[0],
                        (caddr_t)&r_addr.sin_addr,
                        host->h_length);

                  ckstrncpy(ipaddr,(char *)inet_ntoa(r_addr.sin_addr),20);
                  debug(F110,"netopen h_addr_list",ipaddr,0);
                  if (!quiet && *ipaddr) {
                      printf(" Trying %s... ", ipaddr);
                      fflush(stdout);
                  }
#ifdef TCPIPLIB
                  socket_close(ttyfd); /* Close it. */
#else
                  close(ttyfd);
#endif /* TCPIPLIB */
                  continue;
              }
#endif /* h_addr */
#endif  /* HADDRLIST */
              netclos();
              ttyfd = -1;
              wasclosed = 1;
              ttnproto = NP_NONE;
              errno = i;                /* And report this error */
#ifdef EXCELAN
              if (errno) experror("netopen connect");
#else
#ifdef TGVORWIN
              debug(F101,"netopen connect error","",socket_errno);
              /* if (errno) socket_perror("netopen connect"); */
#ifdef OLD_TWG
              errno = socket_errno;
#endif /* OLD_TWG */
              if (!quiet)
                socket_perror("netopen connect");
#else /* TGVORWIN */
              debug(F101,"netopen connect errno","",errno);
#ifdef VMS
              if (!quiet)
                perror("\r\nFailed");
#else
              if (!quiet)
                perror("Failed");
#endif /* VMS */
#ifdef DEC_TCPIP
              if (!quiet)
                perror("netopen connect");
#endif /* DEC_TCPIP */
#ifdef CMU_TCPIP
              if (!quiet)
                perror("netopen connect");
#endif /* CMU_TCPIP */
#endif /* TGVORWIN */
#endif /* EXCELAN */
              return(-1);
          }
#ifdef NT
        WSASafeToCancel = 0;
#endif /* NT */
        isconnect = 1;
    } while (!isconnect);

#ifdef NON_BLOCK_IO
    on = 1;
    x = socket_ioctl(ttyfd,FIONBIO,&on);
    debug(F101,"netopen FIONBIO","",x);
#endif /* NON_BLOCK_IO */

#ifdef NT_TCP_OVERLAPPED
    OverlappedWriteInit();
    OverlappedReadInit();
#endif /* NT_TCP_OVERLAPPED */

    ttnet = nett;                       /* TCP/IP (sockets) network */

#ifndef NOHTTP
    /* We have succeeded in connecting to the HTTP PROXY.  So now we   */
    /* need to attempt to connect through the proxy to the actual host */
    /* If that is successful, we have to pretend that we made a direct */
    /* connection to the actual host.                                  */

    if ( tcp_http_proxy ) {
#ifdef OS2
        char * agent = "Kermit 95";             /* Default user agent */
#else
        char * agent = "C-Kermit";
#endif /* OS2 */

        if (http_connect(ttyfd,
			 tcp_http_proxy_agent ? tcp_http_proxy_agent : agent,
			 NULL,
                         tcp_http_proxy_user,
                         tcp_http_proxy_pwd,
                         0,
                         proxycopy
                         ) < 0) {
            netclos();
            return(-1);
        }

        ckstrncpy(namecopy,proxycopy,NAMECPYL);
        p = namecopy;                       /* Was a service requested? */
        while (*p != '\0' && *p != ':') p++; /* Look for colon */
        *p = '\0';
    }
#endif /* NOHTTP */

    /* Jeff - Does this next block of code that set's the protocol */
    /* need to be here anymore?  5/10/2000                         */

    /* There are certain magic port numbers that when used require */
    /* the use of specific protocols.  Check this now before we    */
    /* set the SO_OOBINLINE state or we might get it wrong.        */
    x = ntohs((unsigned short)service->s_port);
    svcnum = x;
    /* See if the service is TELNET. */
    if (x == TELNET_PORT) {
        /* Yes, so if raw port not requested */
#ifdef COMMENT
	/* Jeff 2005/12/30 */
        if (ttnproto != NP_TCPRAW && ttnproto != NP_SSL_RAW && 
	    ttnproto != NP_TLS_RAW && ttnproto != NP_NONE)
#else
	/* fdc 2005/12/04 */
        if (ttnproto != NP_TCPRAW && ttnproto != NP_NONE)
#endif	/* COMMENT */
          ttnproto = NP_TELNET;         /* Select TELNET protocol. */
    }
#ifdef RLOGCODE
    else if (x == RLOGIN_PORT) {
        ttnproto = NP_RLOGIN;
    }
#ifdef CK_KERBEROS
    /* There is no good way to do this.  If the user didn't tell    */
    /* which one to use up front.  We may guess wrong if the user   */
    /* has both Kerberos versions installed and valid TGTs for each */
    else if (x == KLOGIN_PORT &&
             ttnproto != NP_K4LOGIN &&
             ttnproto != NP_K5LOGIN) {
        if (ck_krb5_is_installed() &&
            ck_krb5_is_tgt_valid())
          ttnproto = NP_K5LOGIN;
        else if (ck_krb4_is_installed() && ck_krb4_is_tgt_valid())
          ttnproto = NP_K4LOGIN;
        else
          ttnproto = NP_K4LOGIN;
    } else if (x == EKLOGIN_PORT &&
               ttnproto != NP_EK4LOGIN &&
               ttnproto != NP_EK5LOGIN) {
        if (ck_krb5_is_installed() && ck_krb5_is_tgt_valid())
          ttnproto = NP_EK5LOGIN;
        else if (ck_krb4_is_installed() && ck_krb4_is_tgt_valid())
          ttnproto = NP_EK4LOGIN;
        else
          ttnproto = NP_EK4LOGIN;
    }
#endif /* CK_KERBEROS */
#endif /* RLOGCODE */
#ifdef IKS_OPTION
    else if (x == KERMIT_PORT) {        /* IKS uses Telnet protocol */
        if (ttnproto == NP_NONE)
          ttnproto = NP_KERMIT;
    }
#endif /* IKS_OPTION */

#ifdef SO_OOBINLINE
/*
  The symbol SO_OOBINLINE is not known to Ultrix 2.0.
  It means "leave out of band data inline".  The normal value is 0x0100,
  but don't try this on systems where the symbol is undefined.
*/
/*
  Note from Jeff Altman: 12/13/95
  In implementing rlogin protocol I have come to the conclusion that it is
  a really bad idea to read out-of-band data inline.
  At least Windows and OS/2 does not handle this well.
  And if you need to know that data is out-of-band, then it becomes
  absolutely pointless.

  Therefore, at least on OS2 and Windows (NT) I have changed the value of
  on to 0, so that out-of-band data stays out-of-band.

  12/18/95
  Actually, OOB data should be read inline when possible.  Especially with
  protocols that don't care about the Urgent flag.  This is true with Telnet.
  With Rlogin, you need to be able to catch OOB data.  However, the best
  way to do this is to set a signal handler on SIGURG.  This isn't possible
  on OS/2 and Windows.  But it is in UNIX.  We will also need OOB data for
  FTP so better create a general mechanism.

  The reason for making OOB data be inline is that the standard ttinc/ttoc
  calls can be used for reading that data on UNIX systems.  If we didn't
  have the OOBINLINE option set then we would have to use recv(,MSG_OOB)
  to read it.
*/
#ifdef RLOGCODE
#ifdef TCPIPLIB
    if (ttnproto == NP_RLOGIN
#ifdef CK_KERBEROS
        || ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN
        || ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN
#endif /* CK_KERBEROS */
      )
      on = 0;
#else /* TCPIPLIB */
    if (ttnproto == NP_RLOGIN
#ifdef CK_KERBEROS
         || ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN
         || ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN
#endif /* CK_KERBEROS */
         ) {
        debug(F100,"Installing rlogoobh on SIGURG","",0);
        signal(SIGURG, rlogoobh);
        on = 0;
    } else {
        debug(F100,"Ignoring SIGURG","",0);
        signal(SIGURG, SIG_DFL);
    }
#endif /* TCPIPLIB */
#endif /* RLOGCODE */

#ifdef datageneral
    setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
#else
#ifdef BSD43
    setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
#else
#ifdef OSF1
    setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
#else
#ifdef POSIX
    setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
#else
#ifdef MOTSV88R4
    setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
#else
#ifdef SOLARIS
/*
  Maybe this applies to all SVR4 versions, but the other (else) way has been
  compiling and working fine on all the others, so best not to change it.
*/
    setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
#else
#ifdef OSK
    setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
#else
#ifdef OS2
    {
        int rc;
        rc = setsockopt(ttyfd,
                        SOL_SOCKET,
                        SO_OOBINLINE,
                        (char *) &on,
                        sizeof on
                        );
        debug(F111,"setsockopt SO_OOBINLINE",on ? "on" : "off" ,rc);
    }
#else
#ifdef VMS /* or, at least, VMS with gcc */
    setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
#else
#ifdef CLIX
    setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
#else
    setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE, &on, sizeof on);
#endif /* CLIX */
#endif /* VMS */
#endif /* OS2 */
#endif /* OSK */
#endif /* SOLARIS */
#endif /* MOTSV88R4 */
#endif /* POSIX */
#endif /* BSD43 */
#endif /* OSF1 */
#endif /* datageneral */
#endif /* SO_OOBINLINE */

#ifndef NOTCPOPTS
#ifndef datageneral
#ifdef SOL_SOCKET
#ifdef TCP_NODELAY
    no_delay(ttyfd,tcp_nodelay);
#endif /* TCP_NODELAY */
#ifdef SO_KEEPALIVE
    keepalive(ttyfd,tcp_keepalive);
#endif /* SO_KEEPALIVE */
#ifdef SO_LINGER
    ck_linger(ttyfd,tcp_linger, tcp_linger_tmo);
#endif /* SO_LINGER */
#ifdef SO_SNDBUF
    sendbuf(ttyfd,tcp_sendbuf);
#endif /* SO_SNDBUF */
#ifdef SO_RCVBUF
    recvbuf(ttyfd,tcp_recvbuf);
#endif /* SO_RCVBUF */
#endif /* SOL_SOCKET */
#endif /* datageneral */
#endif /* NOTCPOPTS */

#ifndef datageneral
    /* Find out our own IP address. */
    /* We need the l_addr structure for [E]KLOGIN. */
    l_slen = sizeof(l_addr);
    bzero((char *)&l_addr, l_slen);
#ifndef EXCELAN
    if (!getsockname(ttyfd, (struct sockaddr *)&l_addr, &l_slen)) {
        char * s = (char *)inet_ntoa(l_addr.sin_addr);
        ckstrncpy(myipaddr, s, 20);
        debug(F110,"getsockname",myipaddr,0);
    }
#endif /* EXCELAN */
#endif /* datageneral */

/*
  This is really only needed for Kerberos IV but is useful information in any
  case.  If we connect to a name that is really a pool, we need to get the
  name of the machine we are actually connecting to for K4 to authenticate
  properly.  This way we also update the names properly.

  However, it is a security hole when used with insecure DNS.

  Note: This does not work on Windows 95 or Windows NT 3.5x.  This is because
  of the Microsoft implementation of gethostbyaddr() in both Winsock 1.1
  and Winsock 2.0 on those platforms.  Their algorithm is:

  1. Check the HOSTENT cache.
  2. Check the HOSTS file at %SystemRoot%\System32\DRIVERS\ETC.
  3. Do a DNS query if the DNS server is configured for name resolution.
  4. Do an additional NetBIOS remote adapter status to an IP address for its
     NetBIOS name table. This step is specific only to the Windows NT version
     3.51 implementation.

  The problem is the use of the HOSTENT cache.  It means that gethostbyaddr()
  can not be used to resolve the real name of machine if it was originally
  accessed by an alias used to represent a cluster.
*/
     if ((tcp_rdns && dns || tcp_rdns == SET_ON
#ifdef CK_KERBEROS
         || tcp_rdns == SET_AUTO &&
          (ck_krb5_is_installed() || ck_krb4_is_installed())
#endif /* CK_KERBEROS */
         )
#ifndef NOHTTP
          && (tcp_http_proxy == NULL)
#endif /* NOHTTP */
#ifdef CK_SSL
          && !(ssl_only_flag || tls_only_flag)
#endif /* CK_SSL */
         ) {
#ifdef NT
        if (isWin95())
          sleep(1);
#endif /* NT */
        if (!quiet) {
            printf(" Reverse DNS Lookup... ");
            fflush(stdout);
        }
        if (host = gethostbyaddr((char *)&r_addr.sin_addr,4,PF_INET)) {
            char * s;
            host = ck_copyhostent(host);
            debug(F100,"netopen gethostbyname != NULL","",0);
            if (!quiet) {
                printf("(OK)\n");
                fflush(stdout);
            }
            s = host->h_name;
            if (!s) {                   /* This can happen... */
                debug(F100,"netopen host->h_name is NULL","",0);
                s = "";
            }
            /* Something is wrong with inet_ntoa() on HPUX 10.xx */
            /* The compiler says "Integral value implicitly converted to */
            /* pointer in assignment."  The prototype is right there */
            /* in <arpa/inet.h> so what's the problem? */
            /* Ditto in HP-UX 5.x, but not 8.x or 9.x... */
            if (!*s) {                  /* No name so substitute the address */
                debug(F100,"netopen host->h_name is empty","",0);
                s = inet_ntoa(r_addr.sin_addr); /* Convert address to string */
                if (!s)                 /* Trust No 1 */
                  s = "";
                if (*s) {               /* If it worked, use this string */
                    ckstrncpy(ipaddr,s,20);
                }
                s = ipaddr;             /* Otherwise stick with the IP */
                if (!*s)                /* or failing that */
                  s = namecopy;         /* the name we were called with. */
            }
            if (*s) {                   /* Copying into our argument? */
                ckstrncpy(name,s,80);   /* Bad Bad Bad */
                if ( (80-strlen(name)) > (strlen(svcbuf)+1) ) {
                    ckstrncat(name,":",80-strlen(name));
                    ckstrncat(name,svcbuf,80-strlen(name));
                }
            }
            if (!quiet && *s
#ifndef NOICP
                && !doconx
#endif /* NOICP */
                ) {
                printf(" %s connected on port %s\n",s,p);
#ifdef BETADEBUG
                /* This is simply for testing the DNS entries */
                if (host->h_aliases) {
                    char ** a = host->h_aliases;
                    while (*a) {
                        printf(" alias => %s\n",*a);
                        a++;
                    }
                }
#endif /* BETADEBUG */
            }
        } else {
            if (!quiet) printf("Failed.\n");
        }
    } else if (!quiet) printf("(OK)\n");
    if (!quiet) fflush(stdout);

    /* This should already have been done but just in case */
    ckstrncpy(ipaddr,(char *)inet_ntoa(r_addr.sin_addr),20);

#ifdef CK_SECURITY

    /* Before Initialization Telnet/Rlogin Negotiations Init Kerberos */
#ifndef NOHTTP
    if (tcp_http_proxy) {
        for (i=strlen(proxycopy); i >= 0 ; i--)
            if ( proxycopy[i] == ':' )
                proxycopy[i] = '\0';
    }
#endif /* NOHTTP */
    ck_auth_init(
#ifndef NOHTTP
                 tcp_http_proxy ? proxycopy :
#endif /* NOHTTP */
                 (tcp_rdns && host && host->h_name && host->h_name[0]) ?
                 (char *)host->h_name : (namecopy2[0] ? namecopy2 : 
                                        (namecopy[0] ? namecopy : ipaddr)),
                 ipaddr,
                 uidbuf,
                 ttyfd
                 );
#endif /* CK_SECURITY */
#ifdef CK_SSL
    if (ck_ssleay_is_installed()) {
        if (!ssl_tn_init(SSL_CLIENT)) {
            debug(F100,"netopen ssl_tn_init() failed","",0);
            if (bio_err!=NULL) {
                BIO_printf(bio_err,"ssl_tn_init() failed\n");
                ERR_print_errors(bio_err);
            } else {
                fflush(stderr);
                fprintf(stderr,"ssl_tn_init() failed\n");
                ERR_print_errors_fp(stderr);
            }
            if (tls_only_flag || ssl_only_flag) {
                debug(F100,"netopen ssl/tls required","",0);
                netclos();
                return(-1);
            }

            /* we will continue to accept the connection   */
            /* without SSL or TLS support unless required. */
            if ( TELOPT_DEF_S_ME_MODE(TELOPT_START_TLS) != TN_NG_MU )
                TELOPT_DEF_S_ME_MODE(TELOPT_START_TLS) = TN_NG_RF;
            if ( TELOPT_DEF_S_U_MODE(TELOPT_START_TLS) != TN_NG_MU )
                TELOPT_DEF_S_U_MODE(TELOPT_START_TLS) = TN_NG_RF;
            if ( TELOPT_DEF_C_ME_MODE(TELOPT_START_TLS) != TN_NG_MU )
                TELOPT_DEF_C_ME_MODE(TELOPT_START_TLS) = TN_NG_RF;
            if ( TELOPT_DEF_C_U_MODE(TELOPT_START_TLS) != TN_NG_MU )
                TELOPT_DEF_C_U_MODE(TELOPT_START_TLS) = TN_NG_RF;
        } else if ( ck_ssl_outgoing(ttyfd) < 0 ) {
            debug(F100,"ck_ssl_outgoing() failed","",0);
            netclos();
            return(-1);
        }
    }
#endif /* CK_SSL */

#ifdef RLOGCODE
    if (ttnproto == NP_RLOGIN
#ifdef CK_KERBEROS
        || ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN
        || ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN
#endif /* CK_KERBEROS */
        ) {                             /* Similar deal for rlogin */
        if (rlog_ini(((tcp_rdns && host && host->h_name && host->h_name[0]) ?
                      (CHAR *)host->h_name : (CHAR *)ipaddr),
                     service->s_port,
                     &l_addr,&r_addr
                     ) < 0) {
            debug(F100,"rlogin initialization failed","",0);
            netclos();
            return(-1);
        }
    } else
#endif /* RLOGCODE */
    if (tn_ini() < 0) {                 /* Start Telnet negotiations. */
        netclos();
        return(-1);                     /* Gone, so open failed.  */
    }
    if (ttchk() < 0) {
        netclos();
        return(-1);
    }
#ifdef CK_KERBEROS
#ifdef KRB5_U2U
   if ( ttnproto == NP_K5U2U ) {
       if (k5_user_to_user_client_auth()) {
           netclos();
           return(-1);
       }
   }
#endif /* KRB5_U2U */
#endif /* CK_KERBEROS */

    debug(F101,"netopen service","",svcnum);
    debug(F110,"netopen name",name,0);
    debug(F110,"netopen ipaddr",ipaddr,0);
    ckstrncpy(hostipaddr,ipaddr,63);

    if (lcl) if (*lcl < 0)              /* Local mode. */
      *lcl = 1;
#endif /* TCPSOCKET */
    return(0);                          /* Done. */
}

/*  N E T C L O S  --  Close current network connection.  */

#ifndef NOLOCAL
_PROTOTYP(VOID slrestor,(VOID));
#ifdef CK_SSL
int tls_norestore = 0;
#endif /* CK_SSL */
#endif /* NOLOCAL */

int
netclos() {
    static int close_in_progress = 0;
    int x = 0, y, z;
    debug(F101,"netclos","",ttyfd);

#ifdef NETLEBUF
    if (!tt_push_inited)
      le_init();
#endif /* NETLEBUF */

    if (ttyfd == -1)                    /* Was open? */
      return(0);                        /* Wasn't. */

    if (close_in_progress)
      return(0);
    close_in_progress = 1;              /* Remember */

#ifndef NOLOCAL
    /* This function call should not be here since this is a direct call */
    /* from an I/O routine to a user interface level function.  However, */
    /* the reality is that we do not have pure interfaces.  If we ever   */
    /* decide to clean this up the UI level should assign this function  */
    /* via a pointer assignment.  - Jeff 9/10/1999                       */
#ifdef CK_SSL
    if (!tls_norestore)
#endif /* CK_SSL */
      slrestor();
#endif /* NOLOCAL */
#ifdef OS2
    RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
#else /* OS2 */
    if (ttyfd > -1)                     /* Was. */
#endif /* OS2 */
      {
#ifdef VMS
	  y = 1;                          /* Turn on nonblocking reads */
	  z = socket_ioctl(ttyfd,FIONBIO,&y);
	  debug(F111,"netclos FIONBIO","on",z);
#endif /* VMS */
#ifdef TNCODE
          if (ttnproto == NP_TELNET) {
            if (!TELOPT_ME(TELOPT_LOGOUT)
#ifdef COMMENT
/* Jeff 2005/12/30 */
#ifdef CK_SSL
		 && !ssl_raw_flag && !tls_raw_flag
#endif	/* CK_SSL */
#endif	/* COMMENT */
		) {
		/* Send LOGOUT option before close */
		if (tn_sopt(DO,TELOPT_LOGOUT) >= 0) {
		    TELOPT_UNANSWERED_DO(TELOPT_LOGOUT) = 1;
		    /* It would be nice to call tn_wait but we can't */
		}
	    }
            tn_push();			/* Place any waiting data into input*/
          }
#endif /* TNCODE */
#ifdef CK_SSL
          if (ssl_active_flag) {
              if (ssl_debug_flag)
                BIO_printf(bio_err,"calling SSL_shutdown\n");
              SSL_shutdown(ssl_con);
              ssl_active_flag = 0;
          }
          if (tls_active_flag) {
              if (ssl_debug_flag)
                BIO_printf(bio_err,"calling SSL_shutdown\n");
              SSL_shutdown(tls_con);
              tls_active_flag = 0;
          }
#endif /* CK_SSL */
#ifdef VMS
          ck_cancio();                  /* Cancel any outstanding reads. */
#endif /* VMS */
#ifdef TCPIPLIB
          x = socket_close(ttyfd);      /* Close it. */
#else
#ifndef OS2
#ifdef IBMX25
        if (ttnet == NET_IX25) {
            /* riehm: should send a disc_req - but only if link is still OK */
            x = x25clear();
            close(ttyfd);
            if (x25serverfd) {
                  /* we were the passive client of a server, now we
                   * go back to being the normal client.
                   * I hope that kermit can cope with the logic that
                   * there can still be a connection after netclos
                   * has been called.
                   */
                  ttyfd = x25serverfd;
                  x25serverfd = 0;
                  /*
                   * need to close the server connection too - because
                   * all file descriptors connected to the NPI have the
                   * same status.
                   *
                   * The problem is that any waiting connections get
                   * lost, the client doesn't realise, and hangs.
                   */
                  netclos();
              }
            x25_state = X25_CLOSED;     /* riehm: dead code? */
        } else
#endif /* IBMX25 */
          x = close(ttyfd);
#endif /* OS2 */
#endif /* TCPIPLIB */
      }
    ttyfd = -1;                         /* Mark it as closed. */
    wasclosed = 1;
#ifdef OS2
    ReleaseTCPIPMutex();
#endif /* OS2 */
#ifdef TNCODE
#ifdef CK_FORWARD_X
    fwdx_close_all();                   /* Shut down any Forward X sockets */
#endif /* CK_FORWARD_X */
    tn_reset();                   /* The Reset Telnet Option table.  */
    debug(F100,"netclose setting tn_init = 0","",0);
    tn_init = 0;                        /* Remember about telnet protocol... */
    sstelnet = 0;                       /* Client-side Telnet */
#endif /* TNCODE */
    *ipaddr = '\0';                     /* Zero the IP address string */
    tcp_incoming = 0;                   /* No longer incoming */
    /* Don't reset ttnproto so that we can remember which protocol is in use */

#ifdef TCPIPLIB
/*
  Empty the internal buffers so they won't be used as invalid input on
  the next connect attempt (rlogin).
*/
    ttibp = 0;
    ttibn = 0;
#endif /* TCPIPLIB */
#ifdef CK_KERBEROS
    /* If we are automatically destroying Kerberos credentials on Close */
    /* do it now. */
#ifdef KRB4
    if (krb4_autodel == KRB_DEL_CL) {
        extern struct krb_op_data krb_op;
        krb_op.version = 4;
        krb_op.cache = NULL;
        ck_krb4_destroy(&krb_op);
    }
#endif /* KRB4 */
#ifdef KRB5
    if (krb5_autodel == KRB_DEL_CL) {
        extern struct krb_op_data krb_op;
        extern char * krb5_d_cc;
        krb_op.version = 5;
        krb_op.cache = krb5_d_cc;
        ck_krb5_destroy(&krb_op);
    }
#endif /* KRB5 */
#endif /* CK_KERBEROS */
    close_in_progress = 0;              /* Remember we are done. */
    return(x);
}

#ifdef OS2
int
os2socketerror( int s_errno ) {
#ifdef OS2ONLY
    if (s_errno > 0 && s_errno <= SOCBASEERR) {
        /* in OS/2, there is a problem with threading in that
         * the value of errno is not thread safe.  It can be
         * set to a value from a previous library call and if
         * it was not cleared it will appear here.  Only treat
         * valid socket error codes as errors in this function.
         */
        debug(F100,"os2socketerror errno.h","",0);
        socket_errno = 0;
        return(0);
    }
#endif /* OS2ONLY */

    switch (s_errno) {
      case 0:                           /* NO ERROR */
        debug(F100,"os2socketerror NOERROR","",0);
        return(0);
#ifdef NT
      case WSAECONNRESET:
#else /* NT */
      case SOCECONNRESET:
      case SOCECONNRESET - SOCBASEERR:
#endif /* NT */
        debug(F100,"os2socketerror ECONRESET","",0);
        tn_debug("ECONRESET");
        netclos();              /* *** *** */
        return(-1);             /* Connection is broken. */
#ifdef NT
      case WSAECONNABORTED:
#else /* NT */
      case SOCECONNABORTED:
      case SOCECONNABORTED - SOCBASEERR:
#endif /* NT */
        debug(F100,"os2socketerror ECONNABORTED","",0);
        tn_debug("ECONNABORTED");
        netclos();              /* *** *** */
        return(-1);             /* Connection is broken. */
#ifdef NT
      case WSAENETRESET:
#else /* NT */
      case SOCENETRESET:
      case SOCENETRESET - SOCBASEERR:
#endif /* NT */
        debug(F100,"os2socketerror ENETRESET","",0);
        tn_debug("ENETRESET");
        netclos();              /* *** *** */
        return(-1);             /* Connection is broken. */
#ifdef NT
      case WSAENOTCONN:
#else /* NT */
      case SOCENOTCONN:
      case SOCENOTCONN - SOCBASEERR:
#endif /* NT */
        debug(F100,"os2socketerror ENOTCONN","",0);
        tn_debug("ENOTCONN");
        netclos();                      /* *** *** */
        return(-1);                     /* Connection is broken. */
#ifdef NT
      case WSAESHUTDOWN:
        debug(F100,"os2socketerror ESHUTDOWN","",0);
        tn_debug("ESHUTDOWN");
        netclos();                      /* *** *** */
        return(-1);                     /* Connection is broken. */
#endif /* NT */
#ifdef NT
      case WSAEWOULDBLOCK:
#else
      case SOCEWOULDBLOCK:
      case SOCEWOULDBLOCK - SOCBASEERR:
#endif /* NT */
        debug(F100,"os2socketerror EWOULDBLOCK","",0);
        return(0);
#ifdef NT
      case ERROR_IO_INCOMPLETE:
      case ERROR_IO_PENDING:
      case ERROR_OPERATION_ABORTED:
        return(0);
#endif /* NT */
      default:
        return(-2);
    }
    return(0);
}
#endif /* OS2 */

/*  N E T T C H K  --  Check if network up, and how many bytes can be read */
/*
  Returns number of bytes waiting, or -1 if connection has been dropped.
*/
int                                     /* Check how many bytes are ready */
nettchk() {                             /* for reading from network */
#ifdef TCPIPLIB
    long count = 0;
    int x = 0, z;
    long y;
    char c;
    int rc;
#ifdef NT
    extern int ionoblock;               /* For Overlapped I/O */
#endif /* NT */

    debug(F101,"nettchk entry ttibn","",ttibn);
    debug(F101,"nettchk entry ttibp","",ttibp);

#ifdef NETLEBUF
    {
        int n = 0;
        if (ttpush >= 0)
          n++;
        n += le_inbuf();
        if (n > 0)
          return(n);
    }
#endif /* NETLEBUF */

#ifndef OS2
#ifndef BEBOX
    socket_errno = 0; /* This is a function call in NT, and BeOS */
#endif /* BEBOX */
#endif /* OS2 */

    if (ttyfd == -1) {
        debug(F100,"nettchk socket is closed","",0);
        return(-1);
    }
/*
  Note: this socket_ioctl() call does NOT return an error if the
  connection has been broken.  (At least not in MultiNet.)
*/
#ifdef COMMENT
/*  Another trick that can be tried here is something like this: */

    if (ttnet == NET_TCPB) {
        char dummy;
        x = read(ttyfd,&dummy,0);       /* Try to read nothing */
        if (x < 0) {                    /* "Connection reset by peer" */
            perror("TCP/IP");           /* or somesuch... */
            ttclos(0);                  /* Close our end too. */
            return(-1);
        }
    }
#endif /* COMMENT */


#ifdef CK_SSL
    if (ssl_active_flag) {
#ifndef IKSDONLY
#ifdef OS2
        if ( IsConnectMode() ) {
            debug(F101,"nettchk (ssl_active_flag) returns","",count);
            return(0);
        }
#endif /* OS2 */
#endif /* IKSDONLY */
        count = SSL_pending(ssl_con);
        if (count < 0) {
            debug(F111,"nettchk","SSL_pending error",count);
            netclos();
            return(-1);
        }
        if ( count > 0 )
            return(count);                  /* Don't perform a read */
    } else if (tls_active_flag) {
#ifndef IKSDONLY
#ifdef OS2
        if ( IsConnectMode() ) {
            debug(F101,"nettchk (tls_active_flag) returns","",count);
            return(0);
        }
#endif /* OS2 */
#endif /* IKSDONLY */
        count = SSL_pending(tls_con);
        if (count < 0) {
            debug(F111,"nettchk","TLS_pending error",count);
            netclos();
            return(-1);
        }
        if ( count > 0 )
            return(count);                  /* Don't perform a read */
    } else
#endif /* CK_SSL */

    if (socket_ioctl(ttyfd,FIONREAD,
#ifdef COMMENT
    /* Now we've changed the ioctl(..,..,x) prototype for DECC to (void *) */
#ifdef __DECC
    /* NOTE: "&count" might need to be "(char *)&count" in some settings. */
                     /* Cast needed for DECC 4.1 & later? */
                     /* Maybe, but __DECC_VER only exists in 5.0 and later */
                     (char *)
#endif /* __DECC */
#endif /* COMMENT */
                     &count
                     ) < 0) {
        debug(F101,"nettchk socket_ioctl error","",socket_errno);
        /* If the connection is gone, the connection is gone. */
        netclos();
#ifdef NT_TCP_OVERLAPPED
        /* Is there anything in the overlapped I/O buffers? */
        count += OverlappedDataWaiting();
#endif /* NT_TCP_OVERLAPPED */
        count += ttibn;
        return(count>0?count:-1);
    }
    debug(F101,"nettchk count","",count);
#ifdef NT_TCP_OVERLAPPED
    /* Is there anything in the overlapped I/O buffers? */
    count += OverlappedDataWaiting();
    debug(F101,"nettchk count w/overlapped","",count);
#endif /* NT_TCP_OVERLAPPED */

#ifdef OS2
#ifndef IKSDONLY
    if ( IsConnectMode() ) {
        debug(F101,"nettchk (FIONREAD) returns","",count);
        return(count);
    }
#endif /* IKSDONLY */
#endif /* OS2 */

/* For the sake of efficiency, if there is still data in the ttibuf */
/* do not go to the bother of checking to see of the connection is  */
/* still valid.  The handle is still good, so just return the count */
/* of the bytes that we already have left to process.               */
#ifdef OS2
    if ( count > 0 || ttibn > 0 ) {
        count+=ttibn;
        debug(F101,"nettchk (count+ttibn > 0) returns","",count);
        return(count);
    } else {
        RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
        if ( ttibn == 0 )
            ttibp = 0;      /* reset for next read */
    }
#else /* OS2 */
    if ( count > 0 || ttibn > 0 ) {
        debug(F101,"nettchk returns","",count+ttibn);
        return(count+ttibn);
    }
    ttibn = ttibp = 0;
#endif /* OS2 */

/*
  The following code works well in most settings, but messes things up in
  others, including CMU/Tek TCP/IP and UCX 2.0, where it somehow manages to
  make it impossible to ever make a new connection to the same host again with
  CONNECT, once it has been logged out from the first time.  Not even if you
  HANGUP first, or SET HOST<CR>, or SET LINE<CR>.  Reportedly, however, it
  does work OK in later releases of UCX.  But there is no way we can
  accommodate both old and new -- we might have static linking or dynamic
  linking, etc etc.  If we have static, I only have access to 2.0, where this
  doesn't work, etc etc blah blah.

  In the following lines, we define a symbol NOCOUNT for builds where we want
  to omit this code.  By default, it is omitted for CMU/Tek.  You can force
  omission of it for other combinations by defining NOCOUNT in CFLAGS.  You
  can force inclusion of this code, even for CMU/Tek, by including NONOCOUNT
  in CFLAGS.
*/
#ifdef NONOCOUNT
#ifdef NOCOUNT
#undef NOCOUNT
#endif /* NOCOUNT */
#else
#ifndef NOCOUNT
#ifdef CMU_TCPIP
#define NOCOUNT
#endif /* CMU_TCPIP */
#endif /* NOCOUNT */
#endif /* NONOCOUNT */


    /* From this point forward we have a possible race condition in K95
     * due to its use of multiple threads.  Therefore, we must ensure
     * that only one thread attempt to read/write from the socket at a
     * time.  Otherwise, it is possible for a buffer to be overwritten.
     */
    /* we know now that count >= 0 and that ttibn == 0 */

    if (count == 0
#ifdef RLOGCODE
#ifdef CK_KERBEROS
        && ttnproto != NP_EK4LOGIN && ttnproto != NP_EK5LOGIN
#endif /* CK_KERBEROS */
#endif /* RLOGCODE */
        ) {
        int s_errno = 0;
#ifndef NOCOUNT
/*
  Here we need to tell the difference between a 0 count on an active
  connection, and a 0 count because the remote end of the socket broke the
  connection.  There is no mechanism in TGV MultiNet (or WIN/TCP?) to query
  the status of the connection, so we have to do a read.  -1 means there was
  no data available (socket_errno == EWOULDBLOCK), 0 means the connection is
  down.  But if, by chance, we actually get a character, we have to put it
  where it won't be lost.
*/
#ifndef NON_BLOCK_IO
#ifdef OS2
#ifdef CK_SSL
        RequestSSLMutex(SEM_INDEFINITE_WAIT);
#endif /* CK_SSL */
#endif /* OS2 */
        y = 1;                          /* Turn on nonblocking reads */
        z = socket_ioctl(ttyfd,FIONBIO,&y);
        debug(F111,"nettchk FIONBIO","on",z);
#ifdef OS2
#ifdef CK_SSL
        ReleaseSSLMutex();
#endif /* CK_SSL */
#endif /* OS2 */
#endif /* NON_BLOCK_IO */
#ifdef NT_TCP_OVERLAPPED
        ionoblock = 1;                  /* For Overlapped I/O */
#endif /* NT_TCP_OVERLAPPED */
#ifdef CK_SSL
        if ( ssl_active_flag || tls_active_flag ) {
#ifdef OS2
	  ssl_read:
            x = SSL_read( ssl_active_flag?ssl_con:tls_con,
                          &ttibuf[ttibp+ttibn],
                          TTIBUFL-ttibp-ttibn );
            switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,x)) {
            case SSL_ERROR_NONE:
                debug(F111,"nettchk SSL_ERROR_NONE","x",x);
                break;
            case SSL_ERROR_WANT_WRITE:
                debug(F100,"nettchk SSL_ERROR_WANT_WRITE","",0);
                x = -1;
                break;
            case SSL_ERROR_WANT_READ:
                debug(F100,"nettchk SSL_ERROR_WANT_READ","",0);
                x = -1;
                break;
            case SSL_ERROR_SYSCALL:
                if ( x == 0 ) { /* EOF */
                    netclos();
                    rc = -1;
                    goto nettchk_return;
              } else {
#ifdef NT
                  int gle = GetLastError();
#endif /* NT */
#ifndef NON_BLOCK_IO
#ifdef OS2
#ifdef CK_SSL
		  RequestSSLMutex(SEM_INDEFINITE_WAIT);
#endif /* CK_SSL */
#endif /* OS2 */
		  y = 0;                          /* Turn off nonblocking reads */
		  z = socket_ioctl(ttyfd,FIONBIO,&y);
		  debug(F111,"nettchk FIONBIO","off",z);
#ifdef OS2
#ifdef CK_SSL
		  ReleaseSSLMutex();
#endif /* CK_SSL */
#endif /* OS2 */
#endif /* NON_BLOCK_IO */
#ifdef NT_TCP_OVERLAPPED
		  ionoblock = 0;                  /* For Overlapped I/O */
#endif /* NT_TCP_OVERLAPPED */
#ifdef NT
                  debug(F111,"nettchk SSL_ERROR_SYSCALL",
                         "GetLastError()",gle);
                  rc = os2socketerror(gle);
                  if (rc == -1)
                      rc = -2;
                  else if ( rc == -2 )
                      rc = -1;
		  goto nettchk_return;
#endif /* NT */
                  break;
              }
          case SSL_ERROR_WANT_X509_LOOKUP:
                debug(F100,"nettchk SSL_ERROR_WANT_X509_LOOKUP","",0);
                break;
            case SSL_ERROR_SSL:
                if (bio_err!=NULL) {
                    int len;
                    extern char ssl_err[];
                    BIO_printf(bio_err,"nettchk() SSL_ERROR_SSL\n");
                    ERR_print_errors(bio_err);
                    len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
                    ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
                    debug(F110,"nettchk SSL_ERROR_SSL",ssl_err,0);
                    if (ssl_debug_flag)
                        printf(ssl_err);
                } else if (ssl_debug_flag) {
                    debug(F100,"nettchk SSL_ERROR_SSL","",0);
                    fflush(stderr);
                    fprintf(stderr,"nettchk() SSL_ERROR_SSL\n");
                    ERR_print_errors_fp(stderr);
                }
#ifdef COMMENT
                netclos();
                rc = -1;
		goto nettchk_return;
#else
                x = -1;
		break;
#endif
          case SSL_ERROR_ZERO_RETURN:
                debug(F100,"nettchk SSL_ERROR_ZERO_RETURN","",0);
                netclos();
                rc = -1;
                goto nettchk_return;
            default:
                debug(F100,"nettchk SSL_ERROR_?????","",0);
                netclos();
                rc = -1;
                goto nettchk_return;
            }
#else /* OS2 */
	    /* Do not block */
	    x = -1;
#endif /* OS2 */
        } else
#endif /* CK_SSL */
        {
#ifdef OS2
        x = socket_read(ttyfd,&ttibuf[ttibp+ttibn],
                         TTIBUFL-ttibp-ttibn);  /* Returns -1 if no data */
#else /* OS2 */
        x = socket_read(ttyfd,&c,1);    /* Returns -1 if no data */
#endif /* OS2 */
        }
        s_errno = socket_errno;         /* socket_errno may be a function */
        debug(F101,"nettchk socket_read","",x);

#ifndef NON_BLOCK_IO
#ifdef OS2
#ifdef CK_SSL
        RequestSSLMutex(SEM_INDEFINITE_WAIT);
#endif /* CK_SSL */
#endif /* OS2 */
        y = 0;                          /* Turn off nonblocking reads */
        z = socket_ioctl(ttyfd,FIONBIO,&y);
        debug(F111,"nettchk FIONBIO","off",z);
#ifdef OS2
#ifdef CK_SSL
        ReleaseSSLMutex();
#endif /* CK_SSL */
#endif /* OS2 */
#endif /* NON_BLOCK_IO */
#ifdef NT_TCP_OVERLAPPED
        ionoblock = 0;                  /* For Overlapped I/O */
#endif /* NT_TCP_OVERLAPPED */

        if (x == -1) {
            debug(F101,"nettchk socket_read errno","",s_errno);
#ifdef OS2
            if (os2socketerror(s_errno) < 0) {
                rc = -1;
                goto nettchk_return;
            }
#endif /* OS2 */
        } else if (x == 0) {
            debug(F100,"nettchk connection closed","",0);
            netclos();                  /* *** *** */
            rc = -1;
            goto nettchk_return;
        }
        if (x >= 1) {                   /* Oops, actually got a byte? */
#ifdef OS2
            /* In OS/2 we read directly into ttibuf[] */
            ckhexdump("nettchk got real data",&ttibuf[ttibp+ttibn],x);
            ttibn += x;
#else /* OS2 */
#ifdef CK_SSL
	    if ( ssl_active_flag || tls_active_flag ) {
		ckhexdump("nettchk got real data",&ttibuf[ttibp+ttibn],x);
		ttibn += x;
	    } else 
#endif /* CK_SSL */
	    {
		debug(F101,"nettchk socket_read char","",c);
		debug(F101,"nettchk ttibp","",ttibp);
		debug(F101,"nettchk ttibn","",ttibn);
/*
  In the case of Overlapped I/O the character would have come from
  the beginning of the buffer, so put it back.
*/
		if (ttibp > 0) {
		    ttibp--;
		    ttibuf[ttibp] = c;
		    ttibn++;
		} else {
		    ttibuf[ttibp+ttibn] = c;
		    ttibn++;
		}
	    }
#endif /* OS2 */
        }
#else /* NOCOUNT */
        if (ttnet == NET_TCPB) {
            char dummy;
            x = read(ttyfd,&dummy,0);   /* Try to read nothing */
            if (x < 0) {                /* "Connection reset by peer" */
                perror("TCP/IP");       /* or somesuch... */
                ttclos(0);              /* Close our end too. */
                rc = -1;
                goto nettchk_return;
            }
        }
#endif /* NOCOUNT */
    }
#ifdef CK_KERBEROS
#ifdef KRB4
#ifdef RLOGCODE
    if (ttnproto == NP_EK4LOGIN)
      count += krb4_des_avail(ttyfd);
#endif /* RLOGCODE */
#endif /* KRB4 */
#ifdef KRB5
#ifdef RLOGCODE
    if (ttnproto == NP_EK5LOGIN)
      count += krb5_des_avail(ttyfd);
#endif /* RLOGCODE */
#ifdef KRB5_U2U
    if (ttnproto == NP_K5U2U)
      count += krb5_u2u_avail(ttyfd);
#endif /* KRB5_U2U */
#endif /* KRB5 */
#endif /* CK_KERBEROS */

    debug(F101,"nettchk returns","",count+ttibn);
    rc = count + ttibn;

  nettchk_return:
#ifdef OS2
    ReleaseTCPIPMutex();
#endif /* OS2 */
    return(rc);

#else /* Not TCPIPLIB */
/*
  UNIX just uses ttchk(), in which the ioctl() calls on the file descriptor
  seem to work OK.
*/
    return(ttchk());
#endif /* TCPIPLIB */
/*
  But what about X.25?
*/
}

#ifndef OS2
VOID
nettout(i) int i; {                     /* Catch the alarm interrupts */
    debug(F100,"nettout caught timeout","",0);
    ttimoff();
    cklongjmp(njbuf, -1);
}
#endif /* !OS2 */

#ifdef TCPIPLIB

VOID
#ifdef CK_ANSIC
donetinc(void * threadinfo)
#else /* CK_ANSIC */
donetinc(threadinfo) VOID * threadinfo;
#endif /* CK_ANSIC */
/* donetinc */ {
#ifdef NTSIG
    extern int TlsIndex;
    setint();
    if (threadinfo) {                   /* Thread local storage... */
        TlsSetValue(TlsIndex,threadinfo);
    }
#endif /* NTSIG */
#ifdef CK_LOGIN
#ifdef NT
#ifdef IKSD
    if (inserver)
      setntcreds();
#endif /* IKSD */
#endif /* NT */
#endif /* CK_LOGIN */
    while (1) {
        if (ttbufr() < 0)               /* Keep trying to refill it. */
          break;                        /* Till we get an error. */
        if (ttibn > 0)                  /* Or we get a character. */
          break;
    }
}
#endif /* TCPIPLIB */

VOID
#ifdef CK_ANSIC
failnetinc(void * threadinfo)
#else /* CK_ANSIC */
failnetinc(threadinfo) VOID * threadinfo;
#endif /* CK_ANSIC */
/* failnetinc */ {
    ; /* Nothing to do on an error */
}

/* N E T X I N -- Input block of characters from network */

int
netxin(n,buf) int n; CHAR * buf; {
    int len, i, j;
#ifdef TCPIPLIB
    int rc;
#endif /* TCPIPLIB */

    if (ttyfd == -1) {
        debug(F100,"netxin socket is closed","",0);
        return(-2);
    }
#ifdef CK_KERBEROS
#ifdef KRB4
#ifdef RLOGCODE
    if (ttnproto == NP_EK4LOGIN) {
        if ((len = krb4_des_read(ttyfd,buf,n)) < 0)
          return(-1);
        else
          return(len);
    }
#endif /* RLOGCODE */
#endif /* KRB4 */
#ifdef KRB5
#ifdef RLOGCODE
    if (ttnproto == NP_EK5LOGIN) {
        if ((len = krb5_des_read(ttyfd,(char *)buf,n,0)) < 0)
          return(-1);
        else
          return(len);
    }
#endif /* RLOGCODE */
#ifdef KRB5_U2U
    if (ttnproto == NP_K5U2U) {
        if ((len = krb5_u2u_read(ttyfd,(char *)buf,n)) < 0)
          return(-1);
        else
          return(len);
    }
#endif /* KRB5_U2U */
#endif /* KRB5 */
#endif /* CK_KERBEROS */

#ifdef TCPIPLIB
#ifdef OS2
    RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
#endif /* OS2 */
    if (ttibn == 0)
      if ((rc = ttbufr()) <= 0) {
#ifdef OS2
        ReleaseTCPIPMutex();
#endif /* OS2 */
        return(rc);
      }

    if (ttibn <= n) {
        len = ttibn;
        memcpy(buf,&ttibuf[ttibp],len);         /* safe */
        ttibp += len;
        ttibn = 0;
    } else {
        memcpy(buf,&ttibuf[ttibp],n);           /* safe */
        ttibp += n;
        ttibn -= n;
        len = n;
    }
#ifdef OS2
    ReleaseTCPIPMutex();
#endif /* OS2 */
#else /* TCPIPLIB */
    for (i = 0; i < n; i++) {
        if ((j = netinc(0)) < 0) {
            if (j < -1)
              return(j);
            else
              break;
        }
        buf[i] = j;
    }
    len = i;
#endif /* TCPIPLIB */

#ifdef COMMENT
#ifdef CK_ENCRYPTION
    /* This would be great if it worked.  But what if the buffer we read  */
    /* contains a telnet negotiation that changes the state of the        */
    /* encryption.  If so, we would be either decrypting unencrypted text */
    /* or not decrypting encrypted text.  So we must move this call to    */
    /* all functions that call ttxin().  In OS2 that means os2_netxin()   */
    /* where the Telnet Negotiations are handled.                         */
    if (u_encrypt)
      ck_tn_decrypt(buf,len);
#endif /* CK_ENCRYPTION */
#endif /* COMMENT */

    return(len);
}

/*  N E T I N C --  Input character from network */

#ifdef NETLEBUF
#define LEBUF
#endif /* NETLEBUF */
#ifdef TTLEBUF
#define LEBUF
#endif /* TTLEBUF */
#ifndef LEBUF
#ifdef OS2
#define LEBUF
#endif /* OS2 */
#endif /* LEBUF */

int
netinc(timo) int timo; {
#ifdef TCPIPLIB
    int x; unsigned char c;             /* The locals. */

#ifdef NETLEBUF
    if (ttpush >= 0) {
        debug(F111,"netinc","ttpush",ttpush);
        c = ttpush;
        ttpush = -1;
        return(c);
    }
    if (le_data) {
        if (le_getchar((CHAR *)&c) > 0) {
            debug(F111,"netinc le_getchar","c",c);
            return(c);
        }
    }
#endif /* NETLEBUF */

    if (ttyfd == -1) {
        debug(F100,"netinc socket is closed","",0);
        return(-2);
    }

#ifdef CK_KERBEROS
#ifdef KRB4
#ifdef RLOGCODE
    if (ttnproto == NP_EK4LOGIN) {
        if ((x = krb4_des_read(ttyfd,&c,1)) == 0)
          return(-1);
        else if (x < 0)
          return(-2);
        else
          return(c);
    }
#endif /* RLOGCODE */
#endif /* KRB4 */
#ifdef KRB5
#ifdef RLOGCODE
    if (ttnproto == NP_EK5LOGIN) {
        if ((x = krb5_des_read(ttyfd,&c,1,0)) == 0)
          return(-1);
        else if (x < 0)
          return(-2);
        else
          return(c);
    }
#endif /* RLOGCODE */
#ifdef KRB5_U2U
    if (ttnproto == NP_K5U2U) {
        if ((x = krb5_u2u_read(ttyfd,&c,1)) == 0)
          return(-1);
        else if (x < 0)
          return(-2);
        else
          return(c);
    }
#endif /* KRB5_U2U */
#endif /* KRB5 */
#endif /* CK_KERBEROS */

#ifdef OS2
    RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
#endif /* OS2 */
    if (ttibn > 0) {                    /* Something in internal buffer? */
#ifdef COMMENT
        debug(F100,"netinc char in buf","",0); /* Yes. */
#endif /* COMMENT */
        x = 0;                          /* Success. */
    } else {                            /* Else must read from network. */
        x = -1;                         /* Assume failure. */
#ifdef DEBUG
        debug(F101,"netinc goes to net, timo","",timo);
#endif /* DEBUG */
#ifdef CK_SSL
        /*
         * In the case of OpenSSL, it is possible that there is still
         * data waiting in the SSL session buffers that has not yet
         * been read by Kermit.  If this is the case we must process
         * it without calling select() because select() will not return
         * with an indication that there is data to be read from the
         * socket.  If there is no data pending in the SSL session
         * buffers then fall through to the select() code and wait for
         * some data to arrive.
         */
        if (ssl_active_flag) {
            x = SSL_pending(ssl_con);
            if (x < 0) {
                debug(F111,"netinc","SSL_pending error",x);
                netclos();
#ifdef OS2
                ReleaseTCPIPMutex();
#endif /* OS2 */
                return(-1);
            } else if ( x > 0 ) {
                if ( ttbufr() >= 0 ) {
                    x = netinc(timo);
#ifdef OS2
                    ReleaseTCPIPMutex();
#endif /* OS2 */
                    return(x);
                }
            }
            x = -1;
        } else if (tls_active_flag) {
            x = SSL_pending(tls_con);
            if (x < 0) {
                debug(F111,"netinc","TLS_pending error",x);
                netclos();
#ifdef OS2
                ReleaseTCPIPMutex();
#endif /* OS2 */
                return(-1);
            } else if ( x > 0 ) {
                if ( ttbufr() >= 0 ) {
                    x = netinc(timo);
#ifdef OS2
                    ReleaseTCPIPMutex();
#endif /* OS2 */
                    return(x);
                }
            }
            x = -1;
        }
#endif /* CK_SSL */
#ifndef LEBUF
        if (timo == 0) {                /* Untimed case. */
            while (1) {                 /* Wait forever if necessary. */
                if (ttbufr() < 0)       /* Refill buffer. */
                  break;                /* Error, fail. */
                if (ttibn > 0) {        /* Success. */
                    x = 0;
                    break;
                }
            }
        } else                          /* Timed case... */
#endif /* LEBUF */
          {
#ifdef NT_TCP_OVERLAPPED
            /* This code is for use on NT when we are using */
            /* Overlapped I/O to handle reads.  In the case */
            /* of outstanding reads select() doesn't work   */

            if (WaitForOverlappedReadData(timo)) {
                while (1) {
                    if (ttbufr() < 0)   /* Keep trying to refill it. */
                        break;          /* Till we get an error. */
                    if (ttibn > 0) {    /* Or we get a character. */
                        x = 0;
                        break;
                    }
                }
            }
#else /* NT_TCP_OVERLAPPED */
#ifdef BSDSELECT
            fd_set rfds;
            struct timeval tv;
            int timeout = timo < 0 ? -timo : 1000 * timo;
            debug(F101,"netinc BSDSELECT","",timo);

            for ( ; timeout >= 0; timeout -= (timo ? 100 : 0)) {
                int rc;
                debug(F111,"netinc","timeout",timeout);
                /* Don't move select() initialization out of the loop. */
                FD_ZERO(&rfds);
                FD_SET(ttyfd, &rfds);
                tv.tv_sec  = tv.tv_usec = 0L;
                if (timo)
                  tv.tv_usec = (long) 100000L;
                else
                  tv.tv_sec = 30;
#ifdef NT
                WSASafeToCancel = 1;
#endif /* NT */
                rc = select(FD_SETSIZE,
#ifdef __DECC
#ifdef INTSELECT
                            (int *)
#else /* def INTSELECT */
                            (fd_set *)
#endif /* def INTSELECT [else] */
#else /* def __DECC */
                            (fd_set *)
#endif /* def __DECC [else] */
                            &rfds, NULL, NULL, &tv);
                if (rc < 0) {
                    int s_errno = socket_errno;
                    debug(F111,"netinc","select",rc);
                    debug(F111,"netinc","socket_errno",s_errno);
                    if (s_errno) {
#ifdef OS2
                        ReleaseTCPIPMutex();
#endif /* OS2 */
                        return(-1);
                    }
                }
                debug(F111,"netinc","select",rc);
#ifdef NT
                WSASafeToCancel = 0;
#endif /* NT */
                if (!FD_ISSET(ttyfd, &rfds)) {
#ifdef LEBUF
                    if (le_inbuf() > 0) {
                        timeout = -1;
                        break;
                    }
#endif /* LEBUF */
                    /* If waiting forever we have no way of knowing if the */
                    /* socket closed so try writing a 0-length TCP packet  */
                    /* which should force an error if the socket is closed */
                    if (!timo) {
                        if ((rc = socket_write(ttyfd,"",0)) < 0) {
                            int s_errno = socket_errno;
                            debug(F101,"netinc socket_write error","",s_errno);
#ifdef OS2
                            if (os2socketerror(s_errno) < 0) {
                              ReleaseTCPIPMutex();
                              return(-2);
                            }
                            ReleaseTCPIPMutex();
#endif /* OS2 */
                            return(-1); /* Call it an i/o error */
                        }
                    }
                    continue;
                }
                while (1) {
                    if (ttbufr() < 0) { /* Keep trying to refill it. */
                        timeout = -1;
                        break;          /* Till we get an error. */
                    }
                    if (ttibn > 0) {    /* Or we get a character. */
                        x = 0;
                        timeout = -1;
                        break;
                    }
                }
            }
#ifdef NT
            WSASafeToCancel = 0;
#endif /* NT */
#else /* !BSDSELECT */
#ifdef IBMSELECT
/*
  Was used by OS/2, currently not used, but might come in handy some day...
  ... and it came in handy!  For our TCP/IP layer, it avoids all the fd_set
  and timeval stuff since this is the only place where it is used.
*/
            int socket = ttyfd;
            int timeout = timo < 0 ? -timo : 1000 * timo;

            debug(F101,"netinc IBMSELECT","",timo);
            for ( ; timeout >= 0; timeout -= (timo ? 100 : 0)) {
                if (select(&socket, 1, 0, 0, 100L) == 1) {
                    while (1) {
                        if (ttbufr() < 0) { /* Keep trying to refill it. */
                            timeout = -1;
                            break;      /* Till we get an error. */
                        }
                        if (ttibn > 0) { /* Or we get a character. */
                            x = 0;
                            timeout = -1;
                            break;
                        }
                    }
                }
#ifdef LEBUF
                else if (le_inbuf() > 0)  {
                    timeout = -1;
                    break;
                }
#endif /* LEBUF */
            }
#else /* !IBMSELECT */
#ifdef WINSOCK
       /* Actually, under WinSock we have a better mechanism than select() */
       /* for setting timeouts (SO_RCVTIMEO, SO_SNDTIMEO) */
            SOCKET socket = ttyfd;
            debug(F101,"netinc NTSELECT","",timo);
            if (setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timo,
                            sizeof(timo))  == NO_ERROR)
              while (1) {
                  if (ttbufr() < 0)     /* Keep trying to refill it. */
                    break;              /* Till we get an error. */
                  if (ttibn > 0) {      /* Or we get a character. */
                      x = 0;
                      break;
                  }
              }
#else /* WINSOCK */
/*
  If we can't use select(), then we use the regular alarm()/signal()
  timeout mechanism.
*/
            debug(F101,"netinc alarm","",timo);
            x = alrm_execute(ckjaddr(njbuf),timo,nettout,donetinc,failnetinc);
            ttimoff();                  /* Timer off. */
#endif /* WINSOCK */
#endif /* IBMSELECT */
#endif /* BSDSELECT */
#endif /* NT_TCP_OVERLAPPED */
        }
    }

#ifdef LEBUF
    if (le_inbuf() > 0) {               /* If data was inserted into the */
        if (le_getchar((CHAR *)&c) > 0) {/* Local Echo buffer while the   */
#ifdef OS2                               /* was taking place do not mix   */
          ReleaseTCPIPMutex();           /* the le data with the net data */
#endif /* OS2 */
          return(c);
        }
    }
#endif /* LEBUF */
    if (x < 0) {                        /* Return -1 if we failed. */
        debug(F100,"netinc timed out","",0);
#ifdef OS2
        ReleaseTCPIPMutex();
#endif /* OS2 */
        return(-1);
    } else {                            /* Otherwise */
        c = ttibuf[ttibp];              /* Return the first char in ttibuf[] */
        if (deblog) {
#ifndef COMMENT
            debug(F101,"netinc returning","",c);
#endif /* COMMENT */
            if (c == 0) {
                debug(F101,"netinc 0 ttibn","",ttibn);
                debug(F101,"netinc 0 ttibp","",ttibp);
#ifdef BETADEBUG
                {
#ifdef OS2
                    extern int tt_type_mode;
                    if ( !ISVTNT(tt_type_mode) )
#endif /* OS2 */
                    ckhexdump("netinc &ttbuf[ttibp]",&ttibuf[ttibp],ttibn);
                }
#endif /* BETADEBUG */
            }
        }
        ttibp++;
        ttibn--;
#ifdef OS2
        ReleaseTCPIPMutex();
#endif /* OS2 */
#ifdef CK_ENCRYPTION
        if (TELOPT_U(TELOPT_ENCRYPTION))
          ck_tn_decrypt(&c,1);
#endif /* CK_ENCRYPTION */
        return(c);
    }
#else /* Not using TCPIPLIB */
    return(-1);
#endif /* TCPIPLIB */
}

/*  N E T T O L  --  Output a string of bytes to the network  */
/*
  Call with s = pointer to string, n = length.
  Returns number of bytes actually written on success, or
  -1 on i/o error, -2 if called improperly.
*/

int
nettol(s,n) CHAR *s; int n; {
#ifdef TCPIPLIB
    int count = 0;
    int len = n;
    int try = 0;

    if (ttyfd == -1) {
        debug(F100,"nettol socket is closed","",0);
        return -1;
    }
    debug(F101,"nettol TCPIPLIB ttnet","",ttnet);
#ifdef COMMENT
    ckhexdump("nettol",s,n);
#endif /* COMMENT */

#ifdef CK_KERBEROS
#ifdef KRB4
#ifdef RLOGCODE
    if (ttnproto == NP_EK4LOGIN) {
        return(krb4_des_write(ttyfd,s,n));
    }
#endif /* RLOGCODE */
#endif /* KRB4 */
#ifdef KRB5
#ifdef RLOGCODE
    if (ttnproto == NP_EK5LOGIN) {
        return(krb5_des_write(ttyfd,s,n,0));
    }
#endif /* RLOGCODE */
#ifdef KRB5_U2U
    if (ttnproto == NP_K5U2U) {
        return(krb5_u2u_write(ttyfd,s,n));
    }
#endif /* KRB5_U2U */
#endif /* KRB5 */
#endif /* CK_KERBEROS */

#ifdef CK_ENCRYPTION
    if (TELOPT_ME(TELOPT_ENCRYPTION))
      ck_tn_encrypt(s,n);
#endif /* CK_ENCRYPTION */

#ifdef CK_SSL
    if (ssl_active_flag || tls_active_flag) {
        int error, r;
        /* Write using SSL */
      ssl_retry:
        if (ssl_active_flag)
          r = SSL_write(ssl_con, s, len /* >1024?1024:len */);
        else
          r = SSL_write(tls_con, s, len /* >1024?1024:len */);
        switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,r)) {
          case SSL_ERROR_NONE:
            debug(F111,"nettol","SSL_write",r);
            if ( r == len )
                return(n);
             s += r;
             len -= r;
             goto ssl_retry;
          case SSL_ERROR_WANT_WRITE:
            debug(F100,"nettol SSL_ERROR_WANT_WRITE","",0);
            return(-1);
          case SSL_ERROR_WANT_READ:
            debug(F100,"nettol SSL_ERROR_WANT_READ","",0);
            return(-1);
          case SSL_ERROR_SYSCALL:
              if ( r == 0 ) { /* EOF */
                  netclos();
                  return(-2);
              } else {
                  int rc = -1;
#ifdef NT
                  int gle = GetLastError();
                  debug(F111,"nettol SSL_ERROR_SYSCALL",
                         "GetLastError()",gle);
                  rc = os2socketerror(gle);
                  if (rc == -1)
                      rc = -2;
                  else if ( rc == -2 )
                      rc = -1;
#endif /* NT */
                  return(rc);
              }
          case SSL_ERROR_WANT_X509_LOOKUP:
            debug(F100,"nettol SSL_ERROR_WANT_X509_LOOKUP","",0);
            netclos();
            return(-2);
          case SSL_ERROR_SSL:
            debug(F100,"nettol SSL_ERROR_SSL","",0);
              if (bio_err!=NULL) {
                  int len;
                  extern char ssl_err[];
                  BIO_printf(bio_err,"nettol() SSL_ERROR_SSL\n");
                  ERR_print_errors(bio_err);
                  len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
                  ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
                  debug(F110,"nettol SSL_ERROR_SSL",ssl_err,0);
                  if (ssl_debug_flag)
                      printf(ssl_err);
              } else if (ssl_debug_flag) {
                  debug(F100,"nettol SSL_ERROR_SSL","",0);
                  fflush(stderr);
                  fprintf(stderr,"nettol() SSL_ERROR_SSL\n");
                  ERR_print_errors_fp(stderr);
              }
#ifdef COMMENT
              netclos();
              return(-2);
#else
              return(-1);
#endif
          case SSL_ERROR_ZERO_RETURN:
            debug(F100,"nettol SSL_ERROR_ZERO_RETURN","",0);
            netclos();
            return(-2);
          default:
            debug(F100,"nettol SSL_ERROR_?????","",0);
            netclos();
            return(-2);
        }
    }
#endif /* CK_SSL */

  nettol_retry:
    try++;                              /* Increase the try counter */

    if (ttnet == NET_TCPB) {
#ifdef BSDSELECT
        fd_set wfds;
        struct timeval tv;

        debug(F101,"nettol BSDSELECT","",0);
        tv.tv_usec = 0L;
        tv.tv_sec=30;
#ifdef NT
        WSASafeToCancel = 1;
#endif /* NT */
#ifdef STREAMING
      do_select:
#endif /* STREAMING */
        FD_ZERO(&wfds);
        FD_SET(ttyfd, &wfds);
        if (select(FD_SETSIZE, NULL,
#ifdef __DECC
#ifndef __DECC_VER
                    (int *)
#endif /* __DECC_VER */
#endif /* __DECC */
                   &wfds, NULL, &tv) < 0) {
            int s_errno = socket_errno;
            debug(F101,"nettol select failed","",s_errno);
#ifdef BETADEBUG
            printf("nettol select failed: %d\n", s_errno);
#endif /* BETADEBUG */
#ifdef NT
            WSASafeToCancel = 0;
            if (!win95selectbug)
#endif /* NT */
              return(-1);
        }
        if (!FD_ISSET(ttyfd, &wfds)) {
#ifdef STREAMING
            if (streaming)
              goto do_select;
#endif /* STREAMING */
            debug(F111,"nettol","!FD_ISSET",ttyfd);
#ifdef NT
            WSASafeToCancel = 0;
            if (!win95selectbug)
#endif /* NT */
              return(-1);
        }
#ifdef NT
        WSASafeToCancel = 0;
#endif /* NT */
#else /* BSDSELECT */
#ifdef IBMSELECT
        {
            int tries = 0;
            debug(F101,"nettol IBMSELECT","",0);
            while (select(&ttyfd, 0, 1, 0, 1000) != 1) {
                int count;
                if (tries++ >= 60) {
                    /* if after 60 seconds we can't get permission to write */
                    debug(F101,"nettol select failed","",socket_errno);
                    return(-1);
                }
                if ((count = nettchk()) < 0) {
                    debug(F111,"nettol","nettchk()",count);
                    return(count);
                }
            }
        }
#endif /* IBMSELECT */
#endif /* BSDSELECT */
        if ((count = socket_write(ttyfd,s,n)) < 0) {
            int s_errno = socket_errno; /* maybe a function */
            debug(F101,"nettol socket_write error","",s_errno);
#ifdef OS2
            if (os2socketerror(s_errno) < 0)
              return(-2);
#endif /* OS2 */
            return(-1);                 /* Call it an i/o error */
        }
        if (count < n) {
            debug(F111,"nettol socket_write",s,count);
            if (try > 25) {
                /* don't try more than 25 times */
                debug(F100,"nettol tried more than 25 times","",0);
                return(-1);
            }
            if (count > 0) {
                s += count;
                n -= count;
            }
            debug(F111,"nettol retry",s,n);
            goto nettol_retry;
        } else {
            debug(F111,"nettol socket_write",s,count);
            return(len); /* success - return total length */
        }
    } else
      return(-2);
#else
    debug(F100,"nettol TCPIPLIB not defined","",0);
    return(-2);
#endif /* TCPIPLIB */
}

/*  N E T T O C  --   Output character to network */
/*
  Call with character to be transmitted.
  Returns 0 if transmission was successful, or
  -1 upon i/o error, or -2 if called improperly.
*/
int
#ifdef CK_ANSIC
nettoc(CHAR c)
#else
nettoc(c) CHAR c;
#endif /* CK_ANSIC */
/* nettoc */ {
#ifdef UNIX
    return(ttoc(c));
#else
#ifdef TCPIPLIB
    unsigned char cc;
    if (ttyfd == -1) {
        debug(F100,"nettoc socket is closed","",0);
        return -1;
    }
    cc = c;
    debug(F101,"nettoc cc","",cc);

#ifdef CK_KERBEROS
#ifdef KRB4
#ifdef RLOGCODE
    if (ttnproto == NP_EK4LOGIN) {
        return(krb4_des_write(ttyfd,&cc,1)==1?0:-1);
    }
#endif /* RLOGCODE */
#endif /* KRB4 */
#ifdef KRB5
#ifdef RLOGCODE
    if (ttnproto == NP_EK5LOGIN) {
        return(krb5_des_write(ttyfd,&cc,1,0)==1?0:-1);
    }
#endif /* RLOGCODE */
#ifdef KRB5_U2U
    if (ttnproto == NP_K5U2U) {
        return(krb5_u2u_write(ttyfd,&cc,1)==1?0:-1);
    }
#endif /* KRB5_U2U */
#endif /* KRB5 */
#endif /* CK_KERBEROS */

#ifdef CK_ENCRYPTION
        if ( TELOPT_ME(TELOPT_ENCRYPTION) )
            ck_tn_encrypt(&cc,1);
#endif /* CK_ENCRYPTION */
#ifdef CK_SSL
    if (ssl_active_flag || tls_active_flag) {
        int len, error;
        /* Write using SSL */
      ssl_retry:
        if (ssl_active_flag)
          len = SSL_write(ssl_con, &cc, 1);
        else
          len = SSL_write(tls_con, &cc, 1);
        switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,len)) {
          case SSL_ERROR_NONE:
            debug(F111,"nettoc","SSL_write",len);
            return(len == 1 ? 0 : -1);
          case SSL_ERROR_WANT_WRITE:
  	  case SSL_ERROR_WANT_READ:
            return(-1);
          case SSL_ERROR_SYSCALL:
              if ( len == 0 ) { /* EOF */
                  netclos();
                  return(-2);
              } else {
                  int rc = -1;
#ifdef NT
                  int gle = GetLastError();
                  debug(F111,"nettoc SSL_ERROR_SYSCALL",
                         "GetLastError()",gle);
                  rc = os2socketerror(gle);
                  if (rc == -1)
                      rc = -2;
                  else if ( rc == -2 )
                      rc = -1;
#endif /* NT */
                  return(rc);
              }
        case SSL_ERROR_SSL:
              if (bio_err!=NULL) {
                  int len;
                  extern char ssl_err[];
                  BIO_printf(bio_err,"nettoc() SSL_ERROR_SSL\n");
                  ERR_print_errors(bio_err);
                  len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
                  ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
                  debug(F110,"nettoc SSL_ERROR_SSL",ssl_err,0);
                  if (ssl_debug_flag)
                      printf(ssl_err);
              } else if (ssl_debug_flag) {
                  debug(F100,"nettoc SSL_ERROR_SSL","",0);
                  fflush(stderr);
                  fprintf(stderr,"nettoc() SSL_ERROR_SSL\n");
                  ERR_print_errors_fp(stderr);
              }
              return(-1);
              break;
          case SSL_ERROR_WANT_X509_LOOKUP:
          case SSL_ERROR_ZERO_RETURN:
          default:
            netclos();
            return(-2);
        }
    }
#endif /* CK_SSL */
    if (ttnet == NET_TCPB) {
#ifdef BSDSELECT
        fd_set wfds;
        struct timeval tv;

        debug(F101,"nettoc BSDSELECT","",0);
        tv.tv_usec = 0L;
        tv.tv_sec = 30;

#ifdef STREAMING
      do_select:
#endif /* STREAMING */

        FD_ZERO(&wfds);
        FD_SET(ttyfd, &wfds);
        if (select(FD_SETSIZE, NULL,
#ifdef __DECC
#ifndef __DECC_VER
                   (int *)
#endif /* __DECC_VER */
#endif /* __DECC */
                   &wfds, NULL, &tv) < 0) {
            int s_errno = socket_errno;
            debug(F101,"nettoc select failed","",s_errno);
#ifdef BETADEBUG
            printf("nettoc select failed: %d\n", s_errno);
#endif /* BETADEBUG */
#ifdef NT
            WSASafeToCancel = 0;
            if (!win95selectbug)
#endif /* NT */
              return(-1);
        }
        if (!FD_ISSET(ttyfd, &wfds)) {
#ifdef STREAMING
            if (streaming)
              goto do_select;
#endif /* STREAMING */
            debug(F111,"nettoc","!FD_ISSET",ttyfd);
#ifdef NT
            WSASafeToCancel = 0;
            if (!win95selectbug)
#endif /* NT */
              return(-1);
        }
#ifdef NT
        WSASafeToCancel = 0;
#endif /* NT */
#else /* BSDSELECT */
#ifdef IBMSELECT
        {
            int tries = 0;
            while (select(&ttyfd, 0, 1, 0, 1000) != 1) {
                int count;
                if (tries++ >= 60) {
                    /* if after 60 seconds we can't get permission to write */
                    debug(F101,"nettoc select failed","",socket_errno);
                    return(-1);
                }
                if ((count = nettchk()) < 0) {
                    debug(F111,"nettoc","nettchk()",count);
                    return(count);
                }
            }
        }
#endif /* IBMSELECT */
#endif /* BSDSELECT */
        if (socket_write(ttyfd,&cc,1) < 1) {
            int s_errno = socket_errno;         /* maybe a function */
            debug(F101,"nettoc socket_write error","",s_errno);
#ifdef OS2
            if (os2socketerror(s_errno) < 0)
              return(-2);
#endif /* OS2 */
            return(-1);
        }
        debug(F101,"nettoc socket_write","", cc);
        return(0);
    } else return(-2);
#else
    return(-2);
#endif /* TCPIPLIB */
#endif /* UNIX */
}

/*  N E T F L U I  --  Flush network input buffer  */

#ifdef TNCODE
static int
#ifdef CK_ANSIC
netgetc(int timo)                       /* Input function to point to... */
#else  /* CK_ANSIC */
netgetc(timo) int timo;
#endif /* CK_ANSIC */
{                                       /* ...in the tn_doop() call */
#ifdef TCPIPLIB
    return netinc(timo);
#else /* TCPIPLIB */
    return ttinc(timo);
#endif /* TCPIPLIB */
}
#endif /* TNCODE */

int
netflui() {
    int n;
    int ch;
#ifdef NETLEBUF
    ttpush = -1;                        /* Clear the peek-ahead char */
    while (le_data && (le_inbuf() > 0)) {
        CHAR ch = '\0';
        if (le_getchar(&ch) > 0) {
            debug(F101,"ttflui le_inbuf ch","",ch);
        }
    }
#endif /* NETLEBUF */

#ifdef TCPIPLIB
#ifdef OS2
    RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
#endif /* OS2 */
#ifdef TNCODE
    if (ttnproto == NP_TELNET) {
        /* Netflui must process Telnet negotiations or get out of sync */
        if ((n = nettchk()) <= 0)
          goto exit_flui;
        while (n-- > 0) {
            ch = netinc(1);
            if (ch == IAC) {
                extern int duplex;  /* this really shouldn't be here but ... */
                int tx = tn_doop((CHAR)(ch & 0xff),duplex,netgetc);
                if (tx == 1) duplex = 1;
                else if (tx == 2) duplex = 0;
                n = nettchk();
            }
        }
    } else
#endif /* TNCODE */
    {
        ttibuf[ttibp+ttibn] = '\0';
        debug(F111,"netflui 1",ttibuf,ttibn);
#ifdef CK_ENCRYPTION
        if (TELOPT_U(TELOPT_ENCRYPTION)) {
            ck_tn_decrypt(&ttibuf[ttibp],ttibn);
        }
#endif /* CK_ENCRYPTION */
        ttibn = ttibp = 0;              /* Flush internal buffer *FIRST* */
        if (ttyfd < 1)
          goto exit_flui;
        if ((n = nettchk()) > 0) {      /* Now see what's waiting on the net */
            if (n > TTIBUFL) n = TTIBUFL;       /* and sponge it up */
            debug(F101,"netflui 2","",n);       /* ... */
            n = socket_read(ttyfd,ttibuf,n); /* into our buffer */
            if (n >= 0) ttibuf[n] = '\0';
            debug(F111,"netflui 3",ttibuf,n);
#ifdef CK_ENCRYPTION
            if (TELOPT_U(TELOPT_ENCRYPTION)) {
                ck_tn_decrypt(&ttibuf[ttibp],n);
            }
#endif /* CK_ENCRYPTION */
            ttibuf[0] = '\0';
        }
    }
#else  /* !TCPIPLIB */
    if (ttyfd < 1)
      goto exit_flui;
#ifdef TNCODE
    if (ttnproto == NP_TELNET) {
        if ((n = ttchk()) <= 0)
          goto exit_flui;
        while (n-- >= 0) {
            /* Netflui must process Telnet negotiations or get out of sync */
            ch = ttinc(1);
            if (ch == IAC) {
                extern int duplex;  /* this really shouldn't be here but ... */
                int tx = tn_doop((CHAR)(ch & 0xff),duplex,netgetc);
                if (tx == 1) duplex = 1;
                else if (tx == 2) duplex = 0;
                n = ttchk();
            }
        };
    } else
#endif /* TNCODE */
    if ((n = ttchk()) > 0) {
        debug(F101,"netflui non-TCPIPLIB","",n);
        while ((n--) && ttinc(1) > -1)  /* Don't worry, ttinc() is buffered */
          ;                             /* and it handles the decryption... */
    }
#endif /* TCPIPLIB */
  exit_flui:
#ifdef OS2
    ReleaseTCPIPMutex();
#endif /* OS2 */
    return(0);
}

#ifdef CK_KERBEROS
/* The following two functions are required for encrypted rlogin */
/* They are called with nettoc() or nettol() are transmitting    */
/* encrypted data.  They call a function to encrypt the data     */
/* and that function needs to be able to write to/read from the  */
/* network in an unimpeded manner.  Hence, these two simple fns. */
int
net_write(fd, buf, len)
    int fd;
    register const char *buf;
    int len;
{
    int cc;
    register int wrlen = len;
    do {
#ifdef TCPIPLIB
        cc = socket_write(fd, buf, wrlen);
#else
        cc = write(fd,buf,wrlen);
#endif /* TCPIPLIB */
        if (cc < 0) {
            int s_errno = socket_errno;
            debug(F101,"net_write error","",s_errno);
#ifdef OS2
            if (os2socketerror(s_errno) < 0)
                return(-1);
            else
                continue;
#else /* OS2 */
            if (errno == EINTR)
                continue;
            return(-1);
#endif /* OS2 */
        }
        else {
            buf += cc;
            wrlen -= cc;
        }
    } while (wrlen > 0);
    return(len);
}
int
net_read(fd, buf, len)
    int fd;
    register char *buf;
    register int len;
{
    int cc, len2 = 0;

    do {
#ifdef TCPIPLIB
        cc = socket_read(fd, buf, len);
#else
        cc = read(fd,buf,len);
#endif
        if (cc < 0) {
            int s_errno = socket_errno;
            debug(F101,"net_read error","",s_errno);
#ifdef OS2
            if (os2socketerror(s_errno) < 0)
                return(-1);
#endif /* OS2 */
            return(cc);          /* errno is already set */
        }
        else if (cc == 0) {
            netclos();
            return(len2);
        } else {
            buf += cc;
            len2 += cc;
            len -= cc;
        }
    } while (len > 0);
    return(len2);
}
#endif /* CK_KERBEROS */
#endif /* NONET */

/* getlocalipaddr() attempts to resolve an IP Address for the local machine.
 *   If the host is multi-homed it returns only one address.
 *
 * Two techniques are used.
 * (1) get the local host name and perform a DNS lookup, then take
 *     the first entry;
 * (2) open a UDP socket, use it to connect to a fictitious host (it's OK,
 *    no data is sent), then retrieve the local address from the socket.
 * Note: the second technique won't work on Microsoft systems.  See
 * Article ID: Q129065 PRB: Getsockname() Returns IP Address 0.0.0.0 for UDP
 */

/* Technique number one cannot work reliably if the machine is a laptop
 * and the hostname is associated with a physical adapter which is not
 * installed and a PPP connection is being used instead.  This is because
 * the hostname DNS lookup will succeed for the physical adapter even though
 * it would be impossible to use it.  In NT4 SP4, the gethostbyname()
 * when given the result of gethostname() returns not the real DNS entries
 * for that name+domain.  Instead it returns all of the static and dynamic
 * IP addresses assigned to any physical or virtual adapter defined in the
 * system regardless of whether or not it is installed.  The order of the
 * addresses is fixed according to the binding order in the NT registry.
 */

/*
 * It appears that calling gethostbyname(NULL) is more reliable than
 * calling gethostbyname(gethostname()) on Windows.  So on Windows we will
 * only call gethostbyname(NULL).
 */

int
getlocalipaddr() {
#ifndef datageneral
    struct sockaddr_in l_sa;
    struct sockaddr_in r_sa;
    GSOCKNAME_T slen = sizeof(struct sockaddr_in);
    int sock;
    int rc;
    struct in_addr laddr;

    /* if still not resolved, then try second strategy */
    /* This second strategy does not work on Windows */

    debug(F100,"getlocalipaddr","",0);
    memset(&l_sa,0,slen);
    memset(&r_sa,0,slen);

    /* get a UDP socket */
    sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock != -1) {
        /* connect to arbirary port and address (NOT loopback) */
        r_sa.sin_family = AF_INET;
        r_sa.sin_port = htons(IPPORT_ECHO);

        /* The following is an "illegal conversion" in AOS/VS */
        /* (and who knows where else) */

#ifdef INADDRX
        inaddrx = inet_addr("128.127.50.1");
        r_sa.sin_addr.s_addr = *(unsigned long *)&inaddrx;
#else
        r_sa.sin_addr.s_addr = inet_addr("128.127.50.1");
#endif /* INADDRX */
        rc = connect(sock, (struct sockaddr *) &r_sa, sizeof(struct sockaddr));
        if (!rc) {                      /* get local address */
            getsockname(sock,(struct sockaddr *)&l_sa,&slen);
#ifdef TCPIPLIB
            socket_close(sock);         /* We're done with the socket */
#else
            close(sock);
#endif /* TCPIPLIB */
            if (l_sa.sin_addr.s_addr != INADDR_ANY) {
                myxipaddr = ntohl(l_sa.sin_addr.s_addr);
                ckstrncpy(myipaddr,(char *)inet_ntoa(l_sa.sin_addr),20);
                debug(F110,"getlocalipaddr setting buf to",myipaddr,0);
                return(0);
            }
        }
    }
    return getlocalipaddrs(myipaddr,sizeof(myipaddr),0);
#else /* datageneral */
    return(-1);
#endif /* datageneral */
}

int
getlocalipaddrs(buf,bufsz,index)
    char * buf;
    int    bufsz;
    int    index;
/* getlocalipaddrs */ {
#ifndef datageneral
    char localhost[256];
    struct hostent * host=NULL;
    struct sockaddr_in l_sa;
    struct sockaddr_in r_sa;
    GSOCKNAME_T slen = sizeof(struct sockaddr_in);
    int rc;
#ifdef COMMENT
    int sock;
    char messageBuf[60];
    struct in_addr laddr;
#endif /* COMMENT */

    debug(F100,"getlocalipaddrs","",0);
    memset(&l_sa,0,slen);
    memset(&r_sa,0,slen);

    /* init local address (to zero) */
    l_sa.sin_addr.s_addr = INADDR_ANY;

#ifdef CKGHNLHOST
    rc = gethostname(localhost, 256);
    debug(F110,"getlocalipaddrs localhost",localhost,0);
#else
    /* This doesn't work on some platforms, e.g. Solaris */
    rc = 0;
    localhost[0] = '\0';
#ifdef NT
    if ( winsock_version < 20 ) {
        rc = gethostname(localhost, 256);
        debug(F110,"getlocalipaddrs localhost",localhost,0);
    }
#endif /* NT */
#endif /* CKGHNLHOST */
    if (!rc) {
        /* resolve host name for local address */
        debug(F110,"getlocalipaddrs","calling gethostbyname()",0);
        host = gethostbyname(localhost);
        /* debug(F111,"getlocalipaddrs","gethostbyname() returned",host); */
        if (host) {
#ifdef HADDRLIST
            host = ck_copyhostent(host);
            if ( index < 0 || index > 63 || !host->h_addr_list[index] ) {
                buf[0] = '\0';
                return(-1);
            }
            l_sa.sin_addr.s_addr =
              *((unsigned long *) (host->h_addr_list[index]));
            ckstrncpy(buf,(char *)inet_ntoa(l_sa.sin_addr),20);
            debug(F110,"getlocalipaddrs setting buf to",buf,0);

#ifdef COMMENT
            /* This is for reporting multiple IP Address */
            while (host->h_addr_list && host->h_addr_list[0]) {
                l_sa.sin_addr.s_addr =
                  *((unsigned long *) (host->h_addr_list[0]));
                ckstrncpy(messageBuf,
                        (char *)inet_ntoa(l_sa.sin_addr),60);
                if (tcp_address) {
                    if (!strcmp(messageBuf,tcp_address))
                      ckstrncpy(myipaddr,tcp_address,20);
                }
                debug(F110,"getlocalipaddrs ip address list", messageBuf, 0);
                host->h_addr_list++;
            }
#endif /* COMMENT */
#else   /* HADDRLIST */
            if (index != 0) {
                buf[0] = '\0';
                return(-1);
            }
            l_sa.sin_addr.s_addr = *((unsigned long *) (host->h_addr));
            ckstrncpy(buf,(char *)inet_ntoa(l_sa.sin_addr),bufsz);
            debug(F110,"getlocalipaddrs setting buf to",buf,0);
#endif  /* HADDRLIST */
            return(0);
        } else debug(F110,
                     "getlocalipaddrs: gethostbyname() failed",
                     localhost,
                     0
                     );
    }
#endif /* datageneral */
    return(-1);
}

#ifdef RLOGCODE                 /* TCP/IP RLOGIN protocol support code */
int
rlog_naws() {
    struct rlog_naws {
        unsigned char id[4];
        unsigned short rows, cols, ypix, xpix;
    } nawsbuf;

    if (ttnet != NET_TCPB)
      return 0;
    if (ttnproto != NP_RLOGIN
#ifdef CK_KERBEROS
        && ttnproto != NP_K4LOGIN
        && ttnproto != NP_EK4LOGIN
        && ttnproto != NP_K5LOGIN
        && ttnproto != NP_EK5LOGIN
#endif /* CK_KERBEROS */
         )
      return 0;
    if (!TELOPT_ME(TELOPT_NAWS))
      return 0;

    debug(F100,"rlogin Window Size sent","",0);

    nawsbuf.id[0] = nawsbuf.id[1] = 0377;
    nawsbuf.id[2] = nawsbuf.id[3] = 's';
#ifdef OS2
    nawsbuf.rows = htons((unsigned short) (VscrnGetHeight(VTERM)
                          -(tt_status[VTERM]?1:0)));
    nawsbuf.cols = htons((unsigned short) VscrnGetWidth(VTERM));
#else /* OS2 */
    nawsbuf.rows = htons((unsigned short) tt_rows);
    nawsbuf.cols = htons((unsigned short) tt_cols);
#endif /* OS2 */
    nawsbuf.ypix = htons(0);            /* y pixels */

    nawsbuf.xpix = htons(0);            /* x pixels */
    if (ttol((CHAR *)(&nawsbuf), sizeof(nawsbuf)) < 0)
      return(-1);
    return(0);
}

#ifdef OS2ORUNIX
#define RLOGOUTBUF
#endif /* OS2 */
static int
#ifdef CK_ANSIC
rlog_ini(CHAR * hostname, int port,
         struct sockaddr_in * l_addr, struct sockaddr_in * r_addr)
#else /* CK_ANSIC */
rlog_ini(hostname, port, l_addr, r_addr)
    CHAR * hostname;
    int port;
    struct sockaddr_in * l_addr;
    struct sockaddr_in * r_addr;
#endif /* CK_ANSIC */
/* rlog_ini */ {

#ifdef RLOGOUTBUF
    char outbuf[512];
    int  outbytes=0;
#endif /* RLOGOUTBUF */
    int flag = 0;
#define TERMLEN 16
#define CONSPDLEN 16
    CHAR localuser[UIDBUFLEN+1];
    CHAR remoteuser[UIDBUFLEN+1];
    int userlen = 0;
    CHAR term_speed[TERMLEN+CONSPDLEN+1];
#ifdef CONGSPD
    long conspd = -1L;
#endif /* CONGSPD */
#ifdef OS2
    extern int tt_type, max_tt;
    extern struct tt_info_rec tt_info[];
#endif /* OS2 */
    int i, n;

    int rc = 0;
    tn_reset();                 /* This call will reset all of the Telnet */
                                /* options and then quit.  We need to do  */
                                /* this since we use the Telnet options   */
                                /* to hold various state information      */
    duplex = 0;                 /* Rlogin is always remote echo */
    rlog_inband = 0;

#ifdef CK_TTGWSIZ
/*
  But compute the values anyway before the first read since the out-
  of-band NAWS request would arrive before the first data byte (NULL).
*/
#ifdef OS2
    /* Console terminal screen rows and columns */
    debug(F101,"rlog_ini tt_rows 1","",VscrnGetHeight(VTERM)
           -(tt_status[VTERM]?1:0));
    debug(F101,"rlog_ini tt_cols 1","",VscrnGetWidth(VTERM));
    /* Not known yet */
    if (VscrnGetWidth(VTERM) < 0 ||
        VscrnGetHeight(VTERM)-(tt_status[VTERM]?1:0) < 0) {
        ttgwsiz();                      /* Try to get screen dimensions */
    }
    debug(F101,
          "rlog_ini tt_rows 2",
          "",
          VscrnGetHeight(VTERM)-(tt_status[VTERM]?1:0)
          );
    debug(F101,"rlog_ini tt_cols 2","",VscrnGetWidth(VTERM));
#else /* OS2 */
    debug(F101,"rlog_ini tt_rows 1","",tt_rows);
    debug(F101,"rlog_ini tt_cols 1","",tt_cols);
    if (tt_rows < 0 || tt_cols < 0) {   /* Not known yet */
        ttgwsiz();                      /* Try to find out */
    }
    debug(F101,"rlog_ini tt_rows 2","",tt_rows);
    debug(F101,"rlog_ini tt_cols 2","",tt_cols);
#endif /* OS2 */
#endif /* CK_TTGWSIZ */

    ttflui();                           /* Start by flushing the buffers */

    rlog_mode = RL_COOKED;

    /* Determine the user's local username ... */

    localuser[0] = '\0';
#ifdef NT
    {
        char localuid[UIDBUFLEN+1];
        ckstrncpy((char *)localuser,(char *)GetLocalUser(),UIDBUFLEN);
    }

    if ( !localuser[0] )
#endif /* NT */
    {
        char * user = getenv("USER");
        if (!user)
          user = "";
        userlen = strlen(user);
        debug(F111,"rlogin getenv(USER)",user,userlen);
        ckstrncpy((char *)localuser,user,UIDBUFLEN);
        debug(F110,"rlog_ini localuser 1",localuser,0);
    }
    if ( !localuser[0] )
        strcpy((char *)localuser,"unknown");
    else if (ck_lcname) {
        cklower((char *)localuser);
        debug(F110,"rlog_ini localuser 2",localuser,0);
    }

    /* And the username to login with */
    if (uidbuf[0]) {
        ckstrncpy((char *)remoteuser,uidbuf,UIDBUFLEN);
        debug(F110,"rlog_ini remoteuser 1",remoteuser,0);
    } else if (localuser[0]) {
        ckstrncpy((char *)remoteuser,(char *)localuser,UIDBUFLEN);
        debug(F110,"rlog_ini remoteuser 2",remoteuser,0);
    } else {
        remoteuser[0] = '\0';
        debug(F110,"rlog_ini remoteuser 3",remoteuser,0);
    }
    if (ck_lcname)
      cklower((char *)remoteuser);
    debug(F110,"rlog_ini remoteuser 4",remoteuser,0);

    /* The command to issue is the terminal type and speed */
    term_speed[0] = '\0';
    if (tn_term) {                      /* SET TELNET TERMINAL-TYPE value */
        if (*tn_term) {                 /* (if any) takes precedence. */
            ckstrncpy((char *)term_speed, tn_term, TERMLEN);
            flag = 1;
        }
    } else {                            /* Otherwise the local terminal type */
#ifdef OS2
        /* In terminal-emulating versions, it's the SET TERM TYPE value */
        ckstrncpy(term_speed, (tt_type >= 0 && tt_type <= max_tt) ?
                tt_info[tt_type].x_name : "network", TERMLEN);
#else
        /* In the others, we just look at the TERM environment variable */
        {
            char *p = getenv("TERM");
            if (p)
              ckstrncpy((char *)term_speed,p,TERMLEN);
            else
              term_speed[0] = '\0';
#ifdef VMS
            for (p = (char *) term_speed; *p; p++) {
                if (*p == '-' && (!strcmp(p,"-80") || !strcmp(p,"-132")))
                  break;
                else if (isupper(*p))
                  *p = tolower(*p);
            }
            *p = '\0';
#endif /* VMS */
        }
#endif /* OS2 */
    }
    n = strlen((char *)term_speed);
    if (n > 0) {                        /* We have a terminal type */
        if (!flag) {                    /* If not user-specified */
            for (i = 0; i < n; i++)     /* then lowercase it.    */
              if (isupper(term_speed[i]))
                term_speed[i] = tolower(term_speed[i]);
        }
        debug(F110,"rlog_ini term_speed 1",term_speed,0);

#ifdef CONGSPD
        /* conspd() is not yet defined in all ck*tio.c modules */
        conspd = congspd();
        if (conspd > 0L) {
            ckstrncat((char *)term_speed,"/",sizeof(term_speed));
            ckstrncat((char *)term_speed,ckltoa(conspd),sizeof(term_speed));
        } else
#endif /* CONGSPD */
          ckstrncat((char *)term_speed,"/19200",sizeof(term_speed));
        debug(F110,"rlog_ini term_speed 2",term_speed,0);
    } else {
        term_speed[0] = '\0';
        debug(F110,"rlog_ini term_speed 3",term_speed,0);
    }

#ifdef CK_KERBEROS
    if (ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN ||
        ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN) {
        int kver, encrypt, rc;
        switch (ttnproto) {
          case NP_K4LOGIN:
            kver = 4;
            encrypt = 0;
            break;
          case NP_EK4LOGIN:
            kver = 4;
            encrypt = 1;
            break;
          case NP_K5LOGIN:
            kver = 5;
            encrypt = 0;
            break;
          case NP_EK5LOGIN:
            kver = 5;
            encrypt = 1;
            break;
        default:
            kver = 0;
            encrypt = 0;
        }
        rc = ck_krb_rlogin(hostname, port,
                           localuser, remoteuser, term_speed,
                           l_addr, r_addr, kver, encrypt);
        if (!rc) {                      /* success */
            TELOPT_ME(TELOPT_NAWS) = 1;
            rc = rlog_naws();
        }
        return(rc);
    } else
#endif /* CK_KERBEROS */
    if (ttnproto == NP_RLOGIN) {
#ifdef RLOGOUTBUF
        /*
         *  The rcmds start the connection with a series of init data:
         *
         *    a port number upon which client is listening for stderr data
         *    the user's name on the client machine
         *    the user's name on the server machine
         *    the terminal_type/speed or command to execute
         */
        outbuf[outbytes++] = 0;
        strcpy((char *)outbuf+outbytes,(char *)localuser);
        outbytes += strlen((char *)localuser) + 1;
        strcpy((char *)outbuf+outbytes,(char *)remoteuser);
        outbytes += strlen((char *)remoteuser) + 1;
        strcpy((char *)outbuf+outbytes,(char *)term_speed);
        outbytes += strlen((char *)term_speed) + 1;
        rc = ttol((CHAR *)outbuf,outbytes);
#else /* RLOGOUTBUF */
        ttoc(0);                        /* Send an initial NUL as wake-up */
        /* Send each variable with the trailing NUL */
        rc = ttol(localuser,strlen((char *)localuser)+1);
        if (rc > 0)
          rc = ttol(remoteuser,strlen((char *)remoteuser)+1);
        if (rc > 0)
          rc = ttol(term_speed,strlen((char *)term_speed)+1);
#endif /* RLOGOUTBUF */

        /* Now we are supposed to get back a single NUL as confirmation */
        errno = 0;
        rc = ttinc(60);
        debug(F101,"rlogin first ttinc","",rc);
        if (rc > 0) {
            debug(F101,"rlogin ttinc 1","",rc);
            printf(
               "Rlogin protocol error - 0x%x received instead of 0x00\n", rc);
            return(-1);
        } else if (rc < 0) {
            debug(F101,"rlogin ttinc errno","",errno);
            /* printf("Network error: %d\n", errno); */
            return(-1);
        }
    }
    return(0);
}

/* two control messages are defined:

   a double flag byte of 'o' indicates a one-byte message which is
   identical to what was once carried out of band.

   a double flag byte of 'q' indicates a zero-byte message.  This
   message is interpreted as two \377 data bytes.  This is just a
   quote rule so that binary data from the server does not confuse the
   client.  */

int 
rlog_ctrl(cp, n)
     unsigned char *cp;
     int n;
{
    if ((n >= 5) && (cp[2] == 'o') && (cp[3] == 'o')) {
        if (rlog_oob(&cp[4],1))
            return(-5);
        return(5);
    } else if ((n >= 4) && (cp[2] == 'q') && (cp[3] == 'q')) {
        /* this is somewhat of a hack */
        cp[2] = '\377';
        cp[3] = '\377';
        return(2);
    }
    return(0);
}

static int
rlog_oob(oobdata, count) CHAR * oobdata; int count; {
    int i;
    int flush = 0;

    debug(F111,"rlogin out_of_band","count",count);

    for (i = 0; i<count; i++)   {
        debug(F101,"rlogin out_of_band","",oobdata[i]);
                if (oobdata[i] & 0x01)
                        continue;

        if (oobdata[i] & 0x02) { /* Flush Buffered Data not yet displayed */
            debug(F101,"rlogin Flush Buffered Data command","",oobdata[i]);

            /* Only flush the data if in fact we are in a mode that won't */
            /* get out of sync.  Ie, not when we are in protocol mode.    */
            switch ( what ) {
            case W_NOTHING:
            case W_CONNECT:
            case W_COMMAND:
                if ( rlog_inband )
                    flush = 1;
                else
                    ttflui();
                break;
            }
        }
        if (oobdata[i] & 0x10) {        /* Switch to RAW mode */
            debug(F101,"rlogin Raw Mode command","",oobdata[i]);
            rlog_mode = RL_RAW;
        }

        if (oobdata[i] & 0x20) {        /* Switch to COOKED mode */
            debug(F101,"rlogin Cooked Mode command","",oobdata[i]);
            rlog_mode = RL_COOKED;
        }
        if (oobdata[i] & 0x80)
        {        /* Send Window Size Info */
            debug(F101,"rlogin Window Size command","",oobdata[i]);
            /* Remember to send WS Info when Window Size changes */
            if ( !TELOPT_ME(TELOPT_NAWS) ) {
                TELOPT_ME(TELOPT_NAWS) = 1;
                rlog_naws();
            }
        }
    }
    return(flush);
}
#ifndef TCPIPLIB
static SIGTYP
rlogoobh(sig) int sig; {
#ifdef SOLARIS
    char                                /* Or should it be char for all? */
#else
    CHAR
#endif /* SOLARIS */
      oobdata;

    /* int  count = 0; */ /* (not used) */

    while (recv(ttyfd, &oobdata, 1, MSG_OOB) < 0) {
      /*
       * We need to do some special processing here.
       * Just in case the socket is blocked for input
       *
       */
        switch (errno) {
          case EWOULDBLOCK:
            break;
          default:
            return;
        }
    }
    debug(F101,"rlogin out_of_band","",oobdata);
    if (oobdata == 0x02) {      /* Flush Buffered Data not yet displayed */
        debug(F101,"rlogin Flush Buffered Data command","",oobdata);
        netflui();
    }
    if (oobdata & 0x10) {               /* Switch to raw mode */
        debug(F101,"rlogin Raw Mode command","",oobdata);
        rlog_mode = RL_RAW;
    }
    if (oobdata & 0x20) {               /* Switch to cooked mode */
        debug(F101,"rlogin Cooked Mode command","",oobdata);
        rlog_mode = RL_COOKED;
    }
    if (oobdata & 0x80) {                 /* Send Window Size Info */
        debug(F101,"rlogin Window Size command","",oobdata);
        /* Remember to send WS Info when Window Size changes */
        if ( !TELOPT_ME(TELOPT_NAWS) ) {
            TELOPT_ME(TELOPT_NAWS) = 1;
            rlog_naws();
        }
    }
}
#endif /* TCPIPLIB */
#endif /* RLOGCODE */

/* Send network BREAK */
/*
  Returns -1 on error, 0 if nothing happens, 1 if BREAK sent successfully.
*/
int
netbreak() {
    CHAR buf[3];
    if (ttnet == NET_TCPB) {
        if (ttnproto == NP_TELNET) {
#ifdef TNCODE
            buf[0] = (CHAR) IAC; buf[1] = (CHAR) BREAK; buf[2] = (CHAR) 0;
            if (
#ifdef OS2
                nettol((char *) buf, 2)
#else
                ttol(buf, 2)
#endif /* OS2 */
                < 2)
              return(-1);
            if (tn_deb || debses || deblog) {
                extern char tn_msg[];
                ckmakmsg(tn_msg,TN_MSG_LEN,"TELNET SENT ",TELCMD(BREAK),
                          NULL,NULL);
                debug(F101,tn_msg,"",BREAK);
                if (debses || tn_deb) tn_debug(tn_msg);
            }
            return(1);
#else
            debug(F100,"netbreak no TNCODE","",0);
            return(0);
#endif /* TNCODE */
        }
        /* Insert other TCP/IP protocols here */
    }
    /* Insert other networks here */
    return(0);
}
#endif /* NETCONN */


#ifdef NETCONN
#ifdef SUNX25
/*
  SunLink X.25 support by Marcello Frutig, Catholic University,
  Rio de Janeiro, Brazil, 1990.
*/

/* PAD X.3, X.28 and X.29 support */

static CHAR x29err[MAXPADPARMS+3] = { X29_ERROR, INVALID_PAD_PARM, '\0' };

/* Initialize PAD */

extern CHAR padparms[];

VOID
initpad() {
  padparms[PAD_BREAK_CHARACTER]        = 0;  /* Break character */
  padparms[PAD_ESCAPE]                 = 1;  /* Escape permitted */
  padparms[PAD_ECHO]                   = 1;  /* Kermit PAD does echo */
  padparms[PAD_DATA_FORWARD_CHAR]      = 2;  /* forward character CR */
  padparms[PAD_DATA_FORWARD_TIMEOUT]   = 0;  /* no timeout forward condition */
  padparms[PAD_FLOW_CONTROL_BY_PAD]    = 0;  /* not used */
  padparms[PAD_SUPPRESSION_OF_SIGNALS] = 1;  /* allow PAD service signals */
  padparms[PAD_BREAK_ACTION]           = 21; /* brk action: INT pk + brk ind*/
  padparms[PAD_SUPPRESSION_OF_DATA]    = 0;  /* no supression of user data */
  padparms[PAD_PADDING_AFTER_CR]       = 0;  /* no padding after CR */
  padparms[PAD_LINE_FOLDING]           = 0;  /* no line fold */
  padparms[PAD_LINE_SPEED]             = 0;  /* line speed - don't care */
  padparms[PAD_FLOW_CONTROL_BY_USER]   = 0;  /* flow cont of PAD - not used */
  padparms[PAD_LF_AFTER_CR]            = 0;  /* no LF insertion after CR */
  padparms[PAD_PADDING_AFTER_LF]       = 0;  /* no padding after LF */
  padparms[PAD_EDITING]                = 1;  /* can edit */
  padparms[PAD_CHAR_DELETE_CHAR]       = 8;  /* character delete character */
  padparms[PAD_BUFFER_DELETE_CHAR]     = 21; /* buffer delete character */
  padparms[PAD_BUFFER_DISPLAY_CHAR]    = 18; /* buffer display character */
}

/* Set PAD parameters */

VOID
setpad(s,n) CHAR *s; int n; {
    int i;
    CHAR *ps = s;

    if (n < 1) {
        initpad();
    } else {
        for (i = 0; i < n; i++) {
            if (*ps > MAXPADPARMS)
              x29err[i+2] = *ps;
            else
              padparms[*ps] = *(ps+1);
            ps += 2;
        }
    }
}

/* Read PAD parameters */

VOID
readpad(s,n,r) CHAR *s; int n; CHAR *r; {
    int i;
    CHAR *ps = s;
    CHAR *pr = r;

    *pr++ = X29_PARAMETER_INDICATION;
    if (n > 0) {
        for (i = 0; i < n; i++, ps++) {
            if (*ps > MAXPADPARMS) {
                x29err[i+2] = *ps++;
            } else {
                *pr++ = *ps;
                *pr++ = padparms[*ps++];
            }
        }
    } else {
        for (i = 1; i < MAXPADPARMS; i++) {
            *pr++ = i;
            *pr++ = padparms[i];
        }
    }
}

int
qbitpkt(s,n) CHAR *s; int n; {
    CHAR *ps = s;
    int x29cmd = *ps;
    CHAR *psa = s+1;
    CHAR x29resp[(MAXPADPARMS*2)+1];

    switch (x29cmd) {

        case X29_SET_PARMS:
            setpad (ps+1,n/2);
            if ((int)strlen((char *)x29err) > 2) {
                ttol(x29err,(int)strlen((char *)x29err));
                x29err[2] = '\0';
            }
            return (-2);
        case X29_READ_PARMS:
            readpad (ps+1,n/2,x29resp);
            setqbit ();
            ttol(x29resp,(n>1)?(n+1):(2*MAXPADPARMS+1));
            if ((int)strlen((char *)x29err) > 2) {
                ttol(x29err,(int)strlen((char *)x29err));
                x29err[2] = '\0';
            }
            resetqbit();
            break;
        case X29_SET_AND_READ_PARMS:
            setpad (ps+1,n/2);
            readpad (ps+1,n/2,x29resp);
            setqbit();
            ttol(x29resp,(n>1)?(n+1):(2*MAXPADPARMS+1));
            if ((int)strlen((char *)x29err) > 2) {
                ttol (x29err,(int)strlen((char *)x29err));
                x29err [2] = '\0';
            }
            resetqbit();
            return (-2);
        case X29_INVITATION_TO_CLEAR:
            (VOID) x25clear();
            return (-1);
        case X29_INDICATION_OF_BREAK:
            break;
    }
    return (0);
}

/* PAD break action processor */

VOID
breakact() {
    extern char x25obuf[MAXOX25];
    extern int obufl;
    extern int active;
    extern unsigned char tosend;
    static CHAR indbrk[3] = {
        X29_INDICATION_OF_BREAK,
        PAD_SUPPRESSION_OF_DATA,
        1
    };
    CHAR intudat, cause, diag;

    if (x25stat() < 0) return;  /* Ignore if no virtual call established */

    if (padparms[PAD_BREAK_ACTION] != 0) /* Forward condition */
        if (ttol((CHAR *)x25obuf,obufl) < 0) {
            perror ("\r\nCan't send characters");
            active = 0;
        } else {
            bzero (x25obuf,sizeof(x25obuf));
            obufl = 0;
            tosend = 0;
        };

    switch (padparms[PAD_BREAK_ACTION]) {

       case 0 : break;                  /* do nothing */
       case 1 : /* send interrupt packet with interrupt user data field = 1 */
                intudat = 1;
                x25intr (intudat);
                break;
       case 2 : /* send reset packet with cause and diag = 0 */
                cause = diag = 0;
                x25reset (cause,diag);
                break;
       case 5 : /* send interrupt packet with interrupt user data field = 0 */
                intudat = 0;
                x25intr (intudat);
                setqbit ();
                /* send indication of break without a parameter field */
                ttoc(X29_INDICATION_OF_BREAK);
                resetqbit ();
                break;
       case 8 : active = 0;             /* leave data transfer */
                conol ("\r\n");
                break;
       case 21: /* send interrupt packet with interrupt user data field = 0 */
                intudat = 0;
                x25intr (intudat);
                setpad (indbrk+1,2);    /* set pad to discard input */
                setqbit ();
                /* send indication of break with parameter field */
                ttol (indbrk,sizeof(indbrk));
                resetqbit ();
                break;
     }
}

/* X.25 support functions */

X25_CAUSE_DIAG diag;

/*
  Convert a null-terminated string representing an X.121 address
  to a packed BCD form.
*/
int
pkx121(str,bcd) char *str; CHAR *bcd; {
    int i, j;
    u_char c;

    i = j = 0;
    while (str[i]) {
        if (i >= 15 || str [i] < '0' || str [i] > '9')
          return (-1);
        c = str [i] - '0';
        if (i & 1)
          bcd [j++] |= c;
        else
          bcd [j] = c << 4;
        i++;
    }
    return (i);
}

/* Reads and prints X.25 diagnostic */

int
x25diag () {
    int i;

    bzero ((char *)&diag,sizeof(diag));
    if (ioctl(ttyfd,X25_RD_CAUSE_DIAG,&diag)) {
        perror ("Reading X.25 diagnostic");
        return(-1);
    }
    if (diag.datalen > 0) {
        printf ("X.25 Diagnostic :");
        for (i = 0; i < (int)diag.datalen; i++)
          printf(" %02h",diag.data[i])+
        printf ("\r\n");
    }
    return(0);
}

/* X.25 Out-of-Band Signal Handler */

SIGTYP
x25oobh(foo) int foo; {
    int oobtype;
    u_char oobdata;
    int t;

    (VOID) signal(SIGURG,x25oobh);
    do {
        if (ioctl(ttyfd,X25_OOB_TYPE,&oobtype)) {
            perror ("Getting signal type");
            return;
        }
        switch (oobtype) {
          case INT_DATA:
            if (recv(ttyfd,(char *)&oobdata,1,MSG_OOB) < 0) {
                perror ("Receiving X.25 interrupt data");
                return;
            }
            t = oobdata;
            printf ("\r\nInterrupt received, data = %d\r\n", t);
            break;
          case VC_RESET:
            printf ("\r\nVirtual circuit reset\r\n");
            x25diag ();
            break;
          case N_RESETS:
            printf ("\r\nReset timeout\r\n");
            break;
          case N_CLEARS:
            printf ("\r\nClear timeout\r\n");
            break;
          case MSG_TOO_LONG:
            printf ("\r\nMessage discarded, too long\r\n");
            break;
          default:
            if (oobtype) printf("\r\nUnknown oob type %d\r\n",oobtype);
            break;
        }
    } while (oobtype);
}

/* Send a X.25 interrupt packet */

int
#ifdef CK_ANSIC
x25intr(char intr)
#else
x25intr(intr) char intr;
#endif /* CK_ANSIC */
/* x25intr */ {
    if (send(ttyfd,&intr,1,MSG_OOB) < 0) return(-1);
    debug(F100,"X.25 intr","",0);
    return(0);
}

/* Reset X.25 virtual circuit */
int
#ifdef CK_ANSIC
x25reset(char cause, char diagn)
#else
x25reset(cause, diagn) char cause; char diagn;
#endif /* CK_ANSIC */
/* x25reset */ {
    bzero ((char *)&diag,sizeof(diag));
    diag.flags   = 0;
    diag.datalen = 2;
    diag.data[0] = cause;
    diag.data[1] = diagn;
    if (ioctl(ttyfd,X25_WR_CAUSE_DIAG,&diag) < 0)
      return(-1);
    debug(F100,"X.25 reset","",0);
    return(0);
}

/* Clear X.25 virtual circuit */
int
x25clear() {
    int i;
    debug(F100,"X.25 clear","",0);
    bzero ((char *)&diag,sizeof(diag));
    diag.flags = (1 << DIAG_TYPE);
    diag.datalen = 2;
    diag.data[0] = 0;
    diag.data[1] = 0;
    ioctl (ttyfd,X25_WR_CAUSE_DIAG,&diag); /* Send Clear Request */
    return(ttclos(0));                  /* Close socket */
}

/* X.25 status */
int
x25stat() {
    if (ttyfd == -1) return (-1);
    return(0);
}

/* Set Q_BIT on */
VOID
setqbit() {
    static int qbiton = 1 << Q_BIT;
    ioctl (ttyfd,X25_SEND_TYPE,&qbiton);
}

/* Set Q_BIT off */
VOID
resetqbit() {
    static int qbitoff = 0;
    ioctl (ttyfd,X25_SEND_TYPE,&qbitoff);
}

/* Read n characters from X.25 circuit into buf */

int
x25xin(n,buf) int n; CHAR *buf; {
    register int x, c;
    int qpkt;

    do {
        x = read(ttyfd,buf,n);
        if (buf[0] & (1 << Q_BIT)) { /* If Q_BIT packet, process it */
            /* If return -1 : invitation to clear; -2 : PAD changes */
            if ((c=qbitpkt(buf+1,x-2)) < 0) return(c);
            qpkt = 1;
        } else qpkt = 0;
    } while (qpkt);

#ifdef COMMENT                  /* Disabled by Stephen Riehm 19.12.97 */
    /* BUG!
     * if buf[] is full, then this null lands in nirvana!
     * I was unable to find any code which needs a trailing null in buf[]
     */
    if (x > 0) buf[x] = '\0';
#endif /* COMMENT */
    if (x < 1) x = -1;
    debug(F101,"x25xin x","",x);

    return(x);
}

#ifdef COMMENT /* NO LONGER NEEDED! */
/* X.25 read a line */

int
#ifdef PARSENSE
#ifdef CK_ANSIC
x25inl(CHAR *dest, int max,int timo, CHAR eol, CHAR start)
#else
x25inl(dest,max,timo,eol,start) int max,timo; CHAR *dest, eol, start;
#endif /* CK_ANSIC */
#else /* not PARSENSE */
#ifdef CK_ANSIC
x25inl(CHAR *dest, int max,int timo, CHAR eol)
#else
x25inl(dest,max,timo,eol) int max,timo; CHAR *dest, eol;
#endif /* __SDTC__ */
#endif /*PARSENSE */
 /* x25inl */ {
    CHAR *pdest;
    int pktype, goteol, rest, n;
    int i, flag = 0;
    extern int ttprty, ttpflg;
    int ttpmsk;

    ttpmsk = (ttprty) ? 0177 : 0377;    /* Set parity stripping mask */

    debug(F101,"x25inl max","",max);
    debug(F101,"x25inl eol","",eol);
    pdest  = dest;
    rest   = max;
    goteol = 0;
    do {
        n = read(ttyfd,pdest,rest);
        n--;
        pktype = *pdest & 0x7f;
        switch (pktype) {
          case 1 << Q_BIT:
            if (qbitpkt(pdest+1,--n) < 0) return(-2);
            break;
          default:
            if (flag == 0) { /* if not in packet, search start */
                for (i = 1; (i < n) &&
                     !(flag = ((dest[i] & 0x7f) == start));
                     i++);
                if (flag == 0) { /* not found, discard junk */
                    debug(F101,"x25inl skipping","",n);
                    continue;
                } else {                /* found, discard junk before start */
                    int k;
                    n = n - i + 1;
                    for (k = 1; k <= n; k++, i++) dest[k] = dest[i];
                }
            }
            for (i = 0; (i < n) && /* search for eol */
                 !(goteol=(((*pdest = *(pdest+1)&ttpmsk)&0x7f)== eol));
                 i++,pdest++);
            *pdest = '\0';
            rest -= n;
        }
    } while ((rest > 0) && (!goteol));

    if (goteol) {
        n = max - rest;
        debug (F111,"x25inl X.25 got",(char *) dest,n);
        if (timo) ttimoff();
        if (ttpflg++ == 0 && ttprty == 0) {
            if ((ttprty = parchk(dest,start,n)) > 0) {
                int j;
                debug(F101,"x25inl senses parity","",ttprty);
                debug(F110,"x25inl packet before",(char *)dest,0);
                ttpmsk = 0x7f;
                for (j = 0; j < n; j++)
                  dest[j] &= 0x7f; /* Strip parity from packet */
                debug(F110,"x25inl packet after ",dest,0);
            } else {
                debug(F101,"parchk","",ttprty);
                if (ttprty < 0) { ttprty = 0; n = -1; }
            }
        }
        ttimoff();
        return(n);
    }
    ttimoff();
    return(-1);
}
#endif /* COMMENT */
#endif /* SUNX25 */

#ifdef IBMX25
/*
 * IBM X25 support - using the NPI streams interface
 * written by Stephen Riehm, pc-plus, Munich Germany
 */

/* riehm: missing functions / TODO list */

/*
  x25intr() - Send an interrupt packet
*/

/* return an error message depending on packet type */
char *
x25err(n) int n; {
    static char buf[30];
    switch (n) {
      case NBADADDR:     return "invalid address";
      case NBADOPT:      return "invalid options";
      case NACCESS:      return "no permission";
      case NNOADDR:      return "unable to allocate address";
      case NOUTSTATE:    return "invalid state";
      case NBADSEQ:      return "invalid sequence number";
      case NSYSERR:      return "system error";
      case NBADDATA:     return "invalid data size";
      case NBADFLAG:     return "invalid flag";
      case NNOTSUPPORT:  return "unsupported primitive";
      case NBOUND:       return "address in use";
      case NBADQOSPARAM: return "bad QOS parameters";
      case NBADQOSTYPE:  return "bad QOS type";
      case NBADTOKEN:    return "bad token value";
      case NNOPROTOID:   return "protocol id could not be allocated";
      case NODDCUD:      return "odd length call user data";
      default:
        ckmakmsg(buf,sizeof(buf),"Unknown NPI error ",ckitoa(n),NULL,NULL);
        return buf;
    }
}

/* turn a meaningless primitive number into a meaningful primitive name */
char *
x25prim(n) int n; {
    static char buf[30];
    switch(n) {
      case N_BIND_ACK:     return "N_BIND_ACK";
      case N_BIND_REQ:     return "N_BIND_REQ";
      case N_CONN_CON:     return "N_CONN_CON";
      case N_CONN_IND:     return "N_CONN_IND";
      case N_CONN_REQ:     return "N_CONN_REQ";
      case N_CONN_RES:     return "N_CONN_RES";
      case N_DATACK_IND:   return "N_DATAACK_IND";
      case N_DATACK_REQ:   return "N_DATAACK_REQ";
      case N_DATA_IND:     return "N_DATA_IND";
      case N_DATA_REQ:     return "N_DATA_REQ";
      case N_DISCON_IND:   return "N_DISCON_IND";
      case N_DISCON_REQ:   return "N_DISCON_REQ";
      case N_ERROR_ACK:    return "N_ERROR_ACK";
      case N_EXDATA_IND:   return "N_EXDATA_IND";
      case N_EXDATA_REQ:   return "N_EXDATA_REQ";
      case N_INFO_ACK:     return "N_INFO_ACK";
      case N_INFO_REQ:     return "N_INFO_REQ";
      case N_OK_ACK:       return "N_OK_ACK";
      case N_OPTMGMT_REQ:  return "N_OPTMGMT_REQ";
      case N_RESET_CON:    return "N_RESET_CON";
      case N_RESET_IND:    return "N_RESET_IND";
      case N_RESET_REQ:    return "N_RESET_REQ";
      case N_RESET_RES:    return "N_RESET_RES";
      case N_UDERROR_IND:  return "N_UDERROR_IND";
      case N_UNBIND_REQ:   return "N_UNBIND_REQ";
      case N_UNITDATA_REQ: return "N_UNITDATA_REQ";
      case N_UNITDATA_IND: return "N_UNITDATA_IND";
      default:
        ckmakmsg(buf,sizeof(buf),"UNKNOWN (",ckitoa(n),")",NULL);
        return buf;
    }
}

/*****************************************************************************
 * Function: x25getmsg()
 * Description: get a STREAMS message, and check it for errors
 *
 * Parameters:
 * fd           - file descriptor to x25 device (opened)
 * control      - control buffer (pre-allocated)
 * ctl_size     - size of control buffer
 * data         - data buffer (pre-allocated)
 * data_size    - size of data buffer
 * flags        - flags for getmsg()
 * expected     - expected Primitive type
 *
 * Return Value:
 *      >= 0    OK (size of data returned)
 *      -1      error
 *
 */
int
x25getmsg( fd, control, ctl_size, data, data_size, get_flags, expected )
    int                 fd;             /* X25 device (opened) */
    N_npi_ctl_t         *control;       /* control buffer (pre-allocated) */
    int                 ctl_size;       /* size of control buffer */
    N_npi_data_t        *data;          /* data buffer (pre-allocated) */
    int                 data_size;      /* size of data buffer */
    int                 *get_flags;     /* getmsg() flags */
    int                 expected;       /* expected primitive type */
/* x25getmsg */ {
    int                 rc = 0;         /* return code */
    struct strbuf       *get_ctl=NULL;  /* getmsg control */
    struct strbuf       *get_data=NULL; /* getmsg data */
    int                 more = 0;       /* flag for more data etc */
    int                 file_status = -1; /* file async status */
    N_npi_ctl_t         * result;       /* pointer to simplify switch() */
    int                 packet_type = -1; /* unknown packet thus far */

#ifdef TRACE
    printf( "TRACE: entering x25getmsg\n" );
#endif /* TRACE */

    debug( F110, "x25getmsg waiting for packet ", x25prim( expected ), 0);
    /* prepare the control structures for getmsg */
    if (control) {
        if ((get_ctl = (struct strbuf*)malloc(sizeof(struct strbuf))) == NULL)
          {
              perror("kermit x25getmsg(): get_ctl malloc failed\n");
              debug( F100, "x25getmsg malloc failed for get_ctl\n", "", 0);
              return(-1);
          }
        /* allow getmsg to return an unexpected packet type (which may be
         * larger than the expected one)
         */
        get_ctl->maxlen = NPI_MAX_CTL;
        get_ctl->len = 0;
        get_ctl->buf = (char *)control;
    } else {
        printf(
 "kermit x25getmsg(): internal error. control buffer MUST be pre-allocated!\n"
               );
        debug(F100,"x25getmsg internal error. no buffer pre-allocated","",0);
        return( -1 );
    }
    if (data) {
        if ((get_data = (struct strbuf*)malloc(sizeof(struct strbuf))) == NULL)
          {
            perror("kermit x25getmsg(): get_data malloc failed\n");
            debug( F100, "x25getmsg malloc failed for get_data\n", "", 0);
            return(-1);
        }
        get_data->maxlen = (NPI_MAX_DATA < data_size ) ?
          NPI_MAX_DATA :
            data_size;
        get_data->len = 0;
        get_data->buf = (char *)data;
    }

    /* get an X.25 packet -
     * it may be any kind of packet, so check for special cases
     * it may be split into multiple parts - so loop if necessary
     */
    do {
#ifdef DEBUG
        printf( "kermit: x25getmsg(): getting a message\n" );
#endif /* DEBUG */
        errno = 0;
        if ((more = getmsg(fd, get_ctl, get_data, get_flags)) < 0) {
#ifdef DEBUG
            printf( "kermit: x25getmsg(): getmsg returned an error\n" );
            perror( "getmsg error was" );
#endif /* DEBUG */
            debug(F101, "x25getmsg getmsg returned an error\n", "", errno);
            if ((errno == EAGAIN) && (get_data && (get_data->len > 0)) ) {
                /* was in non-blocking mode, nothing to get, but we're
                 * already waiting for the rest of the packet -
                 * switch to blocking mode for the next read.
                 * file_status used to reset file status before returning
                 */
                if ((file_status = fcntl(fd, F_GETFL, 0)) < 0
                    || fcntl(fd, F_SETFL, file_status & ~O_NDELAY) < 0)
                  {
                      perror("x25getmsg(): couldn't change x25 blocking mode");
                      debug(F101,
                            "x25getmsg fcntl returned an error\n", "", errno);
                      /* netclos(); */
                      rc = -1;
                      break;
                  } else {
                      /* loop again into a blocking getmsg() */
                      continue;
                  }
            } else {
                /* no data to get in non-blocking mode - return empty handed */
                perror( "x25getmsg(): getmsg failed" );
                debug(F101,"x25getmsg getmsg returned an error\n", "", errno);
                rc = -1;
                break;
            }
        } else if (more & MORECTL) {
            /* panic - the control information was larger than the
             * maximum control buffer size!
             */
            /* riehm: close connection? */
#ifdef DEBUG
            printf("x25getmsg(): received partial control packet - panic\n");
#endif /* DEBUG */
            debug( F101, "x25getmsg getmsg bad control block\n", "", errno);
            rc = -1;
            break;
        }

        if (result = (N_npi_ctl_t *)control) {
            packet_type = result->bind_ack.PRIM_type;
            if (packet_type != N_OK_ACK) {
                x25lastmsg = packet_type;
            }
        }
#ifdef DEBUG
        /* printf( "kermit: x25getmsg(): getting " ); */
        if (get_ctl->len > 0) {
            x25dump_prim(result);
        }
        debug(F110,
              "x25getmsg got packet ",
              x25prim( result->bind_ack.PRIM_type ),
              0
              );
#endif /* DEBUG */

        if (get_ctl->len >= (int)sizeof(result->bind_ack.PRIM_type)) {
            /* not as pretty as a switch(), but switch can't handle
             * runtime variable values :-(
             */
            if (packet_type == expected ) {
                /* got what we wanted, special case for DATA_IND
                 * packets though */
                /* riehm: check Q-bit ? */
#ifdef DEBUG
                printf("x25getmsg(): got expected packet\nrc is %d\n", rc);
#endif /* DEBUG */
                if (packet_type == N_DATA_IND ) {
                    /* data received. May be incomplete, even though
                     * getmsg returned OK
                     */
                    if (result->data_ind.DATA_xfer_flags & N_MORE_DATA_FLAG)
                        more |= MOREDATA;
                    if (result->data_ind.DATA_xfer_flags & N_RC_FLAG)
                        printf( "x25getmsg(): data packet wants ack\n" );
                }
            } else if( packet_type == N_DISCON_IND) {
                printf( "X25 diconnected\n" );
                /* riehm: need to acknowledge a disconnection? */
                x25clear();
                /* x25unbind( ttyfd ); */
                rc = -1;
            } else if( packet_type == N_ERROR_ACK) {
                errno = result->error_ack.UNIX_error;
                perror( "X25 error received" );
                rc = -1;
            } else {
                printf("x25getmsg(): failed %s\n", x25err(packet_type));
                rc = -1;
            }
        }
#ifdef COMMENT
        else {
            /* Panic - no control data */
            printf( "kermit: x25getmsg(): no control data with packet\n" );
            rc = -1;
        }
#endif /* COMMENT */

        if (get_data && (get_data->len >= 0)) {
            get_data->buf += get_data->len;
            get_data->maxlen -= get_data->len;
        }
    } while ((rc == 0)
             && (get_data && (get_data->maxlen > 0))
             && (more & MOREDATA)
             );

    /* return the file status to its original value, unless its still
     * set to -1, or one of the fcntl's failed */
    if ((file_status >= 0) && fcntl(fd, F_SETFL, file_status) < 0)
        rc = -1;

    /*
     * Verify that we received an expected primitive
     * there is apparantly an error case where the primitive is set
     * correctly, but there is not enough data in the control structure
     */
    if ((packet_type != expected) && (get_ctl->len >= ctl_size) ) {
        fprintf(stderr,
                "x25getmsg(): %s NOT received. Primitive received was %s\n",
                x25prim( expected ), x25prim( packet_type ));
        debug(F110, "x25getmsg got an unexpected packet ",
              x25prim(packet_type),
              0
              );
        rc = -1;
    }

    if (rc == 0) {
        if (get_data && ( get_data->len >= 0)) {
            rc = get_data->len;
        }
    }

    if (get_ctl)  { free(get_ctl); get_ctl = NULL; }
    if (get_data) { free(get_data); get_data = NULL; }

#ifdef COMMENT
#ifdef DEBUG
    printf( "kermit x25getmsg(): returning %d\n", rc );
#endif /* DEBUG */
#endif /* COMMENT */
    debug(F110, "x25getmsg returning packet ", x25prim( packet_type ), 0);

#ifdef TRACE
    printf( "TRACE: leaving x25getmsg\n" );
#endif /* TRACE */
    return(rc);
}

/*****************************************************************************
 * Function: x25putmsg()
 *
 * Description:
 *      send a message to a X25 STREAM
 *
 * Parameters:
 *      fd              - file descriptor to x25 device (opened)
 *      control         - control buffer (pre-allocated)
 *      data            - data buffer (pre-allocated)
 *      data_len        - length of data to be transmitted
 *      put_flags       - flags for putmsg()
 *
 * Return Value:
 *      >= 0    number of bytes transmitted
 *      -1      error
 */
int
x25putmsg(fd, control, data, data_len, put_flags)
    int                 fd;             /* X25 device (opened) */
    N_npi_ctl_t         *control;       /* control buffer (pre-allocated) */
    N_npi_data_t        *data;          /* data buffer (pre-allocated) */
    int                 data_len;       /* length of data (not the size of
                                           the buffer) */
    int                 *put_flags;     /* putmsg() flags */
/* x25putmsg */ {
    int                 rc = 0;         /* return code */
    ulong               type;           /* primitive type */
    struct strbuf       *put_ctl = NULL; /* putmsg control */
    struct strbuf       *put_data = NULL; /* putmsg data */

#ifdef TRACE
    printf( "TRACE: entering x25putmsg\n" );
#endif /* TRACE */

#ifdef DEBUG
    printf( "kermit: x25putmsg(): putting " );
    x25dump_prim( control );
    printf( "\tdata:\t\t" );
    x25dump_data( data, 0, data_len );
    debug(F110,"x25putmsg: putting packet ",x25prim(control->PRIM_type),0);
#endif /* DEBUG */

    if (control) {
        put_ctl = (struct strbuf *)malloc( sizeof( struct strbuf ) );
        if (put_ctl == NULL) {
            perror("kermit x25putmsg(): put_ctl malloc failed\n");
            return(-1);
        }
        put_ctl->maxlen = 0;                    /* unused by putmsg */
        put_ctl->len = NPI_MAX_CTL;
        put_ctl->buf = (char *)control;
    }
    if (data && ( data_len > 0)) {
        put_data = (struct strbuf *)malloc( sizeof( struct strbuf ) );
        if( put_data == NULL) {
            perror("kermit x25putmsg(): put_data malloc failed\n");
            return(-1);
        }
        put_data->maxlen = 0;                   /* unused by putmsg */
        put_data->len = data_len;
        put_data->buf = (char *)data;
    }

    errno = 0;
    rc = putmsg (fd, put_ctl, put_data, 0);
    if (rc < 0) {
        printf("x25putmsg(): couldn't put %s\n",x25prim(control->PRIM_type));
        perror("kermit: x25putmsg(): putmsg failed");
        return(-1);
    }

    /* riehm: this should perhaps be discounted! */
    x25lastmsg = control->PRIM_type;

#ifdef COMMENT
#ifdef DEBUG
    printf( "kermit debug: x25putmsg() returning %d\n", data_len );
#endif /* DEBUG */
#endif /* COMMENT */
    debug( F101, "x25putmsg block size put ", "", data_len);

#ifdef TRACE
    printf( "TRACE: leaving x25putmsg\n" );
#endif /* TRACE */

    return( data_len );
}

/*****************************************************************************
* Function: x25bind
* Description:  The bind submitted to NPI provides the information required
*               by the packet layer for it to listen for suitable incoming
*               calls.
*
* WARNING:
*
* This routine needs to be called in a completely different manner for
* the client and server side. When starting a client, the
* num_waiting_calls and CUD information should all be set to 0! The
* client's CUD must be inserted in the CONN_REQ data block.
* When starting a server, the CUD must be set to a CUD pattern, and
* the number of waiting calls should be set to a number other than 0.
* (num waiting calls is the number of incomming calls which are to be
* put on hold while the server is servicing another client.)
*
* Who invented this crap?
*
* Parameters:
*       fd              - X25 device (opened)
*       addr            - local address
*       cud             - User Data (null terminated)
*       cud_len         - User Data length
*       num_waiting_calls - number of outstanding calls allowed on this stream
*       line            - logical port number (1)
*       flags           - 0, DEFAULT_LISTENER or TOKEN_REQUEST
*
* Return Value:
*       if binding is successful, 0 is returned for a client, and a token is
*       returned for a server
*
* Return code: 0 if successful
*              -1 if unsuccessful
*****************************************************************************/

ulong
x25bind(fd, addr, cud, cud_len, num_waiting_calls, line, bind_flags)
    int fd;                             /* X25 device (opened) */
    char * addr;                        /* local address */
    char * cud;                         /* Call User Data (null terminated) */
    int cud_len;                        /* User Data length */
    int num_waiting_calls;              /* Outstanding calls allowed */
    int line;                           /* logical port number */
    ulong bind_flags;           /* 0, DEFAULT_LISTENER or TOKEN_REQUEST */
/* x25bind */ {
    ulong rc;                           /* return code */
    int get_flags;                      /* priority flag passed to getmsg */
    int put_flags = 0;                  /* output flags for putmsg, always 0 */
    ulong type;                         /* primitive type */
    N_bind_req_t *bind_req;             /* pointer to N_BIND_REQ primitive */
    N_bind_ack_t *bind_ack;             /* pointer to N_BIND_ACK primitive */
    char *addtl_info;                   /* pointer to info in addition to
                                         * the N_BIND_REQ primitive that is
                                         * passed in the control structure
                                         * to putmsg */
    int addr_len = 0;                   /* length of address string */
    ulong bind_req_t_size;              /* for debugging only */

#ifdef TRACE
    printf("TRACE: entering x25bind\n" );
#endif /* TRACE */

#ifdef DEBUG
    printf("TRACE: x25bind( %d, %s, %s, %d, %d )\n",
           fd, addr, cud, line, bind_flags
           );
#endif /* DEBUG */

    /*
     * Allocate  and zero out space to hold the control portion of the
     * message passed to putmsg. This will contain the N_BIND_REQ
     * primitive and any additional info required for that.
     *
     * Note: allocated space is the size of the union typedef
     * N_npi_ctl_t to allow the use fo the generic x25putmsg routine.
     */
    bind_req = (N_bind_req_t *) malloc(sizeof( N_npi_ctl_t));
    if (bind_req == NULL) {
        perror("kermit: x25bind(): bind_req malloc failed");
        debug(F100, "x25bind bind_req malloc failed", "", 0);
        return(-1);
    }
    bzero((char *)bind_req, sizeof(N_npi_ctl_t));

    /* Build the Bind Request Primitive */
    bind_req->PRIM_type = (ulong) N_BIND_REQ;

    /* Note that the address length is n+2 and NOT n. Two bytes MUST preceed
     * the actual address in an N_BIND_REQ. The first byte contains the
     * line number being used with this address, and the second byte is the
     * X.121 address prefix, which must be zero.
     */
    addr_len = strlen(addr);
    bind_req->ADDR_length = (ulong) (addr_len + 2);
    bind_req->ADDR_offset = (ulong)(sizeof(N_bind_req_t));
    bind_req->CONIND_number = (ulong)num_waiting_calls; /* server only */
    bind_req->BIND_flags = (ulong) bind_flags; /* 0 in client */
    bind_req->PROTOID_length = (ulong) cud_len; /* 0 in client */
    if (cud_len == 0) {
        bind_req->PROTOID_offset = (ulong) 0;
    } else {
        /* need to remember the trailing NULL in the address - not
         * counted in the address length
         */
        bind_req->PROTOID_offset
          = (ulong) (sizeof(N_bind_req_t) + bind_req->ADDR_length);
    }

    /*
     * Now fill in the additional information required with this primitive
     * (address and protocol information (Call User Data))
     */
    addtl_info = (char *) ((void *)bind_req + bind_req->ADDR_offset);
    /*
     * The bitwise "&" ensures that the line number is only one byte long
     */
    *addtl_info++ = (char) line & 0xff;
    *addtl_info++ = (char) 0; /* X.121 format */
    bcopy( addr, addtl_info, addr_len ); /* include trailing null */
    addtl_info += addr_len;
    if (cud_len > 0)
      bcopy( cud, addtl_info, cud_len );
    /*
     * Call putmsg() to put the bind request message on the stream
     */
    if (x25putmsg(fd,
                  (N_npi_ctl_t*)bind_req,
                  (N_npi_data_t *)NULL,
                  0,
                  &put_flags
                  ) < 0) {
        printf( "kermit: x25bind(): x25putmsg failed\n" );
        return(-1);
    }

    /*
     * Allocate and zero out space for the N_BIND_ACK primitive
     */
    bind_ack = (N_bind_ack_t *) malloc(sizeof(N_npi_ctl_t));
    if (bind_ack == NULL){
        perror("kermit: x25bind(): bind_ack malloc failed");
        return(-1);
    }
    bzero(bind_ack, sizeof(N_npi_ctl_t));
    /*
     * Initialize the control structure and flag variable sent to getmsg
     */
    get_flags=0;

    /* get the ACK for the bind */
#ifdef DEBUG
    printf( "kermit: x25bind() trying to get a BIND_ACK\n" );
#endif /* DEBUG */
    rc = (ulong)x25getmsg( fd, (N_npi_ctl_t*)bind_ack,
            (int)sizeof( N_bind_ack_t ), (N_npi_data_t*)NULL, 0, &get_flags,
            N_BIND_ACK );

    /* turn quantitive return code into a qualitative one */
    if (rc > 0) rc = 0;

    /* if all went well, get the token from the acknowledgement packet */
    if ((bind_flags & TOKEN_REQUEST ) && ( rc >= 0)) {
        rc = bind_ack->TOKEN_value;
    }

    /* free up the memory we allocated earlier */
    free(bind_req);
    free(bind_ack);

#ifdef TRACE
    printf( "TRACE: leaving x25bind\n" );
#endif /* TRACE */

    return( rc );
}

/*****************************************************************************
* Function: x25call
* Description:  This routine builds and sends an N_CONN_REQ primitive, then
*               checks for an N_CONN_CON primitive in return.
*
* Parameters:
* fd    - file descriptor of stream
* caddr - called address (remote address)
*
* Functions Referenced:
* malloc()
* bzero()
* getmsg()
* putmsg()
*
* Return code:
* 0 - if successful
* -1 if not successful
*****************************************************************************/
int
x25call(fd, remote_nua, cud)
    int fd;                             /* X25 device (opened) */
    char * remote_nua;                  /* remote address to call */
    char * cud;                         /* call user data */
/* x25call */ {
    int rc;                             /* return code */
    int flags;                          /* Connection flags */
    int get_flags;                      /* priority flags for getmsg */
    ulong type;                         /* primitive type */
    N_conn_req_t *connreq_ctl;          /* pointer to N_CONN_REQ primitive */
    N_npi_data_t *connreq_data;         /* pointer to N_CONN_REQ data (CUD) */
    int connreq_data_len;               /* length of filled data buffer */
    N_conn_con_t *conncon_ctl;          /* pointer to N_CONN_CON primitive */
    N_npi_data_t *conncon_data;         /* pointer to any data associated with
                                         * the N_CONN_CON primitive */
    char *addtl_info;                   /* pointer to additional info needed
                                         * for N_CONN_REQ primitive */
    int addr_len;                       /* length of address */

#ifdef TRACE
    printf( "TRACE: entering x25call\n" );
#endif /* TRACE */

#ifdef DEBUG
    printf( "x25call( %d, %s )\n", fd, remote_nua );
    printf( "connecting to %s on fd %d\n", remote_nua, fd );
#endif /* DEBUG */

    /*
     * Allocate and zero out space for the N_CONN_REQ primitive
     * use the size of the generic NPI primitive control buffer
     */
    connreq_ctl  = (N_conn_req_t *) malloc(sizeof(N_npi_ctl_t));
    if (connreq_ctl == NULL){
        perror("kermit: x25call(): connreq_ctl malloc failed");
        return(-1);
    }
    bzero(connreq_ctl,sizeof(N_npi_ctl_t));
    /*
     * Build the Connection Request Primitive
     */
    flags = 0;
    connreq_ctl->PRIM_type = (ulong) N_CONN_REQ;

    /* Note that the address length is nchai+1 and not n+2. The line number
     * is only passed with the address for the bind. The first byte of
     * the address for the N_CONN primitives contains the X.121
     * address prefix, which must be zero. The remaining bytes are the
     * address itself.
     */
    addr_len = strlen( remote_nua );
    connreq_ctl->DEST_length = (ulong) (addr_len + 1);
    connreq_ctl->DEST_offset = (ulong) sizeof(N_conn_req_t);
    /* connreq_ctl->CONN_flags = (ulong)EX_DATA_OPT | REC_CONF_OPT; */
    connreq_ctl->CONN_flags = (ulong) 0;
    connreq_ctl->QOS_length = (ulong) 0;        /* unsupported in AIX 4.1 */
    connreq_ctl->QOS_offset = (ulong) 0;        /* unsupported in AIX 4.1 */

    addtl_info = (char *) ((void*)connreq_ctl + connreq_ctl->DEST_offset);
    *addtl_info++ = (char) 0; /* X.121 format */
    bcopy( remote_nua, addtl_info, addr_len );

    /*
     * setup the data buffer for the connection request
     */
    connreq_data  = (N_npi_data_t *) malloc(sizeof(N_npi_data_t));
    if (connreq_data == NULL){
        perror("kermit: x25call(): connreq_data malloc failed");
        return(-1);
    }
    bzero(connreq_data,sizeof(N_npi_data_t));

    /* facility selection needs to be put in the front of connreq_data */
    connreq_data_len = 0;
    connreq_data_len += x25facilities( (char *)connreq_data );
    if (cud && *cud) {
        bcopy(cud,
              (char *)((char *)connreq_data + connreq_data_len),
              strlen(cud)
              );
        connreq_data_len += strlen( cud );
        }

    /*
     * Call putmsg() to put the connection request message on the stream
     */
    rc = x25putmsg( fd, (N_npi_ctl_t*)connreq_ctl, connreq_data,
            connreq_data_len, &flags );
    if (rc < 0) {
        return(-1);
    }

    /*
     * Allocate and zero out space for the N_CONN_CON primitive
     */
    if ((conncon_ctl = (N_conn_con_t *) malloc(sizeof(N_npi_ctl_t))) == NULL) {
        perror("kermit: x25call(): conncon_ctl malloc failed");
        return(-1);
    }
    bzero(conncon_ctl, sizeof(N_npi_ctl_t));

    /*
     * Allocate and zero out space for any data associated with N_CONN_CON
     */
    if ( (conncon_data = (N_npi_data_t *) malloc(NPI_MAX_DATA)) == NULL) {
        perror("kermit: x25call(): conncon_data malloc failed");
        return(-1);
    }
    bzero(conncon_data, NPI_MAX_DATA);

    /* Initialize and build the structures for getmsg */
    get_flags=0;

    rc = x25getmsg( fd, (N_npi_ctl_t*)conncon_ctl, (int)sizeof( N_conn_con_t ),
            conncon_data, NPI_MAX_DATA, &get_flags, N_CONN_CON );

    /* turn quantitive return code into a qualitative one */
    if (rc > 0) rc = 0;

    /* Free the space that we no longer need */
    if (connreq_ctl) { free(connreq_ctl); connreq_ctl = NULL; }
    if (conncon_ctl) { free(conncon_ctl); conncon_ctl = NULL; }
    if (conncon_data) { free(conncon_data); conncon_data = NULL; }

#ifdef TRACE
    printf( "TRACE: leaving x25call\n" );
#endif /* TRACE */

    return(rc);
}

/*****************************************************************************
 * Function: x25getcall
 *
 * Description: This routine checks for an incomming call, verified
 * that it is a CONNIND (connection indication) message, and then
 * accepts the call and returns the file descriptor of the new stream
 *
 * Parameters:
 * fd   - file descriptor of listening stream
 *
 * Return Codes:
 * callfd       - file descriptor of connected incomming call.
 *              - set to -1 if an error occured
 *
 *****************************************************************************/
int
x25getcall(fd) int fd; {
    int x25callfd;                      /* fd of incomming call */
    N_conn_ind_t *connind_ctl;          /* connind controll buffer */
    N_npi_data_t *connind_data;         /* connind data buffer */
    int get_flags;                      /* flags for getmsg */
    ulong flags;                        /* connection flags */
    int rc;                             /* return code */

    extern x25addr_t remote_nua;        /* remote X.25 addr global var */

#ifdef TRACE
    printf( "TRACE: entering x25getcall\n" );
#endif /* TRACE */

    /* allocate space for connection indication buffers */
    if ((connind_ctl = (N_conn_ind_t *)malloc(sizeof(N_npi_ctl_t))) == NULL) {
        perror("kermit: x25getcall(): connind_ctl malloc failed");
        return (-1);
    }
    bzero(connind_ctl, sizeof(N_npi_ctl_t));

    if ((connind_data = (N_npi_data_t *)malloc(NPI_MAX_DATA)) == NULL) {
        perror("kermit: x25getcall(): connind_data malloc failed");
        return (-1);
    }
    bzero(connind_data, NPI_MAX_DATA);

    /* initialise control structures */
    get_flags = 0;

    /* call getmsg to check for a connection indication */
    if (x25getmsg(fd,
                  (N_npi_ctl_t*)connind_ctl,
                  (int)sizeof(N_conn_ind_t),
                  connind_data,
                  NPI_MAX_DATA,
                  &get_flags,
                  N_CONN_IND
                  ) < 0) {
#ifdef DEBUG
        printf( "x25getcall(): errno is: %d\n", errno );
#endif /* DEBUG */
        perror ("x25getcall(): getmsg failed");
        return(-1);
    }

    /* a connection indication was received
     * - pull it to bits and answer the call
     */
    x25seqno = connind_ctl->SEQ_number;
    flags = connind_ctl->CONN_flags;
#ifdef DEBUG
    printf( "setting remote_nua to a new value due to incomming call\n" );
#endif /* DEBUG */
    /*
     * no guarantee that the address is null terminated, ensure that
     * after copying that it is (assumption: remote_nua is longer than
     * the address + 1)
     */
    bzero(remote_nua, sizeof(remote_nua));
    /* note: connind_ctl contains a x121 address, which has a null as
     * the FIRST character - strip it off!
     */
    ckstrncpy(remote_nua,
            (char*)((char*)connind_ctl + connind_ctl->SRC_offset + 1),
            connind_ctl->SRC_length - 1
            );
#ifdef DEBUG
    printf( "remote_nua set to new value of %s\n", remote_nua );
#endif /* DEBUG */

    /* errors handled by callee */
    x25callfd = x25accept(x25seqno, flags);

    /* free the malloc'd buffers */
    if (connind_ctl) { free(connind_ctl); connind_ctl = NULL; }
    if (connind_data) { free(connind_data); connind_data = NULL; }

#ifdef TRACE
    printf( "TRACE: leaving x25getcall\n" );
#endif /* TRACE */

    /* return the file descriptor (or error if < 0) */
    return( x25callfd );
}

/*****************************************************************************
 * Function: x25accept
 *
 * Description: accept an incomming call
 *              This essentially means opening a new STREAM and sending
 *              an acknowledge back to the caller.
 *
 * Parameters:
 *      seqno   - sequence number for acknowledgement
 *      flags   - flags passed to us by the caller
 *
 * Return Codes:
 *      fd      - file descriptor of new STREAM
 *                set to -1 if an error occured
 *
 *****************************************************************************/
int
x25accept(seqno,flags)
    ulong seqno;                        /* connection sequence number */
    ulong flags;                        /* connection flags */
/* x25accept */ {
    int x25callfd;                      /* fd for incomming call */
    int get_flags;                      /* priority flags for getmsg */
    int put_flags = 0;                  /* flags for putmsg, always 0 */
    int addr_len;                       /* length of local address */
    ulong token;                        /* connection token */
    N_conn_res_t *conn_res;             /* N_CONN_RES primitive */
    N_ok_ack_t *ok_ack;                 /* N_OK_ACK primitive */
    char *addtl_info;                   /* temp pointer */
    int rc;                             /* temporary return code */

/* global variables from ckcmai.c */
    extern int revcall, closgr, cudata;
    extern char udata[];
    extern x25addr_t local_nua;         /* local X.25 address */
    extern char x25name[];              /* x25 device name (sx25a0) */
    extern char x25dev[];               /* x25 device file /dev/x25pkt */
    extern int x25port;                 /* logical port to use */
    ulong bind_flags = 0;               /* flags for binding the X25 stream */

#ifdef TRACE
    printf( "TRACE: entering x25accept\n" );
#endif /* TRACE */

    /* open a new packet level stream */
    if ((x25callfd = open(x25dev, O_RDWR)) < 0) {
        perror ("kermit: x25accept(): X.25 device open error");
        debug(F101,"x25accept() device open error","",errno);
        return(-1);
    }

    /* push the NPI onto the STREAM */
    if (ioctl(x25callfd,I_PUSH,"npi") < 0) {
        perror( "kermit: x25accept(): couldn't push npi on the X25 stream" );
        debug(F101,"x25accept can't push npi on the X25 stream","",errno);
        return (-1);
    }

    /* bind kermit server to the local X25 address */
    /* taken from /usr/samples/sx25/npi/npiserver.c (AIX 4) */
    bind_flags |= TOKEN_REQUEST;
    token = x25bind(x25callfd,local_nua,(char *)NULL,0,0,x25port,bind_flags);
    if (token < 0) {
        printf( "kermit: x25accept(): couldn't bind to local X25 address\n" );
        netclos();
        return(-1);
    }

    /* allocate connection response primitive */
    if ((conn_res = (N_conn_res_t *)malloc( NPI_MAX_CTL )) == NULL) {
        perror("kermit: x25accept(): conn_res malloc failed");
        return (-1);
    }
    bzero((char *)conn_res, NPI_MAX_CTL);

    /* setup connection response primitive */
    addr_len = strlen( local_nua );
    conn_res->PRIM_type = (ulong)N_CONN_RES;
    conn_res->TOKEN_value = token;
    /* note address length is n+1 to accomodate the X.121 address prefix */
    conn_res->RES_length = (ulong)(addr_len + 1);
    conn_res->RES_offset = (ulong)sizeof( N_conn_res_t );
    conn_res->SEQ_number = seqno;
    conn_res->CONN_flags = 0;
    conn_res->QOS_length = 0;           /* unsupported - must be 0 (!?) */
    conn_res->QOS_offset = 0;

    addtl_info = (char *)((char *)conn_res + conn_res->RES_offset);
    *addtl_info++ = (char)0;    /* X.121 address prefix */
    bcopy( local_nua, addtl_info, addr_len );

    /*
     * send off the connect response
     */
    if (x25putmsg(x25callfd,
                  (N_npi_ctl_t*)conn_res,
                  (N_npi_data_t *)NULL,
                  0,
                  &put_flags
                  ) < 0 ) {
        perror("kermit: x25accept(): putmsg connect response failed");
        return(-1);
    }

    /*
     * Allocate and zero out space for the OK_ACK primitive
     */
    if ((ok_ack = (N_ok_ack_t *) malloc(sizeof(N_npi_ctl_t))) == NULL) {
        perror("kermit: x25call(): ok_ack malloc failed");
        return(-1);
    }
    bzero(ok_ack, sizeof(N_npi_ctl_t));

    /* Initialize and build the structures for getmsg */
    get_flags=0;

    rc = (int)x25getmsg(x25callfd,
                        (N_npi_ctl_t*)ok_ack,
                        (int)sizeof(N_ok_ack_t),
                        (N_npi_data_t*)NULL,
                        0,
                        &get_flags,
                        N_OK_ACK
                        );
    if (rc == 0) {
        /* sequence number is only for disconnecting when not connected !? */
        x25seqno = 0;
    }

    /* free up malloc'ed buffer space */
    if (conn_res) { free(conn_res); conn_res = NULL; }
    if (ok_ack) { free(ok_ack); ok_ack = NULL; }

#ifdef TRACE
    printf( "TRACE: leaving x25accept\n" );
#endif /* TRACE */

    return( ( rc >= 0 ) ? x25callfd : -1 );
}

/*****************************************************************************
 * Function: x25unbind
 *
 * Description:  This subroutine builds and sends an unbind request and gets
 * the acknowledgement for it.
 *
 * Parameters:
 * fd - File descriptor of the stream
 *
 * Functions Referenced:
 * getmsg()
 * putmsg()
 * malloc()
 * bzero()
 *
 * Return code:
 * 0 - if successful
 * -1 - if not successful
 *****************************************************************************/
int
x25unbind(fd) int fd; {                 /* X25 device (opened) */
    int rc;                             /* return code */
    int flags;                          /* bind flags */
    int get_flags;                      /* priority flag for getmsg */
    ulong type;                         /* primitive type */
    N_unbind_req_t *unbind_req;         /* pointer to N_UNBIND_REQ */
    N_ok_ack_t *ok_ack;                 /* pointer to N_OK_ACK */

#ifdef TRACE
    printf( "TRACE: entering x25unbind\n" );
#endif /* TRACE */

#ifdef DEBUG
    /* printf( "x25unbind( %d )\n", fd ); */
#endif /* DEBUG */
    debug(F101,"x25unbind closing x25 connection #","",fd);

    /* Allocate and zero out space to hold the N_UNBIND_REQ primitive */
    unbind_req = (N_unbind_req_t *) malloc(sizeof(N_npi_ctl_t));
    if (unbind_req == NULL) {
        perror("kermit: x25unbind(): unbind_req malloc failed");
        return(-1);
    }
    bzero(unbind_req, sizeof(N_npi_ctl_t));

    /*
     * Build the Unbind Request Primitive
     */
    flags = 0;
    unbind_req->PRIM_type = (ulong) N_UNBIND_REQ;

    /*
     * Call putmsg() to put the bind request message on the stream
     */
    if (x25putmsg(fd,
                  (N_npi_ctl_t*)unbind_req,
                  (N_npi_data_t *)NULL,
                  0,
                  &flags
                  ) < 0) {
        perror ("kermit: x25unbind(): putmsg failed");
        return(-1);
    }

    /* Allocate and Zero out space for the N_OK_ACK primitive */
    ok_ack = (N_ok_ack_t *) malloc(sizeof(N_npi_ctl_t));
    if (ok_ack == NULL) {
        perror("kermit x25unbind(): ok_ack malloc failed\n");
        return(-1);
    }
    bzero(ok_ack, sizeof(N_npi_ctl_t));

    /* Initialize and build the control structure for getmsg */
    get_flags=0;

    /* Call getmsg() to check for an acknowledgement */
    rc = x25getmsg(fd,
                   (N_npi_ctl_t*)ok_ack,
                   (int)sizeof(N_ok_ack_t),
                   (N_npi_data_t*)NULL,
                   0,
                   &get_flags,
                   N_OK_ACK
                   );
    if (rc < 0) {
        perror ("kermit: x25unbind: getmsg failed");
        return(-1);
    }

    /* Free up the space that we no longer need */
    if (unbind_req) { free(unbind_req); unbind_req = NULL; }
    if (ok_ack) { free(ok_ack); ok_ack = NULL; }

#ifdef TRACE
    printf( "TRACE: leaving x25unbind\n" );
#endif /* TRACE */

    return(0);
}

/*****************************************************************************
 * Function: x25xin
 *
 * Description:
 *      Read n characters from X.25 circuit into buf (AIX only)
 *
 * Parameters:
 *      data_buf_len    maximum size of data buffer
 *      data_buf        pointer to pre-allocated buffer space
 *
 * Return Value:
 *      the number of characters actually read
 */
int
x25xin(data_buf_len,data_buf) int data_buf_len; CHAR *data_buf; {
    struct strbuf getmsg_ctl;           /* streams control structure */
    struct strbuf getmsg_data;          /* streams data structure */
    int rc = 0;                         /* return code */
    int getmsg_flags;                   /* packet priority flags */
    char * ctl_buf;                     /* npi control buffer */
    N_npi_ctl_t * result;               /* pointer to simplify switch() */

#ifdef TRACE
    printf( "TRACE: entering x25xin\n" );
#endif /* TRACE */

    /* ensure that no maximum's are overridden */
    data_buf_len = (NPI_MAX_DATA < data_buf_len) ? NPI_MAX_DATA : data_buf_len;

    /* allocate space for packet control info */
    if ((ctl_buf = (char *)malloc(NPI_MAX_CTL)) == NULL) {
        perror( "kermit: x25xin(): ctl_buf malloc" );
        return(-1);
    }
#ifdef COMMENT
    /* riehm: need zeroed buffer for getmsg? */
    bzero( ctl_buf, NPI_MAX_CTL );
    /* clear data buffer */
    bzero( data_buf, data_buf_len );
#endif /* COMMENT */

    getmsg_flags = 0;                   /* get the first packet available */

    rc = x25getmsg(ttyfd,
                   ctl_buf,
                   NPI_MAX_CTL,
                   data_buf,
                   data_buf_len,
                   &getmsg_flags,
                   N_DATA_IND
                   );
#ifdef COMMENT
#ifdef DEBUG
    if (rc >= 0) {
        printf( "kermit: x25xin(): got " );
        x25dump_data( data_buf, 0, rc );
    } else {
        printf( "x25xin(): attempt to get data resulted in an error\n" );
    }
#endif /* DEBUG */
#endif /* COMMENT */

    /* free buffers */
    if (ctl_buf) { free(ctl_buf); ctl_buf = NULL; }

#ifdef TRACE
    printf( "TRACE: leaving x25xi\n" );
#endif /* TRACE */

    return(rc);
}

/*****************************************************************************
 * Function: x25write
 *
 * Description:
 *      write a block of characters to the X25 STREAM (AIX)
 *
 * Parameters:
 *      fd              file descriptor to write to
 *      databuf         buffer containing data to write
 *      databufsize             size of the buffer to write
 *
 * Return Value:
 *      size            the number of bytes actually transmitted
 */
int
x25write(fd, databuf, databufsize)
    int         fd;                  /* X25 STREAMS file descriptor (ttyfd) */
    char        *databuf;               /* buffer to write */
    int         databufsize;            /* buffer size */
/* x25write */ {
    N_data_req_t *data_req_ctl;
    int rc;                             /* return code (size transmitted) */
    int write_flags = 0;                /* always 0 !? */

#ifdef TRACE
    printf( "TRACE: entering x25write\n" );
#endif /* TRACE */

    if ((data_req_ctl = (N_data_req_t *)malloc(NPI_MAX_CTL) ) == NULL) {
        perror( "kermit: x25write(): data_req_ctl malloc" );
        return(-1);
    }
    data_req_ctl->PRIM_type = N_DATA_REQ;
    data_req_ctl->DATA_xfer_flags = 0;

    /* riehm: possible extension
     * possibly need to think about splitting up the data buffer
     * into multiple parts if databufsize > NPI_MAX_DATA
     */

#ifdef COMMENT
#ifdef DEBUG
    printf( "kermit: x25write(): writing data to x25 stream\n" );
    printf( "\tdata:\t" );
    x25dump_data(databuf, 0, databufsize);
#endif /* DEBUG */
#endif /* COMMENT */
    rc = x25putmsg(fd,
                   (N_npi_ctl_t*)data_req_ctl,
                   (N_npi_data_t*)databuf,
                   databufsize,
                   &write_flags
                   );
    if (data_req) { free(data_req_ctl);  data_req = NULL; }

#ifdef TRACE
    printf( "TRACE: leaving x25write\n" );
#endif /* TRACE */

    return(rc);
}

/*****************************************************************************
 * Function: x25local_nua
 *
 * Description:
 *      This routine is only interesting for IBM computers. In order
 *      to set up a connection (see x25bind()) you need to know the
 *      local NUA (x25 address). Unfortunately, you need all this code
 *      to find that out, I just hope this works for everyone else!
 *
 * Parameters:
 *      a pre-allocated character buffer, long enough to hold an X.25 address
 *      and the tailing null.
 *
 * Return Value:
 *      the length of the address string.
 *      0 = error
 */
int
x25local_nua(char *buf) {
    struct CuAt *response;      /* structure to fill with info from ODM */
    CLASS_SYMBOL retClass;      /* ODM class */
    char query[64];             /* odm database query */
    int rc = 0;                 /* return value (length of local NUA) */
    extern char x25name[];      /* x25 device name (sx25a0) */

#ifdef TRACE
    printf( "TRACE: entering x25local_nua\n" );
#endif /* TRACE */

    /* set up query string */
    if (x25name[0] == '\0') {
#ifdef DEBUG
        printf( "kermit: x25local_nua(): No x25 device set, trying sx25a0\n" );
#endif /* DEBUG */
        strcpy( x25name, "sx25a0" );
    }
    ckmakmsg(query, sizeof(query), "name like ",x25name,
             " and attribute like local_nua");

    /* initialise ODM database */
    odmerrno = 0;
    if (odm_initialize() == -1) {
        printf( "x25local_nua(): can't initialize ODM database");
        switch (odmerrno) {
          case ODMI_INVALID_PATH:
            printf( "invalid path\n" );
            break;
          case ODMI_MALLOC_ERR:
            printf( "malloc failed\n" );
            break;
          default:
            printf( "unknown error %d\nPlease call IBM\n", odmerrno );
        }
        return(rc);
    }

    /* open the CuAt class */
    retClass = odm_open_class(CuAt_CLASS);
    if (((int)retClass) == -1) {
        printf( "kermit: x25local_nua(): can't open CuAt class in odm. " );
        switch (odmerrno) {
          case ODMI_CLASS_DNE:
            printf( "CuAt class doesn't exist\n" );
            break;
          case ODMI_CLASS_PERMS:
            printf( "permission to CuAt class file denied\n" );
            break;
          case ODMI_MAGICNO_ERR:
            printf( "CuAt is an invalid ODM object class\n" );
            break;
          case ODMI_OPEN_ERR:
            printf( "cannot open CuAt class - and don't know why!\n" );
            break;
          case ODMI_INVALID_PATH:
            printf( "invalid path\n" );
            break;
          case ODMI_TOOMANYCLASSES:
            printf( "too many object classes have been opened\n" );
            break;
          default:
            printf( "unknown error %d\nPlease call IBM\n", odmerrno );
        }
        return(rc);
    }

#ifdef DEBUG
    printf("retClass= %d\n", retClass);
#endif /* DEBUG */

    response = (struct CuAt *)odm_get_first( retClass, query, NULL );
    if (((int)response) == -1) {
        printf( "kermit: x25local_nua(): odm query failed " );
        switch (odmerrno) {
          case ODMI_BAD_CRIT:           /* Programming error */
            printf( "bad search criteria\n" );
            break;
          case ODMI_CLASS_DNE:
            printf( "CuAt class doesn't exist\n" );
            break;
          case ODMI_CLASS_PERMS:
            printf( "permission to CuAt class file denied\n" );
            break;
          case ODMI_INTERNAL_ERR:
            printf("odm internal error\nPlease contact your administrator\n" );
            break;
          case ODMI_INVALID_CLXN:
            printf("CuAt is invalid or inconsistent odm class collection\n");
            break;
          case ODMI_INVALID_PATH:
            printf( "invalid path\n" );
            break;
          case ODMI_MAGICNO_ERR:
            printf( "CuAt is an invalid ODM object class\n" );
            break;
          case ODMI_MALLOC_ERR:
            printf( "malloc failed\n" );
            break;
          case ODMI_OPEN_ERR:
            printf( "cannot open CuAt class - and don't know why!\n" );
            break;
          case ODMI_TOOMANYCLASSES:
            printf( "too many object classes have been opened\n" );
            break;
          default:
            printf( "unknown error %d\nPlease call IBM\n", odmerrno );
        }
        return(rc);
    }

    /* check for a meaningfull response */
    if (response != NULL) {
        if (response->value != NULL) {
            strcpy(buf, response->value);
            rc = strlen( buf );
#ifdef DEBUG
/*
            printf( "attribute name is: %s\n", (char *)response->attribute );
            printf( "I think my address is %s\n", (char*)response->value );
*/
#endif /* DEBUG */
        } else {
            printf( "kermit: x25local_nua(): couldn't find the local NUA\n" );
        }
    } else {
        switch (odmerrno) {
          case ODMI_BAD_CRIT:
            printf( "Error: ODMI_BAD_CRIT - bad criteria\n" );
            break;
          case ODMI_CLASS_DNE:
            printf( "Error: ODMI_CLASS_DNE - class doesn't exist\n" );
            break;
          case ODMI_CLASS_PERMS:
            printf( "Error: ODMI_CLASS_PERMS - class permissions\n" );
            break;
          case ODMI_INTERNAL_ERR:
            printf( "Error: ODMI_INTERNAL_ERR - panic\n" );
            break;
          case ODMI_INVALID_CLXN:
            printf( "Error: ODMI_INVALID_CLXN - invalid collection\n" );
            break;
          case ODMI_INVALID_PATH:
            printf( "Error: ODMI_INVALID_PATH - invalid path - what path?\n" );
            break;
          case ODMI_MAGICNO_ERR:
            printf( "Error: ODMI_MAGICNO_ERR - invalid object magic\n" );
            break;
          case ODMI_MALLOC_ERR:
            printf( "Error: ODMI_MALLOC_ERR - malloc failed\n" );
            break;
          case ODMI_OPEN_ERR:
            printf( "Error: ODMI_OPEN_ERR - cannot open class\n" );
            break;
          case ODMI_TOOMANYCLASSES:
            printf( "Error: ODMI_TOOMANYCLASSES - too many classes\n" );
            break;
          default:
            printf( "Unknown error!\n" );
        }
        return(rc);
    }

    /* close the database again */
    odm_close_class( retClass );

    /* forget about ODM all together */
    odm_terminate();

#ifdef TRACE
    printf( "TRACE: leaving x25local_nua\n" );
#endif /* TRACE */

    debug(F110, "x25local_nua local address is ", buf, 0);
    return(rc);
}

/*****************************************************************************
 * Function: x25facilities
 *
 * Description:
 *      build up the facilities data packet for a connection request
 *
 * Parameters:
 *      a pre-allocated char buffer, normally NPI_MAX_DATA big.
 *
 * Return Value:
 *      the number of characters inserted into the buffer
 */
int
x25facilities(buffer) char *buffer; {
    extern int revcall;
    extern int closgr;
    char *p;                            /* temp pointer */
    char *start;                        /* temp pointer */

#ifdef TRACE
    printf( "TRACE: entering x25facilities\n" );
#endif /* TRACE */

    p = buffer + 1;
    start = p;

#ifdef DEBUG
    printf( "kermit: x25facilities(): getting X25 facilities\n" );
#endif /* DEBUG */

    if (revcall != 0) {
#ifdef DEBUG
        printf("reverse charge: %d\n", revcall );
#endif /* DEBUG */
        *++p = 0x01;
        *++p = revcall;
    }
    if (closgr > 0) {
#ifdef DEBUG
        printf("closed user group: %d\n", closgr );
#endif /* DEBUG */
        *++p = 0x03;
        *++p = closgr;
    }

#ifdef DEBUG
    if (p == start) {
        printf( "no facilities\n" );
    }
#endif /* DEBUG */

    /* set the size of the facilities buffer */
    *buffer = (char)( p - start ) & 0xff;

#ifdef DEBUG
    printf( "kermit: x25facilities(): returning %d\n", (int)(p - buffer)  );
#endif /* DEBUG */

#ifdef TRACE
    printf( "TRACE: leaving x25facilities\n" );
#endif /* TRACE */

    /* return the size of the facilities with size byte */
    /* 1 == no facilities, 0 byte returned as facilities size */
    return( (int)(p - buffer) );
}

/*
 * reset the connection
 */
int
x25reset(cause, diagn) char cause; char diagn; {
    /* not implemented */

#ifdef TRACE
    printf( "TRACE: entering x25reset\n" );
#endif /* TRACE */

#ifdef TRACE
    printf( "TRACE: leaving x25reset\n" );
#endif /* TRACE */

    return(0);
}

/*
 * clear the x25 connection - ie: hang up
 */
int
x25clear() {
    int get_flags = 0;                  /* priority flag for getmsg */
    int put_flags = 0;                  /* send flags, always 0 */
    ulong type;                         /* primitive type */
    N_discon_req_t *discon_req;         /* pointer to N_DISCON_REQ */
    N_discon_ind_t *discon_ind;         /* pointer to N_DISCON_IND */
    N_npi_data_t *discon_data;          /* pointer to N_DISCON_IND data */
    int rc = 0;                         /* return code */

#ifdef TRACE
    printf( "TRACE: entering x25clear\n" );
#endif /* TRACE */

#ifdef DEBUG
    /* printf( "x25clear(): checking last msg: %s\n", x25prim(x25lastmsg)); */
#endif /* DEBUG */

    /*
    * The following checks are used to ensure that we don't disconnect
    * or unbind twice - this seems to throw the NPI interface right out of
    * kilter.
    */
    switch(x25lastmsg) {
      case N_BIND_ACK:
      case N_CONN_CON:
      case N_CONN_REQ:
      case N_DATA_REQ:
      case N_DATA_IND:
        {
#ifdef DEBUG
            /* printf("x25clear(): actively disconnecting\n"); */
#endif /* DEBUG */

                discon_req = (N_discon_req_t *)malloc(NPI_MAX_CTL);
                if (discon_req == NULL) {
                    perror("kermit x25clear(): discon_req malloc failed\n");
                    /* fallthrough, try to unbind the NPI anyway */
                } else {
                    discon_req->PRIM_type = N_DISCON_REQ;
                    discon_req->DISCON_reason = 0;      /* not used by AIX */
                    discon_req->RES_length = 0;
                    discon_req->RES_offset = (ulong)(sizeof(N_discon_req_t));
                    discon_req->SEQ_number = x25seqno;  /* global */

                    if (x25putmsg(ttyfd,
                                  (N_npi_ctl_t*)discon_req,
                                  (N_npi_data_t*)NULL,
                                  0,
                                  &put_flags
                                  ) < 0) {
                        perror("x25putmsg failed in x25clear()");
                    }
                    discon_ind = (N_discon_ind_t *)malloc(NPI_MAX_CTL);
                    discon_data = (N_npi_data_t *)malloc(NPI_MAX_DATA);
                    if((discon_ind == NULL) || (discon_data == NULL)) {
                        perror("x25clear(): discon_ind malloc failed\n");
                        /* fallthrough, try to unbind the NPI anyway */
                    } else {
                        if(x25getmsg(ttyfd,
                                     (N_npi_ctl_t*)discon_ind,
                                     NPI_MAX_CTL,
                                     (N_npi_data_t*)discon_data,
                                     NPI_MAX_DATA,
                                     &get_flags,
                                     N_OK_ACK
                                     ) < 0 ) {
                            perror("x25getmsg failed in x25clear()");
                            /* fallthrough, try to unbind the NPI anyway */
                        }
                    }
                }
                break;
            }
    }

    if (x25lastmsg != N_UNBIND_REQ) {
        rc = x25unbind(ttyfd);
    }

#ifdef TRACE
    printf( "TRACE: leaving x25clear\n" );
#endif /* TRACE */

    return(rc);
}

#ifdef DEBUG
/*
 * only for debugging
 *
 * turn the internal representation of a datablock into something
 * half-way readable. Because the length is known, we can print
 * the string including null's etc (important, because the first(!)
 * byte of an X121 address is a null! (X121 addr == 0 + X25 addr)
 */
x25dump_data(char *addr, ulong offset, ulong length) {
    char *ptr = addr + offset;
    ulong i = length;
    /* allocate enough memory for all unprintable chars */
    char *buf = (char *)malloc( length * 4 );
    char *bptr = buf;   /* pointer to current place in the print buffer */

    while (i > 0) {
        if (isprint(*ptr)) {
            *bptr++ = *ptr;
        } else {
            *bptr++ = '[';
            strcpy(bptr,ckctox(*ptr,1)); bptr += 2;
            *bptr++ = ']';
        }
        ptr++;
        i--;
    }
    if (length > 0) {
        *bptr = '\0';
        printf( "%s", buf );
    }
    printf( " (%d+%d)\n", offset, length );

    if (buf) { free(buf); buf = NULL; }
    return;
}

/*
 * only for debugging
 * print as much useful information about a packet as possible
 */
x25dump_prim(primitive)    N_npi_ctl_t *primitive; {
    printf("Primitive");
    switch (primitive->PRIM_type) {
      case N_BIND_ACK:
        printf( "\tN_BIND_ACK\n\taddress:\t" );
        x25dump_data( (char *)primitive,
                     primitive->bind_ack.ADDR_offset,
                     primitive->bind_ack.ADDR_length );
        printf( "\tproto id:\t" );
        x25dump_data( (char *)primitive,
                     primitive->bind_ack.PROTOID_offset,
                     primitive->bind_ack.PROTOID_length );
        printf( "\tconnind:\t%d\n\ttoken:\t\t%d\n",
               primitive->bind_ack.CONIND_number,
               primitive->bind_ack.TOKEN_value );
        break;

      case N_BIND_REQ:
        printf( "\tN_BIND_REQ\n\taddress:\t" );
        x25dump_data( (char *)primitive,
                     primitive->bind_req.ADDR_offset,
                     primitive->bind_req.ADDR_length );
        printf( "\tproto id:\t" );
        x25dump_data( (char *)primitive,
                     primitive->bind_req.PROTOID_offset,
                     primitive->bind_req.PROTOID_length );
        printf( "\tconnind:\t%d\n\tflags:\t\t%d\n",
               primitive->bind_req.CONIND_number,
               primitive->bind_req.BIND_flags );
        break;

      case N_CONN_CON:
        printf( "\tN_CONN_CON\n" );
        printf( "\tRES\t\t" );
        x25dump_data( (char *)primitive,
                     primitive->conn_con.RES_offset,
                     primitive->conn_con.RES_length );
        printf( "\tflags:\t%d\n", primitive->conn_con.CONN_flags );
        break;

      case N_CONN_IND:
        printf( "\tN_CONN_IND\n" );
        printf( "\tsource:\t\t" );
        x25dump_data( (char *)primitive,
                     primitive->conn_ind.SRC_offset,
                     primitive->conn_ind.SRC_length );
        printf( "\tdestination:\t" );
        x25dump_data( (char *)primitive,
                     primitive->conn_ind.DEST_offset,
                     primitive->conn_ind.DEST_length );
        printf( "\tSEQ_number:\t%d\n", primitive->conn_ind.SEQ_number );
        printf( "\tflags:\t%d\n", primitive->conn_ind.CONN_flags );
        break;

      case N_CONN_REQ:
        printf( "\tN_CONN_REQ\n\tdestination:\t" );
        x25dump_data( (char *)primitive,
                     primitive->conn_req.DEST_offset,
                     primitive->conn_req.DEST_length );
        printf( "\tflags:\t%d\n", primitive->conn_req.CONN_flags );
        break;

      case N_CONN_RES:
        printf( "\tN_CONN_RES\n" );
        printf( "\tTOKEN_value\t%d\n", primitive->conn_res.TOKEN_value );
        printf( "\tSEQ_number\t%d\n", primitive->conn_res.SEQ_number );
        printf( "\tCONN_flags\t%d\n", primitive->conn_res.CONN_flags );
        printf( "\tRES\t\t" );
        x25dump_data( (char *)primitive,
                     primitive->conn_res.RES_offset,
                     primitive->conn_res.RES_length );
        break;

      case N_DATACK_IND:
        printf( "\tN_DATACK_IND\n" );
        break;

      case N_DATACK_REQ:
        printf( "\tN_DATACK_REQ\n" );
        printf( "\tflags:\t%d\n", primitive->data_req.DATA_xfer_flags );
        break;

      case N_DATA_IND:
        printf( "\tN_DATA_IND\n" );
        printf( "\tflags:\t%d\n", primitive->data_ind.DATA_xfer_flags );
        break;

      case N_DATA_REQ:
        printf( "\tN_DATA_REQ\n" );
        break;

      case N_DISCON_IND:
        printf( "\tN_DISCON_IND\n" );
        printf( "\torigin:\t%d\n", primitive->discon_ind.DISCON_orig );
        printf( "\treason:\t\t%d\n", primitive->discon_ind.DISCON_reason );
        printf( "\tseq no:\t\t%d\n", primitive->discon_ind.SEQ_number );
        printf( "\tRES:\t" );
        x25dump_data( (char *)primitive,
                     primitive->discon_ind.RES_offset,
                     primitive->discon_ind.RES_length );
        break;

      case N_DISCON_REQ:
        printf( "\tN_DISCON_REQ\n" );
        printf( "\tDISCON_reason:\t%d\n",
               primitive->discon_req.DISCON_reason );
        printf( "\tRES:\t" );
        x25dump_data( (char *)primitive,
                     primitive->discon_req.RES_offset,
                     primitive->discon_req.RES_length );
        printf( "\tSEQ_number:\t%d\n", primitive->discon_req.SEQ_number );
        break;

      case N_ERROR_ACK:
        printf( "\tN_ERROR_ACK\n" );
        printf( "\tCaused by:\t%s\n",
               x25prim( primitive->error_ack.ERROR_prim ) );
        printf( "\tNPI error:\t%s\n",
               x25err( primitive->error_ack.NPI_error ));
        errno = primitive->error_ack.UNIX_error;
        perror( "\t" );
        break;

      case N_EXDATA_IND:
        printf( "\tN_EXDATA_ACK\n" );
        break;

      case N_EXDATA_REQ:
        printf( "\tN_EXDATA_REQ\n" );
        break;

      case N_INFO_ACK:
        printf( "\tN_INFO_ACK\n" );
        printf( "\tNSDU size:\t%d\n", primitive->info_ack.NSDU_size );
        printf( "\tENSDU size:\t%d\n", primitive->info_ack.ENSDU_size );
        printf( "\tCDATA size:\t%d\n", primitive->info_ack.CDATA_size );
        printf( "\tDDATA size:\t%d\n", primitive->info_ack.DDATA_size );
        printf( "\tADDR size:\t%d\n", primitive->info_ack.ADDR_size );
        printf( "\tNIDU size:\t%d\n", primitive->info_ack.NIDU_size );
        break;

      case N_INFO_REQ:
        printf( "\tN_INFO_REQ\n" );
        break;

      case N_OK_ACK:
        printf( "\tN_OK_ACK\n" );
        break;

      case N_OPTMGMT_REQ:
        printf( "\tN_OPTMGMT_REQ\n" );
        break;

      case N_RESET_CON:
        printf( "\tN_RESET_CON\n" );
        break;

      case N_RESET_IND:
        printf( "\tN_RESET_IND\n" );
        printf( "\treason:\t\t%d\n", primitive->reset_ind.RESET_reason );
        printf( "\torigin:\t\t%d\n", primitive->reset_ind.RESET_orig );
        break;

      case N_RESET_REQ:
        printf( "\tN_RESET_REQ\n" );
        printf( "\treason:\t\t%d\n", primitive->reset_req.RESET_reason );
        break;

      case N_RESET_RES:
        printf( "\tN_RESET_RES\n" );
        break;

      case N_UDERROR_IND:
        printf( "\tN_UDERROR_IND\n" );
        break;

      case N_UNBIND_REQ:
        printf( "\tN_UNBIND_REQ\n" );
        break;

      case N_UNITDATA_REQ:
        printf( "\tN_UNITDATA_REQ\n" );
        break;

      case N_UNITDATA_IND:
        printf( "\tN_UNITDATA_IND\n" );
        break;

      default:
        (void) printf( "Unknown NPI error %d", primitive->PRIM_type );
        return 0;
    }
}
#endif /* DEBUG */

/* it looks like signal handling is not needed with streams! */
/* x25oobh()    - handle SIGURG signals - take from isode ? */

#endif /* IBMX25 */

#ifndef NOHTTP
/*
  Which time.h files to include... See ckcdeb.h for defaults.
  Note that 0, 1, 2, or all 3 of these can be included according to
  the symbol definitions.
*/
#ifndef NOTIMEH
#ifdef TIMEH
#include <time.h>
#endif /* TIMEH */
#endif /* NOTIMEH */

#ifndef NOSYSTIMEH
#ifdef SYSTIMEH
#include <sys/time.h>
#endif /* SYSTIMEH */
#endif /* NOSYSTIMEH */

#ifndef NOSYSTIMEBH
#ifdef SYSTIMEBH
#include <sys/timeb.h>
#endif /* SYSTIMEBH */
#endif /* NOSYSTIMEBH */

#ifndef TIMEH
#ifndef SYSTIMEH
#ifndef SYSTIMEBH
#ifdef Plan9
#include <sys/time.h>
#else
#ifdef AIX41
#include <time.h>
#else
#ifdef SUNOS4
#include <sys/time.h>
#else
#ifdef SYSTIMEH
#include <sys/time.h>
#else
#ifdef POSIX
#include <posix/time.h>
#else
#ifdef CLIX
#include <sys/time.h>
#else
#ifdef OS2
#include <time.h>
#else
#include <time.h>
/* #include <utime.h> */
#endif /* OS2 */
#endif /* CLIX */
#endif /* POSIX */
#endif /* SYSTIMEH */
#endif /* SUNOS4 */
#endif /* AIX41 */
#endif /* Plan9 */
#endif
#endif
#endif

#ifdef OS2
#include <sys/utime.h>
#ifdef NT
#define utimbuf _utimbuf
#endif /* NT */
#define utime   _utime
#else
#ifdef SYSUTIMEH                        /* <sys/utime.h> if requested,  */
#include <sys/utime.h>                  /* for extra fields required by */
#else                                   /* 88Open spec. */
#ifdef UTIMEH                           /* or <utime.h> if requested */
#include <utime.h>                      /* (SVR4, POSIX) */
#define SYSUTIMEH                       /* Use this for both cases. */
#endif /* UTIMEH */
#endif /* SYSUTIMEH */
#endif /* OS2 */

#ifdef VMS				/* SMS 2007/02/15 */
#include "ckvrtl.h"
#endif /* def VMS */

#ifndef HTTP_VERSION
#define HTTP_VERSION "HTTP/1.1"
#endif /* HTTP_VERSION */

#ifdef CMDATE2TM
time_t
#ifdef CK_ANSIC
http_date(char * date)
#else
http_date(date) char * date;
#endif /* CK_ANSIC */
/* http_date */ {
    /* HTTP dates are of the form:  "Sun, 06 Oct 1997 20:11:47 GMT" */
    /* There are two older formats which we are required to parse
     * that we currently do not:
     *
     * RFC 850:   "Sunday, 06-Oct-97 20:11:47 GMT"
     * asctime(): "Sun Nov  6 20:11:47 1997"
     *
     * However, it is required that all dates be sent in the form we
     * do accept.  The other two formats are for compatibility with
     * really old servers.
     */
    extern char cmdatebuf[18];
    struct tm t_tm;
    time_t t;
    char ldate[32];
    int j;

    j = ckindex(",",date,0,0,0);
    ckstrncpy(ldate,&date[j+1],25);

    {   /*
           cmcvtate() date changed to return a string pointer.
           fdc, 12 Aug 2001.
        */
        char * dp;
        dp = (char *)cmcvtdate(ldate,0); /* Convert to normal form */
        if (!dp)
          return(0);
        t_tm = *cmdate2tm(dp,1);
    }
/*
  From Lucas Hart, 5 Dec 2001:
  "On the systems to which I have access (SunOS 4.1.1, Solaris 8, and Tru64),
  setting tm_isdst to -1 maintains the correct timezone offsets, i.e., writes
  the specified (GMT) time if the buffer size is 21, or the contemporaneous
  localtime if the buffer size is 25.  Perhaps tm_isdst should be set in
  cmdate2tm(), rather than only in http_date."
*/
#ifndef NOTM_ISDST                      /* For platforms where */
    t_tm.tm_isdst = -1;                 /* tm_isdst doesn't exist. */
#endif /* NOTM_ISDST */

    t = mktime(&t_tm);                  /* NOT PORTABLE */

#ifdef XX_TIMEZONE
    t -= _timezone;
#endif /* XX_TIMEZONE */

    return(t);
}
#endif /* CMDATE2TM */

char *
http_now() {
    static char nowstr[32];
#ifdef CMDATE2TM
    struct tm  *gmt;
    time_t ltime;                       /* NOT PORTABLE */

    time(&ltime);

    gmt = gmtime(&ltime);               /* PROBABLY NOT PORTABLE */
    strftime(nowstr,32,"%a, %d %b %Y %H:%M:%S GMT",gmt); /* NOT PORTABLE */
    /* not only is it not portable but it's locale-dependent */
#else
/*
  This is hopeless.  First of all, it seems that HTTP wants Day and Month
  NAMES?  In English?  Whose idea was that?  Even worse, the date/time must be
  expressed in Zulu (UTC (GMT)), and converting from local time to GMT is a
  nightmare.  Every platform does it differently, if at all -- even if we
  restrict ourselves to UNIX.  For example (quoting from recent C-Kermit edit
  history), "Fixed a longstanding bug in the BSDI version, in which incoming
  file dates were set in GMT rather than local time.  It seems in 4.4BSD,
  localtime() does not return the local time, but rather Zero Meridian (Zulu)
  time (GMT), and must be adjusted by the tm_gmtoff value."  Swell.  For
  greater appreciation of the scope of the problem, just take a look at the
  time-related #ifdefs in ckutio.c.  The only right way to do this is to add
  our own portable API for converting between local time and GMT/UTC/Zulu
  that shields us not only from UNIXisms like time_t and struct tm, but also
  the unbelievable amount of differences in time-related APIs -- e.g. is
  "timezone" an external variable or a function; which header file(s) do we
  include, etc etc etc.  It's a major project.
*/
    int x;
    x = cmcvtdate("",1);

Evidently this code is not used -- if it is, it must be fixed to use
new (aug 2001) cmcvtdate() calling conventions.

    if (x < 0)
      return("");
/*  yyyymmdd hh:mm:ss */
/*  01234567890123456 */
    nowstr[0]  = 'X';                   /* 1st letter of day */
    nowstr[1]  = 'x';                   /* 2nd letter of day */
    nowstr[2]  = 'x';                   /* 3rd letter of day */
    nowstr[3]  = ',';
    nowstr[4]  = ' ';
    nowstr[5]  = cmdate[6];
    nowstr[6]  = cmdate[7];
    nowstr[7]  = ' ';
    nowstr[8]  = ' ';                   /* first letter of month */
    nowstr[9]  = ' ';                   /* second letter of month */
    nowstr[10] = ' ';                   /* third letter of month */
    nowstr[11] = ' ';
    nowstr[12] = cmdate[0];
    nowstr[13] = cmdate[1];
    nowstr[14] = cmdate[2];
    nowstr[15] = cmdate[3];
    nowstr[16] = ' ';
    nowstr[17] = cmdate[9];
    nowstr[18] = cmdate[10];
    nowstr[19] = cmdate[11];
    nowstr[20] = cmdate[12];
    nowstr[21] = cmdate[13];
    nowstr[22] = cmdate[14];
    nowstr[23] = cmdate[15];
    nowstr[24] = cmdate[16];
    nowstr[25] = ' ';
    nowstr[26] = 'G';
    nowstr[27] = 'M';
    nowstr[28] = 'T';
    nowstr[29] = '\0';
#endif /* CMDATE2TM */
    return(nowstr);
}

#ifndef OS2
#ifndef CK_AUTHENTICATION
/* from ckuusr.h, which this module normally doesn't include */
_PROTOTYP( int dclarray, (char, int) );
#endif /* CK_AUTHENTICATION */
#endif /* OS2 */
/*
  Assign http response pairs to given array.
  For best results, response pairs should contain no spaces.

  Call with:
    resp  =  pointer to response list.
    n     =  size of response list.
    array =  array letter.
  Returns:
    0 on failure.
    >= 1, size of array, on success.
*/
static int
#ifdef CK_ANSIC
http_mkarray(char ** resp, int n, char array)
#else
http_mkarray(resp, n, array) char ** resp; int n; char array;
#endif /* CK_ANSIC */
{
#ifndef NOSPL
    int i, x;
    char ** ap;
    extern char ** a_ptr[];
    extern int a_dim[];

    if (!array || n <= 0)
      return(0);
    if ((x = dclarray(array,n)) < 0) {
        printf("?Array declaration failure\n");
        return(-9);
    }
    /* Note: argument array is 0-based but Kermit array is 1-based */
    ap = a_ptr[x];
    ap[0] = NULL;                       /* 0th element is empty */
    for (i = 1; i <= n; i++) {
        ap[i] = resp[i-1];              /* If resp elements were malloc'd */
        resp[i-1] = NULL;
    }
    a_dim[x] = n;
    return(n);
#else
    return(0);
#endif /* NOSPL */
}

#define HTTPHEADCNT 64
int
http_get_chunk_len()
{
    int len = 0;
    int i = 0, j = -1;
    char buf[24];
    int ch;

    while ((ch = http_inc(0)) >= 0 && i < 24) {
        buf[i] = ch;
        if ( buf[i] == ';' )            /* Find chunk-extension (if any) */
            j = i;
        if ( buf[i] == 10 ) {           /* found end of line */
            if (i > 0 && buf[i-1] == 13)
                i--;
            buf[i] = '\0';
            break;
        }
        i++;
    }
    if ( i < 24 ) {                     /* buf now contains len in Hex */
        len = hextoulong(buf, j == -1 ? i : j-1);
    }

    return(len);
}

int
http_isconnected()
{
    return(httpfd != -1);
}

char *
http_host()
{
    return(httpfd != -1 ? http_host_port : "");
}

char *
http_security()
{
    if ( httpfd == -1 )
        return("NULL");
#ifdef CK_SSL
    if (tls_http_active_flag) {
        SSL_CIPHER * cipher;
        const char *cipher_list;
        static char buf[128];
        buf[0] = NUL;
        cipher = SSL_get_current_cipher(tls_http_con);
        cipher_list = SSL_CIPHER_get_name(cipher);
        SSL_CIPHER_description(cipher,buf,sizeof(buf));
        return(buf);
    }
#endif /* CK_SSL */
    return("NULL");
}

int
http_reopen()
{
    int rc = 0;
    char * s = NULL;                    /* strdup is not portable */
    if ( tcp_http_proxy ) {
        char * p;
        makestr(&s,(char *)http_host_port);
        p = s;
        while (*p != '\0' && *p != ':') p++; /* Look for colon */
        if (*p == ':') {                     /* Have a colon */
            *p++ = '\0';                     /* Get service name or number */
        } else {
            p="http";
        }
        rc = http_open(s,p,http_ssl,NULL,0,http_agent);
    } else {
        makestr(&s,(char *)http_ip);
        rc = http_open(s,ckuitoa(http_port),http_ssl,NULL,0,http_agent);
    }
    free(s);
    return(rc);
}


int
#ifdef CK_ANSIC
http_open(char * hostname, char * svcname, int use_ssl, char * rdns_name,
          int rdns_len, char * agent)
#else /* CK_ANSIC */
http_open(hostname, svcname, use_ssl, rdns_name, rdns_len, agent)
    char * hostname;
    char * svcname;
    int    use_ssl;
    char * rdns_name;
    int    rdns_len;
    char * agent;
#endif /* CK_ANSIC */
{
    char namecopy[NAMECPYL];
    char *p;
    int i, x, dns = 0;
#ifdef TCPSOCKET
    int isconnect = 0;
#ifdef SO_OOBINLINE
    int on = 1;
#endif /* SO_OOBINLINE */
    struct servent *service=NULL;
    struct hostent *host=NULL;
    struct sockaddr_in r_addr;
    struct sockaddr_in sin;
    struct sockaddr_in l_addr;
    GSOCKNAME_T l_slen;
#ifdef EXCELAN
    struct sockaddr_in send_socket;
#endif /* EXCELAN */

#ifdef INADDRX
/* inet_addr() is of type struct in_addr */
#ifdef datageneral
    extern struct in_addr inet_addr();
#else
#ifdef HPUX5WINTCP
    extern struct in_addr inet_addr();
#endif /* HPUX5WINTCP */
#endif /* datageneral */
    struct in_addr iax;
#else
#ifdef INADDR_NONE
    struct in_addr iax;
#else /* INADDR_NONE */
    long iax;
#endif /* INADDR_NONE */
#endif /* INADDRX */

    if ( rdns_name == NULL || rdns_len < 0 )
        rdns_len = 0;

    *http_ip = '\0';                     /* Initialize IP address string */
    namecopy[0] = '\0';

#ifdef DEBUG
    if (deblog) {
        debug(F110,"http_open hostname",hostname,0);
        debug(F110,"http_open svcname",svcname,0);
    }
#endif /* DEBUG */
    if (!hostname) hostname = "";
    if (!svcname) svcname = "";
    if (!*hostname || !*svcname) return(-1);

    
    service = ckgetservice(hostname,svcname,http_ip,20);

    if (service == NULL) {
        if ( !quiet )
            printf("?Invalid service: %s\r\n",svcname);
        return(-1);
    }

    /* For HTTP connections we must preserve the original hostname and */
    /* service requested so we can include them in the Host header.    */
    ckmakmsg(http_host_port,sizeof(http_host_port),hostname,":",
              ckuitoa(ntohs(service->s_port)),NULL);
    http_port = ntohs(service->s_port);
    http_ssl = use_ssl;
    debug(F111,"http_open",http_host_port,http_port);

    /* 'http_ip' contains the IP address to which we want to connect        */
    /* 'svcnam'   contains the service name                                 */
    /* 'service->s_port' contains the port number in network byte order     */

    /* If we are using an http proxy, we need to create a buffer containing */
    /*   hostname:port-number                                               */
    /* to pass to the http_connect() function.  Then we need to replace     */
    /* 'namecopy' with the name of the proxy server and the service->s_port */
    /* with the port number of the proxy (default port 80).                 */

    if ( tcp_http_proxy ) {

        ckmakmsg(proxycopy,sizeof(proxycopy),hostname,":",
                 ckuitoa(ntohs(service->s_port)),NULL);
        ckstrncpy(namecopy,tcp_http_proxy,NAMECPYL);

        p = namecopy;                       /* Was a service requested? */
        while (*p != '\0' && *p != ':') p++; /* Look for colon */
        if (*p == ':') {                    /* Have a colon */
            debug(F110,"http_open name has colon",namecopy,0);
            *p++ = '\0';                    /* Get service name or number */
        } else {
            strcpy(++p,"http");
        }

        service = ckgetservice(namecopy,p,http_ip,20);
        if (!service) {
            fprintf(stderr, "Can't find port for service %s\n", p);
#ifdef TGVORWIN
            debug(F101,"http_open can't get service for proxy","",socket_errno);
#else
            debug(F101,"http_open can't get service for proxy","",errno);
#endif /* TGVORWIN */
            errno = 0;                  /* (rather than mislead) */
            return(-1);
        }

        /* copy the proxyname and remove the service if any so we can use 
         * it as the hostname 
         */
        ckstrncpy(namecopy,tcp_http_proxy,NAMECPYL);
        p = namecopy;                       /* Was a service requested? */
        while (*p != '\0' && *p != ':') p++; /* Look for colon */
        if (*p == ':') {                    /* Have a colon */
            *p = '\0';                      /* terminate string */
        }        
        hostname = namecopy;                /* use proxy as hostname */
    }

    /* Set up socket structure and get host address */
    bzero((char *)&r_addr, sizeof(r_addr));
    debug(F100,"http_open bzero ok","",0);

#ifdef INADDR_NONE
    debug(F101,"http_open INADDR_NONE defined","",INADDR_NONE);
#else /* INADDR_NONE */
    debug(F100,"http_open INADDR_NONE not defined","",0);
#endif /* INADDR_NONE */
#ifdef INADDRX
    debug(F100,"http_open INADDRX defined","",0);
#else /* INADDRX */
    debug(F100,"http_open INADDRX not defined","",0);
#endif /* INADDRX */

#ifndef NOMHHOST
#ifdef INADDRX
    iax = inet_addr(http_ip[0]?http_ip:hostname);
    debug(F111,"http_open inet_addr",http_ip[0]?http_ip:hostname,iax.s_addr);
#else /* INADDRX */
#ifdef INADDR_NONE
    iax.s_addr = inet_addr(http_ip[0]?http_ip:hostname);
    debug(F111,"http_open inet_addr",http_ip[0]?http_ip:hostname,iax.s_addr);
#else /* INADDR_NONE */
#ifndef datageneral
    iax = (unsigned int) inet_addr(http_ip[0]?http_ip:hostname);
#else
    iax = -1L;
#endif /* datageneral */
    debug(F111,"http_open inet_addr",http_ip[0]?http_ip:hostname,iax);
#endif /* INADDR_NONE */
#endif /* INADDRX */

    dns = 0;
    if (
#ifdef INADDR_NONE
/* This might give warnings on 64-bit platforms but they should be harmless */
/* because INADDR_NONE should be all 1's anyway, thus the OR part is */
/* probably superfluous -- not sure why it's even there, maybe it should be */
/* removed. */
        iax.s_addr == INADDR_NONE /* || iax.s_addr == (unsigned long) -1L */
#else /* INADDR_NONE */
        iax == -1
#endif /* INADDR_NONE */
        ) {
        if (!quiet) {
            printf(" DNS Lookup... ");
            fflush(stdout);
        }
        if ((host = gethostbyname(http_ip[0] ? http_ip : hostname)) != NULL) {
            debug(F100,"http_open gethostbyname != NULL","",0);
            host = ck_copyhostent(host);
            dns = 1;                    /* Remember we performed dns lookup */
            r_addr.sin_family = host->h_addrtype;
            if (tcp_rdns && host->h_name && host->h_name[0] && (rdns_len > 0)
                 && (tcp_http_proxy == NULL)
                 )
                ckmakmsg(rdns_name,rdns_len,host->h_name,":",svcname,NULL);

#ifdef HADDRLIST
#ifdef h_addr
            /* This is for trying multiple IP addresses - see <netdb.h> */
            if (!(host->h_addr_list))
              return(-1);
            bcopy(host->h_addr_list[0],
                  (caddr_t)&r_addr.sin_addr,
                  host->h_length
                  );
#else
            bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
#endif /* h_addr */
#else  /* HADDRLIST */
            bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
#endif /* HADDRLIST */
#ifdef COMMENT
#ifndef EXCELAN
            debug(F111,"BCOPY","host->h_addr",host->h_addr);
#endif /* EXCELAN */
            debug(F111,"BCOPY"," (caddr_t)&r_addr.sin_addr",
                  (caddr_t)&r_addr.sin_addr);
            debug(F111,"BCOPY"," r_addr.sin_addr.s_addr",
                  r_addr.sin_addr.s_addr);
#endif	/* COMMENT */
            debug(F111,"BCOPY","host->h_length",host->h_length);
        }
    }
#endif /* NOMHHOST */

    if (!dns) {
#ifdef INADDRX
/* inet_addr() is of type struct in_addr */
        struct in_addr ina;
        unsigned long uu;
        debug(F100,"http_open gethostbyname == NULL: INADDRX","",0);
        ina = inet_addr(http_ip[0]?http_ip:hostname);
        uu = *(unsigned int *)&ina;
#else /* Not INADDRX */
/* inet_addr() is unsigned long */
        unsigned long uu;
        debug(F100,"http_open gethostbyname == NULL: Not INADDRX","",0);
        uu = inet_addr(http_ip[0]?http_ip:hostname);
#endif /* INADDRX */
        debug(F101,"http_open uu","",uu);
        if (
#ifdef INADDR_NONE
            !(uu == INADDR_NONE || uu == (unsigned int) -1L)
#else   /* INADDR_NONE */
            uu != ((unsigned long)-1)
#endif /* INADDR_NONE */
            ) {
            r_addr.sin_addr.s_addr = uu;
            r_addr.sin_family = AF_INET;
        } else {
#ifdef VMS
            fprintf(stdout, "\r\n");    /* complete any previous message */
#endif /* VMS */
            fprintf(stderr, "Can't get address for %s\n",
                     http_ip[0]?http_ip:hostname);
#ifdef TGVORWIN
            debug(F101,"http_open can't get address","",socket_errno);
#else
            debug(F101,"http_open can't get address","",errno);
#endif /* TGVORWIN */
            errno = 0;                  /* Rather than mislead */
            return(-1);
        }
    }

    /* Get a file descriptor for the connection. */

    r_addr.sin_port = service->s_port;
    ckstrncpy(http_ip,(char *)inet_ntoa(r_addr.sin_addr),20);
    debug(F110,"http_open trying",http_ip,0);
    if (!quiet && *http_ip) {
        printf(" Trying %s... ", http_ip);
        fflush(stdout);
    }

    /* Loop to try additional IP addresses, if any. */

    do {
#ifdef EXCELAN
        send_socket.sin_family = AF_INET;
        send_socket.sin_addr.s_addr = 0;
        send_socket.sin_port = 0;
        if ((httpfd = socket(SOCK_STREAM, (struct sockproto *)0,
                            &send_socket, SO_REUSEADDR)) < 0)
#else  /* EXCELAN */
        if ((httpfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
#endif /* EXCELAN */
            {
#ifdef EXCELAN
                experror("TCP socket error");
#else
#ifdef TGVORWIN
#ifdef OLD_TWG
                errno = socket_errno;
#endif /* OLD_TWG */
                socket_perror("TCP socket error");
                debug(F101,"http_open socket error","",socket_errno);
#else
                perror("TCP socket error");
                debug(F101,"http_open socket error","",errno);
#endif /* TGVORWIN */
#endif /* EXCELAN */
                return (-1);
            }
        errno = 0;

       /* If a specific TCP address on the local host is desired we */
       /* must bind it to the socket.                               */
#ifndef datageneral
         if (tcp_address) {
             int s_errno;

             debug(F110,"http_open binding socket to",tcp_address,0);
             bzero((char *)&sin,sizeof(sin));
             sin.sin_family = AF_INET;
#ifdef INADDRX
             inaddrx = inet_addr(tcp_address);
             sin.sin_addr.s_addr = *(unsigned long *)&inaddrx;
#else
             sin.sin_addr.s_addr = inet_addr(tcp_address);
#endif /* INADDRX */
             sin.sin_port = 0;
             if (bind(httpfd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
                 s_errno = socket_errno; /* Save error code */
#ifdef TCPIPLIB
                 socket_close(httpfd);
#else /* TCPIPLIB */
                 close(httpfd);
#endif /* TCPIPLIB */
                 httpfd = -1;
                 errno = s_errno;       /* and report this error */
                 debug(F101,"http_open bind errno","",errno);
                 return(-1);
             }
         }
#endif /* datageneral */

/* Now connect to the socket on the other end. */

#ifdef EXCELAN
        if (connect(httpfd, &r_addr) < 0)
#else
#ifdef NT
          WSASafeToCancel = 1;
#endif /* NT */
        if (connect(httpfd, (struct sockaddr *)&r_addr, sizeof(r_addr)) < 0)
#endif /* EXCELAN */
          {
#ifdef NT
              WSASafeToCancel = 0;
#endif /* NT */
#ifdef OS2
              i = socket_errno;
#else /* OS2 */
#ifdef TGVORWIN
              i = socket_errno;
#else
              i = errno;                /* Save error code */
#endif /* TGVORWIN */
#endif /* OS2 */
#ifdef HADDRLIST
#ifdef h_addr
              if (host && host->h_addr_list && host->h_addr_list[1]) {
                  perror("");
                  host->h_addr_list++;
                  bcopy(host->h_addr_list[0],
                        (caddr_t)&r_addr.sin_addr,
                        host->h_length);

                  ckstrncpy(http_ip,(char *)inet_ntoa(r_addr.sin_addr),20);
                  debug(F110,"http_open h_addr_list",http_ip,0);
                  if (!quiet && *http_ip) {
                      printf(" Trying %s... ", http_ip);
                      fflush(stdout);
                  }
#ifdef TCPIPLIB
                  socket_close(httpfd); /* Close it. */
#else
                  close(httpfd);
#endif /* TCPIPLIB */
                  continue;
              }
#endif /* h_addr */
#endif  /* HADDRLIST */
              http_close();
              httpfd = -1;
              errno = i;                /* And report this error */
#ifdef EXCELAN
              if (errno) experror("http_open connect");
#else
#ifdef TGVORWIN
              debug(F101,"http_open connect error","",socket_errno);
              /* if (errno) socket_perror("http_open connect"); */
#ifdef OLD_TWG
              errno = socket_errno;
#endif /* OLD_TWG */
              if (!quiet)
                socket_perror("http_open connect");
#else /* TGVORWIN */
              debug(F101,"http_open connect errno","",errno);
#ifdef VMS
              if (!quiet)
                perror("\r\nFailed");
#else
              if (!quiet)
                perror("Failed");
#endif /* VMS */
#ifdef DEC_TCPIP
              if (!quiet)
                perror("http_open connect");
#endif /* DEC_TCPIP */
#ifdef CMU_TCPIP
              if (!quiet)
                perror("http_open connect");
#endif /* CMU_TCPIP */
#endif /* TGVORWIN */
#endif /* EXCELAN */
              return(-1);
          }
#ifdef NT
        WSASafeToCancel = 0;
#endif /* NT */
        isconnect = 1;
    } while (!isconnect);

#ifdef NON_BLOCK_IO
    on = 1;
    x = socket_ioctl(httpfd,FIONBIO,&on);
    debug(F101,"http_open FIONBIO","",x);
#endif /* NON_BLOCK_IO */

    /* We have succeeded in connecting to the HTTP PROXY.  So now we   */
    /* need to attempt to connect through the proxy to the actual host */
    /* If that is successful, we have to pretend that we made a direct */
    /* connection to the actual host.                                  */

    if ( tcp_http_proxy ) {
#ifdef OS2
        if (!agent) 
	  agent = "Kermit 95";	/* Default user agent */
#else
        if (!agent) 
	  agent = "C-Kermit";
#endif /* OS2 */

        if (http_connect(httpfd,
                         tcp_http_proxy_agent ? tcp_http_proxy_agent : agent,
                         NULL,
                         tcp_http_proxy_user,
                         tcp_http_proxy_pwd,
                         0,
                         proxycopy
                         ) < 0) {
            http_close();
            return(-1);
        }
    }

#ifdef SO_OOBINLINE
    /* See note on SO_OOBINLINE in netopen() */
#ifdef datageneral
    setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
#else
#ifdef BSD43
    setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
#else
#ifdef OSF1
    setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
#else
#ifdef POSIX
    setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
#else
#ifdef MOTSV88R4
    setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
#else
#ifdef SOLARIS
/*
  Maybe this applies to all SVR4 versions, but the other (else) way has been
  compiling and working fine on all the others, so best not to change it.
*/
    setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
#else
#ifdef OSK
    setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
#else
#ifdef OS2
    {
        int rc;
        rc = setsockopt(httpfd,
                        SOL_SOCKET,
                        SO_OOBINLINE,
                        (char *) &on,
                        sizeof on
                        );
        debug(F111,"setsockopt SO_OOBINLINE",on ? "on" : "off" ,rc);
    }
#else
#ifdef VMS /* or, at least, VMS with gcc */
    setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
#else
#ifdef CLIX
    setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
#else
    setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE, &on, sizeof on);
#endif /* CLIX */
#endif /* VMS */
#endif /* OS2 */
#endif /* OSK */
#endif /* SOLARIS */
#endif /* MOTSV88R4 */
#endif /* POSIX */
#endif /* BSD43 */
#endif /* OSF1 */
#endif /* datageneral */
#endif /* SO_OOBINLINE */

#ifndef NOTCPOPTS
#ifndef datageneral
#ifdef SOL_SOCKET
#ifdef TCP_NODELAY
    no_delay(ttyfd,tcp_nodelay);
#endif /* TCP_NODELAY */
#ifdef SO_KEEPALIVE
    keepalive(ttyfd,tcp_keepalive);
#endif /* SO_KEEPALIVE */
#ifdef SO_LINGER
    ck_linger(ttyfd,tcp_linger, tcp_linger_tmo);
#endif /* SO_LINGER */
#ifdef SO_SNDBUF
    sendbuf(ttyfd,tcp_sendbuf);
#endif /* SO_SNDBUF */
#ifdef SO_RCVBUF
    recvbuf(ttyfd,tcp_recvbuf);
#endif /* SO_RCVBUF */
#endif /* SOL_SOCKET */
#endif /* datageneral */
#endif /* NOTCPOPTS */

#ifndef datageneral
    /* Find out our own IP address. */
    /* We need the l_addr structure for [E]KLOGIN. */
    l_slen = sizeof(l_addr);
    bzero((char *)&l_addr, l_slen);
#ifndef EXCELAN
    if (!getsockname(httpfd, (struct sockaddr *)&l_addr, &l_slen)) {
        char * s = (char *)inet_ntoa(l_addr.sin_addr);
        ckstrncpy(myipaddr, s, 20);
        debug(F110,"getsockname",myipaddr,0);
    }
#endif /* EXCELAN */
#endif /* datageneral */

/* See note in netopen() on Reverse DNS lookups */
     if (tcp_rdns == SET_ON) {
#ifdef NT
        if (isWin95())
          sleep(1);
#endif /* NT */
        if (!quiet) {
            printf(" Reverse DNS Lookup... ");
            fflush(stdout);
        }
        if (host = gethostbyaddr((char *)&r_addr.sin_addr,4,PF_INET)) {
            char * s;
            host = ck_copyhostent(host);
            debug(F100,"http_open gethostbyname != NULL","",0);
            if (!quiet) {
                printf("(OK)\n");
                fflush(stdout);
            }
            s = host->h_name;
            if (!s) {                   /* This can happen... */
                debug(F100,"http_open host->h_name is NULL","",0);
                s = "";
            }
            /* Something is wrong with inet_ntoa() on HPUX 10.xx */
            /* The compiler says "Integral value implicitly converted to */
            /* pointer in assignment."  The prototype is right there */
            /* in <arpa/inet.h> so what's the problem? */
            /* Ditto in HP-UX 5.x, but not 8.x or 9.x... */
            if (!*s) {                  /* No name so substitute the address */
                debug(F100,"http_open host->h_name is empty","",0);
                s = inet_ntoa(r_addr.sin_addr); /* Convert address to string */
                if (!s)                 /* Trust No 1 */
                  s = "";
                if (*s) {               /* If it worked, use this string */
                    ckstrncpy(http_ip,s,20);
                }
                s = http_ip;             /* Otherwise stick with the IP */
                if (!*s)                 /* or failing that */
                  s = http_host_port;    /* the name we were called with. */
            }
            if (*s)                     /* return the rdns name */
                ckmakmsg(rdns_name,rdns_len,s,":",svcname,NULL);

            if (!quiet && *s
#ifndef NOICP
                && !doconx
#endif /* NOICP */
                ) {
                printf(" %s connected on port %s\n",s,
                       ckuitoa(ntohs(service->s_port)));
#ifdef BETADEBUG
                /* This is simply for testing the DNS entries */
                if (host->h_aliases) {
                    char ** a = host->h_aliases;
                    while (*a) {
                        printf(" alias => %s\n",*a);
                        a++;
                    }
                }
#endif /* BETADEBUG */
            }
        } else {
            if (!quiet) printf("Failed.\n");
        }
    } else if (!quiet) printf("(OK)\n");
    if (!quiet) fflush(stdout);


    if ( tcp_http_proxy ) {
        /* Erase the IP address since we cannot reuse it */
        http_ip[0] = '\0';
    } else {
        /* This should already have been done but just in case */
        ckstrncpy(http_ip,(char *)inet_ntoa(r_addr.sin_addr),20);
    }
    makestr(&http_agent,agent);

#ifdef CK_SSL
    if (use_ssl && ck_ssleay_is_installed()) {
        if (!ssl_http_init(hostname)) {
            if (bio_err!=NULL) {
                BIO_printf(bio_err,"ssl_tn_init() failed\n");
                ERR_print_errors(bio_err);
            } else {
                fflush(stderr);
                fprintf(stderr,"ssl_tn_init() failed\n");
                ERR_print_errors_fp(stderr);
            }
            http_close();
            return(-1);
        } else if ( ck_ssl_http_client(httpfd,hostname) < 0 ) {
            http_close();
            return(-1);
        }
    }
#endif /* CK_SSL */
#endif /* TCPSOCKET */

    return(0);                          /* Done. */
}

int
#ifdef CK_ANSIC
http_close(VOID)
#else /* CK_ANSIC */
http_close()
#endif /* CK_ANSIC */
{
    int x = 0;
    debug(F101,"http_close","",httpfd);

#ifdef HTTP_BUFFERING
    http_count = 0;
    http_bufp = 0;
#endif	/* HTTP_BUFFERING */

    if (httpfd == -1)                    /* Was open? */
      return(0);                        /* Wasn't. */

#ifndef OS2
    if (httpfd > -1)                     /* Was. */
#endif /* OS2 */
      {
#ifdef CK_SSL
          if (tls_http_active_flag) {
              if (ssl_debug_flag)
                BIO_printf(bio_err,"calling SSL_shutdown\n");
              SSL_shutdown(tls_http_con);
              tls_http_active_flag = 0;
          }
#endif /* CK_SSL */
#ifdef TCPIPLIB
          x = socket_close(httpfd);      /* Close it. */
#else
#ifndef OS2
          x = close(httpfd);
#endif /* OS2 */
#endif /* TCPIPLIB */
      }
    httpfd = -1;                          /* Mark it as closed. */
    /* do not erase http_host_port, http_ip, http_port so they */
    /* can be used by http_reopen() */
    return(x);
}


/* http_tol()
 * Call with s = pointer to string, n = length.
 * Returns number of bytes actually written on success, or
 * -1 on i/o error, -2 if called improperly.
 */

int
http_tol(s,n) CHAR *s; int n; {
    int count = 0;
    int len = n;
    int try = 0;

    if (httpfd == -1) {
        debug(F100,"http_tol socket is closed","",0);
        return -1;
    }
    debug(F101,"http_tol TCPIPLIB ttnet","",ttnet);
#ifdef COMMENT
    ckhexdump("http_tol",s,n);
#endif /* COMMENT */

#ifdef CK_SSL
    if (tls_http_active_flag) {
        int error, r;
        /* Write using SSL */
      ssl_retry:
          r = SSL_write(tls_http_con, s, len /* >1024?1024:len */);
        switch (SSL_get_error(tls_http_con,r)) {
          case SSL_ERROR_NONE:
            debug(F111,"http_tol","SSL_write",r);
            if ( r == len )
                return(n);
             s += r;
             len -= r;
             goto ssl_retry;
          case SSL_ERROR_WANT_WRITE:
            debug(F100,"http_tol SSL_ERROR_WANT_WRITE","",0);
	      return(-1);
          case SSL_ERROR_WANT_READ:
            debug(F100,"http_tol SSL_ERROR_WANT_READ","",0);
            return(-1);
          case SSL_ERROR_SYSCALL:
              if ( r == 0 ) { /* EOF */
                  http_close();
                  return(-2);
              } else {
                  int rc = -1;
#ifdef NT
                  int gle = GetLastError();
                  debug(F111,"http_tol SSL_ERROR_SYSCALL",
                         "GetLastError()",gle);
                  rc = os2socketerror(gle);
                  if (rc == -1)
                      rc = -2;
                  else if ( rc == -2 )
                      return -1;
#endif /* NT */
                  return(rc);
              }
          case SSL_ERROR_WANT_X509_LOOKUP:
            debug(F100,"http_tol SSL_ERROR_WANT_X509_LOOKUP","",0);
            http_close();
            return(-2);
          case SSL_ERROR_SSL:
            debug(F100,"http_tol SSL_ERROR_SSL","",0);
            http_close();
            return(-2);
          case SSL_ERROR_ZERO_RETURN:
            debug(F100,"http_tol SSL_ERROR_ZERO_RETURN","",0);
            http_close();
            return(-2);
          default:
            debug(F100,"http_tol SSL_ERROR_?????","",0);
            http_close();
            return(-2);
        }
    }
#endif /* CK_SSL */

  http_tol_retry:
    try++;                              /* Increase the try counter */

    {
#ifdef BSDSELECT
        fd_set wfds;
        struct timeval tv;

        debug(F101,"http_tol BSDSELECT","",0);
        tv.tv_usec = 0L;
        tv.tv_sec=30;
#ifdef NT
        WSASafeToCancel = 1;
#endif /* NT */
#ifdef STREAMING
      do_select:
#endif /* STREAMING */
        FD_ZERO(&wfds);
        FD_SET(httpfd, &wfds);
        if (select(FD_SETSIZE, NULL,
#ifdef __DECC
#ifndef __DECC_VER
                    (int *)
#endif /* __DECC_VER */
#endif /* __DECC */
                   &wfds, NULL, &tv) < 0) {
            int s_errno = socket_errno;
            debug(F101,"http_tol select failed","",s_errno);
#ifdef BETADEBUG
            printf("http_tol select failed: %d\n", s_errno);
#endif /* BETADEBUG */
#ifdef NT
            WSASafeToCancel = 0;
            if (!win95selectbug)
#endif /* NT */
              return(-1);
        }
        if (!FD_ISSET(httpfd, &wfds)) {
#ifdef STREAMING
            if (streaming)
              goto do_select;
#endif /* STREAMING */
            debug(F111,"http_tol","!FD_ISSET",ttyfd);
#ifdef NT
            WSASafeToCancel = 0;
            if (!win95selectbug)
#endif /* NT */
              return(-1);
        }
#ifdef NT
        WSASafeToCancel = 0;
#endif /* NT */
#else /* BSDSELECT */
#ifdef IBMSELECT
        {
            int tries = 0;
            debug(F101,"http_tol IBMSELECT","",0);
            while (select(&httpfd, 0, 1, 0, 1000) != 1) {
                int count;
                if (tries++ >= 60) {
                    /* if after 60 seconds we can't get permission to write */
                    debug(F101,"http_tol select failed","",socket_errno);
                    return(-1);
                }
#ifdef COMMENT
                if ((count = http_tchk()) < 0) {
                    debug(F111,"http_tol","http_tchk()",count);
                    return(count);
                }
#endif /* COMMENT */
            }
        }
#endif /* IBMSELECT */
#endif /* BSDSELECT */
#ifdef TCPIPLIB
        if ((count = socket_write(httpfd,s,n)) < 0) {
            int s_errno = socket_errno; /* maybe a function */
            debug(F101,"http_tol socket_write error","",s_errno);
#ifdef OS2
            if (os2socketerror(s_errno) < 0)
              return(-2);
#endif /* OS2 */
            return(-1);                 /* Call it an i/o error */
        }
#else /* TCPIPLIB */
        if ((count = write(httpfd,s,n)) < 0) {
            debug(F101,"http_tol socket_write error","",errno);
            return(-1);                 /* Call it an i/o error */
        }
#endif /* TCPIPLIB */
        if (count < n) {
            debug(F111,"http_tol socket_write",s,count);
            if (try > 25) {
                /* don't try more than 25 times */
                debug(F100,"http_tol tried more than 25 times","",0);
                return(-1);
            }
            if (count > 0) {
                s += count;
                n -= count;
            }
            debug(F111,"http_tol retry",s,n);
            goto http_tol_retry;
        } else {
            debug(F111,"http_tol socket_write",s,count);
            return(len); /* success - return total length */
        }
    }
}

int
http_inc(timo) int timo; {
    int x=-1; unsigned char c;             /* The locals. */

    if (httpfd == -1) {
#ifdef HTTP_BUFFERING
	http_count = 0;
  	http_bufp = 0;
#endif	/* HTTP_BUFFERING */
        debug(F100,"http_inc socket is closed","",0);
        return(-2);
    }

#ifdef CK_SSL
    /*
     * In the case of OpenSSL, it is possible that there is still
     * data waiting in the SSL session buffers that has not yet
     * been read by Kermit.  If this is the case we must process
     * it without calling select() because select() will not return
     * with an indication that there is data to be read from the
     * socket.  If there is no data pending in the SSL session
     * buffers then fall through to the select() code and wait for
     * some data to arrive.
     */
    if (tls_http_active_flag) {
        int error;

        x = SSL_pending(tls_http_con);
        if (x < 0) {
            debug(F111,"http_inc","SSL_pending error",x);
            http_close();
            return(-1);
        } else if ( x > 0 ) {
	  ssl_read:
            x = SSL_read(tls_http_con, &c, 1);
            error = SSL_get_error(tls_http_con,x);
            switch (error) {
            case SSL_ERROR_NONE:
                debug(F111,"http_inc SSL_ERROR_NONE","x",x);
                if (x > 0) {
#ifdef OS2
                    ReleaseTCPIPMutex();
#endif /* OS2 */
                    return(c);          /* Return character. */
                } else if (x < 0) {
#ifdef OS2
                    ReleaseTCPIPMutex();
#endif /* OS2 */
                    return(-1);
                } else {
                    http_close();
#ifdef OS2
                    ReleaseTCPIPMutex();
#endif /* OS2 */
                    return(-2);
                }
            case SSL_ERROR_WANT_WRITE:
                debug(F100,"http_inc SSL_ERROR_WANT_WRITE","",0);
#ifdef OS2
                ReleaseTCPIPMutex();
#endif /* OS2 */
                return(-1);
            case SSL_ERROR_WANT_READ:
                debug(F100,"http_inc SSL_ERROR_WANT_READ","",0);
#ifdef OS2
                ReleaseTCPIPMutex();
#endif /* OS2 */
                return(-1);
            case SSL_ERROR_SYSCALL:
                if ( x == 0 ) { /* EOF */
                    http_close();
#ifdef OS2
                    ReleaseTCPIPMutex();
#endif /* OS2 */
                    return(-2);
                } else {
                    int rc = -1;
#ifdef NT
                    int gle = GetLastError();
                    debug(F111,"http_inc SSL_ERROR_SYSCALL",
                           "GetLastError()",gle);
                    rc = os2socketerror(gle);
                    if (rc == -1)
                        rc = -2;
                    else if ( rc == -2 )
                        rc = -1;
#endif /* NT */
#ifdef OS2
                    ReleaseTCPIPMutex();
#endif /* OS2 */
                    return(rc);
                }
            case SSL_ERROR_WANT_X509_LOOKUP:
                debug(F100,"http_inc SSL_ERROR_WANT_X509_LOOKUP","",0);
                http_close();
#ifdef OS2
                ReleaseTCPIPMutex();
#endif /* OS2 */
                return(-2);
            case SSL_ERROR_SSL:
                debug(F100,"http_inc SSL_ERROR_SSL","",0);
#ifdef COMMENT
                http_close();
#endif /* COMMENT */
#ifdef OS2
                ReleaseTCPIPMutex();
#endif /* OS2 */
                return(-2);
            case SSL_ERROR_ZERO_RETURN:
                debug(F100,"http_inc SSL_ERROR_ZERO_RETURN","",0);
                http_close();
#ifdef OS2
                ReleaseTCPIPMutex();
#endif /* OS2 */
                return(-2);
            default:
                debug(F100,"http_inc SSL_ERROR_?????","",0);
                http_close();
#ifdef OS2
                ReleaseTCPIPMutex();
#endif /* OS2 */
                return(-2);
            }
        }
    }
#endif /* CK_SSL */

#ifdef HTTP_BUFFERING
    /* Skip all the select() stuff if we have bytes buffered locally */
    if (http_count > 0)
      goto getfrombuffer;
#endif	/* HTTP_BUFFERING */

    {
#ifdef BSDSELECT
        fd_set rfds;
        struct timeval tv;
        int timeout = timo < 0 ? -timo : 1000 * timo;
        debug(F101,"http_inc BSDSELECT","",timo);

        for ( ; timeout >= 0; timeout -= (timo ? 100 : 0)) {
            int rc;
            debug(F111,"http_inc","timeout",timeout);
            /* Don't move select() initialization out of the loop. */
            FD_ZERO(&rfds);
            FD_SET(httpfd, &rfds);
            tv.tv_sec  = tv.tv_usec = 0L;
            if (timo)
                tv.tv_usec = (long) 100000L;
            else
                tv.tv_sec = 30;
#ifdef NT
            WSASafeToCancel = 1;
#endif /* NT */
            rc = select(FD_SETSIZE,
#ifndef __DECC
                         (fd_set *)
#endif /* __DECC */
                         &rfds, NULL, NULL, &tv);
            if (rc < 0) {
                int s_errno = socket_errno;
                debug(F111,"http_inc","select",rc);
                debug(F111,"http_inc","socket_errno",s_errno);
#ifdef HTTP_BUFFERING
		http_count = 0;
		http_bufp = 0;
#endif	/* HTTP_BUFFERING */
                if (s_errno)
                    return(-1);
            }
            debug(F111,"http_inc","select",rc);
#ifdef NT
            WSASafeToCancel = 0;
#endif /* NT */
            if (FD_ISSET(httpfd, &rfds)) {
                x = 0;
                break;
            } else {
                /* If waiting forever we have no way of knowing if the */
                /* socket closed so try writing a 0-length TCP packet  */
                /* which should force an error if the socket is closed */
                if (!timo) {
#ifdef TCPIPLIB
                    if ((rc = socket_write(httpfd,"",0)) < 0) {
#ifdef HTTP_BUFFERING
			http_count = 0;
			http_bufp = 0;
#endif	/* HTTP_BUFFERING */
                        int s_errno = socket_errno;
                        debug(F101,"http_inc socket_write error","",s_errno);
#ifdef OS2
                        if (os2socketerror(s_errno) < 0)
                            return(-2);
#endif /* OS2 */
                        return(-1); /* Call it an i/o error */
                    }
#else /* TCPIPLIB */
                    if ((rc = write(httpfd,"",0)) < 0) {
#ifdef HTTP_BUFFERING
			http_count = 0;
			http_bufp = 0;
#endif	/* HTTP_BUFFERING */
                        debug(F101,"http_inc socket_write error","",errno);
                        return(-1); /* Call it an i/o error */
                    }
#endif /* TCPIPLIB */
                }
                continue;
            }
        }
#ifdef NT
        WSASafeToCancel = 0;
#endif /* NT */
#else /* !BSDSELECT */
#ifdef IBMSELECT
 /*
  Was used by OS/2, currently not used, but might come in handy some day...
  ... and it came in handy!  For our TCP/IP layer, it avoids all the fd_set
  and timeval stuff since this is the only place where it is used.
 */
        int socket = httpfd;
        int timeout = timo < 0 ? -timo : 1000 * timo;

        debug(F101,"http_inc IBMSELECT","",timo);
        for ( ; timeout >= 0; timeout -= (timo ? 100 : 0)) {
            if (select(&socket, 1, 0, 0, 100L) == 1) {
                x = 0;
                break;
            }
        }
#else /* !IBMSELECT */
        SELECT is required for this code
#endif /* IBMSELECT */
#endif /* BSDSELECT */
    }

    if (timo && x < 0) {        /* select() timed out */
#ifdef HTTP_BUFFERING
	http_count = 0;
	http_bufp = 0;
#endif	/* HTTP_BUFFERING */
        debug(F100,"http_inc select() timed out","",0);
        return(-1); /* Call it an i/o error */
    }

#ifdef CK_SSL
        if ( tls_http_active_flag ) {
            int error;
	  ssl_read2:
            x = SSL_read(tls_http_con, &c, 1);
            error = SSL_get_error(tls_http_con,x);
            switch (error) {
            case SSL_ERROR_NONE:
                debug(F111,"http_inc SSL_ERROR_NONE","x",x);
                if (x > 0) {
#ifdef OS2
                    ReleaseTCPIPMutex();
#endif /* OS2 */
                    return(c);          /* Return character. */
                } else if (x < 0) {
#ifdef OS2
                    ReleaseTCPIPMutex();
#endif /* OS2 */
                    return(-1);
                } else {
                    http_close();
#ifdef OS2
                    ReleaseTCPIPMutex();
#endif /* OS2 */
                    return(-2);
                }
            case SSL_ERROR_WANT_WRITE:
                debug(F100,"http_inc SSL_ERROR_WANT_WRITE","",0);
#ifdef OS2
                ReleaseTCPIPMutex();
#endif /* OS2 */
                return(-1);
            case SSL_ERROR_WANT_READ:
                debug(F100,"http_inc SSL_ERROR_WANT_READ","",0);
#ifdef OS2
                ReleaseTCPIPMutex();
#endif /* OS2 */
                return(-1);
            case SSL_ERROR_SYSCALL:
                if ( x == 0 ) { /* EOF */
                    http_close();
#ifdef OS2
                    ReleaseTCPIPMutex();
#endif /* OS2 */
                    return(-2);
                } else {
                    int rc = -1;
#ifdef NT
                    int gle = GetLastError();
                    debug(F111,"http_inc SSL_ERROR_SYSCALL",
                           "GetLastError()",gle);
                    rc = os2socketerror(gle);
                    if (rc == -1)
                        rc = -2;
                    else if ( rc == -2 )
                        rc = -1;
#endif /* NT */
#ifdef OS2
                    ReleaseTCPIPMutex();
#endif /* OS2 */
                    return(rc);
                }
            case SSL_ERROR_WANT_X509_LOOKUP:
                debug(F100,"http_inc SSL_ERROR_WANT_X509_LOOKUP","",0);
                http_close();
#ifdef OS2
                ReleaseTCPIPMutex();
#endif /* OS2 */
                return(-2);
            case SSL_ERROR_SSL:
                debug(F100,"http_inc SSL_ERROR_SSL","",0);
#ifdef COMMENT
                http_close();
#endif /* COMMENT */
#ifdef OS2
                ReleaseTCPIPMutex();
#endif /* OS2 */
                return(-2);
            case SSL_ERROR_ZERO_RETURN:
                debug(F100,"http_inc SSL_ERROR_ZERO_RETURN","",0);
                http_close();
#ifdef OS2
                ReleaseTCPIPMutex();
#endif /* OS2 */
                return(-2);
            default:
                debug(F100,"http_inc SSL_ERROR_?????","",0);
                http_close();
#ifdef OS2
                ReleaseTCPIPMutex();
#endif /* OS2 */
                return(-2);
            }
        }
#endif /* CK_SSL */

#ifdef HTTP_BUFFERING
/*
  Buffering code added by fdc 15 Dec 2005 for non-SSL case only because HTTP
  GETs were orders of magnitude too slow due to the single-byte read()s.  The
  file-descriptor swapping is pretty gross, but the more elegant solution
  (calling a nettchk() like routine with the fd as a parameter) doesn't work,
  because nettchk() relies on too many other routines that, like itself, are
  hardwired for ttyfd.
*/
  getfrombuffer:
	if (--http_count >= 0) {
	    c = http_inbuf[http_bufp++];
	    x = 1;
	} else {
	    int savefd;
	    savefd = ttyfd;
	    ttyfd = httpfd;
	    x = nettchk();
	    ttyfd = savefd;		
	    debug(F101,"http_inc nettchk","",x);
	    if (x > HTTP_INBUFLEN)
	      x = HTTP_INBUFLEN;
#ifdef TCPIPLIB
	    x = socket_read(httpfd,http_inbuf,x);
#else  /* Not TCPIPLIB */
	    x = read(httpfd,http_inbuf,x);
#endif	/* TCPIPLIB */
	    http_count = 0;
	    http_bufp = 0;
	    if (x > 0) {
		c = http_inbuf[http_bufp++];
		http_count = x - 1;
	    }
	}
#else  /* Not HTTP_BUFFERING */
#ifdef TCPIPLIB
        x = socket_read(httpfd,&c,1);
#else  /* Not TCPIPLIB */
        x = read(httpfd,&c,1);
#endif	/* TCPIPLIB */
#endif	/* HTTP_BUFFERING */

        if (x <= 0) {
            int s_errno = socket_errno;
            debug(F101,"ttbufr socket_read","",x);
            debug(F101,"ttbufr socket_errno","",s_errno);
#ifdef OS2
            if (x == 0 || os2socketerror(s_errno) < 0) {
                http_close();
                ReleaseTCPIPMutex();
                return(-2);
            }
            ReleaseTCPIPMutex();
            return(-1);
#else /* OS2 */
            http_close();                      /* *** *** */
            return(-2);
#endif /* OS2 */
        }
        return(c);
}

void
#ifdef CK_ANSIC
http_set_code_reply(char * msg)
#else
http_set_code_reply(msg)
    char * msg;
#endif /* CK_ANSIC */
{
    char * p = msg;
    char buf[16];
    int i=0;

    while ( *p != SP && *p != NUL ) {
        buf[i] = *p;
        p++;
        i++;
    }

    http_code = atoi(buf);

    while ( *p == SP )
        p++;

    ckstrncpy(http_reply_str,p,HTTPBUFLEN);
}

int
#ifdef CK_ANSIC
http_get(char * agent, char ** hdrlist, char * user,
         char * pwd, char array, char * local, char * remote,
         int stdio)
#else
http_get(agent, hdrlist, user, pwd, array, local, remote, stdio)
    char * agent; char ** hdrlist; char * user;
    char * pwd; char array; char * local; char * remote;
    int stdio;
#endif /* CK_ANSIC */
{
    char * request = NULL;
    int    i, j, len = 0, hdcnt = 0, rc = 0;
    int    ch;
    int    http_fnd = 0;
    char   buf[HTTPBUFLEN], *p;
    int    nullline;
#ifdef OS2
    struct utimbuf u_t;
#else /* OS2 */
#ifdef SYSUTIMEH
    struct utimbuf u_t;
#else
    struct utimbuf {
        time_t atime;
        time_t mtime;
    } u_t;
#endif /* SYSUTIMH */
#endif /* OS2 */
    time_t mod_t = 0;
    time_t srv_t = 0;
    time_t local_t = 0;
    char passwd[64];
    char b64in[128];
    char b64out[256];
    char * headers[HTTPHEADCNT];
    int closecon = 0;
    int chunked = 0;
    int zfile = 0;
    int first = 1;

#ifdef DEBUG
    if (deblog) {
        debug(F101,"http_get httpfd","",httpfd);
        debug(F110,"http_agent",agent,0);
        debug(F110,"http_user",user,0);
        debug(F110,"http_local",local,0);
        debug(F110,"http_remote",remote,0);
    }
#endif /* DEBUG */
    if (!remote) remote = "";

    if (httpfd == -1)
      return(-1);

    if (array) {
        for (i = 0; i < HTTPHEADCNT; i++)
          headers[i] = NULL;
    }
    len = 8;                            /* GET */
    len += strlen(HTTP_VERSION);
    len += strlen(remote);
    len += 16;

    if (hdrlist) {
        for (i = 0; hdrlist[i]; i++)
            len += strlen(hdrlist[i]) + 2;
    }
    len += (int) strlen(http_host_port) + 8;

    if (agent)
      len += 13 + strlen(agent);
    if (user) {
        if (!pwd) {
            readpass("Password: ",passwd,64);
            pwd = passwd;
        }
        ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
        j = b8tob64(b64in,strlen(b64in),b64out,256);
        memset(pwd,0,strlen(pwd));      /* NOT PORTABLE */
        if (j < 0)
          return(-1);
        b64out[j] = '\0';
        len += j + 24;
    }
#ifdef HTTP_CLOSE
    len += 19;                          /* Connection: close */
#endif
    len += 3;                           /* blank line + null */

    request = malloc(len);
    if (!request)
      return(-1);

    sprintf(request,"GET %s %s\r\n",remote,HTTP_VERSION);       /* safe */
    ckstrncat(request,"Host: ", len);
    ckstrncat(request,http_host_port, len);
    ckstrncat(request,"\r\n",len);
    if (agent) {
        ckstrncat(request,"User-agent: ",len);
        ckstrncat(request,agent,len);
        ckstrncat(request,"\r\n",len);
    }
    if (user) {
        ckstrncat(request,"Authorization: Basic ",len);
        ckstrncat(request,b64out,len);
        ckstrncat(request,"\r\n",len);
    }
    if ( hdrlist ) {
        for (i = 0; hdrlist[i]; i++) {
            ckstrncat(request,hdrlist[i],len);
            ckstrncat(request,"\r\n",len);
        }
    }
#ifdef HTTP_CLOSE
    ckstrncat(request,"Connection: close\r\n",len);
#endif
    ckstrncat(request,"\r\n",len);

  getreq:
    if (http_tol((CHAR *)request,strlen(request)) < 0)
    {
        http_close();
        if ( first ) {
            first--;
            http_reopen();
            goto getreq;
        }
        rc = -1;
        goto getexit;
    }

    /* Process the headers */
    local_t = time(NULL);
    nullline = 0;
    i = 0;
    len = -1;
    while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
        buf[i] = ch;
        if ( buf[i] == 10 ) { /* found end of line */
            if (i > 0 && buf[i-1] == 13)
              i--;
            if (i < 1)
              nullline = 1;
            buf[i] = '\0';
            if (array && !nullline && hdcnt < HTTPHEADCNT)
              makestr(&headers[hdcnt++],buf);
            if (!ckstrcmp(buf,"HTTP",4,0)) {
                http_fnd = 1;
                j = ckindex(" ",buf,0,0,0);
                p = &buf[j];
                while ( isspace(*p) )
                  p++;
                switch ( p[0] ) {
                  case '1':             /* Informational message */
                    break;
                  case '2':             /* Success */
                    break;
                  case '3':             /* Redirection */
                  case '4':             /* Client failure */
                  case '5':             /* Server failure */
                  default:              /* Unknown */
                    if (!quiet)
                      printf("Failure: Server reports %s\n",p);
                    rc = -1;
                    local = NULL;
                }
                http_set_code_reply(p);
#ifdef CMDATE2TM
            } else if (!ckstrcmp(buf,"Last-Modified",13,0)) {
                mod_t = http_date(&buf[15]);
            } else if (!ckstrcmp(buf,"Date",4,0)) {
                srv_t = http_date(&buf[4]);
#endif /* CMDATE2TM */
            } else if (!ckstrcmp(buf,"Connection:",11,0)) {
                if ( ckindex("close",buf,11,0,0) != 0 )
                    closecon = 1;
            } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
                len = atoi(&buf[16]);
            } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
                if ( ckindex("chunked",buf,18,0,0) != 0 )
                    chunked = 1;
		debug(F101,"http_get chunked","",chunked);
            }
            i = 0;
        } else {
            i++;
        }
    }
    if (ch < 0 && first) {
        first--;
        http_close();
        http_reopen();
        goto getreq;
    }
    if (http_fnd == 0) {
        rc = -1;
        closecon = 1;
        goto getexit;
    }

    /* Now we have the contents of the file */
    if ( local && local[0] ) {
        if (zopeno(ZOFILE,local,NULL,NULL))
            zfile = 1;
        else
            rc = -1;
    }

    if ( chunked ) {
        while ((len = http_get_chunk_len()) > 0) {
            while (len && (ch = http_inc(0)) >= 0) {
                len--;
                if ( zfile )
                    zchout(ZOFILE,(CHAR)ch);
                if ( stdio )
                    conoc((CHAR)ch);
            }
            if ((ch = http_inc(0)) != CR)
                break;
            if ((ch = http_inc(0)) != LF)
                break;
        }
    } else {
        while (len && (ch = http_inc(0)) >= 0) {
            len--;
            if ( zfile )
                zchout(ZOFILE,(CHAR)ch);
            if ( stdio )
                conoc((CHAR)ch);
        }
    }

    if ( zfile )
        zclose(ZOFILE);

    if ( chunked ) {            /* Parse Trailing Headers */
        nullline = 0;
        while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
            buf[i] = ch;
            if ( buf[i] == 10 ) { /* found end of line */
                if (i > 0 && buf[i-1] == 13)
                  i--;
                if (i < 1)
                  nullline = 1;
                buf[i] = '\0';
                if (array && !nullline && hdcnt < HTTPHEADCNT)
                    makestr(&headers[hdcnt++],buf);
#ifdef CMDATE2TM
                if (!ckstrcmp(buf,"Last-Modified",13,0)) {
                    mod_t = http_date(&buf[15]);
                } else if (!ckstrcmp(buf,"Date",4,0)) {
                    srv_t = http_date(&buf[4]);
                }
#endif /* CMDATE2TM */
                else if (!ckstrcmp(buf,"Connection:",11,0)) {
                    if ( ckindex("close",buf,11,0,0) != 0 )
                        closecon = 1;
                }
                i = 0;
            } else {
                i++;
            }
        }
    }

    if ( zfile ) {              /* Set timestamp */
#ifndef NOSETTIME
#ifdef OS2
        u_t.actime = srv_t ? srv_t : local_t;
        u_t.modtime = mod_t ? mod_t : local_t;
#else /* OS2 */
#ifdef SYSUTIMEH
        u_t.actime = srv_t ? srv_t : local_t;
        u_t.modtime = mod_t ? mod_t : local_t;
#else
#ifdef BSD44
        u_t[0].tv_sec = srv_t ? srv_t : local_t;
        u_t[1].tv_sec = mod_t ? mod_t : local_t;
#else
        u_t.mtime = srv_t ? srv_t : local_t;
        u_t.atime = mod_t ? mod_t : local_t;
#endif /* BSD44 */
#endif /* SYSUTIMEH */
#endif /* OS2 */
            utime(local,&u_t);
#endif /* NOSETTIME */
    }

  getexit:
    if (array)
      http_mkarray(headers,hdcnt,array);

    if ( closecon )
        http_close();
    free(request);
    for (i = 0; i < hdcnt; i++) {
        if (headers[i])
          free(headers[i]);
    }
    return(rc);
}

int
#ifdef CK_ANSIC
http_head(char * agent, char ** hdrlist, char * user,
          char * pwd, char array, char * local, char * remote,
          int stdio)
#else
http_head(agent, hdrlist, user, pwd, array, local, remote, stdio)
    char * agent; char ** hdrlist; char * user;
    char * pwd; char array; char * local; char * remote;
    int stdio;
#endif /* CK_ANSIC */
{
    char * request = NULL;
    int    i, j, len = 0, hdcnt = 0, rc = 0;
    int    ch;
    int    http_fnd = 0;
    char   buf[HTTPBUFLEN], *p;
    int    nullline;
    time_t mod_t;
    time_t srv_t;
    time_t local_t;
    char passwd[64];
    char b64in[128];
    char b64out[256];
    char * headers[HTTPHEADCNT];
    int  closecon = 0;
    int  first = 1;

    if (httpfd == -1)
      return(-1);

    if (array) {
        for (i = 0; i < HTTPHEADCNT; i++)
          headers[i] = NULL;
    }
    len = 9;                            /* HEAD */
    len += strlen(HTTP_VERSION);
    len += strlen(remote);
    len += 16;

    if ( hdrlist ) {
        for (i = 0; hdrlist[i]; i++)
            len += strlen(hdrlist[i]) + 2;
    }
    len += strlen(http_host_port) + 8;

    if (agent)
      len += 13 + strlen(agent);
    if (user) {
        if (!pwd) {
            readpass("Password: ",passwd,64);
            pwd = passwd;
        }
        ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
        j = b8tob64(b64in,strlen(b64in),b64out,256);
        memset(pwd,0,strlen(pwd));      /* NOT PORTABLE */
        if (j < 0)
          return(-1);
        b64out[j] = '\0';
        len += j + 24;
    }
#ifdef HTTP_CLOSE
    len += 19;                          /* Connection: close */
#endif
    len += 3;                           /* blank line + null */

    request = (char *)malloc(len);
    if (!request)
      return(-1);

    sprintf(request,"HEAD %s %s\r\n",remote,HTTP_VERSION);
    ckstrncat(request,"Host: ", len);
    ckstrncat(request,http_host_port, len);
    ckstrncat(request,"\r\n",len);
    if (agent) {
        ckstrncat(request,"User-agent: ",len);
        ckstrncat(request,agent,len);
        ckstrncat(request,"\r\n",len);
    }
    if (user) {
        ckstrncat(request,"Authorization: Basic ",len);
        ckstrncat(request,b64out,len);
        ckstrncat(request,"\r\n",len);
    }
    if ( hdrlist ) {
        for (i = 0; hdrlist[i]; i++) {
            ckstrncat(request,hdrlist[i],len);
            ckstrncat(request,"\r\n",len);
        }
    }
#ifdef HTTP_CLOSE
    ckstrncat(request,"Connection: close\r\n",len);
#endif
    ckstrncat(request,"\r\n",len);

    if ( local && local[0] ) {
        if (!zopeno(ZOFILE,local,NULL,NULL)) {
            free(request);
            return(-1);
        }
    }

  headreq:
    if (http_tol((CHAR *)request,strlen(request)) < 0)
    {
        http_close();
        if ( first ) {
            first--;
            http_reopen();
            goto headreq;
        }
        rc = -1;
        goto headexit;
    }

    /* Process the headers */

    local_t = time(NULL);
    nullline = 0;
    i = 0;
    while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
        buf[i] = ch;
        if (buf[i] == 10) {             /* found end of line */
            if (i > 0 && buf[i-1] == 13)
              i--;
            if (i < 1)
              nullline = 1;
            buf[i] = '\0';
            if (array && !nullline && hdcnt < HTTPHEADCNT)
              makestr(&headers[hdcnt++],buf);
            if (!ckstrcmp(buf,"HTTP",4,0)) {
                http_fnd = 1;
                j = ckindex(" ",buf,0,0,0);
                p = &buf[j];
                while (isspace(*p))
                  p++;
                switch (p[0]) {
                  case '1':             /* Informational message */
                    break;
                  case '2':             /* Success */
                    break;
                  case '3':             /* Redirection */
                  case '4':             /* Client failure */
                  case '5':             /* Server failure */
                  default:              /* Unknown */
                    if (!quiet)
                      printf("Failure: Server reports %s\n",p);
                    rc = -1;
                }
                http_set_code_reply(p);
            } else {
                if (!ckstrcmp(buf,"Connection:",11,0)) {
                    if ( ckindex("close",buf,11,0,0) != 0 )
                        closecon = 1;
                }
                if ( local && local[0] ) {
                    zsout(ZOFILE,buf);
                    zsout(ZOFILE,"\r\n");
                }
                if (stdio)
                    printf("%s\r\n",buf);
            }
            i = 0;
        } else {
            i++;
        }
    }
    if (ch < 0 && first) {
        first--;
        http_close();
        http_reopen();
        goto headreq;
    }
    if ( http_fnd == 0 )
        rc = -1;

    if (array)
      http_mkarray(headers,hdcnt,array);

  headexit:
    if ( local && local[0] )
        zclose(ZOFILE);
    if (closecon)
        http_close();
    free(request);
    for (i = 0; i < hdcnt; i++) {
        if (headers[i])
          free(headers[i]);
    }
    return(rc);
}

int
#ifdef CK_ANSIC
http_index(char * agent, char ** hdrlist, char * user, char * pwd,
             char array, char * local, char * remote, int stdio)
#else
http_index(agent, hdrlist, user, pwd, array, local, remote, stdio)
    char * agent; char ** hdrlist; char * user; char * pwd;
    char array; char * local; char * remote; int stdio;
#endif /* CK_ANSIC */
{
    char * request = NULL;
    int    i, j, len = 0, hdcnt = 0, rc = 0;
    int    ch;
    int    http_fnd = 0;
    char   buf[HTTPBUFLEN], *p;
    int    nullline;
    time_t mod_t;
    time_t srv_t;
    time_t local_t;
    char passwd[64];
    char b64in[128];
    char b64out[256];
    char * headers[HTTPHEADCNT];
    int  closecon = 0;
    int  chunked = 0;
    int  zfile = 0;
    int  first = 1;

    if (httpfd == -1)
      return(-1);

    if (array) {
        for (i = 0; i < HTTPHEADCNT; i++)
          headers[i] = NULL;
    }
    len = 10;                            /* INDEX */
    len += strlen(HTTP_VERSION);
    len += strlen(remote);
    len += 16;

    if ( hdrlist ) {
        for (i = 0; hdrlist[i]; i++)
            len += strlen(hdrlist[i]) + 2;
    }
    len += strlen(http_host_port) + 8;

    if (agent)
        len += 13 + strlen(agent);
    if (user) {
        if (!pwd) {
            readpass("Password: ",passwd,64);
            pwd = passwd;
        }
        ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
        j = b8tob64(b64in,strlen(b64in),b64out,256);
        memset(pwd,0,strlen(pwd));
        if (j < 0)
          return(-1);
        b64out[j] = '\0';
        len += j + 24;
    }
#ifdef HTTP_CLOSE
    len += 19;                          /* Connection: close */
#endif
    len += 3;                           /* blank line + null */

    request = malloc(len);
    if (!request)
      return(-1);

    sprintf(request,"INDEX %s\r\n",HTTP_VERSION);
    ckstrncat(request,"Host: ", len);
    ckstrncat(request,http_host_port, len);
    ckstrncat(request,"\r\n",len);
    if (agent) {
        ckstrncat(request,"User-agent: ",len);
        ckstrncat(request,agent,len);
        ckstrncat(request,"\r\n",len);
    }
    if (user) {
        ckstrncat(request,"Authorization: Basic ",len);
        ckstrncat(request,b64out,len);
        ckstrncat(request,"\r\n",len);
    }
    if ( hdrlist ) {
        for (i = 0; hdrlist[i]; i++) {
            ckstrncat(request,hdrlist[i],len);
            ckstrncat(request,"\r\n",len);
        }
    }
#ifdef HTTP_CLOSE
    ckstrncat(request,"Connection: close\r\n",len);
#endif
    ckstrncat(request,"\r\n",len);
  indexreq:
    if (http_tol((CHAR *)request,strlen(request)) < 0)
    {
        http_close();
        if ( first ) {
            first--;
            http_reopen();
            goto indexreq;
        }
        rc = -1;
        goto indexexit;
    }

    /* Process the headers */
    local_t = time(NULL);
    nullline = 0;
    i = 0;
    len = -1;
    while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
        buf[i] = ch;
        if (buf[i] == 10) {             /* found end of line */
            if (i > 0 && buf[i-1] == 13)
              i--;
            if (i < 1)
              nullline = 1;
            buf[i] = '\0';
            if (array && !nullline && hdcnt < HTTPHEADCNT)
              makestr(&headers[hdcnt++],buf);
            if (!ckstrcmp(buf,"HTTP",4,0)) {
                http_fnd = 1;
                j = ckindex(" ",buf,0,0,0);
                p = &buf[j];
                while (isspace(*p))
                  p++;
                switch ( p[0] ) {
                  case '1':             /* Informational message */
                    break;
                  case '2':             /* Success */
                    break;
                  case '3':             /* Redirection */
                  case '4':             /* Client failure */
                  case '5':             /* Server failure */
                  default:              /* Unknown */
                    if (!quiet)
                      printf("Failure: Server reports %s\n",p);
                    rc = -1;
                }
                http_set_code_reply(p);
            } else if ( !nullline ) {
                if (!ckstrcmp(buf,"Connection:",11,0)) {
                    if ( ckindex("close",buf,11,0,0) != 0 )
                        closecon = 1;
                } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
                    len = atoi(&buf[16]);
                } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
                    if ( ckindex("chunked",buf,18,0,0) != 0 )
                        chunked = 1;
		    debug(F101,"http_index chunked","",chunked);
                }
                printf("%s\n",buf);
            }
            i = 0;
        } else {
            i++;
        }
    }

    if (ch < 0 && first) {
        first--;
        http_close();
        http_reopen();
        goto indexreq;
    }
    if ( http_fnd == 0 ) {
        rc = -1;
        closecon = 1;
        goto indexexit;
    }

    /* Now we have the contents of the file */
    if ( local && local[0] ) {
        if (zopeno(ZOFILE,local,NULL,NULL))
            zfile = 1;
        else
            rc = -1;
    }

    if ( chunked ) {
        while ((len = http_get_chunk_len()) > 0) {
            while (len && (ch = http_inc(0)) >= 0) {
                len--;
                if ( zfile )
                    zchout(ZOFILE,(CHAR)ch);
                if ( stdio )
                    conoc((CHAR)ch);
            }
            if ((ch = http_inc(0)) != CR)
                break;
            if ((ch = http_inc(0)) != LF)
                break;
        }
    } else {
        while (len && (ch = http_inc(0)) >= 0) {
            len--;
            if ( zfile )
                zchout(ZOFILE,(CHAR)ch);
            if ( stdio )
                conoc((CHAR)ch);
        }
    }

    if ( zfile )
        zclose(ZOFILE);

    if ( chunked ) {            /* Parse Trailing Headers */
        nullline = 0;
        while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
            buf[i] = ch;
            if ( buf[i] == 10 ) { /* found end of line */
                if (i > 0 && buf[i-1] == 13)
                  i--;
                if (i < 1)
                  nullline = 1;
                buf[i] = '\0';
                if (array && !nullline && hdcnt < HTTPHEADCNT)
                    makestr(&headers[hdcnt++],buf);
                if (!ckstrcmp(buf,"Connection:",11,0)) {
                    if ( ckindex("close",buf,11,0,0) != 0 )
                        closecon = 1;
                }
                i = 0;
            } else {
                i++;
            }
        }
    }
    rc = 0;

  indexexit:
    if (array)
      http_mkarray(headers,hdcnt,array);

    if (closecon)
        http_close();
    free(request);
    for (i = 0; i < hdcnt; i++) {
        if (headers[i])
          free(headers[i]);
    }
    return(rc);
}

int
#ifdef CK_ANSIC
http_put(char * agent, char ** hdrlist, char * mime, char * user,
         char * pwd, char array, char * local, char * remote,
         char * dest, int stdio)
#else
http_put(agent, hdrlist, mime, user, pwd, array, local, remote, dest, stdio)
    char * agent; char ** hdrlist; char * mime; char * user;
    char * pwd; char array; char * local; char * remote; char * dest;
    int stdio;
#endif /* CK_ANSIC */
{
    char * request=NULL;
    int    i, j, len = 0, hdcnt = 0, rc = 0;
    int    ch;
    int    http_fnd = 0;
    char   buf[HTTPBUFLEN], *p;
    int    nullline;
    time_t mod_t;
    time_t srv_t;
    time_t local_t;
    char passwd[64];
    char b64in[128];
    char b64out[256];
    int  filelen;
    char * headers[HTTPHEADCNT];
    int  closecon = 0;
    int  chunked = 0;
    int  first = 1;
    int  zfile = 0;

    if (httpfd == -1)
      return(-1);
    if (!mime) mime = "";
    if (!remote) remote = "";
    if (!local) local = "";
    if (!*local) return(-1);

    if (array) {
        for (i = 0; i < HTTPHEADCNT; i++)
          headers[i] = NULL;
    }
    filelen = zchki(local);
    if (filelen < 0)
      return(-1);

    /* Compute length of request header */
    len = 8;                            /* PUT */
    len += strlen(HTTP_VERSION);
    len += strlen(remote);
    len += 16;

    if ( hdrlist ) {
        for (i = 0; hdrlist[i]; i++)
            len += strlen(hdrlist[i]) + 2;
    }
    len += strlen(http_host_port) + 8;

    if (agent)
      len += 13 + strlen(agent);
    if (user) {
        if (!pwd) {
            readpass("Password: ",passwd,64);
            pwd = passwd;
        }
        ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
        j = b8tob64(b64in,strlen(b64in),b64out,256);
        memset(pwd,0,strlen(pwd));
        if (j < 0)
          return(-1);
        b64out[j] = '\0';
        len += j + 24;
    }
    len += 16 + strlen(mime);           /* Content-type: */
    len += 32;                          /* Content-length: */
    len += 32;                          /* Date: */
#ifdef HTTP_CLOSE
    len += 19;                          /* Connection: close */
#endif
    len += 3;                           /* blank line + null */

    request = malloc(len);
    if (!request)
      return(-1);

    sprintf(request,"PUT %s %s\r\n",remote,HTTP_VERSION);
    ckstrncat(request,"Date: ",len);
#ifdef CMDATE2TM
    ckstrncat(request,http_now(),len);
#else
    ckstrncat(request,...,len);
#endif /* CMDATE2TM */
    ckstrncat(request,"\r\n",len);
    ckstrncat(request,"Host: ", len);
    ckstrncat(request,http_host_port, len);
    ckstrncat(request,"\r\n",len);
    if (agent) {
        ckstrncat(request,"User-agent: ",len);
        ckstrncat(request,agent,len);
        ckstrncat(request,"\r\n",len);
    }
    if (user) {
        ckstrncat(request,"Authorization: Basic ",len);
        ckstrncat(request,b64out,len);
        ckstrncat(request,"\r\n",len);
    }
    if ( hdrlist ) {
        for (i = 0; hdrlist[i]; i++) {
            ckstrncat(request,hdrlist[i],len);
            ckstrncat(request,"\r\n",len);
        }
    }
    ckstrncat(request,"Content-type: ",len);
    ckstrncat(request,mime,len);
    ckstrncat(request,"\r\n",len);
    sprintf(buf,"Content-length: %d\r\n",filelen); /* safe */
    ckstrncat(request,buf,len);
#ifdef HTTP_CLOSE
    ckstrncat(request,"Connection: close\r\n",len);
#endif
    ckstrncat(request,"\r\n",len);

    /* Now we have the contents of the file */
    if (zopeni(ZIFILE,local)) {

      putreq:				/* Send request */
        if (http_tol((CHAR *)request,strlen(request)) <= 0) {
            http_close();
            if ( first ) {
                first--;
                http_reopen();
                goto putreq;
            }
            zclose(ZIFILE);
            rc = -1;
            goto putexit;
        }
        /* Request headers have been sent */

        i = 0;
        while (zchin(ZIFILE,&ch) == 0) {
            buf[i++] = ch;
            if (i == HTTPBUFLEN) {
                if (http_tol((CHAR *)buf,HTTPBUFLEN) <= 0) {
                    http_close();
                    if ( first ) {
                        first--;
                        http_reopen();
                        goto putreq;
                    }
                }
                i = 0;
            }
        }
        if (i > 0) {
            if (http_tol((CHAR *)buf,i) < 0) {
                http_close();
                if ( first ) {
                    first--;
                    http_reopen();
                    goto putreq;
                }
            }
        }
        zclose(ZIFILE);

        /* Process the response headers */
        local_t = time(NULL);
        nullline = 0;
        i = 0;
        len = -1;
        while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
            buf[i] = ch;
            if (buf[i] == 10) {         /* found end of line */
                if (i > 0 && buf[i-1] == 13)
                  i--;
                if (i < 1)
                  nullline = 1;
                buf[i] = '\0';
                if (array && !nullline && hdcnt < HTTPHEADCNT)
                  makestr(&headers[hdcnt++],buf);
                if (!ckstrcmp(buf,"HTTP",4,0)) {
                    http_fnd = 1;
                    j = ckindex(" ",buf,0,0,0);
                    p = &buf[j];
                    while (isspace(*p))
                      p++;
                    switch (p[0]) {
                      case '1':         /* Informational message */
                        break;
                      case '2':         /* Success */
                        break;
                      case '3':         /* Redirection */
                      case '4':         /* Client failure */
                      case '5':         /* Server failure */
                      default:          /* Unknown */
                        if (!quiet)
                          printf("Failure: Server reports %s\n",p);
                        rc = -1;
                    }
                    http_set_code_reply(p);
                } else {
                    if (!ckstrcmp(buf,"Connection:",11,0)) {
                        if ( ckindex("close",buf,11,0,0) != 0 )
                            closecon = 1;
                    } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
                        len = atoi(&buf[16]);
                    } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
                        if ( ckindex("chunked",buf,18,0,0) != 0 )
                            chunked = 1;
			debug(F101,"http_put chunked","",chunked);
                    }
                    if ( stdio )
                        printf("%s\n",buf);
                }
                i = 0;
            } else {
                i++;
            }
        }
        if (ch < 0 && first) {
            first--;
            http_close();
            http_reopen();
            goto putreq;
        }
        if ( http_fnd == 0 ) {
            closecon = 1;
            rc = -1;
            goto putexit;
        }

        /* Any response data? */
        if ( dest && dest[0] ) {
            if (zopeno(ZOFILE,dest,NULL,NULL))
                zfile = 1;
            else
                rc = -1;
        }

        if ( chunked ) {
            while ((len = http_get_chunk_len()) > 0) {
                while (len && (ch = http_inc(0)) >= 0) {
                    len--;
                    if ( zfile )
                        zchout(ZOFILE,(CHAR)ch);
                    if ( stdio )
                        conoc((CHAR)ch);
                }
                if ((ch = http_inc(0)) != CR)
                    break;
                if ((ch = http_inc(0)) != LF)
                    break;
            }
        } else {
            while (len && (ch = http_inc(0)) >= 0) {
                len--;
                if ( zfile )
                    zchout(ZOFILE,(CHAR)ch);
                if ( stdio )
                    conoc((CHAR)ch);
            }
        }

        if ( zfile )
            zclose(ZOFILE);

        if ( chunked ) {            /* Parse Trailing Headers */
            nullline = 0;
            while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
                buf[i] = ch;
                if ( buf[i] == 10 ) { /* found end of line */
                    if (i > 0 && buf[i-1] == 13)
                      i--;
                    if (i < 1)
                      nullline = 1;
                    buf[i] = '\0';
                    if (array && !nullline && hdcnt < HTTPHEADCNT)
                        makestr(&headers[hdcnt++],buf);
                    if (!ckstrcmp(buf,"Connection:",11,0)) {
                        if ( ckindex("close",buf,11,0,0) != 0 )
                            closecon = 1;
                    }
                    i = 0;
                } else {
                    i++;
                }
            }
        }
    } else {
        rc = -1;
    }

  putexit:
    if ( array )
        http_mkarray(headers,hdcnt,array);

    if (closecon)
        http_close();
    free(request);
    for (i = 0; i < hdcnt; i++) {
        if (headers[i])
          free(headers[i]);
    }
    return(rc);
}

int
#ifdef CK_ANSIC
http_delete(char * agent, char ** hdrlist, char * user,
          char * pwd, char array, char * remote)
#else
http_delete(agent, hdrlist, user, pwd, array, remote)
    char * agent; char ** hdrlist; char * user;
    char * pwd; char array; char * remote;
#endif /* CK_ANSIC */
{
    char * request=NULL;
    int    i, j, len = 0, hdcnt = 0, rc = 0;
    int    ch;
    int    http_fnd = 0;
    char   buf[HTTPBUFLEN], *p;
    int    nullline;
    time_t mod_t;
    time_t srv_t;
    time_t local_t;
    char passwd[64];
    char b64in[128];
    char b64out[256];
    char * headers[HTTPHEADCNT];
    int  closecon = 0;
    int  chunked = 0;
    int  first = 1;

    if (httpfd == -1)
      return(-1);

    if (array) {
        for (i = 0; i < HTTPHEADCNT; i++)
          headers[i] = NULL;
    }

    /* Compute length of request header */
    len = 11;                            /* DELETE */
    len += strlen(HTTP_VERSION);
    len += strlen(remote);
    len += 16;

    if ( hdrlist ) {
        for (i = 0; hdrlist[i]; i++)
            len += strlen(hdrlist[i]) + 2;
    }
    len += strlen(http_host_port) + 8;

    if (agent)
      len += 13 + strlen(agent);
    if (user) {
        if (!pwd) {
            readpass("Password: ",passwd,64);
            pwd = passwd;
        }
        ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
        j = b8tob64(b64in,strlen(b64in),b64out,256);
        memset(pwd,0,strlen(pwd));
        if (j < 0)
          return(-1);
        b64out[j] = '\0';
        len += j + 24;
    }
    len += 32;                          /* Date: */
#ifdef HTTP_CLOSE
    len += 19;                          /* Connection: close */
#endif
    len += 3;                           /* blank line + null */

    request = malloc(len);
    if (!request)
      return(-1);

    sprintf(request,"DELETE %s %s\r\n",remote,HTTP_VERSION);
    ckstrncat(request,"Date: ",len);
#ifdef CMDATE2TM
    ckstrncat(request,http_now(),len);
#else
    ckstrncat(request,...,len);
#endif /* CMDATE2TM */
    ckstrncat(request,"\r\n",len);
    ckstrncat(request,"Host: ", len);
    ckstrncat(request,http_host_port, len);
    ckstrncat(request,"\r\n",len);
    if (agent) {
        ckstrncat(request,"User-agent: ",len);
        ckstrncat(request,agent,len);
        ckstrncat(request,"\r\n",len);
    }
    if (user) {
        ckstrncat(request,"Authorization: Basic ",len);
        ckstrncat(request,b64out,len);
        ckstrncat(request,"\r\n",len);
    }
    if ( hdrlist ) {
        for (i = 0; hdrlist[i]; i++) {
            ckstrncat(request,hdrlist[i],len);
            ckstrncat(request,"\r\n",len);
        }
    }
#ifdef HTTP_CLOSE
    ckstrncat(request,"Connection: close\r\n",len);
#endif
    ckstrncat(request,"\r\n",len);
  delreq:
    if (http_tol((CHAR *)request,strlen(request)) < 0)
    {
        http_close();
        if ( first ) {
            first--;
            http_reopen();
            goto delreq;
        }
        rc = -1;
        goto delexit;
    }

    /* Process the response headers */
    local_t = time(NULL);
    nullline = 0;
    i = 0;
    len = -1;
    while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
        buf[i] = ch;
        if (buf[i] == 10) {         /* found end of line */
            if (i > 0 && buf[i-1] == 13)
              i--;
            if (i < 1)
              nullline = 1;
            buf[i] = '\0';
            if (array && !nullline && hdcnt < HTTPHEADCNT)
                makestr(&headers[hdcnt++],buf);
            if (!ckstrcmp(buf,"HTTP",4,0)) {
                http_fnd = 1;
                j = ckindex(" ",buf,0,0,0);
                p = &buf[j];
                while (isspace(*p))
                  p++;
                switch (p[0]) {
                  case '1':             /* Informational message */
                    break;
                  case '2':             /* Success */
                    break;
                  case '3':             /* Redirection */
                  case '4':             /* Client failure */
                  case '5':             /* Server failure */
                  default:              /* Unknown */
                    if (!quiet)
                      printf("Failure: Server reports %s\n",p);
                    rc = -1;
                }
                http_set_code_reply(p);
            } else {
                if (!ckstrcmp(buf,"Connection:",11,0)) {
                    if ( ckindex("close",buf,11,0,0) != 0 )
                        closecon = 1;
                } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
                    len = atoi(&buf[16]);
                } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
                    if ( ckindex("chunked",buf,18,0,0) != 0 )
                        chunked = 1;
		    debug(F101,"http_delete chunked","",chunked);
                }
                printf("%s\n",buf);
            }
            i = 0;
        } else {
            i++;
        }
    }
    if (ch < 0 && first) {
        first--;
        http_close();
        http_reopen();
        goto delreq;
    }
    if ( http_fnd == 0 ) {
        rc = -1;
        closecon = 1;
        goto delexit;
    }

    /* Any response data? */
    if ( chunked ) {
        while ((len = http_get_chunk_len()) > 0) {
            while (len && (ch = http_inc(0)) >= 0) {
                len--;
                conoc((CHAR)ch);
            }
            if ((ch = http_inc(0)) != CR)
                break;
            if ((ch = http_inc(0)) != LF)
                break;
        }
    } else {
        while (len && (ch = http_inc(0)) >= 0) {
            len--;
            conoc((CHAR)ch);
        }
    }

    if ( chunked ) {            /* Parse Trailing Headers */
        nullline = 0;
        while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
            buf[i] = ch;
            if ( buf[i] == 10 ) { /* found end of line */
                if (i > 0 && buf[i-1] == 13)
                  i--;
                if (i < 1)
                  nullline = 1;
                buf[i] = '\0';
                if (array && !nullline && hdcnt < HTTPHEADCNT)
                    makestr(&headers[hdcnt++],buf);
                if (!ckstrcmp(buf,"Connection:",11,0)) {
                    if ( ckindex("close",buf,11,0,0) != 0 )
                        closecon = 1;
                }
                i = 0;
            } else {
                i++;
            }
        }
    }

  delexit:
    if (array)
        http_mkarray(headers,hdcnt,array);

    if (closecon)
        http_close();
    free(request);
    for (i = 0; i < hdcnt; i++) {
        if (headers[i])
          free(headers[i]);
    }
    return(rc);
}

int
#ifdef CK_ANSIC
http_post(char * agent, char ** hdrlist, char * mime, char * user,
          char * pwd, char array, char * local, char * remote,
          char * dest, int stdio)
#else
http_post(agent, hdrlist, mime, user, pwd, array, local, remote, dest,
          stdio)
    char * agent; char ** hdrlist; char * mime; char * user;
    char * pwd; char array; char * local; char * remote; char * dest;
    int stdio;
#endif /* CK_ANSIC */
{
    char * request=NULL;
    int    i, j, len = 0, hdcnt = 0, rc = 0;
    int    ch;
    int    http_fnd = 0;
    char   buf[HTTPBUFLEN], *p;
    int    nullline;
    time_t mod_t;
    time_t srv_t;
    time_t local_t;
    char passwd[64];
    char b64in[128];
    char b64out[256];
    int  filelen;
    char * headers[HTTPHEADCNT];
    int  closecon = 0;
    int  chunked = 0;
    int  zfile = 0;
    int  first = 1;

    if (httpfd == -1)
      return(-1);

    if (array) {
        for (i = 0; i < HTTPHEADCNT; i++)
          headers[i] = NULL;
    }
    filelen = zchki(local);
    if (filelen < 0)
      return(-1);

    /* Compute length of request header */
    len = 9;                            /* POST */
    len += strlen(HTTP_VERSION);
    len += strlen(remote);
    len += 16;

    if ( hdrlist ) {
        for (i = 0; hdrlist[i]; i++)
            len += strlen(hdrlist[i]) + 2;
    }
    len += strlen(http_host_port) + 8;

    if (agent)
      len += 13 + strlen(agent);
    if (user) {
        if (!pwd) {
            readpass("Password: ",passwd,64);
            pwd = passwd;
        }
        ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
        j = b8tob64(b64in,strlen(b64in),b64out,256);
        memset(pwd,0,strlen(pwd));
        if (j < 0)
          return(-1);
        b64out[j] = '\0';
        len += j + 24;
    }
    len += 16 + strlen(mime);           /* Content-type: */
    len += 32;                          /* Content-length: */
    len += 32;                          /* Date: */
#ifdef HTTP_CLOSE
    len += 19;                          /* Connection: close */
#endif
    len += 3;                           /* blank line + null */

    request = malloc(len);
    if (!request)
      return(-1);

    sprintf(request,"POST %s %s\r\n",remote,HTTP_VERSION);
    ckstrncat(request,"Date: ",len);
    ckstrncat(request,http_now(),len);
    ckstrncat(request,"\r\n",len);
    ckstrncat(request,"Host: ", len);
    ckstrncat(request,http_host_port, len);
    ckstrncat(request,"\r\n",len);
    if (agent) {
        ckstrncat(request,"User-agent: ",len);
        ckstrncat(request,agent,len);
        ckstrncat(request,"\r\n",len);
    }
    if (user) {
        ckstrncat(request,"Authorization: Basic ",len);
        ckstrncat(request,b64out,len);
        ckstrncat(request,"\r\n",len);
    }
    if ( hdrlist ) {
        for (i = 0; hdrlist[i]; i++) {
            ckstrncat(request,hdrlist[i],len);
            ckstrncat(request,"\r\n",len);
        }
    }
    ckstrncat(request,"Content-type: ",len);
    ckstrncat(request,mime,len);
    ckstrncat(request,"\r\n",len);
#ifdef HTTP_CLOSE
    ckstrncat(request,"Connection: close\r\n",len);
#endif
    sprintf(buf,"Content-length: %d\r\n",filelen); /* safe */
    ckstrncat(request,buf,len);
    ckstrncat(request,"\r\n",len);
#ifdef COMMENT
    /* This is apparently a mistake - the previous ckstrncat() already  */
    /* appended a blank line to the request.  There should only be one. */
    /* Servers are not required by RFC 2616 to ignore extraneous empty  */
    /* lines.  -fdc, 28 Aug 2005. */
    ckstrncat(request,"\r\n",len);
#endif	/* COMMENT */

    /* Now we have the contents of the file */
  postopen:
    if (zopeni(ZIFILE,local)) {
      postreq:
        if (http_tol((CHAR *)request,strlen(request)) < 0)
        {
            http_close();
            if ( first ) {
                first--;
                http_reopen();
                goto postreq;
            }
            rc = -1;
            zclose(ZIFILE);
            goto postexit;
        }

        i = 0;
        while (zchin(ZIFILE,&ch) == 0) {
            buf[i++] = ch;
            if (i == HTTPBUFLEN) {
                http_tol((CHAR *)buf,HTTPBUFLEN);
                i = 0;
            }
        }
        if (i > 0)
          http_tol((CHAR *)buf,HTTPBUFLEN);
        zclose(ZIFILE);

        /* Process the response headers */
        local_t = time(NULL);
        nullline = 0;
        i = 0;
        len = -1;
        while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
            buf[i] = ch;
            if (buf[i] == 10) {         /* found end of line */
                if (i > 0 && buf[i-1] == 13)
                  i--;
                if (i < 1)
                  nullline = 1;
                buf[i] = '\0';
                if (array && !nullline && hdcnt < HTTPHEADCNT)
                  makestr(&headers[hdcnt++],buf);
                if (!ckstrcmp(buf,"HTTP",4,0)) {
                    http_fnd = 1;
                    j = ckindex(" ",buf,0,0,0);
                    p = &buf[j];
                    while (isspace(*p))
                      p++;
                    switch (p[0]) {
                      case '1':         /* Informational message */
                        break;
                      case '2':         /* Success */
                        break;
                      case '3':         /* Redirection */
                      case '4':         /* Client failure */
                      case '5':         /* Server failure */
                      default:          /* Unknown */
                        if (!quiet)
                          printf("Failure: Server reports %s\n",p);
                        rc = -1;
                    }
                    http_set_code_reply(p);
                } else {
                    if (!ckstrcmp(buf,"Connection:",11,0)) {
                        if ( ckindex("close",buf,11,0,0) != 0 )
                            closecon = 1;
                    } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
                        len = atoi(&buf[16]);
                    } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
                        if ( ckindex("chunked",buf,18,0,0) != 0 )
                            chunked = 1;
			debug(F101,"http_post chunked","",chunked);
                    }
                    if (stdio)
                        printf("%s\n",buf);
                }
                i = 0;
            } else {
                i++;
            }
        }
        if (ch < 0 && first) {
            first--;
            http_close();
            http_reopen();
            goto postopen;
        }
        if (http_fnd == 0) {
            rc = -1;
            closecon = 1;
            goto postexit;
        }

        /* Any response data? */
        if ( dest && dest[0] ) {
            if (zopeno(ZOFILE,dest,NULL,NULL))
                zfile = 1;
            else
                rc = -1;
        }

        if ( chunked ) {
            while ((len = http_get_chunk_len()) > 0) {
                while (len && (ch = http_inc(0)) >= 0) {
                    len--;
                    if ( zfile )
                        zchout(ZOFILE,(CHAR)ch);
                    if ( stdio )
                        conoc((CHAR)ch);
                }
                if ((ch = http_inc(0)) != CR)
                    break;
                if ((ch = http_inc(0)) != LF)
                    break;
            }
        } else {
            while (len && (ch = http_inc(0)) >= 0) {
                len--;
                if ( zfile )
                    zchout(ZOFILE,(CHAR)ch);
                if ( stdio )
                    conoc((CHAR)ch);
            }
        }

        if ( zfile )
            zclose(ZOFILE);

        if ( chunked ) {            /* Parse Trailing Headers */
            nullline = 0;
            while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
                buf[i] = ch;
                if ( buf[i] == 10 ) { /* found end of line */
                    if (i > 0 && buf[i-1] == 13)
                      i--;
                    if (i < 1)
                      nullline = 1;
                    buf[i] = '\0';
                    if (array && !nullline && hdcnt < HTTPHEADCNT)
                        makestr(&headers[hdcnt++],buf);
                    if (!ckstrcmp(buf,"Connection:",11,0)) {
                        if ( ckindex("close",buf,11,0,0) != 0 )
                            closecon = 1;
                    }
                    i = 0;
                } else {
                    i++;
                }
            }
        }
    } else {
        rc = -1;
    }

  postexit:
    if (array)
        http_mkarray(headers,hdcnt,array);
    if (closecon)
        http_close();
    free(request);
    for (i = 0; i < hdcnt; i++) {
        if (headers[i])
          free(headers[i]);
    }
    return(rc);
}

int
#ifdef CK_ANSIC
http_connect(int socket, char * agent, char ** hdrlist, char * user,
             char * pwd, char array, char * host_port)
#else
http_connect(socket, agent, hdrlist, user, pwd, array, host_port)
    int socket;
    char * agent; char ** hdrlist; char * user;
    char * pwd; char array; char * host_port;
#endif /* CK_ANSIC */
{
    char * request=NULL;
    int    i, j, len = 0, hdcnt = 0, rc = 0;
    int    http_fnd = 0;
    char   buf[HTTPBUFLEN], *p, ch;
    int    nullline;
    time_t mod_t;
    time_t srv_t;
    time_t local_t;
    char passwd[64];
    char b64in[128];
    char b64out[256];
    char * headers[HTTPHEADCNT];
    int    connected = 0;

    tcp_http_proxy_errno = 0;

    if (socket == -1)
      return(-1);

    if (array) {
        for (i = 0; i < HTTPHEADCNT; i++)
          headers[i] = NULL;
    }

    /* Compute length of request header */
    len = 12;                            /* CONNECT */
    len += strlen(HTTP_VERSION);
    len += strlen(host_port);
    len += (int) strlen(http_host_port) + 8;
    len += 16;
    len += strlen("Proxy-Connection: Keep-Alive\r\n");
    if ( hdrlist ) {
        for (i = 0; hdrlist[i]; i++)
            len += strlen(hdrlist[i]) + 2;
    }
    if (agent && agent[0])
      len += 13 + strlen(agent);
    if (user && user[0]) {
        if (!pwd) {
            readpass("Password: ",passwd,64);
            pwd = passwd;
        }
        ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
        j = b8tob64(b64in,strlen(b64in),b64out,256);
        memset(pwd,0,strlen(pwd));
        if (j < 0)
          return(-1);
        b64out[j] = '\0';
        len += j + 72;
    }
    len += 32;                          /* Date: */
    len += 3;                           /* blank line + null */

    request = malloc(len);
    if (!request)
      return(-1);

    sprintf(request,"CONNECT %s %s\r\n",host_port,HTTP_VERSION);
    ckstrncat(request,"Date: ",len);
#ifdef CMDATE2TM
    ckstrncat(request,http_now(),len);
#else
    strcat(request,...);
#endif /* CMDATE2TM */
    ckstrncat(request,"\r\n",len);
    ckstrncat(request,"Host: ", len);
    ckstrncat(request,http_host_port, len);
    ckstrncat(request,"\r\n",len);
    if (agent && agent[0]) {
        ckstrncat(request,"User-agent: ",len);
        ckstrncat(request,agent,len);
        ckstrncat(request,"\r\n",len);
    }
    if (user && user[0]) {
        ckstrncat(request,"Proxy-authorization: Basic ",len);
        ckstrncat(request,b64out,len);
        ckstrncat(request,"\r\n",len);
        ckstrncat(request,"Extension: Security/Remote-Passphrase\r\n",len);
    }
    ckstrncat(request,"Proxy-Connection: Keep-Alive\r\n",len);
    if ( hdrlist ) {
        for (i = 0; hdrlist[i]; i++) {
            ckstrncat(request,hdrlist[i],len);
            ckstrncat(request,"\r\n",len);
        }
    }
    ckstrncat(request,"\r\n",len);
    len = strlen(request);

#ifdef TCPIPLIB
    /* Send request */
    if (socket_write(socket,(CHAR *)request,strlen(request)) < 0) {
      rc = -1;
      goto connexit;
    }
#else
    if (write(socket,(CHAR *)request,strlen(request)) < 0) { /* Send request */
        rc = -1;
        goto connexit;
    }
#endif /* TCPIPLIB */

    /* Process the response headers */
    local_t = time(NULL);
    nullline = 0;
    i = 0;
    while (!nullline &&
#ifdef TCPIPLIB
           (socket_read(socket,&ch,1) == 1) &&
#else
           (read(socket,&ch,1) == 1) &&
#endif /* TCPIPLIB */
           i < HTTPBUFLEN) {
        buf[i] = ch;
        if (buf[i] == 10) {         /* found end of line */
            if (i > 0 && buf[i-1] == 13)
              i--;
            if (i < 1)
              nullline = 1;
            buf[i] = '\0';

            if (array && !nullline && hdcnt < HTTPHEADCNT)
                makestr(&headers[hdcnt++],buf);
            if (!ckstrcmp(buf,"HTTP",4,0)) {
                http_fnd = 1;
                j = ckindex(" ",buf,0,0,0);
                p = &buf[j];
                while (isspace(*p))
                  p++;
                tcp_http_proxy_errno = atoi(p);
                switch (p[0]) {
                  case '1':             /* Informational message */
                    break;
                  case '2':             /* Success */
                    connected = 1;
                    break;
                  case '3':             /* Redirection */
                  case '4':             /* Client failure */
                  case '5':             /* Server failure */
                  default:              /* Unknown */
                    if (!quiet)
                      printf("Failure: Server reports %s\n",p);
                    rc = -1;
                }
                http_set_code_reply(p);
            } else {
                printf("%s\n",buf);
            }
            i = 0;
        } else {
            i++;
        }
    }
    if ( http_fnd == 0 )
        rc = -1;

    if (array)
        http_mkarray(headers,hdcnt,array);

  connexit:
    if ( !connected ) {
        if ( socket == ttyfd ) {
            ttclos(0);
        }
        else if ( socket == httpfd ) {
            http_close();
        }
    }

    free(request);
    for (i = 0; i < hdcnt; i++) {
        if (headers[i])
          free(headers[i]);
    }
    return(rc);
}
#endif /* NOHTTP */

#ifdef CK_DNS_SRV

#define INCR_CHECK(x,y) x += y; if (x > size + answer.bytes) goto dnsout
#define CHECK(x,y) if (x + y > size + answer.bytes) goto dnsout
#define NTOHSP(x,y) x[0] << 8 | x[1]; x += y

#ifndef CKQUERYTYPE
#ifdef UNIXWARE
#ifndef UW7
#define CKQUERYTYPE CHAR
#endif /* UW7 */
#endif /* UNIXWARE */
#endif /* CKQUERYTYPE */

#ifndef CKQUERYTYPE
#define CKQUERYTYPE char
#endif /* CKQUERYTYPE */

/* 1 is success, 0 is failure */
int
locate_srv_dns(host, service, protocol, addr_pp, naddrs)
    char *host;
    char *service;
    char *protocol;
    struct sockaddr **addr_pp;
    int *naddrs;
{
    int nout, j, count;
    union {
        unsigned char bytes[2048];
        HEADER hdr;
    } answer;
    unsigned char *p=NULL;
    CKQUERYTYPE query[MAX_DNS_NAMELEN];
#ifdef CK_ANSIC
    const char * h;
#else
    char * h;
#endif /* CK_ANSIC */
    struct sockaddr *addr = NULL;
    struct sockaddr_in *sin = NULL;
    struct hostent *hp = NULL;
    int type, class;
    int priority, weight, size, len, numanswers, numqueries, rdlen;
    unsigned short port;
#ifdef CK_ANSIC
    const
#endif /* CK_ANSIC */
      int hdrsize = sizeof(HEADER);
    struct srv_dns_entry {
        struct srv_dns_entry *next;
        int priority;
        int weight;
        unsigned short port;
        char *host;
    };
    struct srv_dns_entry *head = NULL;
    struct srv_dns_entry *srv = NULL, *entry = NULL;
    char * s = NULL;

    nout = 0;
    addr = (struct sockaddr *) malloc(sizeof(struct sockaddr));
    if (addr == NULL)
      return 0;

    count = 1;

    /*
     * First build a query of the form:
     *
     *   service.protocol.host
     *
     * which will most likely be something like:
     *
     *   _telnet._tcp.host
     *
     */
    if (((int)strlen(service) + strlen(protocol) + strlen(host) + 5)
        > MAX_DNS_NAMELEN
        )
      goto dnsout;

    /* Realm names don't (normally) end with ".", but if the query
       doesn't end with "." and doesn't get an answer as is, the
       resolv code will try appending the local domain.  Since the
       realm names are absolutes, let's stop that.

       But only if a name has been specified.  If we are performing
       a search on the prefix alone then the intention is to allow
       the local domain or domain search lists to be expanded.
    */
    h = host + strlen (host);
    ckmakxmsg(query, sizeof(query), "_",service,"._",protocol,".", host,
              ((h > host) && (h[-1] != '.')?".":NULL),
               NULL,NULL,NULL,NULL,NULL);

    size = res_search(query, C_IN, T_SRV, answer.bytes, sizeof(answer.bytes));

    if (size < hdrsize)
      goto dnsout;

    /* We got a reply - See how many answers it contains. */

    p = answer.bytes;

    numqueries = ntohs(answer.hdr.qdcount);
    numanswers = ntohs(answer.hdr.ancount);

    p += sizeof(HEADER);

    /*
     * We need to skip over all of the questions, so we have to iterate
     * over every query record.  dn_expand() is able to tell us the size
     * of compressed DNS names, so we use it.
     */
    while (numqueries--) {
        len = dn_expand(answer.bytes,answer.bytes+size,p,query,sizeof(query));
        if (len < 0)
          goto dnsout;
        INCR_CHECK(p, len + 4);
    }

    /*
     * We're now pointing at the answer records.  Only process them if
     * they're actually T_SRV records (they might be CNAME records,
     * for instance).
     *
     * But in a DNS reply, if you get a CNAME you always get the associated
     * "real" RR for that CNAME.  RFC 1034, 3.6.2:
     *
     * CNAME RRs cause special action in DNS software.  When a name server
     * fails to find a desired RR in the resource set associated with the
     * domain name, it checks to see if the resource set consists of a CNAME
     * record with a matching class.  If so, the name server includes the CNAME
     * record in the response and restarts the query at the domain name
     * specified in the data field of the CNAME record.  The one exception to
     * this rule is that queries which match the CNAME type are not restarted.
     *
     * In other words, CNAMEs do not need to be expanded by the client.
     */
    while (numanswers--) {

        /* First is the name; use dn_expand() to get the compressed size. */
        len = dn_expand(answer.bytes,answer.bytes+size,p,query,sizeof(query));
        if (len < 0)
          goto dnsout;
        INCR_CHECK(p, len);

        CHECK(p,2);                     /* Query type */
        type = NTOHSP(p,2);

        CHECK(p, 6);                    /* Query class */
        class = NTOHSP(p,6);            /* Also skip over 4-byte TTL */

        CHECK(p,2);                     /* Record data length */
        rdlen = NTOHSP(p,2);
        /*
         * If this is an SRV record, process it.  Record format is:
         *
         * Priority
         * Weight
         * Port
         * Server name
         */
        if (class == C_IN && type == T_SRV) {
            CHECK(p,2);
            priority = NTOHSP(p,2);
            CHECK(p, 2);
            weight = NTOHSP(p,2);
            CHECK(p, 2);
            port = NTOHSP(p,2);
            len = dn_expand(answer.
                            bytes,
                            answer.bytes + size,
                            p,
                            query,
                            sizeof(query)
                            );
            if (len < 0)
              goto dnsout;
            INCR_CHECK(p, len);
            /*
             * We got everything.  Insert it into our list, but make sure
             * it's in the right order.  Right now we don't do anything
             * with the weight field
             */
            srv = (struct srv_dns_entry *)malloc(sizeof(struct srv_dns_entry));
            if (srv == NULL)
              goto dnsout;

            srv->priority = priority;
            srv->weight = weight;
            srv->port = port;
            makestr(&s,(char *)query);  /* strdup() is not portable */
            srv->host = s;

            if (head == NULL || head->priority > srv->priority) {
                srv->next = head;
                head = srv;
            } else
                /*
                 * Confusing.  Insert an entry into this spot only if:
                 *  . The next person has a higher priority (lower
                 *    priorities are preferred), or:
                 *  . There is no next entry (we're at the end)
                 */
              for (entry = head; entry != NULL; entry = entry->next)
                if ((entry->next &&
                     entry->next->priority > srv->priority) ||
                    entry->next == NULL) {
                    srv->next = entry->next;
                    entry->next = srv;
                    break;
                }
        } else
          INCR_CHECK(p, rdlen);
    }

    /*
     * Now we've got a linked list of entries sorted by priority.
     * Start looking up A records and returning addresses.
     */
    if (head == NULL)
      goto dnsout;

    for (entry = head; entry != NULL; entry = entry->next) {
        hp = gethostbyname(entry->host);
        if (hp != 0) {

            /* Watch out - memset() and memcpy() are not portable... */

            switch (hp->h_addrtype) {
              case AF_INET:
                for (j = 0; hp->h_addr_list[j]; j++) {
                    sin = (struct sockaddr_in *) &addr[nout++];
                    memset ((char *) sin, 0, sizeof (struct sockaddr));
                    sin->sin_family = hp->h_addrtype;
                    sin->sin_port = htons(entry->port);
                    memcpy((char *) &sin->sin_addr,
                           (char *) hp->h_addr_list[j],
                           sizeof(struct in_addr));             /* safe */
                    if (nout + 1 >= count) {
                        count += 5;
                        addr = (struct sockaddr *)
                          realloc((char *) addr,
                                  sizeof(struct sockaddr) * count);
                        if (!addr)
                          goto dnsout;
                    }
                }
                break;
              default:
                break;
            }
        }
    }
    for (entry = head; entry != NULL;) {
        free(entry->host);
        entry->host = NULL;
        srv = entry;
        entry = entry->next;
        free(srv);
        srv = NULL;
    }

  dnsout:
    if (srv)
      free(srv);

    if (nout == 0) {                    /* No good servers */
        if (addr)
          free(addr);
        return 0;
    }
    *addr_pp = addr;
    *naddrs = nout;
    return 1;
}
#undef INCR_CHECK
#undef CHECK
#undef NTOHSP

#define INCR_CHECK(x, y) x += y; if (x > size + answer.bytes) \
                         return 0
#define CHECK(x, y) if (x + y > size + answer.bytes) \
                         return 0
#define NTOHSP(x, y) x[0] << 8 | x[1]; x += y

int
locate_txt_rr(prefix, name, retstr)
    char *prefix, *name;
    char **retstr;
{
    union {
        unsigned char bytes[2048];
        HEADER hdr;
    } answer;
    unsigned char *p;
    char host[MAX_DNS_NAMELEN], *h;
    int size;
    int type, class, numanswers, numqueries, rdlen, len;

    /*
     * Form our query, and send it via DNS
     */

    if (name == NULL || name[0] == '\0') {
        strcpy(host,prefix);
    } else {
        if ( strlen(prefix) + strlen(name) + 3 > MAX_DNS_NAMELEN )
            return 0;

        /* Realm names don't (normally) end with ".", but if the query
           doesn't end with "." and doesn't get an answer as is, the
           resolv code will try appending the local domain.  Since the
           realm names are absolutes, let's stop that.

           But only if a name has been specified.  If we are performing
           a search on the prefix alone then the intention is to allow
           the local domain or domain search lists to be expanded.
        */
        h = host + strlen (host);
        ckmakmsg(host,sizeof(host),prefix, ".", name,
                 ((h > host) && (h[-1] != '.'))?".":NULL);

    }
    size = res_search(host, C_IN, T_TXT, answer.bytes, sizeof(answer.bytes));

    if (size < 0)
        return 0;

    p = answer.bytes;

    numqueries = ntohs(answer.hdr.qdcount);
    numanswers = ntohs(answer.hdr.ancount);

    p += sizeof(HEADER);

    /*
     * We need to skip over the questions before we can get to the answers,
     * which means we have to iterate over every query record.  We use
     * dn_expand to tell us how long each compressed name is.
     */

    while (numqueries--) {
        len = dn_expand(answer.bytes, answer.bytes + size, p, host,
                         sizeof(host));
        if (len < 0)
            return 0;
        INCR_CHECK(p, len + 4);         /* Name plus type plus class */
    }

    /*
     * We're now pointing at the answer records.  Process the first
     * TXT record we find.
     */

    while (numanswers--) {

        /* First the name; use dn_expand to get the compressed size */
        len = dn_expand(answer.bytes, answer.bytes + size, p,
                        host, sizeof(host));
        if (len < 0)
            return 0;
        INCR_CHECK(p, len);

        /* Next is the query type */
        CHECK(p, 2);
        type = NTOHSP(p,2);

        /* Next is the query class; also skip over 4 byte TTL */
        CHECK(p,6);
        class = NTOHSP(p,6);

        /* Record data length - make sure we aren't truncated */

        CHECK(p,2);
        rdlen = NTOHSP(p,2);

        if (p + rdlen > answer.bytes + size)
            return 0;

        /*
         * If this is a TXT record, return the string.  Note that the
         * string has a 1-byte length in the front
         */
        /* XXX What about flagging multiple TXT records as an error?  */

        if (class == C_IN && type == T_TXT) {
            len = *p++;
            if (p + len > answer.bytes + size)
                return 0;
            *retstr = malloc(len + 1);
            if (*retstr == NULL)
                return ENOMEM;
            strncpy(*retstr, (char *) p, len);
            (*retstr)[len] = '\0';
            /* Avoid a common error. */
            if ( (*retstr)[len-1] == '.' )
                (*retstr)[len-1] = '\0';
            return 1;
        }
    }

    return 0;
}
#undef INCR_CHECK
#undef CHECK
#undef NTOHSP
#endif /* CK_DNS_SRV */

#ifdef TNCODE
#ifdef CK_FORWARD_X
#ifdef UNIX
#include <sys/un.h>
#define FWDX_UNIX_SOCK
#ifndef AF_LOCAL
#define AF_LOCAL AF_UNIX
#endif
#ifndef PF_LOCAL
#define PF_LOCAL PF_UNIX
#endif
#ifndef SUN_LEN
/* Evaluate to actual length of the `sockaddr_un' structure.  */
#define SUN_LEN(ptr) ((size_t) (((struct sockaddr_un *) 0)->sun_path)         \
                      + strlen ((ptr)->sun_path))
#endif
#endif /* UNIX */
int
fwdx_create_listen_socket(screen) int screen; {
#ifdef NOPUTENV
    return(-1);
#else /* NOPUTENV */
    struct sockaddr_in saddr;
    int display, port, sock=-1, i;
    static char env[512];

    /*
     * X Windows Servers support multiple displays by listening on
     * one socket per display.  Display 0 is port 6000; Display 1 is
     * port 6001; etc.
     *
     * We start by trying to open port 6001 so that display 0 is
     * reserved for the local X Windows Server.
     */

    for ( display=1; display < 1000 ; display++  ) {

        if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
            debug(F111,"fwdx_create_listen_socket()","socket() < 0",sock);
            return(-1);
        }

        port = 6000 + display;
        bzero((char *)&saddr, sizeof(saddr));
        saddr.sin_family = AF_INET;
        saddr.sin_addr.s_addr = inet_addr(myipaddr);
        saddr.sin_port = htons(port);

        if (bind(sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
            i = errno;                  /* Save error code */
#ifdef TCPIPLIB
            socket_close(sock);
#else /* TCPIPLIB */
            close(sock);
#endif /* TCPIPLIB */
            sock = -1;
            debug(F110,"fwdx_create_listen_socket()","bind() < 0",0);
            continue;
        }

        debug(F100,"fdwx_create_listen_socket() bind OK","",0);
        break;
    }

    if ( display > 1000 ) {
        debug(F100,"fwdx_create_listen_socket() Out of Displays","",0);
        return(-1);
    }

    if (listen(sock, 5) < 0) {
        i = errno;                  /* Save error code */
#ifdef TCPIPLIB
        socket_close(sock);
#else /* TCPIPLIB */
        close(sock);
#endif /* TCPIPLIB */
        debug(F101,"fdwx_create_listen_socket() listen() errno","",errno);
        return(-1);
    }
    debug(F100,"fwdx_create_listen_socket() listen OK","",0);

    TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket = sock;
    if (!myipaddr[0])
        getlocalipaddr();
    if ( myipaddr[0] )
        ckmakxmsg(env,sizeof(env),"DISPLAY=",myipaddr,":",
                  ckuitoa(display),":",ckuitoa(screen),
                  NULL,NULL,NULL,NULL,NULL,NULL);
    else
        ckmakmsg(env,sizeof(env),"DISPLAY=",ckuitoa(display),":",
                 ckuitoa(screen));
    putenv(env);
    return(0);
#endif /* NOPUTENV */
}


int
fwdx_open_client_channel(channel) int channel; {
    char * env;
    struct sockaddr_in saddr;
#ifdef FWDX_UNIX_SOCK
    struct sockaddr_un saddr_un = { AF_LOCAL };
#endif /* FWDX_UNIX_SOCK */
    int colon, dot, display, port, sock, i, screen;
    int family;
    char buf[256], * host=NULL, * rest=NULL;
#ifdef TCP_NODELAY
    int on=1;
#endif /* TCP_NODELAY */

    debug(F111,"fwdx_create_client_channel()","channel",channel);

    for ( i=0; i<MAXFWDX ; i++ ) {
        if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == channel) {
            /* Already open */
            debug(F110,"fwdx_create_client_channel()","already open",0);
            return(0);
        }
    }

    env = getenv("DISPLAY");
    if ( !env )
      env = (char *)tn_get_display();
    if ( env )
      ckstrncpy(buf,env,256);
    else
      ckstrncpy(buf,"127.0.0.1:0.0",256);

    bzero((char *)&saddr,sizeof(saddr));
    saddr.sin_family = AF_INET;

    if (!fwdx_parse_displayname(buf,
                                &family,
                                &host,
                                &display,
                                &screen,
                                &rest
                                )
        ) {
        if ( host ) free(host);
        if ( rest ) free(rest);
        return(0);
    }
    if (rest) free(rest);

#ifndef FWDX_UNIX_SOCK
  /* if $DISPLAY indicates use of unix domain sockets, but we don't support it,
   * we change things to use inet sockets on the ip loopback interface instead,
   * and hope that it works.
   */
    if (family == FamilyLocal) {
        debug(F100,"fwdx_create_client_channel() FamilyLocal","",0);
        family = FamilyInternet;
        if (host) free(host);
        if (host = malloc(strlen("localhost") + 1))
            strcpy(host, "localhost");
        else {
            return(-1);
        }
    }
#else /* FWDX_UNIX_SOCK */
    if (family == FamilyLocal) {
        if (host) free(host);
        sock = socket(PF_LOCAL, SOCK_STREAM, 0);
        if (sock < 0)
            return(-1);

        ckmakmsg(buf,sizeof(buf),"/tmp/.X11-unix/X",ckitoa(display),NULL,NULL);
        strncpy(saddr_un.sun_path, buf, sizeof(saddr_un.sun_path));
        if (connect(sock,(struct sockaddr *)&saddr_un, SUN_LEN(&saddr_un)) < 0)
          return(-1);
    } else
#endif  /* FWDX_UNIX_SOCK */
    {
        /* Otherwise, we are assuming FamilyInternet */
        if (host) {
            ckstrncpy(buf,host,sizeof(buf));
            free(host);
        } else
            ckstrncpy(buf,myipaddr,sizeof(buf));

        debug(F111,"fwdx_create_client_channel()","display",display);

        port = 6000 + display;
        saddr.sin_port = htons(port);

        debug(F110,"fwdx_create_client_channel() ip-address",buf,0);
        saddr.sin_addr.s_addr = inet_addr(buf);
        if ( saddr.sin_addr.s_addr == (unsigned long) -1
#ifdef INADDR_NONE
             || saddr.sin_addr.s_addr == INADDR_NONE
#endif /* INADDR_NONE */
             )
        {
            struct hostent *host;
            host = gethostbyname(buf);
            if ( host == NULL )
                return(-1);
            host = ck_copyhostent(host);
#ifdef HADDRLIST
#ifdef h_addr
            /* This is for trying multiple IP addresses - see <netdb.h> */
            if (!(host->h_addr_list))
                return(-1);
            bcopy(host->h_addr_list[0],
                   (caddr_t)&saddr.sin_addr,
                   host->h_length
                   );
#else
            bcopy(host->h_addr, (caddr_t)&saddr.sin_addr, host->h_length);
#endif /* h_addr */
#else  /* HADDRLIST */
            bcopy(host->h_addr, (caddr_t)&saddr.sin_addr, host->h_length);
#endif /* HADDRLIST */
        }

        if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
            debug(F111,"fwdx_create_client_channel()","socket() < 0",sock);
            return(-1);
        }

        if ( connect(sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
            debug(F110,"fwdx_create_client_channel()","connect() failed",0);
#ifdef TCPIPLIB
            socket_close(sock);
#else /* TCPIPLIB */
            close(sock);
#endif /* TCPIPLIB */
            return(-1);
        }

#ifdef TCP_NODELAY
        setsockopt(sock,IPPROTO_TCP,TCP_NODELAY,(char *)&on,sizeof(on));
#endif /* TCP_NODELAY */
    }

    for (i = 0; i < MAXFWDX; i++) {
     if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == -1) {
         TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd = sock;
         TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id = channel;
       TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].need_to_send_xauth = 1;
         debug(F111,"fwdx_create_client_channel()","socket",sock);
         return(0);
     }
    }
    return(-1);
}

int
fwdx_server_avail() {
    char * env;
    struct sockaddr_in saddr;
#ifdef FWDX_UNIX_SOCK
    struct sockaddr_un saddr_un = { AF_LOCAL };
#endif  /* FWDX_UNIX_SOCK */
    int colon, dot, display, port, sock, i, screen;
    char buf[256], *host=NULL, *rest=NULL;
#ifdef TCP_NODELAY
    int on=1;
#endif /* TCP_NODELAY */
    int family;

    env = getenv("DISPLAY");
    if ( !env )
      env = (char *)tn_get_display();
    if ( env )
      ckstrncpy(buf,env,256);
    else
      ckstrncpy(buf,"127.0.0.1:0.0",256);

    bzero((char *)&saddr,sizeof(saddr));
    saddr.sin_family = AF_INET;

    if (!fwdx_parse_displayname(buf,&family,&host,&display,&screen,&rest)) {
        if ( host ) free(host);
        if ( rest ) free(rest);
        return(0);
    }
    if (rest) free(rest);

#ifndef FWDX_UNIX_SOCK
  /* if $DISPLAY indicates use of unix domain sockets, but we don't support it,
   * we change things to use inet sockets on the ip loopback interface instead,
   * and hope that it works.
   */
    if (family == FamilyLocal) {
        family = FamilyInternet;
        if (host) free(host);
        if (host = malloc(strlen("localhost") + 1))
            strcpy(host, "localhost");
        else {
            return(-1);
        }
    }
#else /* FWDX_UNIX_SOCK */
    if (family == FamilyLocal) {
        debug(F100,"fwdx_server_avail() FamilyLocal","",0);
        if (host) free(host);
        sock = socket(PF_LOCAL, SOCK_STREAM, 0);
        if (sock < 0)
            return(0);

        ckmakmsg(buf,sizeof(buf),"/tmp/.X11-unix/X",ckitoa(display),NULL,NULL);
        strncpy(saddr_un.sun_path, buf, sizeof(saddr_un.sun_path));
        if (connect(sock,(struct sockaddr *)&saddr_un,SUN_LEN(&saddr_un)) < 0)
            return(0);
        close(sock);
        return(1);
    }
#endif  /* FWDX_UNIX_SOCK */

    /* Otherwise, we are assuming FamilyInternet */
    if (host) {
        ckstrncpy(buf,host,sizeof(buf));
        free(host);
    } else
        ckstrncpy(buf,myipaddr,sizeof(buf));

    debug(F111,"fwdx_server_avail()","display",display);

    port = 6000 + display;
    saddr.sin_port = htons(port);

    debug(F110,"fwdx_server_avail() ip-address",buf,0);
    saddr.sin_addr.s_addr = inet_addr(buf);
    if ( saddr.sin_addr.s_addr == (unsigned long) -1
#ifdef INADDR_NONE
         || saddr.sin_addr.s_addr == INADDR_NONE
#endif /* INADDR_NONE */
         )
    {
        struct hostent *host;
        host = gethostbyname(buf);
        if ( host == NULL ) {
            debug(F110,"fwdx_server_avail() gethostbyname() failed",
                   myipaddr,0);
            return(-1);
        }
        host = ck_copyhostent(host);
#ifdef HADDRLIST
#ifdef h_addr
        /* This is for trying multiple IP addresses - see <netdb.h> */
        if (!(host->h_addr_list))
            return(-1);
        bcopy(host->h_addr_list[0],
               (caddr_t)&saddr.sin_addr,
               host->h_length
               );
#else
        bcopy(host->h_addr, (caddr_t)&saddr.sin_addr, host->h_length);
#endif /* h_addr */
#else  /* HADDRLIST */
        bcopy(host->h_addr, (caddr_t)&saddr.sin_addr, host->h_length);
#endif /* HADDRLIST */
    }

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        debug(F111,"fwdx_server_avail()","socket() < 0",sock);
        return(0);
    }

    if ( connect(sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
        debug(F110,"fwdx_server_avail()","connect() failed",0);
#ifdef TCPIPLIB
        socket_close(sock);
#else /* TCPIPLIB */
        close(sock);
#endif /* TCPIPLIB */
        return(0);
    }

#ifdef TCPIPLIB
    socket_close(sock);
#else /* TCPIPLIB */
    close(sock);
#endif /* TCPIPLIB */
    return(1);
}

int
fwdx_open_server_channel() {
    int sock, ready_to_accept, sock2,channel,i;
#ifdef TCP_NODELAY
    int on=1;
#endif /* TCP_NODELAY */
#ifdef UCX50
    static u_int saddrlen;
#else
    static SOCKOPT_T saddrlen;
#endif /* UCX50 */
    struct sockaddr_in saddr;
    char sb[8];
    extern char tn_msg[];
#ifdef BSDSELECT
    fd_set rfds;
    struct timeval tv;
#else
#ifdef BELLSELCT
    fd_set rfds;
#else
    fd_set rfds;
    struct timeval {
        long tv_sec;
        long tv_usec;
    } tv;
#endif /* BELLSELECT */
#endif /* BSDSELECT */
    unsigned short nchannel;
    unsigned char * p;

    sock = TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket;

  try_again:

#ifdef BSDSELECT
    tv.tv_sec  = tv.tv_usec = 0L;
    tv.tv_usec = 50;
    FD_ZERO(&rfds);
    FD_SET(sock, &rfds);
    ready_to_accept =
        ((select(FD_SETSIZE,
#ifdef HPUX
#ifdef HPUX1010
                  (fd_set *)
#else

                  (int *)
#endif /* HPUX1010 */
#else
#ifdef __DECC
                  (fd_set *)
#endif /* __DECC */
#endif /* HPUX */
                  &rfds, NULL, NULL, &tv) > 0) &&
          FD_ISSET(sock, &rfds));
#else /* BSDSELECT */
#ifdef IBMSELECT
    ready_to_accept = (select(&sock, 1, 0, 0, 50) == 1);
#else
#ifdef BELLSELECT
    FD_ZERO(rfds);
    FD_SET(sock, rfds);
    ready_to_accept =
        ((select(128, rfds, NULL, NULL, 50) > 0) &&
          FD_ISSET(sock, rfds));
#else
/* Try this - what's the worst that can happen... */

    tv.tv_sec  = tv.tv_usec = 0L;
    tv.tv_usec = 50;
    FD_ZERO(&rfds);
    FD_SET(sock, &rfds);
    ready_to_accept =
        ((select(FD_SETSIZE,
                  (fd_set *) &rfds, NULL, NULL, &tv) > 0) &&
          FD_ISSET(sock, &rfds));
#endif /* BELLSELECT */
#endif /* IBMSELECT */
#endif /* BSDSELECT */

    if ( !ready_to_accept )
        return(0);

    if ((sock2 = accept(sock,(struct sockaddr *)&saddr,&saddrlen)) < 0) {
        int i = errno;                  /* save error code */
        debug(F101,"tcpsrv_open accept errno","",i);
        return(-1);
    }

    /*
     * Now we have the open socket.  We must now find a channel to store
     * it in, and then notify the client.
     */

    for ( channel=0;channel<MAXFWDX;channel++ ) {
        if ( TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[channel].fd == -1 )
            break;
    }

    if ( channel == MAXFWDX ) {
#ifdef TCPIPLIB
        socket_close(sock2);
#else /* TCPIPLIB */
        close(sock2);
#endif /* TCPIPLIB */
        return(-1);
    }

    if ( fwdx_send_open(channel) < 0 ) {
#ifdef TCPIPLIB
        socket_close(sock2);
#else /* TCPIPLIB */
        close(sock2);
#endif /* TCPIPLIB */
    }

#ifdef TCP_NODELAY
    setsockopt(sock2,IPPROTO_TCP,TCP_NODELAY,(char *)&on,sizeof(on));
#endif /* TCP_NODELAY */

    TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[channel].fd = sock2;
    TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[channel].id = channel;
    goto try_again;

    return(0);  /* never reached */
}

int
fwdx_close_channel(channel) int channel; {
    int i,fd;

    for ( i=0; i<MAXFWDX ; i++ ) {
        if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == channel)
            break;
    }
    if ( i == MAXFWDX )
        return(-1);

    fd = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd;
    TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd = -1;
    TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id = -1;
    TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].need_to_send_xauth = 0;

#ifdef TCPIPLIB
    socket_close(fd);
#else /* TCPIPLIB */
    close(fd);
#endif /* TCPIPLIB */
    return(0);
}

int
fwdx_close_all() {
    int x,fd;

    debug(F111,"fwdx_close_all()",
          "TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket",
          TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket);

    if ( TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket != -1 ) {
#ifdef TCPIPLIB
        socket_close(TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket);
#else /* TCPIPLIB */
        close(TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket);
#endif /* TCPIPLIB */
        TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket = -1;
    }

    for (x = 0; x < MAXFWDX; x++) {
     if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd != -1) {
      fd = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd;
      TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd = -1;
      TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].id = -1;
      TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].need_to_send_xauth = 0;
      TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].suspend = 0;
#ifdef TCPIPLIB
      socket_close(fd);
#else /* TCPIPLIB */
      close(fd);
#endif /* TCPIPLIB */
     }
    }
    return(0);
}

/* The following definitions are for Unix */
#ifndef socket_write
#define socket_write(f,s,n)    write(f,s,n)
#endif /* socket_write */
#ifndef socket_read
#define socket_read(f,s,n)     read(f,s,n)
#endif /* socket_read */

int
fwdx_write_data_to_channel(channel, data, len)
    int channel; char * data; int len;
{
    int sock, count, try=0, length = len, i;

    if ( len <= 0 )
        return(0);

    for ( i=0; i<MAXFWDX ; i++ ) {
        if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == channel)
            break;
    }
    if ( i == MAXFWDX ) {
        debug(F110,"fwdx_write_data_to_channel",
               "attempting to write to closed channel",0);
        return(-1);
    }

    sock = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd;
    debug(F111,"fwdx_write_data_to_channel","socket",sock);
    ckhexdump("fwdx_write_data_to_channel",data,len);

  fwdx_write_data_to_channel_retry:

    if ((count = socket_write(sock,data,len)) < 0) {
        int s_errno = socket_errno; /* maybe a function */
        debug(F101,"fwdx_write_data_to_channel socket_write error","",s_errno);
#ifdef BETATEST
        printf("fwdx_write_data_to_channel error\r\n");
#endif /* BETATEST */
#ifdef OS2
        if (os2socketerror(s_errno) < 0)
            return(-2);
#endif /* OS2 */
        return(-1);                 /* Call it an i/o error */
    }
    if (count < len) {
        debug(F111,"fwdx_write_data_to_channel socket_write",data,count);
        if (count > 0) {
            data += count;
            len -= count;
        }
        debug(F111,"fwdx_write_data_to_channel retry",data,len);
        if ( len > 0 )
            goto fwdx_write_data_to_channel_retry;
    }

    debug(F111,"fwdx_write_data_to_channel complete",data,length);
    return(length); /* success - return total length */
}

VOID
fwdx_check_sockets(fd_set *ibits)
{
    int x, sock, channel, bytes;
    static char buffer[32000];

    debug(F100,"fwdx_check_sockets()","",0);
    if ( sstelnet && !TELOPT_ME(TELOPT_FORWARD_X) ||
         !sstelnet && !TELOPT_U(TELOPT_FORWARD_X)) {
        debug(F110,"fwdx_check_sockets()","TELOPT_FORWARD_X not negotiated",0);
        return;
    }

    for (x = 0; x < MAXFWDX; x++) {
        if ( TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd == -1 ||
             TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].suspend )
            continue;

        sock = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd;
        if (FD_ISSET(sock, ibits))
        {
            channel = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].id;
            debug(F111,"fwdx_check_sockets()","channel set",channel);

            bytes = socket_read(sock, buffer, sizeof(buffer));
            if (bytes > 0)
                fwdx_send_data_from_channel(channel, buffer, bytes);
            else if (bytes == 0) {
                fwdx_close_channel(channel);
                fwdx_send_close(channel);
            }
        }
    }
}

int
fwdx_init_fd_set(fd_set *ibits)
{
    int x,set=0,cnt=0;

    if ( sstelnet && !TELOPT_ME(TELOPT_FORWARD_X) ||
         !sstelnet && !TELOPT_U(TELOPT_FORWARD_X)) {
        debug(F110,"fwdx_init_fd_set()","TELOPT_FORWARD_X not negotiated",0);
        return(0);
    }

    if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket != -1) {
        set++;
        FD_SET(TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket, ibits);
    }
    for (x = 0; x < MAXFWDX; x++) {
        if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd != -1) {
            cnt++;
            if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].suspend)
                continue;
            set++;
            FD_SET(TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd, ibits);
        }
    }
    if (set + cnt == 0) {
        return(-1);
    } else {
        return(set);
    }
}

#ifdef NT
VOID
fwdx_thread( VOID * dummy )
{
    fd_set ifds;
    struct timeval tv;
    extern int priority;
    int n;

    setint();
    SetThreadPrty(priority,isWin95() ? 3 : 11);

    while ( !sstelnet && TELOPT_U(TELOPT_FORWARD_X) ||
            sstelnet && TELOPT_ME(TELOPT_FORWARD_X))
    {
        FD_ZERO(&ifds);
        n = fwdx_init_fd_set(&ifds);
        if (n > 0) {
            tv.tv_sec = 0;
            tv.tv_usec = 2500;
            if ( select(FD_SETSIZE, &ifds, NULL, NULL, &tv) > 0 )
                fwdx_check_sockets(&ifds);

        } else if (n < 0) {
            TELOPT_SB(TELOPT_FORWARD_X).forward_x.thread_started = 0;
            ckThreadEnd(NULL);
        } else {
            sleep(1);
        }
    }
}
#endif /* NT */
#endif /* CK_FORWARD_X */
#endif /* TNCODE */
#endif /* NETCONN */