File: serial.c

package info (click to toggle)
uucp 1.07-24
  • links: PTS
  • area: main
  • in suites: buster
  • size: 6,772 kB
  • ctags: 3,911
  • sloc: ansic: 53,864; sh: 4,480; perl: 199; makefile: 199
file content (3611 lines) | stat: -rw-r--r-- 88,906 bytes parent folder | download | duplicates (3)
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
/* serial.c
   The serial port communication routines for Unix.

   Copyright (C) 1991, 1992, 1993, 1994, 1995, 2002 Ian Lance Taylor

   This file is part of the Taylor UUCP package.

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.

   The author of the program may be contacted at ian@airs.com.
   */

#include "uucp.h"

#if USE_RCS_ID
const char serial_rcsid[] = "$Id: serial.c,v 1.78 2002/03/05 19:10:42 ian Rel $";
#endif

#include "uudefs.h"
#include "uuconf.h"
#include "system.h"
#include "conn.h"
#include "sysdep.h"

#include <errno.h>
#include <ctype.h>

#if HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif

#if HAVE_LIMITS_H
#include <limits.h>
#endif

#if HAVE_TLI
#if HAVE_TIUSER_H
#include <tiuser.h>
#else /* ! HAVE_TIUSER_H */
#if HAVE_XTI_H
#include <xti.h>
#endif /* HAVE_XTI_H */
#endif /* ! HAVE_TIUSER_H */
#endif /* HAVE_TLI */

#if HAVE_FCNTL_H
#include <fcntl.h>
#else
#if HAVE_SYS_FILE_H
#include <sys/file.h>
#endif
#endif

#ifndef O_RDONLY
#define O_RDONLY 0
#define O_WRONLY 1
#define O_RDWR 2
#endif

#ifndef O_NOCTTY
#define O_NOCTTY 0
#endif

#ifndef FD_CLOEXEC
#define FD_CLOEXEC 1
#endif

#if HAVE_SYS_IOCTL_H || HAVE_TXADDCD
#include <sys/ioctl.h>
#endif

#if HAVE_SELECT
#if HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#if HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#endif

#if HAVE_TIME_H
#if ! HAVE_SYS_TIME_H || ! HAVE_SELECT || TIME_WITH_SYS_TIME
#include <time.h>
#endif
#endif

#if HAVE_STRIP_BUG && HAVE_BSD_TTY
#include <termio.h>
#endif

#if HAVE_SVR4_LOCKFILES
/* Get the right definitions for major and minor.  */
#if MAJOR_IN_MKDEV
#include <sys/mkdev.h>
#endif /* MAJOR_IN_MKDEV */
#if MAJOR_IN_SYSMACROS
#include <sys/sysmacros.h>
#endif /* MAJOR_IN_SYSMACROS */
#if ! MAJOR_IN_MKDEV && ! MAJOR_IN_SYSMACROS
#ifndef major
#define major(i) (((i) >> 8) & 0xff)
#endif
#ifndef minor
#define minor(i) ((i) & 0xff)
#endif
#endif /* ! MAJOR_IN_MKDEV && ! MAJOR_IN_SYSMACROS */
#endif /* HAVE_SVR4_LOCKFILES */

#if HAVE_DEV_INFO
#include <sys/dev.h>
#endif

#if HAVE_SYS_TERMIOX_H
#include <sys/termiox.h>
#endif

/* Get definitions for both O_NONBLOCK and O_NDELAY.  */
#ifndef O_NDELAY
#ifdef FNDELAY
#define O_NDELAY FNDELAY
#else /* ! defined (FNDELAY) */
#define O_NDELAY 0
#endif /* ! defined (FNDELAY) */
#endif /* ! defined (O_NDELAY) */

#ifndef O_NONBLOCK
#ifdef FNBLOCK
#define O_NONBLOCK FNBLOCK
#else /* ! defined (FNBLOCK) */
#define O_NONBLOCK 0
#endif /* ! defined (FNBLOCK) */
#endif /* ! defined (O_NONBLOCK) */

#if O_NDELAY == 0 && O_NONBLOCK == 0
 #error No way to do nonblocking I/O
#endif

/* Get definitions for EAGAIN, EWOULDBLOCK and ENODATA.  */
#ifndef EAGAIN
#ifndef EWOULDBLOCK
#define EAGAIN (-1)
#define EWOULDBLOCK (-1)
#else /* defined (EWOULDBLOCK) */
#define EAGAIN EWOULDBLOCK
#endif /* defined (EWOULDBLOCK) */
#else /* defined (EAGAIN) */
#ifndef EWOULDBLOCK
#define EWOULDBLOCK EAGAIN
#endif /* ! defined (EWOULDBLOCK) */
#endif /* defined (EAGAIN) */

#ifndef ENODATA
#define ENODATA EAGAIN
#endif

/* Make sure we have a definition for MAX_INPUT.  */
#ifndef MAX_INPUT
#define MAX_INPUT (256)
#endif

/* If we have the TIOCSINUSE ioctl call, we use it to lock a terminal.
   Otherwise, if we have the TIOCEXCL ioctl call, we have to open the
   terminal before we know that it is unlocked.  */
#ifdef TIOCSINUSE
#define HAVE_TIOCSINUSE 1
#else
#ifdef TIOCEXCL
#define HAVE_TIOCEXCL 1
#endif
#endif

#if HAVE_TLI
extern int t_errno;
extern char *t_errlist[];
extern int t_nerr;
#endif

/* Determine bits to clear for the various terminal control fields for
   HAVE_SYSV_TERMIO and HAVE_POSIX_TERMIOS.  */

/* These fields are defined on some systems, and I am told that it
   does not hurt to clear them, and it sometimes helps.  */
#ifndef IMAXBEL
#define IMAXBEL 0
#endif

#ifndef PENDIN
#define PENDIN 0
#endif

#if HAVE_SYSV_TERMIO
#define ICLEAR_IFLAG (IGNBRK | BRKINT | IGNPAR | PARMRK | INPCK \
		      | ISTRIP | INLCR | IGNCR | ICRNL | IUCLC \
		      | IXON | IXANY | IXOFF | IMAXBEL)
#define ICLEAR_OFLAG (OPOST | OLCUC | ONLCR | OCRNL | ONOCR | ONLRET \
		      | OFILL | OFDEL | NLDLY | CRDLY | TABDLY | BSDLY \
		      | VTDLY | FFDLY)
#define ICLEAR_CFLAG (CBAUD | CSIZE | PARENB | PARODD)
#define ISET_CFLAG (CS8 | CREAD | HUPCL)
#define ICLEAR_LFLAG (ISIG | ICANON | XCASE | ECHO | ECHOE | ECHOK \
		      | ECHONL | NOFLSH | PENDIN)
#endif
#if HAVE_POSIX_TERMIOS
#define ICLEAR_IFLAG (BRKINT | ICRNL | IGNBRK | IGNCR | IGNPAR \
		      | INLCR | INPCK | ISTRIP | IXOFF | IXON \
		      | PARMRK | IMAXBEL)
#define ICLEAR_OFLAG (OPOST)
#define ICLEAR_CFLAG (CSIZE | PARENB | PARODD)
#define ISET_CFLAG (CS8 | CREAD | HUPCL)
#define ICLEAR_LFLAG (ECHO | ECHOE | ECHOK | ECHONL | ICANON | IEXTEN \
		      | ISIG | NOFLSH | TOSTOP | PENDIN)
#endif

enum tclocal_setting
{
  SET_CLOCAL,
  CLEAR_CLOCAL,
  IGNORE_CLOCAL
};

/* Local functions.  */

static RETSIGTYPE usalarm P((int isig));
static boolean fsserial_init P((struct sconnection *qconn,
				const struct sconncmds *qcmds,
				const char *zdevice));
static void usserial_free P((struct sconnection *qconn));
static boolean fsserial_lockfile P((boolean flok,
				    const struct sconnection *));
static boolean fsserial_lock P((struct sconnection *qconn,
				boolean fin, boolean fuser));
static boolean fsserial_unlock P((struct sconnection *qconn));
static boolean fsserial_open P((struct sconnection *qconn, long ibaud,
				boolean fwait, boolean fuser,
				enum tclocal_setting tlocal));
static boolean fsstdin_open P((struct sconnection *qconn, long ibaud,
			       boolean fwait, boolean fuser, boolean nortscts));
static boolean fsmodem_open P((struct sconnection *qconn, long ibaud,
			       boolean fwait, boolean fuser, boolean nortscts));
static boolean fsdirect_open P((struct sconnection *qconn, long ibaud,
				boolean fwait, boolean fuser, boolean nortscts));
static boolean fsblock P((struct ssysdep_conn *q, boolean fblock));
static boolean fsserial_close P((struct ssysdep_conn *q));
static boolean fsstdin_close P((struct sconnection *qconn,
				pointer puuconf,
				struct uuconf_dialer *qdialer,
				boolean fsuccess));
static boolean fsmodem_close P((struct sconnection *qconn,
				pointer puuconf,
				struct uuconf_dialer *qdialer,
				boolean fsuccess));
static boolean fsdirect_close P((struct sconnection *qconn,
				 pointer puuconf,
				 struct uuconf_dialer *qdialer,
				 boolean fsuccess));
static boolean fsserial_break P((struct sconnection *qconn));
static boolean fsstdin_break P((struct sconnection *qconn));
static boolean fsserial_set P((struct sconnection *qconn,
			       enum tparitysetting tparity,
			       enum tstripsetting tstrip,
			       enum txonxoffsetting txonxoff));
static boolean fsstdin_set P((struct sconnection *qconn,
			       enum tparitysetting tparity,
			       enum tstripsetting tstrip,
			       enum txonxoffsetting txonxoff));
static boolean fsmodem_carrier P((struct sconnection *qconn,
				  boolean fcarrier));
static boolean fsserial_hardflow P((struct sconnection *qconn,
				    boolean fhardflow));
static boolean fsrun_chat P((int oread, int owrite, char **pzprog));
static long isserial_baud P((struct sconnection *qconn));

/* The command table for standard input ports.  */

static const struct sconncmds sstdincmds =
{
  usserial_free,
  NULL, /* pflock */
  NULL, /* pfunlock */
  fsstdin_open,
  fsstdin_close,
  NULL, /* pfdial */
  fsdouble_read,
  fsdouble_write,
  fsysdep_conn_io,
  fsstdin_break,
  fsstdin_set,
  NULL, /* pfcarrier */
  fsdouble_chat,
  isserial_baud
};

/* The command table for modem ports.  */

static const struct sconncmds smodemcmds =
{
  usserial_free,
  fsserial_lock,
  fsserial_unlock,
  fsmodem_open,
  fsmodem_close,
  fmodem_dial,
  fsysdep_conn_read,
  fsysdep_conn_write,
  fsysdep_conn_io,
  fsserial_break,
  fsserial_set,
  fsmodem_carrier,
  fsysdep_conn_chat,
  isserial_baud
};

/* The command table for direct ports.  */

static const struct sconncmds sdirectcmds =
{
  usserial_free,
  fsserial_lock,
  fsserial_unlock,
  fsdirect_open,
  fsdirect_close,
  NULL, /* pfdial */
  fsysdep_conn_read,
  fsysdep_conn_write,
  fsysdep_conn_io,
  fsserial_break,
  fsserial_set,
  NULL, /* pfcarrier */
  fsysdep_conn_chat,
  isserial_baud
};

/* If the system will let us set both O_NDELAY and O_NONBLOCK, we do
   so.  This is because some ancient drivers on some systems appear to
   look for one but not the other.  Some other systems will give an
   EINVAL error if we attempt to set both, so we use a static global
   to hold the value we want to set.  If we get EINVAL, we change the
   global and try again (if some system gives an error other than
   EINVAL, the code will have to be modified).  */
static int iSunblock = O_NDELAY | O_NONBLOCK;

/* This code handles SIGALRM.  See the discussion above
   fsysdep_conn_read.  Normally we ignore SIGALRM, but the handler
   will temporarily be set to this function, which should set fSalarm
   and then either longjmp or schedule another SIGALRM.  fSalarm is
   never referred to outside of this file, but we don't make it static
   to try to fool compilers which don't understand volatile.  */

volatile sig_atomic_t fSalarm;

static RETSIGTYPE
usalarm (isig)
     int isig ATTRIBUTE_UNUSED;
{
#if ! HAVE_SIGACTION && ! HAVE_SIGVEC && ! HAVE_SIGSET
  (void) signal (isig, usalarm);
#endif

  fSalarm = TRUE;

#if HAVE_RESTARTABLE_SYSCALLS
  longjmp (sSjmp_buf, 1);
#else
  alarm (1);
#endif
}

/* We need a simple routine to block SIGINT, SIGQUIT, SIGTERM and
   SIGPIPE and another to restore the original state.  When these
   functions are called (in fsysdep_modem_close) SIGHUP is being
   ignored.  The routines are isblocksigs, which returns a value of
   type HELD_SIG_MASK and usunblocksigs which takes a single argument
   of type HELD_SIG_MASK.  */

#if HAVE_SIGPROCMASK

/* Use the POSIX sigprocmask call.  */

#define HELD_SIG_MASK sigset_t

static sigset_t isblocksigs P((void));

static sigset_t
isblocksigs ()
{
  sigset_t sblock, sold;

  /* These expressions need an extra set of parentheses to avoid a bug
     in SCO 3.2.2.  */
  (void) (sigemptyset (&sblock));
  (void) (sigaddset (&sblock, SIGINT));
  (void) (sigaddset (&sblock, SIGQUIT));
  (void) (sigaddset (&sblock, SIGTERM));
  (void) (sigaddset (&sblock, SIGPIPE));

  (void) sigprocmask (SIG_BLOCK, &sblock, &sold);
  return sold;
}

#define usunblocksigs(s) \
  ((void) sigprocmask (SIG_SETMASK, &(s), (sigset_t *) NULL))

#else /* ! HAVE_SIGPROCMASK */
#if HAVE_SIGBLOCK

/* Use the BSD sigblock and sigsetmask calls.  */

#define HELD_SIG_MASK int

#ifndef sigmask
#define sigmask(i) (1 << ((i) - 1))
#endif

#define isblocksigs() \
  sigblock (sigmask (SIGINT) | sigmask (SIGQUIT) \
	    | sigmask (SIGTERM) | sigmask (SIGPIPE))

#define usunblocksigs(i) ((void) sigsetmask (i))

#else /* ! HAVE_SIGBLOCK */

#if HAVE_SIGHOLD

/* Use the SVR3 sighold and sigrelse calls.  */

#define HELD_SIG_MASK int

static int isblocksigs P((void));

static int
isblocksigs ()
{
  sighold (SIGINT);
  sighold (SIGQUIT);
  sighold (SIGTERM);
  sighold (SIGPIPE);
  return 0;
}

static void usunblocksigs P((int));

/*ARGSUSED*/
static void
usunblocksigs (i)
     int i;
{
  sigrelse (SIGINT);
  sigrelse (SIGQUIT);
  sigrelse (SIGTERM);
  sigrelse (SIGPIPE);
}

#else /* ! HAVE_SIGHOLD */

/* We have no way to block signals.  This system will suffer from a
   race condition in fsysdep_modem_close.  */

#define HELD_SIG_MASK int

#define isblocksigs() 0

#define usunblocksigs(i)

#endif /* ! HAVE_SIGHOLD */
#endif /* ! HAVE_SIGBLOCK */
#endif /* ! HAVE_SIGPROCMASK */

/* Initialize a connection for use on a serial port.  */

static boolean
fsserial_init (qconn, qcmds, zdevice)
     struct sconnection *qconn;
     const struct sconncmds *qcmds;
     const char *zdevice;
{
  struct ssysdep_conn *q;

  q = (struct ssysdep_conn *) xmalloc (sizeof (struct ssysdep_conn));
  if (zdevice == NULL
      && qconn->qport != NULL
      && qconn->qport->uuconf_ttype != UUCONF_PORTTYPE_STDIN)
    zdevice = qconn->qport->uuconf_zname;
  if (zdevice == NULL)
    q->zdevice = NULL;
  else if (*zdevice == '/')
    q->zdevice = zbufcpy (zdevice);
  else
    {
      size_t clen;

      clen = strlen (zdevice);
      q->zdevice = zbufalc (sizeof "/dev/" + clen);
      memcpy (q->zdevice, "/dev/", sizeof "/dev/" - 1);
      memcpy (q->zdevice + sizeof "/dev/" - 1, zdevice, clen);
      q->zdevice[sizeof "/dev/" + clen - 1] = '\0';
    }
  q->o = -1;
  q->ord = -1;
  q->owr = -1;
  q->ftli = FALSE;
  qconn->psysdep = (pointer) q;
  qconn->qcmds = qcmds;
  return TRUE;
}

/* Initialize a connection for use on standard input.  */

boolean
fsysdep_stdin_init (qconn)
     struct sconnection *qconn;
{
  /* chmod /dev/tty to prevent other users from writing messages to
     it.  This is essentially `mesg n'.  */
  (void) chmod ("/dev/tty", S_IRUSR | S_IWUSR);
  return fsserial_init (qconn, &sstdincmds, (const char *) NULL);
}

/* Initialize a connection for use on a modem port.  */

boolean
fsysdep_modem_init (qconn)
     struct sconnection *qconn;
{
  return fsserial_init (qconn, &smodemcmds,
			qconn->qport->uuconf_u.uuconf_smodem.uuconf_zdevice);
}

/* Initialize a connection for use on a direct port.  */

boolean
fsysdep_direct_init (qconn)
     struct sconnection *qconn;
{
  return fsserial_init (qconn, &sdirectcmds,
			qconn->qport->uuconf_u.uuconf_sdirect.uuconf_zdevice);
}

/* Free up a serial port.  */

static void
usserial_free (qconn)
     struct sconnection *qconn;
{
  struct ssysdep_conn *qsysdep;

  qsysdep = (struct ssysdep_conn *) qconn->psysdep;
  ubuffree (qsysdep->zdevice);
  xfree ((pointer) qsysdep);
  qconn->psysdep = NULL;
}

#if HAVE_SEQUENT_LOCKFILES
#define LCK_TEMPLATE "LCK..tty"
#else
#define LCK_TEMPLATE "LCK.."
#endif

/* This routine is used for both locking and unlocking.  It is the
   only routine which knows how to translate a device name into the
   name of a lock file.  If it can't figure out a name, it does
   nothing and returns TRUE.  */

static boolean
fsserial_lockfile (flok, qconn)
     boolean flok;
     const struct sconnection *qconn;
{
  struct ssysdep_conn *qsysdep;
  const char *z;
  char *zalc;
  boolean fret;

  qsysdep = (struct ssysdep_conn *) qconn->psysdep;
  if (qconn->qport == NULL)
    z = NULL;
  else
    z = qconn->qport->uuconf_zlockname;
  zalc = NULL;
  if (z == NULL)
    {
#if HAVE_QNX_LOCKFILES
      {
	nid_t idevice_nid;
	char abdevice_nid[13]; /* length of long, a period, and a NUL */
	size_t cdevice_nid;
	const char *zbase;
	size_t clen;

        /* If the node ID is explicitly specified as part of the
           pathname to the device, use that.  Otherwise, presume the
           device is local to the current node. */
        if (qsysdep->zdevice[0] == '/' && qsysdep->zdevice[1] == '/')
          idevice_nid = (nid_t) strtol (qsysdep->zdevice + 2,
					(char **) NULL, 10);
        else
          idevice_nid = getnid ();

        sprintf (abdevice_nid, "%ld.", (long) idevice_nid);
        cdevice_nid = strlen (abdevice_nid);

 	zbase = strrchr (qsysdep->zdevice, '/') + 1;
 	clen = strlen (zbase);

        zalc = zbufalc (sizeof LCK_TEMPLATE + cdevice_nid + clen);

	memcpy (zalc, LCK_TEMPLATE, sizeof LCK_TEMPLATE - 1);
	memcpy (zalc + sizeof LCK_TEMPLATE - 1, abdevice_nid, cdevice_nid);
	memcpy (zalc + sizeof LCK_TEMPLATE - 1 + cdevice_nid,
		zbase, clen + 1);

	z = zalc;
      }
#else /* ! HAVE_QNX_LOCKFILES */
#if ! HAVE_SVR4_LOCKFILES
      {
	const char *zbase;
	size_t clen;

	zbase = strrchr (qsysdep->zdevice, '/') + 1;
	clen = strlen (zbase);
	zalc = zbufalc (sizeof LCK_TEMPLATE + clen);
	memcpy (zalc, LCK_TEMPLATE, sizeof LCK_TEMPLATE - 1);
	memcpy (zalc + sizeof LCK_TEMPLATE - 1, zbase, clen + 1);
#if HAVE_SCO_LOCKFILES
	{
	  char *zl;

	  zl = zalc + sizeof LCK_TEMPLATE + clen - 2;
	  if (isupper (*zl))
	    *zl = tolower (*zl);
	}
#endif
	z = zalc;
      }
#else /* HAVE_SVR4_LOCKFILES */
      {
	struct stat s;

	if (stat (qsysdep->zdevice, &s) != 0)
	  {
	    ulog (LOG_ERROR, "stat (%s): %s", qsysdep->zdevice,
		  strerror (errno));
	    return FALSE;
	  }
	zalc = zbufalc (sizeof "LK.1234567890.1234567890.1234567890");
	sprintf (zalc, "LK.%03d.%03d.%03d", major (s.st_dev),
		 major (s.st_rdev), minor (s.st_rdev));
	z = zalc;
      }
#endif /* HAVE_SVR4_LOCKFILES */
#endif /* ! HAVE_QNX_LOCKFILES */
    }

  if (flok)
    fret = fsdo_lock (z, FALSE, (boolean *) NULL);
  else
    fret = fsdo_unlock (z, FALSE);

#if HAVE_COHERENT_LOCKFILES
  if (fret)
    {
      if (flok)
	{
	  if (lockttyexist (z + sizeof LCK_TEMPLATE - 1))
	    {
	      ulog (LOG_NORMAL, "%s: port already locked",
		    z + sizeof LCK_TEMPLATE - 1);
	      fret = FALSE;
	    }
	  else
	    fret = fscoherent_disable_tty (z + sizeof LCK_TEMPLATE - 1,
					   &qsysdep->zenable);
	}
      else
	{
	  fret = TRUE;
	  if (qsysdep->zenable != NULL)
	    {
	      const char *azargs[3];
	      int aidescs[3];
	      pid_t ipid;

	      azargs[0] = "/etc/enable";
	      azargs[1] = qsysdep->zenable;
	      azargs[2] = NULL;
	      aidescs[0] = SPAWN_NULL;
	      aidescs[1] = SPAWN_NULL;
	      aidescs[2] = SPAWN_NULL;

	      ipid = ixsspawn (azargs, aidescs, TRUE, FALSE,
			       (const char *) NULL, TRUE, TRUE,
			       (const char *) NULL, (const char *) NULL,
			       (const char *) NULL);
	      if (ipid < 0)
		{
		  ulog (LOG_ERROR, "ixsspawn (/etc/enable %s): %s",
			qsysdep->zenable, strerror (errno));
		  fret = FALSE;
		}
	      else
		{
		  if (ixswait ((unsigned long) ipid, (const char *) NULL)
		      == 0)
		    fret = TRUE;
		  else
		    fret = FALSE;
		}
	      ubuffree (qsysdep->zenable);
	      qsysdep->zenable = NULL;
	    }
	}
    }
#endif /* HAVE_COHERENT_LOCKFILES */

  ubuffree (zalc);
  return fret;
}

/* If we can mark a modem line in use, then when we lock a port we
   must open it and mark it in use.  We can't wait until the actual
   open because we can't fail out if it is locked then.  */

static boolean
fsserial_lock (qconn, fin, fuser)
     struct sconnection *qconn;
     boolean fin;
     boolean fuser;
{
  if (! fsserial_lockfile (TRUE, qconn))
    return FALSE;

#if HAVE_TIOCSINUSE || HAVE_TIOCEXCL || HAVE_DEV_INFO
  /* Open the line and try to mark it in use.  */
  {
    struct ssysdep_conn *qsysdep;
    int iflag;
    uid_t ieuid;
    gid_t iegid;

    qsysdep = (struct ssysdep_conn *) qconn->psysdep;

    if (fin)
      iflag = 0;
    else
      iflag = iSunblock;

    if (fuser)
      {
	if (! fsuser_perms (&ieuid, &iegid))
	  {
	    (void) fsserial_lockfile (FALSE, qconn);
	    return FALSE;
	  }
      }

    qsysdep->o = open (qsysdep->zdevice, O_RDWR | iflag);
    if (qsysdep->o < 0)
      {
#if O_NONBLOCK != 0
	if (! fin && iSunblock != O_NONBLOCK && errno == EINVAL)
	  {
	    iSunblock = O_NONBLOCK;
	    qsysdep->o = open (qsysdep->zdevice,
			       O_RDWR | O_NONBLOCK);
	  }
#endif
	if (qsysdep->o < 0)
	  {
	    int ierr;

	    ierr = errno;
	    if (fuser)
	      (void) fsuucp_perms ((long) ieuid, (long) iegid);
	    if (ierr != EBUSY)
	      ulog (LOG_ERROR, "open (%s): %s", qsysdep->zdevice,
		    strerror (ierr));
	    (void) fsserial_lockfile (FALSE, qconn);
	    return FALSE;
	  }
      }

    if (fuser)
      {
	if (! fsuucp_perms ((long) ieuid, (long) iegid))
	  {
	    (void) close (qsysdep->o);
	    qsysdep->o = -1;
	    (void) fsserial_lockfile (FALSE, qconn);
	    return FALSE;
	  }
      }

#if HAVE_TIOCSINUSE
    /* If we can't mark it in use, return FALSE to indicate that the
       lock failed.  */
    if (ioctl (qsysdep->o, TIOCSINUSE, 0) < 0)
      {
	if (errno != EALREADY)
	  ulog (LOG_ERROR, "ioctl (TIOCSINUSE): %s", strerror (errno));
#ifdef TIOCNOTTY
	(void) ioctl (qsysdep->o, TIOCNOTTY, (char *) NULL);
#endif
	(void) close (qsysdep->o);
	qsysdep->o = -1;
	(void) fsserial_lockfile (FALSE, qconn);
	return FALSE;
      }
#endif

#if HAVE_DEV_INFO
    /* QNX programs "lock" a serial port by simply opening it and
       checking if some other program also has the port open.  If the
       count of openers is greater than one, the program presumes the
       port is "locked" and backs off.  This isn't really "locking" of
       course, but it pretty much seems to work.  This can result in
       dropping incoming connections if an outgoing connection is
       started at exactly the same time.  It would probably be better
       to stop using the lock files at all for this case, but that
       would involve more complex changes to the code, and I'm afraid
       I would break something.  -- Joe Wells <jbw@cs.bu.edu>  */
    {
      struct _dev_info_entry sdevinfo;

      if (dev_info (qsysdep->o, &sdevinfo) == -1)
        {
          ulog (LOG_ERROR, "dev_info: %s", strerror (errno));
          sdevinfo.open_count = 2; /* force presumption of "locked" */
        }
      if (sdevinfo.open_count != 1)
        {
#ifdef TIOCNOTTY
          (void) ioctl (qsysdep->o, TIOCNOTTY, (char *) NULL);
#endif /* TIOCNOTTY */
          (void) close (qsysdep->o);
          qsysdep->o = -1;
          (void) fsserial_lockfile (FALSE, qconn);
          return FALSE;
        }
    }
#endif /* HAVE_DEV_INFO */

    if (fcntl (qsysdep->o, F_SETFD,
	       fcntl (qsysdep->o, F_GETFD, 0) | FD_CLOEXEC) < 0)
      {
	ulog (LOG_ERROR, "fcntl (FD_CLOEXEC): %s", strerror (errno));
#ifdef TIOCNOTTY
	(void) ioctl (qsysdep->o, TIOCNOTTY, (char *) NULL);
#endif
	(void) close (qsysdep->o);
	qsysdep->o = -1;
	(void) fsserial_lockfile (FALSE, qconn);
	return FALSE;
      }
  }
#endif /* HAVE_TIOCSINUSE || HAVE_TIOCEXCL */

  return TRUE;
}

/* Unlock a modem or direct port.  */

static boolean
fsserial_unlock (qconn)
     struct sconnection *qconn;
{
  boolean fret;
  struct ssysdep_conn *qsysdep;

  fret = TRUE;

  /* The file may have been opened by fsserial_lock, so close it here
     if necessary.  */
  qsysdep = (struct ssysdep_conn *) qconn->psysdep;
  if (qsysdep->o >= 0)
    {
#ifdef TIOCNOTTY
      (void) ioctl (qsysdep->o, TIOCNOTTY, (char *) NULL);
#endif
      if (close (qsysdep->o) < 0)
	{
	  ulog (LOG_ERROR, "close: %s", strerror (errno));
	  fret = FALSE;
	}
      qsysdep->o = -1;
    }
    
  if (! fsserial_lockfile (FALSE, qconn))
    fret = FALSE;

  return fret;
}

/* A table to map baud rates into index numbers.  */

#if HAVE_POSIX_TERMIOS
typedef speed_t baud_code;
#else
typedef int baud_code;
#endif

static struct sbaud_table
{
  baud_code icode;
  long ibaud;
} asSbaud_table[] =
{
  { B50, 50 },
  { B75, 75 },
  { B110, 110 },
  { B134, 134 },
  { B150, 150 },
  { B200, 200 },
  { B300, 300 },
  { B600, 600 },
  { B1200, 1200 },
  { B1800, 1800 },
  { B2400, 2400 },
  { B4800, 4800 },
  { B9600, 9600 },
#ifdef B19200
  { B19200, 19200 },
#else /* ! defined (B19200) */
#ifdef EXTA
  { EXTA, 19200 },
#endif /* EXTA */
#endif /* ! defined (B19200) */
#ifdef B38400
  { B38400, 38400 },
#else /* ! defined (B38400) */
#ifdef EXTB
  { EXTB, 38400 },
#endif /* EXTB */
#endif /* ! defined (B38400) */
#ifdef B57600
  { B57600, 57600 },
#endif
#ifdef B76800
  { B76800, 76800 },
#endif
#ifdef B115200
  { B115200, 115200 },
#endif
#ifdef B230400
  { B230400, 230400 },
#else
#ifdef _B230400
  { _B230400, 230400 },
#endif /* _B230400 */
#endif /* ! defined (B230400) */
#ifdef B460800
  { B460800, 460800 },
#else
#ifdef _B460800
  { _B460800, 460800 },
#endif /* _B460800 */
#endif /* ! defined (B460800) */
#ifdef B500000
  { B500000, 500000 },
#endif
#ifdef B576000
  { B576000, 576000 },
#endif
#ifdef B921600
  { B921600, 921600 },
#endif
#ifdef B1000000
  { B1000000, 1000000 },
#endif
#ifdef B1152000
  { B1152000, 1152000 },
#endif
#ifdef B1500000
  { B1500000, 1500000 },
#endif
#ifdef B2000000
  { B2000000, 2000000 },
#endif
#ifdef B2500000
  { B2500000, 2500000 },
#endif
#ifdef B3000000
  { B3000000, 3000000 },
#endif
#ifdef B3500000
  { B3500000, 3500000 },
#endif
#ifdef B4000000
  { B4000000, 4000000 },
#endif
  { B0, 0 }
};

#define CBAUD_TABLE (sizeof asSbaud_table / sizeof asSbaud_table[0])

#if HAVE_SYSV_TERMIO || HAVE_POSIX_TERMIOS
/* Hold the MIN value for the terminal to avoid setting it
   unnecessarily.  */
static int cSmin;
#endif /* HAVE_SYSV_TERMIO || HAVE_POSIX_TERMIOS */

/* Open a serial line.  This sets the terminal settings.  We begin in
   seven bit mode and let the protocol change if necessary.  If fwait
   is FALSE we open the terminal in non-blocking mode.  If fuser is
   true we open the port using the user's permissions.  The tlocal
   parameter indicates whether to set, clear, or ignore CLOCAL.  */

static boolean
fsserial_open (qconn, ibaud, fwait, fuser, tlocal)
     struct sconnection *qconn;
     long ibaud;
     boolean fwait;
     boolean fuser;
     enum tclocal_setting tlocal;
{
  struct ssysdep_conn *q;
  baud_code ib;

  q = (struct ssysdep_conn *) qconn->psysdep;

  if (q->zdevice != NULL)
    {
#if LOG_DEVICE_PREFIX
      ulog_device (q->zdevice);
#else
      const char *z;

      if (strncmp (q->zdevice, "/dev/", sizeof "/dev/" - 1) == 0)
	z = q->zdevice + sizeof "/dev/" - 1;
      else
	z = q->zdevice;
      ulog_device (z);
#endif
    }
  else
    {
      const char *zport;
      boolean fdummy;

#if DEBUG > 0
      if (qconn->qport != NULL &&
	  qconn->qport->uuconf_ttype != UUCONF_PORTTYPE_STDIN)
	ulog (LOG_FATAL, "fsserial_open: Can't happen");
#endif
      zport = zsysdep_port_name (&fdummy);
      if (zport != NULL)
	ulog_device (zport);
    }

  ib = B0;
  if (ibaud != 0)
    {
      size_t i;

      for (i = 0; i < CBAUD_TABLE; i++)
	if (asSbaud_table[i].ibaud == ibaud)
	  break;
      if (i >= CBAUD_TABLE)
	{
	  ulog (LOG_ERROR, "Unsupported baud rate %ld", ibaud);
	  return FALSE;
	}
      ib = asSbaud_table[i].icode;
    }

  /* The port may have already been opened by the locking routine.  */
  if (q->o < 0)
    {
      int iflag;
      uid_t ieuid;
      gid_t iegid;

      if (fwait)
	iflag = 0;
      else
	iflag = iSunblock;

      if (fuser)
	{
	  if (! fsuser_perms (&ieuid, &iegid))
	    return FALSE;
	}
	  
      q->o = open (q->zdevice, O_RDWR | iflag);
      if (q->o < 0)
	{
#if O_NONBLOCK != 0
	  if (! fwait && iSunblock != O_NONBLOCK && errno == EINVAL)
	    {
	      iSunblock = O_NONBLOCK;
	      q->o = open (q->zdevice, O_RDWR | O_NONBLOCK);
	    }
#endif
	  if (q->o < 0)
	    {
	      int ierr;

	      ierr = errno;
	      if (fuser)
		(void) fsuucp_perms ((long) ieuid, (long) iegid);
	      ulog (LOG_ERROR, "open (%s): %s", q->zdevice,
		    strerror (ierr));
	      return FALSE;
	    }
	}

      if (fuser)
	{
	  if (! fsuucp_perms ((long) ieuid, (long) iegid))
	    return FALSE;
	}

      if (fcntl (q->o, F_SETFD, fcntl (q->o, F_GETFD, 0) | FD_CLOEXEC) < 0)
	{
	  ulog (LOG_ERROR, "fcntl (FD_CLOEXEC): %s", strerror (errno));
	  return FALSE;
	}
    }

  /* Get the port flags, and make sure the ports are blocking.  */

  q->iflags = fcntl (q->o, F_GETFL, 0);
  if (q->iflags < 0)
    {
      ulog (LOG_ERROR, "fcntl: %s", strerror (errno));
      return FALSE;
    }
  q->iwr_flags = -1;

  if (! fsblock (q, TRUE))
    return FALSE;

  if (! fgetterminfo (q->o, &q->sorig))
    {
      q->fterminal = FALSE;
      return TRUE;
    }

  q->fterminal = TRUE;

  q->snew = q->sorig;

#if HAVE_BSD_TTY

  q->snew.stty.sg_flags = RAW | ANYP;
  if (ibaud == 0)
    ib = q->snew.stty.sg_ospeed;
  else
    {
      q->snew.stty.sg_ispeed = ib;
      q->snew.stty.sg_ospeed = ib;
    }

  /* We don't want to receive any interrupt characters.  */
  q->snew.stchars.t_intrc = -1;
  q->snew.stchars.t_quitc = -1;
  q->snew.stchars.t_eofc = -1;
  q->snew.stchars.t_brkc = -1;
  q->snew.sltchars.t_suspc = -1;
  q->snew.sltchars.t_rprntc = -1;
  q->snew.sltchars.t_dsuspc = -1;
  q->snew.sltchars.t_flushc = -1;
  q->snew.sltchars.t_werasc = -1;
  q->snew.sltchars.t_lnextc = -1;

#ifdef NTTYDISC
  /* We want to use the ``new'' terminal driver so that we can use the
     local mode bits to control XON/XOFF.  */
  {
    int iparam;

    if (ioctl (q->o, TIOCGETD, &iparam) >= 0
	&& iparam != NTTYDISC)
      {
	iparam = NTTYDISC;
	(void) ioctl (q->o, TIOCSETD, &iparam);
      }
  }
#endif

#ifdef TIOCHPCL
  /* When the file is closed, hang up the line.  This is a safety
     measure in case the program crashes.  */
  (void) ioctl (q->o, TIOCHPCL, 0);
#endif

#ifdef TIOCFLUSH
  {
    int iparam;

    /* Flush pending input.  */
#ifdef FREAD
    iparam = FREAD;
#else
    iparam = 0;
#endif
    (void) ioctl (q->o, TIOCFLUSH, &iparam);
  }
#endif /* TIOCFLUSH */

#endif /* HAVE_BSD_TTY */

#if HAVE_SYSV_TERMIO

  if (ibaud == 0)
    ib = q->snew.c_cflag & CBAUD;

  q->snew.c_iflag &=~ ICLEAR_IFLAG;
  q->snew.c_oflag &=~ ICLEAR_OFLAG;
  q->snew.c_cflag &=~ ICLEAR_CFLAG;
  q->snew.c_cflag |= ib | ISET_CFLAG;
  q->snew.c_lflag &=~ ICLEAR_LFLAG;
  cSmin = 1;
  q->snew.c_cc[VMIN] = cSmin;
  q->snew.c_cc[VTIME] = 1;

#ifdef TCFLSH
  /* Flush pending input.  */
  (void) ioctl (q->o, TCFLSH, 0);
#endif

#endif /* HAVE_SYSV_TERMIO */

#if HAVE_POSIX_TERMIOS

  if (ibaud == 0)
    ib = cfgetospeed (&q->snew);

  q->snew.c_iflag &=~ ICLEAR_IFLAG;
  q->snew.c_oflag &=~ ICLEAR_OFLAG;
  q->snew.c_cflag &=~ ICLEAR_CFLAG;
  q->snew.c_cflag |= ISET_CFLAG;
  q->snew.c_lflag &=~ ICLEAR_LFLAG;
  cSmin = 1;
  q->snew.c_cc[VMIN] = cSmin;
  q->snew.c_cc[VTIME] = 1;

  (void) cfsetospeed (&q->snew, ib);
  (void) cfsetispeed (&q->snew, ib);

  /* Flush pending input.  */
  (void) tcflush (q->o, TCIFLUSH);

#endif /* HAVE_POSIX_TERMIOS */

#if HAVE_SYSV_TERMIO || HAVE_POSIX_TERMIOS
  switch (tlocal)
    {
    case SET_CLOCAL:
      q->snew.c_cflag |= CLOCAL;
      break;
    case CLEAR_CLOCAL:
      q->snew.c_cflag &=~ CLOCAL;
      break;
    case IGNORE_CLOCAL:
      break;
    }
#endif /* HAVE_SYSV_TERMIO || HAVE_POSIX_TERMIOS */

  if (! fsetterminfo (q->o, &q->snew))
    {
      ulog (LOG_ERROR, "Can't set terminal settings: %s", strerror (errno));
      return FALSE;
    }

#ifdef TIOCSCTTY
  /* On BSD 4.4, make it our controlling terminal.  */
  (void) ioctl (q->o, TIOCSCTTY, 0);
#endif

  if (ibaud != 0)
    q->ibaud = ibaud;
  else
    {
      size_t i;

      q->ibaud = (long) 1200;
      for (i = 0; i < CBAUD_TABLE; i++)
	{
	  if (asSbaud_table[i].icode == ib
	      && asSbaud_table[i].ibaud != 0)
	    {
	      q->ibaud = asSbaud_table[i].ibaud;
	      break;
	    }
	}

      DEBUG_MESSAGE1 (DEBUG_PORT,
		      "fsserial_open: Baud rate is %ld", q->ibaud);
    }

  return TRUE;
}

/* Open a standard input port.  The code alternates q->o between
   q->ord and q->owr as appropriate.  It is always q->ord before any
   call to fsblock.  */

static boolean
fsstdin_open (qconn, ibaud, fwait, fuser, nortscts)
     struct sconnection *qconn;
     long ibaud;
     boolean fwait;
     boolean fuser;
     boolean nortscts;
{
  struct ssysdep_conn *q;

  q = (struct ssysdep_conn *) qconn->psysdep;
  q->ord = 0;
  q->owr = 1;

  q->o = q->ord;
  if (! fsserial_open (qconn, ibaud, fwait, fuser, IGNORE_CLOCAL))
    return FALSE;
  if (nortscts
      && ! fsserial_hardflow (qconn, FALSE))
    return FALSE;
  q->iwr_flags = fcntl (q->owr, F_GETFL, 0);
  if (q->iwr_flags < 0)
    {
      ulog (LOG_ERROR, "fcntl: %s", strerror (errno));
      return FALSE;
    }
  return TRUE;
}

/* Open a modem port.  */

static boolean
fsmodem_open (qconn, ibaud, fwait, fuser, nortscts)
     struct sconnection *qconn;
     long ibaud;
     boolean fwait;
     boolean fuser;
     boolean nortscts;
{
  struct uuconf_modem_port *qm;

  qm = &qconn->qport->uuconf_u.uuconf_smodem;
  if (ibaud == (long) 0)
    ibaud = qm->uuconf_ibaud;

  if (! fsserial_open (qconn, ibaud, fwait, fuser,
		       fwait ? CLEAR_CLOCAL : SET_CLOCAL))
    return FALSE;

  /* If we are waiting for carrier, then turn on hardware flow
     control.  We don't turn on hardware flow control when dialing
     out, because some modems don't assert the necessary signals until
     they see carrier.  Instead, we turn on hardware flow control in
     fsmodem_carrier.  */
  if (nortscts
      && ! fsserial_hardflow (qconn, FALSE))
    return FALSE;
  else if (fwait
      && ! fsserial_hardflow (qconn, qm->uuconf_fhardflow))
    return FALSE;

  return TRUE;
}

/* Open a direct port.  */

static boolean
fsdirect_open (qconn, ibaud, fwait, fuser, nortscts)
     struct sconnection *qconn;
     long ibaud;
     boolean fwait;
     boolean fuser;
     boolean nortscts;
{
  struct uuconf_direct_port *qd;

  qd = &qconn->qport->uuconf_u.uuconf_sdirect;
  if (ibaud == (long) 0)
    ibaud = qd->uuconf_ibaud;
  if (! fsserial_open (qconn, ibaud, fwait, fuser,
		       qd->uuconf_fcarrier ? CLEAR_CLOCAL : SET_CLOCAL))
    return FALSE;

  /* Always turn on hardware flow control for a direct port when it is
     opened.  There is no other sensible time to turn it on.  */
  return fsserial_hardflow (qconn, qd->uuconf_fhardflow && ! nortscts);
}

/* Change the blocking status of the port.  We keep track of the
   current blocking status to avoid calling fcntl unnecessarily; fcntl
   turns out to be surprisingly expensive, at least on Ultrix.  */

static boolean
fsblock (qs, fblock)
     struct ssysdep_conn *qs;
     boolean fblock;
{
  int iwant;
  int isys;

  if (fblock)
    iwant = qs->iflags &~ (O_NDELAY | O_NONBLOCK);
  else
    iwant = qs->iflags | iSunblock;

  if (iwant == qs->iflags)
    return TRUE;

  isys = fcntl (qs->o, F_SETFL, iwant);
  if (isys < 0)
    {
#if O_NONBLOCK != 0
      if (! fblock && iSunblock != O_NONBLOCK && errno == EINVAL)
	{
	  iSunblock = O_NONBLOCK;
	  iwant = qs->iflags | O_NONBLOCK;
	  isys = fcntl (qs->o, F_SETFL, iwant);
	}
#endif
      if (isys < 0)
	{
	  ulog (LOG_ERROR, "fcntl: %s", strerror (errno));
	  return FALSE;
	}
    }

  qs->iflags = iwant;

  if (qs->iwr_flags >= 0 && qs->ord != qs->owr)
    {
      if (fblock)
	iwant = qs->iwr_flags &~ (O_NDELAY | O_NONBLOCK);
      else
	iwant = qs->iwr_flags | iSunblock;

      isys = fcntl (qs->owr, F_SETFL, iwant);
      if (isys < 0)
	{
#if O_NONBLOCK != 0
	  if (! fblock && iSunblock != O_NONBLOCK && errno == EINVAL)
	    {
	      iSunblock = O_NONBLOCK;
	      iwant = qs->iwr_flags | O_NONBLOCK;
	      isys = fcntl (qs->owr, F_SETFL, iwant);
	    }
#endif
	  if (isys < 0)
	    {
	      ulog (LOG_ERROR, "fcntl: %s", strerror (errno));
	      return FALSE;
	    }
	}

      qs->iwr_flags = iwant;
    }

  return TRUE;
}

/* Close a serial port.  */

static boolean
fsserial_close (q)
     struct ssysdep_conn *q;
{
  if (q->o >= 0)
    {
      /* Use a 30 second timeout to avoid hanging while draining
	 output.  */
      if (q->fterminal)
	{
	  fSalarm = FALSE;

	  if (fsysdep_catch ())
	    {
	      usysdep_start_catch ();
	      usset_signal (SIGALRM, usalarm, TRUE, (boolean *) NULL);
	      (void) alarm (30);

	      (void) fsetterminfodrain (q->o, &q->sorig);
	    }

	  usset_signal (SIGALRM, SIG_IGN, TRUE, (boolean *) NULL);
	  (void) alarm (0);
	  usysdep_end_catch ();

	  /* If we timed out, use the non draining call.  Hopefully
	     this can't hang.  */
	  if (fSalarm)
	    (void) fsetterminfo (q->o, &q->sorig);
	}

#ifdef TIOCNOTTY
      /* We don't want this as our controlling terminal any more, so
	 get rid of it.  This is necessary because we don't want to
	 open /dev/tty, since that can confuse the serial port locking
	 on some computers.  */
      (void) ioctl (q->o, TIOCNOTTY, (char *) NULL);
#endif

      (void) close (q->o);
      q->o = -1;

      /* Sleep to give the terminal a chance to settle, in case we are
	 about to call out again.  */
      sleep (2);
    }

  return TRUE;
}

/* Close a stdin port.  */

/*ARGSUSED*/
static boolean
fsstdin_close (qconn, puuconf, qdialer, fsuccess)
     struct sconnection *qconn;
     pointer puuconf ATTRIBUTE_UNUSED;
     struct uuconf_dialer *qdialer ATTRIBUTE_UNUSED;
     boolean fsuccess ATTRIBUTE_UNUSED;
{
  struct ssysdep_conn *qsysdep;

  qsysdep = (struct ssysdep_conn *) qconn->psysdep;
  (void) close (qsysdep->owr);
  (void) close (2);
  qsysdep->o = qsysdep->ord;
  return fsserial_close (qsysdep);
}

/* Close a modem port.  */

static boolean
fsmodem_close (qconn, puuconf, qdialer, fsuccess)
     struct sconnection *qconn;
     pointer puuconf;
     struct uuconf_dialer *qdialer;
     boolean fsuccess;
{
  struct ssysdep_conn *qsysdep;
  boolean fret;
  struct uuconf_dialer sdialer;
  const struct uuconf_chat *qchat;

  qsysdep = (struct ssysdep_conn *) qconn->psysdep;

  fret = TRUE;

  /* Figure out the dialer so that we can run the complete or abort
     chat scripts.  */
  if (qdialer == NULL)
    {
      if (qconn->qport->uuconf_u.uuconf_smodem.uuconf_pzdialer != NULL)
	{
	  const char *zdialer;
	  int iuuconf;

	  zdialer = qconn->qport->uuconf_u.uuconf_smodem.uuconf_pzdialer[0];
	  iuuconf = uuconf_dialer_info (puuconf, zdialer, &sdialer);
	  if (iuuconf == UUCONF_SUCCESS)
	    qdialer = &sdialer;
	  else
	    {
	      ulog_uuconf (LOG_ERROR, puuconf, iuuconf);
	      fret = FALSE;
	    }
	}
      else
	qdialer = qconn->qport->uuconf_u.uuconf_smodem.uuconf_qdialer;
    }

  /* Get the complete or abort chat script to use.  */
  qchat = NULL;
  if (qdialer != NULL)
    {
      if (fsuccess)
	qchat = &qdialer->uuconf_scomplete;
      else
	qchat = &qdialer->uuconf_sabort;
    }

  if (qchat != NULL
      && (qchat->uuconf_pzprogram != NULL
	  || qchat->uuconf_pzchat != NULL))
    {
      boolean fsighup_ignored;
      HELD_SIG_MASK smask;
      int i;
      sig_atomic_t afhold[INDEXSIG_COUNT];

      /* We're no longer interested in carrier.  */
      (void) fsmodem_carrier (qconn, FALSE);

      /* The port I/O routines check whether any signal has been
	 received, and abort if one has.  While we are closing down
	 the modem, we don't care if we received a signal in the past,
	 but we do care if we receive a new signal (otherwise it would
	 be difficult to kill a uucico which was closing down a
	 modem).  We never care if we get SIGHUP at this point.  So we
	 turn off SIGHUP, remember what signals we've already seen,
	 and clear our notion of what signals we've seen.  We have to
	 block the signals while we remember and clear the array,
	 since we might otherwise miss a signal which occurred between
	 the copy and the clear (old systems can't block signals; they
	 will just have to suffer the race).  */
      usset_signal (SIGHUP, SIG_IGN, FALSE, &fsighup_ignored);
      smask = isblocksigs ();
      for (i = 0; i < INDEXSIG_COUNT; i++)
	{
	  afhold[i] = afSignal[i];
	  afSignal[i] = FALSE;
	}
      usunblocksigs (smask);

      if (! fchat (qconn, puuconf, qchat, (const struct uuconf_system *) NULL,
		   (const struct uuconf_dialer *) NULL, (const char *) NULL,
		   FALSE, qconn->qport->uuconf_zname,
		   qsysdep->ibaud))
	fret = FALSE;

      /* Restore the old signal array and the SIGHUP handler.  It is
	 not necessary to block signals here, since all we are doing
	 is exactly what the signal handler itself would do if the
	 signal occurred.  */
      for (i = 0; i < INDEXSIG_COUNT; i++)
	if (afhold[i])
	  afSignal[i] = TRUE;
      if (! fsighup_ignored)
	usset_signal (SIGHUP, ussignal, TRUE, (boolean *) NULL);
    }

  if (qdialer != NULL
      && qdialer == &sdialer)
    (void) uuconf_dialer_free (puuconf, &sdialer);

#if ! HAVE_RESET_BUG
  /* Reset the terminal to make sure we drop DTR.  It should be
     dropped when we close the descriptor, but that doesn't seem to
     happen on some systems.  Use a 30 second timeout to avoid hanging
     while draining output.  */
  if (qsysdep->fterminal)
    {
#if HAVE_BSD_TTY
      qsysdep->snew.stty.sg_ispeed = B0;
      qsysdep->snew.stty.sg_ospeed = B0;
#endif
#if HAVE_SYSV_TERMIO
      qsysdep->snew.c_cflag = (qsysdep->snew.c_cflag &~ CBAUD) | B0;
#endif
#if HAVE_POSIX_TERMIOS
      (void) cfsetospeed (&qsysdep->snew, B0);
#endif

      fSalarm = FALSE;

      if (fsysdep_catch ())
	{
	  usysdep_start_catch ();
	  usset_signal (SIGALRM, usalarm, TRUE, (boolean *) NULL);
	  (void) alarm (30);

	  (void) fsetterminfodrain (qsysdep->o, &qsysdep->snew);
	}

      usset_signal (SIGALRM, SIG_IGN, TRUE, (boolean *) NULL);
      (void) alarm (0);
      usysdep_end_catch ();

      /* Let the port settle.  */
      sleep (2);
    }
#endif /* ! HAVE_RESET_BUG */

  if (! fsserial_close (qsysdep))
    fret = FALSE;

  return fret;
}

/* Close a direct port.  */

/*ARGSUSED*/
static boolean
fsdirect_close (qconn, puuconf, qdialer, fsuccess)
     struct sconnection *qconn;
     pointer puuconf ATTRIBUTE_UNUSED;
     struct uuconf_dialer *qdialer ATTRIBUTE_UNUSED;
     boolean fsuccess ATTRIBUTE_UNUSED;
{
  return fsserial_close ((struct ssysdep_conn *) qconn->psysdep);
}

/* Begin dialing out on a modem port.  This opens the dialer device if
   there is one.  */

boolean
fsysdep_modem_begin_dial (qconn, qdial)
     struct sconnection *qconn;
     struct uuconf_dialer *qdial;
{
  struct ssysdep_conn *qsysdep;
  const char *z;

  qsysdep = (struct ssysdep_conn *) qconn->psysdep;

#ifdef TIOCMODEM
  /* If we can tell the modem to obey modem control, do so.  */
  {
    int iperm;

    iperm = 0;
    (void) ioctl (qsysdep->o, TIOCMODEM, &iperm);
  }
#endif /* TIOCMODEM */

  /* If we supposed to toggle DTR, do so.  */

  if (qdial->uuconf_fdtr_toggle)
    {
#ifdef TIOCCDTR
      (void) ioctl (qsysdep->o, TIOCCDTR, 0);
      sleep (2);
      (void) ioctl (qsysdep->o, TIOCSDTR, 0);
#else /* ! defined (TIOCCDTR) */
      if (qsysdep->fterminal)
	{
	  sterminal sbaud;

	  sbaud = qsysdep->snew;

#if HAVE_BSD_TTY
	  sbaud.stty.sg_ispeed = B0;
	  sbaud.stty.sg_ospeed = B0;
#endif
#if HAVE_SYSV_TERMIO
	  sbaud.c_cflag = (sbaud.c_cflag &~ CBAUD) | B0;
#endif
#if HAVE_POSIX_TERMIOS
	  (void) cfsetospeed (&sbaud, B0);
#endif

	  (void) fsetterminfodrain (qsysdep->o, &sbaud);
	  sleep (2);
	  (void) fsetterminfo (qsysdep->o, &qsysdep->snew);
	}
#endif /* ! defined (TIOCCDTR) */

      if (qdial->uuconf_fdtr_toggle_wait)
	sleep (2);
    }

  if (! fsmodem_carrier (qconn, FALSE))
    return FALSE;

  /* Open the dial device if there is one.  */
  z = qconn->qport->uuconf_u.uuconf_smodem.uuconf_zdial_device;
  if (z != NULL)
    {
      char *zfree;
      int o;

      qsysdep->ohold = qsysdep->o;

      zfree = NULL;
      if (*z != '/')
	{
	  zfree = zbufalc (sizeof "/dev/" + strlen (z));
	  sprintf (zfree, "/dev/%s", z);
	  z = zfree;
	}

      o = open ((char *) z, O_RDWR | O_NOCTTY);
      if (o < 0)
	{
	  ulog (LOG_ERROR, "open (%s): %s", z, strerror (errno));
	  ubuffree (zfree);
	  return FALSE;
	}
      ubuffree (zfree);

      if (fcntl (o, F_SETFD, fcntl (o, F_GETFD, 0) | FD_CLOEXEC) < 0)
	{
	  ulog (LOG_ERROR, "fcntl (FD_CLOEXEC): %s", strerror (errno));
	  (void) close (o);
	  return FALSE;
	}

      qsysdep->o = o;
    }

  return TRUE;
}

/* Tell the port to require or not require carrier.  On BSD this uses
   TIOCCAR and TIOCNCAR, which I assume are generally supported (it
   can also use the LNOMDM bit supported by IS68K Unix).  On System V
   it resets or sets CLOCAL.  We only require carrier if the port
   supports it.  This will only be called with fcarrier TRUE if the
   dialer supports carrier.  */

static boolean
fsmodem_carrier (qconn, fcarrier)
     struct sconnection *qconn;
     boolean fcarrier;
{
  register struct ssysdep_conn *q;
  struct uuconf_modem_port *qm;

  q = (struct ssysdep_conn *) qconn->psysdep;

  if (! q->fterminal)
    return TRUE;

  qm = &qconn->qport->uuconf_u.uuconf_smodem;
  if (fcarrier)
    {
      if (qm->uuconf_fcarrier)
	{
#ifdef TIOCCAR
	  /* Tell the modem to pay attention to carrier.  */
	  if (ioctl (q->o, TIOCCAR, 0) < 0)
	    {
	      ulog (LOG_ERROR, "ioctl (TIOCCAR): %s", strerror (errno));
	      return FALSE;
	    }
#endif /* TIOCCAR */

#if HAVE_BSD_TTY
#ifdef LNOMDM
	  /* IS68K Unix uses a local LNOMDM bit.  */
	  {
	    int iparam;

	    iparam = LNOMDM;
	    if (ioctl (q->o, TIOCLBIC, &iparam) < 0)
	      {
		ulog (LOG_ERROR, "ioctl (TIOCLBIC, LNOMDM): %s",
		      strerror (errno));
		return FALSE;
	      }
	  }
#endif /* LNOMDM */
#endif /* HAVE_BSD_TTY */

#if HAVE_SYSV_TERMIO || HAVE_POSIX_TERMIOS
	  /* Put the modem into nonlocal mode.  */
	  q->snew.c_cflag &=~ CLOCAL;
	  if (! fsetterminfo (q->o, &q->snew))
	    {
	      ulog (LOG_ERROR, "Can't clear CLOCAL: %s", strerror (errno));
	      return FALSE;
	    }
#endif /* HAVE_SYSV_TERMIO || HAVE_POSIX_TERMIOS */
	}

      /* Turn on hardware flow control after turning on carrier.  We
	 don't do it until now because some modems don't assert the
	 right signals until they see carrier.  */
      if (! fsserial_hardflow (qconn, qm->uuconf_fhardflow))
	return FALSE;
    }
  else
    {
      /* Turn off any hardware flow control before turning off
	 carrier.  */
      if (! fsserial_hardflow (qconn, FALSE))
	return FALSE;

#ifdef TIOCNCAR
      /* Tell the modem to ignore carrier.  */ 
      if (ioctl (q->o, TIOCNCAR, 0) < 0)
	{
	  ulog (LOG_ERROR, "ioctl (TIOCNCAR): %s", strerror (errno));
	  return FALSE;
	}
#endif /* TIOCNCAR */

#if HAVE_BSD_TTY
#ifdef LNOMDM
      /* IS68K Unix uses a local LNOMDM bit.  */
      {
	int iparam;

	iparam = LNOMDM;
	if (ioctl (q->o, TIOCLBIS, &iparam) < 0)
	  {
	    ulog (LOG_ERROR, "ioctl (TIOCLBIS, LNOMDM): %s",
		  strerror (errno));
	    return FALSE;
	  }
      }
#endif /* LNOMDM */
#endif /* HAVE_BSD_TTY */

#if HAVE_SYSV_TERMIO || HAVE_POSIX_TERMIOS
      /* Put the modem into local mode (ignore carrier) to start the chat
	 script.  */
      q->snew.c_cflag |= CLOCAL;
      if (! fsetterminfo (q->o, &q->snew))
	{
	  ulog (LOG_ERROR, "Can't set CLOCAL: %s", strerror (errno));
	  return FALSE;
	}
  
#if HAVE_CLOCAL_BUG
      /* On SCO and AT&T UNIX PC you have to reopen the port.  */
      {
	int onew;
 
	onew = open (q->zdevice, O_RDWR);
	if (onew < 0)
	  {
	    ulog (LOG_ERROR, "open (%s): %s", q->zdevice, strerror (errno));
	    return FALSE;
	  }
 
	if (fcntl (onew, F_SETFD,
		   fcntl (onew, F_GETFD, 0) | FD_CLOEXEC) < 0)
	  {
	    ulog (LOG_ERROR, "fcntl (FD_CLOEXEC): %s", strerror (errno));
	    (void) close (onew);
	    return FALSE;
	  }

	(void) close (q->o);
	q->o = onew;
      }
#endif /* HAVE_CLOCAL_BUG */

#endif /* HAVE_SYSV_TERMIO || HAVE_POSIX_TERMIOS */
    }

  return TRUE;
}

/* Tell the port to use hardware flow control.  There is no standard
   mechanism for controlling this.  This implementation supports
   CRTSCTS and CRTSXOFF on SunOS/Solaris, RTS/CTSFLOW on 386(ish)
   unix, CTSCD on the 3b1, CCTS_OFLOW/CRTS_IFLOW on BSDI,
   TXADDCD/TXDELCD on AIX, IRTS on NCR Tower, and TCGETX/TCSETX on
   HP/UX.  If you know how to do it on other systems, please implement
   it and send me the patches.  */

static boolean
fsserial_hardflow (qconn, fhardflow)
     struct sconnection *qconn;
     boolean fhardflow;
{
  register struct ssysdep_conn *q;

  q = (struct ssysdep_conn *) qconn->psysdep;

  if (! q->fterminal)
    return TRUE;

  /* Don't do anything if we don't know what to do.  */
#if HAVE_BSD_TTY
#define HAVE_HARDFLOW 0
#endif
#if HAVE_SYSV_TERMIO || HAVE_POSIX_TERMIOS
#if ! HAVE_TXADDCD
#ifndef CRTSFL
#ifndef CRTSCTS
#ifndef CTSCD
#ifndef CCTS_OFLOW
#ifndef IRTS
#define HAVE_HARDFLOW 0
#endif
#endif
#endif
#endif
#endif
#endif
#endif

#ifndef HAVE_HARDFLOW
#define HAVE_HARDFLOW 1
#endif

#if HAVE_HARDFLOW
  if (fhardflow)
    {
#if HAVE_TXADDCD
      /* The return value does not reliably indicate whether this
	 actually succeeded.  */
      (void) ioctl (q->o, TXADDCD, "rts");
#else /* ! HAVE_TXADDCD */
#if HAVE_SYSV_TERMIO || HAVE_POSIX_TERMIOS
#ifdef CRTSFL
      q->snew.c_cflag |= CRTSFL;
      q->snew.c_cflag &=~ (RTSFLOW | CTSFLOW);
#endif /* defined (CRTSFL) */
#ifdef CRTSCTS
      q->snew.c_cflag |= CRTSCTS;
#endif /* defined (CRTSCTS) */
#ifdef CRTSXOFF
      q->snew.c_cflag |= CRTSXOFF;
#endif /* defined (CRTSXOFF) */
#ifdef CTSCD
      q->snew.c_cflag |= CTSCD;
#endif /* defined (CTSCD) */
#ifdef CCTS_OFLOW
      q->snew.c_cflag |= CCTS_OFLOW | CRTS_IFLOW;
#endif
#ifdef IRTS
      q->snew.c_iflag |= IRTS;
#endif
#endif /* HAVE_SYSV_TERMIO || HAVE_POSIX_TERMIOS */
      if (! fsetterminfo (q->o, &q->snew))
	{
	  ulog (LOG_ERROR, "Can't enable hardware flow control: %s",
		strerror (errno));
	  return FALSE;
	}
#if HAVE_SYS_TERMIOX
#ifdef TCGETX
      {
	struct termiox tx;

	if (ioctl (q->o, TCGETX, &tx) < 0)
	  {
	    ulog (LOG_ERROR,
		  "Can't enable hardware flow control: ioctl (TCGETX): %s",
		  strerror (errno));
	    return FALSE;
	  }
	tx.x_hflag |= RTSXOFF | CTSXON;
	if (ioctl (q->o, TCSETX, &tx) < 0)
	  {
	    ulog (LOG_ERROR,
		  "Can't enable hardware flow control: ioctl (TCSETX): %s",
		  strerror (errno));
	    return FALSE;
	  }
      }
#endif /* TCGETX */
#endif /* HAVE_SYS_TERMIOX */
#endif /* ! HAVE_TXADDCD */
    }
  else
    {
#if HAVE_TXADDCD
      /* The return value does not reliably indicate whether this
	 actually succeeded.  */
      (void) ioctl (q->o, TXDELCD, "rts");
#else /* ! HAVE_TXADDCD */
#if HAVE_SYSV_TERMIO || HAVE_POSIX_TERMIOS
#ifdef CRTSFL
      q->snew.c_cflag &=~ CRTSFL;
      q->snew.c_cflag &=~ (RTSFLOW | CTSFLOW);
#endif /* defined (CRTSFL) */
#ifdef CRTSCTS
      q->snew.c_cflag &=~ CRTSCTS;
#endif /* defined (CRTSCTS) */
#ifdef CRTSXOFF
      q->snew.c_cflag &=~ CRTSXOFF;
#endif /* defined (CRTSXOFF) */
#ifdef CTSCD
      q->snew.c_cflag &=~ CTSCD;
#endif /* defined (CTSCD) */
#ifdef CCTS_OFLOW
      q->snew.c_cflag &=~ (CCTS_OFLOW | CRTS_IFLOW);
#endif
#ifdef IRTS
      q->snew.c_iflag &=~ IRTS;
#endif
#endif /* HAVE_SYSV_TERMIO || HAVE_POSIX_TERMIOS */
      if (! fsetterminfo (q->o, &q->snew))
	{
	  ulog (LOG_ERROR, "Can't disable hardware flow control: %s",
		strerror (errno));
	  return FALSE;
	}
#if HAVE_SYS_TERMIOX
#ifdef TCGETX
      {
	struct termiox tx;

	if (ioctl (q->o, TCGETX, &tx) < 0)
	  {
	    ulog (LOG_ERROR,
		  "Can't disable hardware flow control: ioctl (TCGETX): %s",
		  strerror (errno));
	    return FALSE;
	  }
	tx.x_hflag &=~ (RTSXOFF | CTSXON);
	if (ioctl (q->o, TCSETX, &tx) < 0)
	  {
	    ulog (LOG_ERROR,
		  "Can't disable hardware flow control: ioctl (TCSETX): %s",
		  strerror (errno));
	    return FALSE;
	  }
      }
#endif /* TCGETX */
#endif /* HAVE_SYS_TERMIOX */
#endif /* ! HAVE_TXADDCD */
    }
#endif /* HAVE_HARDFLOW */

  return TRUE;
}

/* Finish dialing out on a modem by closing any dialer device and waiting
   for carrier.  */

boolean
fsysdep_modem_end_dial (qconn, qdial)
     struct sconnection *qconn;
     struct uuconf_dialer *qdial;
{
  struct ssysdep_conn *q;

  q = (struct ssysdep_conn *) qconn->psysdep;

  if (qconn->qport->uuconf_u.uuconf_smodem.uuconf_zdial_device != NULL)
    {
      (void) close (q->o);
      q->o = q->ohold;
    }

  if (qconn->qport->uuconf_u.uuconf_smodem.uuconf_fcarrier
      && qdial->uuconf_fcarrier)
    {
      /* Tell the port that we need carrier.  */
      if (! fsmodem_carrier (qconn, TRUE))
	return FALSE;

#ifdef TIOCWONLINE

      /* We know how to wait for carrier, so do so.  */

      /* If we already got a signal, just quit now.  */
      if (FGOT_QUIT_SIGNAL ())
	return FALSE;

      /* This bit of code handles signals just like fsysdep_conn_read
	 does.  See that function for a longer explanation.  */

      /* Use fsysdep_catch to handle a longjmp from the signal
	 handler.  */

      fSalarm = FALSE;

      if (fsysdep_catch ())
	{
	  /* Start catching SIGALRM; normally we ignore it.  */
	  usysdep_start_catch ();
	  usset_signal (SIGALRM, usalarm, TRUE, (boolean *) NULL);
	  (void) alarm (qdial->uuconf_ccarrier_wait);

	  /* We really don't care if we get an error, since that will
	     probably just mean that TIOCWONLINE isn't supported in
	     which case there's nothing we can do anyhow.  If we get
	     SIGINT we want to keep waiting for carrier, because
	     SIGINT just means don't start any new sessions.  We don't
	     handle SIGINT correctly if we do a longjmp in the signal
	     handler; too bad.  */
	  while (ioctl (q->o, TIOCWONLINE, 0) < 0
		 && errno == EINTR)
	    {
	      /* Log the signal.  */
	      ulog (LOG_ERROR, (const char *) NULL);
	      if (FGOT_QUIT_SIGNAL () || fSalarm)
		break;
	    }
	}

      /* Turn off the pending SIGALRM and ignore SIGALARM again.  */
      usset_signal (SIGALRM, SIG_IGN, TRUE, (boolean *) NULL);
      (void) alarm (0);
      usysdep_end_catch ();

      /* If we got a random signal, just return FALSE.  */
      if (FGOT_QUIT_SIGNAL ())
	return FALSE;

      /* If we timed out, give an error.  */
      if (fSalarm)
	{
	  ulog (LOG_ERROR, "Timed out waiting for carrier");
	  return FALSE;
	}

#else /* ! defined (TIOCWONLINE) */

      /* Try to open the port again without using O_NDELAY.  In
	 principle, the open should delay until carrier is available.
	 This may not work on some systems, so we just ignore any
	 errors.  */
      {
	int onew;
 
	onew = open (q->zdevice, O_RDWR);
	if (onew >= 0)
	  {
	    boolean fbad;
	    int iflags;

	    fbad = FALSE;

	    if (fcntl (onew, F_SETFD,
		       fcntl (onew, F_GETFD, 0) | FD_CLOEXEC) < 0)
	      fbad = TRUE;

	    if (! fbad)
	      {
		iflags = fcntl (onew, F_GETFL, 0);
		if (iflags < 0
		    || ! fsetterminfo (onew, &q->snew))
		  fbad = TRUE;
	      }

	    if (fbad)
	      (void) close (onew);
	    else
	      {
		(void) close (q->o);
		q->o = onew;
		q->iflags = iflags;
#if HAVE_TIOCSINUSE
		(void) ioctl (onew, TIOCSINUSE, 0);
#endif
	      }
	  }
      }

#endif /* ! defined (TIOCWONLINE) */
    }

  return TRUE; 
}

/* Read data from a connection, with a timeout.  This routine handles
   all types of connections, including TLI.

   This function should return when we have read cmin characters or
   the timeout has occurred.  We have to work a bit to get Unix to do
   this efficiently on a terminal.  The simple implementation
   schedules a SIGALRM signal and then calls read; if there is a
   single character available, the call to read will return
   immediately, so there must be a loop which terminates when the
   SIGALRM is delivered or the correct number of characters has been
   read.  This can be very inefficient with a fast CPU or a low baud
   rate (or both!), since each call to read may return only one or two
   characters.

   Under POSIX or System V, we can specify a minimum number of
   characters to read, so there is no serious trouble.

   Under BSD, we figure out how many characters we have left to read,
   how long it will take for them to arrive at the current baud rate,
   and sleep that long.

   Doing this with a timeout and avoiding all possible race conditions
   get very hairy, though.  Basically, we're going to schedule a
   SIGALRM for when the timeout expires.  I don't really want to do a
   longjmp in the SIGALRM handler, though, because that may lose data.
   Therefore, I have the signal handler set a variable.  However, this
   means that there will be a span of time between the time the code
   checks the variable and the time it calls the read system call; if
   the SIGALRM occurs during that time, the read might hang forever.
   To avoid this, the SIGALRM handler not only sets a global variable,
   it also schedules another SIGALRM for one second in the future
   (POSIX specifies that a signal handler is permitted to safely call
   alarm).  To avoid getting a continual sequence of SIGALRM
   interrupts, we change the signal handler to ignore SIGALRM when
   we're about to exit the function.  This means that every time we
   execute fsysdep_conn_read we make at least five system calls.  It's
   the best I've been able to come up with, though.

   When fsysdep_conn_read finishes, there will be no SIGALRM scheduled
   and SIGALRM will be ignored.  */

boolean
fsysdep_conn_read (qconn, zbuf, pclen, cmin, ctimeout, freport)
     struct sconnection *qconn;
     char *zbuf;
     size_t *pclen;
     size_t cmin;
     int ctimeout;
     boolean freport;
{
  CATCH_PROTECT size_t cwant;
  boolean fret;
  register struct ssysdep_conn * const q
    = (struct ssysdep_conn *) qconn->psysdep;
  int cwouldblock;

  cwant = *pclen;
  *pclen = 0;

  /* Guard against a bad timeout.  We return TRUE when a timeout
     expires.  It is possible to get a negative timeout here because
     the calling code does not check user supplied timeouts for
     plausibility.  */
  if (ctimeout <= 0)
    return TRUE;

  /* We want to do a blocking read.  */
  if (! fsblock (q, TRUE))
    return FALSE;

  fSalarm = FALSE;

  /* We're going to set up an alarm signal to last for the entire
     read.  If the read system call cannot be interrupted, the signal
     handler will do a longjmp causing fsysdep_catch (a macro) to
     return FALSE.  We handle that here.  If read can be interrupted,
     fsysdep_catch will be defined to TRUE.  */
  if (fsysdep_catch ())
    {
      /* Prepare to catch SIGALRM and schedule the signal.  */
      usysdep_start_catch ();
      usset_signal (SIGALRM, usalarm, TRUE, (boolean *) NULL);
      alarm (ctimeout);
    }
  else
    {
      /* We caught a signal.  We don't actually have to do anything,
	 as all the appropriate checks are made at the start of the
	 following loop.  */
    }

  fret = FALSE;

  cwouldblock = 0;
  while (TRUE)
    {
      int cgot;

#if HAVE_SYSV_TERMIO || HAVE_POSIX_TERMIOS
      /* If we can tell the terminal not to return until we have a
	 certain number of characters, do so.  */
      if (q->fterminal)
	{
	  int csetmin;

	  /* I'm not that confident about setting MIN to values larger
	     than 127, although up to 255 would probably work.  */
	  if (cmin < 127)
	    csetmin = cmin;
	  else
	    csetmin = 127;

	  if (csetmin != cSmin)
	    {
	      q->snew.c_cc[VMIN] = csetmin;
	      while (! fsetterminfo (q->o, &q->snew))
		{
		  if (errno != EINTR
		      || FGOT_QUIT_SIGNAL ())
		    {
		      int ierr;

		      /* We turn off the signal before reporting the
			 error to minimize any problems with
			 interrupted system calls.  */
		      ierr = errno;
		      usset_signal (SIGALRM, SIG_IGN, TRUE, (boolean *) NULL);
		      alarm (0);
		      usysdep_end_catch ();
		      ulog (LOG_ERROR, "Can't set MIN for terminal: %s",
			    strerror (ierr));
		      return FALSE;
		    }

		  if (fSalarm)
		    {
		      ulog (LOG_ERROR,
			    "Timed out when setting MIN to %d; retrying",
			    csetmin);
		      fSalarm = FALSE;
		      alarm (ctimeout);
		    }
		}
	      cSmin = csetmin;
	    }
	}
#endif /* HAVE_SYSV_TERMIO || HAVE_POSIX_TERMIOS */

      /* If we've received a signal, get out now.  */
      if (FGOT_QUIT_SIGNAL ())
	break;

      /* If we've already gotten a SIGALRM, get out with whatever
	 we've accumulated.  */
      if (fSalarm)
	{
	  fret = TRUE;
	  break;
	}

      /* Right here is the race condition which we avoid by having the
	 SIGALRM handler schedule another SIGALRM.  */
#if HAVE_TLI
      if (q->ftli)
	{
	  int iflags;

	  cgot = t_rcv (q->o, zbuf, cwant, &iflags);
	  if (cgot < 0 && t_errno != TSYSERR)
	    {
	      usset_signal (SIGALRM, SIG_IGN, TRUE, (boolean *) NULL);
	      alarm (0);
	      usysdep_end_catch ();

	      if (freport)
		ulog (LOG_ERROR, "t_rcv: %s",
		      (t_errno >= 0 && t_errno < t_nerr
		       ? t_errlist[t_errno]
		       : "unknown TLI error"));

	      return FALSE;
	    }
	}
      else
#endif
	cgot = read (q->o, zbuf, cwant);

      /* If the read returned an error, check for signals.  */
      if (cgot < 0)
	{
	  if (errno == EINTR)
	    {
	      /* Log the signal.  */
	      ulog (LOG_ERROR, (const char *) NULL);
	    }
	  if (fSalarm)
	    {
	      fret = TRUE;
	      break;
	    }
	  if (FGOT_QUIT_SIGNAL ())
	    break;
	}

      /* If read returned an error, get out.  We just ignore EINTR
	 here, since it must be from some signal we don't care about.
	 If the read returned 0 then the line must have been hung up
	 (normally we would have received SIGHUP, but we can't count
	 on that).  We turn off the signals before calling ulog to
	 reduce problems with interrupted system calls.  */
      if (cgot > 0)
	cwouldblock = 0;
      else
	{
	  if (cgot < 0 && errno == EINTR)
	    cgot = 0;
	  else if (cgot < 0
		   && (errno == EAGAIN || errno == EWOULDBLOCK)
		   && cwouldblock < 2)
	    {
	      /* Incomprehensibly, on some systems the read will
		 return EWOULDBLOCK even though the descriptor has
		 been set to blocking mode.  We permit the read call
		 to do this twice in a row, and then error out.  We
		 don't want to permit an arbitrary number of
		 EWOULDBLOCK errors, since that could hang us up
		 indefinitely.  */
	      ++cwouldblock;
	      cgot = 0;
	    }
	  else
	    {
	      int ierr;

	      ierr = errno;

	      usset_signal (SIGALRM, SIG_IGN, TRUE, (boolean *) NULL);
	      alarm (0);
	      usysdep_end_catch ();

	      if (freport)
		{
		  if (cgot == 0)
		    ulog (LOG_ERROR, "Line disconnected");
		  else
		    ulog (LOG_ERROR, "read: %s", strerror (ierr));
		}

	      return FALSE;
	    }
	}

      cwant -= cgot;
      if ((size_t) cgot >= cmin)
	cmin = 0;
      else
	cmin -= cgot;
      zbuf += cgot;
      *pclen += cgot;

      /* If we have enough data, get out now.  */
      if (cmin == 0)
	{
	  fret = TRUE;
	  break;
	}

#if HAVE_BSD_TTY
      /* We still want more data, so sleep long enough for the rest of
	 it to arrive.  We don't this for System V or POSIX because
	 setting MIN is good enough (we can't sleep longer than it
	 takes to get MAX_INPUT characters anyhow).

	 The baud rate is approximately 10 times the number of
	 characters which will arrive in one second, so the number of
	 milliseconds to sleep ==
	 characters * (milliseconds / character) ==
	 characters * (1000 * (seconds / character)) ==
	 characters * (1000 * (1 / (baud / 10))) ==
	 characters * (10000 / baud)

	 We arbitrarily reduce the sleep amount by 10 milliseconds to
	 attempt to account for the amount of time it takes to set up
	 the sleep.  This is how long it takes to get half a character
	 at 19200 baud.  We then don't bother to sleep for less than
	 10 milliseconds.  We don't sleep if the read was interrupted.

	 We use select to sleep.  It would be easy to use poll as
	 well, but it's unlikely that any system with BSD ttys would
	 have poll but not select.  Using select avoids hassles with
	 the pending SIGALRM; if it hits the select will be
	 interrupted, and otherwise the select will not affect it.  */

#if ! HAVE_SELECT
 #error This code requires select; feel free to extend it
#endif

      if (q->fterminal && cmin > 1 && cgot > 0)
	{
	  int csleepchars;
	  int isleep;

	  /* We don't try to read all the way up to MAX_INPUT,
	     since that might drop a character.  */
	  if (cmin <= MAX_INPUT - 10)
	    csleepchars = cmin;
	  else
	    csleepchars = MAX_INPUT - 10;

	  isleep = (int) (((long) csleepchars * 10000L) / q->ibaud);
	  isleep -= 10;

	  if (isleep > 10)
	    {
	      struct timeval s;

	      s.tv_sec = isleep / 1000;
	      s.tv_usec = (isleep % 1000) * 1000;

	      /* Some versions of select take a pointer to an int,
		 while some take a pointer to an fd_set.  I just cast
		 the arguments to a generic pointer, and assume that
		 any machine which distinguishes int * from fd_set *
		 (I would be amazed if there are any such machines)
		 have an appropriate prototype somewhere or other.  */
	      (void) select (0, (pointer) NULL, (pointer) NULL,
			     (pointer) NULL, &s);

	      /* Here either the select finished sleeping or we got a
		 SIGALRM.  If the latter occurred, fSalarm was set to
		 TRUE; it will be checked at the top of the loop.  */
	    }
	}
#endif /* HAVE_BSD_TTY */
    }

  /* Turn off the pending SIGALRM and return.  */

  usset_signal (SIGALRM, SIG_IGN, TRUE, (boolean *) NULL);
  alarm (0);
  usysdep_end_catch ();

  return fret;
}

/* Read from a port with separate read/write file descriptors.  */

boolean
fsdouble_read (qconn, zbuf, pclen, cmin, ctimeout, freport)
     struct sconnection *qconn;
     char *zbuf;
     size_t *pclen;
     size_t cmin;
     int ctimeout;
     boolean freport;
{
  struct ssysdep_conn *qsysdep;

  qsysdep = (struct ssysdep_conn *) qconn->psysdep;
  qsysdep->o = qsysdep->ord;
  return fsysdep_conn_read (qconn, zbuf, pclen, cmin, ctimeout, freport);
}

/* Write data to a connection.  This routine handles all types of
   connections, including TLI.  */

boolean
fsysdep_conn_write (qconn, zwrite, cwrite)
     struct sconnection *qconn;
     const char *zwrite;
     size_t cwrite;
{
  struct ssysdep_conn *q;
  int czero;

  q = (struct ssysdep_conn *) qconn->psysdep;

  /* We want blocking writes here.  */
  if (! fsblock (q, TRUE))
    return FALSE;

  czero = 0;

  while (cwrite > 0)
    {
      int cdid;

      /* Loop until we don't get an interrupt.  */
      while (TRUE)
	{
	  /* If we've received a signal, don't continue.  */
	  if (FGOT_QUIT_SIGNAL ())
	    return FALSE;

#if HAVE_TLI
	  if (q->ftli)
	    {
	      cdid = t_snd (q->o, (char *) zwrite, cwrite, 0);
	      if (cdid < 0 && t_errno != TSYSERR)
		{
		  ulog (LOG_ERROR, "t_snd: %s",
			(t_errno >= 0 && t_errno < t_nerr
			 ? t_errlist[t_errno]
			 : "unknown TLI error"));
		  return FALSE;
		}
	    }
	  else
#endif
	    cdid = write (q->o, zwrite, cwrite);

	  if (cdid >= 0)
	    break;
	  if (errno != EINTR)
	    break;

	  /* We were interrupted by a signal.  Log it.  */
	  ulog (LOG_ERROR, (const char *) NULL);
	}

      if (cdid < 0)
	{
	  if (errno != EAGAIN && errno != EWOULDBLOCK && errno != ENODATA)
	    {
	      ulog (LOG_ERROR, "write: %s", strerror (errno));
	      return FALSE;
	    }
	  cdid = 0;
	}

      if (cdid == 0)
	{
	  /* On some systems write will return 0 if carrier is lost.
	     If we fail to write anything ten times in a row, we
	     assume that this has happened.  This is hacked in like
	     this because there seems to be no reliable way to tell
	     exactly why the write returned 0.  */
	  ++czero;
	  if (czero >= 10)
	    {
	      ulog (LOG_ERROR, "Line disconnected");
	      return FALSE;
	    }
	}
      else
	{
	  czero = 0;

	  cwrite -= cdid;
	  zwrite += cdid;
	}
    }

  return TRUE;
}

/* Write to a port with separate read/write file descriptors.  */

boolean
fsdouble_write (qconn, zwrite, cwrite)
     struct sconnection *qconn;
     const char *zwrite;
     size_t cwrite;
{
  struct ssysdep_conn *qsysdep;

  qsysdep = (struct ssysdep_conn *) qconn->psysdep;
  qsysdep->o = qsysdep->ord;
  if (! fsblock (qsysdep, TRUE))
    return FALSE;
  qsysdep->o = qsysdep->owr;
  return fsysdep_conn_write (qconn, zwrite, cwrite);
}

/* The fsysdep_conn_io routine is supposed to both read and write data
   until it has either filled its read buffer or written out all the
   data it was given.  This lets us write out large packets without
   losing incoming data.  It handles all types of connections,
   including TLI.  */

boolean
fsysdep_conn_io (qconn, zwrite, pcwrite, zread, pcread)
     struct sconnection *qconn;
     const char *zwrite;
     size_t *pcwrite;
     char *zread;
     size_t *pcread;
{
  struct ssysdep_conn *q;
  size_t cwrite, cread;
  int czero;

  q = (struct ssysdep_conn *) qconn->psysdep;

  cwrite = *pcwrite;
  *pcwrite = 0;
  cread = *pcread;
  *pcread = 0;

  czero = 0;

  while (TRUE)
    {
      int cgot, cdid;
      size_t cdo;

      /* This used to always use nonblocking writes, but it turns out
	 that some systems don't support them on terminals.

	 The current algorithm is:
	     loop:
	       unblocked read
	       if read buffer full, return
	       if nothing to write, return
	       if HAVE_UNBLOCKED_WRITES
	         write all data
	       else
	         write up to SINGLE_WRITE bytes
	       if all data written, return
	       if no data written
	         if select works
		   select on the write descriptor with a ten second timeout
		 else
		   blocked write of one byte with a ten second alarm

	 This algorithm should work whether the system supports
	 unblocked writes on terminals or not.  If the system supports
	 unblocked writes but HAVE_UNBLOCKED_WRITES is 0, then it will
	 call write more often than it needs to.  If the system does
	 not support unblocked writes but HAVE_UNBLOCKED_WRITES is 1,
	 then the write may hang so long that incoming data is lost.
	 This is actually possible at high baud rates on any system
	 when a blocking write is done; there is no solution, except
	 hardware handshaking.

	 If we were not able to write any data, then we need to block
	 until we can write something.  The code used to simply do a
	 blocking write.  However, that fails when a bidirectional
	 protocol is permitted to push out enough bytes to fill the
	 entire pipe between the two communicating uucico processes.
	 They can both block on writing, because neither is reading.

	 In this case, we use select.  We could select on both the
	 read and write descriptor, but on some systems that would
	 lead to calling read on each byte, which would be very
	 inefficient.  Instead, we select only on the write
	 descriptor.  After the select succeeds or times out, we retry
	 the read.

	 Of course, some systems don't have select, and on some
	 systems that have it it doesn't work on terminal devices.  If
	 we can't use select, then we do a blocked write of a single
	 byte after setting an alarm.  We only write a single byte to
	 avoid any confusion as to whether or not the byte was
	 actually written.  */

      /* If we are running on standard input, we switch the file
	 descriptors by hand.  */
      if (q->ord >= 0)
	q->o = q->ord;

      /* Do an unblocked read.  */
      if (! fsblock (q, FALSE))
	return FALSE;

      /* Loop until we get something (error or data) other than an
	 acceptable EINTR.  */
      while (TRUE)
	{
	  /* If we've received a signal, don't continue.  */
	  if (FGOT_QUIT_SIGNAL ())
	    return FALSE;

#if HAVE_TLI
	  if (q->ftli)
	    {
	      int iflags;

	      cgot = t_rcv (q->o, zread, cread, &iflags);
	      if (cgot < 0)
		{
		  if (t_errno == TNODATA)
		    errno = EAGAIN;
		  else if (t_errno != TSYSERR)
		    {
		      ulog (LOG_ERROR, "t_rcv: %s",
			    (t_errno >= 0 && t_errno < t_nerr
			     ? t_errlist[t_errno]
			     : "unknown TLI error"));
		      return FALSE;
		    }
		}
	    }
	  else
#endif
	    cgot = read (q->o, zread, cread);

	  if (cgot >= 0)
	    break;
	  if (errno != EINTR)
	    break;

	  /* We got interrupted by a signal.  Log it.  */
	  ulog (LOG_ERROR, (const char *) NULL);
	}

      if (cgot < 0)
	{
	  if (errno != EAGAIN && errno != EWOULDBLOCK && errno != ENODATA)
	    {
	      ulog (LOG_ERROR, "read: %s", strerror (errno));
	      return FALSE;
	    }
	  cgot = 0;
	}

      cread -= cgot;
      zread += cgot;
      *pcread += cgot;

      /* If we've filled the read buffer, or we have nothing left to
	 write, return out.  */
      if (cread == 0 || cwrite == 0)
	return TRUE;

      /* The port is currently unblocked.  Do a write.  */
      cdo = cwrite;

#if ! HAVE_UNBLOCKED_WRITES
      if (q->fterminal && cdo > SINGLE_WRITE)
	cdo = SINGLE_WRITE;
#endif

      if (q->owr >= 0)
	q->o = q->owr;

      /* Loop until we get something besides EINTR.  */
      while (TRUE)
	{
	  /* If we've received a signal, don't continue.  */
	  if (FGOT_QUIT_SIGNAL ())
	    return FALSE;

#if HAVE_TLI
	  if (q->ftli)
	    {
	      cdid = t_snd (q->o, (char *) zwrite, cdo, 0);
	      if (cdid < 0)
		{
		  if (t_errno == TFLOW)
		    errno = EAGAIN;
		  else if (t_errno != TSYSERR)
		    {
		      ulog (LOG_ERROR, "t_snd: %s",
			    (t_errno >= 0 && t_errno < t_nerr
			     ? t_errlist[t_errno]
			     : "unknown TLI error"));
		      return FALSE;
		    }
		}
	    }
	  else
#endif
	    cdid = write (q->o, zwrite, cdo);

	  if (cdid >= 0)
	    break;
	  if (errno != EINTR)
	    break;

	  /* We got interrupted by a signal.  Log it.  */
	  ulog (LOG_ERROR, (const char *) NULL);
	}

      if (cdid < 0)
	{
	  if (errno != EAGAIN && errno != EWOULDBLOCK && errno != ENODATA)
	    {
	      ulog (LOG_ERROR, "write: %s", strerror (errno));
	      return FALSE;
	    }
	  cdid = 0;
	}

      if (cdid > 0)
	{
	  /* We wrote some data.  If we wrote everything, return out.
	     Otherwise loop around and do another read.  */
	  cwrite -= cdid;
	  zwrite += cdid;
	  *pcwrite += cdid;

	  if (cwrite == 0)
	    return TRUE;

	  czero = 0;
	}
      else
	{
#if HAVE_SELECT
	  struct timeval stime;
#ifdef FD_ZERO
	  fd_set smask;
#else
	  int smask;
#endif
	  int c;

	  /* We didn't write any data.  Call select.  We use a timeout
             long enough for 1024 bytes to be sent.  But we don't wait
             longer than the times it takes to receive cread bytes, in
             case our read buffer is small.
	       secs/kbyte == (1024 bytes/kbyte * 10 bits/byte) / baud bits/sec
	       usecs/kbyte == (((1024 bytes/kbyte * 1000000 usecs/sec)
	                        / baud bits/sec)
			       * 10 bits/byte)

	     */
	  if (q->fterminal)
	    {
	      unsigned long cwait;

	      cwait = 1024;
	      if (cwait > cread)
		cwait = cread;
	      stime.tv_sec = (cwait * 10) / q->ibaud;
	      stime.tv_usec = ((((cwait * 1000000) / q->ibaud) * 10)
			       % 1000000);
	    }
	  else
	    {
	      /* This is some sort of network connection.  We can't
                 estimate how long it will take to write data.  It
                 also doesn't matter as much, as most systems will
                 buffer much more incoming network data than they will
                 incoming serial data.  Sleep for a second, although
                 normally the select will return sonner because we can
                 write more data.  */
	      stime.tv_sec = 1;
	      stime.tv_usec = 0;
	    }

#ifdef FD_ZERO
	  FD_ZERO (&smask);
	  FD_SET (q->o, &smask);
#else
	  smask = 1 << q->o;
	  if (smask == 0)
	    ulog (LOG_FATAL, "fsysdep_conn_io: File descriptors too large");
#endif

	  /* If we've received a signal, don't continue.  */
	  if (FGOT_QUIT_SIGNAL ())
	    return FALSE;

	  DEBUG_MESSAGE0 (DEBUG_PORT, "fsysdep_conn_io: Calling select");

	  /* We don't bother to loop on EINTR.  If we get a signal, we
             just loop around and try the read and write again.  */
	  c = select (q->o + 1, (pointer) NULL, (pointer) &smask,
		      (pointer) NULL, &stime);
	  if (c < 0 && errno == EINTR)
	    {
	      /* We got interrupted by a signal.  Log it.  */
	      ulog (LOG_ERROR, (const char *) NULL);
	    }
	  else if (c >= 0)
	    {
	      /* The select either discovered that we could write
                 something, or it timed out.  Either way, we go around
                 the main read/write loop again.  */
	    }
	  else
#endif /* HAVE_SELECT */
	    {
	      int ierr;

	      /* Either the select failed for some reason other than
	      	 EINTR, or the system does not support select at all.
	      	 Fall back on a timed write.  We don't worry about why
	      	 the select might have failed, we just assume that it
	      	 will not succeed on this descriptor.  */

#if HAVE_RESTARTABLE_SYSCALLS
	      /* If HAVE_RESTARTABLE_SYSCALLS, then receiving an alarm
                 signal in the middle of a write will not cause the
                 write to return EINTR, and the only way to interrupt
                 the write is to longjmp out of it (see sysh.unx).
                 That is unreliable, because it means that we won't
                 know whether the byte was actually written or not.
                 However, I believe that the only system on which we
                 need to do this longjmp is BSD 4.2, and that system
                 supports select, so we should never execute this
                 case.  */
	      ulog (LOG_FATAL, "fsysdep_conn_io: Unsupported case; see code");
#endif

	      if (q->ord >= 0)
		q->o = q->ord;

	      if (! fsblock (q, TRUE))
		return FALSE;

	      DEBUG_MESSAGE0 (DEBUG_PORT, "fsysdep_conn_io: Blocking write");

	      if (q->owr >= 0)
		q->o = q->owr;

	      /* If we've received a signal, don't continue.  */
	      if (FGOT_QUIT_SIGNAL ())
		return FALSE;

	      /* Start up an alarm to interrupt the write.  Note that
                 we don't need to use the catch stuff, since we know
                 that HAVE_RESTARTABLE_SYSCALLS is 0.  */
	      usset_signal (SIGALRM, usalarm, TRUE, (boolean *) NULL);
	      if (q->fterminal)
		alarm ((int) ((long) 10240 / q->ibaud) + 1);
	      else
		alarm (1);

	      /* There is a race condition here: on a severely loaded
                 system, we could get the alarm before we start the
                 write call.  This would not be a disaster; often the
                 write will succeed anyhow.  */
#if HAVE_TLI
	      if (q->ftli)
		{
		  cdid = t_snd (q->o, (char *) zwrite, 1, 0);
		  if (cdid < 0 && t_errno != TSYSERR)
		    {
		      usset_signal (SIGALRM, SIG_IGN, TRUE, (boolean *) NULL);
		      alarm (0);
		      ulog (LOG_ERROR, "t_snd: %s",
			    (t_errno >= 0 && t_errno < t_nerr
			     ? t_errlist[t_errno]
			     : "unknown TLI error"));
		      return FALSE;
		    }
		}
	      else
#endif
		cdid = write (q->o, zwrite, 1);

	      ierr = errno;

	      /* Note that we don't really care whether the write
                 finished because the byte was written out or whether
                 it finished because the alarm was triggered.  Either
                 way, we are going to loop around and try another
                 read.  */

	      usset_signal (SIGALRM, SIG_IGN, TRUE, (boolean *) NULL);
	      alarm (0);

	      if (cdid < 0)
		{
		  if (ierr == EINTR)
		    {
		      /* We got interrupted by a signal.  Log it.  */
		      ulog (LOG_ERROR, (const char *) NULL);
		    }
		  else
		    {
		      ulog (LOG_ERROR, "write: %s", strerror (ierr));
		      return FALSE;
		    }
		}
	      else if (cdid == 0)
		{
		  /* On some systems write will return 0 if carrier is
		     lost.  If we fail to write anything ten times in
		     a row, we assume that this has happened.  This is
		     hacked in like this because there seems to be no
		     reliable way to tell exactly why the write
		     returned 0.  */
		  ++czero;
		  if (czero >= 10)
		    {
		      ulog (LOG_ERROR, "Line disconnected");
		      return FALSE;
		    }
		}
	      else
		{
		  cwrite -= cdid;
		  zwrite += cdid;
		  *pcwrite += cdid;
		  czero = 0;
		}
	    }
	}
    }
}

/* Send a break character to a serial port.  */

static boolean
fsserial_break (qconn)
     struct sconnection *qconn;
{
  struct ssysdep_conn *q;

  q = (struct ssysdep_conn *) qconn->psysdep;

#if HAVE_BSD_TTY
  (void) ioctl (q->o, TIOCSBRK, 0);
  sleep (2);
  (void) ioctl (q->o, TIOCCBRK, 0);
  return TRUE;
#endif /* HAVE_BSD_TTY */
#if HAVE_SYSV_TERMIO
  (void) ioctl (q->o, TCSBRK, 0);
  return TRUE;
#endif /* HAVE_SYSV_TERMIO */
#if HAVE_POSIX_TERMIOS
  return tcsendbreak (q->o, 0) == 0;
#endif /* HAVE_POSIX_TERMIOS */
}

/* Send a break character to a stdin port.  */

static boolean
fsstdin_break (qconn)
     struct sconnection *qconn;
{
  struct ssysdep_conn *qsysdep;

  qsysdep = (struct ssysdep_conn *) qconn->psysdep;
  qsysdep->o = qsysdep->owr;
  return fsserial_break (qconn);
}

/* Change the setting of a serial port.  */

/*ARGSUSED*/
static boolean
fsserial_set (qconn, tparity, tstrip, txonxoff)
     struct sconnection *qconn;
     enum tparitysetting tparity;
     enum tstripsetting tstrip;
     enum txonxoffsetting txonxoff;
{
  register struct ssysdep_conn *q;
  boolean fchanged, fdo;
  unsigned int iset = 0;
  unsigned int iclear = 0;

  q = (struct ssysdep_conn *) qconn->psysdep;

  if (! q->fterminal)
    return TRUE;

  fchanged = FALSE;

  /* Set the parity for output characters.  */

#if HAVE_BSD_TTY

  /* This will also cause parity detection on input characters.  */

  fdo = FALSE;
  switch (tparity)
    {
    case PARITYSETTING_DEFAULT:
      break;
    case PARITYSETTING_NONE:
#if HAVE_PARITY_BUG
      /* The Sony NEWS mishandles this for some reason.  */
      iset = 0;
      iclear = ANYP;
#else
      iset = ANYP;
      iclear = 0;
#endif
      fdo = TRUE;
      break;
    case PARITYSETTING_EVEN:
      iset = EVENP;
      iclear = ODDP;
      fdo = TRUE;
      break;
    case PARITYSETTING_ODD:
      iset = ODDP;
      iclear = EVENP;
      fdo = TRUE;
      break;
    case PARITYSETTING_MARK:
    case PARITYSETTING_SPACE:
      /* Not supported.  */
      break;
    }

  if (fdo)
    {
      if ((q->snew.stty.sg_flags & iset) != iset
	  || (q->snew.stty.sg_flags & iclear) != 0)
	{
	  q->snew.stty.sg_flags |= iset;
	  q->snew.stty.sg_flags &=~ iclear;
	  fchanged = TRUE;
	}
    }

#else /* ! HAVE_BSD_TTY */

  fdo = FALSE;
  switch (tparity)
    {
    case PARITYSETTING_DEFAULT:
      break;
    case PARITYSETTING_NONE:
      iset = CS8;
      iclear = PARENB | PARODD | (CSIZE &~ CS8);
      fdo = TRUE;
      break;
    case PARITYSETTING_EVEN:
      iset = PARENB | CS7;
      iclear = PARODD | (CSIZE &~ CS7);
      fdo = TRUE;
      break;
    case PARITYSETTING_ODD:
      iset = PARENB | PARODD | CS7;
      iclear = CSIZE &~ CS7;
      fdo = TRUE;
      break;
    case PARITYSETTING_MARK:
    case PARITYSETTING_SPACE:
      /* Not supported.  */
      break;
    }
	  
  if (fdo)
    {
      if ((q->snew.c_cflag & iset) != iset
	  || (q->snew.c_cflag & iclear) != 0)
	{
	  q->snew.c_cflag |= iset;
	  q->snew.c_cflag &=~ iclear;
	  fchanged = TRUE;
	}
    }

#endif /* ! HAVE_BSD_TTY */

  /* Set whether input characters are stripped to seven bits.  */

#if HAVE_BSD_TTY

#ifdef LPASS8
  {
    int i;

    i = LPASS8;
    if (tstrip == STRIPSETTING_EIGHTBITS)
      {
	i = LPASS8;
	(void) ioctl (q->o, TIOCLBIS, &i);
      }
    else if (tstrip == STRIPSETTING_SEVENBITS)
      {
	i = LPASS8;
	(void) ioctl (q->o, TIOCLBIC, &i);
      }
  }
#endif

#else /* ! HAVE_BSD_TTY */      

  fdo = FALSE;
  switch (tstrip)
    {
    case STRIPSETTING_DEFAULT:
      break;
    case STRIPSETTING_EIGHTBITS:
      iset = 0;
      iclear = ISTRIP;
      fdo = TRUE;
      break;
    case STRIPSETTING_SEVENBITS:
      iset = ISTRIP;
      iclear = 0;
      fdo = TRUE;
      break;
    }

  if (fdo)
    {
      if ((q->snew.c_iflag & iset) != iset
	  || (q->snew.c_iflag & iclear) != 0)
	{
	  q->snew.c_iflag |= iset;
	  q->snew.c_iflag &=~ iclear;
	  fchanged = TRUE;
	}
    }

#endif /* ! HAVE_BSD_TTY */

  /* Set XON/XOFF handshaking.  */

#if HAVE_BSD_TTY

  fdo = FALSE;
  switch (txonxoff)
    {
    case XONXOFF_DEFAULT:
      break;
    case XONXOFF_OFF:
      iset = RAW;
      iclear = TANDEM | CBREAK;
      fdo = TRUE;
      break;
    case XONXOFF_ON:
      iset = CBREAK | TANDEM;
      iclear = RAW;
      fdo = TRUE;
      break;
    }

  if (fdo)
    {
      if ((q->snew.stty.sg_flags & iset) != iset
	  || (q->snew.stty.sg_flags & iclear) != 0)
	{
	  q->snew.stty.sg_flags |= iset;
	  q->snew.stty.sg_flags &=~ iclear;
	  fchanged = TRUE;
	}
    }

#else /* ! HAVE_BSD_TTY */

  fdo = FALSE;
  switch (txonxoff)
    {
    case XONXOFF_DEFAULT:
      break;
    case XONXOFF_OFF:
      iset = 0;
      iclear = IXON | IXOFF;
      fdo = TRUE;
      break;
    case XONXOFF_ON:
#ifdef CRTSCTS
#if HAVE_POSIX_TERMIOS
      /* This is system dependent, but I haven't figured out a good
	 way around it yet.  If we are doing hardware flow control, we
	 don't send XON/XOFF characters but we do recognize them.  */
      if ((q->snew.c_cflag & CRTSCTS) != 0)
	{
	  iset = IXON;
	  iclear = IXOFF;
	  fdo = TRUE;
	  break;
	}
#endif /* HAVE_POSIX_TERMIOS */
#endif /* defined (CRTSCTS) */
#ifdef CRTSFL
      if ((q->snew.c_cflag & CRTSFL) != 0)
	{
	  iset = IXON;
	  iclear = IXOFF;
	  /* SCO says we cant have CRTSFL **and** RTSFLOW/CTSFLOW */
#ifdef RTSFLOW
	  iclear |= RTSFLOW;
#endif
#ifdef CTSFLOW
	  iclear |= CTSFLOW;
#endif
	  fdo = TRUE;
	  break;
	}
#endif /* defined(CRTSFL) */
      iset = IXON | IXOFF;
      iclear = 0;
      fdo = TRUE;
      break;
    }

  if (fdo)
    {
      if ((q->snew.c_iflag & iset) != iset
	  || (q->snew.c_iflag & iclear) != 0)
	{
	  q->snew.c_iflag |= iset;
	  q->snew.c_iflag &=~ iclear;
	  fchanged = TRUE;
	}
    }

#endif /* ! HAVE_BSD_TTY */

  if (fchanged)
    {
      if (! fsetterminfodrain (q->o, &q->snew))
	{
	  ulog (LOG_ERROR, "Can't change terminal settings: %s",
		strerror (errno));
	  return FALSE;
	}
    }

#if HAVE_BSD_TTY
  if (txonxoff == XONXOFF_ON
      && (q->snew.stty.sg_flags & ANYP) == ANYP)
    {
      int i;

      /* At least on Ultrix, we seem to have to set LLITOUT and
	 LPASS8.  This shouldn't foul things up anywhere else.  As far
	 as I can tell, this has to be done after setting the terminal
	 into cbreak mode, not before.  */
#ifndef LLITOUT
#define LLITOUT 0
#endif
#ifndef LPASS8
#define LPASS8 0
#endif
#ifndef LAUTOFLOW
#define LAUTOFLOW 0
#endif
      i = LLITOUT | LPASS8 | LAUTOFLOW;
      (void) ioctl (q->o, TIOCLBIS, &i);

#if HAVE_STRIP_BUG
      /* Ultrix 4.0 has a peculiar problem: setting CBREAK always
	 causes input characters to be stripped.  I hope this does not
	 apply to other BSD systems.  It is possible to work around
	 this by using the termio call.  I wish this sort of stuff was
	 not necessary!!!  */
      {
	struct termio s;

	if (ioctl (q->o, TCGETA, &s) >= 0)
	  {
	    s.c_iflag &=~ ISTRIP;
	    (void) ioctl (q->o, TCSETA, &s);
	  }
      }
#endif /* HAVE_STRIP_BUG */
    }
#endif /* HAVE_BSD_TTY */

  return TRUE;
}

/* Change settings of a stdin port.  */

static boolean
fsstdin_set (qconn, tparity, tstrip, txonxoff)
     struct sconnection *qconn;
     enum tparitysetting tparity;
     enum tstripsetting tstrip;
     enum txonxoffsetting txonxoff;
{
  struct ssysdep_conn *qsysdep;

  qsysdep = (struct ssysdep_conn *) qconn->psysdep;
  qsysdep->o = qsysdep->ord;
  return fsserial_set (qconn, tparity, tstrip, txonxoff);
}

/* Run a chat program.  */

static boolean
fsrun_chat (oread, owrite, pzprog)
     int oread;
     int owrite;
     char **pzprog;
{
  int aidescs[3];
  FILE *e;
  pid_t ipid;
  char *z;
  size_t c;

  aidescs[0] = oread;
  aidescs[1] = owrite;
  aidescs[2] = SPAWN_READ_PIPE;

  /* Pass fkeepuid, fkeepenv and fshell as TRUE.  This puts the
     responsibility of maintaing security on the chat program.  */
  ipid = ixsspawn ((const char **) pzprog, aidescs, TRUE, TRUE,
		   (const char *) NULL, FALSE, TRUE, (const char *) NULL,
		   (const char *) NULL, (const char *) NULL);
  if (ipid < 0)
    {
      ulog (LOG_ERROR, "ixsspawn (%s): %s", pzprog[0], strerror (errno));
      return FALSE;
    }

  e = fdopen (aidescs[2], (char *) "r");
  if (e == NULL)
    {
      ulog (LOG_ERROR, "fdopen: %s", strerror (errno));
      (void) close (aidescs[2]);
      (void) kill (ipid, SIGKILL);
      (void) ixswait ((unsigned long) ipid, (const char *) NULL);
      return FALSE;
    }

  /* The FILE e now is attached to stderr of the program.  Forward
     every line the program outputs to the log file.  */
  z = NULL;
  c = 0;
  while (getline (&z, &c, e) > 0)
    {
      size_t clen;

      clen = strlen (z);
      if (z[clen - 1] == '\n')
	z[clen - 1] = '\0';
      if (*z != '\0')
	ulog (LOG_NORMAL, "chat: %s", z);
    }

  xfree ((pointer) z);
  (void) fclose (e);

  return ixswait ((unsigned long) ipid, "Chat program") == 0;
}

/* Run a chat program on a port using separate read/write file
   descriptors.  */

boolean
fsdouble_chat (qconn, pzprog)
     struct sconnection *qconn;
     char **pzprog;
{
  struct ssysdep_conn *qsysdep;
  boolean fret;

  qsysdep = (struct ssysdep_conn *) qconn->psysdep;
  fret = fsrun_chat (qsysdep->ord, qsysdep->owr, pzprog);
  if (qsysdep->fterminal)
    (void) fgetterminfo (qsysdep->ord, &qsysdep->snew);
  return fret;
}

/* Run a chat program on any general type of connection.  */

boolean
fsysdep_conn_chat (qconn, pzprog)
     struct sconnection *qconn;
     char **pzprog;
{
  struct ssysdep_conn *qsysdep;
  boolean fret;

  qsysdep = (struct ssysdep_conn *) qconn->psysdep;
  fret = fsrun_chat (qsysdep->o, qsysdep->o, pzprog);
  if (qsysdep->fterminal)
    (void) fgetterminfo (qsysdep->o, &qsysdep->snew);
  return fret;
}

/* Return baud rate of a serial port.  */

static long
isserial_baud (qconn)
     struct sconnection *qconn;
{
  struct ssysdep_conn *qsysdep;

  qsysdep = (struct ssysdep_conn *) qconn->psysdep;
  return qsysdep->ibaud;
}