summaryrefslogtreecommitdiff
path: root/src/entry/Maat_rule.cpp
blob: e7530d1c8a7b7ac55960826ed61d4cfb77a8222f (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
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>//tolower
#include <iconv.h>
#include <sys/types.h>		//inet_pton
#include <sys/socket.h>	//inet_pton
#include <arpa/inet.h>		//inet_pton
#include <assert.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <strings.h>

#include <MESA/MESA_htable.h>
#include <MESA/MESA_list_queue.h>
#include <MESA/MESA_handle_logger.h>
#include <MESA/field_stat2.h>

#include "Maat_rule.h"
#include "Maat_rule_internal.h"
#include "Maat_utils.h"
#include "json2iris.h"
#include "cJSON.h"
#include "dynamic_array.h"
#include "alignment_int64.h"
#include "config_monitor.h"

#include "map_str2int.h"
#include "rulescan.h"
#include "bool_matcher.h"
#include "stream_fuzzy_hash.h"
#include "gram_index_engine.h"

int MAAT_FRAME_VERSION_2_9_20200622=1;

int is_valid_table_name(const char* str)
{
	size_t i=0, integer_cnt=0;
	for(i=0; i<strlen(str); i++)
	{
		if(str[i]>='0'&&str[i]<='9')
		{
			integer_cnt++;
		}
	}
	if(strlen(str)==0 ||
		integer_cnt==strlen(str) ||
		0==strcasecmp(str, "null"))
	{
		return 0;
	}
	return 1;
}
int is_valid_expr_type(enum MAAT_EXPR_TYPE expr_type)
{
	switch(expr_type)
	{
		case EXPR_TYPE_STRING:
		case EXPR_TYPE_AND:
		case EXPR_TYPE_REGEX:
		case EXPR_TYPE_OFFSET:
			return 1;
		default:
			return 0;
	}
}
int is_valid_match_method(enum MAAT_MATCH_METHOD match_method)
{
	switch(match_method)
	{
		case MATCH_METHOD_SUB:
		case MATCH_METHOD_RIGHT:
		case MATCH_METHOD_LEFT:
		case MATCH_METHOD_COMPLETE:
			return 1;
		default:
			return 0;
	}
}


iconv_t maat_iconv_open(struct Maat_scanner* scanner,enum MAAT_CHARSET to,enum MAAT_CHARSET from)
{
	const char *from_s=charset_get_name(from);
	const char *to_s=charset_get_name(to);
	iconv_t cd;
	if(from==CHARSET_GBK&&to==CHARSET_BIG5)
	{
		from_s="gb2312";
	}
	if(from>=MAX_CHARSET_NUM||to>=MAX_CHARSET_NUM)
	{
		return (iconv_t)-1;
	}

	if(scanner->iconv_handle[to][from]==NULL)
	{
		scanner->iconv_handle[to][from]=iconv_open(to_s, from_s);
	}
	cd=scanner->iconv_handle[to][from];
	return cd;
}

int iconv_convert(struct Maat_scanner* scanner,enum MAAT_CHARSET from,enum MAAT_CHARSET to,char *src,int srclen,char *dst,int *dstlen)
{
	size_t ret;
	int copy_len=0;
	char* copy_buf=NULL;
	if(srclen==0||src==NULL)
	{
		return -1;
	}
	iconv_t cd=maat_iconv_open(scanner,to, from);
	if(cd!=(iconv_t)-1)
	{
		char * pInBuff=src;
		size_t iInBuffLen=srclen;

		size_t iOutBuffLen=10*iInBuffLen;
		char * pOutBuff=(char *)malloc(iOutBuffLen);

		char * pLeftBuff=pOutBuff;
		size_t iLeftLen=iOutBuffLen;

		ret=iconv(cd, &pInBuff, &iInBuffLen, &pLeftBuff, &iLeftLen);
		if(ret!=(size_t)(-1))
		{
			
			if(to==CHARSET_UNICODE&&
				(*(unsigned short*)pOutBuff==0xFFFE||*(unsigned short*)pOutBuff==0XFEFF))//jump unicode 2 bytes BOM, 0xFF 0xFE
			{
				copy_len=iOutBuffLen-iLeftLen-2;
				copy_buf=pOutBuff+2;
			}
			else
			{
				copy_len=iOutBuffLen-iLeftLen;
				copy_buf=pOutBuff;
			}
			assert(copy_len<=*dstlen);
			*dstlen=copy_len;
			memcpy(dst,copy_buf,*dstlen);
			
			free(pOutBuff);
			return 1;
		}
		else
		{
			free(pOutBuff);
			return -1;
		}
	}
	else
	{
		return -1;
	}

}
int URLEncode(const char* str, const int strSize, char* result, const int resultSize)  
{  
	int i;  
	int j = 0;//for result index  
	char ch;  

	if ((str==NULL) || (result==NULL) || (strSize<=0) || (resultSize<=0)) 
	{  
		return -1;  
	}  

	for ( i=0; (i<strSize)&&(j<resultSize); ++i)
	{  
		ch = str[i];  
		if (((ch>='A') && (ch<='Z')) ||  
			((ch>='a') && (ch<='z')) ||  
			((ch>='0') && (ch<='9')))
		{  
			result[j++] = ch;  
		} 
		else if (ch == ' ')
		{  
			result[j++] = '+';  
		}
		else if (ch == '.' || ch == '-' || ch == '_' || ch == '*')
		{  
			result[j++] = ch;  
		}
		else 
		{  
			if (j+3 < resultSize)
			{  
				sprintf(result+j, "%%%02X", (unsigned char)ch);  
				j += 3;  
			} 
			else
			{  
				return -1;  
			}  
		}  
	}  

	result[j] = '\0';  
	return j;  
}  
int uni2ascii(const char* fmt,const char* src, const int srclen, char* dst, const int dstsize) 
{
	int i=0,j=0;
	assert(srclen%2==0);//unicode must be 2 bytes aligned.
	while(i<srclen&&j<dstsize)
	{
		if(*(unsigned short*)(src+i)<0x7f)
		{
			dst[j]=*(unsigned short*)(src+i);
			j++;
		}
		else
		{
			j+=snprintf(dst+j,dstsize-j,fmt,*(unsigned short*)(src+i));
		}
		i+=2;
	}
	return j;
}
int universal_charset_convert(struct Maat_scanner* scanner,enum MAAT_CHARSET from,enum MAAT_CHARSET to,char *src,int srclen,char *dst,int *dstlen)
{
	int ret=0;
	char* tmp_buff=NULL;
	int tmp_buff_size=0;
	MAAT_CHARSET tmp_dst_code=CHARSET_NONE;
	const char* fmt=NULL;
	switch(to)
	{
		case CHARSET_GBK:
		case CHARSET_BIG5:
		case CHARSET_UNICODE:
		case CHARSET_UTF8:
		case CHARSET_WINDOWS1251:
			ret=iconv_convert(scanner,from,to,src,srclen,dst,dstlen);
			return ret;
			break;
		case CHARSET_UNICODE_ASCII_ESC:
			tmp_dst_code=CHARSET_UNICODE;
			fmt="\\u%x;";
			break;
		case CHARSET_UNICODE_ASCII_ALIGNED:
			tmp_dst_code=CHARSET_UNICODE;
			fmt="\\u%04x";
			break;
		case CHARSET_UNICODE_NCR_DEC:	
			tmp_dst_code=CHARSET_UNICODE;
			fmt="&#%u;";
			break;
		case CHARSET_UNICODE_NCR_HEX:
			tmp_dst_code=CHARSET_UNICODE;
			fmt="&#x%x;";
			break;
		case CHARSET_URL_ENCODE_GB2312:	
			tmp_dst_code=CHARSET_GBK;
			fmt=NULL;
			break;
		case CHARSET_URL_ENCODE_UTF8:
			tmp_dst_code=CHARSET_UTF8;
			fmt=NULL;
			break;
		default:
			return -1;
			break;
	}
	tmp_buff_size=*dstlen;
	tmp_buff=(char*)malloc(tmp_buff_size);
	ret=iconv_convert(scanner,from,tmp_dst_code,src,srclen,tmp_buff,&tmp_buff_size);
	if(ret<0)
	{
		goto error_out;
	}
	if(fmt!=NULL)
	{
		ret=uni2ascii(fmt, tmp_buff, tmp_buff_size, dst,*dstlen);
	}
	else
	{
		ret=URLEncode(tmp_buff,tmp_buff_size,dst,*dstlen);
	}
	*dstlen=ret;
error_out:

	free(tmp_buff);
	tmp_buff=NULL;
	
	return ret;
}
char* Maat_str_escape(char* dst,int size,const char*src)
{
	int i=0,j=0;
	int len=strlen(src);
	for(i=0,j=0;i<len&&j<size;i++)
	{
		switch(src[i])
		{
			case '&':
				dst[j]='\\';
				dst[j+1]='&';
				j+=2;
				break;
			case ' ':
				dst[j]='\\';
				dst[j+1]='b';//space,0x20;
				j+=2;
				break;
			case '\\':
				dst[j]='\\';
				dst[j+1]='\\';
				j+=2;
				break;
			default:
				dst[j]=src[i];
				j++;	//undo the followed i++
				break;

		}
	}
	dst[j]='\0';
	return dst;
}

int cnt_maskbits(struct in6_addr mask)
{
	unsigned int i=0;
	int bits_cnt=0;
	unsigned char* p=(unsigned char*)&mask;
	for(i=0;i<sizeof(mask);i++)
	{
		for(;p[i]>0;p[i]=p[i]/2)
		{
			bits_cnt++;
		}
	}
	return bits_cnt;
}
//@param value is a JSON, like {"tags":[{"tag":"location","value":"北京/朝阳/华严北里/甲22号},{"tag":"isp","value":"电信"}]}
int parse_accept_tag(const char* value, struct rule_tag** result, void* logger)
{
	cJSON* json=NULL, *array=NULL,*tag=NULL, *tmp=NULL;
	struct rule_tag* p=NULL;
	int n_tags=0;
	json=cJSON_Parse(value);
	if(!json)
	{
		MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module,
			"MAAT_OPT_ACCEPT_TAGS Error before: %-200.200s",cJSON_GetErrorPtr());
		return 0;
	}
	array=cJSON_GetObjectItem(json, "tags");
	n_tags=cJSON_GetArraySize(array);
	p=ALLOC(struct rule_tag, n_tags);
	for(int i=0;i<n_tags;i++)
	{
		tag=cJSON_GetArrayItem(array, i);
		tmp=cJSON_GetObjectItem(tag, "tag");
		p[i].tag_name=_maat_strdup(tmp->valuestring);
		tmp=cJSON_GetObjectItem(tag, "value");
		p[i].tag_val=_maat_strdup(tmp->valuestring);
	}
	cJSON_Delete(json);
	*result=p;
	return n_tags;
}
static int compare_each_tag(cJSON* tag_obj, const struct rule_tag* accept_tags, int n_accept)
{
	const char* tag_name;
	const char* tag_val;
	int n_val;
	cJSON *tab_name_obj=NULL, *tag_vals_array=NULL, *tag_val_obj=NULL;

	int i=0, j=0, name_matched=0;
	tab_name_obj=cJSON_GetObjectItem(tag_obj,"tag");
	if(!tab_name_obj||tab_name_obj->type!=cJSON_String)
	{
		goto error_out;
	}
	tag_name=tab_name_obj->valuestring;
	tag_vals_array=cJSON_GetObjectItem(tag_obj,"value");
	if(!tag_vals_array||tag_vals_array->type!=cJSON_Array)
	{
		goto error_out;
	}
	n_val=cJSON_GetArraySize(tag_vals_array);
	for(i=0;i<n_accept;i++)
	{
		if(0!=strcmp(accept_tags[i].tag_name, tag_name))
		{
			continue;
		}
		name_matched++;

		for(j=0; j<n_val; j++)
		{
			tag_val_obj=cJSON_GetArrayItem(tag_vals_array, j);
			if(!tag_val_obj||tag_val_obj->type!=cJSON_String)
			{
				goto error_out;
			}
			tag_val=tag_val_obj->valuestring;
			// compare a/b/c with a/b/c/d is a miss.
			if(strlen(accept_tags[i].tag_val)<strlen(tag_val))
			{
				continue;
			}
			// compare a1a2/b1/c1 with a1a2/b/ is a miss.
			//make sure the overlap is ended with a '/' 
			if(0==strncmp(accept_tags[i].tag_val, tag_val, strlen(tag_val))&&
				(strlen(accept_tags[i].tag_val)==strlen(tag_val)||accept_tags[i].tag_val[strlen(tag_val)]=='/'))
			{
				return 1;
			}
		}
	}
	//no matched name is considered as a 
	if(name_matched>0)
	{
		return 0;
	}
	else
	{
		return 1;
	}
error_out:
		return -1;

}
//@param tag_set likes [{"tag":"location","value":["北京/朝阳/华严北里","上海/浦东/陆家嘴"]},{"tag":"isp","value":["电信","移动"]}]
static int compare_each_tag_set(cJSON* tag_set, const struct rule_tag* accept_tags, int n_accept)
{
	cJSON *tag_obj=NULL;
	int  n_tag=0, ret=0, matched=0;	
	n_tag=cJSON_GetArraySize(tag_set);
	for(int i=0; i<n_tag; i++)
	{
		tag_obj=cJSON_GetArrayItem(tag_set, i);
		if(!tag_obj||tag_obj->type!=cJSON_Object)
		{
			goto error_out;
		}
		ret=compare_each_tag(tag_obj,  accept_tags, n_accept);
		if(ret<0)
		{
			return -1;
		}
		if(ret==1)
		{
			matched++;
		}
	}
	if(matched==n_tag)
	{
		return 1;
	}
	else
	{
		return 0;
	}
error_out:
	return -1;
}
//@param value {"tag_sets":[[{"tag":"location","value":["北京/朝阳/华严北里","上海/浦东/陆家嘴"]},{"tag":"isp","value":["电信","移动"]}],[{"tag":"location","value":["北京"]},{"tag":"isp","value":["联通"]}]]}
//@return 1 on match, 0 on not match, -1 on error.
static int compare_accept_tag(const char* value,const struct rule_tag* accept_tags, int n_tags)
{
	cJSON *json=NULL;
	cJSON *tag_set_array=NULL, *tag_set=NULL;
	int ret=-1, n_set=0;
	json=cJSON_Parse(value);
	if(!json)
	{
		goto error_out;
	}
	tag_set_array=cJSON_GetObjectItem(json, "tag_sets");
	if(!tag_set_array||tag_set_array->type!=cJSON_Array)
	{
		goto error_out;
	}
	n_set=cJSON_GetArraySize(tag_set_array);
	for(int i=0; i<n_set; i++)
	{
		tag_set=cJSON_GetArrayItem(tag_set_array,i);
		if(!tag_set||tag_set->type!=cJSON_Array)
		{
			goto error_out;
		}
		ret=compare_each_tag_set(tag_set, accept_tags, n_tags);
		if(ret!=0)//match or error occurs.
		{
			break;
		}
	}
error_out:
	cJSON_Delete(json);
	return ret;
}

void * HASH_fetch_by_id(MESA_htable_handle hash,int id)
{
	return MESA_htable_search(hash,(unsigned char*)&(id),sizeof(id));
}
int HASH_add_by_id(MESA_htable_handle hash,int id,void*data)
{
	int ret=0;
	ret=MESA_htable_add(hash
					,(unsigned char*)&(id)
					,sizeof(id)
					,data);
	return ret;
}
int HASH_delete_by_id(MESA_htable_handle hash,int id)
{
	//destroy function had been initialized when hash create.
	int ret=-1;
	ret=MESA_htable_del(hash,(unsigned char*)&id, sizeof(id), NULL);
	return ret;
}
MAAT_RULE_EX_DATA rule_ex_data_new(const struct Maat_rule_head * rule_head, const char* srv_def, const struct compile_ex_data_idx* ex_desc)
{
	MAAT_RULE_EX_DATA ad=NULL;
	struct Maat_rule_t rule;
	fill_maat_rule(&rule, rule_head, srv_def, strlen(srv_def)+1);
	ex_desc->new_func(ex_desc->idx, &rule, srv_def, &ad, ex_desc->argl,ex_desc->argp);
	return ad;
}
void rule_ex_data_free(const struct Maat_rule_head * rule_head, const char* srv_def, MAAT_RULE_EX_DATA *ad, const struct compile_ex_data_idx* ex_desc)
{
	struct Maat_rule_t rule;
	fill_maat_rule(&rule, rule_head, srv_def, strlen(srv_def)+1);
	ex_desc->free_func(ex_desc->idx, &rule, srv_def, ad, ex_desc->argl,ex_desc->argp);
	return;
}


struct Maat_group_inner* create_group_rule(int group_id, int table_id, struct Maat_scanner *scanner)
{
	int ret=0;
	struct Maat_group_inner* group=ALLOC(struct Maat_group_inner, 1);
	group->group_id=group_id;
	group->region_cnt=0;
	group->region_boundary=0;
	group->ref_by_parent_cnt=0;
	group->regions=dynamic_array_create(1,8);
	group->table_id=table_id;
	group->group_name=NULL;
	group->vertex_id=scanner->grp_vertex_id_generator++;
	assert(igraph_vcount(&scanner->group_graph)==group->vertex_id);
	igraph_add_vertices(&scanner->group_graph, 1, NULL);	//Add 1 vertice.
	ret=HASH_add_by_id(scanner->vertex_id2group, group->vertex_id, group);
	assert(ret>0);
	ret=HASH_add_by_id(scanner->group_hash, group_id, group);
	assert(ret>0);
	pthread_mutex_init(&(group->mutex), NULL);
	return group;
}
void _destroy_group_rule(struct Maat_group_inner* group)
{
	if(group->regions) dynamic_array_destroy(group->regions,free);
	group->region_cnt=0;
	group->region_boundary=0;
	group->regions=NULL;
	group->ref_by_parent_cnt=0;
	group->group_id=-1;
	group->table_id=-1;
	free(group->group_name);
	group->group_name=NULL;
	free(group->top_groups);
	group->top_groups=NULL;
	pthread_mutex_destroy(&(group->mutex));
	free(group);

}
size_t print_igraph_vector(igraph_vector_t *v, char* buff, size_t sz) {
  long int i;
  int printed=0;
  for (i=0; i<igraph_vector_size(v); i++) {
    printed+=snprintf(buff+printed, sz-printed, " %li", (long int) VECTOR(*v)[i]);
  }
  return printed;
}

#define	DESTROY_GROUP_BY_REGION	0
#define	DESTROY_GROUP_BY_PARENT	1
#define	DESTROY_GROUP_BY_CHILD	2
void destroy_group_rule(struct Maat_group_inner* group_rule, int by_whom, struct Maat_scanner* scanner)
{
	switch(by_whom)
	{
		case	DESTROY_GROUP_BY_REGION:
			break;
		case	DESTROY_GROUP_BY_PARENT:
			group_rule->ref_by_parent_cnt--;
			break;
		case	DESTROY_GROUP_BY_CHILD:
			group_rule->ref_by_children_cnt--;
			break;
		default:
			assert(0);
			break;
	}
	igraph_vector_t v; 
	char buff[4096];
	if(group_rule->ref_by_parent_cnt==0&&group_rule->ref_by_children_cnt==0&&group_rule->region_cnt==0)
	{
		HASH_delete_by_id(scanner->group_hash, group_rule->group_id);
		HASH_delete_by_id(scanner->vertex_id2group, group_rule->vertex_id);	
		igraph_vector_init(&v, 8);
		igraph_neighbors(&scanner->group_graph, &v, group_rule->vertex_id, IGRAPH_ALL);
		if(igraph_vector_size(&v)>0)
		{
			print_igraph_vector(&v, buff, sizeof(buff));
			MESA_handle_runtime_log(scanner->logger_ref, RLOG_LV_FATAL, maat_module,
							"Del group %d exception, still reached by %s.",
							group_rule->vertex_id, buff);
			assert(0);
		}
		igraph_vector_destroy(&v);
		//Calling _destroy_group_rule on garbage collection to free memory.
		garbage_bagging(GARBAGE_GROUP_RULE, group_rule, scanner->tomb_ref);

	}
}
void make_group_set(struct Maat_compile_group_relation* relation, struct bool_expr* a_set, unsigned char *has_not)
{
	int i=0,j=0;
	a_set->user_tag=relation;
	struct Maat_group_inner*group=NULL;
	assert(relation->group_cnt<=MAX_ITEMS_PER_BOOL_EXPR);
	for(i=0,j=0;i<relation->group_boundary&&j<MAX_ITEMS_PER_BOOL_EXPR;i++)
	{
		group=(struct Maat_group_inner*)dynamic_array_read(relation->groups, i);
		if(group==NULL)
		{
			continue;
		}
		//high 32 bit is virtual table id, low 32 bit is group id.
		a_set->items[j].item_id=TO_RELATION_ID(relation->virtual_table_id[i], group->group_id);
		a_set->items[j].not_flag=relation->not_flag[i];
		if(a_set->items[j].not_flag)
		{
			*has_not=1;
		}
		j++;
	}
	assert(j==relation->group_cnt);
	a_set->item_num=j;
}
struct compile_walker
{
	MESA_lqueue_head update_q;
	long long compile_has_not_flag;
};
void walk_compile_hash(const uchar * key, uint size, void * data, void * user)
{
	struct bool_expr* one_set=NULL;
	struct Maat_compile_group_relation* relation=(struct Maat_compile_group_relation*)data;
	struct compile_walker* walker=(struct compile_walker*)user;
	unsigned char has_not_flag=0;
	MESA_lqueue_head update_q=walker->update_q;
	if(relation->compile==NULL)
	{
		return;
	}
	//make sure compile rule's each group has loadded.
	if((relation->group_cnt==relation->compile->declared_grp_num
		|| relation->compile->declared_grp_num==0)//for compatible old version
		&& relation->group_cnt>0
		&& relation->group_cnt!=relation->not_group_cnt)
	{
		one_set=ALLOC(struct bool_expr, 1);
		//reading compile rule is safe in update thread, mutex lock called when modified
		make_group_set(relation, one_set, &has_not_flag);
		if(has_not_flag)
		{
			walker->compile_has_not_flag++;
		}
		MESA_lqueue_join_tail(update_q, &one_set, sizeof(one_set));//put the pointer into queue
	}
	return;
}
struct bool_matcher* create_bool_matcher(MESA_htable_handle compile_hash, int thread_num, void* logger)
{
	struct bool_matcher* bm=NULL;
	struct compile_walker walker={NULL, 0};
	walker.update_q=MESA_lqueue_create(0,0);
	MESA_lqueue_head update_q=walker.update_q;
	long data_size=0;
	size_t mem_size=0;
	UNUSED MESA_queue_errno_t q_ret=MESA_QUEUE_RET_OK; 	
	data_size=sizeof(void*);
	struct bool_expr* one_set=NULL;
	struct bool_expr* set_array=NULL;
	int i=0;
	MESA_htable_iterate(compile_hash, walk_compile_hash, &walker);
	
	const long q_cnt=MESA_lqueue_get_count(update_q);
	if(q_cnt==0)
	{
		MESA_handle_runtime_log(logger, RLOG_LV_INFO, maat_module,
									"No compile rule to build a bool matcher.");
		MESA_lqueue_destroy(update_q, lqueue_destroy_cb, NULL);
		return NULL;
	}
	set_array=ALLOC(struct bool_expr, q_cnt);
	for(i=0; i<q_cnt; i++)
	{
		q_ret=(MESA_queue_errno_t)MESA_lqueue_get_head(update_q, &one_set, &data_size);
		assert(data_size==sizeof(struct bool_expr*) && q_ret==MESA_QUEUE_RET_OK);
		set_array[i]=*one_set;
		free(one_set);
		one_set=NULL;
	}
	MESA_handle_runtime_log(logger, RLOG_LV_INFO,maat_module,
								"build bool matcher start: compile count %ld, NOT-logic count %lld",
								q_cnt, walker.compile_has_not_flag);
	bm=bool_matcher_new(set_array, q_cnt, thread_num, &mem_size);
	if(bm!=NULL)
	{
		MESA_handle_runtime_log(logger, RLOG_LV_INFO, maat_module,
								"build bool matcher use %zu memory", mem_size);
	}
	else
	{
		MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module,
								"build bool matcher failed!",
								q_cnt);
	}
	free(set_array);
	set_array=NULL;
	MESA_lqueue_destroy(update_q, lqueue_destroy_cb, NULL);
	return bm;

}
void destroy_bool_matcher(struct bool_matcher * bm)
{
	bool_matcher_free(bm);
	return;

}
void EMPTY_FREE(void*p)
{
	return;
}

struct Maat_compile_rule* create_compile_rule(struct Maat_rule_head* p_head, const char* service_define, int declared_grp_num, double exec_seq, const struct Maat_table_schema* table)
{
	int i=0;
	struct Maat_compile_rule*p=ALLOC(struct Maat_compile_rule, 1);
	p->head=*p_head;
	p->declared_grp_num=declared_grp_num;
	p->ads=ALLOC(MAAT_RULE_EX_DATA, MAX_COMPILE_EX_DATA_NUM);

	//protect by feather->background_update_mutex
	p->ref_table=table;
	p->head.serv_def_len=strlen(service_define)+1;
	p->service_defined=ALLOC(char, p->head.serv_def_len);
	memcpy(p->service_defined, service_define, p->head.serv_def_len);
	p->evaluation_order=exec_seq;

	for(i=0; i<table->compile.ex_data_num; i++)
	{
		p->ads[i]=rule_ex_data_new(&p->head, p->service_defined, table->compile.ex_desc+i);
	}
	p->is_valid=1;
	return p;
}

void destroy_compile_rule(struct Maat_compile_rule* compile_rule)
{
	int i=0;
	const struct compile_table_schema* compile_desc= &(compile_rule->ref_table->compile);

	for(i=0; i<compile_desc->ex_data_num; i++)
	{
		rule_ex_data_free(&(compile_rule->head), compile_rule->service_defined, compile_rule->ads+i, compile_desc->ex_desc+i);
		compile_rule->ads[i]=NULL;
	}
	free(compile_rule->ads);

	compile_rule->is_valid=0;
	compile_rule->declared_grp_num=-1;
	free(compile_rule->service_defined);
	compile_rule->service_defined=NULL;
	free(compile_rule);
	return;
}
struct Maat_compile_group_relation * create_compile_group_relation(int compile_id, struct Maat_scanner *scanner)
{
	int ret=0;
	struct Maat_compile_group_relation* p=ALLOC(struct Maat_compile_group_relation, 1);
	p->magic_num=COMPILE_RELATION_MAGIC;
	p->compile_id=compile_id;
	p->group_cnt=0;
	p->group_boundary=1;
	p->groups=dynamic_array_create(1, 1);
	pthread_rwlock_init(&(p->rwlock), NULL);
	ret=HASH_add_by_id(scanner->compile_hash, compile_id, p);
	assert(ret>0);
	return p;
}

void _destroy_compile_group_relation(struct Maat_compile_group_relation * cg_relation)
{
	assert(cg_relation->magic_num==COMPILE_RELATION_MAGIC);
	pthread_rwlock_wrlock(&(cg_relation->rwlock));
	cg_relation->compile_id=-1;
	dynamic_array_destroy(cg_relation->groups, NULL);
	pthread_rwlock_unlock(&(cg_relation->rwlock));

	pthread_rwlock_destroy(&(cg_relation->rwlock));

	free(cg_relation);
}
void destroy_compile_group_relation(struct Maat_compile_group_relation * p, struct Maat_scanner *scanner)
{
	int i=0;
	UNUSED struct Maat_group_inner* p_group=NULL;
	assert(p->group_cnt==0);
	assert(p->compile==NULL);
	for(i=0;i<p->group_boundary;i++)
	{
		p_group=(struct Maat_group_inner*)dynamic_array_read(p->groups, i);
		assert(p_group==NULL);
	}
	assert(p->magic_num==COMPILE_RELATION_MAGIC);
	HASH_delete_by_id(scanner->compile_hash, p->compile_id);
	garbage_bagging(GARBAGE_COMPILE_GOURP_RELATION, p, scanner->tomb_ref);
}
scan_rule_t* create_rs_str_rule(unsigned int sub_type,enum MAAT_MATCH_METHOD match_method,int is_case_sensitive,const char* string,int len,int l_offset,int r_offset)
{
	scan_rule_t* p_rule=(scan_rule_t* )calloc(sizeof(scan_rule_t),1);
	p_rule->rule_type=RULETYPE_STR;
	p_rule->sub_type=sub_type;
	
	p_rule->string_rule.case_sensitive=is_case_sensitive;
	p_rule->string_rule.match_mode=0;
	p_rule->string_rule.l_offset=-1;
	p_rule->string_rule.r_offset=-1;
	switch(match_method)
	{
		case MATCH_METHOD_COMPLETE:
			p_rule->string_rule.match_mode=1;
			break;
		case MATCH_METHOD_LEFT:
			p_rule->string_rule.l_offset=-2;
			break;
		case MATCH_METHOD_RIGHT:
			p_rule->string_rule.r_offset=-2;
			break;
		case MATCH_METHOD_SUB:
			p_rule->string_rule.l_offset=l_offset;
			p_rule->string_rule.r_offset=r_offset;			
			break;
		default:
			assert(0);
			break;	
	}
	p_rule->string_rule.len=len;
	p_rule->string_rule.str=(char*)calloc(sizeof(char),len);
	memcpy(p_rule->string_rule.str,string,len);
	return p_rule;

}
void destroy_rs_str_rule(scan_rule_t* p_rule)
{
	free(p_rule->string_rule.str);
	free(p_rule);
}
scan_rule_t* create_rs_ip_rule(unsigned int sub_type,struct db_ip_rule_t *db_ip_rule)
{
	scan_rule_t *p_rule=(scan_rule_t*)calloc(sizeof(scan_rule_t),1);
	if(db_ip_rule->addr_type==4)
	{
		p_rule->rule_type=RULETYPE_IPv4;
		memcpy(&(p_rule->ipv4_rule),&(db_ip_rule->ipv4_rule),sizeof(p_rule->ipv4_rule));
	}
	else
	{
		p_rule->rule_type=RULETYPE_IPv6;
		memcpy(&(p_rule->ipv6_rule),&(db_ip_rule->ipv6_rule),sizeof(p_rule->ipv6_rule));
	}
	p_rule->sub_type=sub_type;
	return p_rule;
}
void destroy_rs_ip_rule(scan_rule_t* p)
{
	free(p);
}
scan_rule_t* create_rs_intval_rule(unsigned int sub_type,struct db_intval_rule *intval_rule)
{
	scan_rule_t *p_rule=(scan_rule_t*)calloc(sizeof(scan_rule_t),1);
	p_rule->rule_type=RULETYPE_INT;
	p_rule->sub_type=sub_type;
	p_rule->interval_rule.lb=intval_rule->intval.lb;
	p_rule->interval_rule.ub=intval_rule->intval.ub;
	return p_rule;
}
void destroy_rs_intval_rule(scan_rule_t* p)
{
	free(p);
}

struct op_expr_t* create_op_expr(unsigned int expr_id,int operation,void* u_para,int table_id)
{
	struct op_expr_t* op_expr=NULL;
	op_expr=(struct op_expr_t*)calloc(sizeof(struct op_expr_t),1);
	op_expr->no_effect_convert_cnt=0;
	op_expr->convert_failed=0;
	op_expr->p_expr=(boolean_expr_t*)calloc(sizeof(boolean_expr_t),1);
	op_expr->p_expr->expr_id=expr_id;
	op_expr->p_expr->operation=operation;
	op_expr->p_expr->rnum=0;
	op_expr->p_expr->rules=NULL;
	op_expr->p_expr->tag=u_para;
	op_expr->table_id=table_id;
	return op_expr;
}
void destroy_op_expr(struct op_expr_t*  op_expr)
{
	unsigned int i=0;
	for(i=0;i<op_expr->p_expr->rnum;i++)
	{
		switch(op_expr->p_rules[i]->rule_type)
		{
			case RULETYPE_STR:
			case RULETYPE_REG:
				destroy_rs_str_rule(op_expr->p_rules[i]);
				break;
			case RULETYPE_IPv4:
			case RULETYPE_IPv6:
				destroy_rs_ip_rule(op_expr->p_rules[i]);
				break;
			case RULETYPE_INT:
				destroy_rs_intval_rule(op_expr->p_rules[i]);
				break;
			default:
				assert(0);
				break;
		}
		op_expr->p_rules[i]=NULL;
	}
	free(op_expr->p_expr);
	op_expr->p_expr=NULL;
	free(op_expr);
}
void op_expr_add_rule(struct op_expr_t* op_expr,scan_rule_t* p_rule)
{
	int idx=op_expr->p_expr->rnum;
	op_expr->p_rules[idx]=p_rule;
	op_expr->p_expr->rnum++;
	op_expr->rule_type=p_rule->rule_type;
	return;
}

struct Maat_scanner* create_maat_scanner(unsigned int version,_Maat_feather_t *feather)
{
	int scan_thread_num=feather->scan_thread_num;
	UNUSED int ret=0;
	
	MESA_htable_create_args_t hargs;
	memset(&hargs,0,sizeof(hargs));
	hargs.thread_safe=0;
	hargs.hash_slot_size = 1024*1024;
	hargs.max_elem_num = 0;
	hargs.eliminate_type = HASH_ELIMINATE_ALGO_FIFO;
	hargs.expire_time = 0;
	hargs.key_comp = NULL;
	hargs.key2index = NULL;
	hargs.recursive = 0; 
//	hargs.data_free = _void_destroy_compile_rule;
	hargs.data_free = EMPTY_FREE;

	hargs.data_expire_with_condition = NULL;

	struct Maat_scanner* scanner=NULL;
	scanner=ALLOC(struct Maat_scanner, 1);

	//Function Maat_cmd_append will access compile_hash in user thread.
	hargs.thread_safe=8;
	scanner->compile_hash=MESA_htable_create(&hargs, sizeof(hargs));
	MESA_htable_print_crtl(scanner->compile_hash,0);

	hargs.thread_safe=8;
	scanner->group_hash=MESA_htable_create(&hargs, sizeof(hargs));
	MESA_htable_print_crtl(scanner->group_hash,0);

	scanner->vertex_id2group=MESA_htable_create(&hargs, sizeof(hargs));
	MESA_htable_print_crtl(scanner->vertex_id2group,0);

	hargs.thread_safe=8;
	scanner->exprid_hash=MESA_htable_create(&hargs, sizeof(hargs));
	MESA_htable_print_crtl(scanner->exprid_hash, 0);


	hargs.thread_safe=0;
	hargs.data_free = free;
	scanner->region_hash=MESA_htable_create(&hargs, sizeof(hargs));
	MESA_htable_print_crtl(scanner->region_hash,0);

	ret=igraph_empty(&scanner->group_graph, 0, IGRAPH_DIRECTED);
	assert(ret==IGRAPH_SUCCESS);

	scanner->district_map=map_create();
	
	scanner->version=version;
	scanner->cfg_num=0;
	scanner->dedup_expr_num=0;
	scanner->max_thread_num=scan_thread_num;
	//optimized for CPU cache_alignment 64
	scanner->ref_cnt=alignment_int64_array_alloc(scan_thread_num);
	scanner->region_update_q=MESA_lqueue_create(0, 0);
	scanner->region=rulescan_initialize(scan_thread_num);
	
	//For best scan performance:
	//1.Do NOT set this option, rulescan return no hit detail as default;
	//2.Set necessary STR rule to QUICK;
	if(feather->rule_scan_type==1)
	{
		rulescan_set_param(scanner->region,RULESCAN_DETAIL_RESULT,NULL,0);
	}
	else if(feather->rule_scan_type==2)
	{
		rulescan_set_param(scanner->region,RULESCAN_DETAIL_RESULT,NULL,0);
		rulescan_set_param(scanner->region,RULESCAN_REGEX_GROUP,NULL,0);
	}
	scanner->tomb_ref=feather->garbage_q;
	scanner->logger_ref=feather->logger;
	scanner->region_rslt_buff=ALLOC(scan_result_t, MAX_SCANNER_HIT_NUM*scan_thread_num);
	scanner->gie_rslt_buff=ALLOC(GIE_result_t, MAX_SCANNER_HIT_NUM*scan_thread_num);
	scanner->table_rt_mgr=Maat_table_runtime_manager_create(feather->table_mgr, feather->scan_thread_num);
	scanner->max_table_num=Maat_table_manager_get_size(feather->table_mgr);
	return scanner;
}



void destroy_maat_scanner(struct Maat_scanner*scanner)
{
	long q_cnt=0,data_size=0;
	int i=0,j=0;
	UNUSED int q_ret=0;
	struct op_expr_t* op_expr=NULL;
	if(scanner==NULL)
	{
		return;
	}
	rulescan_destroy(scanner->region);
	MESA_htable_destroy(scanner->compile_hash,(void (*)(void*))_destroy_compile_group_relation);
	MESA_htable_destroy(scanner->group_hash, (void (*)(void*))_destroy_group_rule);
	MESA_htable_destroy(scanner->exprid_hash, NULL);
	MESA_htable_destroy(scanner->region_hash, NULL);
	MESA_htable_destroy(scanner->vertex_id2group, NULL);

	map_destroy(scanner->district_map);
	scanner->district_map=NULL;
	assert(scanner->tmp_district_map==NULL);
	destroy_bool_matcher(scanner->bool_matcher_expr_compiler);
	q_cnt=MESA_lqueue_get_count(scanner->region_update_q);
	for(i=0;i<q_cnt;i++)
	{
		data_size=sizeof(struct op_expr_t*);
		q_ret=(MESA_queue_errno_t)MESA_lqueue_get_head(scanner->region_update_q,&op_expr,&data_size);
		assert(data_size==sizeof(void*)&&q_ret==MESA_QUEUE_RET_OK);
		destroy_op_expr(op_expr);
	}	
	MESA_lqueue_destroy(scanner->region_update_q, lqueue_destroy_cb, NULL);
	free(scanner->region_rslt_buff);
	scanner->region_rslt_buff=NULL;
	free(scanner->gie_rslt_buff);
	scanner->gie_rslt_buff=NULL;
	alignment_int64_array_free(scanner->ref_cnt);
	scanner->ref_cnt=NULL;
	for(i=0;i<MAX_CHARSET_NUM;i++)
	{
		for(j=0;j<MAX_CHARSET_NUM;j++)
		{
			if(scanner->iconv_handle[i][j]!=NULL)
			{
				iconv_close(scanner->iconv_handle[i][j]);
			}
		}
	}
	Maat_table_rt_manager_destroy(scanner->table_rt_mgr);
	scanner->table_rt_mgr=NULL;

	igraph_destroy(&scanner->group_graph);
	free(scanner);
	return;
}


unsigned int make_sub_type(unsigned short table_id,enum MAAT_CHARSET charset,int do_charset_merge)
{
	unsigned int sub_type=0;
	if(do_charset_merge==TRUE)
	{
		sub_type=table_id<<4|CHARSET_NONE;
	}
	else
	{
		sub_type=table_id<<4|charset;
	}
	assert(sub_type<MAX_SUB_RULETYPE);
	return sub_type;
}


void destroy_ip_expr(boolean_expr_t*p)
{
	free(p->rules);
	free(p);
	return;
}
struct _region_stat_t
{
	int cfg_num;
	union
	{
		int expr_rule_cnt;	//expr_type=0,1,3
		int ipv4_rule_cnt;
	};
	union
	{
		int regex_rule_cnt;	//expr_type=2
		int ipv6_rule_cnt;
	};
};
void count_rs_region(struct op_expr_t* op_expr,struct _region_stat_t* region_stat, size_t size)
{
	int op=0;
	if(op_expr->p_expr->operation==0)//add
	{
		op=1;
	}
	else if(op_expr->p_expr->operation==1)//delete
	{
		op=-1;
	}
	else
	{
		assert(0);
	}
	region_stat[op_expr->table_id].cfg_num+=op;
	switch(op_expr->rule_type)
	{
		case RULETYPE_STR:
			region_stat[op_expr->table_id].expr_rule_cnt+=op;
			break;
		case RULETYPE_REG:
			region_stat[op_expr->table_id].regex_rule_cnt+=op;
			break;
		case RULETYPE_INT:
			break;
		case RULETYPE_IPv4:
			region_stat[op_expr->table_id].ipv4_rule_cnt+=op;
			break;
		case RULETYPE_IPv6:
			region_stat[op_expr->table_id].ipv6_rule_cnt+=op;
			break;
		default:
			assert(0);
			break;
	}
	return;
}

void rulescan_batch_update(rule_scanner_t rs_handle,MESA_lqueue_head expr_queue,void*logger,struct Maat_scanner* maat_scanner)
{
	long data_size=0, i=0;
	unsigned int j=0;
	int ret=0;
	unsigned int failed_ids[MAX_FAILED_NUM];
	char failed_info[512], *p=NULL;
	UNUSED	MESA_queue_errno_t q_ret=MESA_QUEUE_RET_OK; 
	memset(failed_ids,0,sizeof(failed_ids));
	memset(failed_info,0,sizeof(failed_info));
	const long q_cnt=MESA_lqueue_get_count(expr_queue);
	struct timespec start,end;
	unsigned long long update_interval=0;
	size_t max_table_num=maat_scanner->max_table_num;
	struct _region_stat_t region_counter[max_table_num];
	memset(region_counter, 0, sizeof(region_counter));
	struct Maat_table_runtime* table_rt=NULL;
	if(q_cnt==0)
	{
		return;
	}
	boolean_expr_t* to_update_expr= ALLOC(boolean_expr_t, q_cnt);
	struct op_expr_t* op_expr=NULL;
	for(i=0;i<q_cnt;i++)
	{
		data_size=sizeof(void*);
		q_ret=(MESA_queue_errno_t)MESA_lqueue_get_head(expr_queue,&op_expr,&data_size);
		assert(data_size==sizeof(void*)&&q_ret==MESA_QUEUE_RET_OK);
		memcpy(&(to_update_expr[i]),op_expr->p_expr,sizeof(boolean_expr_t));
		//make a whole memory chunk
		to_update_expr[i].rules= ALLOC(scan_rule_t, op_expr->p_expr->rnum);
		for(j=0;j<op_expr->p_expr->rnum;j++)
		{
			memcpy(&(to_update_expr[i].rules[j]),op_expr->p_rules[j],sizeof(scan_rule_t));
			if(to_update_expr[i].rules[j].rule_type==RULETYPE_REG||to_update_expr[i].rules[j].rule_type==RULETYPE_STR)
			{
				to_update_expr[i].rules[j].string_rule.str=(char*)calloc(sizeof(char),to_update_expr[i].rules[j].string_rule.len);
				memcpy(to_update_expr[i].rules[j].string_rule.str
					,op_expr->p_rules[j]->string_rule.str
					,to_update_expr[i].rules[j].string_rule.len);
			}
		}
		
		count_rs_region(op_expr, region_counter, max_table_num);
		destroy_op_expr(op_expr);
		op_expr=NULL;
	}
	MESA_handle_runtime_log(logger,RLOG_LV_INFO,maat_module ,
							"rs_handle %p rulescan_update %ld rules.",rs_handle,q_cnt);
	clock_gettime(CLOCK_MONOTONIC,&start);
	ret=rulescan_update(rs_handle, to_update_expr,q_cnt, failed_ids,MAX_FAILED_NUM);
	clock_gettime(CLOCK_MONOTONIC,&end);
	if(ret!=1)
	{
		p=failed_info;
		for(i=0;i<failed_ids[0]&&i<MAX_FAILED_NUM-1&&sizeof(failed_info)-(p-failed_info)>10;i++)
		{
			p+=snprintf(p,sizeof(failed_info)-(p-failed_info),"%d,",failed_ids[i+1]);
		}
		MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
							"rulescan_update error,when batch update %ld rules,regex error %u.",q_cnt,failed_ids[0]);
		assert(0);
	}
	update_interval=(end.tv_sec-start.tv_sec)*1000000000+end.tv_nsec-start.tv_nsec;
	MESA_handle_runtime_log(logger,RLOG_LV_INFO,maat_module ,
							"rs_handle %p rulescan_update with %2.2e (%llu) ns."
							,rs_handle
							,(double)update_interval
							,update_interval);
	//update scanner's region cnt;
	for(i=0; (size_t)i<max_table_num; i++)
	{
		table_rt=Maat_table_runtime_get(maat_scanner->table_rt_mgr, i);
		if(table_rt==NULL)
		{
			continue;
		}
		switch(table_rt->table_type)
		{
			case TABLE_TYPE_EXPR:
			case TABLE_TYPE_EXPR_PLUS:
				table_rt->expr.expr_rule_cnt+=region_counter[i].expr_rule_cnt;
				table_rt->expr.regex_rule_cnt+=region_counter[i].regex_rule_cnt;
				assert(table_rt->expr.expr_rule_cnt>=0);
				assert(table_rt->expr.regex_rule_cnt>=0);
				break;
			case TABLE_TYPE_IP:
			case TABLE_TYPE_IP_PLUS:
				table_rt->ip.ipv4_rule_cnt+=region_counter[i].ipv4_rule_cnt;
				table_rt->ip.ipv6_rule_cnt+=region_counter[i].ipv6_rule_cnt;
				break;
			default:
				break;
		}
		assert(table_rt->origin_rule_num>=0);
	}
	for(i=0;i<q_cnt;i++)
	{
		for(j=0;j<to_update_expr[i].rnum;j++)
		{
			if(to_update_expr[i].rules[j].rule_type==RULETYPE_REG||to_update_expr[i].rules[j].rule_type==RULETYPE_STR)
			{
				free(to_update_expr[i].rules[j].string_rule.str);
			}
		}
		free(to_update_expr[i].rules);
	}
	free(to_update_expr);
}

struct region_group_relation
{
	int region_id;
	int group_id;
	int array_idx;
};
int region_group_relation_add(MESA_htable_handle region_hash, int region_id, int group_id, int array_idx)
{
	struct region_group_relation* relation=ALLOC(struct region_group_relation, 1);
	relation->region_id=region_id;
	relation->group_id=group_id;
	relation->array_idx=array_idx;
	int ret=HASH_add_by_id(region_hash, region_id, relation);
	if(ret<0)
	{
		free(relation);
		return -1;
	}
	else
	{
		return 0;
	}
}
struct region_group_relation* region_group_relation_get(MESA_htable_handle region_hash, int region_id)
{
	struct region_group_relation* relation=NULL;
	relation=(struct region_group_relation*)HASH_fetch_by_id(region_hash, region_id);
	return relation;
}
int region_group_relation_del(MESA_htable_handle region_hash, int region_id)
{
	int	ret=HASH_delete_by_id(region_hash,region_id);
	if(ret==-1)
	{
		return -1;
	}
	else
	{
		return 0;
	}
}
struct Maat_group_inner* add_region_to_group(struct Maat_group_inner* group,int table_id,int region_id,int district_id,int expr_id,enum MAAT_TABLE_TYPE region_type, struct Maat_scanner* scanner)
{
	struct Maat_region_inner* region_rule=NULL;
	struct region_group_relation* relation=NULL;
	relation=region_group_relation_get(scanner->region_hash, region_id);
	int array_idx;
	pthread_mutex_lock(&(group->mutex));
	if(relation==NULL)
	{
		region_rule=ALLOC(struct Maat_region_inner, 1);
		region_rule->region_id=region_id;
		region_rule->expr_id_cnt=1;
		region_rule->expr_id_ub=region_rule->expr_id_lb=expr_id;
		region_rule->district_id=district_id;
		region_rule->table_type=region_type;
		region_rule->table_id=table_id;

		dynamic_array_write(group->regions, group->region_boundary, region_rule);
		array_idx=group->region_boundary;
		region_group_relation_add(scanner->region_hash, region_id, group->group_id, array_idx);
		group->region_cnt++;
		group->region_boundary++;
	}
	else
	{
		assert(relation->group_id==group->group_id);
		assert(relation->array_idx<group->region_boundary);
		array_idx=relation->array_idx;
		region_rule=(struct Maat_region_inner*)dynamic_array_read(group->regions, array_idx);
		assert(expr_id==region_rule->expr_id_ub+1);
		region_rule->expr_id_ub=expr_id;
		region_rule->expr_id_cnt++;
	}
	HASH_add_by_id(scanner->exprid_hash, expr_id, (void*)(long long)array_idx);
	pthread_mutex_unlock(&(group->mutex));

	return group;
}
void cancel_last_region_from_group(struct Maat_group_inner* group,int region_id,int expr_id, struct Maat_scanner* scanner)
{
	struct Maat_region_inner* region_rule=NULL;
	struct region_group_relation* relation=NULL;
	relation=region_group_relation_get(scanner->region_hash, region_id);
	assert(relation->group_id==group->group_id);
	assert(relation->array_idx==group->region_boundary-1);
	int array_idx=relation->array_idx;
	pthread_mutex_lock(&(group->mutex));
	region_rule=(struct Maat_region_inner*)dynamic_array_read(group->regions, array_idx);
	assert(region_rule->expr_id_ub==expr_id&&region_rule->region_id==region_id);
	if(region_rule->expr_id_cnt==1)
	{
		free(region_rule);
		dynamic_array_write(group->regions, group->region_boundary, NULL);
		group->region_cnt--;
		group->region_boundary--;
		relation=NULL;
		region_group_relation_del(scanner->region_hash, region_id);
	}
	else
	{
		region_rule->expr_id_ub--;
		region_rule->expr_id_cnt--;
	}
	HASH_delete_by_id(scanner->exprid_hash, expr_id);
	pthread_mutex_unlock(&(group->mutex));	
	return;
}
unsigned int del_region_from_group(struct Maat_group_inner* group,int region_id,unsigned int *output_expr_id, int output_size, struct Maat_scanner* scanner)
{
	int i=0, j=0, ret=0;
	struct Maat_region_inner* region_rule=NULL;
	struct region_group_relation* relation=NULL;
	relation=region_group_relation_get(scanner->region_hash, region_id);
	if(relation)
	{	
		pthread_mutex_lock(&(group->mutex));
		assert(relation->group_id==group->group_id);
		region_rule=(struct Maat_region_inner*)dynamic_array_read(group->regions, relation->array_idx);
		dynamic_array_write(group->regions, relation->array_idx, NULL);
		for(i=0;i<region_rule->expr_id_cnt;i++)
		{
			output_expr_id[i]=region_rule->expr_id_lb+i;			
			assert(output_expr_id[i]>=0);
		}
		assert(i<=output_size); 
		region_rule->region_id=0;
		free(region_rule);
		region_rule=NULL;
		group->region_cnt--;
		assert(group->region_cnt>=0);
		relation=NULL;
		ret=region_group_relation_del(scanner->region_hash, region_id);
		assert(ret==0);		
		pthread_mutex_unlock(&(group->mutex));
	}
	for(j=0; j<i; j++)
	{
		ret=HASH_delete_by_id(scanner->exprid_hash, output_expr_id[j]);
		assert(ret==0);
	}

	return i;
}

int add_group_to_compile(struct Maat_compile_group_relation*relation, struct Maat_group_inner* a_rule_group, int virual_table_id, int not_flag)
{
	int i=0,ret=-1;
	int write_pos=-1;
	struct Maat_group_inner* p=NULL;
	
	pthread_rwlock_wrlock(&(relation->rwlock));
	if(relation->compile!=NULL
		&& relation->group_cnt>=relation->compile->declared_grp_num
		&& relation->compile->declared_grp_num!=0)
	{
		ret=-1;
		goto error_out;
	}

	for(i=0;i<relation->group_boundary;i++)
	{
		p=(struct Maat_group_inner*)dynamic_array_read(relation->groups,i);
		if(p==NULL)
		{
			write_pos=i;
		}
		else
		{
			if(p->group_id==a_rule_group->group_id && relation->virtual_table_id[i]==virual_table_id)//duplicate group
			{
				ret=-1;
				goto error_out;
			}
		}
	}
	if(write_pos<0&&relation->group_boundary==MAX_EXPR_ITEM_NUM)
	{
		ret=-1;
		goto error_out;
	}
	if(write_pos<0)
	{
		write_pos=relation->group_boundary;
		relation->group_boundary++;
	}
	dynamic_array_write(relation->groups, write_pos, a_rule_group);
	if(not_flag)
	{
		relation->not_flag[write_pos]=1;
		relation->not_group_cnt++;
	}
	else
	{
		relation->not_flag[write_pos]=0;
	}
	relation->virtual_table_id[write_pos]=virual_table_id;
	relation->group_cnt++;
	a_rule_group->ref_by_parent_cnt++;
	ret=1;
error_out:
	pthread_rwlock_unlock(&(relation->rwlock));

	return ret;
}
struct Maat_group_inner* del_group_from_compile(struct Maat_compile_group_relation*relation, int group_id, int virual_table_id)
{
	int i=0;
	struct Maat_group_inner* group_rule=NULL;
	pthread_rwlock_wrlock(&(relation->rwlock));
	for(i=0;i<MAAT_MAX_EXPR_ITEM_NUM;i++)
	{
		group_rule=(struct Maat_group_inner*)dynamic_array_read(relation->groups,i);
		if(group_rule==NULL)
		{
			continue;
		}
		if(group_rule->group_id==group_id && relation->virtual_table_id[i]==virual_table_id)
		{
			dynamic_array_write(relation->groups,i,NULL);			
			if(relation->not_flag[i]==1)
			{
				relation->not_group_cnt--;
				relation->not_flag[i]=0;
			}
			relation->virtual_table_id[i]=0;
			relation->group_cnt--;
			break;
		}
		else
		{
			group_rule=NULL;
		}
	}
	pthread_rwlock_unlock(&(relation->rwlock));
	return group_rule;
}

int sync_region(MESA_htable_handle region_hash,int region_id, int group_id, const char* table_name, int is_valid, void*logger)
{
	struct region_group_relation* relation=NULL;
	relation=region_group_relation_get(region_hash, region_id);
	if(is_valid==TRUE)
	{
		if(relation)
		{
			MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
								"region id %d of table %s is already in group %d.",
								region_id, table_name, relation->group_id);
			return -1;
		}
	}
	else
	{
		if(!relation)
		{
			MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
								"region delete error, id %d in table %s does not exisit.",
								region_id, table_name);
			return -1;
		}
		else
		{
			if(group_id!=relation->group_id)
			{
				MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
									"region delete error, id %d in table %s is already in group %d, but cmd want to delete from group %d.",
									region_id, table_name,
									relation->group_id, group_id);
				return -1;
			}
		}
	}
	return 1;
}
int get_district_id(Maat_scanner *scanner,const char* district_str)
{
	int map_ret=0,district_id=-1;
	map_ret=map_str2int(scanner->district_map, district_str,&district_id);
	if(map_ret<0)
	{
		if(scanner->tmp_district_map==NULL)
		{
			scanner->tmp_district_map=map_duplicate(scanner->district_map);
		}
		map_ret=map_str2int(scanner->tmp_district_map, district_str,&district_id);
		if(map_ret<0)
		{
			district_id= scanner->district_num;
			map_register(scanner->tmp_district_map,district_str, district_id);
			scanner->district_num++;
		}
	}
	return district_id;
}
int add_expr_rule(struct Maat_table_schema* table,struct db_str_rule_t* db_rule,struct Maat_scanner *scanner,void* logger)
{
	unsigned int i=0,j=0;
	char* p=NULL,*saveptr=NULL,*region_string=NULL;
	int region_str_len=0,ret=0,k=0;
	int expr_id=0,district_id=-1;
	struct expr_table_schema* expr_desc=&(table->expr);
	scan_rule_t*p_rule=NULL;
	struct Maat_group_inner* group_rule=NULL;
	enum MAAT_CHARSET dst_charset=CHARSET_NONE;
	char *sub_key_array[MAAT_MAX_EXPR_ITEM_NUM];
	int key_left_offset[MAAT_MAX_EXPR_ITEM_NUM]={-1},key_right_offset[MAAT_MAX_EXPR_ITEM_NUM]={-1};
	for(i=0;i<MAAT_MAX_EXPR_ITEM_NUM;i++)
	{
		key_left_offset[i]=-1;
		key_right_offset[i]=-1;
	}
	int sub_expr_cnt=0;
	struct op_expr_t *op_expr=NULL;
	struct Maat_group_inner* u_para=NULL;

	if(table->table_type==TABLE_TYPE_EXPR_PLUS)
	{
		assert(strlen(db_rule->district)>0);
		str_unescape(db_rule->district);
		district_id=get_district_id(scanner, db_rule->district);
	}
	group_rule=(struct Maat_group_inner*)HASH_fetch_by_id(scanner->group_hash, db_rule->group_id);
	if(group_rule==NULL)
	{
		group_rule=create_group_rule(db_rule->group_id, 0, scanner);
	}
	switch(db_rule->expr_type)
	{
		case EXPR_TYPE_AND:
			for(i=0,p=db_rule->keywords;;i++,p=NULL)
			{
				if(i>=MAAT_MAX_EXPR_ITEM_NUM)
				{
					MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
							"Table %s region cfg %d too many expr.",table->table_name[table->updating_name],db_rule->region_id);
					return -1;
				}
				sub_key_array[i]=strtok_r_esc(p,'&',&saveptr);
				if(sub_key_array[i]==NULL)
				{
					break;
				}
				sub_key_array[i]=str_unescape(sub_key_array[i]);
			}
			sub_expr_cnt=i;
			break;
		case EXPR_TYPE_OFFSET:
			for(i=0,p=db_rule->keywords;;i++,p=NULL)
			{
				if(i>=MAAT_MAX_EXPR_ITEM_NUM)
				{
					MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
							"Table %s region cfg %d too many expr.",table->table_name[table->updating_name],db_rule->region_id);
					return -1;
				}
				sub_key_array[i]=strtok_r_esc(p,'&',&saveptr);
				if(sub_key_array[i]==NULL)
				{
					break;
				}
				sscanf(sub_key_array[i],"%d-%d:",&(key_left_offset[i]),&(key_right_offset[i]));
				if(!(key_left_offset[i]>=0&&key_right_offset[i]>0&&key_left_offset[i]<=key_right_offset[i]))
				{
					MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
							"Table %s region cfg %d invalid offset.",table->table_name[table->updating_name],db_rule->region_id);
					return -1;
				}
				sub_key_array[i]=(char*)memchr(sub_key_array[i],':',strlen(sub_key_array[i]));
				if(sub_key_array[i]==NULL)
				{
					MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
							"Table %s region cfg %d invalid offset keyword format.",table->table_name[table->updating_name],db_rule->region_id);
					return -1;
				}
				sub_key_array[i]++;//jump over ':'
				sub_key_array[i]=str_unescape(sub_key_array[i]);
			}
			sub_expr_cnt=i;
			break;
		case EXPR_TYPE_REGEX://it's easy,no need to charset convert
			expr_id=scanner->exprid_generator++;
			u_para=add_region_to_group(group_rule, table->table_id, db_rule->region_id, district_id, expr_id, TABLE_TYPE_EXPR, scanner);
			if(u_para==NULL)
			{
				return -1;
			}
			op_expr=create_op_expr(expr_id
						,0
						,u_para
						,table->table_id);
			for(i=0,p=db_rule->keywords;;i++,p=NULL)
			{
				if(i>=MAAT_MAX_EXPR_ITEM_NUM)
				{
					MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
							"Table %s region cfg %d too many expr.",table->table_name[table->updating_name],db_rule->region_id);
					return -1;
				}
				sub_key_array[i]=strtok_r_esc(p,'&',&saveptr);
				if(sub_key_array[i]==NULL)
				{
					break;
				}
				sub_key_array[i]=str_unescape_and(sub_key_array[i]);//regex remain use str_unescape_and
				p_rule=create_rs_str_rule(make_sub_type(table->table_id,CHARSET_NONE,0)
										,MATCH_METHOD_SUB//not care db_rule->match_method
										,db_rule->is_case_sensitive
										,sub_key_array[i]
										,strlen(sub_key_array[i])
										,-1
										,-1);
				p_rule->rule_type=RULETYPE_REG;
				op_expr_add_rule(op_expr, p_rule);
			
			}
			MESA_lqueue_join_tail(scanner->region_update_q,&op_expr, sizeof(void*));
			return 0;//yes,we returned.
			break;
		case EXPR_TYPE_STRING:
			sub_expr_cnt=1;
			sub_key_array[0]=db_rule->keywords;
			sub_key_array[0]=str_unescape(sub_key_array[0]);
			break;
		default:
			break;
	}
	for(k=0;k<sub_expr_cnt;k++)
	{
		if(strlen(sub_key_array[k])==0)// keyword like "aa&&cc" or "aa&bb&" will cause strlen==0
		{
			MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
					"Table %s region cfg %d has an empty sub string.",
					table->table_name[table->updating_name],db_rule->region_id);
			//this sub string will jump over before iconv_convert
		}
	}
	if(db_rule->is_hexbin==FALSE)
	{
		for(j=0;j<MAX_CHARSET_NUM;j++)
		{
			dst_charset=expr_desc->dst_charset[j];
			if(dst_charset==CHARSET_NONE)
			{
				break;
			}
			expr_id=scanner->exprid_generator++;
			u_para=add_region_to_group(group_rule,table->table_id, db_rule->region_id,district_id,expr_id, table->table_type, scanner);
			if(u_para==NULL)//duplicate
			{
				return -1;
			}
			op_expr=create_op_expr(expr_id
									,0	//add
									,u_para
									,table->table_id
									);
			for(k=0;k<sub_expr_cnt;k++)
			{
				if(strlen(sub_key_array[k])==0)
				{
						continue;
				}
				region_str_len=strlen(sub_key_array[k])*8+1; // 1 byte map to 8 bytes maximum, e.g. "&#x0627;" or "\u63221;"
				region_string=(char*)calloc(sizeof(char),region_str_len);
				if(expr_desc->src_charset!=dst_charset)//need convert
				{

					ret=universal_charset_convert(scanner,expr_desc->src_charset, dst_charset, 
										sub_key_array[k],strlen(sub_key_array[k]),
										region_string, &region_str_len);
					if(ret<0)
					{
						MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
								"Table %s region cfg %d charset convert from %s to %s failed.",
																					table->table_name,
																					db_rule->region_id,
																					charset_get_name(expr_desc->src_charset),
																					charset_get_name(dst_charset));
						free(region_string);
						op_expr->convert_failed++;
						expr_desc->iconv_err_cnt++;
						break;
					}
					if(region_str_len==(int)strlen(sub_key_array[k])&&
						0==memcmp(sub_key_array[k],region_string,region_str_len))
					{
						op_expr->no_effect_convert_cnt++;
					}
				}
				else
				{
					memcpy(region_string,sub_key_array[k],strlen(sub_key_array[k]));
					region_str_len=strlen(sub_key_array[k]);
				}
				p_rule=create_rs_str_rule(make_sub_type(table->table_id,dst_charset,expr_desc->do_charset_merge)
										,db_rule->match_method
										,db_rule->is_case_sensitive
										,region_string
										,region_str_len
										,key_left_offset[k]
										,key_right_offset[k]);
				op_expr_add_rule(op_expr, p_rule);
				free(region_string);
				region_string=NULL;
			}
			//if each sub string's convert take no effect and src charset is one of the dst.
			//if any sub expr convert failed
			if((TRUE==expr_desc->src_charset_in_dst&&op_expr->no_effect_convert_cnt==sub_expr_cnt)||
				op_expr->convert_failed>0)
			{
				scanner->dedup_expr_num++;
				cancel_last_region_from_group(group_rule,db_rule->region_id,op_expr->p_expr->expr_id, scanner);
				destroy_op_expr(op_expr);
				//redeem expr_id
				scanner->exprid_generator--;
				op_expr=NULL;
			}
			else
			{
				MESA_lqueue_join_tail(scanner->region_update_q,&op_expr, sizeof(void*));
			}
		}
	
	}
	else
	{
		expr_id=scanner->exprid_generator++;
		u_para=add_region_to_group(group_rule, table->table_id, db_rule->region_id,district_id,expr_id, table->table_type, scanner);
		if(u_para==NULL)
		{
			return -1;
		}
		op_expr=create_op_expr(expr_id,
								0,	//add
								u_para,
								table->table_id
								);
		for(k=0;k<sub_expr_cnt;k++)
		{
			region_str_len=strlen(sub_key_array[k])+1;
			region_string=ALLOC(char, region_str_len);
			region_str_len=hex2bin(sub_key_array[k], strlen(sub_key_array[k]), region_string, region_str_len);
			
			p_rule=create_rs_str_rule(make_sub_type(table->table_id,dst_charset,expr_desc->do_charset_merge),
									db_rule->match_method,
									db_rule->is_case_sensitive,
									region_string,
									region_str_len,
									key_left_offset[k],
									key_right_offset[k]);
			op_expr_add_rule(op_expr, p_rule);
			free(region_string);
			region_string=NULL;
		}
		MESA_lqueue_join_tail(scanner->region_update_q,&op_expr, sizeof(void*));
	}
	return 0;
}
int add_ip_rule(struct Maat_table_schema* table,struct db_ip_rule_t* db_ip_rule,struct Maat_scanner *scanner,void* logger)
{
	struct Maat_group_inner* group_rule=NULL;
	scan_rule_t* p_rule=NULL;
	struct op_expr_t* op_expr=NULL;
	struct Maat_group_inner* u_para=NULL;
	int expr_id=0,district_id=-1;

	group_rule=(struct Maat_group_inner*)HASH_fetch_by_id(scanner->group_hash, db_ip_rule->group_id);
	if(group_rule==NULL)
	{
		group_rule=create_group_rule(db_ip_rule->group_id, 0, scanner);
	}

	expr_id=scanner->exprid_generator++;
	u_para=add_region_to_group(group_rule, table->table_id, db_ip_rule->region_id, district_id, expr_id, TABLE_TYPE_IP, scanner);
	if(u_para==NULL)
	{
		return -1;
	}
	op_expr=create_op_expr(expr_id
						,0
						,u_para
						,table->table_id
						);
	p_rule=create_rs_ip_rule(make_sub_type(table->table_id,CHARSET_NONE,0)
						,db_ip_rule);
	op_expr_add_rule(op_expr,p_rule);
	MESA_lqueue_join_tail(scanner->region_update_q, &op_expr, sizeof(void*));
	return 0;
}
int add_intval_rule(struct Maat_table_schema* table,struct db_intval_rule* intval_rule,struct Maat_scanner *scanner,void* logger)
{
	struct Maat_group_inner* group_rule=NULL;
	scan_rule_t* p_rule=NULL;
	struct op_expr_t* op_expr=NULL;
	struct Maat_group_inner* u_para=NULL;
	int expr_id=0,district_id=-1;
	
	group_rule=(struct Maat_group_inner*)HASH_fetch_by_id(scanner->group_hash, intval_rule->group_id);
	if(group_rule==NULL)
	{
		group_rule=create_group_rule(intval_rule->group_id, 0, scanner);
	}
	expr_id=scanner->exprid_generator++;
	u_para=add_region_to_group(group_rule, table->table_id, intval_rule->region_id, district_id, expr_id, TABLE_TYPE_INTERVAL, scanner);
	if(u_para==NULL)
	{
		return -1;
	}
	op_expr=create_op_expr(expr_id
						,0
						,u_para
						,table->table_id
						);
	p_rule=create_rs_intval_rule(make_sub_type(table->table_id,CHARSET_NONE,0)
						,intval_rule);
	op_expr_add_rule(op_expr,p_rule);
	MESA_lqueue_join_tail(scanner->region_update_q, &op_expr, sizeof(void*));
	return 0;
}
int add_digest_rule(struct Maat_table_schema* table, struct db_digest_rule* db_rule, struct Maat_scanner *scanner,void* logger)
{
	struct Maat_group_inner* group_rule=NULL;
	struct Maat_group_inner* u_para=NULL;
	struct Maat_table_runtime * table_rt=Maat_table_runtime_get(scanner->table_rt_mgr, table->table_id);
	int expr_id=0,district_id=-1;

	group_rule=(struct Maat_group_inner*)HASH_fetch_by_id(scanner->group_hash, db_rule->group_id);
	if(group_rule==NULL)
	{
		group_rule=create_group_rule(db_rule->group_id, 0, scanner);
	}
	expr_id=scanner->exprid_generator++;
	u_para=add_region_to_group(group_rule, table->table_id, db_rule->region_id, district_id, expr_id, TABLE_TYPE_DIGEST, scanner);
	if(u_para==NULL)
	{
		return -1;
	}
	Maat_table_runtime_digest_add(table_rt, expr_id, db_rule->digest_string, db_rule->confidence_degree, group_rule);
	scanner->gie_update_q_size++;
	return 0;
}
int del_region_rule(struct Maat_table_schema* table,int region_id,int group_id,int rule_type,struct Maat_scanner *maat_scanner,void* logger)
{
	int i=0;
	unsigned int expr_id[MAAT_MAX_EXPR_ITEM_NUM*MAX_CHARSET_NUM]={0};
	int expr_num=0;
	struct Maat_group_inner* group_rule=NULL;
	struct Maat_table_runtime* table_rt=NULL;
	struct op_expr_t* op_expr=NULL;
	group_rule=(struct Maat_group_inner*)HASH_fetch_by_id(maat_scanner->group_hash, group_id);
	if(group_rule==NULL)
	{
		MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
							"update error, table %s group id %u not exist, while delete region id %d."
							,table->table_name[table->updating_name]
							,group_id
							,region_id);
		return -1;
	}
	assert(group_id==group_rule->group_id);
	expr_num=del_region_from_group(group_rule,region_id, expr_id, sizeof(expr_id)/sizeof(unsigned int), maat_scanner);
	if(expr_num==0)
	{
		MESA_handle_runtime_log(logger,RLOG_LV_INFO,maat_module ,
							"region delete error, id %d table %s region not in  group id %d."
							,region_id
							,table->table_name[table->updating_name]
							,group_id);
		return -1;
	}
	switch(table->table_type)
	{
		case	TABLE_TYPE_IP:
		case	TABLE_TYPE_IP_PLUS:
		case	TABLE_TYPE_EXPR:
		case	TABLE_TYPE_EXPR_PLUS:
		case	TABLE_TYPE_INTERVAL:
			for(i=0;i<expr_num;i++)
			{
				op_expr=create_op_expr(expr_id[i],1,NULL,table->table_id);//del expr
				op_expr->rule_type=rule_type;
				MESA_lqueue_join_tail(maat_scanner->region_update_q,&op_expr, sizeof(void*));
			}
			break;
		case	TABLE_TYPE_SIMILARITY:
		case	TABLE_TYPE_DIGEST:
			assert(expr_num==1);
			table_rt=Maat_table_runtime_get(maat_scanner->table_rt_mgr, table->table_id);
			Maat_table_runtime_digest_del(table_rt, expr_id[0]);
			maat_scanner->gie_update_q_size++;
			break;
		default:
			assert(0);
			break;
	}
	destroy_group_rule(group_rule, DESTROY_GROUP_BY_REGION, maat_scanner);

	return 0;
}
int add_group_rule(struct Maat_table_schema* table, struct db_group_rule_t* db_group_rule, struct Maat_scanner *scanner, void* logger)
{
	struct Maat_group_inner* group_rule=NULL, *parent_group=NULL;
	struct Maat_compile_group_relation*compile_rule=NULL;
	int ret=0;
	igraph_integer_t edge_id;
	group_rule=(struct Maat_group_inner*)HASH_fetch_by_id(scanner->group_hash, db_group_rule->group_id);
	if(group_rule==NULL)
	{
		group_rule=create_group_rule(db_group_rule->group_id, table->table_id, scanner);
	}
	
	if(db_group_rule->parent_type==PARENT_TYPE_GROUP)
	{
		parent_group=(struct Maat_group_inner*)HASH_fetch_by_id(scanner->group_hash, db_group_rule->parent_id);
		if(parent_group==NULL)
		{
			parent_group=create_group_rule(db_group_rule->parent_id, table->table_id, scanner);
		}	
		group_rule->ref_by_parent_cnt++;
		parent_group->ref_by_children_cnt++;
		ret=igraph_get_eid(&scanner->group_graph, &edge_id, group_rule->vertex_id, parent_group->vertex_id, IGRAPH_DIRECTED, /*error*/ 0);
		if(edge_id>0)//if the edge was not found and error is false, then -1 will be assigned to eid.
		{
			MESA_handle_runtime_log(logger, RLOG_LV_FATAL, maat_module,
								"update error, add sub group: %s %d to group %d error, sub group exist.",
																		table->table_name[table->updating_name],
																		db_group_rule->group_id,
																		db_group_rule->parent_id);
			return -1;
		}
		//igraph allow add multiple edges between two vetex, igraph_delete_edges removes one edge per call.
		igraph_add_edge(&scanner->group_graph, group_rule->vertex_id, parent_group->vertex_id);
	}
	else
	{
		group_rule->ref_by_compile_cnt++;
		compile_rule=(struct Maat_compile_group_relation*)HASH_fetch_by_id(scanner->compile_hash, db_group_rule->parent_id);
		if(compile_rule==NULL)
		{
			compile_rule=create_compile_group_relation(db_group_rule->parent_id, scanner);
		}
		ret=add_group_to_compile(compile_rule, group_rule, db_group_rule->virtual_table_id, db_group_rule->not_flag);
		if(ret<0)
		{
			MESA_handle_runtime_log(logger, RLOG_LV_FATAL, maat_module,
								"update error, add group: %s %d to compile rule %d error, compile rule is full or duplicate group.",
																		table->table_name[table->updating_name],
																		db_group_rule->group_id,
																		db_group_rule->parent_id);
			return -1;
		}
	}
	scanner->to_update_group_cnt++;
	return 1;
}
int del_group_rule(struct Maat_table_schema* table, struct db_group_rule_t* db_group_rule, struct Maat_scanner *scanner, void* logger)
{
	struct Maat_compile_group_relation* relation=NULL;
	struct Maat_group_inner* group_rule=NULL, *parent_group=NULL;
	igraph_es_t es;
	int ret=0;
	igraph_integer_t edge_num_before=0, edge_num_after=0;
	
	
	if(db_group_rule->parent_type==PARENT_TYPE_GROUP)
	{
		group_rule=(struct Maat_group_inner*)HASH_fetch_by_id(scanner->group_hash, db_group_rule->group_id);
		parent_group=(struct Maat_group_inner*)HASH_fetch_by_id(scanner->group_hash, db_group_rule->parent_id);
		if(group_rule==NULL)
		{
			MESA_handle_runtime_log(logger, RLOG_LV_FATAL, maat_module ,
								"update error, delete %s group %d from parent group %d error, target group not exisit.",
																		table->table_name[table->updating_name],
																		db_group_rule->group_id,
																		db_group_rule->parent_id);
			return 0;
		}
		if(parent_group==NULL)
		{
			MESA_handle_runtime_log(logger, RLOG_LV_FATAL, maat_module ,
								"update error, delete %s group %d from parent group %d error, parent group not exisit.",
																		table->table_name[table->updating_name],
																		db_group_rule->group_id,
																		db_group_rule->parent_id);
			return 0;
		}
		edge_num_before=igraph_ecount(&scanner->group_graph);
		// The edges between the given pairs of vertices will be included in the edge selection.
		//The vertex pairs must be given as the arguments of the function call, the third argument 
		//is the first vertex of the first edge, the fourth argument is the second vertex of the 
		//first edge, the fifth is the first vertex of the second edge and so on. The last element
		//of the argument list must be -1 to denote the end of the argument list.
		//https://igraph.org/c/doc/igraph-Iterators.html#igraph_es_pairs_small
		ret=igraph_es_pairs_small(&es, IGRAPH_DIRECTED, group_rule->vertex_id, parent_group->vertex_id, -1);
		assert(ret==IGRAPH_SUCCESS);
		// ignore no such edge to abort().
		igraph_set_error_handler(igraph_error_handler_ignore);
		ret=igraph_delete_edges(&scanner->group_graph, es);
		edge_num_after=igraph_ecount(&scanner->group_graph);
		
		if(ret!=IGRAPH_SUCCESS||edge_num_before-edge_num_after!=1)
		{
			MESA_handle_runtime_log(logger, RLOG_LV_FATAL, maat_module ,
								"update error, delete %s group %d from parent group %d error, not such relation before.",
																		table->table_name[table->updating_name],
																		db_group_rule->group_id,
																		db_group_rule->parent_id);
		}
		igraph_es_destroy(&es);
		destroy_group_rule(parent_group, DESTROY_GROUP_BY_CHILD, scanner);
	}
	else
	{
		relation=(struct Maat_compile_group_relation*)HASH_fetch_by_id(scanner->compile_hash, db_group_rule->parent_id);
		if(relation==NULL)
		{
			MESA_handle_runtime_log(logger, RLOG_LV_FATAL, maat_module,
								"update error, delete %s group %d form compile %d error, compile does not exist.",
																		table->table_name[table->updating_name],
																		db_group_rule->group_id,
																		db_group_rule->parent_id);
			return 0;
		}
		group_rule=del_group_from_compile(relation, db_group_rule->group_id, db_group_rule->virtual_table_id);
		if(group_rule==NULL)
		{
			MESA_handle_runtime_log(logger, RLOG_LV_FATAL, maat_module,
								"update error, delete %s group %d from compile %d error, target group does not in compile.",
																		table->table_name[table->updating_name],
																		db_group_rule->group_id,
																		db_group_rule->parent_id);
			return 0;
		}
		if(relation->group_cnt==0 && relation->compile==NULL)
		{
			destroy_compile_group_relation(relation, scanner);
		}
		group_rule->ref_by_compile_cnt--;
	}
	destroy_group_rule(group_rule, DESTROY_GROUP_BY_PARENT, scanner);
	scanner->to_update_group_cnt++;
	return 1;
}
int add_compile_rule(struct Maat_table_schema* table, struct Maat_compile_rule* db_compile_rule, struct Maat_scanner *scanner, void* logger)
{
	struct Maat_compile_group_relation *cg_relation=NULL;
	struct Maat_rule_head *p_maat_rule_head=&(db_compile_rule->head);

	cg_relation=(struct Maat_compile_group_relation*)HASH_fetch_by_id(scanner->compile_hash, p_maat_rule_head->config_id);
	if(cg_relation==NULL)
	{
		cg_relation=create_compile_group_relation(p_maat_rule_head->config_id, scanner);
	}
	else
	{
		if(cg_relation->compile!=NULL)//duplicate config
		{
			return -1;
		}
	}
	cg_relation->compile=db_compile_rule;
	scanner->to_update_compile_cnt++;
	return 0;
	
}
int del_compile_rule(struct Maat_table_schema* table, int compile_id, struct Maat_scanner *scanner, void* logger)
{
	struct Maat_compile_group_relation *cg_relation=NULL;
	cg_relation=(struct Maat_compile_group_relation*)HASH_fetch_by_id(scanner->compile_hash, compile_id);
	if(cg_relation==NULL || cg_relation->compile==NULL)
	{
		MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
							"update error, delete %s compile rule error : compile id %d does not exist."
																	,table->table_name[table->updating_name]
																	,compile_id);
		return -1;
	}

	pthread_rwlock_wrlock(&(cg_relation->rwlock));
	garbage_bagging(GARBAGE_COMPILE_RULE, cg_relation->compile, scanner->tomb_ref);	
	cg_relation->compile=NULL;
	pthread_rwlock_unlock(&(cg_relation->rwlock));

	if(cg_relation->group_cnt==0&&cg_relation->compile==NULL)
	{
		destroy_compile_group_relation(cg_relation, scanner);
	}
	scanner->to_update_compile_cnt++;
	return 1;
}
void update_group_rule(struct Maat_table_schema* table,const char* table_line,struct Maat_scanner *scanner, struct Maat_table_manager* table_mgr, void* logger)
{
	struct db_group_rule_t db_group_rule;
	struct Maat_table_runtime* table_rt=Maat_table_runtime_get(scanner->table_rt_mgr, table->table_id);
	int ret=0;
	char virtual_table_name[MAX_TABLE_NAME_LEN]={0};
	memset(&db_group_rule, 0, sizeof(db_group_rule));
	ret=sscanf(table_line,"%d\t%d\t%d\t%d\t%d\t%s", &(db_group_rule.group_id),
											&(db_group_rule.parent_id),
											&(db_group_rule.is_valid),
											&(db_group_rule.not_flag),
											&(db_group_rule.parent_type),
											virtual_table_name);
	if(ret!=3&&ret!=4&&ret!=5&&ret!=6)
	{
		MESA_handle_runtime_log(logger,RLOG_LV_INFO,maat_module ,
							"update error, invalid format of group table %s:%s",
							table->table_name[table->updating_name], table_line);	
		table->udpate_err_cnt++;
		return;
	}
	if(db_group_rule.not_flag!=1)//compatible to old format that 4th column is op_time
	{
		db_group_rule.not_flag=0;
	}
	if(db_group_rule.parent_type==PARENT_TYPE_GROUP && db_group_rule.not_flag)
	{
		MESA_handle_runtime_log(logger, RLOG_LV_INFO, maat_module ,
							"update error, invalid format of group table %s:%s not operation is forbidden for non-compile parent.",
							table->table_name[table->updating_name], table_line);	
		table->udpate_err_cnt++;
		return;		
	}
	if(is_valid_table_name(virtual_table_name))
	{
		db_group_rule.virtual_table_id=Maat_table_get_id_by_name(table_mgr, virtual_table_name);
		if(db_group_rule.virtual_table_id<0)
		{
			//This happens when one data source (e.g. redis) is consumed by multiple Maat instance.
			//Maat ignores unrealated groups.
			MESA_handle_runtime_log(logger, RLOG_LV_DEBUG, maat_module,
								"group table load abandon, unknown virtual table name: %s of group table %s:%s.",
								virtual_table_name,
								table->table_name[table->updating_name], table_line);	
			table->udpate_err_cnt++;
			return;
		}
	}
	if(db_group_rule.is_valid==FALSE)
	{
		ret=del_group_rule(table, &db_group_rule, scanner, logger);
		//leave no trace when compatible_group_update calling
		assert(table->table_type==TABLE_TYPE_GROUP);
		if(ret==1)
		{
			table_rt->origin_rule_num--;
			assert(table_rt->origin_rule_num>=0);
			if(db_group_rule.not_flag)
			{
				table_rt->group.not_flag_group--;
			}
		}
	}
	else
	{
		ret=add_group_rule(table,&db_group_rule, scanner, logger);
		if(ret<0)
		{
			MESA_handle_runtime_log(logger,RLOG_LV_FATAL, maat_module,
							"duplicate config of group table %s group_id %d compile_id %d.", table->table_name[0],
																							db_group_rule.group_id,
																							db_group_rule.parent_id);

		}
		else
		{
			//no need to free db_group_rule,it was saved in scanner->compile_hash
			if(table->table_type==TABLE_TYPE_GROUP)
			{
				table_rt->origin_rule_num++;
				if(db_group_rule.not_flag)
				{
					table_rt->group.not_flag_group++;
				}
			}
		}
	}
	
	return;	
}
void update_expr_rule(struct Maat_table_schema* table,const char* table_line,struct Maat_scanner *scanner,void* logger)
{
	struct db_str_rule_t* maat_str_rule=ALLOC(struct db_str_rule_t, 1);
	int ret=0,db_hexbin=0,rule_type=0;
	struct Maat_table_runtime* table_rt=Maat_table_runtime_get(scanner->table_rt_mgr, table->table_id);
	switch(table->table_type)
	{
		case	TABLE_TYPE_EXPR:
			ret=sscanf(table_line,"%d\t%d\t%s\t%d\t%d\t%d\t%d",&(maat_str_rule->region_id)
															,&(maat_str_rule->group_id)
															,maat_str_rule->keywords
															,(int*)&(maat_str_rule->expr_type)
															,(int*)&(maat_str_rule->match_method)
															,&db_hexbin
															,&(maat_str_rule->is_valid));
			if(ret!=7)
			{
				MESA_handle_runtime_log(logger, RLOG_LV_FATAL, maat_module,
									"abandon config: invalid format of expr table %s:%s", table->table_name[table->updating_name], table_line);
				free(maat_str_rule);
				maat_str_rule=NULL;	
				table->udpate_err_cnt++;
				return;
			}
			break;
		case	TABLE_TYPE_EXPR_PLUS:
			ret=sscanf(table_line,"%d\t%d\t%s\t%s\t%d\t%d\t%d\t%d",&(maat_str_rule->region_id)
															,&(maat_str_rule->group_id)
															,maat_str_rule->district
															,maat_str_rule->keywords
															,(int*)&(maat_str_rule->expr_type)
															,(int*)&(maat_str_rule->match_method)
															,&db_hexbin
															,&(maat_str_rule->is_valid));
			if(ret!=8)
			{
				MESA_handle_runtime_log(logger, RLOG_LV_FATAL, maat_module,
									"abandon config: invalid format of expr_plus table %s:%s", table->table_name[table->updating_name], table_line);
				free(maat_str_rule);
				maat_str_rule=NULL;	
				table->udpate_err_cnt++;
				return;
			}
			break;
		default:
			assert(0);
			break;
	}
	switch(db_hexbin)
	{
		case	0:
			maat_str_rule->is_hexbin=FALSE;
			maat_str_rule->is_case_sensitive=FALSE;
			break;
		case	1:
			maat_str_rule->is_hexbin=TRUE;
			maat_str_rule->is_case_sensitive=FALSE;
			break;
		case	2:
			maat_str_rule->is_hexbin=FALSE;
			maat_str_rule->is_case_sensitive=TRUE;
			break;
		default:
			MESA_handle_runtime_log(logger, RLOG_LV_FATAL, maat_module,
								"abandon config %d:update error,invalid hexbin value of expr table %s:%s",
								maat_str_rule->region_id,
								table->table_name[table->updating_name], table_line);
			table->udpate_err_cnt++;
			goto error_out;
	}
	if(!is_valid_match_method(maat_str_rule->match_method))
	{
		MESA_handle_runtime_log(logger, RLOG_LV_FATAL, maat_module,
							"abandon config %d:update error,invalid match method=%d in expr table %s:%s",
							maat_str_rule->region_id,
							maat_str_rule->match_method,
							table->table_name[table->updating_name],table_line);
		table->udpate_err_cnt++;
		goto error_out;
	}
	if(!is_valid_expr_type(maat_str_rule->expr_type))
	{
		MESA_handle_runtime_log(logger, RLOG_LV_FATAL, maat_module,
							"abandon config %d:update error,invalid expr type=%d in expr table %s:%s",
							maat_str_rule->region_id,
							maat_str_rule->expr_type,
							table->table_name[table->updating_name], table_line);
		table->udpate_err_cnt++;
		goto error_out;
	}
	ret=sync_region(scanner->region_hash,
					maat_str_rule->region_id,
					maat_str_rule->group_id,
					table->table_name[table->updating_name],
					maat_str_rule->is_valid,logger);
	if(ret<0)
	{
		table->udpate_err_cnt++;
		goto error_out;
	}

	if(maat_str_rule->is_valid==FALSE)
	{
		if(maat_str_rule->expr_type==EXPR_TYPE_REGEX)
		{
			rule_type=RULETYPE_REG;
		}
		else
		{
			rule_type=RULETYPE_STR;
		}
		ret=del_region_rule(table, maat_str_rule->region_id, maat_str_rule->group_id, rule_type,
							scanner, logger);
		if(ret<0)
		{
			table->udpate_err_cnt++;
		}
		else
		{
			table_rt->origin_rule_num--;
		}
	}
	else
	{
		if(maat_str_rule->expr_type==EXPR_TYPE_AND
			&&maat_str_rule->match_method!=MATCH_METHOD_SUB)
		{
			MESA_handle_runtime_log(logger, RLOG_LV_FATAL, maat_module,
			"table %s region cfg %d is EXPR_TYPE_AND,but match method is not MATCH_METHOD_SUB,force fixed.",
			table->table_name[table->updating_name], maat_str_rule->region_id);
			maat_str_rule->match_method=MATCH_METHOD_SUB;
				
		}
		ret=add_expr_rule(table, maat_str_rule, scanner, logger);
		if(ret<0)
		{
			MESA_handle_runtime_log(logger, RLOG_LV_INFO, maat_module,
							"duplicate config of expr table %s region_id=%d",
							table->table_name[table->updating_name], maat_str_rule->region_id);
			table->udpate_err_cnt++;
		}
		else
		{
			table_rt->origin_rule_num++;
		}

	}
error_out:
	free(maat_str_rule);
	maat_str_rule=NULL;
}

void update_ip_rule(struct Maat_table_schema* table, const char* table_line, struct Maat_scanner *scanner, void* logger)
{
	struct db_ip_rule_t* ip_rule=(struct db_ip_rule_t*)calloc(sizeof(struct db_ip_rule_t),1);
	char src_ip1[40]={0}, src_ip2[40]={0}, dst_ip1[40]={0}, dst_ip2[40]={0};
	char saddr_format[16]={0}, sport_format[16]={0}, daddr_format[16]={0}, dport_format[16]={0};
	struct Maat_table_runtime* table_rt=Maat_table_runtime_get(scanner->table_rt_mgr, table->table_id);
	unsigned short src_port1=0, src_port2=0, dst_port1=0, dst_port2=0;
	int protocol=0,direction=0;
	int ret=0;
	int ret_array[8]={1},i=0;

	switch(table->table_type)
	{
		case TABLE_TYPE_IP:
			strncpy(saddr_format, "mask", sizeof(saddr_format));
			strncpy(sport_format, "mask", sizeof(sport_format));
			strncpy(daddr_format, "mask", sizeof(daddr_format));
			strncpy(dport_format, "mask", sizeof(dport_format));

			ret=sscanf(table_line,"%d\t%d\t%d\t%s\t%s\t%hu\t%hu\t%s\t%s\t%hu\t%hu\t%d\t%d\t%d",
															&(ip_rule->region_id),
															&(ip_rule->group_id),
															&(ip_rule->addr_type),
															src_ip1,
															src_ip2,
															&src_port1,
															&src_port2,
															dst_ip1,
															dst_ip2,
															&dst_port1,
															&dst_port2,
															&protocol,
															&direction,
															&(ip_rule->is_valid));
			if(ret!=14)
			{
				MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
									"update error, invalid column number of ip table %s:%s"
									,table->table_name[table->updating_name],table_line);
				table->udpate_err_cnt++;
				goto error_out;
			}
			break;
		case TABLE_TYPE_IP_PLUS:
			ret=sscanf(table_line,"%d\t%d\t%d\t%s\t%s\t%s\t%s\t%hu\t%hu\t%s\t%s\t%s\t%s\t%hu\t%hu\t%d\t%d\t%d",
															&(ip_rule->region_id),
															&(ip_rule->group_id),
															&(ip_rule->addr_type),
															saddr_format,
															src_ip1,
															src_ip2,
															sport_format,
															&src_port1,
															&src_port2,
															daddr_format,
															dst_ip1,
															dst_ip2,
															dport_format,
															&dst_port1,
															&dst_port2,
															&protocol,
															&direction,
															&(ip_rule->is_valid));
			if(ret!=18)
			{
				MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
									"update error, invalid column number of ip_plus table %s:%s"
									,table->table_name[table->updating_name],table_line);
				table->udpate_err_cnt++;
				goto error_out;
			}
			break;
		default:
			table->udpate_err_cnt++;
			goto error_out;
			break;
	}
	if(ip_rule->addr_type!=4&&ip_rule->addr_type!=6)
	{
		MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module,
							"update error, invalid addr type %d of ip/ip_plus table %s:%s",
							ip_rule->addr_type,
							table->table_name[table->updating_name], table_line);
		table->udpate_err_cnt++;
		goto error_out;
	}
	if(protocol>65535 || protocol<0)
	{
		MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module,
							"update error, invalid protocol value %d of ip/ip_plus table %s:%s",
							protocol,
							table->table_name[table->updating_name],table_line);
		table->udpate_err_cnt++;
		goto error_out;
	}
	if(direction!=0 && direction!=1)
	{
		MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module,
							"update error, invalid direction value %d of ip/ip_plus table %s:%s",
							direction,
							table->table_name[table->updating_name],table_line);
		table->udpate_err_cnt++;
		goto error_out;
	}
	if(FORMAT_UNKNOWN==ip_format_str2int(saddr_format)||
		FORMAT_UNKNOWN==ip_format_str2int(sport_format)||
		FORMAT_UNKNOWN==ip_format_str2int(daddr_format)||	
		FORMAT_UNKNOWN==ip_format_str2int(dport_format))
	{
		MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module,
							"update error, invalid addr format of ip/ip_plus table %s:%s, should be range, mask or CIDR",
							table->table_name[table->updating_name], table_line);
		table->udpate_err_cnt++;
		goto error_out;
	}

	if(ip_rule->addr_type==4)
	{
		ret_array[0]=ip_format2range(ip_rule->addr_type, ip_format_str2int(saddr_format), src_ip1, src_ip2, &ip_rule->ipv4_rule.min_saddr, &ip_rule->ipv4_rule.max_saddr);
		ret_array[1]=ip_format2range(ip_rule->addr_type, ip_format_str2int(daddr_format), dst_ip1, dst_ip2, &ip_rule->ipv4_rule.min_daddr, &ip_rule->ipv4_rule.max_daddr);
		
		if(FORMAT_MASK==ip_format_str2int(sport_format))
		{
			ip_rule->ipv4_rule.min_sport=src_port1&src_port2;
			ip_rule->ipv4_rule.max_sport=src_port1|~src_port2;		
		}
		else
		{
			ip_rule->ipv4_rule.min_sport=src_port1;
			ip_rule->ipv4_rule.max_sport=src_port2;
		}

		if(FORMAT_MASK==ip_format_str2int(dport_format))
		{
			ip_rule->ipv4_rule.min_dport=dst_port1&dst_port2;
			ip_rule->ipv4_rule.max_dport=dst_port1|~dst_port2;		
		}
		else
		{
			ip_rule->ipv4_rule.min_dport=dst_port1;
			ip_rule->ipv4_rule.max_dport=dst_port2;
		}

		ip_rule->ipv4_rule.proto=protocol;
		ip_rule->ipv4_rule.direction=direction;
	}
	else
	{
		ret_array[0]=ip_format2range(ip_rule->addr_type, ip_format_str2int(saddr_format), src_ip1, src_ip2, ip_rule->ipv6_rule.min_saddr, ip_rule->ipv6_rule.max_saddr);
		ret_array[1]=ip_format2range(ip_rule->addr_type, ip_format_str2int(daddr_format), dst_ip1, dst_ip2, ip_rule->ipv6_rule.min_daddr, ip_rule->ipv6_rule.max_daddr);
	
		if(FORMAT_MASK==ip_format_str2int(sport_format))
		{
			ip_rule->ipv6_rule.min_sport=src_port1&src_port2;
			ip_rule->ipv6_rule.max_sport=src_port1|~src_port2;		
		}
		else
		{
			ip_rule->ipv6_rule.min_sport=src_port1;
			ip_rule->ipv6_rule.max_sport=src_port2;
		}

		if(FORMAT_MASK==ip_format_str2int(dport_format))
		{
			ip_rule->ipv6_rule.min_dport=dst_port1&dst_port2;
			ip_rule->ipv6_rule.max_dport=dst_port1|~dst_port2;			
		}
		else
		{
			ip_rule->ipv6_rule.min_dport=dst_port1;
			ip_rule->ipv6_rule.max_dport=dst_port2;
		}

		ip_rule->ipv6_rule.proto=protocol;
		ip_rule->ipv6_rule.direction=direction;
	}
	for(i=0;i<4;i++)
	{
		if(ret_array[i]<0)
		{
			MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
								"update error, invalid IP address format of ip table %s:%s"
								,table->table_name[table->updating_name],table_line);
			table->udpate_err_cnt++;
			goto error_out;
		}
	}
	ret=sync_region(scanner->region_hash,
					ip_rule->region_id,
					ip_rule->group_id,
					table->table_name[table->updating_name],
					ip_rule->is_valid,logger);
	if(ret<0)
	{
		table->udpate_err_cnt++;
		goto error_out;
	}
	if(ip_rule->is_valid==FALSE)
	{
		ret=del_region_rule(table,
							ip_rule->region_id, ip_rule->group_id, ip_rule->addr_type==6?RULETYPE_IPv6:RULETYPE_IPv4,
							scanner, logger);
		if(ret<0)
		{
			table->udpate_err_cnt++;
		}
		else
		{
			table_rt->origin_rule_num--;
		}
	}
	else
	{

		ret=add_ip_rule(table, ip_rule, scanner, logger);
		if(ret<0)
		{
			MESA_handle_runtime_log(logger,RLOG_LV_INFO,maat_module ,
							"duplicate config of ip table %s config_id=%d"
							,table->table_name[table->updating_name],ip_rule->region_id);
			table->udpate_err_cnt++;
		}
		else
		{
			table_rt->origin_rule_num++;
		}

	}
error_out:
	free(ip_rule);
	ip_rule=NULL;	
}

void update_intval_rule(struct Maat_table_schema* table, const char* table_line, struct Maat_scanner *scanner, void* logger)
{
	struct db_intval_rule* intval_rule=ALLOC(struct db_intval_rule, 1);
	struct Maat_table_runtime* table_rt=Maat_table_runtime_get(scanner->table_rt_mgr, table->table_id);
	int ret=0;
	ret=sscanf(table_line,"%d\t%d\t%u\t%u\t%d",&(intval_rule->region_id)
											,&(intval_rule->group_id)
											,&(intval_rule->intval.lb)
											,&(intval_rule->intval.ub)
											,&(intval_rule->is_valid));

	if(ret!=5||intval_rule->intval.ub<intval_rule->intval.lb)
	{
		MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
							"update error,invalid format  of interval table %s:%s"
							,table->table_name[table->updating_name],table_line);
		table->udpate_err_cnt++;
		goto error_out;
	}
	ret=sync_region(scanner->region_hash,
					intval_rule->region_id,
					intval_rule->group_id,
					table->table_name[table->updating_name],
					intval_rule->is_valid, logger);
	if(ret<0)
	{
		table->udpate_err_cnt++;
		goto error_out;
	}

	if(intval_rule->is_valid==FALSE)
	{
		ret=del_region_rule(table
							,intval_rule->region_id,intval_rule->group_id,RULETYPE_INT
							,scanner, logger);
		if(ret<0)
		{
			table->udpate_err_cnt++;
		}
		else
		{
			table_rt->origin_rule_num--;
		}

	}
	else
	{
		ret=add_intval_rule(table, intval_rule,scanner,logger);
		if(ret<0)
		{
			MESA_handle_runtime_log(logger,RLOG_LV_INFO,maat_module ,
							"duplicate config of intval table %s config_id=%d"
							,table->table_name[table->updating_name],intval_rule->region_id);
			table->udpate_err_cnt++;
		}
		else
		{
			table_rt->origin_rule_num++;
		}

	}
error_out:
	free(intval_rule);
	intval_rule=NULL;		
}

void update_compile_rule(struct Maat_table_schema* table,const char* table_line ,struct Maat_scanner *scanner, const struct rule_tag* tags, int n_tags,void* logger)
{
	struct compile_table_schema* compile_desc=&(table->compile);
	struct Maat_table_runtime* table_rt=Maat_table_runtime_get(scanner->table_rt_mgr, table->table_id);

	struct Maat_compile_rule *p_compile=NULL;
	struct Maat_rule_head m_rule_tmp;
	memset(&m_rule_tmp, 0, sizeof(m_rule_tmp));

	char service_define[MAX_TABLE_LINE_SIZE]={0};
	char tag_str[MAX_TABLE_LINE_SIZE]={0};
	int ret=0;
	int is_valid=0, declared_grp_num=0;
	double exec_seq=0.0;
	ret=sscanf(table_line,"%d\t%d\t%hhd\t%hhd\t%hhd\t%s\t%s\t%d\t%d\t%lf",&(m_rule_tmp.config_id),
													&(m_rule_tmp.service_id),
													&(m_rule_tmp.action),
													&(m_rule_tmp.do_blacklist),
													&(m_rule_tmp.do_log),
													tag_str,
													service_define,
													&is_valid,
													&declared_grp_num,
													&exec_seq);
	if((ret!=8&&ret!=9&&ret!=10)||declared_grp_num>MAAT_MAX_EXPR_ITEM_NUM)
	{
		MESA_handle_runtime_log(logger, RLOG_LV_FATAL,maat_module ,
							"update error, invalid format of compile table %s:%s"
							,table->table_name[table->updating_name],table_line);	
		goto error_out;
	}
	if(n_tags>0&&strlen(tag_str)>2)
	{
		ret=compare_accept_tag(tag_str, tags, n_tags);
		if(ret<0)
		{
			MESA_handle_runtime_log(logger, RLOG_LV_FATAL,maat_module ,
						"update error, invalid tag format of compile table %s:%s"
						,table->table_name[table->updating_name],table_line);
			goto error_out;
		}
		if(ret==0)
		{
			table->unmatch_tag_cnt++;
			return;
		}
	}
	switch(compile_desc->user_region_encoding)
	{
		case USER_REGION_ENCODE_ESCAPE:
			str_unescape(service_define);
			break;
		default:
			break;
	}

	if(is_valid==FALSE)
	{
		ret=del_compile_rule(table, m_rule_tmp.config_id, scanner, logger);
		if(ret>0)
		{
			table_rt->origin_rule_num--;
		}
		goto error_out;
	}
	else
	{
		p_compile=create_compile_rule(&m_rule_tmp, service_define, declared_grp_num, exec_seq, table);
		ret=add_compile_rule(table, p_compile, scanner, logger);
		if(ret<0)
		{
			MESA_handle_runtime_log(logger, RLOG_LV_INFO, maat_module,
							"duplicate config of compile table %s config_id=%d",
							table->table_name[table->updating_name], m_rule_tmp.config_id);			
			table->udpate_err_cnt++;			
			destroy_compile_rule(p_compile);			
			p_compile=NULL;
			goto error_out;
		}
		table_rt->origin_rule_num++;
	}
	return;
	
error_out:
	table->udpate_err_cnt++;
	return;	
}

void update_digest_rule(struct Maat_table_schema* table, const char* table_line, struct Maat_scanner *scanner, void* logger)
{
	struct Maat_table_runtime* table_rt=Maat_table_runtime_get(scanner->table_rt_mgr, table->table_id);
	struct db_digest_rule* digest_rule=ALLOC(struct db_digest_rule, 1);
	int ret=0;
	char digest_buff[MAX_TABLE_LINE_SIZE]={'\0'};
	if(table->table_type==TABLE_TYPE_DIGEST)
	{
		ret=sscanf(table_line,"%d\t%d\t%llu\t%s\t%hd\t%d",&(digest_rule->region_id)
											,&(digest_rule->group_id)
											,&(digest_rule->orgin_len)
											,digest_buff
											,&(digest_rule->confidence_degree)
											,&(digest_rule->is_valid));
	}
	else if(table->table_type==TABLE_TYPE_SIMILARITY)
	{
		digest_rule->orgin_len=0;
		ret=sscanf(table_line,"%d\t%d\t%s\t%hd\t%d",&(digest_rule->region_id)
											,&(digest_rule->group_id)
											,digest_buff
											,&(digest_rule->confidence_degree)
											,&(digest_rule->is_valid));
	}
	else
	{
		assert(0);
	}
	digest_rule->digest_string=digest_buff;
	if(!(ret==6||ret==5)||digest_rule->confidence_degree>100||digest_rule->confidence_degree<0)
	{
		MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
							"update error,invalid format  of digest table %s:%s"
							,table->table_name[table->updating_name],table_line);
		table->udpate_err_cnt++;
		goto error_out;
	}
	ret=sync_region(scanner->region_hash,
					digest_rule->region_id,
					digest_rule->group_id,
					table->table_name[table->updating_name],
					digest_rule->is_valid, logger);
	if(ret<0)
	{
		table->udpate_err_cnt++;
		goto error_out;
	}

	if(digest_rule->is_valid==FALSE)
	{
		//digest rule is not build with rulescan, this rule type is useless in count_rs_region funciton.
		ret=del_region_rule(table,digest_rule->region_id,digest_rule->group_id,0 ,scanner, logger);
		if(ret<0)
		{
			table->udpate_err_cnt++;
		}
		else
		{
			table_rt->origin_rule_num--;
		}

	}
	else
	{
		ret=add_digest_rule(table, digest_rule,scanner,logger);
		if(ret<0)
		{
			MESA_handle_runtime_log(logger,RLOG_LV_INFO,maat_module ,
							"duplicate config of intval table %s config_id=%d"
							,table->table_name[table->updating_name],digest_rule->region_id);
			table->udpate_err_cnt++;
		}
		else
		{
			table_rt->origin_rule_num++;
		}

	}
error_out:

	digest_rule->digest_string=NULL;
	free(digest_rule);
	digest_rule=NULL;		
}
void garbage_bagging_with_timeout(enum maat_garbage_type type,void *p, int timeout, MESA_lqueue_head garbage_q)
{
	if(p==NULL)
	{
		return;
	}
	struct _maat_garbage_t* bag=(struct _maat_garbage_t*)malloc(sizeof(struct _maat_garbage_t));
	bag->raw=p;
	bag->type=type;
	bag->create_time=time(NULL);
	bag->ok_times=0;
	bag->expire_after=timeout;
	MESA_lqueue_join_tail(garbage_q,&bag,sizeof(void*));
	return;
}
void garbage_bagging(enum maat_garbage_type type, void *p, MESA_lqueue_head garbage_q)
{
	garbage_bagging_with_timeout(type, p, -1, garbage_q);
	return;
}
void garbage_bury(MESA_lqueue_head garbage_q, int timeout, void *logger)
{
	UNUSED	MESA_queue_errno_t q_ret=MESA_QUEUE_RET_OK;
	_maat_garbage_t* bag=NULL;
	long data_size=0;
	const long q_cnt=MESA_lqueue_get_count(garbage_q);
	int i=0,bury_cnt=0, ret=0;
	long long ref_cnt=0;
	int have_timeout=0;
	int override_timeout=0;
	time_t now=time(NULL);
	for(i=0;i<q_cnt;i++)
	{
		data_size=sizeof(void*);
		q_ret=(MESA_queue_errno_t)MESA_lqueue_get_head(garbage_q,&bag,&data_size);
		assert(data_size==sizeof(void*)&&q_ret==MESA_QUEUE_RET_OK);
		if(bag->expire_after<0)
		{
			override_timeout=timeout;
		}
		else
		{
			override_timeout=bag->expire_after;
		}
		if(now-bag->create_time<override_timeout)
		{
			MESA_lqueue_join_tail(garbage_q,&bag,sizeof(void*));
			continue;
		}
		have_timeout=1;
		switch(bag->type)
		{
			case GARBAGE_COMPILE_RULE:
				destroy_compile_rule(bag->compile_rule);				
				break;
			case GARBAGE_COMPILE_GOURP_RELATION:
				_destroy_compile_group_relation(bag->compile_group_relation);
				break;
			case GARBAGE_GROUP_RULE:
				_destroy_group_rule(bag->group_rule);
				break;
			case GARBAGE_SCANNER:
				ref_cnt=alignment_int64_array_sum(bag->scanner->ref_cnt, bag->scanner->max_thread_num);
				if(ref_cnt==0)
				{
					MESA_handle_runtime_log(logger,RLOG_LV_INFO,maat_module,
							"scanner %p version %d has no reference peacefully destroyed.", bag->scanner, bag->scanner->version);
				}
				else
				{
					MESA_handle_runtime_log(logger,RLOG_LV_INFO,maat_module,
							"scanner %p version %d force destroyed, ref_cnt %lld.",
							bag->scanner, bag->scanner->version, ref_cnt);
				}
				destroy_maat_scanner(bag->scanner);
				break;
			case GARBAGE_BOOL_MATCHER:
				destroy_bool_matcher(bag->bool_matcher);
				break;
			case GARBAGE_MAP_STR2INT:
				map_destroy(bag->str2int_map);
				break;
			case GARBAGE_FOREIGN_FILE:
				ret=system_cmd_rm(bag->filename);
				if(ret==-1)
				{
					MESA_handle_runtime_log(logger,RLOG_LV_INFO,maat_module,
							"Foreign content file %s remove failed.",
							bag->filename);
				}
				else
				{

					MESA_handle_runtime_log(logger,RLOG_LV_DEBUG,maat_module,
							"Foreign content file %s remove success.",
							bag->filename);				
				}
				free(bag->filename);
				bag->filename=NULL;
				break;
			case GARBAGE_IP_MATCHER:
				ip_matcher_free(bag->a_ip_matcher);
				bag->a_ip_matcher=NULL;
				break;
			default:
				assert(0);
		}
		free(bag);
		bag=NULL;
		bury_cnt++;
	}
	if(q_cnt>0&&have_timeout==1)
	{
		MESA_handle_runtime_log(logger,RLOG_LV_INFO,maat_module,
							"Garbage queue size %ld, bury %d",
							q_cnt,bury_cnt);
	}
}
void update_plugin_table(struct Maat_table_schema* table_schema, const char* row, Maat_scanner* scanner, const struct rule_tag* tags, int n_tags, void* logger)
{
	int ret=1, matched_tag=1;
	struct plugin_table_schema* plugin_desc=&(table_schema->plugin);
	struct Maat_table_runtime* table_rt=Maat_table_runtime_get(scanner->table_rt_mgr, table_schema->table_id);
	char* copy=NULL;
	size_t accept_tag_offset=0, accept_tag_len=0;
	if(plugin_desc->rule_tag_column>0&&n_tags>0)
	{
		ret=Maat_helper_read_column(row, plugin_desc->rule_tag_column, &accept_tag_offset, &accept_tag_len);
		if(ret<0)
		{
			MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
						"update error, could not locate tag in column %d of plugin table_schema %s:%s",
						plugin_desc->rule_tag_column,
						table_schema->table_name[table_schema->updating_name],
						row);
			table_schema->udpate_err_cnt++;
			return;
		}
		if(accept_tag_len>2)
		{
			copy=ALLOC(char, accept_tag_len+1);
			memcpy(copy, row+accept_tag_offset, accept_tag_len);
			matched_tag=compare_accept_tag(copy, tags, n_tags);
			if(matched_tag<0)
			{
				MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
							"update error,invalid tag format of plugin table_schema %s:%s"
							,table_schema->table_name[table_schema->updating_name],row);
				table_schema->udpate_err_cnt++;
			}
			if(matched_tag==0)
			{
				table_schema->unmatch_tag_cnt++;
			}
			free(copy);
			copy=NULL;
		}
		if(!matched_tag)
		{
			return;
		}
	}
	Maat_table_runtime_plugin_new_row(table_rt, table_schema, row, logger);
}
void update_ip_plugin_table(struct Maat_table_schema* table_schema, const char* table_row, Maat_scanner* scanner, const struct rule_tag* tags, int n_tags, void* logger)
{
	int ret=1, matched_tag=1;
	struct ip_plugin_table_schema* ip_plugin_schema=&(table_schema->ip_plugin);
	struct Maat_table_runtime* table_rt=Maat_table_runtime_get(scanner->table_rt_mgr, table_schema->table_id);
	char* copy=NULL;
	size_t accept_tag_offset=0, accept_tag_len=0;
	if(ip_plugin_schema->rule_tag_column>0&&n_tags>0)
	{
		ret=Maat_helper_read_column(table_row, ip_plugin_schema->rule_tag_column, &accept_tag_offset, &accept_tag_len);
		if(ret<0)
		{
			MESA_handle_runtime_log(logger,RLOG_LV_FATAL,maat_module ,
						"update error, could not locate tag in column %d of plugin table_schema %s:%s",
						ip_plugin_schema->rule_tag_column,
						table_schema->table_name[table_schema->updating_name],
						table_row);
			table_schema->udpate_err_cnt++;
			return;
		}
		if(accept_tag_len>2)
		{
			copy=ALLOC(char, accept_tag_len+1);
			memcpy(copy, table_row+accept_tag_offset, accept_tag_len);
			matched_tag=compare_accept_tag(copy, tags, n_tags);
			if(matched_tag<0)
			{
				MESA_handle_runtime_log(logger, RLOG_LV_FATAL, maat_module,
							"update error, invalid tag format of ip_plugin table_schema %s:%s",
							table_schema->table_name[table_schema->updating_name], table_row);
				table_schema->udpate_err_cnt++;
			}
			if(matched_tag==0)
			{
				table_schema->unmatch_tag_cnt++;
			}
			free(copy);
			copy=NULL;
		}
		if(!matched_tag)
		{
			return;
		}
	}
	Maat_table_runtime_ip_plugin_new_row(table_rt, table_schema, table_row, logger);
	return;
}

void vector_print(igraph_vector_t *v) {
  long int i;
  for (i=0; i<igraph_vector_size(v); i++) {
    printf(" %li", (long int) VECTOR(*v)[i]);
  }
  printf("\n");
}
static size_t effective_vertices_count(igraph_vector_t *vids)
{
	size_t i=0;
	int tmp_vid=0;
	for(i=0; i<(size_t)igraph_vector_size(vids); i++)
	{
		tmp_vid=(int) VECTOR(*vids)[i];
		if(tmp_vid<0)
		{
			break;
		}
	}
	return i;
}
void walk_group_hash(const uchar * key, uint size, void * data, void * user)
{
	struct Maat_group_inner* group_rule=(struct Maat_group_inner*)data;
	struct Maat_group_inner* parent_group=NULL;
	struct Maat_scanner* scanner=(struct Maat_scanner*)user;
	int tmp_vid=0;
	size_t i=0, top_group_cnt=0;
	long long* temp_group_ids=NULL;
	if(group_rule->ref_by_compile_cnt==group_rule->ref_by_parent_cnt)
	{
		//fast path, group is only referenced by compile rules.
		top_group_cnt=1;
		temp_group_ids=ALLOC(long long, top_group_cnt);
		temp_group_ids[0]=group_rule->group_id;
	}
	else
	{
		igraph_vector_t *vids=&(scanner->dfs_vids);
		igraph_dfs(&(scanner->group_graph), group_rule->vertex_id, IGRAPH_OUT, 
					 0, vids, NULL, NULL, NULL, NULL, NULL, NULL);

		temp_group_ids=ALLOC(long long, effective_vertices_count(vids));

		for(i=0; i<(size_t)igraph_vector_size(vids); i++)
		{
			tmp_vid=(int) VECTOR(*vids)[i];
			if(tmp_vid<0)
			{
				break;
			}
			parent_group=(struct Maat_group_inner*)HASH_fetch_by_id(scanner->vertex_id2group, tmp_vid);
			if(parent_group->ref_by_compile_cnt>0)//including itself
			{
				temp_group_ids[top_group_cnt]=parent_group->group_id;
				top_group_cnt++;
			}
		}
	}
	pthread_mutex_lock(&(group_rule->mutex));
	free(group_rule->top_groups);
	group_rule->top_group_cnt=top_group_cnt;
	group_rule->top_groups=ALLOC(long long, group_rule->top_group_cnt);
	memcpy(group_rule->top_groups, temp_group_ids, sizeof(long long)*group_rule->top_group_cnt);
	if(group_rule->top_group_cnt>scanner->max_presented_top_group_cnt)
	{
		scanner->max_presented_top_group_cnt=group_rule->top_group_cnt;
		scanner->most_popular_sub_group=group_rule->group_id;
	}
	pthread_mutex_unlock(&(group_rule->mutex));
	free(temp_group_ids);
	temp_group_ids=NULL;
	return;
}

void find_group_paths(struct Maat_scanner* scanner)
{
	scanner->group_graph_vcount=igraph_vcount(&scanner->group_graph);
	igraph_vector_init(&(scanner->dfs_vids), scanner->group_graph_vcount);
	MESA_htable_iterate(scanner->group_hash, walk_group_hash, scanner);
	igraph_vector_destroy(&scanner->dfs_vids);
	return;
}
void do_scanner_update(struct Maat_scanner* scanner, MESA_lqueue_head garbage_q, int scan_thread_num, void* logger)
{
	struct bool_matcher *tmp1=NULL,*tmp2=NULL;
	MESA_htable_handle tmp_map=NULL;
	struct Maat_table_runtime* table_rt=NULL;
	struct ip_matcher* old_ip_matcher=NULL;
	int i=0, ret=0;
	igraph_bool_t is_dag;
	igraph_is_dag(&(scanner->group_graph), &is_dag);
	if(!is_dag)
	{
		MESA_handle_runtime_log(logger, RLOG_LV_FATAL, maat_module,
								"Sub group cycle detected! Version %d",
								scanner->version);
		return;
	}
	find_group_paths(scanner);
	
	tmp1=create_bool_matcher(scanner->compile_hash,
							scan_thread_num,
							logger);
	tmp2=scanner->bool_matcher_expr_compiler;
	
	//assume pinter = operation is thread safe 
	scanner->bool_matcher_expr_compiler=tmp1;
	if(tmp2!=NULL)
	{
		garbage_bagging(GARBAGE_BOOL_MATCHER, tmp2, garbage_q);
	}
	MESA_handle_runtime_log(logger,RLOG_LV_INFO,maat_module ,
							"Version %d: dedup string rule %lu, sub group %d presents %d top groups",
							scanner->version,
							scanner->dedup_expr_num,
							scanner->most_popular_sub_group,
							scanner->max_presented_top_group_cnt);	
	scanner->dedup_expr_num=0;
	rulescan_batch_update(scanner->region,
							scanner->region_update_q,
							logger,
							scanner);
	for(i=0; (size_t)i<scanner->max_table_num; i++)
	{
		table_rt=Maat_table_runtime_get(scanner->table_rt_mgr, i);
		if(table_rt==NULL)
		{
			continue;
		}
		switch(table_rt->table_type)
		{
			case TABLE_TYPE_DIGEST:
			case TABLE_TYPE_SIMILARITY:
				
				ret=Maat_table_runtime_digest_batch_udpate(table_rt);
				if(ret<0)
				{
					MESA_handle_runtime_log(logger, RLOG_LV_FATAL, maat_module,
										"GIE_update error.");
				}
				break;
			case TABLE_TYPE_IP_PLUGIN:
				Maat_table_runtime_ip_plugin_rebuild_ip_matcher(table_rt);
				old_ip_matcher=Maat_table_runtime_dettach_old_ip_matcher(table_rt);
				garbage_bagging(GARBAGE_IP_MATCHER, old_ip_matcher, garbage_q);
				break;
			default:
				break;
		}

	}
	if(scanner->tmp_district_map!=NULL)
	{
		tmp_map=scanner->district_map;
		scanner->district_map=scanner->tmp_district_map;
		scanner->tmp_district_map=NULL;
		garbage_bagging(GARBAGE_MAP_STR2INT, tmp_map, garbage_q);
	}
	scanner->last_update_time=time(NULL);
	scanner->gie_update_q_size=0;
	scanner->to_update_group_cnt=0;
	scanner->to_update_compile_cnt=0;
	return;

}

void maat_start_cb(long long new_version, int update_type, void*u_para)
{
	struct _Maat_feather_t *feather=(struct _Maat_feather_t *)u_para;
	feather->new_version=new_version;
	
	if(update_type==CM_UPDATE_TYPE_FULL)
	{
		feather->update_tmp_scanner=create_maat_scanner(new_version,feather);
		MESA_handle_runtime_log(feather->logger,RLOG_LV_INFO,maat_module,
								"Full config version %u -> %u update start",
								feather->maat_version,new_version);
	}
	else
	{

		MESA_handle_runtime_log(feather->logger,RLOG_LV_INFO,maat_module,
								"Inc config version %u -> %u update start",
								feather->maat_version,new_version);
		feather->maat_version=new_version;
	}
	Maat_table_manager_all_plugin_cb_start(feather->table_mgr, update_type);
	return;
}
long long scanner_rule_num(struct Maat_scanner *scanner)
{
	long long total=0;
	struct Maat_table_runtime* table_rt=NULL;
	int i=0;
	for(i=0; (size_t)i<scanner->max_table_num; i++)
	{
		table_rt=Maat_table_runtime_get(scanner->table_rt_mgr, i);
		if(table_rt!=NULL)
		{
			total+=table_rt->origin_rule_num;
		}
	}
	return total;
}
void maat_finish_cb(void* u_para)
{
	struct _Maat_feather_t *feather=(struct _Maat_feather_t *)u_para; 
	long expr_wait_q_cnt=0;

	Maat_table_manager_all_plugin_cb_finish(feather->table_mgr);

	if(feather->update_tmp_scanner!=NULL)
	{
		feather->update_tmp_scanner->cfg_num=scanner_rule_num(feather->update_tmp_scanner);
		do_scanner_update(feather->update_tmp_scanner
						,feather->garbage_q
						,feather->scan_thread_num
						,feather->logger);
		MESA_handle_runtime_log(feather->logger,RLOG_LV_INFO,maat_module,
								"Full config version %u load %d entries complete.",
								feather->update_tmp_scanner->version,feather->update_tmp_scanner->cfg_num);	
	}
	else if(feather->scanner!=NULL)
	{
		feather->scanner->cfg_num=scanner_rule_num(feather->scanner);
		feather->scanner->version=feather->maat_version;
		expr_wait_q_cnt=MESA_lqueue_get_count(feather->scanner->region_update_q);
		feather->postpone_q_size=expr_wait_q_cnt+feather->scanner->gie_update_q_size;
		if(time(NULL)-feather->scanner->last_update_time>=feather->effect_interval_ms/1000)
		{
			do_scanner_update(feather->scanner
							,feather->garbage_q
							,feather->scan_thread_num
							,feather->logger);
			MESA_handle_runtime_log(feather->logger, RLOG_LV_INFO, maat_module
									,"Inc config version %u build complete, %d entries in total."
									,feather->scanner->version,feather->scanner->cfg_num);
			feather->postpone_q_size=0;
		}
		else
		{
			MESA_handle_runtime_log(feather->logger, RLOG_LV_INFO, maat_module,
									"Postpone %d entries of version %u load to rulescan.",
									feather->scanner->cfg_num, feather->scanner->version);
		}
	}
	else
	{
		 MESA_handle_runtime_log(feather->logger,RLOG_LV_INFO,maat_module,
									"Version %d have no valid scan rules, plugin callback complete.",
									feather->maat_version);
	}
	feather->new_version=-1;
	return;
}
int maat_update_cb(const char* table_name,const char* line,void *u_para)
{
	struct _Maat_feather_t *feather=(struct _Maat_feather_t *)u_para; 
	Maat_scanner* scanner=NULL;
	struct Maat_table_schema* p_table=NULL;
	if(feather->update_tmp_scanner!=NULL)
	{
		scanner=feather->update_tmp_scanner;
	}
	else
	{
		scanner=feather->scanner;
	}
//	MESA_handle_runtime_log(feather->logger, RLOG_LV_DEBUG, maat_module, "Maat table %s input: %s", table_name, line);
	p_table=Maat_table_get_desc_by_name(feather->table_mgr, table_name);
	if(!p_table)
	{
		MESA_handle_runtime_log(feather->logger, RLOG_LV_INFO, maat_module ,"update warning, unknown table name %s", table_name);
		return -1;	
	}
	Maat_table_set_updating_name(p_table, table_name);

	switch(p_table->table_type)
	{
		case	TABLE_TYPE_EXPR:
		case	TABLE_TYPE_EXPR_PLUS:
			update_expr_rule(p_table, line, scanner, feather->logger);
			break;
		case	TABLE_TYPE_IP:
		case	TABLE_TYPE_IP_PLUS:
			update_ip_rule(p_table, line, scanner, feather->logger);
			break;
		case	TABLE_TYPE_INTERVAL:
			update_intval_rule(p_table, line, scanner,feather->logger);
			break;
		case	TABLE_TYPE_DIGEST:
		case	TABLE_TYPE_SIMILARITY:
			update_digest_rule(p_table, line, scanner,feather->logger);
			break;
		case	TABLE_TYPE_COMPILE:
			update_compile_rule(p_table, line, scanner, feather->accept_tags, feather->n_tags, feather->logger);
			break;
		case	TABLE_TYPE_GROUP:
			update_group_rule(p_table, line, scanner, feather->table_mgr, feather->logger);
			break;
		case	TABLE_TYPE_PLUGIN:
			update_plugin_table(p_table, line, scanner, feather->accept_tags, feather->n_tags, feather->logger);
			break;
		case	TABLE_TYPE_IP_PLUGIN:
			update_ip_plugin_table(p_table, line, scanner, feather->accept_tags, feather->n_tags, feather->logger);
			break;		
		default:
			break;
	
	}
	return 0;
}
void *thread_rule_monitor(void *arg)
{
	struct _Maat_feather_t *feather=(struct _Maat_feather_t *)arg;
	struct Maat_scanner* old_scanner=NULL;
	long expr_wait_q_cnt=0;
	int scan_dir_cnt=0;
	int ret=0;
	char md5_tmp[MD5_DIGEST_LENGTH*2+1]={0};
	char err_str[MAX_TABLE_NAME_LEN]={0};

	struct stat attrib;
	size_t total_wait_rule_cnt=0;

	char maat_name[16];//Defined by prctl: The name can be up to 16 bytes long,and should 
						// be null  terminated if it contains fewer bytes.
	if(strlen(feather->instance_name)>0)
	{
		snprintf(maat_name,sizeof(maat_name),"MAAT_%s",feather->instance_name);
	}
	else
	{
		snprintf(maat_name,sizeof(maat_name),"MAAT");
	}
	ret=prctl(PR_SET_NAME,(unsigned long long)maat_name,NULL,NULL,NULL);
	//pthread_setname_np are introduced in glibc2.12
	//ret=pthread_setname_np(pthread_self(),maat_name); 
	assert(ret>=0);
	
	pthread_mutex_lock(&(feather->background_update_mutex));
	if(feather->DEFERRED_LOAD_ON!=0)
	{
		MESA_handle_runtime_log(feather->logger,RLOG_LV_INFO,maat_module,
								"Deferred Loading ON, updating in %s.",__func__);
		maat_read_full_config(feather);
	}
	pthread_mutex_unlock(&(feather->background_update_mutex));
	while(feather->still_working)
	{
		usleep(feather->scan_interval_ms*1000);
		scan_dir_cnt++;
		if(0==pthread_mutex_trylock(&(feather->background_update_mutex)))
		{
			switch(feather->input_mode)
			{
				case SOURCE_REDIS:
					redis_monitor_traverse(feather->maat_version,
											&(feather->mr_ctx),
											maat_start_cb,
											maat_update_cb,
											maat_finish_cb,
											feather,
											feather->decrypt_key,	//Not used.
											feather);
					break;
				case SOURCE_IRIS_FILE:
					config_monitor_traverse(feather->maat_version,
											feather->iris_ctx.inc_dir, 
											maat_start_cb,
											maat_update_cb,
											maat_finish_cb,
											feather,
											feather->decrypt_key,
											feather->logger);
					break;
				case SOURCE_JSON_FILE:
					memset(md5_tmp, 0, sizeof(md5_tmp));
				    stat(feather->json_ctx.json_file, &attrib);
					if(memcmp(&attrib.st_ctim, &(feather->json_ctx.last_md5_time), sizeof(attrib.st_ctim)))
					{
						feather->json_ctx.last_md5_time=attrib.st_ctim;
						md5_file(feather->json_ctx.json_file, md5_tmp);
						if(0!=strcmp(md5_tmp,feather->json_ctx.effective_json_md5))
						{
							ret=load_maat_json_file(feather, feather->json_ctx.json_file, err_str, sizeof(err_str));
							if(ret<0)
							{
								MESA_handle_runtime_log(feather->logger,RLOG_LV_INFO,maat_module ,
												"Maat re-initiate with JSON file %s (md5=%s)failed: %s",
												feather->json_ctx.json_file,
												md5_tmp,
												err_str);
							}
							else
							{
								config_monitor_traverse(0,
														feather->json_ctx.iris_file,
														maat_start_cb,
														maat_update_cb,
														maat_finish_cb,
														feather,
														feather->decrypt_key,
														feather->logger);
								MESA_handle_runtime_log(feather->logger,RLOG_LV_INFO,maat_module ,
												"Maat re-initiate with JSON file %s success, md5: %s",
												feather->json_ctx.json_file,
												md5_tmp);

							}

						}
					}
					break;
				default:
					assert(0);
					break;
			}

			if(feather->update_tmp_scanner!=NULL)
			{
				old_scanner=feather->scanner;
				//Some OS doesn't have __sync_lock_test_and_set.
				//feather->scanner=__sync_lock_test_and_set(&(feather->scanner),feather->update_tmp_scanner);
				feather->scanner=feather->update_tmp_scanner;
				if(old_scanner!=NULL)
				{
					if(feather->scanner->version>old_scanner->version)
					{
						MESA_handle_runtime_log(feather->logger,RLOG_LV_INFO,maat_module,
												"Maat version updated %d -> %d.",
												old_scanner->version, feather->scanner->version);
					}
					else
					{
						MESA_handle_runtime_log(feather->logger,RLOG_LV_FATAL,maat_module,
												"Maat version roll back %d -> %d.",
												old_scanner->version, feather->scanner->version);
					}
					assert(old_scanner->tomb_ref==feather->garbage_q);
					feather->zombie_rs_stream+=alignment_int64_array_sum(old_scanner->ref_cnt,old_scanner->max_thread_num);
					garbage_bagging(GARBAGE_SCANNER, old_scanner, feather->garbage_q);
				}
				feather->update_tmp_scanner=NULL;
				feather->maat_version=feather->scanner->version;
				feather->last_full_version=feather->scanner->version;
			}
			if(feather->scanner!=NULL)
			{
				expr_wait_q_cnt=MESA_lqueue_get_count(feather->scanner->region_update_q);
				feather->postpone_q_size=expr_wait_q_cnt+feather->scanner->gie_update_q_size;
				total_wait_rule_cnt=feather->postpone_q_size+feather->scanner->to_update_compile_cnt+feather->scanner->to_update_group_cnt;
				if(total_wait_rule_cnt>0&&time(NULL)-feather->scanner->last_update_time>=feather->effect_interval_ms/1000)
				{
					do_scanner_update(feather->scanner
									,feather->garbage_q
									,feather->scan_thread_num
									,feather->logger);
					feather->postpone_q_size=0;
					MESA_handle_runtime_log(feather->logger,RLOG_LV_INFO,maat_module,
											"Actual udpate config version %u, %d entries load to rulescan after postpone.",
											feather->scanner->version,feather->scanner->cfg_num);
				}
			}
			pthread_mutex_unlock(&(feather->background_update_mutex));
		}
		garbage_bury(feather->garbage_q,feather->effect_interval_ms/1000+10,feather->logger);
		if(feather->stat_on==1&&time(NULL)%2==0)//output every 2 seconds
		{
			maat_stat_output(feather);
		}
	}
	
	Maat_table_manager_destroy(feather->table_mgr);
	destroy_maat_scanner(feather->scanner);
	garbage_bury(feather->garbage_q,0,feather->logger);
	assert(0==MESA_lqueue_get_count(feather->garbage_q));
	MESA_lqueue_destroy(feather->garbage_q,lqueue_destroy_cb,NULL);
	
	alignment_int64_array_free(feather->thread_call_cnt);
	alignment_int64_array_free(feather->inner_mid_cnt);
	alignment_int64_array_free(feather->outer_mid_cnt);
	alignment_int64_array_free(feather->hit_cnt);
	alignment_int64_array_free(feather->not_grp_hit_cnt);
	if(feather->input_mode==SOURCE_REDIS)
	{
		if(feather->mr_ctx.read_ctx)
		{
			redisFree(feather->mr_ctx.read_ctx);
			feather->mr_ctx.read_ctx=NULL;
		}
		if(feather->mr_ctx.write_ctx)
		{
			redisFree(feather->mr_ctx.write_ctx);
			feather->mr_ctx.write_ctx=NULL;
		}
	}
	int i=0;
	for(i=0; i<feather->n_tags; i++)
	{
		free(feather->accept_tags[i].tag_name);
		free(feather->accept_tags[i].tag_val);
	}
	free(feather->accept_tags);
	free(feather->accept_tags_raw);
	if(feather->stat_on&& feather->stat_handle)
	{
		FS_stop(&(feather->stat_handle));
	}
	free(feather);
	return NULL;
}