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

#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <arpa/inet.h>
#include <linux/netfilter.h>
#include <linux/netfilter_arp.h>
#include <linux/netfilter/nf_tables.h>
#include <linux/netfilter_ipv4.h>
#include <netinet/ip_icmp.h>
#include <netinet/icmp6.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <errno.h>

#include <expression.h>
#include <statement.h>
#include <netlink.h>
#include <time.h>
#include <rule.h>
#include <erec.h>
#include <gmputil.h>
#include <utils.h>
#include <xt.h>

static int expr_evaluate(struct eval_ctx *ctx, struct expr **expr);

static const char * const byteorder_names[] = {
	[BYTEORDER_INVALID]		= "invalid",
	[BYTEORDER_HOST_ENDIAN]		= "host endian",
	[BYTEORDER_BIG_ENDIAN]		= "big endian",
};

#define chain_error(ctx, s1, fmt, args...) \
	__stmt_binary_error(ctx, &(s1)->location, NULL, fmt, ## args)
#define monitor_error(ctx, s1, fmt, args...) \
	__stmt_binary_error(ctx, &(s1)->location, NULL, fmt, ## args)
#define cmd_error(ctx, loc, fmt, args...) \
	__stmt_binary_error(ctx, loc, NULL, fmt, ## args)

static int __fmtstring(3, 4) set_error(struct eval_ctx *ctx,
				       const struct set *set,
				       const char *fmt, ...)
{
	struct error_record *erec;
	va_list ap;

	va_start(ap, fmt);
	erec = erec_vcreate(EREC_ERROR, &set->location, fmt, ap);
	va_end(ap);
	erec_queue(erec, ctx->msgs);
	return -1;
}

static void key_fix_dtype_byteorder(struct expr *key)
{
	const struct datatype *dtype = key->dtype;

	if (dtype->byteorder == key->byteorder)
		return;

	key->dtype = set_datatype_alloc(dtype, key->byteorder);
	if (dtype->flags & DTYPE_F_ALLOC)
		concat_type_destroy(dtype);
}

static struct expr *implicit_set_declaration(struct eval_ctx *ctx,
					     const char *name,
					     struct expr *key,
					     struct expr *expr)
{
	struct cmd *cmd;
	struct set *set;
	struct handle h;

	key_fix_dtype_byteorder(key);

	set = set_alloc(&expr->location);
	set->flags	= NFT_SET_ANONYMOUS | expr->set_flags;
	set->handle.set.name = xstrdup(name);
	set->key	= key;
	set->init	= expr;
	set->automerge	= set->flags & NFT_SET_INTERVAL;

	if (ctx->table != NULL)
		list_add_tail(&set->list, &ctx->table->sets);
	else {
		handle_merge(&set->handle, &ctx->cmd->handle);
		memset(&h, 0, sizeof(h));
		handle_merge(&h, &set->handle);
		cmd = cmd_alloc(CMD_ADD, CMD_OBJ_SET, &h, &expr->location, set);
		cmd->location = set->location;
		list_add_tail(&cmd->list, &ctx->cmd->list);
	}

	return set_ref_expr_alloc(&expr->location, set);
}

static enum ops byteorder_conversion_op(struct expr *expr,
					enum byteorder byteorder)
{
	switch (expr->byteorder) {
	case BYTEORDER_HOST_ENDIAN:
		if (byteorder == BYTEORDER_BIG_ENDIAN)
			return OP_HTON;
		break;
	case BYTEORDER_BIG_ENDIAN:
		if (byteorder == BYTEORDER_HOST_ENDIAN)
			return OP_NTOH;
		break;
	default:
		break;
	}
	BUG("invalid byte order conversion %u => %u\n",
	    expr->byteorder, byteorder);
}

static int byteorder_conversion(struct eval_ctx *ctx, struct expr **expr,
				enum byteorder byteorder)
{
	enum ops op;

	assert(!expr_is_constant(*expr) || expr_is_singleton(*expr));

	if ((*expr)->byteorder == byteorder)
		return 0;
	if (expr_basetype(*expr)->type != TYPE_INTEGER)
		return expr_error(ctx->msgs, *expr,
			 	  "Byteorder mismatch: expected %s, got %s",
				  byteorder_names[byteorder],
				  byteorder_names[(*expr)->byteorder]);

	if (expr_is_constant(*expr))
		(*expr)->byteorder = byteorder;
	else {
		op = byteorder_conversion_op(*expr, byteorder);
		*expr = unary_expr_alloc(&(*expr)->location, op, *expr);
		if (expr_evaluate(ctx, expr) < 0)
			return -1;
	}
	return 0;
}

static struct table *table_lookup_global(struct eval_ctx *ctx)
{
	struct table *table;

	if (ctx->table != NULL)
		return ctx->table;

	table = table_lookup(&ctx->cmd->handle, &ctx->nft->cache);
	if (table == NULL)
		return NULL;

	return table;
}

static int table_not_found(struct eval_ctx *ctx)
{
	struct table *table;

	table = table_lookup_fuzzy(&ctx->cmd->handle, &ctx->nft->cache);
	if (table == NULL)
		return cmd_error(ctx, &ctx->cmd->handle.table.location,
				 "%s", strerror(ENOENT));

	return cmd_error(ctx, &ctx->cmd->handle.table.location,
			 "%s; did you mean table ‘%s’ in family %s?",
			 strerror(ENOENT), table->handle.table.name,
			 family2str(table->handle.family));
}

static int chain_not_found(struct eval_ctx *ctx)
{
	const struct table *table;
	struct chain *chain;

	chain = chain_lookup_fuzzy(&ctx->cmd->handle, &ctx->nft->cache, &table);
	if (chain == NULL)
		return cmd_error(ctx, &ctx->cmd->handle.chain.location,
				 "%s", strerror(ENOENT));

	return cmd_error(ctx, &ctx->cmd->handle.chain.location,
			 "%s; did you mean chain ‘%s’ in table %s ‘%s’?",
			 strerror(ENOENT), chain->handle.chain.name,
			 family2str(chain->handle.family),
			 table->handle.table.name);
}

/*
 * Symbol expression: parse symbol and evaluate resulting expression.
 */
static int expr_evaluate_symbol(struct eval_ctx *ctx, struct expr **expr)
{
	struct error_record *erec;
	struct table *table;
	struct set *set;
	struct expr *new;
	int ret;

	switch ((*expr)->symtype) {
	case SYMBOL_VALUE:
		(*expr)->dtype = ctx->ectx.dtype;
		erec = symbol_parse(*expr, &new);
		if (erec != NULL) {
			erec_queue(erec, ctx->msgs);
			return -1;
		}
		break;
	case SYMBOL_SET:
		ret = cache_update(ctx->nft, ctx->cmd->op, ctx->msgs);
		if (ret < 0)
			return ret;

		table = table_lookup_global(ctx);
		if (table == NULL)
			return table_not_found(ctx);

		set = set_lookup(table, (*expr)->identifier);
		if (set == NULL)
			return expr_error(ctx->msgs, *expr,
					  "Set '%s' does not exist",
					  (*expr)->identifier);

		new = set_ref_expr_alloc(&(*expr)->location, set);
		break;
	}

	expr_free(*expr);
	*expr = new;

	return expr_evaluate(ctx, expr);
}

static int expr_evaluate_string(struct eval_ctx *ctx, struct expr **exprp)
{
	struct expr *expr = *exprp;
	unsigned int len = div_round_up(expr->len, BITS_PER_BYTE), datalen;
	struct expr *value, *prefix;
	int data_len = ctx->ectx.len > 0 ? ctx->ectx.len : len + 1;
	char data[data_len];

	if (ctx->ectx.len > 0) {
		if (expr->len > ctx->ectx.len)
			return expr_error(ctx->msgs, expr,
					  "String exceeds maximum length of %u",
					  ctx->ectx.len / BITS_PER_BYTE);
		expr->len = ctx->ectx.len;
	}

	memset(data + len, 0, data_len - len);
	mpz_export_data(data, expr->value, BYTEORDER_HOST_ENDIAN, len);

	if (strlen(data) == 0)
		return expr_error(ctx->msgs, expr,
				  "Empty string is not allowed");

	datalen = strlen(data) - 1;
	if (data[datalen] != '*') {
		/* We need to reallocate the constant expression with the right
		 * expression length to avoid problems on big endian.
		 */
		value = constant_expr_alloc(&expr->location, ctx->ectx.dtype,
					    BYTEORDER_HOST_ENDIAN,
					    expr->len, data);
		expr_free(expr);
		*exprp = value;
		return 0;
	}

	if (datalen >= 1 &&
	    data[datalen - 1] == '\\') {
		char unescaped_str[data_len];

		memset(unescaped_str, 0, sizeof(unescaped_str));
		xstrunescape(data, unescaped_str);

		value = constant_expr_alloc(&expr->location, ctx->ectx.dtype,
					    BYTEORDER_HOST_ENDIAN,
					    expr->len, unescaped_str);
		expr_free(expr);
		*exprp = value;
		return 0;
	}
	value = constant_expr_alloc(&expr->location, ctx->ectx.dtype,
				    BYTEORDER_HOST_ENDIAN,
				    datalen * BITS_PER_BYTE, data);

	prefix = prefix_expr_alloc(&expr->location, value,
				   datalen * BITS_PER_BYTE);
	prefix->dtype = ctx->ectx.dtype;
	prefix->flags |= EXPR_F_CONSTANT;
	prefix->byteorder = BYTEORDER_HOST_ENDIAN;

	expr_free(expr);
	*exprp = prefix;
	return 0;
}

static int expr_evaluate_integer(struct eval_ctx *ctx, struct expr **exprp)
{
	struct expr *expr = *exprp;
	char *valstr, *rangestr;
	mpz_t mask;

	if (ctx->ectx.maxval > 0 &&
	    mpz_cmp_ui(expr->value, ctx->ectx.maxval) > 0) {
		valstr = mpz_get_str(NULL, 10, expr->value);
		expr_error(ctx->msgs, expr,
			   "Value %s exceeds valid range 0-%u",
			   valstr, ctx->ectx.maxval);
		free(valstr);
		return -1;
	}

	mpz_init_bitmask(mask, ctx->ectx.len);
	if (mpz_cmp(expr->value, mask) > 0) {
		valstr = mpz_get_str(NULL, 10, expr->value);
		rangestr = mpz_get_str(NULL, 10, mask);
		expr_error(ctx->msgs, expr,
			   "Value %s exceeds valid range 0-%s",
			   valstr, rangestr);
		free(valstr);
		free(rangestr);
		mpz_clear(mask);
		return -1;
	}
	expr->byteorder = ctx->ectx.byteorder;
	expr->len = ctx->ectx.len;
	mpz_clear(mask);
	return 0;
}

static int expr_evaluate_value(struct eval_ctx *ctx, struct expr **expr)
{
	switch (expr_basetype(*expr)->type) {
	case TYPE_INTEGER:
		if (expr_evaluate_integer(ctx, expr) < 0)
			return -1;
		break;
	case TYPE_STRING:
		if (expr_evaluate_string(ctx, expr) < 0)
			return -1;
		break;
	default:
		BUG("invalid basetype %s\n", expr_basetype(*expr)->name);
	}
	return 0;
}

/*
 * Primary expressions determine the datatype context.
 */
static int expr_evaluate_primary(struct eval_ctx *ctx, struct expr **expr)
{
	__expr_set_context(&ctx->ectx, (*expr)->dtype, (*expr)->byteorder,
			   (*expr)->len, 0);
	return 0;
}

static int
conflict_resolution_gen_dependency(struct eval_ctx *ctx, int protocol,
				   const struct expr *expr,
				   struct stmt **res)
{
	enum proto_bases base = expr->payload.base;
	const struct proto_hdr_template *tmpl;
	const struct proto_desc *desc = NULL;
	struct expr *dep, *left, *right;
	struct stmt *stmt;

	assert(expr->payload.base == PROTO_BASE_LL_HDR);

	desc = ctx->pctx.protocol[base].desc;
	tmpl = &desc->templates[desc->protocol_key];
	left = payload_expr_alloc(&expr->location, desc, desc->protocol_key);

	right = constant_expr_alloc(&expr->location, tmpl->dtype,
				    tmpl->dtype->byteorder, tmpl->len,
				    constant_data_ptr(protocol, tmpl->len));

	dep = relational_expr_alloc(&expr->location, OP_EQ, left, right);
	stmt = expr_stmt_alloc(&dep->location, dep);
	if (stmt_evaluate(ctx, stmt) < 0)
		return expr_error(ctx->msgs, expr,
					  "dependency statement is invalid");

	*res = stmt;
	return 0;
}

static uint8_t expr_offset_shift(const struct expr *expr, unsigned int offset,
				 unsigned int *extra_len)
{
	unsigned int new_offset, len;
	int shift;

	new_offset = offset % BITS_PER_BYTE;
	len = round_up(expr->len, BITS_PER_BYTE);
	shift = len - (new_offset + expr->len);
	while (shift < 0) {
		shift += BITS_PER_BYTE;
		*extra_len += BITS_PER_BYTE;
	}
	return shift;
}

static void expr_evaluate_bits(struct eval_ctx *ctx, struct expr **exprp)
{
	struct expr *expr = *exprp, *and, *mask, *lshift, *off;
	unsigned masklen, len = expr->len, extra_len = 0;
	uint8_t shift;
	mpz_t bitmask;

	switch (expr->ops->type) {
	case EXPR_PAYLOAD:
		shift = expr_offset_shift(expr, expr->payload.offset,
					  &extra_len);
		break;
	case EXPR_EXTHDR:
		shift = expr_offset_shift(expr, expr->exthdr.tmpl->offset,
					  &extra_len);
		break;
	default:
		BUG("Unknown expression %s\n", expr->ops->name);
	}

	masklen = len + shift;
	assert(masklen <= NFT_REG_SIZE * BITS_PER_BYTE);

	mpz_init2(bitmask, masklen);
	mpz_bitmask(bitmask, len);
	mpz_lshift_ui(bitmask, shift);

	mask = constant_expr_alloc(&expr->location, expr_basetype(expr),
				   BYTEORDER_HOST_ENDIAN, masklen, NULL);
	mpz_set(mask->value, bitmask);

	and = binop_expr_alloc(&expr->location, OP_AND, expr, mask);
	and->dtype	= expr->dtype;
	and->byteorder	= expr->byteorder;
	and->len	= masklen;

	if (shift) {
		off = constant_expr_alloc(&expr->location,
					  expr_basetype(expr),
					  BYTEORDER_BIG_ENDIAN,
					  sizeof(shift), &shift);

		lshift = binop_expr_alloc(&expr->location, OP_RSHIFT, and, off);
		lshift->dtype		= expr->dtype;
		lshift->byteorder	= expr->byteorder;
		lshift->len		= masklen;

		*exprp = lshift;
	} else
		*exprp = and;

	if (extra_len)
		expr->len += extra_len;
}

static int __expr_evaluate_exthdr(struct eval_ctx *ctx, struct expr **exprp)
{
	struct expr *expr = *exprp;

	if (expr->exthdr.flags & NFT_EXTHDR_F_PRESENT)
		expr->dtype = &boolean_type;

	if (expr_evaluate_primary(ctx, exprp) < 0)
		return -1;

	if (expr->exthdr.tmpl->offset % BITS_PER_BYTE != 0 ||
	    expr->len % BITS_PER_BYTE != 0)
		expr_evaluate_bits(ctx, exprp);

	switch (expr->exthdr.op) {
	case NFT_EXTHDR_OP_TCPOPT: {
		static const unsigned int max_tcpoptlen = (15 * 4 - 20) * BITS_PER_BYTE;
		unsigned int totlen = 0;

		totlen += expr->exthdr.tmpl->offset;
		totlen += expr->exthdr.tmpl->len;
		totlen += expr->exthdr.offset;

		if (totlen > max_tcpoptlen)
			return expr_error(ctx->msgs, expr,
					  "offset and size %u exceeds max tcp headerlen (%u)",
					  totlen, max_tcpoptlen);
		break;
	}
	default:
		break;
	}

	return 0;
}

/*
 * Exthdr expression: check whether dependencies are fulfilled, otherwise
 * generate the necessary relational expression and prepend it to the current
 * statement.
 */
static int expr_evaluate_exthdr(struct eval_ctx *ctx, struct expr **exprp)
{
	const struct proto_desc *base, *dependency = NULL;
	enum proto_bases pb = PROTO_BASE_NETWORK_HDR;
	struct expr *expr = *exprp;
	struct stmt *nstmt;

	switch (expr->exthdr.op) {
	case NFT_EXTHDR_OP_TCPOPT:
		dependency = &proto_tcp;
		pb = PROTO_BASE_TRANSPORT_HDR;
		break;
	case NFT_EXTHDR_OP_IPV6:
	default:
		dependency = &proto_ip6;
		break;
	}

	assert(dependency);

	base = ctx->pctx.protocol[pb].desc;
	if (base == dependency)
		return __expr_evaluate_exthdr(ctx, exprp);

	if (base)
		return expr_error(ctx->msgs, expr,
				  "cannot use exthdr with %s", base->name);

	if (exthdr_gen_dependency(ctx, expr, dependency, pb - 1, &nstmt) < 0)
		return -1;

	list_add(&nstmt->list, &ctx->rule->stmts);

	return __expr_evaluate_exthdr(ctx, exprp);
}

/* dependency supersede.
 *
 * 'inet' is a 'phony' l2 dependency used by NFPROTO_INET to fulfill network
 * header dependency, i.e. ensure that 'ip saddr 1.2.3.4' only sees ip headers.
 *
 * If a match expression that depends on a particular L2 header, e.g. ethernet,
 * is used, we thus get a conflict since we already have a l2 header dependency.
 *
 * But in the inet case we can just ignore the conflict since only another
 * restriction is added, and these are not mutually exclusive.
 *
 * Example: inet filter in ip saddr 1.2.3.4 ether saddr a:b:c:d:e:f
 *
 * ip saddr adds meta dependency on ipv4 packets
 * ether saddr adds another dependeny on ethernet frames.
 */
static int meta_iiftype_gen_dependency(struct eval_ctx *ctx,
				       struct expr *payload, struct stmt **res)
{
	struct stmt *nstmt;
	uint16_t type;

	if (proto_dev_type(payload->payload.desc, &type) < 0)
		return expr_error(ctx->msgs, payload,
				  "protocol specification is invalid "
				  "for this family");

	nstmt = meta_stmt_meta_iiftype(&payload->location, type);
	if (stmt_evaluate(ctx, nstmt) < 0)
		return expr_error(ctx->msgs, payload,
				  "dependency statement is invalid");

	*res = nstmt;
	return 0;
}

static bool proto_is_dummy(const struct proto_desc *desc)
{
	return desc == &proto_inet || desc == &proto_netdev;
}

static int resolve_protocol_conflict(struct eval_ctx *ctx,
				     const struct proto_desc *desc,
				     struct expr *payload)
{
	enum proto_bases base = payload->payload.base;
	struct stmt *nstmt = NULL;
	int link, err;

	if (payload->payload.base == PROTO_BASE_LL_HDR &&
	    proto_is_dummy(desc)) {
		err = meta_iiftype_gen_dependency(ctx, payload, &nstmt);
		if (err < 0)
			return err;

		list_add_tail(&nstmt->list, &ctx->stmt->list);
	}

	assert(base <= PROTO_BASE_MAX);
	/* This payload and the existing context don't match, conflict. */
	if (ctx->pctx.protocol[base + 1].desc != NULL)
		return 1;

	link = proto_find_num(desc, payload->payload.desc);
	if (link < 0 ||
	    conflict_resolution_gen_dependency(ctx, link, payload, &nstmt) < 0)
		return 1;

	payload->payload.offset += ctx->pctx.protocol[base].offset;
	list_add_tail(&nstmt->list, &ctx->stmt->list);

	return 0;
}

/*
 * Payload expression: check whether dependencies are fulfilled, otherwise
 * generate the necessary relational expression and prepend it to the current
 * statement.
 */
static int __expr_evaluate_payload(struct eval_ctx *ctx, struct expr *expr)
{
	struct expr *payload = expr;
	enum proto_bases base = payload->payload.base;
	const struct proto_desc *desc;
	struct stmt *nstmt;
	int err;

	if (expr->ops->type == EXPR_PAYLOAD && expr->payload.is_raw)
		return 0;

	desc = ctx->pctx.protocol[base].desc;
	if (desc == NULL) {
		if (payload_gen_dependency(ctx, payload, &nstmt) < 0)
			return -1;
		list_add_tail(&nstmt->list, &ctx->stmt->list);
	} else {
		/* No conflict: Same payload protocol as context, adjust offset
		 * if needed.
		 */
		if (desc == payload->payload.desc) {
			payload->payload.offset +=
				ctx->pctx.protocol[base].offset;
			return 0;
		}
		/* If we already have context and this payload is on the same
		 * base, try to resolve the protocol conflict.
		 */
		if (payload->payload.base == desc->base) {
			err = resolve_protocol_conflict(ctx, desc, payload);
			if (err <= 0)
				return err;

			desc = ctx->pctx.protocol[base].desc;
			if (desc == payload->payload.desc)
				return 0;
		}
		return expr_error(ctx->msgs, payload,
				  "conflicting protocols specified: %s vs. %s",
				  ctx->pctx.protocol[base].desc->name,
				  payload->payload.desc->name);
	}
	return 0;
}

static bool payload_needs_adjustment(const struct expr *expr)
{
	return expr->payload.offset % BITS_PER_BYTE != 0 ||
	       expr->len % BITS_PER_BYTE != 0;
}

static int expr_evaluate_payload(struct eval_ctx *ctx, struct expr **exprp)
{
	struct expr *expr = *exprp;

	if (__expr_evaluate_payload(ctx, expr) < 0)
		return -1;

	if (expr_evaluate_primary(ctx, exprp) < 0)
		return -1;

	if (payload_needs_adjustment(expr))
		expr_evaluate_bits(ctx, exprp);

	return 0;
}

/*
 * RT expression: validate protocol dependencies.
 */
static int expr_evaluate_rt(struct eval_ctx *ctx, struct expr **expr)
{
	static const char emsg[] = "cannot determine ip protocol version, use \"ip nexthop\" or \"ip6 nexthop\" instead";
	struct expr *rt = *expr;

	rt_expr_update_type(&ctx->pctx, rt);

	switch (rt->rt.key) {
	case NFT_RT_NEXTHOP4:
		if (rt->dtype != &ipaddr_type)
			return expr_error(ctx->msgs, rt, "%s", emsg);
		if (ctx->pctx.family == NFPROTO_IPV6)
			return expr_error(ctx->msgs, rt, "%s nexthop will not match", "ip");
		break;
	case NFT_RT_NEXTHOP6:
		if (rt->dtype != &ip6addr_type)
			return expr_error(ctx->msgs, rt, "%s", emsg);
		if (ctx->pctx.family == NFPROTO_IPV4)
			return expr_error(ctx->msgs, rt, "%s nexthop will not match", "ip6");
		break;
	default:
		break;
	}

	return expr_evaluate_primary(ctx, expr);
}

static int ct_gen_nh_dependency(struct eval_ctx *ctx, struct expr *ct)
{
	const struct proto_desc *base, *base_now;
	struct expr *left, *right, *dep;
	struct stmt *nstmt = NULL;

	base_now = ctx->pctx.protocol[PROTO_BASE_NETWORK_HDR].desc;

	switch (ct->ct.nfproto) {
	case NFPROTO_IPV4:
		base = &proto_ip;
		break;
	case NFPROTO_IPV6:
		base = &proto_ip6;
		break;
	default:
		base = ctx->pctx.protocol[PROTO_BASE_NETWORK_HDR].desc;
		if (base == &proto_ip)
			ct->ct.nfproto = NFPROTO_IPV4;
		else if (base == &proto_ip)
			ct->ct.nfproto = NFPROTO_IPV6;

		if (base)
			break;

		return expr_error(ctx->msgs, ct,
				  "cannot determine ip protocol version, use \"ip %1$caddr\" or \"ip6 %1$caddr\" instead",
				  ct->ct.key == NFT_CT_SRC ? 's' : 'd');
	}

	/* no additional dependency needed? */
	if (base == base_now)
		return 0;

	if (base_now && base_now != base)
		return expr_error(ctx->msgs, ct,
				  "conflicting dependencies: %s vs. %s\n",
				  base->name,
				  ctx->pctx.protocol[PROTO_BASE_NETWORK_HDR].desc->name);
	switch (ctx->pctx.family) {
	case NFPROTO_IPV4:
	case NFPROTO_IPV6:
		return 0;
	}

	left = ct_expr_alloc(&ct->location, NFT_CT_L3PROTOCOL, ct->ct.direction, ct->ct.nfproto);

	right = constant_expr_alloc(&ct->location, left->dtype,
				    left->dtype->byteorder, left->len,
				    constant_data_ptr(ct->ct.nfproto, left->len));
	dep = relational_expr_alloc(&ct->location, OP_EQ, left, right);

	relational_expr_pctx_update(&ctx->pctx, dep);

	nstmt = expr_stmt_alloc(&dep->location, dep);

	list_add_tail(&nstmt->list, &ctx->stmt->list);
	return 0;
}

/*
 * CT expression: update the protocol dependant types bases on the protocol
 * context.
 */
static int expr_evaluate_ct(struct eval_ctx *ctx, struct expr **expr)
{
	struct expr *ct = *expr;

	switch (ct->ct.key) {
	case NFT_CT_SRC:
	case NFT_CT_DST:
		ct_gen_nh_dependency(ctx, ct);
		break;
	default:
		break;
	}

	ct_expr_update_type(&ctx->pctx, ct);

	return expr_evaluate_primary(ctx, expr);
}

/*
 * Prefix expression: the argument must be a constant value of integer or
 * string base type; the prefix length must be less than or equal to the type
 * width.
 */
static int expr_evaluate_prefix(struct eval_ctx *ctx, struct expr **expr)
{
	struct expr *prefix = *expr, *base, *and, *mask;

	if (expr_evaluate(ctx, &prefix->prefix) < 0)
		return -1;
	base = prefix->prefix;

	if (!expr_is_constant(base))
		return expr_error(ctx->msgs, prefix,
				  "Prefix expression is undefined for "
				  "non-constant expressions");

	switch (expr_basetype(base)->type) {
	case TYPE_INTEGER:
	case TYPE_STRING:
		break;
	default:
		return expr_error(ctx->msgs, prefix,
				  "Prefix expression is undefined for "
				  "%s types", base->dtype->desc);
	}

	if (prefix->prefix_len > base->len)
		return expr_error(ctx->msgs, prefix,
				  "Prefix length %u is invalid for type "
				  "of %u bits width",
				  prefix->prefix_len, base->len);

	/* Clear the uncovered bits of the base value */
	mask = constant_expr_alloc(&prefix->location, expr_basetype(base),
				   BYTEORDER_HOST_ENDIAN, base->len, NULL);
	switch (expr_basetype(base)->type) {
	case TYPE_INTEGER:
		mpz_prefixmask(mask->value, base->len, prefix->prefix_len);
		break;
	case TYPE_STRING:
		mpz_init2(mask->value, base->len);
		mpz_bitmask(mask->value, prefix->prefix_len);
		break;
	}
	and  = binop_expr_alloc(&prefix->location, OP_AND, base, mask);
	prefix->prefix = and;
	if (expr_evaluate(ctx, &prefix->prefix) < 0)
		return -1;
	base = prefix->prefix;
	assert(expr_is_constant(base));

	prefix->dtype	  = base->dtype;
	prefix->byteorder = base->byteorder;
	prefix->len	  = base->len;
	prefix->flags	 |= EXPR_F_CONSTANT;
	return 0;
}

/*
 * Range expression: both sides must be constants of integer base type.
 */
static int expr_evaluate_range_expr(struct eval_ctx *ctx,
				    const struct expr *range,
				    struct expr **expr)
{
	if (expr_evaluate(ctx, expr) < 0)
		return -1;

	if (expr_basetype(*expr)->type != TYPE_INTEGER)
		return expr_binary_error(ctx->msgs, *expr, range,
					 "Range expression is undefined for "
					 "%s types", (*expr)->dtype->desc);
	if (!expr_is_constant(*expr))
		return expr_binary_error(ctx->msgs, *expr, range,
					 "Range is not constant");
	return 0;
}

static int expr_evaluate_range(struct eval_ctx *ctx, struct expr **expr)
{
	struct expr *range = *expr, *left, *right;

	if (expr_evaluate_range_expr(ctx, range, &range->left) < 0)
		return -1;
	left = range->left;

	if (expr_evaluate_range_expr(ctx, range, &range->right) < 0)
		return -1;
	right = range->right;

	if (mpz_cmp(left->value, right->value) >= 0)
		return expr_error(ctx->msgs, range,
				  "Range has zero or negative size");

	range->dtype = left->dtype;
	range->flags |= EXPR_F_CONSTANT;
	return 0;
}

/*
 * Unary expressions: unary expressions are only generated internally for
 * byteorder conversion of non-constant numerical expressions.
 */
static int expr_evaluate_unary(struct eval_ctx *ctx, struct expr **expr)
{
	struct expr *unary = *expr, *arg;
	enum byteorder byteorder;

	if (expr_evaluate(ctx, &unary->arg) < 0)
		return -1;
	arg = unary->arg;

	assert(!expr_is_constant(arg));
	assert(expr_basetype(arg)->type == TYPE_INTEGER);
	assert(arg->ops->type != EXPR_UNARY);

	switch (unary->op) {
	case OP_HTON:
		assert(arg->byteorder == BYTEORDER_HOST_ENDIAN);
		byteorder = BYTEORDER_BIG_ENDIAN;
		break;
	case OP_NTOH:
		assert(arg->byteorder == BYTEORDER_BIG_ENDIAN);
		byteorder = BYTEORDER_HOST_ENDIAN;
		break;
	default:
		BUG("invalid unary operation %u\n", unary->op);
	}

	unary->dtype	 = arg->dtype;
	unary->byteorder = byteorder;
	unary->len	 = arg->len;
	return 0;
}

/*
 * Binops
 */
static int constant_binop_simplify(struct eval_ctx *ctx, struct expr **expr)
{
	struct expr *op = *expr, *left = (*expr)->left, *right = (*expr)->right;
	struct expr *new;
	mpz_t val, mask;

	assert(left->ops->type == EXPR_VALUE);
	assert(right->ops->type == EXPR_VALUE);
	assert(left->byteorder == right->byteorder);

	mpz_init2(val, op->len);
	mpz_init_bitmask(mask, op->len);

	switch (op->op) {
	case OP_AND:
		mpz_and(val, left->value, right->value);
		mpz_and(val, val, mask);
		break;
	case OP_XOR:
		mpz_xor(val, left->value, right->value);
		mpz_and(val, val, mask);
		break;
	case OP_OR:
		mpz_ior(val, left->value, right->value);
		mpz_and(val, val, mask);
		break;
	case OP_LSHIFT:
		assert(left->byteorder == BYTEORDER_HOST_ENDIAN);
		mpz_set(val, left->value);
		mpz_lshift_ui(val, mpz_get_uint32(right->value));
		mpz_and(val, val, mask);
		break;
	case OP_RSHIFT:
		assert(left->byteorder == BYTEORDER_HOST_ENDIAN);
		mpz_set(val, left->value);
		mpz_and(val, val, mask);
		mpz_rshift_ui(val, mpz_get_uint32(right->value));
		break;
	default:
		BUG("invalid binary operation %u\n", op->op);
	}

	new = constant_expr_alloc(&op->location, op->dtype, op->byteorder,
				  op->len, NULL);
	mpz_set(new->value, val);

	expr_free(*expr);
	*expr = new;

	mpz_clear(mask);
	mpz_clear(val);

	return expr_evaluate(ctx, expr);
}

static int expr_evaluate_shift(struct eval_ctx *ctx, struct expr **expr)
{
	struct expr *op = *expr, *left = op->left, *right = op->right;

	if (mpz_get_uint32(right->value) >= left->len)
		return expr_binary_error(ctx->msgs, right, left,
					 "%s shift of %u bits is undefined "
					 "for type of %u bits width",
					 op->op == OP_LSHIFT ? "Left" : "Right",
					 mpz_get_uint32(right->value),
					 left->len);

	/* Both sides need to be in host byte order */
	if (byteorder_conversion(ctx, &op->left, BYTEORDER_HOST_ENDIAN) < 0)
		return -1;
	left = op->left;
	if (byteorder_conversion(ctx, &op->right, BYTEORDER_HOST_ENDIAN) < 0)
		return -1;

	op->dtype     = &integer_type;
	op->byteorder = BYTEORDER_HOST_ENDIAN;
	op->len       = left->len;

	if (expr_is_constant(left))
		return constant_binop_simplify(ctx, expr);
	return 0;
}

static int expr_evaluate_bitwise(struct eval_ctx *ctx, struct expr **expr)
{
	struct expr *op = *expr, *left = op->left;

	if (byteorder_conversion(ctx, &op->right, left->byteorder) < 0)
		return -1;

	op->dtype     = left->dtype;
	op->byteorder = left->byteorder;
	op->len	      = left->len;

	if (expr_is_constant(left))
		return constant_binop_simplify(ctx, expr);
	return 0;
}

/*
 * Binop expression: both sides must be of integer base type. The left
 * hand side may be either constant or non-constant; in case its constant
 * it must be a singleton. The ride hand side must always be a constant
 * singleton.
 */
static int expr_evaluate_binop(struct eval_ctx *ctx, struct expr **expr)
{
	struct expr *op = *expr, *left, *right;
	const char *sym = expr_op_symbols[op->op];

	if (expr_evaluate(ctx, &op->left) < 0)
		return -1;
	left = op->left;

	if (op->op == OP_LSHIFT || op->op == OP_RSHIFT)
		expr_set_context(&ctx->ectx, &integer_type, ctx->ectx.len);
	if (expr_evaluate(ctx, &op->right) < 0)
		return -1;
	right = op->right;

	switch (expr_basetype(left)->type) {
	case TYPE_INTEGER:
	case TYPE_STRING:
		break;
	default:
		return expr_binary_error(ctx->msgs, left, op,
					 "Binary operation (%s) is undefined "
					 "for %s types",
					 sym, left->dtype->desc);
	}

	if (expr_is_constant(left) && !expr_is_singleton(left))
		return expr_binary_error(ctx->msgs, left, op,
					 "Binary operation (%s) is undefined "
					 "for %s expressions",
					 sym, left->ops->name);

	if (!expr_is_constant(right))
		return expr_binary_error(ctx->msgs, right, op,
					 "Right hand side of binary operation "
					 "(%s) must be constant", sym);

	if (!expr_is_singleton(right))
		return expr_binary_error(ctx->msgs, left, op,
					 "Binary operation (%s) is undefined "
					 "for %s expressions",
					 sym, right->ops->name);

	/* The grammar guarantees this */
	assert(expr_basetype(left) == expr_basetype(right));

	switch (op->op) {
	case OP_LSHIFT:
	case OP_RSHIFT:
		return expr_evaluate_shift(ctx, expr);
	case OP_AND:
	case OP_XOR:
	case OP_OR:
		return expr_evaluate_bitwise(ctx, expr);
	default:
		BUG("invalid binary operation %u\n", op->op);
	}
}

static int list_member_evaluate(struct eval_ctx *ctx, struct expr **expr)
{
	struct expr *next = list_entry((*expr)->list.next, struct expr, list);
	int err;

	assert(*expr != next);
	list_del(&(*expr)->list);
	err = expr_evaluate(ctx, expr);
	list_add_tail(&(*expr)->list, &next->list);
	return err;
}

static int expr_evaluate_concat(struct eval_ctx *ctx, struct expr **expr,
				bool eval)
{
	const struct datatype *dtype = ctx->ectx.dtype, *tmp;
	uint32_t type = dtype ? dtype->type : 0, ntype = 0;
	int off = dtype ? dtype->subtypes : 0;
	unsigned int flags = EXPR_F_CONSTANT | EXPR_F_SINGLETON;
	struct expr *i, *next;

	list_for_each_entry_safe(i, next, &(*expr)->expressions, list) {
		if (expr_is_constant(*expr) && dtype && off == 0)
			return expr_binary_error(ctx->msgs, i, *expr,
						 "unexpected concat component, "
						 "expecting %s",
						 dtype->desc);

		if (dtype == NULL)
			tmp = datatype_lookup(TYPE_INVALID);
		else
			tmp = concat_subtype_lookup(type, --off);
		expr_set_context(&ctx->ectx, tmp, tmp->size);

		if (eval && list_member_evaluate(ctx, &i) < 0)
			return -1;
		flags &= i->flags;

		if (dtype == NULL && i->dtype->size == 0)
			return expr_binary_error(ctx->msgs, i, *expr,
						 "can not use variable sized "
						 "data types (%s) in concat "
						 "expressions",
						 i->dtype->name);

		ntype = concat_subtype_add(ntype, i->dtype->type);
	}

	(*expr)->flags |= flags;
	(*expr)->dtype = concat_type_alloc(ntype);
	(*expr)->len   = (*expr)->dtype->size;

	if (off > 0)
		return expr_error(ctx->msgs, *expr,
				  "datatype mismatch, expected %s, "
				  "expression has type %s",
				  dtype->desc, (*expr)->dtype->desc);

	expr_set_context(&ctx->ectx, (*expr)->dtype, (*expr)->len);

	return 0;
}

static int expr_evaluate_list(struct eval_ctx *ctx, struct expr **expr)
{
	struct expr *list = *expr, *new, *i, *next;
	mpz_t val;

	mpz_init_set_ui(val, 0);
	list_for_each_entry_safe(i, next, &list->expressions, list) {
		if (list_member_evaluate(ctx, &i) < 0)
			return -1;
		if (i->ops->type != EXPR_VALUE)
			return expr_error(ctx->msgs, i,
					  "List member must be a constant "
					  "value");
		if (i->dtype->basetype->type != TYPE_BITMASK)
			return expr_error(ctx->msgs, i,
					  "Basetype of type %s is not bitmask",
					  i->dtype->desc);
		mpz_ior(val, val, i->value);
	}

	new = constant_expr_alloc(&list->location, ctx->ectx.dtype,
				  BYTEORDER_HOST_ENDIAN, ctx->ectx.len, NULL);
	mpz_set(new->value, val);
	mpz_clear(val);

	expr_free(*expr);
	*expr = new;
	return 0;
}

static int expr_evaluate_set_elem(struct eval_ctx *ctx, struct expr **expr)
{
	struct expr *elem = *expr;

	if (expr_evaluate(ctx, &elem->key) < 0)
		return -1;

	if (ctx->set &&
	    !(ctx->set->flags & (NFT_SET_ANONYMOUS | NFT_SET_INTERVAL))) {
		switch (elem->key->ops->type) {
		case EXPR_PREFIX:
			return expr_error(ctx->msgs, elem,
					  "Set member cannot be prefix, "
					  "missing interval flag on declaration");
		case EXPR_RANGE:
			return expr_error(ctx->msgs, elem,
					  "Set member cannot be range, "
					  "missing interval flag on declaration");
		default:
			break;
		}
	}

	elem->dtype = elem->key->dtype;
	elem->len   = elem->key->len;
	elem->flags = elem->key->flags;
	return 0;
}

static int expr_evaluate_set(struct eval_ctx *ctx, struct expr **expr)
{
	struct expr *set = *expr, *i, *next;

	list_for_each_entry_safe(i, next, &set->expressions, list) {
		if (list_member_evaluate(ctx, &i) < 0)
			return -1;

		if (i->ops->type == EXPR_SET_ELEM &&
		    i->key->ops->type == EXPR_SET_REF)
			return expr_error(ctx->msgs, i,
					  "Set reference cannot be part of another set");

		if (i->ops->type == EXPR_SET_ELEM &&
		    i->key->ops->type == EXPR_SET) {
			struct expr *new = expr_clone(i->key);

			set->set_flags |= i->key->set_flags;
			list_replace(&i->list, &new->list);
			expr_free(i);
			i = new;
		}

		if (!expr_is_constant(i))
			return expr_error(ctx->msgs, i,
					  "Set member is not constant");

		if (i->ops->type == EXPR_SET) {
			/* Merge recursive set definitions */
			list_splice_tail_init(&i->expressions, &i->list);
			list_del(&i->list);
			set->size      += i->size - 1;
			set->set_flags |= i->set_flags;
			expr_free(i);
		} else if (!expr_is_singleton(i))
			set->set_flags |= NFT_SET_INTERVAL;
	}

	set->set_flags |= NFT_SET_CONSTANT;

	set->dtype = ctx->ectx.dtype;
	set->len   = ctx->ectx.len;
	set->flags |= EXPR_F_CONSTANT;
	return 0;
}

static int binop_transfer(struct eval_ctx *ctx, struct expr **expr);
static int expr_evaluate_map(struct eval_ctx *ctx, struct expr **expr)
{
	struct expr_ctx ectx = ctx->ectx;
	struct expr *map = *expr, *mappings;
	struct expr *key;

	expr_set_context(&ctx->ectx, NULL, 0);
	if (expr_evaluate(ctx, &map->map) < 0)
		return -1;
	if (expr_is_constant(map->map))
		return expr_error(ctx->msgs, map->map,
				  "Map expression can not be constant");

	mappings = map->mappings;
	mappings->set_flags |= NFT_SET_MAP;

	switch (map->mappings->ops->type) {
	case EXPR_SET:
		key = constant_expr_alloc(&map->location,
				 ctx->ectx.dtype,
				 ctx->ectx.byteorder,
				 ctx->ectx.len, NULL);

		mappings = implicit_set_declaration(ctx, "__map%d",
						    key,
						    mappings);
		mappings->set->datatype = set_datatype_alloc(ectx.dtype,
							     ectx.byteorder);
		mappings->set->datalen  = ectx.len;

		map->mappings = mappings;

		ctx->set = mappings->set;
		if (expr_evaluate(ctx, &map->mappings->set->init) < 0)
			return -1;
		expr_set_context(&ctx->ectx, ctx->set->key->dtype, ctx->set->key->len);
		if (binop_transfer(ctx, expr) < 0)
			return -1;

		ctx->set->key->len = ctx->ectx.len;
		ctx->set = NULL;
		map = *expr;
		map->mappings->set->flags |= map->mappings->set->init->set_flags;
		break;
	case EXPR_SYMBOL:
		if (expr_evaluate(ctx, &map->mappings) < 0)
			return -1;
		if (map->mappings->ops->type != EXPR_SET_REF ||
		    !(map->mappings->set->flags & NFT_SET_MAP))
			return expr_error(ctx->msgs, map->mappings,
					  "Expression is not a map");
		break;
	default:
		BUG("invalid mapping expression %s\n",
		    map->mappings->ops->name);
	}

	if (!datatype_equal(map->map->dtype, map->mappings->set->key->dtype))
		return expr_binary_error(ctx->msgs, map->mappings, map->map,
					 "datatype mismatch, map expects %s, "
					 "mapping expression has type %s",
					 map->mappings->set->key->dtype->desc,
					 map->map->dtype->desc);

	map->dtype = map->mappings->set->datatype;
	map->flags |= EXPR_F_CONSTANT;

	/* Data for range lookups needs to be in big endian order */
	if (map->mappings->set->flags & NFT_SET_INTERVAL &&
	    byteorder_conversion(ctx, &map->map, BYTEORDER_BIG_ENDIAN) < 0)
		return -1;

	return 0;
}

static int expr_evaluate_mapping(struct eval_ctx *ctx, struct expr **expr)
{
	struct expr *mapping = *expr;
	struct set *set = ctx->set;

	if (set == NULL)
		return expr_error(ctx->msgs, mapping,
				  "mapping outside of map context");
	if (!(set->flags & (NFT_SET_MAP | NFT_SET_OBJECT)))
		return set_error(ctx, set, "set is not a map");

	expr_set_context(&ctx->ectx, set->key->dtype, set->key->len);
	if (expr_evaluate(ctx, &mapping->left) < 0)
		return -1;
	if (!expr_is_constant(mapping->left))
		return expr_error(ctx->msgs, mapping->left,
				  "Key must be a constant");
	mapping->flags |= mapping->left->flags & EXPR_F_SINGLETON;

	expr_set_context(&ctx->ectx, set->datatype, set->datalen);
	if (expr_evaluate(ctx, &mapping->right) < 0)
		return -1;
	if (!expr_is_constant(mapping->right))
		return expr_error(ctx->msgs, mapping->right,
				  "Value must be a constant");
	if (!expr_is_singleton(mapping->right))
		return expr_error(ctx->msgs, mapping->right,
				  "Value must be a singleton");

	mapping->flags |= EXPR_F_CONSTANT;
	return 0;
}

/* We got datatype context via statement. If the basetype is compatible, set
 * this expression datatype to the one of the statement to make it datatype
 * compatible. This is a more conservative approach than enabling datatype
 * compatibility between two different datatypes whose basetype is the same,
 * let's revisit this later once users come with valid usecases to generalize
 * this.
 */
static void expr_dtype_integer_compatible(struct eval_ctx *ctx,
					  struct expr *expr)
{
	if (ctx->ectx.dtype &&
	    ctx->ectx.dtype->basetype == &integer_type &&
	    ctx->ectx.len == 4 * BITS_PER_BYTE) {
		expr->dtype = ctx->ectx.dtype;
		expr->len   = ctx->ectx.len;
	}
}

static int expr_evaluate_numgen(struct eval_ctx *ctx, struct expr **exprp)
{
	struct expr *expr = *exprp;

	expr_dtype_integer_compatible(ctx, expr);

	__expr_set_context(&ctx->ectx, expr->dtype, expr->byteorder, expr->len,
			   expr->numgen.mod - 1);
	return 0;
}

static int expr_evaluate_hash(struct eval_ctx *ctx, struct expr **exprp)
{
	struct expr *expr = *exprp;

	expr_dtype_integer_compatible(ctx, expr);

	expr_set_context(&ctx->ectx, NULL, 0);
	if (expr->hash.expr &&
	    expr_evaluate(ctx, &expr->hash.expr) < 0)
		return -1;

	/* expr_evaluate_primary() sets the context to what to the input
         * expression to be hashed. Since this input is transformed to a 4 bytes
	 * integer, restore context to the datatype that results from hashing.
	 */
	__expr_set_context(&ctx->ectx, expr->dtype, expr->byteorder, expr->len,
			   expr->hash.mod - 1);

	return 0;
}

/*
 * Transfer the invertible binops to the constant side of an equality
 * expression. A left shift is only invertible if the low n bits are
 * zero.
 */
static int binop_can_transfer(struct eval_ctx *ctx,
			      struct expr *left, struct expr *right)
{
	int err;

	switch (right->ops->type) {
	case EXPR_VALUE:
		break;
	case EXPR_SET_ELEM:
		return binop_can_transfer(ctx, left, right->key);
	case EXPR_RANGE:
		err = binop_can_transfer(ctx, left, right->left);
		if (err <= 0)
			return err;
		return binop_can_transfer(ctx, left, right->right);
	case EXPR_MAPPING:
		return binop_can_transfer(ctx, left, right->left);
	default:
		return 0;
	}

	switch (left->op) {
	case OP_LSHIFT:
		if (mpz_scan1(right->value, 0) < mpz_get_uint32(left->right->value))
			return expr_binary_error(ctx->msgs, right, left,
						 "Comparison is always false");
		return 1;
	case OP_RSHIFT:
		if (ctx->ectx.len < right->len + mpz_get_uint32(left->right->value))
			ctx->ectx.len += mpz_get_uint32(left->right->value);
		return 1;
	case OP_XOR:
		return 1;
	default:
		return 0;
	}
}

static int binop_transfer_one(struct eval_ctx *ctx,
			      const struct expr *left, struct expr **right)
{
	int err;

	switch ((*right)->ops->type) {
	case EXPR_MAPPING:
		return binop_transfer_one(ctx, left, &(*right)->left);
	case EXPR_VALUE:
		break;
	case EXPR_SET_ELEM:
		return binop_transfer_one(ctx, left, &(*right)->key);
	case EXPR_RANGE:
		err = binop_transfer_one(ctx, left, &(*right)->left);
		if (err < 0)
			return err;
		return binop_transfer_one(ctx, left, &(*right)->right);
	default:
		return 0;
	}

	expr_get(*right);

	switch (left->op) {
	case OP_LSHIFT:
		(*right) = binop_expr_alloc(&(*right)->location, OP_RSHIFT,
					    *right, expr_get(left->right));
		break;
	case OP_RSHIFT:
		(*right) = binop_expr_alloc(&(*right)->location, OP_LSHIFT,
					    *right, expr_get(left->right));
		break;
	case OP_XOR:
		(*right) = binop_expr_alloc(&(*right)->location, OP_XOR,
					    *right, expr_get(left->right));
		break;
	default:
		BUG("invalid binary operation %u\n", left->op);
	}

	return expr_evaluate(ctx, right);
}

static void binop_transfer_handle_lhs(struct expr **expr)
{
	struct expr *tmp, *left = *expr;
	unsigned int shift;

	assert(left->ops->type == EXPR_BINOP);

	switch (left->op) {
	case OP_RSHIFT:
		/* Mask out the bits the shift would have masked out */
		shift = mpz_get_uint8(left->right->value);
		mpz_bitmask(left->right->value, left->left->len);
		mpz_lshift_ui(left->right->value, shift);
		left->op = OP_AND;
		break;
	case OP_LSHIFT:
	case OP_XOR:
		tmp = expr_get(left->left);
		tmp->dtype = left->dtype;
		expr_free(left);
		*expr = tmp;
		break;
	default:
		BUG("invalid binop operation %u", left->op);
	}
}

static int __binop_transfer(struct eval_ctx *ctx,
			    struct expr *left, struct expr **right)
{
	struct expr *i, *next;
	int err;

	assert(left->ops->type == EXPR_BINOP);

	switch ((*right)->ops->type) {
	case EXPR_VALUE:
		err = binop_can_transfer(ctx, left, *right);
		if (err <= 0)
			return err;
		if (binop_transfer_one(ctx, left, right) < 0)
			return -1;
		break;
	case EXPR_RANGE:
		err = binop_can_transfer(ctx, left, *right);
		if (err <= 0)
			return err;
		if (binop_transfer_one(ctx, left, right) < 0)
			return -1;
		break;
	case EXPR_SET:
		list_for_each_entry(i, &(*right)->expressions, list) {
			err = binop_can_transfer(ctx, left, i);
			if (err <= 0)
				return err;
		}
		list_for_each_entry_safe(i, next, &(*right)->expressions, list) {
			list_del(&i->list);
			err = binop_transfer_one(ctx, left, &i);
			list_add_tail(&i->list, &next->list);
			if (err < 0)
				return err;
		}
		break;
	case EXPR_SET_REF:
		return __binop_transfer(ctx, left, &(*right)->set->init);
	default:
		return 0;
	}

	return 1;
}

static int binop_transfer(struct eval_ctx *ctx, struct expr **expr)
{
	struct expr *left = (*expr)->left;
	int ret;

	if (left->ops->type != EXPR_BINOP)
		return 0;

	ret = __binop_transfer(ctx, left, &(*expr)->right);
	if (ret <= 0)
		return ret;

	binop_transfer_handle_lhs(&(*expr)->left);
	return 0;
}

static int expr_evaluate_relational(struct eval_ctx *ctx, struct expr **expr)
{
	struct expr *rel = *expr, *left, *right;

	if (expr_evaluate(ctx, &rel->left) < 0)
		return -1;
	left = rel->left;

	if (expr_evaluate(ctx, &rel->right) < 0)
		return -1;
	right = rel->right;

	if (!expr_is_constant(right))
		return expr_binary_error(ctx->msgs, right, rel,
					 "Right hand side of relational "
					 "expression (%s) must be constant",
					 expr_op_symbols[rel->op]);
	if (expr_is_constant(left))
		return expr_binary_error(ctx->msgs, left, right,
					 "Relational expression (%s) has "
					 "constant value",
					 expr_op_symbols[rel->op]);

	if (!datatype_equal(left->dtype, right->dtype))
		return expr_binary_error(ctx->msgs, right, left,
					 "datatype mismatch, expected %s, "
					 "expression has type %s",
					 left->dtype->desc,
					 right->dtype->desc);

	switch (rel->op) {
	case OP_EQ:
	case OP_IMPLICIT:
		/*
		 * Update protocol context for payload and meta iiftype
		 * equality expressions.
		 */
		if (expr_is_singleton(right))
			relational_expr_pctx_update(&ctx->pctx, rel);

		/* fall through */
	case OP_NEQ:
		switch (right->ops->type) {
		case EXPR_RANGE:
			if (byteorder_conversion(ctx, &rel->left, BYTEORDER_BIG_ENDIAN) < 0)
				return -1;
			if (byteorder_conversion(ctx, &right->left, BYTEORDER_BIG_ENDIAN) < 0)
				return -1;
			if (byteorder_conversion(ctx, &right->right, BYTEORDER_BIG_ENDIAN) < 0)
				return -1;
			break;
		case EXPR_PREFIX:
			if (byteorder_conversion(ctx, &right->prefix, left->byteorder) < 0)
				return -1;
			break;
		case EXPR_VALUE:
			if (byteorder_conversion(ctx, &rel->right, left->byteorder) < 0)
				return -1;
			break;
		case EXPR_SET:
			right = rel->right =
				implicit_set_declaration(ctx, "__set%d", left, right);
			/* fall through */
		case EXPR_SET_REF:
			/* Data for range lookups needs to be in big endian order */
			if (right->set->flags & NFT_SET_INTERVAL &&
			    byteorder_conversion(ctx, &rel->left, BYTEORDER_BIG_ENDIAN) < 0)
				return -1;
			break;
		default:
			BUG("invalid expression type %s\n", right->ops->name);
		}
		break;
	case OP_LT:
	case OP_GT:
	case OP_LTE:
	case OP_GTE:
		switch (left->ops->type) {
		case EXPR_CONCAT:
			return expr_binary_error(ctx->msgs, left, rel,
					"Relational expression (%s) is undefined "
				        "for %s expressions",
					expr_op_symbols[rel->op],
					left->ops->name);
		default:
			break;
		}

		if (!expr_is_singleton(right))
			return expr_binary_error(ctx->msgs, right, rel,
					"Relational expression (%s) is undefined "
				        "for %s expressions",
					expr_op_symbols[rel->op],
					right->ops->name);

		if (byteorder_conversion(ctx, &rel->left, BYTEORDER_BIG_ENDIAN) < 0)
			return -1;
		if (byteorder_conversion(ctx, &rel->right, BYTEORDER_BIG_ENDIAN) < 0)
			return -1;
		break;
	default:
		BUG("invalid relational operation %u\n", rel->op);
	}

	if (binop_transfer(ctx, expr) < 0)
		return -1;

	return 0;
}

static int expr_evaluate_fib(struct eval_ctx *ctx, struct expr **exprp)
{
	struct expr *expr = *exprp;

	if (expr->flags & EXPR_F_BOOLEAN) {
		expr->fib.flags |= NFTA_FIB_F_PRESENT;
		expr->dtype = &boolean_type;
	}
	return expr_evaluate_primary(ctx, exprp);
}

static int expr_evaluate_meta(struct eval_ctx *ctx, struct expr **exprp)
{
	struct expr *meta = *exprp;

	if (ctx->pctx.family != NFPROTO_INET &&
	    meta->flags & EXPR_F_PROTOCOL &&
	    meta->meta.key == NFT_META_NFPROTO)
		return expr_error(ctx->msgs, meta,
					  "meta nfproto is only useful in the inet family");

	return expr_evaluate_primary(ctx, exprp);
}

static int expr_evaluate_socket(struct eval_ctx *ctx, struct expr **expr)
{
	int maxval = 0;

	if((*expr)->socket.key == NFT_SOCKET_TRANSPARENT)
		maxval = 1;
	__expr_set_context(&ctx->ectx, (*expr)->dtype, (*expr)->byteorder,
			   (*expr)->len, maxval);
	return 0;
}

static int expr_evaluate_osf(struct eval_ctx *ctx, struct expr **expr)
{
	struct netlink_ctx nl_ctx = {
		.nft		= ctx->nft,
		.seqnum		= time(NULL),
	};

	nfnl_osf_load_fingerprints(&nl_ctx, 0);

	return expr_evaluate_primary(ctx, expr);
}

static int expr_evaluate_variable(struct eval_ctx *ctx, struct expr **exprp)
{
	struct expr *new = expr_clone((*exprp)->sym->expr);

	expr_free(*exprp);
	*exprp = new;

	return expr_evaluate(ctx, exprp);
}

static int expr_evaluate_xfrm(struct eval_ctx *ctx, struct expr **exprp)
{
	struct expr *expr = *exprp;

	switch (ctx->pctx.family) {
	case NFPROTO_IPV4:
	case NFPROTO_IPV6:
	case NFPROTO_INET:
		break;
	default:
		return expr_error(ctx->msgs, expr, "ipsec expression is only"
				  " valid in ip/ip6/inet tables");
	}

	return expr_evaluate_primary(ctx, exprp);
}

static int expr_evaluate(struct eval_ctx *ctx, struct expr **expr)
{
	if (ctx->nft->debug_mask & NFT_DEBUG_EVALUATION) {
		struct error_record *erec;
		erec = erec_create(EREC_INFORMATIONAL, &(*expr)->location,
				   "Evaluate %s", (*expr)->ops->name);
		erec_print(&ctx->nft->output, erec, ctx->nft->debug_mask);
		expr_print(*expr, &ctx->nft->output);
		nft_print(&ctx->nft->output, "\n\n");
		erec_destroy(erec);
	}

	switch ((*expr)->ops->type) {
	case EXPR_SYMBOL:
		return expr_evaluate_symbol(ctx, expr);
	case EXPR_VARIABLE:
		return expr_evaluate_variable(ctx, expr);
	case EXPR_SET_REF:
		return 0;
	case EXPR_VALUE:
		return expr_evaluate_value(ctx, expr);
	case EXPR_EXTHDR:
		return expr_evaluate_exthdr(ctx, expr);
	case EXPR_VERDICT:
		return expr_evaluate_primary(ctx, expr);
	case EXPR_META:
		return expr_evaluate_meta(ctx, expr);
	case EXPR_SOCKET:
		return expr_evaluate_socket(ctx, expr);
	case EXPR_OSF:
		return expr_evaluate_osf(ctx, expr);
	case EXPR_FIB:
		return expr_evaluate_fib(ctx, expr);
	case EXPR_PAYLOAD:
		return expr_evaluate_payload(ctx, expr);
	case EXPR_RT:
		return expr_evaluate_rt(ctx, expr);
	case EXPR_CT:
		return expr_evaluate_ct(ctx, expr);
	case EXPR_PREFIX:
		return expr_evaluate_prefix(ctx, expr);
	case EXPR_RANGE:
		return expr_evaluate_range(ctx, expr);
	case EXPR_UNARY:
		return expr_evaluate_unary(ctx, expr);
	case EXPR_BINOP:
		return expr_evaluate_binop(ctx, expr);
	case EXPR_CONCAT:
		return expr_evaluate_concat(ctx, expr, true);
	case EXPR_LIST:
		return expr_evaluate_list(ctx, expr);
	case EXPR_SET:
		return expr_evaluate_set(ctx, expr);
	case EXPR_SET_ELEM:
		return expr_evaluate_set_elem(ctx, expr);
	case EXPR_MAP:
		return expr_evaluate_map(ctx, expr);
	case EXPR_MAPPING:
		return expr_evaluate_mapping(ctx, expr);
	case EXPR_RELATIONAL:
		return expr_evaluate_relational(ctx, expr);
	case EXPR_NUMGEN:
		return expr_evaluate_numgen(ctx, expr);
	case EXPR_HASH:
		return expr_evaluate_hash(ctx, expr);
	case EXPR_XFRM:
		return expr_evaluate_xfrm(ctx, expr);
	default:
		BUG("unknown expression type %s\n", (*expr)->ops->name);
	}
}

static int stmt_evaluate_expr(struct eval_ctx *ctx, struct stmt *stmt)
{
	memset(&ctx->ectx, 0, sizeof(ctx->ectx));
	return expr_evaluate(ctx, &stmt->expr);
}

static int stmt_evaluate_arg(struct eval_ctx *ctx, struct stmt *stmt,
			     const struct datatype *dtype, unsigned int len,
			     enum byteorder byteorder, struct expr **expr)
{
	__expr_set_context(&ctx->ectx, dtype, byteorder, len, 0);
	if (expr_evaluate(ctx, expr) < 0)
		return -1;

	if ((*expr)->ops->type == EXPR_PAYLOAD &&
	    (*expr)->dtype->type == TYPE_INTEGER &&
	    ((*expr)->dtype->type != datatype_basetype(dtype)->type ||
	     (*expr)->len != len))
		return stmt_binary_error(ctx, *expr, stmt,
					 "datatype mismatch: expected %s, "
					 "expression has type %s with length %d",
					 dtype->desc, (*expr)->dtype->desc,
					 (*expr)->len);
	else if ((*expr)->dtype->type != TYPE_INTEGER &&
		 !datatype_equal((*expr)->dtype, dtype))
		return stmt_binary_error(ctx, *expr, stmt,
					 "datatype mismatch: expected %s, "
					 "expression has type %s",
					 dtype->desc, (*expr)->dtype->desc);

	/* we are setting a value, we can't use a set */
	switch ((*expr)->ops->type) {
	case EXPR_SET:
		return stmt_binary_error(ctx, *expr, stmt,
					 "you cannot use a set here, unknown "
					 "value to use");
	case EXPR_SET_REF:
		return stmt_binary_error(ctx, *expr, stmt,
					 "you cannot reference a set here, "
					 "unknown value to use");
	case EXPR_RT:
		return byteorder_conversion(ctx, expr, byteorder);
	default:
		break;
	}

	return 0;
}

static int stmt_evaluate_verdict(struct eval_ctx *ctx, struct stmt *stmt)
{
	if (stmt_evaluate_arg(ctx, stmt, &verdict_type, 0, 0, &stmt->expr) < 0)
		return -1;

	switch (stmt->expr->ops->type) {
	case EXPR_VERDICT:
		if (stmt->expr->verdict != NFT_CONTINUE)
			stmt->flags |= STMT_F_TERMINAL;
		break;
	case EXPR_MAP:
		break;
	default:
		BUG("invalid verdict expression %s\n", stmt->expr->ops->name);
	}
	return 0;
}

static bool stmt_evaluate_payload_need_csum(const struct expr *payload)
{
	const struct proto_desc *desc;

	desc = payload->payload.desc;

	return desc && desc->checksum_key;
}

static int stmt_evaluate_exthdr(struct eval_ctx *ctx, struct stmt *stmt)
{
	struct expr *exthdr;

	if (__expr_evaluate_exthdr(ctx, &stmt->exthdr.expr) < 0)
		return -1;

	exthdr = stmt->exthdr.expr;
	return stmt_evaluate_arg(ctx, stmt, exthdr->dtype, exthdr->len,
				 BYTEORDER_BIG_ENDIAN,
				 &stmt->exthdr.val);
}

static int stmt_evaluate_payload(struct eval_ctx *ctx, struct stmt *stmt)
{
	struct expr *binop, *mask, *and, *payload_bytes;
	unsigned int masklen, extra_len = 0;
	unsigned int payload_byte_size, payload_byte_offset;
	uint8_t shift_imm, data[NFT_REG_SIZE];
	struct expr *payload;
	mpz_t bitmask, ff;
	bool need_csum;

	if (__expr_evaluate_payload(ctx, stmt->payload.expr) < 0)
		return -1;

	payload = stmt->payload.expr;
	if (stmt_evaluate_arg(ctx, stmt, payload->dtype, payload->len,
			      payload->byteorder, &stmt->payload.val) < 0)
		return -1;

	need_csum = stmt_evaluate_payload_need_csum(payload);

	if (!payload_needs_adjustment(payload)) {

		/* We still need to munge the payload in case we have to
		 * update checksum and the length is not even because
		 * kernel checksum functions cannot deal with odd lengths.
		 */
		if (!need_csum || ((payload->len / BITS_PER_BYTE) & 1) == 0)
			return 0;
	}

	payload_byte_offset = payload->payload.offset / BITS_PER_BYTE;

	shift_imm = expr_offset_shift(payload, payload->payload.offset,
				      &extra_len);
	payload_byte_size = round_up(payload->len, BITS_PER_BYTE) / BITS_PER_BYTE;
	payload_byte_size += (extra_len / BITS_PER_BYTE);

	if (need_csum && payload_byte_size & 1) {
		payload_byte_size++;

		if (payload_byte_offset & 1) { /* prefer 16bit aligned fetch */
			payload_byte_offset--;
			assert(payload->payload.offset >= BITS_PER_BYTE);
		} else {
			shift_imm += BITS_PER_BYTE;
		}
	}

	if (shift_imm) {
		struct expr *off;

		off = constant_expr_alloc(&payload->location,
					  expr_basetype(payload),
					  BYTEORDER_HOST_ENDIAN,
					  sizeof(shift_imm), &shift_imm);

		binop = binop_expr_alloc(&payload->location, OP_LSHIFT,
					 stmt->payload.val, off);
		binop->dtype		= payload->dtype;
		binop->byteorder	= payload->byteorder;

		stmt->payload.val = binop;
	}


	masklen = payload_byte_size * BITS_PER_BYTE;
	mpz_init_bitmask(ff, masklen);

	mpz_init2(bitmask, masklen);
	mpz_bitmask(bitmask, payload->len);
	mpz_lshift_ui(bitmask, shift_imm);

	mpz_xor(bitmask, ff, bitmask);
	mpz_clear(ff);

	assert(sizeof(data) * BITS_PER_BYTE >= masklen);
	mpz_export_data(data, bitmask, BYTEORDER_HOST_ENDIAN, sizeof(data));
	mask = constant_expr_alloc(&payload->location, expr_basetype(payload),
				   BYTEORDER_HOST_ENDIAN, masklen, data);

	payload_bytes = payload_expr_alloc(&payload->location, NULL, 0);
	payload_init_raw(payload_bytes, payload->payload.base,
			 payload_byte_offset * BITS_PER_BYTE,
			 payload_byte_size * BITS_PER_BYTE);

	payload_bytes->payload.desc	 = payload->payload.desc;
	payload_bytes->byteorder	 = payload->byteorder;

	payload->len = payload_bytes->len;
	payload->payload.offset = payload_bytes->payload.offset;

	and = binop_expr_alloc(&payload->location, OP_AND, payload_bytes, mask);

	and->dtype		 = payload_bytes->dtype;
	and->byteorder		 = payload_bytes->byteorder;
	and->len		 = payload_bytes->len;

	binop = binop_expr_alloc(&payload->location, OP_XOR, and,
				 stmt->payload.val);
	binop->dtype		= payload->dtype;
	binop->byteorder	= payload->byteorder;
	binop->len		= mask->len;
	stmt->payload.val = binop;

	return expr_evaluate(ctx, &stmt->payload.val);
}

static int stmt_evaluate_meter(struct eval_ctx *ctx, struct stmt *stmt)
{
	struct expr *key, *set, *setref;

	expr_set_context(&ctx->ectx, NULL, 0);
	if (expr_evaluate(ctx, &stmt->meter.key) < 0)
		return -1;
	if (expr_is_constant(stmt->meter.key))
		return expr_error(ctx->msgs, stmt->meter.key,
				  "Meter key expression can not be constant");
	if (stmt->meter.key->comment)
		return expr_error(ctx->msgs, stmt->meter.key,
				  "Meter key expression can not contain comments");

	/* Declare an empty set */
	key = stmt->meter.key;
	set = set_expr_alloc(&key->location, NULL);
	set->set_flags |= NFT_SET_EVAL;
	if (key->timeout)
		set->set_flags |= NFT_SET_TIMEOUT;

	setref = implicit_set_declaration(ctx, stmt->meter.name, key, set);

	setref->set->desc.size = stmt->meter.size;
	stmt->meter.set = setref;

	if (stmt_evaluate(ctx, stmt->meter.stmt) < 0)
		return -1;
	if (!(stmt->meter.stmt->flags & STMT_F_STATEFUL))
		return stmt_binary_error(ctx, stmt->meter.stmt, stmt,
					 "meter statement must be stateful");

	return 0;
}

static int stmt_evaluate_meta(struct eval_ctx *ctx, struct stmt *stmt)
{
	return stmt_evaluate_arg(ctx, stmt,
				 stmt->meta.tmpl->dtype,
				 stmt->meta.tmpl->len,
				 stmt->meta.tmpl->byteorder,
				 &stmt->meta.expr);
}

static int stmt_evaluate_ct(struct eval_ctx *ctx, struct stmt *stmt)
{
	return stmt_evaluate_arg(ctx, stmt,
				 stmt->ct.tmpl->dtype,
				 stmt->ct.tmpl->len,
				 stmt->ct.tmpl->byteorder,
				 &stmt->ct.expr);
}

static int reject_payload_gen_dependency_tcp(struct eval_ctx *ctx,
					     struct stmt *stmt,
					     struct expr **payload)
{
	const struct proto_desc *desc;

	desc = ctx->pctx.protocol[PROTO_BASE_TRANSPORT_HDR].desc;
	if (desc != NULL)
		return 0;
	*payload = payload_expr_alloc(&stmt->location, &proto_tcp,
				      TCPHDR_UNSPEC);
	return 1;
}

static int reject_payload_gen_dependency_family(struct eval_ctx *ctx,
						struct stmt *stmt,
						struct expr **payload)
{
	const struct proto_desc *base;

	base = ctx->pctx.protocol[PROTO_BASE_NETWORK_HDR].desc;
	if (base != NULL)
		return 0;

	if (stmt->reject.icmp_code < 0)
		return stmt_error(ctx, stmt, "missing icmp error type");

	/* Generate a network dependency */
	switch (stmt->reject.family) {
	case NFPROTO_IPV4:
		*payload = payload_expr_alloc(&stmt->location, &proto_ip,
					     IPHDR_PROTOCOL);
		break;
	case NFPROTO_IPV6:
		*payload = payload_expr_alloc(&stmt->location, &proto_ip6,
					     IP6HDR_NEXTHDR);
		break;
	default:
		BUG("unknown reject family");
	}
	return 1;
}

static int stmt_reject_gen_dependency(struct eval_ctx *ctx, struct stmt *stmt,
				      struct expr *expr)
{
	struct expr *payload = NULL;
	struct stmt *nstmt;
	int ret;

	switch (stmt->reject.type) {
	case NFT_REJECT_TCP_RST:
		ret = reject_payload_gen_dependency_tcp(ctx, stmt, &payload);
		break;
	case NFT_REJECT_ICMP_UNREACH:
		ret = reject_payload_gen_dependency_family(ctx, stmt, &payload);
		break;
	default:
		BUG("cannot generate reject dependency for type %d",
		    stmt->reject.type);
	}
	if (ret <= 0)
		return ret;

	if (payload_gen_dependency(ctx, payload, &nstmt) < 0) {
		ret = -1;
		goto out;
	}

	/*
	 * Unlike payload deps this adds the dependency at the beginning, i.e.
	 * log ... reject with tcp-reset
	 * turns into
	 * meta l4proto tcp log ... reject with tcp-reset
	 *
	 * Otherwise we'd log things that won't be rejected.
	 */
	list_add(&nstmt->list, &ctx->rule->stmts);
out:
	xfree(payload);
	return ret;
}

static int stmt_evaluate_reject_inet_family(struct eval_ctx *ctx,
					    struct stmt *stmt,
					    const struct proto_desc *desc)
{
	const struct proto_desc *base;
	int protocol;

	switch (stmt->reject.type) {
	case NFT_REJECT_TCP_RST:
		break;
	case NFT_REJECT_ICMPX_UNREACH:
		break;
	case NFT_REJECT_ICMP_UNREACH:
		base = ctx->pctx.protocol[PROTO_BASE_LL_HDR].desc;
		protocol = proto_find_num(base, desc);
		switch (protocol) {
		case NFPROTO_IPV4:
			if (stmt->reject.family == NFPROTO_IPV4)
				break;
			return stmt_binary_error(ctx, stmt->reject.expr,
				  &ctx->pctx.protocol[PROTO_BASE_NETWORK_HDR],
				  "conflicting protocols specified: ip vs ip6");
		case NFPROTO_IPV6:
			if (stmt->reject.family == NFPROTO_IPV6)
				break;
			return stmt_binary_error(ctx, stmt->reject.expr,
				  &ctx->pctx.protocol[PROTO_BASE_NETWORK_HDR],
				  "conflicting protocols specified: ip vs ip6");
		default:
			BUG("unsupported family");
		}
		break;
	}

	return 0;
}

static int stmt_evaluate_reject_inet(struct eval_ctx *ctx, struct stmt *stmt,
				     struct expr *expr)
{
	const struct proto_desc *desc;

	desc = ctx->pctx.protocol[PROTO_BASE_NETWORK_HDR].desc;
	if (desc != NULL &&
	    stmt_evaluate_reject_inet_family(ctx, stmt, desc) < 0)
		return -1;
	if (stmt->reject.type == NFT_REJECT_ICMPX_UNREACH)
		return 0;
	if (stmt_reject_gen_dependency(ctx, stmt, expr) < 0)
		return -1;
	return 0;
}

static int stmt_evaluate_reject_bridge_family(struct eval_ctx *ctx,
					      struct stmt *stmt,
					      const struct proto_desc *desc)
{
	const struct proto_desc *base;
	int protocol;

	switch (stmt->reject.type) {
	case NFT_REJECT_ICMPX_UNREACH:
	case NFT_REJECT_TCP_RST:
		base = ctx->pctx.protocol[PROTO_BASE_LL_HDR].desc;
		protocol = proto_find_num(base, desc);
		switch (protocol) {
		case __constant_htons(ETH_P_IP):
		case __constant_htons(ETH_P_IPV6):
			break;
		default:
			return stmt_binary_error(ctx, stmt,
				    &ctx->pctx.protocol[PROTO_BASE_NETWORK_HDR],
				    "cannot reject this network family");
		}
		break;
	case NFT_REJECT_ICMP_UNREACH:
		base = ctx->pctx.protocol[PROTO_BASE_LL_HDR].desc;
		protocol = proto_find_num(base, desc);
		switch (protocol) {
		case __constant_htons(ETH_P_IP):
			if (NFPROTO_IPV4 == stmt->reject.family)
				break;
			return stmt_binary_error(ctx, stmt->reject.expr,
				  &ctx->pctx.protocol[PROTO_BASE_NETWORK_HDR],
				  "conflicting protocols specified: ip vs ip6");
		case __constant_htons(ETH_P_IPV6):
			if (NFPROTO_IPV6 == stmt->reject.family)
				break;
			return stmt_binary_error(ctx, stmt->reject.expr,
				  &ctx->pctx.protocol[PROTO_BASE_NETWORK_HDR],
				  "conflicting protocols specified: ip vs ip6");
		default:
			return stmt_binary_error(ctx, stmt,
				    &ctx->pctx.protocol[PROTO_BASE_NETWORK_HDR],
				    "cannot reject this network family");
		}
		break;
	}

	return 0;
}

static int stmt_evaluate_reject_bridge(struct eval_ctx *ctx, struct stmt *stmt,
				       struct expr *expr)
{
	const struct proto_desc *desc;

	desc = ctx->pctx.protocol[PROTO_BASE_LL_HDR].desc;
	if (desc != &proto_eth)
		return stmt_binary_error(ctx,
					 &ctx->pctx.protocol[PROTO_BASE_LL_HDR],
					 stmt, "unsupported link layer protocol");

	desc = ctx->pctx.protocol[PROTO_BASE_NETWORK_HDR].desc;
	if (desc != NULL &&
	    stmt_evaluate_reject_bridge_family(ctx, stmt, desc) < 0)
		return -1;
	if (stmt->reject.type == NFT_REJECT_ICMPX_UNREACH)
		return 0;
	if (stmt_reject_gen_dependency(ctx, stmt, expr) < 0)
		return -1;
	return 0;
}

static int stmt_evaluate_reject_family(struct eval_ctx *ctx, struct stmt *stmt,
				       struct expr *expr)
{
	switch (ctx->pctx.family) {
	case NFPROTO_ARP:
		return stmt_error(ctx, stmt, "cannot use reject with arp");
	case NFPROTO_IPV4:
	case NFPROTO_IPV6:
		switch (stmt->reject.type) {
		case NFT_REJECT_TCP_RST:
			if (stmt_reject_gen_dependency(ctx, stmt, expr) < 0)
				return -1;
			break;
		case NFT_REJECT_ICMPX_UNREACH:
			return stmt_binary_error(ctx, stmt->reject.expr, stmt,
				   "abstracted ICMP unreachable not supported");
		case NFT_REJECT_ICMP_UNREACH:
			if (stmt->reject.family == ctx->pctx.family)
				break;
			return stmt_binary_error(ctx, stmt->reject.expr, stmt,
				  "conflicting protocols specified: ip vs ip6");
		}
		break;
	case NFPROTO_BRIDGE:
		if (stmt_evaluate_reject_bridge(ctx, stmt, expr) < 0)
			return -1;
		break;
	case NFPROTO_INET:
		if (stmt_evaluate_reject_inet(ctx, stmt, expr) < 0)
			return -1;
		break;
	}

	stmt->flags |= STMT_F_TERMINAL;
	return 0;
}

static int stmt_evaluate_reject_default(struct eval_ctx *ctx,
					  struct stmt *stmt)
{
	int protocol;
	const struct proto_desc *desc, *base;

	switch (ctx->pctx.family) {
	case NFPROTO_IPV4:
	case NFPROTO_IPV6:
		stmt->reject.type = NFT_REJECT_ICMP_UNREACH;
		stmt->reject.family = ctx->pctx.family;
		if (ctx->pctx.family == NFPROTO_IPV4)
			stmt->reject.icmp_code = ICMP_PORT_UNREACH;
		else
			stmt->reject.icmp_code = ICMP6_DST_UNREACH_NOPORT;
		break;
	case NFPROTO_INET:
		desc = ctx->pctx.protocol[PROTO_BASE_NETWORK_HDR].desc;
		if (desc == NULL) {
			stmt->reject.type = NFT_REJECT_ICMPX_UNREACH;
			stmt->reject.icmp_code = NFT_REJECT_ICMPX_PORT_UNREACH;
			break;
		}
		stmt->reject.type = NFT_REJECT_ICMP_UNREACH;
		base = ctx->pctx.protocol[PROTO_BASE_LL_HDR].desc;
		protocol = proto_find_num(base, desc);
		switch (protocol) {
		case NFPROTO_IPV4:
			stmt->reject.family = NFPROTO_IPV4;
			stmt->reject.icmp_code = ICMP_PORT_UNREACH;
			break;
		case NFPROTO_IPV6:
			stmt->reject.family = NFPROTO_IPV6;
			stmt->reject.icmp_code = ICMP6_DST_UNREACH_NOPORT;
			break;
		}
		break;
	case NFPROTO_BRIDGE:
		desc = ctx->pctx.protocol[PROTO_BASE_NETWORK_HDR].desc;
		if (desc == NULL) {
			stmt->reject.type = NFT_REJECT_ICMPX_UNREACH;
			stmt->reject.icmp_code = NFT_REJECT_ICMPX_PORT_UNREACH;
			break;
		}
		stmt->reject.type = NFT_REJECT_ICMP_UNREACH;
		base = ctx->pctx.protocol[PROTO_BASE_LL_HDR].desc;
		protocol = proto_find_num(base, desc);
		switch (protocol) {
		case __constant_htons(ETH_P_IP):
			stmt->reject.family = NFPROTO_IPV4;
			stmt->reject.icmp_code = ICMP_PORT_UNREACH;
			break;
		case __constant_htons(ETH_P_IPV6):
			stmt->reject.family = NFPROTO_IPV6;
			stmt->reject.icmp_code = ICMP6_DST_UNREACH_NOPORT;
			break;
		}
		break;
	}
	return 0;
}

static int stmt_evaluate_reject_icmp(struct eval_ctx *ctx, struct stmt *stmt)
{
	struct error_record *erec;
	struct expr *code;

	erec = symbol_parse(stmt->reject.expr, &code);
	if (erec != NULL) {
		erec_queue(erec, ctx->msgs);
		return -1;
	}
	stmt->reject.icmp_code = mpz_get_uint8(code->value);
	return 0;
}

static int stmt_evaluate_reset(struct eval_ctx *ctx, struct stmt *stmt)
{
	int protonum;
	const struct proto_desc *desc, *base;
	struct proto_ctx *pctx = &ctx->pctx;

	desc = pctx->protocol[PROTO_BASE_TRANSPORT_HDR].desc;
	if (desc == NULL)
		return 0;

	base = pctx->protocol[PROTO_BASE_NETWORK_HDR].desc;
	if (base == NULL)
		base = &proto_inet_service;

	protonum = proto_find_num(base, desc);
	switch (protonum) {
	case IPPROTO_TCP:
		break;
	default:
		if (stmt->reject.type == NFT_REJECT_TCP_RST) {
			return stmt_binary_error(ctx, stmt,
				 &ctx->pctx.protocol[PROTO_BASE_TRANSPORT_HDR],
				 "you cannot use tcp reset with this protocol");
		}
		break;
	}
	return 0;
}

static int stmt_evaluate_reject(struct eval_ctx *ctx, struct stmt *stmt)
{
	struct expr *expr = ctx->cmd->expr;

	if (stmt->reject.icmp_code < 0) {
		if (stmt_evaluate_reject_default(ctx, stmt) < 0)
			return -1;
	} else if (stmt->reject.expr != NULL) {
		if (stmt_evaluate_reject_icmp(ctx, stmt) < 0)
			return -1;
	} else {
		if (stmt_evaluate_reset(ctx, stmt) < 0)
			return -1;
	}

	return stmt_evaluate_reject_family(ctx, stmt, expr);
}

static int nat_evaluate_family(struct eval_ctx *ctx, struct stmt *stmt)
{
	switch (ctx->pctx.family) {
	case NFPROTO_IPV4:
	case NFPROTO_IPV6:
		return 0;
	default:
		return stmt_error(ctx, stmt,
				  "NAT is only supported for IPv4/IPv6");
	}
}

static int evaluate_addr(struct eval_ctx *ctx, struct stmt *stmt,
			     struct expr **expr)
{
	struct proto_ctx *pctx = &ctx->pctx;
	const struct datatype *dtype;
	unsigned int len;

	if (pctx->family == NFPROTO_IPV4) {
		dtype = &ipaddr_type;
		len   = 4 * BITS_PER_BYTE;
	} else {
		dtype = &ip6addr_type;
		len   = 16 * BITS_PER_BYTE;
	}

	return stmt_evaluate_arg(ctx, stmt, dtype, len, BYTEORDER_BIG_ENDIAN,
				 expr);
}

static int nat_evaluate_transport(struct eval_ctx *ctx, struct stmt *stmt,
				  struct expr **expr)
{
	struct proto_ctx *pctx = &ctx->pctx;

	if (pctx->protocol[PROTO_BASE_TRANSPORT_HDR].desc == NULL)
		return stmt_binary_error(ctx, *expr, stmt,
					 "transport protocol mapping is only "
					 "valid after transport protocol match");

	return stmt_evaluate_arg(ctx, stmt,
				 &inet_service_type, 2 * BITS_PER_BYTE,
				 BYTEORDER_BIG_ENDIAN, expr);
}

static int stmt_evaluate_nat(struct eval_ctx *ctx, struct stmt *stmt)
{
	int err;

	err = nat_evaluate_family(ctx, stmt);
	if (err < 0)
		return err;

	if (stmt->nat.addr != NULL) {
		err = evaluate_addr(ctx, stmt, &stmt->nat.addr);
		if (err < 0)
			return err;
	}
	if (stmt->nat.proto != NULL) {
		err = nat_evaluate_transport(ctx, stmt, &stmt->nat.proto);
		if (err < 0)
			return err;
	}

	stmt->flags |= STMT_F_TERMINAL;
	return 0;
}

static int stmt_evaluate_tproxy(struct eval_ctx *ctx, struct stmt *stmt)
{
	const struct proto_desc *nproto;
	const struct datatype *dtype;
	int err, len;

	switch (ctx->pctx.family) {
	case NFPROTO_IPV4:
	case NFPROTO_IPV6: /* fallthrough */
		if (stmt->tproxy.family == NFPROTO_UNSPEC)
			stmt->tproxy.family = ctx->pctx.family;
		break;
	case NFPROTO_INET:
		break;
	default:
		return stmt_error(ctx, stmt,
				  "tproxy is only supported for IPv4/IPv6/INET");
	}

	if (ctx->pctx.protocol[PROTO_BASE_TRANSPORT_HDR].desc == NULL)
		return stmt_error(ctx, stmt, "Transparent proxy support requires"
					     " transport protocol match");

	if (!stmt->tproxy.addr && !stmt->tproxy.port)
		return stmt_error(ctx, stmt, "Either address or port must be specified!");

	nproto = ctx->pctx.protocol[PROTO_BASE_NETWORK_HDR].desc;
	if ((nproto == &proto_ip && stmt->tproxy.family != NFPROTO_IPV4) ||
	    (nproto == &proto_ip6 && stmt->tproxy.family != NFPROTO_IPV6))
		/* this prevents us from rules like
		 * ip protocol tcp tproxy ip6 to [dead::beef]
		 */
		return stmt_error(ctx, stmt,
				  "Conflicting network layer protocols.");

	if (stmt->tproxy.addr != NULL) {
		if (stmt->tproxy.addr->ops->type == EXPR_RANGE)
			return stmt_error(ctx, stmt, "Address ranges are not supported for tproxy.");
		if (ctx->pctx.family == NFPROTO_INET) {
			switch (stmt->tproxy.family) {
			case NFPROTO_IPV4:
				dtype = &ipaddr_type;
				len   = 4 * BITS_PER_BYTE;
				break;
			case NFPROTO_IPV6:
				dtype = &ip6addr_type;
				len   = 16 * BITS_PER_BYTE;
				break;
			default:
				return stmt_error(ctx, stmt,
						  "Family must be specified in tproxy statement with address for inet tables.");
			}
			err = stmt_evaluate_arg(ctx, stmt, dtype, len,
						BYTEORDER_BIG_ENDIAN,
						&stmt->tproxy.addr);
			if (err < 0)
				return err;
		}
		else {
			err = evaluate_addr(ctx, stmt, &stmt->tproxy.addr);
			if (err < 0)
				return err;
		}
	}

	if (stmt->tproxy.port != NULL) {
		if (stmt->tproxy.port->ops->type == EXPR_RANGE)
			return stmt_error(ctx, stmt, "Port ranges are not supported for tproxy.");
		err = nat_evaluate_transport(ctx, stmt, &stmt->tproxy.port);
		if (err < 0)
			return err;
	}

	return 0;
}

static int stmt_evaluate_dup(struct eval_ctx *ctx, struct stmt *stmt)
{
	int err;

	switch (ctx->pctx.family) {
	case NFPROTO_IPV4:
	case NFPROTO_IPV6:
		if (stmt->dup.to == NULL)
			return stmt_error(ctx, stmt,
					  "missing destination address");
		err = evaluate_addr(ctx, stmt, &stmt->dup.to);
		if (err < 0)
			return err;

		if (stmt->dup.dev != NULL) {
			err = stmt_evaluate_arg(ctx, stmt, &ifindex_type,
						sizeof(uint32_t) * BITS_PER_BYTE,
						BYTEORDER_HOST_ENDIAN,
						&stmt->dup.dev);
			if (err < 0)
				return err;
		}
		break;
	case NFPROTO_NETDEV:
		if (stmt->dup.to == NULL)
			return stmt_error(ctx, stmt,
					  "missing destination interface");
		if (stmt->dup.dev != NULL)
			return stmt_error(ctx, stmt, "cannot specify device");

		err = stmt_evaluate_arg(ctx, stmt, &ifindex_type,
					sizeof(uint32_t) * BITS_PER_BYTE,
					BYTEORDER_HOST_ENDIAN, &stmt->dup.to);
		if (err < 0)
			return err;
		break;
	default:
		return stmt_error(ctx, stmt, "unsupported family");
	}
	return 0;
}

static int stmt_evaluate_fwd(struct eval_ctx *ctx, struct stmt *stmt)
{
	const struct datatype *dtype;
	int err, len;

	switch (ctx->pctx.family) {
	case NFPROTO_NETDEV:
		if (stmt->fwd.dev == NULL)
			return stmt_error(ctx, stmt,
					  "missing destination interface");

		err = stmt_evaluate_arg(ctx, stmt, &ifindex_type,
					sizeof(uint32_t) * BITS_PER_BYTE,
					BYTEORDER_HOST_ENDIAN, &stmt->fwd.dev);
		if (err < 0)
			return err;

		if (stmt->fwd.addr != NULL) {
			switch (stmt->fwd.family) {
			case NFPROTO_IPV4:
				dtype = &ipaddr_type;
				len   = 4 * BITS_PER_BYTE;
				break;
			case NFPROTO_IPV6:
				dtype = &ip6addr_type;
				len   = 16 * BITS_PER_BYTE;
				break;
			default:
				return stmt_error(ctx, stmt, "missing family");
			}
			err = stmt_evaluate_arg(ctx, stmt, dtype, len,
						BYTEORDER_BIG_ENDIAN,
						&stmt->fwd.addr);
			if (err < 0)
				return err;
		}
		break;
	default:
		return stmt_error(ctx, stmt, "unsupported family");
	}
	return 0;
}

static int stmt_evaluate_queue(struct eval_ctx *ctx, struct stmt *stmt)
{
	if (stmt->queue.queue != NULL) {
		if (stmt_evaluate_arg(ctx, stmt, &integer_type, 16,
				      BYTEORDER_HOST_ENDIAN,
				      &stmt->queue.queue) < 0)
			return -1;
		if (!expr_is_constant(stmt->queue.queue))
			return expr_error(ctx->msgs, stmt->queue.queue,
					  "queue number is not constant");
		if (stmt->queue.queue->ops->type != EXPR_RANGE &&
		    (stmt->queue.flags & NFT_QUEUE_FLAG_CPU_FANOUT))
			return expr_error(ctx->msgs, stmt->queue.queue,
					  "fanout requires a range to be "
					  "specified");
	}
	return 0;
}

static int stmt_evaluate_log(struct eval_ctx *ctx, struct stmt *stmt)
{
	if (stmt->log.flags & (STMT_LOG_GROUP | STMT_LOG_SNAPLEN |
			       STMT_LOG_QTHRESHOLD)) {
		if (stmt->log.flags & STMT_LOG_LEVEL)
			return stmt_error(ctx, stmt,
				  "level and group are mutually exclusive");
		if (stmt->log.logflags)
			return stmt_error(ctx, stmt,
				  "flags and group are mutually exclusive");
	}
	if (stmt->log.level == LOGLEVEL_AUDIT &&
	    (stmt->log.flags & ~STMT_LOG_LEVEL || stmt->log.logflags))
		return stmt_error(ctx, stmt,
				  "log level audit doesn't support any further options");
	return 0;
}

static int stmt_evaluate_set(struct eval_ctx *ctx, struct stmt *stmt)
{
	expr_set_context(&ctx->ectx, NULL, 0);
	if (expr_evaluate(ctx, &stmt->set.set) < 0)
		return -1;
	if (stmt->set.set->ops->type != EXPR_SET_REF)
		return expr_error(ctx->msgs, stmt->set.set,
				  "Expression does not refer to a set");

	if (stmt_evaluate_arg(ctx, stmt,
			      stmt->set.set->set->key->dtype,
			      stmt->set.set->set->key->len,
			      stmt->set.set->set->key->byteorder,
			      &stmt->set.key->key) < 0)
		return -1;
	if (expr_is_constant(stmt->set.key))
		return expr_error(ctx->msgs, stmt->set.key,
				  "Key expression can not be constant");
	if (stmt->set.key->comment != NULL)
		return expr_error(ctx->msgs, stmt->set.key,
				  "Key expression comments are not supported");
	if (stmt->set.stmt) {
		if (stmt_evaluate(ctx, stmt->set.stmt) < 0)
			return -1;
		if (!(stmt->set.stmt->flags & STMT_F_STATEFUL))
			return stmt_binary_error(ctx, stmt->set.stmt, stmt,
						 "meter statement must be stateful");
	}

	return 0;
}

static int stmt_evaluate_map(struct eval_ctx *ctx, struct stmt *stmt)
{
	expr_set_context(&ctx->ectx, NULL, 0);
	if (expr_evaluate(ctx, &stmt->map.set) < 0)
		return -1;
	if (stmt->map.set->ops->type != EXPR_SET_REF)
		return expr_error(ctx->msgs, stmt->map.set,
				  "Expression does not refer to a set");

	if (stmt_evaluate_arg(ctx, stmt,
			      stmt->map.set->set->key->dtype,
			      stmt->map.set->set->key->len,
			      stmt->map.set->set->key->byteorder,
			      &stmt->map.key->key) < 0)
		return -1;
	if (expr_is_constant(stmt->map.key))
		return expr_error(ctx->msgs, stmt->map.key,
				  "Key expression can not be constant");
	if (stmt->map.key->comment != NULL)
		return expr_error(ctx->msgs, stmt->map.key,
				  "Key expression comments are not supported");

	if (stmt_evaluate_arg(ctx, stmt,
			      stmt->map.set->set->datatype,
			      stmt->map.set->set->datalen,
			      stmt->map.set->set->datatype->byteorder,
			      &stmt->map.data->key) < 0)
		return -1;
	if (expr_is_constant(stmt->map.data))
		return expr_error(ctx->msgs, stmt->map.data,
				  "Data expression can not be constant");
	if (stmt->map.data->comment != NULL)
		return expr_error(ctx->msgs, stmt->map.data,
				  "Data expression comments are not supported");

	if (stmt->map.stmt) {
		if (stmt_evaluate(ctx, stmt->map.stmt) < 0)
			return -1;
		if (!(stmt->map.stmt->flags & STMT_F_STATEFUL))
			return stmt_binary_error(ctx, stmt->map.stmt, stmt,
						 "meter statement must be stateful");
	}

	return 0;
}

static int stmt_evaluate_objref_map(struct eval_ctx *ctx, struct stmt *stmt)
{
	struct expr *map = stmt->objref.expr;
	struct expr *mappings;
	struct expr *key;

	expr_set_context(&ctx->ectx, NULL, 0);
	if (expr_evaluate(ctx, &map->map) < 0)
		return -1;
	if (expr_is_constant(map->map))
		return expr_error(ctx->msgs, map->map,
				  "Map expression can not be constant");

	mappings = map->mappings;
	mappings->set_flags |= NFT_SET_OBJECT;

	switch (map->mappings->ops->type) {
	case EXPR_SET:
		key = constant_expr_alloc(&stmt->location,
					  ctx->ectx.dtype,
					  ctx->ectx.byteorder,
					  ctx->ectx.len, NULL);

		mappings = implicit_set_declaration(ctx, "__objmap%d",
						    key, mappings);
		mappings->set->datatype = &string_type;
		mappings->set->datalen  = NFT_OBJ_MAXNAMELEN * BITS_PER_BYTE;
		mappings->set->objtype  = stmt->objref.type;

		map->mappings = mappings;

		ctx->set = mappings->set;
		if (expr_evaluate(ctx, &map->mappings->set->init) < 0)
			return -1;
		ctx->set = NULL;

		map->mappings->set->flags |=
			map->mappings->set->init->set_flags;
		/* fall through */
	case EXPR_SYMBOL:
		if (expr_evaluate(ctx, &map->mappings) < 0)
			return -1;
		if (map->mappings->ops->type != EXPR_SET_REF)
			return expr_error(ctx->msgs, map->mappings,
					  "Expression is not a map");
		if (!(map->mappings->set->flags & NFT_SET_OBJECT))
			return expr_error(ctx->msgs, map->mappings,
					  "Expression is not a map with objects");
		break;
	default:
		BUG("invalid mapping expression %s\n",
		    map->mappings->ops->name);
	}

	if (!datatype_equal(map->map->dtype, map->mappings->set->key->dtype))
		return expr_binary_error(ctx->msgs, map->mappings, map->map,
					 "datatype mismatch, map expects %s, "
					 "mapping expression has type %s",
					 map->mappings->set->key->dtype->desc,
					 map->map->dtype->desc);

	map->dtype = map->mappings->set->datatype;
	map->flags |= EXPR_F_CONSTANT;

	/* Data for range lookups needs to be in big endian order */
	if (map->mappings->set->flags & NFT_SET_INTERVAL &&
	    byteorder_conversion(ctx, &map->map, BYTEORDER_BIG_ENDIAN) < 0)
		return -1;

	return 0;
}

static int stmt_evaluate_objref(struct eval_ctx *ctx, struct stmt *stmt)
{
	/* We need specific map evaluation for stateful objects. */
	if (stmt->objref.expr->ops->type == EXPR_MAP)
		return stmt_evaluate_objref_map(ctx, stmt);

	if (stmt_evaluate_arg(ctx, stmt,
			      &string_type, NFT_OBJ_MAXNAMELEN * BITS_PER_BYTE,
			      BYTEORDER_HOST_ENDIAN, &stmt->objref.expr) < 0)
		return -1;

	if (!expr_is_constant(stmt->objref.expr))
		return expr_error(ctx->msgs, stmt->objref.expr,
				  "Counter expression must be constant");

	return 0;
}

int stmt_evaluate(struct eval_ctx *ctx, struct stmt *stmt)
{
	if (ctx->nft->debug_mask & NFT_DEBUG_EVALUATION) {
		struct error_record *erec;
		erec = erec_create(EREC_INFORMATIONAL, &stmt->location,
				   "Evaluate %s", stmt->ops->name);
		erec_print(&ctx->nft->output, erec, ctx->nft->debug_mask);
		stmt_print(stmt, &ctx->nft->output);
		nft_print(&ctx->nft->output, "\n\n");
		erec_destroy(erec);
	}

	switch (stmt->ops->type) {
	case STMT_CONNLIMIT:
	case STMT_COUNTER:
	case STMT_LIMIT:
	case STMT_QUOTA:
	case STMT_NOTRACK:
	case STMT_FLOW_OFFLOAD:
		return 0;
	case STMT_EXPRESSION:
		return stmt_evaluate_expr(ctx, stmt);
	case STMT_VERDICT:
		return stmt_evaluate_verdict(ctx, stmt);
	case STMT_PAYLOAD:
		return stmt_evaluate_payload(ctx, stmt);
	case STMT_EXTHDR:
		return stmt_evaluate_exthdr(ctx, stmt);
	case STMT_METER:
		return stmt_evaluate_meter(ctx, stmt);
	case STMT_META:
		return stmt_evaluate_meta(ctx, stmt);
	case STMT_CT:
		return stmt_evaluate_ct(ctx, stmt);
	case STMT_LOG:
		return stmt_evaluate_log(ctx, stmt);
	case STMT_REJECT:
		return stmt_evaluate_reject(ctx, stmt);
	case STMT_NAT:
		return stmt_evaluate_nat(ctx, stmt);
	case STMT_TPROXY:
		return stmt_evaluate_tproxy(ctx, stmt);
	case STMT_QUEUE:
		return stmt_evaluate_queue(ctx, stmt);
	case STMT_DUP:
		return stmt_evaluate_dup(ctx, stmt);
	case STMT_FWD:
		return stmt_evaluate_fwd(ctx, stmt);
	case STMT_SET:
		return stmt_evaluate_set(ctx, stmt);
	case STMT_OBJREF:
		return stmt_evaluate_objref(ctx, stmt);
	case STMT_MAP:
		return stmt_evaluate_map(ctx, stmt);
	default:
		BUG("unknown statement type %s\n", stmt->ops->name);
	}
}

static int setelem_evaluate(struct eval_ctx *ctx, struct expr **expr)
{
	struct table *table;
	struct set *set;

	table = table_lookup_global(ctx);
	if (table == NULL)
		return table_not_found(ctx);

	set = set_lookup(table, ctx->cmd->handle.set.name);
	if (set == NULL)
		return cmd_error(ctx, &ctx->cmd->handle.set.location,
				 "Could not process rule: %s",
				 strerror(ENOENT));

	ctx->set = set;
	expr_set_context(&ctx->ectx, set->key->dtype, set->key->len);
	if (expr_evaluate(ctx, expr) < 0)
		return -1;
	ctx->set = NULL;
	return 0;
}

static int set_evaluate(struct eval_ctx *ctx, struct set *set)
{
	struct table *table;
	const char *type;

	table = table_lookup_global(ctx);
	if (table == NULL)
		return table_not_found(ctx);

	if (!(set->flags & NFT_SET_INTERVAL) && set->automerge)
		return set_error(ctx, set, "auto-merge only works with interval sets");

	type = set->flags & NFT_SET_MAP ? "map" : "set";

	if (set->key == NULL)
		return set_error(ctx, set, "%s definition does not specify key",
				 type);

	if (set->key->len == 0) {
		if (set->key->ops->type == EXPR_CONCAT &&
		    expr_evaluate_concat(ctx, &set->key, false) < 0)
			return -1;

		if (set->key->len == 0)
			return set_error(ctx, set, "unqualified key type %s "
					 "specified in %s definition",
					 set->key->dtype->name, type);
	}
	if (set->flags & NFT_SET_INTERVAL &&
	    set->key->ops->type == EXPR_CONCAT)
		return set_error(ctx, set, "concatenated types not supported in interval sets");

	if (set->flags & NFT_SET_MAP) {
		if (set->datatype == NULL)
			return set_error(ctx, set, "map definition does not "
					 "specify mapping data type");

		set->datalen = set->datatype->size;
		if (set->datalen == 0 && set->datatype->type != TYPE_VERDICT)
			return set_error(ctx, set, "unqualified mapping data "
					 "type specified in map definition");
	} else if (set->flags & NFT_SET_OBJECT) {
		set->datatype = &string_type;
		set->datalen  = NFT_OBJ_MAXNAMELEN * BITS_PER_BYTE;
	}

	ctx->set = set;
	if (set->init != NULL) {
		expr_set_context(&ctx->ectx, set->key->dtype, set->key->len);
		if (expr_evaluate(ctx, &set->init) < 0)
			return -1;
	}
	ctx->set = NULL;

	if (set_lookup(table, set->handle.set.name) == NULL)
		set_add_hash(set_get(set), table);

	/* Default timeout value implies timeout support */
	if (set->timeout)
		set->flags |= NFT_SET_TIMEOUT;

	return 0;
}

static bool evaluate_priority(struct prio_spec *prio, int family, int hook)
{
	int priority;

	/* A numeric value has been used to specify priority. */
	if (prio->str == NULL)
		return true;

	priority = std_prio_lookup(prio->str, family, hook);
	if (priority == NF_IP_PRI_LAST)
		return false;
	prio->num += priority;

	return true;
}

static uint32_t str2hooknum(uint32_t family, const char *hook);

static int flowtable_evaluate(struct eval_ctx *ctx, struct flowtable *ft)
{
	struct table *table;

	table = table_lookup_global(ctx);
	if (table == NULL)
		return table_not_found(ctx);

	ft->hooknum = str2hooknum(NFPROTO_NETDEV, ft->hookstr);
	if (ft->hooknum == NF_INET_NUMHOOKS)
		return chain_error(ctx, ft, "invalid hook %s", ft->hookstr);

	if (!evaluate_priority(&ft->priority, NFPROTO_NETDEV, ft->hooknum))
		return __stmt_binary_error(ctx, &ft->priority.loc, NULL,
					   "'%s' is invalid priority.",
					   ft->priority.str);

	if (!ft->dev_expr)
		return chain_error(ctx, ft, "Unbound flowtable not allowed (must specify devices)");

	return 0;
}

/* Convert rule's handle.index into handle.position. */
static int rule_translate_index(struct eval_ctx *ctx, struct rule *rule)
{
	struct table *table;
	struct chain *chain;
	uint64_t index = 0;
	struct rule *r;
	int ret;

	/* update cache with CMD_LIST so that rules are fetched, too */
	ret = cache_update(ctx->nft, CMD_LIST, ctx->msgs);
	if (ret < 0)
		return ret;

	table = table_lookup(&rule->handle, &ctx->nft->cache);
	if (!table)
		return table_not_found(ctx);

	chain = chain_lookup(table, &rule->handle);
	if (!chain)
		return chain_not_found(ctx);

	list_for_each_entry(r, &chain->rules, list) {
		if (++index < rule->handle.index.id)
			continue;
		rule->handle.position.id = r->handle.handle.id;
		rule->handle.position.location = rule->handle.index.location;
		break;
	}
	if (!rule->handle.position.id)
		return cmd_error(ctx, &rule->handle.index.location,
				"Could not process rule: %s",
				strerror(ENOENT));
	return 0;
}

static int rule_evaluate(struct eval_ctx *ctx, struct rule *rule)
{
	struct stmt *stmt, *tstmt = NULL;
	struct error_record *erec;

	proto_ctx_init(&ctx->pctx, rule->handle.family, ctx->nft->debug_mask);
	memset(&ctx->ectx, 0, sizeof(ctx->ectx));

	ctx->rule = rule;
	list_for_each_entry(stmt, &rule->stmts, list) {
		if (tstmt != NULL)
			return stmt_binary_error(ctx, stmt, tstmt,
						 "Statement after terminal "
						 "statement has no effect");

		ctx->stmt = stmt;
		if (stmt_evaluate(ctx, stmt) < 0)
			return -1;
		if (stmt->flags & STMT_F_TERMINAL)
			tstmt = stmt;
	}

	erec = rule_postprocess(rule);
	if (erec != NULL) {
		erec_queue(erec, ctx->msgs);
		return -1;
	}

	if (rule->handle.index.id &&
	    rule_translate_index(ctx, rule))
		return -1;

	return 0;
}

static uint32_t str2hooknum(uint32_t family, const char *hook)
{
	if (!hook)
		return NF_INET_NUMHOOKS;

	switch (family) {
	case NFPROTO_IPV4:
	case NFPROTO_BRIDGE:
	case NFPROTO_IPV6:
	case NFPROTO_INET:
		/* These families have overlapping values for each hook */
		if (!strcmp(hook, "prerouting"))
			return NF_INET_PRE_ROUTING;
		else if (!strcmp(hook, "input"))
			return NF_INET_LOCAL_IN;
		else if (!strcmp(hook, "forward"))
			return NF_INET_FORWARD;
		else if (!strcmp(hook, "postrouting"))
			return NF_INET_POST_ROUTING;
		else if (!strcmp(hook, "output"))
			return NF_INET_LOCAL_OUT;
		break;
	case NFPROTO_ARP:
		if (!strcmp(hook, "input"))
			return NF_ARP_IN;
		else if (!strcmp(hook, "forward"))
			return NF_ARP_FORWARD;
		else if (!strcmp(hook, "output"))
			return NF_ARP_OUT;
		break;
	case NFPROTO_NETDEV:
		if (!strcmp(hook, "ingress"))
			return NF_NETDEV_INGRESS;
		break;
	default:
		break;
	}

	return NF_INET_NUMHOOKS;
}

static int chain_evaluate(struct eval_ctx *ctx, struct chain *chain)
{
	struct table *table;
	struct rule *rule;

	table = table_lookup_global(ctx);
	if (table == NULL)
		return table_not_found(ctx);

	if (chain == NULL) {
		if (chain_lookup(table, &ctx->cmd->handle) == NULL) {
			chain = chain_alloc(NULL);
			handle_merge(&chain->handle, &ctx->cmd->handle);
			chain_add_hash(chain, table);
		}
		return 0;
	} else {
		if (chain_lookup(table, &chain->handle) == NULL)
			chain_add_hash(chain_get(chain), table);
	}

	if (chain->flags & CHAIN_F_BASECHAIN) {
		chain->hooknum = str2hooknum(chain->handle.family,
					     chain->hookstr);
		if (chain->hooknum == NF_INET_NUMHOOKS)
			return chain_error(ctx, chain, "invalid hook %s",
					   chain->hookstr);

		if (!evaluate_priority(&chain->priority, chain->handle.family,
				       chain->hooknum))
			return __stmt_binary_error(ctx, &chain->priority.loc, NULL,
						   "'%s' is invalid priority in this context.",
						   chain->priority.str);
	}

	list_for_each_entry(rule, &chain->rules, list) {
		handle_merge(&rule->handle, &chain->handle);
		if (rule_evaluate(ctx, rule) < 0)
			return -1;
	}
	return 0;
}

static int obj_evaluate(struct eval_ctx *ctx, struct obj *obj)
{
	struct ct_timeout *ct = &obj->ct_timeout;
	struct timeout_state *ts, *next;
	unsigned int i;

	if (obj->type != NFT_OBJECT_CT_TIMEOUT)
		return 0;

	for (i = 0; i < timeout_protocol[ct->l4proto].array_size; i++)
		ct->timeout[i] = timeout_protocol[ct->l4proto].dflt_timeout[i];

	list_for_each_entry_safe(ts, next, &ct->timeout_list, head) {
		if (timeout_str2num(ct->l4proto, ts) < 0)
			return __stmt_binary_error(ctx, &ts->location, NULL,
						   "invalid state for this protocol");

		ct->timeout[ts->timeout_index] = ts->timeout_value;
		list_del(&ts->head);
		xfree(ts);
	}
	return 0;
}

static int table_evaluate(struct eval_ctx *ctx, struct table *table)
{
	struct flowtable *ft;
	struct chain *chain;
	struct set *set;
	struct obj *obj;

	if (table_lookup(&ctx->cmd->handle, &ctx->nft->cache) == NULL) {
		if (table == NULL) {
			table = table_alloc();
			handle_merge(&table->handle, &ctx->cmd->handle);
			table_add_hash(table, &ctx->nft->cache);
		} else {
			table_add_hash(table_get(table), &ctx->nft->cache);
		}
	}

	if (ctx->cmd->table == NULL)
		return 0;

	ctx->table = table;
	list_for_each_entry(set, &table->sets, list) {
		expr_set_context(&ctx->ectx, NULL, 0);
		handle_merge(&set->handle, &table->handle);
		if (set_evaluate(ctx, set) < 0)
			return -1;
	}
	list_for_each_entry(chain, &table->chains, list) {
		handle_merge(&chain->handle, &table->handle);
		if (chain_evaluate(ctx, chain) < 0)
			return -1;
	}
	list_for_each_entry(ft, &table->flowtables, list) {
		handle_merge(&ft->handle, &table->handle);
		if (flowtable_evaluate(ctx, ft) < 0)
			return -1;
	}
	list_for_each_entry(obj, &table->objs, list) {
		handle_merge(&obj->handle, &table->handle);
		if (obj_evaluate(ctx, obj) < 0)
			return -1;
	}

	ctx->table = NULL;
	return 0;
}

static int cmd_evaluate_add(struct eval_ctx *ctx, struct cmd *cmd)
{
	int ret;

	switch (cmd->obj) {
	case CMD_OBJ_SETELEM:
		ret = cache_update(ctx->nft, cmd->op, ctx->msgs);
		if (ret < 0)
			return ret;

		return setelem_evaluate(ctx, &cmd->expr);
	case CMD_OBJ_SET:
		ret = cache_update(ctx->nft, cmd->op, ctx->msgs);
		if (ret < 0)
			return ret;

		handle_merge(&cmd->set->handle, &cmd->handle);
		return set_evaluate(ctx, cmd->set);
	case CMD_OBJ_RULE:
		handle_merge(&cmd->rule->handle, &cmd->handle);
		return rule_evaluate(ctx, cmd->rule);
	case CMD_OBJ_CHAIN:
		ret = cache_update(ctx->nft, cmd->op, ctx->msgs);
		if (ret < 0)
			return ret;

		return chain_evaluate(ctx, cmd->chain);
	case CMD_OBJ_TABLE:
		return table_evaluate(ctx, cmd->table);
	case CMD_OBJ_FLOWTABLE:
		ret = cache_update(ctx->nft, cmd->op, ctx->msgs);
		if (ret < 0)
			return ret;

		handle_merge(&cmd->flowtable->handle, &cmd->handle);
		return flowtable_evaluate(ctx, cmd->flowtable);
	case CMD_OBJ_COUNTER:
	case CMD_OBJ_QUOTA:
	case CMD_OBJ_CT_HELPER:
	case CMD_OBJ_LIMIT:
	case CMD_OBJ_CT_TIMEOUT:
	case CMD_OBJ_SECMARK:
		return obj_evaluate(ctx, cmd->object);
	default:
		BUG("invalid command object type %u\n", cmd->obj);
	}
}

static int cmd_evaluate_delete(struct eval_ctx *ctx, struct cmd *cmd)
{
	int ret;

	switch (cmd->obj) {
	case CMD_OBJ_SETELEM:
		ret = cache_update(ctx->nft, cmd->op, ctx->msgs);
		if (ret < 0)
			return ret;

		return setelem_evaluate(ctx, &cmd->expr);
	case CMD_OBJ_SET:
	case CMD_OBJ_RULE:
	case CMD_OBJ_CHAIN:
	case CMD_OBJ_TABLE:
	case CMD_OBJ_FLOWTABLE:
	case CMD_OBJ_COUNTER:
	case CMD_OBJ_QUOTA:
	case CMD_OBJ_CT_HELPER:
	case CMD_OBJ_CT_TIMEOUT:
	case CMD_OBJ_LIMIT:
	case CMD_OBJ_SECMARK:
		return 0;
	default:
		BUG("invalid command object type %u\n", cmd->obj);
	}
}

static int cmd_evaluate_get(struct eval_ctx *ctx, struct cmd *cmd)
{
	struct table *table;
	struct set *set;
	int ret;

	ret = cache_update(ctx->nft, cmd->op, ctx->msgs);
	if (ret < 0)
		return ret;

	switch (cmd->obj) {
	case CMD_OBJ_SETELEM:
		table = table_lookup(&cmd->handle, &ctx->nft->cache);
		if (table == NULL)
			return table_not_found(ctx);

		set = set_lookup(table, cmd->handle.set.name);
		if (set == NULL || set->flags & (NFT_SET_MAP | NFT_SET_EVAL))
			return cmd_error(ctx, &ctx->cmd->handle.set.location,
					 "Could not process rule: %s",
					 strerror(ENOENT));

		return setelem_evaluate(ctx, &cmd->expr);
	default:
		BUG("invalid command object type %u\n", cmd->obj);
	}
}

static int cmd_evaluate_list_obj(struct eval_ctx *ctx, const struct cmd *cmd,
				 uint32_t obj_type)
{
	const struct table *table;

	if (obj_type == NFT_OBJECT_UNSPEC)
		obj_type = NFT_OBJECT_COUNTER;

	table = table_lookup(&cmd->handle, &ctx->nft->cache);
	if (table == NULL)
		return table_not_found(ctx);

	if (obj_lookup(table, cmd->handle.obj.name, obj_type) == NULL)
		return cmd_error(ctx, &cmd->handle.obj.location,
				 "Could not process rule: %s",
				 strerror(ENOENT));
	return 0;
}

static int cmd_evaluate_list(struct eval_ctx *ctx, struct cmd *cmd)
{
	struct table *table;
	struct set *set;
	int ret;

	ret = cache_update(ctx->nft, cmd->op, ctx->msgs);
	if (ret < 0)
		return ret;

	switch (cmd->obj) {
	case CMD_OBJ_TABLE:
		if (cmd->handle.table.name == NULL)
			return 0;

		table = table_lookup(&cmd->handle, &ctx->nft->cache);
		if (table == NULL)
			return table_not_found(ctx);

		return 0;
	case CMD_OBJ_SET:
		table = table_lookup(&cmd->handle, &ctx->nft->cache);
		if (table == NULL)
			return table_not_found(ctx);

		set = set_lookup(table, cmd->handle.set.name);
		if (set == NULL || set->flags & (NFT_SET_MAP | NFT_SET_EVAL))
			return cmd_error(ctx, &cmd->handle.set.location,
					  "Could not process rule: %s",
					 strerror(ENOENT));
		return 0;
	case CMD_OBJ_METER:
		table = table_lookup(&cmd->handle, &ctx->nft->cache);
		if (table == NULL)
			return table_not_found(ctx);

		set = set_lookup(table, cmd->handle.set.name);
		if (set == NULL || !(set->flags & NFT_SET_EVAL))
			return cmd_error(ctx, &cmd->handle.set.location,
					 "Could not process rule: %s",
					 strerror(ENOENT));
		return 0;
	case CMD_OBJ_MAP:
		table = table_lookup(&cmd->handle, &ctx->nft->cache);
		if (table == NULL)
			return table_not_found(ctx);

		set = set_lookup(table, cmd->handle.set.name);
		if (set == NULL || !(set->flags & NFT_SET_MAP))
			return cmd_error(ctx, &cmd->handle.set.location,
					 "Could not process rule: %s",
					 strerror(ENOENT));
		return 0;
	case CMD_OBJ_CHAIN:
		table = table_lookup(&cmd->handle, &ctx->nft->cache);
		if (table == NULL)
			return table_not_found(ctx);

		if (chain_lookup(table, &cmd->handle) == NULL)
			return chain_not_found(ctx);

		return 0;
	case CMD_OBJ_QUOTA:
		return cmd_evaluate_list_obj(ctx, cmd, NFT_OBJECT_QUOTA);
	case CMD_OBJ_COUNTER:
		return cmd_evaluate_list_obj(ctx, cmd, NFT_OBJECT_COUNTER);
	case CMD_OBJ_CT_HELPER:
		return cmd_evaluate_list_obj(ctx, cmd, NFT_OBJECT_CT_HELPER);
	case CMD_OBJ_CT_TIMEOUT:
		return cmd_evaluate_list_obj(ctx, cmd, NFT_OBJECT_CT_TIMEOUT);
	case CMD_OBJ_LIMIT:
		return cmd_evaluate_list_obj(ctx, cmd, NFT_OBJECT_LIMIT);
	case CMD_OBJ_SECMARK:
		return cmd_evaluate_list_obj(ctx, cmd, NFT_OBJECT_SECMARK);
	case CMD_OBJ_COUNTERS:
	case CMD_OBJ_QUOTAS:
	case CMD_OBJ_CT_HELPERS:
	case CMD_OBJ_LIMITS:
	case CMD_OBJ_SETS:
	case CMD_OBJ_FLOWTABLES:
	case CMD_OBJ_SECMARKS:
		if (cmd->handle.table.name == NULL)
			return 0;
		if (table_lookup(&cmd->handle, &ctx->nft->cache) == NULL)
			return table_not_found(ctx);

		return 0;
	case CMD_OBJ_CHAINS:
	case CMD_OBJ_RULESET:
	case CMD_OBJ_METERS:
	case CMD_OBJ_MAPS:
		return 0;
	default:
		BUG("invalid command object type %u\n", cmd->obj);
	}
}

static int cmd_evaluate_reset(struct eval_ctx *ctx, struct cmd *cmd)
{
	int ret;

	ret = cache_update(ctx->nft, cmd->op, ctx->msgs);
	if (ret < 0)
		return ret;

	switch (cmd->obj) {
	case CMD_OBJ_COUNTER:
	case CMD_OBJ_QUOTA:
	case CMD_OBJ_COUNTERS:
	case CMD_OBJ_QUOTAS:
		if (cmd->handle.table.name == NULL)
			return 0;
		if (table_lookup(&cmd->handle, &ctx->nft->cache) == NULL)
			return table_not_found(ctx);

		return 0;
	default:
		BUG("invalid command object type %u\n", cmd->obj);
	}
}

static int cmd_evaluate_flush(struct eval_ctx *ctx, struct cmd *cmd)
{
	struct table *table;
	struct set *set;
	int ret;

	switch (cmd->obj) {
	case CMD_OBJ_RULESET:
		cache_flush(ctx->nft, cmd->op, ctx->msgs);
		break;
	case CMD_OBJ_TABLE:
		/* Flushing a table does not empty the sets in the table nor remove
		 * any chains.
		 */
	case CMD_OBJ_CHAIN:
		/* Chains don't hold sets */
		break;
	case CMD_OBJ_SET:
		ret = cache_update(ctx->nft, cmd->op, ctx->msgs);
		if (ret < 0)
			return ret;

		table = table_lookup(&cmd->handle, &ctx->nft->cache);
		if (table == NULL)
			return table_not_found(ctx);

		set = set_lookup(table, cmd->handle.set.name);
		if (set == NULL || set->flags & (NFT_SET_MAP | NFT_SET_EVAL))
			return cmd_error(ctx, &cmd->handle.set.location,
					 "Could not process rule: %s",
					 strerror(ENOENT));
		return 0;
	case CMD_OBJ_MAP:
		ret = cache_update(ctx->nft, cmd->op, ctx->msgs);
		if (ret < 0)
			return ret;

		table = table_lookup(&cmd->handle, &ctx->nft->cache);
		if (table == NULL)
			return table_not_found(ctx);

		set = set_lookup(table, cmd->handle.set.name);
		if (set == NULL || !(set->flags & NFT_SET_MAP))
			return cmd_error(ctx, &ctx->cmd->handle.set.location,
					 "Could not process rule: %s",
					 strerror(ENOENT));
		return 0;
	case CMD_OBJ_METER:
		ret = cache_update(ctx->nft, cmd->op, ctx->msgs);
		if (ret < 0)
			return ret;

		table = table_lookup(&cmd->handle, &ctx->nft->cache);
		if (table == NULL)
			return table_not_found(ctx);

		set = set_lookup(table, cmd->handle.set.name);
		if (set == NULL || !(set->flags & NFT_SET_EVAL))
			return cmd_error(ctx, &ctx->cmd->handle.set.location,
					 "Could not process rule: %s",
					 strerror(ENOENT));
		return 0;
	default:
		BUG("invalid command object type %u\n", cmd->obj);
	}
	return 0;
}

static int cmd_evaluate_rename(struct eval_ctx *ctx, struct cmd *cmd)
{
	struct table *table;
	int ret;

	switch (cmd->obj) {
	case CMD_OBJ_CHAIN:
		ret = cache_update(ctx->nft, cmd->op, ctx->msgs);
		if (ret < 0)
			return ret;

		table = table_lookup(&ctx->cmd->handle, &ctx->nft->cache);
		if (table == NULL)
			return table_not_found(ctx);

		if (chain_lookup(table, &ctx->cmd->handle) == NULL)
			return chain_not_found(ctx);

		break;
	default:
		BUG("invalid command object type %u\n", cmd->obj);
	}
	return 0;
}

enum {
	CMD_MONITOR_EVENT_ANY,
	CMD_MONITOR_EVENT_NEW,
	CMD_MONITOR_EVENT_DEL,
	CMD_MONITOR_EVENT_MAX
};

static uint32_t monitor_flags[CMD_MONITOR_EVENT_MAX][CMD_MONITOR_OBJ_MAX] = {
	[CMD_MONITOR_EVENT_ANY] = {
		[CMD_MONITOR_OBJ_ANY]		= 0xffffffff,
		[CMD_MONITOR_OBJ_TABLES]	= (1 << NFT_MSG_NEWTABLE) |
						  (1 << NFT_MSG_DELTABLE),
		[CMD_MONITOR_OBJ_CHAINS]	= (1 << NFT_MSG_NEWCHAIN) |
						  (1 << NFT_MSG_DELCHAIN),
		[CMD_MONITOR_OBJ_RULES]		= (1 << NFT_MSG_NEWRULE) |
						  (1 << NFT_MSG_DELRULE),
		[CMD_MONITOR_OBJ_SETS]		= (1 << NFT_MSG_NEWSET) |
						  (1 << NFT_MSG_DELSET),
		[CMD_MONITOR_OBJ_ELEMS]		= (1 << NFT_MSG_NEWSETELEM) |
						  (1 << NFT_MSG_DELSETELEM),
		[CMD_MONITOR_OBJ_RULESET]	= (1 << NFT_MSG_NEWTABLE) |
						  (1 << NFT_MSG_DELTABLE) |
						  (1 << NFT_MSG_NEWCHAIN) |
						  (1 << NFT_MSG_DELCHAIN) |
						  (1 << NFT_MSG_NEWRULE)  |
						  (1 << NFT_MSG_DELRULE)  |
						  (1 << NFT_MSG_NEWSET)   |
						  (1 << NFT_MSG_DELSET)	  |
						  (1 << NFT_MSG_NEWSETELEM) |
						  (1 << NFT_MSG_DELSETELEM) |
						  (1 << NFT_MSG_NEWOBJ)	  |
						  (1 << NFT_MSG_DELOBJ),
		[CMD_MONITOR_OBJ_TRACE]		= (1 << NFT_MSG_TRACE),
	},
	[CMD_MONITOR_EVENT_NEW] = {
		[CMD_MONITOR_OBJ_ANY]		= (1 << NFT_MSG_NEWTABLE) |
						  (1 << NFT_MSG_NEWCHAIN) |
						  (1 << NFT_MSG_NEWRULE)  |
						  (1 << NFT_MSG_NEWSET)   |
						  (1 << NFT_MSG_NEWSETELEM),
		[CMD_MONITOR_OBJ_TABLES]	= (1 << NFT_MSG_NEWTABLE),
		[CMD_MONITOR_OBJ_CHAINS]	= (1 << NFT_MSG_NEWCHAIN),
		[CMD_MONITOR_OBJ_RULES]		= (1 << NFT_MSG_NEWRULE),
		[CMD_MONITOR_OBJ_SETS]		= (1 << NFT_MSG_NEWSET),
		[CMD_MONITOR_OBJ_ELEMS]		= (1 << NFT_MSG_NEWSETELEM),
		[CMD_MONITOR_OBJ_RULESET]	= (1 << NFT_MSG_NEWTABLE) |
						  (1 << NFT_MSG_NEWCHAIN) |
						  (1 << NFT_MSG_NEWRULE)  |
						  (1 << NFT_MSG_NEWSET)   |
						  (1 << NFT_MSG_NEWSETELEM) |
						  (1 << NFT_MSG_NEWOBJ),
		[CMD_MONITOR_OBJ_TRACE]		= 0,
	},
	[CMD_MONITOR_EVENT_DEL] = {
		[CMD_MONITOR_OBJ_ANY]		= (1 << NFT_MSG_DELTABLE) |
						  (1 << NFT_MSG_DELCHAIN) |
						  (1 << NFT_MSG_DELRULE)  |
						  (1 << NFT_MSG_DELSET)   |
						  (1 << NFT_MSG_DELSETELEM),
		[CMD_MONITOR_OBJ_TABLES]	= (1 << NFT_MSG_DELTABLE),
		[CMD_MONITOR_OBJ_CHAINS]	= (1 << NFT_MSG_DELCHAIN),
		[CMD_MONITOR_OBJ_RULES]		= (1 << NFT_MSG_DELRULE),
		[CMD_MONITOR_OBJ_SETS]		= (1 << NFT_MSG_DELSET),
		[CMD_MONITOR_OBJ_ELEMS]		= (1 << NFT_MSG_DELSETELEM),
		[CMD_MONITOR_OBJ_RULESET]	= (1 << NFT_MSG_DELTABLE) |
						  (1 << NFT_MSG_DELCHAIN) |
						  (1 << NFT_MSG_DELRULE)  |
						  (1 << NFT_MSG_DELSET)   |
						  (1 << NFT_MSG_DELSETELEM) |
						  (1 << NFT_MSG_DELOBJ),
		[CMD_MONITOR_OBJ_TRACE]		= 0,
	},
};

static int cmd_evaluate_monitor(struct eval_ctx *ctx, struct cmd *cmd)
{
	uint32_t event;
	int ret;

	ret = cache_update(ctx->nft, cmd->op, ctx->msgs);
	if (ret < 0)
		return ret;

	if (cmd->monitor->event == NULL)
		event = CMD_MONITOR_EVENT_ANY;
	else if (strcmp(cmd->monitor->event, "new") == 0)
		event = CMD_MONITOR_EVENT_NEW;
	else if (strcmp(cmd->monitor->event, "destroy") == 0)
		event = CMD_MONITOR_EVENT_DEL;
	else {
		return monitor_error(ctx, cmd->monitor, "invalid event %s",
				     cmd->monitor->event);
	}

	cmd->monitor->flags = monitor_flags[event][cmd->monitor->type];
	return 0;
}

static int cmd_evaluate_export(struct eval_ctx *ctx, struct cmd *cmd)
{
	if (cmd->markup->format == __NFT_OUTPUT_NOTSUPP)
		return cmd_error(ctx, &cmd->location,
				 "this output type is not supported");

	return cache_update(ctx->nft, cmd->op, ctx->msgs);
}

static int cmd_evaluate_import(struct eval_ctx *ctx, struct cmd *cmd)
{
	if (cmd->markup->format == __NFT_OUTPUT_NOTSUPP)
		return cmd_error(ctx, &cmd->location,
				 "this output type not supported");

	return 0;
}

static const char * const cmd_op_name[] = {
	[CMD_INVALID]	= "invalid",
	[CMD_ADD]	= "add",
	[CMD_REPLACE]	= "replace",
	[CMD_CREATE]	= "create",
	[CMD_INSERT]	= "insert",
	[CMD_DELETE]	= "delete",
	[CMD_GET]	= "get",
	[CMD_LIST]	= "list",
	[CMD_FLUSH]	= "flush",
	[CMD_RENAME]	= "rename",
	[CMD_EXPORT]	= "export",
	[CMD_MONITOR]	= "monitor",
	[CMD_DESCRIBE]	= "describe",
};

static const char *cmd_op_to_name(enum cmd_ops op)
{
	if (op > CMD_DESCRIBE)
		return "unknown";

	return cmd_op_name[op];
}

int cmd_evaluate(struct eval_ctx *ctx, struct cmd *cmd)
{
	if (ctx->nft->debug_mask & NFT_DEBUG_EVALUATION) {
		struct error_record *erec;

		erec = erec_create(EREC_INFORMATIONAL, &cmd->location,
				   "Evaluate %s", cmd_op_to_name(cmd->op));
		erec_print(&ctx->nft->output, erec, ctx->nft->debug_mask);
		nft_print(&ctx->nft->output, "\n\n");
		erec_destroy(erec);
	}

	memset(&ctx->ectx, 0, sizeof(ctx->ectx));

	ctx->cmd = cmd;
	switch (cmd->op) {
	case CMD_ADD:
	case CMD_REPLACE:
	case CMD_CREATE:
	case CMD_INSERT:
		return cmd_evaluate_add(ctx, cmd);
	case CMD_DELETE:
		return cmd_evaluate_delete(ctx, cmd);
	case CMD_GET:
		return cmd_evaluate_get(ctx, cmd);
	case CMD_LIST:
		return cmd_evaluate_list(ctx, cmd);
	case CMD_RESET:
		return cmd_evaluate_reset(ctx, cmd);
	case CMD_FLUSH:
		return cmd_evaluate_flush(ctx, cmd);
	case CMD_RENAME:
		return cmd_evaluate_rename(ctx, cmd);
	case CMD_EXPORT:
		return cmd_evaluate_export(ctx, cmd);
	case CMD_DESCRIBE:
		return 0;
	case CMD_MONITOR:
		return cmd_evaluate_monitor(ctx, cmd);
	case CMD_IMPORT:
		return cmd_evaluate_import(ctx, cmd);
	default:
		BUG("invalid command operation %u\n", cmd->op);
	};
}