File: ckufio.c

package info (click to toggle)
ckermit 193-3
  • links: PTS
  • area: non-free
  • in suites: slink
  • size: 6,180 kB
  • ctags: 8,803
  • sloc: ansic: 118,504; makefile: 2,474; sh: 52
file content (4158 lines) | stat: -rw-r--r-- 112,341 bytes parent folder | download
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
/* C K U F I O  --  Kermit file system support for UNIX, Aegis, and Plan 9 */

#define CK_NONBLOCK			/* See zoutdump() */

#ifdef aegis
char *ckzv = "Aegis File support, 6.1.130, 7 May 1998";
#else
#ifdef Plan9
char *ckzv = "Plan 9 File support, 6.1.130, 7 May 1998";
#else
char *ckzv = "UNIX File support, 6.1.130, 7 May 1998";
#endif /* Plan9 */
#endif /* aegis */
/*
  NOTE TO CONTRIBUTORS: This file, and all the other C-Kermit 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 any of the portable C-Kermit modules.  You can,
  of course, use these constructions in system-specific modules when you they
  are supported.
*/
/*
  Author: Frank da Cruz <fdc@columbia.edu>,
  Columbia University Academic Information Systems, New York City,
  and others noted in the comments below.  Note: CUCCA = Previous name of
  Columbia University Academic Information Systems.

  Copyright (C) 1985, 1998, Trustees of Columbia University in the City of New
  York.  The C-Kermit software may not be, in whole or in part, licensed or
  sold for profit as a software product itself, nor may it be included in or
  distributed with commercial products or otherwise distributed by commercial
  concerns to their clients or customers without written permission of the
  Office of Kermit Development and Distribution, Columbia University.  This
  copyright notice must not be removed, altered, or obscured.
*/

/* Include Files */

#include "ckcsym.h"
#include "ckcdeb.h"
#include "ckcasc.h"
#include <signal.h>

#ifdef MINIX2
#undef MINIX
#include <limits.h>
#include <time.h>
#define NOFILEH
#endif /* MINIX2 */

#ifdef MINIX
#include <limits.h>
#include <sys/types.h>
#include <time.h>
#else
#ifdef POSIX
#include <limits.h>
#else
#ifdef SVR3
#include <limits.h>
#endif /* SVR3 */
#endif /* POSIX */
#endif /* MINIX */
/*
  Directory Separator macros, to allow this module to work with both UNIX and
  OS/2: Because of ambiguity with the command line editor escape \ character,
  the directory separator is currently left as / for OS/2 too, because the
  OS/2 kernel also accepts / as directory separator.  But this is subject to
  change in future versions to conform to the normal OS/2 style.
*/
#define DIRSEP       '/'
#define ISDIRSEP(c)  ((c)=='/')

#ifdef SDIRENT
#define DIRENT
#endif /* SDIRENT */

#ifdef XNDIR
#include <sys/ndir.h>
#else /* !XNDIR */
#ifdef NDIR
#include <ndir.h>
#else /* !NDIR, !XNDIR */
#ifdef RTU
#include "/usr/lib/ndir.h"
#else /* !RTU, !NDIR, !XNDIR */
#ifdef DIRENT
#ifdef SDIRENT
#include <sys/dirent.h>
#else
#include <dirent.h>
#endif /* SDIRENT */
#else
#include <sys/dir.h>
#endif /* DIRENT */
#endif /* RTU */
#endif /* NDIR */
#endif /* XNDIR */

#ifdef UNIX				/* Pointer arg to wait() allowed */
#define CK_CHILD			/* Assume this is safe in all UNIX */
#endif /* UNIX */

extern int binary;			/* We need to know this for open() */
#ifdef CK_CTRLZ
extern int eofmethod;
#endif /* CK_CTRLZ */

#include <pwd.h>			/* Password file for shell name */

#ifdef POSIX
#define UTIMEH
#endif /* POSIX */

#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 */

#ifndef NOTIMESTAMP

#ifdef POSIX
#ifndef AS400
#define TIMESTAMP
#endif /* AS400 */
#endif /* POSIX */

#ifdef BSD44				/* BSD 4.4 */
#ifndef TIMESTAMP
#define TIMESTAMP			/* Can do file dates */
#endif /* TIMESTAMP */
#include <sys/time.h>
#include <sys/timeb.h>

#else  /* Not BSD44 */

#ifdef BSD4				/* BSD 4.3 and below */
#define TIMESTAMP			/* Can do file dates */
#include <time.h>			/* Need this */
#include <sys/timeb.h>			/* Need this if really BSD */

#else  /* Not BSD 4.3 and below */

#ifdef SVORPOSIX			/* System V or POSIX */
#ifndef TIMESTAMP
#define TIMESTAMP
#endif /* TIMESTAMP */
#include <time.h>

/* void tzset(); (the "void" type upsets some compilers) */
#ifndef IRIX60
#ifndef ultrix
#ifndef CONVEX9
/* ConvexOS 9.0, supposedly POSIX, has extern char *timezone(int,int) */
#ifndef Plan9
extern long timezone;
#endif /* Plan9 */
#endif /* CONVEX9 */
#endif /* ultrix */
#endif /* IRIX60 */
#endif /* SVORPOSIX */
#endif /* BSD4 */
#endif /* BSD44 */

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

/* Is `y' a leap year? */
#define leap(y) (((y) % 4 == 0 && (y) % 100 != 0) || (y) % 400 == 0)

/* Number of leap years from 1970 to `y' (not including `y' itself). */
#define nleap(y) (((y) - 1969) / 4 - ((y) - 1901) / 100 + ((y) - 1601) / 400)

#endif /* NOTIMESTAMP */

#ifdef CIE
#include <stat.h>			/* File status */
#else
#include <sys/stat.h>
#endif /* CIE */

#ifdef DEBUG
extern int deblog;
#endif /* DEBUG */

/*
  Functions (n is one of the predefined file numbers from ckcker.h):

   zopeni(n,name)   -- Opens an existing file for input.
   zopeno(n,name,attr,fcb) -- Opens a new file for output.
   zclose(n)        -- Closes a file.
   zchin(n,&c)      -- Gets the next character from an input file.
   zsinl(n,&s,x)    -- Read a line from file n, max len x, into address s.
   zsout(n,s)       -- Write a null-terminated string to output file, buffered.
   zsoutl(n,s)      -- Like zsout, but appends a line terminator.
   zsoutx(n,s,x)    -- Write x characters to output file, unbuffered.
   zchout(n,c)      -- Add a character to an output file, unbuffered.
   zchki(name)      -- Check if named file exists and is readable, return size.
   zchko(name)      -- Check if named file can be created.
   zchkspa(name,n)  -- Check if n bytes available to create new file, name.
   znewn(name,s)    -- Make a new unique file name based on the given name.
   zdelet(name)     -- Delete the named file.
   zxpand(string)   -- Expands the given wildcard string into a list of files.
   znext(string)    -- Returns the next file from the list in "string".
   zxcmd(n,cmd)     -- Execute the command in a lower fork on file number n.
   zclosf()         -- Close input file associated with zxcmd()'s lower fork.
   zrtol(n1,n2)     -- Convert remote filename into local form.
   zltor(n1,n2)     -- Convert local filename into remote form.
   zchdir(dirnam)   -- Change working directory.
   zhome()          -- Return pointer to home directory name string.
   zkself()         -- Kill self, log out own job.
   zsattr(struct zattr *) -- Return attributes for file which is being sent.
   zstime(f, struct zattr *, x) - Set file creation date from attribute packet.
   zrename(old, new) -- Rename a file.
   zcopy(source,destination) -- Copy a file.
   zmkdir(path)       -- Create the directory path if possible  
   zfnqfp(fname,len,fullpath) - Determine full path for file name.
*/

/* Kermit-specific includes */
/*
  Definitions here supersede those from system include files.
  ckcdeb.h is included above.
*/
#include "ckcker.h"			/* Kermit definitions */
#include "ckucmd.h"			/* For sys-dependent keyword tables */
#include "ckuver.h"			/* Version herald */

char *ckzsys = HERALD;

/*
  File access checking ...  There are two calls to access() in this module.
  If this program is installed setuid or setgid on a Berkeley-based UNIX
  system that does NOT incorporate the saved-original-effective-uid/gid
  feature, then, when we have swapped the effective and original uid/gid,
  access() fails because it uses what it thinks are the REAL ids, but we have
  swapped them.  This occurs on systems where ANYBSD is defined, NOSETREU
  is NOT defined, and SAVEDUID is NOT defined.  So, in theory, we should take
  care of this situation like so:

    ifdef ANYBSD
    ifndef NOSETREU
    ifndef SAVEDUID
    define SW_ACC_ID
    endif
    endif
    endif

  But we can't test such a general scheme everywhere, so let's only do this
  when we know we have to...
*/
#ifdef NEXT				/* NeXTSTEP 1.0-3.0 */
#define SW_ACC_ID
#endif /* NEXT */

/* Support for tilde-expansion in file and directory names */

#ifdef POSIX
#define NAMEENV "LOGNAME"
#endif /* POSIX */

#ifdef BSD4
#define NAMEENV "USER"
#endif /* BSD4 */

#ifdef ATTSV
#define NAMEENV "LOGNAME"
#endif /* ATTSV */

/* Berkeley Unix Version 4.x */
/* 4.1bsd support from Charles E Brooks, EDN-VAX */

#ifdef BSD4
#ifdef MAXNAMLEN
#define BSD42
#endif /* MAXNAMLEN */
#endif /* BSD4 */

/* Definitions of some system commands */

char *DELCMD = "rm -f ";		/* For file deletion */
char *CPYCMD = "cp ";			/* For file copy */
char *RENCMD = "mv ";			/* For file rename */
char *PWDCMD = "pwd ";			/* For saying where I am */

#ifdef COMMENT
#ifdef HPUX10
char *DIRCMD = "/usr/bin/ls -l ";	/* For directory listing */
char *DIRCM2 = "/usr/bin/ls -l ";	/* For directory listing, no args */
#else
char *DIRCMD = "/bin/ls -l ";		/* For directory listing */
char *DIRCM2 = "/bin/ls -l ";		/* For directory listing, no args */
#endif /* HPUX10 */
#else
char *DIRCMD = "ls -l ";		/* For directory listing */
char *DIRCM2 = "ls -l ";		/* For directory listing, no args */
#endif /* COMMENT */

char *TYPCMD = "cat ";			/* For typing a file */

#ifdef DGUX540
char *MAILCMD = "mailx";		/* For sending mail */
#else
#ifdef UNIX
char *MAILCMD = "Mail";
#else
char *MAILCMD = "";
#endif /* UNIX */
#endif /* DGUX40 */

#ifdef UNIX
#ifdef ANYBSD				/* BSD uses lpr to spool */
#ifdef DGUX540				/* And DG/UX */
char * PRINTCMD = "lp";
#else
char * PRINTCMD = "lpr";
#endif /* DGUX540 */
#else					/* Sys V uses lp */
#ifdef TRS16				/* except for Tandy-16/6000... */
char * PRINTCMD = "lpr";
#else
char * PRINTCMD = "lp";
#endif /* TRS16 */
#endif /* ANYBSD */
#else  /* Not UNIX */
#define PRINTCMD ""
#endif /* UNIX */

#ifdef FT18				/* Fortune For:Pro 1.8 */
#undef BSD4
#endif /* FT18 */

#ifdef BSD4
char *SPACMD = "pwd ; df .";		/* Space in current directory */
#else
#ifdef FT18
char *SPACMD = "pwd ; du ; df .";
#else
char *SPACMD = "df ";
#endif /* FT18 */
#endif /* BSD4 */

char *SPACM2 = "df ";			/* For space in specified directory */

#ifdef FT18
#define BSD4
#endif /* FT18 */

#ifdef BSD4
char *WHOCMD = "finger ";
#else
char *WHOCMD = "who ";
#endif /* BSD4 */

#ifdef DTILDE				/* For tilde expansion */
_PROTOTYP( char * tilde_expand, (char *) );
#endif /* DTILDE */

/* More system-dependent includes, which depend on symbols defined */
/* in the Kermit-specific includes.  Oh what a tangled web we weave... */

#ifdef COHERENT				/* <sys/file.h> */
#define NOFILEH
#endif /* COHERENT */

#ifdef MINIX
#define NOFILEH
#endif /* MINIX */

#ifdef aegis
#define NOFILEH
#endif /* aegis */

#ifdef unos
#define NOFILEH
#endif /* unos */

#ifndef NOFILEH
#include <sys/file.h>
#endif /* NOFILEH */

#ifndef is68k				/* Whether to include <fcntl.h> */
#ifndef BSD41				/* All but a couple UNIXes have it. */
#ifndef FT18
#ifndef COHERENT
#include <fcntl.h>
#endif /* COHERENT */
#endif /* FT18  */
#endif /* BSD41 */
#endif /* not is68k */

#ifdef COHERENT
#ifdef _I386
#include <fcntl.h>
#else
#include <sys/fcntl.h>
#endif /* _I386 */
#endif /* COHERENT */

/*
  Change argument to "(const char *)" if this causes trouble.
  Or... if it causes trouble, then maybe it was already declared 
  in a header file after all, so you can remove this prototype.
*/
#ifndef NDGPWNAM /* If not defined No Declare getpwnam... */
#ifndef _POSIX_SOURCE
#ifndef NEXT
#ifndef SVR4
/* POSIX <pwd.h> already gave prototypes for these. */
#ifdef IRIX40
_PROTOTYP( struct passwd * getpwnam, (const char *) );
#else
#ifdef IRIX51
_PROTOTYP( struct passwd * getpwnam, (const char *) );
#else
#ifdef M_UNIX
_PROTOTYP( struct passwd * getpwnam, (const char *) );
#else
#ifdef HPUX9
_PROTOTYP( struct passwd * getpwnam, (const char *) );
#else
#ifdef HPUX10
_PROTOTYP( struct passwd * getpwnam, (const char *) );
#else
#ifdef DCGPWNAM
_PROTOTYP( struct passwd * getpwnam, (const char *) );
#else
_PROTOTYP( struct passwd * getpwnam, (char *) );
#endif /* DCGPWNAM */
#endif /* HPUX10 */
#endif /* HPUX9 */
#endif /* M_UNIX */
#endif /* IRIX51 */
#endif /* IRIX40 */
#ifndef SUNOS4
#ifndef HPUX9
#ifndef HPUX10
#ifndef _SCO_DS
_PROTOTYP( struct passwd * getpwuid, (PWID_T) );
#endif /* _SCO_DS */
#endif /* HPUX10 */
#endif /* HPUX9 */
#endif /* SUNOS4 */
_PROTOTYP( struct passwd * getpwent, (void) );
#endif /* SVR4 */
#endif /* NEXT */
#endif /* _POSIX_SOURCE */
#endif /* NDGPWNAM */

/* Define macros for getting file type */

#ifdef OXOS
/*
  Olivetti X/OS 2.3 has S_ISREG and S_ISDIR defined
  incorrectly, so we force their redefinition.
*/
#undef S_ISREG
#undef S_ISDIR
#endif /* OXOS */

#ifdef UTSV				/* Same deal for Amdahl UTSV */
#undef S_ISREG
#undef S_ISDIR
#endif /* UTSV */

#ifdef UNISYS52				/* And for UNISYS UTS V 5.2 */
#undef S_ISREG
#undef S_ISDIR
#endif /* UNISYS52 */

#ifdef ICLSVR3				/* And for old ICL versions */
#undef S_ISREG
#undef S_ISDIR
#endif /* ICLSVR3 */

#ifdef ISDIRBUG				/* Also allow this from command line */
#ifdef S_ISREG
#undef S_ISREG
#endif /* S_ISREG */
#ifdef S_ISDIR
#undef S_ISDIR
#endif /*  S_ISDIR */
#endif /* ISDIRBUG */

#ifndef S_ISREG
#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
#endif /* S_ISREG */
#ifndef S_ISDIR
#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#endif /* S_ISDIR */

/* Define maximum length for a file name if not already defined */

#ifdef QNX
#ifdef _MAX_FNAME
#define MAXNAMLEN _MAX_FNAME
#else
#define MAXNAMLEN 48
#endif /* _MAX_FNAME */
#else
#ifndef MAXNAMLEN
#ifdef sun
#define MAXNAMLEN 255
#else
#ifdef FILENAME_MAX
#define MAXNAMLEN FILENAME_MAX
#else
#ifdef NAME_MAX
#define MAXNAMLEN NAME_MAX
#else
#ifdef _POSIX_NAME_MAX
#define MAXNAMLEN _POSIX_NAME_MAX
#else
#ifdef _D_NAME_MAX
#define MAXNAMLEN _D_NAME_MAX
#else
#ifdef DIRSIZ
#define MAXNAMLEN DIRSIZ
#else
#define MAXNAMLEN 14
#endif /* DIRSIZ */
#endif /* _D_NAME_MAX */
#endif /* _POSIX_NAME_MAX */
#endif /* NAME_MAX */
#endif /* FILENAME_MAX */
#endif /* sun */
#endif /* MAXNAMLEN */
#endif /* QNX */

/* Longest pathname ... */
/*
  Beware: MAXPATHLEN is one of UNIX's dirty little secrets.  Where is it
  defined?  Who knows...  <param.h>, <mod.h>, <unistd.h>, <limits.h>, ...
  There is not necessarily even a definition for it anywhere, or it might have
  another name.  If you get it wrong, bad things happen with getcwd() and/or
  getwd().  If you allocate a buffer that is too short, getwd() might write
  over memory and getcwd() will fail with ERANGE.  The definitions of these
  functions (e.g. in SVID or POSIX.1) do not tell you how to determine the
  maximum path length in order to allocate a buffer that is the right size.
*/
#ifdef BSD44
#include <sys/param.h>			/* For MAXPATHLEN */
#endif /* BSD44 */

#ifdef COHERENT
#include <sys/param.h>	/* for MAXPATHLEN, needed for -DDIRENT */
#endif /* COHERENT */

#ifdef MAXPATHLEN
#ifdef MAXPATH
#undef MAXPATH
#endif /* MAXPATH */
#define MAXPATH MAXPATHLEN
#else
#ifdef PATH_MAX
#define MAXPATH PATH_MAX
#else
#ifdef _POSIX_PATH_MAX
#define MAXPATH _POSIX_PATH_MAX
#else
#ifdef BSD42
#define MAXPATH 1024
#else
#ifdef SVR4  
#define MAXPATH 1024
#else
#define MAXPATH 255
#endif /* SVR4 */
#endif /* BSD42 */
#endif /* _POSIX_PATH_MAX */
#endif /* PATH_MAX */
#endif /* MAXPATHLEN */

/* Maximum number of filenames for wildcard expansion */

#ifndef MAXWLD				/* (see ckcdeb.h) */
#ifdef CK_SMALL
#define MAXWLD 50
#else
#ifdef BIGBUFOK
#define MAXWLD 102400
#else
#define MAXWLD 1024
#endif /* BIGBUFOK */
#endif /* CK_SMALL */
#endif /* MAXWLD */

/* More internal function prototypes */
/*
 * The path structure is used to represent the name to match.
 * Each slash-separated segment of the name is kept in one
 * such structure, and they are linked together, to make
 * traversing the name easier.
 */
struct path {
    char npart[MAXNAMLEN+4];		/* name part of path segment */
    struct path *fwd;			/* forward ptr */
};
#ifndef NOPUSH
_PROTOTYP( int shxpand, (char *, char *[], int ) );
extern int nopush;
#endif /* NOPUSH */
_PROTOTYP( static int fgen, (char *, char *[], int ) );
_PROTOTYP( static VOID traverse, (struct path *, char *, char *) );
_PROTOTYP( static VOID addresult, (char *) );
_PROTOTYP( static int match, (char *, char *) );
_PROTOTYP( static char * whoami, (void) );
#ifdef aegis
_PROTOTYP( static char * xindex, (char *, char) );
#endif /* aegis */
_PROTOTYP( UID_T real_uid, (void) );
_PROTOTYP( struct path *splitpath, (char *p) );
_PROTOTYP( char * zdtstr, (time_t) );
_PROTOTYP( time_t zstrdt, (char *, int) );

/* Some systems define these symbols in include files, others don't... */

#ifndef R_OK
#define R_OK 4				/* For access */
#endif /* R_OK */

#ifndef W_OK
#define W_OK 2
#endif /* W_OK */

#ifndef O_RDONLY
#define O_RDONLY 000
#endif /* O_RDONLY */

/* Declarations */

int maxnam = MAXNAMLEN;			/* Available to the outside */
int maxpath = MAXPATH;
int ck_znewn = -1;

#ifdef UNIX
char startupdir[MAXPATH+1];
#endif /* UNIX */
  
int pexitstat = -2;			/* Process exit status */

FILE *fp[ZNFILS] = { 			/* File pointers */
    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
};

/* Flags for each file indicating whether it was opened with popen() */
int ispipe[ZNFILS] = { 0, 0, 0, 0, 0, 0, 0, 0 };

/* Buffers and pointers used in buffered file input and output. */
#ifdef DYNAMIC
extern char *zinbuffer, *zoutbuffer;
#else
extern char zinbuffer[], zoutbuffer[];
#endif /* DYNAMIC */
extern char *zinptr, *zoutptr;
extern int zincnt, zoutcnt;
extern int wildxpand, recursive;

extern UID_T real_uid();

static long iflen = -1L;		/* Input file length */

static PID_T pid = 0;			/* pid of child fork */
static int fcount = 0;			/* Number of files in wild group */
static char nambuf[MAXNAMLEN+4];	/* Buffer for a filename */

#ifndef NOFRILLS
static char zmbuf[200];			/* For mail, remote print strings */
#endif /* NOFRILLS */

char **mtchs = NULL;			/* Matches found for filename */
char **mtchptr = NULL;			/* Pointer to current match */

/*  Z K S E L F  --  Kill Self: log out own job, if possible.  */

/* Note, should get current pid, but if your system doesn't have */
/* getppid(), then just kill(0,9)...  */

#ifndef SVR3
#ifndef POSIX
#ifndef OSFPC
/* Already declared in unistd.h for SVR3 and POSIX */
#ifdef CK_ANSIC
extern PID_T getppid(void);
#else
#ifndef PS2AIX10
extern PID_T getppid();
#endif /* PS2AIX10 */
#endif /* CK_ANSIC */
#endif /* OSFPC */
#endif /* POSIX */
#endif /* SVR3 */

int
zkself() {				/* For "bye", but no guarantee! */
#ifdef PROVX1
    return(kill(0,9));
#else
#ifdef V7
    return(kill(0,9));
#else
#ifdef TOWER1
    return(kill(0,9));
#else
#ifdef FT18
    return(kill(0,9));
#else
#ifdef aegis
    return(kill(0,9));
#else
#ifdef COHERENT
    return(kill((PID_T)getpid(),1));
#else
#ifdef PID_T
    exit(kill((PID_T)getppid(),1));
    return(0);
#else
    exit(kill(getppid(),1));
    return(0);
#endif
#endif
#endif
#endif
#endif
#endif
#endif
}

/*  Z O P E N I  --  Open an existing file for input. */

/* Returns 1 on success, 0 on failure */

int
zopeni(n,name) int n; char *name; {
    int x, y;

    debug(F111,"zopeni name",name,n);
    debug(F101,"zopeni fp","", (unsigned) fp[n]);
    if (chkfn(n) != 0) return(0);
    zincnt = 0;				/* Reset input buffer */
    if (n == ZSYSFN) {			/* Input from a system function? */
/*** Note, this function should not be called with ZSYSFN ***/
/*** Always call zxcmd() directly, and give it the real file number ***/
/*** you want to use.  ***/
        debug(F110,"zopeni called with ZSYSFN, failing!",name,0);
	*nambuf = '\0';			/* No filename. */
	return(0);			/* fail. */
#ifdef COMMENT
	return(zxcmd(n,name));		/* Try to fork the command */
#endif
    }
    if (n == ZSTDIO) {			/* Standard input? */
	if (is_a_tty(0)) {
	    fprintf(stderr,"Terminal input not allowed");
	    debug(F110,"zopeni: attempts input from unredirected stdin","",0);
	    return(0);
	}
	fp[ZIFILE] = stdin;
	ispipe[ZIFILE] = 0; 
	return(1);
    }
    fp[n] = fopen(name,"r");		/* Real file, open it. */
    debug(F111,"zopeni fopen", name, fp[n]);
#ifdef ZDEBUG
    printf("ZOPENI fp[%d]=%ld\n",n,fp[n]);
#endif /* ZDEBUG */
    ispipe[n] = 0;
    if (fp[n] == NULL)
      perror("zopeni");
    else
      clearerr(fp[n]);
    return((fp[n] != NULL) ? 1 : 0);
}

#ifdef QNX
#define DONDELAY
#else
#ifdef O_NDELAY
#define DONDELAY
#endif /* O_NDELAY */
#endif /* QNX */

/*  Z O P E N O  --  Open a new file for output.  */

int
zopeno(n,name,zz,fcb)
/* zopeno */  int n; char *name; struct zattr *zz; struct filinfo *fcb; {

    char p[8];

/* As of Version 5A, the attribute structure and the file information */
/* structure are included in the arglist. */

#ifdef DEBUG
    debug(F111,"zopeno",name,n);
    if (fcb) {
	debug(F101,"zopeno fcb disp","",fcb->dsp);
	debug(F101,"zopeno fcb type","",fcb->typ);
	debug(F101,"zopeno fcb char","",fcb->cs);
    } else {
	debug(F100,"zopeno fcb is NULL","",0);
    }
#endif /* DEBUG */

    if (chkfn(n) != 0)			/* Already open? */
      return(0);			/* Nothing to do. */

    if ((n == ZCTERM) || (n == ZSTDIO)) {   /* Terminal or standard output */
	fp[ZOFILE] = stdout;
	ispipe[ZOFILE] = 0;
#ifdef DEBUG
	if (n != ZDFILE)
	  debug(F101,"zopeno fp[n]=stdout","",fp[n]);
#endif /* DEBUG */
	zoutcnt = 0;
	zoutptr = zoutbuffer;
	return(1);
    }

/* A real file.  Open it in desired mode (create or append). */

    strcpy(p,"w");			/* Assume write/create mode */
    if (fcb) {				/* If called with an FCB... */
	if (fcb->dsp == XYFZ_A) {	/* Does it say Append? */
	    strcpy(p,"a");		/* Yes. */
	    debug(F100,"zopeno append","",0);
	}
    }
    debug(F110,"zopeno fopen arg",p,0);
    fp[n] = fopen(name,p);		/* Try to open the file */
    ispipe[ZIFILE] = 0;

#ifdef ZDEBUG 
    printf("ZOPENO fp[%d]=%ld\n",n,fp[n]);
#endif /* ZDEBUG */

    if (fp[n] == NULL) {		/* Failed */
	debug(F101,"zopeno failed errno","",errno);
#ifdef COMMENT				/* Let upper levels print message. */
        perror("Can't open output file");
#endif /* COMMENT */
    } else {				/* Succeeded */
	extern int zofbuffer, zofblock, zobufsize;
	debug(F101, "zopeno zobufsize", "", zobufsize);
        if (n == ZDFILE) {		/* If it's the debug log */
	    setbuf(fp[n],NULL);		/* make it unbuffered */
#ifdef DONDELAY
	} else if (n == ZOFILE && !zofblock) { /* blocking or nonblocking */
	    fcntl(fileno(fp[n]),F_SETFL,
#ifdef QNX
		  O_NONBLOCK
#else
		  O_NDELAY
#endif /* QNX */
		  );
	    debug(F100,"zopeno ZOFILE nonblocking","",0);
#endif /* DONDELAY */
	} else if (n == ZOFILE && !zofbuffer) { /* buffered or unbuffered */
	    setbuf(fp[n],NULL);
	    debug(F100,"zopeno ZOFILE unbuffered","",0);
	}
	debug(F100, "zopeno ok", "", 0);
    }
    zoutcnt = 0;			/* (PWP) reset output buffer */
    zoutptr = zoutbuffer;
    return((fp[n] != NULL) ? 1 : 0);
}

/*  Z C L O S E  --  Close the given file.  */

/*  Returns 0 if arg out of range, 1 if successful, -1 if close failed.  */

int
zclose(n) int n; {
    int x, x2;
    debug(F101,"zclose","",n);
    if (chkfn(n) < 1) return(0);	/* Check range of n */
    if ((n == ZOFILE) && (zoutcnt > 0))	/* (PWP) output leftovers */
      x2 = zoutdump();
    else
      x2 = 0;

    x = 0;				/* Initialize return code */
    if (fp[ZSYSFN] || ispipe[n]) {	/* If file is really pipe */
#ifndef NOPUSH
    	x = zclosf(n);			/* do it specially */
#else
	x = EOF;
#endif /* NOPUSH */
	debug(F101,"zclose zclosf","",x);
	debug(F101,"zclose zclosf fp[n]","",fp[n]);
    } else {
	if ((fp[n] != stdout) && (fp[n] != stdin)) 
	  x = fclose(fp[n]);
	fp[n] = NULL;
    }
    iflen = -1L;			/* Invalidate file length */
    if (x == EOF) {			/* if we got a close error */
	debug(F101,"zclose fclose fails","",x);
	return(-1);
    } else if (x2 < 0) {		/* or error flushing last buffer */
	debug(F101,"zclose error flushing last buffer","",x2);
	return(-1);			/* then return an error */
    } else {
	debug(F101,"zclose returns","",1);
	return(1);
    }
}

/*  Z C H I N  --  Get a character from the input file.  */

/*  Returns -1 if EOF, 0 otherwise with character returned in argument  */

int
zchin(n,c) int n; int *c; {
    int a, x;

    /* (PWP) Just in case this gets called when it shouldn't. */
    if (n == ZIFILE) {
	x = zminchar();
	*c = x;
	return(x);
    }
    /* if (chkfn(n) < 1) return(-1); */
    a = getc(fp[n]);
    if (a == EOF) return(-1);
#ifdef CK_CTRLZ
    /* If SET FILE EOF CTRL-Z, first Ctrl-Z marks EOF */
    if (!binary && a == 0x1A && eofmethod == XYEOF_Z)
      return(-1);
#endif /* CK_CTRLZ */
    *c = (CHAR) a & 0377;
    return(0);
}

/*  Z S I N L  --  Read a line from a file  */

/*
  Writes the line into the address provided by the caller.
  n is the Kermit "channel number".
  Writing terminates when newline is encountered, newline is not copied.
  Writing also terminates upon EOF or if length x is exhausted.
  Returns 0 on success, -1 on EOF or error.
*/
int
zsinl(n,s,x) int n, x; char *s; {
    int a, z = 0;			/* z is return code. */
    extern CHAR feol;			/* Line terminator */

    if (chkfn(n) < 1) {			/* Make sure file is open */
	return(-1);
    }
    a = -1;				/* Current character, none yet. */
    while (x--) {			/* Up to given length */
	int old = 0;
	if (feol) old = a;		/* Previous character */

	if (zchin(n,&a) < 0) {		/* Read a character from the file */
	    debug(F101,"zsinl","",a);
	    z = -1;			/* EOF or other error */
	    break;
	}

	if (feol) {			/* Single-character line terminator */
	    if (a == feol)
	      break;	
	} else {			/* CRLF line terminator */
	    if (a == '\015')		/* CR, get next character */
	      continue;
	    if (old == '\015') {	/* Previous character was CR */
		if (a == '\012')	/* This one is LF, so we have a line */
		  break;
		else			/* Not LF, deposit CR */
		  *s++ = '\015';
	    }
	}
	*s = a;				/* Deposit character */
	s++;
    }
    *s = '\0';				/* Terminate the string */
    return(z);
}

/*  Z X I N  --  Read x bytes from a file  */

/*
  Reads x bytes (or less) from channel n and writes them
  to the address provided by the caller.
  Returns number of bytes read on success, 0 on EOF or error.
*/
int
zxin(n,s,x) int n, x; char *s; {
    return(fread(s, sizeof (char), x, fp[n]));
}

/*
  Z I N F I L L  --  Buffered file input.

  (re)fill the file input buffer with data.  All file input
  should go through this routine, usually by calling the zminchar()
  macro defined in ckcker.h.  Returns:

  Value 0..255 on success, the character that was read.
  -1 on end of file.
  -2 on any kind of error other than end of file.
*/
int
zinfill() {
    int x;

    errno = 0;

#ifdef ZDEBUG 
    printf("ZINFILL fp[%d]=%ld\n",ZIFILE,fp[ZIFILE]);
#endif /* ZDEBUG */

	if (feof(fp[ZIFILE])) {
	    debug(F100,"ZINFILL feof","",0);
#ifdef ZDEBUG 
	    printf("ZINFILL EOF\n");
#endif /* ZDEBUG */
	    return(-1);
	}
	clearerr(fp[ZIFILE]);
	zincnt = fread(zinbuffer, sizeof (char), INBUFSIZE, fp[ZIFILE]);
#ifdef DEBUG
	if (deblog)
	  debug(F101,"ZINFILL fread","",zincnt);
#endif /* DEBUG */
#ifdef ZDEBUG 
	printf("FREAD=%d\n",zincnt);
#endif /* ZDEBUG */

    if (ferror(fp[ZIFILE])) {
	debug(F100,"ZINFILL ferror","",0);
	debug(F100,"ZINFILL errno","",errno);
#ifdef ZDEBUG 
	printf("ZINFILL errno=%d\n",errno);
#endif /* ZDEBUG */
	return(-2);
    }
    /* In case feof() didn't work just above -- sometimes it doesn't... */
    if (zincnt == 0) {
       if (feof(fp[ZIFILE]) ) {
	   debug(F100,"ZINFILL count 0 EOF return -1","",0);
	   return (-1);
       } else {
	   debug(F100,"ZINFILL count 0 not EOF return -2","",0);
	   return(-2);
       }
    }
    zinptr = zinbuffer;	   /* set pointer to beginning, (== &zinbuffer[0]) */
    zincnt--;				/* One less char in buffer */
    return((int)(*zinptr++) & 0377);	/* because we return the first */
}

/*  Z S O U T  --  Write a string out to the given file, buffered.  */

int
zsout(n,s) int n; char *s; {
    int rc = 0;
    if (chkfn(n) < 1) return(-1);	/* Keep this, prevents memory faults */
    if (!s) return(0);			/* Null pointer, do nothing, succeed */
    if (!*s) return(0);			/* empty string, ditto */
    if (n == ZSFILE)
      return(write(fileno(fp[n]),s,(int)strlen(s)));
    rc = fputs(s,fp[n]) == EOF ? -1 : 0;
    if (n == ZWFILE)
      fflush(fp[n]);
    return(rc);
}

/*  Z S O U T L  --  Write string to file, with line terminator, buffered  */

int
zsoutl(n,s) int n; char *s; {
    if (zsout(n,s) < 0) 
        return(-1);
    if (n == ZSFILE)			/* But session log is unbuffered */
      return(write(fileno(fp[n]),"\n",1)); 
    if (fputs("\n",fp[n]) == EOF) 
      return(-1);
    return(0);
}

/*  Z S O U T X  --  Write x characters to file, unbuffered.  */

int
zsoutx(n,s,x) int n, x; char *s; {
#ifdef COMMENT
    if (chkfn(n) < 1) return(-1);
    return(write(fp[n]->_file,s,x));
#endif /* COMMENT */
    return(write(fileno(fp[n]),s,x) == x ? x : -1);
}

/*  Z C H O U T  --  Add a character to the given file.  */

/*  Should return 0 or greater on success, -1 on failure (e.g. disk full)  */

int
#ifdef CK_ANSIC
zchout(register int n, char c)
#else
zchout(n,c) register int n; char c;
#endif /* CK_ANSIC */
/* zchout() */ {
    /* if (chkfn(n) < 1) return(-1); */
    if (n == ZSFILE) 			/* Use unbuffered for session log */
    	return(write(fileno(fp[n]),&c,1) == 1 ? 0 : -1);
                                /* Buffered for everything else */
	if (putc(c,fp[n]) == EOF)	/* If true, maybe there was an error */
        return(ferror(fp[n])?-1:0);	/* Check to make sure */
	else    				/* Otherwise... */
        return(0);			/* There was no error. */
}

/* (PWP) buffered character output routine to speed up file IO */

int
zoutdump() {
    int x;
    char * zp;
    zoutptr = zoutbuffer;		/* Reset buffer pointer in all cases */
#ifdef DEBUG
    if (deblog)
      debug(F101,"zoutdump zoutcnt","",zoutcnt);
#endif /* DEBUG */
    if (zoutcnt == 0) {			/* Nothing to output */
	return(0);
    } else if (zoutcnt < 0) {		/* Unexpected negative argument */
	zoutcnt = 0;			/* Reset output buffer count */
	return(-1);			/* and fail. */
    }
/*
  Frank Prindle suggested that replacing this fwrite() by an fflush()
  followed by a write() would improve the efficiency, especially when
  writing to stdout.  Subsequent tests showed a 5-fold improvement.
*/
#ifdef COMMENT
    if (x = fwrite(zoutbuffer, 1, zoutcnt, fp[ZOFILE])) ...
#endif /* COMMENT */

#ifndef CK_NONBLOCK
    fflush(fp[ZOFILE]);
#endif /* CK_NONBLOCK */
    zp = zoutbuffer;
    while (zoutcnt > 0) {
	if ((x = write(fileno(fp[ZOFILE]),zp,zoutcnt)) > -1) {
#ifdef DEBUG
	    if (deblog)			/* Save a function call... */
	      debug(F101,"zoutdump wrote","",x);
#endif /* DEBUG */
	    zoutcnt -= x;		/* Adjust output buffer count */
	    zp += x;			/* and pointer */
	} else {
#ifdef DEBUG
	    if (deblog) {
		debug(F101,"zoutdump write error","",errno);
		debug(F101,"zoutdump write returns","",x);
	    }
#endif /* DEBUG */
	    zoutcnt = 0;		/* Reset output buffer count */
	    return(-1);			/* write() failed */
	}
    }
    return(0);
}

/*  C H K F N  --  Internal function to verify file number is ok  */

/*
 Returns:
  -1: File number n is out of range
   0: n is in range, but file is not open
   1: n in range and file is open
*/
int
chkfn(n) int n; {
#ifdef COMMENT				/* Save some stack space */
    switch (n) {
	case ZCTERM:
	case ZSTDIO:
	case ZIFILE:
	case ZOFILE:
	case ZDFILE:
	case ZTFILE:
	case ZPFILE:
	case ZSFILE:
	case ZSYSFN:
        case ZRFILE:
        case ZWFILE:
	    break;
	default:
	    debug(F101,"chkfn: file number out of range","",n);
	    fprintf(stderr,"?File number out of range - %d\n",n);
	    return(-1);
    }
    return( (fp[n] == NULL) ? 0 : 1 );
#else
    /* if (n != ZDFILE) debug(F101,"chkfn","",n); */
    if (n < 0 || n >= ZNFILS) {
	if (n != ZDFILE) debug(F101,"chkfn out of range","",n);
	return(-1);
    } else {
	/* if (n != ZDFILE) debug(F101,"chkfn fp[n]","",fp[n]); */
	return((fp[n] == NULL) ? 0 : 1);
    }
#endif /* COMMENT */
}

/*  Z C H K I  --  Check if input file exists and is readable  */

/*
  Returns:
   >= 0 if the file can be read (returns the size).
     -1 if file doesn't exist or can't be accessed,
     -2 if file exists but is not readable (e.g. a directory file).
     -3 if file exists but protected against read access.

  For Berkeley Unix, a file must be of type "regular" to be readable.
  Directory files, special files, and symbolic links are not readable.
*/
long
zchki(name) char *name; {
    struct stat buf;
    int x;

#ifdef UNIX
    x = strlen(name);
    if (x == 9 && !strcmp(name,"/dev/null"))
      return(0);
#endif /* UNIX */

    x = stat(name,&buf);
    if (x < 0) {
	debug(F111,"zchki stat fails",name,errno);
	return(-1);
    }
    if (!S_ISREG (buf.st_mode)		/* Must be regular file */
#ifdef S_ISFIFO
	&& !S_ISFIFO (buf.st_mode)	/* or FIFO */
#endif /* S_ISFIFO */
	) {				
	debug(F111,"zchki skipping:",name,x);
	return(-2);
    }
    debug(F111,"zchki stat ok:",name,x);

#ifdef SW_ACC_ID
    debug(F100,"zchki swapping ids for access()","",0);
    priv_on();
#endif /* SW_ACC_ID */
    x = access(name,R_OK);
#ifdef SW_ACC_ID
    priv_off();
    debug(F100,"zchki swapped ids restored","",0);
#endif /* SW_ACC_ID */
    if (x < 0) { 	/* Is the file accessible? */
	debug(F111,"zchki access failed:",name,x); /* No */
    	return(-3);
    } else {
	iflen = buf.st_size;		/* Yes, remember size */
	strncpy(nambuf,name,MAXNAMLEN); /* and name globally. */
	debug(F111,"zchki access ok:",name,iflen);
	return( (iflen > -1L) ? iflen : 0L );
    }
}

/*  Z C H K O  --  Check if output file can be created  */

/*
 Returns -1 if write permission for the file would be denied, 0 otherwise.
*/
int
zchko(name) char *name; {
    int i, x;
    char *s;

    if (!name) return(-1);		/* Watch out for null pointer. */
    x = (int)strlen(name);		/* Get length of filename */
    debug(F111,"zchko",name,x);

#ifdef UNIX
/*
  Writing to null device is OK.
*/
    if (x == 9 && !strcmp(name,"/dev/null"))
      return(0);
#endif /* UNIX */

    if (isdir(name))			/* Directories are not writeable */
      return(-1);

    s = malloc(x+3);			/* Must copy because we can't */
    if (!s) {				/* write into our argument. */
	fprintf(stderr,"zchko: Malloc error 46\n");
	return(-1);
    }
    strcpy(s,name);

    for (i = x; i > 0; i--)		/* Strip filename from right. */
      if (ISDIRSEP(s[i-1])) break;
    debug(F101,"zchko i","",i);

#ifdef COMMENT
/* X/OPEN XPG3-compliant systems fail if argument ends with "/"...  */
    if (i == 0)				/* If no path, use current directory */
      strcpy(s,"./");
    else				/* Otherwise, use given one. */
      s[i] = '\0';
#else
/* So now we use "path/." if path given, or "." if no path given. */
    s[i++] = '.';			/* Append "." to path. */
    s[i] = '\0';
#endif /* COMMENT */

#ifdef SW_ACC_ID
    debug(F100,"zchko swapping ids for access()","",0);
    priv_on();
#endif /* SW_ACC_ID */

    x = access(s,W_OK);			/* Check access of path. */

#ifdef SW_ACC_ID
    priv_off();
    debug(F100,"zchko swapped ids restored","",0);
#endif /* SW_ACC_ID */
    if (x < 0)
      debug(F111,"zchko access failed:",s,errno);
    else
      debug(F111,"zchko access ok:",s,x);
    free(s);				/* Free temporary storage */
    return((x < 0) ? -1 : 0);		/* and return. */
}

/*  Z D E L E T  --  Delete the named file.  */

int
zdelet(name) char *name; {
    return(unlink(name));
}

/*  Z R T O L  --  Convert remote filename into local form  */

VOID
zrtol(name,name2) char *name, *name2; {
    nzrtol(name,name2,1,0,CKMAXPATH);
}

VOID
nzrtol(name,name2,fncnv,fnrpath,max)
    char *name, *name2; int fncnv, fnrpath, max;
{ /* nzrtol */
    char *p; int flag = 0, n = 0;
    char tmpbuf[CKMAXPATH+1], *tmp;
    int devnull = 0;
    int acase = 0;
    if (!name2) return;
    if (!name) name = "";

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

    /* Handle the path -- we don't have to convert its format, since */
    /* the standard path format and our (UNIX) format are the same. */

    tmpbuf[0] = NUL;
    tmp = tmpbuf;
    devnull = !strcmp(name,"/dev/null");

    if (!devnull && fnrpath == PATH_OFF) { /* RECEIVE PATHNAMES OFF */
	zstrip(name,&p);
	strncpy(tmpbuf,p,CKMAXPATH);
    } else if (!devnull && fnrpath == PATH_ABS) { /* REC PATHNAMES ABSOLUTE */
	strncpy(tmpbuf,name,CKMAXPATH); 
    } else if (!devnull && isabsolute(name)) { /* RECEIVE PATHNAMES RELATIVE */
	sprintf(tmpbuf,".%s",name);
    } else {				/* Ditto */
	strncpy(tmpbuf,name,CKMAXPATH); 
    }
    tmpbuf[CKMAXPATH] = NUL;
    debug(F110,"nzrtol tmpbuf",tmpbuf,0);

    if (!fncnv || devnull) {		/* Not converting */
	strncpy(name2,tmpbuf,max);	/* We're done. */
	return;
    }
    name = tmpbuf;			/* Converting */

    p = name2;
    for (; *name != '\0' && n < maxnam; name++) {
	if (*name > SP) flag = 1;	/* Strip leading blanks and controls */
	if (flag == 0 && *name < '!')
	  continue;
	if (isupper(*name))		/* Check for mixed case */
	  acase |= 1;
	else if (islower(*name))
	  acase |= 2;
	*p++ = *name;
	n++;
    }
    *p-- = '\0';			/* Terminate */
    while (*p < '!' && p > name2)	/* Strip trailing blanks & controls */
      *p-- = '\0';

    if (*name2 == '\0') {		/* Nothing left? */
	strcpy(name2,"NONAME");		/* do this... */
    } else if (acase == 1) {		/* All uppercase? */
	p = name2;			/* So convert all letters to lower */
	while (*p) {
	    if (isupper(*p))
	      *p = tolower(*p);
	    p++;
	}
    }      
    debug(F110,"nzrtol new name",name2,0);
}


/*  Z S T R I P  --  Strip device & directory name from file specification */

/*  Strip pathname from filename "name", return pointer to result in name2 */

static char work[CKMAXPATH+1];

VOID
zstrip(name,name2) char *name, **name2; {
    char *cp, *pp;
    int n = 0;
    debug(F110,"zstrip before",name,0);
    if (!name) { *name2 = ""; return; }
    pp = work;
#ifdef DTILDE
    /* Strip leading tilde */
    if (*name == '~') name++;
    debug(F110,"zstrip after tilde-stripping",name,0);
#endif /* DTILDE */
    for (cp = name; *cp; cp++) {
    	if (ISDIRSEP(*cp)) {
	    pp = work;
	    n = 0;
	} else {
	    *pp++ = *cp;
	    if (n++ >= CKMAXPATH)
	      break;
	}
    }
    *pp = '\0';				/* Terminate the string */
    *name2 = work;
    debug(F110,"zstrip after",*name2,0);
}

/*  Z L T O R  --  Local TO Remote */

VOID
zltor(name,name2) char *name, *name2; {
    nzltor(name,name2,1,0,CKMAXPATH);
}

/*  N Z L T O R  --  New Local TO Remote */

VOID
nzltor(name,name2,fncnv,fnspath,max)
    char *name, *name2; int fncnv, fnspath, max;
{ /* nzltor */
    char *cp, *pp;
#ifdef COMMENT
    int dc = 0;
#endif /* COMMENT */
    int n = 0;
    char *dotp = NULL;
    char tmpbuf[CKMAXPATH+1];
    char *p;

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

    /* Handle pathname */
    
    tmpbuf[0] = NUL;
    if (fnspath == PATH_OFF) {		/* PATHNAMES OFF */
	zstrip(name,&p);
	strncpy(tmpbuf,p,CKMAXPATH);
	tmpbuf[CKMAXPATH] = NUL;
    } else {				/* PATHNAMES RELATIVE or ABSOLUTE */
	int x = 0;
	char * p = name;
	while (1) {
	    if (!strncmp(p,"../",3))
	      p += 3;
	    else if (!strncmp(p,"./",2))
	      p += 2;
	    else
	      break;
	}
	if (fnspath == PATH_ABS) {	/* ABSOLUTE */
	    zfnqfp(p,CKMAXPATH,tmpbuf);
	} else {			/* RELATIVE */
	    strncpy(tmpbuf,p,CKMAXPATH);
	}
    }
    debug(F110,"nzltor tmpbuf",tmpbuf,0);

    if (!fncnv) {			/* Not converting */
	strncpy(name2,tmpbuf,max);	/* We're done. */
	return;
    }
    name = tmpbuf;			/* Converting */

#ifdef aegis
    char *namechars;
    int tilde = 0, bslash = 0;

    if ((namechars = getenv("NAMECHARS")) != NULL) {
    	if (xindex(namechars, '~' ) != NULL) tilde  = '~';
    	if (xindex(namechars, '\\') != NULL) bslash = '\\';
    } else {
        tilde = '~';
        bslash = '\\';
    }
#endif /* aegis */

    pp = work;				/* Output buffer */
    for (cp = name, n = 0; *cp && n < max; cp++,n++) { /* Strip path name */
#ifdef COMMENT
	/* Not any more - we just did this */
	if (ISDIRSEP(*cp)) {
	    dc = 0;			/* Start over... */
	    dotp = NULL;
	    pp = work;
	} else 
#endif /* COMMENT */
	if (islower(*cp))		/* Uppercase letters */
	  *pp++ = toupper(*cp);		/* Change tilde to 'X' */
	else if (*cp == '~')
	  *pp++ = 'X';
	else if (*cp == '#')		/* Change number sign to 'X' */
	  *pp++ = 'X';
	else if (*cp == '*' || *cp == '?')
	  *pp++ = 'X';
	else if (*cp <= ' ')		/* Change space and controls to 'X' */
	  *pp++ = 'X';
	else if (*cp == '.') {		/* Change dot to underscore */
	    dotp = pp;			/* Remember where we last did this */
	    *pp++ = '_';
	} else
	  *pp++ = *cp;
    }
    *pp = NUL;				/* Tie it off. */
    if (dotp) *dotp = '.';		/* Restore last dot (if any) */
    cp = name2;				/* If nothing before dot, */
    if (*work == '.') *cp++ = 'X';	/* insert 'X' */
    strncpy(cp,work,max);
    debug(F110,"nzltor name2",name2,0);
}


/*  Z C H D I R  --  Change directory  */
/*
  Call with:
    dirnam = pointer to name of directory to change to,
      which may be "" or NULL to indicate user's home directory.
  Returns:
    0 on failure
    1 on success
*/
int
zchdir(dirnam) char *dirnam; {
    char *hd, *sp, *p;

    debug(F110,"zchdir",dirnam,0);
    if (dirnam == NULL || dirnam == "" || *dirnam == '\0') /* If arg is null */
      dirnam = zhome();			/* use user's home directory. */
    sp = dirnam;
    debug(F110,"zchdir 2",dirnam,0);

#ifdef DTILDE
    hd = tilde_expand(dirnam);		/* Attempt to expand tilde */
    if (*hd == '\0') hd = dirnam;	/* in directory name. */
#else
    hd = dirnam;
#endif /* DTILDE */
    debug(F110,"zchdir 3",hd,0);

#ifdef pdp11
    /* Just to save some space */
    return((chdir(hd) == 0) ? 1 : 0);
#else
    if (chdir(hd) == 0)			/* Try to cd */
      return(1);
    else
      return(0);

#ifdef COMMENT
/* This doesn't help in Windows or OS/2, and it's wrong in UNIX */
    p = sp;				/* Failed, lowercase it. */
    while (*p) {
	if (isupper(*p)) *p = tolower(*p);
	p++;
    }
    debug(F110,"zchdir 4",hd,0);
#ifdef DTILDE
    hd = tilde_expand(sp);		/* Try again to expand tilde */
    if (*hd == '\0') hd = sp;
#else
    hd = sp;				/* Point to result */
#endif /* DTILDE */
    debug(F110,"zchdir 5",hd,0);
    return((chdir(hd) == 0) ? 1 : 0);
#endif /* COMMENT */

#endif /* pdp11 */
}

/*  Z H O M E  --  Return pointer to user's home directory  */

char *
zhome() {
#ifdef Plan9
    char *home = getenv("home");
#else
    char *home = getenv("HOME");
#endif /* Plan9 */
    return(home ? home : ".");
}

/*  Z G T D I R  --  Return pointer to user's current directory  */

#ifdef pdp11
#define CWDBL 80			/* Save every byte we can... */
#else
#define CWDBL MAXPATH
#endif /* pdp11 */
static char cwdbuf[CWDBL+1];

char *
zgtdir() {
    char *buf;
    int x;

#ifdef BSD44
    extern char *getcwd();
    buf = cwdbuf;
    debug(F101,"zgtdir CWDBL","",CWDBL);
    return(getcwd(buf,CWDBL));
#else
#ifdef MINIX2
    extern char *getcwd();
    buf = cwdbuf;
    debug(F101,"zgtdir CWDBL","",CWDBL);
    return(getcwd(buf,CWDBL));
#else
#ifdef SVORPOSIX
    extern char *getcwd();
    buf = cwdbuf;
    debug(F101,"zgtdir CWDBL","",CWDBL);
    return(getcwd(buf,CWDBL));
#else
#ifdef COHERENT
#ifdef _I386
    extern char *getcwd();
    buf = cwdbuf;
    debug(F101,"zgtdir CWDBL","",CWDBL);
    return(getcwd(buf,CWDBL));
#else
    extern char *getwd();
    buf = cwdbuf;
    debug(F101,"zgtdir CWDBL","",CWDBL);
    return(getwd(buf));
#endif /* _I386 */
#else
#ifdef BSD4
    extern char *getwd();
    char *s;
    buf = cwdbuf;
    s = getwd(buf);
    debug(F110,"zgtdir getwd()",s,0);
    if (!s) s = "";
    return(s);
#else
    return("directory unknown");
#endif /* BSD4 */
#endif /* COHERENT */
#endif /* SYSVORPOSIX */
#endif /* MINIX2 */
#endif /* BSD44 */
}

/*  Z X C M D -- Run a system command so its output can be read like a file */

#ifndef NOPUSH
int
zxcmd(filnum,comand) int filnum; char *comand; {
    int out;
    int pipes[2];

    debug(F111,"zxcmd",comand,filnum);
    if (chkfn(filnum) < 0) return(-1);	/* Need a valid Kermit file number. */
    if (filnum == ZSTDIO || filnum == ZCTERM) /* But not one of these. */
      return(0);

    out = (filnum == ZIFILE || filnum == ZRFILE) ? 0 : 1 ;
    debug(F101,"zxcmd out",comand,out);

/* Output to a command */

    if (out) {				/* Need popen() to do this. */
#ifdef NOPOPEN
	return(0);			/* no popen(), fail. */
#else
/* Use popen() to run the command. */

#ifdef _POSIX_SOURCE
/* Strictly speaking, popen() is not available in POSIX.1 */
#define DCLPOPEN
#endif /* _POSIX_SOURCE */

#ifdef COHERENT
#define DCLPOPEN
	FILE * fdopen();
#endif /* COHERENT */

#ifdef DCLPOPEN
	/* popen() needs declaring because it's not declared in <stdio.h> */
	FILE *popen();
#endif /* DCLPOPEN */

	if (priv_chk() || ((fp[filnum] = popen(comand,"w")) == NULL)) {
	    return(0);
	} else { 
#ifdef COMMENT
/* I wonder what this is all about... */
	    close(pipes[0]);		       /* Don't need the input side */
	    fp[filnum] = fdopen(pipes[1],"w"); /* Open a stream for output. */
	    fp[ZSYSFN] = fp[filnum];	       /* Remember. */
#endif /* COMMENT */
	    ispipe[filnum] = 1;
	    zoutcnt = 0;		       /* (PWP) reset input buffer */
	    zoutptr = zoutbuffer;
	    return(1);
	}
#endif /* NOPOPEN */
    }

/* Input from a command */

    if (pipe(pipes) != 0) {
	debug(F100,"zxcmd pipe failure","",0);
	return(0);			/* can't make pipe, fail */
    }

/* Create a fork in which to run the named process */

    if ((
#ifdef aegis
	 pid = vfork()			/* child */
#else
	 pid = fork()			/* child */
#endif /* aegis */
	 ) == 0) {

/* We're in the fork. */

	char *shpath, *shname, *shptr;	/* Find user's preferred shell */
#ifndef aegis
	struct passwd *p;
	char *defshell;
#ifdef HPUX10				/* Default shell */
	defshell = "/usr/bin/sh";
#else
#ifdef Plan9
	defshell = "/bin/rc";
#else
	defshell = "/bin/sh";
#endif /* Plan9 */
#endif /* HPUX10 */
#endif /* aegis */
	if (priv_can()) exit(1);	/* Turn off any privileges! */
	debug(F101,"zxcmd pid","",pid);
	close(pipes[0]);		/* close input side of pipe */
	close(0);			/* close stdin */
	if (open("/dev/null",0) < 0) return(0); /* replace input by null */
#ifndef OXOS
#ifndef SVORPOSIX
	dup2(pipes[1],1);		/* BSD: replace stdout & stderr */
	dup2(pipes[1],2);		/* by the pipe */
#else
	close(1);			/* AT&T: close stdout */
	if (dup(pipes[1]) != 1)		/* Send stdout to the pipe */
	  return(0);
	close(2);			/* Send stderr to the pipe */
	if (dup(pipes[1]) != 2)
	  return(0);
#endif /* SVORPOSIX */
#else /* OXOS */
	dup2(pipes[1],1);
	dup2(pipes[1],2);
#endif /* OXOS */
	close(pipes[1]);		/* Don't need this any more. */

#ifdef aegis
	if ((shpath = getenv("SERVERSHELL")) == NULL)
	  shpath = "/bin/sh";
#else
	shpath = getenv("SHELL");	/* What shell? */
	if (shpath == NULL) {
	    p = getpwuid( real_uid() );	/* Get login data */
	    if (p == (struct passwd *)NULL || !*(p->pw_shell))
	      shpath = defshell;
	    else shpath = p->pw_shell;
        }
#endif /* aegis */
	shptr = shname = shpath;
	while (*shptr != '\0')
	  if (*shptr++ == '/')
	    shname = shptr;
	debug(F100,"zxcmd...","",0);
	debug(F110,shpath,shname,0);

	execl(shpath,shname,"-c",comand,(char *)NULL); /* Execute the cmd */
	exit(0);			/* just punt if it failed. */
    } else if (pid == (PID_T) -1) {
	debug(F100,"zxcmd fork failure","",0);
	return(0);
    }
    debug(F101,"zxcmd pid","",pid);
    close(pipes[1]);			/* Don't need the output side */
    ispipe[filnum] = 1;			/* Remember it's a pipe */
    fp[filnum] = fdopen(pipes[0],"r"); 	/* Open a stream for input. */
    fp[ZSYSFN] = fp[filnum];		/* Remember. */
    zincnt = 0;				/* (PWP) reset input buffer */
    zinptr = zinbuffer;
    return(1);
} /* zxcmd */

/*  Z C L O S F  - wait for the child fork to terminate and close the pipe. */

/*  Used internally by zclose - returns -1 on failure, 1 on success. */

int
zclosf(filnum) int filnum; {
    int wstat, out;
    int statusp;

    debug(F101,"zclosf filnum","",filnum);
    out = (filnum == ZIFILE || filnum == ZRFILE) ? 0 : 1 ;
    debug(F101,"zclosf out","",out);

#ifndef NOPOPEN
    if (ispipe[filnum]
	/* In UNIX we use popen() only for output files */
	&& out
	) {
	int x;
	x = pclose(fp[filnum]);
  	pexitstat = x >> 8;
	debug(F101,"zclosf pclose","",x);
	debug(F101,"zclosf pexitstat","",pexitstat);
	fp[filnum] = fp[ZSYSFN] = NULL;
	ispipe[filnum] = 0;
	return((x != 0) ? -1 : 1);
    }
#endif /* NOPOPEN */
    debug(F101,"zclosf fp[filnum]","", fp[filnum]);
    debug(F101,"zclosf fp[ZSYSFN]","", fp[ZSYSFN]);

    if (pid != (PID_T) 0) {
	debug(F101,"zclosf killing pid","",pid);
#ifdef Plan9
	kill(pid, SIGKILL);
#else
	kill(pid,9);
#endif /* Plan9 */

#ifndef CK_CHILD
/*
  This is the original code (before 20 April 1997) and has proven totally
  portable.  But it does not give us the process's return code.
*/
        while ((wstat = wait((WAIT_T *)0)) != pid && wstat != -1) ;
#else
/* Here we try to get the return code.  Let's hope this is portable too. */
	while ((wstat = wait(&statusp)) != pid && wstat != -1) ;
	pexitstat = (statusp & 0xff) ? statusp : statusp >> 8;
	debug(F101,"zclosf wait statusp","",statusp);
	debug(F101,"zclosf wait pexitstat","",pexitstat);
#endif /* CK_CHILD */
        pid = 0;
    }
    fclose(fp[filnum]);
    fp[filnum] = fp[ZSYSFN] = NULL;

    ispipe[filnum] = 0;
    debug(F101,"zclosf fp[filnum]","",fp[filnum]);
#ifdef CK_CHILD
    return(pexitstat == 0 ? 1 : -1);
#else
    return(1);
#endif /* CK_CHILD */
}

#else  /* NOPUSH */

int
zxcmd(filnum,comand) int filnum; char *comand; {
    return(0);
}
int
zclosf(filnum) int filnum; {
    return(EOF);
}
#endif /* NOPUSH */


/*  Z X P A N D  --  Expand a wildcard string into an array of strings  */
/*
  Returns the number of files that match fn1, with data structures set up
  so that first file (if any) will be returned by the next znext() call.

  Depends on external variable wildxpand: 0 means we expand wildcards
  internally, nonzero means we call the shell to do it.
*/
int
zxpand(fn) char *fn; {
    char *p;
#ifdef DTILDE				/* Built with tilde-expansion? */
    char *tnam;
#endif /* DTILDE */
    int x;

    debug(F111,"zxpand entry",fn,wildxpand);
    if (!fn)				/* If no argument provided */
      return(0);			/* Return zero files found */
    if (!(*fn))
      return(0);

#ifdef DTILDE				/* Built with tilde-expansion? */
    if (*fn == '~') {			/* Starts with tilde? */
	tnam = tilde_expand(fn);	/* Try to expand it. */
	if (tnam) fn = tnam;
    }
    debug(F110,"zxpand after tilde_x",fn,0);
#endif /* DTILDE */

    x = isdir(fn);
    debug(F111,"zxpand isdir",fn,1);
    if (x) {
	x = strlen(fn);
	if (!ISDIRSEP(fn[x-1]))
	  fn[x++] = DIRSEP;
	fn[x++] = '*';
	fn[x] = '\0';
    }

#ifndef NOPUSH
    if (!nopush && wildxpand)		/* Who is expanding wildcards? */
      fcount = (mtchs == NULL &&	/* Shell */
		(mtchs = (char **)malloc(MAXWLD * sizeof(*mtchs))) == NULL)
	? 0
	  :  shxpand(fn,mtchs,MAXWLD);
    else
#endif /* NOPUSH */
      fcount = (mtchs == NULL &&	/* Kermit */
		(mtchs = (char **)malloc(MAXWLD * sizeof(*mtchs))) == NULL)
	? 0
	  : fgen(fn,mtchs,MAXWLD);	/* Look up the file. */

#ifndef COMMENT
    mtchptr = mtchs;			/* Save pointer for next. */
    debug(F111,"zxpand ok",mtchs[0],fcount);
    return(fcount);
#else
/*
  No, this can produce unpredictable results, like sending files
  from the wrong directory.
*/
    if (fcount > 0) {
	mtchptr = mtchs;		/* Save pointer for next. */
	debug(F111,"zxpand ok",mtchs[0],fcount);
	return(fcount);
    }
    debug(F111,"zxpand fgen1",fn,fcount); /* Didn't get one, or got too many */
    p = malloc((int)strlen(fn) + 10);	/* Make space */
    if (!p) return(0);
    zrtol(fn,p);			/* Try again, maybe lowercase */

#ifndef NOPUSH
    if (!nopush && wildxpand)
      fcount = shxpand(p,mtchs,MAXWLD); /* Shell */
    else
#endif /* NOPUSH */
      fcount = fgen(p,mtchs,MAXWLD);	/* Kermit */
    if (fcount > 0) {			/* Got at least one? */
	mtchptr = mtchs;		/* Save pointer for next. */
	debug(F111,"zxpand fgen2 ok",mtchs[0],fcount);
    } else debug(F111,"zxpand 2 not ok",p,fcount);
    free(p);
    return(fcount);
#endif /* COMMENT */
}


/*  Z N E X T  --  Get name of next file from list created by zxpand(). */
/*
  Returns >0 if there's another file, with its name copied into the arg string,
  or 0 if no more files in list.
*/
int
znext(fn) char *fn; {
    if (fcount-- > 0) strcpy(fn,*mtchptr++);
    else *fn = '\0';
    debug(F111,"znext",fn,fcount+1);
    return(fcount+1);
}

/*  Z C H K S P A  --  Check if there is enough space to store the file  */

/*
 Call with file specification f, size n in bytes.
 Returns -1 on error, 0 if not enough space, 1 if enough space.
*/
int
#ifdef CK_ANSIC
zchkspa(char *f, long n)
#else
zchkspa(f,n) char *f; long n;
#endif /* CK_ANSIC */
/* zchkspa() */ {
    /* In UNIX there is no good (and portable) way. */
    return(1);				/* Always say OK. */
}


/*  Z N E W N  --  Make a new name for the given file  */

/*
  Given the name, fn, of a file that already exists, this function builds a
  new name of the form "<oldname>.~<n>~", where <oldname> is argument name
  (fn), and <n> is a version number, one higher than any existing version
  number for that file, up to 9999.  This format is consistent with that used
  by GNU EMACS.  If the constructed name is too long for the system's maximum,
  enough characters are truncated from the end of <fn> to allow the version
  number to fit.  If no free version numbers exist between 1 and 9999, a
  version number of "xxxx" is used.  Returns a pointer to the new name in
  argument s.
*/

VOID
znewn(fn,s) char *fn, **s; {
#ifdef pdp11
#define ZNEWNBL 63			/* Name buffer length */
#define ZNEWNMD 3			/* Max digits for version number */
#else
#define ZNEWNBL 255
#define ZNEWNMD 4
#endif /* pdp11 */

    static char buf[ZNEWNBL+1];
    char *bp, *xp, *yp;
    int len = 0, d = 0, n, t, i, j, k, power = 1;

    int max = MAXNAMLEN;		/* Maximum name length */

    if (max < 14) max = 14;		/* Make it reasonable */
    if (max > ZNEWNBL) max = ZNEWNBL;
    bp = buf;				/* Buffer for building new name */
    yp = fn;
    while (*yp) {			/* Copy old name into buffer */
	*bp++ = *yp++;
	if (len++ > ZNEWNBL) break;	/* ...up to buffer length */
    }
    *s = NULL;
    for (i = 1; i < ZNEWNMD + 1; i++) {	/* Version numbers up to 10**i - 1 */
	power *= 10;			/* Next power of 10 */
	j = max - len;			/* Space left for version number */
	k = 3 + i;			/* Space needed for it */
	if (j < k) {			/* Make room if necessary */
	    len -= (k - j);		/* Adjust length of filename */
	    bp = buf + len;		/* Point to new end */
	}
	*bp++ = '*';			/* Put a star on the end (UNIX) */
	*bp-- = '\0';			/* Terminate with null */

	debug(F110,"znewn: about to expand",buf,0);
	n = zxpand(buf);		/* Expand the resulting wild name */
					/* n is the number of matches */
	debug(F101,"znewn matches","",n);
	while (n-- > 0) {		/* Find any existing name.~n~ files */
	    xp = *mtchptr++;		/* Point at matching name */
	    xp += len;			/* Look for .~<n>~ at the end of it */
	    if (*xp == '.' && *(xp+1) == '~') {	/* Has a version number */
		t = atoi(xp+2);		        /* Get it */
		if (t > d) d = t;	/* Save d = highest version number */
	    }
	}
	if (d < power-1) {		/* Less than maximum possible? */
	    debug(F110,"znewn number ok",buf,0);
	    sprintf(bp,".~%d~",d+1);	/* Yes, make "name.~<d+1>~" */
	    *s = buf;			/* Point to new name */
	    ck_znewn = d+1;		/* Also make it available globally */
	    break;			/* Done, return it */
	}
    }
    if (*s == NULL) {
	debug(F110,"znewn: too many names",buf,0);
	sprintf(bp,".~xxxx~");		/* Too many, use xxxx. */
	ck_znewn = -1;			/* Also make it available globally */
	*s = buf;
    }
    {
	char *p;
	p = (char *) malloc(ZNEWNBL+1);	/* Get fully qualified name */
	if (p) {
	    if (zfnqfp(buf, ZNEWNBL, p))
	      strncpy(buf,p,ZNEWNBL);
	    free(p);
	}
    }
    return;
}

/*  Z R E N A M E  --  Rename a file  */
/*
   Call with old and new names.
   If new name is the name of a directory, the 'old' file is moved to
   that directory.
   Returns 0 on success, -1 on failure.
*/
int
zrename(old,new) char *old, *new; {
    char *p = NULL, *s = new;
    int x;

    debug(F110,"zrename old",old,0);
    debug(F110,"zrename new",s,0);
    if (isdir(new)) {
	char *q = NULL;
	x = strlen(new);
	if (!(p = malloc(strlen(new) + strlen(old) + 2)))
	  return(-1);
	strcpy(p,new);			/* Directory part */
	if (!ISDIRSEP(*(new+x-1)))	/* Separator, if needed */
	  strcat(p,"/");
	zstrip(old,&q);			/* Strip path part from old name */
	strcat(p,q);			/* Concatenate to new directory */
	s = p;
	debug(F110,"zrename dir",s,0);
    } else debug(F110,"zrename no dir",s,0);
#ifdef RENAME
/*
  Atomic, preferred, uses a single system call, rename(), if available.
  OS/2 rename() returns nonzero, but not necessarily -1 (?), on failure.
*/
    x = rename(old,s);
    if (p) free(p);
    return(x ? -1 : 0);
#else /* !RENAME */
/*
  This way has a window of vulnerability.
*/
    x = -1;				/* Return code. */
    if (link(old,s) < 0) {		/* Make a link with the new name. */
	debug(F111,"zrename link fails, errno",old,errno);
    } else if (unlink(old) < 0) {	/* Unlink the old name. */
	debug(F111,"zrename unlink fails, errno",old,errno);
    } else x = 0;
    if (p) free(p);
    return(x);
#endif /* RENAME */
}

/*  Z C O P Y  --  Copy a file  */
/*
   Call with source and destination names.
   If destination name is the name of a directory, the source file is
   copied to that directory with the original name.
   Returns 0 on success, -1 on failure.
*/
int
zcopy(source,destination) char *source, *destination; {
    char *p = NULL, *s = destination;
    int x;
    
    debug(F110,"zcopy source",source,0);
    debug(F110,"zcopy destination",s,0);
    if (isdir(destination)) {
	char *q = NULL;
	x = strlen(destination);
	if (!(p = malloc(strlen(destination) + strlen(source) + 2)))
	  return(-1);
	strcpy(p,destination);		/* Directory part */
	if (!ISDIRSEP(*(destination+x-1))) /* Separator, if needed */
	  strcat(p,"/");
	zstrip(source,&q);		/* Strip path part from old name */
	strcat(p,q);			/* Concatenate to new directory */
	s = p;
	debug(F110,"zcopy dir",s,0);
    } else debug(F110,"zcopy no dir",s,0);

    {
	int n; char *p = NULL;
	n = (int) strlen(source) + (int) strlen(destination);
	if (p = (char *) malloc(n+6)) {
	    sprintf(p,"%s %s %s",CPYCMD,source,destination);
	    x = zsyscmd(p);		/* This is cp's exit status */
	    if (x != 0) x = -1;
	} else x = -1;
	if (p) free(p);
    }
    return(x);
}

/*  Z S A T T R */
/*
 Fills in a Kermit file attribute structure for the file which is to be sent.
 Returns 0 on success with the structure filled in, or -1 on failure.
 If any string member is null, then it should be ignored.
 If any numeric member is -1, then it should be ignored.
*/
#ifdef CK_PERMS

#ifdef CK_GPERMS
#undef CK_GPERMS
#endif /* CK_GPERMS */

#ifdef UNIX
#ifndef S_IRUSR
#define S_IRUSR 0400
#endif /* S_IRUSR */
#ifndef S_IWUSR
#define S_IXUSR 0200
#endif /* S_IWUSR */
#ifndef S_IXUSR
#define S_IXUSR 0100
#endif /* S_IXUSR */
#endif /* UNIX */

#ifdef S_IRUSR
#ifdef S_IWUSR
#ifdef S_IXUSR
#define CK_GPERMS
#endif /* S_IXUSR */
#endif /* S_IWUSR */
#endif /* S_IRUSR */    

static char gperms[2];

#endif /* CK_GPERMS */

static char lperms[24];

#ifdef CK_PERMS
static char xlperms[24];

char *
zgperm(f) char *f; {
    int x; char *s = (char *)xlperms;
    struct stat buf;
    debug(F110,"zgperm",f,0);
    if (!f) return(NULL);
    if (!*f) return(NULL);
    x = stat(f,&buf);
    if (x < 0)
      return(NULL);
    sprintf(s,"%o",buf.st_mode);
    debug(F110,"zgperm",s,0);
    return(s);
}
#else
char *
zgperm(f) char *f; {
    return(NULL);
}
#endif /* CK_PERMS */

int
zsattr(xx) struct zattr *xx; {
    long k; int x;
    struct stat buf;

    k = iflen % 1024L;			/* File length in K */
    if (k != 0L) k = 1L;
    xx->lengthk = (iflen / 1024L) + k;
    xx->type.len = 0;			/* File type can't be filled in here */
    xx->type.val = "";
    if (*nambuf) {
	xx->date.val = zfcdat(nambuf);	/* File creation date */
	xx->date.len = (int)strlen(xx->date.val);
    } else {
	xx->date.len = 0;
	xx->date.val = "";
    }
    xx->creator.len = 0;		/* File creator */
    xx->creator.val = "";
    xx->account.len = 0;		/* File account */
    xx->account.val = "";
    xx->area.len = 0;			/* File area */
    xx->area.val = "";
    xx->password.len = 0;		/* Area password */
    xx->password.val = "";
    xx->blksize = -1L;			/* File blocksize */
    xx->xaccess.len = 0;		/* File access */
    xx->xaccess.val = "";
    xx->encoding.len = 0;		/* Transfer syntax */
    xx->encoding.val = 0;
    xx->disp.len = 0;			/* Disposition upon arrival */
    xx->disp.val = "";
    xx->lprotect.len = 0;		/* Local protection */
    xx->lprotect.val = "";
    xx->gprotect.len = 0;		/* Generic protection */
    xx->gprotect.val = "";
    x = -1;
    if (*nambuf) x = stat(nambuf,&buf);
    if (x >= 0) {
	debug(F111,"zsattr buf.st_mode & 0777",nambuf,buf.st_mode & 0777);
	/* UNIX filemode as an octal string without filetype bits */
	sprintf(lperms,"%o",buf.st_mode & 0777);
	xx->lprotect.len = (int)strlen(lperms);
	xx->lprotect.val = (char *)lperms;
	x = 0;
#ifdef CK_GPERMS
	/* Generic permissions only if we have stat.h symbols defined */
	if (buf.st_mode & S_IRUSR) x |= 1;      /* Read */
	if (buf.st_mode & S_IWUSR) x |= (2+16); /* Write and Delete */
	if (buf.st_mode & S_IXUSR) x |= 4;      /* Execute */
	gperms[0] = tochar(x);
	gperms[1] = NUL;
	xx->gprotect.len = 1;
	xx->gprotect.val = (char *)gperms;
#endif /* CK_GPERMS */
    }
    debug(F111,"zsattr lperms",xx->lprotect.val,xx->lprotect.len);
    debug(F111,"zsattr gperms",xx->gprotect.val,xx->gprotect.len);
    xx->systemid.val = "U1";		/* U1 = UNIX */
    xx->systemid.len = 2;		/* System ID */
    xx->recfm.len = 0;			/* Record format */
    xx->recfm.val = "";
    xx->sysparam.len = 0;		/* System-dependent parameters */
    xx->sysparam.val = "";
    xx->length = iflen;			/* Length */
    return(0);
}

/* Z F C D A T  --  Get file creation date */
/*
  Call with pointer to filename.
  On success, returns pointer to modification date in yyyymmdd hh:mm:ss format.
  On failure, returns pointer to null string.
*/
static char datbuf[40];

char * 
#ifdef CK_ANSIC
zdtstr(time_t time)
#else
zdtstr(time) time_t time;
#endif /* CK_ANSIC */
/* zdtstr */ {
#ifndef TIMESTAMP
    return("");
#else
    struct tm * time_stamp;
    struct tm * localtime();
    int yy, ss;

    debug(F101,"zdatstr time","",time);
    if (time < 0)
      return("");
    time_stamp = localtime(&(time));
    if (!time_stamp) {
	debug(F100,"localtime returns null","",0);
	return("");
    }
    yy = time_stamp->tm_year;		/* Year - 1900 */
    yy += 1900;
    debug(F101,"zdatstr year","",yy);
#ifdef COMMENT
    if (yy < 1970)			/* By definition of C library */
      return("");
#endif /* COMMENT */

    if (time_stamp->tm_mon  < 0 || time_stamp->tm_mon  > 11)
      return("");
    if (time_stamp->tm_mday < 0 || time_stamp->tm_mday > 31)
      return("");
    if (time_stamp->tm_hour < 0 || time_stamp->tm_hour > 23)
      return("");
    if (time_stamp->tm_min  < 0 || time_stamp->tm_min  > 59)
      return("");
    ss = time_stamp->tm_sec;		/* Seconds */
    if (ss < 0 || ss  > 59)		/* Some systems give a BIG number */
      ss = 0;
    sprintf(datbuf,
#ifdef pdp11
/* For some reason, 2.1x BSD sprintf gets the last field wrong. */
	    "%04d%02d%02d %02d:%02d:00",
#else
	    "%04d%02d%02d %02d:%02d:%02d",
#endif /* pdp11 */
	    yy,
	    time_stamp->tm_mon + 1,
	    time_stamp->tm_mday,
	    time_stamp->tm_hour,
	    time_stamp->tm_min
#ifndef pdp11
	    , ss
#endif /* pdp11 */
	    );
    yy = (int)strlen(datbuf);
    debug(F111,"zdatstr",datbuf,yy);
    if (yy > 17) datbuf[17] = '\0';
    return(datbuf);
#endif /* TIMESTAMP */
}

char *
zfcdat(name) char *name; {
#ifdef TIMESTAMP
    struct stat buffer;
    datbuf[0] = '\0';
    if (stat(name,&buffer) != 0) {
	debug(F110,"zfcdat stat failed",name,0);
	return("");
    }
    return(zdtstr(buffer.st_mtime));
#else
    return("");
#endif /* TIMESTAMP */
}

#ifndef NOTIMESTAMP
time_t
zstrdt(date,len) char * date; int len; {
/*
  To do: adapt code from OS-9 Kermit's ck9fio.c zstime function, which
  is more flexible, allowing [yy]yymmdd[ hh:mm[:ss]].
*/
#ifdef M_UNIX
/*
  SCO UNIX 3.2v2.0 and ODT 2.0 lack prototypes for ftime().
  ODT 3.0 (3.2v4.2 OS) has a prototype, which may vary in
  dependence on the XPG4 supplement presence.  So always use
  what the system header file supplies in ODT 3.0...
*/
#ifndef ODT30
#ifndef _SCO_DS
    extern void ftime();  /* extern void ftime(struct timeb *) */
#endif /* _SCO_DS */
#endif /* ODT30 */
#else
    extern int ftime();    
#endif /* M_UNIX */
    extern int stat();
    extern struct tm * localtime();

    /* And this should have been declared always through a header file */
#ifdef HPUX10
    time_t tmx;
    long days;
#else
    long tmx, days;
#endif /* HPUX10 */
    int i, n, isleapyear;
                   /*       J  F  M  A   M   J   J   A   S   O   N   D   */
                   /*      31 28 31 30  31  30  31  31  30  31  30  31   */
    static
    int monthdays [13] = {  0,0,31,59,90,120,151,181,212,243,273,304,334 };
    char s[5];
    struct tm *time_stamp;

#ifdef BSD44
    struct timeval tp[2];
    long xtimezone;
#else
#ifdef V7
    struct utimbuf {
      time_t timep[2];		/* New access and modificaton time */
    } tp;
    char *tz;
    long timezone;		/* In case timezone not defined in .h file */
#else
#ifdef SYSUTIMEH
    struct utimbuf tp;
#else
    struct utimbuf {
	time_t atime;
	time_t mtime;
    } tp;
#endif /* SYSUTIMEH */
#endif /* V7 */
#endif /* BSD44 */

#ifdef ANYBSD
    long timezone = 0L;
    static struct timeb tbp;
#endif /* ANYBSD */

#ifdef BEBOX
    long timezone = 0L;
#endif /* BEBOX */

    debug(F111,"zstrdt",date,len);

    if ((len == 0)
        || (len != 17)
        || (date[8] != ' ')
        || (date[11] != ':')
        || (date[14] != ':') ) {
        debug(F111,"Bad creation date ",date,len);
        return(-1);
    }
    debug(F111,"zstrdt date check 1",date,len);
    for(i = 0; i < 8; i++) {
	if (!isdigit(date[i])) {
	    debug(F111,"Bad creation date ",date,len);
	    return(-1);
	}
    }
    debug(F111,"zstrdt date check 2",date,len);
    i++;

    for (; i < 16; i += 3) {
	if ((!isdigit(date[i])) || (!isdigit(date[i + 1]))) {
	    debug(F111,"Bad creation date ",date,len);
	    return(-1);
	}
    }
    debug(F111,"zstrdt date check 3",date,len);

#ifdef BSD44
    {
	int x;
	struct timezone tzp;
	x = gettimeofday(NULL, &tzp);
	debug(F101,"zstrdt BSD44 gettimeofday","",x);
	if (x > -1)
	  xtimezone = tzp.tz_minuteswest * 60L;
	else
	  xtimezone = 0L;
	debug(F101,"zstrdt BSD44 timezone","",xtimezone);
    }
#else
#ifdef ANYBSD
    debug(F100,"zstrdt BSD calling ftime","",0);
    ftime(&tbp);
    debug(F100,"zstrdt BSD back from ftime","",0);
    timezone = tbp.timezone * 60L;
    debug(F101,"zstrdt BSD timezone","",timezone);
#else
#ifdef SVORPOSIX
    tzset();				/* Set timezone */
#else
#ifdef V7
    if ((tz = getenv("TZ")) == NULL)
      timezone = 0;			/* UTC/GMT */
    else
      timezone = atoi(&tz[3]);		/* Set 'timezone'. */
    timezone *= 60L;
#endif /* V7 */
#endif /* SVORPOSIX */
#endif /* ANYBSD */
#endif /* BSD44 */

    debug(F100,"zstrdt so far so good","",0);

    s[4] = '\0';
    for (i = 0; i < 4; i++)		/* Fix the year */
      s[i] = date[i];

    n = atoi(s);
    debug(F111,"zstrdt year",s,n);
    if (n < 1970) {
	debug(F100,"zstrdt fails - year","",n);
	return(-1);
    }

/*  Previous year's leap days.  This won't work after year 2100. */

    isleapyear = (( n % 4 == 0 && n % 100 !=0) || n % 400 == 0);
    days = (long) (n - 1970) * 365;
    days += (n - 1968 - 1) / 4 - (n - 1900 - 1) / 100 + (n - 1600 - 1) / 400;

    s[2] = '\0';

    for (i = 4; i < 16; i += 2) {
	s[0] = date[i];
	s[1] = date[i + 1];
	n = atoi(s);
	switch (i) {
	  case 4:			/* MM: month */
	    if ((n < 1 ) || ( n > 12)) {
		debug(F111,"zstrdt 4 bad date ",date,len);
		return(-1);
	    }
	    days += monthdays [n];
	    if (isleapyear && n > 2)
	      ++days;
	    continue;

	  case 6:			/* DD: day */
	    if ((n < 1 ) || ( n > 31)) {
		debug(F111,"zstrdt 6 bad date ",date,len);
		return(-1);
	    }
	    tmx = (days + n - 1) * 24L * 60L * 60L;
	    i++;			/* Skip the space */
	    continue;

	  case 9:			/* hh: hour */
	    if ((n < 0 ) || ( n > 23)) {
		debug(F111,"zstrdt 9 bad date ",date,len);
		return(-1);
	    }
	    tmx += n * 60L * 60L;
	    i++;			/* Skip the colon */
	    continue;

	  case 12:			/* mm: minute */
	    if ((n < 0 ) || ( n > 59)) {
		debug(F111,"zstrdt 12 bad date ",date,len);
		return(-1);
	    }
#ifdef BSD44				/* Correct for time zone */
	    tmx += xtimezone;
	    debug(F101,"zstrdt BSD44 tmx","",tmx);
#else
#ifdef ANYBSD
	    tmx += timezone;
#else
#ifndef CONVEX9 /* Don't yet know how to do this here */
#ifdef ultrix
	    tmx += (long) timezone;
#else
#ifdef Plan9
	    {
		extern time_t tzoffset;
		tmx += tzoffset;
	    }
#else
	    tmx += timezone;
#endif /* Plan9 */
#endif /* ultrix */
#endif /* CONVEX9 */
#endif /* BSD44 */
#endif /* ANYBSD */
	    tmx += n * 60L;
	    i++;			/* Skip the colon */
	    continue;

	  case 15:			/* ss: second */
	    if ((n < 0 ) || ( n > 59)) {
		debug(F111,"zstrdt 15 bad date ",date,len);
		return(-1);
	    }
	    tmx += n;
	}
	time_stamp = localtime(&tmx);
	if (!time_stamp)
	  return(-1);
	if (localtime(&tmx)->tm_isdst)
	  tmx -= 60L * 60L;		/* Adjust for daylight savings time */
    }
    return(tmx);
}
#endif /* NOTIMESTAMP */

/* Z S T I M E  --  Set modification date/time+permissions for incoming file */
/*
 Call with:
 f  = pointer to name of existing file.
 yy = pointer to a Kermit file attribute structure in which yy->date.val
      is a date of the form yyyymmdd hh:mm:ss, e.g. 19900208 13:00:00.
      yy->lprotect.val & yy->gprotect.val are permission/protection values.
 x  = is a function code: 0 means to set the file's attributes as given.
      1 means compare the date in struct yy with the file creation date.
 Returns:
 -1 on any kind of error.
  0 if x is 0 and the attributes were set successfully.
  0 if x is 1 and date from attribute structure <= file creation date.
  1 if x is 1 and date from attribute structure > file creation date.
*/
int
zstime(f,yy,x)
#ifdef HPUX10
#ifdef CK_ANSIC
    const 
#endif /* CK_ANSIC */
#endif /* HPUX10 */
    char *f; struct zattr *yy; int x;
/* zstime */ {
    int r = -1;				/* Return code */
#ifdef CK_PERMS
    int setperms = 0;
#endif /* CK_PERMS */
    int setdate = 0;

/* It is ifdef'd TIMESTAMP because it might not work on V7. bk@kullmar.se.  */

#ifdef TIMESTAMP
#ifdef BSD44
    extern int utimes();
#else
    extern int utime();
#endif /* BSD44 */

    struct stat sb;

/* At least, the declarations for int functions are not needed anyway */

#ifdef BSD44
    struct timeval tp[2];
    long xtimezone;
#else
#ifdef V7
    struct utimbuf {
      time_t timep[2];			/* New access and modificaton time */
    } tp;
    char *tz;
    long timezone;			/* In case not defined in .h file */
#else
#ifdef SYSUTIMEH
    struct utimbuf tp;
#else
    struct utimbuf {
	time_t atime;
	time_t mtime;
    } tp;
#endif /* SYSUTIMEH */
#endif /* V7 */
#endif /* BSD44 */

    long tm;

    debug(F110,"zstime",f,0);
    debug(F111,"zstime date",yy->date.val,yy->date.len);

    if (yy->date.len == 0) {		/* No date in struct */
	if (yy->lprotect.len != 0) {	/* So go do permissions */
	    goto zsperms;
	} else {
	    debug(F100,"zstime: nothing to do","",0);
	    return(0);
	}
    }
    if ((tm = zstrdt(yy->date.val,yy->date.len)) < 0) {
	debug(F101,"zstime: zstrdt fails","",0);
	return(-1);
    }
    debug(F101,"zstime: tm","",tm);
    debug(F111,"zstime: A-pkt date ok ",yy->date.val,yy->date.len);

    if (stat(f,&sb)) {			/* Get the time for the file */
	debug(F111,"zstime: Can't stat file:",f,errno);
	return(-1);
    }
    setdate = 1;

  zsperms:
#ifdef CK_PERMS
    {
	int i, x = 0, xx, flag = 0;
	char * s;
#ifdef DEBUG
	char obuf[24];
	if (deblog) {
	    debug(F111,"zstime lperms",yy->lprotect.val,yy->lprotect.len);
	    debug(F111,"zstime gperms",yy->gprotect.val,yy->gprotect.len);
	    debug(F110,"zstime system id",yy->systemid.val,0);
	    sprintf(obuf,"%o",sb.st_mode);
	    debug(F110,"zstime file perms before",obuf,0);
	}
#endif /* DEBUG */
	if ((yy->lprotect.len > 0 &&	/* Have local-format permissions */
	    yy->systemid.len > 0 &&	/* from A-packet... */
#ifdef UNIX
	    !strcmp(yy->systemid.val,"U1") /* AND you are same as me */
#else
	    0
#endif /* UNIX */
	     ) || (yy->lprotect.len < 0) /* OR by inheritance from old file */
	    ) {
	    flag = 1;
	    s = yy->lprotect.val;	/* UNIX filemode */
	    xx = yy->lprotect.len;
	    if (xx < 0)			/* len < 0 means inheritance */
	      xx = 0 - xx;
	    for (i = 0; i < xx; i++) {	/* Decode octal string */
		if (*s <= '7' && *s >= '0') {
		    x = 8 * x + (int)(*s) - '0';
		} else {
		    flag = 0;
		    break;
		}
		s++;
	    }
#ifdef DEBUG
	    sprintf(obuf,"%o",x);
	    debug(F110,"zstime octal lperm",obuf,0);
#endif /* DEBUG */
	} else if (!flag && yy->gprotect.len > 0) {
	    int g, mask;
	    mask = umask(0);		/* Get umask */
	    debug(F101,"zstime mask 1","",mask);
	    umask(mask);		/* Put it back */
	    mask ^= 0777;		/* Flip the bits */
	    debug(F101,"zstime mask 2","",mask);
	    g = xunchar(*(yy->gprotect.val)); /* Decode generic protection */
	    debug(F101,"zstime gprotect","",g);
#ifdef S_IRUSR
	    debug(F100,"zstime S_IRUSR","",0);
	    if (g & 1) x |= S_IRUSR;	/* Read permission */
	    flag = 1;
#endif /* S_IRUSR */
#ifdef S_IWUSR
	    debug(F100,"zstime S_IWUSR","",0);
	    if (g & 2) x |= S_IWUSR;	/* Write permission */
	    if (g & 16) x |= S_IWUSR;	/* Delete permission */
	    flag = 1;
#endif /* S_IWUSR */
#ifdef S_IXUSR
	    debug(F100,"zstime S_IXUSR","",0);
	    if (g & 4)			/* Has execute permission bit */
	      x |= S_IXUSR;
	    else			/* Doesn't have it */
	      mask &= 666;		/* so also clear it out of mask */
	    flag = 1;
#endif /* S_IXUSR */
	    debug(F101,"zstime mask x","",x);
	    x |= mask;
	    debug(F101,"zstime mask x|mask","",x);
	}
	if (flag) {
	    debug(F101,"zstime flag","",flag);
#ifdef S_IFMT
	    debug(F101,"zstime S_IFMT x","",x);
	    sb.st_mode = (sb.st_mode & S_IFMT) | x;
	    setperms = 1;
#else
#ifdef _IFMT
	    debug(F101,"zstime _IFMT x","",x);
	    sb.st_mode = (sb.st_mode & _IFMT) | x;
	    setperms = 1;
#endif /* _IFMT */
#endif /* S_IFMT */
	}
#ifdef DEBUG
	sprintf(obuf,"%o",sb.st_mode);
	debug(F111,"zstime file perms after",obuf,setperms);
#endif /* DEBUG */
    }
#endif /* CK_PERMS */

    debug(F101,"zstime: sb.st_atime","",sb.st_atime);

#ifdef SYSUTIMEH
    tp.modtime = tm;			/* Set modif. time to creation date */
    tp.actime = sb.st_atime;		/* Don't change the access time */
#else
#ifdef V7
    tp.timep[0] = tm;			/* Set modif. time to creation date */
    tp.timep[1] = sb.st_atime;		/* Don't change the access time */
#else
#ifdef BSD44
    tp[0].tv_sec = sb.st_atime;		/* Access time first */
    tp[1].tv_sec = tm;			/* Update time second */
#else
    tp.mtime = tm;			/* Set modif. time to creation date */
    tp.atime = sb.st_atime;		/* Don't change the access time */
#endif /* BSD44 */
#endif /* V7 */
#endif /* SYSUTIMEH */

    switch (x) {			/* Execute desired function */
      case 0:				/* Set the creation date of the file */
#ifdef CK_PERMS				/* And permissions */
/*
  NOTE: If we are inheriting permissions from a previous file, and the
  previous file was a directory, this would turn the new file into a directory
  too, but it's not, so we try to unset the right bit.  Luckily, this code
  will probably never be executed since the upper level modules do not allow
  reception of a file that has the same name as a directory.

  NOTE 2: We change the permissions *before* we change the modification time,
  otherwise changing the permissions would set the mod time to the present
  time.
*/
	{
	    int x;
	    debug(F101,"zstime setperms","",setperms);
	    if (S_ISDIR(sb.st_mode)) {
		debug(F101,"zstime DIRECTORY bit on","",sb.st_mode);
		sb.st_mode ^= 0040000;
		debug(F101,"zstime DIRECTORY bit off","",sb.st_mode);
	    }
	    if (setperms) {
		x = chmod(f,sb.st_mode);
		debug(F101,"zstime chmod","",x);
	    }
	}
	if (x < 0) return(-1);
#endif /* CK_PERMS */

	if (!setdate)			/* We don't have a date */
	  return(0);			/* so skip the following... */

	if (
#ifdef BSD44
	    utimes(f,tp)
#else
	    utime(f,&tp)
#endif /* BSD44 */
	    ) {				/* Fix modification time */
	    debug(F111,"zstime 0: can't set modtime for file",f,errno);
	    r = -1;
	} else  {
	    debug(F110,"zstime 0: modtime set for file",f,0);
	    r = 0;
	}
	break;

      case 1:				/* Compare the dates */
/*
  This was st_atime, which was wrong.  We want the file-data modification
  time, st_mtime.
*/
	debug(F111,"zstime 1: compare",f,sb.st_mtime);
	debug(F111,"zstime 1: compare","packet",tm);

	r = (sb.st_mtime < tm) ? 0 : 1;
	break;

      default:				/* Error */
	r = -1;
    }
#endif /* TIMESTAMP */
    return(r);
}

/* Find initialization file. */

#ifdef NOTUSED
int
zkermini() {
/*  nothing here for Unix.  This function added for benefit of VMS Kermit.  */
    return(0);
}
#endif /* NOTUSED */

#ifndef NOFRILLS
int
zmail(p,f) char *p; char *f; {		/* Send file f as mail to address p */
/*
  Returns 0 on success
   2 if mail delivered but temp file can't be deleted
  -2 if mail can't be delivered
  The UNIX version always returns 0 because it can't get a good return
  code from zsyscmd.
*/
#ifdef BSD4
/* The idea is to use /usr/ucb/mail, rather than regular mail, so that   */
/* a subject line can be included with -s.  Since we can't depend on the */
/* user's path, we use the convention that /usr/ucb/Mail = /usr/ucb/mail */
/* and even if Mail has been moved to somewhere else, this should still  */
/* find it...  The search could be made more reliable by actually using  */
/* access() to see if /usr/ucb/Mail exists. */

/* Should also make some check on zmbuf overflow... */

#ifdef DGUX540
    sprintf(zmbuf,"mailx -s %c%s%c %s < %s", '"', f, '"', p, f);
#else
    sprintf(zmbuf,"Mail -s %c%s%c %s < %s", '"', f, '"', p, f);
#endif /* DGUX540 */
    zsyscmd(zmbuf);
#else
#ifdef SVORPOSIX
#ifndef OXOS
    sprintf(zmbuf,"mail %s < %s", p, f);
#else /* OXOS */
    sprintf(zmbuf,"mailx -s %c%s%c %s < %s", '"', f, '"', p, f);
#endif /* OXOS */
    zsyscmd(zmbuf);
#else
    *zmbuf = '\0';
#endif
#endif
    return(0);
}
#endif /* NOFRILLS */

#ifndef NOFRILLS
int
zprint(p,f) char *p; char *f; {		/* Print file f with options p */
    extern char * printername;		/* From ckuus3.c */
    extern int printpipe;

    debug(F110,"zprint file",f,0);
    debug(F110,"zprint flags",p,0);
    debug(F110,"zprint printername",printername,0);
    debug(F101,"zprint printpipe","",printpipe);

#ifdef UNIX
/*
  Note use of standard input redirection.  In some systems, lp[r] runs
  setuid to lp (or ...?), so if user has sent a file into a directory
  that lp does not have read access to, it can't be printed unless it is
  fed to lp[r] as standard input.
*/
    if (printpipe && printername) {
	sprintf(zmbuf,"cat %s | %s", f, printername);
    } else if (printername) {
	sprintf(zmbuf,"cat %s >> %s", f, printername);
    } else {
	sprintf(zmbuf,"%s %s < %s", PRINTCMD, p, f);
    }
    debug(F110,"zprint command",zmbuf,0);
    zsyscmd(zmbuf);
#else /* Not UNIX */
    *zmbuf = '\0';
#endif /* UNIX */
    return(0);
}
#endif /* NOFRILLS */

/*
  Wildcard expansion functions.  C-Kermit used to insist on doing this itself
  New code (version 5A, 1990-91) gives user option to ask UNIX to do it.
  This lets users use the wildcard expansion features of their favorite shell.
  Operation is slower because of the forking & piping, but flexibility is
  greater and program is smaller.  For OS/2, C-Kermit still does this itself.
*/
static char scratch[MAXPATH+4];		/* Used by both methods */

static int oldmtchs = 0;		/* Let shell (ls) expand them. */
#ifdef COMMENT
static char *lscmd = "/bin/ls -d"; 	/* Command to use. */
#else
static char *lscmd = "echo";		/* Command to use. */
#endif /* COMMENT */

#ifndef NOPUSH
int
shxpand(pat,namlst,len) char *pat, *namlst[]; int len; {
    char *fgbuf = NULL;			/* Buffer for forming ls command */
    char *p, *q;			/* Workers */
    extern int dironly, fileonly;

    int i, x, retcode, itsadir;
    char c;

    x = (int)strlen(pat) + (int)strlen(lscmd) + 3; /* Length of ls command */
    for (i = 0; i < oldmtchs; i++) {	/* Free previous file list */
	if (namlst[i] ) {		/* If memory is allocated  */
	    free(namlst[i]);		/* Free the memory         */
	    namlst[i] = NULL ;		/* Remember no memory is allocated */
	}
    }
    oldmtchs = 0 ;			/* Remember there are no matches */
    fgbuf = malloc(x);			/* Get buffer for command */
    if (!fgbuf) return(-1);		/* Fail if cannot */
    sprintf(fgbuf,"%s %s",lscmd,pat);	/* Form the command */
    zxcmd(ZIFILE,fgbuf);		/* Start the command */
    i = 0;				/* File counter */
    p = scratch;			/* Point to scratch area */
    retcode = -1;			/* Assume failure */
    while ((x = zminchar()) != -1) {	/* Read characters from command */
	c = (char) x;
	if (c == ' ' || c == '\n') {	/* Got newline or space? */
	    *p = '\0';			/* Yes, terminate string */
	    p = scratch;		/* Point back to beginning */
	    if (zchki(p) == -1)		/* Does file exist? */
	      continue;			/* No, continue */
	    itsadir = isdir(p);		/* Yes, is it a directory? */
	    if (dironly && !itsadir)	/* Want only dirs but this isn't */
	      continue;			/* so skip. */
	    if (fileonly && itsadir)	/* It's a dir but want only files */
	      continue;			/* so skip. */
	    x = (int)strlen(p);		/* Keep - get length of name */
	    q = malloc(x+1);		/* Allocate space for it */
	    if (!q) goto shxfin;	/* Fail if space can't be obtained */
	    strcpy(q,scratch);		/* Copy name to space */
	    namlst[i++] = q;		/* Copy pointer to name into array */
	    if (i >= len) goto shxfin;	/* Fail if too many */
	} else {			/* Regular character */
	    *p++ = c;			/* Copy it into scratch area */
	}
    }
    retcode = i;			/* Return number of matching files */
shxfin:					/* Common exit point */
    free(fgbuf);			/* Free command buffer */
    fgbuf = NULL;
    zclosf(ZIFILE);			/* Delete the command fork. */
    oldmtchs = i;			/* Remember how many files */
    return(retcode);
}
#endif /* NOPUSH */

/*
  Directory-reading functions for UNIX originally written for C-Kermit 4.0 
  by Jeff Damens, CUCCA, 1984.
*/

/* Define the size of the string space for filename expansion. */

#ifndef DYNAMIC
#ifdef PROVX1
#define SSPACE 500
#else
#ifdef BSD29
#define SSPACE 500
#else
#ifdef pdp11
#define SSPACE 500
#else
#ifdef aegis
#define SSPACE 10000			/* Size of string-generating buffer */
#else					/* Default static buffer size */
#ifdef BIGBUFOK
#define SSPACE 65000			/* Size of string-generating buffer */
#else
#define SSPACE 2000			/* size of string-generating buffer */
#endif /* BIGBUFOK */
#endif /* aegis */
#endif /* pdp11 */
#endif /* BSD29 */
#endif /* PROVX1 */
static char sspace[SSPACE];             /* Buffer for generating filenames */
#else /* is DYNAMIC */
#ifdef BIGBUFOK
#define SSPACE 500000
#else
#define SSPACE 10000
#endif /* BIGBUFOK */
static char *sspace = (char *)0;
#endif /* DYNAMIC */
static int ssplen = SSPACE;		/* Length of string space buffer */

static char *freeptr, **resptr;        	/* copies of caller's arguments */
static int remlen;                      /* remaining length in caller's array*/
static int numfnd;                      /* number of matches found */

#ifdef aegis
static char bslash;
#endif /* aegis */

/*
 * splitpath:
 *  takes a string and splits the slash-separated portions into
 *  a list of path structures.  Returns the head of the list.  The
 *  structures are allocated by malloc, so they must be freed.
 *  Splitpath is used internally by the filename generator.
 *
 * Input: A string.
 * Returns: A linked list of the slash-separated segments of the input.
 */

struct path *
splitpath(p) char *p; {
    struct path *head,*cur,*prv;
    int i;

    debug(F111,"splitpath",p,recursive);
    head = prv = NULL;

#ifdef RECURSIVE
/*
  Recursive can be set by the user interface before we are called.
  We also set it here automatically if the pattern is ".".
*/
#ifdef UNIX
    if (!strcmp(p,".")) {		/* Currently . means recursive */
	recursive = 1;			/* as in tar... */
	p = "*";
    } else
#endif /* UNIX */
#ifdef COMMENT
    if (!strncmp(p,".../",4)) {
	recursive = 2;
	if (*(p+4))
	  p += 4;
	else
	  p = "*";
    } else
#endif /* COMMENT */
#endif /* RECURSIVE */

    if (!strcmp(p,"**")) {		/* Fix this */
	p = "*";
    }
    if (ISDIRSEP(*p)) p++;		/* Skip leading slash if any */

    /* Make linked list of path segments from pattern */

    while (*p) {
	cur = (struct path *) malloc(sizeof (struct path));
	debug(F101,"splitpath malloc","",cur);
	if (cur == NULL) {
	    debug(F100,"splitpath malloc failure","",0);
	    return((struct path *)NULL);
	}
	cur -> fwd = NULL;
	if (head == NULL)		/* First, make list head */
	  head = cur;
	else				/* Not first, link into chain */
	  prv -> fwd = cur;
	prv = cur;			/* Link from previous to this one */

#ifdef aegis
	/* treat backslash as "../" */
	if (bslash && *p == bslash) {
	    strcpy(cur->npart, "..");
	    ++p;
	} else {
	    for (i=0; i < MAXNAMLEN && *p && *p != '/' && *p != bslash; i++)
	      cur -> npart[i] = *p++;
	    cur -> npart[i] = '\0';	/* end this segment */
	    if (i >= MAXNAMLEN)
	      while (*p && *p != '/' && *p != bslash)
		p++;
	}
	if (*p == '/') p++;
#else
	/* General case (UNIX) */
	for (i = 0; i < MAXNAMLEN && !ISDIRSEP(*p) && *p != '\0'; i++) {
	    cur -> npart[i] = *p++;
	}

	cur -> npart[i] = '\0';		/* End this path segment */
	if (i >= MAXNAMLEN)
	  while (!ISDIRSEP(*p) && *p != '\0') p++;
	if (ISDIRSEP(*p))
	  p++;

#endif /* aegis */
    }
    return(head);
}

/*
 * fgen:
 *  This is the actual name generator.  It is passed a string,
 *  possibly containing wildcards, and an array of character pointers.
 *  It finds all the matching filenames and stores pointers to them in the
 *  array.  The returned strings are allocated from a static buffer local to
 *  this module (so the caller doesn't have to worry about deallocating
 *  them); this means that successive calls to fgen will wipe out
 *  the results of previous calls.  This isn't a problem here
 *  because we process one wildcard string at a time.
 *
 * Actually it is problem in scripts using \ffiles() and \fnext()...
 *
 * Input:   A wildcard string, an array to write names to, the length
 *          of the array.
 * Returns: the number of matches.  The array is filled with filenames
 *          that matched the pattern.  If there wasn't enough room in 
 *	    the array, -1 is returned.
 * Originally by: Jeff Damens, CUCCA, 1984.  Many changes since then.
 */
static int
fgen(pat,resarry,len) char *pat,*resarry[]; int len; {
    struct path *head;
    char *sptr;
#ifdef aegis
    char *namechars;
    int tilde = 0, bquote = 0;

    if ((namechars = getenv("NAMECHARS")) != NULL) {
	if (xindex(namechars, '~' ) != NULL) tilde  = '~';
	if (xindex(namechars, '\\') != NULL) bslash = '\\';
	if (xindex(namechars, '`' ) != NULL) bquote = '`';
    } else {
	tilde = '~'; bslash = '\\'; bquote = '`';
    }

    sptr = scratch;
    
    /* copy "`node_data", etc. anchors */
    if (bquote && *pat == bquote)
      while (*pat && *pat != '/' && *pat != bslash)
	*sptr++ = *pat++;
    else if (tilde && *pat == tilde)
      *sptr++ = *pat++;
    while (*pat == '/')
      *sptr++ = *pat++;
    if (sptr == scratch) {
	strcpy(scratch,"./");
	sptr = scratch+2;
    }					/* init buffer correctly */

    if (!(head = splitpath(pat))) return(-1);
#else /* not aegis */
    debug(F110,"fgen pat",pat,0);

    scratch[0] = '\0';

    if (!(head = splitpath(pat)))
      return(-1);

    sptr = scratch;

    if (!ISDIRSEP(*pat))
      *sptr++ = '.';			/* Init buffer correctly */
    *sptr++ = DIRSEP;
    *sptr = '\0';			/* And even more correctly */
#endif /* aegis */

    numfnd = 0;				/* None found yet */
#ifdef DYNAMIC
    if (!sspace) {			/* Need to allocate string space? */
	while (ssplen > 50) {
	    if ((sspace = malloc(ssplen+2))) { /* Got it. */
		debug(F101,"fgen string space","",ssplen);
		break;
	    }
	    ssplen = (ssplen / 2) + (ssplen / 4); /* Didn't, reduce by 3/4 */
	}
	if (ssplen <= 50) {		/* Did we get it? */
	    fprintf(stderr,"fgen can't malloc string space\n");
	    return(-1);
	}
    }
#endif /* DYNAMIC */

    freeptr = sspace;			/* this is where matches are copied */
    resptr = resarry;			/* static copies of these so */
    remlen = len;			/* recursive calls can alter them */
    traverse(head,scratch,sptr);	/* go walk the directory tree */

    while (head != NULL) {		/* Done, now free the pattern */
	struct path *next = head -> fwd; /* segment list. */
	free(head);
	head = next;
    }
    return(numfnd);			/* Return the number of matches */
}

/* traverse:
 *  Walks the directory tree looking for matches to its arguments.
 *  The algorithm is, briefly:
 *   If the current pattern segment contains no wildcards, that
 *   segment is added to what we already have.  If the name so far
 *   exists, we call ourselves recursively with the next segment
 *   in the pattern string; otherwise, we just return.
 *
 *   If the current pattern segment contains wildcards, we open the name
 *   we've accumulated so far (assuming it is really a directory), then read
 *   each filename in it, and, if it matches the wildcard pattern segment, add
 *   that filename to what we have so far and call ourselves recursively on 
 *   the next segment.
 *
 *   Finally, when no more pattern segments remain, we add what's accumulated
 *   so far to the result array and increment the number of matches.
 *
 * Input: a pattern path list (as generated by splitpath), a string
 *	  pointer that points to what we've traversed so far (this
 *	  can be initialized to "/" to start the search at the root
 *	  directory, or to "./" to start the search at the current
 *	  directory), and a string pointer to the end of the string
 *	  in the previous argument.
 *
 * Returns: nothing.
 */
static VOID
traverse(pl,sofar,endcur) struct path *pl; char *sofar, *endcur; {

/* Define LONGFN (long file names) automatically for BSD 2.9 and 4.2 */
/* LONGFN can also be defined on the cc command line. */

#ifdef BSD29
#ifndef LONGFN
#define LONGFN
#endif
#endif

#ifdef BSD42
#ifndef LONGFN
#define LONGFN
#endif
#endif

/* Appropriate declarations for directory routines and structures */
/* #define OPENDIR means to use opendir(), readdir(), closedir()  */
/* If OPENDIR not defined, we use open(), read(), close() */

#ifdef DIRENT				/* New way, <dirent.h> */
#define OPENDIR
    DIR *fd, *opendir();
    struct dirent *dirbuf;
    struct dirent *readdir();
#else /* !DIRENT */
#ifdef LONGFN				/* Old way, <dir.h> with opendir() */
#define OPENDIR
    DIR *fd, *opendir();
    struct direct *dirbuf;
#else /* !LONGFN */
    int fd;				/* Old way, <dir.h> with open() */
    struct direct dir_entry;
    struct direct *dirbuf = &dir_entry;
#endif /* LONGFN */
#endif /* DIRENT */

    int itsadir, mresult;
    extern int dironly;			/* See comments in addresult() */
    struct stat statbuf;		/* for file info */

    if (pl == NULL) {			/* End of path-segment list */
	*--endcur = '\0'; /* Terminate string, overwrite trailing slash */
	debug(F110,"traverse adding because pl == NULL",sofar,0);
	addresult(sofar);
	return;
    }
#ifdef RECURSIVE
    if (recursive > 0 && !isdir(sofar)) {
	*--endcur = '\0'; /* Terminate string, overwrite trailing slash */
	debug(F110,"traverse adding because recursive && !isdir",sofar,0);
	addresult(sofar);
	return;
    }
#endif /* RECURSIVE */

    /* Otherwise, if this path segment is not wild, keep digging */

    debug(F110,"traverse",pl -> npart,0);

    if (!recursive && !iswild(pl -> npart)) { /* This path segment not wild? */
	strcpy(endcur,pl -> npart);	/* Not wild. */
	endcur += (int)strlen(pl -> npart);
	*endcur = '\0';			/* End current string. */

	if (stat(sofar,&statbuf) == 0) { /* If current piece exists... */
	    debug(F110,"traverse exists",sofar,0);
	    *endcur++ = DIRSEP;		/* add slash to end */
	    *endcur = '\0';		/* and end the string again. */
	    traverse(pl -> fwd, sofar, endcur);
	}
#ifdef DEBUG
	else debug(F110,"traverse not found", sofar, 0);
#endif /* DEBUG */
	return;
    }

    /* Path segment contains wildcards, have to open and search directory */

    *endcur = '\0';				/* End current string */
    if (stat(sofar,&statbuf) == -1) return;   	/* Doesn't exist, forget it */
    if (!S_ISDIR (statbuf.st_mode)) return; 	/* Not a directory, skip it */

    /* This file is a directory, so open it and read its contents */

#ifdef OPENDIR
    if ((fd = opendir(sofar)) == NULL)	/* Can't open, fail. */
      return;
    while (dirbuf = readdir(fd))
#else /* !OPENDIR */
    if ((fd = open(sofar,O_RDONLY)) < 0)
      return;
    while (read(fd, (char *)dirbuf, sizeof dir_entry))
#endif /* OPENDIR */
      {				/* Read all entries in this directory */
	  char *eos;
	  strncpy(nambuf,		/* Copy the name */
		  dirbuf->d_name,
		  MAXNAMLEN
		  );
	  nambuf[MAXNAMLEN] = '\0';	/* Make sure it's null-terminated */

	  if (!strcmp(nambuf,".") || !strcmp(nambuf,"..")) /* Not interested */
	    continue;			/* skip these. */

	  strcpy(endcur,nambuf);	/* Make sofar be the complete path */
	  eos = endcur + (int)strlen(nambuf);
	  *eos = '\0';
/*
  Now we check the file for (a) whether it is a directory, and (b) whether
  its name matches our pattern.  If it is a directory, and if we have been
  told to build a recursive list, then we must descend regardless of whether
  it matches the pattern.  If it is not a directory and it does not match
  our pattern, we skip it.  Note: sofar is the full pathname, nambuf is
  the name only.
*/
	  itsadir = 0;
#ifdef RECURSIVE
	  if (recursive > 0) {		/* Recursing? */
	      itsadir = isdir(sofar);	/* Is this a directory? */
	      debug(F111,"traverse isdir",sofar,itsadir);
	  }
#endif /* RECURSIVE */

	  mresult = match(pl -> npart, nambuf);	/* String match */
#ifdef DEBUG
	  if (deblog && !mresult)
	    debug(F101,"traverse mresult",nambuf,mresult);
#endif /* DEBUG */
	  if ((itsadir || mresult) &&	/* If chosen and ... */
#ifdef unos
	      dirbuf->d_ino != -1	/* there actually is an inode ... */
#else
#ifdef QNX
	      dirbuf->d_stat.st_ino != 0
#else
#ifdef SOLARIS
	      dirbuf->d_ino != 0
#else
#ifdef sun
	      dirbuf->d_fileno != 0
#else
#ifdef bsdi
	      dirbuf->d_fileno != 0
#else
#ifdef __386BSD__
	      dirbuf->d_fileno != 0
#else
#ifdef __FreeBSD__
	      dirbuf->d_fileno != 0
#else
#ifdef ultrix
	      dirbuf->gd_ino != 0
#else
#ifdef Plan9
	      1
#else
	  dirbuf->d_ino != 0
#endif /* Plan9 */
#endif /* ultrix */
#endif /* __FreeBSD__ */
#endif /* __386BSD__ */
#endif /* bsdi */
#endif /* sun */
#endif /* SOLARIS */
#endif /* QNX */
#endif /* unos */
	      ) {
	      struct path * xx = NULL;

#ifdef RECURSIVE
	      /* If recursively listing directory files add this one now. */
	      if (recursive > 0 && dironly && itsadir ) {
		  if (mresult) {	/* But only if it matched */
		      debug(F110,
			    "traverse adding because recursive && dironly",
			    sofar,0);
		      addresult(sofar);
		  }
	      }
#endif /* RECURSIVE */

	      *eos++ = DIRSEP;		/* Add directory separator */
	      *eos = '\0';		/* to end of segment */

#ifdef RECURSIVE
	      /* Copy previous pattern segment to this new directory */

	      if (recursive > 0 && !(pl -> fwd)) {
		  xx = (struct path *) malloc(sizeof (struct path));
		  pl -> fwd = xx;
		  if (xx)
		    xx -> fwd = NULL;
		  strcpy(xx -> npart, pl -> npart);
	      }
#endif /* RECURSIVE */
	      traverse(pl -> fwd, sofar, eos); /* Traverse new directory */
	  }
      }
#ifdef OPENDIR
    closedir(fd);
#else /* !OPENDIR */
    close(fd);
#endif /* OPENDIR */
}

/*
 * addresult:
 *  Adds a result string to the result array.  Increments the number
 *  of matches found, copies the found string into our string
 *  buffer, and puts a pointer to the buffer into the caller's result
 *  array.  Our free buffer pointer is updated.  If there is no
 *  more room in the caller's array, the number of matches is set to -1.
 * Input: a result string.
 * Returns: nothing.
 */
static VOID
addresult(str) char *str; {
/* 
  "dironly" == a horrible hack to avoid changing the API for all Kermit 
  versions.  If the external variable dironly is nonzero, we only add 
  directories to the list; similarly for "fileonly", which if nonzero
  we add only regular files to the list.
*/
    extern int dironly, fileonly;
    int len, x;
    debug(F111,"addresult",str,remlen);
    x = isdir(str);
    if ((dironly && !x) || (fileonly && x))
      return;
    if (str[0] == '.' && ISDIRSEP(str[1])) str += 2;
    if (--remlen < 0) {
	numfnd = -1;
	return;
    }
    len = (int)strlen(str) + 1;		/* size this will take up */
    if ((freeptr + len) > (sspace + ssplen)) {
	numfnd = -1;			/* do not record if not enough space */
	return;
    }
    strcpy(freeptr,str);
    *resptr++ = freeptr;
    freeptr += len;
    numfnd++;
}

/*
 * match:
 *  pattern matcher.  Takes a string and a pattern possibly containing
 *  the wildcard characters '*' and '?'.  Returns true if the pattern
 *  matches the string, false otherwise.
 * by: Jeff Damens, CUCCA, 1984
 * Lots added since then.
 *
 * Input: a string and a wildcard pattern.
 * Returns: 1 if match, 0 if no match.
 */
static int
match(pattern, string) char *pattern, *string; {
    char *psave = NULL, *ssave = NULL;	/* Backup pointers for failure */
    extern int matchdot;
    int q = 0;				/* Quote flag */

    if (*string == '.' && *pattern != '.' && !matchdot) {
	debug(F110,"match skip",string,0);
	return(0);
    }

    while (1) {
	for (; *pattern == *string; pattern++,string++)	/* Skip first */
	  if (*string == '\0') return(1); /* End of strings, succeed */

	if (*pattern == '\\' && q == 0) { /* Watch out for quoted */
	    q = 1;			/* metacharacters */
	    pattern++;			/* advance past quote */
	    if (*pattern != *string) return(0);
	    continue;
	} else q = 0;

	if (q) {
	    return(0);
	} else {
	    if (*string != '\0' && *pattern == '?') {
		pattern++;		/* '?', let it match */
		string++;
	    } else if (*pattern == '*') { /* '*' ... */
		psave = ++pattern;	/* remember where we saw it */
		ssave = string;		/* let it match 0 chars */
	    } else if (ssave != NULL && *ssave != '\0') { /* if not at end  */
					/* ...have seen a star */
		string = ++ssave;	/* skip 1 char from string */
		pattern = psave;	/* and back up pattern */
	    } else return(0);		/* otherwise just fail */
	}
    }
}

/*
  The following two functions are for expanding tilde in filenames
  Contributed by Howie Kaye, CUCCA, developed for CCMD package.
*/

/*  W H O A M I  --  Get user's username.  */

/*
  1) Get real uid
  2) See if the $USER environment variable is set ($LOGNAME on AT&T)
  3) If $USER's uid is the same as ruid, realname is $USER
  4) Otherwise get logged in user's name
  5) If that name has the same uid as the real uid realname is loginname
  6) Otherwise, get a name for ruid from /etc/passwd
*/
static char *
whoami () {
#ifdef DTILDE
#ifdef pdp11
#define WHOLEN 100
#else
#define WHOLEN 257
#endif /* pdp11 */
    static char realname[256];		/* user's name */
    static int ruid = -1;		/* user's real uid */
    char loginname[256], envname[256];	/* temp storage */
    char *c;
    struct passwd *p;
    _PROTOTYP(extern char * getlogin, (void) );

    if (ruid != -1)
      return(realname);

    ruid = real_uid();			/* get our uid */

  /* how about $USER or $LOGNAME? */
    if ((c = getenv(NAMEENV)) != NULL) { /* check the env variable */
	strcpy (envname, c);
	if ((p = getpwnam(envname)) != NULL) {
	    if (p->pw_uid == ruid) {	/* get passwd entry for envname */
		strcpy (realname, envname); /* if the uid's are the same */
		return(realname);
	    }
	}
    }

  /* can we use loginname() ? */

    if ((c =  getlogin()) != NULL) {	/* name from utmp file */
	strcpy (loginname, c);
	if ((p = getpwnam(loginname)) != NULL) /* get passwd entry */
	  if (p->pw_uid == ruid) {	/* for loginname */
	      strcpy (realname, loginname); /* if the uid's are the same */
	      return(realname);
	  }
    }

  /* Use first name we get for ruid */

    if ((p = getpwuid(ruid)) == NULL) { /* name for uid */
	realname[0] = '\0';		/* no user name */
	ruid = -1;
	return(NULL);
    }
    strcpy (realname, p->pw_name);
    return(realname);
#else
    return(NULL);
#endif /* DTILDE */
}

/*  T I L D E _ E X P A N D  --  expand ~user to the user's home directory. */

char *
tilde_expand(dirname) char *dirname; {
#ifdef DTILDE
#ifdef pdp11
#define BUFLEN 100
#else
#define BUFLEN 257
#endif /* pdp11 */
    struct passwd *user;
    static char olddir[BUFLEN];
    static char oldrealdir[BUFLEN];
    static char temp[BUFLEN];
    int i, j;

    debug(F111,"tilde_expand",dirname,dirname[0]);

    if (dirname[0] != '~')		/* Not a tilde...return param */
      return(dirname);
    if (!strcmp(olddir,dirname)) {	/* Same as last time */
      return(oldrealdir);		/* so return old answer. */
    } else {
	j = (int)strlen(dirname);
	for (i = 0; i < j; i++)		/* find username part of string */
	  if (!ISDIRSEP(dirname[i]))
	    temp[i] = dirname[i];
	  else break;
	temp[i] = '\0';			/* tie off with a NULL */
	if (i == 1) {			/* if just a "~" */
	    user = getpwnam(whoami());	/*  get info on current user */
	} else {
	    user = getpwnam(&temp[1]);	/* otherwise on the specified user */
	}
    }
    if (user != NULL) {			/* valid user? */
	strcpy(olddir, dirname);	/* remember the directory */
	strcpy(oldrealdir,user->pw_dir); /* and their home directory */
	strcat(oldrealdir,&dirname[i]);
	return(oldrealdir);
    } else {				/* invalid? */
	strcpy(olddir, dirname);	/* remember for next time */
	strcpy(oldrealdir, dirname);
	return(oldrealdir);
    }
#else
    return(NULL);
#endif /* DTILDE */
}

/*
  Functions for executing system commands.
  zsyscmd() executes the system command in the normal, default way for
  the system.  In UNIX, it does what system() does.  Thus, its results
  are always predictable.
  zshcmd() executes the command using the user's preferred shell.
*/
int
zsyscmd(s) char *s; {
#ifdef aegis
    if (!priv_chk()) return(system(s));
#else
    PID_T shpid;
#ifdef COMMENT
/* This doesn't work... */
    WAIT_T status;
#else
    int status;
#endif /* COMMENT */

    if (shpid = fork()) {
	if (shpid < (PID_T)0) return(-1); /* Parent */
	while (shpid != (PID_T) wait(&status))
	 ;
	return(status);
    }
    if (priv_can()) {			/* Child: cancel any priv's */
	printf("?Privilege cancellation failure\n");
	_exit(255);
    }
#ifdef HPUX10
    execl("/usr/bin/sh","sh","-c",s,NULL);
    perror("/usr/bin/sh");
#else
#ifdef Plan9
    execl("/bin/rc", "rc", "-c", s, NULL);
    perror("/bin/rc");
#else
    execl("/bin/sh","sh","-c",s,NULL);
    perror("/bin/sh");
#endif /* Plan9 */
#endif /* HPUX10 */
    _exit(255);
    return(0);				/* Shut up ANSI compilers. */
#endif /* aegis */
}

/*
  Original UNIX code by H. Fischer; copyright rights assigned to Columbia U.
  Adapted to use getpwuid to find login shell because many systems do not
  have SHELL in environment, and to use direct calling of shell rather
  than intermediate system() call. -- H. Fischer (1985); many changes since
  then.  Call with s pointing to command to execute.
*/
int
zshcmd(s) char *s; {
    PID_T pid;

#ifdef NOPUSH
    return(0);
#else
#ifdef aegis
    if ((pid = vfork()) == 0) {		/* Make child quickly */
	char *shpath, *shname, *shptr;	/* For finding desired shell */

	if (priv_can()) exit(1);	/* Turn off privs. */
        if ((shpath = getenv("SHELL")) == NULL) shpath = "/com/sh";

#else					/* All Unix systems */
    if ((pid = fork()) == 0) {		/* Make child */
	char *shpath, *shname, *shptr;	/* For finding desired shell */
	struct passwd *p;
#ifdef HPUX10				/* Default */
	char *defshell = "/usr/bin/sh";
#else
#ifdef Plan9
	char *defshell = "/bin/rc";
#else
	char *defshell = "/bin/sh";
#endif /* Plan9 */
#endif /* HPUX10 */
	if (priv_can()) exit(1);	/* Turn off privs. */
#ifdef COMMENT
/* Old way always used /etc/passwd shell */
	p = getpwuid(real_uid());	/* Get login data */
	if (p == (struct passwd *) NULL || !*(p->pw_shell))
	  shpath = defshell;
	else
	  shpath = p->pw_shell;
#else
/* New way lets user override with SHELL variable, but does not rely on it. */
/* This allows user to specify a different shell. */
	shpath = getenv("SHELL");	/* What shell? */
	if (shpath == NULL) {
	    p = getpwuid( real_uid() );	/* Get login data */
	    if (p == (struct passwd *)NULL || !*(p->pw_shell))
	      shpath = defshell;
	    else shpath = p->pw_shell;
        }
#endif /* COMMENT */
#endif /* aegis */
	shptr = shname = shpath;
	while (*shptr != '\0')
	  if (*shptr++ == DIRSEP)
	    shname = shptr;
	if (s == NULL || *s == '\0') {	/* Interactive shell requested? */
	    execl(shpath,shname,"-i",NULL); /* Yes, do that */
	} else {			/* Otherwise, */
	    execl(shpath,shname,"-c",s,NULL); /* exec the given command */
	}				/* If execl() failed, */
	exit(BAD_EXIT);			/* return bad return code. */

    } else {				/* Parent */

    	int wstat;			/* ... must wait for child */
#ifdef CK_CHILD
        int child;			/* Child's exit status */
#endif /* CK_CHILD */
	SIGTYP (*istat)(), (*qstat)();

	if (pid == (PID_T) -1) return(-1); /* fork() failed? */

	istat = signal(SIGINT,SIG_IGN);	/* Let the fork handle keyboard */
	qstat = signal(SIGQUIT,SIG_IGN); /* interrupts itself... */

#ifdef CK_CHILD
    	while (((wstat = wait(&child)) != pid) && (wstat != -1))
#else
    	while (((wstat = wait((WAIT_T *)0)) != pid) && (wstat != -1))
#endif /* CK_CHILD */
	  ;				/* Wait for fork */
	signal(SIGINT,istat);		/* Restore interrupts */
	signal(SIGQUIT,qstat);
#ifdef CK_CHILD
	pexitstat = (child & 0xff) ? child : child >> 8;
	return(child == 0 ? 1 : 0);	/* Return child's status */
#endif /* CK_CHILD */
    }
    return(1);
#endif /* NOPUSH */
}

#ifdef aegis
/*
 Replacement for strchr() and index(), neither of which seem to be universal.
*/
static char *
#ifdef CK_ANSIC
xindex(char * s, char c)
#else
xindex(s,c) char *s, c;
#endif /* CK_ANSIC */
/* xindex */ {
    while (*s != '\0' && *s != c) s++;
    if (*s == c) return(s); else return(NULL);
}
#endif /* aegis */

/*  I S W I L D  --  Check if filespec is "wild"  */

/*
  Returns 0 if it is a single file, 1 if it contains wildcard characters.
  Note: must match the algorithm used by match(), hence no [a-z], etc.
*/
int
iswild(filespec) char *filespec; {
    char c; int x; char *p;
    if (wildxpand) {
	if ((x = zxpand(filespec)) > 1) return(1);
	if (x == 0) return(0);		/* File does not exist */
	p = malloc(MAXNAMLEN + 20);
	znext(p);
	x = (strcmp(filespec,p) != 0);
	free(p);
	p = NULL;
	return(x);
    } else {
	while ((c = *filespec++) != '\0')
	  if (c == '*' || c == '?') return(1);
	return(0);
    }
}

/*
   Tell if string pointer s is the name of an existing directory.
   Returns 1 if directory, 0 if not a directory.
*/
int
isdir(s) char *s; {
    int x;
    struct stat statbuf;

    if (!s) return(0);
    if (!*s) return(0);

    x = stat(s,&statbuf);
    debug(F111,"isdir stat",s,x);
    if (x == -1) {
	debug(F101,"isdir errno","",errno);
	return(0);
    } else {
	debug(F101,"isdir statbuf.st_mode","",statbuf.st_mode);
	return( S_ISDIR (statbuf.st_mode) ? 1 : 0 );
    }
}

#ifdef CK_MKDIR
/* Some systems don't have mkdir(), e.g. Tandy Xenix 3.2.. */

/* Z M K D I R  --  Create directory(s) if necessary */
/*
   Call with:
    A pointer to a file specification that might contain directory
    information.  The filename is expected to be included.
    If the file specification does not include any directory separators,
    then it is assumed to be a plain file.
    If one or more directories are included in the file specification,
    this routine tries to create them if they don't already exist.
   Returns:
    0 or greater on success, i.e. the number of directories created.
   -1 on failure to create the directory
*/
int
zmkdir(path) char *path; {
    char *xp, *tp, c;
    int x, count = 0;

    x = strlen(path);
    debug(F111,"zmkdir",path,x);
    if (x < 1 || x > MAXPATH)		/* Check length */
      return(-1);
    if (!(tp = malloc(x+1)))		/* Make a temporary copy */
      return(-1);
    strcpy(tp,path);
#ifdef DTILDE
    if (*tp == '~') {			/* Starts with tilde? */
	xp = tilde_expand(tp);		/* Attempt to expand tilde */
	if (*xp) {
	    char *zp;
	    debug(F110,"zmkdir tilde_expand",xp,0);
	    if (!(zp = malloc(strlen(xp) + 1))) { /* Make a place for it */
		free(tp);
		tp = NULL;
		return(-1);
	    }
	    free(tp);			/* Free previous buffer */
	    tp = zp;			/* Point to new one */
	    strcpy(tp,xp);		/* Copy expanded name to new buffer */
	}
	debug(F110,"zmkdir tp after tilde_expansion",tp,0);
    }
#endif /* DTILDE */
    xp = tp;
    if (ISDIRSEP(*xp))			/* Don't create root directory! */
      xp++;

    /* Go thru filespec from left to right... */

    for (; *xp; xp++) {			/* Create parts that don't exist */
	if (!ISDIRSEP(*xp))		/* Find next directory separator */
	  continue;
	c = *xp;			/* Got one. */
	*xp = NUL;			/* Make this the end of the string. */
	if (!isdir(tp)) {		/* This directory exists already? */
	    debug(F110,"zmkdir making",tp,0);
	    x =				/* No, try to create it */
#ifdef NOMKDIR
	       -1			/* Systems without mkdir() */
#else
	       mkdir(tp,0777)		/* UNIX */
#endif /* NOMKDIR */
		 ;
	    if (x < 0) {
		debug(F101,"zmkdir failed, errno","",errno);
		free(tp);		/* Free temporary buffer. */
		tp = NULL;
		return(-1);		/* Return failure code. */
	    } else
	      count++;
	}
	*xp = c;			/* Replace the separator. */
    }
    free(tp);				/* Free temporary buffer. */
    return(count);			/* Return success code. */
}
#endif /* CK_MKDIR */

int
zrmdir(path) char *path; {
#ifndef NOMKDIR
    return(rmdir(path));
#else
    return(-1);
#endif /* NOMKDIR */
}

/* Z F S E E K  --  Position input file pointer */
/*
   Call with:
    Long int, 0-based, indicating desired position.
   Returns:
    0 on success.
   -1 on failure.
*/
#ifndef NORESEND
int
#ifdef CK_ANSIC
zfseek(long pos)
#else
zfseek(pos) long pos;
#endif /* CK_ANSIC */
/* zfseek */ {
    zincnt = -1;			/* Must empty the input buffer */
    debug(F101,"zfseek","",pos);
    return(fseek(fp[ZIFILE], pos, 0)?-1:0);
}
#endif /* NORESEND */

struct zfnfp *
zfnqfp(fname, buflen, buf)  char * fname; int buflen; char * buf; {
    int x = 0, y = 0;
    char * xp;
    static struct zfnfp fnfp;

    if (!fname)
      return(NULL);

    debug(F110,"zfnqfp fname",fname,0);

    /* initialize the data structure */
    fnfp.len = buflen;
    fnfp.fpath = buf;
    fnfp.fname = NULL;

#ifdef DTILDE
	if (*fname == '~') {		/* Starts with tilde? */
	    xp = tilde_expand(fname);	/* Attempt to expand tilde */
	    if (*xp) 
	      fname = xp;
	}
#endif /* DTILDE */

	if (*fname == '/') {		/* Pathname is absolute */
	    strncpy(buf,fname,buflen);
	    x = strlen(buf);
	    y = 0;
	} else {			/* Pathname is relative */
	    char * p;
	    if (p = zgtdir()) {		/* So get current directory */
		debug(F110,"zfnqfp zgtdir",p,0);
		strncpy(buf,p,buflen);
		x = strlen(buf);	    
		buf[x++] = '/';
		debug(F110,"zfnqfp buf 1",buf,0);
		buflen -= x;		/* How much room left in buffer */
		if ((y = (int)strlen(fname)) > buflen) /* If enough room... */
		  return(NULL);
		strncpy(buf+x,fname,buflen); /* ... append the filename */
		debug(F110,"zfnqfp buf 2",buf,0);
	    } else {
		return(NULL);
	    }
	}

    for (x = x + y - 1; x > -1; x--)	/* Find where the filename starts */
      if (buf[x] == '/'
	  ) {				/* There is guaranteed to be one */
	  fnfp.fname = buf + x;		/* Got it, set pointer */
	  return(&fnfp);		/* and return. */
      }
    return(NULL);
}