aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/cvs/src/client.c
blob: 0b57b35408f9e830bc79cdc12ee86ffa66881956 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
/* JT thinks BeOS is worth the trouble. */

/* CVS client-related stuff.

   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, 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.  */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */

#include <assert.h>
#include "cvs.h"
#include "getline.h"
#include "edit.h"
#include "buffer.h"

#ifdef CLIENT_SUPPORT

#include "md5.h"

#if defined(AUTH_CLIENT_SUPPORT) || HAVE_KERBEROS || defined(SOCK_ERRNO) || defined(SOCK_STRERROR)
#  ifdef HAVE_WINSOCK_H
#    include <winsock.h>
#  else /* No winsock.h */
#    include <sys/socket.h>
#    include <netinet/in.h>
#    include <arpa/inet.h>
#    include <netdb.h>
#  endif /* No winsock.h */
#endif

/* If SOCK_ERRNO is defined, then send()/recv() and other socket calls
   do not set errno, but that this macro should be used to obtain an
   error code.  This probably doesn't make sense unless
   NO_SOCKET_TO_FD is also defined. */
#ifndef SOCK_ERRNO
#define SOCK_ERRNO errno
#endif

/* If SOCK_STRERROR is defined, then the error codes returned by
   socket operations are not known to strerror, and this macro must be
   used instead to convert those error codes to strings. */
#ifndef SOCK_STRERROR
#  define SOCK_STRERROR strerror

#  if STDC_HEADERS
#    include <string.h>
#  endif

#  ifndef strerror
extern char *strerror ();
#  endif
#endif /* ! SOCK_STRERROR */

#if HAVE_KERBEROS
#define CVS_PORT 1999

#include <krb.h>

extern char *krb_realmofhost ();
#ifndef HAVE_KRB_GET_ERR_TEXT
#define krb_get_err_text(status) krb_err_txt[status]
#endif /* HAVE_KRB_GET_ERR_TEXT */

/* Information we need if we are going to use Kerberos encryption.  */
static C_Block kblock;
static Key_schedule sched;

#endif /* HAVE_KERBEROS */

#ifdef HAVE_GSSAPI

# include "xgssapi.h"

/* This is needed for GSSAPI encryption.  */
static gss_ctx_id_t gcontext;

static int connect_to_gserver PROTO((int, struct hostent *));

#endif /* HAVE_GSSAPI */

static void add_prune_candidate PROTO((char *));

/* All the commands.  */
int add PROTO((int argc, char **argv));
int admin PROTO((int argc, char **argv));
int checkout PROTO((int argc, char **argv));
int commit PROTO((int argc, char **argv));
int diff PROTO((int argc, char **argv));
int history PROTO((int argc, char **argv));
int import PROTO((int argc, char **argv));
int cvslog PROTO((int argc, char **argv));
int patch PROTO((int argc, char **argv));
int release PROTO((int argc, char **argv));
int cvsremove PROTO((int argc, char **argv));
int rtag PROTO((int argc, char **argv));
int status PROTO((int argc, char **argv));
int tag PROTO((int argc, char **argv));
int update PROTO((int argc, char **argv));

/* All the response handling functions.  */
static void handle_ok PROTO((char *, int));
static void handle_error PROTO((char *, int));
static void handle_valid_requests PROTO((char *, int));
static void handle_checked_in PROTO((char *, int));
static void handle_new_entry PROTO((char *, int));
static void handle_checksum PROTO((char *, int));
static void handle_copy_file PROTO((char *, int));
static void handle_updated PROTO((char *, int));
static void handle_merged PROTO((char *, int));
static void handle_patched PROTO((char *, int));
static void handle_rcs_diff PROTO((char *, int));
static void handle_removed PROTO((char *, int));
static void handle_remove_entry PROTO((char *, int));
static void handle_set_static_directory PROTO((char *, int));
static void handle_clear_static_directory PROTO((char *, int));
static void handle_set_sticky PROTO((char *, int));
static void handle_clear_sticky PROTO((char *, int));
static void handle_set_checkin_prog PROTO((char *, int));
static void handle_set_update_prog PROTO((char *, int));
static void handle_module_expansion PROTO((char *, int));
static void handle_wrapper_rcs_option PROTO((char *, int));
static void handle_m PROTO((char *, int));
static void handle_e PROTO((char *, int));
static void handle_f PROTO((char *, int));
static void handle_notified PROTO((char *, int));

static size_t try_read_from_server PROTO ((char *, size_t));
#endif /* CLIENT_SUPPORT */

#ifdef CLIENT_SUPPORT

/* We need to keep track of the list of directories we've sent to the
   server.  This list, along with the current CVSROOT, will help us
   decide which command-line arguments to send.  */
List *dirs_sent_to_server = NULL;

static int is_arg_a_parent_or_listed_dir PROTO((Node *, void *));

static int
is_arg_a_parent_or_listed_dir (n, d)
    Node *n;
    void *d;
{
    char *directory = n->key;	/* name of the dir sent to server */
    char *this_argv_elem = (char *) d;	/* this argv element */

    /* Say we should send this argument if the argument matches the
       beginning of a directory name sent to the server.  This way,
       the server will know to start at the top of that directory
       hierarchy and descend. */

    if (strncmp (directory, this_argv_elem, strlen (this_argv_elem)) == 0)
	return 1;

    return 0;
}

static int arg_should_not_be_sent_to_server PROTO((char *));

/* Return nonzero if this argument should not be sent to the
   server. */

static int
arg_should_not_be_sent_to_server (arg)
    char *arg;
{
    /* Decide if we should send this directory name to the server.  We
       should always send argv[i] if:

       1) the list of directories sent to the server is empty (as it
       will be for checkout, etc.).

       2) the argument is "."

       3) the argument is a file in the cwd and the cwd is checked out
       from the current root

       4) the argument lies within one of the paths in
       dirs_sent_to_server.

       */

    if (list_isempty (dirs_sent_to_server))
	return 0;		/* always send it */

    if (strcmp (arg, ".") == 0)
	return 0;		/* always send it */

    /* We should send arg if it is one of the directories sent to the
       server or the parent of one; this tells the server to descend
       the hierarchy starting at this level. */
    if (isdir (arg))
    {
	if (walklist (dirs_sent_to_server, is_arg_a_parent_or_listed_dir, arg))
	    return 0;

	/* If arg wasn't a parent, we don't know anything about it (we
	   would have seen something related to it during the
	   send_files phase).  Don't send it.  */
	return 1;
    }

    /* Try to decide whether we should send arg to the server by
       checking the contents of the corresponding CVSADM directory. */
    {
	char *t, *this_root;

	/* Calculate "dirname arg" */
	for (t = arg + strlen (arg) - 1; t >= arg; t--)
	{
	    if (ISDIRSEP(*t))
		break;
	}

	/* Now we're either poiting to the beginning of the
	   string, or we found a path separator. */
	if (t >= arg)
	{
	    /* Found a path separator.  */
	    char c = *t;
	    *t = '\0';
	    
	    /* First, check to see if we sent this directory to the
               server, because it takes less time than actually
               opening the stuff in the CVSADM directory.  */
	    if (walklist (dirs_sent_to_server, is_arg_a_parent_or_listed_dir,
			  arg))
	    {
		*t = c;		/* make sure to un-truncate the arg */
		return 0;
	    }

	    /* Since we didn't find it in the list, check the CVSADM
               files on disk.  */
	    this_root = Name_Root (arg, (char *) NULL);
	    *t = c;
	}
	else
	{
	    /* We're at the beginning of the string.  Look at the
               CVSADM files in cwd.  */
	    this_root = Name_Root ((char *) NULL, (char *) NULL);
	}

	/* Now check the value for root. */
	if (this_root && current_parsed_root
	    && (strcmp (this_root, current_parsed_root->original) != 0))
	{
	    /* Don't send this, since the CVSROOTs don't match. */
	    free (this_root);
	    return 1;
	}
	free (this_root);
    }
    
    /* OK, let's send it. */
    return 0;
}


#endif /* CLIENT_SUPPORT */

#if defined(CLIENT_SUPPORT) || defined(SERVER_SUPPORT)

/* Shared with server.  */

/*
 * Return a malloc'd, '\0'-terminated string
 * corresponding to the mode in SB.
 */
char *
#ifdef __STDC__
mode_to_string (mode_t mode)
#else /* ! __STDC__ */
mode_to_string (mode)
	mode_t mode;
#endif /* __STDC__ */
{
    char buf[18], u[4], g[4], o[4];
    int i;

    i = 0;
    if (mode & S_IRUSR) u[i++] = 'r';
    if (mode & S_IWUSR) u[i++] = 'w';
    if (mode & S_IXUSR) u[i++] = 'x';
    u[i] = '\0';

    i = 0;
    if (mode & S_IRGRP) g[i++] = 'r';
    if (mode & S_IWGRP) g[i++] = 'w';
    if (mode & S_IXGRP) g[i++] = 'x';
    g[i] = '\0';

    i = 0;
    if (mode & S_IROTH) o[i++] = 'r';
    if (mode & S_IWOTH) o[i++] = 'w';
    if (mode & S_IXOTH) o[i++] = 'x';
    o[i] = '\0';

    sprintf(buf, "u=%s,g=%s,o=%s", u, g, o);
    return xstrdup(buf);
}

/*
 * Change mode of FILENAME to MODE_STRING.
 * Returns 0 for success or errno code.
 * If RESPECT_UMASK is set, then honor the umask.
 */
int
change_mode (filename, mode_string, respect_umask)
    char *filename;
    char *mode_string;
    int respect_umask;
{
#ifdef CHMOD_BROKEN
    char *p;
    int writeable = 0;

    /* We can only distinguish between
         1) readable
         2) writeable
         3) Picasso's "Blue Period"
       We handle the first two. */
    p = mode_string;
    while (*p != '\0')
    {
	if ((p[0] == 'u' || p[0] == 'g' || p[0] == 'o') && p[1] == '=')
	{
	    char *q = p + 2;
	    while (*q != ',' && *q != '\0')
	    {
		if (*q == 'w')
		    writeable = 1;
		++q;
	    }
	}
	/* Skip to the next field.  */
	while (*p != ',' && *p != '\0')
	    ++p;
	if (*p == ',')
	    ++p;
    }

    /* xchmod honors the umask for us.  In the !respect_umask case, we
       don't try to cope with it (probably to handle that well, the server
       needs to deal with modes in data structures, rather than via the
       modes in temporary files).  */
    xchmod (filename, writeable);
	return 0;

#else /* ! CHMOD_BROKEN */

    char *p;
    mode_t mode = 0;
    mode_t oumask;

    p = mode_string;
    while (*p != '\0')
    {
	if ((p[0] == 'u' || p[0] == 'g' || p[0] == 'o') && p[1] == '=')
	{
	    int can_read = 0, can_write = 0, can_execute = 0;
	    char *q = p + 2;
	    while (*q != ',' && *q != '\0')
	    {
		if (*q == 'r')
		    can_read = 1;
		else if (*q == 'w')
		    can_write = 1;
		else if (*q == 'x')
		    can_execute = 1;
		++q;
	    }
	    if (p[0] == 'u')
	    {
		if (can_read)
		    mode |= S_IRUSR;
		if (can_write)
		    mode |= S_IWUSR;
		if (can_execute)
		    mode |= S_IXUSR;
	    }
	    else if (p[0] == 'g')
	    {
		if (can_read)
		    mode |= S_IRGRP;
		if (can_write)
		    mode |= S_IWGRP;
		if (can_execute)
		    mode |= S_IXGRP;
	    }
	    else if (p[0] == 'o')
	    {
		if (can_read)
		    mode |= S_IROTH;
		if (can_write)
		    mode |= S_IWOTH;
		if (can_execute)
		    mode |= S_IXOTH;
	    }
	}
	/* Skip to the next field.  */
	while (*p != ',' && *p != '\0')
	    ++p;
	if (*p == ',')
	    ++p;
    }

    if (respect_umask)
    {
	oumask = umask (0);
	(void) umask (oumask);
	mode &= ~oumask;
    }

    if (chmod (filename, mode) < 0)
	return errno;
    return 0;
#endif /* ! CHMOD_BROKEN */
}

#endif /* CLIENT_SUPPORT or SERVER_SUPPORT */

#ifdef CLIENT_SUPPORT

int client_prune_dirs;

static List *ignlist = (List *) NULL;

/* Buffer to write to the server.  */
static struct buffer *to_server;
/* The stream underlying to_server, if we are using a stream.  */
static FILE *to_server_fp;

/* Buffer used to read from the server.  */
static struct buffer *from_server;
/* The stream underlying from_server, if we are using a stream.  */
static FILE *from_server_fp;

/* Process ID of rsh subprocess.  */
static int rsh_pid = -1;


/* We want to be able to log data sent between us and the server.  We
   do it using log buffers.  Each log buffer has another buffer which
   handles the actual I/O, and a file to log information to.

   This structure is the closure field of a log buffer.  */

struct log_buffer
{
    /* The underlying buffer.  */
    struct buffer *buf;
    /* The file to log information to.  */
    FILE *log;
};

static struct buffer *log_buffer_initialize
  PROTO((struct buffer *, FILE *, int, void (*) (struct buffer *)));
static int log_buffer_input PROTO((void *, char *, int, int, int *));
static int log_buffer_output PROTO((void *, const char *, int, int *));
static int log_buffer_flush PROTO((void *));
static int log_buffer_block PROTO((void *, int));
static int log_buffer_shutdown PROTO((void *));

/* Create a log buffer.  */

static struct buffer *
log_buffer_initialize (buf, fp, input, memory)
     struct buffer *buf;
     FILE *fp;
     int input;
     void (*memory) PROTO((struct buffer *));
{
    struct log_buffer *n;

    n = (struct log_buffer *) xmalloc (sizeof *n);
    n->buf = buf;
    n->log = fp;
    return buf_initialize (input ? log_buffer_input : NULL,
			   input ? NULL : log_buffer_output,
			   input ? NULL : log_buffer_flush,
			   log_buffer_block,
			   log_buffer_shutdown,
			   memory,
			   n);
}

/* The input function for a log buffer.  */

static int
log_buffer_input (closure, data, need, size, got)
     void *closure;
     char *data;
     int need;
     int size;
     int *got;
{
    struct log_buffer *lb = (struct log_buffer *) closure;
    int status;
    size_t n_to_write;

    if (lb->buf->input == NULL)
	abort ();

    status = (*lb->buf->input) (lb->buf->closure, data, need, size, got);
    if (status != 0)
	return status;

    if (*got > 0)
    {
	n_to_write = *got;
	if (fwrite (data, 1, n_to_write, lb->log) != n_to_write)
	    error (0, errno, "writing to log file");
    }

    return 0;
}

/* The output function for a log buffer.  */

static int
log_buffer_output (closure, data, have, wrote)
     void *closure;
     const char *data;
     int have;
     int *wrote;
{
    struct log_buffer *lb = (struct log_buffer *) closure;
    int status;
    size_t n_to_write;

    if (lb->buf->output == NULL)
	abort ();

    status = (*lb->buf->output) (lb->buf->closure, data, have, wrote);
    if (status != 0)
	return status;

    if (*wrote > 0)
    {
	n_to_write = *wrote;
	if (fwrite (data, 1, n_to_write, lb->log) != n_to_write)
	    error (0, errno, "writing to log file");
    }

    return 0;
}

/* The flush function for a log buffer.  */

static int
log_buffer_flush (closure)
     void *closure;
{
    struct log_buffer *lb = (struct log_buffer *) closure;

    if (lb->buf->flush == NULL)
	abort ();

    /* We don't really have to flush the log file here, but doing it
       will let tail -f on the log file show what is sent to the
       network as it is sent.  */
    if (fflush (lb->log) != 0)
        error (0, errno, "flushing log file");

    return (*lb->buf->flush) (lb->buf->closure);
}

/* The block function for a log buffer.  */

static int
log_buffer_block (closure, block)
     void *closure;
     int block;
{
    struct log_buffer *lb = (struct log_buffer *) closure;

    if (block)
	return set_block (lb->buf);
    else
	return set_nonblock (lb->buf);
}

/* The shutdown function for a log buffer.  */

static int
log_buffer_shutdown (closure)
     void *closure;
{
    struct log_buffer *lb = (struct log_buffer *) closure;
    int retval;

    retval = buf_shutdown (lb->buf);
    if (fclose (lb->log) < 0)
	error (0, errno, "closing log file");
    return retval;
}

#ifdef NO_SOCKET_TO_FD

/* Under certain circumstances, we must communicate with the server
   via a socket using send() and recv().  This is because under some
   operating systems (OS/2 and Windows 95 come to mind), a socket
   cannot be converted to a file descriptor -- it must be treated as a
   socket and nothing else.
   
   We may also need to deal with socket routine error codes differently
   in these cases.  This is handled through the SOCK_ERRNO and
   SOCK_STRERROR macros. */

static int use_socket_style = 0;
static int server_sock;

/* These routines implement a buffer structure which uses send and
   recv.  The buffer is always in blocking mode so we don't implement
   the block routine.  */

/* Note that it is important that these routines always handle errors
   internally and never return a positive errno code, since it would in
   general be impossible for the caller to know in general whether any
   error code came from a socket routine (to decide whether to use
   SOCK_STRERROR or simply strerror to print an error message). */

/* We use an instance of this structure as the closure field.  */

struct socket_buffer
{
    /* The socket number.  */
    int socket;
};

static struct buffer *socket_buffer_initialize
  PROTO ((int, int, void (*) (struct buffer *)));
static int socket_buffer_input PROTO((void *, char *, int, int, int *));
static int socket_buffer_output PROTO((void *, const char *, int, int *));
static int socket_buffer_flush PROTO((void *));

/* Create a buffer based on a socket.  */

static struct buffer *
socket_buffer_initialize (socket, input, memory)
     int socket;
     int input;
     void (*memory) PROTO((struct buffer *));
{
    struct socket_buffer *n;

    n = (struct socket_buffer *) xmalloc (sizeof *n);
    n->socket = socket;
    return buf_initialize (input ? socket_buffer_input : NULL,
			   input ? NULL : socket_buffer_output,
			   input ? NULL : socket_buffer_flush,
			   (int (*) PROTO((void *, int))) NULL,
			   (int (*) PROTO((void *))) NULL,
			   memory,
			   n);
}

/* The buffer input function for a buffer built on a socket.  */

static int
socket_buffer_input (closure, data, need, size, got)
     void *closure;
     char *data;
     int need;
     int size;
     int *got;
{
    struct socket_buffer *sb = (struct socket_buffer *) closure;
    int nbytes;

    /* I believe that the recv function gives us exactly the semantics
       we want.  If there is a message, it returns immediately with
       whatever it could get.  If there is no message, it waits until
       one comes in.  In other words, it is not like read, which in
       blocking mode normally waits until all the requested data is
       available.  */

    *got = 0;

    do
    {

	/* Note that for certain (broken?) networking stacks, like
	   VMS's UCX (not sure what version, problem reported with
	   recv() in 1997), and (according to windows-NT/config.h)
	   Windows NT 3.51, we must call recv or send with a
	   moderately sized buffer (say, less than 200K or something),
	   or else there may be network errors (somewhat hard to
	   produce, e.g. WAN not LAN or some such).  buf_read_data
	   makes sure that we only recv() BUFFER_DATA_SIZE bytes at
	   a time.  */

	nbytes = recv (sb->socket, data, size, 0);
	if (nbytes < 0)
	    error (1, 0, "reading from server: %s", SOCK_STRERROR (SOCK_ERRNO));
	if (nbytes == 0)
	{
	    /* End of file (for example, the server has closed
	       the connection).  If we've already read something, we
	       just tell the caller about the data, not about the end of
	       file.  If we've read nothing, we return end of file.  */
	    if (*got == 0)
		return -1;
	    else
		return 0;
	}
	need -= nbytes;
	size -= nbytes;
	data += nbytes;
	*got += nbytes;
    }
    while (need > 0);

    return 0;
}

/* The buffer output function for a buffer built on a socket.  */

static int
socket_buffer_output (closure, data, have, wrote)
     void *closure;
     const char *data;
     int have;
     int *wrote;
{
    struct socket_buffer *sb = (struct socket_buffer *) closure;

    *wrote = have;

    /* See comment in socket_buffer_input regarding buffer size we pass
       to send and recv.  */

#ifdef SEND_NEVER_PARTIAL
    /* If send() never will produce a partial write, then just do it.  This
       is needed for systems where its return value is something other than
       the number of bytes written.  */
    if (send (sb->socket, data, have, 0) < 0)
	error (1, 0, "writing to server socket: %s", SOCK_STRERROR (SOCK_ERRNO));
#else
    while (have > 0)
    {
	int nbytes;

	nbytes = send (sb->socket, data, have, 0);
	if (nbytes < 0)
	    error (1, 0, "writing to server socket: %s", SOCK_STRERROR (SOCK_ERRNO));

	have -= nbytes;
	data += nbytes;
    }
#endif

    return 0;
}

/* The buffer flush function for a buffer built on a socket.  */

/*ARGSUSED*/
static int
socket_buffer_flush (closure)
     void *closure;
{
    /* Nothing to do.  Sockets are always flushed.  */
    return 0;
}

#endif /* NO_SOCKET_TO_FD */

/*
 * Read a line from the server.  Result does not include the terminating \n.
 *
 * Space for the result is malloc'd and should be freed by the caller.
 *
 * Returns number of bytes read.
 */
static int
read_line (resultp)
    char **resultp;
{
    int status;
    char *result;
    int len;

    status = buf_flush (to_server, 1);
    if (status != 0)
	error (1, status, "writing to server");

    status = buf_read_line (from_server, &result, &len);
    if (status != 0)
    {
	if (status == -1)
	    error (1, 0, "end of file from server (consult above messages if any)");
	else if (status == -2)
	    error (1, 0, "out of memory");
	else
	    error (1, status, "reading from server");
    }

    if (resultp != NULL)
	*resultp = result;
    else
	free (result);

    return len;
}

#endif /* CLIENT_SUPPORT */


#if defined(CLIENT_SUPPORT) || defined(SERVER_SUPPORT)

/*
 * Zero if compression isn't supported or requested; non-zero to indicate
 * a compression level to request from gzip.
 */
int gzip_level;

/*
 * Level of compression to use when running gzip on a single file.
 */
int file_gzip_level;

#endif /* CLIENT_SUPPORT or SERVER_SUPPORT */

#ifdef CLIENT_SUPPORT

/*
 * The Repository for the top level of this command (not necessarily
 * the CVSROOT, just the current directory at the time we do it).
 */
static char *toplevel_repos = NULL;

/* Working directory when we first started.  Note: we could speed things
   up on some systems by using savecwd.h here instead of just always
   storing a name.  */
char *toplevel_wd;

static void
handle_ok (args, len)
    char *args;
    int len;
{
    return;
}

static void
handle_error (args, len)
    char *args;
    int len;
{
    int something_printed;
    
    /*
     * First there is a symbolic error code followed by a space, which
     * we ignore.
     */
    char *p = strchr (args, ' ');
    if (p == NULL)
    {
	error (0, 0, "invalid data from cvs server");
	return;
    }
    ++p;

    /* Next we print the text of the message from the server.  We
       probably should be prefixing it with "server error" or some
       such, because if it is something like "Out of memory", the
       current behavior doesn't say which machine is out of
       memory.  */

    len -= p - args;
    something_printed = 0;
    for (; len > 0; --len)
    {
	something_printed = 1;
	putc (*p++, stderr);
    }
    if (something_printed)
	putc ('\n', stderr);
}

static void
handle_valid_requests (args, len)
    char *args;
    int len;
{
    char *p = args;
    char *q;
    struct request *rq;
    do
    {
	q = strchr (p, ' ');
	if (q != NULL)
	    *q++ = '\0';
	for (rq = requests; rq->name != NULL; ++rq)
	{
	    if (strcmp (rq->name, p) == 0)
		break;
	}
	if (rq->name == NULL)
	    /*
	     * It is a request we have never heard of (and thus never
	     * will want to use).  So don't worry about it.
	     */
	    ;
	else
	{
	    if (rq->flags & RQ_ENABLEME)
	    {
		/*
		 * Server wants to know if we have this, to enable the
		 * feature.
		 */
		send_to_server (rq->name, 0);
                send_to_server ("\012", 0);
	    }
	    else
		rq->flags |= RQ_SUPPORTED;
	}
	p = q;
    } while (q != NULL);
    for (rq = requests; rq->name != NULL; ++rq)
    {
	if ((rq->flags & RQ_SUPPORTED)
	    || (rq->flags & RQ_ENABLEME))
	    continue;
	if (rq->flags & RQ_ESSENTIAL)
	    error (1, 0, "request `%s' not supported by server", rq->name);
    }
}

/* This variable holds the result of Entries_Open, so that we can
   close Entries_Close on it when we move on to a new directory, or
   when we finish.  */
static List *last_entries;

/*
 * Do all the processing for PATHNAME, where pathname consists of the
 * repository and the filename.  The parameters we pass to FUNC are:
 * DATA is just the DATA parameter which was passed to
 * call_in_directory; ENT_LIST is a pointer to an entries list (which
 * we manage the storage for); SHORT_PATHNAME is the pathname of the
 * file relative to the (overall) directory in which the command is
 * taking place; and FILENAME is the filename portion only of
 * SHORT_PATHNAME.  When we call FUNC, the curent directory points to
 * the directory portion of SHORT_PATHNAME.  */

static char *last_dir_name;

static void
call_in_directory (pathname, func, data)
    char *pathname;
    void (*func) PROTO((char *data, List *ent_list, char *short_pathname,
			  char *filename));
    char *data;
{
    char *dir_name;
    char *filename;
    /* This is what we get when we hook up the directory (working directory
       name) from PATHNAME with the filename from REPOSNAME.  For example:
       pathname: ccvs/src/
       reposname: /u/src/master/ccvs/foo/ChangeLog
       short_pathname: ccvs/src/ChangeLog
       */
    char *short_pathname;
    char *p;

    /*
     * Do the whole descent in parallel for the repositories, so we
     * know what to put in CVS/Repository files.  I'm not sure the
     * full hair is necessary since the server does a similar
     * computation; I suspect that we only end up creating one
     * directory at a time anyway.
     *
     * Also note that we must *only* worry about this stuff when we
     * are creating directories; `cvs co foo/bar; cd foo/bar; cvs co
     * CVSROOT; cvs update' is legitimate, but in this case
     * foo/bar/CVSROOT/CVS/Repository is not a subdirectory of
     * foo/bar/CVS/Repository.
     */
    char *reposname;
    char *short_repos;
    char *reposdirname;
    char *rdirp;
    int reposdirname_absolute;

    reposname = NULL;
    read_line (&reposname);
    assert (reposname != NULL);

    reposdirname_absolute = 0;
    if (strncmp (reposname, toplevel_repos, strlen (toplevel_repos)) != 0)
    {
	reposdirname_absolute = 1;
	short_repos = reposname;
    }
    else
    {
	short_repos = reposname + strlen (toplevel_repos) + 1;
	if (short_repos[-1] != '/')
	{
	    reposdirname_absolute = 1;
	    short_repos = reposname;
	}
    }
    reposdirname = xstrdup (short_repos);
    p = strrchr (reposdirname, '/');
    if (p == NULL)
    {
	reposdirname = xrealloc (reposdirname, 2);
	reposdirname[0] = '.'; reposdirname[1] = '\0';
    }
    else
	*p = '\0';

    dir_name = xstrdup (pathname);
    p = strrchr (dir_name, '/');
    if (p == NULL)
    {
	dir_name = xrealloc (dir_name, 2);
	dir_name[0] = '.'; dir_name[1] = '\0';
    }
    else
	*p = '\0';
    if (client_prune_dirs)
	add_prune_candidate (dir_name);

    filename = strrchr (short_repos, '/');
    if (filename == NULL)
	filename = short_repos;
    else
	++filename;

    short_pathname = xmalloc (strlen (pathname) + strlen (filename) + 5);
    strcpy (short_pathname, pathname);
    strcat (short_pathname, filename);

    if (last_dir_name == NULL
	|| strcmp (last_dir_name, dir_name) != 0)
    {
	int newdir;

	if (strcmp (command_name, "export") != 0)
	    if (last_entries)
		Entries_Close (last_entries);

	if (last_dir_name)
	    free (last_dir_name);
	last_dir_name = dir_name;

	if (toplevel_wd == NULL)
	{
	    toplevel_wd = xgetwd ();
	    if (toplevel_wd == NULL)
		error (1, errno, "could not get working directory");
	}

	if (CVS_CHDIR (toplevel_wd) < 0)
	    error (1, errno, "could not chdir to %s", toplevel_wd);
	newdir = 0;

	/* Create the CVS directory at the top level if needed.  The
	   isdir seems like an unneeded system call, but it *does*
	   need to be called both if the CVS_CHDIR below succeeds
	   (e.g.  "cvs co .") or if it fails (e.g. basicb-1a in
	   testsuite).  We only need to do this for the "." case,
	   since the server takes care of forcing this directory to be
	   created in all other cases.  If we don't create CVSADM
	   here, the call to Entries_Open below will fail.  FIXME:
	   perhaps this means that we should change our algorithm
	   below that calls Create_Admin instead of having this code
	   here? */
	if (/* I think the reposdirname_absolute case has to do with
	       things like "cvs update /foo/bar".  In any event, the
	       code below which tries to put toplevel_repos into
	       CVS/Repository is almost surely unsuited to
	       the reposdirname_absolute case.  */
	    !reposdirname_absolute
	    && (strcmp (dir_name, ".") == 0)
	    && ! isdir (CVSADM))
	{
	    char *repo;
	    char *r;

	    newdir = 1;

	    repo = xmalloc (strlen (toplevel_repos)
			    + 10);
	    strcpy (repo, toplevel_repos);
	    r = repo + strlen (repo);
	    if (r[-1] != '.' || r[-2] != '/')
	        strcpy (r, "/.");

	    Create_Admin (".", ".", repo, (char *) NULL,
			  (char *) NULL, 0, 1, 1);

	    free (repo);
	}

	if ( CVS_CHDIR (dir_name) < 0)
	{
	    char *dir;
	    char *dirp;
	    
	    if (! existence_error (errno))
		error (1, errno, "could not chdir to %s", dir_name);
	    
	    /* Directory does not exist, we need to create it.  */
	    newdir = 1;

	    /* Provided we are willing to assume that directories get
	       created one at a time, we could simplify this a lot.
	       Do note that one aspect still would need to walk the
	       dir_name path: the checking for "fncmp (dir, CVSADM)".  */

	    dir = xmalloc (strlen (dir_name) + 1);
	    dirp = dir_name;
	    rdirp = reposdirname;

	    /* This algorithm makes nested directories one at a time
               and create CVS administration files in them.  For
               example, we're checking out foo/bar/baz from the
               repository:

	       1) create foo, point CVS/Repository to <root>/foo
	       2)     .. foo/bar                   .. <root>/foo/bar
	       3)     .. foo/bar/baz               .. <root>/foo/bar/baz
	       
	       As you can see, we're just stepping along DIR_NAME (with
	       DIRP) and REPOSDIRNAME (with RDIRP) respectively.

	       We need to be careful when we are checking out a
	       module, however, since DIR_NAME and REPOSDIRNAME are not
	       going to be the same.  Since modules will not have any
	       slashes in their names, we should watch the output of
	       STRCHR to decide whether or not we should use STRCHR on
	       the RDIRP.  That is, if we're down to a module name,
	       don't keep picking apart the repository directory name.  */

	    do
	    {
		dirp = strchr (dirp, '/');
		if (dirp)
		{
		    strncpy (dir, dir_name, dirp - dir_name);
		    dir[dirp - dir_name] = '\0';
		    /* Skip the slash.  */
		    ++dirp;
		    if (rdirp == NULL)
			/* This just means that the repository string has
			   fewer components than the dir_name string.  But
			   that is OK (e.g. see modules3-8 in testsuite).  */
			;
		    else
			rdirp = strchr (rdirp, '/');
		}
		else
		{
		    /* If there are no more slashes in the dir name,
                       we're down to the most nested directory -OR- to
                       the name of a module.  In the first case, we
                       should be down to a DIRP that has no slashes,
                       so it won't help/hurt to do another STRCHR call
                       on DIRP.  It will definitely hurt, however, if
                       we're down to a module name, since a module
                       name can point to a nested directory (that is,
                       DIRP will still have slashes in it.  Therefore,
                       we should set it to NULL so the routine below
                       copies the contents of REMOTEDIRNAME onto the
                       root repository directory (does this if rdirp
                       is set to NULL, because we used to do an extra
                       STRCHR call here). */

		    rdirp = NULL;
		    strcpy (dir, dir_name);
		}

		if (fncmp (dir, CVSADM) == 0)
		{
		    error (0, 0, "cannot create a directory named %s", dir);
		    error (0, 0, "because CVS uses \"%s\" for its own uses",
			   CVSADM);
		    error (1, 0, "rename the directory and try again");
		}

		if (mkdir_if_needed (dir))
		{
		    /* It already existed, fine.  Just keep going.  */
		}
		else if (strcmp (command_name, "export") == 0)
		    /* Don't create CVSADM directories if this is export.  */
		    ;
		else
		{
		    /*
		     * Put repository in CVS/Repository.  For historical
		     * (pre-CVS/Root) reasons, this is an absolute pathname,
		     * but what really matters is the part of it which is
		     * relative to cvsroot.
		     */
		    char *repo;
		    char *r, *b;

		    repo = xmalloc (strlen (reposdirname)
				    + strlen (toplevel_repos)
				    + 80);
		    if (reposdirname_absolute)
			r = repo;
		    else
		    {
			strcpy (repo, toplevel_repos);
			strcat (repo, "/");
			r = repo + strlen (repo);
		    }

		    if (rdirp)
		    {
			/* See comment near start of function; the only
			   way that the server can put the right thing
			   in each CVS/Repository file is to create the
			   directories one at a time.  I think that the
			   CVS server has been doing this all along.  */
			error (0, 0, "\
warning: server is not creating directories one at a time");
			strncpy (r, reposdirname, rdirp - reposdirname);
			r[rdirp - reposdirname] = '\0';
		    }
		    else
			strcpy (r, reposdirname);

		    Create_Admin (dir, dir, repo,
				  (char *)NULL, (char *)NULL, 0, 0, 1);
		    free (repo);

		    b = strrchr (dir, '/');
		    if (b == NULL)
			Subdir_Register ((List *) NULL, (char *) NULL, dir);
		    else
		    {
			*b = '\0';
			Subdir_Register ((List *) NULL, dir, b + 1);
			*b = '/';
		    }
		}

		if (rdirp != NULL)
		{
		    /* Skip the slash.  */
		    ++rdirp;
		}

	    } while (dirp != NULL);
	    free (dir);
	    /* Now it better work.  */
	    if ( CVS_CHDIR (dir_name) < 0)
		error (1, errno, "could not chdir to %s", dir_name);
	}
	else if (!isdir (CVSADM))
	{
	    /*
	     * Put repository in CVS/Repository.  For historical
	     * (pre-CVS/Root) reasons, this is an absolute pathname,
	     * but what really matters is the part of it which is
	     * relative to cvsroot.
	     */
	    char *repo;

	    if (reposdirname_absolute)
		repo = reposdirname;
	    else
	    {
		repo = xmalloc (strlen (reposdirname)
				+ strlen (toplevel_repos)
				+ 10);
		strcpy (repo, toplevel_repos);
		strcat (repo, "/");
		strcat (repo, reposdirname);
	    }

	    Create_Admin (".", ".", repo, (char *)NULL, (char *)NULL, 0, 1, 1);
	    if (repo != reposdirname)
		free (repo);
	}

	if (strcmp (command_name, "export") != 0)
	{
	    last_entries = Entries_Open (0, dir_name);

	    /* If this is a newly created directory, we will record
	       all subdirectory information, so call Subdirs_Known in
	       case there are no subdirectories.  If this is not a
	       newly created directory, it may be an old working
	       directory from before we recorded subdirectory
	       information in the Entries file.  We force a search for
	       all subdirectories now, to make sure our subdirectory
	       information is up to date.  If the Entries file does
	       record subdirectory information, then this call only
	       does list manipulation.  */
	    if (newdir)
		Subdirs_Known (last_entries);
	    else
	    {
		List *dirlist;

		dirlist = Find_Directories ((char *) NULL, W_LOCAL,
					    last_entries);
		dellist (&dirlist);
	    }
	}
    }
    else
	free (dir_name);
    free (reposdirname);
    (*func) (data, last_entries, short_pathname, filename);
    free (short_pathname);
    free (reposname);
}

static void
copy_a_file (data, ent_list, short_pathname, filename)
    char *data;
    List *ent_list;
    char *short_pathname;
    char *filename;
{
    char *newname;
#ifdef USE_VMS_FILENAMES
    char *p;
#endif

    read_line (&newname);

#ifdef USE_VMS_FILENAMES
    /* Mogrify the filename so VMS is happy with it. */
    for(p = newname; *p; p++)
       if(*p == '.' || *p == '#') *p = '_';
#endif
    /* cvsclient.texi has said for a long time that newname must be in the
       same directory.  Wouldn't want a malicious or buggy server overwriting
       ~/.profile, /etc/passwd, or anything like that.  */
    if (last_component (newname) != newname)
	error (1, 0, "protocol error: Copy-file tried to specify directory");

    if (unlink_file (newname) && !existence_error (errno))
	error (0, errno, "unable to remove %s", newname);
    copy_file (filename, newname);
    free (newname);
}

static void
handle_copy_file (args, len)
    char *args;
    int len;
{
    call_in_directory (args, copy_a_file, (char *)NULL);
}


static void read_counted_file PROTO ((char *, char *));

/* Read from the server the count for the length of a file, then read
   the contents of that file and write them to FILENAME.  FULLNAME is
   the name of the file for use in error messages.  FIXME-someday:
   extend this to deal with compressed files and make update_entries
   use it.  On error, gives a fatal error.  */
static void
read_counted_file (filename, fullname)
    char *filename;
    char *fullname;
{
    char *size_string;
    size_t size;
    char *buf;

    /* Pointers in buf to the place to put data which will be read,
       and the data which needs to be written, respectively.  */
    char *pread;
    char *pwrite;
    /* Number of bytes left to read and number of bytes in buf waiting to
       be written, respectively.  */
    size_t nread;
    size_t nwrite;

    FILE *fp;

    read_line (&size_string);
    if (size_string[0] == 'z')
	error (1, 0, "\
protocol error: compressed files not supported for that operation");
    /* FIXME: should be doing more error checking, probably.  Like using
       strtoul and making sure we used up the whole line.  */
    size = atoi (size_string);
    free (size_string);

    /* A more sophisticated implementation would use only a limited amount
       of buffer space (8K perhaps), and read that much at a time.  We allocate
       a buffer for the whole file only to make it easy to keep track what
       needs to be read and written.  */
    buf = xmalloc (size);

    /* FIXME-someday: caller should pass in a flag saying whether it
       is binary or not.  I haven't carefully looked into whether
       CVS/Template files should use local text file conventions or
       not.  */
    fp = CVS_FOPEN (filename, "wb");
    if (fp == NULL)
	error (1, errno, "cannot write %s", fullname);
    nread = size;
    nwrite = 0;
    pread = buf;
    pwrite = buf;
    while (nread > 0 || nwrite > 0)
    {
	size_t n;

	if (nread > 0)
	{
	    n = try_read_from_server (pread, nread);
	    nread -= n;
	    pread += n;
	    nwrite += n;
	}

	if (nwrite > 0)
	{
	    n = fwrite (pwrite, 1, nwrite, fp);
	    if (ferror (fp))
		error (1, errno, "cannot write %s", fullname);
	    nwrite -= n;
	    pwrite += n;
	}
    }
    free (buf);
    if (fclose (fp) < 0)
	error (1, errno, "cannot close %s", fullname);
}

/* OK, we want to swallow the "U foo.c" response and then output it only
   if we can update the file.  In the future we probably want some more
   systematic approach to parsing tagged text, but for now we keep it
   ad hoc.  "Why," I hear you cry, "do we not just look at the
   Update-existing and Created responses?"  That is an excellent question,
   and the answer is roughly conservatism/laziness--I haven't read through
   update.c enough to figure out the exact correspondence or lack thereof
   between those responses and a "U foo.c" line (note that Merged, from
   join_file, can be either "C foo" or "U foo" depending on the context).  */
/* Nonzero if we have seen +updated and not -updated.  */
static int updated_seen;
/* Filename from an "fname" tagged response within +updated/-updated.  */
static char *updated_fname;

/* This struct is used to hold data when reading the +importmergecmd
   and -importmergecmd tags.  We put the variables in a struct only
   for namespace issues.  FIXME: As noted above, we need to develop a
   more systematic approach.  */
static struct
{
    /* Nonzero if we have seen +importmergecmd and not -importmergecmd.  */
    int seen;
    /* Number of conflicts, from a "conflicts" tagged response.  */
    int conflicts;
    /* First merge tag, from a "mergetag1" tagged response.  */
    char *mergetag1;
    /* Second merge tag, from a "mergetag2" tagged response.  */
    char *mergetag2;
    /* Repository, from a "repository" tagged response.  */
    char *repository;
} importmergecmd;

/* Nonzero if we should arrange to return with a failure exit status.  */
static int failure_exit;


/*
 * The time stamp of the last file we registered.
 */
static time_t last_register_time;

/*
 * The Checksum response gives the checksum for the file transferred
 * over by the next Updated, Merged or Patch response.  We just store
 * it here, and then check it in update_entries.
 */

static int stored_checksum_valid;
static unsigned char stored_checksum[16];

static void
handle_checksum (args, len)
    char *args;
    int len;
{
    char *s;
    char buf[3];
    int i;

    if (stored_checksum_valid)
        error (1, 0, "Checksum received before last one was used");

    s = args;
    buf[2] = '\0';
    for (i = 0; i < 16; i++)
    {
        char *bufend;

	buf[0] = *s++;
	buf[1] = *s++;
	stored_checksum[i] = (char) strtol (buf, &bufend, 16);
	if (bufend != buf + 2)
	    break;
    }

    if (i < 16 || *s != '\0')
        error (1, 0, "Invalid Checksum response: `%s'", args);

    stored_checksum_valid = 1;
}

/* Mode that we got in a "Mode" response (malloc'd), or NULL if none.  */
static char *stored_mode;

static void handle_mode PROTO ((char *, int));

static void
handle_mode (args, len)
    char *args;
    int len;
{
    if (stored_mode != NULL)
	error (1, 0, "protocol error: duplicate Mode");
    stored_mode = xstrdup (args);
}

/* Nonzero if time was specified in Mod-time.  */
static int stored_modtime_valid;
/* Time specified in Mod-time.  */
static time_t stored_modtime;

static void handle_mod_time PROTO ((char *, int));

static void
handle_mod_time (args, len)
    char *args;
    int len;
{
    if (stored_modtime_valid)
	error (0, 0, "protocol error: duplicate Mod-time");
    stored_modtime = get_date (args, NULL);
    if (stored_modtime == (time_t) -1)
	error (0, 0, "protocol error: cannot parse date %s", args);
    else
	stored_modtime_valid = 1;
}

/*
 * If we receive a patch, but the patch program fails to apply it, we
 * want to request the original file.  We keep a list of files whose
 * patches have failed.
 */

char **failed_patches;
int failed_patches_count;

struct update_entries_data
{
    enum {
      /*
       * We are just getting an Entries line; the local file is
       * correct.
       */
      UPDATE_ENTRIES_CHECKIN,
      /* We are getting the file contents as well.  */
      UPDATE_ENTRIES_UPDATE,
      /*
       * We are getting a patch against the existing local file, not
       * an entire new file.
       */
      UPDATE_ENTRIES_PATCH,
      /*
       * We are getting an RCS change text (diff -n output) against
       * the existing local file, not an entire new file.
       */
      UPDATE_ENTRIES_RCS_DIFF
    } contents;

    enum {
	/* We are replacing an existing file.  */
	UPDATE_ENTRIES_EXISTING,
	/* We are creating a new file.  */
	UPDATE_ENTRIES_NEW,
	/* We don't know whether it is existing or new.  */
	UPDATE_ENTRIES_EXISTING_OR_NEW
    } existp;

    /*
     * String to put in the timestamp field or NULL to use the timestamp
     * of the file.
     */
    char *timestamp;
};

/* Update the Entries line for this file.  */
static void
update_entries (data_arg, ent_list, short_pathname, filename)
    char *data_arg;
    List *ent_list;
    char *short_pathname;
    char *filename;
{
    char *entries_line;
    struct update_entries_data *data = (struct update_entries_data *)data_arg;

    char *cp;
    char *user;
    char *vn;
    /* Timestamp field.  Always empty according to the protocol.  */
    char *ts;
    char *options = NULL;
    char *tag = NULL;
    char *date = NULL;
    char *tag_or_date;
    char *scratch_entries = NULL;
    int bin;

#ifdef UTIME_EXPECTS_WRITABLE
    int change_it_back = 0;
#endif

    read_line (&entries_line);

    /*
     * Parse the entries line.
     */
    scratch_entries = xstrdup (entries_line);

    if (scratch_entries[0] != '/')
        error (1, 0, "bad entries line `%s' from server", entries_line);
    user = scratch_entries + 1;
    if ((cp = strchr (user, '/')) == NULL)
        error (1, 0, "bad entries line `%s' from server", entries_line);
    *cp++ = '\0';
    vn = cp;
    if ((cp = strchr (vn, '/')) == NULL)
        error (1, 0, "bad entries line `%s' from server", entries_line);
    *cp++ = '\0';
    
    ts = cp;
    if ((cp = strchr (ts, '/')) == NULL)
        error (1, 0, "bad entries line `%s' from server", entries_line);
    *cp++ = '\0';
    options = cp;
    if ((cp = strchr (options, '/')) == NULL)
        error (1, 0, "bad entries line `%s' from server", entries_line);
    *cp++ = '\0';
    tag_or_date = cp;
    
    /* If a slash ends the tag_or_date, ignore everything after it.  */
    cp = strchr (tag_or_date, '/');
    if (cp != NULL)
        *cp = '\0';
    if (*tag_or_date == 'T')
        tag = tag_or_date + 1;
    else if (*tag_or_date == 'D')
        date = tag_or_date + 1;

    /* Done parsing the entries line. */

    if (data->contents == UPDATE_ENTRIES_UPDATE
	|| data->contents == UPDATE_ENTRIES_PATCH
	|| data->contents == UPDATE_ENTRIES_RCS_DIFF)
    {
	char *size_string;
	char *mode_string;
	int size;
	char *buf;
	char *temp_filename;
	int use_gzip;
	int patch_failed;

	read_line (&mode_string);
	
	read_line (&size_string);
	if (size_string[0] == 'z')
	{
	    use_gzip = 1;
	    size = atoi (size_string+1);
	}
	else
	{
	    use_gzip = 0;
	    size = atoi (size_string);
	}
	free (size_string);

	/* Note that checking this separately from writing the file is
	   a race condition: if the existence or lack thereof of the
	   file changes between now and the actual calls which
	   operate on it, we lose.  However (a) there are so many
	   cases, I'm reluctant to try to fix them all, (b) in some
	   cases the system might not even have a system call which
	   does the right thing, and (c) it isn't clear this needs to
	   work.  */
	if (data->existp == UPDATE_ENTRIES_EXISTING
	    && !isfile (filename))
	    /* Emit a warning and update the file anyway.  */
	    error (0, 0, "warning: %s unexpectedly disappeared",
		   short_pathname);

	if (data->existp == UPDATE_ENTRIES_NEW
	    && isfile (filename))
	{
	    /* Emit a warning and refuse to update the file; we don't want
	       to clobber a user's file.  */
	    size_t nread;
	    size_t toread;

	    /* size should be unsigned, but until we get around to fixing
	       that, work around it.  */
	    size_t usize;

	    char buf[8192];

	    /* This error might be confusing; it isn't really clear to
	       the user what to do about it.  Keep in mind that it has
	       several causes: (1) something/someone creates the file
	       during the time that CVS is running, (2) the repository
	       has two files whose names clash for the client because
	       of case-insensitivity or similar causes, (3) a special
	       case of this is that a file gets renamed for example
	       from a.c to A.C.  A "cvs update" on a case-insensitive
	       client will get this error.  Repeating the update takes
	       care of the problem, but is it clear to the user what
	       is going on and what to do about it?, (4) the client
	       has a file which the server doesn't know about (e.g. "?
	       foo" file), and that name clashes with a file the
	       server does know about, (5) classify.c will print the same
	       message for other reasons.

	       I hope the above paragraph makes it clear that making this
	       clearer is not a one-line fix.  */
	    error (0, 0, "move away %s; it is in the way", short_pathname);
	    if (updated_fname != NULL)
	    {
		cvs_output ("C ", 0);
		cvs_output (updated_fname, 0);
		cvs_output ("\n", 1);
	    }
	    failure_exit = 1;

	discard_file_and_return:
	    /* Now read and discard the file contents.  */
	    usize = size;
	    nread = 0;
	    while (nread < usize)
	    {
		toread = usize - nread;
		if (toread > sizeof buf)
		    toread = sizeof buf;

		nread += try_read_from_server (buf, toread);
		if (nread == usize)
		    break;
	    }

	    free (mode_string);
	    free (scratch_entries);
	    free (entries_line);

	    /* The Mode, Mod-time, and Checksum responses should not carry
	       over to a subsequent Created (or whatever) response, even
	       in the error case.  */
	    if (stored_mode != NULL)
	    {
		free (stored_mode);
		stored_mode = NULL;
	    }
	    stored_modtime_valid = 0;
	    stored_checksum_valid = 0;

	    if (updated_fname != NULL)
	    {
		free (updated_fname);
		updated_fname = NULL;
	    }
	    return;
	}

	temp_filename = xmalloc (strlen (filename) + 80);
#ifdef USE_VMS_FILENAMES
        /* A VMS rename of "blah.dat" to "foo" to implies a
           destination of "foo.dat" which is unfortinate for CVS */
       sprintf (temp_filename, "%s_new_", filename);
#else
#ifdef _POSIX_NO_TRUNC
	sprintf (temp_filename, ".new.%.9s", filename);
#else /* _POSIX_NO_TRUNC */
	sprintf (temp_filename, ".new.%s", filename);
#endif /* _POSIX_NO_TRUNC */
#endif /* USE_VMS_FILENAMES */

	buf = xmalloc (size);

        /* Some systems, like OS/2 and Windows NT, end lines with CRLF
           instead of just LF.  Format translation is done in the C
           library I/O funtions.  Here we tell them whether or not to
           convert -- if this file is marked "binary" with the RCS -kb
           flag, then we don't want to convert, else we do (because
           CVS assumes text files by default). */

	if (options)
	    bin = !(strcmp (options, "-kb"));
	else
	    bin = 0;

	if (data->contents == UPDATE_ENTRIES_RCS_DIFF)
	{
	    /* This is an RCS change text.  We just hold the change
	       text in memory.  */

	    if (use_gzip)
		error (1, 0,
		       "server error: gzip invalid with RCS change text");

	    read_from_server (buf, size);
	}
	else
	{
	    int fd;

	    fd = CVS_OPEN (temp_filename,
			   (O_WRONLY | O_CREAT | O_TRUNC
			    | (bin ? OPEN_BINARY : 0)),
			   0777);

	    if (fd < 0)
	    {
		/* I can see a case for making this a fatal error; for
		   a condition like disk full or network unreachable
		   (for a file server), carrying on and giving an
		   error on each file seems unnecessary.  But if it is
		   a permission problem, or some such, then it is
		   entirely possible that future files will not have
		   the same problem.  */
		error (0, errno, "cannot write %s", short_pathname);
		goto discard_file_and_return;
	    }

	    if (size > 0)
	    {
		read_from_server (buf, size);

		if (use_gzip)
		{
		    if (gunzip_and_write (fd, short_pathname, 
					  (unsigned char *) buf, size))
			error (1, 0, "aborting due to compression error");
		}
		else if (write (fd, buf, size) != size)
		    error (1, errno, "writing %s", short_pathname);
	    }

	    if (close (fd) < 0)
		error (1, errno, "writing %s", short_pathname);
	}

	/* This is after we have read the file from the net (a change
	   from previous versions, where the server would send us
	   "M U foo.c" before Update-existing or whatever), but before
	   we finish writing the file (arguably a bug).  The timing
	   affects a user who wants status info about how far we have
	   gotten, and also affects whether "U foo.c" appears in addition
	   to various error messages.  */
	if (updated_fname != NULL)
	{
	    cvs_output ("U ", 0);
	    cvs_output (updated_fname, 0);
	    cvs_output ("\n", 1);
	    free (updated_fname);
	    updated_fname = 0;
	}

	patch_failed = 0;

	if (data->contents == UPDATE_ENTRIES_UPDATE)
	{
	    rename_file (temp_filename, filename);
	}
	else if (data->contents == UPDATE_ENTRIES_PATCH)
	{
	    /* You might think we could just leave Patched out of
	       Valid-responses and not get this response.  However, if
	       memory serves, the CVS 1.9 server bases this on -u
	       (update-patches), and there is no way for us to send -u
	       or not based on whether the server supports "Rcs-diff".  

	       Fall back to transmitting entire files.  */
	    patch_failed = 1;
	}
	else
	{
	    char *filebuf;
	    size_t filebufsize;
	    size_t nread;
	    char *patchedbuf;
	    size_t patchedlen;

	    /* Handle UPDATE_ENTRIES_RCS_DIFF.  */

	    if (!isfile (filename))
	        error (1, 0, "patch original file %s does not exist",
		       short_pathname);
	    filebuf = NULL;
	    filebufsize = 0;
	    nread = 0;

	    get_file (filename, short_pathname, bin ? FOPEN_BINARY_READ : "r",
		      &filebuf, &filebufsize, &nread);
	    /* At this point the contents of the existing file are in
               FILEBUF, and the length of the contents is in NREAD.
               The contents of the patch from the network are in BUF,
               and the length of the patch is in SIZE.  */

	    if (! rcs_change_text (short_pathname, filebuf, nread, buf, size,
				   &patchedbuf, &patchedlen))
		patch_failed = 1;
	    else
	    {
		if (stored_checksum_valid)
		{
		    struct cvs_MD5Context context;
		    unsigned char checksum[16];

		    /* We have a checksum.  Check it before writing
		       the file out, so that we don't have to read it
		       back in again.  */
		    cvs_MD5Init (&context);
		    cvs_MD5Update (&context,
				   (unsigned char *) patchedbuf, patchedlen);
		    cvs_MD5Final (checksum, &context);
		    if (memcmp (checksum, stored_checksum, 16) != 0)
		    {
			error (0, 0,
			       "checksum failure after patch to %s; will refetch",
			       short_pathname);

			patch_failed = 1;
		    }

		    stored_checksum_valid = 0;
		}

		if (! patch_failed)
		{
		    FILE *e;

		    e = open_file (temp_filename,
				   bin ? FOPEN_BINARY_WRITE : "w");
		    if (fwrite (patchedbuf, 1, patchedlen, e) != patchedlen)
			error (1, errno, "cannot write %s", temp_filename);
		    if (fclose (e) == EOF)
			error (1, errno, "cannot close %s", temp_filename);
		    rename_file (temp_filename, filename);
		}

		free (patchedbuf);
	    }

	    free (filebuf);
	}

	free (temp_filename);

	if (stored_checksum_valid && ! patch_failed)
	{
	    FILE *e;
	    struct cvs_MD5Context context;
	    unsigned char buf[8192];
	    unsigned len;
	    unsigned char checksum[16];

	    /*
	     * Compute the MD5 checksum.  This will normally only be
	     * used when receiving a patch, so we always compute it
	     * here on the final file, rather than on the received
	     * data.
	     *
	     * Note that if the file is a text file, we should read it
	     * here using text mode, so its lines will be terminated the same
	     * way they were transmitted.
	     */
	    e = CVS_FOPEN (filename, "r");
	    if (e == NULL)
	        error (1, errno, "could not open %s", short_pathname);

	    cvs_MD5Init (&context);
	    while ((len = fread (buf, 1, sizeof buf, e)) != 0)
		cvs_MD5Update (&context, buf, len);
	    if (ferror (e))
		error (1, errno, "could not read %s", short_pathname);
	    cvs_MD5Final (checksum, &context);

	    fclose (e);

	    stored_checksum_valid = 0;

	    if (memcmp (checksum, stored_checksum, 16) != 0)
	    {
	        if (data->contents != UPDATE_ENTRIES_PATCH)
		    error (1, 0, "checksum failure on %s",
			   short_pathname);

		error (0, 0,
		       "checksum failure after patch to %s; will refetch",
		       short_pathname);

		patch_failed = 1;
	    }
	}

	if (patch_failed)
	{
	    /* Save this file to retrieve later.  */
	    failed_patches = (char **) xrealloc ((char *) failed_patches,
						 ((failed_patches_count + 1)
						  * sizeof (char *)));
	    failed_patches[failed_patches_count] = xstrdup (short_pathname);
	    ++failed_patches_count;

	    stored_checksum_valid = 0;

	    free (mode_string);
	    free (buf);
	    free (scratch_entries);
	    free (entries_line);

	    return;
	}

        {
	    int status = change_mode (filename, mode_string, 1);
	    if (status != 0)
		error (0, status, "cannot change mode of %s", short_pathname);
	}

	free (mode_string);
	free (buf);
    }

    if (stored_mode != NULL)
    {
	change_mode (filename, stored_mode, 1);
	free (stored_mode);
	stored_mode = NULL;
    }
   
    if (stored_modtime_valid)
    {
	struct utimbuf t;

	memset (&t, 0, sizeof (t));
	/* There is probably little point in trying to preserved the
	   actime (or is there? What about Checked-in?).  */
	t.modtime = t.actime = stored_modtime;

#ifdef UTIME_EXPECTS_WRITABLE
	if (!iswritable (filename))
	{
	    xchmod (filename, 1);
	    change_it_back = 1;
	}
#endif  /* UTIME_EXPECTS_WRITABLE  */

	if (utime (filename, &t) < 0)
	    error (0, errno, "cannot set time on %s", filename);

#ifdef UTIME_EXPECTS_WRITABLE
	if (change_it_back == 1)
	{
	    xchmod (filename, 0);
	    change_it_back = 0;
	}
#endif  /*  UTIME_EXPECTS_WRITABLE  */

	stored_modtime_valid = 0;
    }

    /*
     * Process the entries line.  Do this after we've written the file,
     * since we need the timestamp.
     */
    if (strcmp (command_name, "export") != 0)
    {
	char *local_timestamp;
	char *file_timestamp;

	(void) time (&last_register_time);

	local_timestamp = data->timestamp;
	if (local_timestamp == NULL || ts[0] == '+')
	    file_timestamp = time_stamp (filename);
	else
	    file_timestamp = NULL;

	/*
	 * These special version numbers signify that it is not up to
	 * date.  Create a dummy timestamp which will never compare
	 * equal to the timestamp of the file.
	 */
	if (vn[0] == '\0' || vn[0] == '0' || vn[0] == '-')
	    local_timestamp = "dummy timestamp";
	else if (local_timestamp == NULL)
	{
	    local_timestamp = file_timestamp;

	    /* Checking for command_name of "commit" doesn't seem like
	       the cleanest way to handle this, but it seem to roughly
	       parallel what the :local: code which calls
	       mark_up_to_date ends up amounting to.  Some day, should
	       think more about what the Checked-in response means
	       vis-a-vis both Entries and Base and clarify
	       cvsclient.texi accordingly.  */

	    if (!strcmp (command_name, "commit"))
		mark_up_to_date (filename);
	}

	Register (ent_list, filename, vn, local_timestamp,
		  options, tag, date, ts[0] == '+' ? file_timestamp : NULL);

	if (file_timestamp)
	    free (file_timestamp);

    }
    free (scratch_entries);
    free (entries_line);
}

static void
handle_checked_in (args, len)
    char *args;
    int len;
{
    struct update_entries_data dat;
    dat.contents = UPDATE_ENTRIES_CHECKIN;
    dat.existp = UPDATE_ENTRIES_EXISTING_OR_NEW;
    dat.timestamp = NULL;
    call_in_directory (args, update_entries, (char *)&dat);
}

static void
handle_new_entry (args, len)
    char *args;
    int len;
{
    struct update_entries_data dat;
    dat.contents = UPDATE_ENTRIES_CHECKIN;
    dat.existp = UPDATE_ENTRIES_EXISTING_OR_NEW;
    dat.timestamp = "dummy timestamp from new-entry";
    call_in_directory (args, update_entries, (char *)&dat);
}

static void
handle_updated (args, len)
    char *args;
    int len;
{
    struct update_entries_data dat;
    dat.contents = UPDATE_ENTRIES_UPDATE;
    dat.existp = UPDATE_ENTRIES_EXISTING_OR_NEW;
    dat.timestamp = NULL;
    call_in_directory (args, update_entries, (char *)&dat);
}

static void handle_created PROTO((char *, int));

static void
handle_created (args, len)
    char *args;
    int len;
{
    struct update_entries_data dat;
    dat.contents = UPDATE_ENTRIES_UPDATE;
    dat.existp = UPDATE_ENTRIES_NEW;
    dat.timestamp = NULL;
    call_in_directory (args, update_entries, (char *)&dat);
}

static void handle_update_existing PROTO((char *, int));

static void
handle_update_existing (args, len)
    char *args;
    int len;
{
    struct update_entries_data dat;
    dat.contents = UPDATE_ENTRIES_UPDATE;
    dat.existp = UPDATE_ENTRIES_EXISTING;
    dat.timestamp = NULL;
    call_in_directory (args, update_entries, (char *)&dat);
}

static void
handle_merged (args, len)
    char *args;
    int len;
{
    struct update_entries_data dat;
    dat.contents = UPDATE_ENTRIES_UPDATE;
    /* Think this could be UPDATE_ENTRIES_EXISTING, but just in case...  */
    dat.existp = UPDATE_ENTRIES_EXISTING_OR_NEW;
    dat.timestamp = "Result of merge";
    call_in_directory (args, update_entries, (char *)&dat);
}

static void
handle_patched (args, len)
     char *args;
     int len;
{
    struct update_entries_data dat;
    dat.contents = UPDATE_ENTRIES_PATCH;
    /* Think this could be UPDATE_ENTRIES_EXISTING, but just in case...  */
    dat.existp = UPDATE_ENTRIES_EXISTING_OR_NEW;
    dat.timestamp = NULL;
    call_in_directory (args, update_entries, (char *)&dat);
}

static void
handle_rcs_diff (args, len)
     char *args;
     int len;
{
    struct update_entries_data dat;
    dat.contents = UPDATE_ENTRIES_RCS_DIFF;
    /* Think this could be UPDATE_ENTRIES_EXISTING, but just in case...  */
    dat.existp = UPDATE_ENTRIES_EXISTING_OR_NEW;
    dat.timestamp = NULL;
    call_in_directory (args, update_entries, (char *)&dat);
}

static void
remove_entry (data, ent_list, short_pathname, filename)
    char *data;
    List *ent_list;
    char *short_pathname;
    char *filename;
{
    Scratch_Entry (ent_list, filename);
}

static void
handle_remove_entry (args, len)
    char *args;
    int len;
{
    call_in_directory (args, remove_entry, (char *)NULL);
}

static void
remove_entry_and_file (data, ent_list, short_pathname, filename)
    char *data;
    List *ent_list;
    char *short_pathname;
    char *filename;
{
    Scratch_Entry (ent_list, filename);
    /* Note that we don't ignore existence_error's here.  The server
       should be sending Remove-entry rather than Removed in cases
       where the file does not exist.  And if the user removes the
       file halfway through a cvs command, we should be printing an
       error.  */
    if (unlink_file (filename) < 0)
	error (0, errno, "unable to remove %s", short_pathname);
}

static void
handle_removed (args, len)
    char *args;
    int len;
{
    call_in_directory (args, remove_entry_and_file, (char *)NULL);
}

/* Is this the top level (directory containing CVSROOT)?  */
static int
is_cvsroot_level (pathname)
    char *pathname;
{
    if (strcmp (toplevel_repos, current_parsed_root->directory) != 0)
	return 0;

    return strchr (pathname, '/') == NULL;
}

static void
set_static (data, ent_list, short_pathname, filename)
    char *data;
    List *ent_list;
    char *short_pathname;
    char *filename;
{
    FILE *fp;
    fp = open_file (CVSADM_ENTSTAT, "w+");
    if (fclose (fp) == EOF)
        error (1, errno, "cannot close %s", CVSADM_ENTSTAT);
}

static void
handle_set_static_directory (args, len)
    char *args;
    int len;
{
    if (strcmp (command_name, "export") == 0)
    {
	/* Swallow the repository.  */
	read_line (NULL);
	return;
    }
    call_in_directory (args, set_static, (char *)NULL);
}

static void
clear_static (data, ent_list, short_pathname, filename)
    char *data;
    List *ent_list;
    char *short_pathname;
    char *filename;
{
    if (unlink_file (CVSADM_ENTSTAT) < 0 && ! existence_error (errno))
        error (1, errno, "cannot remove file %s", CVSADM_ENTSTAT);
}

static void
handle_clear_static_directory (pathname, len)
    char *pathname;
    int len;
{
    if (strcmp (command_name, "export") == 0)
    {
	/* Swallow the repository.  */
	read_line (NULL);
	return;
    }

    if (is_cvsroot_level (pathname))
    {
        /*
	 * Top level (directory containing CVSROOT).  This seems to normally
	 * lack a CVS directory, so don't try to create files in it.
	 */
	return;
    }
    call_in_directory (pathname, clear_static, (char *)NULL);
}

static void
set_sticky (data, ent_list, short_pathname, filename)
    char *data;
    List *ent_list;
    char *short_pathname;
    char *filename;
{
    char *tagspec;
    FILE *f;

    read_line (&tagspec);

    /* FIXME-update-dir: error messages should include the directory.  */
    f = CVS_FOPEN (CVSADM_TAG, "w+");
    if (f == NULL)
    {
	/* Making this non-fatal is a bit of a kludge (see dirs2
	   in testsuite).  A better solution would be to avoid having
	   the server tell us about a directory we shouldn't be doing
	   anything with anyway (e.g. by handling directory
	   addition/removal better).  */
	error (0, errno, "cannot open %s", CVSADM_TAG);
	free (tagspec);
	return;
    }
    if (fprintf (f, "%s\n", tagspec) < 0)
	error (1, errno, "writing %s", CVSADM_TAG);
    if (fclose (f) == EOF)
	error (1, errno, "closing %s", CVSADM_TAG);
    free (tagspec);
}

static void
handle_set_sticky (pathname, len)
    char *pathname;
    int len;
{
    if (strcmp (command_name, "export") == 0)
    {
	/* Swallow the repository.  */
	read_line (NULL);
        /* Swallow the tag line.  */
	read_line (NULL);
	return;
    }
    if (is_cvsroot_level (pathname))
    {
        /*
	 * Top level (directory containing CVSROOT).  This seems to normally
	 * lack a CVS directory, so don't try to create files in it.
	 */

	/* Swallow the repository.  */
	read_line (NULL);
        /* Swallow the tag line.  */
	read_line (NULL);
	return;
    }

    call_in_directory (pathname, set_sticky, (char *)NULL);
}

static void
clear_sticky (data, ent_list, short_pathname, filename)
    char *data;
    List *ent_list;
    char *short_pathname;
    char *filename;
{
    if (unlink_file (CVSADM_TAG) < 0 && ! existence_error (errno))
	error (1, errno, "cannot remove %s", CVSADM_TAG);
}

static void
handle_clear_sticky (pathname, len)
    char *pathname;
    int len;
{
    if (strcmp (command_name, "export") == 0)
    {
	/* Swallow the repository.  */
	read_line (NULL);
	return;
    }

    if (is_cvsroot_level (pathname))
    {
        /*
	 * Top level (directory containing CVSROOT).  This seems to normally
	 * lack a CVS directory, so don't try to create files in it.
	 */
	return;
    }

    call_in_directory (pathname, clear_sticky, (char *)NULL);
}


static void template PROTO ((char *, List *, char *, char *));

static void
template (data, ent_list, short_pathname, filename)
    char *data;
    List *ent_list;
    char *short_pathname;
    char *filename;
{
    /* FIXME: should be computing second argument from CVSADM_TEMPLATE
       and short_pathname.  */
    read_counted_file (CVSADM_TEMPLATE, "<CVS/Template file>");
}

static void handle_template PROTO ((char *, int));

static void
handle_template (pathname, len)
    char *pathname;
    int len;
{
    call_in_directory (pathname, template, NULL);
}


struct save_prog {
    char *name;
    char *dir;
    struct save_prog *next;
};

static struct save_prog *checkin_progs;
static struct save_prog *update_progs;

/*
 * Unlike some responses this doesn't include the repository.  So we can't
 * just call call_in_directory and have the right thing happen; we save up
 * the requests and do them at the end.
 */
static void
handle_set_checkin_prog (args, len)
    char *args;
    int len;
{
    char *prog;
    struct save_prog *p;

    read_line (&prog);
    if (strcmp (command_name, "export") == 0)
	return;

    p = (struct save_prog *) xmalloc (sizeof (struct save_prog));
    p->next = checkin_progs;
    p->dir = xstrdup (args);
    p->name = prog;
    checkin_progs = p;
}
    
static void
handle_set_update_prog (args, len)
    char *args;
    int len;
{
    char *prog;
    struct save_prog *p;

    read_line (&prog);
    if (strcmp (command_name, "export") == 0)
	return;

    p = (struct save_prog *) xmalloc (sizeof (struct save_prog));
    p->next = update_progs;
    p->dir = xstrdup (args);
    p->name = prog;
    update_progs = p;
}

static void do_deferred_progs PROTO((void));

static void
do_deferred_progs ()
{
    struct save_prog *p;
    struct save_prog *q;

    char *fname;
    FILE *f;

    if (toplevel_wd != NULL)
    {
	if (CVS_CHDIR (toplevel_wd) < 0)
	    error (1, errno, "could not chdir to %s", toplevel_wd);
    }
    for (p = checkin_progs; p != NULL; )
    {
	fname = xmalloc (strlen (p->dir) + sizeof CVSADM_CIPROG + 10);
	sprintf (fname, "%s/%s", p->dir, CVSADM_CIPROG);
	f = open_file (fname, "w");
	if (fprintf (f, "%s\n", p->name) < 0)
	    error (1, errno, "writing %s", fname);
	if (fclose (f) == EOF)
	    error (1, errno, "closing %s", fname);
	free (p->name);
	free (p->dir);
	q = p->next;
	free (p);
	p = q;
	free (fname);
    }
    checkin_progs = NULL;
    for (p = update_progs; p != NULL; )
    {
	fname = xmalloc (strlen (p->dir) + sizeof CVSADM_UPROG + 10);
	sprintf (fname, "%s/%s", p->dir, CVSADM_UPROG);
	f = open_file (fname, "w");
	if (fprintf (f, "%s\n", p->name) < 0)
	    error (1, errno, "writing %s", fname);
	if (fclose (f) == EOF)
	    error (1, errno, "closing %s", fname);
	free (p->name);
	free (p->dir);
	q = p->next;
	free (p);
	p = q;
	free (fname);
    }
    update_progs = NULL;
}

struct save_dir {
    char *dir;
    struct save_dir *next;
};

struct save_dir *prune_candidates;

static void
add_prune_candidate (dir)
    char *dir;
{
    struct save_dir *p;

    if ((dir[0] == '.' && dir[1] == '\0')
	|| (prune_candidates != NULL
	    && strcmp (dir, prune_candidates->dir) == 0))
	return;
    p = (struct save_dir *) xmalloc (sizeof (struct save_dir));
    p->dir = xstrdup (dir);
    p->next = prune_candidates;
    prune_candidates = p;
}

static void process_prune_candidates PROTO((void));

static void
process_prune_candidates ()
{
    struct save_dir *p;
    struct save_dir *q;

    if (toplevel_wd != NULL)
    {
	if (CVS_CHDIR (toplevel_wd) < 0)
	    error (1, errno, "could not chdir to %s", toplevel_wd);
    }
    for (p = prune_candidates; p != NULL; )
    {
	if (isemptydir (p->dir, 1))
	{
	    char *b;

	    if (unlink_file_dir (p->dir) < 0)
		error (0, errno, "cannot remove %s", p->dir);
	    b = strrchr (p->dir, '/');
	    if (b == NULL)
		Subdir_Deregister ((List *) NULL, (char *) NULL, p->dir);
	    else
	    {
		*b = '\0';
		Subdir_Deregister ((List *) NULL, p->dir, b + 1);
	    }
	}
	free (p->dir);
	q = p->next;
	free (p);
	p = q;
    }
    prune_candidates = NULL;
}

/* Send a Repository line.  */

static char *last_repos;
static char *last_update_dir;

static void send_repository PROTO((char *, char *, char *));

static void
send_repository (dir, repos, update_dir)
    char *dir;
    char *repos;
    char *update_dir;
{
    char *adm_name;

    /* FIXME: this is probably not the best place to check; I wish I
     * knew where in here's callers to really trap this bug.  To
     * reproduce the bug, just do this:
     * 
     *       mkdir junk
     *       cd junk
     *       cvs -d some_repos update foo
     *
     * Poof, CVS seg faults and dies!  It's because it's trying to
     * send a NULL string to the server but dies in send_to_server.
     * That string was supposed to be the repository, but it doesn't
     * get set because there's no CVSADM dir, and somehow it's not
     * getting set from the -d argument either... ?
     */
    if (repos == NULL)
    {
        /* Lame error.  I want a real fix but can't stay up to track
           this down right now. */
        error (1, 0, "no repository");
    }

    if (update_dir == NULL || update_dir[0] == '\0')
	update_dir = ".";

    if (last_repos != NULL
	&& strcmp (repos, last_repos) == 0
	&& last_update_dir != NULL
	&& strcmp (update_dir, last_update_dir) == 0)
	/* We've already sent it.  */
	return;

    if (client_prune_dirs)
	add_prune_candidate (update_dir);

    /* Add a directory name to the list of those sent to the
       server. */
    if (update_dir && (*update_dir != '\0')
	&& (strcmp (update_dir, ".") != 0)
	&& (findnode (dirs_sent_to_server, update_dir) == NULL))
    {
	Node *n;
	n = getnode ();
	n->type = NT_UNKNOWN;
	n->key = xstrdup (update_dir);
	n->data = NULL;

	if (addnode (dirs_sent_to_server, n))
	    error (1, 0, "cannot add directory %s to list", n->key);
    }

    /* 80 is large enough for any of CVSADM_*.  */
    adm_name = xmalloc (strlen (dir) + 80);

    send_to_server ("Directory ", 0);
    {
	/* Send the directory name.  I know that this
	   sort of duplicates code elsewhere, but each
	   case seems slightly different...  */
	char buf[1];
	char *p = update_dir;
	while (*p != '\0')
	{
	    assert (*p != '\012');
	    if (ISDIRSEP (*p))
	    {
		buf[0] = '/';
		send_to_server (buf, 1);
	    }
	    else
	    {
		buf[0] = *p;
		send_to_server (buf, 1);
	    }
	    ++p;
	}
    }
    send_to_server ("\012", 1);
    send_to_server (repos, 0);
    send_to_server ("\012", 1);

    if (supported_request ("Static-directory"))
    {
	adm_name[0] = '\0';
	if (dir[0] != '\0')
	{
	    strcat (adm_name, dir);
	    strcat (adm_name, "/");
	}
	strcat (adm_name, CVSADM_ENTSTAT);
	if (isreadable (adm_name))
	{
	    send_to_server ("Static-directory\012", 0);
	}
    }
    if (supported_request ("Sticky"))
    {
	FILE *f;
	if (dir[0] == '\0')
	    strcpy (adm_name, CVSADM_TAG);
	else
	    sprintf (adm_name, "%s/%s", dir, CVSADM_TAG);

	f = CVS_FOPEN (adm_name, "r");
	if (f == NULL)
	{
	    if (! existence_error (errno))
		error (1, errno, "reading %s", adm_name);
	}
	else
	{
	    char line[80];
	    char *nl = NULL;
	    send_to_server ("Sticky ", 0);
	    while (fgets (line, sizeof (line), f) != NULL)
	    {
		send_to_server (line, 0);
		nl = strchr (line, '\n');
		if (nl != NULL)
		    break;
	    }
	    if (nl == NULL)
                send_to_server ("\012", 1);
	    if (fclose (f) == EOF)
		error (0, errno, "closing %s", adm_name);
	}
    }
    if (supported_request ("Checkin-prog"))
    {
	FILE *f;
	if (dir[0] == '\0')
	    strcpy (adm_name, CVSADM_CIPROG);
	else
	    sprintf (adm_name, "%s/%s", dir, CVSADM_CIPROG);

	f = CVS_FOPEN (adm_name, "r");
	if (f == NULL)
	{
	    if (! existence_error (errno))
		error (1, errno, "reading %s", adm_name);
	}
	else
	{
	    char line[80];
	    char *nl = NULL;

	    send_to_server ("Checkin-prog ", 0);

	    while (fgets (line, sizeof (line), f) != NULL)
	    {
		send_to_server (line, 0);

		nl = strchr (line, '\n');
		if (nl != NULL)
		    break;
	    }
	    if (nl == NULL)
		send_to_server ("\012", 1);
	    if (fclose (f) == EOF)
		error (0, errno, "closing %s", adm_name);
	}
    }
    if (supported_request ("Update-prog"))
    {
	FILE *f;
	if (dir[0] == '\0')
	    strcpy (adm_name, CVSADM_UPROG);
	else
	    sprintf (adm_name, "%s/%s", dir, CVSADM_UPROG);

	f = CVS_FOPEN (adm_name, "r");
	if (f == NULL)
	{
	    if (! existence_error (errno))
		error (1, errno, "reading %s", adm_name);
	}
	else
	{
	    char line[80];
	    char *nl = NULL;

	    send_to_server ("Update-prog ", 0);

	    while (fgets (line, sizeof (line), f) != NULL)
	    {
		send_to_server (line, 0);

		nl = strchr (line, '\n');
		if (nl != NULL)
		    break;
	    }
	    if (nl == NULL)
		send_to_server ("\012", 1);
	    if (fclose (f) == EOF)
		error (0, errno, "closing %s", adm_name);
	}
    }
    free (adm_name);
    if (last_repos != NULL)
	free (last_repos);
    if (last_update_dir != NULL)
	free (last_update_dir);
    last_repos = xstrdup (repos);
    last_update_dir = xstrdup (update_dir);
}

/* Send a Repository line and set toplevel_repos.  */

void
send_a_repository (dir, repository, update_dir)
    char *dir;
    char *repository;
    char *update_dir;
{
    if (toplevel_repos == NULL && repository != NULL)
    {
	if (update_dir[0] == '\0'
	    || (update_dir[0] == '.' && update_dir[1] == '\0'))
	    toplevel_repos = xstrdup (repository);
	else
	{
	    /*
	     * Get the repository from a CVS/Repository file if update_dir
	     * is absolute.  This is not correct in general, because
	     * the CVS/Repository file might not be the top-level one.
	     * This is for cases like "cvs update /foo/bar" (I'm not
	     * sure it matters what toplevel_repos we get, but it does
	     * matter that we don't hit the "internal error" code below).
	     */
	    if (update_dir[0] == '/')
		toplevel_repos = Name_Repository (update_dir, update_dir);
	    else
	    {
		/*
		 * Guess the repository of that directory by looking at a
		 * subdirectory and removing as many pathname components
		 * as are in update_dir.  I think that will always (or at
		 * least almost always) be 1.
		 *
		 * So this deals with directories which have been
		 * renamed, though it doesn't necessarily deal with
		 * directories which have been put inside other
		 * directories (and cvs invoked on the containing
		 * directory).  I'm not sure the latter case needs to
		 * work.
		 *
		 * 21 Aug 1998: Well, Mr. Above-Comment-Writer, it
		 * does need to work after all.  When we are using the
		 * client in a multi-cvsroot environment, it will be
		 * fairly common that we have the above case (e.g.,
		 * cwd checked out from one repository but
		 * subdirectory checked out from another).  We can't
		 * assume that by walking up a directory in our wd we
		 * necessarily walk up a directory in the repository.
		 */
		/*
		 * This gets toplevel_repos wrong for "cvs update ../foo"
		 * but I'm not sure toplevel_repos matters in that case.
		 */

		int repository_len, update_dir_len;

		strip_trailing_slashes (update_dir);

		repository_len = strlen (repository);
		update_dir_len = strlen (update_dir);

		/* Try to remove the path components in UPDATE_DIR
                   from REPOSITORY.  If the path elements don't exist
                   in REPOSITORY, or the removal of those path
                   elements mean that we "step above"
                   current_parsed_root->directory, set toplevel_repos to
                   current_parsed_root->directory. */
		if ((repository_len > update_dir_len)
		    && (strcmp (repository + repository_len - update_dir_len,
				update_dir) == 0)
		    /* TOPLEVEL_REPOS shouldn't be above current_parsed_root->directory */
		    && ((repository_len - update_dir_len)
			> strlen (current_parsed_root->directory)))
		{
		    /* The repository name contains UPDATE_DIR.  Set
                       toplevel_repos to the repository name without
                       UPDATE_DIR. */

		    toplevel_repos = xmalloc (repository_len - update_dir_len);
		    /* Note that we don't copy the trailing '/'.  */
		    strncpy (toplevel_repos, repository,
			     repository_len - update_dir_len - 1);
		    toplevel_repos[repository_len - update_dir_len - 1] = '\0';
		}
		else
		{
		    toplevel_repos = xstrdup (current_parsed_root->directory);
		}
	    }
	}
    }

    send_repository (dir, repository, update_dir);
}

/* The "expanded" modules.  */
static int modules_count;
static int modules_allocated;
static char **modules_vector;

static void
handle_module_expansion (args, len)
    char *args;
    int len;
{
    if (modules_vector == NULL)
    {
	modules_allocated = 1; /* Small for testing */
	modules_vector = (char **) xmalloc
	  (modules_allocated * sizeof (modules_vector[0]));
    }
    else if (modules_count >= modules_allocated)
    {
	modules_allocated *= 2;
	modules_vector = (char **) xrealloc
	  ((char *) modules_vector,
	   modules_allocated * sizeof (modules_vector[0]));
    }
    modules_vector[modules_count] = xmalloc (strlen (args) + 1);
    strcpy (modules_vector[modules_count], args);
    ++modules_count;
}

/* Original, not "expanded" modules.  */
static int module_argc;
static char **module_argv;

void
client_expand_modules (argc, argv, local)
    int argc;
    char **argv;
    int local;
{
    int errs;
    int i;

    module_argc = argc;
    module_argv = (char **) xmalloc ((argc + 1) * sizeof (module_argv[0]));
    for (i = 0; i < argc; ++i)
	module_argv[i] = xstrdup (argv[i]);
    module_argv[argc] = NULL;

    for (i = 0; i < argc; ++i)
	send_arg (argv[i]);
    send_a_repository ("", current_parsed_root->directory, "");

    send_to_server ("expand-modules\012", 0);

    errs = get_server_responses ();
    if (last_repos != NULL)
        free (last_repos);
    last_repos = NULL;
    if (last_update_dir != NULL)
        free (last_update_dir);
    last_update_dir = NULL;
    if (errs)
	error (errs, 0, "cannot expand modules");
}

void
client_send_expansions (local, where, build_dirs)
    int local;
    char *where;
    int build_dirs;
{
    int i;
    char *argv[1];

    /* Send the original module names.  The "expanded" module name might
       not be suitable as an argument to a co request (e.g. it might be
       the result of a -d argument in the modules file).  It might be
       cleaner if we genuinely expanded module names, all the way to a
       local directory and repository, but that isn't the way it works
       now.  */
    send_file_names (module_argc, module_argv, 0);

    for (i = 0; i < modules_count; ++i)
    {
	argv[0] = where ? where : modules_vector[i];
	if (isfile (argv[0]))
	    send_files (1, argv, local, 0, build_dirs ? SEND_BUILD_DIRS : 0);
    }
    send_a_repository ("", current_parsed_root->directory, "");
}

void
client_nonexpanded_setup ()
{
    send_a_repository ("", current_parsed_root->directory, "");
}

/* Receive a cvswrappers line from the server; it must be a line
   containing an RCS option (e.g., "*.exe   -k 'b'").

   Note that this doesn't try to handle -t/-f options (which are a
   whole separate issue which noone has thought much about, as far
   as I know).

   We need to know the keyword expansion mode so we know whether to
   read the file in text or binary mode.  */

static void
handle_wrapper_rcs_option (args, len)
    char *args;
    int len;
{
    char *p;

    /* Enforce the notes in cvsclient.texi about how the response is not
       as free-form as it looks.  */
    p = strchr (args, ' ');
    if (p == NULL)
	goto handle_error;
    if (*++p != '-'
	|| *++p != 'k'
	|| *++p != ' '
	|| *++p != '\'')
	goto handle_error;
    if (strchr (p, '\'') == NULL)
	goto handle_error;

    /* Add server-side cvswrappers line to our wrapper list. */
    wrap_add (args, 0);
    return;
 handle_error:
    error (0, errno, "protocol error: ignoring invalid wrappers %s", args);
}


static void
handle_m (args, len)
    char *args;
    int len;
{
    /* In the case where stdout and stderr point to the same place,
       fflushing stderr will make output happen in the correct order.
       Often stderr will be line-buffered and this won't be needed,
       but not always (is that true?  I think the comment is probably
       based on being confused between default buffering between
       stdout and stderr.  But I'm not sure).  */
    fflush (stderr);
    fwrite (args, len, sizeof (*args), stdout);
    putc ('\n', stdout);
}

static void handle_mbinary PROTO ((char *, int));

static void
handle_mbinary (args, len)
    char *args;
    int len;
{
    char *size_string;
    size_t size;
    size_t totalread;
    size_t nread;
    size_t toread;
    char buf[8192];

    /* See comment at handle_m about (non)flush of stderr.  */

    /* Get the size.  */
    read_line (&size_string);
    size = atoi (size_string);
    free (size_string);

    /* OK, now get all the data.  The algorithm here is that we read
       as much as the network wants to give us in
       try_read_from_server, and then we output it all, and then
       repeat, until we get all the data.  */
    totalread = 0;
    while (totalread < size)
    {
	toread = size - totalread;
	if (toread > sizeof buf)
	    toread = sizeof buf;

	nread = try_read_from_server (buf, toread);
	cvs_output_binary (buf, nread);
	totalread += nread;
    }
}

static void
handle_e (args, len)
    char *args;
    int len;
{
    /* In the case where stdout and stderr point to the same place,
       fflushing stdout will make output happen in the correct order.  */
    fflush (stdout);
    fwrite (args, len, sizeof (*args), stderr);
    putc ('\n', stderr);
}

/*ARGSUSED*/
static void
handle_f (args, len)
    char *args;
    int len;
{
    fflush (stderr);
}

static void handle_mt PROTO ((char *, int));

static void
handle_mt (args, len)
    char *args;
    int len;
{
    char *p;
    char *tag = args;
    char *text;

    /* See comment at handle_m for more details.  */
    fflush (stderr);

    p = strchr (args, ' ');
    if (p == NULL)
	text = NULL;
    else
    {
	*p++ = '\0';
	text = p;
    }

    switch (tag[0])
    {
	case '+':
	    if (strcmp (tag, "+updated") == 0)
		updated_seen = 1;
	    else if (strcmp (tag, "+importmergecmd") == 0)
		importmergecmd.seen = 1;
	    break;
	case '-':
	    if (strcmp (tag, "-updated") == 0)
		updated_seen = 0;
	    else if (strcmp (tag, "-importmergecmd") == 0)
	    {
		char buf[80];

		/* Now that we have gathered the information, we can
                   output the suggested merge command.  */

		if (importmergecmd.conflicts == 0
		    || importmergecmd.mergetag1 == NULL
		    || importmergecmd.mergetag2 == NULL
		    || importmergecmd.repository == NULL)
		{
		    error (0, 0,
			   "invalid server: incomplete importmergecmd tags");
		    break;
		}

		sprintf (buf, "\n%d conflicts created by this import.\n",
			 importmergecmd.conflicts);
		cvs_output (buf, 0);
		cvs_output ("Use the following command to help the merge:\n\n",
			    0);
		cvs_output ("\t", 1);
		cvs_output (program_name, 0);
		if (CVSroot_cmdline != NULL)
		{
		    cvs_output (" -d ", 0);
		    cvs_output (CVSroot_cmdline, 0);
		}
		cvs_output (" checkout -j", 0);
		cvs_output (importmergecmd.mergetag1, 0);
		cvs_output (" -j", 0);
		cvs_output (importmergecmd.mergetag2, 0);
		cvs_output (" ", 1);
		cvs_output (importmergecmd.repository, 0);
		cvs_output ("\n\n", 0);

		/* Clear the static variables so that everything is
                   ready for any subsequent importmergecmd tag.  */
		importmergecmd.conflicts = 0;
		free (importmergecmd.mergetag1);
		importmergecmd.mergetag1 = NULL;
		free (importmergecmd.mergetag2);
		importmergecmd.mergetag2 = NULL;
		free (importmergecmd.repository);
		importmergecmd.repository = NULL;

		importmergecmd.seen = 0;
	    }
	    break;
	default:
	    if (updated_seen)
	    {
		if (strcmp (tag, "fname") == 0)
		{
		    if (updated_fname != NULL)
		    {
			/* Output the previous message now.  This can happen
			   if there was no Update-existing or other such
			   response, due to the -n global option.  */
			cvs_output ("U ", 0);
			cvs_output (updated_fname, 0);
			cvs_output ("\n", 1);
			free (updated_fname);
		    }
		    updated_fname = xstrdup (text);
		}
		/* Swallow all other tags.  Either they are extraneous
		   or they reflect future extensions that we can
		   safely ignore.  */
	    }
	    else if (importmergecmd.seen)
	    {
		if (strcmp (tag, "conflicts") == 0)
		    importmergecmd.conflicts = atoi (text);
		else if (strcmp (tag, "mergetag1") == 0)
		    importmergecmd.mergetag1 = xstrdup (text);
		else if (strcmp (tag, "mergetag2") == 0)
		    importmergecmd.mergetag2 = xstrdup (text);
		else if (strcmp (tag, "repository") == 0)
		    importmergecmd.repository = xstrdup (text);
		/* Swallow all other tags.  Either they are text for
                   which we are going to print our own version when we
                   see -importmergecmd, or they are future extensions
                   we can safely ignore.  */
	    }
	    else if (strcmp (tag, "newline") == 0)
		printf ("\n");
	    else if (text != NULL)
		printf ("%s", text);
    }
}

#endif /* CLIENT_SUPPORT */
#if defined(CLIENT_SUPPORT) || defined(SERVER_SUPPORT)

/* This table must be writeable if the server code is included.  */
struct response responses[] =
{
#ifdef CLIENT_SUPPORT
#define RSP_LINE(n, f, t, s) {n, f, t, s}
#else /* ! CLIENT_SUPPORT */
#define RSP_LINE(n, f, t, s) {n, s}
#endif /* CLIENT_SUPPORT */

    RSP_LINE("ok", handle_ok, response_type_ok, rs_essential),
    RSP_LINE("error", handle_error, response_type_error, rs_essential),
    RSP_LINE("Valid-requests", handle_valid_requests, response_type_normal,
       rs_essential),
    RSP_LINE("Checked-in", handle_checked_in, response_type_normal,
       rs_essential),
    RSP_LINE("New-entry", handle_new_entry, response_type_normal, rs_optional),
    RSP_LINE("Checksum", handle_checksum, response_type_normal, rs_optional),
    RSP_LINE("Copy-file", handle_copy_file, response_type_normal, rs_optional),
    RSP_LINE("Updated", handle_updated, response_type_normal, rs_essential),
    RSP_LINE("Created", handle_created, response_type_normal, rs_optional),
    RSP_LINE("Update-existing", handle_update_existing, response_type_normal,
       rs_optional),
    RSP_LINE("Merged", handle_merged, response_type_normal, rs_essential),
    RSP_LINE("Patched", handle_patched, response_type_normal, rs_optional),
    RSP_LINE("Rcs-diff", handle_rcs_diff, response_type_normal, rs_optional),
    RSP_LINE("Mode", handle_mode, response_type_normal, rs_optional),
    RSP_LINE("Mod-time", handle_mod_time, response_type_normal, rs_optional),
    RSP_LINE("Removed", handle_removed, response_type_normal, rs_essential),
    RSP_LINE("Remove-entry", handle_remove_entry, response_type_normal,
       rs_optional),
    RSP_LINE("Set-static-directory", handle_set_static_directory,
       response_type_normal,
       rs_optional),
    RSP_LINE("Clear-static-directory", handle_clear_static_directory,
       response_type_normal,
       rs_optional),
    RSP_LINE("Set-sticky", handle_set_sticky, response_type_normal,
       rs_optional),
    RSP_LINE("Clear-sticky", handle_clear_sticky, response_type_normal,
       rs_optional),
    RSP_LINE("Template", handle_template, response_type_normal,
       rs_optional),
    RSP_LINE("Set-checkin-prog", handle_set_checkin_prog, response_type_normal,
       rs_optional),
    RSP_LINE("Set-update-prog", handle_set_update_prog, response_type_normal,
       rs_optional),
    RSP_LINE("Notified", handle_notified, response_type_normal, rs_optional),
    RSP_LINE("Module-expansion", handle_module_expansion, response_type_normal,
       rs_optional),
    RSP_LINE("Wrapper-rcsOption", handle_wrapper_rcs_option,
       response_type_normal,
       rs_optional),
    RSP_LINE("M", handle_m, response_type_normal, rs_essential),
    RSP_LINE("Mbinary", handle_mbinary, response_type_normal, rs_optional),
    RSP_LINE("E", handle_e, response_type_normal, rs_essential),
    RSP_LINE("F", handle_f, response_type_normal, rs_optional),
    RSP_LINE("MT", handle_mt, response_type_normal, rs_optional),
    /* Possibly should be response_type_error.  */
    RSP_LINE(NULL, NULL, response_type_normal, rs_essential)

#undef RSP_LINE
};

#endif /* CLIENT_SUPPORT or SERVER_SUPPORT */
#ifdef CLIENT_SUPPORT

/* 
 * If LEN is 0, then send_to_server() computes string's length itself.
 *
 * Therefore, pass the real length when transmitting data that might
 * contain 0's.
 */
void
send_to_server (str, len)
     char *str;
     size_t len;
{
    static int nbytes;

    if (len == 0)
	len = strlen (str);

    buf_output (to_server, str, len);
      
    /* There is no reason not to send data to the server, so do it
       whenever we've accumulated enough information in the buffer to
       make it worth sending.  */
    nbytes += len;
    if (nbytes >= 2 * BUFFER_DATA_SIZE)
    {
	int status;

        status = buf_send_output (to_server);
	if (status != 0)
	    error (1, status, "error writing to server");
	nbytes = 0;
    }
}

/* Read up to LEN bytes from the server.  Returns actual number of
   bytes read, which will always be at least one; blocks if there is
   no data available at all.  Gives a fatal error on EOF or error.  */
static size_t
try_read_from_server (buf, len)
    char *buf;
    size_t len;
{
    int status, nread;
    char *data;

    status = buf_read_data (from_server, len, &data, &nread);
    if (status != 0)
    {
	if (status == -1)
	    error (1, 0,
		   "end of file from server (consult above messages if any)");
	else if (status == -2)
	    error (1, 0, "out of memory");
	else
	    error (1, status, "reading from server");
    }

    memcpy (buf, data, nread);

    return nread;
}

/*
 * Read LEN bytes from the server or die trying.
 */
void
read_from_server (buf, len)
    char *buf;
    size_t len;
{
    size_t red = 0;
    while (red < len)
    {
	red += try_read_from_server (buf + red, len - red);
	if (red == len)
	    break;
    }
}

/*
 * Get some server responses and process them.  Returns nonzero for
 * error, 0 for success.  */
int
get_server_responses ()
{
    struct response *rs;
    do
    {
	char *cmd;
	int len;
	
	len = read_line (&cmd);
	for (rs = responses; rs->name != NULL; ++rs)
	    if (strncmp (cmd, rs->name, strlen (rs->name)) == 0)
	    {
		int cmdlen = strlen (rs->name);
		if (cmd[cmdlen] == '\0')
		    ;
		else if (cmd[cmdlen] == ' ')
		    ++cmdlen;
		else
		    /*
		     * The first len characters match, but it's a different
		     * response.  e.g. the response is "oklahoma" but we
		     * matched "ok".
		     */
		    continue;
		(*rs->func) (cmd + cmdlen, len - cmdlen);
		break;
	    }
	if (rs->name == NULL)
	    /* It's OK to print just to the first '\0'.  */
	    /* We might want to handle control characters and the like
	       in some other way other than just sending them to stdout.
	       One common reason for this error is if people use :ext:
	       with a version of rsh which is doing CRLF translation or
	       something, and so the client gets "ok^M" instead of "ok".
	       Right now that will tend to print part of this error
	       message over the other part of it.  It seems like we could
	       do better (either in general, by quoting or omitting all
	       control characters, and/or specifically, by detecting the CRLF
	       case and printing a specific error message).  */
	    error (0, 0,
		   "warning: unrecognized response `%s' from cvs server",
		   cmd);
	free (cmd);
    } while (rs->type == response_type_normal);

    if (updated_fname != NULL)
    {
	/* Output the previous message now.  This can happen
	   if there was no Update-existing or other such
	   response, due to the -n global option.  */
	cvs_output ("U ", 0);
	cvs_output (updated_fname, 0);
	cvs_output ("\n", 1);
	free (updated_fname);
	updated_fname = NULL;
    }

    if (rs->type == response_type_error)
	return 1;
    if (failure_exit)
	return 1;
    return 0;
}

/* Get the responses and then close the connection.  */
int server_fd = -1;

/*
 * Flag var; we'll set it in start_server() and not one of its
 * callees, such as start_rsh_server().  This means that there might
 * be a small window between the starting of the server and the
 * setting of this var, but all the code in that window shouldn't care
 * because it's busy checking return values to see if the server got
 * started successfully anyway.
 */
int server_started = 0;

int
get_responses_and_close ()
{
    int errs = get_server_responses ();
    int status;

    if (last_entries != NULL)
    {
	Entries_Close (last_entries);
	last_entries = NULL;
    }

    do_deferred_progs ();

    if (client_prune_dirs)
	process_prune_candidates ();

    /* The calls to buf_shutdown are currently only meaningful when we
       are using compression.  First we shut down TO_SERVER.  That
       tells the server that its input is finished.  It then shuts
       down the buffer it is sending to us, at which point our shut
       down of FROM_SERVER will complete.  */

    status = buf_shutdown (to_server);
    if (status != 0)
        error (0, status, "shutting down buffer to server");
    status = buf_shutdown (from_server);
    if (status != 0)
	error (0, status, "shutting down buffer from server");

#ifdef NO_SOCKET_TO_FD
    if (use_socket_style)
    {
	if (shutdown (server_sock, 2) < 0)
	    error (1, 0, "shutting down server socket: %s", SOCK_STRERROR (SOCK_ERRNO));
    }
    else
#endif /* NO_SOCKET_TO_FD */
    {
#if defined(HAVE_KERBEROS) || defined(AUTH_CLIENT_SUPPORT)
	if (server_fd != -1)
	{
	    if (shutdown (server_fd, 1) < 0)
		error (1, 0, "shutting down connection to %s: %s",
		       current_parsed_root->hostname, SOCK_STRERROR (SOCK_ERRNO));
	    server_fd = -1;
            /*
             * This test will always be true because we dup the descriptor
             */
	    if (fileno (from_server_fp) != fileno (to_server_fp))
	    {
		if (fclose (to_server_fp) != 0)
		    error (1, errno,
			   "closing down connection to %s",
			   current_parsed_root->hostname);
	    }
	}
        else
#endif
          
#ifdef SHUTDOWN_SERVER
	    SHUTDOWN_SERVER (fileno (to_server_fp));
#else /* ! SHUTDOWN_SERVER */
	{

#ifdef START_RSH_WITH_POPEN_RW
	    if (pclose (to_server_fp) == EOF)
#else /* ! START_RSH_WITH_POPEN_RW */
		if (fclose (to_server_fp) == EOF)
#endif /* START_RSH_WITH_POPEN_RW */
		{
		    error (1, errno, "closing connection to %s",
			   current_parsed_root->hostname);
		}
        }

	if (! buf_empty_p (from_server)
	    || getc (from_server_fp) != EOF)
	    error (0, 0, "dying gasps from %s unexpected", current_parsed_root->hostname);
	else if (ferror (from_server_fp))
	    error (0, errno, "reading from %s", current_parsed_root->hostname);

	fclose (from_server_fp);
#endif /* SHUTDOWN_SERVER */
    }

    if (rsh_pid != -1
	&& waitpid (rsh_pid, (int *) 0, 0) == -1)
	error (1, errno, "waiting for process %d", rsh_pid);

    buf_free (to_server);
    buf_free (from_server);
    server_started = 0;

    /* see if we need to sleep before returning to avoid time-stamp races */
    if (last_register_time)
    {
	sleep_past (last_register_time);
    }

    return errs;
}
	
#ifndef NO_EXT_METHOD
static void start_rsh_server PROTO((int *, int *));
#endif

int
supported_request (name)
    char *name;
{
    struct request *rq;

    for (rq = requests; rq->name; rq++)
	if (!strcmp (rq->name, name))
	    return (rq->flags & RQ_SUPPORTED) != 0;
    error (1, 0, "internal error: testing support for unknown option?");
    /* NOTREACHED */
    return 0;
}



#if defined (AUTH_CLIENT_SUPPORT) || defined (HAVE_KERBEROS)
static struct hostent *init_sockaddr PROTO ((struct sockaddr_in *, char *,
					     unsigned int));

static struct hostent *
init_sockaddr (name, hostname, port)
    struct sockaddr_in *name;
    char *hostname;
    unsigned int port;
{
    struct hostent *hostinfo;
    unsigned short shortport = port;

    memset (name, 0, sizeof (*name));
    name->sin_family = AF_INET;
    name->sin_port = htons (shortport);
    hostinfo = gethostbyname (hostname);
    if (hostinfo == NULL)
    {
	fprintf (stderr, "Unknown host %s.\n", hostname);
	error_exit ();
    }
    name->sin_addr = *(struct in_addr *) hostinfo->h_addr;
    return hostinfo;
}

#endif /* defined (AUTH_CLIENT_SUPPORT) || defined (HAVE_KERBEROS) */



#ifdef AUTH_CLIENT_SUPPORT

/* Generic function to do port number lookup tasks.
 *
 * In order of precedence, will return:
 * 	getenv (envname), if defined
 * 	getservbyname (portname), if defined
 * 	defaultport
 */
static int
get_port_number (envname, portname, defaultport)
    const char *envname;
    const char *portname;
    int defaultport;
{
    struct servent *s;
    char *port_s;

    if (envname && (port_s = getenv (envname)))
    {
	int port = atoi (port_s);
	if (port <= 0)
	{
	    error (0, 0, "%s must be a positive integer!  If you", envname);
	    error (0, 0, "are trying to force a connection via rsh, please");
	    error (0, 0, "put \":server:\" at the beginning of your CVSROOT");
	    error (1, 0, "variable.");
	}
	return port;
    }
    else if (portname && (s = getservbyname (portname, "tcp")))
	return ntohs (s->s_port);
    else
	return defaultport;
}



/* get the port number for a client to connect to based on the port
 * and method of a cvsroot_t.
 *
 * we do this here instead of in parse_cvsroot so that we can keep network
 * code confined to a localized area and also to delay the lookup until the
 * last possible moment so it remains possible to run cvs client commands that
 * skip opening connections to the server (i.e. skip network operations entirely)
 *
 * and yes, I know none of the the commands do that now, but here's to planning
 * for the future, eh?  cheers.
 *
 * FIXME - We could cache the port lookup safely right now as we never change
 * it for a single root on the fly, but we'd have to un'const some other
 * functions
 */
int
get_cvs_port_number (root)
    const cvsroot_t *root;
{

    if (root->port) return root->port;

    switch (root->method)
    {
	case gserver_method:
	case pserver_method:
	    return get_port_number ("CVS_CLIENT_PORT", "cvspserver", CVS_AUTH_PORT);
#ifdef HAVE_KERBEROS
	case kserver_method:
	    return get_port_number ("CVS_CLIENT_PORT", "cvs", CVS_PORT);
#endif
	default:
	    error(1, EINVAL, "internal error: get_cvs_port_number called for invalid connection method (%s)",
		    method_names[root->method]);
	    break;
    }
}



/* Read a line from socket SOCK.  Result does not include the
   terminating linefeed.  This is only used by the authentication
   protocol, which we call before we set up all the buffering stuff.
   It is possible it should use the buffers too, which would be faster
   (unlike the server, there isn't really a security issue in terms of
   separating authentication from the rest of the code).

   Space for the result is malloc'd and should be freed by the caller.

   Returns number of bytes read.  */
static int
recv_line (sock, resultp)
    int sock;
    char **resultp;
{
    char *result;
    size_t input_index = 0;
    size_t result_size = 80;

    result = (char *) xmalloc (result_size);

    while (1)
    {
	char ch;
	int n;
	n = recv (sock, &ch, 1, 0);
	if (n <= 0)
	    error (1, 0, "recv() from server %s: %s", current_parsed_root->hostname,
		   n == 0 ? "EOF" : SOCK_STRERROR (SOCK_ERRNO));

	if (ch == '\012')
	    break;

	result[input_index++] = ch;
	while (input_index + 1 >= result_size)
	{
	    result_size *= 2;
	    result = (char *) xrealloc (result, result_size);
	}
    }

    if (resultp)
	*resultp = result;

    /* Terminate it just for kicks, but we *can* deal with embedded NULs.  */
    result[input_index] = '\0';

    if (resultp == NULL)
	free (result);
    return input_index;
}

/* Connect to a forked server process. */

void
connect_to_forked_server (tofdp, fromfdp)
     int *tofdp, *fromfdp;
{
    /* This is pretty simple.  All we need to do is choose the correct
       cvs binary and call piped_child. */

    char *command[3];

    command[0] = getenv ("CVS_SERVER");
    if (! command[0])
	command[0] = program_path;
    
    command[1] = "server";
    command[2] = NULL;

    if (trace)
    {
	fprintf (stderr, " -> Forking server: %s %s\n", command[0], command[1]);
    }
    if (! piped_child (command, tofdp, fromfdp))
	error (1, 0, "could not fork server process");
}

/* Connect to the authenticating server.

   If VERIFY_ONLY is non-zero, then just verify that the password is
   correct and then shutdown the connection.

   If VERIFY_ONLY is 0, then really connect to the server.

   If DO_GSSAPI is non-zero, then we use GSSAPI authentication rather
   than the pserver password authentication.

   If we fail to connect or if access is denied, then die with fatal
   error.  */
void
connect_to_pserver (tofdp, fromfdp, verify_only, do_gssapi)
     int *tofdp, *fromfdp;
     int verify_only;
     int do_gssapi;
{
    int sock;
#ifndef NO_SOCKET_TO_FD
    int tofd, fromfd;
#endif
    int port_number;
    char *username;			/* the username we use to connect */
    struct sockaddr_in client_sai;
    struct hostent *hostinfo;
    char no_passwd = 0;			/* gets set if no password found */

    sock = socket (AF_INET, SOCK_STREAM, 0);
    if (sock == -1)
    {
	error (1, 0, "cannot create socket: %s", SOCK_STRERROR (SOCK_ERRNO));
    }
    port_number = get_cvs_port_number (current_parsed_root);
    hostinfo = init_sockaddr (&client_sai, current_parsed_root->hostname, port_number);
    if (trace)
    {
	fprintf (stderr, " -> Connecting to %s(%s):%d\n",
		 current_parsed_root->hostname,
		 inet_ntoa (client_sai.sin_addr), port_number);
    }
    if (connect (sock, (struct sockaddr *) &client_sai, sizeof (client_sai))
	< 0)
	error (1, 0, "connect to %s(%s):%d failed: %s",
	       current_parsed_root->hostname,
	       inet_ntoa (client_sai.sin_addr),
	       port_number, SOCK_STRERROR (SOCK_ERRNO));

    /* Run the authorization mini-protocol before anything else. */
    if (do_gssapi)
    {
#ifdef HAVE_GSSAPI
	if (! connect_to_gserver (sock, hostinfo))
	{
	    error (0, 0,
		    "authorization failed: server %s rejected access to %s",
		    current_parsed_root->hostname, current_parsed_root->directory);
	    goto rejected;
	}
#else
	error (1, 0, "This client does not support GSSAPI authentication");
#endif
    }
    else
    {
	char *begin      = NULL;
	char *password   = NULL;
	char *end        = NULL;
	
	if (verify_only)
	{
	    begin = "BEGIN VERIFICATION REQUEST\012";
	    end   = "END VERIFICATION REQUEST\012";
	}
	else
	{
	    begin = "BEGIN AUTH REQUEST\012";
	    end   = "END AUTH REQUEST\012";
	}

	/* Get the password, probably from ~/.cvspass. */
	password = get_cvs_password ();
        username = current_parsed_root->username ? current_parsed_root->username : getcaller();

        /* Send the empty string by default.  This is so anonymous CVS
           access doesn't require client to have done "cvs login". */
        if (password == NULL) 
        {
            no_passwd = 1;
            password = scramble ("");
        }

	/* Announce that we're starting the authorization protocol. */
	if (send (sock, begin, strlen (begin), 0) < 0)
	    error (1, 0, "cannot send: %s", SOCK_STRERROR (SOCK_ERRNO));

	/* Send the data the server needs. */
	if (send (sock, current_parsed_root->directory, strlen (current_parsed_root->directory), 0) < 0)
	    error (1, 0, "cannot send: %s", SOCK_STRERROR (SOCK_ERRNO));
	if (send (sock, "\012", 1, 0) < 0)
	    error (1, 0, "cannot send: %s", SOCK_STRERROR (SOCK_ERRNO));
	if (send (sock, username, strlen (username), 0) < 0)
	    error (1, 0, "cannot send: %s", SOCK_STRERROR (SOCK_ERRNO));
	if (send (sock, "\012", 1, 0) < 0)
	    error (1, 0, "cannot send: %s", SOCK_STRERROR (SOCK_ERRNO));
	if (send (sock, password, strlen (password), 0) < 0)
	    error (1, 0, "cannot send: %s", SOCK_STRERROR (SOCK_ERRNO));
	if (send (sock, "\012", 1, 0) < 0)
	    error (1, 0, "cannot send: %s", SOCK_STRERROR (SOCK_ERRNO));

	/* Announce that we're ending the authorization protocol. */
	if (send (sock, end, strlen (end), 0) < 0)
	    error (1, 0, "cannot send: %s", SOCK_STRERROR (SOCK_ERRNO));

        /* Paranoia. */
        memset (password, 0, strlen (password));
    }

    {
	char *read_buf;

	/* Loop, getting responses from the server.  */
	while (1)
	{
	    recv_line (sock, &read_buf);

	    if (strcmp (read_buf, "I HATE YOU") == 0)
	    {
		/* Authorization not granted.
		 *
		 * This is a little confusing since we can reach this while loop in GSSAPI
		 * mode, but if GSSAPI authentication failed, we already jumped to the
		 * rejected label (there is no case where the connect_to_gserver function
		 * can return 1 and we will not receive "I LOVE YOU" from the server, barring
		 * broken connections and garbled messages, of course).
		 *
		 * i.e. This is a pserver specific error message and shoiuld be since
		 * GSSAPI doesn't use username.
		 */
		error (0, 0,
			"authorization failed: server %s rejected access to %s for user %s",
			current_parsed_root->hostname, current_parsed_root->directory, username);

		/* Output a special error message if authentication was attempted
		with no password -- the user should be made aware that they may
		have missed a step. */
		if (no_passwd)
		{
		    error (0, 0,
			    "used empty password; try \"cvs login\" with a real password");
		}
		goto rejected;
	    }
	    else if (strncmp (read_buf, "E ", 2) == 0)
	    {
		fprintf (stderr, "%s\n", read_buf + 2);

		/* Continue with the authentication protocol.  */
	    }
	    else if (strncmp (read_buf, "error ", 6) == 0)
	    {
		char *p;

		/* First skip the code.  */
		p = read_buf + 6;
		while (*p != ' ' && *p != '\0')
		    ++p;

		/* Skip the space that follows the code.  */
		if (*p == ' ')
		    ++p;

		/* Now output the text.  */
		fprintf (stderr, "%s\n", p);
		goto rejected;
	    }
	    else if (strcmp (read_buf, "I LOVE YOU") == 0)
	    {
		free (read_buf);
		break;
	    }
	    else
	    {
		/* Unrecognized response from server. */
		if (shutdown (sock, 2) < 0)
		{
		    error (0, 0,
			   "unrecognized auth response from %s: %s", 
			   current_parsed_root->hostname, read_buf);
		    error (1, 0,
			   "shutdown() failed, server %s: %s",
			   current_parsed_root->hostname,
			   SOCK_STRERROR (SOCK_ERRNO));
		}
		error (1, 0, 
		       "unrecognized auth response from %s: %s", 
		       current_parsed_root->hostname, read_buf);
	    }
	    free (read_buf);
	}
    }

    if (verify_only)
    {
	if (shutdown (sock, 2) < 0)
	    error (0, 0, "shutdown() failed, server %s: %s", current_parsed_root->hostname,
		   SOCK_STRERROR (SOCK_ERRNO));
	return;
    }
    else
    {
#ifdef NO_SOCKET_TO_FD
	use_socket_style = 1;
	server_sock = sock;
	/* Try to break mistaken callers: */
	*tofdp = 0;
	*fromfdp = 0;
#else /* ! NO_SOCKET_TO_FD */
	server_fd = sock;
	close_on_exec (server_fd);
	tofd = fromfd = sock;
	/* Hand them back to the caller. */
	*tofdp   = tofd;
	*fromfdp = fromfd;
#endif /* NO_SOCKET_TO_FD */
    }

    return;

  rejected:
    if (shutdown (sock, 2) < 0)
    {
	error (0, 0,
	       "shutdown() failed (server %s): %s",
	       current_parsed_root->hostname,
	       SOCK_STRERROR (SOCK_ERRNO));
    }

    error_exit();
}
#endif /* AUTH_CLIENT_SUPPORT */



#ifdef HAVE_KERBEROS

/* This function has not been changed to deal with NO_SOCKET_TO_FD
   (i.e., systems on which sockets cannot be converted to file
   descriptors).  The first person to try building a kerberos client
   on such a system (OS/2, Windows 95, and maybe others) will have to
   make take care of this.  */
void
start_tcp_server (tofdp, fromfdp)
    int *tofdp, *fromfdp;
{
    int s;
    const char *portenv;
    int port;
    struct hostent *hp;
    struct sockaddr_in sin;
    char *hname;

    s = socket (AF_INET, SOCK_STREAM, 0);
    if (s < 0)
	error (1, 0, "cannot create socket: %s", SOCK_STRERROR (SOCK_ERRNO));

    port = get_cvs_port_number (current_parsed_root);

    hp = init_sockaddr (&sin, current_parsed_root->hostname, port);

    hname = xmalloc (strlen (hp->h_name) + 1);
    strcpy (hname, hp->h_name);
  
    if (trace)
    {
	fprintf (stderr, " -> Connecting to %s(%s):%d\n",
		 current_parsed_root->hostname,
		 inet_ntoa (client_sai.sin_addr), port);
    }

    if (connect (s, (struct sockaddr *) &sin, sizeof sin) < 0)
	error (1, 0, "connect to %s(%s):%d failed: %s",
	       current_parsed_root->hostname,
	       inet_ntoa (client_sai.sin_addr),
	       port, SOCK_STRERROR (SOCK_ERRNO));

    {
	const char *realm;
	struct sockaddr_in laddr;
	int laddrlen;
	KTEXT_ST ticket;
	MSG_DAT msg_data;
	CREDENTIALS cred;
	int status;

	realm = krb_realmofhost (hname);

	laddrlen = sizeof (laddr);
	if (getsockname (s, (struct sockaddr *) &laddr, &laddrlen) < 0)
	    error (1, 0, "getsockname failed: %s", SOCK_STRERROR (SOCK_ERRNO));

	/* We don't care about the checksum, and pass it as zero.  */
	status = krb_sendauth (KOPT_DO_MUTUAL, s, &ticket, "rcmd",
			       hname, realm, (unsigned long) 0, &msg_data,
			       &cred, sched, &laddr, &sin, "KCVSV1.0");
	if (status != KSUCCESS)
	    error (1, 0, "kerberos authentication failed: %s",
		   krb_get_err_text (status));
	memcpy (kblock, cred.session, sizeof (C_Block));
    }

    server_fd = s;
    close_on_exec (server_fd);

    free (hname);

    /* Give caller the values it wants. */
    *tofdp   = s;
    *fromfdp = s;
}

#endif /* HAVE_KERBEROS */

#ifdef HAVE_GSSAPI

/* Receive a given number of bytes.  */

static void
recv_bytes (sock, buf, need)
     int sock;
     char *buf;
     int need;
{
    while (need > 0)
    {
	int got;

	got = recv (sock, buf, need, 0);
	if (got <= 0)
	    error (1, 0, "recv() from server %s: %s", current_parsed_root->hostname,
		   got == 0 ? "EOF" : SOCK_STRERROR (SOCK_ERRNO));

	buf += got;
	need -= got;
    }
}

/* Connect to the server using GSSAPI authentication.  */

static int
connect_to_gserver (sock, hostinfo)
     int sock;
     struct hostent *hostinfo;
{
    char *str;
    char buf[1024];
    gss_buffer_desc *tok_in_ptr, tok_in, tok_out;
    OM_uint32 stat_min, stat_maj;
    gss_name_t server_name;

    str = "BEGIN GSSAPI REQUEST\012";

    if (send (sock, str, strlen (str), 0) < 0)
	error (1, 0, "cannot send: %s", SOCK_STRERROR (SOCK_ERRNO));

    sprintf (buf, "cvs@%s", hostinfo->h_name);
    tok_in.length = strlen (buf);
    tok_in.value = buf;
    gss_import_name (&stat_min, &tok_in, GSS_C_NT_HOSTBASED_SERVICE,
		     &server_name);

    tok_in_ptr = GSS_C_NO_BUFFER;
    gcontext = GSS_C_NO_CONTEXT;

    do
    {
	stat_maj = gss_init_sec_context (&stat_min, GSS_C_NO_CREDENTIAL,
					 &gcontext, server_name,
					 GSS_C_NULL_OID,
					 (GSS_C_MUTUAL_FLAG
					  | GSS_C_REPLAY_FLAG),
					 0, NULL, tok_in_ptr, NULL, &tok_out,
					 NULL, NULL);
	if (stat_maj != GSS_S_COMPLETE && stat_maj != GSS_S_CONTINUE_NEEDED)
	{
	    OM_uint32 message_context;
	    OM_uint32 new_stat_min;

	    message_context = 0;
	    gss_display_status (&new_stat_min, stat_maj, GSS_C_GSS_CODE,
                                GSS_C_NULL_OID, &message_context, &tok_out);
	    error (0, 0, "GSSAPI authentication failed: %s",
		   (char *) tok_out.value);

	    message_context = 0;
	    gss_display_status (&new_stat_min, stat_min, GSS_C_MECH_CODE,
				GSS_C_NULL_OID, &message_context, &tok_out);
	    error (1, 0, "GSSAPI authentication failed: %s",
		   (char *) tok_out.value);
	}

	if (tok_out.length == 0)
	{
	    tok_in.length = 0;
	}
	else
	{
	    char cbuf[2];
	    int need;

	    cbuf[0] = (tok_out.length >> 8) & 0xff;
	    cbuf[1] = tok_out.length & 0xff;
	    if (send (sock, cbuf, 2, 0) < 0)
		error (1, 0, "cannot send: %s", SOCK_STRERROR (SOCK_ERRNO));
	    if (send (sock, tok_out.value, tok_out.length, 0) < 0)
		error (1, 0, "cannot send: %s", SOCK_STRERROR (SOCK_ERRNO));

	    recv_bytes (sock, cbuf, 2);
	    need = ((cbuf[0] & 0xff) << 8) | (cbuf[1] & 0xff);

	    if (need > sizeof buf)
	    {
		int got;

		/* This usually means that the server sent us an error
		   message.  Read it byte by byte and print it out.
		   FIXME: This is a terrible error handling strategy.
		   However, even if we fix the server, we will still
		   want to do this to work with older servers.  */
		buf[0] = cbuf[0];
		buf[1] = cbuf[1];
		got = recv (sock, buf + 2, sizeof buf - 2, 0);
		if (got < 0)
		    error (1, 0, "recv() from server %s: %s",
			   current_parsed_root->hostname, SOCK_STRERROR (SOCK_ERRNO));
		buf[got + 2] = '\0';
		if (buf[got + 1] == '\n')
		    buf[got + 1] = '\0';
		error (1, 0, "error from server %s: %s", current_parsed_root->hostname,
		       buf);
	    }

	    recv_bytes (sock, buf, need);
	    tok_in.length = need;
	}

	tok_in.value = buf;
	tok_in_ptr = &tok_in;
    }
    while (stat_maj == GSS_S_CONTINUE_NEEDED);

    return 1;
}

#endif /* HAVE_GSSAPI */

static int send_variable_proc PROTO ((Node *, void *));

static int
send_variable_proc (node, closure)
    Node *node;
    void *closure;
{
    send_to_server ("Set ", 0);
    send_to_server (node->key, 0);
    send_to_server ("=", 1);
    send_to_server (node->data, 0);
    send_to_server ("\012", 1);
    return 0;
}

/* Contact the server.  */
void
start_server ()
{
    int tofd, fromfd, rootless;
    char *log = getenv ("CVS_CLIENT_LOG");


    /* Clear our static variables for this invocation. */
    if (toplevel_repos != NULL)
	free (toplevel_repos);
    toplevel_repos = NULL;


    /* Note that generally speaking we do *not* fall back to a different
       way of connecting if the first one does not work.  This is slow
       (*really* slow on a 14.4kbps link); the clean way to have a CVS
       which supports several ways of connecting is with access methods.  */

    switch (current_parsed_root->method)
    {

#ifdef AUTH_CLIENT_SUPPORT
	case pserver_method:
	    /* Toss the return value.  It will die with error if anything
	       goes wrong anyway. */
	    connect_to_pserver (&tofd, &fromfd, 0, 0);
	    break;
#endif

#if HAVE_KERBEROS
	case kserver_method:
	    start_tcp_server (&tofd, &fromfd);
	    break;
#endif

#ifdef HAVE_GSSAPI
	case gserver_method:
	    /* GSSAPI authentication is handled by the pserver.  */
	    connect_to_pserver (&tofd, &fromfd, 0, 1);
	    break;
#endif

	case ext_method:
#if defined (NO_EXT_METHOD)
	    error (0, 0, ":ext: method not supported by this port of CVS");
	    error (1, 0, "try :server: instead");
#else
	    start_rsh_server (&tofd, &fromfd);
#endif
	    break;

	case server_method:
#if defined(START_SERVER)
	    START_SERVER (&tofd, &fromfd, getcaller (),
			  current_parsed_root->username, current_parsed_root->hostname,
			  current_parsed_root->directory);
#  if defined (START_SERVER_RETURNS_SOCKET) && defined (NO_SOCKET_TO_FD)
	    /* This is a system on which we can only write to a socket
	       using send/recv.  Therefore its START_SERVER needs to
	       return a socket.  */
	    use_socket_style = 1;
	    server_sock = tofd;
#  endif

#else
	    /* FIXME: It should be possible to implement this portably,
	       like pserver, which would get rid of the duplicated code
	       in {vms,windows-NT,...}/startserver.c.  */
	    error (1, 0, "\
the :server: access method is not supported by this port of CVS");
#endif
	    break;

        case fork_method:
	    connect_to_forked_server (&tofd, &fromfd);
	    break;

	default:
	    error (1, 0, "\
(start_server internal error): unknown access method");
	    break;
    }

    /* "Hi, I'm Darlene and I'll be your server tonight..." */
    server_started = 1;

#ifdef NO_SOCKET_TO_FD
    if (use_socket_style)
    {
	to_server = socket_buffer_initialize (server_sock, 0,
					      (BUFMEMERRPROC) NULL);
	from_server = socket_buffer_initialize (server_sock, 1,
						(BUFMEMERRPROC) NULL);
    }
    else
#endif /* NO_SOCKET_TO_FD */
    {
        /* todo: some OS's don't need these calls... */
        close_on_exec (tofd);
        close_on_exec (fromfd);

	/* SCO 3 and AIX have a nasty bug in the I/O libraries which precludes
	   fdopening the same file descriptor twice, so dup it if it is the
	   same.  */
	if (tofd == fromfd)
	{
	    fromfd = dup (tofd);
	    if (fromfd < 0)
		error (1, errno, "cannot dup net connection");
	}

        /* These will use binary mode on systems which have it.  */
        to_server_fp = fdopen (tofd, FOPEN_BINARY_WRITE);
        if (to_server_fp == NULL)
	    error (1, errno, "cannot fdopen %d for write", tofd);
	to_server = stdio_buffer_initialize (to_server_fp, 0,
					     (BUFMEMERRPROC) NULL);

        from_server_fp = fdopen (fromfd, FOPEN_BINARY_READ);
        if (from_server_fp == NULL)
	    error (1, errno, "cannot fdopen %d for read", fromfd);
	from_server = stdio_buffer_initialize (from_server_fp, 1,
					       (BUFMEMERRPROC) NULL);
    }

    /* Set up logfiles, if any. */
    if (log)
    {
	int len = strlen (log);
	char *buf = xmalloc (len + 5);
	char *p;
	FILE *fp;

	strcpy (buf, log);
	p = buf + len;

	/* Open logfiles in binary mode so that they reflect
	   exactly what was transmitted and received (that is
	   more important than that they be maximally
	   convenient to view).  */
	/* Note that if we create several connections in a single CVS client
	   (currently used by update.c), then the last set of logfiles will
	   overwrite the others.  There is currently no way around this.  */
	strcpy (p, ".in");
	fp = open_file (buf, "wb");
        if (fp == NULL)
	    error (0, errno, "opening to-server logfile %s", buf);
	else
	    to_server = log_buffer_initialize (to_server, fp, 0,
					       (BUFMEMERRPROC) NULL);

	strcpy (p, ".out");
	fp = open_file (buf, "wb");
        if (fp == NULL)
	    error (0, errno, "opening from-server logfile %s", buf);
	else
	    from_server = log_buffer_initialize (from_server, fp, 1,
						 (BUFMEMERRPROC) NULL);

	free (buf);
    }

    /* Clear static variables.  */
    if (toplevel_repos != NULL)
	free (toplevel_repos);
    toplevel_repos = NULL;
    if (last_dir_name != NULL)
	free (last_dir_name);
    last_dir_name = NULL;
    if (last_repos != NULL)
	free (last_repos);
    last_repos = NULL;
    if (last_update_dir != NULL)
	free (last_update_dir);
    last_update_dir = NULL;
    stored_checksum_valid = 0;
    if (stored_mode != NULL)
    {
	free (stored_mode);
	stored_mode = NULL;
    }

    rootless = (strcmp (command_name, "init") == 0);
    if (!rootless)
    {
	send_to_server ("Root ", 0);
	send_to_server (current_parsed_root->directory, 0);
	send_to_server ("\012", 1);
    }

    {
	struct response *rs;

	send_to_server ("Valid-responses", 0);

	for (rs = responses; rs->name != NULL; ++rs)
	{
	    send_to_server (" ", 0);
	    send_to_server (rs->name, 0);
	}
	send_to_server ("\012", 1);
    }
    send_to_server ("valid-requests\012", 0);

    if (get_server_responses ())
	error_exit ();

    /*
     * Now handle global options.
     *
     * -H, -f, -d, -e should be handled OK locally.
     *
     * -b we ignore (treating it as a server installation issue).
     * FIXME: should be an error message.
     *
     * -v we print local version info; FIXME: Add a protocol request to get
     * the version from the server so we can print that too.
     *
     * -l -t -r -w -q -n and -Q need to go to the server.
     */

    {
	int have_global = supported_request ("Global_option");

	if (noexec)
	{
	    if (have_global)
	    {
		send_to_server ("Global_option -n\012", 0);
	    }
	    else
		error (1, 0,
		       "This server does not support the global -n option.");
	}
	if (quiet)
	{
	    if (have_global)
	    {
		send_to_server ("Global_option -q\012", 0);
	    }
	    else
		error (1, 0,
		       "This server does not support the global -q option.");
	}
	if (really_quiet)
	{
	    if (have_global)
	    {
		send_to_server ("Global_option -Q\012", 0);
	    }
	    else
		error (1, 0,
		       "This server does not support the global -Q option.");
	}
	if (!cvswrite)
	{
	    if (have_global)
	    {
		send_to_server ("Global_option -r\012", 0);
	    }
	    else
		error (1, 0,
		       "This server does not support the global -r option.");
	}
	if (trace)
	{
	    if (have_global)
	    {
		send_to_server ("Global_option -t\012", 0);
	    }
	    else
		error (1, 0,
		       "This server does not support the global -t option.");
	}
	if (logoff)
	{
	    if (have_global)
	    {
		send_to_server ("Global_option -l\012", 0);
	    }
	    else
		error (1, 0,
		       "This server does not support the global -l option.");
	}
    }

    /* Find out about server-side cvswrappers.  An extra network
       turnaround for cvs import seems to be unavoidable, unless we
       want to add some kind of client-side place to configure which
       filenames imply binary.  For cvs add, we could avoid the
       problem by keeping a copy of the wrappers in CVSADM (the main
       reason to bother would be so we could make add work without
       contacting the server, I suspect).  */

    if ((strcmp (command_name, "import") == 0)
        || (strcmp (command_name, "add") == 0))
    {
	if (supported_request ("wrapper-sendme-rcsOptions"))
	{
	    int err;
	    send_to_server ("wrapper-sendme-rcsOptions\012", 0);
	    err = get_server_responses ();
	    if (err != 0)
		error (err, 0, "error reading from server");
	}
    }

    if (cvsencrypt && !rootless)
    {
#ifdef ENCRYPTION
	/* Turn on encryption before turning on compression.  We do
           not want to try to compress the encrypted stream.  Instead,
           we want to encrypt the compressed stream.  If we can't turn
           on encryption, bomb out; don't let the user think the data
           is being encrypted when it is not.  */
#ifdef HAVE_KERBEROS
	if (current_parsed_root->method == kserver_method)
	{
	    if (! supported_request ("Kerberos-encrypt"))
		error (1, 0, "This server does not support encryption");
	    send_to_server ("Kerberos-encrypt\012", 0);
	    to_server = krb_encrypt_buffer_initialize (to_server, 0, sched,
						       kblock,
						       (BUFMEMERRPROC) NULL);
	    from_server = krb_encrypt_buffer_initialize (from_server, 1,
							 sched, kblock,
							 (BUFMEMERRPROC) NULL);
	}
	else
#endif /* HAVE_KERBEROS */
#ifdef HAVE_GSSAPI
	if (current_parsed_root->method == gserver_method)
	{
	    if (! supported_request ("Gssapi-encrypt"))
		error (1, 0, "This server does not support encryption");
	    send_to_server ("Gssapi-encrypt\012", 0);
	    to_server = cvs_gssapi_wrap_buffer_initialize (to_server, 0,
							   gcontext,
							   ((BUFMEMERRPROC)
							    NULL));
	    from_server = cvs_gssapi_wrap_buffer_initialize (from_server, 1,
							     gcontext,
							     ((BUFMEMERRPROC)
							      NULL));
	    cvs_gssapi_encrypt = 1;
	}
	else
#endif /* HAVE_GSSAPI */
	    error (1, 0, "Encryption is only supported when using GSSAPI or Kerberos");
#else /* ! ENCRYPTION */
	error (1, 0, "This client does not support encryption");
#endif /* ! ENCRYPTION */
    }

    if (gzip_level && !rootless)
    {
	if (supported_request ("Gzip-stream"))
	{
	    char gzip_level_buf[5];
	    send_to_server ("Gzip-stream ", 0);
	    sprintf (gzip_level_buf, "%d", gzip_level);
	    send_to_server (gzip_level_buf, 0);
	    send_to_server ("\012", 1);

	    /* All further communication with the server will be
               compressed.  */

	    to_server = compress_buffer_initialize (to_server, 0, gzip_level,
						    (BUFMEMERRPROC) NULL);
	    from_server = compress_buffer_initialize (from_server, 1,
						      gzip_level,
						      (BUFMEMERRPROC) NULL);
	}
#ifndef NO_CLIENT_GZIP_PROCESS
	else if (supported_request ("gzip-file-contents"))
	{
            char gzip_level_buf[5];
	    send_to_server ("gzip-file-contents ", 0);
            sprintf (gzip_level_buf, "%d", gzip_level);
	    send_to_server (gzip_level_buf, 0);

	    send_to_server ("\012", 1);

	    file_gzip_level = gzip_level;
	}
#endif
	else
	{
	    fprintf (stderr, "server doesn't support gzip-file-contents\n");
	    /* Setting gzip_level to 0 prevents us from giving the
               error twice if update has to contact the server again
               to fetch unpatchable files.  */
	    gzip_level = 0;
	}
    }

    if (cvsauthenticate && ! cvsencrypt && !rootless)
    {
	/* Turn on authentication after turning on compression, so
	   that we can compress the authentication information.  We
	   assume that encrypted data is always authenticated--the
	   ability to decrypt the data stream is itself a form of
	   authentication.  */
#ifdef HAVE_GSSAPI
	if (current_parsed_root->method == gserver_method)
	{
	    if (! supported_request ("Gssapi-authenticate"))
		error (1, 0,
		       "This server does not support stream authentication");
	    send_to_server ("Gssapi-authenticate\012", 0);
	    to_server = cvs_gssapi_wrap_buffer_initialize (to_server, 0,
							   gcontext,
							   ((BUFMEMERRPROC)
							    NULL));
	    from_server = cvs_gssapi_wrap_buffer_initialize (from_server, 1,
							     gcontext,
							     ((BUFMEMERRPROC)
							      NULL));
	}
	else
	    error (1, 0, "Stream authentication is only supported when using GSSAPI");
#else /* ! HAVE_GSSAPI */
	error (1, 0, "This client does not support stream authentication");
#endif /* ! HAVE_GSSAPI */
    }

#ifdef FILENAMES_CASE_INSENSITIVE
    if (supported_request ("Case") && !rootless)
	send_to_server ("Case\012", 0);
#endif

    /* If "Set" is not supported, just silently fail to send the variables.
       Users with an old server should get a useful error message when it
       fails to recognize the ${=foo} syntax.  This way if someone uses
       several servers, some of which are new and some old, they can still
       set user variables in their .cvsrc without trouble.  */
    if (supported_request ("Set"))
	walklist (variable_list, send_variable_proc, NULL);
}

#ifndef NO_EXT_METHOD

/* Contact the server by starting it with rsh.  */

/* Right now, we have two different definitions for this function,
   depending on whether we start the rsh server using popenRW or not.
   This isn't ideal, and the best thing would probably be to change
   the OS/2 port to be more like the regular Unix client (i.e., by
   implementing piped_child)... but I'm doing something else at the
   moment, and wish to make only one change at a time.  -Karl */

#ifdef START_RSH_WITH_POPEN_RW

/* This is actually a crock -- it's OS/2-specific, for no one else
   uses it.  If I get time, I want to make piped_child and all the
   other stuff in os2/run.c work right.  In the meantime, this gets us
   up and running, and that's most important. */

static void
start_rsh_server (tofdp, fromfdp)
    int *tofdp, *fromfdp;
{
    int pipes[2];

    /* If you're working through firewalls, you can set the
       CVS_RSH environment variable to a script which uses rsh to
       invoke another rsh on a proxy machine.  */
    char *cvs_rsh = getenv ("CVS_RSH");
    char *cvs_server = getenv ("CVS_SERVER");
    int i = 0;
    /* This needs to fit "rsh", "-b", "-l", "USER", "host",
       "cmd (w/ args)", and NULL.  We leave some room to grow. */
    char *rsh_argv[10];

    if (!cvs_rsh)
	/* People sometimes suggest or assume that this should default
	   to "remsh" on systems like HPUX in which that is the
	   system-supplied name for the rsh program.  However, that
	   causes various problems (keep in mind that systems such as
	   HPUX might have non-system-supplied versions of "rsh", like
	   a Kerberized one, which one might want to use).  If we
	   based the name on what is found in the PATH of the person
	   who runs configure, that would make it harder to
	   consistently produce the same result in the face of
	   different people producing binary distributions.  If we
	   based it on "remsh" always being the default for HPUX
	   (e.g. based on uname), that might be slightly better but
	   would require us to keep track of what the defaults are for
	   each system type, and probably would cope poorly if the
	   existence of remsh or rsh varies from OS version to OS
	   version.  Therefore, it seems best to have the default
	   remain "rsh", and tell HPUX users to specify remsh, for
	   example in CVS_RSH or other such mechanisms to be devised,
	   if that is what they want (the manual already tells them
	   that).  */
	cvs_rsh = "rsh";
    if (!cvs_server)
	cvs_server = "cvs";

    /* The command line starts out with rsh. */
    rsh_argv[i++] = cvs_rsh;

#ifdef RSH_NEEDS_BINARY_FLAG
    /* "-b" for binary, under OS/2. */
    rsh_argv[i++] = "-b";
#endif /* RSH_NEEDS_BINARY_FLAG */

    /* Then we strcat more things on the end one by one. */
    if (current_parsed_root->username != NULL)
    {
	rsh_argv[i++] = "-l";
	rsh_argv[i++] = current_parsed_root->username;
    }

    rsh_argv[i++] = current_parsed_root->hostname;
    rsh_argv[i++] = cvs_server;
    rsh_argv[i++] = "server";

    /* Mark the end of the arg list. */
    rsh_argv[i]   = (char *) NULL;

    if (trace)
    {
	fprintf (stderr, " -> Starting server: ");
	for (i = 0; rsh_argv[i]; i++)
	    fprintf (stderr, "%s ", rsh_argv[i]);
	putc ('\n', stderr);
    }

    /* Do the deed. */
    rsh_pid = popenRW (rsh_argv, pipes);
    if (rsh_pid < 0)
	error (1, errno, "cannot start server via rsh");

    /* Give caller the file descriptors. */
    *tofdp   = pipes[0];
    *fromfdp = pipes[1];
}

#else /* ! START_RSH_WITH_POPEN_RW */

static void
start_rsh_server (tofdp, fromfdp)
     int *tofdp;
     int *fromfdp;
{
    /* If you're working through firewalls, you can set the
       CVS_RSH environment variable to a script which uses rsh to
       invoke another rsh on a proxy machine.  */
    char *cvs_rsh = getenv ("CVS_RSH");
    char *cvs_server = getenv ("CVS_SERVER");
    char *command;

    if (!cvs_rsh)
	cvs_rsh = "rsh";
    if (!cvs_server)
	cvs_server = "cvs";

    /* Pass the command to rsh as a single string.  This shouldn't
       affect most rsh servers at all, and will pacify some buggy
       versions of rsh that grab switches out of the middle of the
       command (they're calling the GNU getopt routines incorrectly).  */
    command = xmalloc (strlen (cvs_server)
		       + strlen (current_parsed_root->directory)
		       + 50);

    /* If you are running a very old (Nov 3, 1994, before 1.5)
     * version of the server, you need to make sure that your .bashrc
     * on the server machine does not set CVSROOT to something
     * containing a colon (or better yet, upgrade the server).  */
    sprintf (command, "%s server", cvs_server);

    {
        char *argv[10];
	char **p = argv;

	*p++ = cvs_rsh;
	*p++ = current_parsed_root->hostname;

	/* If the login names differ between client and server
	 * pass it on to rsh.
	 */
	if (current_parsed_root->username != NULL)
	{
	    *p++ = "-l";
	    *p++ = current_parsed_root->username;
	}

	*p++ = command;
	*p++ = NULL;

	if (trace)
        {
	    int i;

            fprintf (stderr, " -> Starting server: ");
	    for (i = 0; argv[i]; i++)
	        fprintf (stderr, "%s ", argv[i]);
	    putc ('\n', stderr);
	}
	rsh_pid = piped_child (argv, tofdp, fromfdp);

	if (rsh_pid < 0)
	    error (1, errno, "cannot start server via rsh");
    }
    free (command);
}

#endif /* START_RSH_WITH_POPEN_RW */

#endif /* NO_EXT_METHOD */



/* Send an argument STRING.  */
void
send_arg (string)
    char *string;
{
    char buf[1];
    char *p = string;

    send_to_server ("Argument ", 0);

    while (*p)
    {
	if (*p == '\n')
	{
	    send_to_server ("\012Argumentx ", 0);
	}
	else
        {
	    buf[0] = *p;
	    send_to_server (buf, 1);
        }
	++p;
    }
    send_to_server ("\012", 1);
}

static void send_modified PROTO ((char *, char *, Vers_TS *));

/* VERS->OPTIONS specifies whether the file is binary or not.  NOTE: BEFORE
   using any other fields of the struct vers, we would need to fix
   client_process_import_file to set them up.  */

static void
send_modified (file, short_pathname, vers)
    char *file;
    char *short_pathname;
    Vers_TS *vers;
{
    /* File was modified, send it.  */
    struct stat sb;
    int fd;
    char *buf;
    char *mode_string;
    size_t bufsize;
    int bin;

    if (trace)
	(void) fprintf (stderr, " -> Sending file `%s' to server\n", file);

    /* Don't think we can assume fstat exists.  */
    if ( CVS_STAT (file, &sb) < 0)
	error (1, errno, "reading %s", short_pathname);

    mode_string = mode_to_string (sb.st_mode);

    /* Beware: on systems using CRLF line termination conventions,
       the read and write functions will convert CRLF to LF, so the
       number of characters read is not the same as sb.st_size.  Text
       files should always be transmitted using the LF convention, so
       we don't want to disable this conversion.  */
    bufsize = sb.st_size;
    buf = xmalloc (bufsize);

    /* Is the file marked as containing binary data by the "-kb" flag?
       If so, make sure to open it in binary mode: */

    if (vers && vers->options)
      bin = !(strcmp (vers->options, "-kb"));
    else
      bin = 0;

#ifdef BROKEN_READWRITE_CONVERSION
    if (!bin)
    {
	/* If only stdio, not open/write/etc., do text/binary
	   conversion, use convert_file which can compensate
	   (FIXME: we could just use stdio instead which would
	   avoid the whole problem).  */
	char tfile[1024]; strcpy(tfile, file); strcat(tfile, ".CVSBFCTMP");
	convert_file (file, O_RDONLY,
		      tfile, O_WRONLY | O_CREAT | O_TRUNC | OPEN_BINARY);
	fd = CVS_OPEN (tfile, O_RDONLY | OPEN_BINARY);
	if (fd < 0)
	    error (1, errno, "reading %s", short_pathname);
    }
    else
	fd = CVS_OPEN (file, O_RDONLY | OPEN_BINARY);
#else
    fd = CVS_OPEN (file, O_RDONLY | (bin ? OPEN_BINARY : 0));
#endif

    if (fd < 0)
	error (1, errno, "reading %s", short_pathname);

    if (file_gzip_level && sb.st_size > 100)
    {
	size_t newsize = 0;

	if (read_and_gzip (fd, short_pathname, (unsigned char **)&buf,
			   &bufsize, &newsize,
			   file_gzip_level))
	    error (1, 0, "aborting due to compression error");

	if (close (fd) < 0)
	    error (0, errno, "warning: can't close %s", short_pathname);

        {
          char tmp[80];

	  send_to_server ("Modified ", 0);
	  send_to_server (file, 0);
	  send_to_server ("\012", 1);
	  send_to_server (mode_string, 0);
	  send_to_server ("\012z", 2);
	  sprintf (tmp, "%lu\n", (unsigned long) newsize);
	  send_to_server (tmp, 0);

          send_to_server (buf, newsize);
        }
    }
    else
    {
    	int newsize;

        {
	    char *bufp = buf;
	    int len;

	    /* FIXME: This is gross.  It assumes that we might read
	       less than st_size bytes (true on NT), but not more.
	       Instead of this we should just be reading a block of
	       data (e.g. 8192 bytes), writing it to the network, and
	       so on until EOF.  */
	    while ((len = read (fd, bufp, (buf + sb.st_size) - bufp)) > 0)
	        bufp += len;

	    if (len < 0)
	        error (1, errno, "reading %s", short_pathname);

	    newsize = bufp - buf;
	}
	if (close (fd) < 0)
	    error (0, errno, "warning: can't close %s", short_pathname);

        {
          char tmp[80];

	  send_to_server ("Modified ", 0);
	  send_to_server (file, 0);
	  send_to_server ("\012", 1);
	  send_to_server (mode_string, 0);
	  send_to_server ("\012", 1);
          sprintf (tmp, "%lu\012", (unsigned long) newsize);
          send_to_server (tmp, 0);
        }
#ifdef BROKEN_READWRITE_CONVERSION
	if (!bin)
	{
	    char tfile[1024]; strcpy(tfile, file); strcat(tfile, ".CVSBFCTMP");
	    if (CVS_UNLINK (tfile) < 0)
		error (0, errno, "warning: can't remove temp file %s", tfile);
	}
#endif

	/*
	 * Note that this only ends with a newline if the file ended with
	 * one.
	 */
	if (newsize > 0)
	    send_to_server (buf, newsize);
    }
    free (buf);
    free (mode_string);
}

/* The address of an instance of this structure is passed to
   send_fileproc, send_filesdoneproc, and send_direntproc, as the
   callerdat parameter.  */

struct send_data
{
    /* Each of the following flags are zero for clear or nonzero for set.  */
    int build_dirs;
    int force;
    int no_contents;
    int backup_modified;
};

static int send_fileproc PROTO ((void *callerdat, struct file_info *finfo));

/* Deal with one file.  */
static int
send_fileproc (callerdat, finfo)
    void *callerdat;
    struct file_info *finfo;
{
    struct send_data *args = (struct send_data *) callerdat;
    Vers_TS *vers;
    struct file_info xfinfo;
    /* File name to actually use.  Might differ in case from
       finfo->file.  */
    char *filename;

    send_a_repository ("", finfo->repository, finfo->update_dir);

    xfinfo = *finfo;
    xfinfo.repository = NULL;
    xfinfo.rcs = NULL;
    vers = Version_TS (&xfinfo, NULL, NULL, NULL, 0, 0);

    if (vers->entdata != NULL)
	filename = vers->entdata->user;
    else
	filename = finfo->file;

    if (vers->vn_user != NULL)
    {
	/* The Entries request.  */
	send_to_server ("Entry /", 0);
	send_to_server (filename, 0);
	send_to_server ("/", 0);
	send_to_server (vers->vn_user, 0);
	send_to_server ("/", 0);
	if (vers->ts_conflict != NULL)
	{
	    if (vers->ts_user != NULL &&
		strcmp (vers->ts_conflict, vers->ts_user) == 0)
		send_to_server ("+=", 0);
	    else
		send_to_server ("+modified", 0);
	}
	send_to_server ("/", 0);
	send_to_server (vers->entdata != NULL
			? vers->entdata->options
			: vers->options,
			0);
	send_to_server ("/", 0);
	if (vers->entdata != NULL && vers->entdata->tag)
	{
	    send_to_server ("T", 0);
	    send_to_server (vers->entdata->tag, 0);
	}
	else if (vers->entdata != NULL && vers->entdata->date)
          {
	    send_to_server ("D", 0);
	    send_to_server (vers->entdata->date, 0);
          }
	send_to_server ("\012", 1);
    }
    else
    {
	/* It seems a little silly to re-read this on each file, but
	   send_dirent_proc doesn't get called if filenames are specified
	   explicitly on the command line.  */
	wrap_add_file (CVSDOTWRAPPER, 1);

	if (wrap_name_has (filename, WRAP_RCSOPTION))
	{
	    /* No "Entry", but the wrappers did give us a kopt so we better
	       send it with "Kopt".  As far as I know this only happens
	       for "cvs add".  Question: is there any reason why checking
	       for options from wrappers isn't done in Version_TS?

	       Note: it might have been better to just remember all the
	       kopts on the client side, rather than send them to the server,
	       and have it send us back the same kopts.  But that seemed like
	       a bigger change than I had in mind making now.  */

	    if (supported_request ("Kopt"))
	    {
		char *opt;

		send_to_server ("Kopt ", 0);
		opt = wrap_rcsoption (filename, 1);
		send_to_server (opt, 0);
		send_to_server ("\012", 1);
		free (opt);
	    }
	    else
		error (0, 0,
		       "\
warning: ignoring -k options due to server limitations");
	}
    }

    if (vers->ts_user == NULL)
    {
	/*
	 * Do we want to print "file was lost" like normal CVS?
	 * Would it always be appropriate?
	 */
	/* File no longer exists.  Don't do anything, missing files
	   just happen.  */
    }
    else if (vers->ts_rcs == NULL
	     || args->force
	     || strcmp (vers->ts_user, vers->ts_rcs) != 0)
    {
	if (args->no_contents
	    && supported_request ("Is-modified"))
	{
	    send_to_server ("Is-modified ", 0);
	    send_to_server (filename, 0);
	    send_to_server ("\012", 1);
	}
	else
	    send_modified (filename, finfo->fullname, vers);

        if (args->backup_modified)
        {
            char *bakname;
            bakname = backup_file (filename, vers->vn_user);
            /* This behavior is sufficiently unexpected to
               justify overinformativeness, I think. */
            if (! really_quiet)
                printf ("(Locally modified %s moved to %s)\n",
                        filename, bakname);
            free (bakname);
        }
    }
    else
    {
	send_to_server ("Unchanged ", 0);
	send_to_server (filename, 0);
	send_to_server ("\012", 1);
    }

    /* if this directory has an ignore list, add this file to it */
    if (ignlist)
    {
	Node *p;

	p = getnode ();
	p->type = FILES;
	p->key = xstrdup (finfo->file);
	(void) addnode (ignlist, p);
    }

    freevers_ts (&vers);
    return 0;
}

static void send_ignproc PROTO ((char *, char *));

static void
send_ignproc (file, dir)
    char *file;
    char *dir;
{
    if (ign_inhibit_server || !supported_request ("Questionable"))
    {
	if (dir[0] != '\0')
	    (void) printf ("? %s/%s\n", dir, file);
	else
	    (void) printf ("? %s\n", file);
    }
    else
    {
	send_to_server ("Questionable ", 0);
	send_to_server (file, 0);
	send_to_server ("\012", 1);
    }
}

static int send_filesdoneproc PROTO ((void *, int, char *, char *, List *));

static int
send_filesdoneproc (callerdat, err, repository, update_dir, entries)
    void *callerdat;
    int err;
    char *repository;
    char *update_dir;
    List *entries;
{
    /* if this directory has an ignore list, process it then free it */
    if (ignlist)
    {
	ignore_files (ignlist, entries, update_dir, send_ignproc);
	dellist (&ignlist);
    }

    return (err);
}

static Dtype send_dirent_proc PROTO ((void *, char *, char *, char *, List *));

/*
 * send_dirent_proc () is called back by the recursion processor before a
 * sub-directory is processed for update.
 * A return code of 0 indicates the directory should be
 * processed by the recursion code.  A return of non-zero indicates the
 * recursion code should skip this directory.
 *
 */
static Dtype
send_dirent_proc (callerdat, dir, repository, update_dir, entries)
    void *callerdat;
    char *dir;
    char *repository;
    char *update_dir;
    List *entries;
{
    struct send_data *args = (struct send_data *) callerdat;
    int dir_exists;
    char *cvsadm_name;

    if (ignore_directory (update_dir))
    {
	/* print the warm fuzzy message */
	if (!quiet)
	    error (0, 0, "Ignoring %s", update_dir);
        return (R_SKIP_ALL);
    }

    /*
     * If the directory does not exist yet (e.g. "cvs update -d foo"),
     * no need to send any files from it.  If the directory does not
     * have a CVS directory, then we pretend that it does not exist.
     * Otherwise, we will fail when trying to open the Entries file.
     * This case will happen when checking out a module defined as
     * ``-a .''.
     */
    cvsadm_name = xmalloc (strlen (dir) + sizeof (CVSADM) + 10);
    sprintf (cvsadm_name, "%s/%s", dir, CVSADM);
    dir_exists = isdir (cvsadm_name);
    free (cvsadm_name);

    /*
     * If there is an empty directory (e.g. we are doing `cvs add' on a
     * newly-created directory), the server still needs to know about it.
     */

    if (dir_exists)
    {
	/*
	 * Get the repository from a CVS/Repository file whenever possible.
	 * The repository variable is wrong if the names in the local
	 * directory don't match the names in the repository.
	 */
	char *repos = Name_Repository (dir, update_dir);
	send_a_repository (dir, repos, update_dir);
	free (repos);

	/* initialize the ignore list for this directory */
	ignlist = getlist ();
    }
    else
    {
	/* It doesn't make sense to send a non-existent directory,
	   because there is no way to get the correct value for
	   the repository (I suppose maybe via the expand-modules
	   request).  In the case where the "obvious" choice for
	   repository is correct, the server can figure out whether
	   to recreate the directory; in the case where it is wrong
	   (that is, does not match what modules give us), we might as
	   well just fail to recreate it.

	   Checking for noexec is a kludge for "cvs -n add dir".  */
	/* Don't send a non-existent directory unless we are building
           new directories (build_dirs is true).  Otherwise, CVS may
           see a D line in an Entries file, and recreate a directory
           which the user removed by hand.  */
	if (args->build_dirs && noexec)
	    send_a_repository (dir, repository, update_dir);
    }

    return (dir_exists ? R_PROCESS : R_SKIP_ALL);
}

static int send_dirleave_proc PROTO ((void *, char *, int, char *, List *));

/*
 * send_dirleave_proc () is called back by the recursion code upon leaving
 * a directory.  All it does is delete the ignore list if it hasn't already
 * been done (by send_filesdone_proc).
 */
/* ARGSUSED */
static int
send_dirleave_proc (callerdat, dir, err, update_dir, entries)
    void *callerdat;
    char *dir;
    int err;
    char *update_dir;
    List *entries;
{

    /* Delete the ignore list if it hasn't already been done.  */
    if (ignlist)
	dellist (&ignlist);
    return err;
}

/*
 * Send each option in a string to the server, one by one.
 * This assumes that the options are separated by spaces, for example
 * STRING might be "--foo -C5 -y".
 */

void
send_option_string (string)
    char *string;
{
    char *copy;
    char *p;

    copy = xstrdup (string);
    p = copy;
    while (1)
    {
        char *s;
	char l;

	for (s = p; *s != ' ' && *s != '\0'; s++)
	    ;
	l = *s;
	*s = '\0';
	if (s != p)
	    send_arg (p);
	if (l == '\0')
	    break;
	p = s + 1;
    }
    free (copy);
}


/* Send the names of all the argument files to the server.  */

void
send_file_names (argc, argv, flags)
    int argc;
    char **argv;
    unsigned int flags;
{
    int i;
    int level;
    int max_level;
    
    /* The fact that we do this here as well as start_recursion is a bit 
       of a performance hit.  Perhaps worth cleaning up someday.  */
    if (flags & SEND_EXPAND_WILD)
	expand_wild (argc, argv, &argc, &argv);

    /* Send Max-dotdot if needed.  */
    max_level = 0;
    for (i = 0; i < argc; ++i)
    {
	level = pathname_levels (argv[i]);
	if (level > max_level)
	    max_level = level;
    }
    if (max_level > 0)
    {
	if (supported_request ("Max-dotdot"))
	{
            char buf[10];
            sprintf (buf, "%d", max_level);

	    send_to_server ("Max-dotdot ", 0);
	    send_to_server (buf, 0);
	    send_to_server ("\012", 1);
	}
	else
	    /*
	     * "leading .." is not strictly correct, as this also includes
	     * cases like "foo/../..".  But trying to explain that in the
	     * error message would probably just confuse users.
	     */
	    error (1, 0,
		   "leading .. not supported by old (pre-Max-dotdot) servers");
    }

    for (i = 0; i < argc; ++i)
    {
	char buf[1];
	char *p = argv[i];
	char *line = NULL;

	if (arg_should_not_be_sent_to_server (argv[i]))
	    continue;

#ifdef FILENAMES_CASE_INSENSITIVE
	/* We want to send the file name as it appears
	   in CVS/Entries.  We put this inside an ifdef
	   to avoid doing all these system calls in
	   cases where fncmp is just strcmp anyway.  */
	/* For now just do this for files in the local
	   directory.  Would be nice to handle the
	   non-local case too, though.  */
	/* The isdir check could more gracefully be replaced
	   with a way of having Entries_Open report back the
	   error to us and letting us ignore existence_error.
	   Or some such.  */
	if (p == last_component (p) && isdir (CVSADM))
	{
	    List *entries;
	    Node *node;

	    /* If we were doing non-local directory,
	       we would save_cwd, CVS_CHDIR
	       like in update.c:isemptydir.  */
	    /* Note that if we are adding a directory,
	       the following will read the entry
	       that we just wrote there, that is, we
	       will get the case specified on the
	       command line, not the case of the
	       directory in the filesystem.  This
	       is correct behavior.  */
	    entries = Entries_Open (0, NULL);
	    node = findnode_fn (entries, p);
	    if (node != NULL)
	    {
		line = xstrdup (node->key);
		p = line;
		delnode (node);
	    }
	    Entries_Close (entries);
	}
#endif /* FILENAMES_CASE_INSENSITIVE */

	send_to_server ("Argument ", 0);

	while (*p)
	{
	    if (*p == '\n')
	    {
		send_to_server ("\012Argumentx ", 0);
	    }
	    else if (ISDIRSEP (*p))
	    {
		buf[0] = '/';
		send_to_server (buf, 1);
	    }
	    else
	    {
		buf[0] = *p;
		send_to_server (buf, 1);
	    }
	    ++p;
	}
	send_to_server ("\012", 1);
	if (line != NULL)
	    free (line);
    }

    if (flags & SEND_EXPAND_WILD)
    {
	int i;
	for (i = 0; i < argc; ++i)
	    free (argv[i]);
	free (argv);
    }
}


/* Send Repository, Modified and Entry.  argc and argv contain only
  the files to operate on (or empty for everything), not options.
  local is nonzero if we should not recurse (-l option).  flags &
  SEND_BUILD_DIRS is nonzero if nonexistent directories should be
  sent.  flags & SEND_FORCE is nonzero if we should send unmodified
  files to the server as though they were modified.  flags &
  SEND_NO_CONTENTS means that this command only needs to know
  _whether_ a file is modified, not the contents.  Also sends Argument
  lines for argc and argv, so should be called after options are sent.  */
void
send_files (argc, argv, local, aflag, flags)
    int argc;
    char **argv;
    int local;
    int aflag;
    unsigned int flags;
{
    struct send_data args;
    int err;

    /*
     * aflag controls whether the tag/date is copied into the vers_ts.
     * But we don't actually use it, so I don't think it matters what we pass
     * for aflag here.
     */
    args.build_dirs = flags & SEND_BUILD_DIRS;
    args.force = flags & SEND_FORCE;
    args.no_contents = flags & SEND_NO_CONTENTS;
    args.backup_modified = flags & BACKUP_MODIFIED_FILES;
    err = start_recursion
	(send_fileproc, send_filesdoneproc,
	 send_dirent_proc, send_dirleave_proc, (void *) &args,
	 argc, argv, local, W_LOCAL, aflag, 0, (char *)NULL, 0);
    if (err)
	error_exit ();
    if (toplevel_repos == NULL)
	/*
	 * This happens if we are not processing any files,
	 * or for checkouts in directories without any existing stuff
	 * checked out.  The following assignment is correct for the
	 * latter case; I don't think toplevel_repos matters for the
	 * former.
	 */
	toplevel_repos = xstrdup (current_parsed_root->directory);
    send_repository ("", toplevel_repos, ".");
}

void
client_import_setup (repository)
    char *repository;
{
    if (toplevel_repos == NULL)		/* should always be true */
        send_a_repository ("", repository, "");
}

/*
 * Process the argument import file.
 */
int
client_process_import_file (message, vfile, vtag, targc, targv, repository,
                            all_files_binary, modtime)
    char *message;
    char *vfile;
    char *vtag;
    int targc;
    char *targv[];
    char *repository;
    int all_files_binary;

    /* Nonzero for "import -d".  */
    int modtime;
{
    char *update_dir;
    char *fullname;
    Vers_TS vers;

    assert (toplevel_repos != NULL);

    if (strncmp (repository, toplevel_repos, strlen (toplevel_repos)) != 0)
	error (1, 0,
	       "internal error: pathname `%s' doesn't specify file in `%s'",
	       repository, toplevel_repos);

    if (strcmp (repository, toplevel_repos) == 0)
    {
	update_dir = "";
	fullname = xstrdup (vfile);
    }
    else
    {
	update_dir = repository + strlen (toplevel_repos) + 1;

	fullname = xmalloc (strlen (vfile) + strlen (update_dir) + 10);
	strcpy (fullname, update_dir);
	strcat (fullname, "/");
	strcat (fullname, vfile);
    }

    send_a_repository ("", repository, update_dir);
    if (all_files_binary)
    {
	vers.options = xmalloc (4); /* strlen("-kb") + 1 */
	strcpy (vers.options, "-kb");
    }
    else
    {
	vers.options = wrap_rcsoption (vfile, 1);
    }
    if (vers.options != NULL)
    {
	if (supported_request ("Kopt"))
	{
	    send_to_server ("Kopt ", 0);
	    send_to_server (vers.options, 0);
	    send_to_server ("\012", 1);
	}
	else
	    error (0, 0,
		   "warning: ignoring -k options due to server limitations");
    }
    if (modtime)
    {
	if (supported_request ("Checkin-time"))
	{
	    struct stat sb;
	    char *rcsdate;
	    char netdate[MAXDATELEN];

	    if (CVS_STAT (vfile, &sb) < 0)
		error (1, errno, "cannot stat %s", fullname);
	    rcsdate = date_from_time_t (sb.st_mtime);
	    date_to_internet (netdate, rcsdate);
	    free (rcsdate);

	    send_to_server ("Checkin-time ", 0);
	    send_to_server (netdate, 0);
	    send_to_server ("\012", 1);
	}
	else
	    error (0, 0,
		   "warning: ignoring -d option due to server limitations");
    }
    send_modified (vfile, fullname, &vers);
    if (vers.options != NULL)
	free (vers.options);
    free (fullname);
    return 0;
}

void
client_import_done ()
{
    if (toplevel_repos == NULL)
	/*
	 * This happens if we are not processing any files,
	 * or for checkouts in directories without any existing stuff
	 * checked out.  The following assignment is correct for the
	 * latter case; I don't think toplevel_repos matters for the
	 * former.
	 */
        /* FIXME: "can't happen" now that we call client_import_setup
	   at the beginning.  */
	toplevel_repos = xstrdup (current_parsed_root->directory);
    send_repository ("", toplevel_repos, ".");
}

static void
notified_a_file (data, ent_list, short_pathname, filename)
    char *data;
    List *ent_list;
    char *short_pathname;
    char *filename;
{
    FILE *fp;
    FILE *newf;
    size_t line_len = 8192;
    char *line = xmalloc (line_len);
    char *cp;
    int nread;
    int nwritten;
    char *p;

    fp = open_file (CVSADM_NOTIFY, "r");
    if (getline (&line, &line_len, fp) < 0)
    {
	if (feof (fp))
	    error (0, 0, "cannot read %s: end of file", CVSADM_NOTIFY);
	else
	    error (0, errno, "cannot read %s", CVSADM_NOTIFY);
	goto error_exit;
    }
    cp = strchr (line, '\t');
    if (cp == NULL)
    {
	error (0, 0, "malformed %s file", CVSADM_NOTIFY);
	goto error_exit;
    }
    *cp = '\0';
    if (strcmp (filename, line + 1) != 0)
    {
	error (0, 0, "protocol error: notified %s, expected %s", filename,
	       line + 1);
    }

    if (getline (&line, &line_len, fp) < 0)
    {
	if (feof (fp))
	{
	    free (line);
	    if (fclose (fp) < 0)
		error (0, errno, "cannot close %s", CVSADM_NOTIFY);
	    if ( CVS_UNLINK (CVSADM_NOTIFY) < 0)
		error (0, errno, "cannot remove %s", CVSADM_NOTIFY);
	    return;
	}
	else
	{
	    error (0, errno, "cannot read %s", CVSADM_NOTIFY);
	    goto error_exit;
	}
    }
    newf = open_file (CVSADM_NOTIFYTMP, "w");
    if (fputs (line, newf) < 0)
    {
	error (0, errno, "cannot write %s", CVSADM_NOTIFYTMP);
	goto error2;
    }
    while ((nread = fread (line, 1, line_len, fp)) > 0)
    {
	p = line;
	while ((nwritten = fwrite (p, 1, nread, newf)) > 0)
	{
	    nread -= nwritten;
	    p += nwritten;
	}
	if (ferror (newf))
	{
	    error (0, errno, "cannot write %s", CVSADM_NOTIFYTMP);
	    goto error2;
	}
    }
    if (ferror (fp))
    {
	error (0, errno, "cannot read %s", CVSADM_NOTIFY);
	goto error2;
    }
    if (fclose (newf) < 0)
    {
	error (0, errno, "cannot close %s", CVSADM_NOTIFYTMP);
	goto error_exit;
    }
    free (line);
    if (fclose (fp) < 0)
    {
	error (0, errno, "cannot close %s", CVSADM_NOTIFY);
	return;
    }

    {
        /* In this case, we want rename_file() to ignore noexec. */
        int saved_noexec = noexec;
        noexec = 0;
        rename_file (CVSADM_NOTIFYTMP, CVSADM_NOTIFY);
        noexec = saved_noexec;
    }

    return;
  error2:
    (void) fclose (newf);
  error_exit:
    free (line);
    (void) fclose (fp);
}

static void
handle_notified (args, len)
    char *args;
    int len;
{
    call_in_directory (args, notified_a_file, NULL);
}

void
client_notify (repository, update_dir, filename, notif_type, val)
    char *repository;
    char *update_dir;
    char *filename;
    int notif_type;
    char *val;
{
    char buf[2];

    send_a_repository ("", repository, update_dir);
    send_to_server ("Notify ", 0);
    send_to_server (filename, 0);
    send_to_server ("\012", 1);
    buf[0] = notif_type;
    buf[1] = '\0';
    send_to_server (buf, 1);
    send_to_server ("\t", 1);
    send_to_server (val, 0);
}

/*
 * Send an option with an argument, dealing correctly with newlines in
 * the argument.  If ARG is NULL, forget the whole thing.
 */
void
option_with_arg (option, arg)
    char *option;
    char *arg;
{
    if (arg == NULL)
	return;

    send_to_server ("Argument ", 0);
    send_to_server (option, 0);
    send_to_server ("\012", 1);

    send_arg (arg);
}

/* Send a date to the server.  The input DATE is in RCS format.
   The time will be GMT.

   We then convert that to the format required in the protocol
   (including the "-D" option) and send it.  According to
   cvsclient.texi, RFC 822/1123 format is preferred.  */

void
client_senddate (date)
    const char *date;
{
    char buf[MAXDATELEN];

    date_to_internet (buf, (char *)date);
    option_with_arg ("-D", buf);
}

void
send_init_command ()
{
    /* This is here because we need the current_parsed_root->directory variable.  */
    send_to_server ("init ", 0);
    send_to_server (current_parsed_root->directory, 0);
    send_to_server ("\012", 0);
}

#endif /* CLIENT_SUPPORT */