summaryrefslogtreecommitdiff
path: root/pith/remote.c
blob: ac03c9a6fbc7e2f62cfb253be7b9a52295c31eb0 (plain)
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
#if !defined(lint) && !defined(DOS)
static char rcsid[] = "$Id: remote.c 1074 2008-06-04 00:08:43Z hubert@u.washington.edu $";
#endif

/*
 * ========================================================================
 * Copyright 2013-2017 Eduardo Chappa
 * Copyright 2006-2008 University of Washington
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * ========================================================================
 */

/*======================================================================
     remote.c
     Implements remote IMAP config files (remote config, remote abook).
  ====*/


#include "../pith/headers.h"
#include "../pith/remote.h"
#include "../pith/conf.h"
#include "../pith/imap.h"
#include "../pith/msgno.h"
#include "../pith/mailview.h"
#include "../pith/status.h"
#include "../pith/flag.h"
#include "../pith/tempfile.h"
#include "../pith/adrbklib.h"
#include "../pith/detach.h"
#include "../pith/filter.h"
#include "../pith/stream.h"
#include "../pith/options.h"
#include "../pith/busy.h"
#include "../pith/readfile.h"


/*
 * Internal prototypes
 */
REMDATA_META_S *rd_find_our_metadata(char *, unsigned long *);
int             rd_meta_is_broken(FILE *);
int             rd_add_hdr_msg(REMDATA_S *, char *);
int             rd_store_fake_hdrs(REMDATA_S *, char *, char *, char *);
int             rd_upgrade_cookies(REMDATA_S *, long, int);
int             rd_check_for_suspect_data(REMDATA_S *);


char meta_prefix[] = ".ab";


char *(*pith_opt_rd_metadata_name)(void);


char *
read_remote_pinerc(PINERC_S *prc, ParsePinerc which_vars)
{
    int        try_cache, no_perm_create_pass = 0;
    char      *file = NULL;
    unsigned   flags;


    dprint((7, "read_remote_pinerc \"%s\"\n",
	   prc->name ? prc->name : "?"));

    /*
     * We don't cache the pinerc, we always copy it.
     *
     * Don't store the config in a temporary file, just leave it
     * in memory while using it.
     * It is currently required that NO_PERM_CACHE be set if NO_FILE is set.
     */
    flags = (NO_PERM_CACHE | NO_FILE);

create_the_remote_folder:

    if(no_perm_create_pass){
	if(prc->rd){
	    prc->rd->flags &= ~DO_REMTRIM;
	    rd_close_remdata(&prc->rd);
	}

	/* this will cause the remote folder to be created */
	flags = 0;
    }

    /*
     * We could parse the name here to find what type it is. So far we
     * only have type RemImap.
     */
    prc->rd = rd_create_remote(RemImap, prc->name,
			       REMOTE_PINERC_SUBTYPE,
			       &flags, _("Error: "),
			       _(" Can't fetch remote configuration."));
    if(!prc->rd)
      goto bail_out;
    
    /*
     * On first use we just use a temp file instead of memory (NO_FILE).
     * In other words, for our convenience, we don't turn NO_FILE back on
     * here. Why is that convenient? Because of the stuff that happened in
     * rd_create_remote when flags was set to zero.
     */
    if(no_perm_create_pass)
      prc->rd->flags |= NO_PERM_CACHE;

    try_cache = rd_read_metadata(prc->rd);

    if(prc->rd->access == MaybeRorW){
	if(prc->rd->read_status == 'R' ||
           !(which_vars == ParsePers || which_vars == ParsePersPost)){
	    prc->rd->access = ReadOnly;
	    prc->rd->read_status = 'R';
	}
	else
	  prc->rd->access = ReadWrite;
    }

    if(prc->rd->access != NoExists){

	rd_check_remvalid(prc->rd, 1L);

	/*
	 * If the cached info says it is readonly but
	 * it looks like it's been fixed now, change it to readwrite.
	 */
        if((which_vars == ParsePers || which_vars == ParsePersPost) &&
	   prc->rd->read_status == 'R'){
	    /*
	     * We go to this trouble since readonly pinercs
	     * are likely a mistake. They are usually supposed to be
	     * readwrite so we open it and check if it's been fixed.
	     */
	    rd_check_readonly_access(prc->rd);
	    if(prc->rd->read_status == 'W'){
		prc->rd->access = ReadWrite;
		prc->rd->flags |= REM_OUTOFDATE;
	    }
	    else
	      prc->rd->access = ReadOnly;
	}

	if(prc->rd->flags & REM_OUTOFDATE){
	    if(rd_update_local(prc->rd) != 0){
		if(!no_perm_create_pass && prc->rd->flags & NO_PERM_CACHE
		   && !(prc->rd->flags & USER_SAID_NO)){
		    /*
		     * We don't check for the existence of the remote
		     * folder when this flag is turned on, so we could
		     * fail here because the remote folder doesn't exist.
		     * We try to create it.
		     */
		    no_perm_create_pass++;
		    goto create_the_remote_folder;
		}

		dprint((1,
		       "read_pinerc_remote: rd_update_local failed\n"));
		/*
		 * Don't give up altogether. We still may be
		 * able to use a cached copy.
		 */
	    }
	    else{
		dprint((7,
		       "%s: copied remote to local (%ld)\n",
		       prc->rd->rn ? prc->rd->rn : "?",
		       (long)prc->rd->last_use));
	    }
	}

	if(prc->rd->access == ReadWrite)
	  prc->rd->flags |= DO_REMTRIM;
    }

    /* If we couldn't get to remote folder, try using the cached copy */
    if(prc->rd->access == NoExists || prc->rd->flags & REM_OUTOFDATE){
	if(try_cache){
	    prc->rd->access = ReadOnly;
	    prc->rd->flags |= USE_OLD_CACHE;
	    q_status_message(SM_ORDER, 3, 4,
	     "Can't contact remote config server, using cached copy");
	    dprint((2,
    "Can't open remote pinerc %s, using local cached copy %s readonly\n",
		   prc->rd->rn ? prc->rd->rn : "?",
		   prc->rd->lf ? prc->rd->lf : "?"));
	}
	else{
	    prc->rd->flags &= ~DO_REMTRIM;
	    goto bail_out;
	}
    }

    if(prc->rd->flags & NO_FILE)
      /* copy text, leave sonofile for later use */
      file = cpystr((char *)so_text(prc->rd->sonofile));
    else
      file = read_file(prc->rd->lf, 0);

bail_out:
    if((which_vars == ParsePers || which_vars == ParsePersPost) &&
       (!file || !prc->rd || prc->rd->access != ReadWrite)){
	prc->readonly = 1;
	if(prc == ps_global->prc)
	  ps_global->readonly_pinerc = 1;
    }
    
   return(file);
}


/*
 * Check if the remote data folder exists and create an empty folder
 * if it doesn't exist.
 *
 * Args -        type -- The type of remote storage.
 *        remote_name -- 
 *          type_spec -- Type-specific data.
 *              flags -- 
 *         err_prefix -- Should usually end with a SPACE
 *         err_suffix -- Should usually begin with a SPACE
 *
 * Returns a pointer to a REMDATA_S with access set to either
 * NoExists or MaybeRorW. On success, "so" will point to a storage object.
 */
REMDATA_S *
rd_create_remote(RemType type, char *remote_name, char *type_spec,
		 unsigned int *flags, char *err_prefix, char *err_suffix)
{
    REMDATA_S *rd = NULL;
    CONTEXT_S *dummy_cntxt = NULL;

    dprint((7, "rd_create_remote \"%s\"\n",
	   remote_name ? remote_name : "?"));

    rd = rd_new_remdata(type, remote_name, type_spec);
    if(flags)
      rd->flags = *flags;
    
    switch(rd->type){
      case RemImap:
	if(rd->flags & NO_PERM_CACHE){
	    if(rd->rn && (rd->so = so_get(CharStar, NULL, WRITE_ACCESS))){
		if(rd->flags & NO_FILE){
		    rd->sonofile = so_get(CharStar, NULL, WRITE_ACCESS);
		    if(!rd->sonofile)
		      rd->flags &= ~NO_FILE;
		}

		/*
		 * We're not going to check if it is there in this case,
		 * in order to save ourselves some round trips and
		 * connections. We'll just try to select it and then
		 * recover at that point if it isn't already there.
		 */
		rd->flags |= REM_OUTOFDATE;
		rd->access = MaybeRorW;
	    }

	}
	else{
	    /*
	     * Open_fcc creates the folder if it didn't already exist.
	     */
	    if(rd->rn && (rd->so = open_fcc(rd->rn, &dummy_cntxt, 1,
					    err_prefix, err_suffix)) != NULL){
		/*
		 * We know the folder is there but don't know what access
		 * rights we have until we try to select it, which we don't
		 * want to do unless we have to. So delay evaluating.
		 */
		rd->access = MaybeRorW;
	    }
	}

	break;

      default:
	q_status_message(SM_ORDER, 3,5, "rd_create_remote: type not supported");
	break;
    }

    return(rd);
}


REMDATA_S *
rd_new_remdata(RemType type, char *remote_name, char *type_spec)
{
    REMDATA_S *rd = NULL;

    rd = (REMDATA_S *)fs_get(sizeof(*rd));
    memset((void *)rd, 0, sizeof(*rd));

    rd->type   = type;
    rd->access = NoExists;

    if(remote_name)
      rd->rn = cpystr(remote_name);

    switch(rd->type){
      case RemImap:
	if(type_spec)
	  rd->t.i.special_hdr = cpystr(type_spec);

	break;

      default:
	q_status_message(SM_ORDER, 3,5, "rd_new_remdata: type not supported");
	break;
    }

    return(rd);
}


/*
 * Closes the remote stream and frees.
 */
void
rd_free_remdata(REMDATA_S **rd)
{
    if(rd && *rd){
	rd_close_remote(*rd);

	if((*rd)->rn)
	  fs_give((void **)&(*rd)->rn);

	if((*rd)->lf)
	  fs_give((void **)&(*rd)->lf);

	if((*rd)->so){
	    so_give(&(*rd)->so);
	    (*rd)->so = NULL;
	}

	if((*rd)->sonofile){
	    so_give(&(*rd)->sonofile);
	    (*rd)->sonofile = NULL;
	}

	switch((*rd)->type){
	  case RemImap:
	    if((*rd)->t.i.special_hdr)
	      fs_give((void **)&(*rd)->t.i.special_hdr);

	    if((*rd)->t.i.chk_date)
	      fs_give((void **)&(*rd)->t.i.chk_date);
	    
	    break;

	  default:
	    q_status_message(SM_ORDER, 3, 5,
			     "rd_free_remdata: type not supported");
	    break;
	}

	fs_give((void **)rd);
    }
}


/*
 * Call this when finished with the remdata. This does the REMTRIM if the
 * flag is set, the DEL_FILE if the flag is set. It also closes the stream
 * and frees the rd.
 */
void
rd_trim_remdata(REMDATA_S **rd)
{
    if(!(rd && *rd))
      return;

    switch((*rd)->type){
      case RemImap:
	/*
	 * Trim the number of saved copies of remote data history.
	 * The first message is a fake message that always
	 * stays there, then come ps_global->remote_abook_history messages
	 * which are each a revision of the data, then comes the active
	 * data.
	 */
	if((*rd)->flags & DO_REMTRIM &&
	   !((*rd)->flags & REM_OUTOFDATE) &&
	   (*rd)->t.i.chk_nmsgs > ps_global->remote_abook_history + 2){

	    /* make sure stream is open */
	    rd_ping_stream(*rd);
	    rd_open_remote(*rd);

	    if(!rd_remote_is_readonly(*rd)){
		if((*rd)->t.i.stream &&
		   (*rd)->t.i.stream->nmsgs >
					ps_global->remote_abook_history + 2){
		    char sequence[20];
		    int  user_deleted = 0;

		    /*
		     * If user manually deleted some, we'd better not delete
		     * any more.
		     */
		    if(count_flagged((*rd)->t.i.stream, F_DEL) == 0L){

			dprint((4, "  rd_trim: trimming remote: mark msgs 2-%ld deleted (%s)\n", (*rd)->t.i.stream->nmsgs - 1 - ps_global->remote_abook_history, (*rd)->rn ? (*rd)->rn : "?"));
			snprintf(sequence, sizeof(sequence), "2:%ld",
		(*rd)->t.i.stream->nmsgs - 1 - ps_global->remote_abook_history);
			mail_flag((*rd)->t.i.stream, sequence,
				  "\\DELETED", ST_SET);
		    }
		    else
		      user_deleted++;

		    mail_expunge((*rd)->t.i.stream);

		    if(!user_deleted)
		      rd_update_metadata(*rd, NULL);
		    /* else
		     *  don't update metafile because user is messing with
		     *  the remote folder manually. We'd better re-read it next
		     *  time.  */
		}
	    }

	    ps_global->noshow_error = 0;
	}

	break;

      default:
	q_status_message(SM_ORDER, 3,5, "rd_trim_remdata: type not supported");
	break;
    }
}


/*
 * All done with this remote data. Trim the folder, close the
 * stream, and free.
 */
void
rd_close_remdata(REMDATA_S **rd)
{
    if(!(rd && *rd))
      return;

    rd_trim_remdata(rd);

    if((*rd)->lf && (*rd)->flags & DEL_FILE)
      our_unlink((*rd)->lf);

    /* this closes the stream and frees memory */
    rd_free_remdata(rd);
}


/*
 * Looks in the metadata file for the cache line corresponding to rd and
 * fills in data in rd.
 *
 * Return value -- 1 if it is likely that the filename we're returning
 *   is the permanent name of the local cache file and it may already have
 *   a cached copy of the data. This is to tell us if it makes sense to use
 *   the cached copy when we are unable to contact the remote server.
 *   0 otherwise.
 */
int
rd_read_metadata(REMDATA_S *rd)
{
    REMDATA_META_S *rab = NULL;
    int             try_cache = 0;

    dprint((7, "rd_read_metadata \"%s\"\n",
	   (rd && rd->rn) ? rd->rn : "?"));

    if(!rd)
      return try_cache;

    if(rd->flags & NO_PERM_CACHE)
      rab = NULL;
    else
      rab = rd_find_our_metadata(rd->rn, &rd->flags);

    if(!rab){
	if(!rd->lf){
	    rd->flags |= (NO_META_UPDATE | REM_OUTOFDATE);
	    if(!(rd->flags & NO_FILE)){
		rd->lf = temp_nam(NULL, "a6");
		rd->flags |= DEL_FILE;
	    }

	    /* display error */
	    if(!(rd->flags & NO_PERM_CACHE))
	      display_message('x');

	    dprint((2, "using temp cache file %s\n",
		   rd->lf ? rd->lf : "<none>"));
	}
    }
    else if(rab->local_cache_file){	/* A-OK, it was in the file already */
	if(!is_absolute_path(rab->local_cache_file)){
	    char  dir[MAXPATH+1], path[MAXPATH+1];
	    char *lc;

	    /*
	     * This should be the normal case. The file is stored as a
	     * filename in the pinerc dir, so that it can be
	     * accessed from the PC or from unix where the pathnames to
	     * get there will be different.
	     */

	    if((lc = last_cmpnt(ps_global->pinerc)) != NULL){
		int to_copy;

		to_copy = (lc - ps_global->pinerc > 1)
			    ? (lc - ps_global->pinerc - 1) : 1;
		strncpy(dir, ps_global->pinerc, MIN(to_copy, sizeof(dir)-1));
		dir[MIN(to_copy, sizeof(dir)-1)] = '\0';
	    }
	    else{
		dir[0] = '.';
		dir[1] = '\0';
	    }

	    build_path(path, dir, rab->local_cache_file, sizeof(path));
	    rd->lf = cpystr(path);
	}
	else{
	    rd->lf = rab->local_cache_file;
	    /* don't free this below, we're using it */
	    rab->local_cache_file = NULL;
	}

	rd->read_status = rab->read_status;

	switch(rd->type){
	  case RemImap:
	    rd->t.i.chk_date    = rab->date;
	    rab->date = NULL;	/* don't free this below, we're using it */

	    dprint((7,
	       "in read_metadata, setting chk_date from metadata to ->%s<-\n",
	       rd->t.i.chk_date ? rd->t.i.chk_date : "?"));
	    rd->t.i.chk_nmsgs   = rab->nmsgs;
	    rd->t.i.uidvalidity = rab->uidvalidity;
	    rd->t.i.uidnext     = rab->uidnext;
	    rd->t.i.uid         = rab->uid;
	    rd->t.i.chk_nmsgs   = rab->nmsgs;
	    dprint((7,
	      "setting uid=%lu uidnext=%lu uidval=%lu read_stat=%c nmsgs=%lu\n",
		 rd->t.i.uid, rd->t.i.uidnext, rd->t.i.uidvalidity,
		 rd->read_status ? rd->read_status : '0',
		 rd->t.i.chk_nmsgs));
	    break;

	  default:
	    q_status_message(SM_ORDER, 3, 5,
			     "rd_read_metadata: type not supported");
	    break;
	}

	if(rd->t.i.chk_nmsgs > 0)
	  try_cache++;	/* cache should be valid if we can't contact server */
    }
    /*
     * The line for this data wasn't in the metadata file yet.
     * Figure out what should go there and put it in.
     */
    else{
	/*
	 * The local_cache_file is where we will store the cached local
	 * copy of the remote data.
	 */
	rab->local_cache_file = tempfile_in_same_dir(ps_global->pinerc,
						     meta_prefix, NULL);
	if(rab->local_cache_file){
	    rd->lf = rab->local_cache_file;
	    rd_write_metadata(rd, 0);
	    rab->local_cache_file = NULL;
	}
	else
	  rd->lf = temp_nam(NULL, "a7");
    }

    if(rab){
	if(rab->local_cache_file)
	  fs_give((void **)&rab->local_cache_file);
	if(rab->date)
	  fs_give((void **)&rab->date);
	fs_give((void **)&rab);
    }

    return(try_cache);
}


/*
 * Write out the contents of the metadata file.
 *
 * Each line should be: folder_name cache_file uidvalidity uidnext uid nmsgs
 *							     read_status date
 *
 * If delete_it is set, then remove the line instead of updating it.
 *
 * We have to be careful with the metadata, because it exists in user's
 * existing metadata files now, and it is oriented towards only RemImap.
 * We would have to change the version number and the format of the lines
 * in the file if we add another type.
 */
void
rd_write_metadata(REMDATA_S *rd, int delete_it)
{
    char *tempfile;
    FILE *fp_old = NULL, *fp_new = NULL;
    char *p = NULL, *pinerc_dir = NULL, *metafile = NULL;
    char *rel_filename, *key;
    char  line[MAILTMPLEN];
    int   fd;

    dprint((7, "rd_write_metadata \"%s\"\n",
	   (rd && rd->rn) ? rd->rn : "?"));

    if(!rd || rd->flags & NO_META_UPDATE)
      return;

    if(rd->type != RemImap){
	q_status_message(SM_ORDER, 3, 5,
			 "rd_write_metadata: type not supported");
	return;
    }

    dprint((9, " - rd_write_metadata: rn=%s lf=%s\n",
	   rd->rn ? rd->rn : "?", rd->lf ? rd->lf : "?"));

    key = rd->rn;

    if(!(pith_opt_rd_metadata_name && (metafile = (*pith_opt_rd_metadata_name)())))
      goto io_err;

    if(!(tempfile = tempfile_in_same_dir(metafile, "a9", &pinerc_dir)))
      goto io_err;

    if((fd = our_open(tempfile, O_TRUNC|O_WRONLY|O_CREAT|O_BINARY, 0600)) >= 0)
      fp_new = fdopen(fd, "w");
    
    if(pinerc_dir && rd->lf && strlen(rd->lf) > strlen(pinerc_dir))
      rel_filename = rd->lf + strlen(pinerc_dir) + 1;
    else
      rel_filename = rd->lf;

    if(pinerc_dir)
      fs_give((void **)&pinerc_dir);

    fp_old = our_fopen(metafile, "rb");

    if(fp_new && fp_old){
	/*
	 * Write the header line.
	 */
	if(fprintf(fp_new, "%s %s Pine Metadata\n",
		   PMAGIC, METAFILE_VERSION_NUM) == EOF)
	  goto io_err;

	while((p = fgets(line, sizeof(line), fp_old)) != NULL){
	    /*
	     * Skip the header line and any lines that don't begin
	     * with a "{".
	     */
	    if(line[0] != '{')
	      continue;

	    /* skip the old cache line for this key */
	    if(strncmp(line, key, strlen(key)) == 0 && line[strlen(key)] == TAB)
	      continue;
	    
	    /* add this line to new version of file */
	    if(fputs(p, fp_new) == EOF)
	      goto io_err;
	}
    }

    /* add the cache line for this key */
    /* Warning: this is type RemImap specific right now! */
    if(!delete_it){
	if(!tempfile ||
	   !fp_old ||
	   !fp_new ||
	   p ||
	   fprintf(fp_new, "%s\t%s\t%lu\t%lu\t%lu\t%lu\t%c\t%s\n",
			    key ? key : "",
			    rel_filename ? rel_filename : "",
			    rd->t.i.uidvalidity, rd->t.i.uidnext, rd->t.i.uid,
			    rd->t.i.chk_nmsgs,
			    rd->read_status ? rd->read_status : '?',
			    rd->t.i.chk_date ? rd->t.i.chk_date : "no-match")
				== EOF)
	  goto io_err;
    }

    if(fclose(fp_new) == EOF){
	fp_new = NULL;
	goto io_err;
    }

    if(fclose(fp_old) == EOF){
	fp_old = NULL;
	goto io_err;
    }

    if(rename_file(tempfile, metafile) < 0)
      goto io_err;

    if(tempfile)
      fs_give((void **)&tempfile);
    
    if(metafile)
      fs_give((void **)&metafile);
    
    return;

io_err:
    dprint((2, "io_err in rd_write_metadata(%s), tempfile=%s: %s\n",
	    metafile ? metafile : "<NULL>", tempfile ? tempfile : "<NULL>",
	    error_description(errno)));
    q_status_message2(SM_ORDER, 3, 5,
		    "Trouble updating metafile %s, continuing (%s)",
		    metafile ? metafile : "<NULL>", error_description(errno));
    if(tempfile){
	our_unlink(tempfile);
	fs_give((void **)&tempfile);
    }
    if(metafile)
      fs_give((void **)&metafile);
    if(fp_old)
      (void)fclose(fp_old);
    if(fp_new)
      (void)fclose(fp_new);
}


void
rd_update_metadata(REMDATA_S *rd, char *date)
{
    if(!rd)
      return;

    dprint((9, " - rd_update_metadata: rn=%s lf=%s\n",
	   rd->rn ? rd->rn : "?", rd->lf ? rd->lf : "<none>"));

    switch(rd->type){
      case RemImap:
	if(rd->t.i.stream){
	    ps_global->noshow_error = 1;
	    rd_ping_stream(rd);
	    if(rd->t.i.stream){
		/*
		 * If nmsgs < 2 then something is wrong. Maybe it is just
		 * that we haven't been told about the messages we've
		 * appended ourselves. Try closing and re-opening the stream
		 * to see those.
		 */
		if(rd->t.i.stream->nmsgs < 2 ||
		   (rd->t.i.shouldbe_nmsgs &&
		    (rd->t.i.shouldbe_nmsgs != rd->t.i.stream->nmsgs))){
		    pine_mail_check(rd->t.i.stream);
		    if(rd->t.i.stream->nmsgs < 2 ||
		       (rd->t.i.shouldbe_nmsgs &&
			(rd->t.i.shouldbe_nmsgs != rd->t.i.stream->nmsgs))){
			rd_close_remote(rd);
			rd_open_remote(rd);
		    }
		}

		rd->t.i.chk_nmsgs = rd->t.i.stream ? rd->t.i.stream->nmsgs : 0L;

		/*
		 * If nmsgs < 2 something is wrong.
		 */
		if(rd->t.i.chk_nmsgs < 2){
		    rd->t.i.uidvalidity = 0L;
		    rd->t.i.uid = 0L;
		    rd->t.i.uidnext = 0L;
		}
		else{
		    rd->t.i.uidvalidity = rd->t.i.stream->uid_validity;
		    rd->t.i.uid = mail_uid(rd->t.i.stream,
					   rd->t.i.stream->nmsgs);
		    /*
		     * Uid_last is not always valid. If the last known uid is
		     * greater than uid_last, go with it instead (uid+1).
		     * If our guess is wrong (too low), the penalty is not
		     * harsh. When the uidnexts don't match we open the
		     * mailbox to check the uid of the actual last message.
		     * If it was a false hit then we adjust uidnext so it
		     * will be correct the next time through.
		     */
		    rd->t.i.uidnext = MAX(rd->t.i.stream->uid_last,rd->t.i.uid)
					+ 1;
		}
	    }

	    ps_global->noshow_error = 0;

	    /*
	     * Save the date so that we can check if it changed next time
	     * we go to write.
	     */
	    if(date){
		if(rd->t.i.chk_date)
		  fs_give((void **)&rd->t.i.chk_date);
		
		rd->t.i.chk_date = cpystr(date);
	    }

	    rd_write_metadata(rd, 0);
	}

	rd->t.i.shouldbe_nmsgs = 0;

	break;

      default:
	q_status_message(SM_ORDER, 3, 5,
			 "rd_update_metadata: type not supported");
	break;
    }
}




REMDATA_META_S *
rd_find_our_metadata(char *key, long unsigned int *flags)
{
    char        *p, *q, *metafile = NULL;
    char         line[MAILTMPLEN];
    REMDATA_META_S *rab = NULL;
    FILE        *fp;

    dprint((9, "rd_find_our_metadata \"%s\"\n", key ? key : "?"));

    if(!(key && *key))
      return rab;

    if(!(pith_opt_rd_metadata_name && (metafile = (*pith_opt_rd_metadata_name)()) != NULL))
      return rab;

    /*
     * Open the metadata file and get some information out.
     */
    fp = our_fopen(metafile, "rb");
    if(fp == NULL){
	q_status_message2(SM_ORDER, 3, 5,
		   _("can't open metadata file %s, continuing (%s)"),
		   metafile, error_description(errno));
	dprint((2,
		   "can't open existing metadata file %s: %s\n",
		   metafile ? metafile : "?", error_description(errno)));
	if(flags)
	  (*flags) |= NO_META_UPDATE;

	fs_give((void **)&metafile);

	return rab;
    }

    /*
     * If we make it to this point where we have opened the metadata file
     * we return a structure (possibly empty) instead of just a NULL pointer.
     */
    rab = (REMDATA_META_S *)fs_get(sizeof(*rab));
    memset(rab, 0, sizeof(*rab));

    /*
     * Check for header line. If it isn't there or is incorrect,
     * return with the empty rab. This call also positions the file pointer
     * past the header line.
     */
    if(rd_meta_is_broken(fp)){

	dprint((2,
		   "metadata file is broken, creating new one: %s\n",
		   metafile ? metafile : "?"));

	/* Make it size zero so we won't copy any bad stuff */
	if(fp_file_size(fp) != 0){
	    int fd;

	    (void)fclose(fp);
	    our_unlink(metafile);

	    if((fd = our_open(metafile, O_TRUNC|O_WRONLY|O_CREAT|O_BINARY, 0600)) < 0){
		q_status_message2(SM_ORDER, 3, 5,
		       _("can't create metadata file %s, continuing (%s)"),
			 metafile, error_description(errno));
		dprint((2,
			   "can't create metadata file %s: %s\n",
			   metafile ? metafile : "?",
			   error_description(errno)));
		fs_give((void **)&rab);
		fs_give((void **)&metafile);
		return NULL;
	    }

	    (void)close(fd);
	}
	else
	  (void)fclose(fp);

	fs_give((void **)&metafile);
	return(rab);
    }

    fs_give((void **)&metafile);

    /* Look for our line */
    while((p = fgets(line, sizeof(line), fp)) != NULL)
      if(strncmp(line, key, strlen(key)) == 0 && line[strlen(key)] == TAB)
	break;
    
#define SKIP_TO_TAB(p) do{while(*p && *p != TAB)p++;}while(0)

    /*
     * The line should be TAB-separated with fields:
     * folder_name cache_file uidvalidity uidnext uid nmsgs read_status date
     * This part is highly RemImap-specific right now.
     */
    if(p){				/* Found the line, parse it. */
      SKIP_TO_TAB(p);			/* skip to TAB following folder_name */
      if(*p == TAB){
	q = ++p;			/* q points to cache_file */
	SKIP_TO_TAB(p);			/* skip to TAB following cache_file */
	if(*p == TAB){
	  *p = '\0';
	  rab->local_cache_file = cpystr(q);
	  q = ++p;			/* q points to uidvalidity */
	  SKIP_TO_TAB(p);		/* skip to TAB following uidvalidity */
	  if(*p == TAB){
	    *p = '\0';
	    rab->uidvalidity = strtoul(q,(char **)NULL,10);
	    q = ++p;			/* q points to uidnext */
	    SKIP_TO_TAB(p);		/* skip to TAB following uidnext */
	    if(*p == TAB){
	      *p = '\0';
	      rab->uidnext = strtoul(q,(char **)NULL,10);
	      q = ++p;			/* q points to uid */
	      SKIP_TO_TAB(p);		/* skip to TAB following uid */
	      if(*p == TAB){
	        *p = '\0';
	        rab->uid = strtoul(q,(char **)NULL,10);
	        q = ++p;		/* q points to nmsgs */
	        SKIP_TO_TAB(p);		/* skip to TAB following nmsgs */
	        if(*p == TAB){
	          *p = '\0';
	          rab->nmsgs = strtoul(q,(char **)NULL,10);
	          q = ++p;		/* q points to read_status */
	          SKIP_TO_TAB(p);	/* skip to TAB following read_status */
	          if(*p == TAB){
	            *p = '\0';
	            rab->read_status = *q;  /* just a char, not whole string */
	            q = ++p;		/* q points to date */
		    while(*p && *p != '\n' && *p != '\r')  /* skip to newline */
		      p++;
		
		    *p = '\0';
		    rab->date = cpystr(q);
	          }
		}
	      }
	    }
	  }
	}
      }
    }

    (void)fclose(fp);
    return(rab);
}


/*
 * Returns: -1 if this doesn't look like a metafile or some error,
 *               or if it looks like a non-current metafile.
 *           0 if it looks like a current metafile.
 *
 * A side effect is that the file pointer will be pointing to the second
 * line if 0 is returned.
 */
int
rd_meta_is_broken(FILE *fp)
{
    char buf[MAILTMPLEN];

    if(fp == (FILE *)NULL)
      return -1;

    if(fp_file_size(fp) <
		    (long)(SIZEOF_PMAGIC + SIZEOF_SPACE + SIZEOF_VERSION_NUM))
      return -1;
    
    if(fseek(fp, (long)TO_FIND_HDR_PMAGIC, 0))
      return -1;

    /* check for magic */
    if(fread(buf, sizeof(char), (unsigned)SIZEOF_PMAGIC, fp) != SIZEOF_PMAGIC)
      return -1;

    buf[SIZEOF_PMAGIC] = '\0';
    if(strcmp(buf, PMAGIC) != 0)
      return -1;

    /*
     * If we change to a new version, we may want to add code here to convert
     * or to cleanup after the old version. For example, it might just
     * remove the old cache files here.
     */

    /* check for matching version number */
    if(fseek(fp, (long)TO_FIND_VERSION_NUM, 0))
      return -1;
    
    if(fread(buf, sizeof(char), (unsigned)SIZEOF_VERSION_NUM, fp) !=
       SIZEOF_VERSION_NUM)
      return -1;
    
    buf[SIZEOF_VERSION_NUM] = '\0';
    if(strcmp(buf, METAFILE_VERSION_NUM) != 0)
      return -1;

    /* Position file pointer to second line */
    if(fseek(fp, (long)TO_FIND_HDR_PMAGIC, 0))
      return -1;
    
    if(fgets(buf, sizeof(buf), fp) == NULL)
      return -1;

    return 0;
}


/*
 * Open a data stream to the remote data.
 */
void
rd_open_remote(REMDATA_S *rd)
{
    long openmode = SP_USEPOOL | SP_TEMPUSE;

    dprint((7, "rd_open_remote \"%s\"\n",
	   (rd && rd->rn) ? rd->rn : "?"));

    if(!rd)
      return;
    
    if(rd_stream_exists(rd)){
	rd->last_use = get_adj_time();
	return;
    }

    switch(rd->type){
      case RemImap:

	if(rd->access == ReadOnly)
	  openmode |= OP_READONLY;

	ps_global->noshow_error = 1;
	rd->t.i.stream = context_open(NULL, NULL, rd->rn, openmode, NULL);
	ps_global->noshow_error = 0;

        /* Don't try to reopen if there was a problem (auth failure, etc.) */
	if(!rd->t.i.stream)  
	  rd->flags |= USER_SAID_NO; /* Caution: overloading USER_SAID_NO */
	
	if(rd->t.i.stream && rd->t.i.stream->halfopen){
	    /* this is a failure */
	    rd_close_remote(rd);
	}

	if(rd->t.i.stream)
	  rd->last_use = get_adj_time();

	break;

      default:
	q_status_message(SM_ORDER, 3, 5, "rd_open_remote: type not supported");
	break;
    }
}


/*
 * Close a data stream to the remote data.
 */
void
rd_close_remote(REMDATA_S *rd)
{
    if(!rd || !rd_stream_exists(rd))
      return;

    switch(rd->type){
      case RemImap:
	ps_global->noshow_error = 1;
	pine_mail_close(rd->t.i.stream);
	rd->t.i.stream = NULL;
	ps_global->noshow_error = 0;
	break;

      default:
	q_status_message(SM_ORDER, 3, 5, "rd_close_remote: type not supported");
	break;
    }
}


int
rd_stream_exists(REMDATA_S *rd)
{
    if(!rd)
      return(0);

    switch(rd->type){
      case RemImap:
	return(rd->t.i.stream ? 1 : 0);

      default:
	q_status_message(SM_ORDER, 3,5, "rd_stream_exists: type not supported");
	break;
    }
    
    return(0);
}


/*
 * Ping the stream and return 1 if it is still alive.
 */
int
rd_ping_stream(REMDATA_S *rd)
{
    int ret = 0;

    dprint((7, "rd_ping_stream \"%s\"\n",
	   (rd && rd->rn) ? rd->rn : "?"));

    if(!rd)
      return(ret);

    if(!rd_stream_exists(rd)){
	switch(rd->type){
	  case RemImap:
	    /*
	     * If this stream is already actually open, officially open
	     * it and use it.
	     */
	    if(sp_stream_get(rd->rn, SP_MATCH)){
		long openflags = SP_USEPOOL | SP_TEMPUSE;

		if(rd->access == ReadOnly)
		  openflags |= OP_READONLY;

		rd->t.i.stream = pine_mail_open(NULL, rd->rn, openflags, NULL);
	    }

	    break;

	  default:
	    break;
	}
    }

    if(!rd_stream_exists(rd))
      return(ret);

    switch(rd->type){
      case RemImap:
	ps_global->noshow_error = 1;
	if(pine_mail_ping(rd->t.i.stream))
	  ret = 1;
	else
	  rd->t.i.stream = NULL;

	ps_global->noshow_error = 0;
	break;

      default:
	q_status_message(SM_ORDER, 3, 5, "rd_ping_stream: type not supported");
	break;
    }
    
    return(ret);
}


/*
 * Change readonly access to readwrite if appropriate. Call this if
 * the remote data ought to be readwrite but it is marked readonly in
 * the metadata.
 */
void
rd_check_readonly_access(REMDATA_S *rd)
{
    if(rd && rd->read_status == 'R'){
	switch(rd->type){
	  case RemImap:
	    rd_open_remote(rd);
	    if(rd->t.i.stream && !rd->t.i.stream->rdonly){
		rd->read_status = 'W';
		rd->access = ReadWrite;
	    }

	    break;

	  default:
	    q_status_message(SM_ORDER, 3, 5,
			     "rd_check_readonly_access: type not supported");
	    break;
	}
    }
}


/*
 * Initialize remote data. The remote data is initialized
 * with no data. On success, the local file will be empty and the remote
 * folder (if type RemImap) will contain a header message and an empty
 * data message.
 * The remote folder already exists before we get here, though it may be empty.
 *
 * Returns -1 on failure
 *          0 on success
 */
int
rd_init_remote(REMDATA_S *rd, int add_only_first_msg)
{
    int  err = 0;
    char date[200];

    dprint((7, "rd_init_remote \"%s\"\n",
	   (rd && rd->rn) ? rd->rn : "?"));

    if(rd && rd->type != RemImap){
	dprint((1, "rd_init_remote: type not supported\n"));
	return -1;
    }

    /*
     * The rest is currently type RemImap-specific. 
     */

    if(!(rd->flags & NO_FILE || rd->lf) ||
       !rd->rn || !rd->so || !rd->t.i.stream ||
       !rd->t.i.special_hdr){
	dprint((1,
	       "rd_init_remote: Unexpected error: %s is NULL\n",
	       !(rd->flags & NO_FILE || rd->lf) ? "localfile" :
		!rd->rn ? "remotename" :
		 !rd->so ? "so" :
		  !rd->t.i.stream ? "stream" :
		   !rd->t.i.special_hdr ? "special_hdr" : "?"));
	return -1;
    }

    /* already init'd */
    if(rd->t.i.stream->nmsgs >= 2 ||
       (rd->t.i.stream->nmsgs >= 1 && add_only_first_msg))
      return err;

    dprint((7, " - rd_init_remote(%s): %s\n",
	   rd->t.i.special_hdr ? rd->t.i.special_hdr : "?",
	   rd->rn ? rd->rn : "?"));
    
    /*
     * We want to protect the user who specifies an actual address book
     * file on the remote system as a remote address book. For example,
     * they might say address-book={host}.addressbook where .addressbook
     * is just a file on host. Remote address books are folders, not
     * files.  We also want to protect the user who specifies an existing
     * mail folder as a remote address book. We do that by requiring the
     * first message in the folder to be our header message.
     */

    if(rd->t.i.stream->rdonly){
	q_status_message1(SM_ORDER | SM_DING, 7, 10,
		 _("Can't initialize folder \"%s\" (write permission)"), rd->rn);
	if(rd->t.i.stream->nmsgs > 0)
	  q_status_message(SM_ORDER | SM_DING, 7, 10,
	   _("Choose a new, unused folder for the remote data"));

	dprint((1,
	       "Can't initialize remote folder \"%s\"\n",
	       rd->rn ? rd->rn : "?"));
	dprint((1,
	       "   No write permission for that remote folder.\n"));
	dprint((1,
		   "   Choose a new unused folder for the remote data.\n"));
	err = -1;
    }

    if(!err){
	if(rd->t.i.stream->nmsgs == 0){
	    int we_cancel;

	    we_cancel = busy_cue(_("Initializing remote data"), NULL, 1);
	    rfc822_date(date);
	    /*
	     * The first message in a remote data folder is a special
	     * header message. It is there as a way to explain what the
	     * folder is to users who open it trying to read it. It is also
	     * used as a consistency check so that we don't use a folder
	     * that was being used for something else as a remote
	     * data folder.
	     */
	    err = rd_add_hdr_msg(rd, date);
	    if(rd->t.i.stream->nmsgs == 0)
	      rd_ping_stream(rd);
	    if(rd->t.i.stream && rd->t.i.stream->nmsgs == 0)
	      pine_mail_check(rd->t.i.stream);

	    if(we_cancel)
	      cancel_busy_cue(-1);
	}
	else{
	    char *eptr = NULL;

	    err = rd_chk_for_hdr_msg(&(rd->t.i.stream), rd, &eptr);
	    if(err){
		q_status_message1(SM_ORDER | SM_DING, 5, 5,
		     _("\"%s\" has invalid format, can't initialize"), rd->rn);

		dprint((1,
		       "Can't initialize remote data \"%s\"\n",
		       rd->rn ? rd->rn : "?"));

		if(eptr){
		    q_status_message1(SM_ORDER, 3, 5, "%s", eptr);
		    dprint((1, "%s\n", eptr ? eptr : "?"));
		    fs_give((void **)&eptr);
		}
	    }
	}
    }

    /*
     * Add the second (empty) message.
     */
    if(!err && !add_only_first_msg){
	char *tempfile = NULL;
	int   fd = -1;

	if(rd->flags & NO_FILE){
	    if(so_truncate(rd->sonofile, 0L) == 0)
	      err = -1;
	}
	else{
	    if(!(tempfile = tempfile_in_same_dir(rd->lf, "a8", NULL))){
		q_status_message1(SM_ORDER | SM_DING, 3, 5,
				  _("Error opening temporary file: %s"),
				  error_description(errno));
		dprint((2, "init_remote: Error opening file: %s\n",
		       error_description(errno)));
		err = -1;
	    }

	    if(!err &&
	       (fd = our_open(tempfile, O_TRUNC|O_WRONLY|O_CREAT|O_BINARY, 0600)) < 0){
		q_status_message2(SM_ORDER | SM_DING, 3, 5,
				  "Error opening temporary file %.200s: %.200s",
				  tempfile, error_description(errno));
		dprint((2,
		       "init_remote: Error opening temporary file: %s: %s\n",
		       tempfile ? tempfile : "?", error_description(errno)));
		our_unlink(tempfile);
		err = -1;
	    }
	    else
	      (void)close(fd);

	    if(!err && rename_file(tempfile, rd->lf) < 0){
		q_status_message2(SM_ORDER | SM_DING, 3, 5,
			      "Error creating cache file %.200s: %.200s",
			      rd->lf, error_description(errno));
		our_unlink(tempfile);
		err = -1;
	    }

	    if(tempfile)
	      fs_give((void **)&tempfile);
	}

	if(!err){
	    err = rd_update_remote(rd, date);
	    if(err){
		q_status_message1(SM_ORDER | SM_DING, 3, 5,
				  _("Error copying to remote folder: %s"),
				  error_description(errno));
		
		q_status_message(SM_ORDER | SM_DING, 5, 5,
				 "Creation of remote data folder failed");
	    }
	}
    }

    if(!err){
	rd_update_metadata(rd, date);
	/* turn off out of date flag */
	rd->flags &= ~REM_OUTOFDATE;
    }

    return(err ? -1 : 0);
}


/*
 * IMAP stream should already be open to a remote folder.
 * Check the first message in the folder to be sure it is the right
 * kind of message, not some message from some other folder.
 *
 * Returns 0 if ok, < 0 if invalid format.
 *
 */
int
rd_chk_for_hdr_msg(MAILSTREAM **streamp, REMDATA_S *rd, char **errmsg)
{
    char *fields[3], *values[3];
    char *h;
    int   tried_again = 0;
    int   ret;
    MAILSTREAM *st = NULL;

    fields[0] = rd->t.i.special_hdr;
    fields[1] = "received";
    fields[2] = NULL;

try_again:
    ret = -1;

    if(!streamp || !*streamp){
	dprint((1, "rd_chk_for_hdr_msg: stream is null\n"));
    }
    else if((*streamp)->nmsgs == 0){
	ret = -2;
	dprint((1,
		   "rd_chk_for_hdr_msg: stream has nmsgs=0, try a ping\n"));
	if(!pine_mail_ping(*streamp))
	  *streamp = NULL;

	if(*streamp && (*streamp)->nmsgs == 0){
	    dprint((1,
	       "rd_chk_for_hdr_msg: still looks like nmsgs=0, try a check\n"));
	    pine_mail_check(*streamp);
	}

	if(*streamp && (*streamp)->nmsgs == 0){
	    dprint((1,
	       "rd_chk_for_hdr_msg: still nmsgs=0, try re-opening stream\n"));

	    if(rd_stream_exists(rd))
	      rd_close_remote(rd);

	    rd_open_remote(rd);
	    if(rd_stream_exists(rd))
	      st = rd->t.i.stream;
	}

	if(!st)
	  st = *streamp;

	if(st && st->nmsgs == 0){
	    dprint((1,
		       "rd_chk_for_hdr_msg: can't see header message\n"));
	}
    }
    else
      st = *streamp;

    if(st && st->nmsgs != 0
       && (h=pine_fetchheader_lines(st, 1L, NULL, fields))){
	simple_header_parse(h, fields, values);
	ret = -3;
	if(values[1])
	  ret = -4;
	else if(values[0]){
	    rd->cookie = strtoul(values[0], (char **)NULL, 10);
	    if(rd->cookie == 0)
	      ret = -5;
	    else if(rd->cookie == 1){
		if(rd->flags & COOKIE_ONE_OK || tried_again)
		  ret = 0;
		else
		  ret = -6;
	    }
	    else if(rd->cookie > 1)
	      ret = 0;
	}

	if(values[0])
	  fs_give((void **)&values[0]);

	if(values[1])
	  fs_give((void **)&values[1]);

	fs_give((void **)&h);
    }
    
    
    if(ret && ret != -6 && errmsg){
	*errmsg = (char *)fs_get(500 * sizeof(char));
	(*errmsg)[0] = '\0';
    }

    if(ret == -1){
	/* null stream */
	if(errmsg)
	  snprintf(*errmsg, 500, _("Can't open remote address book \"%s\""), rd->rn);
    }
    else if(ret == -2){
	/* no messages in folder */
	if(errmsg)
	  snprintf(*errmsg, 500,
		  _("Error: no messages in remote address book \"%s\"!"),
		  rd->rn);
    }
    else if(ret == -3){
	/* no cookie */
	if(errmsg)
	  snprintf(*errmsg, 500,
		  "First msg in \"%s\" should have \"%s\" header",
		  rd->rn, rd->t.i.special_hdr);
    }
    else if(ret == -4){
	/* Received header */
	if(errmsg)
	  snprintf(*errmsg, 500,
		  _("Suspicious Received headers in first msg in \"%s\""),
		  rd->rn);
    }
    else if(ret == -5){

	/* cookie is 0 */

	/*
	 * This is a failure and should not happen, but we're not going to
	 * fail on this condition.
	 */
	dprint((1, "Unexpected value in \"%s\" header of \"%s\"\n",
	       rd->t.i.special_hdr ? rd->t.i.special_hdr : "?",
	       rd->rn ? rd->rn : "?"));
	ret = 0;
    }
    else if(ret == -6){
	dprint((1,
		   "rd_chk_for_hdr_msg: cookie is 1, try to upgrade it\n"));

	if(rd_remote_is_readonly(rd)){
	    dprint((1,
		   "rd_chk_for_hdr_msg:  can't upgrade, readonly\n"));
	    ret = 0;			/* stick with 1 */
	}
	else{
	    /* cookie is 1, upgrade it */
	    if(rd_upgrade_cookies(rd, st->nmsgs, 0) == 0){
		/* now check again */
		if(!tried_again){
		    tried_again++;
		    goto try_again;
		}
	    }

	    /*
	     * This is actually a failure but we've decided that this
	     * failure is ok.
	     */
	    ret = 0;
	}
    }

    if(errmsg && *errmsg)
      dprint((1, "rd_chk_for_hdr_msg: %s\n", *errmsg));

    return ret;
}


/*
 * For remote data, this adds the explanatory header
 * message to the remote IMAP folder.
 *
 * Args:    rd -- Remote data handle
 *        date -- The date string to use
 *
 * Result: 0 success
 *        -1 failure
 */
int
rd_add_hdr_msg(REMDATA_S *rd, char *date)
{
    int           err = 0;

    if(!rd|| rd->type != RemImap || !rd->rn || !rd->so || !rd->t.i.special_hdr){
	dprint((1,
	       "rd_add_hdr_msg: Unexpected error: %s is NULL\n",
	       !rd ? "rd" :
		!rd->rn ? "remotename" :
		 !rd->so ? "so" :
		  !rd->t.i.special_hdr ? "special_hdr" : "?"));
	return -1;
    }

    err = rd_store_fake_hdrs(rd, "Header Message for Remote Data",
			     "plain", date);

    /* Write the dummy message */
    if(!strucmp(rd->t.i.special_hdr, REMOTE_ABOOK_SUBTYPE)){
	if(!err && so_puts(rd->so,
	    "This folder contains a single Alpine addressbook.\015\012") == 0)
	  err = -1;
	if(!err && so_puts(rd->so,
	    "This message is just an explanatory message.\015\012") == 0)
	  err = -1;
	if(!err && so_puts(rd->so,
	    "The last message in the folder is the live addressbook data.\015\012") == 0)
	  err = -1;
	if(!err && so_puts(rd->so,
	    "The rest of the messages contain previous revisions of the addressbook data.\015\012") == 0)
	  err = -1;
	if(!err && so_puts(rd->so,
	    "To restore a previous revision just delete and expunge all of the messages\015\012") == 0)
	  err = -1;
	if(!err && so_puts(rd->so,
	    "which come after it.\015\012") == 0)
	  err = -1;
    }
    else if(!strucmp(rd->t.i.special_hdr, REMOTE_PINERC_SUBTYPE)){
	if(!err && so_puts(rd->so,
	    "This folder contains a Alpine config file.\015\012") == 0)
	  err = -1;
	if(!err && so_puts(rd->so,
	    "This message is just an explanatory message.\015\012") == 0)
	  err = -1;
	if(!err && so_puts(rd->so,
	    "The last message in the folder is the live config data.\015\012") == 0)
	  err = -1;
	if(!err && so_puts(rd->so,
	    "The rest of the messages contain previous revisions of the data.\015\012") == 0)
	  err = -1;
	if(!err && so_puts(rd->so,
	    "To restore a previous revision just delete and expunge all of the messages\015\012") == 0)
	  err = -1;
	if(!err && so_puts(rd->so,
	    "which come after it.\015\012") == 0)
	  err = -1;
    }
    else{
	if(!err && so_puts(rd->so,
	    "This folder contains remote Alpine data.\015\012") == 0)
	  err = -1;
	if(!err && so_puts(rd->so,
	    "This message is just an explanatory message.\015\012") == 0)
	  err = -1;
	if(!err && so_puts(rd->so,
	    "The last message in the folder is the live data.\015\012") == 0)
	  err = -1;
	if(!err && so_puts(rd->so,
	    "The rest of the messages contain previous revisions of the data.\015\012") == 0)
	  err = -1;
	if(!err && so_puts(rd->so,
	    "To restore a previous revision just delete and expunge all of the messages\015\012") == 0)
	  err = -1;
	if(!err && so_puts(rd->so,
	    "which come after it.\015\012") == 0)
	  err = -1;
    }

    /* Take the message from "so" to the remote folder */
    if(!err){
	MAILSTREAM *st;

	if((st = rd->t.i.stream) != NULL)
	  rd->t.i.shouldbe_nmsgs = rd->t.i.stream->nmsgs + 1;
	else
	  st = adrbk_handy_stream(rd->rn);

	err = write_fcc(rd->rn, NULL, rd->so, st, "remote data", NULL) ? 0 : -1;
    }
    
    return err;
}


/*
 * Write some fake header lines into storage object rd->so.
 *
 * Args: rd
 *     subject -- subject to put in header
 *     subtype -- subtype to put in header
 *     date    -- date to put in header
 */
int
rd_store_fake_hdrs(REMDATA_S *rd, char *subject, char *subtype, char *date)
{
    ENVELOPE     *fake_env;
    BODY         *fake_body;
    ADDRESS      *fake_from;
    int           err = 0;
    char          vers[50], *p;
    unsigned long r = 0L;
    RFC822BUFFER rbuf;

    if(!rd|| rd->type != RemImap || !rd->so || !rd->t.i.special_hdr)
      return -1;
    
    fake_env = (ENVELOPE *)fs_get(sizeof(ENVELOPE));
    memset(fake_env, 0, sizeof(ENVELOPE));
    fake_body = (BODY *)fs_get(sizeof(BODY));
    memset(fake_body, 0, sizeof(BODY));
    fake_from = (ADDRESS *)fs_get(sizeof(ADDRESS));
    memset(fake_from, 0, sizeof(ADDRESS));

    fake_env->subject = cpystr(subject);
    fake_env->date = (unsigned char *) cpystr(date);
    fake_from->personal = cpystr("Pine Remote Data");
    fake_from->mailbox = cpystr("nobody");
    fake_from->host = cpystr("nowhere");
    fake_env->from = fake_from;
    fake_body->type = REMOTE_DATA_TYPE;
    fake_body->subtype = cpystr(subtype);
    set_parameter(&fake_body->parameter, "charset", "UTF-8");

    if(rd->cookie > 0)
      r = rd->cookie;

    if(!r){
	int i;

	for(i = 100; i > 0 && r < 1000000; i--)
	  r = random();
	
	if(r < 1000000)
	  r = 1712836L + getpid();
	
	rd->cookie = r;
    }

    snprintf(vers, sizeof(vers), "%ld", r);

    p = tmp_20k_buf;
    *p = '\0';
    rbuf.f   = dummy_soutr;
    rbuf.s   = NULL;
    rbuf.beg = p;
    rbuf.cur = p;
    rbuf.end = p+SIZEOF_20KBUF-1;
    rfc822_output_header_line(&rbuf, rd->t.i.special_hdr, 0L, vers);
    rfc822_output_header(&rbuf, fake_env, fake_body, NULL, 0L);
    *rbuf.cur = '\0';

    mail_free_envelope(&fake_env);
    mail_free_body(&fake_body);

    /* Write the fake headers */
    if(so_puts(rd->so, tmp_20k_buf) == 0)
      err = -1;
    
    return err;
}


/*
 * We have discovered that the data in the remote folder is suspicious.
 * In some cases it is just because it is from an old version of pine.
 * We have decided to update the data so that it won't look suspicious
 * next time.
 *
 * Args -- only_update_last  If set, that means to just add a new last message
 *                           by calling rd_update_remote. Don't create a new
 *                           header message and delete the old header message.
 *         nmsgs             Not used if only_update_last is set
 */
int
rd_upgrade_cookies(REMDATA_S *rd, long int nmsgs, int only_update_last)
{
    char date[200];
    int  err = 0;

    /*
     * We need to copy the data from the last message, add a new header
     * message with a random cookie, add the data back in with the
     * new cookie, and delete the old messages.
     */

    /* get data */
    rd->flags |= COOKIE_ONE_OK;

    /*
     * The local copy may be newer than the remote copy. We don't want to
     * blast the local copy in that case. The BELIEVE_CACHE flag tells us
     * to not do the blasting.
     */
    if(rd->flags & BELIEVE_CACHE)
      rd->flags &= ~BELIEVE_CACHE;
    else{
	dprint((1, "rd_upgrade_cookies:  copy abook data\n"));
	err = rd_update_local(rd);
    }

    if(!err && !only_update_last){
	rd->cookie = 0;		/* causes new cookie to be generated */
	rfc822_date(date);
	dprint((1, "rd_upgrade_cookies:  add new hdr msg to end\n"));
	err = rd_add_hdr_msg(rd, date);
    }

    if(!err){
	dprint((1, "rd_upgrade_cookies:  copy back data\n"));
	err = rd_update_remote(rd, NULL);
    }

    rd->flags &= ~COOKIE_ONE_OK;

    if(!err && !only_update_last){
	char sequence[20];

	/*
	 * We've created a new header message and added a new copy of the
	 * data after it. Only problem is that the new copy will have used
	 * the original header message to get its cookie (== 1) from. We
	 * could have deleted the original messages before the last step
	 * to get it right but that would delete all copies of the data
	 * temporarily. Delete now and then re-update.
	 */
	rd_ping_stream(rd);
	rd_open_remote(rd);
	if(rd->t.i.stream && rd->t.i.stream->nmsgs >= nmsgs+2){
	    snprintf(sequence, sizeof(sequence), "1:%ld", nmsgs);
	    mail_flag(rd->t.i.stream, sequence, "\\DELETED", ST_SET);
	    mail_expunge(rd->t.i.stream);
	    err = rd_update_remote(rd, NULL);
	}
    }

    return(err);
}


/*
 * Copy remote data to local file. If needed, the remote data is initialized
 * with no data. On success, the local file contains the remote data (which
 * means it will be empty if we initialized).
 *
 * Returns != 0 on failure
 *            0 on success
 */
int
rd_update_local(REMDATA_S *rd)
{
    char     *error;
    STORE_S  *store;
    gf_io_t   pc;
    int       i, we_cancel = 0;
    BODY     *body = NULL;
    ENVELOPE *env;
    char     *tempfile = NULL;


    if(!rd || !(rd->flags & NO_FILE || rd->lf) || !rd->rn){
	dprint((1,
	       "rd_update_local: Unexpected error: %s is NULL\n",
	       !rd ? "rd" :
		!(rd->flags & NO_FILE || rd->lf) ? "localfile" :
		 !rd->rn ? "remotename" : "?"));

	return -1;
    }

    dprint((3, " - rd_update_local(%s): %s => %s\n",
	   rd->type == RemImap ? "Imap" : "?", rd->rn ? rd->rn : "?",
	   (rd->flags & NO_FILE) ? "<mem>" : (rd->lf ? rd->lf : "?")));
    
    switch(rd->type){
      case RemImap:
	if(!rd->so || !rd->t.i.special_hdr){
	    dprint((1,
		   "rd_update_local: Unexpected error: %s is NULL\n",
		   !rd->so ? "so" :
		    !rd->t.i.special_hdr ? "special_hdr" : "?"));
	    return -1;
	}

	rd_open_remote(rd);
	if(!rd_stream_exists(rd)){
	    if(rd->flags & NO_PERM_CACHE){
		dprint((1,
	     "rd_update_local: backtrack, remote folder does not exist yet\n"));
	    }
	    else{
		dprint((1,
		       "rd_update_local: Unexpected error: stream is NULL\n"));
	    }

	    return -1;
	}

	if(rd->t.i.stream){
	    char  ebuf[500];
	    char *eptr = NULL;
	    int   chk;

	    /* force ReadOnly */
	    if(rd->t.i.stream->rdonly){
		rd->read_status = 'R';
		rd->access = ReadOnly;
	    }
	    else
	      rd->read_status = 'W';

	    if(rd->t.i.stream->nmsgs < 2)
	      return(rd_init_remote(rd, 0));
	    else if(rd_chk_for_hdr_msg(&(rd->t.i.stream), rd, &eptr)){
		q_status_message1(SM_ORDER | SM_DING, 5, 5,
		     _("Can't initialize \"%s\" (invalid format)"), rd->rn);

		if(eptr){
		    q_status_message1(SM_ORDER, 3, 5, "%s", eptr);
		    dprint((1, "%s\n", eptr));
		    fs_give((void **)&eptr);
		}

		dprint((1,
		       "Can't initialize remote data \"%s\"\n",
		       rd->rn ? rd->rn : "?"));
		return -1;
	    }

	    we_cancel = busy_cue(_("Copying remote data"), NULL, 1);

	    if(rd->flags & NO_FILE){
		store = rd->sonofile;
		so_truncate(store, 0L);
	    }
	    else{
		if(!(tempfile = tempfile_in_same_dir(rd->lf, "a8", NULL))){
		    q_status_message1(SM_ORDER | SM_DING, 3, 5,
				      _("Error opening temporary file: %s"),
				      error_description(errno));
		    dprint((2,
			  "rd_update_local: Error opening temporary file: %s\n",
			  error_description(errno)));
		    return -1;
		}

		/* Copy the data into tempfile */
		if((store = so_get(FileStar, tempfile, WRITE_ACCESS|OWNER_ONLY))
								    == NULL){
		    q_status_message2(SM_ORDER | SM_DING, 3, 5,
				  _("Error opening temporary file %s: %s"),
				      tempfile, error_description(errno));
		    dprint((2,
		      "rd_update_local: Error opening temporary file: %s: %s\n",
		      tempfile ? tempfile : "?",
		      error_description(errno)));
		    our_unlink(tempfile);
		    fs_give((void **)&tempfile);
		    return -1;
		}
	    }

	    /*
	     * Copy from the last message in the folder.
	     */
	    if(!pine_mail_fetchstructure(rd->t.i.stream, rd->t.i.stream->nmsgs,
					 &body)){
		q_status_message(SM_ORDER | SM_DING, 3, 4,
				 _("Can't access remote IMAP data"));
		dprint((2, "Can't access remote IMAP data\n"));
		if(tempfile){
		    our_unlink(tempfile);
		    fs_give((void **)&tempfile);
		}

		if(!(rd->flags & NO_FILE))
		  so_give(&store);

		if(we_cancel)
		  cancel_busy_cue(-1);

		return -1;
	    }

	    if(!body ||
	       body->type != REMOTE_DATA_TYPE ||
	       !body->subtype ||
	       strucmp(body->subtype, rd->t.i.special_hdr)){
		q_status_message(SM_ORDER | SM_DING, 3, 4,
				 _("Remote IMAP folder has wrong contents"));
		dprint((2,
		       "Remote IMAP folder has wrong contents\n"));
		if(tempfile){
		    our_unlink(tempfile);
		    fs_give((void **)&tempfile);
		}

		if(!(rd->flags & NO_FILE))
		  so_give(&store);

		if(we_cancel)
		  cancel_busy_cue(-1);

		return -1;
	    }
	    
	    if(!(env = pine_mail_fetchenvelope(rd->t.i.stream,
					       rd->t.i.stream->nmsgs))){
		q_status_message(SM_ORDER | SM_DING, 3, 4,
				 _("Can't access check date in remote data"));
		dprint((2,
		       "Can't access check date in remote data\n"));
		if(tempfile){
		    our_unlink(tempfile);
		    fs_give((void **)&tempfile);
		}

		if(!(rd->flags & NO_FILE))
		  so_give(&store);

		if(we_cancel)
		  cancel_busy_cue(-1);

		return -1;
	    }

	    if(rd && rd->flags & USER_SAID_YES)
	      chk = 0;
	    else
	      chk = rd_check_for_suspect_data(rd);

	    switch(chk){
	      case -1:		/* suspicious data, user says abort */
		if(tempfile){
		    our_unlink(tempfile);
		    fs_give((void **)&tempfile);
		}

		if(!(rd->flags & NO_FILE))
		  so_give(&store);

		if(we_cancel)
		  cancel_busy_cue(-1);

		return -1;

	      case 1:		/* suspicious data, user says go ahead */
		if(rd_remote_is_readonly(rd)){
		    dprint((1,
			   "rd_update_local:  can't upgrade, readonly\n"));
		}
		else
		  /* attempt to upgrade cookie in last message */
		  (void)rd_upgrade_cookies(rd, 0, 1);

	        break;

	      case 0:		/* all is ok */
	      default:
	        break;
	    }


	    /* store may have been written to at this point, so we'll clear it out  */
	    so_truncate(store, 0L);

	    gf_set_so_writec(&pc, store);

	    error = detach(rd->t.i.stream, rd->t.i.stream->nmsgs, "1", 0L,
			   NULL, pc, NULL, DT_NODFILTER);

	    gf_clear_so_writec(store);


	    if(we_cancel)
	      cancel_busy_cue(-1);

	    if(!(rd->flags & NO_FILE)){
		if(so_give(&store)){
		    snprintf(ebuf, sizeof(ebuf), _("Error writing temp file: %s"),
			    error_description(errno));
		    error = ebuf;
		}
	    }

	    if(error){
		q_status_message1(SM_ORDER | SM_DING, 3, 4,
			      _("%s: Error copying remote IMAP data"), error);
		dprint((2, "rd_update_local: Error copying: %s\n",
		       error ? error : "?"));
		if(tempfile){
		    our_unlink(tempfile);
		    fs_give((void **)&tempfile);
		}

		return -1;
	    }

	    if(tempfile && (i = rename_file(tempfile, rd->lf)) < 0){
#ifdef	_WINDOWS
		if(i == -5){
		    q_status_message2(SM_ORDER | SM_DING, 3, 4,
				    _("Error updating local file: %s: %s"),
				      rd->lf, error_description(errno));
		    q_status_message(SM_ORDER, 3, 4,
				 _("Perhaps another process has the file open?"));
		    dprint((2,
	"Rename_file(%s,%s): %s: returned -5, another process has file open?\n",
			   tempfile ? tempfile : "?",
			   rd->lf ? rd->lf : "?",
			   error_description(errno)));
		}
		else
#endif	/* _WINDOWS */
		{
		q_status_message2(SM_ORDER | SM_DING, 3, 5,
				  _("Error updating cache file %s: %s"),
				  rd->lf, error_description(errno));
		dprint((2,
		       "Error updating cache file %s: rename(%s,%s): %s\n",
		       tempfile ? tempfile : "?",
		       tempfile ? tempfile : "?",
		       rd->lf ? rd->lf : "?",
		       error_description(errno)));
		}

		our_unlink(tempfile);
		fs_give((void **)&tempfile);
		return -1;
	    }

	    dprint((5,
		   "in rd_update_local, setting chk_date to ->%s<-\n",
		   env->date ? (char *)env->date : "?"));
	    rd_update_metadata(rd, (char *) env->date);

	    /* turn off out of date flag */
	    rd->flags &= ~REM_OUTOFDATE;

	    if(tempfile)
	      fs_give((void **)&tempfile);

	    return 0;
	}
	else{
	    q_status_message1(SM_ORDER | SM_DING, 5, 5,
		 _("Can't open remote IMAP folder \"%s\""), rd->rn);
	    dprint((1,
		   "Can't open remote IMAP folder \"%s\"\n",
		   rd->rn ? rd->rn : "?"));
	    rd->access = ReadOnly;
	    return -1;
	}

	break;

      default:
	dprint((1, "rd_update_local: Unsupported type\n"));
	return -1;
    }
}


/*
 * Copy local data to remote folder.
 *
 * Args         lf -- Local file name
 *              rn -- Remote name
 * header_to_check -- Name of indicator header in remote folder
 *       imapstuff -- Structure holding info about connection
 *      returndate -- Pointer to the date that was stored in the remote folder
 *
 * Returns !=0 on failure
 *          0 on success
 */
int
rd_update_remote(REMDATA_S *rd, char *returndate)
{
    STORE_S    *store;
    int         err = 0;
    long        openmode = SP_USEPOOL | SP_TEMPUSE;
    MAILSTREAM *st;
    char       *eptr = NULL;

    if(rd && rd->type != RemImap){
	dprint((1, "rd_update_remote: type not supported\n"));
	return -1;
    }

    if(!rd || !(rd->flags & NO_FILE || rd->lf) || !rd->rn ||
       !rd->so || !rd->t.i.special_hdr){
	dprint((1,
	       "rd_update_remote: Unexpected error: %s is NULL\n",
	       !rd ? "rd" :
	        !(rd->flags & NO_FILE || rd->lf) ? "localfile" :
		 !rd->rn ? "remotename" :
		  !rd->so ? "so" :
		    !rd->t.i.special_hdr ? "special_hdr" : "?"));
	return -1;
    }

    dprint((7, " - rd_update_remote(%s): %s => %s\n",
	   rd->t.i.special_hdr ? rd->t.i.special_hdr : "?",
	   rd->lf ? rd->lf : "<mem>",
	   rd->rn ? rd->rn : "?"));

    if(!(st = rd->t.i.stream))
      st = adrbk_handy_stream(rd->rn);

    if(!st)
      st = rd->t.i.stream = context_open(NULL, NULL, rd->rn, openmode, NULL);

    if(!st){
	q_status_message1(SM_ORDER | SM_DING, 5, 5,
	     _("Can't open \"%s\" for copying"), rd->rn);
	dprint((1,
	  "rd_update_remote: Can't open remote folder \"%s\" for copying\n",
	       rd->rn ? rd->rn : "?"));
	return 1;
    }

    rd->last_use = get_adj_time();
    err = rd_chk_for_hdr_msg(&st, rd, &eptr);
    if(err){
	q_status_message1(SM_ORDER | SM_DING, 5, 5,
			  _("\"%s\" has invalid format"), rd->rn);

	if(eptr){
	    q_status_message1(SM_ORDER, 3, 5, "%s", eptr);
	    dprint((1, "%s\n", eptr));
	    fs_give((void **)&eptr);
	}

	dprint((1,
	   "rd_update_remote: \"%s\" has invalid format\n",
	   rd->rn ? rd->rn : "?"));
	return 1;
    }

    errno = 0;

    /*
     * The data that will be going to the remote folder rn is
     * written into the following storage object and then copied to
     * the remote folder from there.
     */

    if(rd->flags & NO_FILE){
	store = rd->sonofile;
	if(store)
	  so_seek(store, 0L, 0);	/* rewind */
    }
    else
      store = so_get(FileStar, rd->lf, READ_ACCESS);

    if(store != NULL){
	char date[200];
	unsigned char c;
	unsigned char last_c = 0;

	/* Reset the storage object, since we may have already used it. */
	if(so_truncate(rd->so, 0L) == 0)
	  err = 1;

	rfc822_date(date);
	dprint((7,
	       "in rd_update_remote, storing date ->%s<-\n",
	       date ? date : "?"));
	if(!err && rd_store_fake_hdrs(rd, "Pine Remote Data Container",
				      rd->t.i.special_hdr, date))
	  err = 1;
	
	/* save the date for later comparisons */
	if(!err && returndate)
	  strncpy(returndate, date, 100);

	/* Write the data */
	while(!err && so_readc(&c, store)){
	    /*
	     * C-client expects CRLF-terminated lines. Convert them
	     * as we copy into c-client. Read ahead isn't available.
	     * Leave CRLF as is, convert LF to CRLF, leave CR as is.
	     */
	    if(last_c != '\r' && c == '\n'){
		/* Convert \n to CRFL */
		if(so_writec('\r', rd->so) == 0 || so_writec('\n', rd->so) == 0)
		  err = 1;
		
		last_c = 0;
	    }
	    else{
		last_c = c;
		if(so_writec((int) c, rd->so) == 0)
		  err = 1;
	    }
	}

	/*
	 * Take that message from so to the remote folder.
	 * We append to that folder and always
	 * use the final message as the active data.
	 */
	if(!err){
	    MAILSTREAM *st;

	    if((st = rd->t.i.stream) != NULL)
	      rd->t.i.shouldbe_nmsgs = rd->t.i.stream->nmsgs + 1;
	    else
	      st = adrbk_handy_stream(rd->rn);

	    err = write_fcc(rd->rn, NULL, rd->so, st,
			    "remote data", NULL) ? 0 : 1;
	}


	if(!(rd->flags & NO_FILE))
	  so_give(&store);
    }
    else
      err = -1;

    if(err)
	dprint((2, "error in rd_update_remote for %s => %s\n",
	       rd->lf ? rd->lf : "<mem>", rd->rn ? rd->rn : "?"));

    return(err);
}


/*
 * Check to see if the remote data has changed since we cached it.
 *
 * Args    rd -- REMDATA handle
 *  do_it_now -- If > 0, check now regardless
 *               If = 0, check if time since last chk more than default
 *               If < 0, check if time since last chk more than -do_it_now
 */
void
rd_check_remvalid(REMDATA_S *rd, long int do_it_now)
{
    time_t      chk_interval;
    long        openmode = SP_USEPOOL | SP_TEMPUSE;
    MAILSTREAM *stat_stream = NULL;
    int         we_cancel = 0, got_cmsgs = 0;
    unsigned long current_nmsgs;

    dprint((7, "- rd_check_remvalid(%s) -\n",
	   (rd && rd->rn) ? rd->rn : ""));

    if(rd && rd->type != RemImap){
	dprint((1, "rd_check_remvalid: type not supported\n"));
	return;
    }

    if(!rd || rd->flags & REM_OUTOFDATE || rd->flags & USE_OLD_CACHE)
      return;

    if(!rd->t.i.chk_date){
	dprint((2,
	       "rd_check_remvalid: remote data %s changed (chk_date)\n",
	       rd->rn));
	rd->flags |= REM_OUTOFDATE;
	return;
    }

    if(rd->t.i.chk_nmsgs <= 1){
	dprint((2,
	  "rd_check_remvalid: remote data %s changed (chk_nmsgs <= 1)\n",
	       rd->rn ? rd->rn : "?"));
	rd->flags |= REM_OUTOFDATE;
	return;
    }

    if(do_it_now < 0L){
	chk_interval = -1L * do_it_now;
	do_it_now = 0L;
    }
    else
      chk_interval = ps_global->remote_abook_validity * 60L;

    /* too soon to check again */
    if(!do_it_now &&
       (chk_interval == 0L ||
        get_adj_time() <= rd->last_valid_chk + chk_interval))
      return;
    
    if(rd->access == ReadOnly)
      openmode |= OP_READONLY;

    rd->last_valid_chk = get_adj_time();
    mm_status_result.flags  = 0L;

    /* make sure the cache file is still there */
    if(rd->lf && can_access(rd->lf, READ_ACCESS) != 0){
	dprint((2,
	       "rd_check_remvalid: %s: cache file %s disappeared\n",
	       rd->rn ? rd->rn : "?",
	       rd->lf ? rd->lf : "?"));
	rd->flags |= REM_OUTOFDATE;
	return;
    }

    /*
     * If the stream is open we should check there instead of using
     * a STATUS command. Check to see if it is really still alive with the
     * ping. It would be convenient if we could use a status command
     * on the open stream but apparently that won't work everywhere.
     */
    rd_ping_stream(rd);

try_looking_in_stream:

    /*
     * Get the current number of messages in the folder to
     * compare with our saved number of messages.
     */
    current_nmsgs = 0;
    if(rd->t.i.stream){
	dprint((7, "using open remote data stream\n"));
	rd->last_use = get_adj_time();
	current_nmsgs = rd->t.i.stream->nmsgs;
	got_cmsgs++;
    }
    else{

	/*
	 * Try to use the imap status command
	 * to get the information as cheaply as possible.
	 * If NO_STATUSCMD is set we just bypass all this stuff.
	 */

	if(!(rd->flags & NO_STATUSCMD))
	  stat_stream = adrbk_handy_stream(rd->rn);

	/*
	 * If we don't have a stream to use for the status command we
	 * skip it and open the folder instead. Then, next time we want to
	 * check we'll probably be able to use that open stream instead of
	 * opening another one each time for the status command.
	 */
	if(stat_stream){
	    if(!LEVELSTATUS(stat_stream)){
		rd->flags |= NO_STATUSCMD;
		dprint((2,
   "rd_check_remvalid: remote data %s: server doesn't support status\n",
		       rd->rn ? rd->rn : "?"));
	    }
	    else{
		/*
		 * This sure seems like a crock. We have to check to
		 * see if the stream is actually open to the folder
		 * we want to do the status on because c-client can't
		 * do a status on an open folder. In this case, we fake
		 * the status command results ourselves.
		 * If we're so unlucky as to get back a stream that will
		 * work for the status command while we also have another
		 * stream that is rd->rn and we don't pick up on that,
		 * too bad.
		 */
		if(same_stream_and_mailbox(rd->rn, stat_stream)){
		    dprint((7,
			   "rd_check_remvalid: faking status\n"));
		    mm_status_result.flags = SA_MESSAGES | SA_UIDVALIDITY
					     | SA_UIDNEXT;
		    mm_status_result.messages = stat_stream->nmsgs;
		    mm_status_result.uidvalidity = stat_stream->uid_validity;
		    mm_status_result.uidnext = stat_stream->uid_last+1;
		}
		else{

		    dprint((7,
			   "rd_check_remvalid: trying status\n"));
		    ps_global->noshow_error = 1;
		    if(!pine_mail_status(stat_stream, rd->rn,
				    SA_UIDVALIDITY | SA_UIDNEXT | SA_MESSAGES)){
			/* failed, mark it so we won't try again */
			rd->flags |= NO_STATUSCMD;
			dprint((2,
		   "rd_check_remvalid: addrbook %s: status command failed\n",
		   rd->rn ? rd->rn : "?"));
			mm_status_result.flags = 0L;
		    }
		}

		ps_global->noshow_error = 0;
	    }
	}

	/* if we got back a result from the status command, use it */
	if(mm_status_result.flags){
	    dprint((7,
		   "rd_check_remvalid: got status_result 0x%x\n",
		   mm_status_result.flags));
	    if(mm_status_result.flags & SA_MESSAGES){
		current_nmsgs = mm_status_result.messages;
		got_cmsgs++;
	    }
	}
    }

    /*
     * Check current_nmsgs versus what we think it should be.
     * If they're different we know things have changed and we can
     * return now. If they're the same we don't know.
     */
    if(got_cmsgs && current_nmsgs != rd->t.i.chk_nmsgs){
	rd->flags |= REM_OUTOFDATE;
	dprint((2,
	       "rd_check_remvalid: remote data %s changed (current msgs (%ld) != chk_nmsgs (%ld))\n",
	       rd->rn ? rd->rn : "?", current_nmsgs, rd->t.i.chk_nmsgs));
	return;
    }
    
    /*
     * Get the current uidvalidity and uidnext values from the
     * folder to compare with our saved values.
     */
    if(rd->t.i.stream){
	if(rd->t.i.stream->uid_validity == rd->t.i.uidvalidity){
	    /*
	     * Uid is valid so we just have to check whether or not the
	     * uid of the last message has changed or not and return.
	     */
	    if(mail_uid(rd->t.i.stream, rd->t.i.stream->nmsgs) != rd->t.i.uid){
		/* uid has changed so we're out of date */
		rd->flags |= REM_OUTOFDATE;
		dprint((2,
		     "rd_check_remvalid: remote data %s changed (uid)\n",
		     rd->rn ? rd->rn : "?"));
	    }
	    else{
		dprint((7,"rd_check_remvalid: uids match\n"));
	    }

	    return;
	}
	else{
	    /*
	     * If the uidvalidity changed that probably means it can't
	     * be relied on to be meaningful, so don't use it in the future.
	     */
	    rd->flags |= NO_STATUSCMD;
	    dprint((7,
       "rd_check_remvalid: remote data %s uidvalidity changed, don't use uid\n",
		   rd->rn ? rd->rn : "?"));
	}
    }
    else{			/* stream not open, use status results */
	if(mm_status_result.flags & SA_UIDVALIDITY &&
	   mm_status_result.flags & SA_UIDNEXT &&
	   mm_status_result.uidvalidity == rd->t.i.uidvalidity){

	    /*
	     * Uids are valid.
	     */

	    if(mm_status_result.uidnext == rd->t.i.uidnext){
		/*
		 * Uidnext valid and unchanged, so the folder is unchanged.
		 */
		dprint((7, "rd_check_remvalid: uidnexts match\n"));
		return;
	    }
	    else{	/* uidnext changed, folder _may_ have changed */

		dprint((7,
   "rd_check_remvalid: uidnexts don't match, ours=%lu status=%lu\n",
		   rd->t.i.uidnext, mm_status_result.uidnext));

		/*
		 * Since c-client can't handle a status cmd on the selected
		 * mailbox, we may have had to guess at the value of uidnext,
		 * and we don't know for sure that this is a real change.
		 * We need to open the mailbox and find out for sure.
		 */
		we_cancel = busy_cue(NULL, NULL, 1);
		ps_global->noshow_error = 1;
		if((rd->t.i.stream = context_open(NULL, NULL, rd->rn, openmode,
						 NULL)) != NULL){
		    imapuid_t last_msg_uid;

		    if(rd->t.i.stream->rdonly)
		      rd->read_status = 'R';

		    last_msg_uid = mail_uid(rd->t.i.stream,
					    rd->t.i.stream->nmsgs);
		    ps_global->noshow_error = 0;
		    rd->last_use = get_adj_time();
		    dprint((7,
			   "%s: opened to check uid (%ld)\n",
			   rd->rn ? rd->rn : "?", (long)rd->last_use));
		    if(last_msg_uid != rd->t.i.uid){	/* really did change */
			rd->flags |= REM_OUTOFDATE;
			dprint((2,
 "rd_check_remvalid: remote data %s changed, our uid=%lu real uid=%lu\n",
			       rd->rn ? rd->rn : "?",
			       rd->t.i.uid, last_msg_uid));
		    }
		    else{				/* false hit */
			/*
			 * The uid of the last message is the same as we
			 * remembered, so the problem is that our guess
			 * for the nextuid was wrong. It didn't actually
			 * change. Since we know the correct uidnext now we
			 * can reset that guess to the correct value for
			 * next time, avoiding this extra mail_open.
			 */
			dprint((2,
			       "rd_check_remvalid: remote data %s false change: adjusting uidnext from %lu to %lu\n",
			       rd->rn ? rd->rn : "?",
			       rd->t.i.uidnext,
			       mm_status_result.uidnext));
			rd->t.i.uidnext = mm_status_result.uidnext;
			rd_write_metadata(rd, 0);
		    }

		    if(we_cancel)
		      cancel_busy_cue(-1);

		    return;
		}
		else{
		    ps_global->noshow_error = 0;
		    dprint((2,
			   "rd_check_remvalid: couldn't open %s\n",
			   rd->rn ? rd->rn : "?"));
		}
	    }
	}
	else{
	    /*
	     * If the status command doesn't return these or
	     * if the uidvalidity is changing that probably means it can't
	     * be relied on to be meaningful, so don't use it.
	     *
	     * We also come here if we don't have a stat_stream handy to
	     * look up the status. This happens, for example, if our
	     * address book is on a different server from the open mail
	     * folders. In that case, instead of opening a stream,
	     * doing a status command, and closing the stream, we open
	     * the stream and use it to check next time, too.
	     */
	    if(stat_stream){
		rd->flags |= NO_STATUSCMD;
		dprint((7,
		  "rd_check_remvalid: remote data %s don't use status\n",
		   rd->rn ? rd->rn : "?"));
	    }

	    dprint((7,
		   "opening remote data stream for validity check\n"));
	    we_cancel = busy_cue(NULL, NULL, 1);
	    ps_global->noshow_error = 1;
	    rd->t.i.stream = context_open(NULL, NULL, rd->rn, openmode,
					  NULL);
	    ps_global->noshow_error = 0;
	    if(we_cancel)
	      cancel_busy_cue(-1);

	    we_cancel = 0;
	    if(rd->t.i.stream)
	      goto try_looking_in_stream;
	    else{
		dprint((7,
		  "rd_check_remvalid: cannot open remote mailbox\n"));
		return;
	    }
	}
    }

    /*
     * If we got here that means that we still don't know if the folder
     * changed or not. If the stream is open then it must be the case that
     * uidvalidity changed so we can't rely on using uids.  If the stream
     * isn't open, then either the status command didn't work or the
     * uidvalidity changed. In any case, we need to fall back to looking
     * inside the folder at the last message and checking whether or not the
     * Date of the last message is the one we remembered.
     */

    dprint((7,
	   "rd_check_remvalid: falling back to Date check\n"));

    /*
     * Fall back to looking in the folder at the Date header.
     */

    if(!rd->t.i.stream)
      we_cancel = busy_cue(NULL, NULL, 1);

    ps_global->noshow_error = 1;
    if(rd->t.i.stream ||
       (rd->t.i.stream = context_open(NULL,NULL,rd->rn,openmode,NULL))){
	ENVELOPE *env = NULL;

	if(rd->t.i.stream->rdonly)
	  rd->read_status = 'R';

	if(rd->t.i.stream->nmsgs != rd->t.i.chk_nmsgs){
	    rd->flags |= REM_OUTOFDATE;
	    dprint((2,
   "rd_check_remvalid: remote data %s changed (expected nmsgs %ld, got %ld)\n",
		   rd->rn ? rd->rn : "?",
		   rd->t.i.chk_nmsgs, rd->t.i.stream->nmsgs));
	}
	else if(rd->t.i.stream->nmsgs > 1){
	    env = pine_mail_fetchenvelope(rd->t.i.stream,rd->t.i.stream->nmsgs);
	
	    if(!env || (env->date && strucmp((char *) env->date, rd->t.i.chk_date))){
		rd->flags |= REM_OUTOFDATE;
		dprint((2,
		      "rd_check_remvalid: remote data %s changed (%s)\n",
		      rd->rn ? rd->rn : "?", env ? "date" : "not enough msgs"));
	    }
	}

	rd->last_use = get_adj_time();
	if(env)
	  dprint((7,
	         "%s: got envelope to check date (%ld)\n",
	         rd->rn ? rd->rn : "?", (long)rd->last_use));
    }
    /* else, we give up and go with the cache copy */

    ps_global->noshow_error = 0;

    if(we_cancel)
      cancel_busy_cue(-1);

    dprint((7, "rd_check_remvalid: falling off end\n"));
}


/*
 * Returns nonzero if remote data is currently readonly.
 *
 * Returns 0 -- apparently writeable
 *         1 -- stream not open
 *         2 -- stream open but not writeable
 */
int
rd_remote_is_readonly(REMDATA_S *rd)
{
    if(!rd || rd->access == ReadOnly || !rd_stream_exists(rd))
      return(1);
    
    switch(rd->type){
      case RemImap:
	if(rd->t.i.stream->rdonly)
	  return(2);
	
	break;

      default:
	q_status_message(SM_ORDER, 3, 5,
			 "rd_remote_is_readonly: type not supported");
	break;
    }

    return(0);
}


/*
 * Returns  0 if ok
 *         -1 if not ok and user says No
 *          1 if not ok but user says Yes, ok to use it
 */
int
rd_check_for_suspect_data(REMDATA_S *rd)
{
    int           ans = -1;
    char         *fields[3], *values[3], *h;
    unsigned long cookie;

    if(!rd || rd->type != RemImap || !rd->so || !rd->rn || !rd->t.i.special_hdr)
      return -1;

    fields[0] = rd->t.i.special_hdr;
    fields[1] = "received";
    fields[2] = NULL;
    cookie = 0L;
    if((h=pine_fetchheader_lines(rd->t.i.stream, rd->t.i.stream->nmsgs,
				NULL, fields)) != NULL){
	simple_header_parse(h, fields, values);
	if(values[1])				/* Received lines present! */
	  ans = rd_prompt_about_forged_remote_data(-1, rd, NULL);
	else if(values[0]){
	    cookie = strtoul(values[0], (char **)NULL, 10);
	    if(cookie == rd->cookie)		/* all's well */
	      ans = 0;
	    else
	      ans = rd_prompt_about_forged_remote_data(cookie > 1L
							  ? 100 : cookie,
						       rd, values[0]);
	}
	else
	  ans = rd_prompt_about_forged_remote_data(-2, rd, NULL);

	if(values[0])
	  fs_give((void **)&values[0]);

	if(values[1])
	  fs_give((void **)&values[1]);

	fs_give((void **)&h);
    }
    else					/* missing magic header */
      ans = rd_prompt_about_forged_remote_data(-2, rd, NULL);

    return ans;
}