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

#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>

#include <ctype.h>
#include <errno.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include <haproxy/action.h>
#include <haproxy/api.h>
#include <haproxy/cfgparse.h>
#include <haproxy/check.h>
#include <haproxy/chunk.h>
#include <haproxy/connection.h>
#include <haproxy/errors.h>
#include <haproxy/global.h>
#include <haproxy/h1.h>
#include <haproxy/http.h>
#include <haproxy/http_htx.h>
#include <haproxy/htx.h>
#include <haproxy/istbuf.h>
#include <haproxy/list.h>
#include <haproxy/log.h>
#include <haproxy/net_helper.h>
#include <haproxy/protocol.h>
#include <haproxy/proxy-t.h>
#include <haproxy/regex.h>
#include <haproxy/sample.h>
#include <haproxy/server.h>
#include <haproxy/ssl_sock.h>
#include <haproxy/stconn.h>
#include <haproxy/task.h>
#include <haproxy/tcpcheck.h>
#include <haproxy/ticks.h>
#include <haproxy/tools.h>
#include <haproxy/trace.h>
#include <haproxy/vars.h>


#define TRACE_SOURCE &trace_check

/* Global tree to share all tcp-checks */
struct eb_root shared_tcpchecks = EB_ROOT;


DECLARE_POOL(pool_head_tcpcheck_rule, "tcpcheck_rule", sizeof(struct tcpcheck_rule));

/**************************************************************************/
/*************** Init/deinit tcp-check rules and ruleset ******************/
/**************************************************************************/
/* Releases memory allocated for a log-format string */
static void free_tcpcheck_fmt(struct list *fmt)
{
	struct logformat_node *lf, *lfb;

	list_for_each_entry_safe(lf, lfb, fmt, list) {
		LIST_DELETE(&lf->list);
		release_sample_expr(lf->expr);
		free(lf->arg);
		free(lf);
	}
}

/* Releases memory allocated for an HTTP header used in a tcp-check send rule */
void free_tcpcheck_http_hdr(struct tcpcheck_http_hdr *hdr)
{
	if (!hdr)
		return;

	free_tcpcheck_fmt(&hdr->value);
	istfree(&hdr->name);
	free(hdr);
}

/* Releases memory allocated for an HTTP header list used in a tcp-check send
 * rule
 */
static void free_tcpcheck_http_hdrs(struct list *hdrs)
{
	struct tcpcheck_http_hdr *hdr, *bhdr;

	list_for_each_entry_safe(hdr, bhdr, hdrs, list) {
		LIST_DELETE(&hdr->list);
		free_tcpcheck_http_hdr(hdr);
	}
}

/* Releases memory allocated for a tcp-check. If in_pool is set, it means the
 * tcp-check was allocated using a memory pool (it is used to instantiate email
 * alerts).
 */
void free_tcpcheck(struct tcpcheck_rule *rule, int in_pool)
{
	if (!rule)
		return;

	free(rule->comment);
	switch (rule->action) {
	case TCPCHK_ACT_SEND:
		switch (rule->send.type) {
		case TCPCHK_SEND_STRING:
		case TCPCHK_SEND_BINARY:
			istfree(&rule->send.data);
			break;
		case TCPCHK_SEND_STRING_LF:
		case TCPCHK_SEND_BINARY_LF:
			free_tcpcheck_fmt(&rule->send.fmt);
			break;
		case TCPCHK_SEND_HTTP:
			free(rule->send.http.meth.str.area);
			if (!(rule->send.http.flags & TCPCHK_SND_HTTP_FL_URI_FMT))
				istfree(&rule->send.http.uri);
			else
				free_tcpcheck_fmt(&rule->send.http.uri_fmt);
			istfree(&rule->send.http.vsn);
			free_tcpcheck_http_hdrs(&rule->send.http.hdrs);
			if (!(rule->send.http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT))
				istfree(&rule->send.http.body);
			else
				free_tcpcheck_fmt(&rule->send.http.body_fmt);
			break;
		case TCPCHK_SEND_UNDEF:
			break;
		}
		break;
	case TCPCHK_ACT_EXPECT:
		free_tcpcheck_fmt(&rule->expect.onerror_fmt);
		free_tcpcheck_fmt(&rule->expect.onsuccess_fmt);
		release_sample_expr(rule->expect.status_expr);
		switch (rule->expect.type) {
		case TCPCHK_EXPECT_HTTP_STATUS:
			free(rule->expect.codes.codes);
			break;
		case TCPCHK_EXPECT_STRING:
		case TCPCHK_EXPECT_BINARY:
		case TCPCHK_EXPECT_HTTP_BODY:
			istfree(&rule->expect.data);
			break;
		case TCPCHK_EXPECT_STRING_REGEX:
		case TCPCHK_EXPECT_BINARY_REGEX:
		case TCPCHK_EXPECT_HTTP_STATUS_REGEX:
		case TCPCHK_EXPECT_HTTP_BODY_REGEX:
			regex_free(rule->expect.regex);
			break;
		case TCPCHK_EXPECT_STRING_LF:
		case TCPCHK_EXPECT_BINARY_LF:
		case TCPCHK_EXPECT_HTTP_BODY_LF:
			free_tcpcheck_fmt(&rule->expect.fmt);
			break;
		case TCPCHK_EXPECT_HTTP_HEADER:
			if (rule->expect.flags & TCPCHK_EXPT_FL_HTTP_HNAME_REG)
				regex_free(rule->expect.hdr.name_re);
			else if (rule->expect.flags & TCPCHK_EXPT_FL_HTTP_HNAME_FMT)
				free_tcpcheck_fmt(&rule->expect.hdr.name_fmt);
			else
				istfree(&rule->expect.hdr.name);

			if (rule->expect.flags & TCPCHK_EXPT_FL_HTTP_HVAL_REG)
				regex_free(rule->expect.hdr.value_re);
			else if (rule->expect.flags & TCPCHK_EXPT_FL_HTTP_HVAL_FMT)
				free_tcpcheck_fmt(&rule->expect.hdr.value_fmt);
			else if (!(rule->expect.flags & TCPCHK_EXPT_FL_HTTP_HVAL_NONE))
				istfree(&rule->expect.hdr.value);
			break;
		case TCPCHK_EXPECT_CUSTOM:
		case TCPCHK_EXPECT_UNDEF:
			break;
		}
		break;
	case TCPCHK_ACT_CONNECT:
		free(rule->connect.sni);
		free(rule->connect.alpn);
		release_sample_expr(rule->connect.port_expr);
		break;
	case TCPCHK_ACT_COMMENT:
		break;
	case TCPCHK_ACT_ACTION_KW:
		free(rule->action_kw.rule);
		break;
	}

	if (in_pool)
		pool_free(pool_head_tcpcheck_rule, rule);
	else
		free(rule);
}

/* Creates a tcp-check variable used in preset variables before executing a
 * tcp-check ruleset.
 */
struct tcpcheck_var *create_tcpcheck_var(const struct ist name)
{
	struct tcpcheck_var *var = NULL;

	var = calloc(1, sizeof(*var));
	if (var == NULL)
		return NULL;

	var->name = istdup(name);
	if (!isttest(var->name)) {
		free(var);
		return NULL;
	}

	LIST_INIT(&var->list);
	return var;
}

/* Releases memory allocated for a preset tcp-check variable */
void free_tcpcheck_var(struct tcpcheck_var *var)
{
	if (!var)
		return;

	istfree(&var->name);
	if (var->data.type == SMP_T_STR || var->data.type == SMP_T_BIN)
		free(var->data.u.str.area);
	else if (var->data.type == SMP_T_METH && var->data.u.meth.meth == HTTP_METH_OTHER)
		free(var->data.u.meth.str.area);
	free(var);
}

/* Releases a list of preset tcp-check variables */
void free_tcpcheck_vars(struct list *vars)
{
	struct tcpcheck_var *var, *back;

	list_for_each_entry_safe(var, back, vars, list) {
		LIST_DELETE(&var->list);
		free_tcpcheck_var(var);
	}
}

/* Duplicate a list of preset tcp-check variables */
int dup_tcpcheck_vars(struct list *dst, const struct list *src)
{
	const struct tcpcheck_var *var;
	struct tcpcheck_var *new = NULL;

	list_for_each_entry(var, src, list) {
		new = create_tcpcheck_var(var->name);
		if (!new)
			goto error;
		new->data.type = var->data.type;
		if (var->data.type == SMP_T_STR || var->data.type == SMP_T_BIN) {
			if (chunk_dup(&new->data.u.str, &var->data.u.str) == NULL)
				goto error;
			if (var->data.type == SMP_T_STR)
				new->data.u.str.area[new->data.u.str.data] = 0;
		}
		else if (var->data.type == SMP_T_METH && var->data.u.meth.meth == HTTP_METH_OTHER) {
			if (chunk_dup(&new->data.u.str, &var->data.u.str) == NULL)
				goto error;
			new->data.u.str.area[new->data.u.str.data] = 0;
			new->data.u.meth.meth = var->data.u.meth.meth;
		}
		else
			new->data.u = var->data.u;
		LIST_APPEND(dst, &new->list);
	}
	return 1;

 error:
	free(new);
	return 0;
}

/* Looks for a shared tcp-check ruleset given its name. */
struct tcpcheck_ruleset *find_tcpcheck_ruleset(const char *name)
{
	struct tcpcheck_ruleset *rs;
	struct ebpt_node *node;

	node = ebis_lookup_len(&shared_tcpchecks, name, strlen(name));
	if (node) {
		rs = container_of(node, typeof(*rs), node);
		return rs;
	}
	return NULL;
}

/* Creates a new shared tcp-check ruleset and insert it in shared_tcpchecks
 * tree.
 */
struct tcpcheck_ruleset *create_tcpcheck_ruleset(const char *name)
{
	struct tcpcheck_ruleset *rs;

	rs = calloc(1, sizeof(*rs));
	if (rs == NULL)
		return NULL;

	rs->node.key = strdup(name);
	if (rs->node.key == NULL) {
		free(rs);
		return NULL;
	}

	LIST_INIT(&rs->rules);
	ebis_insert(&shared_tcpchecks, &rs->node);
	return rs;
}

/* Releases memory allocated by a tcp-check ruleset. */
void free_tcpcheck_ruleset(struct tcpcheck_ruleset *rs)
{
	struct tcpcheck_rule *r, *rb;

	if (!rs)
		return;

	ebpt_delete(&rs->node);
	free(rs->node.key);
	list_for_each_entry_safe(r, rb, &rs->rules, list) {
		LIST_DELETE(&r->list);
		free_tcpcheck(r, 0);
	}
	free(rs);
}


/**************************************************************************/
/**************** Everything about tcp-checks execution *******************/
/**************************************************************************/
/* Returns the id of a step in a tcp-check ruleset */
int tcpcheck_get_step_id(const struct check *check, const struct tcpcheck_rule *rule)
{
	if (!rule)
		rule = check->current_step;

	/* no last started step => first step */
	if (!rule)
		return 1;

	/* last step is the first implicit connect */
	if (rule->index == 0 &&
	    rule->action == TCPCHK_ACT_CONNECT &&
	    (rule->connect.options & TCPCHK_OPT_IMPLICIT))
		return 0;

	return rule->index + 1;
}

/* Returns the first non COMMENT/ACTION_KW tcp-check rule from list <list> or
 * NULL if none was found.
 */
struct tcpcheck_rule *get_first_tcpcheck_rule(const struct tcpcheck_rules *rules)
{
	struct tcpcheck_rule *r;

	list_for_each_entry(r, rules->list, list) {
		if (r->action != TCPCHK_ACT_COMMENT && r->action != TCPCHK_ACT_ACTION_KW)
			return r;
	}
	return NULL;
}

/* Returns the last non COMMENT/ACTION_KW tcp-check rule from list <list> or
 * NULL if none was found.
 */
static struct tcpcheck_rule *get_last_tcpcheck_rule(struct tcpcheck_rules *rules)
{
	struct tcpcheck_rule *r;

	list_for_each_entry_rev(r, rules->list, list) {
		if (r->action != TCPCHK_ACT_COMMENT && r->action != TCPCHK_ACT_ACTION_KW)
			return r;
	}
	return NULL;
}

/* Returns the non COMMENT/ACTION_KW tcp-check rule from list <list> following
 * <start> or NULL if non was found. If <start> is NULL, it relies on
 * get_first_tcpcheck_rule().
 */
static struct tcpcheck_rule *get_next_tcpcheck_rule(struct tcpcheck_rules *rules, struct tcpcheck_rule *start)
{
	struct tcpcheck_rule *r;

	if (!start)
		return get_first_tcpcheck_rule(rules);

	r = LIST_NEXT(&start->list, typeof(r), list);
	list_for_each_entry_from(r, rules->list, list) {
		if (r->action != TCPCHK_ACT_COMMENT && r->action != TCPCHK_ACT_ACTION_KW)
			return r;
	}
	return NULL;
}


/* Creates info message when a tcp-check healthcheck fails on an expect rule */
static void tcpcheck_expect_onerror_message(struct buffer *msg, struct check *check, struct tcpcheck_rule *rule,
					    int match, struct ist info)
{
	struct sample *smp;
	int is_empty;

	/* Follows these step to produce the info message:
	 *     1. if info field is already provided, copy it
	 *     2. if the expect rule provides an onerror log-format string,
	 *        use it to produce the message
	 *     3. the expect rule is part of a protocol check (http, redis, mysql...), do nothing
	 *     4. Otherwise produce the generic tcp-check info message
	 */
	if (istlen(info)) {
		chunk_istcat(msg, info);
		goto comment;
	}
	else if (!LIST_ISEMPTY(&rule->expect.onerror_fmt)) {
		msg->data += sess_build_logline(check->sess, NULL, b_tail(msg), b_room(msg), &rule->expect.onerror_fmt);
		goto comment;
	}

	is_empty = (IS_HTX_SC(check->sc) ? htx_is_empty(htxbuf(&check->bi)) : !b_data(&check->bi));
	if (is_empty) {
		TRACE_ERROR("empty response", CHK_EV_RX_DATA|CHK_EV_RX_ERR, check);
		chunk_printf(msg, "TCPCHK got an empty response at step %d",
			     tcpcheck_get_step_id(check, rule));
		goto comment;
	}

	if (check->type == PR_O2_TCPCHK_CHK &&
	    (check->tcpcheck_rules->flags & TCPCHK_RULES_PROTO_CHK) != TCPCHK_RULES_TCP_CHK) {
		goto comment;
	}

	chunk_strcat(msg, (match ? "TCPCHK matched unwanted content" : "TCPCHK did not match content"));
	switch (rule->expect.type) {
	case TCPCHK_EXPECT_HTTP_STATUS:
		chunk_appendf(msg, "(status codes) at step %d", tcpcheck_get_step_id(check, rule));
		break;
	case TCPCHK_EXPECT_STRING:
	case TCPCHK_EXPECT_HTTP_BODY:
		chunk_appendf(msg, " '%.*s' at step %d", (unsigned int)istlen(rule->expect.data), istptr(rule->expect.data),
			      tcpcheck_get_step_id(check, rule));
		break;
	case TCPCHK_EXPECT_BINARY:
		chunk_appendf(msg, " (binary) at step %d", tcpcheck_get_step_id(check, rule));
		break;
	case TCPCHK_EXPECT_STRING_REGEX:
	case TCPCHK_EXPECT_HTTP_STATUS_REGEX:
	case TCPCHK_EXPECT_HTTP_BODY_REGEX:
		chunk_appendf(msg, " (regex) at step %d", tcpcheck_get_step_id(check, rule));
		break;
	case TCPCHK_EXPECT_BINARY_REGEX:
		chunk_appendf(msg, " (binary regex) at step %d", tcpcheck_get_step_id(check, rule));
		break;
	case TCPCHK_EXPECT_STRING_LF:
	case TCPCHK_EXPECT_HTTP_BODY_LF:
		chunk_appendf(msg, " (log-format string) at step %d", tcpcheck_get_step_id(check, rule));
		break;
	case TCPCHK_EXPECT_BINARY_LF:
		chunk_appendf(msg, " (log-format binary) at step %d", tcpcheck_get_step_id(check, rule));
		break;
	case TCPCHK_EXPECT_CUSTOM:
		chunk_appendf(msg, " (custom function) at step %d", tcpcheck_get_step_id(check, rule));
		break;
	case TCPCHK_EXPECT_HTTP_HEADER:
		chunk_appendf(msg, " (header pattern) at step %d", tcpcheck_get_step_id(check, rule));
	case TCPCHK_EXPECT_UNDEF:
		/* Should never happen. */
		return;
	}

  comment:
	/* If the failing expect rule provides a comment, it is concatenated to
	 * the info message.
	 */
	if (rule->comment) {
		chunk_strcat(msg, " comment: ");
		chunk_strcat(msg, rule->comment);
	}

	/* Finally, the check status code is set if the failing expect rule
	 * defines a status expression.
	 */
	if (rule->expect.status_expr) {
		smp = sample_fetch_as_type(check->proxy, check->sess, NULL, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
					   rule->expect.status_expr, SMP_T_STR);

		if (smp && sample_casts[smp->data.type][SMP_T_SINT] &&
                    sample_casts[smp->data.type][SMP_T_SINT](smp))
			check->code = smp->data.u.sint;
	}

	*(b_tail(msg)) = '\0';
}

/* Creates info message when a tcp-check healthcheck succeeds on an expect rule */
static void tcpcheck_expect_onsuccess_message(struct buffer *msg, struct check *check, struct tcpcheck_rule *rule,
					      struct ist info)
{
	struct sample *smp;

	/* Follows these step to produce the info message:
	 *     1. if info field is already provided, copy it
	 *     2. if the expect rule provides an onsucces log-format string,
	 *        use it to produce the message
	 *     3. the expect rule is part of a protocol check (http, redis, mysql...), do nothing
	 *     4. Otherwise produce the generic tcp-check info message
	 */
	if (istlen(info))
		chunk_istcat(msg, info);
	if (!LIST_ISEMPTY(&rule->expect.onsuccess_fmt))
		msg->data += sess_build_logline(check->sess, NULL, b_tail(msg), b_room(msg),
						&rule->expect.onsuccess_fmt);
	else if (check->type == PR_O2_TCPCHK_CHK &&
		 (check->tcpcheck_rules->flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_TCP_CHK)
		chunk_strcat(msg, "(tcp-check)");

	/* Finally, the check status code is set if the expect rule defines a
	 * status expression.
	 */
	if (rule->expect.status_expr) {
		smp = sample_fetch_as_type(check->proxy, check->sess, NULL, SMP_OPT_DIR_RES | SMP_OPT_FINAL,
					   rule->expect.status_expr, SMP_T_STR);

		if (smp && sample_casts[smp->data.type][SMP_T_SINT] &&
                    sample_casts[smp->data.type][SMP_T_SINT](smp))
			check->code = smp->data.u.sint;
	}

	*(b_tail(msg)) = '\0';
}

/* Internal functions to parse and validate a MySQL packet in the context of an
 * expect rule. It start to parse the input buffer at the offset <offset>. If
 * <last_read> is set, no more data are expected.
 */
static enum tcpcheck_eval_ret tcpcheck_mysql_expect_packet(struct check *check, struct tcpcheck_rule *rule,
							   unsigned int offset, int last_read)
{
	enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
	enum healthcheck_status status;
	struct buffer *msg = NULL;
	struct ist desc = IST_NULL;
	unsigned int err = 0, plen = 0;


	TRACE_ENTER(CHK_EV_TCPCHK_EXP, check);

	/* 3 Bytes for the packet length and 1 byte for the sequence id */
	if (b_data(&check->bi) < offset+4) {
		if (!last_read)
			goto wait_more_data;

		/* invalid length or truncated response */
		status = HCHK_STATUS_L7RSP;
		goto error;
	}

	plen = ((unsigned char) *b_peek(&check->bi, offset)) +
		(((unsigned char) *(b_peek(&check->bi, offset+1))) << 8) +
		(((unsigned char) *(b_peek(&check->bi, offset+2))) << 16);

	if (b_data(&check->bi) < offset+plen+4) {
		if (!last_read)
			goto wait_more_data;

		/* invalid length or truncated response */
		status = HCHK_STATUS_L7RSP;
		goto error;
	}

	if (*b_peek(&check->bi, offset+4) == '\xff') {
		/* MySQL Error packet always begin with field_count = 0xff */
		status = HCHK_STATUS_L7STS;
		err = ((unsigned char) *b_peek(&check->bi, offset+5)) +
			(((unsigned char) *(b_peek(&check->bi, offset+6))) << 8);
		desc = ist2(b_peek(&check->bi, offset+7), b_data(&check->bi) - offset - 7);
		goto error;
	}

	if (get_next_tcpcheck_rule(check->tcpcheck_rules, rule) != NULL) {
		/* Not the last rule, continue */
		goto out;
	}

	/* We set the MySQL Version in description for information purpose
	 * FIXME : it can be cool to use MySQL Version for other purpose,
	 * like mark as down old MySQL server.
	 */
	status = ((rule->expect.ok_status != HCHK_STATUS_UNKNOWN) ? rule->expect.ok_status : HCHK_STATUS_L7OKD);
	set_server_check_status(check, status, b_peek(&check->bi, 5));

  out:
	free_trash_chunk(msg);
	TRACE_LEAVE(CHK_EV_TCPCHK_EXP, check, 0, 0, (size_t[]){ret});
	return ret;

  error:
	ret = TCPCHK_EVAL_STOP;
	check->code = err;
	msg = alloc_trash_chunk();
	if (msg)
		tcpcheck_expect_onerror_message(msg, check, rule, 0, desc);
	set_server_check_status(check, status, (msg ? b_head(msg) : NULL));
	goto out;

  wait_more_data:
	TRACE_DEVEL("waiting for more data", CHK_EV_TCPCHK_EXP, check);
	ret = TCPCHK_EVAL_WAIT;
	goto out;
}

/* Custom tcp-check expect function to parse and validate the MySQL initial
 * handshake packet. Returns TCPCHK_EVAL_WAIT to wait for more data,
 * TCPCHK_EVAL_CONTINUE to evaluate the next rule or TCPCHK_EVAL_STOP if an
 * error occurred.
 */
enum tcpcheck_eval_ret tcpcheck_mysql_expect_iniths(struct check *check, struct tcpcheck_rule *rule, int last_read)
{
	return tcpcheck_mysql_expect_packet(check, rule, 0, last_read);
}

/* Custom tcp-check expect function to parse and validate the MySQL OK packet
 * following the initial handshake. Returns TCPCHK_EVAL_WAIT to wait for more
 * data, TCPCHK_EVAL_CONTINUE to evaluate the next rule or TCPCHK_EVAL_STOP if
 * an error occurred.
 */
enum tcpcheck_eval_ret tcpcheck_mysql_expect_ok(struct check *check, struct tcpcheck_rule *rule, int last_read)
{
	unsigned int hslen = 0;

	hslen = 4 + ((unsigned char) *b_head(&check->bi)) +
		(((unsigned char) *(b_peek(&check->bi, 1))) << 8) +
		(((unsigned char) *(b_peek(&check->bi, 2))) << 16);

	return tcpcheck_mysql_expect_packet(check, rule, hslen, last_read);
}

/* Custom tcp-check expect function to parse and validate the LDAP bind response
 * package packet. Returns TCPCHK_EVAL_WAIT to wait for more data,
 * TCPCHK_EVAL_CONTINUE to evaluate the next rule or TCPCHK_EVAL_STOP if an
 * error occurred.
 */
enum tcpcheck_eval_ret tcpcheck_ldap_expect_bindrsp(struct check *check, struct tcpcheck_rule *rule, int last_read)
{
	enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
	enum healthcheck_status status;
	struct buffer *msg = NULL;
	struct ist desc = IST_NULL;
	char *ptr;
	unsigned short nbytes = 0;
	size_t msglen = 0;

	TRACE_ENTER(CHK_EV_TCPCHK_EXP, check);

	/* Check if the server speaks LDAP (ASN.1/BER)
	 * http://en.wikipedia.org/wiki/Basic_Encoding_Rules
	 * http://tools.ietf.org/html/rfc4511
	 */
	ptr = b_head(&check->bi) + 1;

	/* size of LDAPMessage */
	if (*ptr & 0x80) {
		/* For message size encoded on several bytes, we only handle
		 * size encoded on 2 or 4 bytes. There is no reason to make this
		 * part to complex because only Active Directory is known to
		 * encode BindReponse length on 4 bytes.
		 */
		nbytes = (*ptr & 0x7f);
		if (b_data(&check->bi) < 1 + nbytes)
			goto too_short;
		switch (nbytes) {
			case 4: msglen = read_n32(ptr+1); break;
			case 2: msglen = read_n16(ptr+1); break;
			default:
				status = HCHK_STATUS_L7RSP;
				desc = ist("Not LDAPv3 protocol");
				goto error;
		}
	}
	else
		msglen = *ptr;
	ptr += 1 + nbytes;

	if (b_data(&check->bi) < 2 + nbytes + msglen)
		goto too_short;

	/* http://tools.ietf.org/html/rfc4511#section-4.2.2
	 *   messageID: 0x02 0x01 0x01: INTEGER 1
	 *   protocolOp: 0x61: bindResponse
	 */
	if (memcmp(ptr, "\x02\x01\x01\x61", 4) != 0) {
		status = HCHK_STATUS_L7RSP;
		desc = ist("Not LDAPv3 protocol");
		goto error;
	}
	ptr += 4;

	/* skip size of bindResponse */
	nbytes = 0;
	if (*ptr & 0x80)
		nbytes = (*ptr & 0x7f);
	ptr += 1 + nbytes;

	/* http://tools.ietf.org/html/rfc4511#section-4.1.9
	 *   ldapResult: 0x0a 0x01: ENUMERATION
	 */
	if (memcmp(ptr, "\x0a\x01", 2) != 0) {
		status = HCHK_STATUS_L7RSP;
		desc = ist("Not LDAPv3 protocol");
		goto error;
	}
	ptr += 2;

	/* http://tools.ietf.org/html/rfc4511#section-4.1.9
	 *   resultCode
	 */
	check->code = *ptr;
	if (check->code) {
		status = HCHK_STATUS_L7STS;
		desc = ist("See RFC: http://tools.ietf.org/html/rfc4511#section-4.1.9");
		goto error;
	}

	status = ((rule->expect.ok_status != HCHK_STATUS_UNKNOWN) ? rule->expect.ok_status : HCHK_STATUS_L7OKD);
	set_server_check_status(check, status, "Success");

  out:
	free_trash_chunk(msg);
	TRACE_LEAVE(CHK_EV_TCPCHK_EXP, check, 0, 0, (size_t[]){ret});
	return ret;

  error:
	ret = TCPCHK_EVAL_STOP;
	msg = alloc_trash_chunk();
	if (msg)
		tcpcheck_expect_onerror_message(msg, check, rule, 0, desc);
	set_server_check_status(check, status, (msg ? b_head(msg) : NULL));
	goto out;

  too_short:
	if (!last_read)
		goto wait_more_data;
	/* invalid length or truncated response */
	status = HCHK_STATUS_L7RSP;
	goto error;

  wait_more_data:
	TRACE_DEVEL("waiting for more data", CHK_EV_TCPCHK_EXP, check);
	ret = TCPCHK_EVAL_WAIT;
	goto out;
}

/* Custom tcp-check expect function to parse and validate the SPOP hello agent
 * frame. Returns TCPCHK_EVAL_WAIT to wait for more data, TCPCHK_EVAL_CONTINUE
 * to evaluate the next rule or TCPCHK_EVAL_STOP if an error occurred.
 */
enum tcpcheck_eval_ret tcpcheck_spop_expect_agenthello(struct check *check, struct tcpcheck_rule *rule, int last_read)
{
	enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
	enum healthcheck_status status;
	struct buffer *msg = NULL;
	struct ist desc = IST_NULL;
	unsigned int framesz;

	TRACE_ENTER(CHK_EV_TCPCHK_EXP, check);

	memcpy(&framesz, b_head(&check->bi), 4);
	framesz = ntohl(framesz);

	if (!last_read && b_data(&check->bi) < (4+framesz))
		goto wait_more_data;

	memset(b_orig(&trash), 0, b_size(&trash));
	if (spoe_handle_healthcheck_response(b_peek(&check->bi, 4), framesz, b_orig(&trash), HCHK_DESC_LEN) == -1) {
		status = HCHK_STATUS_L7RSP;
		desc = ist2(b_orig(&trash), strlen(b_orig(&trash)));
		goto error;
	}

	status = ((rule->expect.ok_status != HCHK_STATUS_UNKNOWN) ? rule->expect.ok_status : HCHK_STATUS_L7OKD);
	set_server_check_status(check, status, "SPOA server is ok");

  out:
	free_trash_chunk(msg);
	TRACE_LEAVE(CHK_EV_TCPCHK_EXP, check, 0, 0, (size_t[]){ret});
	return ret;

  error:
	ret = TCPCHK_EVAL_STOP;
	msg = alloc_trash_chunk();
	if (msg)
		tcpcheck_expect_onerror_message(msg, check, rule, 0, desc);
	set_server_check_status(check, status, (msg ? b_head(msg) : NULL));
	goto out;

  wait_more_data:
	TRACE_DEVEL("waiting for more data", CHK_EV_TCPCHK_EXP, check);
	ret = TCPCHK_EVAL_WAIT;
	goto out;
}

/* Custom tcp-check expect function to parse and validate the agent-check
 * reply. Returns TCPCHK_EVAL_WAIT to wait for more data, TCPCHK_EVAL_CONTINUE
 * to evaluate the next rule or TCPCHK_EVAL_STOP if an error occurred.
 */
enum tcpcheck_eval_ret tcpcheck_agent_expect_reply(struct check *check, struct tcpcheck_rule *rule, int last_read)
{
	enum tcpcheck_eval_ret ret = TCPCHK_EVAL_STOP;
	enum healthcheck_status status = HCHK_STATUS_CHECKED;
	const char *hs = NULL; /* health status      */
	const char *as = NULL; /* admin status */
	const char *ps = NULL; /* performance status */
	const char *sc = NULL; /* maxconn */
	const char *err = NULL; /* first error to report */
	const char *wrn = NULL; /* first warning to report */
	char *cmd, *p;

	TRACE_ENTER(CHK_EV_TCPCHK_EXP, check);

	/* We're getting an agent check response. The agent could
	 * have been disabled in the mean time with a long check
	 * still pending. It is important that we ignore the whole
	 * response.
	 */
	if (!(check->state & CHK_ST_ENABLED))
		goto out;

	/* The agent supports strings made of a single line ended by the
	 * first CR ('\r') or LF ('\n'). This line is composed of words
	 * delimited by spaces (' '), tabs ('\t'), or commas (','). The
	 * line may optionally contained a description of a state change
	 * after a sharp ('#'), which is only considered if a health state
	 * is announced.
	 *
	 * Words may be composed of :
	 *   - a numeric weight suffixed by the percent character ('%').
	 *   - a health status among "up", "down", "stopped", and "fail".
	 *   - an admin status among "ready", "drain", "maint".
	 *
	 * These words may appear in any order. If multiple words of the
	 * same category appear, the last one wins.
	 */

	p = b_head(&check->bi);
	while (*p && *p != '\n' && *p != '\r')
		p++;

	if (!*p) {
		if (!last_read)
			goto wait_more_data;

		/* at least inform the admin that the agent is mis-behaving */
		set_server_check_status(check, check->status, "Ignoring incomplete line from agent");
		goto out;
	}

	*p = 0;
	cmd = b_head(&check->bi);

	while (*cmd) {
		/* look for next word */
		if (*cmd == ' ' || *cmd == '\t' || *cmd == ',') {
			cmd++;
			continue;
		}

		if (*cmd == '#') {
			/* this is the beginning of a health status description,
			 * skip the sharp and blanks.
			 */
			cmd++;
			while (*cmd == '\t' || *cmd == ' ')
				cmd++;
			break;
		}

		/* find the end of the word so that we have a null-terminated
		 * word between <cmd> and <p>.
		 */
		p = cmd + 1;
		while (*p && *p != '\t' && *p != ' ' && *p != '\n' && *p != ',')
			p++;
		if (*p)
			*p++ = 0;

		/* first, health statuses */
		if (strcasecmp(cmd, "up") == 0) {
			check->health = check->rise + check->fall - 1;
			status = HCHK_STATUS_L7OKD;
			hs = cmd;
		}
		else if (strcasecmp(cmd, "down") == 0) {
			check->health = 0;
			status = HCHK_STATUS_L7STS;
			hs = cmd;
		}
		else if (strcasecmp(cmd, "stopped") == 0) {
			check->health = 0;
			status = HCHK_STATUS_L7STS;
			hs = cmd;
		}
		else if (strcasecmp(cmd, "fail") == 0) {
			check->health = 0;
			status = HCHK_STATUS_L7STS;
			hs = cmd;
		}
		/* admin statuses */
		else if (strcasecmp(cmd, "ready") == 0) {
			as = cmd;
		}
		else if (strcasecmp(cmd, "drain") == 0) {
			as = cmd;
		}
		else if (strcasecmp(cmd, "maint") == 0) {
			as = cmd;
		}
		/* try to parse a weight here and keep the last one */
		else if (isdigit((unsigned char)*cmd) && strchr(cmd, '%') != NULL) {
			ps = cmd;
		}
		/* try to parse a maxconn here */
		else if (strncasecmp(cmd, "maxconn:", strlen("maxconn:")) == 0) {
			sc = cmd;
		}
		else {
			/* keep a copy of the first error */
			if (!err)
				err = cmd;
		}
		/* skip to next word */
		cmd = p;
	}
	/* here, cmd points either to \0 or to the beginning of a
	 * description. Skip possible leading spaces.
	 */
	while (*cmd == ' ' || *cmd == '\n')
		cmd++;

	/* First, update the admin status so that we avoid sending other
	 * possibly useless warnings and can also update the health if
	 * present after going back up.
	 */
	if (as) {
		if (strcasecmp(as, "drain") == 0) {
			TRACE_DEVEL("set server into DRAIN mode", CHK_EV_TCPCHK_EXP, check);
			srv_adm_set_drain(check->server);
		}
		else if (strcasecmp(as, "maint") == 0) {
			TRACE_DEVEL("set server into MAINT mode", CHK_EV_TCPCHK_EXP, check);
			srv_adm_set_maint(check->server);
		}
		else {
			TRACE_DEVEL("set server into READY mode", CHK_EV_TCPCHK_EXP, check);
			srv_adm_set_ready(check->server);
		}
	}

	/* now change weights */
	if (ps) {
		const char *msg;

		TRACE_DEVEL("change server weight", CHK_EV_TCPCHK_EXP, check);
		msg = server_parse_weight_change_request(check->server, ps);
		if (!wrn || !*wrn)
			wrn = msg;
	}

	if (sc) {
		const char *msg;

		sc += strlen("maxconn:");

		TRACE_DEVEL("change server maxconn", CHK_EV_TCPCHK_EXP, check);
		/* This is safe to call server_parse_maxconn_change_request
		 * because the server lock is held during the check.
		 */
		msg = server_parse_maxconn_change_request(check->server, sc);
		if (!wrn || !*wrn)
			wrn = msg;
	}

	/* and finally health status */
	if (hs) {
		/* We'll report some of the warnings and errors we have
		 * here. Down reports are critical, we leave them untouched.
		 * Lack of report, or report of 'UP' leaves the room for
		 * ERR first, then WARN.
		 */
		const char *msg = cmd;
		struct buffer *t;

		if (!*msg || status == HCHK_STATUS_L7OKD) {
			if (err && *err)
				msg = err;
			else if (wrn && *wrn)
				msg = wrn;
		}

		t = get_trash_chunk();
		chunk_printf(t, "via agent : %s%s%s%s",
			     hs, *msg ? " (" : "",
			     msg, *msg ? ")" : "");
		TRACE_DEVEL("update server health status", CHK_EV_TCPCHK_EXP, check);
		set_server_check_status(check, status, t->area);
	}
	else if (err && *err) {
		/* No status change but we'd like to report something odd.
		 * Just report the current state and copy the message.
		 */
		TRACE_DEVEL("agent reports an error", CHK_EV_TCPCHK_EXP, check);
		chunk_printf(&trash, "agent reports an error : %s", err);
		set_server_check_status(check, status/*check->status*/, trash.area);
	}
	else if (wrn && *wrn) {
		/* No status change but we'd like to report something odd.
		 * Just report the current state and copy the message.
		 */
		TRACE_DEVEL("agent reports a warning", CHK_EV_TCPCHK_EXP, check);
		chunk_printf(&trash, "agent warns : %s", wrn);
		set_server_check_status(check, status/*check->status*/, trash.area);
	}
	else {
		TRACE_DEVEL("update server health status", CHK_EV_TCPCHK_EXP, check);
		set_server_check_status(check, status, NULL);
	}

  out:
	TRACE_LEAVE(CHK_EV_TCPCHK_EXP, check, 0, 0, (size_t[]){ret});
	return ret;

  wait_more_data:
	TRACE_DEVEL("waiting for more data", CHK_EV_TCPCHK_EXP, check);
	ret = TCPCHK_EVAL_WAIT;
	goto out;
}

/* Evaluates a TCPCHK_ACT_CONNECT rule. Returns TCPCHK_EVAL_WAIT to wait the
 * connection establishment, TCPCHK_EVAL_CONTINUE to evaluate the next rule or
 * TCPCHK_EVAL_STOP if an error occurred.
 */
enum tcpcheck_eval_ret tcpcheck_eval_connect(struct check *check, struct tcpcheck_rule *rule)
{
	enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
	struct tcpcheck_connect *connect = &rule->connect;
	struct proxy *proxy = check->proxy;
	struct server *s = check->server;
	struct task *t = check->task;
	struct connection *conn = sc_conn(check->sc);
	struct protocol *proto;
	struct xprt_ops *xprt;
	struct tcpcheck_rule *next;
	int status, port;

	TRACE_ENTER(CHK_EV_TCPCHK_CONN, check);

	next = get_next_tcpcheck_rule(check->tcpcheck_rules, rule);

	/* current connection already created, check if it is established or not */
	if (conn) {
		if (conn->flags & CO_FL_WAIT_XPRT) {
			/* We are still waiting for the connection establishment */
			if (next && next->action == TCPCHK_ACT_SEND) {
				if (!(check->sc->wait_event.events & SUB_RETRY_SEND))
					conn->mux->subscribe(check->sc, SUB_RETRY_SEND, &check->sc->wait_event);
				ret = TCPCHK_EVAL_WAIT;
				TRACE_DEVEL("not connected yet", CHK_EV_TCPCHK_CONN, check);
			}
			else
				ret = tcpcheck_eval_recv(check, rule);
		}
		goto out;
	}

	/* Note: here check->sc = sc = conn = NULL */

	/* Always release input and output buffer when a new connect is evaluated */
	check_release_buf(check, &check->bi);
	check_release_buf(check, &check->bo);

	/* No connection, prepare a new one */
	conn = conn_new((s ? &s->obj_type : &proxy->obj_type));
	if (!conn) {
		chunk_printf(&trash, "TCPCHK error allocating connection at step %d",
			     tcpcheck_get_step_id(check, rule));
		if (rule->comment)
			chunk_appendf(&trash, " comment: '%s'", rule->comment);
		set_server_check_status(check, HCHK_STATUS_SOCKERR, trash.area);
		ret = TCPCHK_EVAL_STOP;
		TRACE_ERROR("stconn allocation error", CHK_EV_TCPCHK_CONN|CHK_EV_TCPCHK_ERR, check);
		goto out;
	}
	if (sc_attach_mux(check->sc, NULL, conn) < 0) {
		TRACE_ERROR("mux attach error", CHK_EV_TCPCHK_CONN|CHK_EV_TCPCHK_ERR, check);
		conn_free(conn);
		conn = NULL;
		status = SF_ERR_RESOURCE;
		goto fail_check;
	}
	conn->ctx = check->sc;
	conn_set_owner(conn, check->sess, NULL);

	/* no client address */
	if (!sockaddr_alloc(&conn->dst, NULL, 0)) {
		TRACE_ERROR("sockaddr allocation error", CHK_EV_TCPCHK_CONN|CHK_EV_TCPCHK_ERR, check);
		status = SF_ERR_RESOURCE;
		goto fail_check;
	}

	/* connect to the connect rule addr if specified, otherwise the check
	 * addr if specified on the server. otherwise, use the server addr (it
	 * MUST exist at this step).
	 */
	*conn->dst = (is_addr(&connect->addr)
		      ? connect->addr
		      : (is_addr(&check->addr) ? check->addr : s->addr));
	proto = protocol_lookup(conn->dst->ss_family, PROTO_TYPE_STREAM, 0);

	port = 0;
	if (connect->port)
		port = connect->port;
	if (!port && connect->port_expr) {
		struct sample *smp;

		smp = sample_fetch_as_type(check->proxy, check->sess, NULL,
					   SMP_OPT_DIR_REQ | SMP_OPT_FINAL,
					   connect->port_expr, SMP_T_SINT);
		if (smp)
			port = smp->data.u.sint;
	}
	if (!port && is_inet_addr(&connect->addr))
		port = get_host_port(&connect->addr);
	if (!port && check->port)
		port = check->port;
	if (!port && is_inet_addr(&check->addr))
		port = get_host_port(&check->addr);
	if (!port) {
		/* The server MUST exist here */
		port = s->svc_port;
	}
	set_host_port(conn->dst, port);
	TRACE_DEVEL("set port", CHK_EV_TCPCHK_CONN, check, 0, 0, (size_t[]){port});

	xprt = ((connect->options & TCPCHK_OPT_SSL)
		? xprt_get(XPRT_SSL)
		: ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) ? check->xprt : xprt_get(XPRT_RAW)));

	if (conn_prepare(conn, proto, xprt) < 0) {
		TRACE_ERROR("xprt allocation error", CHK_EV_TCPCHK_CONN|CHK_EV_TCPCHK_ERR, check);
		status = SF_ERR_RESOURCE;
		goto fail_check;
	}

	if ((connect->options & TCPCHK_OPT_SOCKS4) && s && (s->flags & SRV_F_SOCKS4_PROXY)) {
		conn->send_proxy_ofs = 1;
		conn->flags |= CO_FL_SOCKS4;
		TRACE_DEVEL("configure SOCKS4 proxy", CHK_EV_TCPCHK_CONN);
	}
	else if ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) && s && s->check.via_socks4 && (s->flags & SRV_F_SOCKS4_PROXY)) {
		conn->send_proxy_ofs = 1;
		conn->flags |= CO_FL_SOCKS4;
		TRACE_DEVEL("configure SOCKS4 proxy", CHK_EV_TCPCHK_CONN);
	}

	if (connect->options & TCPCHK_OPT_SEND_PROXY) {
		conn->send_proxy_ofs = 1;
		conn->flags |= CO_FL_SEND_PROXY;
		TRACE_DEVEL("configure PROXY protocol", CHK_EV_TCPCHK_CONN, check);
	}
	else if ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) && s && s->check.send_proxy && !(check->state & CHK_ST_AGENT)) {
		conn->send_proxy_ofs = 1;
		conn->flags |= CO_FL_SEND_PROXY;
		TRACE_DEVEL("configure PROXY protocol", CHK_EV_TCPCHK_CONN, check);
	}

	status = SF_ERR_INTERNAL;
	if (proto && proto->connect) {
		int flags = 0;

		if (!next)
			flags |= CONNECT_DELACK_ALWAYS;
		if (connect->options & TCPCHK_OPT_HAS_DATA)
			flags |= (CONNECT_HAS_DATA|CONNECT_DELACK_ALWAYS);
		status = proto->connect(conn, flags);
	}

	if (status != SF_ERR_NONE)
		goto fail_check;

	conn_set_private(conn);
	conn->ctx = check->sc;

#ifdef USE_OPENSSL
	if (connect->sni)
		ssl_sock_set_servername(conn, connect->sni);
	else if ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) && s && s->check.sni)
		ssl_sock_set_servername(conn, s->check.sni);

	if (connect->alpn)
		ssl_sock_set_alpn(conn, (unsigned char *)connect->alpn, connect->alpn_len);
	else if ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) && s && s->check.alpn_str)
		ssl_sock_set_alpn(conn, (unsigned char *)s->check.alpn_str, s->check.alpn_len);
#endif

	if (conn_ctrl_ready(conn) && (connect->options & TCPCHK_OPT_LINGER) && !(conn->flags & CO_FL_FDLESS)) {
		/* Some servers don't like reset on close */
		HA_ATOMIC_AND(&fdtab[conn->handle.fd].state, ~FD_LINGER_RISK);
	}

	if (conn_ctrl_ready(conn) && (conn->flags & (CO_FL_SEND_PROXY | CO_FL_SOCKS4))) {
		if (xprt_add_hs(conn) < 0)
			status = SF_ERR_RESOURCE;
	}

	if (conn_xprt_start(conn) < 0) {
		status = SF_ERR_RESOURCE;
		goto fail_check;
	}

	/* The mux may be initialized now if there isn't server attached to the
	 * check (email alerts) or if there is a mux proto specified or if there
	 * is no alpn.
	 */
	if (!s || ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) && check->mux_proto) ||
	    connect->mux_proto || (!connect->alpn && !check->alpn_str)) {
		const struct mux_ops *mux_ops;

		TRACE_DEVEL("try to install mux now", CHK_EV_TCPCHK_CONN, check);
		if (connect->mux_proto)
			mux_ops = connect->mux_proto->mux;
		else if ((connect->options & TCPCHK_OPT_DEFAULT_CONNECT) && check->mux_proto)
			mux_ops = check->mux_proto->mux;
		else {
			int mode = ((check->tcpcheck_rules->flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_HTTP_CHK
				    ? PROTO_MODE_HTTP
				    : PROTO_MODE_TCP);

			mux_ops = conn_get_best_mux(conn, IST_NULL, PROTO_SIDE_BE, mode);
		}
		if (mux_ops && conn_install_mux(conn, mux_ops, check->sc, proxy, check->sess) < 0) {
			TRACE_ERROR("failed to install mux", CHK_EV_TCPCHK_CONN|CHK_EV_TCPCHK_ERR, check);
			status = SF_ERR_INTERNAL;
			goto fail_check;
		}
	}

  fail_check:
	/* It can return one of :
	 *  - SF_ERR_NONE if everything's OK
	 *  - SF_ERR_SRVTO if there are no more servers
	 *  - SF_ERR_SRVCL if the connection was refused by the server
	 *  - SF_ERR_PRXCOND if the connection has been limited by the proxy (maxconn)
	 *  - SF_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
	 *  - SF_ERR_INTERNAL for any other purely internal errors
	 * Additionally, in the case of SF_ERR_RESOURCE, an emergency log will be emitted.
	 * Note that we try to prevent the network stack from sending the ACK during the
	 * connect() when a pure TCP check is used (without PROXY protocol).
	 */
	switch (status) {
	case SF_ERR_NONE:
		/* we allow up to min(inter, timeout.connect) for a connection
		 * to establish but only when timeout.check is set as it may be
		 * to short for a full check otherwise
		 */
		t->expire = tick_add(now_ms, MS_TO_TICKS(check->inter));

		if (proxy->timeout.check && proxy->timeout.connect) {
			int t_con = tick_add(now_ms, proxy->timeout.connect);
			t->expire = tick_first(t->expire, t_con);
		}
		break;
	case SF_ERR_SRVTO: /* ETIMEDOUT */
	case SF_ERR_SRVCL: /* ECONNREFUSED, ENETUNREACH, ... */
	case SF_ERR_PRXCOND:
	case SF_ERR_RESOURCE:
	case SF_ERR_INTERNAL:
		TRACE_ERROR("report connection error", CHK_EV_TCPCHK_CONN|CHK_EV_TCPCHK_ERR, check, 0, 0, (size_t[]){status});
		chk_report_conn_err(check, errno, 0);
		ret = TCPCHK_EVAL_STOP;
		goto out;
	}

	/* don't do anything until the connection is established */
	if (conn->flags & CO_FL_WAIT_XPRT) {
		if (conn->mux) {
			if (next && next->action == TCPCHK_ACT_SEND)
				conn->mux->subscribe(check->sc, SUB_RETRY_SEND, &check->sc->wait_event);
			else
				conn->mux->subscribe(check->sc, SUB_RETRY_RECV, &check->sc->wait_event);
		}
		ret = TCPCHK_EVAL_WAIT;
		TRACE_DEVEL("not connected yet", CHK_EV_TCPCHK_CONN, check);
		goto out;
	}

  out:
	if (conn && check->result == CHK_RES_FAILED) {
		conn->flags |= CO_FL_ERROR;
		TRACE_ERROR("connect failed, report connection error", CHK_EV_TCPCHK_CONN|CHK_EV_TCPCHK_ERR, check);
	}

	if (ret == TCPCHK_EVAL_CONTINUE && check->proxy->timeout.check)
		check->task->expire = tick_add_ifset(now_ms, check->proxy->timeout.check);

	TRACE_LEAVE(CHK_EV_TCPCHK_CONN, check, 0, 0, (size_t[]){ret});
	return ret;
}

/* Evaluates a TCPCHK_ACT_SEND rule. Returns TCPCHK_EVAL_WAIT if outgoing data
 * were not fully sent, TCPCHK_EVAL_CONTINUE to evaluate the next rule or
 * TCPCHK_EVAL_STOP if an error occurred.
 */
enum tcpcheck_eval_ret tcpcheck_eval_send(struct check *check, struct tcpcheck_rule *rule)
{
	enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
	struct tcpcheck_send *send = &rule->send;
	struct stconn *sc = check->sc;
	struct connection *conn = __sc_conn(sc);
	struct buffer *tmp = NULL;
	struct htx *htx = NULL;
	int connection_hdr = 0;

	TRACE_ENTER(CHK_EV_TCPCHK_SND|CHK_EV_TX_DATA, check);

	if (check->state & CHK_ST_OUT_ALLOC) {
		ret = TCPCHK_EVAL_WAIT;
		TRACE_STATE("waiting for output buffer allocation", CHK_EV_TCPCHK_SND|CHK_EV_TX_DATA|CHK_EV_TX_BLK, check);
		goto out;
	}

	if (!check_get_buf(check, &check->bo)) {
		check->state |= CHK_ST_OUT_ALLOC;
		ret = TCPCHK_EVAL_WAIT;
		TRACE_STATE("waiting for output buffer allocation", CHK_EV_TCPCHK_SND|CHK_EV_TX_DATA|CHK_EV_TX_BLK, check);
		goto out;
	}

	/* Data already pending in the output buffer, send them now */
	if ((IS_HTX_CONN(conn) && !htx_is_empty(htxbuf(&check->bo))) || (!IS_HTX_CONN(conn) && b_data(&check->bo))) {
		TRACE_DEVEL("Data still pending, try to send it now", CHK_EV_TCPCHK_SND|CHK_EV_TX_DATA, check);
		goto do_send;
	}

	/* Always release input buffer when a new send is evaluated */
	check_release_buf(check, &check->bi);

	switch (send->type) {
	case TCPCHK_SEND_STRING:
	case TCPCHK_SEND_BINARY:
		if (istlen(send->data) >= b_size(&check->bo)) {
			chunk_printf(&trash, "tcp-check send : string too large (%u) for buffer size (%u) at step %d",
				     (unsigned int)istlen(send->data), (unsigned int)b_size(&check->bo),
				     tcpcheck_get_step_id(check, rule));
			set_server_check_status(check, HCHK_STATUS_L7RSP, trash.area);
			ret = TCPCHK_EVAL_STOP;
			goto out;
		}
		b_putist(&check->bo, send->data);
		break;
	case TCPCHK_SEND_STRING_LF:
		check->bo.data = sess_build_logline(check->sess, NULL, b_orig(&check->bo), b_size(&check->bo), &rule->send.fmt);
		if (!b_data(&check->bo))
			goto out;
		break;
	case TCPCHK_SEND_BINARY_LF: {
		int len = b_size(&check->bo);

		tmp = alloc_trash_chunk();
		if (!tmp)
			goto error_lf;
		tmp->data = sess_build_logline(check->sess, NULL, b_orig(tmp), b_size(tmp), &rule->send.fmt);
		if (!b_data(tmp))
			goto out;
		tmp->area[tmp->data] = '\0';
		if (parse_binary(b_orig(tmp),  &check->bo.area, &len, NULL) == 0)
			goto error_lf;
		check->bo.data = len;
		break;
	}
	case TCPCHK_SEND_HTTP: {
		struct htx_sl *sl;
		struct ist meth, uri, vsn, clen, body;
		unsigned int slflags = 0;

		tmp = alloc_trash_chunk();
		if (!tmp)
			goto error_htx;

		meth = ((send->http.meth.meth == HTTP_METH_OTHER)
			? ist2(send->http.meth.str.area, send->http.meth.str.data)
			: http_known_methods[send->http.meth.meth]);
		if (send->http.flags & TCPCHK_SND_HTTP_FL_URI_FMT) {
			tmp->data = sess_build_logline(check->sess, NULL, b_orig(tmp), b_size(tmp), &send->http.uri_fmt);
			uri = (b_data(tmp) ? ist2(b_orig(tmp), b_data(tmp)) : ist("/"));
		}
		else
			uri = (isttest(send->http.uri) ? send->http.uri : ist("/"));
		vsn = (isttest(send->http.vsn) ? send->http.vsn : ist("HTTP/1.0"));

		if ((istlen(vsn) == 6 && *(vsn.ptr+5) == '2') ||
		    (istlen(vsn) == 8 && (*(vsn.ptr+5) > '1' || (*(vsn.ptr+5) == '1' && *(vsn.ptr+7) >= '1'))))
			slflags |= HTX_SL_F_VER_11;
		slflags |= (HTX_SL_F_XFER_LEN|HTX_SL_F_CLEN);
		if (!(send->http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT) && !isttest(send->http.body))
			slflags |= HTX_SL_F_BODYLESS;

		htx = htx_from_buf(&check->bo);
		sl = htx_add_stline(htx, HTX_BLK_REQ_SL, slflags, meth, uri, vsn);
		if (!sl)
			goto error_htx;
		sl->info.req.meth = send->http.meth.meth;
		if (!http_update_host(htx, sl, uri))
			goto error_htx;

		if (!LIST_ISEMPTY(&send->http.hdrs)) {
			struct tcpcheck_http_hdr *hdr;
			struct ist hdr_value;

			list_for_each_entry(hdr, &send->http.hdrs, list) {
				chunk_reset(tmp);
                                tmp->data = sess_build_logline(check->sess, NULL, b_orig(tmp), b_size(tmp), &hdr->value);
				if (!b_data(tmp))
					continue;
				hdr_value = ist2(b_orig(tmp), b_data(tmp));
				if (!htx_add_header(htx, hdr->name, hdr_value))
					goto error_htx;
				if ((sl->flags & HTX_SL_F_HAS_AUTHORITY) && isteqi(hdr->name, ist("host"))) {
					if (!http_update_authority(htx, sl, hdr_value))
						goto error_htx;
				}
				if (isteqi(hdr->name, ist("connection")))
					connection_hdr = 1;
			}

		}
		if (check->proxy->options2 & PR_O2_CHK_SNDST) {
			chunk_reset(tmp);
			httpchk_build_status_header(check->server, tmp);
			if (!htx_add_header(htx, ist("X-Haproxy-Server-State"), ist2(b_orig(tmp), b_data(tmp))))
				goto error_htx;
		}


		if (send->http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT) {
			chunk_reset(tmp);
			tmp->data = sess_build_logline(check->sess, NULL, b_orig(tmp), b_size(tmp), &send->http.body_fmt);
			body = ist2(b_orig(tmp), b_data(tmp));
		}
		else
			body = send->http.body;

		if (!connection_hdr && !htx_add_header(htx, ist("Connection"), ist("close")))
			goto error_htx;

		if ((send->http.meth.meth != HTTP_METH_OPTIONS &&
		     send->http.meth.meth != HTTP_METH_GET &&
		     send->http.meth.meth != HTTP_METH_HEAD &&
		     send->http.meth.meth != HTTP_METH_DELETE) || istlen(body)) {
			clen = ist((!istlen(body) ? "0" : ultoa(istlen(body))));
			if (!htx_add_header(htx, ist("Content-length"), clen))
				goto error_htx;
		}

		if (!htx_add_endof(htx, HTX_BLK_EOH) ||
		    (istlen(body) && !htx_add_data_atonce(htx, body)))
			goto error_htx;

		/* no more data are expected */
		htx->flags |= HTX_FL_EOM;
		htx_to_buf(htx, &check->bo);
		break;
	}
	case TCPCHK_SEND_UNDEF:
		/* Should never happen. */
		ret = TCPCHK_EVAL_STOP;
		goto out;
	};

  do_send:
	TRACE_DATA("send data", CHK_EV_TCPCHK_SND|CHK_EV_TX_DATA, check);
	if (conn->mux->snd_buf(sc, &check->bo,
			       (IS_HTX_CONN(conn) ? (htxbuf(&check->bo))->data: b_data(&check->bo)), 0) <= 0) {
		if ((conn->flags & CO_FL_ERROR) || sc_ep_test(sc, SE_FL_ERROR)) {
			ret = TCPCHK_EVAL_STOP;
			TRACE_DEVEL("connection error during send", CHK_EV_TCPCHK_SND|CHK_EV_TX_DATA|CHK_EV_TX_ERR, check);
			goto out;
		}
	}
	if ((IS_HTX_CONN(conn) && !htx_is_empty(htxbuf(&check->bo))) || (!IS_HTX_CONN(conn) && b_data(&check->bo))) {
		conn->mux->subscribe(sc, SUB_RETRY_SEND, &sc->wait_event);
		ret = TCPCHK_EVAL_WAIT;
		TRACE_DEVEL("data not fully sent, wait", CHK_EV_TCPCHK_SND|CHK_EV_TX_DATA, check);
		goto out;
	}

  out:
	free_trash_chunk(tmp);
	if (!b_data(&check->bo) || ret == TCPCHK_EVAL_STOP)
		check_release_buf(check, &check->bo);

	TRACE_LEAVE(CHK_EV_TCPCHK_SND, check, 0, 0, (size_t[]){ret});
	return ret;

  error_htx:
	if (htx) {
		htx_reset(htx);
		htx_to_buf(htx, &check->bo);
	}
	chunk_printf(&trash, "tcp-check send : failed to build HTTP request at step %d",
		     tcpcheck_get_step_id(check, rule));
	TRACE_ERROR("failed to build HTTP request", CHK_EV_TCPCHK_SND|CHK_EV_TX_DATA|CHK_EV_TCPCHK_ERR, check);
	set_server_check_status(check, HCHK_STATUS_L7RSP, trash.area);
	ret = TCPCHK_EVAL_STOP;
	goto out;

  error_lf:
	chunk_printf(&trash, "tcp-check send : failed to build log-format string at step %d",
		     tcpcheck_get_step_id(check, rule));
	TRACE_ERROR("failed to build log-format string", CHK_EV_TCPCHK_SND|CHK_EV_TX_DATA|CHK_EV_TCPCHK_ERR, check);
	set_server_check_status(check, HCHK_STATUS_L7RSP, trash.area);
	ret = TCPCHK_EVAL_STOP;
	goto out;

}

/* Try to receive data before evaluating a tcp-check expect rule. Returns
 * TCPCHK_EVAL_WAIT if it is already subscribed on receive events or if nothing
 * was received, TCPCHK_EVAL_CONTINUE to evaluate the expect rule or
 * TCPCHK_EVAL_STOP if an error occurred.
 */
enum tcpcheck_eval_ret tcpcheck_eval_recv(struct check *check, struct tcpcheck_rule *rule)
{
	struct stconn *sc = check->sc;
	struct connection *conn = __sc_conn(sc);
	enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
	size_t max, read, cur_read = 0;
	int is_empty;
	int read_poll = MAX_READ_POLL_LOOPS;

	TRACE_ENTER(CHK_EV_RX_DATA, check);

	if (sc->wait_event.events & SUB_RETRY_RECV) {
		TRACE_DEVEL("waiting for response", CHK_EV_RX_DATA, check);
		goto wait_more_data;
	}

	if (sc_ep_test(sc, SE_FL_EOS))
		goto end_recv;

	if (check->state & CHK_ST_IN_ALLOC) {
		TRACE_STATE("waiting for input buffer allocation", CHK_EV_RX_DATA|CHK_EV_RX_BLK, check);
		goto wait_more_data;
	}

	if (!check_get_buf(check, &check->bi)) {
		check->state |= CHK_ST_IN_ALLOC;
		TRACE_STATE("waiting for input buffer allocation", CHK_EV_RX_DATA|CHK_EV_RX_BLK, check);
		goto wait_more_data;
	}

	/* errors on the connection and the stream connector were already checked */

	/* prepare to detect if the mux needs more room */
	sc_ep_clr(sc, SE_FL_WANT_ROOM);

	while (sc_ep_test(sc, SE_FL_RCV_MORE) ||
	       (!(conn->flags & CO_FL_ERROR) && !sc_ep_test(sc, SE_FL_ERROR | SE_FL_EOS))) {
		max = (IS_HTX_SC(sc) ?  htx_free_space(htxbuf(&check->bi)) : b_room(&check->bi));
		read = conn->mux->rcv_buf(sc, &check->bi, max, 0);
		cur_read += read;
		if (!read ||
		    sc_ep_test(sc, SE_FL_WANT_ROOM) ||
		    (--read_poll <= 0) ||
		    (read < max && read >= global.tune.recv_enough))
			break;
	}

  end_recv:
	is_empty = (IS_HTX_SC(sc) ? htx_is_empty(htxbuf(&check->bi)) : !b_data(&check->bi));
	if (is_empty && ((conn->flags & CO_FL_ERROR) || sc_ep_test(sc, SE_FL_ERROR))) {
		/* Report network errors only if we got no other data. Otherwise
		 * we'll let the upper layers decide whether the response is OK
		 * or not. It is very common that an RST sent by the server is
		 * reported as an error just after the last data chunk.
		 */
		TRACE_ERROR("connection error during recv", CHK_EV_RX_DATA|CHK_EV_RX_ERR, check);
		goto stop;
	}
	else if (!cur_read && !sc_ep_test(sc, SE_FL_WANT_ROOM | SE_FL_ERROR | SE_FL_EOS)) {
		conn->mux->subscribe(sc, SUB_RETRY_RECV, &sc->wait_event);
		TRACE_DEVEL("waiting for response", CHK_EV_RX_DATA, check);
		goto wait_more_data;
	}
	TRACE_DATA("data received", CHK_EV_RX_DATA, check, 0, 0, (size_t[]){cur_read});

  out:
	if (!b_data(&check->bi) || ret == TCPCHK_EVAL_STOP)
		check_release_buf(check, &check->bi);

	TRACE_LEAVE(CHK_EV_RX_DATA, check, 0, 0, (size_t[]){ret});
	return ret;

  stop:
	ret = TCPCHK_EVAL_STOP;
	goto out;

  wait_more_data:
	ret = TCPCHK_EVAL_WAIT;
	goto out;
}

/* Evaluates an HTTP TCPCHK_ACT_EXPECT rule. If <last_read> is set , no more data
 * are expected. Returns TCPCHK_EVAL_WAIT to wait for more data,
 * TCPCHK_EVAL_CONTINUE to evaluate the next rule or TCPCHK_EVAL_STOP if an
 * error occurred.
 */
enum tcpcheck_eval_ret tcpcheck_eval_expect_http(struct check *check, struct tcpcheck_rule *rule, int last_read)
{
	struct htx *htx = htxbuf(&check->bi);
	struct htx_sl *sl;
	struct htx_blk *blk;
	enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
	struct tcpcheck_expect *expect = &rule->expect;
	struct buffer *msg = NULL, *tmp = NULL, *nbuf = NULL, *vbuf = NULL;
	enum healthcheck_status status = HCHK_STATUS_L7RSP;
	struct ist desc = IST_NULL;
	int i, match, inverse;

	TRACE_ENTER(CHK_EV_TCPCHK_EXP, check);

	last_read |= (!htx_free_data_space(htx) || (htx->flags & HTX_FL_EOM));

	if (htx->flags & HTX_FL_PARSING_ERROR) {
		TRACE_ERROR("invalid response", CHK_EV_TCPCHK_EXP|CHK_EV_TCPCHK_ERR, check);
		status = HCHK_STATUS_L7RSP;
		goto error;
	}

	if (htx_is_empty(htx)) {
		if (last_read) {
			TRACE_ERROR("empty response received", CHK_EV_TCPCHK_EXP|CHK_EV_TCPCHK_ERR, check);
			status = HCHK_STATUS_L7RSP;
			goto error;
		}
		TRACE_DEVEL("waiting for more data", CHK_EV_TCPCHK_EXP, check);
		goto wait_more_data;
	}

	sl = http_get_stline(htx);
	check->code = sl->info.res.status;

	if (check->server &&
	    (check->server->proxy->options & PR_O_DISABLE404) &&
	    (check->server->next_state != SRV_ST_STOPPED) &&
	    (check->code == 404)) {
		/* 404 may be accepted as "stopping" only if the server was up */
		TRACE_STATE("404 response & disable-404", CHK_EV_TCPCHK_EXP, check);
		goto out;
	}

	inverse = !!(expect->flags & TCPCHK_EXPT_FL_INV);
	/* Make GCC happy ; initialize match to a failure state. */
	match = inverse;
	status = expect->err_status;

	switch (expect->type) {
	case TCPCHK_EXPECT_HTTP_STATUS:
		match = 0;
		for (i = 0; i < expect->codes.num; i++) {
			if (sl->info.res.status >= expect->codes.codes[i][0] &&
			    sl->info.res.status <= expect->codes.codes[i][1]) {
				match = 1;
				break;
			}
		}

		/* Set status and description in case of error */
		status = ((status != HCHK_STATUS_UNKNOWN) ? status : HCHK_STATUS_L7STS);
		if (LIST_ISEMPTY(&expect->onerror_fmt))
			desc = htx_sl_res_reason(sl);
		break;
	case TCPCHK_EXPECT_HTTP_STATUS_REGEX:
		match = regex_exec2(expect->regex, HTX_SL_RES_CPTR(sl), HTX_SL_RES_CLEN(sl));

		/* Set status and description in case of error */
		status = ((status != HCHK_STATUS_UNKNOWN) ? status : HCHK_STATUS_L7STS);
		if (LIST_ISEMPTY(&expect->onerror_fmt))
			desc = htx_sl_res_reason(sl);
		break;

	case TCPCHK_EXPECT_HTTP_HEADER: {
		struct http_hdr_ctx ctx;
		struct ist npat, vpat, value;
		int full = (expect->flags & (TCPCHK_EXPT_FL_HTTP_HVAL_NONE|TCPCHK_EXPT_FL_HTTP_HVAL_FULL));

		if (expect->flags & TCPCHK_EXPT_FL_HTTP_HNAME_FMT) {
			nbuf = alloc_trash_chunk();
			if (!nbuf) {
				status = HCHK_STATUS_L7RSP;
				desc = ist("Failed to allocate buffer to eval log-format string");
				TRACE_ERROR("buffer allocation failure", CHK_EV_TCPCHK_EXP|CHK_EV_TCPCHK_ERR, check);
				goto error;
			}
			nbuf->data = sess_build_logline(check->sess, NULL, b_orig(nbuf), b_size(nbuf), &expect->hdr.name_fmt);
			if (!b_data(nbuf)) {
				status = HCHK_STATUS_L7RSP;
				desc = ist("log-format string evaluated to an empty string");
				TRACE_ERROR("invalid log-format string (hdr name)", CHK_EV_TCPCHK_EXP|CHK_EV_TCPCHK_ERR, check);
				goto error;
			}
			npat = ist2(b_orig(nbuf), b_data(nbuf));
		}
		else if (!(expect->flags & TCPCHK_EXPT_FL_HTTP_HNAME_REG))
			npat = expect->hdr.name;

		if (expect->flags & TCPCHK_EXPT_FL_HTTP_HVAL_FMT) {
			vbuf = alloc_trash_chunk();
			if (!vbuf) {
				status = HCHK_STATUS_L7RSP;
				desc = ist("Failed to allocate buffer to eval log-format string");
				TRACE_ERROR("buffer allocation failure", CHK_EV_TCPCHK_EXP|CHK_EV_TCPCHK_ERR, check);
				goto error;
			}
			vbuf->data = sess_build_logline(check->sess, NULL, b_orig(vbuf), b_size(vbuf), &expect->hdr.value_fmt);
			if (!b_data(vbuf)) {
				status = HCHK_STATUS_L7RSP;
				desc = ist("log-format string evaluated to an empty string");
				TRACE_ERROR("invalid log-format string (hdr value)", CHK_EV_TCPCHK_EXP|CHK_EV_TCPCHK_ERR, check);
				goto error;
			}
			vpat = ist2(b_orig(vbuf), b_data(vbuf));
		}
		else if (!(expect->flags & TCPCHK_EXPT_FL_HTTP_HVAL_REG))
			vpat = expect->hdr.value;

		match = 0;
		ctx.blk = NULL;
		while (1) {
			switch (expect->flags & TCPCHK_EXPT_FL_HTTP_HNAME_TYPE) {
			case TCPCHK_EXPT_FL_HTTP_HNAME_STR:
				if (!http_find_str_header(htx, npat, &ctx, full))
					goto end_of_match;
				break;
			case TCPCHK_EXPT_FL_HTTP_HNAME_BEG:
				if (!http_find_pfx_header(htx, npat, &ctx, full))
					goto end_of_match;
				break;
			case TCPCHK_EXPT_FL_HTTP_HNAME_END:
				if (!http_find_sfx_header(htx, npat, &ctx, full))
					goto end_of_match;
				break;
			case TCPCHK_EXPT_FL_HTTP_HNAME_SUB:
				if (!http_find_sub_header(htx, npat, &ctx, full))
					goto end_of_match;
				break;
			case TCPCHK_EXPT_FL_HTTP_HNAME_REG:
				if (!http_match_header(htx, expect->hdr.name_re, &ctx, full))
					goto end_of_match;
				break;
			default:
				/* should never happen */
				goto end_of_match;
			}

			/* A header has matched the name pattern, let's test its
			 * value now (always defined from there). If there is no
			 * value pattern, it is a good match.
			 */

			if (expect->flags & TCPCHK_EXPT_FL_HTTP_HVAL_NONE) {
				match = 1;
				goto end_of_match;
			}

			value = ctx.value;
			switch (expect->flags & TCPCHK_EXPT_FL_HTTP_HVAL_TYPE) {
			case TCPCHK_EXPT_FL_HTTP_HVAL_STR:
				if (isteq(value, vpat)) {
					match = 1;
					goto end_of_match;
				}
				break;
			case TCPCHK_EXPT_FL_HTTP_HVAL_BEG:
				if (istlen(value) < istlen(vpat))
					break;
				value = ist2(istptr(value), istlen(vpat));
				if (isteq(value, vpat)) {
					match = 1;
					goto end_of_match;
				}
				break;
			case TCPCHK_EXPT_FL_HTTP_HVAL_END:
				if (istlen(value) < istlen(vpat))
					break;
				value = ist2(istend(value) - istlen(vpat), istlen(vpat));
				if (isteq(value, vpat)) {
					match = 1;
					goto end_of_match;
				}
				break;
			case TCPCHK_EXPT_FL_HTTP_HVAL_SUB:
				if (isttest(istist(value, vpat))) {
					match = 1;
					goto end_of_match;
				}
				break;
			case TCPCHK_EXPT_FL_HTTP_HVAL_REG:
				if (regex_exec2(expect->hdr.value_re, istptr(value), istlen(value))) {
					match = 1;
					goto end_of_match;
				}
				break;
			}
		}

	  end_of_match:
		status = ((status != HCHK_STATUS_UNKNOWN) ? status : HCHK_STATUS_L7STS);
		if (LIST_ISEMPTY(&expect->onerror_fmt))
			desc = htx_sl_res_reason(sl);
		break;
	}

	case TCPCHK_EXPECT_HTTP_BODY:
	case TCPCHK_EXPECT_HTTP_BODY_REGEX:
	case TCPCHK_EXPECT_HTTP_BODY_LF:
		match = 0;
		chunk_reset(&trash);
		for (blk = htx_get_head_blk(htx); blk; blk = htx_get_next_blk(htx, blk)) {
			enum htx_blk_type type = htx_get_blk_type(blk);

			if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
				break;
			if (type == HTX_BLK_DATA) {
				if (!chunk_istcat(&trash, htx_get_blk_value(htx, blk)))
					break;
			}
		}

		if (!b_data(&trash)) {
			if (!last_read) {
				TRACE_DEVEL("waiting for more data", CHK_EV_TCPCHK_EXP, check);
				goto wait_more_data;
			}
			status = ((status != HCHK_STATUS_UNKNOWN) ? status : HCHK_STATUS_L7RSP);
			if (LIST_ISEMPTY(&expect->onerror_fmt))
				desc = ist("HTTP content check could not find a response body");
			TRACE_ERROR("no response boduy found while expected", CHK_EV_TCPCHK_EXP|CHK_EV_TCPCHK_ERR, check);
			goto error;
		}

		if (expect->type == TCPCHK_EXPECT_HTTP_BODY_LF) {
			tmp = alloc_trash_chunk();
			if (!tmp) {
				status = HCHK_STATUS_L7RSP;
				desc = ist("Failed to allocate buffer to eval log-format string");
				TRACE_ERROR("buffer allocation failure", CHK_EV_TCPCHK_EXP|CHK_EV_TCPCHK_ERR, check);
				goto error;
			}
			tmp->data = sess_build_logline(check->sess, NULL, b_orig(tmp), b_size(tmp), &expect->fmt);
			if (!b_data(tmp)) {
				status = HCHK_STATUS_L7RSP;
				desc = ist("log-format string evaluated to an empty string");
				TRACE_ERROR("invalid log-format string", CHK_EV_TCPCHK_EXP|CHK_EV_TCPCHK_ERR, check);
				goto error;
			}
		}

		if (!last_read &&
		    ((expect->type == TCPCHK_EXPECT_HTTP_BODY && b_data(&trash) < istlen(expect->data)) ||
		     ((expect->type == TCPCHK_EXPECT_HTTP_BODY_LF && b_data(&trash) < b_data(tmp))) ||
		     (expect->min_recv > 0 && b_data(&trash) < expect->min_recv))) {
			ret = TCPCHK_EVAL_WAIT;
			goto out;
		}

		if (expect->type ==TCPCHK_EXPECT_HTTP_BODY)
			match = my_memmem(b_orig(&trash), b_data(&trash), istptr(expect->data), istlen(expect->data)) != NULL;
		else if (expect->type ==TCPCHK_EXPECT_HTTP_BODY_LF)
			match = my_memmem(b_orig(&trash), b_data(&trash), b_orig(tmp), b_data(tmp)) != NULL;
		else
			match = regex_exec2(expect->regex, b_orig(&trash), b_data(&trash));

		/* Wait for more data on mismatch only if no minimum is defined (-1),
		 * otherwise the absence of match is already conclusive.
		 */
		if (!match && !last_read && (expect->min_recv == -1)) {
			ret = TCPCHK_EVAL_WAIT;
			TRACE_DEVEL("waiting for more data", CHK_EV_TCPCHK_EXP, check);
			goto out;
		}

		/* Set status and description in case of error */
		status = ((status != HCHK_STATUS_UNKNOWN) ? status : HCHK_STATUS_L7RSP);
		if (LIST_ISEMPTY(&expect->onerror_fmt))
			desc = (inverse
				? ist("HTTP check matched unwanted content")
				: ist("HTTP content check did not match"));
		break;


	default:
		/* should never happen */
		status = ((status != HCHK_STATUS_UNKNOWN) ? status : HCHK_STATUS_L7RSP);
		goto error;
	}

	if (!(match ^ inverse)) {
		TRACE_STATE("expect rule failed", CHK_EV_TCPCHK_EXP|CHK_EV_TCPCHK_ERR, check);
		goto error;
	}

	TRACE_STATE("expect rule succeeded", CHK_EV_TCPCHK_EXP, check);

  out:
	free_trash_chunk(tmp);
	free_trash_chunk(nbuf);
	free_trash_chunk(vbuf);
	free_trash_chunk(msg);
	TRACE_LEAVE(CHK_EV_TCPCHK_EXP, check, 0, 0, (size_t[]){ret});
	return ret;

  error:
	TRACE_STATE("expect rule failed", CHK_EV_TCPCHK_EXP|CHK_EV_TCPCHK_ERR, check);
	ret = TCPCHK_EVAL_STOP;
	msg = alloc_trash_chunk();
	if (msg)
		tcpcheck_expect_onerror_message(msg, check, rule, 0, desc);
	set_server_check_status(check, status, (msg ? b_head(msg) : NULL));
	goto out;

  wait_more_data:
	ret = TCPCHK_EVAL_WAIT;
	goto out;
}

/* Evaluates a TCP TCPCHK_ACT_EXPECT rule. Returns TCPCHK_EVAL_WAIT to wait for
 * more data, TCPCHK_EVAL_CONTINUE to evaluate the next rule or TCPCHK_EVAL_STOP
 * if an error occurred.
 */
enum tcpcheck_eval_ret tcpcheck_eval_expect(struct check *check, struct tcpcheck_rule *rule, int last_read)
{
	enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
	struct tcpcheck_expect *expect = &rule->expect;
	struct buffer *msg = NULL, *tmp = NULL;
	struct ist desc = IST_NULL;
	enum healthcheck_status status;
	int match, inverse;

	TRACE_ENTER(CHK_EV_TCPCHK_EXP, check);

	last_read |= b_full(&check->bi);

	/* The current expect might need more data than the previous one, check again
	 * that the minimum amount data required to match is respected.
	 */
	if (!last_read) {
		if ((expect->type == TCPCHK_EXPECT_STRING || expect->type == TCPCHK_EXPECT_BINARY) &&
		    (b_data(&check->bi) < istlen(expect->data))) {
			ret = TCPCHK_EVAL_WAIT;
			TRACE_DEVEL("waiting for more data", CHK_EV_TCPCHK_EXP, check);
			goto out;
		}
		if (expect->min_recv > 0 && (b_data(&check->bi) < expect->min_recv)) {
			ret = TCPCHK_EVAL_WAIT;
			TRACE_DEVEL("waiting for more data", CHK_EV_TCPCHK_EXP, check);
			goto out;
		}
	}

	inverse = !!(expect->flags & TCPCHK_EXPT_FL_INV);
	/* Make GCC happy ; initialize match to a failure state. */
	match = inverse;
	status = ((expect->err_status != HCHK_STATUS_UNKNOWN) ? expect->err_status : HCHK_STATUS_L7RSP);

	switch (expect->type) {
	case TCPCHK_EXPECT_STRING:
	case TCPCHK_EXPECT_BINARY:
		match = my_memmem(b_head(&check->bi), b_data(&check->bi), istptr(expect->data), istlen(expect->data)) != NULL;
		break;
	case TCPCHK_EXPECT_STRING_REGEX:
		match = regex_exec2(expect->regex, b_head(&check->bi), MIN(b_data(&check->bi), b_size(&check->bi)-1));
		break;

	case TCPCHK_EXPECT_BINARY_REGEX:
		chunk_reset(&trash);
		dump_binary(&trash, b_head(&check->bi), b_data(&check->bi));
		match = regex_exec2(expect->regex, b_head(&trash), MIN(b_data(&trash), b_size(&trash)-1));
		break;

	case TCPCHK_EXPECT_STRING_LF:
	case TCPCHK_EXPECT_BINARY_LF:
		match = 0;
		tmp = alloc_trash_chunk();
		if (!tmp) {
			status = HCHK_STATUS_L7RSP;
			desc = ist("Failed to allocate buffer to eval format string");
			TRACE_ERROR("buffer allocation failure", CHK_EV_TCPCHK_EXP|CHK_EV_TCPCHK_ERR, check);
			goto error;
		}
		tmp->data = sess_build_logline(check->sess, NULL, b_orig(tmp), b_size(tmp), &expect->fmt);
		if (!b_data(tmp)) {
			status = HCHK_STATUS_L7RSP;
			desc = ist("log-format string evaluated to an empty string");
			TRACE_ERROR("invalid log-format string", CHK_EV_TCPCHK_EXP|CHK_EV_TCPCHK_ERR, check);
			goto error;
		}
		if (expect->type == TCPCHK_EXPECT_BINARY_LF) {
			int len = tmp->data;
			if (parse_binary(b_orig(tmp),  &tmp->area, &len, NULL) == 0) {
				status = HCHK_STATUS_L7RSP;
				desc = ist("Failed to parse hexastring resulting of eval of a log-format string");
				TRACE_ERROR("invalid binary log-format string", CHK_EV_TCPCHK_EXP|CHK_EV_TCPCHK_ERR, check);
				goto error;
			}
			tmp->data = len;
		}
		if (b_data(&check->bi) < tmp->data) {
			if (!last_read) {
				ret = TCPCHK_EVAL_WAIT;
				TRACE_DEVEL("waiting for more data", CHK_EV_TCPCHK_EXP, check);
				goto out;
			}
			break;
		}
		match = my_memmem(b_head(&check->bi), b_data(&check->bi), b_orig(tmp), b_data(tmp)) != NULL;
		break;

	case TCPCHK_EXPECT_CUSTOM:
		/* Don't eval custom function if the buffer is empty. It means
		 * custom functions can't expect an empty response. If this
		 * change, don't forget to change this test and update all
		 * custom functions.
		 */
		if (!b_data(&check->bi))
			break;
		if (expect->custom)
			ret = expect->custom(check, rule, last_read);
		goto out;
	default:
		/* Should never happen. */
		ret = TCPCHK_EVAL_STOP;
		goto out;
	}


	/* Wait for more data on mismatch only if no minimum is defined (-1),
	 * otherwise the absence of match is already conclusive.
	 */
	if (!match && !last_read && (expect->min_recv == -1)) {
		ret = TCPCHK_EVAL_WAIT;
		TRACE_DEVEL("waiting for more data", CHK_EV_TCPCHK_EXP, check);
		goto out;
	}

	/* Result as expected, next rule. */
	if (match ^ inverse) {
		TRACE_STATE("expect rule succeeded", CHK_EV_TCPCHK_EXP, check);
		goto out;
	}

  error:
	/* From this point on, we matched something we did not want, this is an error state. */
	TRACE_STATE("expect rule failed", CHK_EV_TCPCHK_EXP|CHK_EV_TCPCHK_ERR, check);
	ret = TCPCHK_EVAL_STOP;
	msg = alloc_trash_chunk();
	if (msg)
		tcpcheck_expect_onerror_message(msg, check, rule, match, desc);
	set_server_check_status(check, status, (msg ? b_head(msg) : NULL));
	free_trash_chunk(msg);

  out:
	free_trash_chunk(tmp);
	TRACE_LEAVE(CHK_EV_TCPCHK_EXP, check, 0, 0, (size_t[]){ret});
	return ret;
}

/* Evaluates a TCPCHK_ACT_ACTION_KW rule. Returns TCPCHK_EVAL_CONTINUE to
 * evaluate the next rule or TCPCHK_EVAL_STOP if an error occurred. It never
 * waits.
 */
enum tcpcheck_eval_ret tcpcheck_eval_action_kw(struct check *check, struct tcpcheck_rule *rule)
{
	enum tcpcheck_eval_ret ret = TCPCHK_EVAL_CONTINUE;
	struct act_rule *act_rule;
	enum act_return act_ret;

	act_rule =rule->action_kw.rule;
	act_ret = act_rule->action_ptr(act_rule, check->proxy, check->sess, NULL, 0);
	if (act_ret != ACT_RET_CONT) {
		chunk_printf(&trash, "TCPCHK ACTION unexpected result at step %d\n",
			     tcpcheck_get_step_id(check, rule));
		set_server_check_status(check, HCHK_STATUS_L7RSP, trash.area);
		ret = TCPCHK_EVAL_STOP;
	}

	return ret;
}

/* Executes a tcp-check ruleset. Note that this is called both from the
 * connection's wake() callback and from the check scheduling task.  It returns
 * 0 on normal cases, or <0 if a close() has happened on an existing connection,
 * presenting the risk of an fd replacement.
 *
 * Please do NOT place any return statement in this function and only leave
 * via the out_end_tcpcheck label after setting retcode.
 */
int tcpcheck_main(struct check *check)
{
	struct tcpcheck_rule *rule;
	struct stconn *sc = check->sc;
	struct connection *conn = sc_conn(sc);
	int must_read = 1, last_read = 0;
	int retcode = 0;
	enum tcpcheck_eval_ret eval_ret;

	/* here, we know that the check is complete or that it failed */
	if (check->result != CHK_RES_UNKNOWN)
		goto out;

	TRACE_ENTER(CHK_EV_TCPCHK_EVAL, check);

	/* Note: the stream connector and the connection may only be undefined before
	 * the first rule evaluation (it is always a connect rule) or when the
	 * stream connector allocation failed on a connect rule, during sc allocation.
	 */

	/* 1- check for connection error, if any */
	if ((conn && conn->flags & CO_FL_ERROR) || sc_ep_test(sc, SE_FL_ERROR))
		goto out_end_tcpcheck;

	/* 2- check if a rule must be resume. It happens if check->current_step
	 *    is defined. */
	else if (check->current_step) {
		rule = check->current_step;
		TRACE_PROTO("resume rule evaluation", CHK_EV_TCPCHK_EVAL, check, 0, 0, (size_t[]){ tcpcheck_get_step_id(check, rule)});
	}

	/* 3- It is the first evaluation. We must create a session and preset
	 *    tcp-check variables */
        else {
		struct tcpcheck_var *var;

		/* First evaluation, create a session */
		check->sess = session_new(&checks_fe, NULL, &check->obj_type);
		if (!check->sess) {
			chunk_printf(&trash, "TCPCHK error allocating check session");
			TRACE_ERROR("session allocation failure", CHK_EV_TCPCHK_EVAL|CHK_EV_TCPCHK_ERR, check);
			set_server_check_status(check, HCHK_STATUS_SOCKERR, trash.area);
			goto out_end_tcpcheck;
		}
		vars_init_head(&check->vars, SCOPE_CHECK);
		rule = LIST_NEXT(check->tcpcheck_rules->list, typeof(rule), list);

		/* Preset tcp-check variables */
		list_for_each_entry(var, &check->tcpcheck_rules->preset_vars, list) {
			struct sample smp;

			memset(&smp, 0, sizeof(smp));
			smp_set_owner(&smp, check->proxy, check->sess, NULL, SMP_OPT_FINAL);
			smp.data = var->data;
			vars_set_by_name_ifexist(istptr(var->name), istlen(var->name), &smp);
		}
		TRACE_PROTO("start rules evaluation", CHK_EV_TCPCHK_EVAL, check);
	}

	/* Now evaluate the tcp-check rules */

	list_for_each_entry_from(rule, check->tcpcheck_rules->list, list) {
		check->code = 0;
		switch (rule->action) {
		case TCPCHK_ACT_CONNECT:
			/* Not the first connection, release it first */
			if (sc_conn(sc) && check->current_step != rule) {
				check->state |= CHK_ST_CLOSE_CONN;
				retcode = -1;
			}

			check->current_step = rule;

			/* We are still waiting the connection gets closed */
			if (check->state & CHK_ST_CLOSE_CONN) {
				TRACE_DEVEL("wait previous connection closure", CHK_EV_TCPCHK_EVAL|CHK_EV_TCPCHK_CONN, check);
				eval_ret = TCPCHK_EVAL_WAIT;
				break;
			}

			TRACE_PROTO("eval connect rule", CHK_EV_TCPCHK_EVAL|CHK_EV_TCPCHK_CONN, check);
			eval_ret = tcpcheck_eval_connect(check, rule);

			/* Refresh connection */
			conn = sc_conn(sc);
			last_read = 0;
			must_read = (IS_HTX_SC(sc) ? htx_is_empty(htxbuf(&check->bi)) : !b_data(&check->bi));
			break;
		case TCPCHK_ACT_SEND:
			check->current_step = rule;
			TRACE_PROTO("eval send rule", CHK_EV_TCPCHK_EVAL|CHK_EV_TCPCHK_SND, check);
			eval_ret = tcpcheck_eval_send(check, rule);
			must_read = 1;
			break;
		case TCPCHK_ACT_EXPECT:
			check->current_step = rule;
			TRACE_PROTO("eval expect rule", CHK_EV_TCPCHK_EVAL|CHK_EV_TCPCHK_EXP, check);
			if (must_read) {
				eval_ret = tcpcheck_eval_recv(check, rule);
				if (eval_ret == TCPCHK_EVAL_STOP)
					goto out_end_tcpcheck;
				else if (eval_ret == TCPCHK_EVAL_WAIT)
					goto out;
				last_read = ((conn->flags & CO_FL_ERROR) || sc_ep_test(sc, SE_FL_ERROR | SE_FL_EOS));
				must_read = 0;
			}

			eval_ret = ((check->tcpcheck_rules->flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_HTTP_CHK
				    ? tcpcheck_eval_expect_http(check, rule, last_read)
				    : tcpcheck_eval_expect(check, rule, last_read));

			if (eval_ret == TCPCHK_EVAL_WAIT) {
				check->current_step = rule->expect.head;
				if (!(sc->wait_event.events & SUB_RETRY_RECV))
					conn->mux->subscribe(sc, SUB_RETRY_RECV, &sc->wait_event);
			}
			break;
		case TCPCHK_ACT_ACTION_KW:
			/* Don't update the current step */
			TRACE_PROTO("eval action kw rule", CHK_EV_TCPCHK_EVAL|CHK_EV_TCPCHK_ACT, check);
			eval_ret = tcpcheck_eval_action_kw(check, rule);
			break;
		default:
			/* Otherwise, just go to the next one and don't update
			 * the current step
			 */
			eval_ret = TCPCHK_EVAL_CONTINUE;
			break;
		}

		switch (eval_ret) {
		case TCPCHK_EVAL_CONTINUE:
			break;
		case TCPCHK_EVAL_WAIT:
			goto out;
		case TCPCHK_EVAL_STOP:
			goto out_end_tcpcheck;
		}
	}

	/* All rules was evaluated */
	if (check->current_step) {
		rule = check->current_step;

		TRACE_DEVEL("eval tcp-check result", CHK_EV_TCPCHK_EVAL, check);

		if (rule->action == TCPCHK_ACT_EXPECT) {
			struct buffer *msg;
			enum healthcheck_status status;

			if (check->server &&
			    (check->server->proxy->options & PR_O_DISABLE404) &&
			    (check->server->next_state != SRV_ST_STOPPED) &&
			    (check->code == 404)) {
				set_server_check_status(check, HCHK_STATUS_L7OKCD, NULL);
				TRACE_PROTO("tcp-check conditionally passed (disable-404)", CHK_EV_TCPCHK_EVAL, check);
				goto out_end_tcpcheck;
			}

			msg = alloc_trash_chunk();
			if (msg)
				tcpcheck_expect_onsuccess_message(msg, check, rule, IST_NULL);
			status = ((rule->expect.ok_status != HCHK_STATUS_UNKNOWN) ? rule->expect.ok_status : HCHK_STATUS_L7OKD);
			set_server_check_status(check, status, (msg ? b_head(msg) : "(tcp-check)"));
			free_trash_chunk(msg);
		}
		else if (rule->action == TCPCHK_ACT_CONNECT) {
			const char *msg = ((rule->connect.options & TCPCHK_OPT_IMPLICIT) ? NULL : "(tcp-check)");
			enum healthcheck_status status = HCHK_STATUS_L4OK;
#ifdef USE_OPENSSL
			if (conn_is_ssl(conn))
				status = HCHK_STATUS_L6OK;
#endif
			set_server_check_status(check, status, msg);
		}
		else
			set_server_check_status(check, HCHK_STATUS_L7OKD, "(tcp-check)");
	}
	else {
		set_server_check_status(check, HCHK_STATUS_L7OKD, "(tcp-check)");
	}
	TRACE_PROTO("tcp-check passed", CHK_EV_TCPCHK_EVAL, check);

  out_end_tcpcheck:
	if ((conn && conn->flags & CO_FL_ERROR) || sc_ep_test(sc, SE_FL_ERROR)) {
		TRACE_ERROR("report connection error", CHK_EV_TCPCHK_EVAL|CHK_EV_TCPCHK_ERR, check);
		chk_report_conn_err(check, errno, 0);
	}

	/* the tcpcheck is finished, release in/out buffer now */
	check_release_buf(check, &check->bi);
	check_release_buf(check, &check->bo);

  out:
	TRACE_LEAVE(CHK_EV_HCHK_RUN, check);
	return retcode;
}

void tcp_check_keywords_register(struct action_kw_list *kw_list)
{
	LIST_APPEND(&tcp_check_keywords.list, &kw_list->list);
}

/**************************************************************************/
/******************* Internals to parse tcp-check rules *******************/
/**************************************************************************/
struct action_kw_list tcp_check_keywords = {
	.list = LIST_HEAD_INIT(tcp_check_keywords.list),
};

/* Creates a tcp-check rule resulting from parsing a custom keyword. NULL is
 * returned on error.
 */
struct tcpcheck_rule *parse_tcpcheck_action(char **args, int cur_arg, struct proxy *px,
                                            struct list *rules, struct action_kw *kw,
                                            const char *file, int line, char **errmsg)
{
	struct tcpcheck_rule *chk = NULL;
	struct act_rule *actrule = NULL;

	actrule = new_act_rule(ACT_F_TCP_CHK, file, line);
	if (!actrule) {
		memprintf(errmsg, "out of memory");
		goto error;
	}
	actrule->kw = kw;

	cur_arg++;
	if (kw->parse((const char **)args, &cur_arg, px, actrule, errmsg) == ACT_RET_PRS_ERR) {
		memprintf(errmsg, "'%s' : %s", kw->kw, *errmsg);
		goto error;
	}

	chk = calloc(1, sizeof(*chk));
	if (!chk) {
		memprintf(errmsg, "out of memory");
		goto error;
	}
	chk->action = TCPCHK_ACT_ACTION_KW;
	chk->action_kw.rule = actrule;
	return chk;

  error:
	free(actrule);
	return NULL;
}

/* Parses and creates a tcp-check connect or an http-check connect rule. NULL is
 * returned on error.
 */
struct tcpcheck_rule *parse_tcpcheck_connect(char **args, int cur_arg, struct proxy *px, struct list *rules,
                                             const char *file, int line, char **errmsg)
{
	struct tcpcheck_rule *chk = NULL;
	struct sockaddr_storage *sk = NULL;
	char *comment = NULL, *sni = NULL, *alpn = NULL;
	struct sample_expr *port_expr = NULL;
	const struct mux_proto_list *mux_proto = NULL;
	unsigned short conn_opts = 0;
	long port = 0;
	int alpn_len = 0;

	list_for_each_entry(chk, rules, list) {
		if (chk->action == TCPCHK_ACT_CONNECT)
			break;
		if (chk->action == TCPCHK_ACT_COMMENT ||
		    chk->action == TCPCHK_ACT_ACTION_KW ||
		    (chk->action == TCPCHK_ACT_SEND && (chk->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT)))
			continue;

		memprintf(errmsg, "first step MUST also be a 'connect', "
			  "optionally preceded by a 'set-var', an 'unset-var' or a 'comment', "
			  "when there is a 'connect' step in the tcp-check ruleset");
		goto error;
	}

	cur_arg++;
	while (*(args[cur_arg])) {
		if (strcmp(args[cur_arg], "default") == 0)
			conn_opts |= TCPCHK_OPT_DEFAULT_CONNECT;
		else if (strcmp(args[cur_arg], "addr") == 0) {
			int port1, port2;

			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects <ipv4|ipv6> as argument.", args[cur_arg]);
				goto error;
			}

			sk = str2sa_range(args[cur_arg+1], NULL, &port1, &port2, NULL, NULL, NULL,
			                  errmsg, NULL, NULL, PA_O_RESOLVE | PA_O_PORT_OK | PA_O_STREAM | PA_O_CONNECT);
			if (!sk) {
				memprintf(errmsg, "'%s' : %s.", args[cur_arg], *errmsg);
				goto error;
			}

			cur_arg++;
		}
		else if (strcmp(args[cur_arg], "port") == 0) {
			const char *p, *end;

			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a port number or a sample expression as argument.", args[cur_arg]);
				goto error;
			}
			cur_arg++;

			port = 0;
			release_sample_expr(port_expr);
			p = args[cur_arg]; end = p + strlen(p);
			port = read_uint(&p, end);
			if (p != end) {
				int idx = 0;

				px->conf.args.ctx = ARGC_SRV;
				port_expr = sample_parse_expr((char *[]){args[cur_arg], NULL}, &idx,
							      file, line, errmsg, &px->conf.args, NULL);

				if (!port_expr) {
					memprintf(errmsg, "error detected while parsing port expression : %s", *errmsg);
					goto error;
				}
				if (!(port_expr->fetch->val & SMP_VAL_BE_CHK_RUL)) {
					memprintf(errmsg, "error detected while parsing port expression : "
						  " fetch method '%s' extracts information from '%s', "
						  "none of which is available here.\n",
						  args[cur_arg], sample_src_names(port_expr->fetch->use));
					goto error;
				}
				px->http_needed |= !!(port_expr->fetch->use & SMP_USE_HTTP_ANY);
			}
			else if (port > 65535 || port < 1) {
				memprintf(errmsg, "expects a valid TCP port (from range 1 to 65535) or a sample expression, got %s.",
					  args[cur_arg]);
				goto error;
			}
		}
		else if (strcmp(args[cur_arg], "proto") == 0) {
			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a MUX protocol as argument.", args[cur_arg]);
				goto error;
			}
			mux_proto = get_mux_proto(ist(args[cur_arg + 1]));
			if (!mux_proto) {
				memprintf(errmsg, "'%s' : unknown MUX protocol '%s'.", args[cur_arg], args[cur_arg+1]);
				goto error;
			}

			if (strcmp(args[0], "tcp-check") == 0 && mux_proto->mode != PROTO_MODE_TCP) {
				memprintf(errmsg, "'%s' : invalid MUX protocol '%s' for tcp-check", args[cur_arg], args[cur_arg+1]);
				goto error;
			}
			else if (strcmp(args[0], "http-check") == 0 && mux_proto->mode != PROTO_MODE_HTTP) {
				memprintf(errmsg, "'%s' : invalid MUX protocol '%s' for http-check", args[cur_arg], args[cur_arg+1]);
				goto error;
			}

			cur_arg++;
		}
		else if (strcmp(args[cur_arg], "comment") == 0) {
			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
				goto error;
			}
			cur_arg++;
			free(comment);
			comment = strdup(args[cur_arg]);
			if (!comment) {
				memprintf(errmsg, "out of memory");
				goto error;
			}
		}
		else if (strcmp(args[cur_arg], "send-proxy") == 0)
			conn_opts |= TCPCHK_OPT_SEND_PROXY;
		else if (strcmp(args[cur_arg], "via-socks4") == 0)
			conn_opts |= TCPCHK_OPT_SOCKS4;
		else if (strcmp(args[cur_arg], "linger") == 0)
			conn_opts |= TCPCHK_OPT_LINGER;
#ifdef USE_OPENSSL
		else if (strcmp(args[cur_arg], "ssl") == 0) {
			px->options |= PR_O_TCPCHK_SSL;
			conn_opts |= TCPCHK_OPT_SSL;
		}
		else if (strcmp(args[cur_arg], "sni") == 0) {
			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
				goto error;
			}
			cur_arg++;
			free(sni);
			sni = strdup(args[cur_arg]);
			if (!sni) {
				memprintf(errmsg, "out of memory");
				goto error;
			}
		}
		else if (strcmp(args[cur_arg], "alpn") == 0) {
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
			free(alpn);
			if (ssl_sock_parse_alpn(args[cur_arg + 1], &alpn, &alpn_len, errmsg)) {
				memprintf(errmsg, "'%s' : %s", args[cur_arg], *errmsg);
				goto error;
			}
			cur_arg++;
#else
			memprintf(errmsg, "'%s' : library does not support TLS ALPN extension.", args[cur_arg]);
			goto error;
#endif
		}
#endif /* USE_OPENSSL */

		else {
			memprintf(errmsg, "expects 'comment', 'port', 'addr', 'send-proxy'"
#ifdef USE_OPENSSL
				  ", 'ssl', 'sni', 'alpn'"
#endif /* USE_OPENSSL */
				  " or 'via-socks4', 'linger', 'default' but got '%s' as argument.",
				  args[cur_arg]);
			goto error;
		}
		cur_arg++;
	}

	chk = calloc(1, sizeof(*chk));
	if (!chk) {
		memprintf(errmsg, "out of memory");
		goto error;
	}
	chk->action  = TCPCHK_ACT_CONNECT;
	chk->comment = comment;
	chk->connect.port    = port;
	chk->connect.options = conn_opts;
	chk->connect.sni     = sni;
	chk->connect.alpn    = alpn;
	chk->connect.alpn_len= alpn_len;
	chk->connect.port_expr= port_expr;
	chk->connect.mux_proto= mux_proto;
	if (sk)
		chk->connect.addr = *sk;
	return chk;

  error:
	free(alpn);
	free(sni);
	free(comment);
	release_sample_expr(port_expr);
	return NULL;
}

/* Parses and creates a tcp-check send rule. NULL is returned on error */
struct tcpcheck_rule *parse_tcpcheck_send(char **args, int cur_arg, struct proxy *px, struct list *rules,
                                          const char *file, int line, char **errmsg)
{
	struct tcpcheck_rule *chk = NULL;
	char *comment = NULL, *data = NULL;
	enum tcpcheck_send_type type = TCPCHK_SEND_UNDEF;

	if (strcmp(args[cur_arg], "send-binary-lf") == 0)
		type = TCPCHK_SEND_BINARY_LF;
	else if (strcmp(args[cur_arg], "send-binary") == 0)
		type = TCPCHK_SEND_BINARY;
	else if (strcmp(args[cur_arg], "send-lf") == 0)
		type = TCPCHK_SEND_STRING_LF;
	else if (strcmp(args[cur_arg], "send") == 0)
		type = TCPCHK_SEND_STRING;

	if (!*(args[cur_arg+1])) {
		memprintf(errmsg, "'%s' expects a %s as argument",
			  (type == TCPCHK_SEND_BINARY ? "binary string": "string"), args[cur_arg]);
		goto error;
	}

	data = args[cur_arg+1];

	cur_arg += 2;
	while (*(args[cur_arg])) {
		if (strcmp(args[cur_arg], "comment") == 0) {
			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
				goto error;
			}
			cur_arg++;
			free(comment);
			comment = strdup(args[cur_arg]);
			if (!comment) {
				memprintf(errmsg, "out of memory");
				goto error;
			}
		}
		else {
			memprintf(errmsg, "expects 'comment' but got '%s' as argument.",
				  args[cur_arg]);
			goto error;
		}
		cur_arg++;
	}

	chk = calloc(1, sizeof(*chk));
	if (!chk) {
		memprintf(errmsg, "out of memory");
		goto error;
	}
	chk->action      = TCPCHK_ACT_SEND;
	chk->comment     = comment;
	chk->send.type   = type;

	switch (chk->send.type) {
	case TCPCHK_SEND_STRING:
		chk->send.data = ist(strdup(data));
		if (!isttest(chk->send.data)) {
			memprintf(errmsg, "out of memory");
			goto error;
		}
		break;
	case TCPCHK_SEND_BINARY: {
		int len = chk->send.data.len;
		if (parse_binary(data, &chk->send.data.ptr, &len, errmsg) == 0) {
			memprintf(errmsg, "'%s' invalid binary string (%s).\n", data, *errmsg);
			goto error;
		}
		chk->send.data.len = len;
		break;
	}
	case TCPCHK_SEND_STRING_LF:
	case TCPCHK_SEND_BINARY_LF:
		LIST_INIT(&chk->send.fmt);
		px->conf.args.ctx = ARGC_SRV;
		if (!parse_logformat_string(data, px, &chk->send.fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
			memprintf(errmsg, "'%s' invalid log-format string (%s).\n", data, *errmsg);
			goto error;
		}
		break;
	case TCPCHK_SEND_HTTP:
	case TCPCHK_SEND_UNDEF:
		goto error;
	}

	return chk;

  error:
	free(chk);
	free(comment);
	return NULL;
}

/* Parses and creates a http-check send rule. NULL is returned on error */
struct tcpcheck_rule *parse_tcpcheck_send_http(char **args, int cur_arg, struct proxy *px, struct list *rules,
                                               const char *file, int line, char **errmsg)
{
	struct tcpcheck_rule *chk = NULL;
	struct tcpcheck_http_hdr *hdr = NULL;
        struct http_hdr hdrs[global.tune.max_http_hdr];
	char *meth = NULL, *uri = NULL, *vsn = NULL;
	char *body = NULL, *comment = NULL;
	unsigned int flags = 0;
	int i = 0, host_hdr = -1;

	cur_arg++;
	while (*(args[cur_arg])) {
		if (strcmp(args[cur_arg], "meth") == 0) {
			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
				goto error;
			}
			cur_arg++;
			meth = args[cur_arg];
		}
		else if (strcmp(args[cur_arg], "uri") == 0 || strcmp(args[cur_arg], "uri-lf") == 0) {
			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
				goto error;
			}
			flags &= ~TCPCHK_SND_HTTP_FL_URI_FMT;
			if (strcmp(args[cur_arg], "uri-lf") == 0)
				flags |= TCPCHK_SND_HTTP_FL_URI_FMT;
			cur_arg++;
			uri = args[cur_arg];
		}
		else if (strcmp(args[cur_arg], "ver") == 0) {
			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
				goto error;
			}
			cur_arg++;
			vsn = args[cur_arg];
		}
                else if (strcmp(args[cur_arg], "hdr") == 0) {
			if (!*args[cur_arg+1] || !*args[cur_arg+2]) {
				memprintf(errmsg, "'%s' expects <name> and <value> as arguments", args[cur_arg]);
				goto error;
			}

			if (strcasecmp(args[cur_arg+1], "host") == 0) {
				if (host_hdr >= 0) {
					memprintf(errmsg, "'%s' header already defined (previous value is '%s')",
						  args[cur_arg+1], istptr(hdrs[host_hdr].v));
					goto error;
				}
				host_hdr = i;
			}
			else if (strcasecmp(args[cur_arg+1], "content-length") == 0 ||
				 strcasecmp(args[cur_arg+1], "transfer-encoding") == 0)
				goto skip_hdr;

			hdrs[i].n = ist(args[cur_arg + 1]);
			hdrs[i].v = ist(args[cur_arg + 2]);
			i++;
		  skip_hdr:
			cur_arg += 2;
		}
		else if (strcmp(args[cur_arg], "body") == 0 || strcmp(args[cur_arg], "body-lf") == 0) {
			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
				goto error;
			}
			flags &= ~TCPCHK_SND_HTTP_FL_BODY_FMT;
			if (strcmp(args[cur_arg], "body-lf") == 0)
				flags |= TCPCHK_SND_HTTP_FL_BODY_FMT;
			cur_arg++;
			body = args[cur_arg];
		}
		else if (strcmp(args[cur_arg], "comment") == 0) {
			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a string as argument.", args[cur_arg]);
				goto error;
			}
			cur_arg++;
			free(comment);
			comment = strdup(args[cur_arg]);
			if (!comment) {
				memprintf(errmsg, "out of memory");
				goto error;
			}
		}
		else {
			memprintf(errmsg, "expects 'comment', 'meth', 'uri', 'uri-lf', 'ver', 'hdr', 'body' or 'body-lf'"
				  " but got '%s' as argument.", args[cur_arg]);
			goto error;
		}
		cur_arg++;
	}

	hdrs[i].n = hdrs[i].v = IST_NULL;

	chk = calloc(1, sizeof(*chk));
	if (!chk) {
		memprintf(errmsg, "out of memory");
		goto error;
	}
	chk->action    = TCPCHK_ACT_SEND;
	chk->comment   = comment; comment = NULL;
	chk->send.type = TCPCHK_SEND_HTTP;
	chk->send.http.flags = flags;
	LIST_INIT(&chk->send.http.hdrs);

	if (meth) {
		chk->send.http.meth.meth = find_http_meth(meth, strlen(meth));
		chk->send.http.meth.str.area = strdup(meth);
		chk->send.http.meth.str.data = strlen(meth);
		if (!chk->send.http.meth.str.area) {
			memprintf(errmsg, "out of memory");
			goto error;
		}
	}
	if (uri) {
		if (chk->send.http.flags & TCPCHK_SND_HTTP_FL_URI_FMT) {
			LIST_INIT(&chk->send.http.uri_fmt);
			px->conf.args.ctx = ARGC_SRV;
			if (!parse_logformat_string(uri, px, &chk->send.http.uri_fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
				memprintf(errmsg, "'%s' invalid log-format string (%s).\n", uri, *errmsg);
				goto error;
			}
		}
		else {
			chk->send.http.uri = ist(strdup(uri));
			if (!isttest(chk->send.http.uri)) {
				memprintf(errmsg, "out of memory");
				goto error;
			}
		}
	}
	if (vsn) {
		chk->send.http.vsn = ist(strdup(vsn));
		if (!isttest(chk->send.http.vsn)) {
			memprintf(errmsg, "out of memory");
			goto error;
		}
	}
	for (i = 0; istlen(hdrs[i].n); i++) {
		hdr = calloc(1, sizeof(*hdr));
		if (!hdr) {
			memprintf(errmsg, "out of memory");
			goto error;
		}
		LIST_INIT(&hdr->value);
		hdr->name = istdup(hdrs[i].n);
		if (!isttest(hdr->name)) {
			memprintf(errmsg, "out of memory");
			goto error;
		}

		ist0(hdrs[i].v);
		if (!parse_logformat_string(istptr(hdrs[i].v), px, &hdr->value, 0, SMP_VAL_BE_CHK_RUL, errmsg))
			goto error;
		LIST_APPEND(&chk->send.http.hdrs, &hdr->list);
		hdr = NULL;
	}

	if (body) {
		if (chk->send.http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT) {
			LIST_INIT(&chk->send.http.body_fmt);
			px->conf.args.ctx = ARGC_SRV;
			if (!parse_logformat_string(body, px, &chk->send.http.body_fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
				memprintf(errmsg, "'%s' invalid log-format string (%s).\n", body, *errmsg);
				goto error;
			}
		}
		else {
			chk->send.http.body = ist(strdup(body));
			if (!isttest(chk->send.http.body)) {
				memprintf(errmsg, "out of memory");
				goto error;
			}
		}
	}

	return chk;

  error:
	free_tcpcheck_http_hdr(hdr);
	free_tcpcheck(chk, 0);
	free(comment);
	return NULL;
}

/* Parses and creates a http-check comment rule. NULL is returned on error */
struct tcpcheck_rule *parse_tcpcheck_comment(char **args, int cur_arg, struct proxy *px, struct list *rules,
                                             const char *file, int line, char **errmsg)
{
	struct tcpcheck_rule *chk = NULL;
	char *comment = NULL;

	if (!*(args[cur_arg+1])) {
		memprintf(errmsg, "expects a string as argument");
		goto error;
	}
	cur_arg++;
	comment = strdup(args[cur_arg]);
	if (!comment) {
		memprintf(errmsg, "out of memory");
		goto error;
	}

	chk = calloc(1, sizeof(*chk));
	if (!chk) {
		memprintf(errmsg, "out of memory");
		goto error;
	}
	chk->action  = TCPCHK_ACT_COMMENT;
	chk->comment = comment;
	return chk;

  error:
	free(comment);
	return NULL;
}

/* Parses and creates a tcp-check or an http-check expect rule. NULL is returned
 * on error. <proto> is set to the right protocol flags (covered by the
 * TCPCHK_RULES_PROTO_CHK mask).
 */
struct tcpcheck_rule *parse_tcpcheck_expect(char **args, int cur_arg, struct proxy *px,
                                            struct list *rules, unsigned int proto,
                                            const char *file, int line, char **errmsg)
{
	struct tcpcheck_rule *prev_check, *chk = NULL;
	struct sample_expr *status_expr = NULL;
	char *on_success_msg, *on_error_msg, *comment, *pattern, *npat, *vpat;
	enum tcpcheck_expect_type type = TCPCHK_EXPECT_UNDEF;
	enum healthcheck_status ok_st = HCHK_STATUS_UNKNOWN;
	enum healthcheck_status err_st = HCHK_STATUS_UNKNOWN;
	enum healthcheck_status tout_st = HCHK_STATUS_UNKNOWN;
	unsigned int flags = 0;
	long min_recv = -1;
	int inverse = 0;

	on_success_msg = on_error_msg = comment = pattern = npat = vpat = NULL;
	if (!*(args[cur_arg+1])) {
		memprintf(errmsg, "expects at least a matching pattern as arguments");
		goto error;
	}

	cur_arg++;
	while (*(args[cur_arg])) {
		int in_pattern = 0;

	  rescan:
		if (strcmp(args[cur_arg], "min-recv") == 0) {
			if (in_pattern) {
				memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
				goto error;
			}
			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a integer as argument", args[cur_arg]);
				goto error;
			}
			/* Use an signed integer here because of bufsize */
			cur_arg++;
			min_recv = atol(args[cur_arg]);
			if (min_recv < -1 || min_recv > INT_MAX) {
				memprintf(errmsg, "'%s' expects -1 or an integer from 0 to INT_MAX" , args[cur_arg-1]);
				goto error;
			}
		}
		else if (*(args[cur_arg]) == '!') {
			in_pattern = 1;
			while (*(args[cur_arg]) == '!') {
				inverse = !inverse;
				args[cur_arg]++;
			}
			if (!*(args[cur_arg]))
				cur_arg++;
			goto rescan;
		}
		else if (strcmp(args[cur_arg], "string") == 0 || strcmp(args[cur_arg], "rstring") == 0) {
			if (type != TCPCHK_EXPECT_UNDEF) {
				memprintf(errmsg, "only on pattern expected");
				goto error;
			}
			if (proto != TCPCHK_RULES_HTTP_CHK)
				type = ((*(args[cur_arg]) == 's') ? TCPCHK_EXPECT_STRING : TCPCHK_EXPECT_STRING_REGEX);
			else
				type = ((*(args[cur_arg]) == 's') ? TCPCHK_EXPECT_HTTP_BODY : TCPCHK_EXPECT_HTTP_BODY_REGEX);

			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a <pattern> as argument", args[cur_arg]);
				goto error;
			}
			cur_arg++;
			pattern = args[cur_arg];
		}
		else if (strcmp(args[cur_arg], "binary") == 0 || strcmp(args[cur_arg], "rbinary") == 0) {
			if (proto == TCPCHK_RULES_HTTP_CHK)
				goto bad_http_kw;
			if (type != TCPCHK_EXPECT_UNDEF) {
				memprintf(errmsg, "only on pattern expected");
				goto error;
			}
			type = ((*(args[cur_arg]) == 'b') ?  TCPCHK_EXPECT_BINARY : TCPCHK_EXPECT_BINARY_REGEX);

			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a <pattern> as argument", args[cur_arg]);
				goto error;
			}
			cur_arg++;
			pattern = args[cur_arg];
		}
		else if (strcmp(args[cur_arg], "string-lf") == 0 || strcmp(args[cur_arg], "binary-lf") == 0) {
			if (type != TCPCHK_EXPECT_UNDEF) {
				memprintf(errmsg, "only on pattern expected");
				goto error;
			}
			if (proto != TCPCHK_RULES_HTTP_CHK)
				type = ((*(args[cur_arg]) == 's') ? TCPCHK_EXPECT_STRING_LF : TCPCHK_EXPECT_BINARY_LF);
			else {
				if (*(args[cur_arg]) != 's')
					goto bad_http_kw;
				type = TCPCHK_EXPECT_HTTP_BODY_LF;
			}

			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a <pattern> as argument", args[cur_arg]);
				goto error;
			}
			cur_arg++;
			pattern = args[cur_arg];
		}
		else if (strcmp(args[cur_arg], "status") == 0 || strcmp(args[cur_arg], "rstatus") == 0) {
			if (proto != TCPCHK_RULES_HTTP_CHK)
				goto bad_tcp_kw;
			if (type != TCPCHK_EXPECT_UNDEF) {
				memprintf(errmsg, "only on pattern expected");
				goto error;
			}
			type = ((*(args[cur_arg]) == 's') ? TCPCHK_EXPECT_HTTP_STATUS : TCPCHK_EXPECT_HTTP_STATUS_REGEX);

			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a <pattern> as argument", args[cur_arg]);
				goto error;
			}
			cur_arg++;
			pattern = args[cur_arg];
		}
		else if (strcmp(args[cur_arg], "custom") == 0) {
			if (in_pattern) {
				memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
				goto error;
			}
			if (type != TCPCHK_EXPECT_UNDEF) {
				memprintf(errmsg, "only on pattern expected");
				goto error;
			}
			type = TCPCHK_EXPECT_CUSTOM;
		}
		else if (strcmp(args[cur_arg], "hdr") == 0 || strcmp(args[cur_arg], "fhdr") == 0) {
			int orig_arg = cur_arg;

			if (proto != TCPCHK_RULES_HTTP_CHK)
				goto bad_tcp_kw;
			if (type != TCPCHK_EXPECT_UNDEF) {
				memprintf(errmsg, "only on pattern expected");
				goto error;
			}
			type = TCPCHK_EXPECT_HTTP_HEADER;

			if (strcmp(args[cur_arg], "fhdr") == 0)
				flags |= TCPCHK_EXPT_FL_HTTP_HVAL_FULL;

			/* Parse the name pattern, mandatory */
			if (!*(args[cur_arg+1]) || !*(args[cur_arg+2]) ||
			    (strcmp(args[cur_arg+1], "name") != 0 && strcmp(args[cur_arg+1], "name-lf") != 0)) {
				memprintf(errmsg, "'%s' expects at the name keyword as first argument followed by a pattern",
					  args[orig_arg]);
				goto error;
			}

			if (strcmp(args[cur_arg+1], "name-lf") == 0)
				flags |= TCPCHK_EXPT_FL_HTTP_HNAME_FMT;

			cur_arg += 2;
			if (strcmp(args[cur_arg], "-m") == 0) {
				if  (!*(args[cur_arg+1])) {
					memprintf(errmsg, "'%s' : '%s' expects at a matching pattern ('str', 'beg', 'end', 'sub' or 'reg')",
						  args[orig_arg], args[cur_arg]);
					goto error;
				}
				if (strcmp(args[cur_arg+1], "str") == 0)
					flags |= TCPCHK_EXPT_FL_HTTP_HNAME_STR;
				else if (strcmp(args[cur_arg+1], "beg") == 0)
					flags |= TCPCHK_EXPT_FL_HTTP_HNAME_BEG;
				else if (strcmp(args[cur_arg+1], "end") == 0)
					flags |= TCPCHK_EXPT_FL_HTTP_HNAME_END;
				else if (strcmp(args[cur_arg+1], "sub") == 0)
					flags |= TCPCHK_EXPT_FL_HTTP_HNAME_SUB;
				else if (strcmp(args[cur_arg+1], "reg") == 0) {
					if (flags & TCPCHK_EXPT_FL_HTTP_HNAME_FMT) {
						memprintf(errmsg, "'%s': log-format string is not supported with a regex matching method",
							  args[orig_arg]);
						goto error;
					}
					flags |= TCPCHK_EXPT_FL_HTTP_HNAME_REG;
				}
				else {
					memprintf(errmsg, "'%s' : '%s' only supports 'str', 'beg', 'end', 'sub' or 'reg' (got '%s')",
						  args[orig_arg], args[cur_arg], args[cur_arg+1]);
					goto error;
				}
				cur_arg += 2;
			}
			else
				flags |= TCPCHK_EXPT_FL_HTTP_HNAME_STR;
			npat = args[cur_arg];

			if (!*(args[cur_arg+1]) ||
			    (strcmp(args[cur_arg+1], "value") != 0 && strcmp(args[cur_arg+1], "value-lf") != 0)) {
				flags |= TCPCHK_EXPT_FL_HTTP_HVAL_NONE;
				goto next;
			}
			if (strcmp(args[cur_arg+1], "value-lf") == 0)
				flags |= TCPCHK_EXPT_FL_HTTP_HVAL_FMT;

			/* Parse the value pattern, optional */
			if (strcmp(args[cur_arg+2], "-m") == 0) {
				cur_arg += 2;
				if  (!*(args[cur_arg+1])) {
					memprintf(errmsg, "'%s' : '%s' expects at a matching pattern ('str', 'beg', 'end', 'sub' or 'reg')",
						  args[orig_arg], args[cur_arg]);
					goto error;
				}
				if (strcmp(args[cur_arg+1], "str") == 0)
					flags |= TCPCHK_EXPT_FL_HTTP_HVAL_STR;
				else if (strcmp(args[cur_arg+1], "beg") == 0)
					flags |= TCPCHK_EXPT_FL_HTTP_HVAL_BEG;
				else if (strcmp(args[cur_arg+1], "end") == 0)
					flags |= TCPCHK_EXPT_FL_HTTP_HVAL_END;
				else if (strcmp(args[cur_arg+1], "sub") == 0)
					flags |= TCPCHK_EXPT_FL_HTTP_HVAL_SUB;
				else if (strcmp(args[cur_arg+1], "reg") == 0) {
					if (flags & TCPCHK_EXPT_FL_HTTP_HVAL_FMT) {
						memprintf(errmsg, "'%s': log-format string is not supported with a regex matching method",
							  args[orig_arg]);
						goto error;
					}
					flags |= TCPCHK_EXPT_FL_HTTP_HVAL_REG;
				}
				else {
					memprintf(errmsg, "'%s' : '%s' only supports 'str', 'beg', 'end', 'sub' or 'reg' (got '%s')",
						  args[orig_arg], args[cur_arg], args[cur_arg+1]);
					goto error;
				}
			}
			else
				flags |= TCPCHK_EXPT_FL_HTTP_HVAL_STR;

			if (!*(args[cur_arg+2])) {
				memprintf(errmsg, "'%s' expect a pattern with the value keyword", args[orig_arg]);
				goto error;
			}
			vpat = args[cur_arg+2];
			cur_arg += 2;
		}
		else if (strcmp(args[cur_arg], "comment") == 0) {
			if (in_pattern) {
				memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
				goto error;
			}
			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a string as argument", args[cur_arg]);
				goto error;
			}
			cur_arg++;
			free(comment);
			comment = strdup(args[cur_arg]);
			if (!comment) {
				memprintf(errmsg, "out of memory");
				goto error;
			}
		}
		else if (strcmp(args[cur_arg], "on-success") == 0) {
			if (in_pattern) {
				memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
				goto error;
			}
			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a string as argument", args[cur_arg]);
				goto error;
			}
			cur_arg++;
			on_success_msg = args[cur_arg];
		}
		else if (strcmp(args[cur_arg], "on-error") == 0) {
			if (in_pattern) {
				memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
				goto error;
			}
			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a string as argument", args[cur_arg]);
				goto error;
			}
			cur_arg++;
			on_error_msg = args[cur_arg];
		}
		else if (strcmp(args[cur_arg], "ok-status") == 0) {
			if (in_pattern) {
				memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
				goto error;
			}
			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a string as argument", args[cur_arg]);
				goto error;
			}
			if (strcasecmp(args[cur_arg+1], "L7OK") == 0)
				ok_st = HCHK_STATUS_L7OKD;
			else if (strcasecmp(args[cur_arg+1], "L7OKC") == 0)
				ok_st = HCHK_STATUS_L7OKCD;
			else if (strcasecmp(args[cur_arg+1], "L6OK") == 0)
				ok_st = HCHK_STATUS_L6OK;
			else if (strcasecmp(args[cur_arg+1], "L4OK") == 0)
				ok_st = HCHK_STATUS_L4OK;
			else  {
				memprintf(errmsg, "'%s' only supports 'L4OK', 'L6OK', 'L7OK' or 'L7OKC' status (got '%s').",
					  args[cur_arg], args[cur_arg+1]);
				goto error;
			}
			cur_arg++;
		}
		else if (strcmp(args[cur_arg], "error-status") == 0) {
			if (in_pattern) {
				memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
				goto error;
			}
			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a string as argument", args[cur_arg]);
				goto error;
			}
			if (strcasecmp(args[cur_arg+1], "L7RSP") == 0)
				err_st = HCHK_STATUS_L7RSP;
			else if (strcasecmp(args[cur_arg+1], "L7STS") == 0)
				err_st = HCHK_STATUS_L7STS;
			else if (strcasecmp(args[cur_arg+1], "L7OKC") == 0)
				err_st = HCHK_STATUS_L7OKCD;
			else if (strcasecmp(args[cur_arg+1], "L6RSP") == 0)
				err_st = HCHK_STATUS_L6RSP;
			else if (strcasecmp(args[cur_arg+1], "L4CON") == 0)
				err_st = HCHK_STATUS_L4CON;
			else  {
				memprintf(errmsg, "'%s' only supports 'L4CON', 'L6RSP', 'L7RSP' or 'L7STS' status (got '%s').",
					  args[cur_arg], args[cur_arg+1]);
				goto error;
			}
			cur_arg++;
		}
		else if (strcmp(args[cur_arg], "status-code") == 0) {
			int idx = 0;

			if (in_pattern) {
				memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
				goto error;
			}
			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects an expression as argument", args[cur_arg]);
				goto error;
			}

			cur_arg++;
			release_sample_expr(status_expr);
			px->conf.args.ctx = ARGC_SRV;
			status_expr = sample_parse_expr((char *[]){args[cur_arg], NULL}, &idx,
							file, line, errmsg, &px->conf.args, NULL);
			if (!status_expr) {
				memprintf(errmsg, "error detected while parsing status-code expression : %s", *errmsg);
				goto error;
			}
			if (!(status_expr->fetch->val & SMP_VAL_BE_CHK_RUL)) {
				memprintf(errmsg, "error detected while parsing status-code expression : "
					  " fetch method '%s' extracts information from '%s', "
					  "none of which is available here.\n",
					  args[cur_arg], sample_src_names(status_expr->fetch->use));
					goto error;
			}
			px->http_needed |= !!(status_expr->fetch->use & SMP_USE_HTTP_ANY);
		}
		else if (strcmp(args[cur_arg], "tout-status") == 0) {
			if (in_pattern) {
				memprintf(errmsg, "[!] not supported with '%s'", args[cur_arg]);
				goto error;
			}
			if (!*(args[cur_arg+1])) {
				memprintf(errmsg, "'%s' expects a string as argument", args[cur_arg]);
				goto error;
			}
			if (strcasecmp(args[cur_arg+1], "L7TOUT") == 0)
				tout_st = HCHK_STATUS_L7TOUT;
			else if (strcasecmp(args[cur_arg+1], "L6TOUT") == 0)
				tout_st = HCHK_STATUS_L6TOUT;
			else if (strcasecmp(args[cur_arg+1], "L4TOUT") == 0)
				tout_st = HCHK_STATUS_L4TOUT;
			else  {
				memprintf(errmsg, "'%s' only supports 'L4TOUT', 'L6TOUT' or 'L7TOUT' status (got '%s').",
					  args[cur_arg], args[cur_arg+1]);
				goto error;
			}
			cur_arg++;
		}
		else {
			if (proto == TCPCHK_RULES_HTTP_CHK) {
			  bad_http_kw:
				memprintf(errmsg, "'only supports min-recv, [!]string', '[!]rstring', '[!]string-lf', '[!]status', "
					  "'[!]rstatus', [!]hdr, [!]fhdr or comment but got '%s' as argument.", args[cur_arg]);
			}
			else {
			  bad_tcp_kw:
				memprintf(errmsg, "'only supports min-recv, '[!]binary', '[!]string', '[!]rstring', '[!]string-lf'"
					  "'[!]rbinary', '[!]binary-lf' or comment but got '%s' as argument.", args[cur_arg]);
			}
			goto error;
		}
	  next:
		cur_arg++;
	}

	chk = calloc(1, sizeof(*chk));
	if (!chk) {
		memprintf(errmsg, "out of memory");
		goto error;
	}
	chk->action  = TCPCHK_ACT_EXPECT;
	LIST_INIT(&chk->expect.onerror_fmt);
	LIST_INIT(&chk->expect.onsuccess_fmt);
	chk->comment = comment; comment = NULL;
	chk->expect.type = type;
	chk->expect.min_recv = min_recv;
	chk->expect.flags = flags | (inverse ? TCPCHK_EXPT_FL_INV : 0);
	chk->expect.ok_status = ok_st;
	chk->expect.err_status = err_st;
	chk->expect.tout_status = tout_st;
	chk->expect.status_expr = status_expr; status_expr = NULL;

	if (on_success_msg) {
		px->conf.args.ctx = ARGC_SRV;
		if (!parse_logformat_string(on_success_msg, px, &chk->expect.onsuccess_fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
			memprintf(errmsg, "'%s' invalid log-format string (%s).\n", on_success_msg, *errmsg);
			goto error;
		}
	}
	if (on_error_msg) {
		px->conf.args.ctx = ARGC_SRV;
		if (!parse_logformat_string(on_error_msg, px, &chk->expect.onerror_fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
			memprintf(errmsg, "'%s' invalid log-format string (%s).\n", on_error_msg, *errmsg);
			goto error;
		}
	}

	switch (chk->expect.type) {
	case TCPCHK_EXPECT_HTTP_STATUS: {
		const char *p = pattern;
		unsigned int c1,c2;

		chk->expect.codes.codes = NULL;
		chk->expect.codes.num   = 0;
		while (1) {
			c1 = c2 = read_uint(&p, pattern + strlen(pattern));
			if (*p == '-') {
				p++;
				c2 = read_uint(&p, pattern + strlen(pattern));
			}
			if (c1 > c2) {
				memprintf(errmsg, "invalid range of status codes '%s'", pattern);
				goto error;
			}

			chk->expect.codes.num++;
			chk->expect.codes.codes = my_realloc2(chk->expect.codes.codes,
							      chk->expect.codes.num * sizeof(*chk->expect.codes.codes));
			if (!chk->expect.codes.codes) {
				memprintf(errmsg, "out of memory");
				goto error;
			}
			chk->expect.codes.codes[chk->expect.codes.num-1][0] = c1;
			chk->expect.codes.codes[chk->expect.codes.num-1][1] = c2;

			if (*p == '\0')
				break;
			if (*p != ',') {
				memprintf(errmsg, "invalid character '%c' in the list of status codes", *p);
				goto error;
			}
			p++;
		}
		break;
	}
	case TCPCHK_EXPECT_STRING:
	case TCPCHK_EXPECT_HTTP_BODY:
		chk->expect.data = ist(strdup(pattern));
		if (!isttest(chk->expect.data)) {
			memprintf(errmsg, "out of memory");
			goto error;
		}
		break;
	case TCPCHK_EXPECT_BINARY: {
		int len = chk->expect.data.len;

		if (parse_binary(pattern, &chk->expect.data.ptr, &len, errmsg) == 0) {
			memprintf(errmsg, "invalid binary string (%s)", *errmsg);
			goto error;
		}
		chk->expect.data.len = len;
		break;
	}
	case TCPCHK_EXPECT_STRING_REGEX:
	case TCPCHK_EXPECT_BINARY_REGEX:
	case TCPCHK_EXPECT_HTTP_STATUS_REGEX:
	case TCPCHK_EXPECT_HTTP_BODY_REGEX:
		chk->expect.regex = regex_comp(pattern, 1, 0, errmsg);
		if (!chk->expect.regex)
			goto error;
		break;

	case TCPCHK_EXPECT_STRING_LF:
	case TCPCHK_EXPECT_BINARY_LF:
	case TCPCHK_EXPECT_HTTP_BODY_LF:
		LIST_INIT(&chk->expect.fmt);
		px->conf.args.ctx = ARGC_SRV;
		if (!parse_logformat_string(pattern, px, &chk->expect.fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
			memprintf(errmsg, "'%s' invalid log-format string (%s).\n", pattern, *errmsg);
			goto error;
		}
		break;

	case TCPCHK_EXPECT_HTTP_HEADER:
		if (!npat) {
			memprintf(errmsg, "unexpected error, undefined header name pattern");
			goto error;
		}
		if (chk->expect.flags & TCPCHK_EXPT_FL_HTTP_HNAME_REG) {
			chk->expect.hdr.name_re = regex_comp(npat, 0, 0, errmsg);
			if (!chk->expect.hdr.name_re)
				goto error;
		}
		else if (chk->expect.flags & TCPCHK_EXPT_FL_HTTP_HNAME_FMT) {
			px->conf.args.ctx = ARGC_SRV;
			LIST_INIT(&chk->expect.hdr.name_fmt);
			if (!parse_logformat_string(npat, px, &chk->expect.hdr.name_fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
				memprintf(errmsg, "'%s' invalid log-format string (%s).\n", npat, *errmsg);
				goto error;
			}
		}
		else {
			chk->expect.hdr.name = ist(strdup(npat));
			if (!isttest(chk->expect.hdr.name)) {
				memprintf(errmsg, "out of memory");
				goto error;
			}
		}

		if (chk->expect.flags & TCPCHK_EXPT_FL_HTTP_HVAL_NONE) {
			chk->expect.hdr.value = IST_NULL;
			break;
		}

		if (!vpat) {
			memprintf(errmsg, "unexpected error, undefined header value pattern");
			goto error;
		}
		else if (chk->expect.flags & TCPCHK_EXPT_FL_HTTP_HVAL_REG) {
			chk->expect.hdr.value_re = regex_comp(vpat, 1, 0, errmsg);
			if (!chk->expect.hdr.value_re)
				goto error;
		}
		else if (chk->expect.flags & TCPCHK_EXPT_FL_HTTP_HVAL_FMT) {
			px->conf.args.ctx = ARGC_SRV;
			LIST_INIT(&chk->expect.hdr.value_fmt);
			if (!parse_logformat_string(vpat, px, &chk->expect.hdr.value_fmt, 0, SMP_VAL_BE_CHK_RUL, errmsg)) {
				memprintf(errmsg, "'%s' invalid log-format string (%s).\n", npat, *errmsg);
				goto error;
			}
		}
		else {
			chk->expect.hdr.value = ist(strdup(vpat));
			if (!isttest(chk->expect.hdr.value)) {
				memprintf(errmsg, "out of memory");
				goto error;
			}
		}

		break;
	case TCPCHK_EXPECT_CUSTOM:
		chk->expect.custom = NULL; /* Must be defined by the caller ! */
		break;
	case TCPCHK_EXPECT_UNDEF:
		memprintf(errmsg, "pattern not found");
		goto error;
	}

	/* All tcp-check expect points back to the first inverse expect rule in
	 * a chain of one or more expect rule, potentially itself.
	 */
	chk->expect.head = chk;
	list_for_each_entry_rev(prev_check, rules, list) {
		if (prev_check->action == TCPCHK_ACT_EXPECT) {
			if (prev_check->expect.flags & TCPCHK_EXPT_FL_INV)
				chk->expect.head = prev_check;
			continue;
		}
		if (prev_check->action != TCPCHK_ACT_COMMENT && prev_check->action != TCPCHK_ACT_ACTION_KW)
			break;
	}
	return chk;

  error:
	free_tcpcheck(chk, 0);
	free(comment);
	release_sample_expr(status_expr);
	return NULL;
}

/* Overwrites fields of the old http send rule with those of the new one. When
 * replaced, old values are freed and replaced by the new ones. New values are
 * not copied but transferred. At the end <new> should be empty and can be
 * safely released. This function never fails.
 */
void tcpcheck_overwrite_send_http_rule(struct tcpcheck_rule *old, struct tcpcheck_rule *new)
{
	struct logformat_node *lf, *lfb;
	struct tcpcheck_http_hdr *hdr, *bhdr;


	if (new->send.http.meth.str.area) {
		free(old->send.http.meth.str.area);
		old->send.http.meth.meth = new->send.http.meth.meth;
		old->send.http.meth.str.area = new->send.http.meth.str.area;
		old->send.http.meth.str.data = new->send.http.meth.str.data;
		new->send.http.meth.str = BUF_NULL;
	}

	if (!(new->send.http.flags & TCPCHK_SND_HTTP_FL_URI_FMT) && isttest(new->send.http.uri)) {
		if (!(old->send.http.flags & TCPCHK_SND_HTTP_FL_URI_FMT))
			istfree(&old->send.http.uri);
		else
			free_tcpcheck_fmt(&old->send.http.uri_fmt);
		old->send.http.flags &= ~TCPCHK_SND_HTTP_FL_URI_FMT;
		old->send.http.uri = new->send.http.uri;
		new->send.http.uri = IST_NULL;
	}
	else if ((new->send.http.flags & TCPCHK_SND_HTTP_FL_URI_FMT) && !LIST_ISEMPTY(&new->send.http.uri_fmt)) {
		if (!(old->send.http.flags & TCPCHK_SND_HTTP_FL_URI_FMT))
			istfree(&old->send.http.uri);
		else
			free_tcpcheck_fmt(&old->send.http.uri_fmt);
		old->send.http.flags |= TCPCHK_SND_HTTP_FL_URI_FMT;
		LIST_INIT(&old->send.http.uri_fmt);
		list_for_each_entry_safe(lf, lfb, &new->send.http.uri_fmt, list) {
			LIST_DELETE(&lf->list);
			LIST_APPEND(&old->send.http.uri_fmt, &lf->list);
		}
	}

	if (isttest(new->send.http.vsn)) {
		istfree(&old->send.http.vsn);
		old->send.http.vsn = new->send.http.vsn;
		new->send.http.vsn = IST_NULL;
	}

	if (!LIST_ISEMPTY(&new->send.http.hdrs)) {
		free_tcpcheck_http_hdrs(&old->send.http.hdrs);
		list_for_each_entry_safe(hdr, bhdr, &new->send.http.hdrs, list) {
			LIST_DELETE(&hdr->list);
			LIST_APPEND(&old->send.http.hdrs, &hdr->list);
		}
	}

	if (!(new->send.http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT) && isttest(new->send.http.body)) {
		if (!(old->send.http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT))
			istfree(&old->send.http.body);
		else
			free_tcpcheck_fmt(&old->send.http.body_fmt);
		old->send.http.flags &= ~TCPCHK_SND_HTTP_FL_BODY_FMT;
		old->send.http.body = new->send.http.body;
		new->send.http.body = IST_NULL;
	}
	else if ((new->send.http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT) && !LIST_ISEMPTY(&new->send.http.body_fmt)) {
		if (!(old->send.http.flags & TCPCHK_SND_HTTP_FL_BODY_FMT))
			istfree(&old->send.http.body);
		else
			free_tcpcheck_fmt(&old->send.http.body_fmt);
		old->send.http.flags |= TCPCHK_SND_HTTP_FL_BODY_FMT;
		LIST_INIT(&old->send.http.body_fmt);
		list_for_each_entry_safe(lf, lfb, &new->send.http.body_fmt, list) {
			LIST_DELETE(&lf->list);
			LIST_APPEND(&old->send.http.body_fmt, &lf->list);
		}
	}
}

/* Internal function used to add an http-check rule in a list during the config
 * parsing step. Depending on its type, and the previously inserted rules, a
 * specific action may be performed or an error may be reported. This functions
 * returns 1 on success and 0 on error and <errmsg> is filled with the error
 * message.
 */
int tcpcheck_add_http_rule(struct tcpcheck_rule *chk, struct tcpcheck_rules *rules, char **errmsg)
{
	struct tcpcheck_rule *r;

	/* the implicit send rule coming from an "option httpchk" line must be
	 * merged with the first explici http-check send rule, if
	 * any. Depending on the declaration order some tests are required.
	 *
	 * Some tests are also required for other kinds of http-check rules to be
	 * sure the ruleset remains valid.
	 */

	if (chk->action == TCPCHK_ACT_SEND && (chk->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT)) {
		/* Tries to add an implicit http-check send rule from an "option httpchk" line.
		 * First, the first rule is retrieved, skipping the first CONNECT, if any, and
		 * following tests are performed :
		 *
		 *  1- If there is no such rule or if it is not a send rule, the implicit send
		 *     rule is pushed in front of the ruleset
		 *
		 *  2- If it is another implicit send rule, it is replaced with the new one.
		 *
		 *  3- Otherwise, it means it is an explicit send rule. In this case we merge
		 *     both, overwriting the old send rule (the explicit one) with info of the
		 *     new send rule (the implicit one).
		 */
		r = get_first_tcpcheck_rule(rules);
		if (r && r->action == TCPCHK_ACT_CONNECT)
			r = get_next_tcpcheck_rule(rules, r);
		if (!r || r->action != TCPCHK_ACT_SEND)
			LIST_INSERT(rules->list, &chk->list);
		else if (r->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT) {
			LIST_DELETE(&r->list);
			free_tcpcheck(r, 0);
			LIST_INSERT(rules->list, &chk->list);
		}
		else {
			tcpcheck_overwrite_send_http_rule(r, chk);
			free_tcpcheck(chk, 0);
		}
	}
	else {
		/* Tries to add an explicit http-check rule. First of all we check the typefo the
		 * last inserted rule to be sure it is valid. Then for send rule, we try to merge it
		 * with an existing implicit send rule, if any. At the end, if there is no error,
		 * the rule is appended to the list.
		 */

		r = get_last_tcpcheck_rule(rules);
		if (!r || (r->action == TCPCHK_ACT_SEND && (r->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT)))
			/* no error */;
		else if (r->action != TCPCHK_ACT_CONNECT && chk->action == TCPCHK_ACT_SEND) {
			memprintf(errmsg, "unable to add http-check send rule at step %d (missing connect rule).",
				  chk->index+1);
			return 0;
		}
		else if (r->action != TCPCHK_ACT_SEND && r->action != TCPCHK_ACT_EXPECT && chk->action == TCPCHK_ACT_EXPECT) {
			memprintf(errmsg, "unable to add http-check expect rule at step %d (missing send rule).",
				  chk->index+1);
			return 0;
		}
		else if (r->action != TCPCHK_ACT_EXPECT && chk->action == TCPCHK_ACT_CONNECT) {
			memprintf(errmsg, "unable to add http-check connect rule at step %d (missing expect rule).",
				  chk->index+1);
			return 0;
		}

		if (chk->action == TCPCHK_ACT_SEND) {
			r = get_first_tcpcheck_rule(rules);
			if (r && r->action == TCPCHK_ACT_SEND && (r->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT)) {
				tcpcheck_overwrite_send_http_rule(r, chk);
				free_tcpcheck(chk, 0);
				LIST_DELETE(&r->list);
				r->send.http.flags &= ~TCPCHK_SND_HTTP_FROM_OPT;
				chk = r;
			}
		}
		LIST_APPEND(rules->list, &chk->list);
	}
	return 1;
}

/* Check tcp-check health-check configuration for the proxy <px>. */
static int check_proxy_tcpcheck(struct proxy *px)
{
	struct tcpcheck_rule *chk, *back;
	char *comment = NULL, *errmsg = NULL;
	enum tcpcheck_rule_type prev_action = TCPCHK_ACT_COMMENT;
	int ret = ERR_NONE;

	if (!(px->cap & PR_CAP_BE) || (px->options2 & PR_O2_CHK_ANY) != PR_O2_TCPCHK_CHK) {
		deinit_proxy_tcpcheck(px);
		goto out;
	}

	ha_free(&px->check_command);
	ha_free(&px->check_path);

	if (!px->tcpcheck_rules.list) {
		ha_alert("proxy '%s' : tcp-check configured but no ruleset defined.\n", px->id);
		ret |= ERR_ALERT | ERR_FATAL;
		goto out;
	}

	/* HTTP ruleset only :  */
	if ((px->tcpcheck_rules.flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_HTTP_CHK) {
		struct tcpcheck_rule *next;

		/* move remaining implicit send rule from "option httpchk" line to the right place.
		 * If such rule exists, it must be the first one. In this case, the rule is moved
		 * after the first connect rule, if any. Otherwise, nothing is done.
		 */
		chk = get_first_tcpcheck_rule(&px->tcpcheck_rules);
		if (chk && chk->action == TCPCHK_ACT_SEND && (chk->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT)) {
			next = get_next_tcpcheck_rule(&px->tcpcheck_rules, chk);
			if (next && next->action == TCPCHK_ACT_CONNECT) {
				LIST_DELETE(&chk->list);
				LIST_INSERT(&next->list, &chk->list);
				chk->index = next->index + 1;
			}
		}

		/* add implicit expect rule if the last one is a send. It is inherited from previous
		 * versions where the http expect rule was optional. Now it is possible to chained
		 * send/expect rules but the last expect may still be implicit.
		 */
		chk = get_last_tcpcheck_rule(&px->tcpcheck_rules);
		if (chk && chk->action == TCPCHK_ACT_SEND) {
			next = parse_tcpcheck_expect((char *[]){"http-check", "expect", "status", "200-399", ""},
						     1, px, px->tcpcheck_rules.list, TCPCHK_RULES_HTTP_CHK,
						     px->conf.file, px->conf.line, &errmsg);
			if (!next) {
				ha_alert("proxy '%s': unable to add implicit http-check expect rule "
					 "(%s).\n", px->id, errmsg);
				free(errmsg);
				ret |= ERR_ALERT | ERR_FATAL;
				goto out;
			}
			LIST_APPEND(px->tcpcheck_rules.list, &next->list);
			next->index = chk->index + 1;
		}
	}

	/* For all ruleset: */

	/* If there is no connect rule preceding all send / expect rules, an
	 * implicit one is inserted before all others.
	 */
	chk = get_first_tcpcheck_rule(&px->tcpcheck_rules);
	if (!chk || chk->action != TCPCHK_ACT_CONNECT) {
		chk = calloc(1, sizeof(*chk));
		if (!chk) {
			ha_alert("proxy '%s': unable to add implicit tcp-check connect rule "
				 "(out of memory).\n", px->id);
			ret |= ERR_ALERT | ERR_FATAL;
			goto out;
		}
		chk->action = TCPCHK_ACT_CONNECT;
		chk->connect.options = (TCPCHK_OPT_DEFAULT_CONNECT|TCPCHK_OPT_IMPLICIT);
		LIST_INSERT(px->tcpcheck_rules.list, &chk->list);
	}

	/* Remove all comment rules. To do so, when a such rule is found, the
	 * comment is assigned to the following rule(s).
	 */
	list_for_each_entry_safe(chk, back, px->tcpcheck_rules.list, list) {
		struct tcpcheck_rule *next;

		if (chk->action != prev_action && prev_action != TCPCHK_ACT_COMMENT)
			ha_free(&comment);

		prev_action = chk->action;
		switch (chk->action) {
		case TCPCHK_ACT_COMMENT:
			free(comment);
			comment = chk->comment;
			LIST_DELETE(&chk->list);
			free(chk);
			break;
		case TCPCHK_ACT_CONNECT:
			if (!chk->comment && comment)
				chk->comment = strdup(comment);
			next = get_next_tcpcheck_rule(&px->tcpcheck_rules, chk);
			if (next && next->action == TCPCHK_ACT_SEND)
				chk->connect.options |= TCPCHK_OPT_HAS_DATA;
			__fallthrough;
		case TCPCHK_ACT_ACTION_KW:
			ha_free(&comment);
			break;
		case TCPCHK_ACT_SEND:
		case TCPCHK_ACT_EXPECT:
			if (!chk->comment && comment)
				chk->comment = strdup(comment);
			break;
		}
	}
	ha_free(&comment);

  out:
	return ret;
}

void deinit_proxy_tcpcheck(struct proxy *px)
{
	free_tcpcheck_vars(&px->tcpcheck_rules.preset_vars);
	px->tcpcheck_rules.flags = 0;
	px->tcpcheck_rules.list  = NULL;
}

static void deinit_tcpchecks()
{
	struct tcpcheck_ruleset *rs;
	struct tcpcheck_rule *r, *rb;
	struct ebpt_node *node, *next;

	node = ebpt_first(&shared_tcpchecks);
	while (node) {
		next = ebpt_next(node);
		ebpt_delete(node);
		free(node->key);
		rs = container_of(node, typeof(*rs), node);
		list_for_each_entry_safe(r, rb, &rs->rules, list) {
			LIST_DELETE(&r->list);
			free_tcpcheck(r, 0);
		}
		free(rs);
		node = next;
	}
}

int add_tcpcheck_expect_str(struct tcpcheck_rules *rules, const char *str)
{
	struct tcpcheck_rule *tcpcheck, *prev_check;
	struct tcpcheck_expect *expect;

	if ((tcpcheck = pool_zalloc(pool_head_tcpcheck_rule)) == NULL)
		return 0;
	tcpcheck->action = TCPCHK_ACT_EXPECT;

	expect = &tcpcheck->expect;
	expect->type = TCPCHK_EXPECT_STRING;
	LIST_INIT(&expect->onerror_fmt);
	LIST_INIT(&expect->onsuccess_fmt);
	expect->ok_status = HCHK_STATUS_L7OKD;
	expect->err_status = HCHK_STATUS_L7RSP;
	expect->tout_status = HCHK_STATUS_L7TOUT;
	expect->data = ist(strdup(str));
	if (!isttest(expect->data)) {
		pool_free(pool_head_tcpcheck_rule, tcpcheck);
		return 0;
	}

	/* All tcp-check expect points back to the first inverse expect rule
	 * in a chain of one or more expect rule, potentially itself.
	 */
	tcpcheck->expect.head = tcpcheck;
	list_for_each_entry_rev(prev_check, rules->list, list) {
		if (prev_check->action == TCPCHK_ACT_EXPECT) {
			if (prev_check->expect.flags & TCPCHK_EXPT_FL_INV)
				tcpcheck->expect.head = prev_check;
			continue;
		}
		if (prev_check->action != TCPCHK_ACT_COMMENT && prev_check->action != TCPCHK_ACT_ACTION_KW)
			break;
	}
	LIST_APPEND(rules->list, &tcpcheck->list);
	return 1;
}

int add_tcpcheck_send_strs(struct tcpcheck_rules *rules, const char * const *strs)
{
	struct tcpcheck_rule *tcpcheck;
	struct tcpcheck_send *send;
	const char *in;
	char *dst;
	int i;

	if ((tcpcheck = pool_zalloc(pool_head_tcpcheck_rule)) == NULL)
		return 0;
	tcpcheck->action       = TCPCHK_ACT_SEND;

	send = &tcpcheck->send;
	send->type = TCPCHK_SEND_STRING;

	for (i = 0; strs[i]; i++)
		send->data.len += strlen(strs[i]);

	send->data.ptr = malloc(istlen(send->data) + 1);
	if (!isttest(send->data)) {
		pool_free(pool_head_tcpcheck_rule, tcpcheck);
		return 0;
	}

	dst = istptr(send->data);
	for (i = 0; strs[i]; i++)
		for (in = strs[i]; (*dst = *in++); dst++);
	*dst = 0;

	LIST_APPEND(rules->list, &tcpcheck->list);
	return 1;
}

/* Parses the "tcp-check" proxy keyword */
static int proxy_parse_tcpcheck(char **args, int section, struct proxy *curpx,
				const struct proxy *defpx, const char *file, int line,
				char **errmsg)
{
	struct tcpcheck_ruleset *rs = NULL;
	struct tcpcheck_rule *chk = NULL;
	int index, cur_arg, ret = 0;

	if (warnifnotcap(curpx, PR_CAP_BE, file, line, args[0], NULL))
		ret = 1;

	/* Deduce the ruleset name from the proxy info */
	chunk_printf(&trash, "*tcp-check-%s_%s-%d",
		     ((curpx == defpx) ? "defaults" : curpx->id),
		     curpx->conf.file, curpx->conf.line);

	rs = find_tcpcheck_ruleset(b_orig(&trash));
	if (rs == NULL) {
		rs = create_tcpcheck_ruleset(b_orig(&trash));
		if (rs == NULL) {
			memprintf(errmsg, "out of memory.\n");
			goto error;
		}
	}

	index = 0;
	if (!LIST_ISEMPTY(&rs->rules)) {
		chk = LIST_PREV(&rs->rules, typeof(chk), list);
		index = chk->index + 1;
		chk = NULL;
	}

	cur_arg = 1;
	if (strcmp(args[cur_arg], "connect") == 0)
		chk = parse_tcpcheck_connect(args, cur_arg, curpx, &rs->rules, file, line, errmsg);
	else if (strcmp(args[cur_arg], "send") == 0 || strcmp(args[cur_arg], "send-binary") == 0 ||
		 strcmp(args[cur_arg], "send-lf") == 0 || strcmp(args[cur_arg], "send-binary-lf") == 0)
		chk = parse_tcpcheck_send(args, cur_arg, curpx, &rs->rules, file, line, errmsg);
	else if (strcmp(args[cur_arg], "expect") == 0)
		chk = parse_tcpcheck_expect(args, cur_arg, curpx, &rs->rules, 0, file, line, errmsg);
	else if (strcmp(args[cur_arg], "comment") == 0)
		chk = parse_tcpcheck_comment(args, cur_arg, curpx, &rs->rules, file, line, errmsg);
	else {
		struct action_kw *kw = action_kw_tcp_check_lookup(args[cur_arg]);

		if (!kw) {
			action_kw_tcp_check_build_list(&trash);
			memprintf(errmsg, "'%s' only supports 'comment', 'connect', 'send', 'send-binary', 'expect'"
				  "%s%s. but got '%s'",
				  args[0], (*trash.area ? ", " : ""), trash.area, args[1]);
			goto error;
		}
		chk = parse_tcpcheck_action(args, cur_arg, curpx, &rs->rules, kw, file, line, errmsg);
	}

	if (!chk) {
		memprintf(errmsg, "'%s %s' : %s.", args[0], args[1], *errmsg);
		goto error;
	}
	ret = (ret || (*errmsg != NULL)); /* Handle warning */

	/* No error: add the tcp-check rule in the list */
	chk->index = index;
	LIST_APPEND(&rs->rules, &chk->list);

	if ((curpx->options2 & PR_O2_CHK_ANY) == PR_O2_TCPCHK_CHK &&
	    (curpx->tcpcheck_rules.flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_TCP_CHK) {
		/* Use this ruleset if the proxy already has tcp-check enabled */
		curpx->tcpcheck_rules.list = &rs->rules;
		curpx->tcpcheck_rules.flags &= ~TCPCHK_RULES_UNUSED_TCP_RS;
	}
	else {
		/* mark this ruleset as unused for now */
		curpx->tcpcheck_rules.flags |= TCPCHK_RULES_UNUSED_TCP_RS;
	}

	return ret;

  error:
	free_tcpcheck(chk, 0);
	free_tcpcheck_ruleset(rs);
	return -1;
}

/* Parses the "http-check" proxy keyword */
static int proxy_parse_httpcheck(char **args, int section, struct proxy *curpx,
				 const struct proxy *defpx, const char *file, int line,
				 char **errmsg)
{
	struct tcpcheck_ruleset *rs = NULL;
	struct tcpcheck_rule *chk = NULL;
	int index, cur_arg, ret = 0;

	if (warnifnotcap(curpx, PR_CAP_BE, file, line, args[0], NULL))
		ret = 1;

	cur_arg = 1;
	if (strcmp(args[cur_arg], "disable-on-404") == 0) {
		/* enable a graceful server shutdown on an HTTP 404 response */
		curpx->options |= PR_O_DISABLE404;
		if (too_many_args(1, args, errmsg, NULL))
			goto error;
		goto out;
	}
	else if (strcmp(args[cur_arg], "send-state") == 0) {
		/* enable emission of the apparent state of a server in HTTP checks */
		curpx->options2 |= PR_O2_CHK_SNDST;
		if (too_many_args(1, args, errmsg, NULL))
			goto error;
		goto out;
	}

	/* Deduce the ruleset name from the proxy info */
	chunk_printf(&trash, "*http-check-%s_%s-%d",
		     ((curpx == defpx) ? "defaults" : curpx->id),
		     curpx->conf.file, curpx->conf.line);

	rs = find_tcpcheck_ruleset(b_orig(&trash));
	if (rs == NULL) {
		rs = create_tcpcheck_ruleset(b_orig(&trash));
		if (rs == NULL) {
			memprintf(errmsg, "out of memory.\n");
			goto error;
		}
	}

	index = 0;
	if (!LIST_ISEMPTY(&rs->rules)) {
		chk = LIST_PREV(&rs->rules, typeof(chk), list);
		if (chk->action != TCPCHK_ACT_SEND || !(chk->send.http.flags & TCPCHK_SND_HTTP_FROM_OPT))
			index = chk->index + 1;
		chk = NULL;
	}

	if (strcmp(args[cur_arg], "connect") == 0)
		chk = parse_tcpcheck_connect(args, cur_arg, curpx, &rs->rules, file, line, errmsg);
	else if (strcmp(args[cur_arg], "send") == 0)
		chk = parse_tcpcheck_send_http(args, cur_arg, curpx, &rs->rules, file, line, errmsg);
	else if (strcmp(args[cur_arg], "expect") == 0)
		chk = parse_tcpcheck_expect(args, cur_arg, curpx, &rs->rules, TCPCHK_RULES_HTTP_CHK,
					    file, line, errmsg);
	else if (strcmp(args[cur_arg], "comment") == 0)
		chk = parse_tcpcheck_comment(args, cur_arg, curpx, &rs->rules, file, line, errmsg);
	else {
		struct action_kw *kw = action_kw_tcp_check_lookup(args[cur_arg]);

		if (!kw) {
			action_kw_tcp_check_build_list(&trash);
			memprintf(errmsg, "'%s' only supports 'disable-on-404', 'send-state', 'comment', 'connect',"
				  " 'send', 'expect'%s%s. but got '%s'",
				  args[0], (*trash.area ? ", " : ""), trash.area, args[1]);
			goto error;
		}
		chk = parse_tcpcheck_action(args, cur_arg, curpx, &rs->rules, kw, file, line, errmsg);
	}

	if (!chk) {
		memprintf(errmsg, "'%s %s' : %s.", args[0], args[1], *errmsg);
		goto error;
	}
	ret = (*errmsg != NULL); /* Handle warning */

	chk->index = index;
	if ((curpx->options2 & PR_O2_CHK_ANY) == PR_O2_TCPCHK_CHK &&
	    (curpx->tcpcheck_rules.flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_HTTP_CHK) {
		/* Use this ruleset if the proxy already has http-check enabled */
		curpx->tcpcheck_rules.list = &rs->rules;
		curpx->tcpcheck_rules.flags &= ~TCPCHK_RULES_UNUSED_HTTP_RS;
		if (!tcpcheck_add_http_rule(chk, &curpx->tcpcheck_rules, errmsg)) {
			memprintf(errmsg, "'%s %s' : %s.", args[0], args[1], *errmsg);
			curpx->tcpcheck_rules.list = NULL;
			goto error;
		}
	}
	else {
		/* mark this ruleset as unused for now */
		curpx->tcpcheck_rules.flags |= TCPCHK_RULES_UNUSED_HTTP_RS;
		LIST_APPEND(&rs->rules, &chk->list);
	}

  out:
	return ret;

  error:
	free_tcpcheck(chk, 0);
	free_tcpcheck_ruleset(rs);
	return -1;
}

/* Parses the "option redis-check" proxy keyword */
int proxy_parse_redis_check_opt(char **args, int cur_arg, struct proxy *curpx, const struct proxy *defpx,
				const char *file, int line)
{
	static char *redis_req = "*1\r\n$4\r\nPING\r\n";
	static char *redis_res = "+PONG\r\n";

	struct tcpcheck_ruleset *rs = NULL;
	struct tcpcheck_rules *rules = &curpx->tcpcheck_rules;
	struct tcpcheck_rule *chk;
	char *errmsg = NULL;
	int err_code = 0;

	if (warnifnotcap(curpx, PR_CAP_BE, file, line, args[cur_arg+1], NULL))
		err_code |= ERR_WARN;

	if (alertif_too_many_args_idx(0, 1, file, line, args, &err_code))
		goto out;

	curpx->options2 &= ~PR_O2_CHK_ANY;
	curpx->options2 |= PR_O2_TCPCHK_CHK;

	free_tcpcheck_vars(&rules->preset_vars);
	rules->list  = NULL;
	rules->flags = 0;

	rs = find_tcpcheck_ruleset("*redis-check");
	if (rs)
		goto ruleset_found;

	rs = create_tcpcheck_ruleset("*redis-check");
	if (rs == NULL) {
		ha_alert("parsing [%s:%d] : out of memory.\n", file, line);
		goto error;
	}

	chk = parse_tcpcheck_send((char *[]){"tcp-check", "send", redis_req, ""},
				  1, curpx, &rs->rules, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->index = 0;
	LIST_APPEND(&rs->rules, &chk->list);

	chk = parse_tcpcheck_expect((char *[]){"tcp-check", "expect", "string", redis_res,
				               "error-status", "L7STS",
				               "on-error", "%[res.payload(0,0),cut_crlf]",
				               "on-success", "Redis server is ok",
				               ""},
				    1, curpx, &rs->rules, TCPCHK_RULES_REDIS_CHK, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->index = 1;
	LIST_APPEND(&rs->rules, &chk->list);

  ruleset_found:
	rules->list = &rs->rules;
	rules->flags &= ~(TCPCHK_RULES_PROTO_CHK|TCPCHK_RULES_UNUSED_RS);
	rules->flags |= TCPCHK_RULES_REDIS_CHK;

  out:
	free(errmsg);
	return err_code;

  error:
	free_tcpcheck_ruleset(rs);
	err_code |= ERR_ALERT | ERR_FATAL;
	goto out;
}


/* Parses the "option ssl-hello-chk" proxy keyword */
int proxy_parse_ssl_hello_chk_opt(char **args, int cur_arg, struct proxy *curpx, const struct proxy *defpx,
				  const char *file, int line)
{
	/* This is the SSLv3 CLIENT HELLO packet used in conjunction with the
	 * ssl-hello-chk option to ensure that the remote server speaks SSL.
	 *
	 * Check RFC 2246 (TLSv1.0) sections A.3 and A.4 for details.
	 */
	static char sslv3_client_hello[] = {
		"16"                        /* ContentType         : 0x16 = Handshake          */
		"0300"                      /* ProtocolVersion     : 0x0300 = SSLv3            */
		"0079"                      /* ContentLength       : 0x79 bytes after this one */
		"01"                        /* HanshakeType        : 0x01 = CLIENT HELLO       */
		"000075"                    /* HandshakeLength     : 0x75 bytes after this one */
		"0300"                      /* Hello Version       : 0x0300 = v3               */
		"%[date(),htonl,hex]"       /* Unix GMT Time (s)   : filled with <now> (@0x0B) */
		"%[str(HAPROXYSSLCHK\nHAPROXYSSLCHK\n),hex]" /* Random   : must be exactly 28 bytes  */
		"00"                        /* Session ID length   : empty (no session ID)     */
		"004E"                      /* Cipher Suite Length : 78 bytes after this one   */
		"0001" "0002" "0003" "0004" /* 39 most common ciphers :  */
		"0005" "0006" "0007" "0008" /* 0x01...0x1B, 0x2F...0x3A  */
		"0009" "000A" "000B" "000C" /* This covers RSA/DH,       */
		"000D" "000E" "000F" "0010" /* various bit lengths,      */
		"0011" "0012" "0013" "0014" /* SHA1/MD5, DES/3DES/AES... */
		"0015" "0016" "0017" "0018"
		"0019" "001A" "001B" "002F"
		"0030" "0031" "0032" "0033"
		"0034" "0035" "0036" "0037"
		"0038" "0039" "003A"
		"01"                       /* Compression Length  : 0x01 = 1 byte for types   */
		"00"                       /* Compression Type    : 0x00 = NULL compression   */
	};

	struct tcpcheck_ruleset *rs = NULL;
	struct tcpcheck_rules *rules = &curpx->tcpcheck_rules;
	struct tcpcheck_rule *chk;
	char *errmsg = NULL;
	int err_code = 0;

	if (warnifnotcap(curpx, PR_CAP_BE, file, line, args[cur_arg+1], NULL))
		err_code |= ERR_WARN;

	if (alertif_too_many_args_idx(0, 1, file, line, args, &err_code))
		goto out;

	curpx->options2 &= ~PR_O2_CHK_ANY;
	curpx->options2 |= PR_O2_TCPCHK_CHK;

	free_tcpcheck_vars(&rules->preset_vars);
	rules->list  = NULL;
	rules->flags = 0;

	rs = find_tcpcheck_ruleset("*ssl-hello-check");
	if (rs)
		goto ruleset_found;

	rs = create_tcpcheck_ruleset("*ssl-hello-check");
	if (rs == NULL) {
		ha_alert("parsing [%s:%d] : out of memory.\n", file, line);
		goto error;
	}

	chk = parse_tcpcheck_send((char *[]){"tcp-check", "send-binary-lf", sslv3_client_hello, ""},
				  1, curpx, &rs->rules, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->index = 0;
	LIST_APPEND(&rs->rules, &chk->list);

	chk = parse_tcpcheck_expect((char *[]){"tcp-check", "expect", "rbinary", "^1[56]",
				                "min-recv", "5", "ok-status", "L6OK",
				                "error-status", "L6RSP", "tout-status", "L6TOUT",
				                ""},
		                    1, curpx, &rs->rules, TCPCHK_RULES_SSL3_CHK, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->index = 1;
	LIST_APPEND(&rs->rules, &chk->list);

  ruleset_found:
	rules->list = &rs->rules;
	rules->flags &= ~(TCPCHK_RULES_PROTO_CHK|TCPCHK_RULES_UNUSED_RS);
	rules->flags |= TCPCHK_RULES_SSL3_CHK;

  out:
	free(errmsg);
	return err_code;

  error:
	free_tcpcheck_ruleset(rs);
	err_code |= ERR_ALERT | ERR_FATAL;
	goto out;
}

/* Parses the "option smtpchk" proxy keyword */
int proxy_parse_smtpchk_opt(char **args, int cur_arg, struct proxy *curpx, const struct proxy *defpx,
			    const char *file, int line)
{
	static char *smtp_req = "%[var(check.smtp_cmd)]\r\n";

	struct tcpcheck_ruleset *rs = NULL;
	struct tcpcheck_rules *rules = &curpx->tcpcheck_rules;
	struct tcpcheck_rule *chk;
	struct tcpcheck_var *var = NULL;
	char *cmd = NULL, *errmsg = NULL;
	int err_code = 0;

	if (warnifnotcap(curpx, PR_CAP_BE, file, line, args[cur_arg+1], NULL))
		err_code |= ERR_WARN;

	if (alertif_too_many_args_idx(2, 1, file, line, args, &err_code))
		goto out;

	curpx->options2 &= ~PR_O2_CHK_ANY;
	curpx->options2 |= PR_O2_TCPCHK_CHK;

	free_tcpcheck_vars(&rules->preset_vars);
	rules->list  = NULL;
	rules->flags = 0;

	cur_arg += 2;
	if (*args[cur_arg] && *args[cur_arg+1] &&
	    (strcmp(args[cur_arg], "EHLO") == 0 || strcmp(args[cur_arg], "HELO") == 0)) {
		/* <EHLO|HELO> + space (1) + <host> + null byte (1) */
		size_t len = strlen(args[cur_arg]) + 1 + strlen(args[cur_arg+1]) + 1;
		cmd = calloc(1, len);
		if (cmd)
			snprintf(cmd, len, "%s %s", args[cur_arg], args[cur_arg+1]);
	}
	else {
		/* this just hits the default for now, but you could potentially expand it to allow for other stuff
		   though, it's unlikely you'd want to send anything other than an EHLO or HELO */
		cmd = strdup("HELO localhost");
	}

	var = create_tcpcheck_var(ist("check.smtp_cmd"));
	if (cmd == NULL || var == NULL) {
		ha_alert("parsing [%s:%d] : out of memory.\n", file, line);
		goto error;
	}
	var->data.type = SMP_T_STR;
	var->data.u.str.area = cmd;
	var->data.u.str.data = strlen(cmd);
	LIST_INIT(&var->list);
	LIST_APPEND(&rules->preset_vars, &var->list);
	cmd = NULL;
	var = NULL;

	rs = find_tcpcheck_ruleset("*smtp-check");
	if (rs)
		goto ruleset_found;

	rs = create_tcpcheck_ruleset("*smtp-check");
	if (rs == NULL) {
		ha_alert("parsing [%s:%d] : out of memory.\n", file, line);
		goto error;
	}

	chk = parse_tcpcheck_connect((char *[]){"tcp-check", "connect", "default", "linger", ""},
				     1, curpx, &rs->rules, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->index = 0;
	LIST_APPEND(&rs->rules, &chk->list);

	chk = parse_tcpcheck_expect((char *[]){"tcp-check", "expect", "rstring", "^[0-9]{3}[ \r]",
				               "min-recv", "4",
				               "error-status", "L7RSP",
				               "on-error", "%[res.payload(0,0),cut_crlf]",
				               ""},
		                    1, curpx, &rs->rules, TCPCHK_RULES_SMTP_CHK, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->index = 1;
	LIST_APPEND(&rs->rules, &chk->list);

	chk = parse_tcpcheck_expect((char *[]){"tcp-check", "expect", "rstring", "^2[0-9]{2}[ \r]",
				               "min-recv", "4",
				               "error-status", "L7STS",
				               "on-error", "%[res.payload(4,0),ltrim(' '),cut_crlf]",
				               "status-code", "res.payload(0,3)",
				               ""},
		                    1, curpx, &rs->rules, TCPCHK_RULES_SMTP_CHK, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->index = 2;
	LIST_APPEND(&rs->rules, &chk->list);

	chk = parse_tcpcheck_send((char *[]){"tcp-check", "send-lf", smtp_req, ""},
				  1, curpx, &rs->rules, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->index = 3;
	LIST_APPEND(&rs->rules, &chk->list);

	chk = parse_tcpcheck_expect((char *[]){"tcp-check", "expect", "rstring", "^(2[0-9]{2}-[^\r]*\r\n)*2[0-9]{2}[ \r]",
				               "error-status", "L7STS",
				               "on-error", "%[res.payload(4,0),ltrim(' '),cut_crlf]",
				               "on-success", "%[res.payload(4,0),ltrim(' '),cut_crlf]",
				               "status-code", "res.payload(0,3)",
				               ""},
		                    1, curpx, &rs->rules, TCPCHK_RULES_SMTP_CHK, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->index = 4;
	LIST_APPEND(&rs->rules, &chk->list);

        /* Send an SMTP QUIT to ensure clean disconnect (issue 1812), and expect a 2xx response code */

        chk = parse_tcpcheck_send((char *[]){"tcp-check", "send", "QUIT\r\n", ""},
                                  1, curpx, &rs->rules, file, line, &errmsg);
        if (!chk) {
                ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
                goto error;
        }
        chk->index = 5;
        LIST_APPEND(&rs->rules, &chk->list);

        chk = parse_tcpcheck_expect((char *[]){"tcp-check", "expect", "rstring", "^2[0-9]{2}[- \r]",
                                               "min-recv", "4",
                                               "error-status", "L7STS",
                                               "on-error", "%[res.payload(4,0),ltrim(' '),cut_crlf]",
                                               "on-success", "%[res.payload(4,0),ltrim(' '),cut_crlf]",
                                               "status-code", "res.payload(0,3)",
                                               ""},
                                    1, curpx, &rs->rules, TCPCHK_RULES_SMTP_CHK, file, line, &errmsg);
        if (!chk) {
                ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
                goto error;
        }
        chk->index = 6;
        LIST_APPEND(&rs->rules, &chk->list);

  ruleset_found:
	rules->list = &rs->rules;
	rules->flags &= ~(TCPCHK_RULES_PROTO_CHK|TCPCHK_RULES_UNUSED_RS);
	rules->flags |= TCPCHK_RULES_SMTP_CHK;

  out:
	free(errmsg);
	return err_code;

  error:
	free(cmd);
	free(var);
	free_tcpcheck_vars(&rules->preset_vars);
	free_tcpcheck_ruleset(rs);
	err_code |= ERR_ALERT | ERR_FATAL;
	goto out;
}

/* Parses the "option pgsql-check" proxy keyword */
int proxy_parse_pgsql_check_opt(char **args, int cur_arg, struct proxy *curpx, const struct proxy *defpx,
				const char *file, int line)
{
	static char pgsql_req[] = {
		"%[var(check.plen),htonl,hex]" /* The packet length*/
		"00030000"                     /* the version 3.0 */
		"7573657200"                   /* "user" key */
		"%[var(check.username),hex]00" /* the username */
		"00"
	};

	struct tcpcheck_ruleset *rs = NULL;
	struct tcpcheck_rules *rules = &curpx->tcpcheck_rules;
	struct tcpcheck_rule *chk;
	struct tcpcheck_var *var = NULL;
	char *user = NULL, *errmsg = NULL;
	size_t packetlen = 0;
	int err_code = 0;

	if (warnifnotcap(curpx, PR_CAP_BE, file, line, args[cur_arg+1], NULL))
		err_code |= ERR_WARN;

	if (alertif_too_many_args_idx(2, 1, file, line, args, &err_code))
		goto out;

	curpx->options2 &= ~PR_O2_CHK_ANY;
	curpx->options2 |= PR_O2_TCPCHK_CHK;

	free_tcpcheck_vars(&rules->preset_vars);
	rules->list  = NULL;
	rules->flags = 0;

	cur_arg += 2;
	if (!*args[cur_arg] || !*args[cur_arg+1]) {
		ha_alert("parsing [%s:%d] : '%s %s' expects 'user <username>' as argument.\n",
			 file, line, args[0], args[1]);
		goto error;
	}
	if (strcmp(args[cur_arg], "user") == 0) {
		packetlen = 15 + strlen(args[cur_arg+1]);
		user = strdup(args[cur_arg+1]);

		var = create_tcpcheck_var(ist("check.username"));
		if (user == NULL || var == NULL) {
			ha_alert("parsing [%s:%d] : out of memory.\n", file, line);
			goto error;
		}
		var->data.type = SMP_T_STR;
		var->data.u.str.area = user;
		var->data.u.str.data = strlen(user);
		LIST_INIT(&var->list);
		LIST_APPEND(&rules->preset_vars, &var->list);
		user = NULL;
		var = NULL;

		var = create_tcpcheck_var(ist("check.plen"));
		if (var == NULL) {
			ha_alert("parsing [%s:%d] : out of memory.\n", file, line);
			goto error;
		}
		var->data.type = SMP_T_SINT;
		var->data.u.sint = packetlen;
		LIST_INIT(&var->list);
		LIST_APPEND(&rules->preset_vars, &var->list);
		var = NULL;
	}
	else {
		ha_alert("parsing [%s:%d] : '%s %s' only supports optional values: 'user'.\n",
			 file, line, args[0], args[1]);
		goto error;
	}

	rs = find_tcpcheck_ruleset("*pgsql-check");
	if (rs)
		goto ruleset_found;

	rs = create_tcpcheck_ruleset("*pgsql-check");
	if (rs == NULL) {
		ha_alert("parsing [%s:%d] : out of memory.\n", file, line);
		goto error;
	}

	chk = parse_tcpcheck_connect((char *[]){"tcp-check", "connect", "default", "linger", ""},
				     1, curpx, &rs->rules, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->index = 0;
	LIST_APPEND(&rs->rules, &chk->list);

	chk = parse_tcpcheck_send((char *[]){"tcp-check", "send-binary-lf", pgsql_req, ""},
				  1, curpx, &rs->rules, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->index = 1;
	LIST_APPEND(&rs->rules, &chk->list);

	chk = parse_tcpcheck_expect((char *[]){"tcp-check", "expect", "!rstring", "^E",
				               "min-recv", "5",
				               "error-status", "L7RSP",
				               "on-error", "%[res.payload(6,0)]",
				               ""},
		                    1, curpx, &rs->rules, TCPCHK_RULES_PGSQL_CHK, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->index = 2;
	LIST_APPEND(&rs->rules, &chk->list);

	chk = parse_tcpcheck_expect((char *[]){"tcp-check", "expect", "rbinary", "^52000000[A-Z0-9]{2}000000(00|02|03|04|05|06|07|09|0A)",
				               "min-recv", "9",
				               "error-status", "L7STS",
				               "on-success", "PostgreSQL server is ok",
				               "on-error",   "PostgreSQL unknown error",
				               ""},
		                    1, curpx, &rs->rules, TCPCHK_RULES_PGSQL_CHK, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->index = 3;
	LIST_APPEND(&rs->rules, &chk->list);

  ruleset_found:
	rules->list = &rs->rules;
	rules->flags &= ~(TCPCHK_RULES_PROTO_CHK|TCPCHK_RULES_UNUSED_RS);
	rules->flags |= TCPCHK_RULES_PGSQL_CHK;

  out:
	free(errmsg);
	return err_code;

  error:
	free(user);
	free(var);
	free_tcpcheck_vars(&rules->preset_vars);
	free_tcpcheck_ruleset(rs);
	err_code |= ERR_ALERT | ERR_FATAL;
	goto out;
}


/* Parses the "option mysql-check" proxy keyword */
int proxy_parse_mysql_check_opt(char **args, int cur_arg, struct proxy *curpx, const struct proxy *defpx,
				const char *file, int line)
{
	/* This is an example of a MySQL >=4.0 client Authentication packet kindly provided by Cyril Bonte.
	 * const char mysql40_client_auth_pkt[] = {
	 * 	"\x0e\x00\x00"	// packet length
	 * 	"\x01"		// packet number
	 * 	"\x00\x00"	// client capabilities
	 * 	"\x00\x00\x01"	// max packet
	 * 	"haproxy\x00"	// username (null terminated string)
	 * 	"\x00"		// filler (always 0x00)
	 * 	"\x01\x00\x00"	// packet length
	 * 	"\x00"		// packet number
	 * 	"\x01"		// COM_QUIT command
	 * };
	 */
	static char mysql40_rsname[] = "*mysql40-check";
	static char mysql40_req[] = {
		"%[var(check.header),hex]"     /* 3 bytes for the packet length and 1 byte for the sequence ID */
		"0080"                         /* client capabilities */
		"000001"                       /* max packet */
		"%[var(check.username),hex]00" /* the username */
		"00"                           /* filler (always 0x00) */
		"010000"                       /* packet length*/
		"00"                           /* sequence ID */
		"01"                           /* COM_QUIT command */
	};

	/* This is an example of a MySQL >=4.1  client Authentication packet provided by Nenad Merdanovic.
	 * const char mysql41_client_auth_pkt[] = {
	 * 	"\x0e\x00\x00\"		// packet length
	 * 	"\x01"			// packet number
	 * 	"\x00\x00\x00\x00"	// client capabilities
	 * 	"\x00\x00\x00\x01"	// max packet
	 *	"\x21"			// character set (UTF-8)
	 *	char[23]		// All zeroes
	 * 	"haproxy\x00"		// username (null terminated string)
	 * 	"\x00"			// filler (always 0x00)
	 * 	"\x01\x00\x00"		// packet length
	 * 	"\x00"			// packet number
	 * 	"\x01"			// COM_QUIT command
	 * };
	 */
	static char mysql41_rsname[] = "*mysql41-check";
	static char mysql41_req[] = {
		"%[var(check.header),hex]"     /* 3 bytes for the packet length and 1 byte for the sequence ID */
		"00820000"                     /* client capabilities */
		"00800001"                     /* max packet */
		"21"                           /* character set (UTF-8) */
		"000000000000000000000000"     /* 23 bytes, al zeroes */
		"0000000000000000000000"
		"%[var(check.username),hex]00" /* the username */
		"00"                           /* filler (always 0x00) */
		"010000"                       /* packet length*/
		"00"                           /* sequence ID */
		"01"                           /* COM_QUIT command */
	};

	struct tcpcheck_ruleset *rs = NULL;
	struct tcpcheck_rules *rules = &curpx->tcpcheck_rules;
	struct tcpcheck_rule *chk;
	struct tcpcheck_var *var = NULL;
	char *mysql_rsname = "*mysql-check";
	char *mysql_req = NULL, *hdr = NULL, *user = NULL, *errmsg = NULL;
	int index = 0, err_code = 0;

	if (warnifnotcap(curpx, PR_CAP_BE, file, line, args[cur_arg+1], NULL))
		err_code |= ERR_WARN;

	if (alertif_too_many_args_idx(3, 1, file, line, args, &err_code))
		goto out;

	curpx->options2 &= ~PR_O2_CHK_ANY;
	curpx->options2 |= PR_O2_TCPCHK_CHK;

	free_tcpcheck_vars(&rules->preset_vars);
	rules->list  = NULL;
	rules->flags = 0;

	cur_arg += 2;
	if (*args[cur_arg]) {
		int packetlen, userlen;

		if (strcmp(args[cur_arg], "user") != 0) {
			ha_alert("parsing [%s:%d] : '%s %s' only supports optional values: 'user' (got '%s').\n",
				 file, line, args[0], args[1], args[cur_arg]);
			goto error;
		}

		if (*(args[cur_arg+1]) == 0) {
			ha_alert("parsing [%s:%d] : '%s %s %s' expects <username> as argument.\n",
				 file, line, args[0], args[1], args[cur_arg]);
			goto error;
		}

		hdr     = calloc(4, sizeof(*hdr));
		user    = strdup(args[cur_arg+1]);
		userlen = strlen(args[cur_arg+1]);

		if (hdr == NULL || user == NULL) {
			ha_alert("parsing [%s:%d] : out of memory.\n", file, line);
			goto error;
		}

		if (!*args[cur_arg+2] || strcmp(args[cur_arg+2], "post-41") == 0) {
			packetlen = userlen + 7 + 27;
			mysql_req = mysql41_req;
			mysql_rsname  = mysql41_rsname;
		}
		else if (strcmp(args[cur_arg+2], "pre-41") == 0) {
			packetlen = userlen + 7;
			mysql_req = mysql40_req;
			mysql_rsname  = mysql40_rsname;
		}
		else  {
			ha_alert("parsing [%s:%d] : keyword '%s' only supports 'post-41' and 'pre-41' (got '%s').\n",
				 file, line, args[cur_arg], args[cur_arg+2]);
			goto error;
		}

		hdr[0] = (unsigned char)(packetlen & 0xff);
		hdr[1] = (unsigned char)((packetlen >> 8) & 0xff);
		hdr[2] = (unsigned char)((packetlen >> 16) & 0xff);
		hdr[3] = 1;

		var = create_tcpcheck_var(ist("check.header"));
		if (var == NULL) {
			ha_alert("parsing [%s:%d] : out of memory.\n", file, line);
			goto error;
		}
		var->data.type = SMP_T_STR;
		var->data.u.str.area = hdr;
		var->data.u.str.data = 4;
		LIST_INIT(&var->list);
		LIST_APPEND(&rules->preset_vars, &var->list);
		hdr = NULL;
		var = NULL;

		var = create_tcpcheck_var(ist("check.username"));
		if (var == NULL) {
			ha_alert("parsing [%s:%d] : out of memory.\n", file, line);
			goto error;
		}
		var->data.type = SMP_T_STR;
		var->data.u.str.area = user;
		var->data.u.str.data = strlen(user);
		LIST_INIT(&var->list);
		LIST_APPEND(&rules->preset_vars, &var->list);
		user = NULL;
		var = NULL;
	}

	rs = find_tcpcheck_ruleset(mysql_rsname);
	if (rs)
		goto ruleset_found;

	rs = create_tcpcheck_ruleset(mysql_rsname);
	if (rs == NULL) {
		ha_alert("parsing [%s:%d] : out of memory.\n", file, line);
		goto error;
	}

	chk = parse_tcpcheck_connect((char *[]){"tcp-check", "connect", "default", "linger", ""},
				     1, curpx, &rs->rules, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->index = index++;
	LIST_APPEND(&rs->rules, &chk->list);

	if (mysql_req) {
		chk = parse_tcpcheck_send((char *[]){"tcp-check", "send-binary-lf", mysql_req, ""},
					  1, curpx, &rs->rules, file, line, &errmsg);
		if (!chk) {
			ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
			goto error;
		}
		chk->index = index++;
		LIST_APPEND(&rs->rules, &chk->list);
	}

	chk = parse_tcpcheck_expect((char *[]){"tcp-check", "expect", "custom", ""},
		                    1, curpx, &rs->rules, TCPCHK_RULES_MYSQL_CHK, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->expect.custom = tcpcheck_mysql_expect_iniths;
	chk->index = index++;
	LIST_APPEND(&rs->rules, &chk->list);

	if (mysql_req) {
		chk = parse_tcpcheck_expect((char *[]){"tcp-check", "expect", "custom", ""},
					    1, curpx, &rs->rules, TCPCHK_RULES_MYSQL_CHK, file, line, &errmsg);
		if (!chk) {
			ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
			goto error;
		}
		chk->expect.custom = tcpcheck_mysql_expect_ok;
		chk->index = index++;
		LIST_APPEND(&rs->rules, &chk->list);
	}

  ruleset_found:
	rules->list = &rs->rules;
	rules->flags &= ~(TCPCHK_RULES_PROTO_CHK|TCPCHK_RULES_UNUSED_RS);
	rules->flags |= TCPCHK_RULES_MYSQL_CHK;

  out:
	free(errmsg);
	return err_code;

  error:
	free(hdr);
	free(user);
	free(var);
	free_tcpcheck_vars(&rules->preset_vars);
	free_tcpcheck_ruleset(rs);
	err_code |= ERR_ALERT | ERR_FATAL;
	goto out;
}

int proxy_parse_ldap_check_opt(char **args, int cur_arg, struct proxy *curpx, const struct proxy *defpx,
			       const char *file, int line)
{
	static char *ldap_req = "300C020101600702010304008000";

	struct tcpcheck_ruleset *rs = NULL;
	struct tcpcheck_rules *rules = &curpx->tcpcheck_rules;
	struct tcpcheck_rule *chk;
	char *errmsg = NULL;
	int err_code = 0;

	if (warnifnotcap(curpx, PR_CAP_BE, file, line, args[cur_arg+1], NULL))
		err_code |= ERR_WARN;

	if (alertif_too_many_args_idx(0, 1, file, line, args, &err_code))
		goto out;

	curpx->options2 &= ~PR_O2_CHK_ANY;
	curpx->options2 |= PR_O2_TCPCHK_CHK;

	free_tcpcheck_vars(&rules->preset_vars);
	rules->list  = NULL;
	rules->flags = 0;

	rs = find_tcpcheck_ruleset("*ldap-check");
	if (rs)
		goto ruleset_found;

	rs = create_tcpcheck_ruleset("*ldap-check");
	if (rs == NULL) {
		ha_alert("parsing [%s:%d] : out of memory.\n", file, line);
		goto error;
	}

	chk = parse_tcpcheck_send((char *[]){"tcp-check", "send-binary", ldap_req, ""},
				  1, curpx, &rs->rules, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->index = 0;
	LIST_APPEND(&rs->rules, &chk->list);

	chk = parse_tcpcheck_expect((char *[]){"tcp-check", "expect", "rbinary", "^30",
				               "min-recv", "14",
				               "on-error", "Not LDAPv3 protocol",
				               ""},
		                    1, curpx, &rs->rules, TCPCHK_RULES_LDAP_CHK, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->index = 1;
	LIST_APPEND(&rs->rules, &chk->list);

	chk = parse_tcpcheck_expect((char *[]){"tcp-check", "expect", "custom", ""},
		                    1, curpx, &rs->rules, TCPCHK_RULES_LDAP_CHK, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->expect.custom = tcpcheck_ldap_expect_bindrsp;
	chk->index = 2;
	LIST_APPEND(&rs->rules, &chk->list);

  ruleset_found:
	rules->list = &rs->rules;
	rules->flags &= ~(TCPCHK_RULES_PROTO_CHK|TCPCHK_RULES_UNUSED_RS);
	rules->flags |= TCPCHK_RULES_LDAP_CHK;

  out:
	free(errmsg);
	return err_code;

  error:
	free_tcpcheck_ruleset(rs);
	err_code |= ERR_ALERT | ERR_FATAL;
	goto out;
}

int proxy_parse_spop_check_opt(char **args, int cur_arg, struct proxy *curpx, const struct proxy *defpx,
			       const char *file, int line)
{
	struct tcpcheck_ruleset *rs = NULL;
	struct tcpcheck_rules *rules = &curpx->tcpcheck_rules;
	struct tcpcheck_rule *chk;
	char *spop_req = NULL;
	char *errmsg = NULL;
	int spop_len = 0, err_code = 0;

	if (warnifnotcap(curpx, PR_CAP_BE, file, line, args[cur_arg+1], NULL))
		err_code |= ERR_WARN;

	if (alertif_too_many_args_idx(0, 1, file, line, args, &err_code))
		goto out;

	curpx->options2 &= ~PR_O2_CHK_ANY;
	curpx->options2 |= PR_O2_TCPCHK_CHK;

	free_tcpcheck_vars(&rules->preset_vars);
	rules->list  = NULL;
	rules->flags = 0;


	rs = find_tcpcheck_ruleset("*spop-check");
	if (rs)
		goto ruleset_found;

	rs = create_tcpcheck_ruleset("*spop-check");
	if (rs == NULL) {
		ha_alert("parsing [%s:%d] : out of memory.\n", file, line);
		goto error;
	}

	if (spoe_prepare_healthcheck_request(&spop_req, &spop_len) == -1) {
		ha_alert("parsing [%s:%d] : out of memory.\n", file, line);
		goto error;
	}
	chunk_reset(&trash);
	dump_binary(&trash, spop_req, spop_len);
	trash.area[trash.data] = '\0';

	chk = parse_tcpcheck_send((char *[]){"tcp-check", "send-binary", b_head(&trash), ""},
				  1, curpx, &rs->rules, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->index = 0;
	LIST_APPEND(&rs->rules, &chk->list);

	chk = parse_tcpcheck_expect((char *[]){"tcp-check", "expect", "custom", "min-recv", "4", ""},
		                    1, curpx, &rs->rules, TCPCHK_RULES_SPOP_CHK, file, line, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : %s\n", file, line, errmsg);
		goto error;
	}
	chk->expect.custom = tcpcheck_spop_expect_agenthello;
	chk->index = 1;
	LIST_APPEND(&rs->rules, &chk->list);

  ruleset_found:
	rules->list = &rs->rules;
	rules->flags &= ~(TCPCHK_RULES_PROTO_CHK|TCPCHK_RULES_UNUSED_RS);
	rules->flags |= TCPCHK_RULES_SPOP_CHK;

  out:
	free(spop_req);
	free(errmsg);
	return err_code;

  error:
	free_tcpcheck_ruleset(rs);
	err_code |= ERR_ALERT | ERR_FATAL;
	goto out;
}


static struct tcpcheck_rule *proxy_parse_httpchk_req(char **args, int cur_arg, struct proxy *px, char **errmsg)
{
	struct tcpcheck_rule *chk = NULL;
	struct tcpcheck_http_hdr *hdr = NULL;
	char *meth = NULL, *uri = NULL, *vsn = NULL;
	char *hdrs, *body;

	hdrs = (*args[cur_arg+2] ? strstr(args[cur_arg+2], "\r\n") : NULL);
	body = (*args[cur_arg+2] ? strstr(args[cur_arg+2], "\r\n\r\n") : NULL);
	if (hdrs || body) {
		memprintf(errmsg, "hiding headers or body at the end of the version string is unsupported."
			  "Use 'http-check send' directive instead.");
		goto error;
	}

	chk = calloc(1, sizeof(*chk));
	if (!chk) {
		memprintf(errmsg, "out of memory");
		goto error;
	}
	chk->action    = TCPCHK_ACT_SEND;
	chk->send.type = TCPCHK_SEND_HTTP;
	chk->send.http.flags |= TCPCHK_SND_HTTP_FROM_OPT;
	chk->send.http.meth.meth = HTTP_METH_OPTIONS;
	LIST_INIT(&chk->send.http.hdrs);

	/* Copy the method, uri and version */
	if (*args[cur_arg]) {
		if (!*args[cur_arg+1])
			uri = args[cur_arg];
		else
			meth = args[cur_arg];
	}
	if (*args[cur_arg+1])
		uri = args[cur_arg+1];
	if (*args[cur_arg+2])
		vsn = args[cur_arg+2];

	if (meth) {
		chk->send.http.meth.meth = find_http_meth(meth, strlen(meth));
		chk->send.http.meth.str.area = strdup(meth);
		chk->send.http.meth.str.data = strlen(meth);
		if (!chk->send.http.meth.str.area) {
			memprintf(errmsg, "out of memory");
			goto error;
		}
	}
	if (uri) {
		chk->send.http.uri = ist(strdup(uri));
		if (!isttest(chk->send.http.uri)) {
			memprintf(errmsg, "out of memory");
			goto error;
		}
	}
	if (vsn) {
		chk->send.http.vsn = ist(strdup(vsn));
		if (!isttest(chk->send.http.vsn)) {
			memprintf(errmsg, "out of memory");
			goto error;
		}
	}

	return chk;

  error:
	free_tcpcheck_http_hdr(hdr);
	free_tcpcheck(chk, 0);
	return NULL;
}

/* Parses the "option httpchck" proxy keyword */
int proxy_parse_httpchk_opt(char **args, int cur_arg, struct proxy *curpx, const struct proxy *defpx,
			    const char *file, int line)
{
	struct tcpcheck_ruleset *rs = NULL;
	struct tcpcheck_rules *rules = &curpx->tcpcheck_rules;
	struct tcpcheck_rule *chk;
	char *errmsg = NULL;
	int err_code = 0;

	if (warnifnotcap(curpx, PR_CAP_BE, file, line, args[cur_arg+1], NULL))
		err_code |= ERR_WARN;

	if (alertif_too_many_args_idx(3, 1, file, line, args, &err_code))
		goto out;

	chk = proxy_parse_httpchk_req(args, cur_arg+2, curpx, &errmsg);
	if (!chk) {
		ha_alert("parsing [%s:%d] : '%s %s' : %s.\n", file, line, args[0], args[1], errmsg);
		goto error;
	}
	if (errmsg) {
		ha_warning("parsing [%s:%d]: '%s %s' : %s\n", file, line, args[0], args[1], errmsg);
		err_code |= ERR_WARN;
		ha_free(&errmsg);
	}

  no_request:
	curpx->options2 &= ~PR_O2_CHK_ANY;
	curpx->options2 |= PR_O2_TCPCHK_CHK;

	free_tcpcheck_vars(&rules->preset_vars);
	rules->list = NULL;
	rules->flags |= TCPCHK_SND_HTTP_FROM_OPT;

	/* Deduce the ruleset name from the proxy info */
	chunk_printf(&trash, "*http-check-%s_%s-%d",
		     ((curpx == defpx) ? "defaults" : curpx->id),
		     curpx->conf.file, curpx->conf.line);

	rs = find_tcpcheck_ruleset(b_orig(&trash));
	if (rs == NULL) {
		rs = create_tcpcheck_ruleset(b_orig(&trash));
		if (rs == NULL) {
			ha_alert("parsing [%s:%d] : out of memory.\n", file, line);
			goto error;
		}
	}

	rules->list = &rs->rules;
	rules->flags &= ~(TCPCHK_RULES_PROTO_CHK|TCPCHK_RULES_UNUSED_RS);
	rules->flags |= TCPCHK_RULES_HTTP_CHK;
	if (!tcpcheck_add_http_rule(chk, rules, &errmsg)) {
		ha_alert("parsing [%s:%d] : '%s %s' : %s.\n", file, line, args[0], args[1], errmsg);
		rules->list = NULL;
		goto error;
	}

  out:
	free(errmsg);
	return err_code;

  error:
	free_tcpcheck_ruleset(rs);
	free_tcpcheck(chk, 0);
	err_code |= ERR_ALERT | ERR_FATAL;
	goto out;
}

/* Parses the "option tcp-check" proxy keyword */
int proxy_parse_tcp_check_opt(char **args, int cur_arg, struct proxy *curpx, const struct proxy *defpx,
			      const char *file, int line)
{
	struct tcpcheck_ruleset *rs = NULL;
	struct tcpcheck_rules *rules = &curpx->tcpcheck_rules;
	int err_code = 0;

	if (warnifnotcap(curpx, PR_CAP_BE, file, line, args[cur_arg+1], NULL))
		err_code |= ERR_WARN;

	if (alertif_too_many_args_idx(0, 1, file, line, args, &err_code))
		goto out;

	curpx->options2 &= ~PR_O2_CHK_ANY;
	curpx->options2 |= PR_O2_TCPCHK_CHK;

	if ((rules->flags & TCPCHK_RULES_PROTO_CHK) == TCPCHK_RULES_TCP_CHK) {
		/* If a tcp-check rulesset is already set, do nothing */
		if (rules->list)
			goto out;

		/* If a tcp-check ruleset is waiting to be used for the current proxy,
		 * get it.
		 */
		if (rules->flags & TCPCHK_RULES_UNUSED_TCP_RS)
			goto curpx_ruleset;

		/* Otherwise, try to get the tcp-check ruleset of the default proxy */
		chunk_printf(&trash, "*tcp-check-defaults_%s-%d", defpx->conf.file, defpx->conf.line);
		rs = find_tcpcheck_ruleset(b_orig(&trash));
		if (rs)
			goto ruleset_found;
	}

  curpx_ruleset:
	/* Deduce the ruleset name from the proxy info */
	chunk_printf(&trash, "*tcp-check-%s_%s-%d",
		     ((curpx == defpx) ? "defaults" : curpx->id),
		     curpx->conf.file, curpx->conf.line);

	rs = find_tcpcheck_ruleset(b_orig(&trash));
	if (rs == NULL) {
		rs = create_tcpcheck_ruleset(b_orig(&trash));
		if (rs == NULL) {
			ha_alert("parsing [%s:%d] : out of memory.\n", file, line);
			goto error;
		}
	}

  ruleset_found:
	free_tcpcheck_vars(&rules->preset_vars);
	rules->list = &rs->rules;
	rules->flags &= ~(TCPCHK_RULES_PROTO_CHK|TCPCHK_RULES_UNUSED_RS);
	rules->flags |= TCPCHK_RULES_TCP_CHK;

  out:
	return err_code;

  error:
	err_code |= ERR_ALERT | ERR_FATAL;
	goto out;
}

static struct cfg_kw_list cfg_kws = {ILH, {
        { CFG_LISTEN, "http-check",     proxy_parse_httpcheck },
        { CFG_LISTEN, "tcp-check",      proxy_parse_tcpcheck },
        { 0, NULL, NULL },
}};

REGISTER_POST_PROXY_CHECK(check_proxy_tcpcheck);
REGISTER_PROXY_DEINIT(deinit_proxy_tcpcheck);
REGISTER_POST_DEINIT(deinit_tcpchecks);
INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);