File: arc.c

package info (click to toggle)
openarc 1.0.0~beta3%2Bdfsg-1~exp4
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 1,752 kB
  • sloc: ansic: 12,537; xml: 1,455; sh: 292; makefile: 94
file content (3717 lines) | stat: -rw-r--r-- 78,955 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
/*
**  Copyright (c) 2009-2017, The Trusted Domain Project.  All rights reserved.
*/

#include "build-config.h"

/* for Solaris */
#ifndef _REENTRANT
# define _REENTRANT
#endif /* ! REENTRANT */

/* system includes */
#include <sys/param.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <arpa/nameser.h>
#ifdef HAVE_STDBOOL_H
# include <stdbool.h>
#endif /* HAVE_STDBOOL_H */
#include <netdb.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <assert.h>
#include <string.h>
#include <limits.h>
#include <unistd.h>
#include <pthread.h>
#include <resolv.h>

#ifdef __STDC__
# include <stdarg.h>
#else /* __STDC__ */
# include <varargs.h>
#endif /* _STDC_ */

/* OpenSSL includes */
#include <openssl/opensslv.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/sha.h>

/* libopenarc includes */
#include "arc-internal.h"
#include "arc-canon.h"
#include "arc-dns.h"
#include "arc-keys.h"
#include "arc-tables.h"
#include "arc-types.h"
#include "arc-util.h"
#include "arc.h"
#include "base64.h"

/* libbsd if found */
#ifdef USE_BSD_H
# include <bsd/string.h>
#endif /* USE_BSD_H */

/* libstrl if needed */
#ifdef USE_STRL_H
# include <strl.h>
#endif /* USE_STRL_H */

/* prototypes */
void arc_error __P((ARC_MESSAGE *, const char *, ...));

/* macros */
#define	ARC_STATE_INIT		0
#define	ARC_STATE_HEADER	1
#define	ARC_STATE_EOH		2
#define	ARC_STATE_BODY		3
#define	ARC_STATE_EOM		4
#define	ARC_STATE_UNUSABLE	99

#define	CRLF			"\r\n"

#define	BUFRSZ			1024
#define	DEFERRLEN		128
#define	DEFTIMEOUT		10

/* generic array size macro */
#define NITEMS(array) ((int)(sizeof(array)/sizeof(array[0])))

/* local definitions needed for DNS queries */
#define MAXPACKET		8192
#if defined(__RES) && (__RES >= 19940415)
# define RES_UNC_T		char *
#else /* __RES && __RES >= 19940415 */
# define RES_UNC_T		unsigned char *
#endif /* __RES && __RES >= 19940415 */

#ifndef T_AAAA
# define T_AAAA			28
#endif /* ! T_AAAA */

/* macros */
#define ARC_ISLWSP(x)  ((x) == 011 || (x) == 013 || (x) == 014 || (x) == 040)

#define	ARC_PHASH(x)		((x) - 32)

/*
**  ARC_ERROR -- log an error into a DKIM handle
**
**  Parameters:
**  	msg -- ARC message context in which this is performed
**  	format -- format to apply
**  	... -- arguments
**
**  Return value:
**  	None.
*/

void
arc_error(ARC_MESSAGE *msg, const char *format, ...)
{
	int flen;
	int saverr;
	u_char *new;
	va_list va;

	assert(msg != NULL);
	assert(format != NULL);

	saverr = errno;

	if (msg->arc_error == NULL)
	{
		msg->arc_error = ARC_MALLOC(DEFERRLEN);
		if (msg->arc_error == NULL)
		{
			errno = saverr;
			return;
		}
		msg->arc_errorlen = DEFERRLEN;
	}

	for (;;)
	{
		va_start(va, format);
		flen = vsnprintf((char *) msg->arc_error, msg->arc_errorlen,
		                 format, va);
		va_end(va);

		/* compensate for broken vsnprintf() implementations */
		if (flen == -1)
			flen = msg->arc_errorlen * 2;

		if (flen >= msg->arc_errorlen)
		{
			new = ARC_MALLOC(flen + 1);
			if (new == NULL)
			{
				errno = saverr;
				return;
			}

			ARC_FREE(msg->arc_error);
			msg->arc_error = new;
			msg->arc_errorlen = flen + 1;
		}
		else
		{
			break;
		}
	}

	errno = saverr;
}

/*
**  ARC_KEY_HASHOK -- return TRUE iff a signature's hash is in the approved
**                    list of hashes for a given key
**
**  Parameters:
**  	msg -- ARC_MESSAGE handle
**  	hashlist -- colon-separated approved hash list
**
**  Return value:
**  	TRUE iff a particular hash is in the approved list of hashes.
*/

static _Bool
arc_key_hashok(ARC_MESSAGE *msg, u_char *hashlist)
{
	int hashalg;
	u_char *x, *y;
	u_char tmp[BUFRSZ + 1];

	assert(msg != NULL);

	if (hashlist == NULL)
		return TRUE;

	x = NULL;
	memset(tmp, '\0', sizeof tmp);

	y = hashlist;
	for (;;)
	{
		if (*y == ':' || *y == '\0')
		{
			if (x != NULL)
			{
				strlcpy((char *) tmp, (char *) x, sizeof tmp);
				tmp[y - x] = '\0';
				hashalg = arc_name_to_code(hashes,
				                           (char *) tmp);
				if (hashalg == msg->arc_hashtype)
					return TRUE;
			}

			x = NULL;
		}
		else if (x == NULL)
		{
			x = y;
		}

		if (*y == '\0')
			return FALSE;
		y++;
	}

	/* NOTREACHED */
}

/*
**  ARC_KEY_HASHESOK -- return TRUE iff this key supports at least one
**                      hash method we know about (or doesn't specify)
**
**  Parameters:
**  	hashlist -- colon-separated list of hashes (or NULL)
**
**  Return value:
**  	TRUE iff this key supports at least one hash method we know about
**  	(or doesn't specify)
*/

static _Bool
arc_key_hashesok(ARC_LIB *lib, u_char *hashlist)
{
	u_char *x, *y;
	u_char tmp[BUFRSZ + 1];

	assert(lib != NULL);

	if (hashlist == NULL)
		return TRUE;

	x = NULL;
	memset(tmp, '\0', sizeof tmp);

	y = hashlist;
	for (;;)
	{
		if (*y == ':' || *y == '\0')
		{
			if (x != NULL)
			{
				int hashcode;

				strlcpy((char *) tmp, (char *) x, sizeof tmp);
				tmp[y - x] = '\0';

				hashcode = arc_name_to_code(hashes,
				                            (char *) tmp);

				if (hashcode != -1 &&
				    (hashcode != ARC_HASHTYPE_SHA256 ||
				     arc_libfeature(lib, ARC_FEATURE_SHA256)))
					return TRUE;
			}

			x = NULL;
		}
		else if (x == NULL)
		{
			x = y;
		}

		if (*y == '\0')
			return FALSE;
		y++;
	}

	/* NOTREACHED */
}

/*
**  ARC_GENAMSHDR -- generate a signature or seal header field
**
**  Parameters:
**  	arc -- ARC_MESSAGE handle
**  	dstr -- dstring to which to write
**  	delim -- delimiter
**  	seal -- true IFF a seal is being generated
**
**  Return value:
**  	Number of bytes written to "dstr", or <= 0 on error.
*/

static size_t
arc_genamshdr(ARC_MESSAGE *msg, struct arc_dstring *dstr, char *delim,
              _Bool seal)
{
	_Bool firsthdr;
	_Bool nosigner = FALSE;
	int n;
	int status;
	int delimlen;
	size_t hashlen;
	char *format;
	u_char *hash;
	struct arc_hdrfield *hdr;
	u_char tmp[ARC_MAXHEADER + 1];
	u_char b64hash[ARC_MAXHEADER + 1];

	assert(msg != NULL);
	assert(dstr != NULL);
	assert(delim != NULL);

	delimlen = strlen(delim);

	/*
	**  We need to generate an ARC-Message-Signature: header field template
	**  and include it in the canonicalization.
	*/

	/* basic required stuff */
	if (sizeof(msg->arc_timestamp) == sizeof(unsigned long long))
		format = "i=%u;%sa=%s;%sd=%s;%ss=%s;%st=%llu";
	else if (sizeof(msg->arc_timestamp) == sizeof(unsigned long))
		format = "i=%u;%sa=%s;%sd=%s;%ss=%s;%st=%lu";
	else
		format = "i=%u;%sa=%s;%sd=%s;%ss=%s;%st=%u";


	(void) arc_dstring_printf(dstr, format,
                                  msg->arc_nsets + 1, delim,
	                          arc_code_to_name(algorithms,
	                                           msg->arc_signalg), delim,
	                          msg->arc_domain, delim,
	                          msg->arc_selector, delim,
	                          msg->arc_timestamp);

	if (seal)
	{
		arc_dstring_printf(dstr, ";%scv=%s", delim,
	                           arc_code_to_name(chainstatus,
	                                            msg->arc_cstate));
	}
	else
	{
		arc_dstring_printf(dstr, ";%sc=%s/%s", delim,
	                           arc_code_to_name(canonicalizations,
	                                            msg->arc_canonhdr),
	                           arc_code_to_name(canonicalizations,
	                                            msg->arc_canonbody));
	}

	if (msg->arc_querymethods != NULL)
	{
		_Bool firstq = TRUE;
		struct arc_qmethod *q;

		for (q = msg->arc_querymethods; q != NULL; q = q->qm_next)
		{
			if (firstq)
			{
				arc_dstring_printf(dstr, ";%sq=%s", delim,
				                   q->qm_type);
			}
			else
			{
				arc_dstring_printf(dstr, ":%s", q->qm_type);
			}

			if (q->qm_options)
			{
				arc_dstring_printf(dstr, "/%s", q->qm_options);
			}

			firstq = FALSE;
		}
	}

	if (msg->arc_sigttl != 0)
	{
		uint64_t expire;

		expire = msg->arc_timestamp + msg->arc_sigttl;
		if (sizeof(expire) == sizeof(unsigned long long))
			arc_dstring_printf(dstr, ";%sx=%llu", delim, expire);
		else if (sizeof(expire) == sizeof(unsigned long))
			arc_dstring_printf(dstr, ";%sx=%lu", delim, expire);
		else
			arc_dstring_printf(dstr, ";%sx=%u", delim, expire);
	}

	if (msg->arc_xtags != NULL)
	{
		struct arc_xtag *x;

		for (x = msg->arc_xtags; x != NULL; x = x->xt_next)
		{
			arc_dstring_printf(dstr, ";%s%s=%s", delim,
			                    x->xt_tag, x->xt_value);
		}
	}

	if (!seal)
	{
		memset(b64hash, '\0', sizeof b64hash);

		status = arc_canon_closebody(msg);
		if (status != ARC_STAT_OK)
			return 0;

		status = arc_canon_getfinal(msg->arc_sign_bodycanon,
		                            &hash, &hashlen);
		if (status != ARC_STAT_OK)
		{
			arc_error(msg, "arc_canon_getfinal() failed");
			return (size_t) -1;
		}

		status = arc_base64_encode(hash, hashlen,
		                           b64hash, sizeof b64hash);
		arc_dstring_printf(dstr, ";%sbh=%s", delim, b64hash);

		/* l= */
		if (msg->arc_partial)
		{
			arc_dstring_printf(dstr, ";%sl=%lu", delim,
					   (u_long) msg->arc_sign_bodycanon->canon_wrote);
		}

		/* h= */
		firsthdr = TRUE;
		for (hdr = msg->arc_hhead; hdr != NULL; hdr = hdr->hdr_next)
		{
			if ((hdr->hdr_flags & ARC_HDR_SIGNED) == 0)
				continue;

			if (!firsthdr)
			{
				arc_dstring_cat1(dstr, ':');
			}
			else
			{
				arc_dstring_cat1(dstr, ';');
				arc_dstring_catn(dstr, (u_char *) delim,
				                 delimlen);
				arc_dstring_catn(dstr, (u_char *) "h=", 2);
			}

			firsthdr = FALSE;

			arc_dstring_catn(dstr, hdr->hdr_text, hdr->hdr_namelen);
		}

		if (msg->arc_library->arcl_oversignhdrs != NULL &&
		    msg->arc_library->arcl_oversignhdrs[0] != NULL)
		{
			_Bool wrote = FALSE;

			if (firsthdr)
			{
				arc_dstring_cat1(dstr, ';');
				arc_dstring_catn(dstr, delim, delimlen);
				arc_dstring_catn(dstr, "h=", 2);
			}
			else
			{
				arc_dstring_cat1(dstr, ':');
			}

			for (n = 0;
			     msg->arc_library->arcl_oversignhdrs[n] != NULL;
			     n++)
			{
				if (msg->arc_library->arcl_oversignhdrs[n][0] == '\0')
					continue;

				if (wrote)
					arc_dstring_cat1(dstr, ':');

				arc_dstring_cat(dstr, msg->arc_library->arcl_oversignhdrs[n]);

				wrote = TRUE;
			}
		}
	}

	/* and finally, an empty b= */
	arc_dstring_cat1(dstr, ';');
	arc_dstring_catn(dstr, (u_char *) delim, delimlen);
	arc_dstring_catn(dstr, (u_char *) "b=", 2);

	return arc_dstring_len(dstr);
}

/*
**  ARC_GETAMSHDR_D -- for signing operations, retrieve the complete signature
**                     header, doing so dynamically
**
**  Parameters:
**  	msg -- ARC_MESSAGE handle
**  	initial -- initial line width
**  	buf -- pointer to buffer containing the signature (returned)
**  	buflen -- number of bytes at "buf" (returned)
**  	seal -- true IFF we're generating a seal
**
**  Return value:
**  	An ARC_STAT_* constant.
**
**  Notes:
**  	Per RFC6376 Section 3.7, the signature header returned here does
**  	not contain a trailing CRLF.
*/

ARC_STAT
arc_getamshdr_d(ARC_MESSAGE *msg, size_t initial, u_char **buf, size_t *buflen,
                _Bool seal)
{
	size_t len;
	char *ctx;
	char *pv;
	struct arc_dstring *tmpbuf;

	assert(msg != NULL);
	assert(buf != NULL);
	assert(buflen != NULL);

#define	DELIMITER	"\001"

	tmpbuf = arc_dstring_new(msg, BUFRSZ, MAXBUFRSZ);
	if (tmpbuf == NULL)
	{
		arc_error(msg, "failed to allocate dynamic string");
		return ARC_STAT_NORESOURCE;
	}

	if (msg->arc_hdrbuf == NULL)
	{
		msg->arc_hdrbuf = arc_dstring_new(msg, BUFRSZ, MAXBUFRSZ);
		if (msg->arc_hdrbuf == NULL)
		{
			arc_dstring_free(tmpbuf);
			arc_error(msg, "failed to allocate dynamic string");
			return ARC_STAT_NORESOURCE;
		}
	}
	else
	{
		arc_dstring_blank(msg->arc_hdrbuf);
	}

	/* compute and extract the signature header */
	len = arc_genamshdr(msg, tmpbuf, DELIMITER, seal);
	if (len == 0)
	{
		arc_dstring_free(tmpbuf);
		return ARC_STAT_INVALID;
	}

	if (msg->arc_b64sig != NULL)
		arc_dstring_cat(tmpbuf, msg->arc_b64sig);

	if (msg->arc_margin == 0)
	{
		_Bool first = TRUE;

		for (pv = strtok_r((char *) arc_dstring_get(tmpbuf),
		                   DELIMITER, &ctx);
		     pv != NULL;
		     pv = strtok_r(NULL, DELIMITER, &ctx))
		{
			if (!first)
				arc_dstring_cat1(msg->arc_hdrbuf, ' ');

			arc_dstring_cat(msg->arc_hdrbuf, (u_char *) pv);

			first = FALSE;
		}
	}
	else
	{
		_Bool first = TRUE;
		_Bool forcewrap;
		int pvlen;
		int whichlen;
		char *p;
		char *q;
		char *end;
		char which[MAXTAGNAME + 1];

		len = initial;
		end = which + MAXTAGNAME;

		for (pv = strtok_r((char *) arc_dstring_get(tmpbuf),
		                   DELIMITER, &ctx);
		     pv != NULL;
		     pv = strtok_r(NULL, DELIMITER, &ctx))
		{
			for (p = pv, q = which; *p != '=' && q <= end; p++, q++)
			{
				*q = *p;
				*(q + 1) = '\0';
			}

			whichlen = strlen(which);

			/* force wrapping of "b=" ? */

			forcewrap = FALSE;
			if (msg->arc_keytype == ARC_KEYTYPE_RSA)
			{
				u_int siglen;

				siglen = BASE64SIZE(msg->arc_keybits / 8);
				if (strcmp(which, "b") == 0 &&
				    len + whichlen + siglen + 1 >= msg->arc_margin)
					forcewrap = TRUE;
			}

			pvlen = strlen(pv);

			if (len == 0 || first)
			{
				arc_dstring_catn(msg->arc_hdrbuf,
				                  (u_char *) pv,
				                  pvlen);
				len += pvlen;
				first = FALSE;
			}
			else if (forcewrap || len + pvlen > msg->arc_margin)
			{
				forcewrap = FALSE;
				arc_dstring_catn(msg->arc_hdrbuf,
				                  (u_char *) "\n\t", 2);
				len = 8;

				if (strcmp(which, "h") == 0)
				{			/* break at colons */
					_Bool ifirst = TRUE;
					int tmplen;
					char *tmp;
					char *ctx2;

					for (tmp = strtok_r(pv, ":", &ctx2);
					     tmp != NULL;
					     tmp = strtok_r(NULL, ":", &ctx2))
					{
						tmplen = strlen(tmp);

						if (ifirst)
						{
							arc_dstring_catn(msg->arc_hdrbuf,
							                 (u_char *) tmp,
							                 tmplen);
							len += tmplen;
							ifirst = FALSE;
						}
						else if (len + tmplen + 1 > msg->arc_margin)
						{
							arc_dstring_cat1(msg->arc_hdrbuf,
							                 ':');
							len += 1;
							arc_dstring_catn(msg->arc_hdrbuf,
							                 (u_char *) "\n\t ",
							                 3);
							len = 9;
							arc_dstring_catn(msg->arc_hdrbuf,
							                 (u_char *) tmp,
							                 tmplen);
							len += tmplen;
						}
						else
						{
							arc_dstring_cat1(msg->arc_hdrbuf,
							                  ':');
							len += 1;
							arc_dstring_catn(msg->arc_hdrbuf,
							                  (u_char *) tmp,
							                  tmplen);
							len += tmplen;
						}
					}

				}
				else if (strcmp(which, "b") == 0 ||
				         strcmp(which, "bh") == 0 ||
				         strcmp(which, "z") == 0)
				{			/* break at margins */
					int offset;
					int n;
					char *x;
					char *y;

					offset = whichlen + 1;

					arc_dstring_catn(msg->arc_hdrbuf,
					                 (u_char *) which,
					                 whichlen);
					arc_dstring_cat1(msg->arc_hdrbuf,
					                 '=');

					len += offset;

					x = pv + offset;
					y = pv + pvlen;

					while (x < y)
					{
						if (msg->arc_margin - len == 0)
						{
							arc_dstring_catn(msg->arc_hdrbuf,
							                  (u_char *) "\n\t ",
							                  3);
							len = 9;
						}

						n = MIN(msg->arc_margin - len,
						        y - x);
						arc_dstring_catn(msg->arc_hdrbuf,
						                  (u_char *) x,
						                  n);
						x += n;
						len += n;

					}
				}
				else
				{			/* break at delimiter */
					arc_dstring_catn(msg->arc_hdrbuf,
					                  (u_char *) pv,
					                  pvlen);
					len += pvlen;
				}
			}
			else
			{
				if (!first)
				{
					arc_dstring_cat1(msg->arc_hdrbuf,
					                  ' ');
					len += 1;
				}

				first = FALSE;
				arc_dstring_catn(msg->arc_hdrbuf,
				                  (u_char *) pv,
				                  pvlen);
				len += pvlen;
			}
		}
	}

	*buf = arc_dstring_get(msg->arc_hdrbuf);
	*buflen = arc_dstring_len(msg->arc_hdrbuf);

	arc_dstring_free(tmpbuf);

	return ARC_STAT_OK;
}

/*
**  ARC_INIT -- create a library instance
**
**  Parameters:
**  	None.
**
**  Return value:
**  	A new library instance.
*/

ARC_LIB *
arc_init(void)
{
	ARC_LIB *lib;

	lib = (ARC_LIB *) ARC_MALLOC(sizeof *lib);
	if (lib == NULL)
		return lib;

	memset(lib, '\0', sizeof *lib);
	lib->arcl_minkeysize = ARC_DEFAULT_MINKEYSIZE;
	lib->arcl_flags = ARC_LIBFLAGS_DEFAULT;

#define FEATURE_INDEX(x)	((x) / (8 * sizeof(u_int)))
#define FEATURE_OFFSET(x)	((x) % (8 * sizeof(u_int)))
#define FEATURE_ADD(lib,x)	(lib)->arcl_flist[FEATURE_INDEX((x))] |= (1 << FEATURE_OFFSET(x))

	lib->arcl_flsize = (FEATURE_INDEX(ARC_FEATURE_MAX)) + 1;
	lib->arcl_flist = (u_int *) ARC_MALLOC(sizeof(u_int) * lib->arcl_flsize);
	if (lib->arcl_flist == NULL)
	{
		ARC_FREE(lib);
		return NULL;
	}
	memset(lib->arcl_flist, '\0', sizeof(u_int) * lib->arcl_flsize);

	lib->arcl_dns_callback = NULL;
	lib->arcl_dns_service = NULL;
	lib->arcl_dnsinit_done = FALSE;
	lib->arcl_dns_init = arc_res_init;
	lib->arcl_dns_close = arc_res_close;
	lib->arcl_dns_start = arc_res_query;
	lib->arcl_dns_cancel = arc_res_cancel;
	lib->arcl_dns_waitreply = arc_res_waitreply;
	strncpy(lib->arcl_tmpdir, DEFTMPDIR, sizeof lib->arcl_tmpdir - 1);

#ifdef HAVE_SHA256
	FEATURE_ADD(lib, ARC_FEATURE_SHA256);
#endif /* HAVE_SHA256 */

	return lib;
}

/*
**  ARC_CLOSE -- terminate a library instance
**
**  Parameters:
**  	lib -- library instance to terminate
**
**  Return value:
**  	None.
*/

void
arc_close(ARC_LIB *lib)
{
	ARC_FREE(lib->arcl_flist);
	ARC_FREE(lib);
}

/*
**  ARC_GETERROR -- return any stored error string from within the ARC
**                  context handle
**
**  Parameters:
**  	msg -- ARC_MESSAGE handle from which to retrieve an error string
**
**  Return value:
**  	A pointer to the stored string, or NULL if none was stored.
*/

const char *
arc_geterror(ARC_MESSAGE *msg)
{
	assert(msg != NULL);

	return (const char *) msg->arc_error;
}

/*
**
**  ARC_OPTIONS -- get/set library options
**
**  Parameters:
**  	lib -- library instance of interest
**  	opt -- ARC_OP_GETOPT or ARC_OP_SETOPT
**  	arg -- ARC_OPTS_* constant
**  	val -- pointer to the new value (or NULL)
**  	valsz -- size of the thing at val
**
**  Return value:
**  	An ARC_STAT_* constant.
*/

ARC_STAT
arc_options(ARC_LIB *lib, int op, int arg, void *val, size_t valsz)
{
	assert(lib != NULL);
	assert(op == ARC_OP_GETOPT || op == ARC_OP_SETOPT);

	switch (arg)
	{
	  case ARC_OPTS_FLAGS:
		if (val == NULL)
			return ARC_STAT_INVALID;

		if (valsz != sizeof lib->arcl_flags)
			return ARC_STAT_INVALID;

		if (op == ARC_OP_GETOPT)
			memcpy(val, &lib->arcl_flags, valsz);
		else
			memcpy(&lib->arcl_flags, val, valsz);

		return ARC_STAT_OK;

	  case ARC_OPTS_TMPDIR:
		if (op == ARC_OP_GETOPT)
		{
			strlcpy((char *) val, (char *) lib->arcl_tmpdir,
			        valsz);
		}
		else if (val == NULL)
		{
			strlcpy((char *) lib->arcl_tmpdir, DEFTMPDIR,
			        sizeof lib->arcl_tmpdir);
		}
		else
		{
			strlcpy((char *) lib->arcl_tmpdir, (char *) val,
			        sizeof lib->arcl_tmpdir);
		}
		return ARC_STAT_OK;

	  case ARC_OPTS_FIXEDTIME:
		if (val == NULL)
			return ARC_STAT_INVALID;

		if (valsz != sizeof lib->arcl_fixedtime)
			return ARC_STAT_INVALID;

		if (op == ARC_OP_GETOPT)
			memcpy(val, &lib->arcl_fixedtime, valsz);
		else
			memcpy(&lib->arcl_fixedtime, val, valsz);

		return ARC_STAT_OK;

	  case ARC_OPTS_MINKEYSIZE:
		if (val == NULL)
			return ARC_STAT_INVALID;

		if (valsz != sizeof lib->arcl_minkeysize)
			return ARC_STAT_INVALID;

		if (op == ARC_OP_GETOPT)
			memcpy(val, &lib->arcl_minkeysize, valsz);
		else
			memcpy(&lib->arcl_minkeysize, val, valsz);

		return ARC_STAT_OK;

	  case ARC_OPTS_SIGNHDRS:
		if (valsz != sizeof(char **) || op == ARC_OP_GETOPT)
		{
			return ARC_STAT_INVALID;
		}
		else if (val == NULL)
		{
			if (lib->arcl_signre)
			{
				(void) regfree(&lib->arcl_hdrre);
				lib->arcl_signre = FALSE;
			}
		}
		else
		{
			int status;
			u_char **hdrs;
			char buf[BUFRSZ + 1];

			if (lib->arcl_signre)
			{
				(void) regfree(&lib->arcl_hdrre);
				lib->arcl_signre = FALSE;
			}
			memset(buf, '\0', sizeof buf);

			hdrs = (u_char **) val;
			(void) strlcpy(buf, "^(", sizeof buf);
			if (!arc_hdrlist((u_char *) buf, sizeof buf,
			                  hdrs, TRUE))
				return ARC_STAT_INVALID;

			if (strlcat(buf, ")$", sizeof buf) >= sizeof buf)
				return ARC_STAT_INVALID;

			status = regcomp(&lib->arcl_hdrre, buf,
			                 (REG_EXTENDED|REG_ICASE));
			if (status != 0)
				return ARC_STAT_INTERNAL;

			lib->arcl_signre = TRUE;
		}
		return ARC_STAT_OK;

	  case ARC_OPTS_OVERSIGNHDRS:
		if (valsz != sizeof lib->arcl_oversignhdrs)
			return ARC_STAT_INVALID;

		if (op == ARC_OP_GETOPT)
		{
			memcpy(val, &lib->arcl_oversignhdrs, valsz);
		}
		else if (val == NULL)
		{
			if (lib->arcl_oversignhdrs != NULL)
				arc_clobber_array((char **) lib->arcl_oversignhdrs);
			lib->arcl_oversignhdrs = NULL;
		}
		else
		{
			const char **tmp;

			tmp = arc_copy_array(val);
			if (tmp == NULL)
				return ARC_STAT_NORESOURCE;

			if (lib->arcl_oversignhdrs != NULL)
				arc_clobber_array((char **) lib->arcl_oversignhdrs);

			lib->arcl_oversignhdrs = (u_char **) tmp;
		}
		return ARC_STAT_OK;

	  default:
		assert(0);
	}
}

/*
**  ARC_GETSSLBUF -- retrieve SSL error buffer
**
**  Parameters:
**  	lib -- library handle
**
**  Return value:
**  	Pointer to the SSL buffer in the library handle.
*/

const char *
arc_getsslbuf(ARC_LIB *lib)
{
	return (const char *) arc_dstring_get(lib->arcl_sslerrbuf);
}

/*
**  ARC_CHECK_UINT -- check a parameter for a valid unsigned integer
**
**  Parameters:
**  	value -- value to check
**  	allow_zero -- if true, allow zero
**
**  Return value:
**  	TRUE iff the input value looks like a properly formed unsigned integer
** 	that is not zero.
*/

static _Bool
arc_check_uint(u_char *value)
{
	uint64_t tmp = 0;
	char *end;

	assert(value != NULL);

	errno = 0;

	if (value[0] == '-')
	{
		errno = ERANGE;
		tmp = -1;
	}
	else if (value[0] == '\0')
	{
		errno = EINVAL;
		tmp = -1;
	}
	else
	{
		tmp = strtoll((char *) value, &end, 10);
	}

	return !(tmp <= 0 || errno != 0 || *end != '\0');
}

/*
**  ARC_PARAM_GET -- get a parameter from a set
**
**  Parameters:
**  	set -- set to search
**  	param -- parameter to find
**
**  Return value:
**  	Pointer to the parameter requested, or NULL if it's not in the set.
*/

static u_char *
arc_param_get(ARC_KVSET *set, u_char *param)
{
	ARC_PLIST *plist;

	assert(set != NULL);
	assert(param != NULL);

	for (plist = set->set_plist[ARC_PHASH(param[0])];
	     plist != NULL;
	     plist = plist->plist_next)
	{
		if (strcmp((char *) plist->plist_param, (char *) param) == 0)
			return plist->plist_value;
	}

	return NULL;
}

/*
**  ARC_SET_FIRST -- return first set in a context
**
**  Parameters:
**  	msg -- ARC message context
**  	type -- type to find, or ARC_KVSETTYPE_ANY
**
**  Return value:
**  	Pointer to the first ARC_KVSET in the context, or NULL if none.
*/

static ARC_KVSET *
arc_set_first(ARC_MESSAGE *msg, arc_kvsettype_t type)
{
	ARC_KVSET *set;

	assert(msg != NULL);

	if (type == ARC_KVSETTYPE_ANY)
		return msg->arc_kvsethead;

	for (set = msg->arc_kvsethead; set != NULL; set = set->set_next)
	{
		if (set->set_type == type)
			return set;
	}

	return NULL;
}

/*
**  ARC_SET_NEXT -- return next set in a context
**
**  Parameters:
**  	set -- last set reported (i.e. starting point for this search)
**  	type -- type to find, or ARC_KVSETTYPE_ANY
**
**  Return value:
**  	Pointer to the next ARC_KVSET in the context, or NULL if none.
*/

static ARC_KVSET *
arc_set_next(ARC_KVSET *cur, arc_kvsettype_t type)
{
	ARC_KVSET *set;

	assert(cur != NULL);

	if (type == ARC_KVSETTYPE_ANY)
		return cur->set_next;

	for (set = cur->set_next; set != NULL; set = set->set_next)
	{
		if (set->set_type == type)
			return set;
	}

	return NULL;
}

/*
**  ARC_SET_TYPE -- return the type of a KVSET
**
**  Parameters:
**  	set -- set of interest
**
**  Return value:
**  	Its type field, one of the ARC_KVSETTYPE_* constants.
*/

static arc_kvsettype_t
arc_set_type(ARC_KVSET *set)
{
	return set->set_type;
}

/*
**  ARC_SET_UDATA -- return the udata of a KVSET
**
**  Parameters:
**  	set -- set of interest
**
**  Return value:
**  	Its udata, as provided to arc_process_set() originally.
*/

static void *
arc_set_udata(ARC_KVSET *set)
{
	return set->set_udata;
}

/*
**  ARC_KEY_SMTP -- return TRUE iff a parameter set defines an SMTP key
**
**  Parameters:
**  	set -- set to be checked
**
**  Return value:
**  	TRUE iff "set" contains an "s" parameter whose value is either
**  	"email" or "*".
*/

static _Bool
arc_key_smtp(ARC_KVSET *set)
{
	u_char *val;
	char *last;
	u_char *p;
	char buf[BUFRSZ + 1];

	assert(set != NULL);
	assert(set->set_type == ARC_KVSETTYPE_KEY);

	val = arc_param_get(set, (u_char * ) "s");

	if (val == NULL)
		return TRUE;

	strlcpy(buf, (char *) val, sizeof buf);

	for (p = (u_char *) strtok_r(buf, ":", &last);
	     p != NULL;
	     p = (u_char *) strtok_r(NULL, ":", &last))
	{
		if (strcmp((char *) p, "*") == 0 ||
		    strcasecmp((char *) p, "email") == 0)
			return TRUE;
	}

	return FALSE;
}

/*
**  ARC_ADD_PLIST -- add an entry to a parameter-value set
**
**  Parameters:
**  	msg -- ARC message context in which this is performed
**  	set -- set to modify
**   	param -- parameter
**  	value -- value
**  	force -- override existing value, if any
**  	ignore_dups -- drop duplicate submissions
**
**  Return value:
**  	0 on success, -1 on failure.
**
**  Notes:
**  	Data is not copied; a reference to it is stored.
*/

static int
arc_add_plist(ARC_MESSAGE *msg, ARC_KVSET *set, u_char *param, u_char *value,
              _Bool force, _Bool ignore_dups)
{
	ARC_PLIST *plist;

	assert(msg != NULL);
	assert(set != NULL);
	assert(param != NULL);
	assert(value != NULL);

	if (!isprint(param[0]))
	{
		arc_error(msg, "invalid parameter '%s'", param);
		return -1;
	}

	/* see if we have one already */
	for (plist = set->set_plist[ARC_PHASH(param[0])];
	     plist != NULL;
	     plist = plist->plist_next)
	{
		if (strcasecmp((char *) plist->plist_param,
		               (char *) param) == 0)
		{
			if (ignore_dups)
				return 0;

			arc_error(msg, "duplicate parameter '%s'", param);
			return -1;
		}
	}

	/* nope; make one and connect it */
	if (plist == NULL)
	{
		int n;

		plist = (ARC_PLIST *) ARC_MALLOC(sizeof(ARC_PLIST));
		if (plist == NULL)
		{
			arc_error(msg, "unable to allocate %d byte(s)",
			          sizeof(ARC_PLIST));
			return -1;
		}
		force = TRUE;
		n = ARC_PHASH(param[0]);
		plist->plist_next = set->set_plist[n];
		set->set_plist[n] = plist;
		plist->plist_param = param;
	}

	/* set the value if "force" was set (or this was a new entry) */
	if (force)
		plist->plist_value = value;

	return 0;
}

/*
**  ARC_PROCESS_SET -- process a parameter set, i.e. a string of the form
**                     param=value[; param=value]*
**
**  Parameters:
**  	msg -- ARC_MESSAGE context in which this is performed
**  	type -- an ARC_KVSETTYPE constant
**  	str -- string to be scanned
**  	len -- number of bytes available at "str"
**  	data -- opaque handle to store with the set
**  	out -- the set created by this function (returned)
**
**  Return value:
**  	An ARC_STAT constant.
*/

static ARC_STAT
arc_process_set(ARC_MESSAGE *msg, arc_kvsettype_t type, u_char *str,
                size_t len, void *data, ARC_KVSET **out)
{
	_Bool spaced;
	_Bool stop = FALSE;
	int state;
	int status;
	u_char *p;
	u_char *param;
	u_char *value;
	u_char *hcopy;
	char *ctx;
	ARC_KVSET *set;
	const char *settype;
	struct arc_plist *par;
	struct arc_plist *dup;

	assert(msg != NULL);
	assert(str != NULL);
	assert(type == ARC_KVSETTYPE_SEAL ||
	       type == ARC_KVSETTYPE_SIGNATURE ||
	       type == ARC_KVSETTYPE_AR ||
	       type == ARC_KVSETTYPE_KEY);

	param = NULL;
	value = NULL;
	state = 0;
	spaced = FALSE;

	hcopy = (u_char *) ARC_MALLOC(len + 1);
	if (hcopy == NULL)
	{
		arc_error(msg, "unable to allocate %d byte(s)", len + 1);
		return ARC_STAT_INTERNAL;
	}
	strlcpy((char *) hcopy, (char *) str, len + 1);

	set = (ARC_KVSET *) ARC_MALLOC(sizeof(ARC_KVSET));
	if (set == NULL)
	{
		ARC_FREE(hcopy);
		arc_error(msg, "unable to allocate %d byte(s)",
		          sizeof(ARC_KVSET));
		return ARC_STAT_INTERNAL;
	}
	memset(set, '\0', sizeof(ARC_KVSET));

	set->set_udata = data;
	set->set_type = type;
	settype = arc_code_to_name(settypes, type);

	if (msg->arc_kvsethead == NULL)
		msg->arc_kvsethead = set;
	else
		msg->arc_kvsettail->set_next = set;

	msg->arc_kvsettail = set;

	set->set_next = NULL;
	memset(&set->set_plist, '\0', sizeof set->set_plist);
	set->set_data = hcopy;
	set->set_bad = FALSE;

	for (p = hcopy; *p != '\0' && !stop; p++)
	{
		if (!isascii(*p) || (!isprint(*p) && !isspace(*p)))
		{
			arc_error(msg,
			          "invalid character (ASCII 0x%02x at offset %d) in %s data",
			          *p, p - hcopy, settype);
			set->set_bad = TRUE;
			return ARC_STAT_SYNTAX;
		}

		switch (state)
		{
		  case 0:				/* before param */
			if (isspace(*p))
			{
				continue;
			}
			else if (isalnum(*p))
			{
				param = p;
				state = 1;
			}
			else
			{
				arc_error(msg,
				          "syntax error in %s data (ASCII 0x%02x at offset %d)",
				          settype, *p, p - hcopy);
				set->set_bad = TRUE;
				return ARC_STAT_SYNTAX;
			}
			break;

		  case 1:				/* in param */
			if (isspace(*p))
			{
				spaced = TRUE;
			}
			else if (*p == '=')
			{
				*p = '\0';
				state = 2;
				spaced = FALSE;
			}
			else if (*p == ';' || spaced)
			{
				arc_error(msg,
				          "syntax error in %s data (ASCII 0x%02x at offset %d)",
				          settype, *p, p - hcopy);
				set->set_bad = TRUE;
				return ARC_STAT_SYNTAX;
			}
			break;

		  case 2:				/* before value */
			if (isspace(*p))
			{
				continue;
			}
			else if (*p == ';')		/* empty value */
			{
				*p = '\0';
				value = p;

				/* collapse the parameter */
				arc_collapse(param);

				/* create the ARC_PLIST entry */
				status = arc_add_plist(msg, set, param,
				                       value, TRUE, FALSE);
				if (status == -1)
				{
					set->set_bad = TRUE;
					return ARC_STAT_INTERNAL;
				}

				/* reset */
				param = NULL;
				value = NULL;
				state = 0;
			}
			else
			{
				value = p;
				state = 3;
			}
			break;

		  case 3:				/* in value */
			if (*p == ';')
			{
				*p = '\0';

				/* collapse the parameter and value */
				arc_collapse(param);
				arc_collapse(value);

				/* create the ARC_PLIST entry */
				status = arc_add_plist(msg, set, param,
				                       value, TRUE, FALSE);
				if (status == -1)
				{
					set->set_bad = TRUE;
					return ARC_STAT_INTERNAL;
				}

				/*
				**  Short-circuit ARC-Authentication-Results
				**  after one tag, which should be the "i="
				*/

				if (type == ARC_KVSETTYPE_AR)
					stop = TRUE;

				/* reset */
				param = NULL;
				value = NULL;
				state = 0;
			}
			break;

		  default:				/* shouldn't happen */
			assert(0);
		}
	}

	switch (state)
	{
	  case 0:					/* before param */
	  case 3:					/* in value */
		/* parse the data found, if any */
		if (value != NULL)
		{
			/* collapse the parameter and value */
			arc_collapse(param);
			arc_collapse(value);

			/* create the ARC_PLIST entry */
			status = arc_add_plist(msg, set, param, value,
			                       TRUE, FALSE);
			if (status == -1)
			{
				set->set_bad = TRUE;
				return ARC_STAT_INTERNAL;
			}
		}
		break;

	  case 2:					/* before value */
		/* create an empty ARC_PLIST entry */
		status = arc_add_plist(msg, set, param, (u_char *) "",
		                       TRUE, FALSE);
		if (status == -1)
		{
			set->set_bad = TRUE;
			return ARC_STAT_INTERNAL;
		}
		break;

	  case 1:					/* after param */
		arc_error(msg, "tag without value at end of %s data",
		          settype);
		set->set_bad = TRUE;
		return ARC_STAT_SYNTAX;

	  default:					/* shouldn't happen */
		assert(0);
	}

	/* load up defaults, assert requirements */
	switch (set->set_type)
	{
	  case ARC_KVSETTYPE_SIGNATURE:
		/* make sure required stuff is here */
		if (arc_param_get(set, (u_char *) "s") == NULL ||
		    arc_param_get(set, (u_char *) "h") == NULL ||
		    arc_param_get(set, (u_char *) "d") == NULL ||
		    arc_param_get(set, (u_char *) "b") == NULL ||
		    arc_param_get(set, (u_char *) "bh") == NULL ||
		    arc_param_get(set, (u_char *) "i") == NULL ||
		    arc_param_get(set, (u_char *) "c") == NULL ||
		    arc_param_get(set, (u_char *) "a") == NULL)
		{
			arc_error(msg, "missing parameter(s) in %s data",
			          settype);
			set->set_bad = TRUE;
			return ARC_STAT_SYNTAX;
		}

		/* make sure nothing got signed that shouldn't be */
		p = arc_param_get(set, (u_char *) "h");
		hcopy = ARC_STRDUP(p);
		if (hcopy == NULL)
		{
			len = strlen(p);
			arc_error(msg, "unable to allocate %d byte(s)",
			          len + 1);
			set->set_bad = TRUE;
			return ARC_STAT_INTERNAL;
		}

		for (p = strtok_r(hcopy, ":", &ctx);
		     p != NULL;
		     p = strtok_r(NULL, ":", &ctx))
		{
			if (strcasecmp(p, ARC_SEAL_HDRNAME) == 0)
			{
				arc_error(msg, "ARC-Message-Signature signs %s",
				          p);
				set->set_bad = TRUE;
				ARC_FREE(hcopy);
				return ARC_STAT_INTERNAL;
			}
		}
		ARC_FREE(hcopy);

		/* test validity of "t", "x", and "i" */
		p = arc_param_get(set, (u_char *) "t");
		if (p != NULL && !arc_check_uint(p))
		{
			arc_error(msg,
			          "invalid \"t\" value in %s data",
			          settype);
			set->set_bad = TRUE;
			return ARC_STAT_SYNTAX;
		}

		p = arc_param_get(set, (u_char *) "x");
		if (p != NULL && !arc_check_uint(p))
		{
			arc_error(msg,
			          "invalid \"x\" value in %s data",
			          settype);
			set->set_bad = TRUE;
			return ARC_STAT_SYNTAX;
		}

		if (!arc_check_uint(arc_param_get(set, (u_char *) "i")))
		{
			arc_error(msg,
			          "invalid \"i\" value in %s data",
			          settype);
			set->set_bad = TRUE;
			return ARC_STAT_SYNTAX;
		}

		/* default for "q" */
		status = arc_add_plist(msg, set, (u_char *) "q",
		                       (u_char *) "dns/txt", FALSE, TRUE);
		if (status == -1)
		{
			set->set_bad = TRUE;
			return ARC_STAT_INTERNAL;
		}

  		break;

	  case ARC_KVSETTYPE_KEY:
		status = arc_add_plist(msg, set, (u_char *) "k",
		                       (u_char *) "rsa", FALSE, TRUE);
		if (status == -1)
		{
			set->set_bad = TRUE;
			return ARC_STAT_INTERNAL;
		}

		break;

	  /* these have no defaults */
	  case ARC_KVSETTYPE_SEAL:
		/* make sure required stuff is here */
		if (arc_param_get(set, (u_char *) "cv") == NULL ||
		    arc_param_get(set, (u_char *) "i") == NULL ||
		    arc_param_get(set, (u_char *) "b") == NULL ||
		    arc_param_get(set, (u_char *) "s") == NULL ||
		    arc_param_get(set, (u_char *) "d") == NULL ||
		    arc_param_get(set, (u_char *) "a") == NULL)
		{
			arc_error(msg, "missing parameter(s) in %s data",
			          settype);
			set->set_bad = TRUE;
			return ARC_STAT_SYNTAX;
		}

		/* test validity of "i" */
		p = arc_param_get(set, (u_char *) "i");
		if (p != NULL && !arc_check_uint(p))
		{
			arc_error(msg,
			          "invalid \"i\" value in %s data",
			          settype);
			set->set_bad = TRUE;
			return ARC_STAT_SYNTAX;
		}

		break;

	  case ARC_KVSETTYPE_AR:
		if (arc_param_get(set, (u_char *) "i") == NULL)
		{
			arc_error(msg, "missing parameter(s) in %s data",
			          settype);
			set->set_bad = TRUE;
			return ARC_STAT_SYNTAX;
		}

		/* test validity of "i" */
		p = arc_param_get(set, (u_char *) "i");
		if (p != NULL && !arc_check_uint(p))
		{
			arc_error(msg,
			          "invalid \"i\" value in %s data",
			          settype);
			set->set_bad = TRUE;
			return ARC_STAT_SYNTAX;
		}

		break;
	}

	if (out != NULL)
		*out = set;

	return ARC_STAT_OK;
}

/*
**  ARC_GET_KEY -- acquire a public key used for verification
**
**  Parameters:
**  	msg -- ARC_MESSAGE handle
**  	test -- skip signature-specific validity checks
**
**  Return value:
**  	An ARC_STAT_* constant.
*/

ARC_STAT
arc_get_key(ARC_MESSAGE *msg, _Bool test)
{
	_Bool gotkey = FALSE;			/* key stored */
	_Bool gotset = FALSE;			/* set parsed */
	_Bool gotreply = FALSE;			/* reply received */
	int status;
	int c;
	struct arc_kvset *set = NULL;
	struct arc_kvset *nextset;
	unsigned char *p;
	unsigned char buf[BUFRSZ + 1];

	assert(msg != NULL);
	assert(msg->arc_selector != NULL);
	assert(msg->arc_domain != NULL);

	memset(buf, '\0', sizeof buf);

	/* use appropriate get method */
	switch (msg->arc_query)
	{
	  case ARC_QUERY_DNS:
		status = (int) arc_get_key_dns(msg, buf, sizeof buf);
		if (status != (int) ARC_STAT_OK)
			return (ARC_STAT) status;
		break;

	  case ARC_QUERY_FILE:
		status = (int) arc_get_key_file(msg, buf, sizeof buf);
		if (status != (int) ARC_STAT_OK)
			return (ARC_STAT) status;
		break;

	  default:
		assert(0);
	}

	/* decode the payload */
	if (buf[0] == '\0')
	{
		arc_error(msg, "empty key record");
		return ARC_STAT_SYNTAX;
	}

	status = arc_process_set(msg, ARC_KVSETTYPE_KEY, buf,
				 strlen((char *) buf), NULL, NULL);
	if (status != ARC_STAT_OK)
		return status;

	/* get the last key */
	set = arc_set_first(msg, ARC_KVSETTYPE_KEY);
	assert(set != NULL);
	for (;;)
	{
		nextset = arc_set_next(set, ARC_KVSETTYPE_KEY);
		if (nextset == NULL)
			break;
		set = nextset;
	}
	assert(set != NULL);

	/* verify key version first */
	p = arc_param_get(set, (u_char *) "v");
	if (p != NULL && strcmp((char *) p, DKIM_VERSION_KEY) != 0)
	{
		arc_error(msg, "invalid key version '%s'", p);
		return ARC_STAT_SYNTAX;
	}

	/* then make sure the hash type is something we can handle */
	p = arc_param_get(set, (u_char *) "h");
	if (!arc_key_hashesok(msg->arc_library, p))
	{
		arc_error(msg, "unknown hash '%s'", p);
		return ARC_STAT_SYNTAX;
	}
	/* ...and that this key is approved for this signature's hash */
	else if (!test && !arc_key_hashok(msg, p))
	{
		arc_error(msg, "signature-key hash mismatch");
		return ARC_STAT_CANTVRFY;
	}

	/* make sure it's a key designated for e-mail */
	if (!arc_key_smtp(set))
	{
		arc_error(msg, "key type mismatch");
		return ARC_STAT_CANTVRFY;
	}

	/* then key type */
	p = arc_param_get(set, (u_char *) "k");
	if (p == NULL)
	{
		arc_error(msg, "key type missing");
		return ARC_STAT_SYNTAX;
	}
	else if (arc_name_to_code(keytypes, (char *) p) == -1)
	{
		arc_error(msg, "unknown key type '%s'", p);
		return ARC_STAT_SYNTAX;
	}

	/* decode the key */
	msg->arc_b64key = arc_param_get(set, (u_char *) "p");
	if (msg->arc_b64key == NULL)
	{
		arc_error(msg, "key missing");
		return ARC_STAT_SYNTAX;
	}
	else if (msg->arc_b64key[0] == '\0')
	{
		return ARC_STAT_REVOKED;
	}
	msg->arc_b64keylen = strlen((char *) msg->arc_b64key);

	if (msg->arc_key != NULL)
		ARC_FREE(msg->arc_key);

	msg->arc_key = ARC_MALLOC(msg->arc_b64keylen);
	if (msg->arc_key == NULL)
	{
		arc_error(msg, "unable to allocate %d byte(s)",
		          msg->arc_b64keylen);
		return ARC_STAT_NORESOURCE;
	}

	status = arc_base64_decode(msg->arc_b64key, msg->arc_key,
	                           msg->arc_b64keylen);
	if (status < 0)
	{
		arc_error(msg, "key missing");
		return ARC_STAT_SYNTAX;
	}

	msg->arc_keylen = status;
	msg->arc_flags = 0;

	/* store key flags */
	p = arc_param_get(set, (u_char *) "t");
	if (p != NULL)
	{
		u_int flag;
		char *t;
		char *last;
		char tmp[BUFRSZ + 1];

		strlcpy(tmp, (char *) p, sizeof tmp);

		for (t = strtok_r(tmp, ":", &last);
		     t != NULL;
		     t = strtok_r(NULL, ":", &last))
		{
			flag = (u_int) arc_name_to_code(keyflags, t);
			if (flag != (u_int) -1)
				msg->arc_flags |= flag;
		}
	}

	return ARC_STAT_OK;
}

/*
**  ARC_VALIDATE_MSG -- validate a specific ARC-Message-Signature
**
**  Parameters:
**  	msg -- ARC message handle
**  	set -- ARC set number whose AMS should be validated (zero-based)
**  	verify -- verify or sign
**
**  Return value:
**  	An ARC_STAT_* constant.
*/

static ARC_STAT
arc_validate_msg(ARC_MESSAGE *msg, u_int setnum)
{
	int nid;
	int rsastat;
	size_t elen;
	size_t hhlen;
	size_t bhlen;
	size_t b64siglen;
	size_t b64bhlen;
	size_t siglen;
	size_t keysize;
	ARC_STAT status;
	u_char *alg;
	u_char *b64sig;
	u_char *b64bh;
	u_char *b64bhtag;
	void *hh;
	void *bh;
	void *sig;
	struct arc_set *set;
	struct arc_hdrfield *h;
	ARC_KVSET *kvset;
	BIO *keydata;
	EVP_PKEY *pkey;
	RSA *rsa;

	assert(msg != NULL);

	/* pull the (set-1)th ARC Set */
	set = &msg->arc_sets[setnum - 1];

	/*
	**  Validate the ARC-Message-Signature.
	*/

	/* finalize body canonicalizations */
	status = arc_canon_closebody(msg);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg, "arc_canon_closebody() failed");
		return status;
	}

	/*
	**  The stub AMS was generated, canonicalized, and hashed by
	**  arc_canon_runheaders().  It should also have been finalized.
	*/

	/* extract selector and domain */
	kvset = set->arcset_ams->hdr_data;
	msg->arc_selector = arc_param_get(kvset, "s");
	msg->arc_domain = arc_param_get(kvset, "d");

	/* get the key from DNS (or wherever) */
	status = arc_get_key(msg, FALSE);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg, "arc_get_key() failed");
		return status;
	}

	/* extract the header and body hashes from the message */
	status = arc_canon_gethashes(msg, &hh, &hhlen, &bh, &bhlen);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg, "arc_canon_gethashes() failed");
		return status;
	}

	/* extract the signature and body hash from the message */
	b64sig = arc_param_get(kvset, "b");
	b64bhtag = arc_param_get(kvset, "bh");
	b64siglen = strlen(b64sig);

	sig = ARC_MALLOC(b64siglen);
	if (sig == NULL)
	{
		arc_error(msg, "unable to allocate %d bytes", b64siglen);
		return ARC_STAT_INTERNAL;
	}
	siglen = arc_base64_decode(b64sig, sig, b64siglen);
	if (siglen < 0)
	{
		arc_error(msg, "unable to decode signature");
		return ARC_STAT_SYNTAX;
	}

	/* verify the signature against the header hash and the key */
	keydata = BIO_new_mem_buf(msg->arc_key, msg->arc_keylen);
	if (keydata == NULL)
	{
		arc_error(msg, "BIO_new_mem_buf() failed");
		ARC_FREE(sig);
		return ARC_STAT_INTERNAL;
	}

	pkey = d2i_PUBKEY_bio(keydata, NULL);
	if (pkey == NULL)
	{
		arc_error(msg, "d2i_PUBKEY_bio() failed");
		BIO_free(keydata);
		ARC_FREE(sig);
		return ARC_STAT_INTERNAL;
	}

	rsa = EVP_PKEY_get1_RSA(pkey);
	if (rsa == NULL)
	{
		arc_error(msg, "EVP_PKEY_get1_RSA() failed");
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		ARC_FREE(sig);
		return ARC_STAT_INTERNAL;
	}

	keysize = RSA_size(rsa);
	if (keysize * 8 < msg->arc_library->arcl_minkeysize)
	{
		arc_error(msg, "key size (%u) below minimum (%u)",
		          keysize, msg->arc_library->arcl_minkeysize);
		RSA_free(rsa);
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		ARC_FREE(sig);
		return ARC_STAT_CANTVRFY;
	}

	alg = arc_param_get(kvset, "a");
	nid = NID_sha1;
	if (alg != NULL && strcmp(alg, "rsa-sha256") == 0)
		nid = NID_sha256;

	rsastat = RSA_verify(nid, hh, hhlen, sig, siglen, rsa);

	RSA_free(rsa);
	EVP_PKEY_free(pkey);
	BIO_free(keydata);
	ARC_FREE(sig);

	if (rsastat != 1)
		return ARC_STAT_BADSIG;

	/* verify the signature's "bh" against our computed one */
	b64bhlen = BASE64SIZE(bhlen);
	b64bh = ARC_MALLOC(b64bhlen + 1);
	if (b64bh == NULL)
	{
		arc_error(msg, "unable to allocate %d bytes", b64bhlen + 1);
		return ARC_STAT_INTERNAL;
	}
	memset(b64bh, '\0', b64bhlen + 1);
	elen = arc_base64_encode(bh, bhlen, b64bh, b64bhlen);
	if (elen != strlen(b64bhtag) || strcmp(b64bh, b64bhtag) != 0)
	{
		ARC_FREE(b64bh);
		arc_error(msg, "body hash mismatch");
		return ARC_STAT_BADSIG;
	}

	ARC_FREE(b64bh);
	/* if we got this far, the signature was good */
	return ARC_STAT_OK;
}

/*
**  ARC_VALIDATE_SEAL -- validate a specific ARC seal
**
**  Parameters:
**  	msg -- ARC message handle
**  	set -- ARC set number to be validated (zero-based)
**
**  Return value:
**  	An ARC_STAT_* constant.
**
**  Side effects:
**  	Updates msg->arc_cstate.
*/

static ARC_STAT
arc_validate_seal(ARC_MESSAGE *msg, u_int setnum)
{
	int nid;
	int rsastat;
	ARC_STAT status;
	size_t shlen;
	size_t siglen;
	size_t b64siglen;
	u_char *b64sig;
	void *sh;
	void *sig;
	u_char *alg;
	struct arc_set *set;
	BIO *keydata;
	EVP_PKEY *pkey;
	RSA *rsa;
	ARC_KVSET *kvset;

	assert(msg != NULL);

	/* pull the (set-1)th ARC Set */
	set = &msg->arc_sets[setnum - 1];

	/* extract selector and domain */
	kvset = set->arcset_as->hdr_data;
	msg->arc_selector = arc_param_get(kvset, "s");
	msg->arc_domain = arc_param_get(kvset, "d");

	if (msg->arc_selector == NULL)
	{
		arc_error(msg, "seal at i=%u has no selector", setnum);
		return ARC_STAT_SYNTAX;
	}
	if (msg->arc_domain == NULL)
	{
		arc_error(msg, "seal at i=%u has no domain", setnum);
		return ARC_STAT_SYNTAX;
	}

	/* get the key from DNS (or wherever) */
	status = arc_get_key(msg, FALSE);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg, "arc_get_key() failed");
		return status;
	}

	/* extract the seal hash */
	status = arc_canon_getsealhash(msg, setnum, &sh, &shlen);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg, "arc_canon_getsealhashes() failed");
		return status;
	}

	/* extract the signature from the seal */
	b64sig = arc_param_get(kvset, "b");
	b64siglen = strlen(b64sig);
	sig = ARC_MALLOC(b64siglen);
	if (sig == NULL)
	{
		arc_error(msg, "unable to allocate %d bytes", b64siglen);
		return ARC_STAT_INTERNAL;
	}
	siglen = arc_base64_decode(b64sig, sig, b64siglen);
	if (siglen < 0)
	{
		arc_error(msg, "unable to decode signature");
		ARC_FREE(sig);
		return ARC_STAT_SYNTAX;
	}

	/* verify the signature against the header hash and the key */
	keydata = BIO_new_mem_buf(msg->arc_key, msg->arc_keylen);
	if (keydata == NULL)
	{
		arc_error(msg, "BIO_new_mem_buf() failed");
		ARC_FREE(sig);
		return ARC_STAT_INTERNAL;
	}

	pkey = d2i_PUBKEY_bio(keydata, NULL);
	if (pkey == NULL)
	{
		arc_error(msg, "d2i_PUBKEY_bio() failed");
		BIO_free(keydata);
		ARC_FREE(sig);
		return ARC_STAT_INTERNAL;
	}

	rsa = EVP_PKEY_get1_RSA(pkey);
	if (rsa == NULL)
	{
		arc_error(msg, "EVP_PKEY_get1_RSA() failed");
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		ARC_FREE(sig);
		return ARC_STAT_INTERNAL;
	}

	alg = arc_param_get(kvset, "a");
	nid = NID_sha1;
	if (alg != NULL && strcmp(alg, "rsa-sha256") == 0)
		nid = NID_sha256;

	rsastat = RSA_verify(nid, sh, shlen, sig, siglen, rsa);

	RSA_free(rsa);
	EVP_PKEY_free(pkey);
	BIO_free(keydata);
	ARC_FREE(sig);

	if (rsastat != 1)
	{
		msg->arc_cstate = ARC_CHAIN_FAIL;
		return ARC_STAT_BADSIG;
	}

	/* if we got this far, the signature was good */
	return ARC_STAT_OK;
}

/*
**  ARC_MESSAGE -- create a new message handle
**
**  Parameters:
**  	lib -- containing library instance
**  	canonhdr -- canonicalization mode to use on the header
**  	canonbody -- canonicalization mode to use on the body
**  	signalg -- signing algorithm
**  	err -- error string (returned)
**
**  Return value:
**  	A new message instance, or NULL on failure (and "err" is updated).
*/

ARC_MESSAGE *
arc_message(ARC_LIB *lib, arc_canon_t canonhdr, arc_canon_t canonbody,
            arc_alg_t signalg, arc_mode_t mode, const u_char **err)
{
	ARC_MESSAGE *msg;

	if (mode == 0)
	{
		if (err != NULL)
			*err = "no mode(s) selected";
		return NULL;
	}

	msg = (ARC_MESSAGE *) ARC_MALLOC(sizeof *msg);
	if (msg == NULL)
	{
		*err = strerror(errno);
	}
	else
	{
		memset(msg, '\0', sizeof *msg);

		msg->arc_library = lib;
		if (lib->arcl_fixedtime != 0)
			msg->arc_timestamp = lib->arcl_fixedtime;
		else
			(void) time(&msg->arc_timestamp);
	}

	msg->arc_canonhdr = canonhdr;
	msg->arc_canonbody = canonbody;
	msg->arc_signalg = signalg;
	msg->arc_margin = ARC_HDRMARGIN;
	msg->arc_mode = mode;

	return msg;
}

/*
**  ARC_FREE -- deallocate a message object
**
**  Parameters:
**  	msg -- message object to be destroyed
**
**  Return value:
**  	None.
*/

void
arc_free(ARC_MESSAGE *msg)
{
	struct arc_hdrfield *h;
	struct arc_hdrfield *tmp;

	if (msg->arc_error != NULL)
		ARC_FREE(msg->arc_error);

	h = msg->arc_hhead;
	while (h != NULL)
	{
		tmp = h->hdr_next;
		ARC_FREE(h->hdr_text);
		ARC_FREE(h);
		h = tmp;
	}

	h = msg->arc_sealhead;
	while (h != NULL)
	{
		tmp = h->hdr_next;
		ARC_FREE(h->hdr_text);
		ARC_FREE(h);
		h = tmp;
	}

	if (msg->arc_hdrlist != NULL)
	{
		ARC_FREE(msg->arc_hdrlist);
	}

	if (msg->arc_hdrbuf != NULL)
	{
		arc_dstring_free(msg->arc_hdrbuf);
	}

	while (msg->arc_kvsethead != NULL)
	{
		int i;
		ARC_KVSET *set = msg->arc_kvsethead;

		msg->arc_kvsethead = set->set_next;
		ARC_FREE(set->set_data);

		for (i = 0; i < NITEMS(set->set_plist); i++)
		{
			while (set->set_plist[i] != NULL)
			{
				ARC_PLIST *plist = set->set_plist[i];
				set->set_plist[i] = plist->plist_next;
				ARC_FREE(plist);
			}
		}

		ARC_FREE(set);
	}

	arc_canon_cleanup(msg);

	if (msg->arc_sealcanons != NULL)
		ARC_FREE(msg->arc_sealcanons);

	if (msg->arc_sets != NULL)
		ARC_FREE(msg->arc_sets);

	if (msg->arc_key != NULL)
		ARC_FREE(msg->arc_key);

	ARC_FREE(msg);
}

/*
**  ARC_PARSE_HEADER_FIELD -- parse a header field into an internal object
**
**  Parameters:
**  	msg -- message handle
**  	hdr -- full text of the header field
**  	hlen -- bytes to use at hname
**  	ret -- (returned) object, if it's good
**
**  Return value:
**  	An ARC_STAT_* constant.
*/

static ARC_STAT
arc_parse_header_field(ARC_MESSAGE *msg, u_char *hdr, size_t hlen,
                       struct arc_hdrfield **ret)
{
	u_char *colon;
	u_char *semicolon;
	u_char *end = NULL;
	size_t c;
	struct arc_hdrfield *h;

	assert(msg != NULL);
	assert(hdr != NULL);
	assert(hlen != 0);

	/* enforce RFC 5322, Section 2.2 */
	colon = NULL;
	for (c = 0; c < hlen; c++)
	{
		if (colon == NULL)
		{
			/*
			**  Field names are printable ASCII; also tolerate
			**  plain whitespace.
			*/

			if (hdr[c] < 32 || hdr[c] > 126)
				return ARC_STAT_SYNTAX;

			/* the colon is special */
			if (hdr[c] == ':')
				colon = &hdr[c];
		}
		else
		{
			/* field bodies are printable ASCII, SP, HT, CR, LF */
			if (!(hdr[c] != 9 ||  /* HT */
			      hdr[c] != 10 || /* LF */
			      hdr[c] != 13 || /* CR */
			      (hdr[c] >= 32 && hdr[c] <= 126) /* SP, print */ ))
				return ARC_STAT_SYNTAX;
		}
	}

	if (colon == NULL)
		return ARC_STAT_SYNTAX;

	end = colon;

	while (end > hdr && isascii(*(end - 1)) && isspace(*(end - 1)))
		end--;

	/* don't allow a field name containing a semicolon */
	semicolon = memchr(hdr, ';', hlen);
	if (semicolon != NULL && colon != NULL && semicolon < colon)
		return ARC_STAT_SYNTAX;

	h = ARC_MALLOC(sizeof *h);
	if (h == NULL)
	{
		arc_error(msg, "unable to allocate %d byte(s)", sizeof *h);
		return ARC_STAT_NORESOURCE;
	}

	if ((msg->arc_library->arcl_flags & ARC_LIBFLAGS_FIXCRLF) != 0)
	{
		u_char prev = '\0';
		u_char *p;
		u_char *q;
		struct arc_dstring *tmphdr;

		tmphdr = arc_dstring_new(msg, BUFRSZ, MAXBUFRSZ);
		if (tmphdr == NULL)
		{
			ARC_FREE(h);
			return ARC_STAT_NORESOURCE;
		}

		q = hdr + hlen;

		for (p = hdr; p < q && *p != '\0'; p++)
		{
			if (*p == '\n' && prev != '\r')		/* bare LF */
			{
				arc_dstring_catn(tmphdr, CRLF, 2);
			}
			else if (prev == '\r' && *p != '\n')	/* bare CR */
			{
				arc_dstring_cat1(tmphdr, '\n');
				arc_dstring_cat1(tmphdr, *p);
			}
			else					/* other */
			{
				arc_dstring_cat1(tmphdr, *p);
			}

			prev = *p;
		}

		if (prev == '\r')				/* end CR */
			arc_dstring_cat1(tmphdr, '\n');

		h->hdr_text = arc_strndup(arc_dstring_get(tmphdr),
		                          arc_dstring_len(tmphdr));

		arc_dstring_free(tmphdr);
	}
	else
	{
		h->hdr_text = arc_strndup(hdr, hlen);
	}

	if (h->hdr_text == NULL)
	{
		ARC_FREE(h);
		return ARC_STAT_NORESOURCE;
	}

	h->hdr_namelen = end != NULL ? end - hdr : hlen;
	h->hdr_textlen = hlen;
	if (colon == NULL)
		h->hdr_colon = NULL;
	else
		h->hdr_colon = h->hdr_text + (colon - hdr);
	h->hdr_flags = 0;
	h->hdr_next = NULL;

	*ret = h;

	return ARC_STAT_OK;
}

/*
**  ARC_HEADER_FIELD -- consume a header field
**
**  Parameters:
**  	msg -- message handle
**  	hdr -- full text of the header field
**  	hlen -- bytes to use at hname
**
**  Return value:
**  	An ARC_STAT_* constant.
*/

ARC_STAT
arc_header_field(ARC_MESSAGE *msg, u_char *hdr, size_t hlen)
{
	ARC_STAT status;
	struct arc_hdrfield *h;

	assert(msg != NULL);
	assert(hdr != NULL);
	assert(hlen != 0);

	if (msg->arc_state > ARC_STATE_HEADER)
		return ARC_STAT_INVALID;
	msg->arc_state = ARC_STATE_HEADER;

	status = arc_parse_header_field(msg, hdr, hlen, &h);
	if (status != ARC_STAT_OK)
		return status;

	if (msg->arc_hhead == NULL)
	{
		msg->arc_hhead = h;
		msg->arc_htail = h;
	}
	else
	{
		msg->arc_htail->hdr_next = h;
		msg->arc_htail = h;
	}

	msg->arc_hdrcnt++;

	return ARC_STAT_OK;
}

/*
**  ARC_EOH_VERIFY -- verifying side of the end-of-header handler
**
**  Parameters:
**  	msg -- message handle
**
**  Return value:
**  	An ARC_STAT_* constant.
*/

ARC_STAT
arc_eoh_verify(ARC_MESSAGE *msg)
{
	u_int c;
	u_int n;
	u_int hashtype;
	ARC_STAT status;
	struct arc_hdrfield *h;
	u_char *htag;
	arc_canon_t hdr_canon;
	arc_canon_t body_canon;

	/* if the chain is dead, nothing to do here */
	if (msg->arc_cstate == ARC_CHAIN_FAIL)
		return ARC_STAT_OK;

	/*
	**  Request specific canonicalizations we want to run.
	*/

	h = NULL;
	htag = NULL;
	if (msg->arc_nsets > 0)
	{
		u_char *c;

		/* headers, validation */
		h = msg->arc_sets[msg->arc_nsets - 1].arcset_ams;
		htag = arc_param_get(h->hdr_data, "h");
		if (strcmp(arc_param_get(h->hdr_data, "a"), "rsa-sha1") == 0)
			hashtype = ARC_HASHTYPE_SHA1;
		else
			hashtype = ARC_HASHTYPE_SHA256;

 		c = arc_param_get(h->hdr_data, "c");
		if (c != NULL)
		{
			status = arc_parse_canon_t(c, &hdr_canon, &body_canon);
			if (status != ARC_STAT_OK)
			{
				arc_error(msg,
					  "failed to parse header c= tag with value %s",
					  c);
				hdr_canon = ARC_CANON_SIMPLE;
				body_canon = ARC_CANON_SIMPLE;
				msg->arc_cstate = ARC_CHAIN_FAIL;
			}
		}
		else
		{
			hdr_canon = ARC_CANON_SIMPLE;
			body_canon = ARC_CANON_SIMPLE;
		}

		status = arc_add_canon(msg, ARC_CANONTYPE_HEADER, hdr_canon,
		                       hashtype, htag, h, (ssize_t) -1,
		                       &msg->arc_valid_hdrcanon);

		if (status != ARC_STAT_OK)
		{
			arc_error(msg,
			          "failed to initialize header canonicalization object");
			return status;
		}

		/* body, validation */
		status = arc_add_canon(msg, ARC_CANONTYPE_BODY, body_canon,
		                       hashtype, NULL, NULL, (ssize_t) -1,
		                       &msg->arc_valid_bodycanon);

		if (status != ARC_STAT_OK)
		{
			arc_error(msg,
			          "failed to initialize body canonicalization object");
			return status;
		}
	}

	/* sets already in the chain, validation */
	if (msg->arc_nsets > 0)
	{
		msg->arc_sealcanons = ARC_MALLOC(msg->arc_nsets * sizeof(ARC_CANON *));
		if (msg->arc_sealcanons == NULL)
		{
			arc_error(msg,
		          	"failed to allocate memory for canonicalizations");
			return status;
		}

		for (n = 0; n < msg->arc_nsets; n++)
		{
			h = msg->arc_sets[n].arcset_as;

			int hashtype;
			if (strcmp(arc_param_get(h->hdr_data, "a"), "rsa-sha1") == 0)
				hashtype = ARC_HASHTYPE_SHA1;
			else
				hashtype = ARC_HASHTYPE_SHA256;

			status = arc_add_canon(msg,
			                       ARC_CANONTYPE_SEAL,
			                       ARC_CANON_RELAXED,
			                       hashtype,
			                       NULL,
			                       h,
			                       (ssize_t) -1,
			                       &msg->arc_sealcanons[n]);
			if (status != ARC_STAT_OK)
			{
				arc_error(msg,
					"failed to initialize seal canonicalization object");
				return status;
			}
		}
	}

	return ARC_STAT_OK;
}

/*
**  ARC_EOH_SIGN -- signing side of the end-of-header handler
**
**  Parameters:
**  	msg -- message handle
**
**  Return value:
**  	An ARC_STAT_* constant.
*/

ARC_STAT
arc_eoh_sign(ARC_MESSAGE *msg)
{
	ARC_STAT status;

	/* headers, signing */
	status = arc_add_canon(msg, ARC_CANONTYPE_AMS, msg->arc_canonhdr,
	                       msg->arc_signalg, NULL, NULL, (ssize_t) -1,
	                       &msg->arc_sign_hdrcanon);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg,
		          "failed to initialize header canonicalization object");
		return status;
	}

	/* all sets, for the next chain, signing */
	status = arc_add_canon(msg,
	                       ARC_CANONTYPE_SEAL,
	                       ARC_CANON_RELAXED,
	                       msg->arc_signalg,
	                       NULL,
	                       NULL,
	                       (ssize_t) -1,
	                       &msg->arc_sealcanon);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg,
			"failed to initialize seal canonicalization object");
		return status;
	}

	/* body, signing */
	status = arc_add_canon(msg, ARC_CANONTYPE_BODY, msg->arc_canonbody,
	                       msg->arc_signalg, NULL, NULL, (ssize_t) -1,
	                       &msg->arc_sign_bodycanon);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg,
		          "failed to initialize body canonicalization object");
		return status;
	}

	return ARC_STAT_OK;
}

/*
**  ARC_EOH -- declare no more header fields are coming
**
**  Parameters:
**  	msg -- message handle
**
**  Return value:
**  	An ARC_STAT_* constant.
*/

ARC_STAT
arc_eoh(ARC_MESSAGE *msg)
{
	_Bool keep;
	u_int c;
	u_int n;
	u_int nsets = 0;
	arc_kvsettype_t type;
	ARC_STAT status;
	u_char *inst;
	char *p;
	struct arc_hdrfield *h;
	ARC_KVSET *set;

	assert(msg != NULL);

	if (msg->arc_state >= ARC_STATE_EOH)
		return ARC_STAT_INVALID;
	msg->arc_state = ARC_STATE_EOH;

	/*
	**  Process all the header fields that make up ARC sets.
	*/

	for (h = msg->arc_hhead; h != NULL; h = h->hdr_next)
	{
		char hnbuf[ARC_MAXHEADER + 1];

		memset(hnbuf, '\0', sizeof hnbuf);
		strncpy(hnbuf, h->hdr_text, h->hdr_namelen);
		if (strcasecmp(hnbuf, ARC_AR_HDRNAME) == 0 ||
		    strcasecmp(hnbuf, ARC_MSGSIG_HDRNAME) == 0 ||
		    strcasecmp(hnbuf, ARC_SEAL_HDRNAME) == 0)
		{
			arc_kvsettype_t kvtype;

			kvtype = arc_name_to_code(archdrnames, hnbuf);
			status = arc_process_set(msg, kvtype,
			                         h->hdr_colon + 1,
			                         h->hdr_textlen - h->hdr_namelen - 1,
			                         h,
			                         &set);
			if (status != ARC_STAT_OK)
				msg->arc_cstate = ARC_CHAIN_FAIL;
			h->hdr_data = set;
		}
	}

	/*
	**  Ensure all sets are complete.
	*/

	/* find the highest instance number we've got */
	for (set = arc_set_first(msg, ARC_KVSETTYPE_ANY);
             set != NULL;
             set = arc_set_next(set, ARC_KVSETTYPE_ANY))
	{
		inst = arc_param_get(set, "i");
		if (inst != NULL)
		{
			n = strtoul(inst, NULL, 10);
			nsets = MAX(n, nsets);
		}
	}

	msg->arc_nsets = nsets;

	/* build up the array of ARC sets, for use later */
	if (nsets > 0)
	{
		msg->arc_sets = ARC_MALLOC(sizeof(struct arc_set) * nsets);
		if (msg->arc_sets == NULL)
			return ARC_STAT_NORESOURCE;
		memset(msg->arc_sets, '\0', sizeof(struct arc_set) * nsets);
	}

	for (set = arc_set_first(msg, ARC_KVSETTYPE_ANY);
             set != NULL;
             set = arc_set_next(set, ARC_KVSETTYPE_ANY))
	{
		type = arc_set_type(set);

		/* if i= is missing or bogus, just skip it */
		inst = arc_param_get(set, "i");
		if (inst == NULL || !arc_check_uint(inst))
			continue;
		n = strtoul(inst, &p, 10);

		switch (type)
		{
		  case ARC_KVSETTYPE_AR:
			if (msg->arc_sets[n - 1].arcset_aar != NULL)
			{
				arc_error(msg,
				          "multiple ARC auth results at instance %u",
				          n);
				msg->arc_cstate = ARC_CHAIN_FAIL;
				break;
			}

			msg->arc_sets[n - 1].arcset_aar = arc_set_udata(set);
			break;

		  case ARC_KVSETTYPE_SIGNATURE:
			if (msg->arc_sets[n - 1].arcset_ams != NULL)
			{
				arc_error(msg,
				          "multiple ARC signatures at instance %u",
				          n);
				msg->arc_cstate = ARC_CHAIN_FAIL;
				break;
			}

			msg->arc_sets[n - 1].arcset_ams = arc_set_udata(set);
			break;

		  case ARC_KVSETTYPE_SEAL:
			if (msg->arc_sets[n - 1].arcset_as != NULL)
			{
				arc_error(msg,
				          "multiple ARC seals at instance %u",
				          n);
				msg->arc_cstate = ARC_CHAIN_FAIL;
				break;
			}

			msg->arc_sets[n - 1].arcset_as = arc_set_udata(set);
			break;
		}
	}

	/* look for invalid stuff */
	for (c = 0; c < nsets; c++)
	{
		if (msg->arc_sets[c].arcset_aar == NULL ||
		    msg->arc_sets[c].arcset_ams == NULL ||
		    msg->arc_sets[c].arcset_as == NULL)
		{
			arc_error(msg,
			          "missing or incomplete ARC set at instance %u",
			          c);
			msg->arc_cstate = ARC_CHAIN_FAIL;
			break;
		}
	}

	/*
	**  Always call arc_eoh_verify() because the hashes it sets up are
	**  needed in either mode.
	*/

	status = arc_eoh_verify(msg);
	if (status != ARC_STAT_OK)
		return status;

	/* only call the signing side stuff when we're going to make a seal */
	if ((msg->arc_mode & ARC_MODE_SIGN) != 0)
	{
		status = arc_eoh_sign(msg);
		if (status != ARC_STAT_OK)
			return status;
	}

	/* initialize the canonicalizations */
	keep = ((msg->arc_library->arcl_flags & ARC_LIBFLAGS_KEEPFILES) != 0);
	status = arc_canon_init(msg, keep, keep);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg, "arc_canon_init() failed");
		return ARC_STAT_SYNTAX;
	}

	/* process everything */
	status = arc_canon_runheaders(msg);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg, "arc_canon_runheaders() failed");
		return ARC_STAT_SYNTAX;
	}

	if ((msg->arc_mode & ARC_MODE_VERIFY) != 0 &&
	    msg->arc_cstate != ARC_CHAIN_FAIL)
	{
		status = arc_canon_runheaders_seal(msg);
		if (status != ARC_STAT_OK)
		{
			arc_error(msg, "arc_canon_runheaders_seal() failed");
			return ARC_STAT_SYNTAX;
		}
	}

	return ARC_STAT_OK;
}

/*
**  ARC_BODY -- process a body chunk
**
**  Parameters:
**  	msg -- an ARC message handle
**  	buf -- the body chunk to be processed, in canonical format
**  	len -- number of bytes to process starting at "buf"
**
**  Return value:
**  	A ARC_STAT_* constant.
*/

ARC_STAT
arc_body(ARC_MESSAGE *msg, u_char *buf, size_t len)
{
	assert(msg != NULL);
	assert(buf != NULL);

	if (msg->arc_state == ARC_CHAIN_FAIL)
		return ARC_STAT_OK;

	if (msg->arc_state > ARC_STATE_BODY ||
	    msg->arc_state < ARC_STATE_EOH)
		return ARC_STAT_INVALID;
	msg->arc_state = ARC_STATE_BODY;

	return arc_canon_bodychunk(msg, buf, len);
}

/*
**  ARC_EOM -- declare end of message
**
**  Parameters:
**  	msg -- message handle
**
**  Return value:
**  	An ARC_STAT_* constant.
*/

ARC_STAT
arc_eom(ARC_MESSAGE *msg)
{
	/* nothing to do outside of verify mode */
	if ((msg->arc_mode & ARC_MODE_VERIFY) == 0)
		return ARC_STAT_OK;

	/* nothing to do if the chain has been expressly failed */
	if (msg->arc_state == ARC_CHAIN_FAIL)
		return ARC_STAT_OK;

	/*
	**  Verify the existing chain, if any.
	*/

	if (msg->arc_nsets == 0)
	{
		msg->arc_cstate = ARC_CHAIN_NONE;
	}
	else if (msg->arc_cstate != ARC_CHAIN_FAIL)
	{
		/* validate the final ARC-Message-Signature */
		if (arc_validate_msg(msg, msg->arc_nsets) != ARC_STAT_OK)
		{
			msg->arc_cstate = ARC_CHAIN_FAIL;
		}
		else
		{
			u_int set;
			u_char *inst;
			u_char *cv;
			ARC_KVSET *kvset;

			msg->arc_cstate = ARC_CHAIN_PASS;
			for (set = msg->arc_nsets; set > 0; set--)
			{
				for (kvset = arc_set_first(msg, ARC_KVSETTYPE_SEAL);
				     kvset != NULL;
				     kvset = arc_set_next(kvset, ARC_KVSETTYPE_SEAL))
				{
					inst = arc_param_get(kvset, "i");
					if (atoi(inst) == set)
						break;
				}

				cv = arc_param_get(kvset, "cv");
				if (!((set == 1 && strcasecmp(cv, "none") == 0) ||
				     (set != 1 && strcasecmp(cv, "pass") == 0)))
				{
					/* the chain has already failed */
					msg->arc_cstate = ARC_CHAIN_FAIL;

					/* note that it failed inbound */
					msg->arc_infail = TRUE;

					break;
				}

				if (msg->arc_cstate != ARC_CHAIN_FAIL &&
				    arc_validate_seal(msg, set) != ARC_STAT_OK)
				{
					msg->arc_cstate = ARC_CHAIN_FAIL;
					break;
				}
			}
		}
	}

	return ARC_STAT_OK;
}

/*
**  ARC_SET_CV -- force the chain state
**
**  Parameters:
**  	msg -- ARC_MESSAGE object
**  	cv -- chain state
**
**  Return value:
**  	None.
*/

void
arc_set_cv(ARC_MESSAGE *msg, ARC_CHAIN cv)
{
	assert(msg != NULL);
	assert(cv == ARC_CHAIN_UNKNOWN ||
	       cv == ARC_CHAIN_NONE ||
	       cv == ARC_CHAIN_FAIL ||
	       cv == ARC_CHAIN_PASS);

	msg->arc_cstate = cv;
}

/*
**  ARC_GETSEAL -- get the "seal" to apply to this message
**
**  Parameters:
**  	msg -- ARC_MESSAGE object
**  	seal -- seal to apply (returned)
**      authservid -- authservid to use when generating the seal
**      selector -- selector name
**      domain -- domain name
**      key -- secret key, printable
**      keylen -- key length
**  	ar -- Authentication-Results to be enshrined
**
**  Return value:
**  	An ARC_STAT_* constant.
*/

ARC_STAT
arc_getseal(ARC_MESSAGE *msg, ARC_HDRFIELD **seal, char *authservid,
            char *selector, char *domain, u_char *key, size_t keylen,
            u_char *ar)
{
	int rstatus;
	int siglen;
	int nid;
	u_int set;
	ARC_STAT status;
	size_t diglen;
	size_t keysize;
	size_t len;
	size_t b64siglen;
	u_char *sighdr;
	u_char *digest;
	u_char *sigout;
	u_char *b64sig;
	ARC_HDRFIELD *h;
	ARC_HDRFIELD hdr;
	struct arc_dstring *dstr;
	BIO *keydata;
	EVP_PKEY *pkey;
	RSA *rsa;

	assert(msg != NULL);
	assert(seal != NULL);
	assert(authservid != NULL);
	assert(selector != NULL);
	assert(domain != NULL);
	assert(key != NULL);
	assert(keylen > 0);

	/* if the chain arrived already failed, don't add anything */
	if (msg->arc_infail)
	{
		*seal = NULL;
		return ARC_STAT_OK;
	}

	/* copy required stuff */
	msg->arc_domain = domain;
	msg->arc_selector = selector;
	msg->arc_authservid = authservid;

	/* load the key */
	keydata = BIO_new_mem_buf(key, keylen);
	if (keydata == NULL)
	{
		arc_error(msg, "BIO_new_mem_buf() failed");
		return ARC_STAT_NORESOURCE;
	}

	if (strncmp(key, "-----", 5) == 0)
	{
		pkey = PEM_read_bio_PrivateKey(keydata, NULL, NULL, NULL);
		if (pkey == NULL)
		{
			arc_error(msg, "PEM_read_bio_PrivateKey() failed");
			BIO_free(keydata);
			return ARC_STAT_NORESOURCE;
		}
	}
	else
	{
		pkey = d2i_PrivateKey_bio(keydata, NULL);
		if (pkey == NULL)
		{
			arc_error(msg, "d2i_PrivateKey_bio() failed");
			BIO_free(keydata);
			return ARC_STAT_NORESOURCE;
		}
	}

	rsa = EVP_PKEY_get1_RSA(pkey);
	if (rsa == NULL)
	{
		arc_error(msg, "EVP_PKEY_get1_RSA() failed");
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		return ARC_STAT_NORESOURCE;
	}

	keysize = RSA_size(rsa);
	if (keysize * 8 < msg->arc_library->arcl_minkeysize)
	{
		arc_error(msg, "key size (%u) below minimum (%u)",
		          keysize, msg->arc_library->arcl_minkeysize);
		EVP_PKEY_free(pkey);
		RSA_free(rsa);
		BIO_free(keydata);
		return ARC_STAT_CANTVRFY;
	}

	sigout = ARC_MALLOC(keysize);
	if (sigout == NULL)
	{
		arc_error(msg, "can't allocate %d bytes for signature",
		          keysize);
		EVP_PKEY_free(pkey);
		RSA_free(rsa);
		BIO_free(keydata);
		return ARC_STAT_NORESOURCE;
	}

	dstr = arc_dstring_new(msg, ARC_MAXHEADER, 0);

	/*
	**  Generate a new signature and store it.
	*/

	/* purge any previous seal */
	if (msg->arc_sealhead != NULL)
	{
		ARC_HDRFIELD *tmphdr;
		ARC_HDRFIELD *next;

		tmphdr = msg->arc_sealhead;
		while (tmphdr != NULL)
		{
			next = tmphdr->hdr_next;
			ARC_FREE(tmphdr->hdr_text);
			ARC_FREE(tmphdr);
			tmphdr = next;
		}

		msg->arc_sealhead = NULL;
		msg->arc_sealtail = NULL;
	}

	/*
	**  Part 1: Construct a new AAR
	*/

	arc_dstring_printf(dstr, "ARC-Authentication-Results:i=%u; %s",
	                   msg->arc_nsets + 1,
	                   msg->arc_authservid);
	if (ar != NULL)
		arc_dstring_printf(dstr, "; %s", (char *) ar);

	status = arc_parse_header_field(msg, arc_dstring_get(dstr),
	                                arc_dstring_len(dstr), &h);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg, "arc_parse_header_field() failed");
		arc_dstring_free(dstr);
		ARC_FREE(sigout);
		EVP_PKEY_free(pkey);
		RSA_free(rsa);
		BIO_free(keydata);
		return status;
	}

	msg->arc_sealhead = h;
	msg->arc_sealtail = h;

	/*
	**  Part B: Construct a new AMS (basically a no-frills DKIM signature)
	*/

	/* finalize body canonicalizations */
	status = arc_canon_closebody(msg);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg, "arc_canon_closebody() failed");
		arc_dstring_free(dstr);
		ARC_FREE(sigout);
		RSA_free(rsa);
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		return status;
	}

	/* construct the AMS */
	arc_dstring_blank(dstr);
	arc_dstring_catn(dstr, (u_char *) ARC_MSGSIG_HDRNAME ":",
	                 sizeof ARC_MSGSIG_HDRNAME);

	status = arc_getamshdr_d(msg, arc_dstring_len(dstr), &sighdr, &len,
	                         FALSE);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg, "arc_getamshdr_d() failed");
		arc_dstring_free(dstr);
		ARC_FREE(sigout);
		RSA_free(rsa);
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		return status;
	}

	arc_dstring_catn(dstr, sighdr, len);
	len = arc_dstring_len(dstr);

	hdr.hdr_text = arc_dstring_get(dstr);
	hdr.hdr_colon = hdr.hdr_text + ARC_MSGSIG_HDRNAMELEN;
	hdr.hdr_namelen = ARC_MSGSIG_HDRNAMELEN;
	hdr.hdr_textlen = len;
	hdr.hdr_flags = 0;
	hdr.hdr_next = NULL;

	/* canonicalize */
	status = arc_canon_signature(msg, &hdr, ARC_CANONTYPE_AMS);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg, "arc_canon_signature() failed");
		arc_dstring_free(dstr);
		ARC_FREE(sigout);
		ARC_FREE(sighdr);
		RSA_free(rsa);
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		return ARC_STAT_INTERNAL;
	}

	status = arc_canon_getfinal(msg->arc_sign_hdrcanon, &digest, &diglen);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg, "arc_canon_getfinal() failed");
		arc_dstring_free(dstr);
		ARC_FREE(sigout);
		RSA_free(rsa);
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		return ARC_STAT_INTERNAL;
	}

	/* encrypt the digest; that's our signature */
	nid = NID_sha256;
	rstatus = RSA_sign(nid, digest, diglen, sigout, &siglen, rsa);
	if (rstatus != 1 || siglen == 0)
	{
		arc_error(msg, "RSA_sign() failed (status %d, length %d)",
		          rstatus, siglen);
		arc_dstring_free(dstr);
		ARC_FREE(sigout);
		RSA_free(rsa);
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		return ARC_STAT_INTERNAL;
	}

	/* base64 encode it */
	b64siglen = siglen * 3 + 5;
	b64siglen += (b64siglen / 60);
	b64sig = ARC_MALLOC(b64siglen);
	if (b64sig == NULL)
	{
		arc_error(msg, "can't allocate %d bytes for base64 signature",
		          b64siglen);
		arc_dstring_free(dstr);
		ARC_FREE(sigout);
		RSA_free(rsa);
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		return ARC_STAT_NORESOURCE;
	}

	memset(b64sig, '\0', b64siglen);
	rstatus = arc_base64_encode(sigout, siglen, b64sig, b64siglen);
	if (rstatus == -1)
	{
		arc_error(msg, "signature base64 encoding failed");
		arc_dstring_free(dstr);
		ARC_FREE(b64sig);
		ARC_FREE(sigout);
		RSA_free(rsa);
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		return ARC_STAT_INTERNAL;
	}

	/* append it to the stub */
	arc_dstring_cat(dstr, b64sig);

	/* XXX -- wrapping needs to happen here */

	/* add it to the seal */
	h = ARC_MALLOC(sizeof hdr);
	if (h == NULL)
	{
		arc_error(msg, "can't allocate %d bytes", sizeof hdr);
		arc_dstring_free(dstr);
		ARC_FREE(b64sig);
		ARC_FREE(sigout);
		RSA_free(rsa);
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		return ARC_STAT_INTERNAL;
	}

	h->hdr_text = ARC_STRDUP(arc_dstring_get(dstr));
	if (h->hdr_text == NULL)
	{
		arc_error(msg, "can't allocate %d bytes",
		          arc_dstring_len(dstr));
		arc_dstring_free(dstr);
		ARC_FREE(h);
		ARC_FREE(b64sig);
		ARC_FREE(sigout);
		RSA_free(rsa);
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		return ARC_STAT_INTERNAL;
	}
	h->hdr_colon = h->hdr_text + ARC_MSGSIG_HDRNAMELEN;
	h->hdr_namelen = ARC_MSGSIG_HDRNAMELEN;
	h->hdr_textlen = arc_dstring_len(dstr);
	h->hdr_flags = 0;
	h->hdr_next = NULL;

	msg->arc_sealtail->hdr_next = h;
	msg->arc_sealtail = h;

	/*
	**  Part III: Construct a new AS
	*/

	arc_dstring_blank(dstr);
	arc_dstring_catn(dstr, (u_char *) ARC_SEAL_HDRNAME ":",
	                 sizeof ARC_SEAL_HDRNAME);

	/* feed the seal we have so far */
	status = arc_canon_add_to_seal(msg);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg, "arc_canon_add_to_seal() failed");
		arc_dstring_free(dstr);
		ARC_FREE(sigout);
		RSA_free(rsa);
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		return status;
	}

	status = arc_getamshdr_d(msg, arc_dstring_len(dstr), &sighdr, &len,
	                         TRUE);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg, "arc_getamshdr_d() failed");
		arc_dstring_free(dstr);
		ARC_FREE(sigout);
		RSA_free(rsa);
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		return status;
	}

	arc_dstring_catn(dstr, sighdr, len);

	hdr.hdr_text = arc_dstring_get(dstr);
	hdr.hdr_colon = hdr.hdr_text + ARC_SEAL_HDRNAMELEN;
	hdr.hdr_namelen = ARC_SEAL_HDRNAMELEN;
	hdr.hdr_textlen = len;
	hdr.hdr_flags = 0;
	hdr.hdr_next = NULL;

	/* canonicalize */
	status = arc_canon_signature(msg, &hdr, ARC_CANONTYPE_SEAL);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg, "arc_canon_signature() failed");
		arc_dstring_free(dstr);
		ARC_FREE(sigout);
		ARC_FREE(sighdr);
		RSA_free(rsa);
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		return ARC_STAT_INTERNAL;
	}

	status = arc_canon_getfinal(msg->arc_sealcanon, &digest, &diglen);
	if (status != ARC_STAT_OK)
	{
		arc_error(msg, "arc_canon_getseal() failed");
		arc_dstring_free(dstr);
		ARC_FREE(sigout);
		RSA_free(rsa);
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		return status;
	}

	/* encrypt the digest; that's our signature */
	nid = NID_sha256;
	rstatus = RSA_sign(nid, digest, diglen, sigout, &siglen, rsa);
	if (rstatus != 1 || siglen == 0)
	{
		arc_error(msg, "RSA_sign() failed (status %d, length %d)",
		          rstatus, siglen);
		arc_dstring_free(dstr);
		ARC_FREE(sigout);
		RSA_free(rsa);
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		return ARC_STAT_INTERNAL;
	}

	/* base64 encode it */
	memset(b64sig, '\0', b64siglen);
	rstatus = arc_base64_encode(sigout, siglen, b64sig, b64siglen);
	if (rstatus == -1)
	{
		arc_error(msg, "signature base64 encoding failed");
		arc_dstring_free(dstr);
		ARC_FREE(b64sig);
		ARC_FREE(sigout);
		RSA_free(rsa);
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		return ARC_STAT_INTERNAL;
	}

	/* append it to the stub */
	arc_dstring_cat(dstr, b64sig);

	/* XXX -- wrapping needs to happen here */

	/* add it to the seal */
	h = ARC_MALLOC(sizeof hdr);
	if (h == NULL)
	{
		arc_error(msg, "can't allocate %d bytes", sizeof hdr);
		arc_dstring_free(dstr);
		ARC_FREE(b64sig);
		ARC_FREE(sigout);
		RSA_free(rsa);
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		return ARC_STAT_INTERNAL;
	}
	h->hdr_text = ARC_STRDUP(arc_dstring_get(dstr));
	if (h->hdr_text == NULL)
	{
		arc_error(msg, "can't allocate %d bytes", sizeof hdr);
		arc_dstring_free(dstr);
		ARC_FREE(b64sig);
		ARC_FREE(sigout);
		RSA_free(rsa);
		EVP_PKEY_free(pkey);
		BIO_free(keydata);
		return ARC_STAT_INTERNAL;
	}
	h->hdr_colon = h->hdr_text + ARC_SEAL_HDRNAMELEN;
	h->hdr_namelen = ARC_SEAL_HDRNAMELEN;
	h->hdr_textlen = len;
	h->hdr_flags = 0;
	h->hdr_next = NULL;

	msg->arc_sealtail->hdr_next = h;
	msg->arc_sealtail = h;

	/* tidy up */
	arc_dstring_free(dstr);
	ARC_FREE(b64sig);
	ARC_FREE(sigout);
	RSA_free(rsa);
		EVP_PKEY_free(pkey);
	BIO_free(keydata);

	*seal = msg->arc_sealhead;

	return ARC_STAT_OK;
}

/*
**  ARC_HDR_NAME -- extract name from an ARC_HDRFIELD
**
**  Parameters:
**  	hdr -- ARC_HDRFIELD object
**
**  Return value:
**  	Header field name stored in the object.
*/

u_char *
arc_hdr_name(ARC_HDRFIELD *hdr, size_t *len)
{
	if (len != NULL)
		*len = hdr->hdr_namelen;
	return hdr->hdr_text;
}

/*
**  ARC_HDR_VALUE -- extract value from an ARC_HDRFIELD
**
**  Parameters:
**  	hdr -- ARC_HDRFIELD object
**
**  Return value:
**  	Header field value stored in the object.
*/

u_char *
arc_hdr_value(ARC_HDRFIELD *hdr)
{
	return hdr->hdr_colon + 1;
}

/*
**  ARC_HDR_NEXT -- return pointer to next ARC_HDRFIELD
**
**  Parameters:
**  	hdr -- ARC_HDRFIELD object
**
**  Return value:
**  	Pointer to the next ARC_HDRFIELD in the sequence.
*/

ARC_HDRFIELD *
arc_hdr_next(ARC_HDRFIELD *hdr)
{
	return hdr->hdr_next;
}

/*
**  ARC_SSL_VERSION -- report the version of the crypto library against which
**  	the library was compiled, so the caller can ensure it matches
**
**  Parameters:
**  	None.
**
**  Return value:
**  	SSL library version, expressed as a uint64_t.
*/

uint64_t
arc_ssl_version(void)
{
	return OPENSSL_VERSION_NUMBER;
}

/*
**  ARC_LIBFEATURE -- determine whether or not a particular library feature
**                    is actually available
**
**  Parameters:
**  	lib -- library handle
**  	fc -- feature code to check
**
**  Return value:
**  	TRUE iff the specified feature was compiled in
*/

_Bool
arc_libfeature(ARC_LIB *lib, u_int fc)
{
	u_int idx;
	u_int offset;

	idx = fc / (8 * sizeof(int));
	offset = fc % (8 * sizeof(int));

	if (idx > lib->arcl_flsize)
		return FALSE;
	return ((lib->arcl_flist[idx] & (1 << offset)) != 0);
}

/*
**  ARC_GET_DOMAIN -- retrieve stored domain for this message
**
**  Parameters:
**  	msg -- ARC_MESSAGE object
**
**  Return value:
**  	Pointer to string containing the domain stored for this message
*/

char *
arc_get_domain(ARC_MESSAGE *msg)
{
	return msg->arc_domain;
}

/*
**  ARC_CHAIN_STATUS_STR -- retrieve chain status, as a string
**
**  Parameters:
**      msg -- ARC_MESSAGE object
**
**  Return value:
**      Pointer to string containing the current chain status.
*/

const char *
arc_chain_status_str(ARC_MESSAGE *msg)
{
	return arc_code_to_name(chainstatus, msg->arc_cstate);
}

/*
**  ARC_CHAIN_CUSTODY_STR -- retrieve domain chain, as a string
**
**  Parameters:
**      msg -- ARC_MESSAGE object
**      buf -- where to write
**      buflen -- bytes at "buf"
**
**  Return value:
**  	Number of bytes written. If value is greater than or equal to buflen
**  	argument, then buffer was too small and output was truncated.
*/

int
arc_chain_custody_str(ARC_MESSAGE *msg, u_char *buf, size_t buflen)
{
	int set;
	u_char *instance;
	ARC_KVSET *kvset;
	char *str = NULL;
	struct arc_dstring *tmpbuf;
	int appendlen = 0;

	assert(msg != NULL);
	assert(buf != NULL);
	assert(buflen > 0);

	if (msg->arc_cstate != ARC_CHAIN_PASS)
		return 0;

	tmpbuf = arc_dstring_new(msg, BUFRSZ, MAXBUFRSZ);
	if (tmpbuf == NULL)
	{
		arc_dstring_free(tmpbuf);
		arc_error(msg, "failed to allocate dynamic string");
		return ARC_STAT_NORESOURCE;
	}

	memset(buf, '\0', buflen);

	for (set = msg->arc_nsets - 1; set >= 0; set--)
	{
		kvset = msg->arc_sets[set].arcset_ams->hdr_data;
		str = arc_param_get(kvset, "d");
		(void) arc_dstring_printf(tmpbuf, "%s%s",
		                          (set < msg->arc_nsets - 1 ? ":" : ""),
		                          str);
	}

	appendlen = snprintf(buf, buflen, "%s", arc_dstring_get(tmpbuf));
	arc_dstring_free(tmpbuf);

	return appendlen;
}