1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
|
/*----------------------------------------------------------------------
T H E P I N E M A I L S Y S T E M
Laurence Lundblade and Mike Seibel
Networks and Distributed Computing
Computing and Communications
University of Washington
Administration Builiding, AG-44
Seattle, Washington, 98195, USA
Internet: lgl@CAC.Washington.EDU
mikes@CAC.Washington.EDU
Please address all bugs and comments to "pine-bugs@cac.washington.edu"
Pine and Pico are registered trademarks of the University of Washington.
No commercial use of these trademarks may be made without prior written
permission of the University of Washington.
Pine, Pico, and Pilot software and its included text are Copyright
1989-1998 by the University of Washington.
The full text of our legal notices is contained in the file called
CPYRIGHT, included with this distribution.
Pine is in part based on The Elm Mail System:
***********************************************************************
* The Elm Mail System - Revision: 2.13 *
* *
* Copyright (c) 1986, 1987 Dave Taylor *
* Copyright (c) 1988, 1989 USENET Community Trust *
***********************************************************************
----------------------------------------------------------------------*/
/*======================================================================
This contains most of Pine's interface to the local operating system
and hardware. Hopefully this file, os-xxx.h and makefile.xxx are the
only ones that have to be modified for most ports. Signals.c, ttyin.c,
and ttyout.c also have some dependencies. See the doc/tech-notes for
notes on porting Pine to other platforms. Here is a list of the functions
required for an implementation:
File System Access
can_access -- See if a file can be accessed
name_file_size -- Return the number of bytes in the file (by name)
fp_file_size -- Return the number of bytes in the file (by FILE *)
name_file_mtime -- Return the mtime of a file (by name)
fp_file_mtime -- Return the mtime of a file (by FILE *)
file_attrib_copy -- Copy attributes of one file to another.
is_writable_dir -- Check to see if directory exists and is writable
create_mail_dir -- Make a directory
rename_file -- change name of a file
build_path -- Put together a file system path
last_cmpnt -- Returns pointer to last component of path
expand_foldername -- Expand a folder name to full path
fnexpand -- Do filename exansion for csh style "~"
filter_filename -- Make sure file name hasn't got weird chars
cntxt_allowed -- Check whether a pathname is allowed for read/write
disk_quota -- Check the user's disk quota
read_file -- Read whole file into memory (for small files)
create_tmpfile -- Just like ANSI C tmpfile function
temp_nam -- Almost like common tempnam function
fget_pos,fset_pos -- Just like ANSI C fgetpos, fsetpos functions
Abort
coredump -- Abort running Pine dumping core if possible
System Name and Domain
hostname -- Figure out the system's host name, only
used internally in this file.
getdomainnames -- Figure out the system's domain name
canonical_name -- Returns canonical form of host name
Job Control
have_job_control -- Returns 1 if job control exists
stop_process -- What to do to stop process when it's time to stop
(only used if have_job_control returns 1)
System Error Messages (in case given one is a problem)
error_description -- Returns string describing error
System Password and Accounts
gcos_name -- Parses full name from system, only used
locally in this file so if you don't use it you
don't need it
get_user_info -- Finds in login name, full name, and homedir
local_name_lookup -- Get full name of user on system
change_passwd -- Calls system password changer
MIME utilities
mime_can_display -- Can we display this type/subtype?
exec_mailcap_cmd -- Run the mailcap command to view a type/subtype.
exec_mailcap_test_cmd -- Run mailcap test= test command.
Other stuff
srandom -- Dummy srandom if you don't have this function
init_debug
do_debug
save_debug_on_crash
====*/
#include "headers.h"
/*----------------------------------------------------------------------
Check if we can access a file in a given way
Args: file -- The file to check
mode -- The mode ala the access() system call, see ACCESS_EXISTS
and friends in pine.h.
Result: returns 0 if the user can access the file according to the mode,
-1 if he can't (and errno is set).
----*/
int
can_access(file, mode)
char *file;
int mode;
{
return(access(file, mode));
}
/*----------------------------------------------------------------------
Check if we can access a file in a given way in the given path
Args: path -- The path to look for "file" in
file -- The file to check
mode -- The mode ala the access() system call, see ACCESS_EXISTS
and friends in pine.h.
Result: returns 0 if the user can access the file according to the mode,
-1 if he can't (and errno is set).
----*/
can_access_in_path(path, file, mode)
char *path, *file;
int mode;
{
char tmp[MAXPATH], *path_copy, *p, *t;
int rv = -1;
if(!path || !*path || *file == '/'){
rv = access(file, mode);
}
else if(*file == '~'){
strcpy(tmp, file);
rv = fnexpand(tmp, sizeof(tmp)) ? access(tmp, mode) : -1;
}
else{
for(p = path_copy = cpystr(path); p && *p; p = t){
if(t = strindex(p, ':'))
*t++ = '\0';
sprintf(tmp, "%s/%s", p, file);
if((rv = access(tmp, mode)) == 0)
break;
}
fs_give((void **)&path_copy);
}
return(rv);
}
/*----------------------------------------------------------------------
Return the number of bytes in given file
Args: file -- file name
Result: the number of bytes in the file is returned or
-1 on error, in which case errno is valid
----*/
long
name_file_size(file)
char *file;
{
struct stat buffer;
if(stat(file, &buffer) != 0)
return(-1L);
return((long)buffer.st_size);
}
/*----------------------------------------------------------------------
Return the number of bytes in given file
Args: fp -- FILE * for open file
Result: the number of bytes in the file is returned or
-1 on error, in which case errno is valid
----*/
long
fp_file_size(fp)
FILE *fp;
{
struct stat buffer;
if(fstat(fileno(fp), &buffer) != 0)
return(-1L);
return((long)buffer.st_size);
}
/*----------------------------------------------------------------------
Return the modification time of given file
Args: file -- file name
Result: the time of last modification (mtime) of the file is returned or
-1 on error, in which case errno is valid
----*/
time_t
name_file_mtime(file)
char *file;
{
struct stat buffer;
if(stat(file, &buffer) != 0)
return((time_t)(-1));
return(buffer.st_mtime);
}
/*----------------------------------------------------------------------
Return the modification time of given file
Args: fp -- FILE * for open file
Result: the time of last modification (mtime) of the file is returned or
-1 on error, in which case errno is valid
----*/
time_t
fp_file_mtime(fp)
FILE *fp;
{
struct stat buffer;
if(fstat(fileno(fp), &buffer) != 0)
return((time_t)(-1));
return(buffer.st_mtime);
}
/*----------------------------------------------------------------------
Copy the mode, owner, and group of sourcefile to targetfile.
Args: targetfile --
sourcefile --
We don't bother keeping track of success or failure because we don't care.
----*/
void
file_attrib_copy(targetfile, sourcefile)
char *targetfile;
char *sourcefile;
{
struct stat buffer;
if(stat(sourcefile, &buffer) == 0){
chmod(targetfile, buffer.st_mode);
#if !defined(DOS) && !defined(OS2)
chown(targetfile, buffer.st_uid, buffer.st_gid);
#endif
}
}
/*----------------------------------------------------------------------
Check to see if a directory exists and is writable by us
Args: dir -- directory name
Result: returns 0 if it exists and is writable
1 if it is a directory, but is not writable
2 if it is not a directory
3 it doesn't exist.
----*/
is_writable_dir(dir)
char *dir;
{
struct stat sb;
if(stat(dir, &sb) < 0)
/*--- It doesn't exist ---*/
return(3);
if(!(sb.st_mode & S_IFDIR))
/*---- it's not a directory ---*/
return(2);
if(can_access(dir, 07))
return(1);
else
return(0);
}
/*----------------------------------------------------------------------
Create the mail subdirectory.
Args: dir -- Name of the directory to create
Result: Directory is created. Returns 0 on success, else -1 on error
and errno is valid.
----*/
create_mail_dir(dir)
char *dir;
{
if(mkdir(dir, 0700) < 0)
return(-1);
(void)chmod(dir, 0700);
/* Some systems need this, on others we don't care if it fails */
(void)chown(dir, getuid(), getgid());
return(0);
}
/*----------------------------------------------------------------------
Rename a file
Args: tmpfname -- Old name of file
fname -- New name of file
Result: File is renamed. Returns 0 on success, else -1 on error
and errno is valid.
----*/
rename_file(tmpfname, fname)
char *tmpfname, *fname;
{
return(rename(tmpfname, fname));
}
/*----------------------------------------------------------------------
Paste together two pieces of a file name path
Args: pathbuf -- Put the result here
first_part -- of path name
second_part -- of path name
Result: New path is in pathbuf. No check is made for overflow. Note that
we don't have to check for /'s at end of first_part and beginning
of second_part since multiple slashes are ok.
BUGS: This is a first stab at dealing with fs naming dependencies, and others
still exist.
----*/
void
build_path(pathbuf, first_part, second_part)
char *pathbuf, *first_part, *second_part;
{
if(!first_part)
strcpy(pathbuf, second_part);
else
sprintf(pathbuf, "%s%s%s", first_part,
(*first_part && first_part[strlen(first_part)-1] != '/')
? "/" : "",
second_part);
}
/*----------------------------------------------------------------------
Test to see if the given file path is absolute
Args: file -- file path to test
Result: TRUE if absolute, FALSE otw
----*/
int
is_absolute_path(path)
char *path;
{
return(path && (*path == '/' || *path == '~'));
}
/*----------------------------------------------------------------------
Return pointer to last component of pathname.
Args: filename -- The pathname.
Result: Returned pointer points to last component in the input argument.
----*/
char *
last_cmpnt(filename)
char *filename;
{
register char *p = NULL, *q = filename;
while(q = strchr(q, '/'))
if(*++q)
p = q;
return(p);
}
/*----------------------------------------------------------------------
Expand a folder name, taking account of the folders_dir and `~'.
Args: filename -- The name of the file that is the folder
Result: The folder name is expanded in place.
Returns 0 and queues status message if unsuccessful.
Input string is overwritten with expanded name.
Returns 1 if successful.
BUG should limit length to MAXPATH
----*/
int
expand_foldername(filename)
char *filename;
{
char temp_filename[MAXPATH+1];
dprint(5, (debugfile, "=== expand_foldername called (%s) ===\n",filename));
/*
* We used to check for valid filename chars here if "filename"
* didn't refer to a remote mailbox. This has been rethought
*/
strcpy(temp_filename, filename);
if(strucmp(temp_filename, "inbox") == 0) {
strcpy(filename, ps_global->VAR_INBOX_PATH == NULL ? "inbox" :
ps_global->VAR_INBOX_PATH);
} else if(temp_filename[0] == '{') {
strcpy(filename, temp_filename);
} else if(ps_global->restricted
&& (strindex("./~", temp_filename[0]) != NULL
|| srchstr(temp_filename,"/../"))){
q_status_message(SM_ORDER, 0, 3, "Can only open local folders");
return(0);
} else if(temp_filename[0] == '*') {
strcpy(filename, temp_filename);
} else if(ps_global->VAR_OPER_DIR && srchstr(temp_filename,"..")){
q_status_message(SM_ORDER, 0, 3,
"\"..\" not allowed in folder name");
return(0);
} else if (temp_filename[0] == '~'){
if(fnexpand(temp_filename, sizeof(temp_filename)) == NULL) {
char *p = strindex(temp_filename, '/');
if(p != NULL)
*p = '\0';
q_status_message1(SM_ORDER, 3, 3,
"Error expanding folder name: \"%s\" unknown user",
temp_filename);
return(0);
}
strcpy(filename, temp_filename);
} else if(temp_filename[0] == '/') {
strcpy(filename, temp_filename);
} else if(F_ON(F_USE_CURRENT_DIR, ps_global)){
strcpy(filename, temp_filename);
} else if(ps_global->VAR_OPER_DIR){
build_path(filename, ps_global->VAR_OPER_DIR, temp_filename);
} else {
build_path(filename, ps_global->home_dir, temp_filename);
}
dprint(5, (debugfile, "returning \"%s\"\n", filename));
return(1);
}
struct passwd *getpwnam();
/*----------------------------------------------------------------------
Expand the ~ in a file ala the csh (as home directory)
Args: buf -- The filename to expand (nothing happens unless begins with ~)
len -- The length of the buffer passed in (expansion is in place)
Result: Expanded string is returned using same storage as passed in.
If expansion fails, NULL is returned
----*/
char *
fnexpand(buf, len)
char *buf;
int len;
{
struct passwd *pw;
register char *x,*y;
char name[20];
if(*buf == '~') {
for(x = buf+1, y = name; *x != '/' && *x != '\0'; *y++ = *x++);
*y = '\0';
if(x == buf + 1)
pw = getpwuid(getuid());
else
pw = getpwnam(name);
if(pw == NULL)
return((char *)NULL);
if(strlen(pw->pw_dir) + strlen(buf) > len) {
return((char *)NULL);
}
rplstr(buf, x - buf, pw->pw_dir);
}
return(len ? buf : (char *)NULL);
}
/*----------------------------------------------------------------------
Filter file names for strange characters
Args: file -- the file name to check
Result: Returns NULL if file name is OK
Returns formatted error message if it is not
----*/
char *
filter_filename(file, fatal)
char *file;
int *fatal;
{
#ifdef ALLOW_WEIRD
static char illegal[] = {'\177', '\0'};
#else
static char illegal[] = {'"', '#', '$', '%', '&', '\'','(', ')','*',
',', ':', ';', '<', '=', '>', '?', '[', ']',
'\\', '^', '|', '\177', '\0'};
#endif
static char error[100];
char ill_file[MAXPATH+1], *ill_char, *ptr, e2[10];
int i;
for(ptr = file; *ptr == ' '; ptr++) ; /* leading spaces gone */
while(*ptr && (unsigned char)(*ptr) >= ' ' && strindex(illegal, *ptr) == 0)
ptr++;
*fatal = TRUE;
if(*ptr != '\0') {
if(*ptr == '\n') {
ill_char = "<newline>";
} else if(*ptr == '\r') {
ill_char = "<carriage return>";
} else if(*ptr == '\t') {
ill_char = "<tab>";
*fatal = FALSE; /* just whitespace */
} else if(*ptr < ' ') {
sprintf(e2, "control-%c", *ptr + '@');
ill_char = e2;
} else if (*ptr == '\177') {
ill_char = "<del>";
} else {
e2[0] = *ptr;
e2[1] = '\0';
ill_char = e2;
*fatal = FALSE; /* less offensive? */
}
if(!*fatal){
strcpy(error, ill_char);
}
else if(ptr != file) {
strncpy(ill_file, file, ptr - file);
ill_file[ptr - file] = '\0';
sprintf(error,
"Character \"%s\" after \"%s\" not allowed in file name",
ill_char, ill_file);
} else {
sprintf(error,
"First character, \"%s\", not allowed in file name",
ill_char);
}
return(error);
}
if((i=is_writable_dir(file)) == 0 || i == 1){
sprintf(error, "\"%s\" is a directory", file);
return(error);
}
if(ps_global->restricted || ps_global->VAR_OPER_DIR){
for(ptr = file; *ptr == ' '; ptr++) ; /* leading spaces gone */
if((ptr[0] == '.' && ptr[1] == '.') || srchstr(ptr, "/../")){
sprintf(error, "\"..\" not allowed in filename");
return(error);
}
}
return((char *)NULL);
}
/*----------------------------------------------------------------------
Check to see if user is allowed to read or write this folder.
Args: s -- the name to check
Result: Returns 1 if OK
Returns 0 and posts an error message if access is denied
----*/
int
cntxt_allowed(s)
char *s;
{
struct variable *vars = ps_global->vars;
int retval = 1;
MAILSTREAM stream; /* fake stream for error message in mm_notify */
if(ps_global->restricted
&& (strindex("./~", s[0]) || srchstr(s, "/../"))){
stream.mailbox = s;
mm_notify(&stream, "Restricted mode doesn't allow operation", WARN);
retval = 0;
}
else if(VAR_OPER_DIR
&& s[0] != '{' && !(s[0] == '*' && s[1] == '{')
&& strucmp(s,ps_global->inbox_name) != 0
&& strcmp(s, ps_global->VAR_INBOX_PATH) != 0){
char *p, *free_this = NULL;
p = s;
if(strindex(s, '~')){
p = strindex(s, '~');
free_this = (char *)fs_get(strlen(p) + 200);
strcpy(free_this, p);
fnexpand(free_this, strlen(p)+200);
p = free_this;
}
else if(p[0] != '/'){ /* add home dir to relative paths */
free_this = p = (char *)fs_get(strlen(s)
+ strlen(ps_global->home_dir) + 2);
build_path(p, ps_global->home_dir, s);
}
if(!in_dir(VAR_OPER_DIR, p)){
char err[200];
sprintf(err, "Not allowed outside of %s", VAR_OPER_DIR);
stream.mailbox = p;
mm_notify(&stream, err, WARN);
retval = 0;
}
else if(srchstr(p, "/../")){ /* check for .. in path */
stream.mailbox = p;
mm_notify(&stream, "\"..\" not allowed in name", WARN);
retval = 0;
}
if(free_this)
fs_give((void **)&free_this);
}
return retval;
}
#if defined(USE_QUOTAS)
/*----------------------------------------------------------------------
This system doesn't have disk quotas.
Return space left in disk quota on file system which given path is in.
Args: path - Path name of file or directory on file system of concern
over - pointer to flag that is set if the user is over quota
Returns: If *over = 0, the number of bytes free in disk quota as per
the soft limit.
If *over = 1, the number of bytes *over* quota.
-1 is returned on an error looking up quota
0 is returned if there is no quota
BUG: If there's more than 2.1Gb free this function will break
----*/
long
disk_quota(path, over)
char *path;
int *over;
{
return(0L);
}
#endif /* USE_QUOTAS */
/*----------------------------------------------------------------------
Read whole file into memory
Args: filename -- path name of file to read
Result: Returns pointer to malloced memory with the contents of the file
or NULL
This won't work very well if the file has NULLs in it and is mostly
intended for fairly small text files.
----*/
char *
read_file(filename)
char *filename;
{
int fd;
struct stat statbuf;
char *buf;
int nb;
fd = open(filename, O_RDONLY);
if(fd < 0)
return((char *)NULL);
fstat(fd, &statbuf);
buf = fs_get((size_t)statbuf.st_size + 1);
/*
* On some systems might have to loop here, if one read isn't guaranteed
* to get the whole thing.
*/
if((nb = read(fd, buf, (int)statbuf.st_size)) < 0)
fs_give((void **)&buf); /* NULL's buf */
else
buf[nb] = '\0';
close(fd);
return(buf);
}
/*----------------------------------------------------------------------
Create a temporary file, the name of which we don't care about
and that goes away when it is closed. Just like ANSI C tmpfile.
----*/
FILE *
create_tmpfile()
{
return(tmpfile());
}
/*----------------------------------------------------------------------
Abort with a core dump
----*/
void
coredump()
{
abort();
}
/*----------------------------------------------------------------------
Call system gethostname
Args: hostname -- buffer to return host name in
size -- Size of buffer hostname is to be returned in
Result: returns 0 if the hostname is correctly set,
-1 if not (and errno is set).
----*/
hostname(hostname,size)
char *hostname;
int size;
{
return(gethostname(hostname, size));
}
/*----------------------------------------------------------------------
Get the current host and domain names
Args: hostname -- buffer to return the hostname in
hsize -- size of buffer above
domainname -- buffer to return domain name in
dsize -- size of buffer above
Result: The system host and domain names are returned. If the full host
name is akbar.cac.washington.edu then the domainname is
cac.washington.edu.
On Internet connected hosts this look up uses /etc/hosts and DNS to
figure all this out. On other less well connected machines some other
file may be read. If there is no notion of a domain name the domain
name may be left blank. On a PC where there really isn't a host name
this should return blank strings. The .pinerc will take care of
configuring the domain names. That is, this should only return the
native system's idea of what the names are if the system has such
a concept.
----*/
void
getdomainnames(hostname, hsize, domainname, dsize)
char *hostname, *domainname;
int hsize, dsize;
{
char *dn, hname[MAX_ADDRESS+1];
struct hostent *he;
char **alias;
char *maybe = NULL;
gethostname(hname, MAX_ADDRESS);
he = gethostbyname(hname);
hostname[0] = '\0';
if(he == NULL)
strncpy(hostname, hname, hsize-1);
else{
/*
* If no dot in hostname it may be the case that there
* is an alias which is really the fully-qualified
* hostname. This could happen if the administrator has
* (incorrectly) put the unqualified name first in the
* hosts file, for example. The problem with looking for
* an alias with a dot is that now we're guessing, since
* the aliases aren't supposed to be the official hostname.
* We'll compromise and only use an alias if the primary
* name has no dot and exactly one of the aliases has a
* dot.
*/
strncpy(hostname, he->h_name, hsize-1);
if(strindex(hostname, '.') == NULL){ /* no dot in hostname */
for(alias = he->h_aliases; *alias; alias++){
if(strindex(*alias, '.') != NULL){ /* found one */
if(maybe){ /* oops, this is the second one */
maybe = NULL;
break;
}
else
maybe = *alias;
}
}
if(maybe)
strncpy(hostname, maybe, hsize-1);
}
}
hostname[hsize-1] = '\0';
if((dn = strindex(hostname, '.')) != NULL)
strncpy(domainname, dn+1, dsize-1);
else
strncpy(domainname, hostname, dsize-1);
domainname[dsize-1] = '\0';
}
/*----------------------------------------------------------------------
Return canonical form of host name ala c-client (UNIX version).
Args: host -- The host name
Result: Canonical form, or input argument (worst case)
----*/
char *
canonical_name(host)
char *host;
{
struct hostent *hent;
char hostname[MAILTMPLEN];
char tmp[MAILTMPLEN];
extern char *lcase();
/* domain literal is easy */
if (host[0] == '[' && host[(strlen (host))-1] == ']')
return host;
strcpy (hostname,host); /* UNIX requires lowercase */
/* lookup name, return canonical form */
return (hent = gethostbyname (lcase (strcpy (tmp,host)))) ?
hent->h_name : host;
}
/*----------------------------------------------------------------------
This routine returns 1 if job control is available. Note, thiis
could be some type of fake job control. It doesn't have to be
real BSD-style job control.
----*/
have_job_control()
{
return 1;
}
/*----------------------------------------------------------------------
If we don't have job control, this routine is never called.
----*/
stop_process()
{
SigType (*save_usr2) SIG_PROTO((int));
/*
* Since we can't respond to KOD while stopped, the process that sent
* the KOD is going to go read-only. Therefore, we can safely ignore
* any KODs that come in before we are ready to respond...
*/
save_usr2 = signal(SIGUSR2, SIG_IGN);
kill(0, SIGSTOP);
(void)signal(SIGUSR2, save_usr2);
}
/*----------------------------------------------------------------------
Return string describing the error
Args: errnumber -- The system error number (errno)
Result: long string describing the error is returned
----*/
char *
error_description(errnumber)
int errnumber;
{
static char buffer[50+1];
if(errnumber >= 0 && errnumber < sys_nerr)
sprintf(buffer, "%.*s", 50, sys_errlist[errnumber]);
else
sprintf(buffer, "Unknown error #%d", errnumber);
return ( (char *) buffer);
}
/*----------------------------------------------------------------------
Pull the name out of the gcos field if we have that sort of /etc/passwd
Args: gcos_field -- The long name or GCOS field to be parsed
logname -- Replaces occurances of & with logname string
Result: returns pointer to buffer with name
----*/
static char *
gcos_name(gcos_field, logname)
char *logname, *gcos_field;
{
static char fullname[MAX_FULLNAME+1];
register char *fncp, *gcoscp, *lncp, *end;
/* full name is all chars up to first ',' (or whole gcos, if no ',') */
/* replace any & with logname in upper case */
for(fncp = fullname, gcoscp= gcos_field, end = fullname + MAX_FULLNAME - 1;
(*gcoscp != ',' && *gcoscp != '\0' && fncp != end);
gcoscp++) {
if(*gcoscp == '&') {
for(lncp = logname; *lncp; fncp++, lncp++)
*fncp = toupper((unsigned char)(*lncp));
} else {
*fncp++ = *gcoscp;
}
}
*fncp = '\0';
return(fullname);
}
/*----------------------------------------------------------------------
Fill in homedir, login, and fullname for the logged in user.
These are all pointers to static storage so need to be copied
in the caller.
Args: ui -- struct pointer to pass back answers
Result: fills in the fields
----*/
void
get_user_info(ui)
struct user_info *ui;
{
struct passwd *unix_pwd;
unix_pwd = getpwuid(getuid());
if(unix_pwd == NULL) {
ui->homedir = cpystr("");
ui->login = cpystr("");
ui->fullname = cpystr("");
}else {
ui->homedir = cpystr(unix_pwd->pw_dir);
ui->login = cpystr(unix_pwd->pw_name);
ui->fullname = cpystr(gcos_name(unix_pwd->pw_gecos, unix_pwd->pw_name));
}
}
/*----------------------------------------------------------------------
Look up a userid on the local system and return rfc822 address
Args: name -- possible login name on local system
Result: returns NULL or pointer to alloc'd string rfc822 address.
----*/
char *
local_name_lookup(name)
char *name;
{
struct passwd *pw = getpwnam(name);
if(pw == NULL){
char *p;
for(p = name; *p; p++)
if(isupper((unsigned char)*p))
break;
/* try changing it to all lower case */
if(p && *p){
char *lcase;
lcase = cpystr(name);
for(p = lcase; *p; p++)
if(isupper((unsigned char)*p))
*p = tolower((unsigned char)*p);
pw = getpwnam(lcase);
if(pw)
strcpy(name, lcase);
fs_give((void **)&lcase);
}
}
if(pw == NULL)
return((char *)NULL);
return(cpystr(gcos_name(pw->pw_gecos, name)));
}
/*----------------------------------------------------------------------
Call the system to change the passwd
It would be nice to talk to the passwd program via a pipe or ptty so the
user interface could be consistent, but we can't count on the the prompts
and responses from the passwd program to be regular so we just let the user
type at the passwd program with some screen space, hope he doesn't scroll
off the top and repaint when he's done.
----*/
change_passwd()
{
char cmd_buf[100];
ClearLines(1, ps_global->ttyo->screen_rows - 1);
MoveCursor(5, 0);
fflush(stdout);
PineRaw(0);
strcpy(cmd_buf, PASSWD_PROG);
system(cmd_buf);
sleep(3);
PineRaw(1);
}
/*----------------------------------------------------------------------
Can we display this type/subtype?
Args: type -- the MIME type to check
subtype -- the MIME subtype
params -- parameters
use_viewer -- tell caller he should run external viewer cmd to view
Result: Returns:
MCD_NONE if we can't display this type at all
MCD_INTERNAL if we can display it internally
MCD_EXTERNAL if it can be displayed via an external viewer
----*/
mime_can_display(type, subtype, params)
int type;
char *subtype;
PARAMETER *params;
{
return((mailcap_can_display(type, subtype, params)
? MCD_EXTERNAL : MCD_NONE)
| ((type == TYPETEXT || type == TYPEMESSAGE
|| MIME_VCARD(type,subtype))
? MCD_INTERNAL : MCD_NONE));
}
/*======================================================================
pipe
Initiate I/O to and from a process. These functions are similar to
popen and pclose, but both an incoming stream and an output file are
provided.
====*/
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
#define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
#define STDERR_FILENO 2
#endif
/*
* Defs to help fish child's exit status out of wait(2)
*/
#ifdef HAVE_WAIT_UNION
#define WaitType union wait
#ifndef WIFEXITED
#define WIFEXITED(X) (!(X).w_termsig) /* child exit by choice */
#endif
#ifndef WEXITSTATUS
#define WEXITSTATUS(X) (X).w_retcode /* childs chosen exit value */
#endif
#else
#define WaitType int
#ifndef WIFEXITED
#define WIFEXITED(X) (!((X) & 0xff)) /* low bits tell how it died */
#endif
#ifndef WEXITSTATUS
#define WEXITSTATUS(X) (((X) >> 8) & 0xff) /* high bits tell exit value */
#endif
#endif
/*
* Global's to helpsignal handler tell us child's status has changed...
*/
short child_signalled;
short child_jump = 0;
jmp_buf child_state;
int child_pid;
/*
* Internal Protos
*/
void pipe_error_cleanup PROTO((PIPE_S **, char *, char *, char *));
void zot_pipe PROTO((PIPE_S **));
static SigType pipe_alarm SIG_PROTO((int));
/*----------------------------------------------------------------------
Spawn a child process and optionally connect read/write pipes to it
Args: command -- string to hand the shell
outfile -- address of pointer containing file to receive output
errfile -- address of pointer containing file to receive error output
mode -- mode for type of shell, signal protection etc...
Returns: pointer to alloc'd PIPE_S on success, NULL otherwise
The outfile is either NULL, a pointer to a NULL value, or a pointer
to the requested name for the output file. In the pointer-to-NULL case
the caller doesn't care about the name, but wants to see the pipe's
results so we make one up. It's up to the caller to make sure the
free storage containing the name is cleaned up.
Mode bits serve several purposes.
PIPE_WRITE tells us we need to open a pipe to write the child's
stdin.
PIPE_READ tells us we need to open a pipe to read from the child's
stdout/stderr. *NOTE* Having neither of the above set means
we're not setting up any pipes, just forking the child and exec'ing
the command. Also, this takes precedence over any named outfile.
PIPE_STDERR means we're to tie the childs stderr to the same place
stdout is going. *NOTE* This only makes sense then if PIPE_READ
or an outfile is provided. Also, this takes precedence over any
named errfile.
PIPE_PROT means to protect the child from the usual nasty signals
that might cause premature death. Otherwise, the default signals are
set so the child can deal with the nasty signals in its own way.
PIPE_NOSHELL means we're to exec the command without the aid of
a system shell. *NOTE* This negates the affect of PIPE_USER.
PIPE_USER means we're to try executing the command in the user's
shell. Right now we only look in the environment, but that may get
more sophisticated later.
PIPE_RESET means we reset the terminal mode to what it was before
we started pine and then exec the command.
----*/
PIPE_S *
open_system_pipe(command, outfile, errfile, mode, timeout)
char *command;
char **outfile, **errfile;
int mode, timeout;
{
PIPE_S *syspipe = NULL;
char shellpath[32], *shell;
int p[2], oparentd = -1, ochildd = -1, iparentd = -1, ichildd = -1;
dprint(5, (debugfile, "Opening pipe: \"%s\" (%s%s%s%s%s%s)\n", command,
(mode & PIPE_WRITE) ? "W":"", (mode & PIPE_READ) ? "R":"",
(mode & PIPE_NOSHELL) ? "N":"", (mode & PIPE_PROT) ? "P":"",
(mode & PIPE_USER) ? "U":"", (mode & PIPE_RESET) ? "T":""));
syspipe = (PIPE_S *)fs_get(sizeof(PIPE_S));
memset(syspipe, 0, sizeof(PIPE_S));
/*
* If we're not using the shell's command parsing smarts, build
* argv by hand...
*/
if(mode & PIPE_NOSHELL){
char **ap, *p;
size_t n;
/* parse the arguments into argv */
for(p = command; *p && isspace((unsigned char)(*p)); p++)
; /* swallow leading ws */
if(*p){
syspipe->args = cpystr(p);
}
else{
pipe_error_cleanup(&syspipe, "<null>", "execute",
"No command name found");
return(NULL);
}
for(p = syspipe->args, n = 2; *p; p++) /* count the args */
if(isspace((unsigned char)(*p))
&& *(p+1) && !isspace((unsigned char)(*(p+1))))
n++;
syspipe->argv = ap = (char **)fs_get(n * sizeof(char *));
memset(syspipe->argv, 0, n * sizeof(char *));
for(p = syspipe->args; *p; ){ /* collect args */
while(*p && isspace((unsigned char)(*p)))
*p++ = '\0';
*ap++ = (*p) ? p : NULL;
while(*p && !isspace((unsigned char)(*p)))
p++;
}
/* make sure argv[0] exists in $PATH */
if(can_access_in_path(getenv("PATH"), syspipe->argv[0],
EXECUTE_ACCESS) < 0){
pipe_error_cleanup(&syspipe, syspipe->argv[0], "access",
error_description(errno));
return(NULL);
}
}
/* fill in any output filenames */
if(!(mode & PIPE_READ)){
if(outfile && !*outfile)
*outfile = temp_nam(NULL, "pine_p"); /* asked for, but not named? */
if(errfile && !*errfile)
*errfile = temp_nam(NULL, "pine_p"); /* ditto */
}
/* create pipes */
if(mode & (PIPE_WRITE | PIPE_READ)){
if(mode & PIPE_WRITE){
pipe(p); /* alloc pipe to write child */
oparentd = p[STDOUT_FILENO];
ichildd = p[STDIN_FILENO];
}
if(mode & PIPE_READ){
pipe(p); /* alloc pipe to read child */
iparentd = p[STDIN_FILENO];
ochildd = p[STDOUT_FILENO];
}
}
else if(!(mode & PIPE_SILENT)){
flush_status_messages(0); /* just clean up display */
ClearScreen();
fflush(stdout);
}
if((syspipe->mode = mode) & PIPE_RESET)
PineRaw(0);
#ifdef SIGCHLD
/*
* Prepare for demise of child. Use SIGCHLD if it's available so
* we can do useful things, like keep the IMAP stream alive, while
* we're waiting on the child.
*/
child_signalled = child_jump = 0;
#endif
if((syspipe->pid = vfork()) == 0){
/* reset child's handlers in requested fashion... */
(void)signal(SIGINT, (mode & PIPE_PROT) ? SIG_IGN : SIG_DFL);
(void)signal(SIGQUIT, (mode & PIPE_PROT) ? SIG_IGN : SIG_DFL);
(void)signal(SIGHUP, (mode & PIPE_PROT) ? SIG_IGN : SIG_DFL);
#ifdef SIGCHLD
(void) signal(SIGCHLD, SIG_DFL);
#endif
/* if parent isn't reading, and we have a filename to write */
if(!(mode & PIPE_READ) && outfile){ /* connect output to file */
int output = creat(*outfile, 0600);
dup2(output, STDOUT_FILENO);
if(mode & PIPE_STDERR)
dup2(output, STDERR_FILENO);
else if(errfile)
dup2(creat(*errfile, 0600), STDERR_FILENO);
}
if(mode & PIPE_WRITE){ /* connect process input */
close(oparentd);
dup2(ichildd, STDIN_FILENO); /* tie stdin to pipe */
close(ichildd);
}
if(mode & PIPE_READ){ /* connect process output */
close(iparentd);
dup2(ochildd, STDOUT_FILENO); /* tie std{out,err} to pipe */
if(mode & PIPE_STDERR)
dup2(ochildd, STDERR_FILENO);
else if(errfile)
dup2(creat(*errfile, 0600), STDERR_FILENO);
close(ochildd);
}
if(mode & PIPE_NOSHELL){
execvp(syspipe->argv[0], syspipe->argv);
}
else{
if(mode & PIPE_USER){
char *env, *sh;
if((env = getenv("SHELL")) && (sh = strrchr(env, '/'))){
shell = sh + 1;
strcpy(shellpath, env);
}
else{
shell = "csh";
strcpy(shellpath, "/bin/csh");
}
}
else{
shell = "sh";
strcpy(shellpath, "/bin/sh");
}
execl(shellpath, shell, command ? "-c" : 0, command, 0);
}
fprintf(stderr, "Can't exec %s\nReason: %s",
command, error_description(errno));
_exit(-1);
}
if((child_pid = syspipe->pid) > 0){
syspipe->isig = signal(SIGINT, SIG_IGN); /* Reset handlers to make */
syspipe->qsig = signal(SIGQUIT, SIG_IGN); /* sure we don't come to */
syspipe->hsig = signal(SIGHUP, SIG_IGN); /* a premature end... */
if((syspipe->timeout = timeout) != 0){
syspipe->alrm = signal(SIGALRM, pipe_alarm);
syspipe->old_timeo = alarm(timeout);
}
if(mode & PIPE_WRITE){
close(ichildd);
if(mode & PIPE_DESC)
syspipe->out.d = oparentd;
else
syspipe->out.f = fdopen(oparentd, "w");
}
if(mode & PIPE_READ){
close(ochildd);
if(mode & PIPE_DESC)
syspipe->in.d = iparentd;
else
syspipe->in.f = fdopen(iparentd, "r");
}
dprint(5, (debugfile, "PID: %d, COMMAND: %s\n",syspipe->pid,command));
}
else{
if(mode & (PIPE_WRITE | PIPE_READ)){
if(mode & PIPE_WRITE){
close(oparentd);
close(ichildd);
}
if(mode & PIPE_READ){
close(iparentd);
close(ochildd);
}
}
else if(!(mode & PIPE_SILENT)){
ClearScreen();
ps_global->mangled_screen = 1;
}
if(mode & PIPE_RESET)
PineRaw(1);
#ifdef SIGCHLD
(void) signal(SIGCHLD, SIG_DFL);
#endif
if(outfile)
fs_give((void **) outfile);
pipe_error_cleanup(&syspipe, command, "fork",error_description(errno));
}
return(syspipe);
}
/*----------------------------------------------------------------------
Write appropriate error messages and cleanup after pipe error
Args: syspipe -- address of pointer to struct to clean up
cmd -- command we were trying to exec
op -- operation leading up to the exec
res -- result of that operation
----*/
void
pipe_error_cleanup(syspipe, cmd, op, res)
PIPE_S **syspipe;
char *cmd, *op, *res;
{
q_status_message3(SM_ORDER, 3, 3, "Pipe can't %s \"%.20s\": %s",
op, cmd, res);
dprint(1, (debugfile, "* * PIPE CAN'T %s(%s): %s\n", op, cmd, res));
zot_pipe(syspipe);
}
/*----------------------------------------------------------------------
Free resources associated with the given pipe struct
Args: syspipe -- address of pointer to struct to clean up
----*/
void
zot_pipe(syspipe)
PIPE_S **syspipe;
{
if((*syspipe)->args)
fs_give((void **) &(*syspipe)->args);
if((*syspipe)->argv)
fs_give((void **) &(*syspipe)->argv);
if((*syspipe)->tmp)
fs_give((void **) &(*syspipe)->tmp);
fs_give((void **)syspipe);
}
/*----------------------------------------------------------------------
Close pipe previously allocated and wait for child's death
Args: syspipe -- address of pointer to struct returned by open_system_pipe
Returns: returns exit status of child or -1 if invalid syspipe
----*/
int
close_system_pipe(syspipe)
PIPE_S **syspipe;
{
WaitType stat;
int status;
if(!(syspipe && *syspipe))
return(-1);
if(((*syspipe)->mode) & PIPE_WRITE){
if(((*syspipe)->mode) & PIPE_DESC){
if((*syspipe)->out.d >= 0)
close((*syspipe)->out.d);
}
else if((*syspipe)->out.f)
fclose((*syspipe)->out.f);
}
if(((*syspipe)->mode) & PIPE_READ){
if(((*syspipe)->mode) & PIPE_DESC){
if((*syspipe)->in.d >= 0)
close((*syspipe)->in.d);
}
else if((*syspipe)->in.f)
fclose((*syspipe)->in.f);
}
#ifdef SIGCHLD
{
SigType (*alarm_sig)();
int old_cue = F_ON(F_SHOW_DELAY_CUE, ps_global);
/*
* remember the current SIGALRM handler, and make sure it's
* installed when we're finished just in case the longjmp
* out of the SIGCHLD handler caused sleep() to lose it.
* Don't pay any attention to that man behind the curtain.
*/
alarm_sig = signal(SIGALRM, SIG_IGN);
F_SET(F_SHOW_DELAY_CUE, ps_global, 0);
ps_global->noshow_timeout = 1;
while(!child_signalled){
/* wake up and prod server */
new_mail(0, 2, ((*syspipe)->mode & PIPE_RESET)
? NM_NONE : NM_DEFER_SORT);
if(!child_signalled){
if(setjmp(child_state) == 0){
child_jump = 1; /* prepare to wake up */
sleep(600); /* give it 5mins to happend */
}
else
our_sigunblock(SIGCHLD);
}
child_jump = 0;
}
ps_global->noshow_timeout = 0;
F_SET(F_SHOW_DELAY_CUE, ps_global, old_cue);
(void) signal(SIGALRM, alarm_sig);
}
#endif
/*
* Call c-client's pid reaper to wait() on the demise of our child,
* then fish out its exit status...
*/
grim_pid_reap_status((*syspipe)->pid, 0, &stat);
status = WIFEXITED(stat) ? WEXITSTATUS(stat) : -1;
/*
* restore original handlers...
*/
(void)signal(SIGINT, (*syspipe)->isig);
(void)signal(SIGHUP, (*syspipe)->hsig);
(void)signal(SIGQUIT, (*syspipe)->qsig);
if((*syspipe)->timeout){
(void)signal(SIGALRM, (*syspipe)->alrm);
alarm((*syspipe)->old_timeo);
child_pid = 0;
}
if((*syspipe)->mode & PIPE_RESET) /* restore our tty modes */
PineRaw(1);
if(!((*syspipe)->mode & (PIPE_WRITE | PIPE_READ | PIPE_SILENT))){
ClearScreen(); /* No I/O to forked child */
ps_global->mangled_screen = 1;
}
zot_pipe(syspipe);
return(status);
}
static SigType
pipe_alarm SIG_PROTO((int sig))
{
if(child_pid)
kill(child_pid, SIGINT);
}
/*======================================================================
post_reap
Manage exit status collection of a child spawned to handle posting
====*/
#if defined(BACKGROUND_POST) && defined(SIGCHLD)
/*----------------------------------------------------------------------
Check to see if we have any posting processes to clean up after
Args: none
Returns: any finished posting process reaped
----*/
post_reap()
{
WaitType stat;
int r;
if(ps_global->post && ps_global->post->pid){
r = waitpid(ps_global->post->pid, &stat, WNOHANG);
if(r == ps_global->post->pid){
ps_global->post->status = WIFEXITED(stat) ? WEXITSTATUS(stat) : -1;
ps_global->post->pid = 0;
return(1);
}
else if(r < 0 && errno != EINTR){ /* pid's become bogus?? */
fs_give((void **) &ps_global->post);
}
}
return(0);
}
#endif
/*----------------------------------------------------------------------
Routines used to hand off messages to local agents for sending/posting
The two exported routines are:
1) smtp_command() -- used to get local transport agent to invoke
2) post_handoff() -- used to pass messages to local posting agent
----*/
/*
* Protos for "sendmail" internal functions
*/
static char *mta_parse_post PROTO((METAENV *, BODY *, char *, char *));
static long pine_pipe_soutr_nl PROTO((void *, char *));
/* ----------------------------------------------------------------------
Figure out command to start local SMTP agent
Args: errbuf -- buffer for reporting errors (assumed non-NULL)
Returns an alloc'd copy of the local SMTP agent invocation or NULL
----*/
char *
smtp_command(errbuf)
char *errbuf;
{
#if defined(SENDMAIL) && defined(SENDMAILFLAGS)
char tmp[256];
sprintf(tmp, "%s %s", SENDMAIL, SENDMAILFLAGS);
return(cpystr(tmp));
#else
strcpy(errbuf, "No default posting command.");
return(NULL);
#endif
}
/*----------------------------------------------------------------------
Hand off given message to local posting agent
Args: envelope -- The envelope for the BCC and debugging
header -- The text of the message header
errbuf -- buffer for reporting errors (assumed non-NULL)
----*/
int
mta_handoff(header, body, errbuf)
METAENV *header;
BODY *body;
char *errbuf;
{
char cmd_buf[256], *cmd = NULL;
/*
* A bit of complicated policy implemented here.
* There are two posting variables sendmail-path and smtp-server.
* Precedence is in that order.
* They can be set one of 4 ways: fixed, command-line, user, or globally.
* Precedence is in that order.
* Said differently, the order goes something like what's below.
*
* NOTE: the fixed/command-line/user precendence handling is also
* indicated by what's pointed to by ps_global->VAR_*, but since
* that also includes the global defaults, it's not sufficient.
*/
if(ps_global->FIX_SENDMAIL_PATH
&& ps_global->FIX_SENDMAIL_PATH[0]){
cmd = ps_global->FIX_SENDMAIL_PATH;
}
else if(!(ps_global->FIX_SMTP_SERVER
&& ps_global->FIX_SMTP_SERVER[0])){
if(ps_global->COM_SENDMAIL_PATH
&& ps_global->COM_SENDMAIL_PATH[0]){
cmd = ps_global->COM_SENDMAIL_PATH;
}
else if(!(ps_global->COM_SMTP_SERVER
&& ps_global->COM_SMTP_SERVER[0])){
if(ps_global->USR_SENDMAIL_PATH
&& ps_global->USR_SENDMAIL_PATH[0]){
cmd = ps_global->USR_SENDMAIL_PATH;
}
else if(!(ps_global->USR_SMTP_SERVER
&& ps_global->USR_SMTP_SERVER[0])){
if(ps_global->GLO_SENDMAIL_PATH
&& ps_global->GLO_SENDMAIL_PATH[0]){
cmd = ps_global->GLO_SENDMAIL_PATH;
}
#ifdef DF_SENDMAIL_PATH
/*
* This defines the default method of posting. So,
* unless we're told otherwise use it...
*/
else if(!(ps_global->GLO_SMTP_SERVER
&& ps_global->GLO_SMTP_SERVER[0])){
strcpy(cmd = cmd_buf, DF_SENDMAIL_PATH);
}
#endif
}
}
}
*errbuf = '\0';
if(cmd){
dprint(4, (debugfile, "call_mailer via cmd: %s\n", cmd));
(void) mta_parse_post(header, body, cmd, errbuf);
return(1);
}
else
return(0);
}
/*----------------------------------------------------------------------
Hand off given message to local posting agent
Args: envelope -- The envelope for the BCC and debugging
header -- The text of the message header
errbuf -- buffer for reporting errors (assumed non-NULL)
Fork off mailer process and pipe the message into it
Called to post news via Inews when NNTP is unavailable
----*/
char *
post_handoff(header, body, errbuf)
METAENV *header;
BODY *body;
char *errbuf;
{
char *err = NULL;
#ifdef SENDNEWS
char *s;
if(s = strstr(header->env->date," (")) /* fix the date format for news */
*s = '\0';
if(err = mta_parse_post(header, body, SENDNEWS, errbuf))
sprintf(err = errbuf, "News not posted: \"%s\": %s", SENDNEWS, err);
if(s)
*s = ' '; /* restore the date */
#else /* !SENDNEWS */ /* this is the default case */
sprintf(err = errbuf, "Can't post, NNTP-server must be defined!");
#endif /* !SENDNEWS */
return(err);
}
/*----------------------------------------------------------------------
Hand off message to local MTA; it parses recipients from 822 header
Args: header -- struct containing header data
body -- struct containing message body data
cmd -- command to use for handoff (%s says where file should go)
errs -- pointer to buf to hold errors
----*/
static char *
mta_parse_post(header, body, cmd, errs)
METAENV *header;
BODY *body;
char *cmd;
char *errs;
{
char *result = NULL;
PIPE_S *pipe;
dprint(1, (debugfile, "=== mta_parse_post(%s) ===\n", cmd));
if(pipe = open_system_pipe(cmd, &result, NULL,
PIPE_STDERR|PIPE_WRITE|PIPE_PROT|PIPE_NOSHELL|PIPE_DESC, 0)){
if(!pine_rfc822_output(header, body, pine_pipe_soutr_nl,
(TCPSTREAM *) pipe))
strcpy(errs, "Error posting.");
if(close_system_pipe(&pipe) && !*errs){
sprintf(errs, "Posting program %s returned error", cmd);
if(result)
display_output_file(result, "POSTING ERRORS", errs, 1);
}
}
else
sprintf(errs, "Error running \"%s\"", cmd);
if(result){
unlink(result);
fs_give((void **)&result);
}
return(*errs ? errs : NULL);
}
/*
* pine_pipe_soutr - Replacement for tcp_soutr that writes one of our
* pipes rather than a tcp stream
*/
static long
pine_pipe_soutr_nl (stream,s)
void *stream;
char *s;
{
long rv = T;
char *p;
size_t n;
while(*s && rv){
if(n = (p = strstr(s, "\015\012")) ? p - s : strlen(s))
while((rv = write(((PIPE_S *)stream)->out.d, s, n)) != n)
if(rv < 0){
if(errno != EINTR){
rv = 0;
break;
}
}
else{
s += rv;
n -= rv;
}
if(p && rv){
s = p + 2; /* write UNIX EOL */
while((rv = write(((PIPE_S *)stream)->out.d,"\n",1)) != 1)
if(rv < 0 && errno != EINTR){
rv = 0;
break;
}
}
else
break;
}
return(rv);
}
/* ----------------------------------------------------------------------
Execute the given mailcap command
Args: cmd -- the command to execute
image_file -- the file the data is in
needsterminal -- does this command want to take over the terminal?
----*/
void
exec_mailcap_cmd(cmd, image_file, needsterminal)
char *cmd;
char *image_file;
int needsterminal;
{
char *command = NULL,
*result_file = NULL,
*p;
char **r_file_h;
PIPE_S *syspipe;
int mode;
p = command = (char *)fs_get((32 + strlen(cmd) + (2*strlen(image_file)))
* sizeof(char));
if(!needsterminal) /* put in background if it doesn't need terminal */
*p++ = '(';
sprintf(p, "%s ; rm -f %s", cmd, image_file);
p += strlen(p);
if(!needsterminal){
*p++ = ')';
*p++ = ' ';
*p++ = '&';
}
*p++ = '\n';
*p = '\0';
dprint(9, (debugfile, "exec_mailcap_cmd: command=%s\n", command));
mode = PIPE_RESET;
if(needsterminal == 1)
r_file_h = NULL;
else{
mode |= PIPE_WRITE | PIPE_STDERR;
result_file = temp_nam(NULL, "pine_cmd");
r_file_h = &result_file;
}
if(syspipe = open_system_pipe(command, r_file_h, NULL, mode, 0)){
close_system_pipe(&syspipe);
if(needsterminal == 1)
q_status_message(SM_ORDER, 0, 4, "VIEWER command completed");
else if(needsterminal == 2)
display_output_file(result_file, "VIEWER", " command result", 1);
else
display_output_file(result_file, "VIEWER", " command launched", 1);
}
else
q_status_message1(SM_ORDER, 3, 4, "Cannot spawn command : %s", cmd);
fs_give((void **)&command);
if(result_file)
fs_give((void **)&result_file);
}
/* ----------------------------------------------------------------------
Execute the given mailcap test= cmd
Args: cmd -- command to execute
Returns exit status
----*/
int
exec_mailcap_test_cmd(cmd)
char *cmd;
{
PIPE_S *syspipe;
return((syspipe = open_system_pipe(cmd, NULL, NULL, PIPE_SILENT, 0))
? close_system_pipe(&syspipe) : -1);
}
/*======================================================================
print routines
Functions having to do with printing on paper and forking of spoolers
In general one calls open_printer() to start printing. One of
the little print functions to send a line or string, and then
call print_end() when complete. This takes care of forking off a spooler
and piping the stuff down it. No handles or anything here because there's
only one printer open at a time.
====*/
static char *trailer; /* so both open and close_printer can see it */
/*----------------------------------------------------------------------
Open the printer
Args: desc -- Description of item to print. Should have one trailing blank.
Return value: < 0 is a failure.
0 a success.
This does most of the work of popen so we can save the standard output of the
command we execute and send it back to the user.
----*/
int
open_printer(desc)
char *desc;
{
char command[201], prompt[200];
int cmd, rc, just_one;
char *p, *init, *nick;
char aname[100];
char *printer;
int done = 0, i, lastprinter, cur_printer = 0;
HelpType help;
char **list;
static ESCKEY_S ekey[] = {
{'y', 'y', "Y", "Yes"},
{'n', 'n', "N", "No"},
{ctrl('P'), 10, "^P", "Prev Printer"},
{ctrl('N'), 11, "^N", "Next Printer"},
{-2, 0, NULL, NULL},
{'c', 'c', "C", "CustomPrint"},
{KEY_UP, 10, "", ""},
{KEY_DOWN, 11, "", ""},
{-1, 0, NULL, NULL}};
#define PREV_KEY 2
#define NEXT_KEY 3
#define CUSTOM_KEY 5
#define UP_KEY 6
#define DOWN_KEY 7
trailer = NULL;
init = NULL;
nick = NULL;
command[200] = '\0';
if(ps_global->VAR_PRINTER == NULL){
q_status_message(SM_ORDER | SM_DING, 3, 5,
"No printer has been chosen. Use SETUP on main menu to make choice.");
return(-1);
}
/* Is there just one print command available? */
just_one = (ps_global->printer_category!=3&&ps_global->printer_category!=2)
|| (ps_global->printer_category == 2
&& !(ps_global->VAR_STANDARD_PRINTER
&& ps_global->VAR_STANDARD_PRINTER[0]
&& ps_global->VAR_STANDARD_PRINTER[1]))
|| (ps_global->printer_category == 3
&& !(ps_global->VAR_PERSONAL_PRINT_COMMAND
&& ps_global->VAR_PERSONAL_PRINT_COMMAND[0]
&& ps_global->VAR_PERSONAL_PRINT_COMMAND[1]));
if(F_ON(F_CUSTOM_PRINT, ps_global))
ekey[CUSTOM_KEY].ch = 'c'; /* turn this key on */
else
ekey[CUSTOM_KEY].ch = -2; /* turn this key off */
if(just_one){
ekey[PREV_KEY].ch = -2; /* turn these keys off */
ekey[NEXT_KEY].ch = -2;
ekey[UP_KEY].ch = -2;
ekey[DOWN_KEY].ch = -2;
}
else{
ekey[PREV_KEY].ch = ctrl('P'); /* turn these keys on */
ekey[NEXT_KEY].ch = ctrl('N');
ekey[UP_KEY].ch = KEY_UP;
ekey[DOWN_KEY].ch = KEY_DOWN;
/*
* count how many printers in list and find the default in the list
*/
if(ps_global->printer_category == 2)
list = ps_global->VAR_STANDARD_PRINTER;
else
list = ps_global->VAR_PERSONAL_PRINT_COMMAND;
for(i = 0; list[i]; i++)
if(strcmp(ps_global->VAR_PRINTER, list[i]) == 0)
cur_printer = i;
lastprinter = i - 1;
}
help = NO_HELP;
ps_global->mangled_footer = 1;
while(!done){
if(init)
fs_give((void **)&init);
if(trailer)
fs_give((void **)&trailer);
if(just_one)
printer = ps_global->VAR_PRINTER;
else
printer = list[cur_printer];
parse_printer(printer, &nick, &p, &init, &trailer, NULL, NULL);
strncpy(command, p, 200);
fs_give((void **)&p);
sprintf(prompt, "Print %.50s%susing \"%.50s\" ? ",
desc ? desc : "",
(desc && *desc && desc[strlen(desc) - 1] != ' ') ? " " : "",
*nick ? nick : command);
fs_give((void **)&nick);
cmd = radio_buttons(prompt, -FOOTER_ROWS(ps_global),
ekey, 'y', 'x', help, RB_NORM);
switch(cmd){
case 'y':
q_status_message1(SM_ORDER, 0, 9,
"Printing with command \"%s\"", command);
done++;
break;
case 10:
cur_printer = (cur_printer>0)
? (cur_printer-1)
: lastprinter;
break;
case 11:
cur_printer = (cur_printer<lastprinter)
? (cur_printer+1)
: 0;
break;
case 'n':
case 'x':
done++;
break;
case 'c':
done++;
break;
default:
break;
}
}
if(cmd == 'c'){
if(init)
fs_give((void **)&init);
if(trailer)
fs_give((void **)&trailer);
sprintf(prompt, "Enter custom command : ");
command[0] = '\0';
rc = 1;
help = NO_HELP;
while(rc){
int flags = OE_APPEND_CURRENT;
rc = optionally_enter(command, -FOOTER_ROWS(ps_global), 0,
200, prompt, NULL, help, &flags);
if(rc == 1){
cmd = 'x';
rc = 0;
}
else if(rc == 3)
help = (help == NO_HELP) ? h_custom_print : NO_HELP;
else if(rc == 0){
removing_trailing_white_space(command);
removing_leading_white_space(command);
q_status_message1(SM_ORDER, 0, 9,
"Printing with command \"%s\"", command);
}
}
}
if(cmd == 'x' || cmd == 'n'){
q_status_message(SM_ORDER, 0, 2, "Print cancelled");
if(init)
fs_give((void **)&init);
if(trailer)
fs_give((void **)&trailer);
return(-1);
}
display_message('x');
ps_global->print = (PRINT_S *)fs_get(sizeof(PRINT_S));
memset(ps_global->print, 0, sizeof(PRINT_S));
strcat(strcpy(aname, ANSI_PRINTER), "-no-formfeed");
if(strucmp(command, ANSI_PRINTER) == 0
|| strucmp(command, aname) == 0){
/*----------- Printer attached to ansi device ---------*/
q_status_message(SM_ORDER, 0, 9,
"Printing to attached desktop printer...");
display_message('x');
xonxoff_proc(1); /* make sure XON/XOFF used */
crlf_proc(1); /* AND LF->CR xlation */
fputs("\033[5i", stdout);
ps_global->print->fp = stdout;
if(strucmp(command, ANSI_PRINTER) == 0){
/* put formfeed at the end of the trailer string */
if(trailer){
int len = strlen(trailer);
fs_resize((void **)&trailer, len+2);
trailer[len] = '\f';
trailer[len+1] = '\0';
}
else
trailer = cpystr("\f");
}
}
else{
/*----------- Print by forking off a UNIX command ------------*/
dprint(4, (debugfile, "Printing using command \"%s\"\n", command));
ps_global->print->result = temp_nam(NULL, "pine_prt");
if(ps_global->print->pipe = open_system_pipe(command,
&ps_global->print->result, NULL,
PIPE_WRITE | PIPE_STDERR, 0)){
ps_global->print->fp = ps_global->print->pipe->out.f;
}
else{
fs_give((void **)&ps_global->print->result);
q_status_message1(SM_ORDER | SM_DING, 3, 4,
"Error opening printer: %s",
error_description(errno));
dprint(2, (debugfile, "Error popening printer \"%s\"\n",
error_description(errno)));
if(init)
fs_give((void **)&init);
if(trailer)
fs_give((void **)&trailer);
return(-1);
}
}
ps_global->print->err = 0;
if(init){
if(*init)
fputs(init, ps_global->print->fp);
fs_give((void **)&init);
}
return(0);
}
/*----------------------------------------------------------------------
Close printer
If we're piping to a spooler close down the pipe and wait for the process
to finish. If we're sending to an attached printer send the escape sequence.
Also let the user know the result of the print
----*/
void
close_printer()
{
if(trailer){
if(*trailer)
fputs(trailer, ps_global->print->fp);
fs_give((void **)&trailer);
}
if(ps_global->print->fp == stdout) {
fputs("\033[4i", stdout);
fflush(stdout);
if(F_OFF(F_PRESERVE_START_STOP, ps_global))
xonxoff_proc(0); /* turn off XON/XOFF */
crlf_proc(0); /* turn off CF->LF xlantion */
} else {
(void) close_system_pipe(&ps_global->print->pipe);
display_output_file(ps_global->print->result, "PRINT", NULL, 1);
fs_give((void **)&ps_global->print->result);
}
fs_give((void **)&ps_global->print);
q_status_message(SM_ASYNC, 0, 3, "Print command completed");
display_message('x');
}
/*----------------------------------------------------------------------
Print a single character
Args: c -- char to print
Returns: 1 on success, 0 on ps_global->print->err
----*/
int
print_char(c)
int c;
{
if(!ps_global->print->err && putc(c, ps_global->print->fp) == EOF)
ps_global->print->err = 1;
return(!ps_global->print->err);
}
/*----------------------------------------------------------------------
Send a line of text to the printer
Args: line -- Text to print
----*/
void
print_text(line)
char *line;
{
if(!ps_global->print->err && fputs(line, ps_global->print->fp) == EOF)
ps_global->print->err = 1;
}
/*----------------------------------------------------------------------
printf style formatting with one arg for printer
Args: line -- The printf control string
a1 -- The 1st argument for printf
----*/
void
print_text1(line, a1)
char *line, *a1;
{
if(!ps_global->print->err
&& fprintf(ps_global->print->fp, line, a1) < 0)
ps_global->print->err = 1;
}
/*----------------------------------------------------------------------
printf style formatting with one arg for printer
Args: line -- The printf control string
a1 -- The 1st argument for printf
a2 -- The 2nd argument for printf
----*/
void
print_text2(line, a1, a2)
char *line, *a1, *a2;
{
if(!ps_global->print->err
&& fprintf(ps_global->print->fp, line, a1, a2) < 0)
ps_global->print->err = 1;
}
/*----------------------------------------------------------------------
printf style formatting with one arg for printer
Args: line -- The printf control string
a1 -- The 1st argument for printf
a2 -- The 2nd argument for printf
a3 -- The 3rd argument for printf
----*/
void
print_text3(line, a1, a2, a3)
char *line, *a1, *a2, *a3;
{
if(!ps_global->print->err
&& fprintf(ps_global->print->fp, line, a1, a2, a3) < 0)
ps_global->print->err = 1;
}
#ifdef DEBUG
/*----------------------------------------------------------------------
Initialize debugging - open the debug log file
Args: none
Result: opens the debug logfile for dprints
Opens the file "~/.pine-debug1. Also maintains .pine-debug[2-4]
by renaming them each time so the last 4 sessions are saved.
----*/
void
init_debug()
{
char nbuf[5];
char newfname[MAXPATH+1], filename[MAXPATH+1];
int i, fd;
if(!(debug || ps_global->debug_imap))
return;
for(i = ps_global->debug_nfiles - 1; i > 0; i--){
build_path(filename, ps_global->home_dir, DEBUGFILE);
strcpy(newfname, filename);
sprintf(nbuf, "%d", i);
strcat(filename, nbuf);
sprintf(nbuf, "%d", i+1);
strcat(newfname, nbuf);
(void)rename_file(filename, newfname);
}
build_path(filename, ps_global->home_dir, DEBUGFILE);
strcat(filename, "1");
debugfile = NULL;
if((fd = open(filename, O_TRUNC|O_RDWR|O_CREAT, 0600)) >= 0)
debugfile = fdopen(fd, "w+");
if(debugfile != NULL){
time_t now = time((time_t *)0);
if(ps_global->debug_flush)
setbuf(debugfile, NULL);
if(ps_global->debug_nfiles == 0){
/*
* If no debug files are asked for, make filename a tempfile
* to be used for a record should pine later crash...
*/
if(debug < 9 && !ps_global->debug_flush && ps_global->debug_imap<4)
unlink(filename);
}
dprint(0, (debugfile,
"Debug output of the Pine program (debug=%d debug_imap=%d). Version %s\n%s\n",
debug, ps_global->debug_imap, pine_version, ctime(&now)));
}
}
/*----------------------------------------------------------------------
Try to save the debug file if we crash in a controlled way
Args: dfile: pointer to open debug file
Result: tries to move the appropriate .pine-debugx file to .pine-crash
Looks through the four .pine-debug files hunting for the one that is
associated with this pine, and then renames it.
----*/
void
save_debug_on_crash(dfile)
FILE *dfile;
{
char nbuf[5], crashfile[MAXPATH+1], filename[MAXPATH+1];
int i;
struct stat dbuf, tbuf;
time_t now = time((time_t *)0);
if(!(dfile && fstat(fileno(dfile), &dbuf) != 0))
return;
fprintf(dfile, "\nsave_debug_on_crash: Version %s: debug level %d\n",
pine_version, debug);
fprintf(dfile, "\n : %s\n", ctime(&now));
build_path(crashfile, ps_global->home_dir, ".pine-crash");
fprintf(dfile, "\nAttempting to save debug file to %s\n", crashfile);
fprintf(stderr,
"\n\n Attempting to save debug file to %s\n\n", crashfile);
/* Blat out last n keystrokes */
fputs("========== Latest keystrokes ==========\n", dfile);
while((i = key_playback(0)) != -1)
fprintf(dfile, "\t%s\t(0x%04.4x)\n", pretty_command(i), i);
/* look for existing debug file */
for(i = 1; i <= ps_global->debug_nfiles; i++){
build_path(filename, ps_global->home_dir, DEBUGFILE);
sprintf(nbuf, "%d", i);
strcat(filename, nbuf);
if(stat(filename, &tbuf) != 0)
continue;
/* This must be the current debug file */
if(tbuf.st_dev == dbuf.st_dev && tbuf.st_ino == dbuf.st_ino){
rename_file(filename, crashfile);
break;
}
}
/* if current debug file name not found, write it by hand */
if(i > ps_global->debug_nfiles){
FILE *cfp;
char buf[1025];
/*
* Copy the debug temp file into the
*/
if(cfp = fopen(crashfile, "w")){
buf[1024] = '\0';
fseek(dfile, 0L, 0);
while(fgets(buf, 1025, dfile) && fputs(buf, cfp) != EOF)
;
fclose(cfp);
}
}
fclose(dfile);
}
#define CHECK_EVERY_N_TIMES 100
#define MAX_DEBUG_FILE_SIZE 200000L
/*
* This is just to catch runaway Pines that are looping spewing out
* debugging (and filling up a file system). The stop doesn't have to be
* at all precise, just soon enough to hopefully prevent filling the
* file system. If the debugging level is high (9 for now), then we're
* presumably looking for some problem, so don't truncate.
*/
int
do_debug(debug_fp)
FILE *debug_fp;
{
static int counter = CHECK_EVERY_N_TIMES;
static int ok = 1;
long filesize;
if(debug == DEFAULT_DEBUG
&& !ps_global->debug_flush
&& !ps_global->debug_timestamp
&& ps_global->debug_imap < 2
&& ok
&& --counter <= 0){
if((filesize = fp_file_size(debug_fp)) != -1L)
ok = (unsigned long)filesize < (unsigned long)MAX_DEBUG_FILE_SIZE;
counter = CHECK_EVERY_N_TIMES;
if(!ok){
fprintf(debug_fp, "\n\n --- No more debugging ---\n");
fprintf(debug_fp,
" (debug file growing too large - over %ld bytes)\n\n",
MAX_DEBUG_FILE_SIZE);
fflush(debug_fp);
}
}
if(ok && ps_global->debug_timestamp)
fprintf(debug_fp, "\n%s\n", debug_time(0));
return(ok);
}
/*
* Returns a pointer to static string for a timestamp.
*
* If timestamp is set .subseconds are added if available.
* If include_date is set the date is appended.
*/
char *
debug_time(include_date)
int include_date;
{
time_t t;
struct tm *tm_now;
struct timeval tp;
struct timezone tzp;
static char timestring[23];
char subsecond[8];
char datestr[7];
if(gettimeofday(&tp, &tzp) == 0){
t = (time_t)tp.tv_sec;
if(include_date){
tm_now = localtime(&t);
sprintf(datestr, " %d/%d", tm_now->tm_mon+1, tm_now->tm_mday);
}
else
datestr[0] = '\0';
if(ps_global->debug_timestamp)
sprintf(subsecond, ".%06ld", tp.tv_usec);
else
subsecond[0] = '\0';
sprintf(timestring, "%.8s%s%s", ctime(&t)+11, subsecond, datestr);
}
else
timestring[0] = '\0';
return(timestring);
}
#endif /* DEBUG */
/*
* Fills in the passed in structure with the current time.
*
* Returns 0 if ok
* -1 if can't do it
*/
int
get_time(our_time_val)
TIMEVAL_S *our_time_val;
{
struct timeval tp;
struct timezone tzp;
if(gettimeofday(&tp, &tzp) == 0){
our_time_val->sec = tp.tv_sec;
our_time_val->usec = tp.tv_usec;
return 0;
}
else
return -1;
}
/*
* Returns the difference between the two values, in microseconds.
* Value returned is first - second.
*/
long
time_diff(first, second)
TIMEVAL_S *first,
*second;
{
return(1000000L*(first->sec - second->sec) + (first->usec - second->usec));
}
/*======================================================================
Things having to do with reading from the tty driver and keyboard
- initialize tty driver and reset tty driver
- read a character from terminal with keyboard escape seqence mapping
- initialize keyboard (keypad or such) and reset keyboard
- prompt user for a line of input
- read a command from keyboard with timeouts.
====*/
/*
* Helpful definitions
*/
#define RETURN_CH(X) return(key_recorder((X)))
/*
* Should really be using pico's TERM's t_getchar to read a character but
* we're just calling ttgetc directly for now. Ttgetc is the same as
* t_getchar whenever we use it so we're avoiding the trouble of initializing
* the TERM struct and calling ttgetc directly.
*/
#define READ_A_CHAR() ttgetc(NO_OP_COMMAND, key_recorder, read_bail)
/*
* Internal prototypes
*/
int pine_simple_ttgetc PROTO((int (*)(), void (*)()));
void line_paint PROTO((int, int *));
int process_config_input PROTO((int *));
int check_for_timeout PROTO((int));
void read_bail PROTO((void));
/*----------------------------------------------------------------------
Initialize the tty driver to do single char I/O and whatever else (UNIX)
Args: struct pine
Result: tty driver is put in raw mode so characters can be read one
at a time. Returns -1 if unsuccessful, 0 if successful.
Some file descriptor voodoo to allow for pipes across vforks. See
open_mailer for details.
----------------------------------------------------------------------*/
init_tty_driver(ps)
struct pine *ps;
{
#ifdef MOUSE
if(F_ON(F_ENABLE_MOUSE, ps_global))
init_mouse();
#endif /* MOUSE */
/* turn off talk permission by default */
if(F_ON(F_ALLOW_TALK, ps))
allow_talk(ps);
else
disallow_talk(ps);
return(PineRaw(1));
}
/*----------------------------------------------------------------------
Set or clear the specified tty mode
Args: ps -- struct pine
mode -- mode bits to modify
clear -- whether or not to clear or set
Result: tty driver mode change.
----------------------------------------------------------------------*/
void
tty_chmod(ps, mode, func)
struct pine *ps;
int mode;
int func;
{
char *tty_name;
int new_mode;
struct stat sbuf;
static int saved_mode = -1;
/* if no problem figuring out tty's name & mode? */
if((((tty_name = (char *) ttyname(STDIN_FD)) != NULL
&& fstat(STDIN_FD, &sbuf) == 0)
|| ((tty_name = (char *) ttyname(STDOUT_FD)) != NULL
&& fstat(STDOUT_FD, &sbuf) == 0))
&& !(func == TMD_RESET && saved_mode < 0)){
new_mode = (func == TMD_RESET)
? saved_mode
: (func == TMD_CLEAR)
? (sbuf.st_mode & ~mode)
: (sbuf.st_mode | mode);
/* assign tty new mode */
if(chmod(tty_name, new_mode) == 0){
if(func == TMD_RESET) /* forget we knew */
saved_mode = -1;
else if(saved_mode < 0)
saved_mode = sbuf.st_mode; /* remember original */
}
}
}
/*----------------------------------------------------------------------
End use of the tty, put it back into it's normal mode (UNIX)
Args: ps -- struct pine
Result: tty driver mode change.
----------------------------------------------------------------------*/
void
end_tty_driver(ps)
struct pine *ps;
{
ps = ps; /* get rid of unused parameter warning */
#ifdef MOUSE
end_mouse();
#endif /* MOUSE */
fflush(stdout);
dprint(2, (debugfile, "about to end_tty_driver\n"));
tty_chmod(ps, 0, TMD_RESET);
PineRaw(0);
}
/*----------------------------------------------------------------------
Actually set up the tty driver (UNIX)
Args: state -- which state to put it in. 1 means go into raw, 0 out of
Result: returns 0 if successful and < 0 if not.
----*/
PineRaw(state)
int state;
{
int result;
result = Raw(state);
if(result == 0 && state == 1){
/*
* Only go into 8 bit mode if we are doing something other
* than plain ASCII. This will save the folks that have
* their parity on their serial lines wrong thr trouble of
* getting it right
*/
if(ps_global->VAR_CHAR_SET && ps_global->VAR_CHAR_SET[0] &&
strucmp(ps_global->VAR_CHAR_SET, "us-ascii"))
bit_strip_off();
#ifdef DEBUG
if(debug < 9) /* only on if full debugging set */
#endif
quit_char_off();
ps_global->low_speed = ttisslow();
crlf_proc(0);
xonxoff_proc(F_ON(F_PRESERVE_START_STOP, ps_global));
}
return(result);
}
#ifdef RESIZING
jmp_buf winch_state;
int winch_occured = 0;
int ready_for_winch = 0;
#endif
/*----------------------------------------------------------------------
This checks whether or not a character (UNIX)
is ready to be read, or it times out.
Args: time_out -- number of seconds before it will timeout
Result: Returns a NO_OP_IDLE or a NO_OP_COMMAND if the timeout expires
before input is available, or a KEY_RESIZE if a resize event
occurs, or READY_TO_READ if input is available before the timeout.
----*/
int
check_for_timeout(time_out)
int time_out;
{
int res;
fflush(stdout);
#ifdef RESIZING
if(!winch_occured){
if(setjmp(winch_state) != 0){
winch_occured = 1;
ready_for_winch = 0;
/*
* Need to unblock signal after longjmp from handler, because
* signal is normally unblocked upon routine exit from the handler.
*/
our_sigunblock(SIGWINCH);
}
else
ready_for_winch = 1;
}
if(winch_occured){
winch_occured = ready_for_winch = 0;
fix_windsize(ps_global);
return(KEY_RESIZE);
}
#endif /* RESIZING */
switch(res = input_ready(time_out)){
case BAIL_OUT:
read_bail(); /* non-tragic exit */
/* NO RETURN */
case PANIC_NOW:
panic1("Select error: %s\n", error_description(errno));
/* NO RETURN */
case READ_INTR:
res = NO_OP_COMMAND;
/* fall through */
case NO_OP_IDLE:
case NO_OP_COMMAND:
case READY_TO_READ:
#ifdef RESIZING
ready_for_winch = 0;
#endif
return(res);
}
}
/*----------------------------------------------------------------------
Read input characters with lots of processing for arrow keys and such (UNIX)
Args: time_out -- The timeout to for the reads
Result: returns the character read. Possible special chars.
This deals with function and arrow keys as well.
The idea is that this routine handles all escape codes so it done in
only one place. Especially so the back arrow key can work when entering
things on a line. Also so all function keys can be disabled and not
cause weird things to happen.
---*/
int
read_char(time_out)
int time_out;
{
int ch, status, cc;
/* Get input from initial-keystrokes */
if(process_config_input(&ch))
return(ch);
/*
* We only check for timeouts at the start of read_char, not in the
* middle of escape sequences.
*/
if((ch = check_for_timeout(time_out)) != READY_TO_READ)
goto done;
ps_global->time_of_last_input = time((time_t *)0);
switch(status = kbseq(pine_simple_ttgetc, key_recorder, read_bail, &ch)){
case KEY_DOUBLE_ESC:
/*
* Special hack to get around comm devices eating control characters.
*/
if(check_for_timeout(5) != READY_TO_READ){
ch = KEY_JUNK; /* user typed ESC ESC, then stopped */
goto done;
}
else
ch = READ_A_CHAR();
ch &= 0x7f;
if(isdigit((unsigned char)ch)){
int n = 0, i = ch - '0';
if(i < 0 || i > 2){
ch = KEY_JUNK;
goto done; /* bogus literal char value */
}
while(n++ < 2){
if(check_for_timeout(5) != READY_TO_READ
|| (!isdigit((unsigned char) (ch = READ_A_CHAR()))
|| (n == 1 && i == 2 && ch > '5')
|| (n == 2 && i == 25 && ch > '5'))){
ch = KEY_JUNK; /* user typed ESC ESC #, stopped */
goto done;
}
i = (i * 10) + (ch - '0');
}
ch = i;
}
else{
if(islower((unsigned char)ch)) /* canonicalize if alpha */
ch = toupper((unsigned char)ch);
ch = (isalpha((unsigned char)ch) || ch == '@'
|| (ch >= '[' && ch <= '_'))
? ctrl(ch) : ((ch == SPACE) ? ctrl('@'): ch);
}
goto done;
#ifdef MOUSE
case KEY_XTERM_MOUSE:
if(mouseexist()){
/*
* Special hack to get mouse events from an xterm.
* Get the details, then pass it past the keymenu event
* handler, and then to the installed handler if there
* is one...
*/
static int down = 0;
int x, y, button;
unsigned cmd;
clear_cursor_pos();
button = READ_A_CHAR() & 0x03;
x = READ_A_CHAR() - '!';
y = READ_A_CHAR() - '!';
ch = NO_OP_COMMAND;
if(button == 0){ /* xterm button 1 down */
down = 1;
if(checkmouse(&cmd, 1, x, y))
ch = (int)cmd;
}
else if (down && button == 3){
down = 0;
if(checkmouse(&cmd, 0, x, y))
ch = (int)cmd;
}
goto done;
}
break;
#endif /* MOUSE */
case KEY_UP :
case KEY_DOWN :
case KEY_RIGHT :
case KEY_LEFT :
case KEY_PGUP :
case KEY_PGDN :
case KEY_HOME :
case KEY_END :
case KEY_DEL :
case PF1 :
case PF2 :
case PF3 :
case PF4 :
case PF5 :
case PF6 :
case PF7 :
case PF8 :
case PF9 :
case PF10 :
case PF11 :
case PF12 :
dprint(9, (debugfile, "Read char returning: %d %s\n",
status, pretty_command(status)));
return(status);
case KEY_SWALLOW_Z:
status = KEY_JUNK;
case KEY_SWAL_UP:
case KEY_SWAL_DOWN:
case KEY_SWAL_LEFT:
case KEY_SWAL_RIGHT:
do
if(check_for_timeout(2) != READY_TO_READ){
status = KEY_JUNK;
break;
}
while(!strchr("~qz", READ_A_CHAR()));
ch = (status == KEY_JUNK) ? status : status - (KEY_SWAL_UP - KEY_UP);
goto done;
case KEY_KERMIT:
do{
cc = ch;
if(check_for_timeout(2) != READY_TO_READ){
status = KEY_JUNK;
break;
}
else
ch = READ_A_CHAR();
}while(cc != '\033' && ch != '\\');
ch = KEY_JUNK;
goto done;
case BADESC:
ch = KEY_JUNK;
goto done;
case 0: /* regular character */
default:
/*
* we used to strip (ch &= 0x7f;), but this seems much cleaner
* in the face of line noise and has the benefit of making it
* tougher to emit mistakenly labeled MIME...
*/
if((ch & 0x80) && (!ps_global->VAR_CHAR_SET
|| !strucmp(ps_global->VAR_CHAR_SET, "US-ASCII"))){
dprint(9, (debugfile, "Read char returning: %d %s\n",
status, pretty_command(status)));
return(KEY_JUNK);
}
else if(ch == ctrl('Z')){
dprint(9, (debugfile, "Read char calling do_suspend\n"));
return(do_suspend());
}
done:
dprint(9, (debugfile, "Read char returning: %d %s\n",
ch, pretty_command(ch)));
return(ch);
}
}
/*----------------------------------------------------------------------
Reading input somehow failed and we need to shutdown now
Args: none
Result: pine exits
---*/
void
read_bail()
{
end_signals(1);
if(ps_global->inbox_stream){
if(ps_global->inbox_stream == ps_global->mail_stream)
ps_global->mail_stream = NULL;
if(!ps_global->inbox_stream->lock) /* shouldn't be... */
pine_close_stream(ps_global->inbox_stream);
}
if(ps_global->mail_stream && !ps_global->mail_stream->lock)
pine_close_stream(ps_global->mail_stream);
end_keyboard(F_ON(F_USE_FK,ps_global));
end_tty_driver(ps_global);
if(filter_data_file(0))
unlink(filter_data_file(0));
exit(0);
}
int
pine_simple_ttgetc(fi, fv)
int (*fi)();
void (*fv)();
{
int ch;
#ifdef RESIZING
if(!winch_occured){
if(setjmp(winch_state) != 0){
winch_occured = 1;
ready_for_winch = 0;
/*
* Need to unblock signal after longjmp from handler, because
* signal is normally unblocked upon routine exit from the handler.
*/
our_sigunblock(SIGWINCH);
}
else
ready_for_winch = 1;
}
if(winch_occured){
winch_occured = ready_for_winch = 0;
fix_windsize(ps_global);
return(KEY_RESIZE);
}
#endif /* RESIZING */
ch = simple_ttgetc(fi, fv);
#ifdef RESIZING
ready_for_winch = 0;
#endif
return(ch);
}
extern char term_name[];
/* -------------------------------------------------------------------
Set up the keyboard -- usually enable some function keys (UNIX)
Args: struct pine
So far all we do here is turn on keypad mode for certain terminals
Hack for NCSA telnet on an IBM PC to put the keypad in the right mode.
This is the same for a vtXXX terminal or [zh][12]9's which we have
a lot of at UW
----*/
void
init_keyboard(use_fkeys)
int use_fkeys;
{
if(use_fkeys && (!strucmp(term_name,"vt102")
|| !strucmp(term_name,"vt100")))
printf("\033\133\071\071\150");
}
/*----------------------------------------------------------------------
Clear keyboard, usually disable some function keys (UNIX)
Args: pine state (terminal type)
Result: keyboard state reset
----*/
void
end_keyboard(use_fkeys)
int use_fkeys;
{
if(use_fkeys && (!strcmp(term_name, "vt102")
|| !strcmp(term_name, "vt100"))){
printf("\033\133\071\071\154");
fflush(stdout);
}
}
#ifdef _WINDOWS
#line 3 "osdep/termin.gen"
static int g_mc_row, g_mc_col;
int pcpine_oe_cursor PROTO((int, long));
#endif
/*
* Generic tty input routines
*/
/*----------------------------------------------------------------------
Read a character from keyboard with timeout
Input: none
Result: Returns command read via read_char
Times out and returns a null command every so often
Calculates the timeout for the read, and does a few other house keeping
things. The duration of the timeout is set in pine.c.
----------------------------------------------------------------------*/
int
read_command()
{
int ch, tm = 0;
long dtime;
cancel_busy_alarm(-1);
tm = (messages_queued(&dtime) > 1) ? (int)dtime : timeo;
/*
* Before we sniff at the input queue, make sure no external event's
* changed our picture of the message sequence mapping. If so,
* recalculate the dang thing and run thru whatever processing loop
* we're in again...
*/
if(ps_global->expunge_count){
q_status_message3(SM_ORDER, 3, 3,
"%s message%s expunged from folder \"%s\"",
long2string(ps_global->expunge_count),
plural(ps_global->expunge_count),
pretty_fn(ps_global->cur_folder));
ps_global->expunge_count = 0L;
display_message('x');
}
if(ps_global->inbox_expunge_count){
q_status_message3(SM_ORDER, 3, 3,
"%s message%s expunged from folder \"%s\"",
long2string(ps_global->inbox_expunge_count),
plural(ps_global->inbox_expunge_count),
pretty_fn(ps_global->inbox_name));
ps_global->inbox_expunge_count = 0L;
display_message('x');
}
if(ps_global->mail_box_changed && ps_global->new_mail_count){
dprint(2, (debugfile, "Noticed %ld new msgs! \n",
ps_global->new_mail_count));
return(NO_OP_COMMAND); /* cycle thru so caller can update */
}
ch = read_char(tm);
dprint(9, (debugfile, "Read command returning: %d %s\n", ch,
pretty_command(ch)));
if(ch != NO_OP_COMMAND && ch != NO_OP_IDLE && ch != KEY_RESIZE)
zero_new_mail_count();
#ifdef BACKGROUND_POST
/*
* Any expired children to report on?
*/
if(ps_global->post && ps_global->post->pid == 0){
int winner = 0;
if(ps_global->post->status < 0){
q_status_message(SM_ORDER | SM_DING, 3, 3, "Abysmal failure!");
}
else{
(void) pine_send_status(ps_global->post->status,
ps_global->post->fcc, tmp_20k_buf,
&winner);
q_status_message(SM_ORDER | (winner ? 0 : SM_DING), 3, 3,
tmp_20k_buf);
}
if(!winner)
q_status_message(SM_ORDER, 0, 3,
"Re-send via \"Compose\" then \"Yes\" to \"Continue INTERRUPTED?\"");
if(ps_global->post->fcc)
fs_give((void **) &ps_global->post->fcc);
fs_give((void **) &ps_global->post);
}
#endif
return(ch);
}
/*
*
*/
static struct display_line {
int row, col; /* where display starts */
int dlen; /* length of display line */
char *dl; /* line on display */
char *vl; /* virtual line */
int vlen; /* length of virtual line */
int vused; /* length of virtual line in use */
int vbase; /* first virtual char on display */
} dline;
static struct key oe_keys[] =
{{"^G","Help",KS_SCREENHELP}, {"^C","Cancel",KS_NONE},
{"^T","xxx",KS_NONE}, {"Ret","Accept",KS_NONE},
{NULL,NULL,KS_NONE}, {NULL,NULL,KS_NONE},
{NULL,NULL,KS_NONE}, {NULL,NULL,KS_NONE},
{NULL,NULL,KS_NONE}, {NULL,NULL,KS_NONE},
{NULL,NULL,KS_NONE}, {NULL,NULL,KS_NONE}};
INST_KEY_MENU(oe_keymenu, oe_keys);
#define OE_HELP_KEY 0
#define OE_CANCEL_KEY 1
#define OE_CTRL_T_KEY 2
#define OE_ENTER_KEY 3
/*----------------------------------------------------------------------
Prompt user for a string in status line with various options
Args: string -- the buffer result is returned in, and original string (if
any) is passed in.
y_base -- y position on screen to start on. 0,0 is upper left
negative numbers start from bottom
x_base -- column position on screen to start on. 0,0 is upper left
field_len -- Maximum length of string to accept
prompt -- The string to prompt with
escape_list -- pointer to array of ESCKEY_S's. input chars matching
those in list return value from list.
help -- Arrary of strings for help text in bottom screen lines
flags -- pointer (because some are return values) to flags
OE_USER_MODIFIED - Set on return if user modified buffer
OE_DISALLOW_CANCEL - No cancel in menu.
OE_DISALLOW_HELP - No help in menu.
OE_KEEP_TRAILING_SPACE - Allow trailing space.
OE_SEQ_SENSITIVE - Caller is sensitive to sequence
number changes.
OE_APPEND_CURRENT - String should not be truncated
before accepting user input.
OE_PASSWD - Don't echo on screen.
Result: editing input string
returns -1 unexpected errors
returns 0 normal entry typed (editing and return or PF2)
returns 1 typed ^C or PF2 (cancel)
returns 3 typed ^G or PF1 (help)
returns 4 typed ^L for a screen redraw
WARNING: Care is required with regard to the escape_list processing.
The passed array is terminated with an entry that has ch = -1.
Function key labels and key strokes need to be setup externally!
Traditionally, a return value of 2 is used for ^T escapes.
Unless in escape_list, tabs are trapped by isprint().
This allows near full weemacs style editing in the line
^A beginning of line
^E End of line
^R Redraw line
^G Help
^F forward
^B backward
^D delete
----------------------------------------------------------------------*/
optionally_enter(string, y_base, x_base, field_len,
prompt, escape_list, help, flags)
char *string, *prompt;
ESCKEY_S *escape_list;
HelpType help;
int x_base, y_base, field_len;
int *flags;
{
register char *s2;
register int field_pos;
int i, j, return_v, cols, ch, prompt_len, too_thin,
real_y_base, km_popped, passwd;
char *saved_original = NULL, *k, *kb;
char *kill_buffer = NULL;
char **help_text;
int fkey_table[12];
struct key_menu *km;
bitmap_t bitmap;
COLOR_PAIR *lastc = NULL, *promptc = NULL;
struct variable *vars = ps_global->vars;
#ifdef _WINDOWS
int cursor_shown;
#endif
dprint(5, (debugfile, "=== optionally_enter called ===\n"));
dprint(9, (debugfile, "string:\"%s\" y:%d x:%d length: %d append: %d\n",
string, x_base, y_base, field_len,
(flags && *flags & OE_APPEND_CURRENT)));
dprint(9, (debugfile, "passwd:%d prompt:\"%s\" label:\"%s\"\n",
(flags && *flags & OE_PASSWD),
prompt, (escape_list && escape_list[0].ch != -1)
? escape_list[0].label: ""));
#ifdef _WINDOWS
if (mswin_usedialog ()) {
MDlgButton button_list[12];
int b;
int i;
memset (&button_list, 0, sizeof (MDlgButton) * 12);
b = 0;
for (i = 0; escape_list && escape_list[i].ch != -1 && i < 11; ++i) {
if (escape_list[i].name != NULL
&& escape_list[i].ch > 0 && escape_list[i].ch < 256) {
button_list[b].ch = escape_list[i].ch;
button_list[b].rval = escape_list[i].rval;
button_list[b].name = escape_list[i].name;
button_list[b].label = escape_list[i].label;
++b;
}
}
button_list[b].ch = -1;
help_text = get_help_text (help);
return_v = mswin_dialog (prompt, string, field_len,
(flags && *flags & OE_APPEND_CURRENT),
(flags && *flags & OE_PASSWD),
button_list,
help_text, flags ? *flags : OE_NONE);
free_list_array (&help_text);
return (return_v);
}
#endif
suspend_busy_alarm();
cols = ps_global->ttyo->screen_cols;
prompt_len = strlen(prompt);
too_thin = 0;
km_popped = 0;
if(y_base > 0) {
real_y_base = y_base;
} else {
real_y_base= y_base + ps_global->ttyo->screen_rows;
if(real_y_base < 2)
real_y_base = ps_global->ttyo->screen_rows;
}
flush_ordered_messages();
mark_status_dirty();
if(flags && *flags & OE_APPEND_CURRENT) /* save a copy in case of cancel */
saved_original = cpystr(string);
/*
* build the function key mapping table, skipping predefined keys...
*/
memset(fkey_table, NO_OP_COMMAND, 12 * sizeof(int));
for(i = 0, j = 0; escape_list && escape_list[i].ch != -1 && i+j < 12; i++){
if(i+j == OE_HELP_KEY)
j++;
if(i+j == OE_CANCEL_KEY)
j++;
if(i+j == OE_ENTER_KEY)
j++;
fkey_table[i+j] = escape_list[i].ch;
}
#if defined(HELPFILE)
help_text = (help != NO_HELP) ? get_help_text(help) : (char **)NULL;
#else
help_text = help;
#endif
if(help_text){ /*---- Show help text -----*/
int width = ps_global->ttyo->screen_cols - x_base;
if(FOOTER_ROWS(ps_global) == 1){
km_popped++;
FOOTER_ROWS(ps_global) = 3;
clearfooter(ps_global);
y_base = -3;
real_y_base = y_base + ps_global->ttyo->screen_rows;
}
for(j = 0; j < 2 && help_text[j]; j++){
MoveCursor(real_y_base + 1 + j, x_base);
CleartoEOLN();
if(width < strlen(help_text[j])){
char *tmp = fs_get((width + 1) * sizeof(char));
strncpy(tmp, help_text[j], width);
tmp[width] = '\0';
PutLine0(real_y_base + 1 + j, x_base, tmp);
fs_give((void **)&tmp);
}
else
PutLine0(real_y_base + 1 + j, x_base, help_text[j]);
}
#if defined(HELPFILE)
free_list_array(&help_text);
#endif
} else {
clrbitmap(bitmap);
clrbitmap((km = &oe_keymenu)->bitmap); /* force formatting */
if(!(flags && (*flags) & OE_DISALLOW_HELP))
setbitn(OE_HELP_KEY, bitmap);
setbitn(OE_ENTER_KEY, bitmap);
if(!(flags && (*flags) & OE_DISALLOW_CANCEL))
setbitn(OE_CANCEL_KEY, bitmap);
setbitn(OE_CTRL_T_KEY, bitmap);
/*---- Show the usual possible keys ----*/
for(i=0,j=0; escape_list && escape_list[i].ch != -1 && i+j < 12; i++){
if(i+j == OE_HELP_KEY)
j++;
if(i+j == OE_CANCEL_KEY)
j++;
if(i+j == OE_ENTER_KEY)
j++;
oe_keymenu.keys[i+j].label = escape_list[i].label;
oe_keymenu.keys[i+j].name = escape_list[i].name;
setbitn(i+j, bitmap);
}
for(i = i+j; i < 12; i++)
if(!(i == OE_HELP_KEY || i == OE_ENTER_KEY || i == OE_CANCEL_KEY))
oe_keymenu.keys[i].name = NULL;
draw_keymenu(km, bitmap, cols, 1-FOOTER_ROWS(ps_global), 0, FirstMenu);
}
if(pico_usingcolor() && VAR_PROMPT_FORE_COLOR &&
VAR_PROMPT_BACK_COLOR &&
pico_is_good_color(VAR_PROMPT_FORE_COLOR) &&
pico_is_good_color(VAR_PROMPT_BACK_COLOR)){
lastc = pico_get_cur_color();
if(lastc){
promptc = new_color_pair(VAR_PROMPT_FORE_COLOR,
VAR_PROMPT_BACK_COLOR);
(void)pico_set_colorp(promptc, PSC_NONE);
}
}
else
StartInverse();
/*
* if display length isn't wide enough to support input,
* shorten up the prompt...
*/
if((dline.dlen = cols - (x_base + prompt_len + 1)) < 5){
prompt_len += (dline.dlen - 5); /* adding negative numbers */
prompt -= (dline.dlen - 5); /* subtracting negative numbers */
dline.dlen = 5;
}
dline.dl = fs_get((size_t)dline.dlen + 1);
memset((void *)dline.dl, 0, (size_t)(dline.dlen + 1) * sizeof(char));
dline.row = real_y_base;
dline.col = x_base + prompt_len;
dline.vl = string;
dline.vlen = --field_len; /* -1 for terminating NULL */
dline.vbase = field_pos = 0;
#ifdef _WINDOWS
cursor_shown = mswin_showcaret(1);
#endif
PutLine0(real_y_base, x_base, prompt);
/* make sure passed in string is shorter than field_len */
/* and adjust field_pos.. */
while((flags && *flags & OE_APPEND_CURRENT) &&
field_pos < field_len && string[field_pos] != '\0')
field_pos++;
string[field_pos] = '\0';
dline.vused = (int)(&string[field_pos] - string);
passwd = (flags && *flags & OE_PASSWD) ? 1 : 0;
line_paint(field_pos, &passwd);
/*----------------------------------------------------------------------
The main loop
here field_pos is the position in the string.
s always points to where we are in the string.
loops until someone sets the return_v.
----------------------------------------------------------------------*/
return_v = -10;
while(return_v == -10) {
#ifdef MOUSE
mouse_in_content(KEY_MOUSE, -1, -1, 0x5, 0);
register_mfunc(mouse_in_content,
real_y_base, x_base + prompt_len,
real_y_base, ps_global->ttyo->screen_cols);
#endif
#ifdef _WINDOWS
mswin_allowpaste(MSWIN_PASTE_LINE);
g_mc_row = real_y_base;
g_mc_col = x_base + prompt_len;
mswin_mousetrackcallback(pcpine_oe_cursor);
#endif
/* Timeout 10 min to keep imap mail stream alive */
ch = read_char(600);
#ifdef MOUSE
clear_mfunc(mouse_in_content);
#endif
#ifdef _WINDOWS
mswin_allowpaste(MSWIN_PASTE_DISABLE);
mswin_mousetrackcallback(NULL);
#endif
/*
* Don't want to intercept all characters if typing in passwd.
* We select an ad hoc set that we will catch and let the rest
* through. We would have caught the set below in the big switch
* but we skip the switch instead. Still catch things like ^K,
* DELETE, ^C, RETURN.
*/
if(passwd)
switch(ch) {
case ctrl('F'):
case KEY_RIGHT:
case ctrl('B'):
case KEY_LEFT:
case ctrl('U'):
case ctrl('A'):
case KEY_HOME:
case ctrl('E'):
case KEY_END:
case TAB:
goto ok_for_passwd;
}
if(too_thin && ch != KEY_RESIZE && ch != ctrl('Z') && ch != ctrl('C'))
goto bleep;
switch(ch) {
/*--------------- KEY RIGHT ---------------*/
case ctrl('F'):
case KEY_RIGHT:
if(field_pos >= field_len || string[field_pos] == '\0')
goto bleep;
line_paint(++field_pos, &passwd);
break;
/*--------------- KEY LEFT ---------------*/
case ctrl('B'):
case KEY_LEFT:
if(field_pos <= 0)
goto bleep;
line_paint(--field_pos, &passwd);
break;
/*-------------------- WORD SKIP --------------------*/
case ctrl('@'):
/*
* Note: read_char *can* return NO_OP_COMMAND which is
* the def'd with the same value as ^@ (NULL), BUT since
* read_char has a big timeout (>25 secs) it won't.
*/
/* skip thru current word */
while(string[field_pos]
&& isalnum((unsigned char) string[field_pos]))
field_pos++;
/* skip thru current white space to next word */
while(string[field_pos]
&& !isalnum((unsigned char) string[field_pos]))
field_pos++;
line_paint(field_pos, &passwd);
break;
/*-------------------- RETURN --------------------*/
case PF4:
if(F_OFF(F_USE_FK,ps_global)) goto bleep;
case ctrl('J'):
case ctrl('M'):
return_v = 0;
break;
/*-------------------- Destructive backspace --------------------*/
case '\177': /* DEL */
case ctrl('H'):
/* Try and do this with by telling the terminal to delete a
a character. If that fails, then repaint the rest of the
line, acheiving the same much less efficiently
*/
if(field_pos <= 0)
goto bleep;
field_pos--;
/* drop thru to pull line back ... */
/*-------------------- Delete char --------------------*/
case ctrl('D'):
case KEY_DEL:
if(field_pos >= field_len || !string[field_pos])
goto bleep;
dline.vused--;
for(s2 = &string[field_pos]; *s2 != '\0'; s2++)
*s2 = s2[1];
*s2 = '\0'; /* Copy last NULL */
line_paint(field_pos, &passwd);
if(flags) /* record change if requested */
*flags |= OE_USER_MODIFIED;
break;
/*--------------- Kill line -----------------*/
case ctrl('K'):
if(kill_buffer != NULL)
fs_give((void **)&kill_buffer);
if(field_pos != 0 || string[0]){
if(!passwd && F_ON(F_DEL_FROM_DOT, ps_global))
dline.vused -= strlen(&string[i = field_pos]);
else
dline.vused = i = 0;
kill_buffer = cpystr(&string[field_pos = i]);
string[field_pos] = '\0';
line_paint(field_pos, &passwd);
if(flags) /* record change if requested */
*flags |= OE_USER_MODIFIED;
}
break;
/*------------------- Undelete line --------------------*/
case ctrl('U'):
if(kill_buffer == NULL)
goto bleep;
/* Make string so it will fit */
kb = cpystr(kill_buffer);
dprint(2, (debugfile,
"Undelete: %d %d\n", strlen(string), field_len));
if(strlen(kb) + strlen(string) > field_len)
kb[field_len - strlen(string)] = '\0';
dprint(2, (debugfile,
"Undelete: %d %d\n", field_len - strlen(string),
strlen(kb)));
if(string[field_pos] == '\0') {
/*--- adding to the end of the string ----*/
for(k = kb; *k; k++)
string[field_pos++] = *k;
string[field_pos] = '\0';
} else {
goto bleep;
/* To lazy to do insert in middle of string now */
}
if(*kb && flags) /* record change if requested */
*flags |= OE_USER_MODIFIED;
dline.vused = strlen(string);
fs_give((void **)&kb);
line_paint(field_pos, &passwd);
break;
/*-------------------- Interrupt --------------------*/
case ctrl('C'): /* ^C */
if(F_ON(F_USE_FK,ps_global)
|| (flags && ((*flags) & OE_DISALLOW_CANCEL)))
goto bleep;
goto cancel;
case PF2:
if(F_OFF(F_USE_FK,ps_global)
|| (flags && ((*flags) & OE_DISALLOW_CANCEL)))
goto bleep;
cancel:
return_v = 1;
if(saved_original)
strcpy(string, saved_original);
break;
case ctrl('A'):
case KEY_HOME:
/*-------------------- Start of line -------------*/
line_paint(field_pos = 0, &passwd);
break;
case ctrl('E'):
case KEY_END:
/*-------------------- End of line ---------------*/
line_paint(field_pos = dline.vused, &passwd);
break;
/*-------------------- Help --------------------*/
case ctrl('G') :
case PF1:
if(flags && ((*flags) & OE_DISALLOW_HELP))
goto bleep;
else if(FOOTER_ROWS(ps_global) == 1 && km_popped == 0){
km_popped++;
FOOTER_ROWS(ps_global) = 3;
clearfooter(ps_global);
if(lastc)
(void)pico_set_colorp(lastc, PSC_NONE);
else
EndInverse();
draw_keymenu(km, bitmap, cols, 1-FOOTER_ROWS(ps_global),
0, FirstMenu);
if(promptc)
(void)pico_set_colorp(promptc, PSC_NONE);
else
StartInverse();
mark_keymenu_dirty();
y_base = -3;
dline.row = real_y_base = y_base + ps_global->ttyo->screen_rows;
PutLine0(real_y_base, x_base, prompt);
fs_resize((void **)&dline.dl, (size_t)dline.dlen + 1);
memset((void *)dline.dl, 0, (size_t)(dline.dlen + 1));
line_paint(field_pos, &passwd);
break;
}
if(FOOTER_ROWS(ps_global) > 1){
mark_keymenu_dirty();
return_v = 3;
}
else
goto bleep;
break;
#ifdef MOUSE
case KEY_MOUSE :
{
MOUSEPRESS mp;
mouse_get_last (NULL, &mp);
/* The clicked line have anything special on it? */
switch(mp.button){
case M_BUTTON_LEFT : /* position cursor */
mp.col -= x_base + prompt_len; /* normalize column */
if(dline.vbase + mp.col <= dline.vused)
line_paint(field_pos = dline.vbase + mp.col, &passwd);
break;
case M_BUTTON_RIGHT :
#ifdef _WINDOWS
mp.col -= x_base + prompt_len; /* normalize column */
if(dline.vbase + mp.col <= dline.vused)
line_paint(field_pos = dline.vbase + mp.col, &passwd);
mswin_allowpaste(MSWIN_PASTE_LINE);
mswin_paste_popup();
mswin_allowpaste(MSWIN_PASTE_DISABLE);
break;
#endif
case M_BUTTON_MIDDLE : /* NO-OP for now */
default: /* just ignore */
break;
}
}
break;
#endif
case NO_OP_IDLE:
/* Keep mail stream alive */
i = new_mail(0, 2, NM_DEFER_SORT);
if(ps_global->expunge_count &&
flags && ((*flags) & OE_SEQ_SENSITIVE))
goto cancel;
if(i < 0){
line_paint(field_pos, &passwd);
break; /* no changes, get on with life */
}
/* Else fall into redraw */
/*-------------------- Redraw --------------------*/
case ctrl('L'):
/*---------------- re size ----------------*/
case KEY_RESIZE:
dline.row = real_y_base = y_base > 0 ? y_base :
y_base + ps_global->ttyo->screen_rows;
if(lastc)
(void)pico_set_colorp(lastc, PSC_NONE);
else
EndInverse();
ClearScreen();
redraw_titlebar();
if(ps_global->redrawer != (void (*)())NULL)
(*ps_global->redrawer)();
redraw_keymenu();
if(promptc)
(void)pico_set_colorp(promptc, PSC_NONE);
else
StartInverse();
PutLine0(real_y_base, x_base, prompt);
cols = ps_global->ttyo->screen_cols;
too_thin = 0;
if(cols < x_base + prompt_len + 4) {
Writechar(BELL, 0);
PutLine0(real_y_base, 0, "Screen's too thin. Ouch!");
too_thin = 1;
} else {
dline.col = x_base + prompt_len;
dline.dlen = cols - (x_base + prompt_len + 1);
fs_resize((void **)&dline.dl, (size_t)dline.dlen + 1);
memset((void *)dline.dl, 0, (size_t)(dline.dlen + 1));
line_paint(field_pos, &passwd);
}
fflush(stdout);
dprint(9, (debugfile,
"optionally_enter RESIZE new_cols:%d too_thin: %d\n",
cols, too_thin));
break;
case PF3 : /* input to potentially remap */
case PF5 :
case PF6 :
case PF7 :
case PF8 :
case PF9 :
case PF10 :
case PF11 :
case PF12 :
if(F_ON(F_USE_FK,ps_global)
&& fkey_table[ch - PF1] != NO_OP_COMMAND)
ch = fkey_table[ch - PF1]; /* remap function key input */
default:
if(escape_list){ /* in the escape key list? */
for(j=0; escape_list[j].ch != -1; j++){
if(escape_list[j].ch == ch){
return_v = escape_list[j].rval;
break;
}
}
if(return_v != -10)
break;
}
if(iscntrl(ch & 0x7f)){
bleep:
putc(BELL, stdout);
continue;
}
ok_for_passwd:
/*--- Insert a character -----*/
if(dline.vused >= field_len)
goto bleep;
/*---- extending the length of the string ---*/
for(s2 = &string[++dline.vused]; s2 - string > field_pos; s2--)
*s2 = *(s2-1);
string[field_pos++] = ch;
line_paint(field_pos, &passwd);
if(flags) /* record change if requested */
*flags |= OE_USER_MODIFIED;
} /*---- End of switch on char ----*/
}
#ifdef _WINDOWS
if(!cursor_shown)
mswin_showcaret(0);
#endif
fs_give((void **)&dline.dl);
if(saved_original)
fs_give((void **)&saved_original);
if(kill_buffer)
fs_give((void **)&kill_buffer);
if (!(flags && (*flags) & OE_KEEP_TRAILING_SPACE))
removing_trailing_white_space(string);
if(lastc){
(void)pico_set_colorp(lastc, PSC_NONE);
free_color_pair(&lastc);
if(promptc)
free_color_pair(&promptc);
}
else
EndInverse();
MoveCursor(real_y_base, x_base); /* Move the cursor to show we're done */
fflush(stdout);
resume_busy_alarm(0);
if(km_popped){
FOOTER_ROWS(ps_global) = 1;
clearfooter(ps_global);
ps_global->mangled_body = 1;
}
return(return_v);
}
/*
* line_paint - where the real work of managing what is displayed gets done.
* The passwd variable is overloaded: if non-zero, don't
* output anything, else only blat blank chars across line
* once and use this var to tell us we've already written the
* line.
*/
void
line_paint(offset, passwd)
int offset; /* current dot offset into line */
int *passwd; /* flag to hide display of chars */
{
register char *pfp, *pbp;
register char *vfp, *vbp;
int extra = 0;
#define DLEN (dline.vbase + dline.dlen)
/*
* for now just leave line blank, but maybe do '*' for each char later
*/
if(*passwd){
if(*passwd > 1)
return;
else
*passwd = 2; /* only blat once */
extra = 0;
MoveCursor(dline.row, dline.col);
while(extra++ < dline.dlen)
Writechar(' ', 0);
MoveCursor(dline.row, dline.col);
return;
}
/* adjust right margin */
while(offset >= DLEN + ((dline.vused > DLEN) ? -1 : 1))
dline.vbase += dline.dlen/2;
/* adjust left margin */
while(offset < dline.vbase + ((dline.vbase) ? 2 : 0))
dline.vbase = max(dline.vbase - (dline.dlen/2), 0);
if(dline.vbase){ /* off screen cue left */
vfp = &dline.vl[dline.vbase+1];
pfp = &dline.dl[1];
if(dline.dl[0] != '<'){
MoveCursor(dline.row, dline.col);
Writechar(dline.dl[0] = '<', 0);
}
}
else{
vfp = dline.vl;
pfp = dline.dl;
if(dline.dl[0] == '<'){
MoveCursor(dline.row, dline.col);
Writechar(dline.dl[0] = ' ', 0);
}
}
if(dline.vused > DLEN){ /* off screen right... */
vbp = vfp + (long)(dline.dlen-(dline.vbase ? 2 : 1));
pbp = pfp + (long)(dline.dlen-(dline.vbase ? 2 : 1));
if(pbp[1] != '>'){
MoveCursor(dline.row, dline.col+dline.dlen);
Writechar(pbp[1] = '>', 0);
}
}
else{
extra = dline.dlen - (dline.vused - dline.vbase);
vbp = &dline.vl[max(0, dline.vused-1)];
pbp = &dline.dl[dline.dlen];
if(pbp[0] == '>'){
MoveCursor(dline.row, dline.col+dline.dlen);
Writechar(pbp[0] = ' ', 0);
}
}
while(*pfp == *vfp && vfp < vbp) /* skip like chars */
pfp++, vfp++;
if(pfp == pbp && *pfp == *vfp){ /* nothing to paint! */
MoveCursor(dline.row, dline.col + (offset - dline.vbase));
return;
}
/* move backward thru like characters */
if(extra){
while(extra >= 0 && *pbp == ' ') /* back over spaces */
extra--, pbp--;
while(extra >= 0) /* paint new ones */
pbp[-(extra--)] = ' ';
}
if((vbp - vfp) == (pbp - pfp)){ /* space there? */
while((*pbp == *vbp) && pbp != pfp) /* skip like chars */
pbp--, vbp--;
}
if(pfp != pbp || *pfp != *vfp){ /* anything to paint?*/
MoveCursor(dline.row, dline.col + (int)(pfp - dline.dl));
do
Writechar((unsigned char)((vfp <= vbp && *vfp)
? ((*pfp = *vfp++) == TAB) ? ' ' : *pfp
: (*pfp = ' ')), 0);
while(++pfp <= pbp);
}
MoveCursor(dline.row, dline.col + (offset - dline.vbase));
}
/*----------------------------------------------------------------------
Check to see if the given command is reasonably valid
Args: ch -- the character to check
Result: A valid command is returned, or a well know bad command is returned.
---*/
validatekeys(ch)
int ch;
{
#ifndef _WINDOWS
if(F_ON(F_USE_FK,ps_global)) {
if(ch >= 'a' && ch <= 'z')
return(KEY_JUNK);
} else {
if(ch >= PF1 && ch <= PF12)
return(KEY_JUNK);
}
#else
/*
* In windows menu items are bound to a single key command which
* gets inserted into the input stream as if the user had typed
* that key. But all the menues are bonund to alphakey commands,
* not PFkeys. to distinguish between a keyboard command and a
* menu command we insert a flag (KEY_MENU_FLAG) into the
* command value when setting up the bindings in
* configure_menu_items(). Here we strip that flag.
*/
if(F_ON(F_USE_FK,ps_global)) {
if(ch >= 'a' && ch <= 'z' && !(ch & KEY_MENU_FLAG))
return(KEY_JUNK);
ch &= ~ KEY_MENU_FLAG;
} else {
ch &= ~ KEY_MENU_FLAG;
if(ch >= PF1 && ch <= PF12)
return(KEY_JUNK);
}
#endif
return(ch);
}
/*----------------------------------------------------------------------
Prepend config'd commands to keyboard input
Args: ch -- pointer to storage for returned command
Returns: TRUE if we're passing back a useful command, FALSE otherwise
---*/
int
process_config_input(ch)
int *ch;
{
static char firsttime = (char) 1;
/* commands in config file */
if(ps_global->initial_cmds && *ps_global->initial_cmds) {
/*
* There are a few commands that may require keyboard input before
* we enter the main command loop. That input should be interactive,
* not from our list of initial keystrokes.
*/
if(ps_global->dont_use_init_cmds)
return(0);
*ch = *ps_global->initial_cmds++;
if(!*ps_global->initial_cmds && ps_global->free_initial_cmds){
fs_give((void **)&(ps_global->free_initial_cmds));
ps_global->initial_cmds = 0;
}
return(1);
}
if(firsttime) {
firsttime = 0;
if(ps_global->in_init_seq) {
ps_global->in_init_seq = 0;
ps_global->save_in_init_seq = 0;
clear_cursor_pos();
F_SET(F_USE_FK,ps_global,ps_global->orig_use_fkeys);
/* draw screen */
*ch = ctrl('L');
return(1);
}
}
return(0);
}
#define TAPELEN 256
static int tape[TAPELEN];
static long recorded = 0L;
static short length = 0;
/*
* record user keystrokes
*
* Args: ch -- the character to record
*
* Returns: character recorded
*/
int
key_recorder(ch)
int ch;
{
tape[recorded++ % TAPELEN] = ch;
if(length < TAPELEN)
length++;
return(ch);
}
/*
* playback user keystrokes
*
* Args: ch -- ignored
*
* Returns: character played back or -1 to indicate end of tape
*/
int
key_playback(ch)
int ch;
{
ch = length ? tape[(recorded + TAPELEN - length--) % TAPELEN] : -1;
return(ch);
}
#ifdef _WINDOWS
int
pcpine_oe_cursor(col, row)
int col;
long row;
{
return((row == g_mc_row
&& col >= g_mc_col
&& col < ps_global->ttyo->screen_cols)
? MSWIN_CURSOR_IBEAM
: MSWIN_CURSOR_ARROW);
}
#endif
/*======================================================================
Routines for painting the screen
- figure out what the terminal type is
- deal with screen size changes
- save special output sequences
- the usual screen clearing, cursor addressing and scrolling
This library gives programs the ability to easily access the
termcap information and write screen oriented and raw input
programs. The routines can be called as needed, except that
to use the cursor / screen routines there must be a call to
InitScreen() first. The 'Raw' input routine can be used
independently, however. (Elm comment)
Not sure what the original source of this code was. It got to be
here as part of ELM. It has been changed significantly from the
ELM version to be more robust in the face of inconsistent terminal
autowrap behaviour. Also, the unused functions were removed, it was
made to pay attention to the window size, and some code was made nicer
(in my opinion anyways). It also outputs the terminal initialization
strings and provides for minimal scrolling and detects terminals
with out enough capabilities. (Pine comment, 1990)
This code used to pay attention to the "am" auto margin and "xn"
new line glitch fields, but they were so often incorrect because many
terminals can be configured to do either that we've taken it out. It
now assumes it dosn't know where the cursor is after outputing in the
80th column.
*/
#define PUTLINE_BUFLEN 256
static int _lines, _columns;
static int _line = FARAWAY;
static int _col = FARAWAY;
static int _in_inverse;
/*
* Internal prototypes
*/
static void moveabsolute PROTO((int, int));
static void CursorUp PROTO((int));
static void CursorDown PROTO((int));
static void CursorLeft PROTO((int));
static void CursorRight PROTO((int));
extern char *_clearscreen, *_moveto, *_up, *_down, *_right, *_left,
*_setinverse, *_clearinverse,
*_cleartoeoln, *_cleartoeos,
*_startinsert, *_endinsert, *_insertchar, *_deletechar,
*_deleteline, *_insertline,
*_scrollregion, *_scrollup, *_scrolldown,
*_termcap_init, *_termcap_end;
extern char term_name[];
extern int _tlines, _tcolumns, _bce;
static enum {NoScroll,UseScrollRegion,InsertDelete} _scrollmode;
char *tgoto(); /* and the goto stuff */
/*----------------------------------------------------------------------
Initialize the screen for output, set terminal type, etc
Args: tt -- Pointer to variable to store the tty output structure.
Result: terminal size is discovered and set in pine state
termcap entry is fetched and stored
make sure terminal has adequate capabilites
evaluate scrolling situation
returns status of indicating the state of the screen/termcap entry
Returns:
-1 indicating no terminal name associated with this shell,
-2..-n No termcap for this terminal type known
-3 Can't open termcap file
-4 Terminal not powerful enough - missing clear to eoln or screen
or cursor motion
----*/
int
config_screen(tt)
struct ttyo **tt;
{
struct ttyo *ttyo;
int err;
ttyo = (struct ttyo *)fs_get(sizeof (struct ttyo));
_line = 0; /* where are we right now?? */
_col = 0; /* assume zero, zero... */
/*
* This is an ugly hack to let vtterminalinfo know it's being called
* from pine.
*/
Pmaster = (PICO *)1;
if(err = vtterminalinfo(F_ON(F_TCAP_WINS, ps_global)))
return(err);
Pmaster = NULL;
if(_tlines <= 0)
_lines = DEFAULT_LINES_ON_TERMINAL;
else
_lines = _tlines;
if(_tcolumns <= 0)
_columns = DEFAULT_COLUMNS_ON_TERMINAL;
else
_columns = _tcolumns;
get_windsize(ttyo);
ttyo->header_rows = 2;
ttyo->footer_rows = 3;
/*---- Make sure this terminal has the capability.
All we need is cursor address, clear line, and
reverse video.
---*/
if(_moveto == NULL || _cleartoeoln == NULL ||
_setinverse == NULL || _clearinverse == NULL) {
return(-4);
}
dprint(1, (debugfile, "Terminal type: %s\n", term_name));
/*------ Figure out scrolling mode -----*/
if(_scrollregion != NULL && _scrollregion[0] != '\0' &&
_scrollup != NULL && _scrollup[0] != '\0'){
_scrollmode = UseScrollRegion;
} else if(_insertline != NULL && _insertline[0] != '\0' &&
_deleteline != NULL && _deleteline[0] != '\0') {
_scrollmode = InsertDelete;
} else {
_scrollmode = NoScroll;
}
dprint(7, (debugfile, "Scroll mode: %s\n",
_scrollmode==NoScroll ? "No Scroll" :
_scrollmode==InsertDelete ? "InsertDelete" : "Scroll Regions"));
if (!_left) {
_left = "\b";
}
*tt = ttyo;
return(0);
}
/*----------------------------------------------------------------------
Initialize the screen with the termcap string
----*/
void
init_screen()
{
if(_termcap_init) /* init using termcap's rule */
tputs(_termcap_init, 1, outchar);
/* and make sure there are no scrolling surprises! */
BeginScroll(0, ps_global->ttyo->screen_rows - 1);
pico_toggle_color(0);
switch(ps_global->color_style){
case COL_NONE:
case COL_TERMDEF:
pico_set_color_options(0);
break;
case COL_ANSI8:
pico_set_color_options(COLOR_ANSI8_OPT);
break;
case COL_ANSI16:
pico_set_color_options(COLOR_ANSI16_OPT);
break;
}
if(ps_global->color_style != COL_NONE)
pico_toggle_color(1);
/* set colors */
if(pico_usingcolor()){
if(ps_global->VAR_NORM_FORE_COLOR)
pico_nfcolor(ps_global->VAR_NORM_FORE_COLOR);
if(ps_global->VAR_NORM_BACK_COLOR)
pico_nbcolor(ps_global->VAR_NORM_BACK_COLOR);
if(ps_global->VAR_REV_FORE_COLOR)
pico_rfcolor(ps_global->VAR_REV_FORE_COLOR);
if(ps_global->VAR_REV_BACK_COLOR)
pico_rbcolor(ps_global->VAR_REV_BACK_COLOR);
pico_set_normal_color();
}
/* and make sure icon text starts out consistent */
icon_text(NULL);
fflush(stdout);
}
/*----------------------------------------------------------------------
Get the current window size
Args: ttyo -- pointer to structure to store window size in
NOTE: we don't override the given values unless we know better
----*/
int
get_windsize(ttyo)
struct ttyo *ttyo;
{
#ifdef RESIZING
struct winsize win;
/*
* Get the window size from the tty driver. If we can't fish it from
* stdout (pine's output is directed someplace else), try stdin (which
* *must* be associated with the terminal; see init_tty_driver)...
*/
if(ioctl(1, TIOCGWINSZ, &win) >= 0 /* 1 is stdout */
|| ioctl(0, TIOCGWINSZ, &win) >= 0){ /* 0 is stdin */
if(win.ws_row)
_lines = min(win.ws_row, MAX_SCREEN_ROWS);
if(win.ws_col)
_columns = min(win.ws_col, MAX_SCREEN_COLS);
dprint(2, (debugfile, "new win size -----<%d %d>------\n",
_lines, _columns));
}
else
/* Depending on the OS, the ioctl() may have failed because
of a 0 rows, 0 columns setting. That happens on DYNIX/ptx 1.3
(with a kernel patch that happens to involve the negotiation
of window size in the telnet streams module.) In this case
the error is EINVARG. Leave the default settings. */
dprint(1, (debugfile, "ioctl(TIOCWINSZ) failed :%s\n",
error_description(errno)));
#endif
ttyo->screen_cols = min(_columns, MAX_SCREEN_COLS);
ttyo->screen_rows = min(_lines, MAX_SCREEN_ROWS);
return(0);
}
/*----------------------------------------------------------------------
End use of the screen.
Print status message, if any.
Flush status messages.
----*/
void
end_screen(message)
char *message;
{
int footer_rows_was_one = 0;
dprint(9, (debugfile, "end_screen called\n"));
if(FOOTER_ROWS(ps_global) == 1){
footer_rows_was_one++;
FOOTER_ROWS(ps_global) = 3;
mark_status_unknown();
}
flush_status_messages(1);
blank_keymenu(_lines - 2, 0);
MoveCursor(_lines - 2, 0);
/* unset colors */
if(pico_hascolor())
pico_endcolor();
if(_termcap_end != NULL)
tputs(_termcap_end, 1, outchar);
if(message){
printf("%s\r\n", message);
}
if(F_ON(F_ENABLE_XTERM_NEWMAIL, ps_global) && getenv("DISPLAY"))
icon_text("xterm");
fflush(stdout);
if(footer_rows_was_one){
FOOTER_ROWS(ps_global) = 1;
mark_status_unknown();
}
}
/*----------------------------------------------------------------------
Clear the terminal screen
Result: The screen is cleared
internal cursor position set to 0,0
----*/
void
ClearScreen()
{
_line = 0; /* clear leaves us at top... */
_col = 0;
if(ps_global->in_init_seq)
return;
mark_status_unknown();
mark_keymenu_dirty();
mark_titlebar_dirty();
/*
* If the terminal doesn't have back color erase, then we have to
* erase manually to preserve the background color.
*/
if(pico_usingcolor() && (!_bce || !_clearscreen)){
ClearLines(0, _lines-1);
MoveCursor(0, 0);
}
else if(_clearscreen){
tputs(_clearscreen, 1, outchar);
moveabsolute(0, 0); /* some clearscreens don't move correctly */
}
}
/*----------------------------------------------------------------------
Internal move cursor to absolute position
Args: col -- column to move cursor to
row -- row to move cursor to
Result: cursor is moved (variables, not updates)
----*/
static void
moveabsolute(col, row)
{
char *stuff, *tgoto();
stuff = tgoto(_moveto, col, row);
tputs(stuff, 1, outchar);
}
/*----------------------------------------------------------------------
Move the cursor to the row and column number
Args: row number
column number
Result: Cursor moves
internal position updated
----*/
void
MoveCursor(row, col)
int row, col;
{
/** move cursor to the specified row column on the screen.
0,0 is the top left! **/
int scrollafter = 0;
/* we don't want to change "rows" or we'll mangle scrolling... */
if(ps_global->in_init_seq)
return;
if (col < 0)
col = 0;
if (col >= ps_global->ttyo->screen_cols)
col = ps_global->ttyo->screen_cols - 1;
if (row < 0)
row = 0;
if (row > ps_global->ttyo->screen_rows) {
if (col == 0)
scrollafter = row - ps_global->ttyo->screen_rows;
row = ps_global->ttyo->screen_rows;
}
if (!_moveto)
return;
if (row == _line) {
if (col == _col)
return; /* already there! */
else if (abs(col - _col) < 5) { /* within 5 spaces... */
if (col > _col && _right)
CursorRight(col - _col);
else if (col < _col && _left)
CursorLeft(_col - col);
else
moveabsolute(col, row);
}
else /* move along to the new x,y loc */
moveabsolute(col, row);
}
else if (col == _col && abs(row - _line) < 5) {
if (row < _line && _up)
CursorUp(_line - row);
else if (_line > row && _down)
CursorDown(row - _line);
else
moveabsolute(col, row);
}
else if (_line == row-1 && col == 0) {
putchar('\n'); /* that's */
putchar('\r'); /* easy! */
}
else
moveabsolute(col, row);
_line = row; /* to ensure we're really there... */
_col = col;
if (scrollafter) {
while (scrollafter--) {
putchar('\n');
putchar('\r');
}
}
return;
}
/*----------------------------------------------------------------------
Newline, move the cursor to the start of next line
Result: Cursor moves
----*/
void
NewLine()
{
/** move the cursor to the beginning of the next line **/
Writechar('\n', 0);
Writechar('\r', 0);
}
/*----------------------------------------------------------------------
Move cursor up n lines with terminal escape sequence
Args: n -- number of lines to go up
Result: cursor moves,
internal position updated
Only for ttyout use; not outside callers
----*/
static void
CursorUp(n)
int n;
{
/** move the cursor up 'n' lines **/
/** Calling function must check that _up is not null before calling **/
_line = (_line-n > 0? _line - n: 0); /* up 'n' lines... */
while (n-- > 0)
tputs(_up, 1, outchar);
}
/*----------------------------------------------------------------------
Move cursor down n lines with terminal escape sequence
Arg: n -- number of lines to go down
Result: cursor moves,
internal position updated
Only for ttyout use; not outside callers
----*/
static void
CursorDown(n)
int n;
{
/** move the cursor down 'n' lines **/
/** Caller must check that _down is not null before calling **/
_line = (_line+n < ps_global->ttyo->screen_rows ? _line + n
: ps_global->ttyo->screen_rows);
/* down 'n' lines... */
while (n-- > 0)
tputs(_down, 1, outchar);
}
/*----------------------------------------------------------------------
Move cursor left n lines with terminal escape sequence
Args: n -- number of lines to go left
Result: cursor moves,
internal position updated
Only for ttyout use; not outside callers
----*/
static void
CursorLeft(n)
int n;
{
/** move the cursor 'n' characters to the left **/
/** Caller must check that _left is not null before calling **/
_col = (_col - n> 0? _col - n: 0); /* left 'n' chars... */
while (n-- > 0)
tputs(_left, 1, outchar);
}
/*----------------------------------------------------------------------
Move cursor right n lines with terminal escape sequence
Args: number of lines to go right
Result: cursor moves,
internal position updated
Only for ttyout use; not outside callers
----*/
static void
CursorRight(n)
int n;
{
/** move the cursor 'n' characters to the right (nondestructive) **/
/** Caller must check that _right is not null before calling **/
_col = (_col+n < ps_global->ttyo->screen_cols? _col + n :
ps_global->ttyo->screen_cols); /* right 'n' chars... */
while (n-- > 0)
tputs(_right, 1, outchar);
}
/*----------------------------------------------------------------------
Insert character on screen pushing others right
Args: c -- character to insert
Result: charcter is inserted if possible
return -1 if it can't be done
----------------------------------------------------------------------*/
InsertChar(c)
int c;
{
if(_insertchar != NULL && *_insertchar != '\0') {
tputs(_insertchar, 1, outchar);
Writechar(c, 0);
} else if(_startinsert != NULL && *_startinsert != '\0') {
tputs(_startinsert, 1, outchar);
Writechar(c, 0);
tputs(_endinsert, 1, outchar);
} else {
return(-1);
}
return(0);
}
/*----------------------------------------------------------------------
Delete n characters from line, sliding rest of line left
Args: n -- number of characters to delete
Result: characters deleted on screen
returns -1 if it wasn't done
----------------------------------------------------------------------*/
DeleteChar(n)
int n;
{
if(_deletechar == NULL || *_deletechar == '\0')
return(-1);
while(n) {
tputs(_deletechar, 1, outchar);
n--;
}
return(0);
}
/*----------------------------------------------------------------------
Go into scrolling mode, that is set scrolling region if applicable
Args: top -- top line of region to scroll
bottom -- bottom line of region to scroll
(These are zero-origin numbers)
Result: either set scrolling region or
save values for later scrolling
returns -1 if we can't scroll
Unfortunately this seems to leave the cursor in an unpredictable place
at least the manuals don't say where, so we force it here.
-----*/
static int __t, __b;
BeginScroll(top, bottom)
int top, bottom;
{
char *stuff;
if(_scrollmode == NoScroll)
return(-1);
__t = top;
__b = bottom;
if(_scrollmode == UseScrollRegion){
stuff = tgoto(_scrollregion, bottom, top);
tputs(stuff, 1, outchar);
/*-- a location very far away to force a cursor address --*/
_line = FARAWAY;
_col = FARAWAY;
}
return(0);
}
/*----------------------------------------------------------------------
End scrolling -- clear scrolling regions if necessary
Result: Clear scrolling region on terminal
-----*/
void
EndScroll()
{
if(_scrollmode == UseScrollRegion && _scrollregion != NULL){
/* Use tgoto even though we're not cursor addressing because
the format of the capability is the same.
*/
char *stuff = tgoto(_scrollregion, ps_global->ttyo->screen_rows -1, 0);
tputs(stuff, 1, outchar);
/*-- a location very far away to force a cursor address --*/
_line = FARAWAY;
_col = FARAWAY;
}
}
/* ----------------------------------------------------------------------
Scroll the screen using insert/delete or scrolling regions
Args: lines -- number of lines to scroll, positive forward
Result: Screen scrolls
returns 0 if scroll succesful, -1 if not
positive lines goes foward (new lines come in at bottom
Leaves cursor at the place to insert put new text
0,0 is the upper left
-----*/
ScrollRegion(lines)
int lines;
{
int l;
if(lines == 0)
return(0);
if(_scrollmode == UseScrollRegion) {
if(lines > 0) {
MoveCursor(__b, 0);
for(l = lines ; l > 0 ; l--)
tputs((_scrolldown == NULL || _scrolldown[0] =='\0') ? "\n" :
_scrolldown, 1, outchar);
} else {
MoveCursor(__t, 0);
for(l = -lines; l > 0; l--)
tputs(_scrollup, 1, outchar);
}
} else if(_scrollmode == InsertDelete) {
if(lines > 0) {
MoveCursor(__t, 0);
for(l = lines; l > 0; l--)
tputs(_deleteline, 1, outchar);
MoveCursor(__b, 0);
for(l = lines; l > 0; l--)
tputs(_insertline, 1, outchar);
} else {
for(l = -lines; l > 0; l--) {
MoveCursor(__b, 0);
tputs(_deleteline, 1, outchar);
MoveCursor(__t, 0);
tputs(_insertline, 1, outchar);
}
}
} else {
return(-1);
}
fflush(stdout);
return(0);
}
/*----------------------------------------------------------------------
Write a character to the screen, keeping track of cursor position
Args: ch -- character to output
Result: character output
cursor position variables updated
----*/
void
Writechar(ch, new_esc_len)
register unsigned int ch;
int new_esc_len;
{
static int esc_len = 0;
if(ps_global->in_init_seq /* silent */
|| (F_ON(F_BLANK_KEYMENU, ps_global) /* or bottom, */
&& !esc_len /* right cell */
&& _line + 1 == ps_global->ttyo->screen_rows
&& _col + 1 == ps_global->ttyo->screen_cols))
return;
if(!iscntrl(ch & 0x7f)){
putchar(ch);
if(esc_len > 0)
esc_len--;
else
_col++;
}
else{
switch(ch){
case LINE_FEED:
/*-- Don't have to watch out for auto wrap or newline glitch
because we never let it happen. See below
---*/
putchar('\n');
_line = min(_line+1,ps_global->ttyo->screen_rows);
esc_len = 0;
break;
case RETURN : /* move to column 0 */
putchar('\r');
_col = 0;
esc_len = 0;
break;
case BACKSPACE : /* move back a space if not in column 0 */
if(_col != 0) {
putchar('\b');
_col--;
} /* else BACKSPACE does nothing */
break;
case BELL : /* ring the bell but don't advance _col */
putchar(ch);
break;
case TAB : /* if a tab, output it */
do /* BUG? ignores tty driver's spacing */
putchar(' ');
while(_col < ps_global->ttyo->screen_cols - 1
&& ((++_col)&0x07) != 0);
break;
case ESCAPE :
/* If we're outputting an escape here, it may be part of an iso2022
escape sequence in which case take up no space on the screen.
Unfortunately such sequences are variable in length.
*/
esc_len = new_esc_len - 1;
putchar(ch);
break;
default : /* Change remaining control characters to ? */
if(F_ON(F_PASS_CONTROL_CHARS, ps_global))
putchar(ch);
else
putchar('?');
if(esc_len > 0)
esc_len--;
else
_col++;
break;
}
}
/* Here we are at the end of the line. We've decided to make no
assumptions about how the terminal behaves at this point.
What can happen now are the following
1. Cursor is at start of next line, and next character will
apear there. (autowrap, !newline glitch)
2. Cursor is at start of next line, and if a newline is output
it'll be ignored. (autowrap, newline glitch)
3. Cursor is still at end of line and next char will apear
there over the top of what is there now (no autowrap).
We ignore all this and force the cursor to the next line, just
like case 1. A little expensive but worth it to avoid problems
with terminals configured so they don't match termcap
*/
if(_col == ps_global->ttyo->screen_cols) {
_col = 0;
if(_line + 1 < ps_global->ttyo->screen_rows)
_line++;
moveabsolute(_col, _line);
}
}
/*----------------------------------------------------------------------
Write string to screen at current cursor position
Args: string -- string to be output
Result: String written to the screen
----*/
void
Write_to_screen(string) /* UNIX */
register char *string;
{
while(*string)
Writechar((unsigned char) *string++, 0);
}
/*----------------------------------------------------------------------
Write no more than n chars of string to screen at current cursor position
Args: string -- string to be output
n -- number of chars to output
Result: String written to the screen
----*/
void
Write_to_screen_n(string, n) /* UNIX */
register char *string;
int n;
{
while(n-- && *string)
Writechar((unsigned char) *string++, 0);
}
/*----------------------------------------------------------------------
Clear screen to end of line on current line
Result: Line is cleared
----*/
void
CleartoEOLN()
{
int c, starting_col, starting_line;
char *last_bg_color;
/*
* If the terminal doesn't have back color erase, then we have to
* erase manually to preserve the background color.
*/
if(pico_usingcolor() && (!_bce || !_cleartoeoln)){
starting_col = _col;
starting_line = _line;
last_bg_color = pico_get_last_bg_color();
pico_set_nbg_color();
for(c = _col; c < _columns; c++)
Writechar(' ', 0);
MoveCursor(starting_line, starting_col);
if(last_bg_color){
(void)pico_set_bg_color(last_bg_color);
fs_give((void **)&last_bg_color);
}
}
else if(_cleartoeoln)
tputs(_cleartoeoln, 1, outchar);
}
/*----------------------------------------------------------------------
Clear screen to end of screen from current point
Result: screen is cleared
----*/
CleartoEOS()
{
int starting_col, starting_line;
/*
* If the terminal doesn't have back color erase, then we have to
* erase manually to preserve the background color.
*/
if(pico_usingcolor() && (!_bce || !_cleartoeos)){
starting_col = _col;
starting_line = _line;
CleartoEOLN();
ClearLines(_line+1, _lines-1);
MoveCursor(starting_line, starting_col);
}
else if(_cleartoeos)
tputs(_cleartoeos, 1, outchar);
}
/*----------------------------------------------------------------------
function to output character used by termcap
Args: c -- character to output
Result: character output to screen via stdio
----*/
void
outchar(c)
int c;
{
/** output the given character. From tputs... **/
/** Note: this CANNOT be a macro! **/
putc((unsigned char)c, stdout);
}
/*----------------------------------------------------------------------
function to output string such that it becomes icon text
Args: s -- string to write
Result: string indicated become our "icon" text
----*/
void
icon_text(s)
char *s;
{
static char *old_s;
static enum {ukn, yes, no} xterm;
if(xterm == ukn)
xterm = (getenv("DISPLAY") != NULL) ? yes : no;
if(F_ON(F_ENABLE_XTERM_NEWMAIL,ps_global) && xterm == yes && (s || old_s)){
fputs("\033]1;", stdout);
fputs((old_s = s) ? s : ps_global->pine_name, stdout);
fputs("\007", stdout);
fflush(stdout);
}
}
#ifdef _WINDOWS
#line 3 "osdep/termout.gen"
#endif
/*
* Generic tty output routines...
*/
/*----------------------------------------------------------------------
Printf style output line to the screen at given position, 0 args
Args: x -- column position on the screen
y -- row position on the screen
line -- line of text to output
Result: text is output
cursor position is update
----*/
void
PutLine0(x, y, line)
int x,y;
register char *line;
{
MoveCursor(x,y);
Write_to_screen(line);
}
/*----------------------------------------------------------------------
Output line of length len to the display observing embedded attributes
Args: x -- column position on the screen
y -- column position on the screen
line -- text to be output
length -- length of text to be output
Result: text is output
cursor position is updated
----------------------------------------------------------------------*/
void
PutLine0n8b(x, y, line, length, handles)
int x, y, length;
register char *line;
HANDLE_S *handles;
{
unsigned char c;
#ifdef _WINDOWS
int hkey = 0;
#endif
MoveCursor(x,y);
while(length-- && (c = (unsigned char)*line++)){
if(c == (unsigned char)TAG_EMBED && length){
length--;
switch(*line++){
case TAG_INVON :
StartInverse();
break;
case TAG_INVOFF :
EndInverse();
break;
case TAG_BOLDON :
StartBold();
break;
case TAG_BOLDOFF :
EndBold();
break;
case TAG_ULINEON :
StartUnderline();
break;
case TAG_ULINEOFF :
EndUnderline();
break;
case TAG_HANDLE :
length -= *line + 1; /* key length plus length tag */
if(handles){
int key, n;
for(key = 0, n = *line++; n; n--) /* forget Horner? */
key = (key * 10) + (*line++ - '0');
#if _WINDOWS
hkey = key;
#endif
if(key == handles->key){
if(pico_usingcolor() &&
ps_global->VAR_SLCTBL_FORE_COLOR &&
ps_global->VAR_SLCTBL_BACK_COLOR){
pico_set_normal_color();
}
else
EndBold();
StartInverse();
}
}
else{
/* BUG: complain? */
line += *line + 1;
}
break;
case TAG_FGCOLOR :
if(length < RGBLEN){
Writechar(TAG_EMBED, 0);
Writechar(*(line-1), 0);
break;
}
(void)pico_set_fg_color(line);
length -= RGBLEN;
line += RGBLEN;
break;
case TAG_BGCOLOR :
if(length < RGBLEN){
Writechar(TAG_EMBED, 0);
Writechar(*(line-1), 0);
break;
}
(void)pico_set_bg_color(line);
length -= RGBLEN;
line += RGBLEN;
break;
default : /* literal "embed" char? */
Writechar(TAG_EMBED, 0);
Writechar(*(line-1), 0);
break;
} /* tag with handle, skip it */
}
else if(c == '\033') /* check for iso-2022 escape */
Writechar(c, match_escapes(line));
else
Writechar(c, 0);
}
#if _WINDOWS_X
if(hkey) {
char *tmp_file = NULL, ext[32], mtype[128];
HANDLE_S *h;
extern HANDLE_S *get_handle (HANDLE_S *, int);
if((h = get_handle(handles, hkey)) && h->type == Attach){
ext[0] = '\0';
strcpy(mtype, body_type_names(h->h.attach->body->type));
if (h->h.attach->body->subtype) {
strcat (mtype, "/");
strcat (mtype, h->h.attach->body->subtype);
}
if(!set_mime_extension_by_type(ext, mtype)){
char *namep, *dotp, *p;
if(namep = rfc2231_get_param(h->h.attach->body->parameter,
"name", NULL, NULL)){
for(dotp = NULL, p = namep; *p; p++)
if(*p == '.')
dotp = p + 1;
if(dotp && strlen(dotp) < sizeof(ext) - 1)
strcpy(ext, dotp);
fs_give((void **) &namep);
}
}
if(ext[0] && (tmp_file = temp_nam_ext(NULL, "im", ext))){
FILE *f = fopen(tmp_file, "w");
mswin_registericon(x, h->key, tmp_file);
fclose(f);
unlink(tmp_file);
fs_give((void **)&tmp_file);
}
}
}
#endif
}
/*----------------------------------------------------------------------
Printf style output line to the screen at given position, 1 arg
Input: position on the screen
line of text to output
Result: text is output
cursor position is update
----------------------------------------------------------------------*/
void
/*VARARGS2*/
PutLine1(x, y, line, arg1)
int x, y;
char *line;
void *arg1;
{
char buffer[PUTLINE_BUFLEN];
sprintf(buffer, line, arg1);
PutLine0(x, y, buffer);
}
/*----------------------------------------------------------------------
Printf style output line to the screen at given position, 2 args
Input: position on the screen
line of text to output
Result: text is output
cursor position is update
----------------------------------------------------------------------*/
void
/*VARARGS3*/
PutLine2(x, y, line, arg1, arg2)
int x, y;
char *line;
void *arg1, *arg2;
{
char buffer[PUTLINE_BUFLEN];
sprintf(buffer, line, arg1, arg2);
PutLine0(x, y, buffer);
}
/*----------------------------------------------------------------------
Printf style output line to the screen at given position, 3 args
Input: position on the screen
line of text to output
Result: text is output
cursor position is update
----------------------------------------------------------------------*/
void
/*VARARGS4*/
PutLine3(x, y, line, arg1, arg2, arg3)
int x, y;
char *line;
void *arg1, *arg2, *arg3;
{
char buffer[PUTLINE_BUFLEN];
sprintf(buffer, line, arg1, arg2, arg3);
PutLine0(x, y, buffer);
}
/*----------------------------------------------------------------------
Printf style output line to the screen at given position, 4 args
Args: x -- column position on the screen
y -- column position on the screen
line -- printf style line of text to output
Result: text is output
cursor position is update
----------------------------------------------------------------------*/
void
/*VARARGS5*/
PutLine4(x, y, line, arg1, arg2, arg3, arg4)
int x, y;
char *line;
void *arg1, *arg2, *arg3, *arg4;
{
char buffer[PUTLINE_BUFLEN];
sprintf(buffer, line, arg1, arg2, arg3, arg4);
PutLine0(x, y, buffer);
}
/*----------------------------------------------------------------------
Printf style output line to the screen at given position, 5 args
Args: x -- column position on the screen
y -- column position on the screen
line -- printf style line of text to output
Result: text is output
cursor position is update
----------------------------------------------------------------------*/
void
/*VARARGS6*/
PutLine5(x, y, line, arg1, arg2, arg3, arg4, arg5)
int x, y;
char *line;
void *arg1, *arg2, *arg3, *arg4, *arg5;
{
char buffer[PUTLINE_BUFLEN];
sprintf(buffer, line, arg1, arg2, arg3, arg4, arg5);
PutLine0(x, y, buffer);
}
/*----------------------------------------------------------------------
Output a line to the screen, centered
Input: Line number to print on, string to output
Result: String is output to screen
Returns column number line is output on
----------------------------------------------------------------------*/
int
Centerline(line, string)
int line;
char *string;
{
register int length, col;
length = strlen(string);
if (length > ps_global->ttyo->screen_cols)
col = 0;
else
col = (ps_global->ttyo->screen_cols - length) / 2;
PutLine0(line, col, string);
return(col);
}
/*----------------------------------------------------------------------
Clear specified line on the screen
Result: The line is blanked and the cursor is left at column 0.
----*/
void
ClearLine(n)
int n;
{
if(ps_global->in_init_seq)
return;
MoveCursor(n, 0);
CleartoEOLN();
}
/*----------------------------------------------------------------------
Clear specified lines on the screen
Result: The lines starting at 'x' and ending at 'y' are blanked
and the cursor is left at row 'x', column 0
----*/
void
ClearLines(x, y)
int x, y;
{
int i;
for(i = x; i <= y; i++)
ClearLine(i);
MoveCursor(x, 0);
}
/*----------------------------------------------------------------------
Indicate to the screen painting here that the position of the cursor
has been disturbed and isn't where these functions might think.
----*/
void
clear_cursor_pos()
{
_line = FARAWAY;
_col = FARAWAY;
}
|