summaryrefslogtreecommitdiffstats
path: root/src/detect-engine.c
blob: c86366314513a9155cf385bad371766a35f004de (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
5151
/* Copyright (C) 2007-2022 Open Information Security Foundation
 *
 * You can copy, redistribute or modify this Program under the terms of
 * the GNU General Public License version 2 as published by the Free
 * Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * version 2 along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

/**
 * \file
 *
 * \author Victor Julien <victor@inliniac.net>
 */

#include "suricata-common.h"
#include "suricata.h"
#include "detect.h"
#include "flow.h"
#include "flow-private.h"
#include "flow-util.h"
#include "flow-worker.h"
#include "conf.h"
#include "conf-yaml-loader.h"
#include "datasets.h"

#include "app-layer-parser.h"
#include "app-layer-htp.h"

#include "detect-parse.h"
#include "detect-engine-sigorder.h"

#include "detect-engine-build.h"
#include "detect-engine-siggroup.h"
#include "detect-engine-address.h"
#include "detect-engine-port.h"
#include "detect-engine-prefilter.h"
#include "detect-engine-mpm.h"
#include "detect-engine-iponly.h"
#include "detect-engine-tag.h"
#include "detect-engine-frame.h"

#include "detect-engine-file.h"

#include "detect-engine.h"
#include "detect-engine-state.h"
#include "detect-engine-payload.h"
#include "detect-fast-pattern.h"
#include "detect-byte-extract.h"
#include "detect-content.h"
#include "detect-uricontent.h"
#include "detect-tcphdr.h"
#include "detect-engine-threshold.h"
#include "detect-engine-content-inspection.h"

#include "detect-engine-loader.h"

#include "util-classification-config.h"
#include "util-reference-config.h"
#include "util-threshold-config.h"
#include "util-error.h"
#include "util-hash.h"
#include "util-byte.h"
#include "util-debug.h"
#include "util-unittest.h"
#include "util-action.h"
#include "util-magic.h"
#include "util-signal.h"
#include "util-spm.h"
#include "util-device.h"
#include "util-var-name.h"
#include "util-path.h"
#include "util-profiling.h"
#include "util-validate.h"
#include "util-hash-string.h"
#include "util-enum.h"
#include "util-conf.h"

#include "tm-threads.h"
#include "runmodes.h"

#include "reputation.h"

#define DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT 3000

static int DetectEngineCtxLoadConf(DetectEngineCtx *);

static DetectEngineMasterCtx g_master_de_ctx = { SCMUTEX_INITIALIZER,
    0, 99, NULL, NULL, TENANT_SELECTOR_UNKNOWN, NULL, NULL, 0};

static uint32_t TenantIdHash(HashTable *h, void *data, uint16_t data_len);
static char TenantIdCompare(void *d1, uint16_t d1_len, void *d2, uint16_t d2_len);
static void TenantIdFree(void *d);
static uint32_t DetectEngineTenantGetIdFromLivedev(const void *ctx, const Packet *p);
static uint32_t DetectEngineTenantGetIdFromVlanId(const void *ctx, const Packet *p);
static uint32_t DetectEngineTenantGetIdFromPcap(const void *ctx, const Packet *p);

static DetectEngineAppInspectionEngine *g_app_inspect_engines = NULL;
static DetectEnginePktInspectionEngine *g_pkt_inspect_engines = NULL;
static DetectEngineFrameInspectionEngine *g_frame_inspect_engines = NULL;

// clang-format off
const struct SignatureProperties signature_properties[SIG_TYPE_MAX] = {
    /* SIG_TYPE_NOT_SET */      { SIG_PROP_FLOW_ACTION_PACKET, },
    /* SIG_TYPE_IPONLY */       { SIG_PROP_FLOW_ACTION_FLOW, },
    /* SIG_TYPE_LIKE_IPONLY */  { SIG_PROP_FLOW_ACTION_FLOW, },
    /* SIG_TYPE_PDONLY */       { SIG_PROP_FLOW_ACTION_FLOW, },
    /* SIG_TYPE_DEONLY */       { SIG_PROP_FLOW_ACTION_PACKET, },
    /* SIG_TYPE_PKT */          { SIG_PROP_FLOW_ACTION_PACKET, },
    /* SIG_TYPE_PKT_STREAM */   { SIG_PROP_FLOW_ACTION_FLOW_IF_STATEFUL, },
    /* SIG_TYPE_STREAM */       { SIG_PROP_FLOW_ACTION_FLOW_IF_STATEFUL, },
    /* SIG_TYPE_APPLAYER */     { SIG_PROP_FLOW_ACTION_FLOW, },
    /* SIG_TYPE_APP_TX */       { SIG_PROP_FLOW_ACTION_FLOW, },
};
// clang-format on

/** \brief register inspect engine at start up time
 *
 *  \note errors are fatal */
void DetectPktInspectEngineRegister(const char *name,
        InspectionBufferGetPktDataPtr GetPktData,
        InspectionBufferPktInspectFunc Callback)
{
    DetectBufferTypeRegister(name);
    const int sm_list = DetectBufferTypeGetByName(name);
    if (sm_list == -1) {
        FatalError("failed to register inspect engine %s", name);
    }

    if ((sm_list < DETECT_SM_LIST_MATCH) || (sm_list >= SHRT_MAX) ||
        (Callback == NULL))
    {
        SCLogError("Invalid arguments");
        BUG_ON(1);
    }

    DetectEnginePktInspectionEngine *new_engine = SCCalloc(1, sizeof(*new_engine));
    if (unlikely(new_engine == NULL)) {
        FatalError("failed to register inspect engine %s: %s", name, strerror(errno));
    }
    new_engine->sm_list = (uint16_t)sm_list;
    new_engine->sm_list_base = (uint16_t)sm_list;
    new_engine->v1.Callback = Callback;
    new_engine->v1.GetData = GetPktData;

    if (g_pkt_inspect_engines == NULL) {
        g_pkt_inspect_engines = new_engine;
    } else {
        DetectEnginePktInspectionEngine *t = g_pkt_inspect_engines;
        while (t->next != NULL) {
            t = t->next;
        }

        t->next = new_engine;
    }
}

/** \brief register inspect engine at start up time
 *
 *  \note errors are fatal */
void DetectFrameInspectEngineRegister(const char *name, int dir,
        InspectionBufferFrameInspectFunc Callback, AppProto alproto, uint8_t type)
{
    DetectBufferTypeRegister(name);
    const int sm_list = DetectBufferTypeGetByName(name);
    if (sm_list == -1) {
        FatalError("failed to register inspect engine %s", name);
    }

    if ((sm_list < DETECT_SM_LIST_MATCH) || (sm_list >= SHRT_MAX) || (Callback == NULL)) {
        SCLogError("Invalid arguments");
        BUG_ON(1);
    }

    uint8_t direction;
    if (dir == SIG_FLAG_TOSERVER) {
        direction = 0;
    } else {
        direction = 1;
    }

    DetectEngineFrameInspectionEngine *new_engine = SCCalloc(1, sizeof(*new_engine));
    if (unlikely(new_engine == NULL)) {
        FatalError("failed to register inspect engine %s: %s", name, strerror(errno));
    }
    new_engine->sm_list = (uint16_t)sm_list;
    new_engine->sm_list_base = (uint16_t)sm_list;
    new_engine->dir = direction;
    new_engine->v1.Callback = Callback;
    new_engine->alproto = alproto;
    new_engine->type = type;

    if (g_frame_inspect_engines == NULL) {
        g_frame_inspect_engines = new_engine;
    } else {
        DetectEngineFrameInspectionEngine *t = g_frame_inspect_engines;
        while (t->next != NULL) {
            t = t->next;
        }

        t->next = new_engine;
    }
}

/** \brief register inspect engine at start up time
 *
 *  \note errors are fatal */
void DetectAppLayerInspectEngineRegister2(const char *name,
        AppProto alproto, uint32_t dir, int progress,
        InspectEngineFuncPtr2 Callback2,
        InspectionBufferGetDataPtr GetData)
{
    BUG_ON(progress >= 48);

    DetectBufferTypeRegister(name);
    const int sm_list = DetectBufferTypeGetByName(name);
    if (sm_list == -1) {
        FatalError("failed to register inspect engine %s", name);
    }
    SCLogDebug("name %s id %d", name, sm_list);

    if ((alproto >= ALPROTO_FAILED) ||
        (!(dir == SIG_FLAG_TOSERVER || dir == SIG_FLAG_TOCLIENT)) ||
        (sm_list < DETECT_SM_LIST_MATCH) || (sm_list >= SHRT_MAX) ||
        (progress < 0 || progress >= SHRT_MAX) ||
        (Callback2 == NULL))
    {
        SCLogError("Invalid arguments");
        BUG_ON(1);
    } else if (Callback2 == DetectEngineInspectBufferGeneric && GetData == NULL) {
        SCLogError("Invalid arguments: must register "
                   "GetData with DetectEngineInspectBufferGeneric");
        BUG_ON(1);
    }

    uint8_t direction;
    if (dir == SIG_FLAG_TOSERVER) {
        direction = 0;
    } else {
        direction = 1;
    }

    DetectEngineAppInspectionEngine *new_engine = SCMalloc(sizeof(DetectEngineAppInspectionEngine));
    if (unlikely(new_engine == NULL)) {
        exit(EXIT_FAILURE);
    }
    memset(new_engine, 0, sizeof(*new_engine));
    new_engine->alproto = alproto;
    new_engine->dir = direction;
    new_engine->sm_list = (uint16_t)sm_list;
    new_engine->sm_list_base = (uint16_t)sm_list;
    new_engine->progress = (int16_t)progress;
    new_engine->v2.Callback = Callback2;
    new_engine->v2.GetData = GetData;

    if (g_app_inspect_engines == NULL) {
        g_app_inspect_engines = new_engine;
    } else {
        DetectEngineAppInspectionEngine *t = g_app_inspect_engines;
        while (t->next != NULL) {
            t = t->next;
        }

        t->next = new_engine;
    }
}

/* copy an inspect engine with transforms to a new list id. */
static void DetectAppLayerInspectEngineCopy(
        DetectEngineCtx *de_ctx,
        int sm_list, int new_list,
        const DetectEngineTransforms *transforms)
{
    const DetectEngineAppInspectionEngine *t = g_app_inspect_engines;
    while (t) {
        if (t->sm_list == sm_list) {
            DetectEngineAppInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEngineAppInspectionEngine));
            if (unlikely(new_engine == NULL)) {
                exit(EXIT_FAILURE);
            }
            new_engine->alproto = t->alproto;
            new_engine->dir = t->dir;
            DEBUG_VALIDATE_BUG_ON(new_list < 0 || new_list > UINT16_MAX);
            new_engine->sm_list = (uint16_t)new_list; /* use new list id */
            DEBUG_VALIDATE_BUG_ON(sm_list < 0 || sm_list > UINT16_MAX);
            new_engine->sm_list_base = (uint16_t)sm_list;
            new_engine->progress = t->progress;
            new_engine->v2 = t->v2;
            new_engine->v2.transforms = transforms; /* assign transforms */

            if (de_ctx->app_inspect_engines == NULL) {
                de_ctx->app_inspect_engines = new_engine;
            } else {
                DetectEngineAppInspectionEngine *list = de_ctx->app_inspect_engines;
                while (list->next != NULL) {
                    list = list->next;
                }

                list->next = new_engine;
            }
        }
        t = t->next;
    }
}

/* copy inspect engines from global registrations to de_ctx list */
static void DetectAppLayerInspectEngineCopyListToDetectCtx(DetectEngineCtx *de_ctx)
{
    const DetectEngineAppInspectionEngine *t = g_app_inspect_engines;
    DetectEngineAppInspectionEngine *list = de_ctx->app_inspect_engines;
    while (t) {
        DetectEngineAppInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEngineAppInspectionEngine));
        if (unlikely(new_engine == NULL)) {
            exit(EXIT_FAILURE);
        }
        new_engine->alproto = t->alproto;
        new_engine->dir = t->dir;
        new_engine->sm_list = t->sm_list;
        new_engine->sm_list_base = t->sm_list;
        new_engine->progress = t->progress;
        new_engine->v2 = t->v2;

        if (list == NULL) {
            de_ctx->app_inspect_engines = new_engine;
        } else {
            list->next = new_engine;
        }
        list = new_engine;

        t = t->next;
    }
}

/* copy an inspect engine with transforms to a new list id. */
static void DetectPktInspectEngineCopy(
        DetectEngineCtx *de_ctx,
        int sm_list, int new_list,
        const DetectEngineTransforms *transforms)
{
    const DetectEnginePktInspectionEngine *t = g_pkt_inspect_engines;
    while (t) {
        if (t->sm_list == sm_list) {
            DetectEnginePktInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEnginePktInspectionEngine));
            if (unlikely(new_engine == NULL)) {
                exit(EXIT_FAILURE);
            }
            DEBUG_VALIDATE_BUG_ON(new_list < 0 || new_list > UINT16_MAX);
            new_engine->sm_list = (uint16_t)new_list; /* use new list id */
            DEBUG_VALIDATE_BUG_ON(sm_list < 0 || sm_list > UINT16_MAX);
            new_engine->sm_list_base = (uint16_t)sm_list;
            new_engine->v1 = t->v1;
            new_engine->v1.transforms = transforms; /* assign transforms */

            if (de_ctx->pkt_inspect_engines == NULL) {
                de_ctx->pkt_inspect_engines = new_engine;
            } else {
                DetectEnginePktInspectionEngine *list = de_ctx->pkt_inspect_engines;
                while (list->next != NULL) {
                    list = list->next;
                }

                list->next = new_engine;
            }
        }
        t = t->next;
    }
}

/* copy inspect engines from global registrations to de_ctx list */
static void DetectPktInspectEngineCopyListToDetectCtx(DetectEngineCtx *de_ctx)
{
    const DetectEnginePktInspectionEngine *t = g_pkt_inspect_engines;
    while (t) {
        SCLogDebug("engine %p", t);
        DetectEnginePktInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEnginePktInspectionEngine));
        if (unlikely(new_engine == NULL)) {
            exit(EXIT_FAILURE);
        }
        new_engine->sm_list = t->sm_list;
        new_engine->sm_list_base = t->sm_list;
        new_engine->v1 = t->v1;

        if (de_ctx->pkt_inspect_engines == NULL) {
            de_ctx->pkt_inspect_engines = new_engine;
        } else {
            DetectEnginePktInspectionEngine *list = de_ctx->pkt_inspect_engines;
            while (list->next != NULL) {
                list = list->next;
            }

            list->next = new_engine;
        }

        t = t->next;
    }
}

/** \brief register inspect engine at start up time
 *
 *  \note errors are fatal */
void DetectEngineFrameInspectEngineRegister(DetectEngineCtx *de_ctx, const char *name, int dir,
        InspectionBufferFrameInspectFunc Callback, AppProto alproto, uint8_t type)
{
    const int sm_list = DetectEngineBufferTypeRegister(de_ctx, name);
    if (sm_list < 0) {
        FatalError("failed to register inspect engine %s", name);
    }

    if ((sm_list < DETECT_SM_LIST_MATCH) || (sm_list >= SHRT_MAX) || (Callback == NULL)) {
        SCLogError("Invalid arguments");
        BUG_ON(1);
    }

    uint8_t direction;
    if (dir == SIG_FLAG_TOSERVER) {
        direction = 0;
    } else {
        direction = 1;
    }

    DetectEngineFrameInspectionEngine *new_engine = SCCalloc(1, sizeof(*new_engine));
    if (unlikely(new_engine == NULL)) {
        FatalError("failed to register inspect engine %s: %s", name, strerror(errno));
    }
    new_engine->sm_list = (uint16_t)sm_list;
    new_engine->sm_list_base = (uint16_t)sm_list;
    new_engine->dir = direction;
    new_engine->v1.Callback = Callback;
    new_engine->alproto = alproto;
    new_engine->type = type;

    if (de_ctx->frame_inspect_engines == NULL) {
        de_ctx->frame_inspect_engines = new_engine;
    } else {
        DetectEngineFrameInspectionEngine *list = de_ctx->frame_inspect_engines;
        while (list->next != NULL) {
            list = list->next;
        }

        list->next = new_engine;
    }
}

/* copy an inspect engine with transforms to a new list id. */
static void DetectFrameInspectEngineCopy(DetectEngineCtx *de_ctx, int sm_list, int new_list,
        const DetectEngineTransforms *transforms)
{
    /* take the list from the detect engine as the buffers can be registered
     * dynamically. */
    DetectEngineFrameInspectionEngine *t = de_ctx->frame_inspect_engines;
    while (t) {
        if (t->sm_list == sm_list) {
            DetectEngineFrameInspectionEngine *new_engine =
                    SCCalloc(1, sizeof(DetectEngineFrameInspectionEngine));
            if (unlikely(new_engine == NULL)) {
                exit(EXIT_FAILURE);
            }
            DEBUG_VALIDATE_BUG_ON(new_list < 0 || new_list > UINT16_MAX);
            new_engine->sm_list = (uint16_t)new_list; /* use new list id */
            DEBUG_VALIDATE_BUG_ON(sm_list < 0 || sm_list > UINT16_MAX);
            new_engine->sm_list_base = (uint16_t)sm_list;
            new_engine->dir = t->dir;
            new_engine->alproto = t->alproto;
            new_engine->type = t->type;
            new_engine->v1 = t->v1;
            new_engine->v1.transforms = transforms; /* assign transforms */

            /* append to the list */
            DetectEngineFrameInspectionEngine *list = t;
            while (list->next != NULL) {
                list = list->next;
            }

            list->next = new_engine;
        }
        t = t->next;
    }
}

/* copy inspect engines from global registrations to de_ctx list */
static void DetectFrameInspectEngineCopyListToDetectCtx(DetectEngineCtx *de_ctx)
{
    const DetectEngineFrameInspectionEngine *t = g_frame_inspect_engines;
    while (t) {
        SCLogDebug("engine %p", t);
        DetectEngineFrameInspectionEngine *new_engine =
                SCCalloc(1, sizeof(DetectEngineFrameInspectionEngine));
        if (unlikely(new_engine == NULL)) {
            exit(EXIT_FAILURE);
        }
        new_engine->sm_list = t->sm_list;
        new_engine->sm_list_base = t->sm_list;
        new_engine->dir = t->dir;
        new_engine->alproto = t->alproto;
        new_engine->type = t->type;
        new_engine->v1 = t->v1;

        if (de_ctx->frame_inspect_engines == NULL) {
            de_ctx->frame_inspect_engines = new_engine;
        } else {
            DetectEngineFrameInspectionEngine *list = de_ctx->frame_inspect_engines;
            while (list->next != NULL) {
                list = list->next;
            }

            list->next = new_engine;
        }

        t = t->next;
    }
}

/** \internal
 *  \brief append the stream inspection
 *
 *  If stream inspection is MPM, then prepend it.
 */
static void AppendStreamInspectEngine(
        Signature *s, SigMatchData *stream, uint8_t direction, uint8_t id)
{
    bool prepend = false;

    DetectEngineAppInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEngineAppInspectionEngine));
    if (unlikely(new_engine == NULL)) {
        exit(EXIT_FAILURE);
    }
    if (s->init_data->mpm_sm_list == DETECT_SM_LIST_PMATCH) {
        SCLogDebug("stream is mpm");
        prepend = true;
        new_engine->mpm = true;
    }
    new_engine->alproto = ALPROTO_UNKNOWN; /* all */
    new_engine->dir = direction;
    new_engine->stream = true;
    new_engine->sm_list = DETECT_SM_LIST_PMATCH;
    new_engine->sm_list_base = DETECT_SM_LIST_PMATCH;
    new_engine->smd = stream;
    new_engine->v2.Callback = DetectEngineInspectStream;
    new_engine->progress = 0;

    /* append */
    if (s->app_inspect == NULL) {
        s->app_inspect = new_engine;
        new_engine->id = DE_STATE_FLAG_BASE; /* id is used as flag in stateful detect */
    } else if (prepend) {
        new_engine->next = s->app_inspect;
        s->app_inspect = new_engine;
        new_engine->id = id;

    } else {
        DetectEngineAppInspectionEngine *a = s->app_inspect;
        while (a->next != NULL) {
            a = a->next;
        }

        a->next = new_engine;
        new_engine->id = id;
    }
    SCLogDebug("sid %u: engine %p/%u added", s->id, new_engine, new_engine->id);
}

static void AppendFrameInspectEngine(DetectEngineCtx *de_ctx,
        const DetectEngineFrameInspectionEngine *u, Signature *s, SigMatchData *smd,
        const int mpm_list)
{
    bool prepend = false;

    if (u->alproto == ALPROTO_UNKNOWN) {
        /* special case, inspect engine applies to all protocols */
    } else if (s->alproto != ALPROTO_UNKNOWN && !AppProtoEquals(s->alproto, u->alproto))
        return;

    if (s->flags & SIG_FLAG_TOSERVER && !(s->flags & SIG_FLAG_TOCLIENT)) {
        if (u->dir == 1)
            return;
    } else if (s->flags & SIG_FLAG_TOCLIENT && !(s->flags & SIG_FLAG_TOSERVER)) {
        if (u->dir == 0)
            return;
    }

    DetectEngineFrameInspectionEngine *new_engine =
            SCCalloc(1, sizeof(DetectEngineFrameInspectionEngine));
    if (unlikely(new_engine == NULL)) {
        exit(EXIT_FAILURE);
    }
    if (mpm_list == u->sm_list) {
        SCLogDebug("%s is mpm", DetectEngineBufferTypeGetNameById(de_ctx, u->sm_list));
        prepend = true;
        new_engine->mpm = true;
    }

    new_engine->type = u->type;
    new_engine->sm_list = u->sm_list;
    new_engine->sm_list_base = u->sm_list_base;
    new_engine->smd = smd;
    new_engine->v1 = u->v1;
    SCLogDebug("sm_list %d new_engine->v1 %p/%p", new_engine->sm_list, new_engine->v1.Callback,
            new_engine->v1.transforms);

    if (s->frame_inspect == NULL) {
        s->frame_inspect = new_engine;
    } else if (prepend) {
        new_engine->next = s->frame_inspect;
        s->frame_inspect = new_engine;
    } else {
        DetectEngineFrameInspectionEngine *a = s->frame_inspect;
        while (a->next != NULL) {
            a = a->next;
        }
        new_engine->next = a->next;
        a->next = new_engine;
    }
}

static void AppendPacketInspectEngine(DetectEngineCtx *de_ctx,
        const DetectEnginePktInspectionEngine *e, Signature *s, SigMatchData *smd,
        const int mpm_list)
{
    bool prepend = false;

    DetectEnginePktInspectionEngine *new_engine =
            SCCalloc(1, sizeof(DetectEnginePktInspectionEngine));
    if (unlikely(new_engine == NULL)) {
        exit(EXIT_FAILURE);
    }
    if (mpm_list == e->sm_list) {
        SCLogDebug("%s is mpm", DetectEngineBufferTypeGetNameById(de_ctx, e->sm_list));
        prepend = true;
        new_engine->mpm = true;
    }

    new_engine->sm_list = e->sm_list;
    new_engine->sm_list_base = e->sm_list_base;
    new_engine->smd = smd;
    new_engine->v1 = e->v1;
    SCLogDebug("sm_list %d new_engine->v1 %p/%p/%p", new_engine->sm_list, new_engine->v1.Callback,
            new_engine->v1.GetData, new_engine->v1.transforms);

    if (s->pkt_inspect == NULL) {
        s->pkt_inspect = new_engine;
    } else if (prepend) {
        new_engine->next = s->pkt_inspect;
        s->pkt_inspect = new_engine;
    } else {
        DetectEnginePktInspectionEngine *a = s->pkt_inspect;
        while (a->next != NULL) {
            a = a->next;
        }
        new_engine->next = a->next;
        a->next = new_engine;
    }
}

static void AppendAppInspectEngine(DetectEngineCtx *de_ctx,
        const DetectEngineAppInspectionEngine *t, Signature *s, SigMatchData *smd,
        const int mpm_list, const int files_id, uint8_t *last_id, bool *head_is_mpm)
{
    if (t->alproto == ALPROTO_UNKNOWN) {
        /* special case, inspect engine applies to all protocols */
    } else if (s->alproto != ALPROTO_UNKNOWN && !AppProtoEquals(s->alproto, t->alproto))
        return;

    if (s->flags & SIG_FLAG_TOSERVER && !(s->flags & SIG_FLAG_TOCLIENT)) {
        if (t->dir == 1)
            return;
    } else if (s->flags & SIG_FLAG_TOCLIENT && !(s->flags & SIG_FLAG_TOSERVER)) {
        if (t->dir == 0)
            return;
    }
    SCLogDebug("app engine: t %p t->id %u => alproto:%s files:%s", t, t->id,
            AppProtoToString(t->alproto), BOOL2STR(t->sm_list == files_id));

    DetectEngineAppInspectionEngine *new_engine =
            SCCalloc(1, sizeof(DetectEngineAppInspectionEngine));
    if (unlikely(new_engine == NULL)) {
        exit(EXIT_FAILURE);
    }
    bool prepend = false;
    if (mpm_list == t->sm_list) {
        SCLogDebug("%s is mpm", DetectEngineBufferTypeGetNameById(de_ctx, t->sm_list));
        prepend = true;
        *head_is_mpm = true;
        new_engine->mpm = true;
    }

    new_engine->alproto = t->alproto;
    new_engine->dir = t->dir;
    new_engine->sm_list = t->sm_list;
    new_engine->sm_list_base = t->sm_list_base;
    new_engine->smd = smd;
    new_engine->progress = t->progress;
    new_engine->v2 = t->v2;
    SCLogDebug("sm_list %d new_engine->v2 %p/%p/%p", new_engine->sm_list, new_engine->v2.Callback,
            new_engine->v2.GetData, new_engine->v2.transforms);

    if (s->app_inspect == NULL) {
        s->app_inspect = new_engine;
        if (new_engine->sm_list == files_id) {
            new_engine->id = DE_STATE_ID_FILE_INSPECT;
            SCLogDebug("sid %u: engine %p/%u is FILE ENGINE", s->id, new_engine, new_engine->id);
        } else {
            new_engine->id = DE_STATE_FLAG_BASE; /* id is used as flag in stateful detect */
            SCLogDebug("sid %u: engine %p/%u %s", s->id, new_engine, new_engine->id,
                    DetectEngineBufferTypeGetNameById(de_ctx, new_engine->sm_list));
        }

        /* prepend engine if forced or if our engine has a lower progress. */
    } else if (prepend || (!(*head_is_mpm) && s->app_inspect->progress > new_engine->progress)) {
        new_engine->next = s->app_inspect;
        s->app_inspect = new_engine;
        if (new_engine->sm_list == files_id) {
            new_engine->id = DE_STATE_ID_FILE_INSPECT;
            SCLogDebug("sid %u: engine %p/%u is FILE ENGINE", s->id, new_engine, new_engine->id);
        } else {
            new_engine->id = ++(*last_id);
            SCLogDebug("sid %u: engine %p/%u %s", s->id, new_engine, new_engine->id,
                    DetectEngineBufferTypeGetNameById(de_ctx, new_engine->sm_list));
        }

    } else {
        DetectEngineAppInspectionEngine *a = s->app_inspect;
        while (a->next != NULL) {
            if (a->next && a->next->progress > new_engine->progress) {
                break;
            }
            a = a->next;
        }

        new_engine->next = a->next;
        a->next = new_engine;
        if (new_engine->sm_list == files_id) {
            new_engine->id = DE_STATE_ID_FILE_INSPECT;
            SCLogDebug("sid %u: engine %p/%u is FILE ENGINE", s->id, new_engine, new_engine->id);
        } else {
            new_engine->id = ++(*last_id);
            SCLogDebug("sid %u: engine %p/%u %s", s->id, new_engine, new_engine->id,
                    DetectEngineBufferTypeGetNameById(de_ctx, new_engine->sm_list));
        }
    }

    SCLogDebug("sid %u: engine %p/%u added", s->id, new_engine, new_engine->id);

    s->init_data->init_flags |= SIG_FLAG_INIT_STATE_MATCH;
}

/**
 *  \note for the file inspect engine, the id DE_STATE_ID_FILE_INSPECT
 *        is assigned.
 */
int DetectEngineAppInspectionEngine2Signature(DetectEngineCtx *de_ctx, Signature *s)
{
    const int mpm_list = s->init_data->mpm_sm ? s->init_data->mpm_sm_list : -1;
    const int files_id = DetectBufferTypeGetByName("files");
    bool head_is_mpm = false;
    uint8_t last_id = DE_STATE_FLAG_BASE;

    for (uint32_t x = 0; x < s->init_data->buffer_index; x++) {
        SigMatchData *smd = SigMatchList2DataArray(s->init_data->buffers[x].head);
        SCLogDebug("smd %p, id %u", smd, s->init_data->buffers[x].id);

        const DetectBufferType *b =
                DetectEngineBufferTypeGetById(de_ctx, s->init_data->buffers[x].id);
        if (b == NULL)
            FatalError("unknown buffer");

        if (b->frame) {
            for (const DetectEngineFrameInspectionEngine *u = de_ctx->frame_inspect_engines;
                    u != NULL; u = u->next) {
                if (u->sm_list == s->init_data->buffers[x].id) {
                    AppendFrameInspectEngine(de_ctx, u, s, smd, mpm_list);
                }
            }
        } else if (b->packet) {
            /* set up pkt inspect engines */
            for (const DetectEnginePktInspectionEngine *e = de_ctx->pkt_inspect_engines; e != NULL;
                    e = e->next) {
                SCLogDebug("e %p sm_list %u", e, e->sm_list);
                if (e->sm_list == s->init_data->buffers[x].id) {
                    AppendPacketInspectEngine(de_ctx, e, s, smd, mpm_list);
                }
            }
        } else {
            SCLogDebug("app %s id %u parent %u rule %u xforms %u", b->name, b->id, b->parent_id,
                    s->init_data->buffers[x].id, b->transforms.cnt);
            for (const DetectEngineAppInspectionEngine *t = de_ctx->app_inspect_engines; t != NULL;
                    t = t->next) {
                if (t->sm_list == s->init_data->buffers[x].id) {
                    AppendAppInspectEngine(
                            de_ctx, t, s, smd, mpm_list, files_id, &last_id, &head_is_mpm);
                }
            }
        }
    }

    if ((s->init_data->init_flags & SIG_FLAG_INIT_STATE_MATCH) &&
            s->init_data->smlists[DETECT_SM_LIST_PMATCH] != NULL)
    {
        /* if engine is added multiple times, we pass it the same list */
        SigMatchData *stream = SigMatchList2DataArray(s->init_data->smlists[DETECT_SM_LIST_PMATCH]);
        BUG_ON(stream == NULL);
        if (s->flags & SIG_FLAG_TOSERVER && !(s->flags & SIG_FLAG_TOCLIENT)) {
            AppendStreamInspectEngine(s, stream, 0, last_id + 1);
        } else if (s->flags & SIG_FLAG_TOCLIENT && !(s->flags & SIG_FLAG_TOSERVER)) {
            AppendStreamInspectEngine(s, stream, 1, last_id + 1);
        } else {
            AppendStreamInspectEngine(s, stream, 0, last_id + 1);
            AppendStreamInspectEngine(s, stream, 1, last_id + 1);
        }

        if (s->init_data->init_flags & SIG_FLAG_INIT_NEED_FLUSH) {
            SCLogDebug("set SIG_FLAG_FLUSH on %u", s->id);
            s->flags |= SIG_FLAG_FLUSH;
        }
    }

#ifdef DEBUG
    const DetectEngineAppInspectionEngine *iter = s->app_inspect;
    while (iter) {
        SCLogDebug("%u: engine %s id %u progress %d %s", s->id,
                DetectEngineBufferTypeGetNameById(de_ctx, iter->sm_list), iter->id, iter->progress,
                iter->sm_list == mpm_list ? "MPM" : "");
        iter = iter->next;
    }
#endif
    return 0;
}

/** \brief free app inspect engines for a signature
 *
 *  For lists that are registered multiple times, like http_header and
 *  http_cookie, making the engines owner of the lists is complicated.
 *  Multiple engines in a sig may be pointing to the same list. To
 *  address this the 'free' code needs to be extra careful about not
 *  double freeing, so it takes an approach to first fill an array
 *  of the to-free pointers before freeing them.
 */
void DetectEngineAppInspectionEngineSignatureFree(DetectEngineCtx *de_ctx, Signature *s)
{
    int engines = 0;

    DetectEngineAppInspectionEngine *ie = s->app_inspect;
    while (ie) {
        ie = ie->next;
        engines++;
    }
    DetectEnginePktInspectionEngine *e = s->pkt_inspect;
    while (e) {
        e = e->next;
        engines++;
    }
    DetectEngineFrameInspectionEngine *u = s->frame_inspect;
    while (u) {
        u = u->next;
        engines++;
    }
    if (engines == 0) {
        BUG_ON(s->pkt_inspect);
        BUG_ON(s->frame_inspect);
        return;
    }

    SigMatchData *bufs[engines];
    memset(&bufs, 0, (engines * sizeof(SigMatchData *)));
    int arrays = 0;

    /* free engines and put smd in the array */
    ie = s->app_inspect;
    while (ie) {
        DetectEngineAppInspectionEngine *next = ie->next;

        bool skip = false;
        for (int i = 0; i < arrays; i++) {
            if (bufs[i] == ie->smd) {
                skip = true;
                break;
            }
        }
        if (!skip) {
            bufs[arrays++] = ie->smd;
        }
        SCFree(ie);
        ie = next;
    }
    e = s->pkt_inspect;
    while (e) {
        DetectEnginePktInspectionEngine *next = e->next;

        bool skip = false;
        for (int i = 0; i < arrays; i++) {
            if (bufs[i] == e->smd) {
                skip = true;
                break;
            }
        }
        if (!skip) {
            bufs[arrays++] = e->smd;
        }
        SCFree(e);
        e = next;
    }
    u = s->frame_inspect;
    while (u) {
        DetectEngineFrameInspectionEngine *next = u->next;

        bool skip = false;
        for (int i = 0; i < arrays; i++) {
            if (bufs[i] == u->smd) {
                skip = true;
                break;
            }
        }
        if (!skip) {
            bufs[arrays++] = u->smd;
        }
        SCFree(u);
        u = next;
    }

    for (int i = 0; i < engines; i++) {
        if (bufs[i] == NULL)
            continue;
        SigMatchData *smd = bufs[i];
        while (1) {
            if (sigmatch_table[smd->type].Free != NULL) {
                sigmatch_table[smd->type].Free(de_ctx, smd->ctx);
            }
            if (smd->is_last)
                break;
            smd++;
        }
        SCFree(bufs[i]);
    }
}

/* code for registering buffers */

#include "util-hash-lookup3.h"

static HashListTable *g_buffer_type_hash = NULL;
static int g_buffer_type_id = DETECT_SM_LIST_DYNAMIC_START;
static int g_buffer_type_reg_closed = 0;

int DetectBufferTypeMaxId(void)
{
    return g_buffer_type_id;
}

static uint32_t DetectBufferTypeHashNameFunc(HashListTable *ht, void *data, uint16_t datalen)
{
    const DetectBufferType *map = (DetectBufferType *)data;
    uint32_t hash = hashlittle_safe(map->name, strlen(map->name), 0);
    hash += hashlittle_safe((uint8_t *)&map->transforms, sizeof(map->transforms), 0);
    hash %= ht->array_size;
    return hash;
}

static uint32_t DetectBufferTypeHashIdFunc(HashListTable *ht, void *data, uint16_t datalen)
{
    const DetectBufferType *map = (DetectBufferType *)data;
    uint32_t hash = map->id;
    hash %= ht->array_size;
    return hash;
}

static char DetectBufferTypeCompareNameFunc(void *data1, uint16_t len1, void *data2, uint16_t len2)
{
    DetectBufferType *map1 = (DetectBufferType *)data1;
    DetectBufferType *map2 = (DetectBufferType *)data2;

    char r = (strcmp(map1->name, map2->name) == 0);
    r &= (memcmp((uint8_t *)&map1->transforms, (uint8_t *)&map2->transforms, sizeof(map2->transforms)) == 0);
    return r;
}

static char DetectBufferTypeCompareIdFunc(void *data1, uint16_t len1, void *data2, uint16_t len2)
{
    DetectBufferType *map1 = (DetectBufferType *)data1;
    DetectBufferType *map2 = (DetectBufferType *)data2;
    return map1->id == map2->id;
}

static void DetectBufferTypeFreeFunc(void *data)
{
    DetectBufferType *map = (DetectBufferType *)data;

    if (map == NULL) {
        return;
    }

    /* Release transformation option memory, if any */
    for (int i = 0; i < map->transforms.cnt; i++) {
        if (map->transforms.transforms[i].options == NULL)
            continue;
        if (sigmatch_table[map->transforms.transforms[i].transform].Free == NULL) {
            SCLogError("%s allocates transform option memory but has no free routine",
                    sigmatch_table[map->transforms.transforms[i].transform].name);
            continue;
        }
        sigmatch_table[map->transforms.transforms[i].transform].Free(NULL, map->transforms.transforms[i].options);
    }

    SCFree(map);
}

static int DetectBufferTypeInit(void)
{
    BUG_ON(g_buffer_type_hash);
    g_buffer_type_hash = HashListTableInit(256, DetectBufferTypeHashNameFunc,
            DetectBufferTypeCompareNameFunc, DetectBufferTypeFreeFunc);
    if (g_buffer_type_hash == NULL)
        return -1;

    return 0;
}
#if 0
static void DetectBufferTypeFree(void)
{
    if (g_buffer_type_hash == NULL)
        return;

    HashListTableFree(g_buffer_type_hash);
    g_buffer_type_hash = NULL;
    return;
}
#endif
static int DetectBufferTypeAdd(const char *string)
{
    BUG_ON(string == NULL || strlen(string) >= 32);

    DetectBufferType *map = SCCalloc(1, sizeof(*map));
    if (map == NULL)
        return -1;

    strlcpy(map->name, string, sizeof(map->name));
    map->id = g_buffer_type_id++;

    BUG_ON(HashListTableAdd(g_buffer_type_hash, (void *)map, 0) != 0);
    SCLogDebug("buffer %s registered with id %d", map->name, map->id);
    return map->id;
}

static DetectBufferType *DetectBufferTypeLookupByName(const char *string)
{
    DetectBufferType map;
    memset(&map, 0, sizeof(map));
    strlcpy(map.name, string, sizeof(map.name));

    DetectBufferType *res = HashListTableLookup(g_buffer_type_hash, &map, 0);
    return res;
}

int DetectBufferTypeRegister(const char *name)
{
    BUG_ON(g_buffer_type_reg_closed);
    if (g_buffer_type_hash == NULL)
        DetectBufferTypeInit();

    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
    if (!exists) {
        return DetectBufferTypeAdd(name);
    } else {
        return exists->id;
    }
}

void DetectBufferTypeSupportsMultiInstance(const char *name)
{
    BUG_ON(g_buffer_type_reg_closed);
    DetectBufferTypeRegister(name);
    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
    BUG_ON(!exists);
    exists->multi_instance = true;
    SCLogDebug("%p %s -- %d supports multi instance", exists, name, exists->id);
}

void DetectBufferTypeSupportsFrames(const char *name)
{
    BUG_ON(g_buffer_type_reg_closed);
    DetectBufferTypeRegister(name);
    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
    BUG_ON(!exists);
    exists->frame = true;
    SCLogDebug("%p %s -- %d supports frame inspection", exists, name, exists->id);
}

void DetectBufferTypeSupportsPacket(const char *name)
{
    BUG_ON(g_buffer_type_reg_closed);
    DetectBufferTypeRegister(name);
    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
    BUG_ON(!exists);
    exists->packet = true;
    SCLogDebug("%p %s -- %d supports packet inspection", exists, name, exists->id);
}

void DetectBufferTypeSupportsMpm(const char *name)
{
    BUG_ON(g_buffer_type_reg_closed);
    DetectBufferTypeRegister(name);
    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
    BUG_ON(!exists);
    exists->mpm = true;
    SCLogDebug("%p %s -- %d supports mpm", exists, name, exists->id);
}

void DetectBufferTypeSupportsTransformations(const char *name)
{
    BUG_ON(g_buffer_type_reg_closed);
    DetectBufferTypeRegister(name);
    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
    BUG_ON(!exists);
    exists->supports_transforms = true;
    SCLogDebug("%p %s -- %d supports transformations", exists, name, exists->id);
}

int DetectBufferTypeGetByName(const char *name)
{
    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
    if (!exists) {
        return -1;
    }
    return exists->id;
}

static DetectBufferType *DetectEngineBufferTypeLookupByName(
        const DetectEngineCtx *de_ctx, const char *string)
{
    DetectBufferType map;
    memset(&map, 0, sizeof(map));
    strlcpy(map.name, string, sizeof(map.name));

    DetectBufferType *res = HashListTableLookup(de_ctx->buffer_type_hash_name, &map, 0);
    return res;
}

const DetectBufferType *DetectEngineBufferTypeGetById(const DetectEngineCtx *de_ctx, const int id)
{
    DetectBufferType lookup;
    memset(&lookup, 0, sizeof(lookup));
    lookup.id = id;
    const DetectBufferType *res =
            HashListTableLookup(de_ctx->buffer_type_hash_id, (void *)&lookup, 0);
    return res;
}

const char *DetectEngineBufferTypeGetNameById(const DetectEngineCtx *de_ctx, const int id)
{
    const DetectBufferType *res = DetectEngineBufferTypeGetById(de_ctx, id);
    return res ? res->name : NULL;
}

static int DetectEngineBufferTypeAdd(DetectEngineCtx *de_ctx, const char *string)
{
    BUG_ON(string == NULL || strlen(string) >= 32);

    DetectBufferType *map = SCCalloc(1, sizeof(*map));
    if (map == NULL)
        return -1;

    strlcpy(map->name, string, sizeof(map->name));
    map->id = de_ctx->buffer_type_id++;

    BUG_ON(HashListTableAdd(de_ctx->buffer_type_hash_name, (void *)map, 0) != 0);
    BUG_ON(HashListTableAdd(de_ctx->buffer_type_hash_id, (void *)map, 0) != 0);
    SCLogDebug("buffer %s registered with id %d", map->name, map->id);
    return map->id;
}

int DetectEngineBufferTypeRegisterWithFrameEngines(DetectEngineCtx *de_ctx, const char *name,
        const int direction, const AppProto alproto, const uint8_t frame_type)
{
    DetectBufferType *exists = DetectEngineBufferTypeLookupByName(de_ctx, name);
    if (exists) {
        return exists->id;
    }

    const int buffer_id = DetectEngineBufferTypeAdd(de_ctx, name);
    if (buffer_id < 0) {
        return -1;
    }

    /* TODO hack we need the map to get the name. Should we return the map at reg? */
    const DetectBufferType *map = DetectEngineBufferTypeGetById(de_ctx, buffer_id);
    BUG_ON(!map);

    /* register MPM/inspect engines */
    if (direction & SIG_FLAG_TOSERVER) {
        DetectEngineFrameMpmRegister(de_ctx, map->name, SIG_FLAG_TOSERVER, 2,
                PrefilterGenericMpmFrameRegister, alproto, frame_type);
        DetectEngineFrameInspectEngineRegister(de_ctx, map->name, SIG_FLAG_TOSERVER,
                DetectEngineInspectFrameBufferGeneric, alproto, frame_type);
    }
    if (direction & SIG_FLAG_TOCLIENT) {
        DetectEngineFrameMpmRegister(de_ctx, map->name, SIG_FLAG_TOCLIENT, 2,
                PrefilterGenericMpmFrameRegister, alproto, frame_type);
        DetectEngineFrameInspectEngineRegister(de_ctx, map->name, SIG_FLAG_TOCLIENT,
                DetectEngineInspectFrameBufferGeneric, alproto, frame_type);
    }

    return buffer_id;
}

int DetectEngineBufferTypeRegister(DetectEngineCtx *de_ctx, const char *name)
{
    DetectBufferType *exists = DetectEngineBufferTypeLookupByName(de_ctx, name);
    if (!exists) {
        return DetectEngineBufferTypeAdd(de_ctx, name);
    } else {
        return exists->id;
    }
}

void DetectBufferTypeSetDescriptionByName(const char *name, const char *desc)
{
    BUG_ON(desc == NULL || strlen(desc) >= 128);

    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
    if (!exists) {
        return;
    }
    strlcpy(exists->description, desc, sizeof(exists->description));
}

const char *DetectEngineBufferTypeGetDescriptionById(const DetectEngineCtx *de_ctx, const int id)
{
    const DetectBufferType *exists = DetectEngineBufferTypeGetById(de_ctx, id);
    if (!exists) {
        return NULL;
    }
    return exists->description;
}

const char *DetectBufferTypeGetDescriptionByName(const char *name)
{
    const DetectBufferType *exists = DetectBufferTypeLookupByName(name);
    if (!exists) {
        return NULL;
    }
    return exists->description;
}

void DetectEngineBufferTypeSupportsFrames(DetectEngineCtx *de_ctx, const char *name)
{
    DetectBufferType *exists = DetectEngineBufferTypeLookupByName(de_ctx, name);
    BUG_ON(!exists);
    exists->frame = true;
    SCLogDebug("%p %s -- %d supports frame inspection", exists, name, exists->id);
}

void DetectEngineBufferTypeSupportsPacket(DetectEngineCtx *de_ctx, const char *name)
{
    DetectBufferType *exists = DetectEngineBufferTypeLookupByName(de_ctx, name);
    BUG_ON(!exists);
    exists->packet = true;
    SCLogDebug("%p %s -- %d supports packet inspection", exists, name, exists->id);
}

void DetectEngineBufferTypeSupportsMpm(DetectEngineCtx *de_ctx, const char *name)
{
    DetectBufferType *exists = DetectEngineBufferTypeLookupByName(de_ctx, name);
    BUG_ON(!exists);
    exists->mpm = true;
    SCLogDebug("%p %s -- %d supports mpm", exists, name, exists->id);
}

void DetectEngineBufferTypeSupportsTransformations(DetectEngineCtx *de_ctx, const char *name)
{
    DetectBufferType *exists = DetectEngineBufferTypeLookupByName(de_ctx, name);
    BUG_ON(!exists);
    exists->supports_transforms = true;
    SCLogDebug("%p %s -- %d supports transformations", exists, name, exists->id);
}

bool DetectEngineBufferTypeSupportsMultiInstanceGetById(const DetectEngineCtx *de_ctx, const int id)
{
    const DetectBufferType *map = DetectEngineBufferTypeGetById(de_ctx, id);
    if (map == NULL)
        return false;
    SCLogDebug("map %p id %d multi_instance? %s", map, id, BOOL2STR(map->multi_instance));
    return map->multi_instance;
}

bool DetectEngineBufferTypeSupportsPacketGetById(const DetectEngineCtx *de_ctx, const int id)
{
    const DetectBufferType *map = DetectEngineBufferTypeGetById(de_ctx, id);
    if (map == NULL)
        return false;
    SCLogDebug("map %p id %d packet? %d", map, id, map->packet);
    return map->packet;
}

bool DetectEngineBufferTypeSupportsMpmGetById(const DetectEngineCtx *de_ctx, const int id)
{
    const DetectBufferType *map = DetectEngineBufferTypeGetById(de_ctx, id);
    if (map == NULL)
        return false;
    SCLogDebug("map %p id %d mpm? %d", map, id, map->mpm);
    return map->mpm;
}

bool DetectEngineBufferTypeSupportsFramesGetById(const DetectEngineCtx *de_ctx, const int id)
{
    const DetectBufferType *map = DetectEngineBufferTypeGetById(de_ctx, id);
    if (map == NULL)
        return false;
    SCLogDebug("map %p id %d frame? %d", map, id, map->frame);
    return map->frame;
}

void DetectBufferTypeRegisterSetupCallback(const char *name,
        void (*SetupCallback)(const DetectEngineCtx *, Signature *))
{
    BUG_ON(g_buffer_type_reg_closed);
    DetectBufferTypeRegister(name);
    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
    BUG_ON(!exists);
    exists->SetupCallback = SetupCallback;
}

void DetectEngineBufferRunSetupCallback(const DetectEngineCtx *de_ctx, const int id, Signature *s)
{
    const DetectBufferType *map = DetectEngineBufferTypeGetById(de_ctx, id);
    if (map && map->SetupCallback) {
        map->SetupCallback(de_ctx, s);
    }
}

void DetectBufferTypeRegisterValidateCallback(const char *name,
        bool (*ValidateCallback)(const Signature *, const char **sigerror))
{
    BUG_ON(g_buffer_type_reg_closed);
    DetectBufferTypeRegister(name);
    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
    BUG_ON(!exists);
    exists->ValidateCallback = ValidateCallback;
}

bool DetectEngineBufferRunValidateCallback(
        const DetectEngineCtx *de_ctx, const int id, const Signature *s, const char **sigerror)
{
    const DetectBufferType *map = DetectEngineBufferTypeGetById(de_ctx, id);
    if (map && map->ValidateCallback) {
        return map->ValidateCallback(s, sigerror);
    }
    return true;
}

SigMatch *DetectBufferGetFirstSigMatch(const Signature *s, const uint32_t buf_id)
{
    for (uint32_t i = 0; i < s->init_data->buffer_index; i++) {
        if (buf_id == s->init_data->buffers[i].id) {
            return s->init_data->buffers[i].head;
        }
    }
    return NULL;
}

SigMatch *DetectBufferGetLastSigMatch(const Signature *s, const uint32_t buf_id)
{
    SigMatch *last = NULL;
    for (uint32_t i = 0; i < s->init_data->buffer_index; i++) {
        if (buf_id == s->init_data->buffers[i].id) {
            last = s->init_data->buffers[i].tail;
        }
    }
    return last;
}

bool DetectBufferIsPresent(const Signature *s, const uint32_t buf_id)
{
    for (uint32_t i = 0; i < s->init_data->buffer_index; i++) {
        if (buf_id == s->init_data->buffers[i].id) {
            return true;
        }
    }
    return false;
}

int DetectBufferSetActiveList(DetectEngineCtx *de_ctx, Signature *s, const int list)
{
    BUG_ON(s->init_data == NULL);

    if (s->init_data->list == DETECT_SM_LIST_BASE64_DATA) {
        SCLogError("Rule buffer cannot be reset after base64_data.");
        return -1;
    }

    if (s->init_data->list && s->init_data->transforms.cnt) {
        SCLogError("no matches following transform(s)");
        return -1;
    }
    s->init_data->list = list;
    s->init_data->list_set = true;

    // check if last has matches -> if no, error
    if (s->init_data->curbuf && s->init_data->curbuf->head == NULL) {
        SCLogError("previous sticky buffer has no matches");
        return -1;
    }

    for (uint32_t x = 0; x < s->init_data->buffers_size; x++) {
        SignatureInitDataBuffer *b = &s->init_data->buffers[x];
        for (SigMatch *sm = b->head; sm != NULL; sm = sm->next) {
            SCLogDebug(
                    "buf:%p: id:%u: '%s' pos %u", b, b->id, sigmatch_table[sm->type].name, sm->idx);
        }
        if ((uint32_t)list == b->id) {
            SCLogDebug("found buffer %p for list %d", b, list);
            if (s->init_data->buffers[x].sm_init) {
                s->init_data->buffers[x].sm_init = false;
                SCLogDebug("sm_init was true for %p list %d", b, list);
                s->init_data->curbuf = b;
                return 0;

            } else if (DetectEngineBufferTypeSupportsMultiInstanceGetById(de_ctx, list)) {
                // fall through
            } else {
                SCLogWarning("duplicate instance for %s in '%s'",
                        DetectEngineBufferTypeGetNameById(de_ctx, list), s->sig_str);
                s->init_data->curbuf = b;
                return 0;
            }
        }
    }

    if (list < DETECT_SM_LIST_MAX)
        return 0;

    if (SignatureInitDataBufferCheckExpand(s) < 0) {
        SCLogError("failed to expand rule buffer array");
        return -1;
    }

    /* initialize new buffer */
    s->init_data->curbuf = &s->init_data->buffers[s->init_data->buffer_index++];
    s->init_data->curbuf->id = list;
    s->init_data->curbuf->head = NULL;
    s->init_data->curbuf->tail = NULL;
    s->init_data->curbuf->multi_capable =
            DetectEngineBufferTypeSupportsMultiInstanceGetById(de_ctx, list);
    SCLogDebug("new: idx %u list %d set up curbuf %p", s->init_data->buffer_index - 1, list,
            s->init_data->curbuf);

    return 0;
}

int DetectBufferGetActiveList(DetectEngineCtx *de_ctx, Signature *s)
{
    BUG_ON(s->init_data == NULL);

    if (s->init_data->list && s->init_data->transforms.cnt) {
        if (s->init_data->list == DETECT_SM_LIST_NOTSET ||
            s->init_data->list < DETECT_SM_LIST_DYNAMIC_START) {
            SCLogError("previous transforms not consumed "
                       "(list: %u, transform_cnt %u)",
                    s->init_data->list, s->init_data->transforms.cnt);
            SCReturnInt(-1);
        }

        SCLogDebug("buffer %d has transform(s) registered: %d",
                s->init_data->list, s->init_data->transforms.cnt);
        int new_list = DetectEngineBufferTypeGetByIdTransforms(de_ctx, s->init_data->list,
                s->init_data->transforms.transforms, s->init_data->transforms.cnt);
        if (new_list == -1) {
            SCReturnInt(-1);
        }
        int base_list = s->init_data->list;
        SCLogDebug("new_list %d", new_list);
        s->init_data->list = new_list;
        s->init_data->list_set = false;
        // reset transforms now that we've set up the list
        s->init_data->transforms.cnt = 0;

        if (s->init_data->curbuf && s->init_data->curbuf->head != NULL) {
            if (SignatureInitDataBufferCheckExpand(s) < 0) {
                SCLogError("failed to expand rule buffer array");
                return -1;
            }
            s->init_data->curbuf = &s->init_data->buffers[s->init_data->buffer_index++];
            s->init_data->curbuf->multi_capable =
                    DetectEngineBufferTypeSupportsMultiInstanceGetById(de_ctx, base_list);
        }
        if (s->init_data->curbuf == NULL) {
            SCLogError("failed to setup buffer");
            DEBUG_VALIDATE_BUG_ON(1);
            SCReturnInt(-1);
        }
        s->init_data->curbuf->id = new_list;
        SCLogDebug("new list after applying transforms: %u", new_list);
    }

    SCReturnInt(0);
}

void InspectionBufferClean(DetectEngineThreadCtx *det_ctx)
{
    /* single buffers */
    for (uint32_t i = 0; i < det_ctx->inspect.to_clear_idx; i++)
    {
        const uint32_t idx = det_ctx->inspect.to_clear_queue[i];
        InspectionBuffer *buffer = &det_ctx->inspect.buffers[idx];
        buffer->inspect = NULL;
        buffer->initialized = false;
    }
    det_ctx->inspect.to_clear_idx = 0;

    /* multi buffers */
    for (uint32_t i = 0; i < det_ctx->multi_inspect.to_clear_idx; i++)
    {
        const uint32_t idx = det_ctx->multi_inspect.to_clear_queue[i];
        InspectionBufferMultipleForList *mbuffer = &det_ctx->multi_inspect.buffers[idx];
        for (uint32_t x = 0; x <= mbuffer->max; x++) {
            InspectionBuffer *buffer = &mbuffer->inspection_buffers[x];
            buffer->inspect = NULL;
            buffer->initialized = false;
        }
        mbuffer->init = 0;
        mbuffer->max = 0;
    }
    det_ctx->multi_inspect.to_clear_idx = 0;
}

InspectionBuffer *InspectionBufferGet(DetectEngineThreadCtx *det_ctx, const int list_id)
{
    return &det_ctx->inspect.buffers[list_id];
}

static InspectionBufferMultipleForList *InspectionBufferGetMulti(
        DetectEngineThreadCtx *det_ctx, const int list_id)
{
    InspectionBufferMultipleForList *buffer = &det_ctx->multi_inspect.buffers[list_id];
    if (!buffer->init) {
        det_ctx->multi_inspect.to_clear_queue[det_ctx->multi_inspect.to_clear_idx++] = list_id;
        buffer->init = 1;
    }
    return buffer;
}

/** \brief for a InspectionBufferMultipleForList get a InspectionBuffer
 *  \param fb the multiple buffer array
 *  \param local_id the index to get a buffer
 *  \param buffer the inspect buffer or NULL in case of error */
InspectionBuffer *InspectionBufferMultipleForListGet(
        DetectEngineThreadCtx *det_ctx, const int list_id, const uint32_t local_id)
{
    if (unlikely(local_id >= 1024)) {
        DetectEngineSetEvent(det_ctx, DETECT_EVENT_TOO_MANY_BUFFERS);
        return NULL;
    }

    InspectionBufferMultipleForList *fb = InspectionBufferGetMulti(det_ctx, list_id);

    if (local_id >= fb->size) {
        uint32_t old_size = fb->size;
        uint32_t new_size = local_id + 1;
        uint32_t grow_by = new_size - old_size;
        SCLogDebug("size is %u, need %u, so growing by %u", old_size, new_size, grow_by);

        SCLogDebug("fb->inspection_buffers %p", fb->inspection_buffers);
        void *ptr = SCRealloc(fb->inspection_buffers, (local_id + 1) * sizeof(InspectionBuffer));
        if (ptr == NULL)
            return NULL;

        InspectionBuffer *to_zero = (InspectionBuffer *)ptr + old_size;
        SCLogDebug("ptr %p to_zero %p", ptr, to_zero);
        memset((uint8_t *)to_zero, 0, (grow_by * sizeof(InspectionBuffer)));
        fb->inspection_buffers = ptr;
        fb->size = new_size;
    }

    fb->max = MAX(fb->max, local_id);
    InspectionBuffer *buffer = &fb->inspection_buffers[local_id];
    SCLogDebug("using buffer %p", buffer);
#ifdef DEBUG_VALIDATION
    buffer->multi = true;
#endif
    return buffer;
}

void InspectionBufferInit(InspectionBuffer *buffer, uint32_t initial_size)
{
    memset(buffer, 0, sizeof(*buffer));
    buffer->buf = SCCalloc(initial_size, sizeof(uint8_t));
    if (buffer->buf != NULL) {
        buffer->size = initial_size;
    }
}

/** \brief setup the buffer empty */
void InspectionBufferSetupMultiEmpty(InspectionBuffer *buffer)
{
#ifdef DEBUG_VALIDATION
    DEBUG_VALIDATE_BUG_ON(buffer->initialized);
    DEBUG_VALIDATE_BUG_ON(!buffer->multi);
#endif
    buffer->inspect = NULL;
    buffer->inspect_len = 0;
    buffer->len = 0;
    buffer->initialized = true;
}

/** \brief setup the buffer with our initial data */
void InspectionBufferSetupMulti(InspectionBuffer *buffer, const DetectEngineTransforms *transforms,
        const uint8_t *data, const uint32_t data_len)
{
#ifdef DEBUG_VALIDATION
    DEBUG_VALIDATE_BUG_ON(!buffer->multi);
#endif
    buffer->inspect = buffer->orig = data;
    buffer->inspect_len = buffer->orig_len = data_len;
    buffer->len = 0;
    buffer->initialized = true;

    InspectionBufferApplyTransforms(buffer, transforms);
}

/** \brief setup the buffer with our initial data */
void InspectionBufferSetup(DetectEngineThreadCtx *det_ctx, const int list_id,
        InspectionBuffer *buffer, const uint8_t *data, const uint32_t data_len)
{
#ifdef DEBUG_VALIDATION
    DEBUG_VALIDATE_BUG_ON(buffer->multi);
    DEBUG_VALIDATE_BUG_ON(buffer != InspectionBufferGet(det_ctx, list_id));
#endif
    if (buffer->inspect == NULL) {
#ifdef UNITTESTS
        if (det_ctx && list_id != -1)
#endif
            det_ctx->inspect.to_clear_queue[det_ctx->inspect.to_clear_idx++] = list_id;
    }
    buffer->inspect = buffer->orig = data;
    buffer->inspect_len = buffer->orig_len = data_len;
    buffer->len = 0;
    buffer->initialized = true;
}

void InspectionBufferFree(InspectionBuffer *buffer)
{
    if (buffer->buf != NULL) {
        SCFree(buffer->buf);
    }
    memset(buffer, 0, sizeof(*buffer));
}

/**
 * \brief make sure that the buffer has at least 'min_size' bytes
 * Expand the buffer if necessary
 */
void InspectionBufferCheckAndExpand(InspectionBuffer *buffer, uint32_t min_size)
{
    if (likely(buffer->size >= min_size))
        return;

    uint32_t new_size = (buffer->size == 0) ? 4096 : buffer->size;
    while (new_size < min_size) {
        new_size *= 2;
    }

    void *ptr = SCRealloc(buffer->buf, new_size);
    if (ptr != NULL) {
        buffer->buf = ptr;
        buffer->size = new_size;
    }
}

void InspectionBufferCopy(InspectionBuffer *buffer, uint8_t *buf, uint32_t buf_len)
{
    InspectionBufferCheckAndExpand(buffer, buf_len);

    if (buffer->size) {
        uint32_t copy_size = MIN(buf_len, buffer->size);
        memcpy(buffer->buf, buf, copy_size);
        buffer->inspect = buffer->buf;
        buffer->inspect_len = copy_size;
        buffer->initialized = true;
    }
}

/** \brief Check content byte array compatibility with transforms
 *
 *  The "content" array is presented to the transforms so that each
 *  transform may validate that it's compatible with the transform.
 *
 *  When a transform indicates the byte array is incompatible, none of the
 *  subsequent transforms, if any, are invoked. This means the first validation
 *  failure terminates the loop.
 *
 *  \param de_ctx Detection engine context.
 *  \param sm_list The SM list id.
 *  \param content The byte array being validated
 *  \param namestr returns the name of the transform that is incompatible with
 *  content.
 *
 *  \retval true (false) If any of the transforms indicate the byte array is
 *  (is not) compatible.
 **/
bool DetectEngineBufferTypeValidateTransform(DetectEngineCtx *de_ctx, int sm_list,
        const uint8_t *content, uint16_t content_len, const char **namestr)
{
    const DetectBufferType *dbt = DetectEngineBufferTypeGetById(de_ctx, sm_list);
    BUG_ON(dbt == NULL);

    for (int i = 0; i < dbt->transforms.cnt; i++) {
        const TransformData *t = &dbt->transforms.transforms[i];
        if (!sigmatch_table[t->transform].TransformValidate)
            continue;

        if (sigmatch_table[t->transform].TransformValidate(content, content_len, t->options)) {
            continue;
        }

        if (namestr) {
            *namestr = sigmatch_table[t->transform].name;
        }

        return false;
    }

    return true;
}

void InspectionBufferApplyTransforms(InspectionBuffer *buffer,
        const DetectEngineTransforms *transforms)
{
    if (transforms) {
        for (int i = 0; i < DETECT_TRANSFORMS_MAX; i++) {
            const int id = transforms->transforms[i].transform;
            if (id == 0)
                break;
            BUG_ON(sigmatch_table[id].Transform == NULL);
            sigmatch_table[id].Transform(buffer, transforms->transforms[i].options);
            SCLogDebug("applied transform %s", sigmatch_table[id].name);
        }
    }
}

static void DetectBufferTypeSetupDetectEngine(DetectEngineCtx *de_ctx)
{
    const int size = g_buffer_type_id;
    BUG_ON(!(size > 0));

    de_ctx->buffer_type_hash_name = HashListTableInit(256, DetectBufferTypeHashNameFunc,
            DetectBufferTypeCompareNameFunc, DetectBufferTypeFreeFunc);
    BUG_ON(de_ctx->buffer_type_hash_name == NULL);
    de_ctx->buffer_type_hash_id =
            HashListTableInit(256, DetectBufferTypeHashIdFunc, DetectBufferTypeCompareIdFunc,
                    NULL); // entries owned by buffer_type_hash_name
    BUG_ON(de_ctx->buffer_type_hash_id == NULL);
    de_ctx->buffer_type_id = g_buffer_type_id;

    SCLogDebug("DETECT_SM_LIST_DYNAMIC_START %u", DETECT_SM_LIST_DYNAMIC_START);
    HashListTableBucket *b = HashListTableGetListHead(g_buffer_type_hash);
    while (b) {
        DetectBufferType *map = HashListTableGetListData(b);

        DetectBufferType *copy = SCCalloc(1, sizeof(*copy));
        BUG_ON(!copy);
        memcpy(copy, map, sizeof(*copy));
        int r = HashListTableAdd(de_ctx->buffer_type_hash_name, (void *)copy, 0);
        BUG_ON(r != 0);
        r = HashListTableAdd(de_ctx->buffer_type_hash_id, (void *)copy, 0);
        BUG_ON(r != 0);

        SCLogDebug("name %s id %d mpm %s packet %s -- %s. "
                   "Callbacks: Setup %p Validate %p",
                map->name, map->id, map->mpm ? "true" : "false", map->packet ? "true" : "false",
                map->description, map->SetupCallback, map->ValidateCallback);
        b = HashListTableGetListNext(b);
    }

    PrefilterInit(de_ctx);
    DetectMpmInitializeAppMpms(de_ctx);
    DetectAppLayerInspectEngineCopyListToDetectCtx(de_ctx);
    DetectMpmInitializeFrameMpms(de_ctx);
    DetectFrameInspectEngineCopyListToDetectCtx(de_ctx);
    DetectMpmInitializePktMpms(de_ctx);
    DetectPktInspectEngineCopyListToDetectCtx(de_ctx);
}

static void DetectBufferTypeFreeDetectEngine(DetectEngineCtx *de_ctx)
{
    if (de_ctx) {
        if (de_ctx->buffer_type_hash_name)
            HashListTableFree(de_ctx->buffer_type_hash_name);
        if (de_ctx->buffer_type_hash_id)
            HashListTableFree(de_ctx->buffer_type_hash_id);

        DetectEngineAppInspectionEngine *ilist = de_ctx->app_inspect_engines;
        while (ilist) {
            DetectEngineAppInspectionEngine *next = ilist->next;
            SCFree(ilist);
            ilist = next;
        }
        DetectBufferMpmRegistry *mlist = de_ctx->app_mpms_list;
        while (mlist) {
            DetectBufferMpmRegistry *next = mlist->next;
            SCFree(mlist);
            mlist = next;
        }
        DetectEnginePktInspectionEngine *plist = de_ctx->pkt_inspect_engines;
        while (plist) {
            DetectEnginePktInspectionEngine *next = plist->next;
            SCFree(plist);
            plist = next;
        }
        DetectBufferMpmRegistry *pmlist = de_ctx->pkt_mpms_list;
        while (pmlist) {
            DetectBufferMpmRegistry *next = pmlist->next;
            SCFree(pmlist);
            pmlist = next;
        }
        DetectEngineFrameInspectionEngine *framelist = de_ctx->frame_inspect_engines;
        while (framelist) {
            DetectEngineFrameInspectionEngine *next = framelist->next;
            SCFree(framelist);
            framelist = next;
        }
        DetectBufferMpmRegistry *framemlist = de_ctx->frame_mpms_list;
        while (framemlist) {
            DetectBufferMpmRegistry *next = framemlist->next;
            SCFree(framemlist);
            framemlist = next;
        }
        PrefilterDeinit(de_ctx);
    }
}

void DetectBufferTypeCloseRegistration(void)
{
    BUG_ON(g_buffer_type_hash == NULL);

    g_buffer_type_reg_closed = 1;
}

int DetectEngineBufferTypeGetByIdTransforms(
        DetectEngineCtx *de_ctx, const int id, TransformData *transforms, int transform_cnt)
{
    const DetectBufferType *base_map = DetectEngineBufferTypeGetById(de_ctx, id);
    if (!base_map) {
        return -1;
    }
    if (!base_map->supports_transforms) {
        SCLogError("buffer '%s' does not support transformations", base_map->name);
        return -1;
    }

    SCLogDebug("base_map %s", base_map->name);

    DetectEngineTransforms t;
    memset(&t, 0, sizeof(t));
    for (int i = 0; i < transform_cnt; i++) {
        t.transforms[i] = transforms[i];
    }
    t.cnt = transform_cnt;

    DetectBufferType lookup_map;
    memset(&lookup_map, 0, sizeof(lookup_map));
    strlcpy(lookup_map.name, base_map->name, sizeof(lookup_map.name));
    lookup_map.transforms = t;
    DetectBufferType *res = HashListTableLookup(de_ctx->buffer_type_hash_name, &lookup_map, 0);

    SCLogDebug("res %p", res);
    if (res != NULL) {
        return res->id;
    }

    DetectBufferType *map = SCCalloc(1, sizeof(*map));
    if (map == NULL)
        return -1;

    strlcpy(map->name, base_map->name, sizeof(map->name));
    map->id = de_ctx->buffer_type_id++;
    map->parent_id = base_map->id;
    map->transforms = t;
    map->mpm = base_map->mpm;
    map->packet = base_map->packet;
    map->frame = base_map->frame;
    map->SetupCallback = base_map->SetupCallback;
    map->ValidateCallback = base_map->ValidateCallback;
    if (map->frame) {
        DetectFrameMpmRegisterByParentId(de_ctx, map->id, map->parent_id, &map->transforms);
    } else if (map->packet) {
        DetectPktMpmRegisterByParentId(de_ctx,
                map->id, map->parent_id, &map->transforms);
    } else {
        DetectAppLayerMpmRegisterByParentId(de_ctx,
                map->id, map->parent_id, &map->transforms);
    }

    BUG_ON(HashListTableAdd(de_ctx->buffer_type_hash_name, (void *)map, 0) != 0);
    BUG_ON(HashListTableAdd(de_ctx->buffer_type_hash_id, (void *)map, 0) != 0);
    SCLogDebug("buffer %s registered with id %d, parent %d", map->name, map->id, map->parent_id);

    if (map->frame) {
        DetectFrameInspectEngineCopy(de_ctx, map->parent_id, map->id, &map->transforms);
    } else if (map->packet) {
        DetectPktInspectEngineCopy(de_ctx, map->parent_id, map->id, &map->transforms);
    } else {
        DetectAppLayerInspectEngineCopy(de_ctx, map->parent_id, map->id, &map->transforms);
    }
    return map->id;
}

/* returns false if no match, true if match */
static int DetectEngineInspectRulePacketMatches(
    DetectEngineThreadCtx *det_ctx,
    const DetectEnginePktInspectionEngine *engine,
    const Signature *s,
    Packet *p, uint8_t *_alert_flags)
{
    SCEnter();

    /* run the packet match functions */
    KEYWORD_PROFILING_SET_LIST(det_ctx, DETECT_SM_LIST_MATCH);
    const SigMatchData *smd = s->sm_arrays[DETECT_SM_LIST_MATCH];

    SCLogDebug("running match functions, sm %p", smd);
    while (1) {
        KEYWORD_PROFILING_START;
        if (sigmatch_table[smd->type].Match(det_ctx, p, s, smd->ctx) <= 0) {
            KEYWORD_PROFILING_END(det_ctx, smd->type, 0);
            SCLogDebug("no match");
            return false;
        }
        KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
        if (smd->is_last) {
            SCLogDebug("match and is_last");
            break;
        }
        smd++;
    }
    return true;
}

static int DetectEngineInspectRulePayloadMatches(
     DetectEngineThreadCtx *det_ctx,
     const DetectEnginePktInspectionEngine *engine,
     const Signature *s, Packet *p, uint8_t *alert_flags)
{
    SCEnter();

    DetectEngineCtx *de_ctx = det_ctx->de_ctx;

    KEYWORD_PROFILING_SET_LIST(det_ctx, DETECT_SM_LIST_PMATCH);
    /* if we have stream msgs, inspect against those first,
     * but not for a "dsize" signature */
    if (s->flags & SIG_FLAG_REQUIRE_STREAM) {
        int pmatch = 0;
        if (p->flags & PKT_DETECT_HAS_STREAMDATA) {
            pmatch = DetectEngineInspectStreamPayload(de_ctx, det_ctx, s, p->flow, p);
            if (pmatch) {
                det_ctx->flags |= DETECT_ENGINE_THREAD_CTX_STREAM_CONTENT_MATCH;
                *alert_flags |= PACKET_ALERT_FLAG_STREAM_MATCH;
            }
        }
        /* no match? then inspect packet payload */
        if (pmatch == 0) {
            SCLogDebug("no match in stream, fall back to packet payload");

            /* skip if we don't have to inspect the packet and segment was
             * added to stream */
            if (!(s->flags & SIG_FLAG_REQUIRE_PACKET) && (p->flags & PKT_STREAM_ADD)) {
                return false;
            }
            if (DetectEngineInspectPacketPayload(de_ctx, det_ctx, s, p->flow, p) != 1) {
                return false;
            }
        }
    } else {
        if (DetectEngineInspectPacketPayload(de_ctx, det_ctx, s, p->flow, p) != 1) {
            return false;
        }
    }
    return true;
}

bool DetectEnginePktInspectionRun(ThreadVars *tv,
        DetectEngineThreadCtx *det_ctx, const Signature *s,
        Flow *f, Packet *p,
        uint8_t *alert_flags)
{
    SCEnter();

    for (DetectEnginePktInspectionEngine *e = s->pkt_inspect; e != NULL; e = e->next) {
        if (e->v1.Callback(det_ctx, e, s, p, alert_flags) == false) {
            SCLogDebug("sid %u: e %p Callback returned false", s->id, e);
            return false;
        }
        SCLogDebug("sid %u: e %p Callback returned true", s->id, e);
    }

    SCLogDebug("sid %u: returning true", s->id);
    return true;
}

/**
 * \param data pointer to SigMatchData. Allowed to be NULL.
 */
static int DetectEnginePktInspectionAppend(Signature *s, InspectionBufferPktInspectFunc Callback,
        SigMatchData *data, const int list_id)
{
    DetectEnginePktInspectionEngine *e = SCCalloc(1, sizeof(*e));
    if (e == NULL)
        return -1;

    e->mpm = s->init_data->mpm_sm_list == list_id;
    DEBUG_VALIDATE_BUG_ON(list_id < 0 || list_id > UINT16_MAX);
    e->sm_list = (uint16_t)list_id;
    e->sm_list_base = (uint16_t)list_id;
    e->v1.Callback = Callback;
    e->smd = data;

    if (s->pkt_inspect == NULL) {
        s->pkt_inspect = e;
    } else {
        DetectEnginePktInspectionEngine *a = s->pkt_inspect;
        while (a->next != NULL) {
            a = a->next;
        }
        a->next = e;
    }
    return 0;
}

int DetectEnginePktInspectionSetup(Signature *s)
{
    /* only handle PMATCH here if we're not an app inspect rule */
    if (s->sm_arrays[DETECT_SM_LIST_PMATCH] && (s->init_data->init_flags & SIG_FLAG_INIT_STATE_MATCH) == 0) {
        if (DetectEnginePktInspectionAppend(
                    s, DetectEngineInspectRulePayloadMatches, NULL, DETECT_SM_LIST_PMATCH) < 0)
            return -1;
        SCLogDebug("sid %u: DetectEngineInspectRulePayloadMatches appended", s->id);
    }

    if (s->sm_arrays[DETECT_SM_LIST_MATCH]) {
        if (DetectEnginePktInspectionAppend(
                    s, DetectEngineInspectRulePacketMatches, NULL, DETECT_SM_LIST_MATCH) < 0)
            return -1;
        SCLogDebug("sid %u: DetectEngineInspectRulePacketMatches appended", s->id);
    }

    return 0;
}

/* code to control the main thread to do a reload */

enum DetectEngineSyncState {
    IDLE,   /**< ready to start a reload */
    RELOAD, /**< command main thread to do the reload */
};


typedef struct DetectEngineSyncer_ {
    SCMutex m;
    enum DetectEngineSyncState state;
} DetectEngineSyncer;

static DetectEngineSyncer detect_sync = { SCMUTEX_INITIALIZER, IDLE };

/* tell main to start reloading */
int DetectEngineReloadStart(void)
{
    int r = 0;
    SCMutexLock(&detect_sync.m);
    if (detect_sync.state == IDLE) {
        detect_sync.state = RELOAD;
    } else {
        r = -1;
    }
    SCMutexUnlock(&detect_sync.m);
    return r;
}

/* main thread checks this to see if it should start */
int DetectEngineReloadIsStart(void)
{
    int r = 0;
    SCMutexLock(&detect_sync.m);
    if (detect_sync.state == RELOAD) {
        r = 1;
    }
    SCMutexUnlock(&detect_sync.m);
    return r;
}

/* main thread sets done when it's done */
void DetectEngineReloadSetIdle(void)
{
    SCMutexLock(&detect_sync.m);
    detect_sync.state = IDLE;
    SCMutexUnlock(&detect_sync.m);
}

/* caller loops this until it returns 1 */
int DetectEngineReloadIsIdle(void)
{
    int r = 0;
    SCMutexLock(&detect_sync.m);
    if (detect_sync.state == IDLE) {
        r = 1;
    }
    SCMutexUnlock(&detect_sync.m);
    return r;
}

/** \brief Do the content inspection & validation for a signature
 *
 *  \param de_ctx Detection engine context
 *  \param det_ctx Detection engine thread context
 *  \param s Signature to inspect
 *  \param sm SigMatch to inspect
 *  \param f Flow
 *  \param flags app layer flags
 *  \param state App layer state
 *
 *  \retval 0 no match
 *  \retval 1 match
 */
uint8_t DetectEngineInspectGenericList(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
        const struct DetectEngineAppInspectionEngine_ *engine, const Signature *s, Flow *f,
        uint8_t flags, void *alstate, void *txv, uint64_t tx_id)
{
    SigMatchData *smd = engine->smd;
    SCLogDebug("running match functions, sm %p", smd);
    if (smd != NULL) {
        while (1) {
            int match = 0;
            KEYWORD_PROFILING_START;
            match = sigmatch_table[smd->type].
                AppLayerTxMatch(det_ctx, f, flags, alstate, txv, s, smd->ctx);
            KEYWORD_PROFILING_END(det_ctx, smd->type, (match == 1));
            if (match == 0)
                return DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
            if (match == 2) {
                return DETECT_ENGINE_INSPECT_SIG_CANT_MATCH;
            }

            if (smd->is_last)
                break;
            smd++;
        }
    }

    return DETECT_ENGINE_INSPECT_SIG_MATCH;
}


/**
 * \brief Do the content inspection & validation for a signature
 *
 * \param de_ctx Detection engine context
 * \param det_ctx Detection engine thread context
 * \param s Signature to inspect
 * \param f Flow
 * \param flags app layer flags
 * \param state App layer state
 *
 * \retval 0 no match.
 * \retval 1 match.
 * \retval 2 Sig can't match.
 */
uint8_t DetectEngineInspectBufferGeneric(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
        const DetectEngineAppInspectionEngine *engine, const Signature *s, Flow *f, uint8_t flags,
        void *alstate, void *txv, uint64_t tx_id)
{
    const int list_id = engine->sm_list;
    SCLogDebug("running inspect on %d", list_id);

    const bool eof = (AppLayerParserGetStateProgress(f->proto, f->alproto, txv, flags) > engine->progress);

    SCLogDebug("list %d mpm? %s transforms %p",
            engine->sm_list, engine->mpm ? "true" : "false", engine->v2.transforms);

    /* if prefilter didn't already run, we need to consider transformations */
    const DetectEngineTransforms *transforms = NULL;
    if (!engine->mpm) {
        transforms = engine->v2.transforms;
    }

    const InspectionBuffer *buffer = engine->v2.GetData(det_ctx, transforms,
            f, flags, txv, list_id);
    if (unlikely(buffer == NULL)) {
        return eof ? DETECT_ENGINE_INSPECT_SIG_CANT_MATCH :
                     DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
    }

    const uint32_t data_len = buffer->inspect_len;
    const uint8_t *data = buffer->inspect;
    const uint64_t offset = buffer->inspect_offset;

    uint8_t ci_flags = eof ? DETECT_CI_FLAGS_END : 0;
    ci_flags |= (offset == 0 ? DETECT_CI_FLAGS_START : 0);
    ci_flags |= buffer->flags;

    det_ctx->discontinue_matching = 0;
    det_ctx->buffer_offset = 0;
    det_ctx->inspection_recursion_counter = 0;

    /* Inspect all the uricontents fetched on each
     * transaction at the app layer */
    int r = DetectEngineContentInspection(de_ctx, det_ctx,
                                          s, engine->smd,
                                          NULL, f,
                                          (uint8_t *)data, data_len, offset, ci_flags,
                                          DETECT_ENGINE_CONTENT_INSPECTION_MODE_STATE);
    if (r == 1) {
        return DETECT_ENGINE_INSPECT_SIG_MATCH;
    } else {
        return eof ? DETECT_ENGINE_INSPECT_SIG_CANT_MATCH :
                     DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
    }
}

/**
 * \brief Do the content inspection & validation for a signature
 *
 * \param de_ctx Detection engine context
 * \param det_ctx Detection engine thread context
 * \param s Signature to inspect
 * \param p Packet
 *
 * \retval 0 no match.
 * \retval 1 match.
 */
int DetectEngineInspectPktBufferGeneric(
        DetectEngineThreadCtx *det_ctx,
        const DetectEnginePktInspectionEngine *engine,
        const Signature *s, Packet *p, uint8_t *_alert_flags)
{
    const int list_id = engine->sm_list;
    SCLogDebug("running inspect on %d", list_id);

    SCLogDebug("list %d transforms %p",
            engine->sm_list, engine->v1.transforms);

    /* if prefilter didn't already run, we need to consider transformations */
    const DetectEngineTransforms *transforms = NULL;
    if (!engine->mpm) {
        transforms = engine->v1.transforms;
    }

    const InspectionBuffer *buffer = engine->v1.GetData(det_ctx, transforms, p,
            list_id);
    if (unlikely(buffer == NULL)) {
        return DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
    }

    const uint32_t data_len = buffer->inspect_len;
    const uint8_t *data = buffer->inspect;
    const uint64_t offset = 0;

    uint8_t ci_flags = DETECT_CI_FLAGS_START|DETECT_CI_FLAGS_END;
    ci_flags |= buffer->flags;

    det_ctx->discontinue_matching = 0;
    det_ctx->buffer_offset = 0;
    det_ctx->inspection_recursion_counter = 0;

    /* Inspect all the uricontents fetched on each
     * transaction at the app layer */
    int r = DetectEngineContentInspection(det_ctx->de_ctx, det_ctx,
                                          s, engine->smd,
                                          p, p->flow,
                                          (uint8_t *)data, data_len, offset, ci_flags,
                                          DETECT_ENGINE_CONTENT_INSPECTION_MODE_HEADER);
    if (r == 1) {
        return DETECT_ENGINE_INSPECT_SIG_MATCH;
    } else {
        return DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
    }
}

/** \internal
 *  \brief inject a pseudo packet into each detect thread that doesn't use the
 *         new det_ctx yet
 */
static void InjectPackets(ThreadVars **detect_tvs,
                          DetectEngineThreadCtx **new_det_ctx,
                          int no_of_detect_tvs)
{
    /* inject a fake packet if the detect thread isn't using the new ctx yet,
     * this speeds up the process */
    for (int i = 0; i < no_of_detect_tvs; i++) {
        if (SC_ATOMIC_GET(new_det_ctx[i]->so_far_used_by_detect) != 1) {
            if (detect_tvs[i]->inq != NULL) {
                Packet *p = PacketGetFromAlloc();
                if (p != NULL) {
                    p->flags |= PKT_PSEUDO_STREAM_END;
                    PKT_SET_SRC(p, PKT_SRC_DETECT_RELOAD_FLUSH);
                    PacketQueue *q = detect_tvs[i]->inq->pq;
                    SCMutexLock(&q->mutex_q);
                    PacketEnqueue(q, p);
                    SCCondSignal(&q->cond_q);
                    SCMutexUnlock(&q->mutex_q);
                }
            }
        }
    }
}

/** \internal
 *  \brief Update detect threads with new detect engine
 *
 *  Atomically update each detect thread with a new thread context
 *  that is associated to the new detection engine(s).
 *
 *  If called in unix socket mode, it's possible that we don't have
 *  detect threads yet.
 *
 *  \retval -1 error
 *  \retval 0 no detection threads
 *  \retval 1 successful reload
 */
static int DetectEngineReloadThreads(DetectEngineCtx *new_de_ctx)
{
    SCEnter();
    uint32_t i = 0;

    /* count detect threads in use */
    uint32_t no_of_detect_tvs = TmThreadCountThreadsByTmmFlags(TM_FLAG_DETECT_TM);
    /* can be zero in unix socket mode */
    if (no_of_detect_tvs == 0) {
        return 0;
    }

    /* prepare swap structures */
    DetectEngineThreadCtx *old_det_ctx[no_of_detect_tvs];
    DetectEngineThreadCtx *new_det_ctx[no_of_detect_tvs];
    ThreadVars *detect_tvs[no_of_detect_tvs];
    memset(old_det_ctx, 0x00, (no_of_detect_tvs * sizeof(DetectEngineThreadCtx *)));
    memset(new_det_ctx, 0x00, (no_of_detect_tvs * sizeof(DetectEngineThreadCtx *)));
    memset(detect_tvs, 0x00, (no_of_detect_tvs * sizeof(ThreadVars *)));

    /* start the process of swapping detect threads ctxs */

    /* get reference to tv's and setup new_det_ctx array */
    SCMutexLock(&tv_root_lock);
    for (ThreadVars *tv = tv_root[TVT_PPT]; tv != NULL; tv = tv->next) {
        if ((tv->tmm_flags & TM_FLAG_DETECT_TM) == 0) {
            continue;
        }
        for (TmSlot *s = tv->tm_slots; s != NULL; s = s->slot_next) {
            TmModule *tm = TmModuleGetById(s->tm_id);
            if (!(tm->flags & TM_FLAG_DETECT_TM)) {
                continue;
            }

            if (suricata_ctl_flags != 0) {
                SCMutexUnlock(&tv_root_lock);
                goto error;
            }

            old_det_ctx[i] = FlowWorkerGetDetectCtxPtr(SC_ATOMIC_GET(s->slot_data));
            detect_tvs[i] = tv;

            new_det_ctx[i] = DetectEngineThreadCtxInitForReload(tv, new_de_ctx, 1);
            if (new_det_ctx[i] == NULL) {
                SCLogError("Detect engine thread init "
                           "failure in live rule swap.  Let's get out of here");
                SCMutexUnlock(&tv_root_lock);
                goto error;
            }
            SCLogDebug("live rule swap created new det_ctx - %p and de_ctx "
                       "- %p\n", new_det_ctx[i], new_de_ctx);
            i++;
            break;
        }
    }
    BUG_ON(i != no_of_detect_tvs);

    /* atomically replace the det_ctx data */
    i = 0;
    for (ThreadVars *tv = tv_root[TVT_PPT]; tv != NULL; tv = tv->next) {
        if ((tv->tmm_flags & TM_FLAG_DETECT_TM) == 0) {
            continue;
        }
        for (TmSlot *s = tv->tm_slots; s != NULL; s = s->slot_next) {
            TmModule *tm = TmModuleGetById(s->tm_id);
            if (!(tm->flags & TM_FLAG_DETECT_TM)) {
                continue;
            }
            SCLogDebug("swapping new det_ctx - %p with older one - %p",
                       new_det_ctx[i], SC_ATOMIC_GET(s->slot_data));
            FlowWorkerReplaceDetectCtx(SC_ATOMIC_GET(s->slot_data), new_det_ctx[i++]);
            break;
        }
    }
    SCMutexUnlock(&tv_root_lock);

    /* threads now all have new data, however they may not have started using
     * it and may still use the old data */

    SCLogDebug("Live rule swap has swapped %d old det_ctx's with new ones, "
               "along with the new de_ctx", no_of_detect_tvs);

    InjectPackets(detect_tvs, new_det_ctx, no_of_detect_tvs);

    /* loop waiting for detect threads to switch to the new det_ctx. Try to
     * wake up capture if needed (break loop). */
    uint32_t threads_done = 0;
retry:
    for (i = 0; i < no_of_detect_tvs; i++) {
        if (suricata_ctl_flags != 0) {
            threads_done = no_of_detect_tvs;
            break;
        }
        usleep(1000);
        if (SC_ATOMIC_GET(new_det_ctx[i]->so_far_used_by_detect) == 1) {
            SCLogDebug("new_det_ctx - %p used by detect engine", new_det_ctx[i]);
            threads_done++;
        } else {
            TmThreadsCaptureBreakLoop(detect_tvs[i]);
        }
    }
    if (threads_done < no_of_detect_tvs) {
        threads_done = 0;
        SleepMsec(250);
        goto retry;
    }

    /* this is to make sure that if someone initiated shutdown during a live
     * rule swap, the live rule swap won't clean up the old det_ctx and
     * de_ctx, till all detect threads have stopped working and sitting
     * silently after setting RUNNING_DONE flag and while waiting for
     * THV_DEINIT flag */
    if (i != no_of_detect_tvs) { // not all threads we swapped
        for (ThreadVars *tv = tv_root[TVT_PPT]; tv != NULL; tv = tv->next) {
            if ((tv->tmm_flags & TM_FLAG_DETECT_TM) == 0) {
                continue;
            }

            while (!TmThreadsCheckFlag(tv, THV_RUNNING_DONE)) {
                usleep(100);
            }
        }
    }

    /* free all the ctxs */
    for (i = 0; i < no_of_detect_tvs; i++) {
        SCLogDebug("Freeing old_det_ctx - %p used by detect",
                   old_det_ctx[i]);
        DetectEngineThreadCtxDeinit(NULL, old_det_ctx[i]);
    }

    SRepReloadComplete();

    return 1;

 error:
    for (i = 0; i < no_of_detect_tvs; i++) {
        if (new_det_ctx[i] != NULL)
            DetectEngineThreadCtxDeinit(NULL, new_det_ctx[i]);
    }
    return -1;
}

static DetectEngineCtx *DetectEngineCtxInitReal(enum DetectEngineType type, const char *prefix)
{
    DetectEngineCtx *de_ctx = SCMalloc(sizeof(DetectEngineCtx));
    if (unlikely(de_ctx == NULL))
        goto error;

    memset(de_ctx,0,sizeof(DetectEngineCtx));
    memset(&de_ctx->sig_stat, 0, sizeof(SigFileLoaderStat));
    TAILQ_INIT(&de_ctx->sig_stat.failed_sigs);
    de_ctx->sigerror = NULL;
    de_ctx->type = type;
    de_ctx->filemagic_thread_ctx_id = -1;

    if (type == DETECT_ENGINE_TYPE_DD_STUB || type == DETECT_ENGINE_TYPE_MT_STUB) {
        de_ctx->version = DetectEngineGetVersion();
        SCLogDebug("stub %u with version %u", type, de_ctx->version);
        return de_ctx;
    }

    if (prefix != NULL) {
        strlcpy(de_ctx->config_prefix, prefix, sizeof(de_ctx->config_prefix));
    }

    int failure_fatal = 0;
    if (ConfGetBool("engine.init-failure-fatal", (int *)&failure_fatal) != 1) {
        SCLogDebug("ConfGetBool could not load the value.");
    }
    de_ctx->failure_fatal = (failure_fatal == 1);

    de_ctx->mpm_matcher = PatternMatchDefaultMatcher();
    de_ctx->spm_matcher = SinglePatternMatchDefaultMatcher();
    SCLogConfig("pattern matchers: MPM: %s, SPM: %s",
        mpm_table[de_ctx->mpm_matcher].name,
        spm_table[de_ctx->spm_matcher].name);

    de_ctx->spm_global_thread_ctx = SpmInitGlobalThreadCtx(de_ctx->spm_matcher);
    if (de_ctx->spm_global_thread_ctx == NULL) {
        SCLogDebug("Unable to alloc SpmGlobalThreadCtx.");
        goto error;
    }

    if (DetectEngineCtxLoadConf(de_ctx) == -1) {
        goto error;
    }

    SigGroupHeadHashInit(de_ctx);
    MpmStoreInit(de_ctx);
    ThresholdHashInit(de_ctx);
    DetectParseDupSigHashInit(de_ctx);
    DetectAddressMapInit(de_ctx);
    DetectMetadataHashInit(de_ctx);
    DetectBufferTypeSetupDetectEngine(de_ctx);
    DetectEngineInitializeFastPatternList(de_ctx);

    /* init iprep... ignore errors for now */
    (void)SRepInit(de_ctx);

    SCClassConfInit(de_ctx);
    if (!SCClassConfLoadClassificationConfigFile(de_ctx, NULL)) {
        if (RunmodeGetCurrent() == RUNMODE_CONF_TEST)
            goto error;
    }

    if (ActionInitConfig() < 0) {
        goto error;
    }
    SCReferenceConfInit(de_ctx);
    if (SCRConfLoadReferenceConfigFile(de_ctx, NULL) < 0) {
        if (RunmodeGetCurrent() == RUNMODE_CONF_TEST)
            goto error;
    }

    de_ctx->version = DetectEngineGetVersion();
    SCLogDebug("dectx with version %u", de_ctx->version);
    return de_ctx;
error:
    if (de_ctx != NULL) {
        DetectEngineCtxFree(de_ctx);
    }
    return NULL;

}

DetectEngineCtx *DetectEngineCtxInitStubForMT(void)
{
    return DetectEngineCtxInitReal(DETECT_ENGINE_TYPE_MT_STUB, NULL);
}

DetectEngineCtx *DetectEngineCtxInitStubForDD(void)
{
    return DetectEngineCtxInitReal(DETECT_ENGINE_TYPE_DD_STUB, NULL);
}

DetectEngineCtx *DetectEngineCtxInit(void)
{
    return DetectEngineCtxInitReal(DETECT_ENGINE_TYPE_NORMAL, NULL);
}

DetectEngineCtx *DetectEngineCtxInitWithPrefix(const char *prefix)
{
    if (prefix == NULL || strlen(prefix) == 0)
        return DetectEngineCtxInit();
    else
        return DetectEngineCtxInitReal(DETECT_ENGINE_TYPE_NORMAL, prefix);
}

static void DetectEngineCtxFreeThreadKeywordData(DetectEngineCtx *de_ctx)
{
    HashListTableFree(de_ctx->keyword_hash);
}

static void DetectEngineCtxFreeFailedSigs(DetectEngineCtx *de_ctx)
{
    SigString *item = NULL;
    SigString *sitem;

    TAILQ_FOREACH_SAFE(item, &de_ctx->sig_stat.failed_sigs, next, sitem) {
        SCFree(item->filename);
        SCFree(item->sig_str);
        if (item->sig_error) {
            SCFree(item->sig_error);
        }
        TAILQ_REMOVE(&de_ctx->sig_stat.failed_sigs, item, next);
        SCFree(item);
    }
}

/**
 * \brief Free a DetectEngineCtx::
 *
 * \param de_ctx DetectEngineCtx:: to be freed
 */
void DetectEngineCtxFree(DetectEngineCtx *de_ctx)
{

    if (de_ctx == NULL)
        return;

#ifdef PROFILE_RULES
    if (de_ctx->profile_ctx != NULL) {
        SCProfilingRuleDestroyCtx(de_ctx->profile_ctx);
        de_ctx->profile_ctx = NULL;
    }
#endif
#ifdef PROFILING
    if (de_ctx->profile_keyword_ctx != NULL) {
        SCProfilingKeywordDestroyCtx(de_ctx);//->profile_keyword_ctx);
//        de_ctx->profile_keyword_ctx = NULL;
    }
    if (de_ctx->profile_sgh_ctx != NULL) {
        SCProfilingSghDestroyCtx(de_ctx);
    }
    SCProfilingPrefilterDestroyCtx(de_ctx);
#endif

    /* Normally the hashes are freed elsewhere, but
     * to be sure look at them again here.
     */
    SigGroupHeadHashFree(de_ctx);
    MpmStoreFree(de_ctx);
    DetectParseDupSigHashFree(de_ctx);
    SCSigSignatureOrderingModuleCleanup(de_ctx);
    ThresholdContextDestroy(de_ctx);
    SigCleanSignatures(de_ctx);
    if (de_ctx->sig_array)
        SCFree(de_ctx->sig_array);

    DetectEngineFreeFastPatternList(de_ctx);
    SCClassConfDeInitContext(de_ctx);
    SCRConfDeInitContext(de_ctx);

    SigGroupCleanup(de_ctx);

    SpmDestroyGlobalThreadCtx(de_ctx->spm_global_thread_ctx);

    MpmFactoryDeRegisterAllMpmCtxProfiles(de_ctx);

    DetectEngineCtxFreeThreadKeywordData(de_ctx);
    SRepDestroy(de_ctx);
    DetectEngineCtxFreeFailedSigs(de_ctx);

    DetectAddressMapFree(de_ctx);
    DetectMetadataHashFree(de_ctx);

    /* if we have a config prefix, remove the config from the tree */
    if (strlen(de_ctx->config_prefix) > 0) {
        /* remove config */
        ConfNode *node = ConfGetNode(de_ctx->config_prefix);
        if (node != NULL) {
            ConfNodeRemove(node); /* frees node */
        }
#if 0
        ConfDump();
#endif
    }

    DetectPortCleanupList(de_ctx, de_ctx->tcp_whitelist);
    DetectPortCleanupList(de_ctx, de_ctx->udp_whitelist);

    DetectBufferTypeFreeDetectEngine(de_ctx);
    SCClassConfDeinit(de_ctx);
    SCReferenceConfDeinit(de_ctx);

    if (de_ctx->tenant_path) {
        SCFree(de_ctx->tenant_path);
    }

    if (de_ctx->requirements) {
        SCDetectRequiresStatusFree(de_ctx->requirements);
    }

    SCFree(de_ctx);
    //DetectAddressGroupPrintMemory();
    //DetectSigGroupPrintMemory();
    //DetectPortPrintMemory();
}

/** \brief  Function that load DetectEngineCtx config for grouping sigs
 *          used by the engine
 *  \retval 0 if no config provided, 1 if config was provided
 *          and loaded successfully
 */
static int DetectEngineCtxLoadConf(DetectEngineCtx *de_ctx)
{
    uint8_t profile = ENGINE_PROFILE_MEDIUM;
    const char *max_uniq_toclient_groups_str = NULL;
    const char *max_uniq_toserver_groups_str = NULL;
    const char *sgh_mpm_context = NULL;
    const char *de_ctx_profile = NULL;

    (void)ConfGet("detect.profile", &de_ctx_profile);
    (void)ConfGet("detect.sgh-mpm-context", &sgh_mpm_context);

    ConfNode *de_ctx_custom = ConfGetNode("detect-engine");
    ConfNode *opt = NULL;

    if (de_ctx_custom != NULL) {
        TAILQ_FOREACH(opt, &de_ctx_custom->head, next) {
            if (de_ctx_profile == NULL) {
                if (opt->val && strcmp(opt->val, "profile") == 0) {
                    de_ctx_profile = opt->head.tqh_first->val;
                }
            }

            if (sgh_mpm_context == NULL) {
                if (opt->val && strcmp(opt->val, "sgh-mpm-context") == 0) {
                    sgh_mpm_context = opt->head.tqh_first->val;
                }
            }
        }
    }

    if (de_ctx_profile != NULL) {
        if (strcmp(de_ctx_profile, "low") == 0 ||
            strcmp(de_ctx_profile, "lowest") == 0) {        // legacy
            profile = ENGINE_PROFILE_LOW;
        } else if (strcmp(de_ctx_profile, "medium") == 0) {
            profile = ENGINE_PROFILE_MEDIUM;
        } else if (strcmp(de_ctx_profile, "high") == 0 ||
                   strcmp(de_ctx_profile, "highest") == 0) { // legacy
            profile = ENGINE_PROFILE_HIGH;
        } else if (strcmp(de_ctx_profile, "custom") == 0) {
            profile = ENGINE_PROFILE_CUSTOM;
        } else {
            SCLogError("invalid value for detect.profile: '%s'. "
                       "Valid options: low, medium, high and custom.",
                    de_ctx_profile);
            return -1;
        }

        SCLogDebug("Profile for detection engine groups is \"%s\"", de_ctx_profile);
    } else {
        SCLogDebug("Profile for detection engine groups not provided "
                   "at suricata.yaml. Using default (\"medium\").");
    }

    /* detect-engine.sgh-mpm-context option parsing */
    if (sgh_mpm_context == NULL || strcmp(sgh_mpm_context, "auto") == 0) {
        /* for now, since we still haven't implemented any intelligence into
         * understanding the patterns and distributing mpm_ctx across sgh */
        if (de_ctx->mpm_matcher == MPM_AC || de_ctx->mpm_matcher == MPM_AC_KS ||
#ifdef BUILD_HYPERSCAN
            de_ctx->mpm_matcher == MPM_HS ||
#endif
            de_ctx->mpm_matcher == MPM_AC_BS) {
            de_ctx->sgh_mpm_ctx_cnf = ENGINE_SGH_MPM_FACTORY_CONTEXT_SINGLE;
        } else {
            de_ctx->sgh_mpm_ctx_cnf = ENGINE_SGH_MPM_FACTORY_CONTEXT_FULL;
        }
    } else {
        if (strcmp(sgh_mpm_context, "single") == 0) {
            de_ctx->sgh_mpm_ctx_cnf = ENGINE_SGH_MPM_FACTORY_CONTEXT_SINGLE;
        } else if (strcmp(sgh_mpm_context, "full") == 0) {
            de_ctx->sgh_mpm_ctx_cnf = ENGINE_SGH_MPM_FACTORY_CONTEXT_FULL;
        } else {
            SCLogError("You have supplied an "
                       "invalid conf value for detect-engine.sgh-mpm-context-"
                       "%s",
                    sgh_mpm_context);
            exit(EXIT_FAILURE);
        }
    }

    if (run_mode == RUNMODE_UNITTEST) {
        de_ctx->sgh_mpm_ctx_cnf = ENGINE_SGH_MPM_FACTORY_CONTEXT_FULL;
    }

    /* parse profile custom-values */
    opt = NULL;
    switch (profile) {
        case ENGINE_PROFILE_LOW:
            de_ctx->max_uniq_toclient_groups = 15;
            de_ctx->max_uniq_toserver_groups = 25;
            break;

        case ENGINE_PROFILE_HIGH:
            de_ctx->max_uniq_toclient_groups = 75;
            de_ctx->max_uniq_toserver_groups = 75;
            break;

        case ENGINE_PROFILE_CUSTOM:
            (void)ConfGet("detect.custom-values.toclient-groups",
                    &max_uniq_toclient_groups_str);
            (void)ConfGet("detect.custom-values.toserver-groups",
                    &max_uniq_toserver_groups_str);

            if (de_ctx_custom != NULL) {
                TAILQ_FOREACH(opt, &de_ctx_custom->head, next) {
                    if (opt->val && strcmp(opt->val, "custom-values") == 0) {
                        if (max_uniq_toclient_groups_str == NULL) {
                            max_uniq_toclient_groups_str = (char *)ConfNodeLookupChildValue
                                (opt->head.tqh_first, "toclient-sp-groups");
                        }
                        if (max_uniq_toclient_groups_str == NULL) {
                            max_uniq_toclient_groups_str = (char *)ConfNodeLookupChildValue
                                (opt->head.tqh_first, "toclient-groups");
                        }
                        if (max_uniq_toserver_groups_str == NULL) {
                            max_uniq_toserver_groups_str = (char *)ConfNodeLookupChildValue
                                (opt->head.tqh_first, "toserver-dp-groups");
                        }
                        if (max_uniq_toserver_groups_str == NULL) {
                            max_uniq_toserver_groups_str = (char *)ConfNodeLookupChildValue
                                (opt->head.tqh_first, "toserver-groups");
                        }
                    }
                }
            }
            if (max_uniq_toclient_groups_str != NULL) {
                if (StringParseUint16(&de_ctx->max_uniq_toclient_groups, 10,
                            (uint16_t)strlen(max_uniq_toclient_groups_str),
                            (const char *)max_uniq_toclient_groups_str) <= 0) {
                    de_ctx->max_uniq_toclient_groups = 20;

                    SCLogWarning("parsing '%s' for "
                                 "toclient-groups failed, using %u",
                            max_uniq_toclient_groups_str, de_ctx->max_uniq_toclient_groups);
                }
            } else {
                de_ctx->max_uniq_toclient_groups = 20;
            }
            SCLogConfig("toclient-groups %u", de_ctx->max_uniq_toclient_groups);

            if (max_uniq_toserver_groups_str != NULL) {
                if (StringParseUint16(&de_ctx->max_uniq_toserver_groups, 10,
                            (uint16_t)strlen(max_uniq_toserver_groups_str),
                            (const char *)max_uniq_toserver_groups_str) <= 0) {
                    de_ctx->max_uniq_toserver_groups = 40;

                    SCLogWarning("parsing '%s' for "
                                 "toserver-groups failed, using %u",
                            max_uniq_toserver_groups_str, de_ctx->max_uniq_toserver_groups);
                }
            } else {
                de_ctx->max_uniq_toserver_groups = 40;
            }
            SCLogConfig("toserver-groups %u", de_ctx->max_uniq_toserver_groups);
            break;

        /* Default (or no config provided) is profile medium */
        case ENGINE_PROFILE_MEDIUM:
        case ENGINE_PROFILE_UNKNOWN:
        default:
            de_ctx->max_uniq_toclient_groups = 20;
            de_ctx->max_uniq_toserver_groups = 40;
            break;
    }

    intmax_t value = 0;
    if (ConfGetInt("detect.inspection-recursion-limit", &value) == 1)
    {
        if (value >= 0 && value <= INT_MAX) {
            de_ctx->inspection_recursion_limit = (int)value;
        }

    /* fall back to old config parsing */
    } else {
        ConfNode *insp_recursion_limit_node = NULL;
        char *insp_recursion_limit = NULL;

        if (de_ctx_custom != NULL) {
            opt = NULL;
            TAILQ_FOREACH(opt, &de_ctx_custom->head, next) {
                if (opt->val && strcmp(opt->val, "inspection-recursion-limit") != 0)
                    continue;

                insp_recursion_limit_node = ConfNodeLookupChild(opt, opt->val);
                if (insp_recursion_limit_node == NULL) {
                    SCLogError("Error retrieving conf "
                               "entry for detect-engine:inspection-recursion-limit");
                    break;
                }
                insp_recursion_limit = insp_recursion_limit_node->val;
                SCLogDebug("Found detect-engine.inspection-recursion-limit - %s:%s",
                        insp_recursion_limit_node->name, insp_recursion_limit_node->val);
                break;
            }

            if (insp_recursion_limit != NULL) {
                if (StringParseInt32(&de_ctx->inspection_recursion_limit, 10,
                                     0, (const char *)insp_recursion_limit) < 0) {
                    SCLogWarning("Invalid value for "
                                 "detect-engine.inspection-recursion-limit: %s "
                                 "resetting to %d",
                            insp_recursion_limit, DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT);
                    de_ctx->inspection_recursion_limit =
                        DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT;
                }
            } else {
                de_ctx->inspection_recursion_limit =
                    DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT;
            }
        }
    }

    if (de_ctx->inspection_recursion_limit == 0)
        de_ctx->inspection_recursion_limit = -1;

    SCLogDebug("de_ctx->inspection_recursion_limit: %d",
               de_ctx->inspection_recursion_limit);

    /* parse port grouping whitelisting settings */

    const char *ports = NULL;
    (void)ConfGet("detect.grouping.tcp-whitelist", &ports);
    if (ports) {
        SCLogConfig("grouping: tcp-whitelist %s", ports);
    } else {
        ports = "53, 80, 139, 443, 445, 1433, 3306, 3389, 6666, 6667, 8080";
        SCLogConfig("grouping: tcp-whitelist (default) %s", ports);

    }
    if (DetectPortParse(de_ctx, &de_ctx->tcp_whitelist, ports) != 0) {
        SCLogWarning("'%s' is not a valid value "
                     "for detect.grouping.tcp-whitelist",
                ports);
    }
    DetectPort *x = de_ctx->tcp_whitelist;
    for ( ; x != NULL;  x = x->next) {
        if (x->port != x->port2) {
            SCLogWarning("'%s' is not a valid value "
                         "for detect.grouping.tcp-whitelist: only single ports allowed",
                    ports);
            DetectPortCleanupList(de_ctx, de_ctx->tcp_whitelist);
            de_ctx->tcp_whitelist = NULL;
            break;
        }
    }

    ports = NULL;
    (void)ConfGet("detect.grouping.udp-whitelist", &ports);
    if (ports) {
        SCLogConfig("grouping: udp-whitelist %s", ports);
    } else {
        ports = "53, 135, 5060";
        SCLogConfig("grouping: udp-whitelist (default) %s", ports);

    }
    if (DetectPortParse(de_ctx, &de_ctx->udp_whitelist, ports) != 0) {
        SCLogWarning("'%s' is not a valid value "
                     "for detect.grouping.udp-whitelist",
                ports);
    }
    for (x = de_ctx->udp_whitelist; x != NULL;  x = x->next) {
        if (x->port != x->port2) {
            SCLogWarning("'%s' is not a valid value "
                         "for detect.grouping.udp-whitelist: only single ports allowed",
                    ports);
            DetectPortCleanupList(de_ctx, de_ctx->udp_whitelist);
            de_ctx->udp_whitelist = NULL;
            break;
        }
    }

    de_ctx->prefilter_setting = DETECT_PREFILTER_MPM;
    const char *pf_setting = NULL;
    if (ConfGet("detect.prefilter.default", &pf_setting) == 1 && pf_setting) {
        if (strcasecmp(pf_setting, "mpm") == 0) {
            de_ctx->prefilter_setting = DETECT_PREFILTER_MPM;
        } else if (strcasecmp(pf_setting, "auto") == 0) {
            de_ctx->prefilter_setting = DETECT_PREFILTER_AUTO;
        }
    }
    switch (de_ctx->prefilter_setting) {
        case DETECT_PREFILTER_MPM:
            SCLogConfig("prefilter engines: MPM");
            break;
        case DETECT_PREFILTER_AUTO:
            SCLogConfig("prefilter engines: MPM and keywords");
            break;
    }

    return 0;
}

/*
 * getting & (re)setting the internal sig i
 */

//inline uint32_t DetectEngineGetMaxSigId(DetectEngineCtx *de_ctx)
//{
//    return de_ctx->signum;
//}

void DetectEngineResetMaxSigId(DetectEngineCtx *de_ctx)
{
    de_ctx->signum = 0;
}

static int DetectEngineThreadCtxInitGlobalKeywords(DetectEngineThreadCtx *det_ctx)
{
    const DetectEngineMasterCtx *master = &g_master_de_ctx;

    if (master->keyword_id > 0) {
        // coverity[suspicious_sizeof : FALSE]
        det_ctx->global_keyword_ctxs_array = (void **)SCCalloc(master->keyword_id, sizeof(void *));
        if (det_ctx->global_keyword_ctxs_array == NULL) {
            SCLogError("setting up thread local detect ctx");
            return TM_ECODE_FAILED;
        }
        det_ctx->global_keyword_ctxs_size = master->keyword_id;

        const DetectEngineThreadKeywordCtxItem *item = master->keyword_list;
        while (item) {
            det_ctx->global_keyword_ctxs_array[item->id] = item->InitFunc(item->data);
            if (det_ctx->global_keyword_ctxs_array[item->id] == NULL) {
                SCLogError("setting up thread local detect ctx "
                           "for keyword \"%s\" failed",
                        item->name);
                return TM_ECODE_FAILED;
            }
            item = item->next;
        }
    }
    return TM_ECODE_OK;
}

static void DetectEngineThreadCtxDeinitGlobalKeywords(DetectEngineThreadCtx *det_ctx)
{
    if (det_ctx->global_keyword_ctxs_array == NULL ||
        det_ctx->global_keyword_ctxs_size == 0) {
        return;
    }

    const DetectEngineMasterCtx *master = &g_master_de_ctx;
    if (master->keyword_id > 0) {
        const DetectEngineThreadKeywordCtxItem *item = master->keyword_list;
        while (item) {
            if (det_ctx->global_keyword_ctxs_array[item->id] != NULL)
                item->FreeFunc(det_ctx->global_keyword_ctxs_array[item->id]);

            item = item->next;
        }
        det_ctx->global_keyword_ctxs_size = 0;
        SCFree(det_ctx->global_keyword_ctxs_array);
        det_ctx->global_keyword_ctxs_array = NULL;
    }
}

static int DetectEngineThreadCtxInitKeywords(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx)
{
    if (de_ctx->keyword_id > 0) {
        // coverity[suspicious_sizeof : FALSE]
        det_ctx->keyword_ctxs_array = SCMalloc(de_ctx->keyword_id * sizeof(void *));
        if (det_ctx->keyword_ctxs_array == NULL) {
            SCLogError("setting up thread local detect ctx");
            return TM_ECODE_FAILED;
        }

        memset(det_ctx->keyword_ctxs_array, 0x00, de_ctx->keyword_id * sizeof(void *));

        det_ctx->keyword_ctxs_size = de_ctx->keyword_id;

        HashListTableBucket *hb = HashListTableGetListHead(de_ctx->keyword_hash);
        for (; hb != NULL; hb = HashListTableGetListNext(hb)) {
            DetectEngineThreadKeywordCtxItem *item = HashListTableGetListData(hb);

            det_ctx->keyword_ctxs_array[item->id] = item->InitFunc(item->data);
            if (det_ctx->keyword_ctxs_array[item->id] == NULL) {
                SCLogError("setting up thread local detect ctx "
                           "for keyword \"%s\" failed",
                        item->name);
                return TM_ECODE_FAILED;
            }
        }
    }
    return TM_ECODE_OK;
}

static void DetectEngineThreadCtxDeinitKeywords(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx)
{
    if (de_ctx->keyword_id > 0) {
        HashListTableBucket *hb = HashListTableGetListHead(de_ctx->keyword_hash);
        for (; hb != NULL; hb = HashListTableGetListNext(hb)) {
            DetectEngineThreadKeywordCtxItem *item = HashListTableGetListData(hb);

            if (det_ctx->keyword_ctxs_array[item->id] != NULL)
                item->FreeFunc(det_ctx->keyword_ctxs_array[item->id]);
        }
        det_ctx->keyword_ctxs_size = 0;
        SCFree(det_ctx->keyword_ctxs_array);
        det_ctx->keyword_ctxs_array = NULL;
    }
}

/** NOTE: master MUST be locked before calling this */
static TmEcode DetectEngineThreadCtxInitForMT(ThreadVars *tv, DetectEngineThreadCtx *det_ctx)
{
    DetectEngineMasterCtx *master = &g_master_de_ctx;
    DetectEngineTenantMapping *map_array = NULL;
    uint32_t map_array_size = 0;
    uint32_t map_cnt = 0;
    uint32_t max_tenant_id = 0;
    DetectEngineCtx *list = master->list;
    HashTable *mt_det_ctxs_hash = NULL;

    if (master->tenant_selector == TENANT_SELECTOR_UNKNOWN) {
        SCLogError("no tenant selector set: "
                   "set using multi-detect.selector");
        return TM_ECODE_FAILED;
    }

    uint32_t tcnt = 0;
    while (list) {
        if (list->tenant_id > max_tenant_id)
            max_tenant_id = list->tenant_id;

        list = list->next;
        tcnt++;
    }

    mt_det_ctxs_hash = HashTableInit(tcnt * 2, TenantIdHash, TenantIdCompare, TenantIdFree);
    if (mt_det_ctxs_hash == NULL) {
        goto error;
    }

    if (tcnt == 0) {
        SCLogInfo("no tenants left, or none registered yet");
    } else {
        max_tenant_id++;

        DetectEngineTenantMapping *map = master->tenant_mapping_list;
        while (map) {
            map_cnt++;
            map = map->next;
        }

        if (map_cnt > 0) {
            map_array_size = map_cnt + 1;

            map_array = SCCalloc(map_array_size, sizeof(*map_array));
            if (map_array == NULL)
                goto error;

            /* fill the array */
            map_cnt = 0;
            map = master->tenant_mapping_list;
            while (map) {
                if (map_cnt >= map_array_size) {
                    goto error;
                }
                map_array[map_cnt].traffic_id = map->traffic_id;
                map_array[map_cnt].tenant_id = map->tenant_id;
                map_cnt++;
                map = map->next;
            }

        }

        /* set up hash for tenant lookup */
        list = master->list;
        while (list) {
            SCLogDebug("tenant-id %u", list->tenant_id);
            if (list->tenant_id != 0) {
                DetectEngineThreadCtx *mt_det_ctx = DetectEngineThreadCtxInitForReload(tv, list, 0);
                if (mt_det_ctx == NULL)
                    goto error;
                if (HashTableAdd(mt_det_ctxs_hash, mt_det_ctx, 0) != 0) {
                    goto error;
                }
            }
            list = list->next;
        }
    }

    det_ctx->mt_det_ctxs_hash = mt_det_ctxs_hash;
    mt_det_ctxs_hash = NULL;

    det_ctx->mt_det_ctxs_cnt = max_tenant_id;

    det_ctx->tenant_array = map_array;
    det_ctx->tenant_array_size = map_array_size;

    switch (master->tenant_selector) {
        case TENANT_SELECTOR_UNKNOWN:
            SCLogDebug("TENANT_SELECTOR_UNKNOWN");
            break;
        case TENANT_SELECTOR_VLAN:
            det_ctx->TenantGetId = DetectEngineTenantGetIdFromVlanId;
            SCLogDebug("TENANT_SELECTOR_VLAN");
            break;
        case TENANT_SELECTOR_LIVEDEV:
            det_ctx->TenantGetId = DetectEngineTenantGetIdFromLivedev;
            SCLogDebug("TENANT_SELECTOR_LIVEDEV");
            break;
        case TENANT_SELECTOR_DIRECT:
            det_ctx->TenantGetId = DetectEngineTenantGetIdFromPcap;
            SCLogDebug("TENANT_SELECTOR_DIRECT");
            break;
    }

    return TM_ECODE_OK;
error:
    if (map_array != NULL)
        SCFree(map_array);
    if (mt_det_ctxs_hash != NULL)
        HashTableFree(mt_det_ctxs_hash);

    return TM_ECODE_FAILED;
}

/** \internal
 *  \brief Helper for DetectThread setup functions
 */
static TmEcode ThreadCtxDoInit (DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx)
{
    PatternMatchThreadPrepare(&det_ctx->mtc, de_ctx->mpm_matcher);
    PatternMatchThreadPrepare(&det_ctx->mtcs, de_ctx->mpm_matcher);
    PatternMatchThreadPrepare(&det_ctx->mtcu, de_ctx->mpm_matcher);

    PmqSetup(&det_ctx->pmq);

    det_ctx->spm_thread_ctx = SpmMakeThreadCtx(de_ctx->spm_global_thread_ctx);
    if (det_ctx->spm_thread_ctx == NULL) {
        return TM_ECODE_FAILED;
    }

    /* sized to the max of our sgh settings. A max setting of 0 implies that all
     * sgh's have: sgh->non_pf_store_cnt == 0 */
    if (de_ctx->non_pf_store_cnt_max > 0) {
        det_ctx->non_pf_id_array =  SCCalloc(de_ctx->non_pf_store_cnt_max, sizeof(SigIntId));
        BUG_ON(det_ctx->non_pf_id_array == NULL);
    }

    /* DeState */
    if (de_ctx->sig_array_len > 0) {
        det_ctx->match_array_len = de_ctx->sig_array_len;
        det_ctx->match_array = SCMalloc(det_ctx->match_array_len * sizeof(Signature *));
        if (det_ctx->match_array == NULL) {
            return TM_ECODE_FAILED;
        }
        memset(det_ctx->match_array, 0,
               det_ctx->match_array_len * sizeof(Signature *));

        RuleMatchCandidateTxArrayInit(det_ctx, de_ctx->sig_array_len);
    }

    /* Alert processing queue */
    AlertQueueInit(det_ctx);

    /* byte_extract storage */
    det_ctx->byte_values = SCMalloc(sizeof(*det_ctx->byte_values) *
                                  (de_ctx->byte_extract_max_local_id + 1));
    if (det_ctx->byte_values == NULL) {
        return TM_ECODE_FAILED;
    }

    /* Allocate space for base64 decoded data. */
    if (de_ctx->base64_decode_max_len) {
        det_ctx->base64_decoded = SCMalloc(de_ctx->base64_decode_max_len);
        if (det_ctx->base64_decoded == NULL) {
            return TM_ECODE_FAILED;
        }
        det_ctx->base64_decoded_len_max = de_ctx->base64_decode_max_len;
        det_ctx->base64_decoded_len = 0;
    }

    det_ctx->inspect.buffers_size = de_ctx->buffer_type_id;
    det_ctx->inspect.buffers = SCCalloc(det_ctx->inspect.buffers_size, sizeof(InspectionBuffer));
    if (det_ctx->inspect.buffers == NULL) {
        return TM_ECODE_FAILED;
    }
    det_ctx->inspect.to_clear_queue = SCCalloc(det_ctx->inspect.buffers_size, sizeof(uint32_t));
    if (det_ctx->inspect.to_clear_queue == NULL) {
        return TM_ECODE_FAILED;
    }
    det_ctx->inspect.to_clear_idx = 0;

    det_ctx->multi_inspect.buffers_size = de_ctx->buffer_type_id;
    det_ctx->multi_inspect.buffers = SCCalloc(det_ctx->multi_inspect.buffers_size, sizeof(InspectionBufferMultipleForList));
    if (det_ctx->multi_inspect.buffers == NULL) {
        return TM_ECODE_FAILED;
    }
    det_ctx->multi_inspect.to_clear_queue = SCCalloc(det_ctx->multi_inspect.buffers_size, sizeof(uint32_t));
    if (det_ctx->multi_inspect.to_clear_queue == NULL) {
        return TM_ECODE_FAILED;
    }
    det_ctx->multi_inspect.to_clear_idx = 0;


    DetectEngineThreadCtxInitKeywords(de_ctx, det_ctx);
    DetectEngineThreadCtxInitGlobalKeywords(det_ctx);
#ifdef PROFILE_RULES
    SCProfilingRuleThreadSetup(de_ctx->profile_ctx, det_ctx);
#endif
#ifdef PROFILING
    SCProfilingKeywordThreadSetup(de_ctx->profile_keyword_ctx, det_ctx);
    SCProfilingPrefilterThreadSetup(de_ctx->profile_prefilter_ctx, det_ctx);
    SCProfilingSghThreadSetup(de_ctx->profile_sgh_ctx, det_ctx);
#endif
    SC_ATOMIC_INIT(det_ctx->so_far_used_by_detect);

    return TM_ECODE_OK;
}

/** \brief initialize thread specific detection engine context
 *
 *  \note there is a special case when using delayed detect. In this case the
 *        function is called twice per thread. The first time the rules are not
 *        yet loaded. de_ctx->delayed_detect_initialized will be 0. The 2nd
 *        time they will be loaded. de_ctx->delayed_detect_initialized will be 1.
 *        This is needed to do the per thread counter registration before the
 *        packet runtime starts. In delayed detect mode, the first call will
 *        return a NULL ptr through the data ptr.
 *
 *  \param tv ThreadVars for this thread
 *  \param initdata pointer to de_ctx
 *  \param data[out] pointer to store our thread detection ctx
 *
 *  \retval TM_ECODE_OK if all went well
 *  \retval TM_ECODE_FAILED on serious errors
 */
TmEcode DetectEngineThreadCtxInit(ThreadVars *tv, void *initdata, void **data)
{
    DetectEngineThreadCtx *det_ctx = SCMalloc(sizeof(DetectEngineThreadCtx));
    if (unlikely(det_ctx == NULL))
        return TM_ECODE_FAILED;
    memset(det_ctx, 0, sizeof(DetectEngineThreadCtx));

    det_ctx->tv = tv;
    det_ctx->de_ctx = DetectEngineGetCurrent();
    if (det_ctx->de_ctx == NULL) {
#ifdef UNITTESTS
        if (RunmodeIsUnittests()) {
            det_ctx->de_ctx = (DetectEngineCtx *)initdata;
        } else {
            DetectEngineThreadCtxDeinit(tv, det_ctx);
            return TM_ECODE_FAILED;
        }
#else
        DetectEngineThreadCtxDeinit(tv, det_ctx);
        return TM_ECODE_FAILED;
#endif
    }

    if (det_ctx->de_ctx->type == DETECT_ENGINE_TYPE_NORMAL ||
        det_ctx->de_ctx->type == DETECT_ENGINE_TYPE_TENANT)
    {
        if (ThreadCtxDoInit(det_ctx->de_ctx, det_ctx) != TM_ECODE_OK) {
            DetectEngineThreadCtxDeinit(tv, det_ctx);
            return TM_ECODE_FAILED;
        }
    }

    /** alert counter setup */
    det_ctx->counter_alerts = StatsRegisterCounter("detect.alert", tv);
    det_ctx->counter_alerts_overflow = StatsRegisterCounter("detect.alert_queue_overflow", tv);
    det_ctx->counter_alerts_suppressed = StatsRegisterCounter("detect.alerts_suppressed", tv);
#ifdef PROFILING
    det_ctx->counter_mpm_list = StatsRegisterAvgCounter("detect.mpm_list", tv);
    det_ctx->counter_nonmpm_list = StatsRegisterAvgCounter("detect.nonmpm_list", tv);
    det_ctx->counter_fnonmpm_list = StatsRegisterAvgCounter("detect.fnonmpm_list", tv);
    det_ctx->counter_match_list = StatsRegisterAvgCounter("detect.match_list", tv);
#endif

    if (DetectEngineMultiTenantEnabled()) {
        if (DetectEngineThreadCtxInitForMT(tv, det_ctx) != TM_ECODE_OK) {
            DetectEngineThreadCtxDeinit(tv, det_ctx);
            return TM_ECODE_FAILED;
        }
    }

    /* pass thread data back to caller */
    *data = (void *)det_ctx;

    return TM_ECODE_OK;
}

/**
 * \internal
 * \brief initialize a det_ctx for reload cases
 * \param new_de_ctx the new detection engine
 * \param mt flag to indicate if MT should be set up for this det_ctx
 *           this should only be done for the 'root' det_ctx
 *
 * \retval det_ctx detection engine thread ctx or NULL in case of error
 */
DetectEngineThreadCtx *DetectEngineThreadCtxInitForReload(
        ThreadVars *tv, DetectEngineCtx *new_de_ctx, int mt)
{
    DetectEngineThreadCtx *det_ctx = SCMalloc(sizeof(DetectEngineThreadCtx));
    if (unlikely(det_ctx == NULL))
        return NULL;
    memset(det_ctx, 0, sizeof(DetectEngineThreadCtx));

    det_ctx->tenant_id = new_de_ctx->tenant_id;
    det_ctx->tv = tv;
    det_ctx->de_ctx = DetectEngineReference(new_de_ctx);
    if (det_ctx->de_ctx == NULL) {
        SCFree(det_ctx);
        return NULL;
    }

    /* most of the init happens here */
    if (det_ctx->de_ctx->type == DETECT_ENGINE_TYPE_NORMAL ||
        det_ctx->de_ctx->type == DETECT_ENGINE_TYPE_TENANT)
    {
        if (ThreadCtxDoInit(det_ctx->de_ctx, det_ctx) != TM_ECODE_OK) {
            DetectEngineDeReference(&det_ctx->de_ctx);
            SCFree(det_ctx);
            return NULL;
        }
    }

    /** alert counter setup */
    det_ctx->counter_alerts = StatsRegisterCounter("detect.alert", tv);
    det_ctx->counter_alerts_overflow = StatsRegisterCounter("detect.alert_queue_overflow", tv);
    det_ctx->counter_alerts_suppressed = StatsRegisterCounter("detect.alerts_suppressed", tv);
#ifdef PROFILING
    uint16_t counter_mpm_list = StatsRegisterAvgCounter("detect.mpm_list", tv);
    uint16_t counter_nonmpm_list = StatsRegisterAvgCounter("detect.nonmpm_list", tv);
    uint16_t counter_fnonmpm_list = StatsRegisterAvgCounter("detect.fnonmpm_list", tv);
    uint16_t counter_match_list = StatsRegisterAvgCounter("detect.match_list", tv);
    det_ctx->counter_mpm_list = counter_mpm_list;
    det_ctx->counter_nonmpm_list = counter_nonmpm_list;
    det_ctx->counter_fnonmpm_list = counter_fnonmpm_list;
    det_ctx->counter_match_list = counter_match_list;
#endif

    if (mt && DetectEngineMultiTenantEnabled()) {
        if (DetectEngineThreadCtxInitForMT(tv, det_ctx) != TM_ECODE_OK) {
            DetectEngineDeReference(&det_ctx->de_ctx);
            SCFree(det_ctx);
            return NULL;
        }
    }

    return det_ctx;
}

static void DetectEngineThreadCtxFree(DetectEngineThreadCtx *det_ctx)
{
#if  DEBUG
    SCLogDebug("PACKET PKT_STREAM_ADD: %"PRIu64, det_ctx->pkt_stream_add_cnt);

    SCLogDebug("PAYLOAD MPM %"PRIu64"/%"PRIu64, det_ctx->payload_mpm_cnt, det_ctx->payload_mpm_size);
    SCLogDebug("STREAM  MPM %"PRIu64"/%"PRIu64, det_ctx->stream_mpm_cnt, det_ctx->stream_mpm_size);

    SCLogDebug("PAYLOAD SIG %"PRIu64"/%"PRIu64, det_ctx->payload_persig_cnt, det_ctx->payload_persig_size);
    SCLogDebug("STREAM  SIG %"PRIu64"/%"PRIu64, det_ctx->stream_persig_cnt, det_ctx->stream_persig_size);
#endif

    if (det_ctx->tenant_array != NULL) {
        SCFree(det_ctx->tenant_array);
        det_ctx->tenant_array = NULL;
    }

#ifdef PROFILE_RULES
    SCProfilingRuleThreadCleanup(det_ctx);
#endif
#ifdef PROFILING
    SCProfilingKeywordThreadCleanup(det_ctx);
    SCProfilingPrefilterThreadCleanup(det_ctx);
    SCProfilingSghThreadCleanup(det_ctx);
#endif

    /** \todo get rid of this static */
    if (det_ctx->de_ctx != NULL) {
        PatternMatchThreadDestroy(&det_ctx->mtc, det_ctx->de_ctx->mpm_matcher);
        PatternMatchThreadDestroy(&det_ctx->mtcs, det_ctx->de_ctx->mpm_matcher);
        PatternMatchThreadDestroy(&det_ctx->mtcu, det_ctx->de_ctx->mpm_matcher);
    }

    PmqFree(&det_ctx->pmq);

    if (det_ctx->spm_thread_ctx != NULL) {
        SpmDestroyThreadCtx(det_ctx->spm_thread_ctx);
    }

    if (det_ctx->non_pf_id_array != NULL)
        SCFree(det_ctx->non_pf_id_array);

    if (det_ctx->match_array != NULL)
        SCFree(det_ctx->match_array);

    RuleMatchCandidateTxArrayFree(det_ctx);

    AlertQueueFree(det_ctx);

    if (det_ctx->byte_values != NULL)
        SCFree(det_ctx->byte_values);

    /* Decoded base64 data. */
    if (det_ctx->base64_decoded != NULL) {
        SCFree(det_ctx->base64_decoded);
    }

    if (det_ctx->inspect.buffers) {
        for (uint32_t i = 0; i < det_ctx->inspect.buffers_size; i++) {
            InspectionBufferFree(&det_ctx->inspect.buffers[i]);
        }
        SCFree(det_ctx->inspect.buffers);
    }
    if (det_ctx->inspect.to_clear_queue) {
        SCFree(det_ctx->inspect.to_clear_queue);
    }
    if (det_ctx->multi_inspect.buffers) {
        for (uint32_t i = 0; i < det_ctx->multi_inspect.buffers_size; i++) {
            InspectionBufferMultipleForList *fb = &det_ctx->multi_inspect.buffers[i];
            for (uint32_t x = 0; x < fb->size; x++) {
                InspectionBufferFree(&fb->inspection_buffers[x]);
            }
            SCFree(fb->inspection_buffers);
        }
        SCFree(det_ctx->multi_inspect.buffers);
    }
    if (det_ctx->multi_inspect.to_clear_queue) {
        SCFree(det_ctx->multi_inspect.to_clear_queue);
    }

    DetectEngineThreadCtxDeinitGlobalKeywords(det_ctx);
    if (det_ctx->de_ctx != NULL) {
        DetectEngineThreadCtxDeinitKeywords(det_ctx->de_ctx, det_ctx);
#ifdef UNITTESTS
        if (!RunmodeIsUnittests() || det_ctx->de_ctx->ref_cnt > 0)
            DetectEngineDeReference(&det_ctx->de_ctx);
#else
        DetectEngineDeReference(&det_ctx->de_ctx);
#endif
    }

    AppLayerDecoderEventsFreeEvents(&det_ctx->decoder_events);

    SCFree(det_ctx);
}

TmEcode DetectEngineThreadCtxDeinit(ThreadVars *tv, void *data)
{
    DetectEngineThreadCtx *det_ctx = (DetectEngineThreadCtx *)data;

    if (det_ctx == NULL) {
        SCLogWarning("argument \"data\" NULL");
        return TM_ECODE_OK;
    }

    if (det_ctx->mt_det_ctxs_hash != NULL) {
        HashTableFree(det_ctx->mt_det_ctxs_hash);
        det_ctx->mt_det_ctxs_hash = NULL;
    }
    DetectEngineThreadCtxFree(det_ctx);

    return TM_ECODE_OK;
}

void DetectEngineThreadCtxInfo(ThreadVars *t, DetectEngineThreadCtx *det_ctx)
{
    /* XXX */
    PatternMatchThreadPrint(&det_ctx->mtc, det_ctx->de_ctx->mpm_matcher);
    PatternMatchThreadPrint(&det_ctx->mtcu, det_ctx->de_ctx->mpm_matcher);
}

static uint32_t DetectKeywordCtxHashFunc(HashListTable *ht, void *data, uint16_t datalen)
{
    DetectEngineThreadKeywordCtxItem *ctx = data;
    const char *name = ctx->name;
    uint64_t hash = StringHashDjb2((const uint8_t *)name, strlen(name)) + (ptrdiff_t)ctx->data;
    hash %= ht->array_size;
    return hash;
}

static char DetectKeywordCtxCompareFunc(void *data1, uint16_t len1, void *data2, uint16_t len2)
{
    DetectEngineThreadKeywordCtxItem *ctx1 = data1;
    DetectEngineThreadKeywordCtxItem *ctx2 = data2;
    const char *name1 = ctx1->name;
    const char *name2 = ctx2->name;
    return (strcmp(name1, name2) == 0 && ctx1->data == ctx2->data);
}

static void DetectKeywordCtxFreeFunc(void *ptr)
{
    SCFree(ptr);
}

/** \brief Register Thread keyword context Funcs
 *
 *  \param de_ctx detection engine to register in
 *  \param name keyword name for error printing
 *  \param InitFunc function ptr
 *  \param data keyword init data to pass to Func. Can be NULL.
 *  \param FreeFunc function ptr
 *  \param mode 0 normal (ctx per keyword instance) 1 shared (one ctx per det_ct)
 *
 *  \retval id for retrieval of ctx at runtime
 *  \retval -1 on error
 *
 *  \note make sure "data" remains valid and it free'd elsewhere. It's
 *        recommended to store it in the keywords global ctx so that
 *        it's freed when the de_ctx is freed.
 */
int DetectRegisterThreadCtxFuncs(DetectEngineCtx *de_ctx, const char *name, void *(*InitFunc)(void *), void *data, void (*FreeFunc)(void *), int mode)
{
    BUG_ON(de_ctx == NULL || InitFunc == NULL || FreeFunc == NULL);

    if (de_ctx->keyword_hash == NULL) {
        de_ctx->keyword_hash = HashListTableInit(4096, // TODO
                DetectKeywordCtxHashFunc, DetectKeywordCtxCompareFunc, DetectKeywordCtxFreeFunc);
        BUG_ON(de_ctx->keyword_hash == NULL);
    }

    if (mode) {
        DetectEngineThreadKeywordCtxItem search = { .data = data, .name = name };

        DetectEngineThreadKeywordCtxItem *item =
                HashListTableLookup(de_ctx->keyword_hash, (void *)&search, 0);
        if (item)
            return item->id;

        /* fall through */
    }

    DetectEngineThreadKeywordCtxItem *item = SCCalloc(1, sizeof(DetectEngineThreadKeywordCtxItem));
    if (unlikely(item == NULL))
        return -1;

    item->InitFunc = InitFunc;
    item->FreeFunc = FreeFunc;
    item->data = data;
    item->name = name;
    item->id = de_ctx->keyword_id++;

    if (HashListTableAdd(de_ctx->keyword_hash, (void *)item, 0) < 0) {
        SCFree(item);
        return -1;
    }
    return item->id;
}

/** \brief Remove Thread keyword context registration
 *
 *  \param de_ctx detection engine to deregister from
 *  \param det_ctx detection engine thread context to deregister from
 *  \param data keyword init data to pass to Func. Can be NULL.
 *  \param name keyword name for error printing
 *
 *  \retval 1 Item unregistered
 *  \retval 0 otherwise
 *
 *  \note make sure "data" remains valid and it free'd elsewhere. It's
 *        recommended to store it in the keywords global ctx so that
 *        it's freed when the de_ctx is freed.
 */
int DetectUnregisterThreadCtxFuncs(DetectEngineCtx *de_ctx, void *data, const char *name)
{
    /* might happen if we call this before a call to *Register* */
    if (de_ctx->keyword_hash == NULL)
        return 1;
    DetectEngineThreadKeywordCtxItem remove = { .data = data, .name = name };
    if (HashListTableRemove(de_ctx->keyword_hash, (void *)&remove, 0) == 0)
        return 1;
    return 0;
}
/** \brief Retrieve thread local keyword ctx by id
 *
 *  \param det_ctx detection engine thread ctx to retrieve the ctx from
 *  \param id id of the ctx returned by DetectRegisterThreadCtxInitFunc at
 *            keyword init.
 *
 *  \retval ctx or NULL on error
 */
void *DetectThreadCtxGetKeywordThreadCtx(DetectEngineThreadCtx *det_ctx, int id)
{
    if (id < 0 || id > det_ctx->keyword_ctxs_size || det_ctx->keyword_ctxs_array == NULL)
        return NULL;

    return det_ctx->keyword_ctxs_array[id];
}


/** \brief Register Thread keyword context Funcs (Global)
 *
 *  IDs stay static over reloads and between tenants
 *
 *  \param name keyword name for error printing
 *  \param InitFunc function ptr
 *  \param FreeFunc function ptr
 *
 *  \retval id for retrieval of ctx at runtime
 *  \retval -1 on error
 */
int DetectRegisterThreadCtxGlobalFuncs(const char *name,
        void *(*InitFunc)(void *), void *data, void (*FreeFunc)(void *))
{
    int id;
    BUG_ON(InitFunc == NULL || FreeFunc == NULL);

    DetectEngineMasterCtx *master = &g_master_de_ctx;

    /* if already registered, return existing id */
    DetectEngineThreadKeywordCtxItem *item = master->keyword_list;
    while (item != NULL) {
        if (strcmp(name, item->name) == 0) {
            id = item->id;
            return id;
        }

        item = item->next;
    }

    item = SCCalloc(1, sizeof(*item));
    if (unlikely(item == NULL)) {
        return -1;
    }
    item->InitFunc = InitFunc;
    item->FreeFunc = FreeFunc;
    item->name = name;
    item->data = data;

    item->next = master->keyword_list;
    master->keyword_list = item;
    item->id = master->keyword_id++;

    id = item->id;
    return id;
}

/** \brief Retrieve thread local keyword ctx by id
 *
 *  \param det_ctx detection engine thread ctx to retrieve the ctx from
 *  \param id id of the ctx returned by DetectRegisterThreadCtxInitFunc at
 *            keyword init.
 *
 *  \retval ctx or NULL on error
 */
void *DetectThreadCtxGetGlobalKeywordThreadCtx(DetectEngineThreadCtx *det_ctx, int id)
{
    if (id < 0 || id > det_ctx->global_keyword_ctxs_size ||
        det_ctx->global_keyword_ctxs_array == NULL) {
        return NULL;
    }

    return det_ctx->global_keyword_ctxs_array[id];
}

/** \brief Check if detection is enabled
 *  \retval bool true or false */
int DetectEngineEnabled(void)
{
    DetectEngineMasterCtx *master = &g_master_de_ctx;
    SCMutexLock(&master->lock);

    if (master->list == NULL) {
        SCMutexUnlock(&master->lock);
        return 0;
    }

    SCMutexUnlock(&master->lock);
    return 1;
}

uint32_t DetectEngineGetVersion(void)
{
    uint32_t version;
    DetectEngineMasterCtx *master = &g_master_de_ctx;
    SCMutexLock(&master->lock);
    version = master->version;
    SCMutexUnlock(&master->lock);
    return version;
}

void DetectEngineBumpVersion(void)
{
    DetectEngineMasterCtx *master = &g_master_de_ctx;
    SCMutexLock(&master->lock);
    master->version++;
    SCLogDebug("master version now %u", master->version);
    SCMutexUnlock(&master->lock);
}

DetectEngineCtx *DetectEngineGetCurrent(void)
{
    DetectEngineMasterCtx *master = &g_master_de_ctx;
    SCMutexLock(&master->lock);

    DetectEngineCtx *de_ctx = master->list;
    while (de_ctx) {
        if (de_ctx->type == DETECT_ENGINE_TYPE_NORMAL ||
            de_ctx->type == DETECT_ENGINE_TYPE_DD_STUB ||
            de_ctx->type == DETECT_ENGINE_TYPE_MT_STUB)
        {
            de_ctx->ref_cnt++;
            SCLogDebug("de_ctx %p ref_cnt %u", de_ctx, de_ctx->ref_cnt);
            SCMutexUnlock(&master->lock);
            return de_ctx;
        }
        de_ctx = de_ctx->next;
    }

    SCMutexUnlock(&master->lock);
    return NULL;
}

DetectEngineCtx *DetectEngineReference(DetectEngineCtx *de_ctx)
{
    if (de_ctx == NULL)
        return NULL;
    de_ctx->ref_cnt++;
    return de_ctx;
}

/** TODO locking? Not needed if this is a one time setting at startup */
int DetectEngineMultiTenantEnabled(void)
{
    DetectEngineMasterCtx *master = &g_master_de_ctx;
    return (master->multi_tenant_enabled);
}

/** \internal
 *  \brief load a tenant from a yaml file
 *
 *  \param tenant_id the tenant id by which the config is known
 *  \param filename full path of a yaml file
 *  \param loader_id id of loader thread or -1
 *
 *  \retval 0 ok
 *  \retval -1 failed
 */
static int DetectEngineMultiTenantLoadTenant(uint32_t tenant_id, const char *filename, int loader_id)
{
    DetectEngineCtx *de_ctx = NULL;
    char prefix[64];

    snprintf(prefix, sizeof(prefix), "multi-detect.%u", tenant_id);

    SCStat st;
    if (SCStatFn(filename, &st) != 0) {
        SCLogError("failed to stat file %s", filename);
        goto error;
    }

    de_ctx = DetectEngineGetByTenantId(tenant_id);
    if (de_ctx != NULL) {
        SCLogError("tenant %u already registered", tenant_id);
        DetectEngineDeReference(&de_ctx);
        goto error;
    }

    ConfNode *node = ConfGetNode(prefix);
    if (node == NULL) {
        SCLogError("failed to properly setup yaml %s", filename);
        goto error;
    }

    de_ctx = DetectEngineCtxInitWithPrefix(prefix);
    if (de_ctx == NULL) {
        SCLogError("initializing detection engine "
                   "context failed.");
        goto error;
    }
    SCLogDebug("de_ctx %p with prefix %s", de_ctx, de_ctx->config_prefix);

    de_ctx->type = DETECT_ENGINE_TYPE_TENANT;
    de_ctx->tenant_id = tenant_id;
    de_ctx->loader_id = loader_id;
    de_ctx->tenant_path = SCStrdup(filename);
    if (de_ctx->tenant_path == NULL) {
        SCLogError("Failed to duplicate path");
        goto error;
    }

    if (SigLoadSignatures(de_ctx, NULL, 0) < 0) {
        SCLogError("Loading signatures failed.");
        goto error;
    }

    DetectEngineAddToMaster(de_ctx);

    return 0;

error:
    if (de_ctx != NULL) {
        DetectEngineCtxFree(de_ctx);
    }
    return -1;
}

static int DetectEngineMultiTenantReloadTenant(uint32_t tenant_id, const char *filename, int reload_cnt)
{
    DetectEngineCtx *old_de_ctx = DetectEngineGetByTenantId(tenant_id);
    if (old_de_ctx == NULL) {
        SCLogError("tenant detect engine not found");
        return -1;
    }

    if (filename == NULL)
        filename = old_de_ctx->tenant_path;

    char prefix[64];
    snprintf(prefix, sizeof(prefix), "multi-detect.%u.reload.%d", tenant_id, reload_cnt);
    reload_cnt++;
    SCLogDebug("prefix %s", prefix);

    if (ConfYamlLoadFileWithPrefix(filename, prefix) != 0) {
        SCLogError("failed to load yaml");
        goto error;
    }

    ConfNode *node = ConfGetNode(prefix);
    if (node == NULL) {
        SCLogError("failed to properly setup yaml %s", filename);
        goto error;
    }

    DetectEngineCtx *new_de_ctx = DetectEngineCtxInitWithPrefix(prefix);
    if (new_de_ctx == NULL) {
        SCLogError("initializing detection engine "
                   "context failed.");
        goto error;
    }
    SCLogDebug("de_ctx %p with prefix %s", new_de_ctx, new_de_ctx->config_prefix);

    new_de_ctx->type = DETECT_ENGINE_TYPE_TENANT;
    new_de_ctx->tenant_id = tenant_id;
    new_de_ctx->loader_id = old_de_ctx->loader_id;
    new_de_ctx->tenant_path = SCStrdup(filename);
    if (new_de_ctx->tenant_path == NULL) {
        SCLogError("Failed to duplicate path");
        goto error;
    }

    if (SigLoadSignatures(new_de_ctx, NULL, 0) < 0) {
        SCLogError("Loading signatures failed.");
        goto error;
    }

    DetectEngineAddToMaster(new_de_ctx);

    /* move to free list */
    DetectEngineMoveToFreeList(old_de_ctx);
    DetectEngineDeReference(&old_de_ctx);
    return 0;

error:
    DetectEngineDeReference(&old_de_ctx);
    return -1;
}


typedef struct TenantLoaderCtx_ {
    uint32_t tenant_id;
    int reload_cnt; /**< used by reload */
    char *yaml;     /**< heap alloc'd copy of file path for the yaml */
} TenantLoaderCtx;

static void DetectLoaderFreeTenant(void *ctx)
{
    TenantLoaderCtx *t = (TenantLoaderCtx *)ctx;
    if (t->yaml != NULL) {
        SCFree(t->yaml);
    }
    SCFree(t);
}

static int DetectLoaderFuncLoadTenant(void *vctx, int loader_id)
{
    TenantLoaderCtx *ctx = (TenantLoaderCtx *)vctx;

    SCLogDebug("loader %d", loader_id);
    if (DetectEngineMultiTenantLoadTenant(ctx->tenant_id, ctx->yaml, loader_id) != 0) {
        return -1;
    }
    return 0;
}

static int DetectLoaderSetupLoadTenant(uint32_t tenant_id, const char *yaml)
{
    TenantLoaderCtx *t = SCCalloc(1, sizeof(*t));
    if (t == NULL)
        return -ENOMEM;

    t->tenant_id = tenant_id;
    t->yaml = SCStrdup(yaml);
    if (t->yaml == NULL) {
        SCFree(t);
        return -ENOMEM;
    }

    return DetectLoaderQueueTask(-1, DetectLoaderFuncLoadTenant, t, DetectLoaderFreeTenant);
}

static int DetectLoaderFuncReloadTenant(void *vctx, int loader_id)
{
    TenantLoaderCtx *ctx = (TenantLoaderCtx *)vctx;

    SCLogDebug("loader_id %d", loader_id);

    if (DetectEngineMultiTenantReloadTenant(ctx->tenant_id, ctx->yaml, ctx->reload_cnt) != 0) {
        return -1;
    }
    return 0;
}

static int DetectLoaderSetupReloadTenants(const int reload_cnt)
{
    int ret = 0;
    DetectEngineMasterCtx *master = &g_master_de_ctx;
    SCMutexLock(&master->lock);

    DetectEngineCtx *de_ctx = master->list;
    while (de_ctx) {
        if (de_ctx->type == DETECT_ENGINE_TYPE_TENANT) {
            TenantLoaderCtx *t = SCCalloc(1, sizeof(*t));
            if (t == NULL) {
                ret = -1;
                goto error;
            }
            t->tenant_id = de_ctx->tenant_id;
            t->reload_cnt = reload_cnt;
            int loader_id = de_ctx->loader_id;

            int r = DetectLoaderQueueTask(
                    loader_id, DetectLoaderFuncReloadTenant, t, DetectLoaderFreeTenant);
            if (r < 0) {
                ret = -2;
                goto error;
            }
        }

        de_ctx = de_ctx->next;
    }
error:
    SCMutexUnlock(&master->lock);
    return ret;
}

static int DetectLoaderSetupReloadTenant(uint32_t tenant_id, const char *yaml, int reload_cnt)
{
    DetectEngineCtx *old_de_ctx = DetectEngineGetByTenantId(tenant_id);
    if (old_de_ctx == NULL)
        return -ENOENT;
    int loader_id = old_de_ctx->loader_id;
    DetectEngineDeReference(&old_de_ctx);

    TenantLoaderCtx *t = SCCalloc(1, sizeof(*t));
    if (t == NULL)
        return -ENOMEM;

    t->tenant_id = tenant_id;
    if (yaml != NULL) {
        t->yaml = SCStrdup(yaml);
        if (t->yaml == NULL) {
            SCFree(t);
            return -ENOMEM;
        }
    }
    t->reload_cnt = reload_cnt;

    SCLogDebug("loader_id %d", loader_id);

    return DetectLoaderQueueTask(
            loader_id, DetectLoaderFuncReloadTenant, t, DetectLoaderFreeTenant);
}

/** \brief Load a tenant and wait for loading to complete
 */
int DetectEngineLoadTenantBlocking(uint32_t tenant_id, const char *yaml)
{
    int r = DetectLoaderSetupLoadTenant(tenant_id, yaml);
    if (r < 0)
        return r;

    if (DetectLoadersSync() != 0)
        return -1;

    return 0;
}

/** \brief Reload a tenant and wait for loading to complete
 */
int DetectEngineReloadTenantBlocking(uint32_t tenant_id, const char *yaml, int reload_cnt)
{
    int r = DetectLoaderSetupReloadTenant(tenant_id, yaml, reload_cnt);
    if (r < 0)
        return r;

    if (DetectLoadersSync() != 0)
        return -1;

    return 0;
}

/** \brief Reload all tenants and wait for loading to complete
 */
int DetectEngineReloadTenantsBlocking(const int reload_cnt)
{
    int r = DetectLoaderSetupReloadTenants(reload_cnt);
    if (r < 0)
        return r;

    if (DetectLoadersSync() != 0)
        return -1;

    return 0;
}

static int DetectEngineMultiTenantSetupLoadLivedevMappings(const ConfNode *mappings_root_node,
        bool failure_fatal)
{
    ConfNode *mapping_node = NULL;

    int mapping_cnt = 0;
    if (mappings_root_node != NULL) {
        TAILQ_FOREACH(mapping_node, &mappings_root_node->head, next) {
            ConfNode *tenant_id_node = ConfNodeLookupChild(mapping_node, "tenant-id");
            if (tenant_id_node == NULL)
                goto bad_mapping;
            ConfNode *device_node = ConfNodeLookupChild(mapping_node, "device");
            if (device_node == NULL)
                goto bad_mapping;

            uint32_t tenant_id = 0;
            if (StringParseUint32(&tenant_id, 10, (uint16_t)strlen(tenant_id_node->val),
                        tenant_id_node->val) < 0) {
                SCLogError("tenant-id  "
                           "of %s is invalid",
                        tenant_id_node->val);
                goto bad_mapping;
            }

            const char *dev = device_node->val;
            LiveDevice *ld = LiveGetDevice(dev);
            if (ld == NULL) {
                SCLogWarning("device %s not found", dev);
                goto bad_mapping;
            }

            if (ld->tenant_id_set) {
                SCLogWarning("device %s already mapped to tenant-id %u", dev, ld->tenant_id);
                goto bad_mapping;
            }

            ld->tenant_id = tenant_id;
            ld->tenant_id_set = true;

            if (DetectEngineTenantRegisterLivedev(tenant_id, ld->id) != 0) {
                goto error;
            }

            SCLogConfig("device %s connected to tenant-id %u", dev, tenant_id);
            mapping_cnt++;
            continue;

        bad_mapping:
            if (failure_fatal)
                goto error;
        }
    }
    SCLogConfig("%d device - tenant-id mappings defined", mapping_cnt);
    return mapping_cnt;

error:
    return 0;
}

static int DetectEngineMultiTenantSetupLoadVlanMappings(const ConfNode *mappings_root_node,
        bool failure_fatal)
{
    ConfNode *mapping_node = NULL;

    int mapping_cnt = 0;
    if (mappings_root_node != NULL) {
        TAILQ_FOREACH(mapping_node, &mappings_root_node->head, next) {
            ConfNode *tenant_id_node = ConfNodeLookupChild(mapping_node, "tenant-id");
            if (tenant_id_node == NULL)
                goto bad_mapping;
            ConfNode *vlan_id_node = ConfNodeLookupChild(mapping_node, "vlan-id");
            if (vlan_id_node == NULL)
                goto bad_mapping;

            uint32_t tenant_id = 0;
            if (StringParseUint32(&tenant_id, 10, (uint16_t)strlen(tenant_id_node->val),
                        tenant_id_node->val) < 0) {
                SCLogError("tenant-id  "
                           "of %s is invalid",
                        tenant_id_node->val);
                goto bad_mapping;
            }

            uint16_t vlan_id = 0;
            if (StringParseUint16(
                        &vlan_id, 10, (uint16_t)strlen(vlan_id_node->val), vlan_id_node->val) < 0) {
                SCLogError("vlan-id  "
                           "of %s is invalid",
                        vlan_id_node->val);
                goto bad_mapping;
            }
            if (vlan_id == 0 || vlan_id >= 4095) {
                SCLogError("vlan-id  "
                           "of %s is invalid. Valid range 1-4094.",
                        vlan_id_node->val);
                goto bad_mapping;
            }

            if (DetectEngineTenantRegisterVlanId(tenant_id, vlan_id) != 0) {
                goto error;
            }
            SCLogConfig("vlan %u connected to tenant-id %u", vlan_id, tenant_id);
            mapping_cnt++;
            continue;

        bad_mapping:
            if (failure_fatal)
                goto error;
        }
    }
    return mapping_cnt;

error:
    return 0;
}

/**
 *  \brief setup multi-detect / multi-tenancy
 *
 *  See if MT is enabled. If so, setup the selector, tenants and mappings.
 *  Tenants and mappings are optional, and can also dynamically be added
 *  and removed from the unix socket.
 */
int DetectEngineMultiTenantSetup(const bool unix_socket)
{
    enum DetectEngineTenantSelectors tenant_selector = TENANT_SELECTOR_UNKNOWN;
    DetectEngineMasterCtx *master = &g_master_de_ctx;
    int failure_fatal = 0;
    (void)ConfGetBool("engine.init-failure-fatal", &failure_fatal);

    int enabled = 0;
    (void)ConfGetBool("multi-detect.enabled", &enabled);
    if (enabled == 1) {
        DetectLoadersInit();
        TmModuleDetectLoaderRegister();
        DetectLoaderThreadSpawn();
        TmThreadContinueDetectLoaderThreads();

        SCMutexLock(&master->lock);
        master->multi_tenant_enabled = 1;

        const char *handler = NULL;
        if (ConfGet("multi-detect.selector", &handler) == 1) {
            SCLogConfig("multi-tenant selector type %s", handler);

            if (strcmp(handler, "vlan") == 0) {
                tenant_selector = master->tenant_selector = TENANT_SELECTOR_VLAN;

                int vlanbool = 0;
                if ((ConfGetBool("vlan.use-for-tracking", &vlanbool)) == 1 && vlanbool == 0) {
                    SCLogError("vlan tracking is disabled, "
                               "can't use multi-detect selector 'vlan'");
                    SCMutexUnlock(&master->lock);
                    goto error;
                }

            } else if (strcmp(handler, "direct") == 0) {
                tenant_selector = master->tenant_selector = TENANT_SELECTOR_DIRECT;
            } else if (strcmp(handler, "device") == 0) {
                tenant_selector = master->tenant_selector = TENANT_SELECTOR_LIVEDEV;
                if (EngineModeIsIPS()) {
                    SCLogWarning("multi-tenant 'device' mode not supported for IPS");
                    SCMutexUnlock(&master->lock);
                    goto error;
                }

            } else {
                SCLogError("unknown value %s "
                           "multi-detect.selector",
                        handler);
                SCMutexUnlock(&master->lock);
                goto error;
            }
        }
        SCMutexUnlock(&master->lock);
        SCLogConfig("multi-detect is enabled (multi tenancy). Selector: %s", handler);

        /* traffic -- tenant mappings */
        ConfNode *mappings_root_node = ConfGetNode("multi-detect.mappings");

        if (tenant_selector == TENANT_SELECTOR_VLAN) {
            int mapping_cnt = DetectEngineMultiTenantSetupLoadVlanMappings(mappings_root_node,
                    failure_fatal);
            if (mapping_cnt == 0) {
                /* no mappings are valid when we're in unix socket mode,
                 * they can be added on the fly. Otherwise warn/error
                 * depending on failure_fatal */

                if (unix_socket) {
                    SCLogNotice("no tenant traffic mappings defined, "
                            "tenants won't be used until mappings are added");
                } else {
                    if (failure_fatal) {
                        SCLogError("no multi-detect mappings defined");
                        goto error;
                    } else {
                        SCLogWarning("no multi-detect mappings defined");
                    }
                }
            }
        } else if (tenant_selector == TENANT_SELECTOR_LIVEDEV) {
            int mapping_cnt = DetectEngineMultiTenantSetupLoadLivedevMappings(mappings_root_node,
                    failure_fatal);
            if (mapping_cnt == 0) {
                if (failure_fatal) {
                    SCLogError("no multi-detect mappings defined");
                    goto error;
                } else {
                    SCLogWarning("no multi-detect mappings defined");
                }
            }
        }

        /* tenants */
        ConfNode *tenants_root_node = ConfGetNode("multi-detect.tenants");
        ConfNode *tenant_node = NULL;

        if (tenants_root_node != NULL) {
            const char *path = NULL;
            ConfNode *path_node = ConfGetNode("multi-detect.config-path");
            if (path_node) {
                path = path_node->val;
                SCLogConfig("tenants config path: %s", path);
            }

            TAILQ_FOREACH(tenant_node, &tenants_root_node->head, next) {
                ConfNode *id_node = ConfNodeLookupChild(tenant_node, "id");
                if (id_node == NULL) {
                    goto bad_tenant;
                }
                ConfNode *yaml_node = ConfNodeLookupChild(tenant_node, "yaml");
                if (yaml_node == NULL) {
                    goto bad_tenant;
                }

                uint32_t tenant_id = 0;
                if (StringParseUint32(
                            &tenant_id, 10, (uint16_t)strlen(id_node->val), id_node->val) < 0) {
                    SCLogError("tenant_id  "
                               "of %s is invalid",
                            id_node->val);
                    goto bad_tenant;
                }
                SCLogDebug("tenant id: %u, %s", tenant_id, yaml_node->val);

                char yaml_path[PATH_MAX] = "";
                if (path) {
                    PathMerge(yaml_path, PATH_MAX, path, yaml_node->val);
                } else {
                    strlcpy(yaml_path, yaml_node->val, sizeof(yaml_path));
                }
                SCLogDebug("tenant path: %s", yaml_path);

                /* setup the yaml in this loop so that it's not done by the loader
                 * threads. ConfYamlLoadFileWithPrefix is not thread safe. */
                char prefix[64];
                snprintf(prefix, sizeof(prefix), "multi-detect.%u", tenant_id);
                if (ConfYamlLoadFileWithPrefix(yaml_path, prefix) != 0) {
                    SCLogError("failed to load yaml %s", yaml_path);
                    goto bad_tenant;
                }

                int r = DetectLoaderSetupLoadTenant(tenant_id, yaml_path);
                if (r < 0) {
                    /* error logged already */
                    goto bad_tenant;
                }
                continue;

            bad_tenant:
                if (failure_fatal)
                    goto error;
            }
        }

        /* wait for our loaders to complete their tasks */
        if (DetectLoadersSync() != 0) {
            goto error;
        }

        VarNameStoreActivate();

    } else {
        SCLogDebug("multi-detect not enabled (multi tenancy)");
    }
    return 0;
error:
    return -1;
}

static uint32_t DetectEngineTenantGetIdFromVlanId(const void *ctx, const Packet *p)
{
    const DetectEngineThreadCtx *det_ctx = ctx;
    uint32_t x = 0;
    uint32_t vlan_id = 0;

    if (p->vlan_idx == 0)
        return 0;

    vlan_id = p->vlan_id[0];

    if (det_ctx == NULL || det_ctx->tenant_array == NULL || det_ctx->tenant_array_size == 0)
        return 0;

    /* not very efficient, but for now we're targeting only limited amounts.
     * Can use hash/tree approach later. */
    for (x = 0; x < det_ctx->tenant_array_size; x++) {
        if (det_ctx->tenant_array[x].traffic_id == vlan_id)
            return det_ctx->tenant_array[x].tenant_id;
    }

    return 0;
}

static uint32_t DetectEngineTenantGetIdFromLivedev(const void *ctx, const Packet *p)
{
    const DetectEngineThreadCtx *det_ctx = ctx;
    const LiveDevice *ld = p->livedev;

    if (ld == NULL || det_ctx == NULL)
        return 0;

    SCLogDebug("using tenant-id %u for packet on device %s", ld->tenant_id, ld->dev);
    return ld->tenant_id;
}

static int DetectEngineTenantRegisterSelector(
        enum DetectEngineTenantSelectors selector, uint32_t tenant_id, uint32_t traffic_id)
{
    DetectEngineMasterCtx *master = &g_master_de_ctx;
    SCMutexLock(&master->lock);

    if (!(master->tenant_selector == TENANT_SELECTOR_UNKNOWN || master->tenant_selector == selector)) {
        SCLogInfo("conflicting selector already set");
        SCMutexUnlock(&master->lock);
        return -1;
    }

    DetectEngineTenantMapping *m = master->tenant_mapping_list;
    while (m) {
        if (m->traffic_id == traffic_id) {
            SCLogInfo("traffic id already registered");
            SCMutexUnlock(&master->lock);
            return -1;
        }
        m = m->next;
    }

    DetectEngineTenantMapping *map = SCCalloc(1, sizeof(*map));
    if (map == NULL) {
        SCLogInfo("memory fail");
        SCMutexUnlock(&master->lock);
        return -1;
    }
    map->traffic_id = traffic_id;
    map->tenant_id = tenant_id;

    map->next = master->tenant_mapping_list;
    master->tenant_mapping_list = map;

    master->tenant_selector = selector;

    SCLogDebug("tenant handler %u %u %u registered", selector, tenant_id, traffic_id);
    SCMutexUnlock(&master->lock);
    return 0;
}

static int DetectEngineTenantUnregisterSelector(
        enum DetectEngineTenantSelectors selector, uint32_t tenant_id, uint32_t traffic_id)
{
    DetectEngineMasterCtx *master = &g_master_de_ctx;
    SCMutexLock(&master->lock);

    if (master->tenant_mapping_list == NULL) {
        SCMutexUnlock(&master->lock);
        return -1;
    }

    DetectEngineTenantMapping *prev = NULL;
    DetectEngineTenantMapping *map = master->tenant_mapping_list;
    while (map) {
        if (map->traffic_id == traffic_id &&
            map->tenant_id == tenant_id)
        {
            if (prev != NULL)
                prev->next = map->next;
            else
                master->tenant_mapping_list = map->next;

            map->next = NULL;
            SCFree(map);
            SCLogInfo("tenant handler %u %u %u unregistered", selector, tenant_id, traffic_id);
            SCMutexUnlock(&master->lock);
            return 0;
        }
        prev = map;
        map = map->next;
    }

    SCMutexUnlock(&master->lock);
    return -1;
}

int DetectEngineTenantRegisterLivedev(uint32_t tenant_id, int device_id)
{
    return DetectEngineTenantRegisterSelector(
            TENANT_SELECTOR_LIVEDEV, tenant_id, (uint32_t)device_id);
}

int DetectEngineTenantRegisterVlanId(uint32_t tenant_id, uint16_t vlan_id)
{
    return DetectEngineTenantRegisterSelector(TENANT_SELECTOR_VLAN, tenant_id, (uint32_t)vlan_id);
}

int DetectEngineTenantUnregisterVlanId(uint32_t tenant_id, uint16_t vlan_id)
{
    return DetectEngineTenantUnregisterSelector(TENANT_SELECTOR_VLAN, tenant_id, (uint32_t)vlan_id);
}

int DetectEngineTenantRegisterPcapFile(uint32_t tenant_id)
{
    SCLogInfo("registering %u %d 0", TENANT_SELECTOR_DIRECT, tenant_id);
    return DetectEngineTenantRegisterSelector(TENANT_SELECTOR_DIRECT, tenant_id, 0);
}

int DetectEngineTenantUnregisterPcapFile(uint32_t tenant_id)
{
    SCLogInfo("unregistering %u %d 0", TENANT_SELECTOR_DIRECT, tenant_id);
    return DetectEngineTenantUnregisterSelector(TENANT_SELECTOR_DIRECT, tenant_id, 0);
}

static uint32_t DetectEngineTenantGetIdFromPcap(const void *ctx, const Packet *p)
{
    return p->pcap_v.tenant_id;
}

DetectEngineCtx *DetectEngineGetByTenantId(uint32_t tenant_id)
{
    DetectEngineMasterCtx *master = &g_master_de_ctx;
    SCMutexLock(&master->lock);

    if (master->list == NULL) {
        SCMutexUnlock(&master->lock);
        return NULL;
    }

    DetectEngineCtx *de_ctx = master->list;
    while (de_ctx) {
        if (de_ctx->type == DETECT_ENGINE_TYPE_TENANT &&
                de_ctx->tenant_id == tenant_id)
        {
            de_ctx->ref_cnt++;
            break;
        }

        de_ctx = de_ctx->next;
    }

    SCMutexUnlock(&master->lock);
    return de_ctx;
}

void DetectEngineDeReference(DetectEngineCtx **de_ctx)
{
    BUG_ON((*de_ctx)->ref_cnt == 0);
    (*de_ctx)->ref_cnt--;
    *de_ctx = NULL;
}

static int DetectEngineAddToList(DetectEngineCtx *instance)
{
    DetectEngineMasterCtx *master = &g_master_de_ctx;

    if (instance == NULL)
        return -1;

    if (master->list == NULL) {
        master->list = instance;
    } else {
        instance->next = master->list;
        master->list = instance;
    }

    return 0;
}

int DetectEngineAddToMaster(DetectEngineCtx *de_ctx)
{
    int r;

    if (de_ctx == NULL)
        return -1;

    SCLogDebug("adding de_ctx %p to master", de_ctx);

    DetectEngineMasterCtx *master = &g_master_de_ctx;
    SCMutexLock(&master->lock);
    r = DetectEngineAddToList(de_ctx);
    SCMutexUnlock(&master->lock);
    return r;
}

static int DetectEngineMoveToFreeListNoLock(DetectEngineMasterCtx *master, DetectEngineCtx *de_ctx)
{
    DetectEngineCtx *instance = master->list;
    if (instance == NULL) {
        return -1;
    }

    /* remove from active list */
    if (instance == de_ctx) {
        master->list = instance->next;
    } else {
        DetectEngineCtx *prev = instance;
        instance = instance->next; /* already checked first element */

        while (instance) {
            DetectEngineCtx *next = instance->next;

            if (instance == de_ctx) {
                prev->next = instance->next;
                break;
            }

            prev = instance;
            instance = next;
        }
        if (instance == NULL) {
            return -1;
        }
    }

    /* instance is now detached from list */
    instance->next = NULL;

    /* add to free list */
    if (master->free_list == NULL) {
        master->free_list = instance;
    } else {
        instance->next = master->free_list;
        master->free_list = instance;
    }
    SCLogDebug("detect engine %p moved to free list (%u refs)", de_ctx, de_ctx->ref_cnt);
    return 0;
}

int DetectEngineMoveToFreeList(DetectEngineCtx *de_ctx)
{
    int ret = 0;
    DetectEngineMasterCtx *master = &g_master_de_ctx;
    SCMutexLock(&master->lock);
    ret = DetectEngineMoveToFreeListNoLock(master, de_ctx);
    SCMutexUnlock(&master->lock);
    return ret;
}

void DetectEnginePruneFreeList(void)
{
    DetectEngineMasterCtx *master = &g_master_de_ctx;
    SCMutexLock(&master->lock);

    DetectEngineCtx *prev = NULL;
    DetectEngineCtx *instance = master->free_list;
    while (instance) {
        DetectEngineCtx *next = instance->next;

        SCLogDebug("detect engine %p has %u ref(s)", instance, instance->ref_cnt);

        if (instance->ref_cnt == 0) {
            if (prev == NULL) {
                master->free_list = next;
            } else {
                prev->next = next;
            }

            SCLogDebug("freeing detect engine %p", instance);
            DetectEngineCtxFree(instance);
            instance = NULL;
        }

        prev = instance;
        instance = next;
    }
    SCMutexUnlock(&master->lock);
}

void DetectEngineClearMaster(void)
{
    DetectEngineMasterCtx *master = &g_master_de_ctx;
    SCMutexLock(&master->lock);

    DetectEngineCtx *instance = master->list;
    while (instance) {
        DetectEngineCtx *next = instance->next;
        DEBUG_VALIDATE_BUG_ON(instance->ref_cnt);
        SCLogDebug("detect engine %p has %u ref(s)", instance, instance->ref_cnt);
        instance->ref_cnt = 0;
        DetectEngineMoveToFreeListNoLock(master, instance);
        instance = next;
    }
    SCMutexUnlock(&master->lock);
    DetectEnginePruneFreeList();
}

static int reloads = 0;

/** \brief Reload the detection engine
 *
 *  \param filename YAML file to load for the detect config
 *
 *  \retval -1 error
 *  \retval 0 ok
 */
int DetectEngineReload(const SCInstance *suri)
{
    DetectEngineCtx *new_de_ctx = NULL;
    DetectEngineCtx *old_de_ctx = NULL;

    char prefix[128];
    memset(prefix, 0, sizeof(prefix));

    SCLogNotice("rule reload starting");

    if (suri->conf_filename != NULL) {
        snprintf(prefix, sizeof(prefix), "detect-engine-reloads.%d", reloads++);
        SCLogConfig("Reloading %s", suri->conf_filename);
        if (ConfYamlLoadFileWithPrefix(suri->conf_filename, prefix) != 0) {
            SCLogError("failed to load yaml %s", suri->conf_filename);
            return -1;
        }

        ConfNode *node = ConfGetNode(prefix);
        if (node == NULL) {
            SCLogError("failed to properly setup yaml %s", suri->conf_filename);
            return -1;
        }

        if (suri->additional_configs) {
            for (int i = 0; suri->additional_configs[i] != NULL; i++) {
                SCLogConfig("Reloading %s", suri->additional_configs[i]);
                ConfYamlHandleInclude(node, suri->additional_configs[i]);
            }
        }

#if 0
        ConfDump();
#endif
    }

    /* get a reference to the current de_ctx */
    old_de_ctx = DetectEngineGetCurrent();
    if (old_de_ctx == NULL)
        return -1;
    SCLogDebug("get ref to old_de_ctx %p", old_de_ctx);
    DatasetReload();

    /* only reload a regular 'normal' and 'delayed detect stub' detect engines */
    if (!(old_de_ctx->type == DETECT_ENGINE_TYPE_NORMAL ||
          old_de_ctx->type == DETECT_ENGINE_TYPE_DD_STUB))
    {
        DetectEngineDeReference(&old_de_ctx);
        SCLogNotice("rule reload complete");
        return -1;
    }

    /* get new detection engine */
    new_de_ctx = DetectEngineCtxInitWithPrefix(prefix);
    if (new_de_ctx == NULL) {
        SCLogError("initializing detection engine "
                   "context failed.");
        DetectEngineDeReference(&old_de_ctx);
        return -1;
    }
    if (SigLoadSignatures(new_de_ctx,
                          suri->sig_file, suri->sig_file_exclusive) != 0) {
        DetectEngineCtxFree(new_de_ctx);
        DetectEngineDeReference(&old_de_ctx);
        return -1;
    }
    SCLogDebug("set up new_de_ctx %p", new_de_ctx);

    /* add to master */
    DetectEngineAddToMaster(new_de_ctx);

    /* move to old free list */
    DetectEngineMoveToFreeList(old_de_ctx);
    DetectEngineDeReference(&old_de_ctx);

    SCLogDebug("going to reload the threads to use new_de_ctx %p", new_de_ctx);
    /* update the threads */
    DetectEngineReloadThreads(new_de_ctx);
    SCLogDebug("threads now run new_de_ctx %p", new_de_ctx);

    /* walk free list, freeing the old_de_ctx */
    DetectEnginePruneFreeList();

    DatasetPostReloadCleanup();

    DetectEngineBumpVersion();

    SCLogDebug("old_de_ctx should have been freed");

    SCLogNotice("rule reload complete");
    return 0;
}

static uint32_t TenantIdHash(HashTable *h, void *data, uint16_t data_len)
{
    DetectEngineThreadCtx *det_ctx = (DetectEngineThreadCtx *)data;
    return det_ctx->tenant_id % h->array_size;
}

static char TenantIdCompare(void *d1, uint16_t d1_len, void *d2, uint16_t d2_len)
{
    DetectEngineThreadCtx *det1 = (DetectEngineThreadCtx *)d1;
    DetectEngineThreadCtx *det2 = (DetectEngineThreadCtx *)d2;
    return (det1->tenant_id == det2->tenant_id);
}

static void TenantIdFree(void *d)
{
    DetectEngineThreadCtxFree(d);
}

int DetectEngineMTApply(void)
{
    DetectEngineMasterCtx *master = &g_master_de_ctx;
    SCMutexLock(&master->lock);

    if (master->tenant_selector == TENANT_SELECTOR_UNKNOWN) {
        SCLogInfo("error, no tenant selector");
        SCMutexUnlock(&master->lock);
        return -1;
    }

    DetectEngineCtx *stub_de_ctx = NULL;
    DetectEngineCtx *list = master->list;
    for ( ; list != NULL; list = list->next) {
        SCLogDebug("list %p tenant %u", list, list->tenant_id);

        if (list->type == DETECT_ENGINE_TYPE_NORMAL ||
            list->type == DETECT_ENGINE_TYPE_MT_STUB ||
            list->type == DETECT_ENGINE_TYPE_DD_STUB)
        {
            stub_de_ctx = list;
            break;
        }
    }
    if (stub_de_ctx == NULL) {
        stub_de_ctx = DetectEngineCtxInitStubForMT();
        if (stub_de_ctx == NULL) {
            SCMutexUnlock(&master->lock);
            return -1;
        }

        if (master->list == NULL) {
            master->list = stub_de_ctx;
        } else {
            stub_de_ctx->next = master->list;
            master->list = stub_de_ctx;
        }
    }

    /* update the threads */
    SCLogDebug("MT reload starting");
    DetectEngineReloadThreads(stub_de_ctx);
    SCLogDebug("MT reload done");

    SCMutexUnlock(&master->lock);

    /* walk free list, freeing the old_de_ctx */
    DetectEnginePruneFreeList();
    // needed for VarNameStoreFree
    DetectEngineBumpVersion();

    SCLogDebug("old_de_ctx should have been freed");
    return 0;
}

static int g_parse_metadata = 0;

void DetectEngineSetParseMetadata(void)
{
    g_parse_metadata = 1;
}

void DetectEngineUnsetParseMetadata(void)
{
    g_parse_metadata = 0;
}

int DetectEngineMustParseMetadata(void)
{
    return g_parse_metadata;
}

const char *DetectSigmatchListEnumToString(enum DetectSigmatchListEnum type)
{
    switch (type) {
        case DETECT_SM_LIST_MATCH:
            return "packet";
        case DETECT_SM_LIST_PMATCH:
            return "packet/stream payload";

        case DETECT_SM_LIST_TMATCH:
            return "tag";

        case DETECT_SM_LIST_BASE64_DATA:
            return "base64_data";

        case DETECT_SM_LIST_POSTMATCH:
            return "post-match";

        case DETECT_SM_LIST_SUPPRESS:
            return "suppress";
        case DETECT_SM_LIST_THRESHOLD:
            return "threshold";

        case DETECT_SM_LIST_MAX:
            return "max (internal)";
    }
    return "error";
}

/* events api */
void DetectEngineSetEvent(DetectEngineThreadCtx *det_ctx, uint8_t e)
{
    AppLayerDecoderEventsSetEventRaw(&det_ctx->decoder_events, e);
    det_ctx->events++;
}

AppLayerDecoderEvents *DetectEngineGetEvents(DetectEngineThreadCtx *det_ctx)
{
    return det_ctx->decoder_events;
}

/*************************************Unittest*********************************/

#ifdef UNITTESTS

static int DetectEngineInitYamlConf(const char *conf)
{
    ConfCreateContextBackup();
    ConfInit();
    return ConfYamlLoadString(conf, strlen(conf));
}

static void DetectEngineDeInitYamlConf(void)
{
    ConfDeInit();
    ConfRestoreContextBackup();

    return;
}

static int DetectEngineTest01(void)
{
    const char *conf =
        "%YAML 1.1\n"
        "---\n"
        "detect-engine:\n"
        "  - profile: medium\n"
        "  - custom-values:\n"
        "      toclient_src_groups: 2\n"
        "      toclient_dst_groups: 2\n"
        "      toclient_sp_groups: 2\n"
        "      toclient_dp_groups: 3\n"
        "      toserver_src_groups: 2\n"
        "      toserver_dst_groups: 4\n"
        "      toserver_sp_groups: 2\n"
        "      toserver_dp_groups: 25\n"
        "  - inspection-recursion-limit: 0\n";

    FAIL_IF(DetectEngineInitYamlConf(conf) == -1);

    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
    FAIL_IF_NULL(de_ctx);

    FAIL_IF_NOT(de_ctx->inspection_recursion_limit == -1);

    DetectEngineCtxFree(de_ctx);

    DetectEngineDeInitYamlConf();

    PASS;
}

static int DetectEngineTest02(void)
{
    const char *conf =
        "%YAML 1.1\n"
        "---\n"
        "detect-engine:\n"
        "  - profile: medium\n"
        "  - custom-values:\n"
        "      toclient_src_groups: 2\n"
        "      toclient_dst_groups: 2\n"
        "      toclient_sp_groups: 2\n"
        "      toclient_dp_groups: 3\n"
        "      toserver_src_groups: 2\n"
        "      toserver_dst_groups: 4\n"
        "      toserver_sp_groups: 2\n"
        "      toserver_dp_groups: 25\n"
        "  - inspection-recursion-limit:\n";

    FAIL_IF(DetectEngineInitYamlConf(conf) == -1);

    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
    FAIL_IF_NULL(de_ctx);

    FAIL_IF_NOT(
            de_ctx->inspection_recursion_limit == DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT);

    DetectEngineCtxFree(de_ctx);

    DetectEngineDeInitYamlConf();

    PASS;
}

static int DetectEngineTest03(void)
{
    const char *conf =
        "%YAML 1.1\n"
        "---\n"
        "detect-engine:\n"
        "  - profile: medium\n"
        "  - custom-values:\n"
        "      toclient_src_groups: 2\n"
        "      toclient_dst_groups: 2\n"
        "      toclient_sp_groups: 2\n"
        "      toclient_dp_groups: 3\n"
        "      toserver_src_groups: 2\n"
        "      toserver_dst_groups: 4\n"
        "      toserver_sp_groups: 2\n"
        "      toserver_dp_groups: 25\n";

    FAIL_IF(DetectEngineInitYamlConf(conf) == -1);

    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
    FAIL_IF_NULL(de_ctx);

    FAIL_IF_NOT(
            de_ctx->inspection_recursion_limit == DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT);

    DetectEngineCtxFree(de_ctx);

    DetectEngineDeInitYamlConf();

    PASS;
}

static int DetectEngineTest04(void)
{
    const char *conf =
        "%YAML 1.1\n"
        "---\n"
        "detect-engine:\n"
        "  - profile: medium\n"
        "  - custom-values:\n"
        "      toclient_src_groups: 2\n"
        "      toclient_dst_groups: 2\n"
        "      toclient_sp_groups: 2\n"
        "      toclient_dp_groups: 3\n"
        "      toserver_src_groups: 2\n"
        "      toserver_dst_groups: 4\n"
        "      toserver_sp_groups: 2\n"
        "      toserver_dp_groups: 25\n"
        "  - inspection-recursion-limit: 10\n";

    FAIL_IF(DetectEngineInitYamlConf(conf) == -1);

    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
    FAIL_IF_NULL(de_ctx);

    FAIL_IF_NOT(de_ctx->inspection_recursion_limit == 10);

    DetectEngineCtxFree(de_ctx);

    DetectEngineDeInitYamlConf();

    PASS;
}

static int DetectEngineTest08(void)
{
    const char *conf =
        "%YAML 1.1\n"
        "---\n"
        "detect-engine:\n"
        "  - profile: custom\n"
        "  - custom-values:\n"
        "      toclient-groups: 23\n"
        "      toserver-groups: 27\n";

    FAIL_IF(DetectEngineInitYamlConf(conf) == -1);

    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
    FAIL_IF_NULL(de_ctx);

    FAIL_IF_NOT(de_ctx->max_uniq_toclient_groups == 23);
    FAIL_IF_NOT(de_ctx->max_uniq_toserver_groups == 27);

    DetectEngineCtxFree(de_ctx);

    DetectEngineDeInitYamlConf();

    PASS;
}

/** \test bug 892 bad values */
static int DetectEngineTest09(void)
{
    const char *conf =
        "%YAML 1.1\n"
        "---\n"
        "detect-engine:\n"
        "  - profile: custom\n"
        "  - custom-values:\n"
        "      toclient-groups: BA\n"
        "      toserver-groups: BA\n"
        "  - inspection-recursion-limit: 10\n";

    FAIL_IF(DetectEngineInitYamlConf(conf) == -1);

    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
    FAIL_IF_NULL(de_ctx);

    FAIL_IF_NOT(de_ctx->max_uniq_toclient_groups == 20);
    FAIL_IF_NOT(de_ctx->max_uniq_toserver_groups == 40);

    DetectEngineCtxFree(de_ctx);

    DetectEngineDeInitYamlConf();

    PASS;
}

#endif

void DetectEngineRegisterTests(void)
{
#ifdef UNITTESTS
    UtRegisterTest("DetectEngineTest01", DetectEngineTest01);
    UtRegisterTest("DetectEngineTest02", DetectEngineTest02);
    UtRegisterTest("DetectEngineTest03", DetectEngineTest03);
    UtRegisterTest("DetectEngineTest04", DetectEngineTest04);
    UtRegisterTest("DetectEngineTest08", DetectEngineTest08);
    UtRegisterTest("DetectEngineTest09", DetectEngineTest09);
#endif
    return;
}