summaryrefslogtreecommitdiff
path: root/pith/smime.c
blob: 8e65cfabefc0239b77abba974d3c4098b87758db (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
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
#if !defined(lint) && !defined(DOS)
static char rcsid[] = "$Id: smime.c 1176 2008-09-29 21:16:42Z hubert@u.washington.edu $";
#endif

/*
 * ========================================================================
 * Copyright 2013-2014 Eduardo Chappa
 * Copyright 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
 *
 * ========================================================================
 */

/*
 *  This is based on a contribution from Jonathan Paisley
 *
 *  File:   	    smime.c
 *  Author: 	    paisleyj@dcs.gla.ac.uk
 *  Date:   	    01/2001
 */


#include "../pith/headers.h"

#ifdef SMIME

#include "../pith/osdep/canaccess.h"
#include "../pith/helptext.h"
#include "../pith/store.h"
#include "../pith/status.h"
#include "../pith/detach.h"
#include "../pith/conf.h"
#include "../pith/smkeys.h"
#include "../pith/smime.h"
#include "../pith/mailpart.h"
#include "../pith/reply.h"
#include "../pith/tempfile.h"
#include "../pith/readfile.h"
#include "../pith/remote.h"

#include <openssl/buffer.h>
#include <openssl/x509v3.h>

/* internal prototypes */
static void            forget_private_keys(void);
static int             app_RAND_load_file(const char *file);
static void            openssl_extra_randomness(void);
static int             app_RAND_write_file(const char *file);
static const char     *openssl_error_string(void);
static int             load_private_key(PERSONAL_CERT *pcert);
static void            create_local_cache(char *h, char *base, BODY *b);
static long            rfc822_output_func(void *b, char *string);
static void            setup_pkcs7_body_for_signature(BODY *b, char *description,
						      char *type, char *filename);
static BIO            *body_to_bio(BODY *body);
static BIO            *bio_from_store(STORE_S *store);
static STORE_S        *get_part_contents(long msgno, const char *section);
static PKCS7         *get_pkcs7_from_part(long msgno, const char *section);
static int            do_signature_verify(PKCS7 *p7, BIO *in, BIO *out, int silent);
static int            do_detached_signature_verify(BODY *b, long msgno, char *section);
static PERSONAL_CERT *find_certificate_matching_pkcs7(PKCS7 *p7);
static int            do_decoding(BODY *b, long msgno, const char *section);
static void           free_smime_struct(SMIME_STUFF_S **smime);
static void           setup_storage_locations(void);
static int            copy_container_to_dir(WhichCerts which);
void		      setup_privatekey_storage(void);
int		      smime_path(char *rpath, char *fpath, size_t len);
int		      smime_extract_and_save_cert(PKCS7 *p7);
int		      same_cert(X509 *, X509 *);
CertList *	      certlist_from_personal_certs(PERSONAL_CERT *pc);
#ifdef PASSFILE
void		      load_key_and_cert(char *pathdir, char **keyfile, char **certfile, EVP_PKEY **pkey, X509 **pcert);
#endif /* PASSFILE */
STACK_OF(X509)	     *get_chain_for_cert(X509 *cert, int *error);
EVP_PKEY 	     *load_pkey_with_prompt(char *fpath, char *text, char *prompt);

int  (*pith_opt_smime_get_passphrase)(void);
int  (*pith_smime_import_certificate)(char *, char *, size_t);
int  (*pith_smime_enter_password)(char *prompt, char *, size_t);

static X509_STORE   *s_cert_store;

/* State management for randomness functions below */
static int seeded = 0;
static int egdsocket = 0;


#ifdef PASSFILE
void
load_key_and_cert(char *pathdir, char **keyfile, 
		char **certfile, EVP_PKEY **pkey, X509 **pcert)
{
   BIO *in;
   char buf[MAXPATH+1], pathkey[MAXPATH+1], prompt[MAILTMPLEN];
   DIR *dirp;
   struct dirent *d;

   if(keyfile) *keyfile = NULL;
   if(certfile) *certfile = NULL;
   if(pkey) *pkey = NULL;
   if(pcert) *pcert = NULL;

   if(pathdir == NULL) return;

   if((dirp = opendir(pathdir)) != NULL){
      while((d=readdir(dirp)) != NULL){
	size_t ll;

        if((ll=strlen(d->d_name)) && ll > 4){
	   if(pkey && *pkey == NULL && keyfile && !strcmp(d->d_name+ll-4, ".key")){
              strncpy(buf, d->d_name, sizeof(buf));
              buf[sizeof(buf)-1] = '\0';
	      build_path(pathkey, pathdir, buf, sizeof(pathkey));
	      buf[strlen(buf)-4] = '\0';
	      snprintf(prompt, sizeof(prompt),
		_("Enter password of key <%s> to unlock password file: "), buf);
	      if((*pkey = load_pkey_with_prompt(pathkey, NULL, prompt)) != NULL)
		*keyfile = cpystr(buf);
	   }

	   if(pcert && *pcert == NULL && certfile && !strcmp(d->d_name+ll-4, ".crt")){
              strncpy(buf, d->d_name, sizeof(buf));
              buf[sizeof(buf)-1] = '\0';
	      build_path(pathkey, pathdir, buf, sizeof(pathkey));
	      if((in = BIO_new_file(pathkey, "r")) != NULL){
		 if((*pcert = PEM_read_bio_X509(in, NULL, NULL, NULL)) != NULL)
		    *certfile = cpystr(buf);
		 else{
		    q_status_message1(SM_ORDER, 0, 2,
                      _("loading public certificate %s failed. Continuing..."), buf);
		 }
		 BIO_free(in);
	      }
	   }
	}
      }
   }
}


/* setup a key and certificate to encrypt and decrypt a password file. 
 * These files will be saved in the .alpine-smime/.pwd directory, but its
 * location can be setup in the command line with the -pwdcertdir option.
 * Here are the rules:
 *
 *  Check if the .alpine-smime/.pwd (or -pwdcertdir directory) exists, 
 *  if not create it. If we are successful, move to the next step
 *
 *  - If the user has a key/cert pair, setup is successful;
 *  - if the used does not have a key/cert pair, or one cannot be found
 *    create one, setup is successful; (TODO: implement this)
 *  - in any other case, setup is not successful.
 *
 *  If setup is successful, setup ps_global->smime->pwdcert.
 *  If any of this fails, ps_global->smime->pwdcert will be null.
 *  Ok, that should do it.
 */
void
setup_pwdcert(void **pwdcert)
{
  int setup_dir = 0;	/* make it non zero if we know which dir to use */
  int i,j,k;
  struct stat sbuf;
  char pathdir[MAXPATH+1], pathkey[MAXPATH+1], fpath[MAXPATH+1];
  char prompt[MAILTMPLEN], buf[MAXPATH+1];
  char *keyfile, *certfile, *text;
  DIR *dirp;
  struct dirent *d;
  EVP_PKEY *pkey = NULL;
  X509 *pcert = NULL;
  BIO *in = NULL;
  PERSONAL_CERT *pc, *pc2 = NULL;

  smime_init();

  if(ps_global->pwdcertdir){
     if(our_stat(ps_global->pwdcertdir, &sbuf) == 0
	&& ((sbuf.st_mode & S_IFMT) == S_IFDIR)){
	setup_dir++;
	strncpy(pathdir, ps_global->pwdcertdir, sizeof(pathdir));
	pathdir[sizeof(pathdir)-1] = '\0';
     }
  } else {
      smime_path(DF_PASSWORD_DIR, pathdir, sizeof(pathdir));
      if(our_stat(pathdir, &sbuf) == 0){
	if((sbuf.st_mode & S_IFMT) == S_IFDIR)
	  setup_dir++;
      } else {
	if(can_access(pathdir, ACCESS_EXISTS) != 0
	    && our_mkpath(pathdir, 0700) == 0)
	  setup_dir++;
      }
  }

  if(setup_dir == 0)
    return;

  /* reuse setup dir to mean setup_key */
  setup_dir = 0;

  /* BUG: add container support */
  load_key_and_cert(pathdir, &keyfile, &certfile, &pkey, &pcert);

  if(certfile && keyfile)
    setup_dir++;

  if(setup_dir == 0){
     if(keyfile == NULL){
	/* PATHCERTDIR(Private) must be null, so create a path */
	set_current_val(&ps_global->vars[V_PRIVATEKEY_DIR], TRUE, TRUE);
	smime_path(ps_global->VAR_PRIVATEKEY_DIR, pathkey, MAXPATH);
	load_key_and_cert(pathkey, &keyfile, NULL, &pkey, NULL);
     }
     if(certfile == NULL){
	/* PATHCERTDIR(Public) must be null, so create a path */
	set_current_val(&ps_global->vars[V_PUBLICCERT_DIR], TRUE, TRUE);
	smime_path(ps_global->VAR_PUBLICCERT_DIR, pathkey, MAXPATH);
	load_key_and_cert(pathkey, NULL, &certfile, NULL, &pcert);
     }
     smime_reinit();
     if(certfile && keyfile){
	build_path(fpath, pathdir, keyfile, sizeof(fpath));
	strncat(fpath, ".key", 4);
	fpath[sizeof(fpath)-1] = '\0';

	smime_path(ps_global->VAR_PRIVATEKEY_DIR, pathkey, MAXPATH);
	strncat(pathkey, "/", 1);
	strncat(pathkey, keyfile, strlen(keyfile));
	strncat(pathkey, ".key", 4);
	pathkey[sizeof(pathkey)-1] = '\0';

	if(our_copy(fpath, pathkey) == 0)
	   setup_dir++;

	if(setup_dir){
	  setup_dir = 0;

	  build_path(fpath, pathdir, certfile, sizeof(fpath));

	  smime_path(ps_global->VAR_PUBLICCERT_DIR, pathkey, MAXPATH);
	  strncat(pathkey, "/", 1);
	  strncat(pathkey, keyfile, strlen(keyfile));
	  strncat(pathkey, ".crt", 4);
	  pathkey[sizeof(pathkey)-1] = '\0';

	  if(our_copy(fpath, pathkey) == 0)
	     setup_dir++;
	}
     }
  }

  if(setup_dir > 0){
     pc2 = (PERSONAL_CERT *) fs_get(sizeof(PERSONAL_CERT));
     memset((void *)pc2, 0, sizeof(PERSONAL_CERT));
     pc2->name = keyfile;
     pc2->key  = pkey;
     pc2->cert = pcert;
     if(pwdcert) *pwdcert = (void *) pc2;
  }

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

  if(setup_dir == 0){	/* try looking for an existent key */
    if(ps_global->smime->personal_certs){
      pc = (PERSONAL_CERT *) ps_global->smime->personal_certs;
      if(ps_global->smime->privatetype == Directory){
	 build_path(pathkey, ps_global->smime->privatepath, pc->name, sizeof(pathkey));
	 strncat(pathkey, ".key", 4);
	 pathkey[sizeof(pathkey)-1] = '\0';
	 text = NULL;
      } else { 		/* ps_global->smime->privatetype == Container */
	 if(pc->keytext == NULL){	/* we should *never* be here, but just in case */
	   if(ps_global->smime->privatecontent != NULL){
	     char tmp[MAILTMPLEN], *s, *t, c;
	     snprintf(tmp, sizeof(tmp), "%s%s", EMAILADDRLEADER, pc->name);
	     tmp[sizeof(tmp)-1] = '\0';
	     if((s = strstr(ps_global->smime->privatecontent, tmp)) != NULL){
		if((t = strstr(s+strlen(tmp), EMAILADDRLEADER)) != NULL){
		   c = *t;
		   *t = '\0';
		   pc->keytext = cpystr(s + strlen(tmp) + 1); /* 1 = strlen("\n") */
		   *t = c;
	        }
		else
		   pc->keytext = cpystr(s + strlen(tmp) + 1); /* 1 = strlen("\n") */
	     }
	   }
	 }
	 if(pc->keytext != NULL)	/* we should go straigth here */
	   text = pc->keytext;
      }
      if((pathkey && *pathkey) || text){
	snprintf(prompt, sizeof(prompt),
          _("Enter password of key <%s> to unlock password file: "), pc->name);

	 if((pkey = load_pkey_with_prompt(pathkey, text, prompt)) != NULL){
	   pc2 = (PERSONAL_CERT *) fs_get(sizeof(PERSONAL_CERT));
	   memset((void *)pc2, 0, sizeof(PERSONAL_CERT));
	   pc2->name = cpystr(pc->name);
	   pc2->key  = pkey;
	   pc2->cert = X509_dup(pc->cert);

	   /* now copy the keys and certs, starting by the key...  */
	   build_path(fpath, pathdir, pc->name, sizeof(fpath));
	   strncat(fpath, ".key", 4);
	   fpath[sizeof(fpath)-1] = '\0';
	   if(our_stat(fpath, &sbuf) == 0){
	     if((sbuf.st_mode & S_IFMT) == S_IFREG)
	       setup_dir++;
	   }
	   else { if(ps_global->smime->privatetype == Directory){
		     if(our_copy(fpath, pathkey) == 0)
		        setup_dir++;
		} else {   /* ps_global->smime->privatetype == Container */
		     BIO *out;
		     if((out = BIO_new_file(fpath, "w")) != NULL){
			if(BIO_puts(out, pc->keytext) > 0)
			   setup_dir++;
		        BIO_free(out);
		     }
	        }
	   }

	   /* successful copy of key, now continue with certificate */
	   if(setup_dir){
	      setup_dir = 0;

	      build_path(pathkey, ps_global->smime->publicpath, pc->name, sizeof(pathkey));
	      strncat(pathkey, ".crt", 4);
	      pathkey[sizeof(pathkey)-1] = '\0';

	      build_path(fpath, pathdir, pc->name, sizeof(fpath));
	      strncat(fpath, ".crt", 4);
	      fpath[sizeof(fpath)-1] = '\0';

	      if(our_stat(fpath, &sbuf) == 0){
		if((sbuf.st_mode & S_IFMT) == S_IFREG)
		  setup_dir++;
	      }
	      else{ if(ps_global->smime->privatetype == Directory){
		       if(our_copy(fpath, pathkey) == 0)
			 setup_dir++;
		    } else { /* ps_global->smime->privatetype == Container */
			BIO *out;
			if((out = BIO_new_file(fpath, "w")) != NULL){
			   if(PEM_write_bio_X509(out, pc->cert))
			     setup_dir++;
			   BIO_free(out);
			}
		    }
	      }
	   }		

	   if(setup_dir)
	     if(pwdcert) *pwdcert = (void *) pc2;
	   else{
	     free_personal_certs(&pc2);
	     return;
	   }
	 }			/* end of if(pkey != NULL) */
	 BIO_free(in);
      } 			/* end of if(in != NULL) */
    } 				/* end of if(ps_global->personal_certs) */
  }

  /* TODO: create self signed certificate */
  if(setup_dir == 0)
     q_status_message(SM_ORDER, 0, 2,
	   _("No key/certificate pair found. Password file not encrypted!"));
}
#endif /* PASSFILE */

/* smime_expunge_cert.
 * Return values: < 0 there was an error.
 *                >=0 the number of messages expunged
 */
int
smime_expunge_cert(WhichCerts ctype)
{
  int count, removed; 
  CertList *cl, *dummy, *data;
  char *path, *ext, buf[MAXPATH+1];
  char *contents;

  if(DATACERT(ctype)== NULL)
    return -1;

  /* data cert is the way we unify certificate management across functions, but it is
   * not where we really save the information in the case ctype is equal to Private.
   * What we will do is to update the datacert, and in the case of ctype equal to Private
   * use the updated certdata to update the personal_certs data.
   */

  path = PATHCERTDIR(ctype);
  ext  = EXTCERT(ctype);

  if(path){
    /* add a fake certificate at the beginning of the list */
    dummy = fs_get(sizeof(CertList));
    memset((void *)dummy, 0, sizeof(CertList));
    dummy->next = DATACERT(ctype);

    for(cl = dummy, count = 0; cl && cl->next;){
	if(cl->next->data.deleted == 0){
	   cl = cl->next;
	   continue;
	}

	removed = 1;		/* assume success */
	if(SMHOLDERTYPE(ctype) == Directory){
	  build_path(buf, path, cl->next->name, sizeof(buf));
	  if(ctype == Private && strlen(buf) + strlen(EXTCERT(Private)) < sizeof(buf))
	    strcat(buf, EXTCERT(Private));

	  if(our_unlink(buf) < 0){
	     q_status_message1(SM_ORDER, 3, 3, _("Error removing certificate %s"), cl->next->name);
	     cl = cl->next;
	     removed = 0;
	  }
	}
	else {	/* SMHOLDERTYPE(ctype) == Container */
	  char *prefix= ctype == CACert ? CACERTSTORELEADER : EMAILADDRLEADER;
	  char tmp[MAILTMPLEN], *s, *t;

	  contents = CONTENTCERTLIST(ctype);
	  snprintf(tmp, sizeof(tmp), "%s%s", prefix, cl->next->name);
	  tmp[sizeof(tmp) - 1] = '\0';
	  if((s = strstr(contents, tmp)) != NULL){
	     if((t = strstr(s+strlen(tmp), prefix)) == NULL)
		*s = '\0';
	     else
		memmove(s, t, strlen(t)+1);
	     fs_resize((void **)&contents, strlen(contents)+1);
	     switch(ctype){
		case Private: ps_global->smime->privatecontent = contents; break;
		case Public : ps_global->smime->publiccontent = contents; break;
		case CACert : ps_global->smime->cacontent = contents; break;
		default  : break;
	     }
	  }
	  else
	     removed = 0;
	}

 	if(removed > 0){
	   count++;	/* count it! */
	   data = cl->next;
	   cl->next = data->next;
	   if(data->name) fs_give((void **)&data->name);
	   fs_give((void **)&data);
	}
    }
  } else
	q_status_message(SM_ORDER, 3, 3, _("Error expunging certificate"));

  switch(ctype){
     case Private: ps_global->smime->privatecertlist = dummy->next; break;
     case Public : ps_global->smime->publiccertlist = dummy->next; break;
     case CACert : ps_global->smime->cacertlist = dummy->next; break;
	default  : break;
  }
  fs_give((void **)&dummy);
  if(SMHOLDERTYPE(ctype) == Container){
    if(copy_dir_to_container(ctype, contents) < 0) 
      count = 0;
  }
  if(count > 0){
    q_status_message2(SM_ORDER, 3, 3, _("Removed %s certificate%s"), comatose(count), plural(count));
  }
  else
    q_status_message(SM_ORDER, 3, 3, _("Error: No certificates were removed"));
  return count;
}

void
mark_cert_deleted(WhichCerts ctype, int num, unsigned state)
{
  CertList *cl;
  int i;

  for(cl = DATACERT(ctype), i = 0; cl != NULL && i < num; cl = cl->next, i++);
  cl->data.deleted = state;
}

unsigned
get_cert_deleted(WhichCerts ctype, int num)
{
  CertList *cl;
  int i;

  for(cl = DATACERT(ctype), i = 0; cl != NULL && i < num; cl = cl->next, i++);
  return (cl && cl->data.deleted) ? 1 : 0;
}

EVP_PKEY *
load_pkey_with_prompt(char *fpath, char *text, char *prompt)
{
  EVP_PKEY *pkey;
  int rc = 0;   /* rc == 1, cancel, rc == 0 success */
  int we_clear = 0;
  char pass[MAILTMPLEN+1];
  BIO *in;

  /* attempt to load with empty password */
  in = text ? BIO_new_mem_buf(text, strlen(text)) : BIO_new_file(fpath, "r");
  if(in != NULL){
     pkey = PEM_read_bio_PrivateKey(in, NULL, NULL, "");
     BIO_free(in);
     if(pkey != NULL) return pkey;
  }

  if(pith_smime_enter_password)
    while(pkey == NULL && rc != 1){
       in = text ? BIO_new_mem_buf(text, strlen(text)) : BIO_new_file(fpath, "r");
       if(in != NULL){
	 do {
	   rc = (*pith_smime_enter_password)(prompt, (char *)pass, sizeof(pass));
	 } while (rc!=0 && rc!=1 && rc>0);

	 pkey = PEM_read_bio_PrivateKey(in, NULL, NULL, (char *)pass);
	 BIO_free(in);
       }
       else rc = 1;
    }

  return pkey;
}



int
import_certificate(WhichCerts ctype)
{
   int   r = 1, rc; 
   char  filename[MAXPATH+1], full_filename[MAXPATH+1], buf[MAXPATH+1];

   if(pith_smime_import_certificate == NULL){
     q_status_message(SM_ORDER, 0, 2,
                      _("import of certificates not implemented yet!"));
     return -1;     
  }

   smime_init();

   r = (*pith_smime_import_certificate)(filename, full_filename, sizeof(filename) - 20);

   ps_global->mangled_screen = 1;

   if(r < 0)
     return r;
   else if (ctype == Private){
	char prompt[500], *s, *t;
	BIO *in;
	EVP_PKEY *key = NULL;
	PERSONAL_CERT *pc;

	if(!ps_global->smime->privatecertlist){
	  ps_global->smime->privatecertlist = fs_get(sizeof(CertList));
	  memset((void *)DATACERT(ctype), 0, sizeof(CertList));
	}

	for(s = t = filename; (t = strstr(s, ".key")) != NULL; s = t + 1);
	if(s) *(s-1) = 0;

	snprintf(prompt, sizeof(prompt), _("Enter passphrase for <%s>: "), filename);
        if((key = load_pkey_with_prompt(full_filename, NULL, prompt)) != NULL){
	  if(SMHOLDERTYPE(ctype) == Directory){
	    build_path(buf, PATHCERTDIR(ctype), filename, sizeof(buf));
	    if(strcmp(buf + strlen(buf) - 4, EXTCERT(ctype)) != 0 && strlen(buf) + 4 < sizeof(buf))
	       strcat(buf, EXTCERT(ctype));
	    rc = our_copy(buf, full_filename);
	  }
	  else /* if(SMHOLDERTYPE(ctype) == Container){ */
	     rc = add_file_to_container(ctype, full_filename, NULL);
	  if(rc == 0)
	     q_status_message(SM_ORDER, 1, 3, _("Private key saved"));
	  else
	     q_status_message(SM_ORDER, 1, 3, _("Error saving private key"));
	  if(ps_global->smime->publiccertlist)
	     ps_global->smime->publiccertlist->data.renew = 1;
	}
	else
	  q_status_message(SM_ORDER, 1, 3, _("Problem unlocking key (not a certificate and/or wrong password)"));
   } else  if (ctype == CACert){
      BIO *ins;
      X509 *cert;

      if((ins = BIO_new_file(full_filename, "r")) != NULL){
	if((cert = PEM_read_bio_X509(ins, NULL, NULL, NULL)) != NULL){
	  if(SMHOLDERTYPE(ctype) == Directory){
	    build_path(buf, PATHCERTDIR(ctype), filename, sizeof(buf));
	    if(strcmp(buf + strlen(buf) - 4, ".crt") != 0 && strlen(buf) + 4 < sizeof(buf))
	       strcat(buf, EXTCERT(ctype));

	    rc = our_copy(buf, full_filename);
	  }
	  else /* if(SMHOLDERTYPE(ctype) == Container){ */
	     rc = add_file_to_container(ctype, full_filename, NULL);
	  if(rc == 0)
	      q_status_message(SM_ORDER, 1, 3, _("Certificate saved"));
	  else
	      q_status_message(SM_ORDER, 1, 3, _("Error saving certificate"));
	  X509_free(cert);	/* not needed anymore */
	}
	else
	  q_status_message(SM_ORDER, 1, 3, _("Error in certificate file (not a certificate?)"));
	BIO_free(ins);
      }
      renew_store();
   } else { /* ctype == Public. save certificate, but first validate that it is one */
      BIO *ins;
      X509 *cert;

      if((ins = BIO_new_file(full_filename, "r")) != NULL){
	if((cert = PEM_read_bio_X509(ins, NULL, NULL, NULL)) != NULL){
	  if(SMHOLDERTYPE(ctype) == Directory){
	    char **email = get_x509_subject_email(cert);
	    int i;

	    for(i = 0; email[i] != NULL; i++){
	       save_cert_for(email[i], cert, Public);
	       fs_give((void **)&email[i]);
	    }
	    fs_give((void **)email);
	  }
	  else  /* if(SMHOLDERTYPE(ctype) == Container){ */
	     add_file_to_container(ctype, full_filename, NULL);
	  X509_free(cert);
	  if(ps_global->smime->publiccertlist)
	     ps_global->smime->publiccertlist->data.renew = 1;
	}
	else
	  q_status_message(SM_ORDER, 1, 3, _("Error in certificate file (not a certificate?)"));
	BIO_free(ins);
      }
   }
   if(DATACERT(ctype)) RENEWCERT(DATACERT(ctype)) = 1;
   return 0;
}

/* itype: information type to add: 0 - public, 1 - private.
 * Memory freed by caller
 */
BIO *
print_private_key_information(char *email, int itype)
{
  BIO *out;
  PERSONAL_CERT *pc;

  if(ps_global->smime == NULL 
	|| ps_global->smime->personal_certs == NULL 
	|| (itype != 0 && itype != 1))
    return NULL;

  for(pc = ps_global->smime->personal_certs;
        pc != NULL && strcmp(pc->name, email) != 0; pc = pc->next);
  if(pc->key == NULL
	&& !load_private_key(pc)
	&& ps_global->smime
	&& ps_global->smime->need_passphrase){
	if (*pith_opt_smime_get_passphrase)
	   (*pith_opt_smime_get_passphrase)();
	load_private_key(pc);
  }

  if(pc->key == NULL)
     return NULL;

  out = BIO_new(BIO_s_mem());
  if(itype == 0)		/* 0 means public */
    EVP_PKEY_print_public(out, pc->key, 0, NULL);
  else if (itype == 1)		/* 1 means private */
    EVP_PKEY_print_private(out, pc->key, 0, NULL);

  if(F_OFF(F_REMEMBER_SMIME_PASSPHRASE,ps_global))
    forget_private_keys();

  return out;
}

/*
 * Forget any cached private keys
 */
static void
forget_private_keys(void)
{
    PERSONAL_CERT *pcert;
    size_t len;
    volatile char *p;
    
    dprint((9, "forget_private_keys()"));
    if(ps_global->smime){
	for(pcert=(PERSONAL_CERT *) ps_global->smime->personal_certs;
	    pcert;
	    pcert=pcert->next){

	    if(pcert->key){
		EVP_PKEY_free(pcert->key);
		pcert->key = NULL;
	    }
	}

	ps_global->smime->entered_passphrase = 0;
	len = sizeof(ps_global->smime->passphrase);
	p = ps_global->smime->passphrase;

	while(len-- > 0)
	  *p++ = '\0';
    }
}

/* modelled after signature_path in reply.c, but uses home dir instead of the
 * directory where the .pinerc is located, since according to documentation,
 * the .alpine-smime directories are subdirectories of the home directory
 */
int smime_path(char *rpath, char *fpath, size_t len)
{
    *fpath = '\0';
    if(rpath && *rpath){
        size_t spl = strlen(rpath);

        if(IS_REMOTE(rpath)){
            if(spl < len - 1)
              strncpy(fpath, rpath, len-1);
            fpath[len-1] = '\0';
        }
        else if(is_absolute_path(rpath)){
            strncpy(fpath, rpath, len-1);
            fpath[len-1] = '\0';
            fnexpand(fpath, len);
        }
        else if(ps_global->VAR_OPER_DIR){
            if(strlen(ps_global->VAR_OPER_DIR) + spl < len - 1)
              build_path(fpath, ps_global->VAR_OPER_DIR, rpath, len);
        }
	else if(ps_global->home_dir){
            if(strlen(ps_global->home_dir) + spl < len - 1)
              build_path(fpath, ps_global->home_dir, rpath, len);
	}
    }
    return fpath && *fpath ? 1 : 0;
}



/*
 * taken from openssl/apps/app_rand.c
 */
static int
app_RAND_load_file(const char *file)
{
    char buffer[200];

    if(file == NULL)
      file = RAND_file_name(buffer, sizeof buffer);
    else if(RAND_egd(file) > 0){
	/* we try if the given filename is an EGD socket.
	   if it is, we don't write anything back to the file. */
	egdsocket = 1;
	return 1;
    }

    if(file == NULL || !RAND_load_file(file, -1)){
	if(RAND_status() == 0){
	    dprint((1, "unable to load 'random state'\n"));
	    dprint((1, "This means that the random number generator has not been seeded\n"));
	    dprint((1, "with much random data.\n"));
	}

	return 0;
    }

    seeded = 1;
    return 1;
}


/*
 * copied and fiddled from imap/src/osdep/unix/auth_ssl.c
 */
static void
openssl_extra_randomness(void)
{
#if !defined(WIN32)
    int fd;
    unsigned long i;
    char *tf = NULL;
    char tmp[MAXPATH];
    struct stat sbuf;
				/* if system doesn't have /dev/urandom */
    if(stat ("/dev/urandom", &sbuf)){
      tmp[0] = '0';
      tf = temp_nam(NULL, NULL);
      if(tf){
	strncpy(tmp, tf, sizeof(tmp));
	tmp[sizeof(tmp)-1] = '\0';
	fs_give((void **) &tf);
      }     

      if((fd = open(tmp, O_WRONLY|O_CREAT|O_EXCL, 0600)) < 0)
	i = (unsigned long) tmp;
      else{
	unlink(tmp);		/* don't need the file */
	fstat(fd, &sbuf);	/* get information about the file */
	i = sbuf.st_ino;	/* remember its inode */
	close(fd);		/* or its descriptor */
      }
				/* not great but it'll have to do */
      snprintf(tmp+strlen(tmp), sizeof(tmp)-strlen(tmp), "%.80s%lx%lx%lx",
	       tcp_serverhost (),i,
	       (unsigned long) (time (0) ^ gethostid ()),
	       (unsigned long) getpid ());
      RAND_seed(tmp, strlen(tmp));
    }
#endif
}


/* taken from openssl/apps/app_rand.c */
static int
app_RAND_write_file(const char *file)
{
    char buffer[200];

    if(egdsocket || !seeded)
	/*
	 * If we did not manage to read the seed file,
	 * we should not write a low-entropy seed file back --
	 * it would suppress a crucial warning the next time
	 * we want to use it.
	 */
	return 0;

    if(file == NULL)
      file = RAND_file_name(buffer, sizeof buffer);

    if(file == NULL || !RAND_write_file(file)){
	dprint((1, "unable to write 'random state'\n"));
	return 0;
    }

    return 1;
}

CertList *
certlist_from_personal_certs(PERSONAL_CERT *pc)
{
   CertList *cl;

   if(pc == NULL)
     return NULL;

   cl = fs_get(sizeof(CertList));
   memset((void *)cl, 0, sizeof(CertList));
   cl->name = cpystr(pc->name);
   cl->next = certlist_from_personal_certs(pc->next);

   return cl;
}


void
renew_cert_data(CertList **data, WhichCerts ctype)
{
  smime_init();
  if(ctype == Private){
     if(data){
	PERSONAL_CERT *pc = (PERSONAL_CERT *)ps_global->smime->personal_certs;
	if(*data)
	  free_certlist(data);
	free_personal_certs(&pc);
	setup_privatekey_storage();
        *data = certlist_from_personal_certs((PERSONAL_CERT *)ps_global->smime->personal_certs);
	if(data && *data)
	    RENEWCERT(*data) = 0;
        ps_global->smime->privatecertlist = *data;
     }
     if(ps_global->smime->privatecertlist)
       RENEWCERT(ps_global->smime->privatecertlist) = 0;
  } else {
    X509_LOOKUP    *lookup = NULL;
    X509_STORE     *store = NULL;

    if((store = X509_STORE_new()) != NULL)
       if((lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file())) == NULL){
          X509_STORE_free(store);
          store = NULL;
       }
    else{
       free_certlist(data);
       if(SMHOLDERTYPE(ctype) == Directory)
           add_certs_in_dir(lookup, PATHCERTDIR(ctype), EXTCERT(ctype), data);
       else /* if(SMHOLDERTYPE(ctype) == Container) */
	  *data = mem_to_certlist(CONTENTCERTLIST(ctype), ctype);
       if(data && *data)
	 RENEWCERT(*data) = 0;
       if(ctype == Public)
         ps_global->smime->publiccertlist = *data;
       else
         ps_global->smime->cacertlist = *data;
    }
  }
}

void
smime_reinit(void)
{
   smime_deinit();
   smime_init();
}

/* Installed as an atexit() handler to save the random data */
void
smime_deinit(void)
{
    dprint((9, "smime_deinit()"));
    app_RAND_write_file(NULL);
    free_smime_struct(&ps_global->smime);
}

/* we renew the store when it has changed */
void renew_store(void)
{
    if(ps_global->smime->inited){
       if(s_cert_store != NULL)
	 X509_STORE_free(s_cert_store);
	s_cert_store = get_ca_store();
    }
}

/* Initialise openssl stuff if needed */
void
smime_init(void)
{
    if(F_OFF(F_DONT_DO_SMIME, ps_global) && !(ps_global->smime && ps_global->smime->inited)){

	dprint((9, "smime_init()"));
	if(!ps_global->smime)
	  ps_global->smime = new_smime_struct();

	setup_storage_locations();

	s_cert_store = get_ca_store();

        OpenSSL_add_all_algorithms();
        ERR_load_crypto_strings();

	app_RAND_load_file(NULL);
    	openssl_extra_randomness();
	ps_global->smime->inited = 1;
    }
    
    ERR_clear_error();
}


/* validate a certificate. Return value : 0 for no error, -1 for error.
 * In the latter case, set the openssl smime error in *error.
 */
int smime_validate_cert(X509 *cert, long *error)
{
   X509_STORE_CTX *csc;

   ERR_clear_error();
   *error = 0;
   if((csc = X509_STORE_CTX_new()) != NULL){
     X509_STORE_set_flags(s_cert_store, 0);
     if(X509_STORE_CTX_init(csc,s_cert_store,cert,NULL)
	&& X509_verify_cert(csc) <= 0)
	*error   = X509_STORE_CTX_get_error(csc);
     X509_STORE_CTX_free(csc);
   }
   return *error ? -1 : 0;
}

PERSONAL_CERT *
get_personal_certs(char *path)
{
    PERSONAL_CERT *result = NULL;
    char buf2[MAXPATH];
    struct dirent *d;
    DIR *dirp;

    ps_global->smime->privatepath = cpystr(path);
    dirp = opendir(path);
    if(dirp){
	while((d=readdir(dirp)) != NULL){
	    X509 *cert;
	    size_t ll;

	    if((ll=strlen(d->d_name)) && ll > 4 && !strcmp(d->d_name+ll-4, ".key")){

		/* copy file name to temp buffer */
		strncpy(buf2, d->d_name, sizeof(buf2)-1);
		buf2[sizeof(buf2)-1] = '\0';
		/* chop off ".key" trailier */
		buf2[strlen(buf2)-4] = 0;
		/* Look for certificate */
		cert = get_cert_for(buf2, Public);

		if(cert){
		    PERSONAL_CERT *pc;

		    /* create a new PERSONAL_CERT, fill it in */

		    pc = (PERSONAL_CERT *) fs_get(sizeof(*pc));
		    pc->cert = cert;
		    pc->name = cpystr(buf2);

		    /* Try to load the key with an empty password */
		    pc->key = load_key(pc, "");

		    pc->next = result;
		    result = pc;
		}
	    }
	}
	closedir(dirp);
    }
    return result;
}


void
setup_privatekey_storage(void)
{
    char path[MAXPATH+1], *contents;
    int privatekeycontainer = 0;

    /* private keys in a container */
    if(ps_global->VAR_PRIVATEKEY_CONTAINER && ps_global->VAR_PRIVATEKEY_CONTAINER[0]){

	privatekeycontainer = 1;
	contents = NULL;
	path[0] = '\0';
	if(!smime_path(ps_global->VAR_PRIVATEKEY_CONTAINER, path, MAXPATH))
	  privatekeycontainer = 0;

	if(privatekeycontainer && !IS_REMOTE(path)
	   && ps_global->VAR_OPER_DIR
           && !in_dir(ps_global->VAR_OPER_DIR, path)){
	    q_status_message2(SM_ORDER | SM_DING, 3, 4,
			  /* TRANSLATORS: First arg is the directory name, second is
			     the file user wants to read but can't. */
			  _("Can't read file outside %s: %s"),
			  ps_global->VAR_OPER_DIR, path);
	    privatekeycontainer = 0;
	}

	if(privatekeycontainer
	   && (IS_REMOTE(path) || can_access(path, ACCESS_EXISTS) == 0)){
	    if(!(IS_REMOTE(path) && (contents = simple_read_remote_file(path, REMOTE_SMIME_SUBTYPE)))
	       &&
	       !(contents = read_file(path, READ_FROM_LOCALE)))
	      privatekeycontainer = 0;
	}

	if(privatekeycontainer && path[0]){
	    ps_global->smime->privatetype = Container;
	    ps_global->smime->privatepath = cpystr(path);

	    if(contents){
		ps_global->smime->privatecontent = contents;
		ps_global->smime->personal_certs = mem_to_personal_certs(contents);
	    }
	}
    }

    /* private keys in a directory of files */
    if(!privatekeycontainer){
	PERSONAL_CERT *result = NULL;

	ps_global->smime->privatetype = Directory;

	path[0] = '\0';
	if(!(smime_path(ps_global->VAR_PRIVATEKEY_DIR, path, MAXPATH)
	     && !IS_REMOTE(path)))
	  ps_global->smime->privatetype = Nada;
	else if(can_access(path, ACCESS_EXISTS)){
	    if(our_mkpath(path, 0700)){
		q_status_message1(SM_ORDER, 3, 3, _("Can't create directory %s"), path);
		ps_global->smime->privatetype = Nada;
	    }
	}

	if(ps_global->smime->privatetype == Directory)
	   ps_global->smime->personal_certs = get_personal_certs(path);
    }
}



static void
setup_storage_locations(void)
{
    int publiccertcontainer = 0, cacertcontainer = 0;
    char path[MAXPATH+1], *contents;

    if(!ps_global->smime)
      return;

#ifdef APPLEKEYCHAIN
    if(F_ON(F_PUBLICCERTS_IN_KEYCHAIN, ps_global)){
	ps_global->smime->publictype = Keychain;
    }
    else{
#endif /* APPLEKEYCHAIN */
    /* Public certificates in a container */
    if(ps_global->VAR_PUBLICCERT_CONTAINER && ps_global->VAR_PUBLICCERT_CONTAINER[0]){

	publiccertcontainer = 1;
	contents = NULL;
	path[0] = '\0';
	if(!smime_path(ps_global->VAR_PUBLICCERT_CONTAINER, path, MAXPATH))
	  publiccertcontainer = 0;

	if(publiccertcontainer && !IS_REMOTE(path)
	   && ps_global->VAR_OPER_DIR
           && !in_dir(ps_global->VAR_OPER_DIR, path)){
	    q_status_message2(SM_ORDER | SM_DING, 3, 4,
			  /* TRANSLATORS: First arg is the directory name, second is
			     the file user wants to read but can't. */
			  _("Can't read file outside %s: %s"),
			  ps_global->VAR_OPER_DIR, path);
	    publiccertcontainer = 0;
	}

	if(publiccertcontainer
	   && (IS_REMOTE(path) || can_access(path, ACCESS_EXISTS) == 0)){
	    if(!(IS_REMOTE(path) && (contents = simple_read_remote_file(path, REMOTE_SMIME_SUBTYPE)))
	       &&
	       !(contents = read_file(path, READ_FROM_LOCALE)))
	      publiccertcontainer = 0;
	}

	if(publiccertcontainer && path[0]){
	    ps_global->smime->publictype = Container;
	    ps_global->smime->publicpath = cpystr(path);

	    if(contents){
		ps_global->smime->publiccontent = contents;
		ps_global->smime->publiccertlist = mem_to_certlist(contents, Public);
	    }
	}
    }

    /* Public certificates in a directory of files */
    if(!publiccertcontainer){
	ps_global->smime->publictype = Directory;

	path[0] = '\0';
	if(!(smime_path(ps_global->VAR_PUBLICCERT_DIR, path, MAXPATH)
	     && !IS_REMOTE(path)))
	  ps_global->smime->publictype = Nada;
	else if(can_access(path, ACCESS_EXISTS)){
	    if(our_mkpath(path, 0700)){
		q_status_message1(SM_ORDER, 3, 3, _("Can't create directory %s"), path);
		ps_global->smime->publictype = Nada;
	    }
	}

	if(ps_global->smime->publictype == Directory)
	  ps_global->smime->publicpath = cpystr(path);
    }

#ifdef APPLEKEYCHAIN
    }
#endif /* APPLEKEYCHAIN */

    setup_privatekey_storage();

    /* extra cacerts in a container */
    if(ps_global->VAR_CACERT_CONTAINER && ps_global->VAR_CACERT_CONTAINER[0]){

	cacertcontainer = 1;
	contents = NULL;
	path[0] = '\0';
	if(!smime_path(ps_global->VAR_CACERT_CONTAINER, path, MAXPATH))
	  cacertcontainer = 0;

	if(cacertcontainer && !IS_REMOTE(path)
	   && ps_global->VAR_OPER_DIR
           && !in_dir(ps_global->VAR_OPER_DIR, path)){
	    q_status_message2(SM_ORDER | SM_DING, 3, 4,
			  /* TRANSLATORS: First arg is the directory name, second is
			     the file user wants to read but can't. */
			  _("Can't read file outside %s: %s"),
			  ps_global->VAR_OPER_DIR, path);
	    cacertcontainer = 0;
	}

	if(cacertcontainer
	   && (IS_REMOTE(path) || can_access(path, ACCESS_EXISTS) == 0)){
	    if(!(IS_REMOTE(path) && (contents = simple_read_remote_file(path, REMOTE_SMIME_SUBTYPE)))
	       &&
	       !(contents = read_file(path, READ_FROM_LOCALE)))
	      cacertcontainer = 0;
	}

	if(cacertcontainer && path[0]){
	    ps_global->smime->catype = Container;
	    ps_global->smime->capath = cpystr(path);
	    ps_global->smime->cacontent = contents;
	    if(contents)
	      ps_global->smime->cacertlist = mem_to_certlist(contents, CACert);
	}
    }

    if(!cacertcontainer){
	ps_global->smime->catype = Directory;

	path[0] = '\0';
	if(!(smime_path(ps_global->VAR_CACERT_DIR, path, MAXPATH)
	     && !IS_REMOTE(path)))
	  ps_global->smime->catype = Nada;
	else if(can_access(path, ACCESS_EXISTS)){
	    if(our_mkpath(path, 0700)){
		q_status_message1(SM_ORDER, 3, 3, _("Can't create directory %s"), path);
		ps_global->smime->catype = Nada;
	    }
	}

	if(ps_global->smime->catype == Directory)
	  ps_global->smime->capath = cpystr(path);
    }
}


int
copy_publiccert_dir_to_container(void)
{
    return(copy_dir_to_container(Public, NULL));
}


int
copy_publiccert_container_to_dir(void)
{
    return(copy_container_to_dir(Public));
}


int
copy_privatecert_dir_to_container(void)
{
    return(copy_dir_to_container(Private, NULL));
}


int
copy_privatecert_container_to_dir(void)
{
    return(copy_container_to_dir(Private));
}


int
copy_cacert_dir_to_container(void)
{
    return(copy_dir_to_container(CACert, NULL));
}


int
copy_cacert_container_to_dir(void)
{
    return(copy_container_to_dir(CACert));
}

/* Add the contents of a file to a container. Do not check the content
 * of the file, just add it using the format for that container. The
 * caller must check the format, so that there is no data corruption
 * in the future.
 * return value: 0 - success,
 *               != 0 - failure.
 */
int
add_file_to_container(WhichCerts ctype, char *fpath, char *altname)
{
    char *sep = (ctype == Public || ctype == Private)
                ? EMAILADDRLEADER : CACERTSTORELEADER;
    char *content = ctype == Public ? ps_global->smime->publiccontent
		    : (ctype == Private ? ps_global->smime->privatecontent
		    : ps_global->smime->cacontent);
    char *name;
    char *s, c;
    struct stat sbuf;
    STORE_S *in = NULL;
    int rv = -1; 	/* assume error */

    if(our_stat(fpath, &sbuf) < 0 
	|| (in = so_get(FileStar, fpath, READ_ACCESS | READ_FROM_LOCALE)) == NULL)
      goto endadd;

    if(altname != NULL)
      name = altname;
    else if((name = strrchr(fpath, '/')) != NULL){
      size_t ll;
      if((ll = strlen(++name)) > 4 && strucmp(name + ll - 4, EXTCERT(ctype)) == 0)
        name[ll-strlen(EXTCERT(ctype))] = '\0';
    }
    else 
      goto endadd;

    if(content){
      fs_resize((void **)&content, strlen(content) + strlen(sep) + strlen(name) + sbuf.st_size + 3); /* 2 = \n + \n + \0*/
      s = content;
      content += strlen(content);
    }
    else{
      s = content = fs_get(strlen(sep) + strlen(name) + sbuf.st_size + 1); /* 2 = \n + \0 */
      *content = '\0';
    }
    strncat(content, sep, strlen(sep));
    strncat(content, name, strlen(name));
    content += strlen(content);
    *content++ = '\n';

    while(so_readc(&c, in))
       *content++ = c;
    *content = '\0';

    switch(ctype){
      case Private:   ps_global->smime->privatecontent = s; break;
      case Public :   ps_global->smime->publiccontent = s; break;
      case CACert :   ps_global->smime->cacontent = s; break;
      default : break;
    }

    rv = copy_dir_to_container(ctype, s);

endadd: 
    if(in) so_give(&in);

    return rv;
}


/*
 * returns 0 on success, -1 on failure
 * contents is an argument which tells this function to write the value
 * of this variable instead of reading the contents of the directory.
 * If the var contents is not null use its value as the value of the 
 * container.
 */
int
copy_dir_to_container(WhichCerts which, char *contents)
{
    int ret = 0;
    BIO *bio_out = NULL, *bio_in = NULL;
    char srcpath[MAXPATH+1], dstpath[MAXPATH+1], emailaddr[MAXPATH], file[MAXPATH], line[4096];
    char *tempfile = NULL;
    DIR *dirp;
    struct dirent *d;
    REMDATA_S *rd = NULL;
    char *configdir = NULL;
    char *configpath = NULL;
    char *filesuffix = NULL;

    dprint((9, "copy_dir_to_container(%s)", which==Public ? "Public" : which==Private ? "Private" : which==CACert ? "CACert" : "?"));
    smime_init();

    srcpath[0] = '\0';
    dstpath[0] = '\0';
    file[0] = '\0';
    emailaddr[0] = '\0';

    if(which == Public){
	configdir  = ps_global->VAR_PUBLICCERT_DIR;
	configpath = ps_global->smime->publicpath;
	filesuffix = ".crt";
    }
    else if(which == Private){
	configdir = ps_global->VAR_PRIVATEKEY_DIR;
	configpath = ps_global->smime->privatepath;
	filesuffix = ".key";
    }
    else if(which == CACert){
	configdir = ps_global->VAR_CACERT_DIR;
	configpath = ps_global->smime->capath;
	filesuffix = ".crt";
    }

    if(!(configdir && configdir[0])){
	q_status_message(SM_ORDER, 3, 3, _("Directory not defined"));
	return -1;
    }

    if(!(configpath && configpath[0])){
#ifdef APPLEKEYCHAIN
	if(which == Public && F_ON(F_PUBLICCERTS_IN_KEYCHAIN, ps_global)){
	    q_status_message(SM_ORDER, 3, 3, _("Turn off the Keychain feature above first"));
	    return -1;
	}
#endif /* APPLEKEYCHAIN */
	q_status_message(SM_ORDER, 3, 3, _("Container path is not defined"));
	return -1;
    }

    if(!(filesuffix && strlen(filesuffix) == 4)){
	return -1;
    }


    /*
     * If there is a legit directory to read from set up the
     * container file to write to.
     */
    if(smime_path(configdir, srcpath, MAXPATH) && !IS_REMOTE(srcpath)){

	if(IS_REMOTE(configpath)){
	    rd = rd_create_remote(RemImap, configpath, REMOTE_SMIME_SUBTYPE,
				  NULL, "Error: ",
				  _("Can't access remote smime configuration."));
	    if(!rd)
	      return -1;
	    
	    (void) rd_read_metadata(rd);

	    if(rd->access == MaybeRorW){
		if(rd->read_status == 'R')
		  rd->access = ReadOnly;
		else
		  rd->access = ReadWrite;
	    }

	    if(rd->access != NoExists){

		rd_check_remvalid(rd, 1L);

		/*
		 * If the cached info says it is readonly but
		 * it looks like it's been fixed now, change it to readwrite.
		 */
		if(rd->read_status == 'R'){
		    rd_check_readonly_access(rd);
		    if(rd->read_status == 'W'){
			rd->access = ReadWrite;
			rd->flags |= REM_OUTOFDATE;
		    }
		    else
		      rd->access = ReadOnly;
		}
	    }

	    if(rd->flags & REM_OUTOFDATE){
		if(rd_update_local(rd) != 0){

		    dprint((1, "copy_dir_to_container: rd_update_local failed\n"));
		    rd_close_remdata(&rd);
		    return -1;
		}
	    }
	    else
	      rd_open_remote(rd);

	    if(rd->access != ReadWrite || rd_remote_is_readonly(rd)){
		rd_close_remdata(&rd);
		return -1;
	    }

	    rd->flags |= DO_REMTRIM;

	    strncpy(dstpath, rd->lf, sizeof(dstpath)-1);
	    dstpath[sizeof(dstpath)-1] = '\0';
	}
	else{
	    strncpy(dstpath, configpath, sizeof(dstpath)-1);
	    dstpath[sizeof(dstpath)-1] = '\0';
	}

	/*
	 * dstpath is either the local Container file or the local cache file
	 * for the remote Container file.
	 */
	tempfile = tempfile_in_same_dir(dstpath, "az", NULL);
    }

    /*
     * If there is a legit directory to read from and a tempfile
     * to write to we continue.
     */
    if(tempfile && (bio_out=BIO_new_file(tempfile, "w")) != NULL){

	if(contents != NULL){
	   if(BIO_puts(bio_out, contents) < 0)
	     ret = -1;
	}
	else {
	  if((dirp = opendir(srcpath)) != NULL){

	    while((d=readdir(dirp)) && !ret){
		size_t ll;

		if((ll=strlen(d->d_name)) && ll > 4 && !strcmp(d->d_name+ll-4, filesuffix)){

		    /* copy file name to temp buffer */
		    strncpy(emailaddr, d->d_name, sizeof(emailaddr)-1);
		    emailaddr[sizeof(emailaddr)-1] = '\0';
		    /* chop off suffix trailier */
		    emailaddr[strlen(emailaddr)-4] = 0;

		    /*
		     * This is the separator between the contents of
		     * different files.
		     */
		    if(which == CACert){
			if(!((BIO_puts(bio_out, CACERTSTORELEADER) > 0)
			     && (BIO_puts(bio_out, emailaddr) > 0)
			     && (BIO_puts(bio_out, "\n") > 0)))
			  ret = -1;
		    }
		    else{
			if(!((BIO_puts(bio_out, EMAILADDRLEADER) > 0)
			     && (BIO_puts(bio_out, emailaddr) > 0)
			     && (BIO_puts(bio_out, "\n") > 0)))
			  ret = -1;
		    }

		    /* read then write contents of file */
		    build_path(file, srcpath, d->d_name, sizeof(file));
		    if(!(bio_in = BIO_new_file(file, "r")))
		      ret = -1;

		    if(!ret){
			int good_stuff = 0;

			while(BIO_gets(bio_in, line, sizeof(line)) > 0){
			    if(strncmp("-----BEGIN", line, strlen("-----BEGIN")) == 0)
			      good_stuff = 1;

			    if(good_stuff)
			      BIO_puts(bio_out, line);

			    if(strncmp("-----END", line, strlen("-----END")) == 0)
			      good_stuff = 0;
			}
		    }

		    BIO_free(bio_in);
		}
	    }

	    closedir(dirp);
	  }
	}

	BIO_free(bio_out);

	if(!ret){
	    if(rename_file(tempfile, dstpath) < 0){
		q_status_message2(SM_ORDER, 3, 3,
		    _("Can't rename %s to %s"), tempfile, dstpath);
		ret = -1;
	    }
	    
	    /* if the container is remote, copy it */
	    if(!ret && IS_REMOTE(configpath)){
		int   e;
		char datebuf[200];

		datebuf[0] = '\0';

		if((e = rd_update_remote(rd, datebuf)) != 0){
		    if(e == -1){
			q_status_message2(SM_ORDER | SM_DING, 3, 5,
			  _("Error opening temporary smime file %s: %s"),
			    rd->lf, error_description(errno));
			dprint((1,
			   "write_remote_smime: error opening temp file %s\n",
			   rd->lf ? rd->lf : "?"));
		    }
		    else{
			q_status_message2(SM_ORDER | SM_DING, 3, 5,
					_("Error copying to %s: %s"),
					rd->rn, error_description(errno));
			dprint((1,
			  "write_remote_smime: error copying from %s to %s\n",
			  rd->lf ? rd->lf : "?", rd->rn ? rd->rn : "?"));
		    }
		    
		    q_status_message(SM_ORDER | SM_DING, 5, 5,
       _("Copy of smime key to remote folder failed, NOT saved remotely"));
		}
		else{
		    rd_update_metadata(rd, datebuf);
		    rd->read_status = 'W';
		}

		rd_close_remdata(&rd);
	    }
	}
    }

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

    return ret;
}


/*
 * returns 0 on success, -1 on failure
 */
int
copy_container_to_dir(WhichCerts which)
{
    char  path[MAXPATH+1], file[MAXPATH+1], buf[MAXPATH+1];
    char  iobuf[4096];
    char *contents = NULL;
    char *leader = NULL;
    char *filesuffix = NULL;
    char *configdir = NULL;
    char *configpath = NULL;
    char *tempfile = NULL;
    char *p, *q, *line, *name, *certtext, *save_p;
    int  len;
    BIO *in, *out;

    dprint((9, "copy_container_to_dir(%s)", which==Public ? "Public" : which==Private ? "Private" : which==CACert ? "CACert" : "?"));
    smime_init();

    path[0] = '\0';

    if(which == Public){
	leader = EMAILADDRLEADER;
	contents  = ps_global->smime->publiccontent;
	configdir  = ps_global->VAR_PUBLICCERT_DIR;
	configpath = ps_global->smime->publicpath;
	filesuffix = ".crt";
	if(!(configpath && configpath[0])){
#ifdef APPLEKEYCHAIN
	    if(which == Public && F_ON(F_PUBLICCERTS_IN_KEYCHAIN, ps_global)){
		q_status_message(SM_ORDER, 3, 3, _("Turn off the Keychain feature above first"));
		return -1;
	    }
#endif /* APPLEKEYCHAIN */
	    q_status_message(SM_ORDER, 3, 3, _("Container path is not defined"));
	    return -1;
	}

	fs_give((void **) &ps_global->smime->publicpath);

	path[0] = '\0';
	if(!(smime_path(ps_global->VAR_PUBLICCERT_DIR, path, MAXPATH)
	     && !IS_REMOTE(path))){
	    q_status_message(SM_ORDER, 3, 3, _("Directory is not defined"));
	    return -1;
	}

	if(can_access(path, ACCESS_EXISTS)){
	    if(our_mkpath(path, 0700)){
		q_status_message1(SM_ORDER, 3, 3, _("Can't create directory %s"), path);
		return -1;
	    }
	}

	ps_global->smime->publicpath = cpystr(path);
	configpath = ps_global->smime->publicpath;
    }
    else if(which == Private){
	leader = EMAILADDRLEADER;
	contents  = ps_global->smime->privatecontent;
	configdir = ps_global->VAR_PRIVATEKEY_DIR;
	configpath = ps_global->smime->privatepath;
	filesuffix = ".key";
	if(!(configpath && configpath[0])){
	    q_status_message(SM_ORDER, 3, 3, _("Container path is not defined"));
	    return -1;
	}

	fs_give((void **) &ps_global->smime->privatepath);

	path[0] = '\0';
	if(!(smime_path(ps_global->VAR_PRIVATEKEY_DIR, path, MAXPATH)
	     && !IS_REMOTE(path))){
	    q_status_message(SM_ORDER, 3, 3, _("Directory is not defined"));
	    return -1;
	}

	if(can_access(path, ACCESS_EXISTS)){
	    if(our_mkpath(path, 0700)){
		q_status_message1(SM_ORDER, 3, 3, _("Can't create directory %s"), path);
		return -1;
	    }
	}

	ps_global->smime->privatepath = cpystr(path);
	configpath = ps_global->smime->privatepath;
    }
    else if(which == CACert){
	leader = CACERTSTORELEADER;
	contents  = ps_global->smime->cacontent;
	configdir = ps_global->VAR_CACERT_DIR;
	configpath = ps_global->smime->capath;
	filesuffix = ".crt";
	if(!(configpath && configpath[0])){
	    q_status_message(SM_ORDER, 3, 3, _("Container path is not defined"));
	    return -1;
	}

	fs_give((void **) &ps_global->smime->capath);

	path[0] = '\0';
	if(!(smime_path(ps_global->VAR_CACERT_DIR, path, MAXPATH)
	     && !IS_REMOTE(path))){
	    q_status_message(SM_ORDER, 3, 3, _("Directory is not defined"));
	    return -1;
	}

	if(can_access(path, ACCESS_EXISTS)){
	    if(our_mkpath(path, 0700)){
		q_status_message1(SM_ORDER, 3, 3, _("Can't create directory %s"), path);
		return -1;
	    }
	}

	ps_global->smime->capath = cpystr(path);
	configpath = ps_global->smime->capath;
    }

    if(!(configdir && configdir[0])){
	q_status_message(SM_ORDER, 3, 3, _("Directory not defined"));
	return -1;
    }

    if(!(configpath && configpath[0])){
	q_status_message(SM_ORDER, 3, 3, _("Container path is not defined"));
	return -1;
    }

    if(!(filesuffix && strlen(filesuffix) == 4)){
	return -1;
    }


    if(contents && *contents){
	for(p = contents; *p != '\0';){
	    line = p;

	    while(*p && *p != '\n')
	      p++;

	    save_p = NULL;
	    if(*p == '\n'){
		save_p = p;
		*p++ = '\0';
	    }

	    if(strncmp(leader, line, strlen(leader)) == 0){
		name = line + strlen(leader);
		certtext = p;
		if(strncmp("-----BEGIN", certtext, strlen("-----BEGIN")) == 0){
		    if((q = strstr(certtext, leader)) != NULL){
			p = q;
		    }
		    else{		/* end of file */
			q = certtext + strlen(certtext);
			p = q;
		    }

		    strncpy(buf, name, sizeof(buf)-5);
		    buf[sizeof(buf)-5] = '\0';
		    strncat(buf, filesuffix, 5);
		    build_path(file, configpath, buf, sizeof(file));

		    in = BIO_new_mem_buf(certtext, q-certtext);
		    if(in){
			tempfile = tempfile_in_same_dir(file, "az", NULL);
			out = NULL;
			if(tempfile)
			  out = BIO_new_file(tempfile, "w");

			if(out){
			    while((len = BIO_read(in, iobuf, sizeof(iobuf))) > 0)
			      BIO_write(out, iobuf, len);

			    BIO_free(out);

			    if(rename_file(tempfile, file) < 0){
				q_status_message2(SM_ORDER, 3, 3,
				                  _("Can't rename %s to %s"),
						  tempfile, file);
				return -1;
			    }

			    fs_give((void **) &tempfile);
			}
			  
			BIO_free(in);
		    }
		}
	    }

	    if(save_p)
	      *save_p = '\n';
	}
    }

    return 0;
}


#ifdef APPLEKEYCHAIN

int
copy_publiccert_container_to_keychain(void)
{
    /* NOT IMPLEMNTED */
    return -1;
}

int
copy_publiccert_keychain_to_container(void)
{
    /* NOT IMPLEMNTED */
    return -1;
}

#endif /* APPLEKEYCHAIN */


/*
 * Get a pointer to a string describing the most recent OpenSSL error.
 * It's statically allocated, so don't change or attempt to free it.
 */
static const char *
openssl_error_string(void)
{
    char	*errs;
    const char	*data = NULL;
    long errn;

    errn = ERR_peek_error_line_data(NULL, NULL, &data, NULL);
    errs = (char*) ERR_reason_error_string(errn);

    if(errs)
      return errs;
    else if(data)
      return data;

    return "unknown error";
}


/* Return true if the body looks like a PKCS7 object */
int
is_pkcs7_body(BODY *body)
{
    int result;

    result = body->type==TYPEAPPLICATION &&
             body->subtype &&
             (strucmp(body->subtype,"pkcs7-mime")==0 ||
              strucmp(body->subtype,"x-pkcs7-mime")==0 ||
	      strucmp(body->subtype,"pkcs7-signature")==0 ||
	      strucmp(body->subtype,"x-pkcs7-signature")==0);

    return result;
}


#ifdef notdef
/*
 * Somewhat useful debug utility to dump the contents of a BIO to a file.
 * Note that a memory BIO will have its contents eliminated after they
 * are read so this will break the next step.
 */
static void
dump_bio_to_file(BIO *in, char *filename)
{
    char iobuf[4096];
    int len;
    BIO *out;
    
    out = BIO_new_file(filename, "w");
    
    if(out){
	if(BIO_method_type(in) != BIO_TYPE_MEM)
    	  BIO_reset(in);
    
	while((len = BIO_read(in, iobuf, sizeof(iobuf))) > 0)
	  BIO_write(out, iobuf, len);

    	BIO_free(out);
    }
	
    BIO_reset(in);
}
#endif


/*
 * Recursively stash a pointer to the decrypted data in our
 * manufactured body.
 */
static void
create_local_cache(char *h, char *base, BODY *b)
{
    if(b->type==TYPEMULTIPART){
        PART *p;

#if 0 
        cpytxt(&b->contents.text, base + b->contents.offset, b->size.bytes);
#else
    	/*
    	 * We don't really want to copy the real body contents. It shouldn't be
	 * used, and in the case of a message with attachments, we'll be 
	 * duplicating the files multiple times.
	 */
    	cpytxt(&b->contents.text, "BODY UNAVAILABLE", 16);
#endif

        for(p=b->nested.part; p; p=p->next)
          create_local_cache(h, base, (BODY*) p);
    }
    else{
	cpytxt(&b->mime.text, h+b->mime.offset, b->mime.text.size);
        cpytxt(&b->contents.text, base + b->contents.offset, b->size.bytes);
    }
}


static long
rfc822_output_func(void *b, char *string)
{
    BIO *bio = (BIO *) b;

    return(string ? *string ? (BIO_puts(bio, string) >  0 ? 1L : 0L) 
			    : (BIO_puts(bio, string) >= 0 ? 1L : 0L)  
		  : 0L);
}


/*
 * Attempt to load the private key for the given PERSONAL_CERT.
 * This sets the appropriate passphrase globals in order to
 * interact with the user correctly.
 */
static int
load_private_key(PERSONAL_CERT *pcert)
{
    if(!pcert->key){
    
    	/* Try empty password by default */
    	char	*password = "";
    
    	if(ps_global->smime
           && (ps_global->smime->need_passphrase
               || ps_global->smime->entered_passphrase)){
	    /* We've already been in here and discovered we need a different password */
	    
	    if(ps_global->smime->entered_passphrase)
    	      password = (char *) ps_global->smime->passphrase;	/* already entered */
	    else
	      return 0;
	}

        ERR_clear_error();

        if(!(pcert->key = load_key(pcert, password))){
            long err = ERR_get_error();

    	    /* Couldn't load key... */

	    if(ps_global->smime && ps_global->smime->entered_passphrase){

    	    	/* The user got the password wrong maybe? */

        	if((ERR_GET_LIB(err)==ERR_LIB_EVP && ERR_GET_REASON(err)==EVP_R_BAD_DECRYPT) ||
                	(ERR_GET_LIB(err)==ERR_LIB_PEM && ERR_GET_REASON(err)==PEM_R_BAD_DECRYPT))
                  q_status_message(SM_ORDER | SM_DING, 4, 4, _("Incorrect passphrase"));
        	else
		  q_status_message1(SM_ORDER, 4, 4, _("Couldn't read key: %s"),(char*)openssl_error_string());
    	    	
		/* This passphrase is no good; forget it */
		ps_global->smime->entered_passphrase = 0;
	    }
	    
	    if(ps_global->smime){
	    /* Indicate to the UI that we need re-entry (see mailcmd.c:process_cmd())*/
		ps_global->smime->need_passphrase = 1;
		if(ps_global->smime->passphrase_emailaddr){
		  int i;
		  for(i = 0; ps_global->smime->passphrase_emailaddr[i] != NULL; i++)
		     fs_give((void **)&ps_global->smime->passphrase_emailaddr[i]);
		  fs_give((void **) ps_global->smime->passphrase_emailaddr);
		}

		ps_global->smime->passphrase_emailaddr = get_x509_subject_email(pcert->cert);
	    }

            return 0;
        }
	else{
	    /* This key will be cached, so we won't be called again */
	    if(ps_global->smime){
		ps_global->smime->entered_passphrase = 0;
		ps_global->smime->need_passphrase = 0;
	    }
	}
	
	return 1;
    }
    
    return 0;
}


static void
setup_pkcs7_body_for_signature(BODY *b, char *description, char *type, char *filename)
{
    b->type = TYPEAPPLICATION;
    b->subtype = cpystr(type);
    b->encoding = ENCBINARY;
    b->description = cpystr(description);

    b->disposition.type = cpystr("attachment");
    set_parameter(&b->disposition.parameter, "filename", filename);

    set_parameter(&b->parameter, "name", filename);
}


/*
 * Look for a personal certificate matching the 
 * given address
 */
PERSONAL_CERT *
match_personal_cert_to_email(ADDRESS *a)
{
    PERSONAL_CERT   *pcert = NULL;
    char	buf[MAXPATH];
    char    	**email;
    int i, done;

    if(!a || !a->mailbox || !a->host)
      return NULL;
    
    snprintf(buf, sizeof(buf), "%s@%s", a->mailbox, a->host);
    
    if(ps_global->smime){
	for(pcert=(PERSONAL_CERT *) ps_global->smime->personal_certs;
	    pcert;
	    pcert=pcert->next){
	
	    if(!pcert->cert)
	      continue;
	
	    email = get_x509_subject_email(pcert->cert);

	    done = 0;
	    if(email != NULL){
		for(i = 0; email[i] && strucmp(email[i], buf) != 0; i++);
		if(email[i] != NULL) done++;
		for(i = 0; email[i] != NULL; i++)
		   fs_give((void **)&email[i]);
		fs_give((void **)email);
	    }

	    if(done > 0)
	      break;
	}
    }
    
    return pcert;
}


/*
 * Look for a personal certificate matching the from
 * (or reply_to? in the given envelope)
 */
PERSONAL_CERT *
match_personal_cert(ENVELOPE *env)
{
    PERSONAL_CERT   *pcert;
    
    pcert = match_personal_cert_to_email(env->reply_to);
    if(!pcert)
      pcert = match_personal_cert_to_email(env->from);
        
    return pcert;
}


/*
 * Flatten the given body into its MIME representation.
 * Return the result in a BIO.
 */
static BIO *
body_to_bio(BODY *body)
{
    BIO *bio = NULL;
    int  len;

    bio = BIO_new(BIO_s_mem());
    if(!bio)
      return NULL;
    
    pine_encode_body(body); /* this attaches random boundary strings to multiparts */
    pine_write_body_header(body, rfc822_output_func, bio);
    pine_rfc822_output_body(body, rfc822_output_func, bio);

    /*
     * Now need to truncate by two characters since the above
     * appends CRLF.
     */
    if((len=BIO_ctrl_pending(bio)) > 1){
	BUF_MEM *biobuf = NULL;

	BIO_get_mem_ptr(bio, &biobuf);
	if(biobuf){
	    BUF_MEM_grow(biobuf, len-2);	/* remove CRLF */
	}
    }

    return bio;
} 


static BIO *
bio_from_store(STORE_S *store)
{
    BIO *ret = NULL;

    if(store && store->src == BioType && store->txt){
	ret = (BIO *) store->txt;
    }

    return(ret);
}

/* 
 * Encrypt file; given a path (char *) fp, replace the file
 * by an encrypted version of it. If (char *) text is not null, then
 * replace the text of (char *) fp by the encrypted version of (char *) text.
 * certpath is the FULL path to the file containing the certificate used for 
 * encryption.
 */
int
encrypt_file(char *fp, char *text, PERSONAL_CERT *pc)
{
  const EVP_CIPHER *cipher = NULL;
  STACK_OF(X509) *encerts = NULL;
  X509 *cert;
  BIO *out;
  PKCS7 *p7 = NULL;
  FILE *fpp;
  int i, rv = 0;
  char *fname;
  char emailaddress[MAILTMPLEN];

  smime_init();
  cipher = EVP_aes_256_cbc();
  encerts = sk_X509_new_null();

  if(pc == NULL)
    goto end;

  sk_X509_push(encerts, X509_dup(pc->cert));

  if(text){
    if((out = BIO_new(BIO_s_mem())) == NULL)
      goto end;
    (void) BIO_reset(out);
    BIO_puts(out, text);
  }
  else{
    if(!(out = BIO_new_file(fp, "rb")))
      goto end;

    BIO_read_filename(out, fp);
  }

  if((p7 = PKCS7_encrypt(encerts, out, cipher, 0)) == NULL)
     goto end;
  BIO_set_close(out, BIO_CLOSE);
  BIO_free(out);
  if(!(out = BIO_new_file(fp, "w")))
    goto end;
  BIO_reset(out);
  rv = PEM_write_bio_PKCS7(out, p7);
  BIO_flush(out);

end:
  BIO_free(out);
  PKCS7_free(p7);
  sk_X509_pop_free(encerts, X509_free);

  return rv;
}

/*
 * Encrypt a message on the way out. Called from call_mailer in send.c
 * The body may be reallocated.
 */
int
encrypt_outgoing_message(METAENV *header, BODY **bodyP)
{
    PKCS7 *p7 = NULL;
    BIO	*in = NULL;
    BIO *out = NULL;
    const EVP_CIPHER *cipher = NULL;
    STACK_OF(X509) *encerts = NULL;
    STORE_S *outs = NULL;
    PINEFIELD	*pf;
    ADDRESS	*a;
    BODY	*body = *bodyP;
    BODY	*newBody = NULL;
    int		 result = 0;

    dprint((9, "encrypt_outgoing_message()"));
    smime_init();

    cipher = EVP_aes_256_cbc();

    encerts = sk_X509_new_null();

    /* Look for a certificate for each of the recipients */
    for(pf = header->local; pf && pf->name; pf = pf->next)
        if(pf->type == Address && pf->rcptto && pf->addr && *pf->addr){
            for(a=*pf->addr; a; a=a->next){
                X509	*cert;
                char	 buf[MAXPATH];

                snprintf(buf, sizeof(buf), "%s@%s", a->mailbox, a->host);

                cert = get_cert_for(buf, Public);
                if(cert)
                  sk_X509_push(encerts,cert);
                else{
                    q_status_message2(SM_ORDER, 1, 1,
                                      _("Unable to find certificate for <%s@%s>"),
				      a->mailbox, a->host);
                    goto end;
                }
            }
        }


    in = body_to_bio(body);

    p7 = PKCS7_encrypt(encerts, in, cipher, 0);

    outs = so_get(BioType, NULL, EDIT_ACCESS);
    out = bio_from_store(outs);

    i2d_PKCS7_bio(out, p7);
    (void) BIO_flush(out);

    so_seek(outs, 0, SEEK_SET);

    newBody = mail_newbody();

    newBody->type = TYPEAPPLICATION;
    newBody->subtype = cpystr("pkcs7-mime");
    newBody->encoding = ENCBINARY;

    newBody->disposition.type = cpystr("attachment");
    set_parameter(&newBody->disposition.parameter, "filename", "smime.p7m");

    newBody->description = cpystr("S/MIME Encrypted Message");
    set_parameter(&newBody->parameter, "smime-type", "enveloped-data");
    set_parameter(&newBody->parameter, "name", "smime.p7m");

    newBody->contents.text.data = (unsigned char *) outs;

    *bodyP = newBody;

    result = 1;

end:

    BIO_free(in);
    PKCS7_free(p7);
    sk_X509_pop_free(encerts, X509_free);

    dprint((9, "encrypt_outgoing_message returns %d", result));
    return result;
}


/*
    Get (and decode) the body of the given section of msg
 */
static STORE_S*
get_part_contents(long msgno, const char *section)
{
    long len;
    gf_io_t     pc;
    STORE_S *store = NULL;
    char	*err;

    store = so_get(CharStar, NULL, EDIT_ACCESS);
    if(store){
        gf_set_so_writec(&pc,store);

        err = detach(ps_global->mail_stream, msgno, (char*) section, 0L, &len, pc, NULL, 0L);

        gf_clear_so_writec(store);

        so_seek(store, 0, SEEK_SET);

        if(err)
          so_give(&store);
    }

    return store;
}


static PKCS7 *
get_pkcs7_from_part(long msgno,const char *section)
{
    STORE_S *store = NULL;
    PKCS7   *p7 = NULL;
    BIO	   *in = NULL;

    store = get_part_contents(msgno, section);

    if(store){
	if(store->src == CharStar){
	    int len;

	    /*
	     * We're reaching inside the STORE_S structure. We should
	     * probably have a way to get the length, instead.
	     */
	    len = (int) (store->eod - store->dp);
	    in = BIO_new_mem_buf(store->txt, len);
	}
	else{				/* just copy it */
	    unsigned char c;

	    in = BIO_new(BIO_s_mem());
	    (void) BIO_reset(in);

	    so_seek(store, 0L, 0);
	    while(so_readc(&c, store)){
		BIO_write(in, &c, 1);
	    }
	}

        if(in){
/* dump_bio_to_file(in, "/tmp/decoded-signature"); */
            if((p7=d2i_PKCS7_bio(in,NULL)) == NULL){
		/* error */
	    }

	    BIO_free(in);
        }

	so_give(&store);
    }

    return p7;
}

int same_cert(X509 *x, X509 *cert)
{
   char    bufcert[256],  bufx[256];
   int rv = 0;

   get_fingerprint(cert, EVP_md5(), bufcert, sizeof(bufcert));
   get_fingerprint(x, EVP_md5(), bufx, sizeof(bufx));
   if(strcmp(bufx, bufcert) == 0)
     rv = 1;

   return rv;
}


/* extract and save certificates from a PKCS7 package. The ctype variable
 * tells us if we want to extract it to a public/ or a ca/ directory. The
 * later makes sense only for recoverable errors (errors that can be fixed
 * by saving to the ca/ directory before we verify the signature).
 * Return value:
 *	0 - no errors (in public/) no need to try again, 
 *          or validated self signed certificate (in ca/)
 *    < 0 - certificate error is not recoverable, don't even think about it.
 */

int smime_extract_and_save_cert(PKCS7 *p7)
{
    STACK_OF(X509) *signers;
    X509 *x, *cert;
    char **email;
    int i, j;
    long error;

    if((signers = PKCS7_get0_signers(p7, NULL, 0)) == NULL)
      return -1;

    for(i = 0; i < sk_X509_num(signers); i++){
	if((x = sk_X509_value(signers,i)) == NULL)
	    continue;

	if((email = get_x509_subject_email(x)) != NULL){
	  for(j = 0; email[j] != NULL; j++){
	     if((cert = get_cert_for(email[j], Public)) == NULL 
		  || same_cert(x, cert) == 0)
	        save_cert_for(email[j], x, Public);
	     X509_free(cert);
	     fs_give((void **) &email[i]);
	  }
	  fs_give((void **) email);
	}
    }
    sk_X509_free(signers);

    return 0;
}

/*
 * Try to verify a signature.
 * 
 * p7  - the pkcs7 object to verify
 * in  - the plain data to verify (NULL if not detached)
 * out - BIO to which to write the opaque data
 * silent - if non zero, do not print errors, only print success.
 */
static int
do_signature_verify(PKCS7 *p7, BIO *in, BIO *out, int silent)
{
    STACK_OF(X509) *otherCerts = NULL;
    int result;
    const char *data;
    long err;
    
    if(!s_cert_store){
	if(!silent) q_status_message(SM_ORDER | SM_DING, 2, 2,
		_("Couldn't verify S/MIME signature: No CA Certs were loaded"));

    	return -1;
    }

    smime_extract_and_save_cert(p7);

    result = PKCS7_verify(p7, otherCerts, s_cert_store, in, out, 0);
    
    if(result){
	q_status_message(SM_ORDER, 1, 1, _("S/MIME signature verified ok"));
    }
    else{
	err = ERR_peek_error_line_data(NULL, NULL, &data, NULL);

	if(out && err==ERR_PACK(ERR_LIB_PKCS7,PKCS7_F_PKCS7_VERIFY,PKCS7_R_CERTIFICATE_VERIFY_ERROR)){

	    /* Retry verification so we can get the plain text */
	    /* Might be better to reimplement PKCS7_verify here? */
	    
	    PKCS7_verify(p7, otherCerts, s_cert_store, in, out, PKCS7_NOVERIFY);
	}
	if (!silent) q_status_message1(SM_ORDER | SM_DING, 3, 3,
		_("Couldn't verify S/MIME signature: %s"), (char*) openssl_error_string());
    }

    return result;
}


void
free_smime_body_sparep(void **sparep)
{
    if(sparep && *sparep){
	PKCS7_free((PKCS7 *) (*sparep));
	*sparep = NULL;
    }
}

/* Big comment, explaining the mess that exists out there, and how we deal
   with it, and also how we solve the problems that are created this way.

  When Alpine sends a message, it constructs that message, computes the 
  signature, but then it forgets the message it signed and reconstructs it 
  again. Since it signs a message containing a notice about "mime aware 
  tools", but it does not send that we do not include that in the part that 
  is signed, and that takes care of much of the problems.
 
  Another problem is what is received from the servers. All servers tested 
  seem to transmit the message that was signed intact and Alpine can check 
  the signature correctly. That is not a problem. The problem arises when 
  the message includes attachments. In this case different servers send 
  different things, so it will be up to us to figure out what is the text 
  that was actually signed. Confused? here is the story:
 
  When a message containing and attachment is sent by Alpine, UW-IMAP, 
  Panda-IMAP, Gmail, and local reading of folders send exactly the message 
  that was sent by Alpine, but GMX.com, Exchange, and probably other servers 
  add a trailing \r\n in the message, so when validating the signature, 
  these messages will not validate. There are several things that can be 
  done.
 
  1. Add a trailing \r\n to any message that contains attachments, sign that 
     and send that. In this way, all messages will validate with all 
     servers.
  
  2. Compatibility mode: If a message has an attachment, contains a trailing 
     \r\n and does not validate (sent by an earlier version of Alpine), 
     remove the trailing \r\n and try to revalidate again.

  3. We do not add \r\n to validate a message that we sent, because that 
     would only work in Alpine, and not in any other client. That would not 
     be a good thing to do.

  PART II

  Now we have to deal with encrypted and signed messages. The problem is that 
  c-client makes all its pointers point to "on disk" content, but since we 
  decrypted the data earlier, we have to make sure of two things. One is that we 
  saved that data (so we do not have to decrypt it again) and second that we can 
  use it.

  In order to save the data we use create_local_cache, so that we do not
  have to redecrypt the message. Once this is saved, c-client functions will
  find it and send it to us in mail_fetch_mime and mail_fetch_body.

 */

/*
 * Given a multipart body of type multipart/signed, attempt to verify it.
 * Returns non-zero if the body was changed.
 */
static int
do_detached_signature_verify(BODY *b, long msgno, char *section)
{
    PKCS7   *p7 = NULL;
    BIO	    *in = NULL;
    PART    *p;
    int	     result, modified_the_body = 0;
    unsigned long mimelen, bodylen;
    char     newSec[100], *mimetext, *bodytext;
    char    *what_we_did;

    dprint((9, "do_detached_signature_verify(msgno=%ld type=%d subtype=%s section=%s)", msgno, b->type, b->subtype ? b->subtype : "NULL", (section && *section) ? section : (section != NULL) ? "Top" : "NULL"));
    smime_init();

    snprintf(newSec, sizeof(newSec), "%s%s1", section ? section : "", (section && *section) ? "." : "");

    mimetext = mail_fetch_mime(ps_global->mail_stream, msgno, (char*) newSec, &mimelen, 0);

    if(mimetext)
       bodytext = mail_fetch_body (ps_global->mail_stream, msgno, (char*) newSec, &bodylen, 0);

    if (mimetext == NULL || bodytext ==  NULL)
       return modified_the_body;

    snprintf(newSec, sizeof(newSec), "%s%s2", section ? section : "", (section && *section) ? "." : "");

    if((p7 = get_pkcs7_from_part(msgno, newSec)) == NULL 
	|| (in = BIO_new(BIO_s_mem())) == NULL)
       return modified_the_body;

    (void) BIO_reset(in);
    BIO_write(in, mimetext, mimelen);
    BIO_write(in, bodytext, bodylen);

    /* Try compatibility with the past and check if this message
     * validates when we remove the last two characters. Silence
     * any failures first.
     */
    if(((result = do_signature_verify(p7, in, NULL, 1)) == 0)
	&& bodylen > 2 
	&& (strncmp(bodytext+bodylen-2,"\r\n", 2) == 0)){
	BUF_MEM *biobuf = NULL;

	BIO_get_mem_ptr(in, &biobuf);
	if(biobuf)
	  BUF_MEM_grow(biobuf, mimelen + bodylen - 2);
	result = do_signature_verify(p7, in, NULL, 0);
    }

    BIO_free(in);
    if(b->subtype)
	fs_give((void**) &b->subtype);

    b->subtype = cpystr(OUR_PKCS7_ENCLOSURE_SUBTYPE);
    b->encoding = ENC8BIT;

    if(b->description)
	fs_give ((void**) &b->description);

    what_we_did = result ? _("This message was cryptographically signed.") :
			   _("This message was cryptographically signed but the signature could not be verified.");

    b->description = cpystr(what_we_did);

    b->sparep = p7;

    p = b->nested.part;
	
    /* p is signed plaintext */
    if(p && p->next)
	mail_free_body_part(&p->next); /* hide the pkcs7 from the viewer */

    modified_the_body = 1;

    return modified_the_body;
}


PERSONAL_CERT *
find_certificate_matching_recip_info(PKCS7_RECIP_INFO *ri)
{
    PERSONAL_CERT *x = NULL;

    if(ps_global->smime){
	for(x = (PERSONAL_CERT *) ps_global->smime->personal_certs; x; x=x->next){
	    X509 *mine;

	    mine = x->cert;

	    if(!X509_NAME_cmp(ri->issuer_and_serial->issuer,mine->cert_info->issuer) &&
		    !ASN1_INTEGER_cmp(ri->issuer_and_serial->serial,mine->cert_info->serialNumber)){
		break;
	    }
	}
    }
    
    return x;
}


static PERSONAL_CERT *
find_certificate_matching_pkcs7(PKCS7 *p7)
{
    int i;
    STACK_OF(PKCS7_RECIP_INFO) *recips;
    PERSONAL_CERT *x = NULL;

    recips = p7->d.enveloped->recipientinfo;

    for(i=0; i<sk_PKCS7_RECIP_INFO_num(recips); i++){
        PKCS7_RECIP_INFO	*ri;

        ri = sk_PKCS7_RECIP_INFO_value(recips, i);

        if((x=find_certificate_matching_recip_info(ri))!=0){
            break;
        }
    }
    
    return x;
}

/* decrypt an encrypted file.
   Args: fp - the path to the encrypted file.
	 rv - a code that tells the caller what happened inside the function 
	 pcert - a personal certificate that was used to encrypt this file
   Returns the decoded text allocated in a char *, whose memory must be
   freed by caller 
 */

char *
decrypt_file(char *fp, int *rv, PERSONAL_CERT *pc)
{
  PKCS7 *p7 = NULL;
  char *text, *tmp, file_name[MAILTMPLEN];
  BIO *in = NULL, *out = NULL;
  EVP_PKEY *pkey = NULL;
  X509 *recip;
  int i, j;
  long unsigned int len;
  void *ret;
   
  smime_init();   
   
  if(pc == NULL || (text = read_file(fp, 0)) == NULL)
    return NULL;

  tmp = fs_get(strlen(text) + (strlen(text) << 6) + 1);
  for(j = 0, i = strlen("-----BEGIN PKCS7-----") + 1; text[i] != '\0'
                && text[i] != '-'; j++, i++)
     tmp[j] = text[i];
  tmp[j] = '\0';
  
  ret = rfc822_base64(tmp, strlen(tmp), &len);
  
  if((in = BIO_new_mem_buf((char *)ret, len)) != NULL){
     p7 = d2i_PKCS7_bio(in, NULL);
     BIO_free(in);
  }
  
  if (text) fs_give((void **)&text);
  if (ret)  fs_give((void **)&ret);
  
  if (rv) *rv = pc->key == NULL ? -1 : 1;

  out = BIO_new(BIO_s_mem());
  (void) BIO_reset(out);
  
  i = PKCS7_decrypt(p7, pc->key, pc->cert, out, 0);
       
  if(i == 0){
    q_status_message1(SM_ORDER, 1, 1, _("Error decrypting: %s"),
                              (char*) openssl_error_string());
    goto end;
  } 
   
  BIO_get_mem_data(out, &tmp);   
        
  text = cpystr(tmp);
  BIO_free(out);
    
end:
  PKCS7_free(p7);
  
  return text;
}

/*
 * Try to decode (decrypt or verify a signature) a PKCS7 body
 * Returns non-zero if something was changed.
 */
static int
do_decoding(BODY *b, long msgno, const char *section)
{
    int modified_the_body = 0;
    BIO *out = NULL;
    PKCS7 *p7 = NULL;
    X509 *recip = NULL;
    EVP_PKEY *key = NULL;
    PERSONAL_CERT 	*pcert = NULL;
    char    *what_we_did = "";
    char     null[1];

    dprint((9, "do_decoding(msgno=%ld type=%d subtype=%s section=%s)", msgno, b->type, b->subtype ? b->subtype : "NULL", (section && *section) ? section : (section != NULL) ? "Top" : "NULL"));
    null[0] = '\0';
    smime_init();

    /*
     *	Extract binary data from part to an in-memory store
     */

    if(b->sparep){		/* already done */
    	p7 = (PKCS7*) b->sparep;
    }
    else{

	p7 = get_pkcs7_from_part(msgno, section && *section ? section : "1");
	if(!p7){
            q_status_message1(SM_ORDER, 2, 2, "Couldn't load PKCS7 object: %s",
			     (char*) openssl_error_string());
            goto end;
	}

    	/*
    	 * Save the PKCS7 object for later dealings by the user interface.
	 * It will be cleaned up when the body is garbage collected.
	 */
	b->sparep = p7;
    }

    dprint((1, "type_is_signed = %d, type_is_enveloped = %d", PKCS7_type_is_signed(p7), PKCS7_type_is_enveloped(p7)));

    if(PKCS7_type_is_signed(p7)){
    	int 	sigok;
	
	out = BIO_new(BIO_s_mem());
	(void) BIO_reset(out);
	BIO_puts(out, "MIME-Version: 1.0\r\n"); /* needed so rfc822_parse_msg_full believes it's MIME */

    	sigok = do_signature_verify(p7, NULL, out, 0);

	what_we_did = sigok ? _("This message was cryptographically signed.") :
			      _("This message was cryptographically signed but the signature could not be verified.");

	/* make sure it's null terminated */
	BIO_write(out, null, 1);
    }
    else if(!PKCS7_type_is_enveloped(p7)){
        q_status_message(SM_ORDER, 1, 1, "PKCS7 object not recognised.");
        goto end;
    }
    else{ /* It *is* enveloped */
	int decrypt_result;

	what_we_did = _("This message was encrypted.");

	/* now need to find a cert that can decrypt this */
	pcert = find_certificate_matching_pkcs7(p7);

	if(!pcert){
            q_status_message(SM_ORDER, 3, 3, _("Couldn't find the certificate needed to decrypt."));
            goto end;
	}

	recip = pcert->cert;

	if(!load_private_key(pcert)
	   && ps_global->smime
	   && ps_global->smime->need_passphrase
	   && !ps_global->smime->already_auto_asked){
	    /* Couldn't load key with blank password, ask user */
	    ps_global->smime->already_auto_asked = 1;
	    if(pith_opt_smime_get_passphrase){
	      (*pith_opt_smime_get_passphrase)();
	      load_private_key(pcert);
	    }
	}

	key = pcert->key;
	if(!key)	
    	  goto end;

	out = BIO_new(BIO_s_mem());
	(void) BIO_reset(out);
	BIO_puts(out, "MIME-Version: 1.0\r\n");

	decrypt_result = PKCS7_decrypt(p7, key, recip, out, 0);

	if(F_OFF(F_REMEMBER_SMIME_PASSPHRASE,ps_global))
	  forget_private_keys();

	if(!decrypt_result){
            q_status_message1(SM_ORDER, 1, 1, _("Error decrypting: %s"),
			      (char*) openssl_error_string());
            goto end;
	}

	BIO_write(out, null, 1);
    }

    /*
     * We've now produced a flattened MIME object in BIO out.
     * It needs to be turned back into a BODY.
     */

    if(out){
        BODY	 *body;
        ENVELOPE *env;
        char	 *h = NULL;
        char	 *bstart;
        STRING	  s;
	BUF_MEM  *bptr = NULL;

	BIO_get_mem_ptr(out, &bptr);
	if(bptr)
          h = bptr->data;

        /* look for start of body */
        bstart = strstr(h, "\r\n\r\n");

        if(!bstart){
            q_status_message(SM_ORDER, 3, 3, _("Encrypted data couldn't be parsed."));
     	}
	else{
            bstart += 4; /* skip over CRLF*2 */

            INIT(&s, mail_string, bstart, strlen(bstart));
            rfc822_parse_msg_full(&env, &body, h, (bstart-h)-2, &s, BADHOST, 0, 0);
            mail_free_envelope(&env); /* Don't care about this */

	    body->mime.offset    = 0;
	    body->mime.text.size = 0;
            /*
             * Now convert original body (application/pkcs7-mime)
             * to a multipart body with one sub-part (the decrypted body).
	     * Note that the sub-part may also be multipart!
             */

            b->type = TYPEMULTIPART;
            if(b->subtype)
	      fs_give((void**) &b->subtype);

    	    /*
    	     * This subtype is used in mailview.c to annotate the display of
	     * encrypted or signed messages. We know for sure then that it's a PKCS7
	     * part because the sparep field is set to the PKCS7 object (see above).
	     */
	    b->subtype = cpystr(OUR_PKCS7_ENCLOSURE_SUBTYPE);
            b->encoding = ENC8BIT;

    	    if(b->description)
	      fs_give((void**) &b->description);

	    b->description = cpystr(what_we_did);

            if(b->disposition.type)
	      fs_give((void **) &b->disposition.type);

            if(b->contents.text.data)
	      fs_give((void **) &b->contents.text.data);

    	    if(b->parameter)
	      mail_free_body_parameter(&b->parameter);

            /* Allocate mem for the sub-part, and copy over the contents of our parsed body */
            b->nested.part = fs_get(sizeof(PART));
            b->nested.part->body = *body;
            b->nested.part->next = NULL;

            fs_give((void**) &body);

            /*
             * IMPORTANT BIT: set the body->contents.text.data elements to contain the decrypted
             * data. Otherwise, it'll try to load it from the original data. Eek.
             */
            create_local_cache(bstart-b->nested.part->body.mime.offset, bstart, &b->nested.part->body);

            modified_the_body = 1;
        }
    }

end:
    if(out)
      BIO_free(out);

    return modified_the_body;
}


/*
 * Recursively handle PKCS7 bodies in our message.
 *
 * Returns non-zero if some fiddling was done.
 */
static int
do_fiddle_smime_message(BODY *b, long msgno, char *section)
{
    int modified_the_body = 0;

    if(!b)
      return 0;

    dprint((9, "do_fiddle_smime_message(msgno=%ld type=%d subtype=%s section=%s)", msgno, b->type, b->subtype ? b->subtype : "NULL", (section && *section) ? section : (section != NULL) ? "Top" : "NULL"));

    if(is_pkcs7_body(b)){
    
        if(do_decoding(b, msgno, section)){
            /*
             *	b should now be a multipart message:
	     *   fiddle it too in case it's been multiply-encrypted!
             */

            /* fallthru */
            modified_the_body = 1;
        }
    }

    if(b->type==TYPEMULTIPART || MIME_MSG(b->type, b->subtype)){

        PART	*p;
        int		partNum;
        char	newSec[100];

	if(MIME_MULT_SIGNED(b->type, b->subtype)){


            /*
             * Ahah. We have a multipart signed entity.
	     *
	     * Multipart/signed
             *   part 1 (signed thing)
             *   part 2 (the pkcs7 signature)
	     *
	     * We're going to convert that to
	     *
	     * Multipart/OUR_PKCS7_ENCLOSURE_SUBTYPE
             *   part 1 (signed thing)
	     *   part 2 has been freed
	     *
	     * We also extract the signature from part 2 and save it
	     * in the multipart body->sparep, and we add a description
	     * in the multipart body->description.
	     *
	     *
	     * The results of a decrypted message will be similar. It
	     * will be
	     *
	     * Multipart/OUR_PKCS7_ENCLOSURE_SUBTYPE
             *   part 1 (decrypted thing)
             */

            modified_the_body += do_detached_signature_verify(b, msgno, section);
        }
	else if(MIME_MSG(b->type, b->subtype)){
	    modified_the_body += do_fiddle_smime_message(b->nested.msg->body, msgno, section);
	}
	else{

            for(p=b->nested.part,partNum=1; p; p=p->next,partNum++){

                /* Append part number to the section string */

                snprintf(newSec, sizeof(newSec), "%s%s%d", section, *section ? "." : "", partNum);

                modified_the_body += do_fiddle_smime_message(&p->body, msgno, newSec);
            }
        }
    }

    return modified_the_body;
}


/*
 * Fiddle a message in-place by decrypting/verifying S/MIME entities.
 * Returns non-zero if something was changed.
 */
int
fiddle_smime_message(BODY *b, long msgno)
{
    return do_fiddle_smime_message(b, msgno, "");
}


/********************************************************************************/


/*
 *  Output a string in a distinctive style
 */
void
gf_puts_uline(char *txt, gf_io_t pc)
{
    pc(TAG_EMBED); pc(TAG_BOLDON);
    gf_puts(txt, pc);
    pc(TAG_EMBED); pc(TAG_BOLDOFF);
}


STACK_OF(X509) *
get_chain_for_cert(X509 *cert, int *error)   
{
  STACK_OF(X509) *chain = NULL;
  X509_STORE_CTX *ctx;   
  X509 *x, *xtmp;
  int rc;       /* return code */
            
  *error = 0;
  ERR_clear_error();
  if((ctx = X509_STORE_CTX_new()) != NULL){
      X509_STORE_set_flags(s_cert_store, 0);
      if(!X509_STORE_CTX_init(ctx, s_cert_store, cert, NULL))
	*error   = X509_STORE_CTX_get_error(ctx);
      else if((chain = sk_X509_new_null()) != NULL){
	for(x = cert; ; x = xtmp){
	    sk_X509_push(chain, X509_dup(x));
	    rc = X509_STORE_CTX_get1_issuer(&xtmp, ctx, x);
	    if(rc < 0)
	      *error = 1;
	    if(rc <= 0)
	      break;
	    if(!X509_check_issued(xtmp, xtmp))
	       break;
	}
      }
      if(*error && chain != NULL)
	sk_X509_pop_free(chain, X509_free);
      X509_STORE_CTX_free(ctx);
  }
  return chain;
}


/*
 * Sign a message. Called from call_mailer in send.c.
 *
 * This takes the header for the outgoing message as well as a pointer
 * to the current body (which may be reallocated).
 */
int
sign_outgoing_message(METAENV *header, BODY **bodyP, int dont_detach)
{
    STORE_S *outs = NULL;
    BODY    *body = *bodyP;
    BODY    *newBody = NULL;
    PART    *p1 = NULL;
    PART    *p2 = NULL;
    PERSONAL_CERT   *pcert;
    BIO *in = NULL;
    BIO *out = NULL;
    PKCS7   *p7 = NULL;
    STACK_OF(X509) *chain;
    int result = 0, error;
    int flags = dont_detach ? 0 : PKCS7_DETACHED;

    dprint((9, "sign_outgoing_message()"));

    smime_init();

    /* Look for a private key matching the sender address... */
    
    pcert = match_personal_cert(header->env);
    
    if(!pcert){
        q_status_message(SM_ORDER, 3, 3, _("Couldn't find the certificate needed to sign."));
	goto end;
    }
    
    if(!load_private_key(pcert) && ps_global->smime && ps_global->smime->need_passphrase){
    	/* Couldn't load key with blank password, try again */
	if(pith_opt_smime_get_passphrase){
	  (*pith_opt_smime_get_passphrase)();
	  load_private_key(pcert);
	}
    }
    
    if(!pcert->key)
      goto end;
    
    in = body_to_bio(body);

    chain = get_chain_for_cert(pcert->cert, &error);

    p7 = PKCS7_sign(pcert->cert, pcert->key, chain, in, flags);

    if(F_OFF(F_REMEMBER_SMIME_PASSPHRASE,ps_global))
      forget_private_keys();

    if(chain)
      sk_X509_pop_free(chain, X509_free);

    if(!p7){
        q_status_message(SM_ORDER, 1, 1, _("Error creating signed object."));
	goto end;
    }

    if(error)
      q_status_message(SM_ORDER, 1, 1, _("Not all certificates needed to verify signature included in signed message"));
   
    outs = so_get(BioType, NULL, EDIT_ACCESS);
    out = bio_from_store(outs);

    i2d_PKCS7_bio(out, p7);
    (void) BIO_flush(out);

    so_seek(outs, 0, SEEK_SET);
    
    if((flags&PKCS7_DETACHED)==0){
   
    	/* the simple case: the signed data is in the pkcs7 object */
    
	newBody = mail_newbody();
    	
	setup_pkcs7_body_for_signature(newBody, "S/MIME Cryptographically Signed Message", "pkcs7-mime", "smime.p7m");

    	newBody->contents.text.data = (unsigned char *) outs;
	*bodyP = newBody;

	result = 1;
    }
    else{
    
	/*
	 * OK.
    	 * We have to create a new body as follows:
	 *
	 * multipart/signed; blah blah blah
	 *      reference to existing body
	 *
	 *	pkcs7 object
	 */

	newBody = mail_newbody();

	newBody->type = TYPEMULTIPART;
	newBody->subtype = cpystr("signed");
	newBody->encoding = ENC7BIT;

	set_parameter(&newBody->parameter, "protocol", "application/pkcs7-signature");
	set_parameter(&newBody->parameter, "micalg", "sha1");

	p1 = mail_newbody_part();
	p2 = mail_newbody_part();

    	/*
    	 * This is nasty. We're just copying the body in here,
	 * but since our newBody is freed at the end of call_mailer,
	 * we mustn't let this body (the original one) be freed twice.
	 */
	p1->body = *body; /* ARRGH. This is special cased at the end of call_mailer */

	p1->next = p2;

	setup_pkcs7_body_for_signature(&p2->body, "S/MIME Cryptographic Signature", "pkcs7-signature", "smime.p7s");
    	p2->body.contents.text.data = (unsigned char *) outs;

    	newBody->nested.part = p1;

	*bodyP = newBody;
	
	result = 1;
    }

end:

    PKCS7_free(p7);
    BIO_free(in);

    dprint((9, "sign_outgoing_message returns %d", result));
    return result;
}


SMIME_STUFF_S *
new_smime_struct(void)
{
    SMIME_STUFF_S *ret = NULL;

    ret = (SMIME_STUFF_S *) fs_get(sizeof(*ret));
    memset((void *) ret, 0, sizeof(*ret));
    ret->publictype = Nada;

    return ret;
}


static void
free_smime_struct(SMIME_STUFF_S **smime)
{
    if(smime && *smime){
	if((*smime)->passphrase_emailaddr){
	  int i;
	  for(i = 0; (*smime)->passphrase_emailaddr[i] != NULL; i++)
	     fs_give((void **) &(*smime)->passphrase_emailaddr[i]);
	  fs_give((void **) (*smime)->passphrase_emailaddr);
	}

	if((*smime)->publicpath)
	  fs_give((void **) &(*smime)->publicpath);

	if((*smime)->publiccertlist)
	  free_certlist(&(*smime)->publiccertlist);

	if((*smime)->cacertlist)
	  free_certlist(&(*smime)->cacertlist);

	if((*smime)->privatecertlist)
	  free_certlist(&(*smime)->privatecertlist);

	if((*smime)->publiccontent)
	  fs_give((void **) &(*smime)->publiccontent);

	if((*smime)->privatepath)
	  fs_give((void **) &(*smime)->privatepath);

	if((*smime)->personal_certs){
	    PERSONAL_CERT *pc;

	    pc = (PERSONAL_CERT *) (*smime)->personal_certs;
	    free_personal_certs(&pc);
	    (*smime)->personal_certs = NULL;
	}

#ifdef PASSFILE
	if((*smime)->pwdcert){
	    PERSONAL_CERT *pc;

	    pc = (PERSONAL_CERT *) (*smime)->pwdcert;
	    free_personal_certs(&pc);
	    (*smime)->pwdcert = NULL;
	}
#endif /* PASSFILE */

	if((*smime)->privatecontent)
	  fs_give((void **) &(*smime)->privatecontent);

	if((*smime)->capath)
	  fs_give((void **) &(*smime)->capath);

	if((*smime)->cacontent)
	  fs_give((void **) &(*smime)->cacontent);

	fs_give((void **) smime);
    }
}

#endif /* SMIME */