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

/*
 * Copyright (c) 2006, 2007, 2008 Reyk Floeter <reyk@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/types.h>
#include <sys/queue.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/tree.h>
#include <sys/hash.h>

#include <net/if.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>

#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <err.h>
#include <pwd.h>
#include <event.h>
#include <fnmatch.h>

#include <openssl/ssl.h>

#include "relayd.h"

void		 relay_statistics(int, short, void *);
int		 relay_dispatch_parent(int, struct privsep_proc *,
		    struct imsg *);
int		 relay_dispatch_pfe(int, struct privsep_proc *,
		    struct imsg *);
void		 relay_shutdown(void);

void		 relay_nodedebug(const char *, struct protonode *);
void		 relay_protodebug(struct relay *);
void		 relay_init(struct privsep *, struct privsep_proc *p, void *);
void		 relay_launch(void);
int		 relay_socket(struct sockaddr_storage *, in_port_t,
		    struct protocol *, int, int);
int		 relay_socket_listen(struct sockaddr_storage *, in_port_t,
		    struct protocol *);
int		 relay_socket_connect(struct sockaddr_storage *, in_port_t,
		    struct protocol *, int);

void		 relay_accept(int, short, void *);
void		 relay_input(struct rsession *);

int		 relay_connect(struct rsession *);
void		 relay_connected(int, short, void *);
void		 relay_bindanyreq(struct rsession *, in_port_t, int);
void		 relay_bindany(int, short, void *);

u_int32_t	 relay_hash_addr(struct sockaddr_storage *, u_int32_t);

void		 relay_write(struct bufferevent *, void *);
void		 relay_read(struct bufferevent *, void *);
void		 relay_error(struct bufferevent *, short, void *);
void		 relay_dump(struct ctl_relay_event *, const void *, size_t);

int		 relay_splice(struct ctl_relay_event *);
int		 relay_splicelen(struct ctl_relay_event *);

int		 relay_resolve(struct ctl_relay_event *,
		    struct protonode *, struct protonode *);
int		 relay_handle_http(struct ctl_relay_event *,
		    struct protonode *, struct protonode *,
		    struct protonode *, int);
int		 relay_lognode(struct rsession *,
		    struct protonode *, struct protonode *, char *, size_t);
void		 relay_read_http(struct bufferevent *, void *);
static int	_relay_lookup_url(struct ctl_relay_event *, char *, char *,
		    char *, enum digest_type);
int		 relay_lookup_url(struct ctl_relay_event *,
		    const char *, enum digest_type);
int		 relay_lookup_query(struct ctl_relay_event *);
int		 relay_lookup_cookie(struct ctl_relay_event *, const char *);
void		 relay_read_httpcontent(struct bufferevent *, void *);
void		 relay_read_httpchunks(struct bufferevent *, void *);
char		*relay_expand_http(struct ctl_relay_event *, char *,
		    char *, size_t);
void		 relay_close_http(struct rsession *, u_int, const char *,
		    u_int16_t);
void		 relay_http_request_close(struct ctl_relay_event *);

SSL_CTX		*relay_ssl_ctx_create(struct relay *);
void		 relay_ssl_transaction(struct rsession *,
		    struct ctl_relay_event *);
void		 relay_ssl_accept(int, short, void *);
void		 relay_ssl_connect(int, short, void *);
void		 relay_ssl_connected(struct ctl_relay_event *);
void		 relay_ssl_readcb(int, short, void *);
void		 relay_ssl_writecb(int, short, void *);

int		 relay_bufferevent_add(struct event *, int);
#ifdef notyet
int		 relay_bufferevent_printf(struct ctl_relay_event *,
		    const char *, ...);
#endif
int		 relay_bufferevent_print(struct ctl_relay_event *, char *);
int		 relay_bufferevent_write_buffer(struct ctl_relay_event *,
		    struct evbuffer *);
int		 relay_bufferevent_write_chunk(struct ctl_relay_event *,
		    struct evbuffer *, size_t);
int		 relay_bufferevent_write(struct ctl_relay_event *,
		    void *, size_t);
char		*relay_load_file(const char *, off_t *);
static __inline int
		 relay_proto_cmp(struct protonode *, struct protonode *);
extern void	 bufferevent_read_pressure_cb(struct evbuffer *, size_t,
		    size_t, void *);

volatile sig_atomic_t relay_sessions;
objid_t relay_conid;

static struct relayd		*env = NULL;
int				 proc_id;

static struct privsep_proc procs[] = {
	{ "parent",	PROC_PARENT,	relay_dispatch_parent },
	{ "pfe",	PROC_PFE,	relay_dispatch_pfe },
};

pid_t
relay(struct privsep *ps, struct privsep_proc *p)
{
	env = ps->ps_env;
	return (proc_run(ps, p, procs, nitems(procs), relay_init, NULL));
}

void
relay_shutdown(void)
{
	config_purge(env, CONFIG_ALL);
	usleep(200);	/* XXX relay needs to shutdown last */
}

void
relay_nodedebug(const char *name, struct protonode *pn)
{
	const char	*s;
	int		 digest;

	if (pn->action == NODE_ACTION_NONE)
		return;

	fprintf(stderr, "\t\t");
	fprintf(stderr, "%s ", name);

	switch (pn->type) {
	case NODE_TYPE_HEADER:
		break;
	case NODE_TYPE_QUERY:
		fprintf(stderr, "query ");
		break;
	case NODE_TYPE_COOKIE:
		fprintf(stderr, "cookie ");
		break;
	case NODE_TYPE_PATH:
		fprintf(stderr, "path ");
		break;
	case NODE_TYPE_URL:
		fprintf(stderr, "url ");
		break;
	}

	switch (pn->action) {
	case NODE_ACTION_APPEND:
		fprintf(stderr, "append \"%s\" to \"%s\"",
		    pn->value, pn->key);
		break;
	case NODE_ACTION_CHANGE:
		fprintf(stderr, "change \"%s\" to \"%s\"",
		    pn->key, pn->value);
		break;
	case NODE_ACTION_REMOVE:
		fprintf(stderr, "remove \"%s\"",
		    pn->key);
		break;
	case NODE_ACTION_EXPECT:
	case NODE_ACTION_FILTER:
		s = pn->action == NODE_ACTION_EXPECT ? "expect" : "filter";
		digest = pn->flags & PNFLAG_LOOKUP_URL_DIGEST;
		if (strcmp(pn->value, "*") == 0)
			fprintf(stderr, "%s %s\"%s\"", s,
			    digest ? "digest " : "", pn->key);
		else
			fprintf(stderr, "%s \"%s\" from \"%s\"", s,
			    pn->value, pn->key);
		break;
	case NODE_ACTION_HASH:
		fprintf(stderr, "hash \"%s\"", pn->key);
		break;
	case NODE_ACTION_LOG:
		fprintf(stderr, "log \"%s\"", pn->key);
		break;
	case NODE_ACTION_MARK:
		if (strcmp(pn->value, "*") == 0)
			fprintf(stderr, "mark \"%s\"", pn->key);
		else
			fprintf(stderr, "mark \"%s\" from \"%s\"",
			    pn->value, pn->key);
		break;
	case NODE_ACTION_NONE:
		break;
	}
	fprintf(stderr, "\n");
}

void
relay_protodebug(struct relay *rlay)
{
	struct protocol		*proto = rlay->rl_proto;
	struct protonode	*proot, *pn;
	struct proto_tree	*tree;
	const char		*name;
	int			 i;

	fprintf(stderr, "protocol %d: name %s\n",
	    proto->id, proto->name);
	fprintf(stderr, "\tflags: %s, relay flags: %s\n",
	    printb_flags(proto->flags, F_BITS),
	    printb_flags(rlay->rl_conf.flags, F_BITS));
	if (proto->tcpflags)
		fprintf(stderr, "\ttcp flags: %s\n",
		    printb_flags(proto->tcpflags, TCPFLAG_BITS));
	if ((rlay->rl_conf.flags & (F_SSL|F_SSLCLIENT)) && proto->sslflags)
		fprintf(stderr, "\tssl flags: %s\n",
		    printb_flags(proto->sslflags, SSLFLAG_BITS));
	if (proto->cache != -1)
		fprintf(stderr, "\tssl session cache: %d\n", proto->cache);
	fprintf(stderr, "\ttype: ");
	switch (proto->type) {
	case RELAY_PROTO_TCP:
		fprintf(stderr, "tcp\n");
		break;
	case RELAY_PROTO_HTTP:
		fprintf(stderr, "http\n");
		break;
	case RELAY_PROTO_DNS:
		fprintf(stderr, "dns\n");
		break;
	}

	name = "request";
	tree = &proto->request_tree;
 show:
	i = 0;
	RB_FOREACH(proot, proto_tree, tree) {
#if DEBUG > 1
		i = 0;
#endif
		PROTONODE_FOREACH(pn, proot, entry) {
#if DEBUG > 1
			i = 0;
#endif
			if (++i > 100)
				break;
			relay_nodedebug(name, pn);
		}
		/* Limit the number of displayed lines */
		if (++i > 100) {
			fprintf(stderr, "\t\t...\n");
			break;
		}
	}
	if (tree == &proto->request_tree) {
		name = "response";
		tree = &proto->response_tree;
		goto show;
	}
}

int
relay_privinit(struct relay *rlay)
{
	extern int	 debug;

	log_debug("%s: adding relay %s", __func__, rlay->rl_conf.name);

	if (debug)
		relay_protodebug(rlay);

	switch (rlay->rl_proto->type) {
	case RELAY_PROTO_DNS:
		relay_udp_privinit(env, rlay);
		break;
	case RELAY_PROTO_TCP:
	case RELAY_PROTO_HTTP:
		/* Use defaults */
		break;
	}

	if (rlay->rl_conf.flags & F_UDP)
		rlay->rl_s = relay_udp_bind(&rlay->rl_conf.ss,
		    rlay->rl_conf.port, rlay->rl_proto);
	else
		rlay->rl_s = relay_socket_listen(&rlay->rl_conf.ss,
		    rlay->rl_conf.port, rlay->rl_proto);
	if (rlay->rl_s == -1)
		return (-1);

	return (0);
}

void
relay_init(struct privsep *ps, struct privsep_proc *p, void *arg)
{
	struct timeval	 tv;

	if (config_init(ps->ps_env) == -1)
		fatal("failed to initialize configuration");

	/* We use a custom shutdown callback */
	p->p_shutdown = relay_shutdown;

	/* Unlimited file descriptors (use system limits) */
	socket_rlimit(-1);

	/* Schedule statistics timer */
	evtimer_set(&env->sc_statev, relay_statistics, NULL);
	bcopy(&env->sc_statinterval, &tv, sizeof(tv));
	evtimer_add(&env->sc_statev, &tv);
}

void
relay_statistics(int fd, short events, void *arg)
{
	struct relay		*rlay;
	struct ctl_stats	 crs, *cur;
	struct timeval		 tv, tv_now;
	int			 resethour = 0, resetday = 0;
	struct rsession		*con, *next_con;

	/*
	 * This is a hack to calculate some average statistics.
	 * It doesn't try to be very accurate, but could be improved...
	 */

	timerclear(&tv);
	if (gettimeofday(&tv_now, NULL) == -1)
		fatal("relay_init: gettimeofday");

	TAILQ_FOREACH(rlay, env->sc_relays, rl_entry) {
		bzero(&crs, sizeof(crs));
		resethour = resetday = 0;

		cur = &rlay->rl_stats[proc_id];
		cur->cnt += cur->last;
		cur->tick++;
		cur->avg = (cur->last + cur->avg) / 2;
		cur->last_hour += cur->last;
		if ((cur->tick % (3600 / env->sc_statinterval.tv_sec)) == 0) {
			cur->avg_hour = (cur->last_hour + cur->avg_hour) / 2;
			resethour++;
		}
		cur->last_day += cur->last;
		if ((cur->tick % (86400 / env->sc_statinterval.tv_sec)) == 0) {
			cur->avg_day = (cur->last_day + cur->avg_day) / 2;
			resethour++;
		}
		bcopy(cur, &crs, sizeof(crs));

		cur->last = 0;
		if (resethour)
			cur->last_hour = 0;
		if (resetday)
			cur->last_day = 0;

		crs.id = rlay->rl_conf.id;
		crs.proc = proc_id;
		proc_compose_imsg(env->sc_ps, PROC_PFE, -1, IMSG_STATISTICS, -1,
		    &crs, sizeof(crs));

		for (con = SPLAY_ROOT(&rlay->rl_sessions);
		    con != NULL; con = next_con) {
			next_con = SPLAY_NEXT(session_tree,
			    &rlay->rl_sessions, con);
			timersub(&tv_now, &con->se_tv_last, &tv);
			if (timercmp(&tv, &rlay->rl_conf.timeout, >=))
				relay_close(con, "hard timeout");
		}
	}

	/* Schedule statistics timer */
	evtimer_set(&env->sc_statev, relay_statistics, NULL);
	bcopy(&env->sc_statinterval, &tv, sizeof(tv));
	evtimer_add(&env->sc_statev, &tv);
}

void
relay_launch(void)
{
	void		(*callback)(int, short, void *);
	struct relay	*rlay;
	struct host	*host;

	TAILQ_FOREACH(rlay, env->sc_relays, rl_entry) {
		if ((rlay->rl_conf.flags & (F_SSL|F_SSLCLIENT)) &&
		    (rlay->rl_ssl_ctx = relay_ssl_ctx_create(rlay)) == NULL)
			fatal("relay_init: failed to create SSL context");

		if (rlay->rl_dsttable != NULL) {
			switch (rlay->rl_conf.dstmode) {
			case RELAY_DSTMODE_ROUNDROBIN:
				rlay->rl_dstkey = 0;
				break;
			case RELAY_DSTMODE_LOADBALANCE:
			case RELAY_DSTMODE_HASH:
				rlay->rl_dstkey =
				    hash32_str(rlay->rl_conf.name, HASHINIT);
				rlay->rl_dstkey =
				    hash32_str(rlay->rl_dsttable->conf.name,
				    rlay->rl_dstkey);
				break;
			}
			rlay->rl_dstnhosts = 0;
			TAILQ_FOREACH(host, &rlay->rl_dsttable->hosts, entry) {
				if (rlay->rl_dstnhosts >= RELAY_MAXHOSTS)
					fatal("relay_init: "
					    "too many hosts in table");
				host->idx = rlay->rl_dstnhosts;
				rlay->rl_dsthost[rlay->rl_dstnhosts++] = host;
			}
			log_info("adding %d hosts from table %s%s",
			    rlay->rl_dstnhosts, rlay->rl_dsttable->conf.name,
			    rlay->rl_dsttable->conf.check ? "" : " (no check)");
		}

		switch (rlay->rl_proto->type) {
		case RELAY_PROTO_DNS:
			relay_udp_init(rlay);
			break;
		case RELAY_PROTO_TCP:
		case RELAY_PROTO_HTTP:
			/* Use defaults */
			break;
		}

		log_debug("%s: running relay %s", __func__,
		    rlay->rl_conf.name);

		rlay->rl_up = HOST_UP;

		if (rlay->rl_conf.flags & F_UDP)
			callback = relay_udp_server;
		else
			callback = relay_accept;

		event_set(&rlay->rl_ev, rlay->rl_s, EV_READ|EV_PERSIST,
		    callback, rlay);
		event_add(&rlay->rl_ev, NULL);
	}
}

int
relay_socket_af(struct sockaddr_storage *ss, in_port_t port)
{
	switch (ss->ss_family) {
	case AF_INET:
		((struct sockaddr_in *)ss)->sin_port = port;
		((struct sockaddr_in *)ss)->sin_len =
		    sizeof(struct sockaddr_in);
		break;
	case AF_INET6:
		((struct sockaddr_in6 *)ss)->sin6_port = port;
		((struct sockaddr_in6 *)ss)->sin6_len =
		    sizeof(struct sockaddr_in6);
		break;
	default:
		return (-1);
	}

	return (0);
}

in_port_t
relay_socket_getport(struct sockaddr_storage *ss)
{
	switch (ss->ss_family) {
	case AF_INET:
		return (((struct sockaddr_in *)ss)->sin_port);
	case AF_INET6:
		return (((struct sockaddr_in6 *)ss)->sin6_port);
	default:
		return (0);
	}

	/* NOTREACHED */
	return (0);
}

int
relay_socket(struct sockaddr_storage *ss, in_port_t port,
    struct protocol *proto, int fd, int reuseport)
{
	int s = -1, val;
	struct linger lng;

	if (relay_socket_af(ss, port) == -1)
		goto bad;

	s = fd == -1 ? socket(ss->ss_family, SOCK_STREAM, IPPROTO_TCP) : fd;
	if (s == -1)
		goto bad;

	/*
	 * Socket options
	 */
	bzero(&lng, sizeof(lng));
	if (setsockopt(s, SOL_SOCKET, SO_LINGER, &lng, sizeof(lng)) == -1)
		goto bad;
	if (reuseport) {
		val = 1;
		if (setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &val,
			sizeof(int)) == -1)
			goto bad;
	}
	if (fcntl(s, F_SETFL, O_NONBLOCK) == -1)
		goto bad;
	if (proto->tcpflags & TCPFLAG_BUFSIZ) {
		val = proto->tcpbufsiz;
		if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
		    &val, sizeof(val)) == -1)
			goto bad;
		val = proto->tcpbufsiz;
		if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
		    &val, sizeof(val)) == -1)
			goto bad;
	}

	/*
	 * IP options
	 */
	if (proto->tcpflags & TCPFLAG_IPTTL) {
		val = (int)proto->tcpipttl;
		if (setsockopt(s, IPPROTO_IP, IP_TTL,
		    &val, sizeof(val)) == -1)
			goto bad;
	}
	if (proto->tcpflags & TCPFLAG_IPMINTTL) {
		val = (int)proto->tcpipminttl;
		if (setsockopt(s, IPPROTO_IP, IP_MINTTL,
		    &val, sizeof(val)) == -1)
			goto bad;
	}

	/*
	 * TCP options
	 */
	if (proto->tcpflags & (TCPFLAG_NODELAY|TCPFLAG_NNODELAY)) {
		if (proto->tcpflags & TCPFLAG_NNODELAY)
			val = 0;
		else
			val = 1;
		if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
		    &val, sizeof(val)) == -1)
			goto bad;
	}
	if (proto->tcpflags & (TCPFLAG_SACK|TCPFLAG_NSACK)) {
		if (proto->tcpflags & TCPFLAG_NSACK)
			val = 0;
		else
			val = 1;
		if (setsockopt(s, IPPROTO_TCP, TCP_SACK_ENABLE,
		    &val, sizeof(val)) == -1)
			goto bad;
	}

	return (s);

 bad:
	if (s != -1)
		close(s);
	return (-1);
}

int
relay_socket_connect(struct sockaddr_storage *ss, in_port_t port,
    struct protocol *proto, int fd)
{
	int	s;

	if ((s = relay_socket(ss, port, proto, fd, 0)) == -1)
		return (-1);

	if (connect(s, (struct sockaddr *)ss, ss->ss_len) == -1) {
		if (errno != EINPROGRESS)
			goto bad;
	}

	return (s);

 bad:
	close(s);
	return (-1);
}

int
relay_socket_listen(struct sockaddr_storage *ss, in_port_t port,
    struct protocol *proto)
{
	int s;

	if ((s = relay_socket(ss, port, proto, -1, 1)) == -1)
		return (-1);

	if (bind(s, (struct sockaddr *)ss, ss->ss_len) == -1)
		goto bad;
	if (listen(s, proto->tcpbacklog) == -1)
		goto bad;

	return (s);

 bad:
	close(s);
	return (-1);
}

void
relay_connected(int fd, short sig, void *arg)
{
	struct rsession		*con = (struct rsession *)arg;
	struct relay		*rlay = (struct relay *)con->se_relay;
	struct protocol		*proto = rlay->rl_proto;
	evbuffercb		 outrd = relay_read;
	evbuffercb		 outwr = relay_write;
	struct bufferevent	*bev;
	struct ctl_relay_event	*out = &con->se_out;

	if (sig == EV_TIMEOUT) {
		relay_close_http(con, 504, "connect timeout", 0);
		return;
	}

	if ((rlay->rl_conf.flags & F_SSLCLIENT) && (out->ssl == NULL)) {
		relay_ssl_transaction(con, out);
		return;
	}

	DPRINTF("%s: session %d: %ssuccessful", __func__,
	    con->se_id, rlay->rl_proto->lateconnect ? "late connect " : "");

	switch (rlay->rl_proto->type) {
	case RELAY_PROTO_HTTP:
		/* Check the servers's HTTP response */
		if (!RB_EMPTY(&rlay->rl_proto->response_tree)) {
			outrd = relay_read_http;
			if ((con->se_out.nodes = calloc(proto->response_nodes,
			    sizeof(u_int8_t))) == NULL) {
				relay_close_http(con, 500,
				    "failed to allocate nodes", 0);
				return;
			}
		}
		break;
	case RELAY_PROTO_TCP:
		/* Use defaults */
		break;
	default:
		fatalx("relay_connected: unknown protocol");
	}

	/*
	 * Relay <-> Server
	 */
	bev = bufferevent_new(fd, outrd, outwr, relay_error, &con->se_out);
	if (bev == NULL) {
		relay_close_http(con, 500,
		    "failed to allocate output buffer event", 0);
		return;
	}
	evbuffer_free(bev->output);
	bev->output = con->se_out.output;
	if (bev->output == NULL)
		fatal("relay_connected: invalid output buffer");
	con->se_out.bev = bev;

	/* Initialize the SSL wrapper */
	if ((rlay->rl_conf.flags & F_SSLCLIENT) && (out->ssl != NULL))
		relay_ssl_connected(out);

	bufferevent_settimeout(bev,
	    rlay->rl_conf.timeout.tv_sec, rlay->rl_conf.timeout.tv_sec);
	bufferevent_enable(bev, EV_READ|EV_WRITE);

	if (relay_splice(&con->se_out) == -1)
		relay_close(con, strerror(errno));
}

void
relay_input(struct rsession *con)
{
	struct relay	*rlay = (struct relay *)con->se_relay;
	struct protocol *proto = rlay->rl_proto;
	evbuffercb	 inrd = relay_read;
	evbuffercb	 inwr = relay_write;

	switch (rlay->rl_proto->type) {
	case RELAY_PROTO_HTTP:
		/* Check the client's HTTP request */
		if (!RB_EMPTY(&rlay->rl_proto->request_tree) ||
		    proto->lateconnect) {
			inrd = relay_read_http;
			if ((con->se_in.nodes = calloc(proto->request_nodes,
			    sizeof(u_int8_t))) == NULL) {
				relay_close(con, "failed to allocate nodes");
				return;
			}
		}
		break;
	case RELAY_PROTO_TCP:
		/* Use defaults */
		break;
	default:
		fatalx("relay_input: unknown protocol");
	}

	/*
	 * Client <-> Relay
	 */
	con->se_in.bev = bufferevent_new(con->se_in.s, inrd, inwr,
	    relay_error, &con->se_in);
	if (con->se_in.bev == NULL) {
		relay_close(con, "failed to allocate input buffer event");
		return;
	}

	/* Initialize the SSL wrapper */
	if ((rlay->rl_conf.flags & F_SSL) && con->se_in.ssl != NULL)
		relay_ssl_connected(&con->se_in);

	bufferevent_settimeout(con->se_in.bev,
	    rlay->rl_conf.timeout.tv_sec, rlay->rl_conf.timeout.tv_sec);
	bufferevent_enable(con->se_in.bev, EV_READ|EV_WRITE);

	if (relay_splice(&con->se_in) == -1)
		relay_close(con, strerror(errno));
}

void
relay_write(struct bufferevent *bev, void *arg)
{
	struct ctl_relay_event	*cre = (struct ctl_relay_event *)arg;
	struct rsession		*con = cre->con;
	if (gettimeofday(&con->se_tv_last, NULL) == -1)
		con->se_done = 1;
	if (con->se_done)
		relay_close(con, "last write (done)");
}

void
relay_dump(struct ctl_relay_event *cre, const void *buf, size_t len)
{
	if (!len)
		return;

	/*
	 * This function will dump the specified message directly
	 * to the underlying session, without waiting for success
	 * of non-blocking events etc. This is useful to print an
	 * error message before gracefully closing the session.
	 */
	if (cre->ssl != NULL)
		(void)SSL_write(cre->ssl, buf, len);
	else
		(void)write(cre->s, buf, len);
}

void
relay_read(struct bufferevent *bev, void *arg)
{
	struct ctl_relay_event	*cre = (struct ctl_relay_event *)arg;
	struct rsession		*con = cre->con;
	struct evbuffer		*src = EVBUFFER_INPUT(bev);

	if (gettimeofday(&con->se_tv_last, NULL) == -1)
		goto fail;
	if (!EVBUFFER_LENGTH(src))
		return;
	if (relay_bufferevent_write_buffer(cre->dst, src) == -1)
		goto fail;
	if (con->se_done)
		goto done;
	if (cre->dst->bev)
		bufferevent_enable(cre->dst->bev, EV_READ);
	return;
 done:
	relay_close(con, "last read (done)");
	return;
 fail:
	relay_close(con, strerror(errno));
}

int
relay_resolve(struct ctl_relay_event *cre,
    struct protonode *proot, struct protonode *pn)
{
	struct rsession		*con = cre->con;
	char			 buf[IBUF_READ_SIZE], *ptr;
	int			 id;

	if (pn->mark && (pn->mark != con->se_mark))
		return (0);

	switch (pn->action) {
	case NODE_ACTION_FILTER:
		id = cre->nodes[proot->id];
		if (SIMPLEQ_NEXT(pn, entry) == NULL)
			cre->nodes[proot->id] = 0;
		if (id <= 1)
			return (0);
		break;
	case NODE_ACTION_EXPECT:
		id = cre->nodes[proot->id];
		if (SIMPLEQ_NEXT(pn, entry) == NULL)
			cre->nodes[proot->id] = 0;
		if (id > 1)
			return (0);
		break;
	default:
		if (cre->nodes[pn->id]) {
			cre->nodes[pn->id] = 0;
			return (0);
		}
		break;
	}
	switch (pn->action) {
	case NODE_ACTION_APPEND:
	case NODE_ACTION_CHANGE:
		ptr = pn->value;
		if ((pn->flags & PNFLAG_MACRO) &&
		    (ptr = relay_expand_http(cre, pn->value,
		    buf, sizeof(buf))) == NULL)
			break;
		if (relay_bufferevent_print(cre->dst, pn->key) == -1 ||
		    relay_bufferevent_print(cre->dst, ": ") == -1 ||
		    relay_bufferevent_print(cre->dst, ptr) == -1 ||
		    relay_bufferevent_print(cre->dst, "\r\n") == -1) {
			relay_close_http(con, 500,
			    "failed to modify header", 0);
			return (-1);
		}
		DPRINTF("%s: add '%s: %s'", __func__, pn->key, ptr);
		break;
	case NODE_ACTION_EXPECT:
		DPRINTF("%s: missing '%s: %s'", __func__, pn->key, pn->value);
		relay_close_http(con, 403, "incomplete request", pn->label);
		return (-1);
	case NODE_ACTION_FILTER:
		DPRINTF("%s: filtered '%s: %s'", __func__, pn->key, pn->value);
		relay_close_http(con, 403, "rejecting request", pn->label);
		return (-1);
	default:
		break;
	}
	return (0);
}

char *
relay_expand_http(struct ctl_relay_event *cre, char *val, char *buf, size_t len)
{
	struct rsession	*con = cre->con;
	struct relay	*rlay = (struct relay *)con->se_relay;
	char		 ibuf[128];

	(void)strlcpy(buf, val, len);

	if (strstr(val, "$REMOTE_") != NULL) {
		if (strstr(val, "$REMOTE_ADDR") != NULL) {
			if (print_host(&cre->ss, ibuf, sizeof(ibuf)) == NULL)
				return (NULL);
			if (expand_string(buf, len,
			    "$REMOTE_ADDR", ibuf) != 0)
				return (NULL);
		}
		if (strstr(val, "$REMOTE_PORT") != NULL) {
			snprintf(ibuf, sizeof(ibuf), "%u", ntohs(cre->port));
			if (expand_string(buf, len,
			    "$REMOTE_PORT", ibuf) != 0)
				return (NULL);
		}
	}
	if (strstr(val, "$SERVER_") != NULL) {
		if (strstr(val, "$SERVER_ADDR") != NULL) {
			if (print_host(&rlay->rl_conf.ss,
			    ibuf, sizeof(ibuf)) == NULL)
				return (NULL);
			if (expand_string(buf, len,
			    "$SERVER_ADDR", ibuf) != 0)
				return (NULL);
		}
		if (strstr(val, "$SERVER_PORT") != NULL) {
			snprintf(ibuf, sizeof(ibuf), "%u",
			    ntohs(rlay->rl_conf.port));
			if (expand_string(buf, len,
			    "$SERVER_PORT", ibuf) != 0)
				return (NULL);
		}
		if (strstr(val, "$SERVER_NAME") != NULL) {
			if (expand_string(buf, len,
			    "$SERVER_NAME", RELAYD_SERVERNAME) != 0)
				return (NULL);
		}
	}
	if (strstr(val, "$TIMEOUT") != NULL) {
		snprintf(ibuf, sizeof(ibuf), "%lu",
		    rlay->rl_conf.timeout.tv_sec);
		if (expand_string(buf, len, "$TIMEOUT", ibuf) != 0)
			return (NULL);
	}

	return (buf);
}

int
relay_lognode(struct rsession *con, struct protonode *pn, struct protonode *pk,
    char *buf, size_t len)
{
	const char		*label = NULL;

	if ((pn->flags & PNFLAG_LOG) == 0)
		return (0);
	bzero(buf, len);
	if (pn->label != 0)
		label = pn_id2name(pn->label);
	if (snprintf(buf, len, " [%s%s%s: %s]",
	    label == NULL ? "" : label,
	    label == NULL ? "" : ", ",
	    pk->key, pk->value) == -1 ||
	    evbuffer_add(con->se_log, buf, strlen(buf)) == -1)
		return (-1);
	return (0);
}

int
relay_handle_http(struct ctl_relay_event *cre, struct protonode *proot,
    struct protonode *pn, struct protonode *pk, int header)
{
	struct rsession		*con = cre->con;
	char			 buf[IBUF_READ_SIZE], *ptr;
	int			 ret = PN_DROP, mark = 0;
	struct protonode	*next;

	/* Check if this action depends on a marked session */
	if (pn->mark != 0)
		mark = pn->mark == con->se_mark ? 1 : -1;

	switch (pn->action) {
	case NODE_ACTION_EXPECT:
	case NODE_ACTION_FILTER:
	case NODE_ACTION_MARK:
		break;
	default:
		if (mark == -1)
			return (PN_PASS);
		break;
	}

	switch (pn->action) {
	case NODE_ACTION_APPEND:
		if (!header)
			return (PN_PASS);
		ptr = pn->value;
		if ((pn->flags & PNFLAG_MACRO) &&
		    (ptr = relay_expand_http(cre, pn->value,
		    buf, sizeof(buf))) == NULL)
			break;
		if (relay_bufferevent_print(cre->dst, pn->key) == -1 ||
		    relay_bufferevent_print(cre->dst, ": ") == -1 ||
		    relay_bufferevent_print(cre->dst, pk->value) == -1 ||
		    relay_bufferevent_print(cre->dst, ", ") == -1 ||
		    relay_bufferevent_print(cre->dst, ptr) == -1 ||
		    relay_bufferevent_print(cre->dst, "\r\n") == -1)
			goto fail;
		cre->nodes[pn->id] = 1;
		DPRINTF("%s: append '%s: %s, %s'", __func__,
		    pk->key, pk->value, ptr);
		break;
	case NODE_ACTION_CHANGE:
	case NODE_ACTION_REMOVE:
		if (!header)
			return (PN_PASS);
		DPRINTF("%s: change/remove '%s: %s'", __func__,
		    pk->key, pk->value);
		break;
	case NODE_ACTION_EXPECT:
		/*
		 * A client may specify the header line for multiple times
		 * trying to circumvent the filter.
		 */
		if (cre->nodes[proot->id] > 1) {
			relay_close_http(con, 400, "repeated header line", 0);
			return (PN_FAIL);
		}
		/* FALLTHROUGH */
	case NODE_ACTION_FILTER:
		DPRINTF("%s: %s '%s: %s'", __func__,
		    (pn->action == NODE_ACTION_EXPECT) ? "expect" : "filter",
		    pn->key, pn->value);

		/* Do not drop the entity */
		ret = PN_PASS;

		if (mark != -1 &&
		    fnmatch(pn->value, pk->value, FNM_CASEFOLD) == 0) {
			cre->nodes[proot->id] = 1;

			/* Fail instantly */
			if (pn->action == NODE_ACTION_FILTER) {
				(void)relay_lognode(con, pn, pk,
				    buf, sizeof(buf));
				relay_close_http(con, 403,
				    "rejecting request", pn->label);
				return (PN_FAIL);
			}
		}
		next = SIMPLEQ_NEXT(pn, entry);
		if (next == NULL || next->action != pn->action)
			cre->nodes[proot->id]++;
		break;
	case NODE_ACTION_HASH:
		DPRINTF("%s: hash '%s: %s'", __func__,
		    pn->key, pk->value);
		con->se_hashkey = hash32_str(pk->value, con->se_hashkey);
		ret = PN_PASS;
		break;
	case NODE_ACTION_LOG:
		log_info("%s: log '%s: %s'", __func__, pn->key, pk->value);
		ret = PN_PASS;
		break;
	case NODE_ACTION_MARK:
		DPRINTF("%s: mark '%s: %s'", __func__,
		    pn->key, pk->value);
		if (fnmatch(pn->value, pk->value, FNM_CASEFOLD) == 0)
			con->se_mark = pn->mark;
		ret = PN_PASS;
		break;
	case NODE_ACTION_NONE:
		return (PN_PASS);
	}
	if (mark != -1 && relay_lognode(con, pn, pk, buf, sizeof(buf)) == -1)
		goto fail;

	return (ret);
 fail:
	relay_close_http(con, 500, strerror(errno), 0);
	return (PN_FAIL);
}

void
relay_read_httpcontent(struct bufferevent *bev, void *arg)
{
	struct ctl_relay_event	*cre = (struct ctl_relay_event *)arg;
	struct rsession		*con = cre->con;
	struct evbuffer		*src = EVBUFFER_INPUT(bev);
	size_t			 size;

	if (gettimeofday(&con->se_tv_last, NULL) == -1)
		goto fail;
	size = EVBUFFER_LENGTH(src);
	DPRINTF("%s: size %d, to read %d", __func__,
	    size, cre->toread);
	if (!size)
		return;
	if (relay_bufferevent_write_buffer(cre->dst, src) == -1)
		goto fail;
	if (size >= cre->toread)
		bev->readcb = relay_read_http;
	cre->toread -= size;
	DPRINTF("%s: done, size %d, to read %d", __func__,
	    size, cre->toread);
	if (con->se_done)
		goto done;
	if (bev->readcb != relay_read_httpcontent)
		bev->readcb(bev, arg);
	bufferevent_enable(bev, EV_READ);
	return;
 done:
	relay_close(con, "last http content read");
	return;
 fail:
	relay_close(con, strerror(errno));
}

void
relay_read_httpchunks(struct bufferevent *bev, void *arg)
{
	struct ctl_relay_event	*cre = (struct ctl_relay_event *)arg;
	struct rsession		*con = cre->con;
	struct evbuffer		*src = EVBUFFER_INPUT(bev);
	char			*line;
	long			 lval;
	size_t			 size;

	if (gettimeofday(&con->se_tv_last, NULL) == -1)
		goto fail;
	size = EVBUFFER_LENGTH(src);
	DPRINTF("%s: size %d, to read %d", __func__,
	    size, cre->toread);
	if (!size)
		return;

	if (!cre->toread) {
		line = evbuffer_readline(src);
		if (line == NULL) {
			/* Ignore empty line, continue */
			bufferevent_enable(bev, EV_READ);
			return;
		}
		if (!strlen(line)) {
			free(line);
			goto next;
		}

		/* Read prepended chunk size in hex, ingore the trailer */
		if (sscanf(line, "%lx", &lval) != 1) {
			free(line);
			relay_close(con, "invalid chunk size");
			return;
		}

		if (relay_bufferevent_print(cre->dst, line) == -1 ||
		    relay_bufferevent_print(cre->dst, "\r\n") == -1) {
			free(line);
			goto fail;
		}
		free(line);

		/* Last chunk is 0 bytes followed by an empty newline */
		if ((cre->toread = lval) == 0) {
			DPRINTF("%s: last chunk", __func__);

			line = evbuffer_readline(src);
			if (line == NULL) {
				relay_close(con, "invalid last chunk");
				return;
			}
			free(line);
			if (relay_bufferevent_print(cre->dst, "\r\n") == -1)
				goto fail;

			/* Switch to HTTP header mode */
			bev->readcb = relay_read_http;
		}
	} else {
		/* Read chunk data */
		if (size > cre->toread)
			size = cre->toread;
		if (relay_bufferevent_write_chunk(cre->dst, src, size) == -1)
			goto fail;
		cre->toread -= size;
		DPRINTF("%s: done, size %d, to read %d", __func__,
		    size, cre->toread);

		if (cre->toread == 0) {
			/* Chunk is terminated by an empty (empty) newline */
			line = evbuffer_readline(src);
			if (line != NULL)
				free(line);
			if (relay_bufferevent_print(cre->dst, "\r\n\r\n") == -1)
				goto fail;
		}
	}

 next:
	if (con->se_done)
		goto done;
	if (EVBUFFER_LENGTH(src))
		bev->readcb(bev, arg);
	bufferevent_enable(bev, EV_READ);
	return;

 done:
	relay_close(con, "last http chunk read (done)");
	return;
 fail:
	relay_close(con, strerror(errno));
}

void
relay_http_request_close(struct ctl_relay_event *cre)
{
	if (cre->path != NULL) {
		free(cre->path);
		cre->path = NULL;
	}

	cre->args = NULL;
	cre->version = NULL;

	if (cre->buf != NULL) {
		free(cre->buf);
		cre->buf = NULL;
		cre->buflen = 0;
	}

	cre->line = 0;
	cre->method = 0;
	cre->done = 0;
	cre->chunked = 0;
}

void
relay_read_http(struct bufferevent *bev, void *arg)
{
	struct ctl_relay_event	*cre = (struct ctl_relay_event *)arg;
	struct rsession		*con = cre->con;
	struct relay		*rlay = (struct relay *)con->se_relay;
	struct protocol		*proto = rlay->rl_proto;
	struct evbuffer		*src = EVBUFFER_INPUT(bev);
	struct protonode	*pn, pk, *proot, *pnv = NULL, pkv;
	char			*line;
	int			 header = 0, ret, pass = 0;
	const char		*errstr;
	size_t			 size;

	if (gettimeofday(&con->se_tv_last, NULL) == -1)
		goto fail;
	size = EVBUFFER_LENGTH(src);
	DPRINTF("%s: size %d, to read %d", __func__, size, cre->toread);
	if (!size) {
		if (cre->dir == RELAY_DIR_RESPONSE)
			return;
		cre->toread = 0;
		goto done;
	}

	pk.type = NODE_TYPE_HEADER;

	while (!cre->done && (line = evbuffer_readline(src)) != NULL) {
		/*
		 * An empty line indicates the end of the request.
		 * libevent already stripped the \r\n for us.
		 */
		if (!strlen(line)) {
			cre->done = 1;
			free(line);
			break;
		}
		pk.key = line;

		/*
		 * The first line is the GET/POST/PUT/... request,
		 * subsequent lines are HTTP headers.
		 */
		if (++cre->line == 1) {
			pk.value = strchr(pk.key, ' ');
		} else
			pk.value = strchr(pk.key, ':');
		if (pk.value == NULL || strlen(pk.value) < 3) {
			if (cre->line == 1) {
				free(line);
				relay_close_http(con, 400, "malformed", 0);
				return;
			}

			DPRINTF("%s: request '%s'", __func__, line);
			/* Append line to the output buffer */
			if (relay_bufferevent_print(cre->dst, line) == -1 ||
			    relay_bufferevent_print(cre->dst, "\r\n") == -1) {
				free(line);
				goto fail;
			}
			free(line);
			continue;
		}
		if (*pk.value == ':') {
			*pk.value++ = '\0';
			pk.value += strspn(pk.value, " \t\r\n");
			header = 1;
		} else {
			*pk.value++ = '\0';
			header = 0;
		}

		DPRINTF("%s: header '%s: %s'", __func__, pk.key, pk.value);

		/*
		 * Identify and handle specific HTTP request methods
		 */
		if (cre->line == 1) {
			if (cre->dir == RELAY_DIR_RESPONSE) {
				cre->method = HTTP_METHOD_RESPONSE;
				goto lookup;
			} else if (strcmp("HEAD", pk.key) == 0)
				cre->method = HTTP_METHOD_HEAD;
			else if (strcmp("POST", pk.key) == 0)
				cre->method = HTTP_METHOD_POST;
			else if (strcmp("PUT", pk.key) == 0)
				cre->method = HTTP_METHOD_PUT;
			else if (strcmp("DELETE", pk.key) == 0)
				cre->method = HTTP_METHOD_DELETE;
			else if (strcmp("OPTIONS", pk.key) == 0)
				cre->method = HTTP_METHOD_OPTIONS;
			else if (strcmp("TRACE", pk.key) == 0)
				cre->method = HTTP_METHOD_TRACE;
			else if (strcmp("CONNECT", pk.key) == 0)
				cre->method = HTTP_METHOD_CONNECT;
			else {
				/* Use GET method as the default */
				cre->method = HTTP_METHOD_GET;
			}

			/*
			 * Decode the path and query
			 */
			cre->path = strdup(pk.value);
			if (cre->path == NULL) {
				free(line);
				goto fail;
			}
			cre->version = strchr(cre->path, ' ');
			if (cre->version != NULL)
				*cre->version++ = '\0';
			cre->args = strchr(cre->path, '?');
			if (cre->args != NULL)
				*cre->args++ = '\0';
#ifdef DEBUG
			char	 buf[BUFSIZ];
			if (snprintf(buf, sizeof(buf), " \"%s\"",
			    cre->path) == -1 ||
			    evbuffer_add(con->se_log, buf, strlen(buf)) == -1) {
				free(line);
				goto fail;
			}
#endif

			/*
			 * Lookup protocol handlers in the URL path
			 */
			if ((proto->flags & F_LOOKUP_PATH) == 0)
				goto lookup;

			pkv.key = cre->path;
			pkv.type = NODE_TYPE_PATH;
			pkv.value = cre->args == NULL ? "" : cre->args;

			DPRINTF("%s: lookup path '%s: %s'",
			    __func__, pkv.key, pkv.value);

			if ((proot = RB_FIND(proto_tree,
			    cre->tree, &pkv)) == NULL)
				goto lookup;

			PROTONODE_FOREACH(pnv, proot, entry) {
				ret = relay_handle_http(cre, proot,
				    pnv, &pkv, 0);
				if (ret == PN_FAIL)
					goto abort;
			}
		} else if ((cre->method == HTTP_METHOD_POST ||
		    cre->method == HTTP_METHOD_PUT ||
		    cre->method == HTTP_METHOD_RESPONSE) &&
		    strcasecmp("Content-Length", pk.key) == 0) {
			/*
			 * Need to read data from the client after the
			 * HTTP header.
			 * XXX What about non-standard clients not using
			 * the carriage return? And some browsers seem to
			 * include the line length in the content-length.
			 */
			cre->toread = strtonum(pk.value, 0, INT_MAX, &errstr);
			if (errstr) {
				relay_close_http(con, 500, errstr, 0);
				goto abort;
			}
		}
 lookup:
		if (strcasecmp("Transfer-Encoding", pk.key) == 0 &&
		    strcasecmp("chunked", pk.value) == 0)
			cre->chunked = 1;

		/* Match the HTTP header */
		if ((pn = RB_FIND(proto_tree, cre->tree, &pk)) == NULL)
			goto next;

		if (cre->dir == RELAY_DIR_RESPONSE)
			goto handle;

		if (pn->flags & PNFLAG_LOOKUP_URL) {
			/*
			 * Lookup the URL of type example.com/path?args.
			 * Either as a plain string or SHA1/MD5 digest.
			 */
			if ((pn->flags & PNFLAG_LOOKUP_DIGEST(0)) &&
			    relay_lookup_url(cre, pk.value,
			    DIGEST_NONE) == PN_FAIL)
				goto abort;
			if ((pn->flags & PNFLAG_LOOKUP_DIGEST(DIGEST_SHA1)) &&
			    relay_lookup_url(cre, pk.value,
			    DIGEST_SHA1) == PN_FAIL)
				goto abort;
			if ((pn->flags & PNFLAG_LOOKUP_DIGEST(DIGEST_MD5)) &&
			    relay_lookup_url(cre, pk.value,
			    DIGEST_MD5) == PN_FAIL)
				goto abort;
		} else if (pn->flags & PNFLAG_LOOKUP_QUERY) {
			/* Lookup the HTTP query arguments */
			if (relay_lookup_query(cre) == PN_FAIL)
				goto abort;
		} else if (pn->flags & PNFLAG_LOOKUP_COOKIE) {
			/* Lookup the HTTP cookie */
			if (relay_lookup_cookie(cre, pk.value) == PN_FAIL)
				goto abort;
		}

 handle:
		pass = 0;
		PROTONODE_FOREACH(pnv, pn, entry) {
			ret = relay_handle_http(cre, pn, pnv, &pk, header);
			if (ret == PN_PASS)
				pass = 1;
			else if (ret == PN_FAIL)
				goto abort;
		}

		if (pass) {
 next:
			if (relay_bufferevent_print(cre->dst, pk.key) == -1 ||
			    relay_bufferevent_print(cre->dst,
			    header ? ": " : " ") == -1 ||
			    relay_bufferevent_print(cre->dst, pk.value) == -1 ||
			    relay_bufferevent_print(cre->dst, "\r\n") == -1) {
				free(line);
				goto fail;
			}
		}
		free(line);
	}
	if (cre->done) {
		RB_FOREACH(proot, proto_tree, cre->tree) {
			PROTONODE_FOREACH(pn, proot, entry)
				if (relay_resolve(cre, proot, pn) != 0)
					return;
		}

		switch (cre->method) {
		case HTTP_METHOD_NONE:
			relay_close_http(con, 406, "no method", 0);
			return;
		case HTTP_METHOD_CONNECT:
			/* Data stream */
			bev->readcb = relay_read;
			break;
		case HTTP_METHOD_POST:
		case HTTP_METHOD_PUT:
		case HTTP_METHOD_RESPONSE:
			/* HTTP request payload */
			if (cre->toread) {
				bev->readcb = relay_read_httpcontent;
				break;
			}

			/* Single-pass HTTP response */
			bev->readcb = relay_read;
			break;
		default:
			/* HTTP handler */
			bev->readcb = relay_read_http;
			break;
		}
		if (cre->chunked) {
			/* Chunked transfer encoding */
			cre->toread = 0;
			bev->readcb = relay_read_httpchunks;
		}

		/* Write empty newline and switch to relay mode */
		if (relay_bufferevent_print(cre->dst, "\r\n") == -1)
			goto fail;

		relay_http_request_close(cre);

 done:
		if (cre->dir == RELAY_DIR_REQUEST && !cre->toread &&
		    proto->lateconnect && cre->dst->bev == NULL) {
			if (rlay->rl_conf.fwdmode == FWD_TRANS) {
				relay_bindanyreq(con, 0, IPPROTO_TCP);
				return;
			}
			if (relay_connect(con) == -1)
				relay_close_http(con, 502, "session failed", 0);
			return;
		}
	}
	if (con->se_done) {
		relay_close(con, "last http read (done)");
		return;
	}
	if (EVBUFFER_LENGTH(src) && bev->readcb != relay_read_http)
		bev->readcb(bev, arg);
	bufferevent_enable(bev, EV_READ);
	return;
 fail:
	relay_close_http(con, 500, strerror(errno), 0);
	return;
 abort:
	free(line);
}

static int
_relay_lookup_url(struct ctl_relay_event *cre, char *host, char *path,
    char *query, enum digest_type type)
{
	struct rsession		*con = cre->con;
	struct protonode	*proot, *pnv, pkv;
	char			*val, *md = NULL;
	int			 ret = PN_FAIL;

	if (asprintf(&val, "%s%s%s%s",
	    host, path,
	    query == NULL ? "" : "?",
	    query == NULL ? "" : query) == -1) {
		relay_close_http(con, 500, "failed to allocate URL", 0);
		return (PN_FAIL);
	}

	DPRINTF("%s: %s", __func__, val);

	switch (type) {
	case DIGEST_SHA1:
	case DIGEST_MD5:
		if ((md = digeststr(type, val, strlen(val), NULL)) == NULL) {
			relay_close_http(con, 500,
			    "failed to allocate digest", 0);
			goto fail;
		}
		pkv.key = md;
		break;
	case DIGEST_NONE:
		pkv.key = val;
		break;
	}
	pkv.type = NODE_TYPE_URL;
	pkv.value = "";

	if ((proot = RB_FIND(proto_tree, cre->tree, &pkv)) == NULL)
		goto done;

	PROTONODE_FOREACH(pnv, proot, entry) {
		ret = relay_handle_http(cre, proot, pnv, &pkv, 0);
		if (ret == PN_FAIL)
			goto fail;
	}

 done:
	ret = PN_PASS;
 fail:
	if (md != NULL)
		free(md);
	free(val);
	return (ret);
}

int
relay_lookup_url(struct ctl_relay_event *cre, const char *str,
    enum digest_type type)
{
	struct rsession	*con = cre->con;
	int		 i, j, dots;
	char		*hi[RELAY_MAXLOOKUPLEVELS], *p, *pp, *c, ch;
	char		 ph[MAXHOSTNAMELEN];
	int		 ret;

	if (cre->path == NULL)
		return (PN_PASS);

	/*
	 * This is an URL lookup algorithm inspired by
	 * http://code.google.com/apis/safebrowsing/
	 *     developers_guide.html#PerformingLookups
	 */

	DPRINTF("%s: host: '%s', path: '%s', query: '%s'", __func__,
	    str, cre->path, cre->args == NULL ? "" : cre->args);

	if (canonicalize_host(str, ph, sizeof(ph)) == NULL) {
		relay_close_http(con, 400, "invalid host name", 0);
		return (PN_FAIL);
	}

	bzero(hi, sizeof(hi));
	for (dots = -1, i = strlen(ph) - 1; i > 0; i--) {
		if (ph[i] == '.' && ++dots)
			hi[dots - 1] = &ph[i + 1];
		if (dots > (RELAY_MAXLOOKUPLEVELS - 2))
			break;
	}
	if (dots == -1)
		dots = 0;
	hi[dots] = ph;

	if ((pp = strdup(cre->path)) == NULL) {
		relay_close_http(con, 500, "failed to allocate path", 0);
		return (PN_FAIL);
	}
	for (i = (RELAY_MAXLOOKUPLEVELS - 1); i >= 0; i--) {
		if (hi[i] == NULL)
			continue;

		/* 1. complete path with query */
		if (cre->args != NULL)
			if ((ret = _relay_lookup_url(cre, hi[i],
			    pp, cre->args, type)) != PN_PASS)
				goto done;

		/* 2. complete path without query */
		if ((ret = _relay_lookup_url(cre, hi[i],
		    pp, NULL, type)) != PN_PASS)
			goto done;

		/* 3. traverse path */
		for (j = 0, p = strchr(pp, '/');
		    p != NULL; p = strchr(p, '/'), j++) {
			if (j > (RELAY_MAXLOOKUPLEVELS - 2) || ++p == '\0')
				break;
			c = &pp[p - pp];
			ch = *c;
			*c = '\0';
			if ((ret = _relay_lookup_url(cre, hi[i],
			    pp, NULL, type)) != PN_PASS)
				goto done;
			*c = ch;
		}
	}

	ret = PN_PASS;
 done:
	free(pp);
	return (ret);
}

int
relay_lookup_query(struct ctl_relay_event *cre)
{
	struct rsession		*con = cre->con;
	struct protonode	*proot, *pnv, pkv;
	char			*val, *ptr;
	int			 ret;

	if (cre->path == NULL || cre->args == NULL || strlen(cre->args) < 2)
		return (PN_PASS);
	if ((val = strdup(cre->args)) == NULL) {
		relay_close_http(con, 500, "failed to allocate query", 0);
		return (PN_FAIL);
	}

	ptr = val;
	while (ptr != NULL && strlen(ptr)) {
		pkv.key = ptr;
		pkv.type = NODE_TYPE_QUERY;
		if ((ptr = strchr(ptr, '&')) != NULL)
			*ptr++ = '\0';
		if ((pkv.value =
		    strchr(pkv.key, '=')) == NULL ||
		    strlen(pkv.value) < 1)
			continue;
		*pkv.value++ = '\0';

		if ((proot = RB_FIND(proto_tree, cre->tree, &pkv)) == NULL)
			continue;
		PROTONODE_FOREACH(pnv, proot, entry) {
			ret = relay_handle_http(cre, proot,
			    pnv, &pkv, 0);
			if (ret == PN_FAIL)
				goto done;
		}
	}

	ret = PN_PASS;
 done:
	free(val);
	return (ret);
}

int
relay_lookup_cookie(struct ctl_relay_event *cre, const char *str)
{
	struct rsession		*con = cre->con;
	struct protonode	*proot, *pnv, pkv;
	char			*val, *ptr;
	int			 ret;

	if ((val = strdup(str)) == NULL) {
		relay_close_http(con, 500, "failed to allocate cookie", 0);
		return (PN_FAIL);
	}

	for (ptr = val; ptr != NULL && strlen(ptr);) {
		if (*ptr == ' ')
			*ptr++ = '\0';
		pkv.key = ptr;
		pkv.type = NODE_TYPE_COOKIE;
		if ((ptr = strchr(ptr, ';')) != NULL)
			*ptr++ = '\0';
		/*
		 * XXX We do not handle attributes
		 * ($Path, $Domain, or $Port)
		 */
		if (*pkv.key == '$')
			continue;

		if ((pkv.value =
		    strchr(pkv.key, '=')) == NULL ||
		    strlen(pkv.value) < 1)
			continue;
		*pkv.value++ = '\0';
		if (*pkv.value == '"')
			*pkv.value++ = '\0';
		if (pkv.value[strlen(pkv.value) - 1] == '"')
			pkv.value[strlen(pkv.value) - 1] = '\0';
		if ((proot = RB_FIND(proto_tree, cre->tree, &pkv)) == NULL)
			continue;
		PROTONODE_FOREACH(pnv, proot, entry) {
			ret = relay_handle_http(cre, proot, pnv, &pkv, 0);
			if (ret == PN_FAIL)
				goto done;
		}
	}

	ret = PN_PASS;
 done:
	free(val);
	return (ret);
}

void
relay_close_http(struct rsession *con, u_int code, const char *msg,
    u_int16_t labelid)
{
	struct relay		*rlay = (struct relay *)con->se_relay;
	struct bufferevent	*bev = con->se_in.bev;
	const char		*httperr = print_httperror(code), *text = "";
	char			*httpmsg;
	time_t			 t;
	struct tm		*lt;
	char			 tmbuf[32], hbuf[128];
	const char		*style, *label = NULL;

	/* In some cases this function may be called from generic places */
	if (rlay->rl_proto->type != RELAY_PROTO_HTTP ||
	    (rlay->rl_proto->flags & F_RETURN) == 0) {
		relay_close(con, msg);
		return;
	}

	if (bev == NULL)
		goto done;

	/* Some system information */
	if (print_host(&rlay->rl_conf.ss, hbuf, sizeof(hbuf)) == NULL)
		goto done;

	/* RFC 2616 "tolerates" asctime() */
	time(&t);
	lt = localtime(&t);
	tmbuf[0] = '\0';
	if (asctime_r(lt, tmbuf) != NULL)
		tmbuf[strlen(tmbuf) - 1] = '\0';	/* skip final '\n' */

	/* Do not send details of the Internal Server Error */
	if (code != 500)
		text = msg;
	if (labelid != 0)
		label = pn_id2name(labelid);

	/* A CSS stylesheet allows minimal customization by the user */
	if ((style = rlay->rl_proto->style) == NULL)
		style = "body { background-color: #a00000; color: white; }";

	/* Generate simple HTTP+HTML error document */
	if (asprintf(&httpmsg,
	    "HTTP/1.x %03d %s\r\n"
	    "Date: %s\r\n"
	    "Server: %s\r\n"
	    "Connection: close\r\n"
	    "Content-Type: text/html\r\n"
	    "\r\n"
	    "<!DOCTYPE HTML PUBLIC "
	    "\"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"
	    "<html>\n"
	    "<head>\n"
	    "<title>%03d %s</title>\n"
	    "<style type=\"text/css\"><!--\n%s\n--></style>\n"
	    "</head>\n"
	    "<body>\n"
	    "<h1>%s</h1>\n"
	    "<div id='m'>%s</div>\n"
	    "<div id='l'>%s</div>\n"
	    "<hr><address>%s at %s port %d</address>\n"
	    "</body>\n"
	    "</html>\n",
	    code, httperr, tmbuf, RELAYD_SERVERNAME,
	    code, httperr, style, httperr, text,
	    label == NULL ? "" : label,
	    RELAYD_SERVERNAME, hbuf, ntohs(rlay->rl_conf.port)) == -1)
		goto done;

	/* Dump the message without checking for success */
	relay_dump(&con->se_in, httpmsg, strlen(httpmsg));
	free(httpmsg);

 done:
	if (asprintf(&httpmsg, "%s (%03d %s)", msg, code, httperr) == -1)
		relay_close(con, msg);
	else {
		relay_close(con, httpmsg);
		free(httpmsg);
	}
}

int
relay_splice(struct ctl_relay_event *cre)
{
	struct rsession		*con = cre->con;
	struct relay		*rlay = (struct relay *)con->se_relay;
	struct protocol		*proto = rlay->rl_proto;
	struct splice		 sp;

	if ((rlay->rl_conf.flags & (F_SSL|F_SSLCLIENT)) ||
	    (proto->tcpflags & TCPFLAG_NSPLICE))
		return (0);

	if (cre->bev->readcb != relay_read)
		return (0);

	bzero(&sp, sizeof(sp));
	sp.sp_fd = cre->dst->s;
	sp.sp_idle = rlay->rl_conf.timeout;
	if (setsockopt(cre->s, SOL_SOCKET, SO_SPLICE, &sp, sizeof(sp)) == -1) {
		log_debug("%s: session %d: splice dir %d failed: %s",
		    __func__, con->se_id, cre->dir, strerror(errno));
		return (-1);
	}
	cre->splicelen = 0;
	DPRINTF("%s: session %d: splice dir %d successful",
	    __func__, con->se_id, cre->dir);
	return (1);
}

int
relay_splicelen(struct ctl_relay_event *cre)
{
	struct rsession		*con = cre->con;
	off_t			 len;
	socklen_t		 optlen;

	optlen = sizeof(len);
	if (getsockopt(cre->s, SOL_SOCKET, SO_SPLICE, &len, &optlen) == -1) {
		log_debug("%s: session %d: splice dir %d get length failed: %s",
		    __func__, con->se_id, cre->dir, strerror(errno));
		return (-1);
	}
	if (len > cre->splicelen) {
		cre->splicelen = len;
		return (1);
	}
	return (0);
}

void
relay_error(struct bufferevent *bev, short error, void *arg)
{
	struct ctl_relay_event *cre = (struct ctl_relay_event *)arg;
	struct rsession *con = cre->con;
	struct evbuffer *dst;

	if (error & EVBUFFER_TIMEOUT) {
		if (cre->splicelen >= 0) {
			bufferevent_enable(bev, EV_READ);
		} else if (cre->dst->splicelen >= 0) {
			switch (relay_splicelen(cre->dst)) {
			case -1:
				goto fail;
			case 0:
				relay_close(con, "buffer event timeout");
				break;
			case 1:
				bufferevent_enable(bev, EV_READ);
				break;
			}
		} else {
			relay_close(con, "buffer event timeout");
		}
		return;
	}
	if (error & EVBUFFER_ERROR && errno == ETIMEDOUT) {
		if (cre->dst->splicelen >= 0) {
			switch (relay_splicelen(cre->dst)) {
			case -1:
				goto fail;
			case 0:
				relay_close(con, "splice timeout");
				return;
			case 1:
				bufferevent_enable(bev, EV_READ);
				break;
			}
		}
		if (relay_splice(cre) == -1)
			goto fail;
		return;
	}
	if (error & (EVBUFFER_READ|EVBUFFER_WRITE|EVBUFFER_EOF)) {
		bufferevent_disable(bev, EV_READ|EV_WRITE);

		con->se_done = 1;
		if (cre->dst->bev != NULL) {
			dst = EVBUFFER_OUTPUT(cre->dst->bev);
			if (EVBUFFER_LENGTH(dst))
				return;
		} else
			return;

		relay_close(con, "done");
		return;
	}
	relay_close(con, "buffer event error");
	return;
 fail:
	relay_close(con, strerror(errno));
}

void
relay_accept(int fd, short sig, void *arg)
{
	struct relay *rlay = (struct relay *)arg;
	struct protocol *proto = rlay->rl_proto;
	struct rsession *con = NULL;
	struct ctl_natlook *cnl = NULL;
	socklen_t slen;
	struct timeval tv;
	struct sockaddr_storage ss;
	int s = -1;

	slen = sizeof(ss);
	if ((s = accept(fd, (struct sockaddr *)&ss, (socklen_t *)&slen)) == -1)
		return;

	if (relay_sessions >= RELAY_MAX_SESSIONS ||
	    rlay->rl_conf.flags & F_DISABLE)
		goto err;

	if (fcntl(s, F_SETFL, O_NONBLOCK) == -1)
		goto err;

	if ((con = calloc(1, sizeof(*con))) == NULL)
		goto err;

	con->se_in.s = s;
	con->se_in.ssl = NULL;
	con->se_out.s = -1;
	con->se_out.ssl = NULL;
	con->se_in.dst = &con->se_out;
	con->se_out.dst = &con->se_in;
	con->se_in.con = con;
	con->se_out.con = con;
	con->se_in.splicelen = -1;
	con->se_out.splicelen = -1;
	con->se_relay = rlay;
	con->se_id = ++relay_conid;
	con->se_relayid = rlay->rl_conf.id;
	con->se_pid = getpid();
	con->se_hashkey = rlay->rl_dstkey;
	con->se_in.tree = &proto->request_tree;
	con->se_out.tree = &proto->response_tree;
	con->se_in.dir = RELAY_DIR_REQUEST;
	con->se_out.dir = RELAY_DIR_RESPONSE;
	con->se_retry = rlay->rl_conf.dstretry;
	con->se_bnds = -1;
	if (gettimeofday(&con->se_tv_start, NULL) == -1)
		goto err;
	bcopy(&con->se_tv_start, &con->se_tv_last, sizeof(con->se_tv_last));
	bcopy(&ss, &con->se_in.ss, sizeof(con->se_in.ss));
	con->se_out.port = rlay->rl_conf.dstport;
	switch (ss.ss_family) {
	case AF_INET:
		con->se_in.port = ((struct sockaddr_in *)&ss)->sin_port;
		break;
	case AF_INET6:
		con->se_in.port = ((struct sockaddr_in6 *)&ss)->sin6_port;
		break;
	}

	relay_sessions++;
	SPLAY_INSERT(session_tree, &rlay->rl_sessions, con);

	/* Increment the per-relay session counter */
	rlay->rl_stats[proc_id].last++;

	/* Pre-allocate output buffer */
	con->se_out.output = evbuffer_new();
	if (con->se_out.output == NULL) {
		relay_close(con, "failed to allocate output buffer");
		return;
	}

	/* Pre-allocate log buffer */
	con->se_log = evbuffer_new();
	if (con->se_log == NULL) {
		relay_close(con, "failed to allocate log buffer");
		return;
	}

	if (rlay->rl_conf.flags & F_DIVERT) {
		slen = sizeof(con->se_out.ss);
		if (getsockname(s, (struct sockaddr *)&con->se_out.ss,
		    &slen) == -1) {
			relay_close(con, "peer lookup failed");
			return;
		}
		con->se_out.port = relay_socket_getport(&con->se_out.ss);

		/* Detect loop and fall back to the alternate forward target */
		if (bcmp(&rlay->rl_conf.ss, &con->se_out.ss,
		    sizeof(con->se_out.ss)) == 0 &&
		    con->se_out.port == rlay->rl_conf.port)
			con->se_out.ss.ss_family = AF_UNSPEC;
	} else if (rlay->rl_conf.flags & F_NATLOOK) {
		if ((cnl = (struct ctl_natlook *)
		    calloc(1, sizeof(struct ctl_natlook))) == NULL) {
			relay_close(con, "failed to allocate nat lookup");
			return;
		}

		con->se_cnl = cnl;
		bzero(cnl, sizeof(*cnl));
		cnl->in = -1;
		cnl->id = con->se_id;
		cnl->proc = proc_id;
		cnl->proto = IPPROTO_TCP;

		bcopy(&con->se_in.ss, &cnl->src, sizeof(cnl->src));
		slen = sizeof(cnl->dst);
		if (getsockname(s,
		    (struct sockaddr *)&cnl->dst, &slen) == -1) {
			relay_close(con, "failed to get local address");
			return;
		}

		proc_compose_imsg(env->sc_ps, PROC_PFE, -1, IMSG_NATLOOK, -1,
		    cnl, sizeof(*cnl));

		/* Schedule timeout */
		evtimer_set(&con->se_ev, relay_natlook, con);
		bcopy(&rlay->rl_conf.timeout, &tv, sizeof(tv));
		evtimer_add(&con->se_ev, &tv);
		return;
	}

	relay_session(con);
	return;
 err:
	if (s != -1) {
		close(s);
		if (con != NULL)
			free(con);
	}
}

u_int32_t
relay_hash_addr(struct sockaddr_storage *ss, u_int32_t p)
{
	struct sockaddr_in	*sin4;
	struct sockaddr_in6	*sin6;

	if (ss->ss_family == AF_INET) {
		sin4 = (struct sockaddr_in *)ss;
		p = hash32_buf(&sin4->sin_addr,
		    sizeof(struct in_addr), p);
	} else {
		sin6 = (struct sockaddr_in6 *)ss;
		p = hash32_buf(&sin6->sin6_addr,
		    sizeof(struct in6_addr), p);
	}

	return (p);
}

int
relay_from_table(struct rsession *con)
{
	struct relay		*rlay = (struct relay *)con->se_relay;
	struct host		*host;
	struct table		*table = rlay->rl_dsttable;
	u_int32_t		 p = con->se_hashkey;
	int			 idx = 0;

	if (table->conf.check && !table->up && !rlay->rl_backuptable->up) {
		log_debug("%s: no active hosts", __func__);
		return (-1);
	} else if (!table->up && rlay->rl_backuptable->up) {
		table = rlay->rl_backuptable;
	}

	switch (rlay->rl_conf.dstmode) {
	case RELAY_DSTMODE_ROUNDROBIN:
		if ((int)rlay->rl_dstkey >= rlay->rl_dstnhosts)
			rlay->rl_dstkey = 0;
		idx = (int)rlay->rl_dstkey;
		break;
	case RELAY_DSTMODE_LOADBALANCE:
		p = relay_hash_addr(&con->se_in.ss, p);
		/* FALLTHROUGH */
	case RELAY_DSTMODE_HASH:
		p = relay_hash_addr(&rlay->rl_conf.ss, p);
		p = hash32_buf(&rlay->rl_conf.port,
		    sizeof(rlay->rl_conf.port), p);
		if ((idx = p % rlay->rl_dstnhosts) >= RELAY_MAXHOSTS)
			return (-1);
	}
	host = rlay->rl_dsthost[idx];
	DPRINTF("%s: host %s, p 0x%08x, idx %d", __func__,
	    host->conf.name, p, idx);
	while (host != NULL) {
		DPRINTF("%s: host %s", __func__, host->conf.name);
		if (!table->conf.check || host->up == HOST_UP)
			goto found;
		host = TAILQ_NEXT(host, entry);
	}
	TAILQ_FOREACH(host, &table->hosts, entry) {
		DPRINTF("%s: next host %s", __func__, host->conf.name);
		if (!table->conf.check || host->up == HOST_UP)
			goto found;
	}

	/* Should not happen */
	fatalx("relay_from_table: no active hosts, desynchronized");

 found:
	if (rlay->rl_conf.dstmode == RELAY_DSTMODE_ROUNDROBIN)
		rlay->rl_dstkey = host->idx + 1;
	con->se_retry = host->conf.retry;
	con->se_out.port = table->conf.port;
	bcopy(&host->conf.ss, &con->se_out.ss, sizeof(con->se_out.ss));

	return (0);
}

void
relay_natlook(int fd, short event, void *arg)
{
	struct rsession		*con = (struct rsession *)arg;
	struct relay		*rlay = (struct relay *)con->se_relay;
	struct ctl_natlook	*cnl = con->se_cnl;

	if (cnl == NULL)
		fatalx("invalid NAT lookup");

	if (con->se_out.ss.ss_family == AF_UNSPEC && cnl->in == -1 &&
	    rlay->rl_conf.dstss.ss_family == AF_UNSPEC &&
	    rlay->rl_dsttable == NULL) {
		relay_close(con, "session NAT lookup failed");
		return;
	}
	if (cnl->in != -1) {
		bcopy(&cnl->rdst, &con->se_out.ss, sizeof(con->se_out.ss));
		con->se_out.port = cnl->rdport;
	}
	free(con->se_cnl);
	con->se_cnl = NULL;

	relay_session(con);
}

void
relay_session(struct rsession *con)
{
	struct relay		*rlay = (struct relay *)con->se_relay;
	struct ctl_relay_event	*in = &con->se_in, *out = &con->se_out;

	if (bcmp(&rlay->rl_conf.ss, &out->ss, sizeof(out->ss)) == 0 &&
	    out->port == rlay->rl_conf.port) {
		log_debug("%s: session %d: looping", __func__, con->se_id);
		relay_close(con, "session aborted");
		return;
	}

	if (rlay->rl_conf.flags & F_UDP) {
		/*
		 * Call the UDP protocol-specific handler
		 */
		if (rlay->rl_proto->request == NULL)
			fatalx("invalide UDP session");
		if ((*rlay->rl_proto->request)(con) == -1)
			relay_close(con, "session failed");
		return;
	}

	if ((rlay->rl_conf.flags & F_SSL) && (in->ssl == NULL)) {
		relay_ssl_transaction(con, in);
		return;
	}

	if (!rlay->rl_proto->lateconnect) {
		if (rlay->rl_conf.fwdmode == FWD_TRANS)
			relay_bindanyreq(con, 0, IPPROTO_TCP);
		else if (relay_connect(con) == -1) {
			relay_close(con, "session failed");
			return;
		}
	}

	relay_input(con);
}

void
relay_bindanyreq(struct rsession *con, in_port_t port, int proto)
{
	struct relay		*rlay = (struct relay *)con->se_relay;
	struct ctl_bindany	 bnd;
	struct timeval		 tv;

	bzero(&bnd, sizeof(bnd));
	bnd.bnd_id = con->se_id;
	bnd.bnd_proc = proc_id;
	bnd.bnd_port = port;
	bnd.bnd_proto = proto;
	bcopy(&con->se_in.ss, &bnd.bnd_ss, sizeof(bnd.bnd_ss));
	proc_compose_imsg(env->sc_ps, PROC_PARENT, -1, IMSG_BINDANY,
	    -1, &bnd, sizeof(bnd));

	/* Schedule timeout */
	evtimer_set(&con->se_ev, relay_bindany, con);
	bcopy(&rlay->rl_conf.timeout, &tv, sizeof(tv));
	evtimer_add(&con->se_ev, &tv);
}

void
relay_bindany(int fd, short event, void *arg)
{
	struct rsession	*con = (struct rsession *)arg;

	if (con->se_bnds == -1) {
		relay_close(con, "bindany failed, invalid socket");
		return;
	}

	if (relay_connect(con) == -1)
		relay_close(con, "session failed");
}

int
relay_connect(struct rsession *con)
{
	struct relay	*rlay = (struct relay *)con->se_relay;
	int		 bnds = -1, ret;

	if (gettimeofday(&con->se_tv_start, NULL) == -1)
		return (-1);

	if (rlay->rl_dsttable != NULL) {
		if (relay_from_table(con) != 0)
			return (-1);
	} else if (con->se_out.ss.ss_family == AF_UNSPEC) {
		bcopy(&rlay->rl_conf.dstss, &con->se_out.ss,
		    sizeof(con->se_out.ss));
		con->se_out.port = rlay->rl_conf.dstport;
	}

	if (rlay->rl_conf.fwdmode == FWD_TRANS) {
		if (con->se_bnds == -1) {
			log_debug("%s: could not bind any sock", __func__);
			return (-1);
		}
		bnds = con->se_bnds;
	}

	/* Do the IPv4-to-IPv6 or IPv6-to-IPv4 translation if requested */
	if (rlay->rl_conf.dstaf.ss_family != AF_UNSPEC) {
		if (con->se_out.ss.ss_family == AF_INET &&
		    rlay->rl_conf.dstaf.ss_family == AF_INET6)
			ret = map4to6(&con->se_out.ss, &rlay->rl_conf.dstaf);
		else if (con->se_out.ss.ss_family == AF_INET6 &&
		    rlay->rl_conf.dstaf.ss_family == AF_INET)
			ret = map6to4(&con->se_out.ss);
		else
			ret = 0;
		if (ret != 0) {
			log_debug("%s: mapped to invalid address", __func__);
			return (-1);
		}
	}

 retry:
	if ((con->se_out.s = relay_socket_connect(&con->se_out.ss,
	    con->se_out.port, rlay->rl_proto, bnds)) == -1) {
		if (con->se_retry) {
			con->se_retry--;
			log_debug("%s: session %d: "
			    "forward failed: %s, %s", __func__,
			    con->se_id, strerror(errno),
			    con->se_retry ? "next retry" : "last retry");
			goto retry;
		}
		log_debug("%s: session %d: forward failed: %s", __func__,
		    con->se_id, strerror(errno));
		return (-1);
	}

	if (errno == EINPROGRESS)
		event_again(&con->se_ev, con->se_out.s, EV_WRITE|EV_TIMEOUT,
		    relay_connected, &con->se_tv_start, &rlay->rl_conf.timeout,
		    con);
	else
		relay_connected(con->se_out.s, EV_WRITE, con);

	return (0);
}

void
relay_close(struct rsession *con, const char *msg)
{
	struct relay	*rlay = (struct relay *)con->se_relay;
	char		 ibuf[128], obuf[128], *ptr = NULL;

	SPLAY_REMOVE(session_tree, &rlay->rl_sessions, con);

	event_del(&con->se_ev);
	if (con->se_in.bev != NULL)
		bufferevent_disable(con->se_in.bev, EV_READ|EV_WRITE);
	if (con->se_out.bev != NULL)
		bufferevent_disable(con->se_out.bev, EV_READ|EV_WRITE);

	if ((env->sc_opts & RELAYD_OPT_LOGUPDATE) && msg != NULL) {
		bzero(&ibuf, sizeof(ibuf));
		bzero(&obuf, sizeof(obuf));
		(void)print_host(&con->se_in.ss, ibuf, sizeof(ibuf));
		(void)print_host(&con->se_out.ss, obuf, sizeof(obuf));
		if (EVBUFFER_LENGTH(con->se_log) &&
		    evbuffer_add_printf(con->se_log, "\r\n") != -1)
			ptr = evbuffer_readline(con->se_log);
		log_info("relay %s, "
		    "session %d (%d active), %d, %s -> %s:%d, "
		    "%s%s%s", rlay->rl_conf.name, con->se_id, relay_sessions,
		    con->se_mark, ibuf, obuf, ntohs(con->se_out.port), msg,
		    ptr == NULL ? "" : ",", ptr == NULL ? "" : ptr);
		if (ptr != NULL)
			free(ptr);
	}

	if (con->se_priv != NULL)
		free(con->se_priv);
	if (con->se_in.bev != NULL)
		bufferevent_free(con->se_in.bev);
	else if (con->se_in.output != NULL)
		evbuffer_free(con->se_in.output);
	if (con->se_in.ssl != NULL) {
		/* XXX handle non-blocking shutdown */
		if (SSL_shutdown(con->se_in.ssl) == 0)
			SSL_shutdown(con->se_in.ssl);
		SSL_free(con->se_in.ssl);
	}
	if (con->se_in.s != -1)
		close(con->se_in.s);
	if (con->se_in.path != NULL)
		free(con->se_in.path);
	if (con->se_in.buf != NULL)
		free(con->se_in.buf);
	if (con->se_in.nodes != NULL)
		free(con->se_in.nodes);

	if (con->se_out.bev != NULL)
		bufferevent_free(con->se_out.bev);
	else if (con->se_out.output != NULL)
		evbuffer_free(con->se_out.output);
	if (con->se_out.ssl != NULL) {
		/* XXX handle non-blocking shutdown */
		if (SSL_shutdown(con->se_out.ssl) == 0)
			SSL_shutdown(con->se_out.ssl);
		SSL_free(con->se_out.ssl);
	}
	if (con->se_out.s != -1)
		close(con->se_out.s);
	if (con->se_out.path != NULL)
		free(con->se_out.path);
	if (con->se_out.buf != NULL)
		free(con->se_out.buf);
	if (con->se_out.nodes != NULL)
		free(con->se_out.nodes);

	if (con->se_log != NULL)
		evbuffer_free(con->se_log);

	if (con->se_cnl != NULL) {
#if 0
		proc_compose_imsg(env->sc_ps, PROC_PFE, -1, IMSG_KILLSTATES, -1,
		    cnl, sizeof(*cnl));
#endif
		free(con->se_cnl);
	}

	free(con);
	relay_sessions--;
}

int
relay_dispatch_pfe(int fd, struct privsep_proc *p, struct imsg *imsg)
{
	struct relay		*rlay;
	struct rsession		*con, se;
	struct ctl_natlook	 cnl;
	struct timeval		 tv;
	struct host		*host;
	struct table		*table;
	struct ctl_status	 st;
	objid_t			 id;
	int			 cid;

	switch (imsg->hdr.type) {
	case IMSG_HOST_DISABLE:
		memcpy(&id, imsg->data, sizeof(id));
		if ((host = host_find(env, id)) == NULL)
			fatalx("relay_dispatch_pfe: desynchronized");
		if ((table = table_find(env, host->conf.tableid)) ==
		    NULL)
			fatalx("relay_dispatch_pfe: invalid table id");
		if (host->up == HOST_UP)
			table->up--;
		host->flags |= F_DISABLE;
		host->up = HOST_UNKNOWN;
		break;
	case IMSG_HOST_ENABLE:
		memcpy(&id, imsg->data, sizeof(id));
		if ((host = host_find(env, id)) == NULL)
			fatalx("relay_dispatch_pfe: desynchronized");
		host->flags &= ~(F_DISABLE);
		host->up = HOST_UNKNOWN;
		break;
	case IMSG_TABLE_DISABLE:
		memcpy(&id, imsg->data, sizeof(id));
		if ((table = table_find(env, id)) == NULL)
			fatalx("relay_dispatch_pfe: desynchronized");
		table->conf.flags |= F_DISABLE;
		table->up = 0;
		TAILQ_FOREACH(host, &table->hosts, entry)
			host->up = HOST_UNKNOWN;
		break;
	case IMSG_TABLE_ENABLE:
		memcpy(&id, imsg->data, sizeof(id));
		if ((table = table_find(env, id)) == NULL)
			fatalx("relay_dispatch_pfe: desynchronized");
		table->conf.flags &= ~(F_DISABLE);
		table->up = 0;
		TAILQ_FOREACH(host, &table->hosts, entry)
			host->up = HOST_UNKNOWN;
		break;
	case IMSG_HOST_STATUS:
		IMSG_SIZE_CHECK(imsg, &st);
		memcpy(&st, imsg->data, sizeof(st));
		if ((host = host_find(env, st.id)) == NULL)
			fatalx("relay_dispatch_pfe: invalid host id");
		if (host->flags & F_DISABLE)
			break;
		if (host->up == st.up) {
			log_debug("%s: host %d => %d", __func__,
			    host->conf.id, host->up);
			fatalx("relay_dispatch_pfe: desynchronized");
		}

		if ((table = table_find(env, host->conf.tableid))
		    == NULL)
			fatalx("relay_dispatch_pfe: invalid table id");

		DPRINTF("%s: [%d] state %d for "
		    "host %u %s", __func__, proc_id, st.up,
		    host->conf.id, host->conf.name);

		if ((st.up == HOST_UNKNOWN && host->up == HOST_DOWN) ||
		    (st.up == HOST_DOWN && host->up == HOST_UNKNOWN)) {
			host->up = st.up;
			break;
		}
		if (st.up == HOST_UP)
			table->up++;
		else
			table->up--;
		host->up = st.up;
		break;
	case IMSG_NATLOOK:
		bcopy(imsg->data, &cnl, sizeof(cnl));
		if ((con = session_find(env, cnl.id)) == NULL ||
		    con->se_cnl == NULL) {
			log_debug("%s: session %d: expired",
			    __func__, cnl.id);
			break;
		}
		bcopy(&cnl, con->se_cnl, sizeof(*con->se_cnl));
		evtimer_del(&con->se_ev);
		evtimer_set(&con->se_ev, relay_natlook, con);
		bzero(&tv, sizeof(tv));
		evtimer_add(&con->se_ev, &tv);
		break;
	case IMSG_CTL_SESSION:
		IMSG_SIZE_CHECK(imsg, &cid);
		memcpy(&cid, imsg->data, sizeof(cid));
		TAILQ_FOREACH(rlay, env->sc_relays, rl_entry) {
			SPLAY_FOREACH(con, session_tree,
			    &rlay->rl_sessions) {
				memcpy(&se, con, sizeof(se));
				se.se_cid = cid;
				proc_compose_imsg(env->sc_ps, p->p_id, -1,
				    IMSG_CTL_SESSION,
				    -1, &se, sizeof(se));
			}
		}
		proc_compose_imsg(env->sc_ps, p->p_id, -1, IMSG_CTL_END,
		    -1, &cid, sizeof(cid));
		break;
	default:
		return (-1);
	}

	return (0);
}

int
relay_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)
{
	struct rsession		*con;
	struct timeval		 tv;
	objid_t			 id;

	switch (imsg->hdr.type) {
	case IMSG_BINDANY:
		bcopy(imsg->data, &id, sizeof(id));
		if ((con = session_find(env, id)) == NULL) {
			log_debug("%s: session %d: expired",
			    __func__, id);
			break;
		}

		/* Will validate the result later */
		con->se_bnds = imsg->fd;

		evtimer_del(&con->se_ev);
		evtimer_set(&con->se_ev, relay_bindany, con);
		bzero(&tv, sizeof(tv));
		evtimer_add(&con->se_ev, &tv);
		break;
	case IMSG_CFG_TABLE:
		config_gettable(env, imsg);
		break;
	case IMSG_CFG_HOST:
		config_gethost(env, imsg);
		break;
	case IMSG_CFG_PROTO:
		config_getproto(env, imsg);
		break;
	case IMSG_CFG_PROTONODE:
		return (config_getprotonode(env, imsg));
	case IMSG_CFG_RELAY:
		config_getrelay(env, imsg);
		break;
	case IMSG_CFG_DONE:
		config_getcfg(env, imsg);
		break;
	case IMSG_CTL_START:
		relay_launch();
		break;
	case IMSG_CTL_RESET:
		config_getreset(env, imsg);
		break;
	default:
		return (-1);
	}

	return (0);
}

SSL_CTX *
relay_ssl_ctx_create(struct relay *rlay)
{
	struct protocol *proto = rlay->rl_proto;
	SSL_CTX *ctx;

	ctx = SSL_CTX_new(SSLv23_method());
	if (ctx == NULL)
		goto err;

	/* Modify session timeout and cache size*/
	SSL_CTX_set_timeout(ctx, rlay->rl_conf.timeout.tv_sec);
	if (proto->cache < -1) {
		SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
	} else if (proto->cache >= -1) {
		SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER);
		if (proto->cache >= 0)
			SSL_CTX_sess_set_cache_size(ctx, proto->cache);
	}

	/* Enable all workarounds and set SSL options */
	SSL_CTX_set_options(ctx, SSL_OP_ALL);
	SSL_CTX_set_options(ctx,
	    SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);

	/* Set the allowed SSL protocols */
	if ((proto->sslflags & SSLFLAG_SSLV2) == 0)
		SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
	if ((proto->sslflags & SSLFLAG_SSLV3) == 0)
		SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3);
	if ((proto->sslflags & SSLFLAG_TLSV1) == 0)
		SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1);

	if (!SSL_CTX_set_cipher_list(ctx, proto->sslciphers))
		goto err;

	/* Verify the server certificate if we have a CA chain */
	if ((rlay->rl_conf.flags & F_SSLCLIENT) &&
	    (rlay->rl_ssl_ca != NULL)) {
		if (!ssl_ctx_load_verify_memory(ctx,
		    rlay->rl_ssl_ca, rlay->rl_conf.ssl_ca_len))
			goto err;
		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
	}

	if ((rlay->rl_conf.flags & F_SSL) == 0)
		return (ctx);

	log_debug("%s: loading certificate", __func__);
	if (!ssl_ctx_use_certificate_chain(ctx,
	    rlay->rl_ssl_cert, rlay->rl_conf.ssl_cert_len))
		goto err;

	log_debug("%s: loading private key", __func__);
	if (!ssl_ctx_use_private_key(ctx, rlay->rl_ssl_key,
	    rlay->rl_conf.ssl_key_len))
		goto err;
	if (!SSL_CTX_check_private_key(ctx))
		goto err;

	/* Set session context to the local relay name */
	if (!SSL_CTX_set_session_id_context(ctx, rlay->rl_conf.name,
	    strlen(rlay->rl_conf.name)))
		goto err;

	return (ctx);

 err:
	if (ctx != NULL)
		SSL_CTX_free(ctx);
	ssl_error(rlay->rl_conf.name, "relay_ssl_ctx_create");
	return (NULL);
}

void
relay_ssl_transaction(struct rsession *con, struct ctl_relay_event *cre)
{
	struct relay		*rlay = (struct relay *)con->se_relay;
	SSL			*ssl;
	const SSL_METHOD	*method;
	void			(*cb)(int, short, void *);
	u_int			 flag;

	ssl = SSL_new(rlay->rl_ssl_ctx);
	if (ssl == NULL)
		goto err;

	if (cre->dir == RELAY_DIR_REQUEST) {
		cb = relay_ssl_accept;
		method = SSLv23_server_method();
		flag = EV_READ;
	} else {
		cb = relay_ssl_connect;
		method = SSLv23_client_method();
		flag = EV_WRITE;
	}

	if (!SSL_set_ssl_method(ssl, method))
		goto err;
	if (!SSL_set_fd(ssl, cre->s))
		goto err;

	if (cre->dir == RELAY_DIR_REQUEST)
		SSL_set_accept_state(ssl);
	else
		SSL_set_connect_state(ssl);

	cre->ssl = ssl;

	DPRINTF("%s: session %d: scheduling on %s", __func__, con->se_id,
	    (flag == EV_READ) ? "EV_READ" : "EV_WRITE");
	event_again(&con->se_ev, cre->s, EV_TIMEOUT|flag, cb,
	    &con->se_tv_start, &rlay->rl_conf.timeout, con);
	return;

 err:
	if (ssl != NULL)
		SSL_free(ssl);
	ssl_error(rlay->rl_conf.name, "relay_ssl_transaction");
	relay_close(con, "session ssl failed");
}

void
relay_ssl_accept(int fd, short event, void *arg)
{
	struct rsession	*con = (struct rsession *)arg;
	struct relay	*rlay = (struct relay *)con->se_relay;
	int		 ret;
	int		 ssl_err;
	int		 retry_flag;

	if (event == EV_TIMEOUT) {
		relay_close(con, "SSL accept timeout");
		return;
	}

	retry_flag = ssl_err = 0;

	ret = SSL_accept(con->se_in.ssl);
	if (ret <= 0) {
		ssl_err = SSL_get_error(con->se_in.ssl, ret);

		switch (ssl_err) {
		case SSL_ERROR_WANT_READ:
			retry_flag = EV_READ;
			goto retry;
		case SSL_ERROR_WANT_WRITE:
			retry_flag = EV_WRITE;
			goto retry;
		case SSL_ERROR_ZERO_RETURN:
		case SSL_ERROR_SYSCALL:
			if (ret == 0) {
				relay_close(con, "closed");
				return;
			}
			/* FALLTHROUGH */
		default:
			ssl_error(rlay->rl_conf.name, "relay_ssl_accept");
			relay_close(con, "SSL accept error");
			return;
		}
	}


#ifdef DEBUG
	log_info(
#else
	log_debug(
#endif
	    "relay %s, session %d established (%d active)",
	    rlay->rl_conf.name, con->se_id, relay_sessions);

	relay_session(con);
	return;

retry:
	DPRINTF("%s: session %d: scheduling on %s", __func__, con->se_id,
	    (retry_flag == EV_READ) ? "EV_READ" : "EV_WRITE");
	event_again(&con->se_ev, fd, EV_TIMEOUT|retry_flag, relay_ssl_accept,
	    &con->se_tv_start, &rlay->rl_conf.timeout, con);
}

void
relay_ssl_connect(int fd, short event, void *arg)
{
	struct rsession	*con = (struct rsession *)arg;
	struct relay	*rlay = (struct relay *)con->se_relay;
	int		 ret;
	int		 ssl_err;
	int		 retry_flag;

	if (event == EV_TIMEOUT) {
		relay_close(con, "SSL connect timeout");
		return;
	}

	retry_flag = ssl_err = 0;

	ret = SSL_connect(con->se_out.ssl);
	if (ret <= 0) {
		ssl_err = SSL_get_error(con->se_out.ssl, ret);

		switch (ssl_err) {
		case SSL_ERROR_WANT_READ:
			retry_flag = EV_READ;
			goto retry;
		case SSL_ERROR_WANT_WRITE:
			retry_flag = EV_WRITE;
			goto retry;
		case SSL_ERROR_ZERO_RETURN:
		case SSL_ERROR_SYSCALL:
			if (ret == 0) {
				relay_close(con, "closed");
				return;
			}
			/* FALLTHROUGH */
		default:
			ssl_error(rlay->rl_conf.name, "relay_ssl_connect");
			relay_close(con, "SSL connect error");
			return;
		}
	}

#ifdef DEBUG
	log_info(
#else
	log_debug(
#endif
	    "relay %s, session %d connected (%d active)",
	    rlay->rl_conf.name, con->se_id, relay_sessions);

	relay_connected(fd, EV_WRITE, con);
	return;

retry:
	DPRINTF("%s: session %d: scheduling on %s", __func__, con->se_id,
	    (retry_flag == EV_READ) ? "EV_READ" : "EV_WRITE");
	event_again(&con->se_ev, fd, EV_TIMEOUT|retry_flag, relay_ssl_connect,
	    &con->se_tv_start, &rlay->rl_conf.timeout, con);
}

void
relay_ssl_connected(struct ctl_relay_event *cre)
{
	/*
	 * Hack libevent - we overwrite the internal bufferevent I/O
	 * functions to handle the SSL abstraction.
	 */
	event_set(&cre->bev->ev_read, cre->s, EV_READ,
	    relay_ssl_readcb, cre->bev);
	event_set(&cre->bev->ev_write, cre->s, EV_WRITE,
	    relay_ssl_writecb, cre->bev);
}

void
relay_ssl_readcb(int fd, short event, void *arg)
{
	struct bufferevent *bufev = arg;
	struct ctl_relay_event *cre = (struct ctl_relay_event *)bufev->cbarg;
	struct rsession *con = cre->con;
	struct relay *rlay = (struct relay *)con->se_relay;
	int ret = 0, ssl_err = 0;
	short what = EVBUFFER_READ;
	size_t len;
	char rbuf[IBUF_READ_SIZE];
	int howmuch = IBUF_READ_SIZE;

	if (event == EV_TIMEOUT) {
		what |= EVBUFFER_TIMEOUT;
		goto err;
	}

	if (bufev->wm_read.high != 0)
		howmuch = MIN(sizeof(rbuf), bufev->wm_read.high);

	ret = SSL_read(cre->ssl, rbuf, howmuch);
	if (ret <= 0) {
		ssl_err = SSL_get_error(cre->ssl, ret);

		switch (ssl_err) {
		case SSL_ERROR_WANT_READ:
			DPRINTF("%s: session %d: want read",
			    __func__, con->se_id);
			goto retry;
		case SSL_ERROR_WANT_WRITE:
			DPRINTF("%s: session %d: want write",
			    __func__, con->se_id);
			goto retry;
		default:
			if (ret == 0)
				what |= EVBUFFER_EOF;
			else {
				ssl_error(rlay->rl_conf.name,
				    "relay_ssl_readcb");
				what |= EVBUFFER_ERROR;
			}
			goto err;
		}
	}

	if (evbuffer_add(bufev->input, rbuf, ret) == -1) {
		what |= EVBUFFER_ERROR;
		goto err;
	}

	relay_bufferevent_add(&bufev->ev_read, bufev->timeout_read);

	len = EVBUFFER_LENGTH(bufev->input);
	if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
		return;
	if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
		struct evbuffer *buf = bufev->input;
		event_del(&bufev->ev_read);
		evbuffer_setcb(buf, bufferevent_read_pressure_cb, bufev);
		return;
	}

	if (bufev->readcb != NULL)
		(*bufev->readcb)(bufev, bufev->cbarg);
	return;

 retry:
	relay_bufferevent_add(&bufev->ev_read, bufev->timeout_read);
	return;

 err:
	(*bufev->errorcb)(bufev, what, bufev->cbarg);
}

void
relay_ssl_writecb(int fd, short event, void *arg)
{
	struct bufferevent *bufev = arg;
	struct ctl_relay_event *cre = (struct ctl_relay_event *)bufev->cbarg;
	struct rsession *con = cre->con;
	struct relay *rlay = (struct relay *)con->se_relay;
	int ret = 0, ssl_err;
	short what = EVBUFFER_WRITE;

	if (event == EV_TIMEOUT) {
		what |= EVBUFFER_TIMEOUT;
		goto err;
	}

	if (EVBUFFER_LENGTH(bufev->output)) {
		if (cre->buf == NULL) {
			cre->buflen = EVBUFFER_LENGTH(bufev->output);
			if ((cre->buf = malloc(cre->buflen)) == NULL) {
				what |= EVBUFFER_ERROR;
				goto err;
			}
			bcopy(EVBUFFER_DATA(bufev->output),
			    cre->buf, cre->buflen);
		}

		ret = SSL_write(cre->ssl, cre->buf, cre->buflen);
		if (ret <= 0) {
			ssl_err = SSL_get_error(cre->ssl, ret);

			switch (ssl_err) {
			case SSL_ERROR_WANT_READ:
				DPRINTF("%s: session %d: want read",
				    __func__, con->se_id);
				goto retry;
			case SSL_ERROR_WANT_WRITE:
				DPRINTF("%s: session %d: want write",
				    __func__, con->se_id);
				goto retry;
			default:
				if (ret == 0)
					what |= EVBUFFER_EOF;
				else {
					ssl_error(rlay->rl_conf.name,
					    "relay_ssl_writecb");
					what |= EVBUFFER_ERROR;
				}
				goto err;
			}
		}
		evbuffer_drain(bufev->output, ret);
	}
	if (cre->buf != NULL) {
		free(cre->buf);
		cre->buf = NULL;
		cre->buflen = 0;
	}

	if (EVBUFFER_LENGTH(bufev->output) != 0)
		relay_bufferevent_add(&bufev->ev_write, bufev->timeout_write);

	if (bufev->writecb != NULL &&
	    EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
		(*bufev->writecb)(bufev, bufev->cbarg);
	return;

 retry:
	if (cre->buflen != 0)
		relay_bufferevent_add(&bufev->ev_write, bufev->timeout_write);
	return;

 err:
	if (cre->buf != NULL) {
		free(cre->buf);
		cre->buf = NULL;
		cre->buflen = 0;
	}
	(*bufev->errorcb)(bufev, what, bufev->cbarg);
}

int
relay_bufferevent_add(struct event *ev, int timeout)
{
	struct timeval tv, *ptv = NULL;

	if (timeout) {
		timerclear(&tv);
		tv.tv_sec = timeout;
		ptv = &tv;
	}

	return (event_add(ev, ptv));
}

#ifdef notyet
int
relay_bufferevent_printf(struct ctl_relay_event *cre, const char *fmt, ...)
{
	int ret;
	va_list ap;

	va_start(ap, fmt);
	ret = evbuffer_add_vprintf(cre->output, fmt, ap);
	va_end(ap);

	if (cre->bev != NULL &&
	    ret != -1 && EVBUFFER_LENGTH(cre->output) > 0 &&
	    (cre->bev->enabled & EV_WRITE))
		bufferevent_enable(cre->bev, EV_WRITE);

	return (ret);
}
#endif

int
relay_bufferevent_print(struct ctl_relay_event *cre, char *str)
{
	if (cre->bev == NULL)
		return (evbuffer_add(cre->output, str, strlen(str)));
	return (bufferevent_write(cre->bev, str, strlen(str)));
}

int
relay_bufferevent_write_buffer(struct ctl_relay_event *cre,
    struct evbuffer *buf)
{
	if (cre->bev == NULL)
		return (evbuffer_add_buffer(cre->output, buf));
	return (bufferevent_write_buffer(cre->bev, buf));
}

int
relay_bufferevent_write_chunk(struct ctl_relay_event *cre,
    struct evbuffer *buf, size_t size)
{
	int ret;
	ret = relay_bufferevent_write(cre, buf->buffer, size);
	if (ret != -1)
		evbuffer_drain(buf, size);
	return (ret);
}

int
relay_bufferevent_write(struct ctl_relay_event *cre, void *data, size_t size)
{
	if (cre->bev == NULL)
		return (evbuffer_add(cre->output, data, size));
	return (bufferevent_write(cre->bev, data, size));
}

int
relay_cmp_af(struct sockaddr_storage *a, struct sockaddr_storage *b)
{
	int ret = -1;
	struct sockaddr_in ia, ib;
	struct sockaddr_in6 ia6, ib6;

	switch (a->ss_family) {
	case AF_INET:
		bcopy(a, &ia, sizeof(struct sockaddr_in));
		bcopy(b, &ib, sizeof(struct sockaddr_in));

		ret = memcmp(&ia.sin_addr, &ib.sin_addr,
		    sizeof(ia.sin_addr));
		if (ret == 0)
			ret = memcmp(&ia.sin_port, &ib.sin_port,
			    sizeof(ia.sin_port));
		break;
	case AF_INET6:
		bcopy(a, &ia6, sizeof(struct sockaddr_in6));
		bcopy(b, &ib6, sizeof(struct sockaddr_in6));

		ret = memcmp(&ia6.sin6_addr, &ib6.sin6_addr,
		    sizeof(ia6.sin6_addr));
		if (ret == 0)
			ret = memcmp(&ia6.sin6_port, &ib6.sin6_port,
			    sizeof(ia6.sin6_port));
		break;
	default:
		break;
	}

	return (ret);
}

char *
relay_load_file(const char *name, off_t *len)
{
	struct stat	 st;
	off_t		 size;
	u_int8_t	*buf = NULL;
	int		 fd;

	if ((fd = open(name, O_RDONLY)) == -1)
		return (NULL);
	if (fstat(fd, &st) != 0)
		goto fail;
	size = st.st_size;
	if ((buf = (char *)calloc(1, size + 1)) == NULL)
		goto fail;
	if (read(fd, buf, size) != size)
		goto fail;

	close(fd);

	*len = size;
	return (buf);

 fail:
	if (buf != NULL)
		free(buf);
	close(fd);
	return (NULL);
}

int
relay_load_certfiles(struct relay *rlay)
{
	struct protocol *proto = rlay->rl_proto;
	char	 certfile[PATH_MAX];
	char	 hbuf[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")];

	if ((rlay->rl_conf.flags & F_SSLCLIENT) && strlen(proto->sslca)) {
		if ((rlay->rl_ssl_ca = relay_load_file(proto->sslca,
		    &rlay->rl_conf.ssl_ca_len)) == NULL)
			return (-1);
		log_debug("%s: using ca %s", __func__, proto->sslca);
	}

	if ((rlay->rl_conf.flags & F_SSL) == 0)
		return (0);

	if (print_host(&rlay->rl_conf.ss, hbuf, sizeof(hbuf)) == NULL)
		return (-1);

	if (snprintf(certfile, sizeof(certfile),
	    "/etc/ssl/%s.crt", hbuf) == -1)
		return (-1);
	if ((rlay->rl_ssl_cert = relay_load_file(certfile,
	    &rlay->rl_conf.ssl_cert_len)) == NULL)
		return (-1);
	log_debug("%s: using certificate %s", __func__, certfile);

	if (snprintf(certfile, sizeof(certfile),
	    "/etc/ssl/private/%s.key", hbuf) == -1)
		return -1;
	if ((rlay->rl_ssl_key = relay_load_file(certfile,
	    &rlay->rl_conf.ssl_key_len)) == NULL)
		return (-1);
	log_debug("%s: using private key %s", __func__, certfile);

	return (0);
}

static __inline int
relay_proto_cmp(struct protonode *a, struct protonode *b)
{
	int ret;
	ret = strcasecmp(a->key, b->key);
	if (ret == 0)
		ret = (int)a->type - b->type;
	return (ret);
}

RB_GENERATE(proto_tree, protonode, nodes, relay_proto_cmp);

int
relay_session_cmp(struct rsession *a, struct rsession *b)
{
	struct relay	*rlay = (struct relay *)b->se_relay;
	struct protocol	*proto = rlay->rl_proto;

	if (proto != NULL && proto->cmp != NULL)
		return ((*proto->cmp)(a, b));

	return ((int)a->se_id - b->se_id);
}

SPLAY_GENERATE(session_tree, rsession, se_nodes, relay_session_cmp);