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

#include "lib/zebra.h"
#include "lib/prefix.h"
#include "lib/agg_table.h"
#include "lib/vty.h"
#include "lib/memory.h"
#include "lib/routemap.h"
#include "lib/log.h"
#include "lib/linklist.h"
#include "lib/command.h"
#include "lib/stream.h"
#include "lib/ringbuf.h"
#include "lib/lib_errors.h"

#include "bgpd/bgpd.h"
#include "bgpd/bgp_ecommunity.h"
#include "bgpd/bgp_attr.h"

#include "bgpd/rfapi/bgp_rfapi_cfg.h"
#include "bgpd/rfapi/rfapi.h"
#include "bgpd/rfapi/rfapi_backend.h"

#include "bgpd/bgp_route.h"
#include "bgpd/bgp_mplsvpn.h"
#include "bgpd/bgp_aspath.h"
#include "bgpd/bgp_advertise.h"
#include "bgpd/bgp_vnc_types.h"
#include "bgpd/bgp_zebra.h"

#include "bgpd/rfapi/rfapi_import.h"
#include "bgpd/rfapi/rfapi_private.h"
#include "bgpd/rfapi/rfapi_monitor.h"
#include "bgpd/rfapi/rfapi_vty.h"
#include "bgpd/rfapi/vnc_export_bgp.h"
#include "bgpd/rfapi/vnc_export_bgp_p.h"
#include "bgpd/rfapi/vnc_zebra.h"
#include "bgpd/rfapi/vnc_import_bgp.h"
#include "bgpd/rfapi/rfapi_rib.h"
#include "bgpd/rfapi/rfapi_ap.h"
#include "bgpd/rfapi/rfapi_encap_tlv.h"
#include "bgpd/rfapi/vnc_debug.h"

#ifdef HAVE_GLIBC_BACKTRACE
/* for backtrace and friends */
#include <execinfo.h>
#endif /* HAVE_GLIBC_BACKTRACE */

#define DEBUG_CLEANUP 0

struct ethaddr rfapi_ethaddr0 = {{0}};

#define DEBUG_RFAPI_STR "RF API debugging/testing command\n"

const char *rfapi_error_str(int code)
{
	switch (code) {
	case 0:
		return "Success";
	case ENXIO:
		return "BGP or VNC not configured";
	case ENOENT:
		return "No match";
	case EEXIST:
		return "Handle already open";
	case ENOMSG:
		return "Incomplete configuration";
	case EAFNOSUPPORT:
		return "Invalid address family";
	case EDEADLK:
		return "Called from within a callback procedure";
	case EBADF:
		return "Invalid handle";
	case EINVAL:
		return "Invalid argument";
	case ESTALE:
		return "Stale descriptor";
	default:
		return "Unknown error";
	}
}

/*------------------------------------------
 * rfapi_get_response_lifetime_default
 *
 * Returns the default lifetime for a response.
 *    rfp_start_val     value returned by rfp_start or
 *                      NULL (=use default instance)
 *
 * input:
 *    None
 *
 * output:
 *
 * return value: The bgp instance default lifetime for a response.
 --------------------------------------------*/
int rfapi_get_response_lifetime_default(void *rfp_start_val)
{
	struct bgp *bgp = rfapi_bgp_lookup_by_rfp(rfp_start_val);
	if (bgp)
		return bgp->rfapi_cfg->default_response_lifetime;
	return BGP_VNC_DEFAULT_RESPONSE_LIFETIME_DEFAULT;
}

/*------------------------------------------
 * rfapi_is_vnc_configured
 *
 * Returns if VNC is configured
 *
 * input:
 *    rfp_start_val     value returned by rfp_start or
 *                      NULL (=use default instance)
 *
 * output:
 *
 * return value: If VNC is configured for the bgpd instance
 *	0		Success
 *	ENXIO		VNC not configured
 --------------------------------------------*/
int rfapi_is_vnc_configured(void *rfp_start_val)
{
	struct bgp *bgp = rfapi_bgp_lookup_by_rfp(rfp_start_val);
	if (bgp_rfapi_is_vnc_configured(bgp) == 0)
		return 0;
	return ENXIO;
}


/*------------------------------------------
 * rfapi_get_vn_addr
 *
 * Get the virtual network address used by an NVE based on it's RFD
 *
 * input:
 *    rfd: rfapi descriptor returned by rfapi_open or rfapi_create_generic
 *
 * output:
 *
 * return value:
 *	vn		NVE virtual network address
 *------------------------------------------*/
struct rfapi_ip_addr *rfapi_get_vn_addr(void *rfd)
{
	struct rfapi_descriptor *rrfd = (struct rfapi_descriptor *)rfd;
	return &rrfd->vn_addr;
}

/*------------------------------------------
 * rfapi_get_un_addr
 *
 * Get the underlay network address used by an NVE based on it's RFD
 *
 * input:
 *    rfd: rfapi descriptor returned by rfapi_open or rfapi_create_generic
 *
 * output:
 *
 * return value:
 *	un		NVE underlay network address
 *------------------------------------------*/
struct rfapi_ip_addr *rfapi_get_un_addr(void *rfd)
{
	struct rfapi_descriptor *rrfd = (struct rfapi_descriptor *)rfd;
	return &rrfd->un_addr;
}

int rfapi_ip_addr_cmp(struct rfapi_ip_addr *a1, struct rfapi_ip_addr *a2)
{
	if (a1->addr_family != a2->addr_family)
		return a1->addr_family - a2->addr_family;

	if (a1->addr_family == AF_INET) {
		return IPV4_ADDR_CMP(&a1->addr.v4, &a2->addr.v4);
	}

	if (a1->addr_family == AF_INET6) {
		return IPV6_ADDR_CMP(&a1->addr.v6, &a2->addr.v6);
	}

	assert(1);
	/* NOTREACHED */
	return 1;
}

static int rfapi_find_node(struct bgp *bgp, struct rfapi_ip_addr *vn_addr,
			   struct rfapi_ip_addr *un_addr,
			   struct agg_node **node)
{
	struct rfapi *h;
	struct prefix p;
	struct agg_node *rn;
	int rc;
	afi_t afi;

	if (!bgp) {
		return ENXIO;
	}

	h = bgp->rfapi;
	if (!h) {
		return ENXIO;
	}

	afi = family2afi(un_addr->addr_family);
	if (!afi) {
		return EAFNOSUPPORT;
	}

	if ((rc = rfapiRaddr2Qprefix(un_addr, &p)))
		return rc;

	rn = agg_node_lookup(h->un[afi], &p);

	if (!rn)
		return ENOENT;

	agg_unlock_node(rn);

	*node = rn;

	return 0;
}


int rfapi_find_rfd(struct bgp *bgp, struct rfapi_ip_addr *vn_addr,
		   struct rfapi_ip_addr *un_addr, struct rfapi_descriptor **rfd)
{
	struct agg_node *rn;
	int rc;

	rc = rfapi_find_node(bgp, vn_addr, un_addr, &rn);

	if (rc)
		return rc;

	for (*rfd = (struct rfapi_descriptor *)(rn->info); *rfd;
	     *rfd = (*rfd)->next) {
		if (!rfapi_ip_addr_cmp(&(*rfd)->vn_addr, vn_addr))
			break;
	}

	if (!*rfd)
		return ENOENT;

	return 0;
}

/*------------------------------------------
 * rfapi_find_handle
 *
 * input:
 *	un		underlay network address
 *	vn		virtual network address
 *
 * output:
 *	pHandle		pointer to location to store handle
 *
 * return value:
 *	0		Success
 *	ENOENT		no matching handle
 *	ENXIO		BGP or VNC not configured
 *------------------------------------------*/
static int rfapi_find_handle(struct bgp *bgp, struct rfapi_ip_addr *vn_addr,
			     struct rfapi_ip_addr *un_addr,
			     rfapi_handle *handle)
{
	struct rfapi_descriptor **rfd;

	rfd = (struct rfapi_descriptor **)handle;

	return rfapi_find_rfd(bgp, vn_addr, un_addr, rfd);
}

static int rfapi_find_handle_vty(struct vty *vty, struct rfapi_ip_addr *vn_addr,
				 struct rfapi_ip_addr *un_addr,
				 rfapi_handle *handle)
{
	struct bgp *bgp;
	struct rfapi_descriptor **rfd;

	bgp = bgp_get_default(); /* assume 1 instance for now */

	rfd = (struct rfapi_descriptor **)handle;

	return rfapi_find_rfd(bgp, vn_addr, un_addr, rfd);
}

static int is_valid_rfd(struct rfapi_descriptor *rfd)
{
	rfapi_handle hh;

	if (!rfd || rfd->bgp == NULL)
		return 0;

	if (CHECK_FLAG(
		    rfd->flags,
		    RFAPI_HD_FLAG_IS_VRF)) /* assume VRF/internal are valid */
		return 1;

	if (rfapi_find_handle(rfd->bgp, &rfd->vn_addr, &rfd->un_addr, &hh))
		return 0;

	if (rfd != hh)
		return 0;

	return 1;
}

/*
 * check status of descriptor
 */
int rfapi_check(void *handle)
{
	struct rfapi_descriptor *rfd = (struct rfapi_descriptor *)handle;
	rfapi_handle hh;
	int rc;

	if (!rfd || rfd->bgp == NULL)
		return EINVAL;

	if (CHECK_FLAG(
		    rfd->flags,
		    RFAPI_HD_FLAG_IS_VRF)) /* assume VRF/internal are valid */
		return 0;

	if ((rc = rfapi_find_handle(rfd->bgp, &rfd->vn_addr, &rfd->un_addr,
				    &hh)))
		return rc;

	if (rfd != hh)
		return ENOENT;

	if (!rfd->rfg)
		return ESTALE;

	return 0;
}


void del_vnc_route(struct rfapi_descriptor *rfd,
		   struct peer *peer, /* rfd->peer for RFP regs */
		   struct bgp *bgp, safi_t safi, const struct prefix *p,
		   struct prefix_rd *prd, uint8_t type, uint8_t sub_type,
		   struct rfapi_nexthop *lnh, int kill)
{
	afi_t afi; /* of the VN address */
	struct bgp_dest *bn;
	struct bgp_path_info *bpi;
	struct prefix_rd prd0;

	afi = family2afi(p->family);
	assert(afi == AFI_IP || afi == AFI_IP6);

	if (safi == SAFI_ENCAP) {
		memset(&prd0, 0, sizeof(prd0));
		prd0.family = AF_UNSPEC;
		prd0.prefixlen = 64;
		prd = &prd0;
	}
	bn = bgp_afi_node_get(bgp->rib[afi][safi], afi, safi, p, prd);

	vnc_zlog_debug_verbose(
		"%s: peer=%p, prefix=%pFX, prd=%pRDP afi=%d, safi=%d bn=%p, bn->info=%p",
		__func__, peer, p, prd, afi, safi, bn,
		(bn ? bgp_dest_get_bgp_path_info(bn) : NULL));

	for (bpi = (bn ? bgp_dest_get_bgp_path_info(bn) : NULL); bpi;
	     bpi = bpi->next) {

		vnc_zlog_debug_verbose(
			"%s: trying bpi=%p, bpi->peer=%p, bpi->type=%d, bpi->sub_type=%d, bpi->extra->vnc.export.rfapi_handle=%p, local_pref=%" PRIu64,
			__func__, bpi, bpi->peer, bpi->type, bpi->sub_type,
			(bpi->extra ? bpi->extra->vnc.export.rfapi_handle
				    : NULL),
			CHECK_FLAG(bpi->attr->flag,
				   ATTR_FLAG_BIT(BGP_ATTR_LOCAL_PREF)
				   ? bpi->attr->local_pref : 0));

		if (bpi->peer == peer && bpi->type == type
		    && bpi->sub_type == sub_type && bpi->extra
		    && bpi->extra->vnc.export.rfapi_handle == (void *)rfd) {

			vnc_zlog_debug_verbose("%s: matched it", __func__);

			break;
		}
	}

	if (lnh) {
		/*
		 * lnh set means to JUST delete the local nexthop from this
		 * route. Leave the route itself in place.
		 * TBD add return code reporting of success/failure
		 */
		if (!bpi || !bpi->extra
		    || !bpi->extra->vnc.export.local_nexthops) {
			/*
			 * no local nexthops
			 */
			vnc_zlog_debug_verbose(
				"%s: lnh list already empty at prefix %pFX",
				__func__, p);
			goto done;
		}

		/*
		 * look for it
		 */
		struct listnode *node;
		struct rfapi_nexthop *pLnh = NULL;

		for (ALL_LIST_ELEMENTS_RO(bpi->extra->vnc.export.local_nexthops,
					  node, pLnh)) {

			if (prefix_same(&pLnh->addr, &lnh->addr)) {
				break;
			}
		}

		if (pLnh) {
			listnode_delete(bpi->extra->vnc.export.local_nexthops,
					pLnh);

			/* silly rabbit, listnode_delete doesn't invoke
			 * list->del on data */
			rfapi_nexthop_free(pLnh);
		} else {
			vnc_zlog_debug_verbose("%s: desired lnh not found %pFX",
					       __func__, p);
		}
		goto done;
	}

	/*
	 * loop back to import tables
	 * Do this before removing from BGP RIB because rfapiProcessWithdraw
	 * might refer to it
	 */
	rfapiProcessWithdraw(peer, rfd, p, prd, NULL, afi, safi, type, kill);

	if (bpi) {
		vnc_zlog_debug_verbose(
			"%s: Found route (safi=%d) to delete at prefix %pFX",
			__func__, safi, p);

		if (safi == SAFI_MPLS_VPN) {
			struct bgp_dest *pdest = NULL;
			struct bgp_table *table = NULL;

			pdest = bgp_node_get(bgp->rib[afi][safi],
					     (struct prefix *)prd);
			table = bgp_dest_get_bgp_table_info(pdest);
			if (table)
				vnc_import_bgp_del_vnc_host_route_mode_resolve_nve(
					bgp, prd, table, p, bpi);
			bgp_dest_unlock_node(pdest);
		}

		/*
		 * Delete local_nexthops list
		 */
		if (bpi->extra && bpi->extra->vnc.export.local_nexthops)
			list_delete(&bpi->extra->vnc.export.local_nexthops);

		bgp_aggregate_decrement(bgp, p, bpi, afi, safi);
		bgp_path_info_delete(bn, bpi);
		bgp_process(bgp, bn, afi, safi);
	} else {
		vnc_zlog_debug_verbose(
			"%s: Couldn't find route (safi=%d) at prefix %pFX",
			__func__, safi, p);
	}
done:
	bgp_dest_unlock_node(bn);
}

struct rfapi_nexthop *rfapi_nexthop_new(struct rfapi_nexthop *copyme)
{
	struct rfapi_nexthop *new =
		XCALLOC(MTYPE_RFAPI_NEXTHOP, sizeof(struct rfapi_nexthop));
	if (copyme)
		*new = *copyme;
	return new;
}

void rfapi_nexthop_free(void *p)
{
	struct rfapi_nexthop *goner = p;
	XFREE(MTYPE_RFAPI_NEXTHOP, goner);
}

struct rfapi_vn_option *rfapi_vn_options_dup(struct rfapi_vn_option *existing)
{
	struct rfapi_vn_option *p;
	struct rfapi_vn_option *head = NULL;
	struct rfapi_vn_option *tail = NULL;

	for (p = existing; p; p = p->next) {
		struct rfapi_vn_option *new;

		new = XCALLOC(MTYPE_RFAPI_VN_OPTION,
			      sizeof(struct rfapi_vn_option));
		*new = *p;
		new->next = NULL;
		if (tail)
			(tail)->next = new;
		tail = new;
		if (!head) {
			head = new;
		}
	}
	return head;
}

void rfapi_un_options_free(struct rfapi_un_option *p)
{
	struct rfapi_un_option *next;

	while (p) {
		next = p->next;
		XFREE(MTYPE_RFAPI_UN_OPTION, p);
		p = next;
	}
}

void rfapi_vn_options_free(struct rfapi_vn_option *p)
{
	struct rfapi_vn_option *next;

	while (p) {
		next = p->next;
		XFREE(MTYPE_RFAPI_VN_OPTION, p);
		p = next;
	}
}

/* Based on bgp_redistribute_add() */
void add_vnc_route(struct rfapi_descriptor *rfd, /* cookie, VPN UN addr, peer */
		   struct bgp *bgp, int safi, const struct prefix *p,
		   struct prefix_rd *prd, struct rfapi_ip_addr *nexthop,
		   uint32_t *local_pref,
		   uint32_t *lifetime, /* NULL => dont send lifetime */
		   struct bgp_tea_options *rfp_options,
		   struct rfapi_un_option *options_un,
		   struct rfapi_vn_option *options_vn,
		   struct ecommunity *rt_export_list, /* Copied, not consumed */
		   uint32_t *med,		   /* NULL => don't set med */
		   uint32_t *label,		   /* low order 3 bytes */
		   uint8_t type, uint8_t sub_type, /* RFP, NORMAL or REDIST */
		   int flags)
{
	afi_t afi; /* of the VN address */
	struct bgp_path_info *new;
	struct bgp_path_info *bpi;
	struct bgp_dest *bn;

	struct attr attr = {0};
	struct attr *new_attr;
	uint32_t label_val;

	struct bgp_attr_encap_subtlv *encaptlv;
	char buf[PREFIX_STRLEN];

	struct rfapi_nexthop *lnh = NULL; /* local nexthop */
	struct rfapi_vn_option *vo;
	struct rfapi_l2address_option *l2o = NULL;
	struct rfapi_ip_addr *un_addr = &rfd->un_addr;

	bgp_encap_types TunnelType = BGP_ENCAP_TYPE_RESERVED;
	struct bgp_redist *red;

	if (safi == SAFI_ENCAP
	    && !(bgp->rfapi_cfg->flags & BGP_VNC_CONFIG_ADV_UN_METHOD_ENCAP)) {

		/*
		 * Encap mode not enabled. UN addresses will be communicated
		 * via VNC Tunnel subtlv instead.
		 */
		vnc_zlog_debug_verbose(
			"%s: encap mode not enabled, not adding SAFI_ENCAP route",
			__func__);
		return;
	}

	for (vo = options_vn; vo; vo = vo->next) {
		if (RFAPI_VN_OPTION_TYPE_L2ADDR == vo->type) {
			l2o = &vo->v.l2addr;
			if (RFAPI_0_ETHERADDR(&l2o->macaddr))
				l2o = NULL; /* not MAC resolution */
		}
		if (RFAPI_VN_OPTION_TYPE_LOCAL_NEXTHOP == vo->type) {
			lnh = &vo->v.local_nexthop;
		}
	}

	if (label)
		label_val = *label;
	else
		label_val = MPLS_LABEL_IMPLICIT_NULL;

	afi = family2afi(p->family);
	assert(afi == AFI_IP || afi == AFI_IP6);

	vnc_zlog_debug_verbose("%s: afi=%s, safi=%s", __func__, afi2str(afi),
			       safi2str(safi));

	/* Make default attribute. Produces already-interned attr.aspath */
	/* Cripes, the memory management of attributes is byzantine */

	bgp_attr_default_set(&attr, bgp, BGP_ORIGIN_INCOMPLETE);

	/*
	 * At this point:
	 * attr: static
	 *  extra: dynamically allocated, owned by attr
	 *  aspath: points to interned hash from aspath hash table
	 */


	/*
	 * Route-specific un_options get added to the VPN SAFI
	 * advertisement tunnel encap attribute.  (the per-NVE
	 * "default" un_options are put into the 1-per-NVE ENCAP
	 * SAFI advertisement). The VPN SAFI also gets the
	 * default un_options if there are no route-specific options.
	 */
	if (options_un) {
		struct rfapi_un_option *uo;

		for (uo = options_un; uo; uo = uo->next) {
			if (RFAPI_UN_OPTION_TYPE_TUNNELTYPE == uo->type) {
				TunnelType = rfapi_tunneltype_option_to_tlv(
					bgp, un_addr, &uo->v.tunnel, &attr,
					l2o != NULL);
			}
		}
	} else {
		/*
		 * Add encap attr
		 * These are the NVE-specific "default" un_options which are
		 * put into the 1-per-NVE ENCAP advertisement.
		 */
		if (rfd->default_tunneltype_option.type) {
			TunnelType = rfapi_tunneltype_option_to_tlv(
				bgp, un_addr, &rfd->default_tunneltype_option,
				&attr, l2o != NULL);
		} else /* create default for local addse  */
			if (type == ZEBRA_ROUTE_BGP
			    && sub_type == BGP_ROUTE_RFP)
			TunnelType = rfapi_tunneltype_option_to_tlv(
				bgp, un_addr, NULL, &attr, l2o != NULL);
	}

	if (TunnelType == BGP_ENCAP_TYPE_MPLS) {
		if (safi == SAFI_ENCAP) {
			/* Encap SAFI not used with MPLS  */
			vnc_zlog_debug_verbose(
				"%s: mpls tunnel type, encap safi omitted",
				__func__);
			aspath_unintern(&attr.aspath); /* Unintern original. */
			return;
		}
	}

	if (local_pref) {
		attr.local_pref = *local_pref;
		attr.flag |= ATTR_FLAG_BIT(BGP_ATTR_LOCAL_PREF);
	}

	if (med) {
		attr.med = *med;
		attr.flag |= ATTR_FLAG_BIT(BGP_ATTR_MULTI_EXIT_DISC);
	}

	/* override default weight assigned by bgp_attr_default_set() */
	attr.weight = rfd->peer ? rfd->peer->weight[afi][safi] : 0;

	/*
	 * NB: ticket 81: do not reset attr.aspath here because it would
	 * cause iBGP peers to drop route
	 */

	/*
	 * Set originator ID for routes imported from BGP directly.
	 * These routes could be synthetic, and therefore could
	 * reuse the peer pointers of the routes they are derived
	 * from. Setting the originator ID to "us" prevents the
	 * wrong originator ID from being sent when this route is
	 * sent from a route reflector.
	 */
	if (type == ZEBRA_ROUTE_BGP_DIRECT
	    || type == ZEBRA_ROUTE_BGP_DIRECT_EXT) {
		attr.flag |= ATTR_FLAG_BIT(BGP_ATTR_ORIGINATOR_ID);
		attr.originator_id = bgp->router_id;
	}


	/* Set up vnc attribute (sub-tlv for Prefix Lifetime) */
	if (lifetime && *lifetime != RFAPI_INFINITE_LIFETIME) {
		uint32_t lt;

		encaptlv = XCALLOC(MTYPE_ENCAP_TLV,
				   sizeof(struct bgp_attr_encap_subtlv) + 4);
		encaptlv->type =
			BGP_VNC_SUBTLV_TYPE_LIFETIME; /* prefix lifetime */
		encaptlv->length = 4;
		lt = htonl(*lifetime);
		memcpy(encaptlv->value, &lt, 4);
		bgp_attr_set_vnc_subtlvs(&attr, encaptlv);
		vnc_zlog_debug_verbose(
			"%s: set Encap Attr Prefix Lifetime to %d", __func__,
			*lifetime);
	}

	/* add rfp options to vnc attr */
	if (rfp_options) {

		if (flags & RFAPI_AHR_RFPOPT_IS_VNCTLV) {
			struct bgp_attr_encap_subtlv *vnc_subtlvs =
				bgp_attr_get_vnc_subtlvs(&attr);
			/*
			 * this flag means we're passing a pointer to an
			 * existing encap tlv chain which we should copy.
			 * It's a hack to avoid adding yet another argument
			 * to add_vnc_route()
			 */
			encaptlv = encap_tlv_dup(
				(struct bgp_attr_encap_subtlv *)rfp_options);
			if (vnc_subtlvs)
				vnc_subtlvs->next = encaptlv;
			else
				bgp_attr_set_vnc_subtlvs(&attr, encaptlv);
		} else {
			struct bgp_tea_options *hop;
			/* XXX max of one tlv present so far from above code */
			struct bgp_attr_encap_subtlv *tail =
				bgp_attr_get_vnc_subtlvs(&attr);

			for (hop = rfp_options; hop; hop = hop->next) {

				/*
				 * Construct subtlv
				 */
				encaptlv = XCALLOC(
					MTYPE_ENCAP_TLV,
					sizeof(struct bgp_attr_encap_subtlv) + 2
						+ hop->length);
				encaptlv->type =
					BGP_VNC_SUBTLV_TYPE_RFPOPTION; /* RFP
									  option
									  */
				encaptlv->length = 2 + hop->length;
				*((uint8_t *)(encaptlv->value) + 0) = hop->type;
				*((uint8_t *)(encaptlv->value) + 1) =
					hop->length;
				memcpy(((uint8_t *)encaptlv->value) + 2,
				       hop->value, hop->length);

				/*
				 * add to end of subtlv chain
				 */
				if (tail)
					tail->next = encaptlv;
				else
					bgp_attr_set_vnc_subtlvs(&attr,
								 encaptlv);
				tail = encaptlv;
			}
		}
	}

	/*
	 * At this point:
	 * attr: static
	 *  extra: dynamically allocated, owned by attr
	 *      vnc_subtlvs: dynamic chain, length 1
	 *  aspath: points to interned hash from aspath hash table
	 */


	bgp_attr_set_ecommunity(&attr, ecommunity_new());
	assert(bgp_attr_get_ecommunity(&attr));

	if (TunnelType != BGP_ENCAP_TYPE_MPLS
	    && TunnelType != BGP_ENCAP_TYPE_RESERVED) {
		/*
		 * Add BGP Encapsulation Extended Community. Format described in
		 * section 4.5 of RFC 5512.
		 * Always include when not MPLS type, to disambiguate this case.
		 */
		struct ecommunity_val beec;

		memset(&beec, 0, sizeof(beec));
		beec.val[0] = ECOMMUNITY_ENCODE_OPAQUE;
		beec.val[1] = ECOMMUNITY_OPAQUE_SUBTYPE_ENCAP;
		beec.val[6] = ((TunnelType) >> 8) & 0xff;
		beec.val[7] = (TunnelType)&0xff;
		ecommunity_add_val(bgp_attr_get_ecommunity(&attr), &beec, false,
				   false);
	}

	/*
	 * Add extended community attributes to match rt export list
	 */
	if (rt_export_list) {
		bgp_attr_set_ecommunity(
			&attr, ecommunity_merge(bgp_attr_get_ecommunity(&attr),
						rt_export_list));
	}

	struct ecommunity *ecomm = bgp_attr_get_ecommunity(&attr);

	if (!ecomm->size) {
		ecommunity_free(&ecomm);
		bgp_attr_set_ecommunity(&attr, NULL);
	}
	vnc_zlog_debug_verbose("%s: attr.ecommunity=%p", __func__, ecomm);


	/*
	 * At this point:
	 * attr: static
	 *  extra: dynamically allocated, owned by attr
	 *      vnc_subtlvs: dynamic chain, length 1
	 *      ecommunity: dynamic 2-part
	 *  aspath: points to interned hash from aspath hash table
	 */

	/* stuff nexthop in attr_extra; which field depends on IPv4 or IPv6 */
	switch (nexthop->addr_family) {
	case AF_INET:
		/*
		 * set this field to prevent bgp_route.c code from setting
		 * mp_nexthop_global_in to self
		 */
		attr.nexthop.s_addr = nexthop->addr.v4.s_addr;

		attr.mp_nexthop_global_in = nexthop->addr.v4;
		attr.mp_nexthop_len = BGP_ATTR_NHLEN_IPV4;
		break;

	case AF_INET6:
		attr.mp_nexthop_global = nexthop->addr.v6;
		attr.mp_nexthop_len = BGP_ATTR_NHLEN_IPV6_GLOBAL;
		break;

	default:
		assert(0);
	}


	prefix2str(p, buf, sizeof(buf));

	/*
	 * At this point:
	 *
	 * attr: static
	 *  extra: dynamically allocated, owned by attr
	 *      vnc_subtlvs: dynamic chain, length 1
	 *      ecommunity: dynamic 2-part
	 *  aspath: points to interned hash from aspath hash table
	 */

	red = bgp_redist_lookup(bgp, afi, type, 0);

	if (red && red->redist_metric_flag) {
		attr.med = red->redist_metric;
		attr.flag |= ATTR_FLAG_BIT(BGP_ATTR_MULTI_EXIT_DISC);
	}

	bn = bgp_afi_node_get(bgp->rib[afi][safi], afi, safi, p, prd);

	/*
	 * bgp_attr_intern creates a new reference to a cached
	 * attribute, but leaves the following bits of trash:
	 * - old attr
	 * - old attr->extra (free via bgp_attr_extra_free(attr))
	 *
	 * Note that it frees the original attr->extra->ecommunity
	 * but leaves the new attribute pointing to the ORIGINAL
	 * vnc options (which therefore we needn't free from the
	 * static attr)
	 */
	new_attr = bgp_attr_intern(&attr);

	aspath_unintern(&attr.aspath); /* Unintern original. */

	/*
	 * At this point:
	 *
	 * attr: static
	 *  extra: dynamically allocated, owned by attr
	 *      vnc_subtlvs: dynamic chain, length 1
	 *      ecommunity: POINTS TO INTERNED ecom, THIS REF NOT COUNTED
	 *
	 * new_attr: an attr that is part of the hash table, distinct
	 *           from attr which is static.
	 *  extra: dynamically allocated, owned by new_attr (in hash table)
	 *      vnc_subtlvs: POINTS TO SAME dynamic chain AS attr
	 *      ecommunity: POINTS TO interned/refcounted dynamic 2-part AS attr
	 *  aspath: POINTS TO interned/refcounted hashed block
	 */
	for (bpi = bgp_dest_get_bgp_path_info(bn); bpi; bpi = bpi->next) {
		/* probably only need to check
		 * bpi->extra->vnc.export.rfapi_handle */
		if (bpi->peer == rfd->peer && bpi->type == type
		    && bpi->sub_type == sub_type && bpi->extra
		    && bpi->extra->vnc.export.rfapi_handle == (void *)rfd) {

			break;
		}
	}

	if (bpi) {

		/*
		 * Adding new local_nexthop, which does not by itself change
		 * what is advertised via BGP
		 */
		if (lnh) {
			if (!bpi->extra->vnc.export.local_nexthops) {
				/* TBD make arrangements to free when needed */
				bpi->extra->vnc.export.local_nexthops =
					list_new();
				bpi->extra->vnc.export.local_nexthops->del =
					rfapi_nexthop_free;
			}

			/*
			 * already present?
			 */
			struct listnode *node;
			struct rfapi_nexthop *pLnh = NULL;

			for (ALL_LIST_ELEMENTS_RO(
				     bpi->extra->vnc.export.local_nexthops,
				     node, pLnh)) {

				if (prefix_same(&pLnh->addr, &lnh->addr)) {
					break;
				}
			}

			/*
			 * Not present, add new one
			 */
			if (!pLnh) {
				pLnh = rfapi_nexthop_new(lnh);
				listnode_add(
					bpi->extra->vnc.export.local_nexthops,
					pLnh);
			}
		}

		if (attrhash_cmp(bpi->attr, new_attr)
		    && !CHECK_FLAG(bpi->flags, BGP_PATH_REMOVED)) {
			bgp_attr_unintern(&new_attr);
			bgp_dest_unlock_node(bn);

			vnc_zlog_debug_any(
				"%s: Found route (safi=%d) at prefix %s, no change",
				__func__, safi, buf);

			goto done;
		} else {
			/* The attribute is changed. */
			bgp_path_info_set_flag(bn, bpi, BGP_PATH_ATTR_CHANGED);

			if (safi == SAFI_MPLS_VPN) {
				struct bgp_dest *pdest = NULL;
				struct bgp_table *table = NULL;

				pdest = bgp_node_get(bgp->rib[afi][safi],
						     (struct prefix *)prd);
				table = bgp_dest_get_bgp_table_info(pdest);
				if (table)
					vnc_import_bgp_del_vnc_host_route_mode_resolve_nve(
						bgp, prd, table, p, bpi);
				bgp_dest_unlock_node(pdest);
			}

			/* Rewrite BGP route information. */
			if (CHECK_FLAG(bpi->flags, BGP_PATH_REMOVED))
				bgp_path_info_restore(bn, bpi);
			else
				bgp_aggregate_decrement(bgp, p, bpi, afi, safi);
			bgp_attr_unintern(&bpi->attr);
			bpi->attr = new_attr;
			bpi->uptime = monotime(NULL);


			if (safi == SAFI_MPLS_VPN) {
				struct bgp_dest *pdest = NULL;
				struct bgp_table *table = NULL;

				pdest = bgp_node_get(bgp->rib[afi][safi],
						     (struct prefix *)prd);
				table = bgp_dest_get_bgp_table_info(pdest);
				if (table)
					vnc_import_bgp_add_vnc_host_route_mode_resolve_nve(
						bgp, prd, table, p, bpi);
				bgp_dest_unlock_node(pdest);
			}

			/* Process change. */
			bgp_aggregate_increment(bgp, p, bpi, afi, safi);
			bgp_process(bgp, bn, afi, safi);
			bgp_dest_unlock_node(bn);

			vnc_zlog_debug_any(
				"%s: Found route (safi=%d) at prefix %s, changed attr",
				__func__, safi, buf);

			goto done;
		}
	}

	new = info_make(type, sub_type, 0, rfd->peer, new_attr, NULL);
	SET_FLAG(new->flags, BGP_PATH_VALID);

	/* save backref to rfapi handle */
	bgp_path_info_extra_get(new);
	new->extra->vnc.export.rfapi_handle = (void *)rfd;
	encode_label(label_val, &new->extra->label[0]);

	/* debug */

	if (VNC_DEBUG(VERBOSE)) {
		vnc_zlog_debug_verbose("%s: printing BPI", __func__);
		rfapiPrintBi(NULL, new);
	}

	bgp_aggregate_increment(bgp, p, new, afi, safi);
	bgp_path_info_add(bn, new);

	if (safi == SAFI_MPLS_VPN) {
		struct bgp_dest *pdest = NULL;
		struct bgp_table *table = NULL;

		pdest = bgp_node_get(bgp->rib[afi][safi], (struct prefix *)prd);
		table = bgp_dest_get_bgp_table_info(pdest);
		if (table)
			vnc_import_bgp_add_vnc_host_route_mode_resolve_nve(
				bgp, prd, table, p, new);
		bgp_dest_unlock_node(pdest);
		encode_label(label_val, &bn->local_label);
	}

	bgp_dest_unlock_node(bn);
	bgp_process(bgp, bn, afi, safi);

	vnc_zlog_debug_any(
		"%s: Added route (safi=%s) at prefix %s (bn=%p, prd=%pRDP)",
		__func__, safi2str(safi), buf, bn, prd);

done:
	/* Loop back to import tables */
	rfapiProcessUpdate(rfd->peer, rfd, p, prd, new_attr, afi, safi, type,
			   sub_type, &label_val);
	vnc_zlog_debug_verbose("%s: looped back import route (safi=%d)",
			       __func__, safi);
}

uint32_t rfp_cost_to_localpref(uint8_t cost)
{
	return 255 - cost;
}

static void rfapiTunnelRouteAnnounce(struct bgp *bgp,
				     struct rfapi_descriptor *rfd,
				     uint32_t *pLifetime)
{
	struct prefix_rd prd;
	struct prefix pfx_vn;
	int rc;
	uint32_t local_pref = rfp_cost_to_localpref(0);

	rc = rfapiRaddr2Qprefix(&(rfd->vn_addr), &pfx_vn);
	assert(!rc);

	/*
	 * Construct route distinguisher = 0
	 */
	memset(&prd, 0, sizeof(prd));
	prd.family = AF_UNSPEC;
	prd.prefixlen = 64;

	add_vnc_route(rfd,	/* rfapi descr, for export list  & backref */
		      bgp,	/* which bgp instance */
		      SAFI_ENCAP, /* which SAFI */
		      &pfx_vn,    /* prefix to advertise */
		      &prd,       /* route distinguisher to use */
		      &rfd->un_addr, /* nexthop */
		      &local_pref,
		      pLifetime, /* max lifetime of child VPN routes */
		      NULL,      /* no rfp options  for ENCAP safi */
		      NULL,      /* rfp un options */
		      NULL,      /* rfp vn options */
		      rfd->rt_export_list, NULL, /* med */
		      NULL,			 /* label: default */
		      ZEBRA_ROUTE_BGP, BGP_ROUTE_RFP, 0);
}


/***********************************************************************
 *			RFP processing behavior configuration
 ***********************************************************************/

/*------------------------------------------
 * rfapi_rfp_set_configuration
 *
 * This is used to change rfapi's processing behavior based on
 * RFP requirements.
 *
 * input:
 *    rfp_start_val     value returned by rfp_start
 *    rfapi_rfp_cfg     Pointer to configuration structure
 *
 * output:
 *    none
 *
 * return value:
 *	0		Success
 *	ENXIO		Unabled to locate configured BGP/VNC
--------------------------------------------*/
int rfapi_rfp_set_configuration(void *rfp_start_val, struct rfapi_rfp_cfg *new)
{
	struct rfapi_rfp_cfg *rcfg;
	struct bgp *bgp;

	bgp = rfapi_bgp_lookup_by_rfp(rfp_start_val);

	if (!new || !bgp || !bgp->rfapi_cfg)
		return ENXIO;

	rcfg = &bgp->rfapi_cfg->rfp_cfg;
	rcfg->download_type = new->download_type;
	rcfg->ftd_advertisement_interval = new->ftd_advertisement_interval;
	rcfg->holddown_factor = new->holddown_factor;

	if (rcfg->use_updated_response != new->use_updated_response) {
		rcfg->use_updated_response = new->use_updated_response;
		if (rcfg->use_updated_response)
			rfapiMonitorCallbacksOn(bgp);
		else
			rfapiMonitorCallbacksOff(bgp);
	}
	if (rcfg->use_removes != new->use_removes) {
		rcfg->use_removes = new->use_removes;
		if (rcfg->use_removes)
			rfapiMonitorResponseRemovalOn(bgp);
		else
			rfapiMonitorResponseRemovalOff(bgp);
	}
	return 0;
}

/*------------------------------------------
 * rfapi_rfp_set_cb_methods
 *
 * Change registered callback functions for asynchronous notifications
 * from RFAPI to the RFP client.
 *
 * input:
 *    rfp_start_val     value returned by rfp_start
 *    methods		Pointer to struct rfapi_rfp_cb_methods containing
 *			pointers to callback methods as described above
 *
 * return value:
 *	0		Success
 *	ENXIO		BGP or VNC not configured
 *------------------------------------------*/
int rfapi_rfp_set_cb_methods(void *rfp_start_val,
			     struct rfapi_rfp_cb_methods *methods)
{
	struct rfapi *h;
	struct bgp *bgp;

	bgp = rfapi_bgp_lookup_by_rfp(rfp_start_val);
	if (!bgp)
		return ENXIO;

	h = bgp->rfapi;
	if (!h)
		return ENXIO;

	h->rfp_methods = *methods;

	return 0;
}

/***********************************************************************
 *			NVE Sessions
 ***********************************************************************/
/*
 * Caller must supply an already-allocated rfd with the "caller"
 * fields already set (vn_addr, un_addr, callback, cookie)
 * The advertised_prefixes[] array elements should be NULL to
 * have this function set them to newly-allocated radix trees.
 */
static int rfapi_open_inner(struct rfapi_descriptor *rfd, struct bgp *bgp,
			    struct rfapi *h, struct rfapi_nve_group_cfg *rfg)
{
	int ret;

	if (h->flags & RFAPI_INCALLBACK)
		return EDEADLK;

	/*
	 * Fill in configured fields
	 */

	/*
	 * If group's RD is specified as "auto", then fill in based
	 * on NVE's VN address
	 */
	rfd->rd = rfg->rd;

	if (rfd->rd.family == AF_UNIX) {
		ret = rfapi_set_autord_from_vn(&rfd->rd, &rfd->vn_addr);
		if (ret != 0)
			return ret;
	}
	rfd->rt_export_list = (rfg->rt_export_list)
				      ? ecommunity_dup(rfg->rt_export_list)
				      : NULL;
	rfd->response_lifetime = rfg->response_lifetime;
	rfd->rfg = rfg;

	/*
	 * Fill in BGP peer structure
	 */
	rfd->peer = peer_new(bgp);
	rfd->peer->connection->status = Established; /* keep bgp core happy */

	bgp_peer_connection_buffers_free(rfd->peer->connection);

	{ /* base code assumes have valid host pointer */
		char buf[INET6_ADDRSTRLEN];
		buf[0] = 0;

		if (rfd->vn_addr.addr_family == AF_INET) {
			inet_ntop(AF_INET, &rfd->vn_addr.addr.v4, buf,
				  sizeof(buf));
		} else if (rfd->vn_addr.addr_family == AF_INET6) {
			inet_ntop(AF_INET6, &rfd->vn_addr.addr.v6, buf,
				  sizeof(buf));
		}
		rfd->peer->host = XSTRDUP(MTYPE_BGP_PEER_HOST, buf);
	}
	/* Mark peer as belonging to HD */
	SET_FLAG(rfd->peer->flags, PEER_FLAG_IS_RFAPI_HD);

	/*
	 * Set min prefix lifetime to max value so it will get set
	 * upon first rfapi_register()
	 */
	rfd->min_prefix_lifetime = UINT32_MAX;

/*
 * Allocate response tables if needed
 */
#define RFD_RTINIT_AFI(rh, ary, afi)                                           \
	do {                                                                   \
		if (!ary[afi]) {                                               \
			ary[afi] = agg_table_init();                           \
			agg_set_table_info(ary[afi], rh);                      \
		}                                                              \
	} while (0)

#define RFD_RTINIT(rh, ary)                                                    \
	do {                                                                   \
		RFD_RTINIT_AFI(rh, ary, AFI_IP);                               \
		RFD_RTINIT_AFI(rh, ary, AFI_IP6);                              \
		RFD_RTINIT_AFI(rh, ary, AFI_L2VPN);                            \
	} while (0)

	RFD_RTINIT(rfd, rfd->rib);
	RFD_RTINIT(rfd, rfd->rib_pending);
	RFD_RTINIT(rfd, rfd->rsp_times);

	/*
	 * Link to Import Table
	 */
	rfd->import_table = rfg->rfapi_import_table;
	rfd->import_table->refcount += 1;

	rfapiApInit(&rfd->advertised);

	/*
	 * add this NVE descriptor to the list of NVEs in the NVE group
	 */
	if (!rfg->nves) {
		rfg->nves = list_new();
	}
	listnode_add(rfg->nves, rfd);

	vnc_direct_bgp_add_nve(bgp, rfd);
	vnc_zebra_add_nve(bgp, rfd);

	return 0;
}

/* moved from rfapi_register */
int rfapi_init_and_open(struct bgp *bgp, struct rfapi_descriptor *rfd,
			struct rfapi_nve_group_cfg *rfg)
{
	struct rfapi *h = bgp->rfapi;
	char buf_vn[BUFSIZ];
	char buf_un[BUFSIZ];
	afi_t afi_vn, afi_un;
	struct prefix pfx_un;
	struct agg_node *rn;

	rfd->open_time = monotime(NULL);

	if (rfg->type == RFAPI_GROUP_CFG_VRF)
		SET_FLAG(rfd->flags, RFAPI_HD_FLAG_IS_VRF);

	rfapiRfapiIpAddr2Str(&rfd->vn_addr, buf_vn, BUFSIZ);
	rfapiRfapiIpAddr2Str(&rfd->un_addr, buf_un, BUFSIZ);

	vnc_zlog_debug_verbose("%s: new RFD with VN=%s UN=%s cookie=%p",
			       __func__, buf_vn, buf_un, rfd->cookie);

	if (rfg->type != RFAPI_GROUP_CFG_VRF) /* unclear if needed for VRF */
	{
		listnode_add(&h->descriptors, rfd);
		if (h->descriptors.count > h->stat.max_descriptors) {
			h->stat.max_descriptors = h->descriptors.count;
		}

		/*
		 * attach to UN radix tree
		 */
		afi_vn = family2afi(rfd->vn_addr.addr_family);
		afi_un = family2afi(rfd->un_addr.addr_family);
		assert(afi_vn && afi_un);
		assert(!rfapiRaddr2Qprefix(&rfd->un_addr, &pfx_un));

		rn = agg_node_get(h->un[afi_un], &pfx_un);
		assert(rn);
		rfd->next = rn->info;
		rn->info = rfd;
		rfd->un_node = rn;
	}
	return rfapi_open_inner(rfd, bgp, h, rfg);
}

struct rfapi_vn_option *rfapiVnOptionsDup(struct rfapi_vn_option *orig)
{
	struct rfapi_vn_option *head = NULL;
	struct rfapi_vn_option *tail = NULL;
	struct rfapi_vn_option *vo = NULL;

	for (vo = orig; vo; vo = vo->next) {
		struct rfapi_vn_option *new;

		new = XCALLOC(MTYPE_RFAPI_VN_OPTION,
			      sizeof(struct rfapi_vn_option));
		memcpy(new, vo, sizeof(struct rfapi_vn_option));
		new->next = NULL;

		if (tail) {
			tail->next = new;
		} else {
			head = tail = new;
		}
	}
	return head;
}

struct rfapi_un_option *rfapiUnOptionsDup(struct rfapi_un_option *orig)
{
	struct rfapi_un_option *head = NULL;
	struct rfapi_un_option *tail = NULL;
	struct rfapi_un_option *uo = NULL;

	for (uo = orig; uo; uo = uo->next) {
		struct rfapi_un_option *new;

		new = XCALLOC(MTYPE_RFAPI_UN_OPTION,
			      sizeof(struct rfapi_un_option));
		memcpy(new, uo, sizeof(struct rfapi_un_option));
		new->next = NULL;

		if (tail) {
			tail->next = new;
		} else {
			head = tail = new;
		}
	}
	return head;
}

struct bgp_tea_options *rfapiOptionsDup(struct bgp_tea_options *orig)
{
	struct bgp_tea_options *head = NULL;
	struct bgp_tea_options *tail = NULL;
	struct bgp_tea_options *hop = NULL;

	for (hop = orig; hop; hop = hop->next) {
		struct bgp_tea_options *new;

		new = XCALLOC(MTYPE_BGP_TEA_OPTIONS,
			      sizeof(struct bgp_tea_options));
		memcpy(new, hop, sizeof(struct bgp_tea_options));
		new->next = NULL;
		if (hop->value) {
			new->value = XCALLOC(MTYPE_BGP_TEA_OPTIONS_VALUE,
					     hop->length);
			memcpy(new->value, hop->value, hop->length);
		}
		if (tail) {
			tail->next = new;
		} else {
			head = tail = new;
		}
	}
	return head;
}

void rfapiFreeBgpTeaOptionChain(struct bgp_tea_options *p)
{
	struct bgp_tea_options *next;

	while (p) {
		next = p->next;

		XFREE(MTYPE_BGP_TEA_OPTIONS_VALUE, p->value);
		XFREE(MTYPE_BGP_TEA_OPTIONS, p);

		p = next;
	}
}

void rfapiAdbFree(struct rfapi_adb *adb)
{
	XFREE(MTYPE_RFAPI_ADB, adb);
}

static int
rfapi_query_inner(void *handle, struct rfapi_ip_addr *target,
		  struct rfapi_l2address_option *l2o, /* may be NULL */
		  struct rfapi_next_hop_entry **ppNextHopEntry)
{
	afi_t afi;
	struct prefix p;
	struct prefix p_original;
	struct agg_node *rn;
	struct rfapi_descriptor *rfd = (struct rfapi_descriptor *)handle;
	struct bgp *bgp = rfd->bgp;
	struct rfapi_next_hop_entry *pNHE = NULL;
	struct rfapi_ip_addr *self_vn_addr = NULL;
	int eth_is_0 = 0;
	int use_eth_resolution = 0;
	struct rfapi_next_hop_entry *i_nhe;

	/* preemptive */
	if (!bgp) {
		vnc_zlog_debug_verbose("%s: No BGP instance, returning ENXIO",
				       __func__);
		return ENXIO;
	}
	if (!bgp->rfapi) {
		vnc_zlog_debug_verbose("%s: No RFAPI instance, returning ENXIO",
				       __func__);
		return ENXIO;
	}
	if (bgp->rfapi->flags & RFAPI_INCALLBACK) {
		vnc_zlog_debug_verbose(
			"%s: Called during calback, returning EDEADLK",
			__func__);
		return EDEADLK;
	}

	if (!is_valid_rfd(rfd)) {
		vnc_zlog_debug_verbose("%s: invalid handle, returning EBADF",
				       __func__);
		return EBADF;
	}

	rfd->rsp_counter++;		  /* dedup: identify this generation */
	rfd->rsp_time = monotime(NULL);	  /* response content dedup */
	rfd->ftd_last_allowed_time =
		monotime(NULL) -
		bgp->rfapi_cfg->rfp_cfg.ftd_advertisement_interval;

	if (l2o) {
		if (!memcmp(l2o->macaddr.octet, rfapi_ethaddr0.octet,
			    ETH_ALEN)) {
			eth_is_0 = 1;
		}
		/* per t/c Paul/Lou 151022 */
		if (!eth_is_0 || l2o->logical_net_id) {
			use_eth_resolution = 1;
		}
	}

	if (ppNextHopEntry)
		*ppNextHopEntry = NULL;

	/*
	 * Save original target in prefix form. In case of L2-based queries,
	 * p_original will be modified to reflect the L2 target
	 */
	assert(!rfapiRaddr2Qprefix(target, &p_original));

	if (bgp->rfapi_cfg->rfp_cfg.download_type == RFAPI_RFP_DOWNLOAD_FULL) {
		/* convert query to 0/0 when full-table download is enabled */
		memset((char *)&p, 0, sizeof(p));
		p.family = target->addr_family;
	} else {
		p = p_original;
	}

	{
		char *s;

		vnc_zlog_debug_verbose("%s(rfd=%p, target=%pFX, ppNextHop=%p)",
				       __func__, rfd, &p, ppNextHopEntry);

		s = ecommunity_ecom2str(rfd->import_table->rt_import_list,
					ECOMMUNITY_FORMAT_ROUTE_MAP, 0);
		vnc_zlog_debug_verbose(
			"%s rfd->import_table=%p, rfd->import_table->rt_import_list: %s",
			__func__, rfd->import_table, s);
		XFREE(MTYPE_ECOMMUNITY_STR, s);
	}

	afi = family2afi(p.family);
	assert(afi);

	if (CHECK_FLAG(bgp->rfapi_cfg->flags,
		       BGP_VNC_CONFIG_FILTER_SELF_FROM_RSP)) {
		self_vn_addr = &rfd->vn_addr;
	}

	if (use_eth_resolution) {
		uint32_t logical_net_id = l2o->logical_net_id;
		struct ecommunity *l2com;

		/*
		 * fix up p_original to contain L2 address
		 */
		rfapiL2o2Qprefix(l2o, &p_original);

		l2com = bgp_rfapi_get_ecommunity_by_lni_label(
			bgp, 1, logical_net_id, l2o->label);
		if (l2com) {
			uint8_t *v = l2com->val;
			logical_net_id = (v[5] << 16) + (v[6] << 8) + (v[7]);
		}
		/*
		 * Ethernet/L2-based lookup
		 *
		 * Always returns IT node corresponding to route
		 */

		if (RFAPI_RFP_DOWNLOAD_FULL
		    == bgp->rfapi_cfg->rfp_cfg.download_type) {
			eth_is_0 = 1;
		}

		rn = rfapiMonitorEthAdd(
			bgp, rfd, (eth_is_0 ? &rfapi_ethaddr0 : &l2o->macaddr),
			logical_net_id);

		if (eth_is_0) {
			struct rfapi_ip_prefix rprefix;

			memset(&rprefix, 0, sizeof(rprefix));
			rprefix.prefix.addr_family = target->addr_family;
			if (target->addr_family == AF_INET) {
				rprefix.length = IPV4_MAX_BITLEN;
			} else {
				rprefix.length = IPV6_MAX_BITLEN;
			}

			pNHE = rfapiEthRouteTable2NextHopList(
				logical_net_id, &rprefix,
				rfd->response_lifetime, self_vn_addr,
				rfd->rib[afi], &p_original);
			goto done;
		}

	} else {

		/*
		 * IP-based lookup
		 */

		rn = rfapiMonitorAdd(bgp, rfd, &p);

		/*
		 * If target address is 0, this request is special: means to
		 * return ALL routes in the table
		 *
		 * Monitors for All-Routes queries get put on a special list,
		 * not in the VPN tree
		 */
		if (RFAPI_0_PREFIX(&p)) {

			vnc_zlog_debug_verbose("%s: 0-prefix", __func__);

			/*
			 * Generate nexthop list for caller
			 */
			pNHE = rfapiRouteTable2NextHopList(
				rfd->import_table->imported_vpn[afi],
				rfd->response_lifetime, self_vn_addr,
				rfd->rib[afi], &p_original);
			goto done;
		}

		if (rn) {
			agg_lock_node(rn); /* so we can unlock below */
		} else {
			/*
			 * returns locked node. Don't unlock yet because the
			 * unlock
			 * might free it before we're done with it. This
			 * situation
			 * could occur when rfapiMonitorGetAttachNode() returns
			 * a
			 * newly-created default node.
			 */
			rn = rfapiMonitorGetAttachNode(rfd, &p);
		}
	}

	assert(rn);
	if (!rn->info) {
		agg_unlock_node(rn);
		vnc_zlog_debug_verbose(
			"%s: VPN route not found, returning ENOENT", __func__);
		return ENOENT;
	}

	if (VNC_DEBUG(RFAPI_QUERY)) {
		rfapiShowImportTable(NULL, "query",
				     rfd->import_table->imported_vpn[afi], 1);
	}

	if (use_eth_resolution) {

		struct rfapi_ip_prefix rprefix;

		memset(&rprefix, 0, sizeof(rprefix));
		rprefix.prefix.addr_family = target->addr_family;
		if (target->addr_family == AF_INET) {
			rprefix.length = IPV4_MAX_BITLEN;
		} else {
			rprefix.length = IPV6_MAX_BITLEN;
		}

		pNHE = rfapiEthRouteNode2NextHopList(
			rn, &rprefix, rfd->response_lifetime, self_vn_addr,
			rfd->rib[afi], &p_original);


	} else {
		/*
		 * Generate answer to query
		 */
		pNHE = rfapiRouteNode2NextHopList(rn, rfd->response_lifetime,
						  self_vn_addr, rfd->rib[afi],
						  &p_original);
	}

	agg_unlock_node(rn);

done:
	if (ppNextHopEntry) {
		/* only count if caller gets it */
		++bgp->rfapi->response_immediate_count;
	}

	if (!pNHE) {
		vnc_zlog_debug_verbose("%s: NO NHEs, returning ENOENT",
				       __func__);
		return ENOENT;
	}

	/*
	 * count nexthops for statistics
	 */
	for (i_nhe = pNHE; i_nhe; i_nhe = i_nhe->next) {
		++rfd->stat_count_nh_reachable;
	}

	if (ppNextHopEntry) {
		*ppNextHopEntry = pNHE;
	} else {
		rfapi_free_next_hop_list(pNHE);
	}

	vnc_zlog_debug_verbose("%s: success", __func__);
	return 0;
}

/*
 * support on-the-fly reassignment of an already-open nve to a new
 * nve-group in the event that its original nve-group is
 * administratively deleted.
 */
static int rfapi_open_rfd(struct rfapi_descriptor *rfd, struct bgp *bgp)
{
	struct prefix pfx_vn;
	struct prefix pfx_un;
	struct rfapi_nve_group_cfg *rfg;
	struct rfapi *h;
	struct rfapi_cfg *hc;
	int rc;

	h = bgp->rfapi;
	if (!h)
		return ENXIO;

	hc = bgp->rfapi_cfg;
	if (!hc)
		return ENXIO;

	rc = rfapiRaddr2Qprefix(&rfd->vn_addr, &pfx_vn);
	assert(!rc);

	rc = rfapiRaddr2Qprefix(&rfd->un_addr, &pfx_un);
	assert(!rc);

	/*
	 * Find the matching nve group config block
	 */
	rfg = bgp_rfapi_cfg_match_group(hc, &pfx_vn, &pfx_un);
	if (!rfg) {
		return ENOENT;
	}

	/*
	 * check nve group config block for required values
	 */
	if (!rfg->rt_export_list || !rfg->rfapi_import_table) {

		return ENOMSG;
	}

	rc = rfapi_open_inner(rfd, bgp, h, rfg);
	if (rc) {
		return rc;
	}

	/*
	 * re-advertise registered routes, this time as part of new NVE-group
	 */
	rfapiApReadvertiseAll(bgp, rfd);

	/*
	 * re-attach callbacks to import table
	 */
	if (!(bgp->rfapi_cfg->flags & BGP_VNC_CONFIG_CALLBACK_DISABLE)) {
		rfapiMonitorAttachImportHd(rfd);
	}

	return 0;
}

/*------------------------------------------
 * rfapi_open
 *
 * This function initializes a NVE record and associates it with
 * the specified VN and underlay network addresses
 *
 * input:
 *      rfp_start_val   value returned by rfp_start
 *	vn		NVE virtual network address
 *
 *	un		NVE underlay network address
 *
 *	default_options	Default options to use on registrations.
 *			For now only tunnel type is supported.
 *			May be overridden per-prefix in rfapi_register().
 *			Caller owns (rfapi_open() does not free)
 *
 *	response_cb	Pointer to next hop list update callback function or
 *			NULL when no callbacks are desired.
 *
 *	userdata	Passed to subsequent response_cb invocations.
 *
 * output:
 *	response_lifetime The length of time that responses sent to this
 *			NVE are valid.
 *
 *	pHandle		pointer to location to store rfapi handle. The
 *			handle must be passed on subsequent rfapi_ calls.
 *
 *
 * return value:
 *	0		Success
 *	EEXIST		NVE with this {vn,un} already open
 *	ENOENT		No matching nve group config
 *	ENOMSG		Matched nve group config was incomplete
 *	ENXIO		BGP or VNC not configured
 *	EAFNOSUPPORT	Matched nve group specifies auto-assignment of RD,
 *			but underlay network address is not IPv4
 *	EDEADLK		Called from within a callback procedure
 *------------------------------------------*/
int rfapi_open(void *rfp_start_val, struct rfapi_ip_addr *vn,
	       struct rfapi_ip_addr *un,
	       struct rfapi_un_option *default_options,
	       uint32_t *response_lifetime,
	       void *userdata, /* callback cookie */
	       rfapi_handle *pHandle)
{
	struct bgp *bgp;
	struct rfapi *h;
	struct rfapi_descriptor *rfd;
	struct rfapi_cfg *hc;
	struct rfapi_nve_group_cfg *rfg;

	struct prefix pfx_vn;
	struct prefix pfx_un;

	int rc;
	rfapi_handle hh = NULL;
	int reusing_provisional = 0;

	{
		char buf[2][INET_ADDRSTRLEN];
		vnc_zlog_debug_verbose(
			"%s: VN=%s UN=%s", __func__,
			rfapiRfapiIpAddr2Str(vn, buf[0], INET_ADDRSTRLEN),
			rfapiRfapiIpAddr2Str(un, buf[1], INET_ADDRSTRLEN));
	}

	assert(pHandle);
	*pHandle = NULL;

	bgp = rfapi_bgp_lookup_by_rfp(rfp_start_val);
	if (!bgp)
		return ENXIO;

	h = bgp->rfapi;
	if (!h)
		return ENXIO;

	hc = bgp->rfapi_cfg;
	if (!hc)
		return ENXIO;

	if (h->flags & RFAPI_INCALLBACK)
		return EDEADLK;

	rc = rfapiRaddr2Qprefix(vn, &pfx_vn);
	assert(!rc);

	rc = rfapiRaddr2Qprefix(un, &pfx_un);
	assert(!rc);

	/*
	 * already have a descriptor with VN and UN?
	 */
	if (!rfapi_find_handle(bgp, vn, un, &hh)) {
		/*
		 * we might have set up a handle for static routes before
		 * this NVE was opened. In that case, reuse the handle
		 */
		rfd = hh;
		if (!CHECK_FLAG(rfd->flags, RFAPI_HD_FLAG_PROVISIONAL)) {
			return EEXIST;
		}

		/*
		 * reuse provisional descriptor
		 * hh is not NULL
		 */
		reusing_provisional = 1;
	}

	/*
	 * Find the matching nve group config block
	 */
	rfg = bgp_rfapi_cfg_match_group(hc, &pfx_vn, &pfx_un);
	if (!rfg) {
		++h->stat.count_unknown_nves;
		{
			char buf[2][INET_ADDRSTRLEN];
			zlog_notice("%s: no matching group VN=%s UN=%s",
				    __func__,
				    rfapiRfapiIpAddr2Str(vn, buf[0],
							 INET_ADDRSTRLEN),
				    rfapiRfapiIpAddr2Str(un, buf[1],
							 INET_ADDRSTRLEN));
		}
		return ENOENT;
	}

	/*
	 * check nve group config block for required values
	 */
	if (!rfg->rt_export_list || !rfg->rfapi_import_table) {

		++h->stat.count_unknown_nves;
		return ENOMSG;
	}

	/*
	 * If group config specifies auto-rd assignment, check that
	 * VN address is IPv4|v6 so we don't fail in rfapi_open_inner().
	 * Check here so we don't need to unwind memory allocations, &c.
	 */
	if ((rfg->rd.family == AF_UNIX) && (vn->addr_family != AF_INET)
	    && (vn->addr_family != AF_INET6)) {
		return EAFNOSUPPORT;
	}

	if (hh) {
		/*
		 * reusing provisional rfd
		 */
		rfd = hh;
	} else {
		rfd = XCALLOC(MTYPE_RFAPI_DESC,
			      sizeof(struct rfapi_descriptor));
	}

	rfd->bgp = bgp;
	if (default_options) {
		struct rfapi_un_option *p;

		for (p = default_options; p; p = p->next) {
			if ((RFAPI_UN_OPTION_TYPE_PROVISIONAL == p->type)) {
				rfd->flags |= RFAPI_HD_FLAG_PROVISIONAL;
			}
			if ((RFAPI_UN_OPTION_TYPE_TUNNELTYPE == p->type)) {
				rfd->default_tunneltype_option = p->v.tunnel;
			}
		}
	}

	/*
	 * Fill in caller fields
	 */
	rfd->vn_addr = *vn;
	rfd->un_addr = *un;
	rfd->cookie = userdata;

	if (!reusing_provisional) {
		rc = rfapi_init_and_open(bgp, rfd, rfg);
		/*
		 * This can fail only if the VN address is IPv6 and the group
		 * specified auto-assignment of RDs, which only works for v4,
		 * and the check above should catch it.
		 *
		 * Another failure possibility is that we were called
		 * during an rfapi callback. Also checked above.
		 */
		assert(!rc);
	}

	if (response_lifetime)
		*response_lifetime = rfd->response_lifetime;
	*pHandle = rfd;
	return 0;
}

/*
 * For use with debug functions
 */
static int rfapi_set_response_cb(struct rfapi_descriptor *rfd,
				 rfapi_response_cb_t *response_cb)
{
	if (!is_valid_rfd(rfd))
		return EBADF;
	rfd->response_cb = response_cb;
	return 0;
}

/*
 * rfapi_close_inner
 *
 * Does almost all the work of rfapi_close, except:
 *	1. preserves the descriptor (doesn't free it)
 *	2. preserves the prefix query list (i.e., rfd->mon list)
 *	3. preserves the advertised prefix list (rfd->advertised)
 *	4. preserves the rib and rib_pending tables
 *
 * The purpose of organizing it this way is to support on-the-fly
 * reassignment of an already-open nve to a new nve-group in the
 * event that its original nve-group is administratively deleted.
 */
static int rfapi_close_inner(struct rfapi_descriptor *rfd, struct bgp *bgp)
{
	int rc;
	struct prefix pfx_vn;
	struct prefix_rd prd; /* currently always 0 for VN->UN */

	if (!is_valid_rfd(rfd))
		return EBADF;

	rc = rfapiRaddr2Qprefix(&rfd->vn_addr, &pfx_vn);
	assert(!rc); /* should never have bad AF in stored vn address */

	/*
	 * update exported routes to reflect disappearance of this NVE as
	 * nexthop
	 */
	vnc_direct_bgp_del_nve(bgp, rfd);
	vnc_zebra_del_nve(bgp, rfd);

	/*
	 * unlink this HD's monitors from import table
	 */
	rfapiMonitorDetachImportHd(rfd);

	/*
	 * Unlink from Import Table
	 * NB rfd->import_table will be NULL if we are closing a stale
	 * descriptor
	 */
	if (rfd->import_table)
		rfapiImportTableRefDelByIt(bgp, rfd->import_table);
	rfd->import_table = NULL;

	/*
	 * Construct route distinguisher
	 */
	memset(&prd, 0, sizeof(prd));
	prd = rfd->rd;
	prd.family = AF_UNSPEC;
	prd.prefixlen = 64;

	/*
	 * withdraw tunnel
	 */
	del_vnc_route(rfd, rfd->peer, bgp, SAFI_ENCAP,
		      &pfx_vn, /* prefix being advertised */
		      &prd,    /* route distinguisher to use (0 for ENCAP) */
		      ZEBRA_ROUTE_BGP, BGP_ROUTE_RFP, NULL, 0); /* no kill */

	/*
	 * Construct route distinguisher for VPN routes
	 */
	prd = rfd->rd;
	prd.family = AF_UNSPEC;
	prd.prefixlen = 64;

	/*
	 * find all VPN routes associated with this rfd and delete them, too
	 */
	rfapiApWithdrawAll(bgp, rfd);

	/*
	 * remove this nve descriptor from the list of nves
	 * associated with the nve group
	 */
	if (rfd->rfg) {
		listnode_delete(rfd->rfg->nves, rfd);
		rfd->rfg = NULL; /* XXX mark as orphaned/stale */
	}

	if (rfd->rt_export_list)
		ecommunity_free(&rfd->rt_export_list);
	rfd->rt_export_list = NULL;

	/*
	 * free peer structure (possibly delayed until its
	 * refcount reaches zero)
	 */
	if (rfd->peer) {
		vnc_zlog_debug_verbose("%s: calling peer_delete(%p), #%d",
				       __func__, rfd->peer, rfd->peer->lock);
		peer_delete(rfd->peer);
	}
	rfd->peer = NULL;

	return 0;
}

int rfapi_close(void *handle)
{
	struct rfapi_descriptor *rfd = (struct rfapi_descriptor *)handle;
	int rc;
	struct agg_node *node;
	struct bgp *bgp;
	struct rfapi *h;

	vnc_zlog_debug_verbose("%s: rfd=%p", __func__, rfd);

#ifdef RFAPI_WHO_IS_CALLING_ME
#ifdef HAVE_GLIBC_BACKTRACE
#define RFAPI_DEBUG_BACKTRACE_NENTRIES 5
	{
		void *buf[RFAPI_DEBUG_BACKTRACE_NENTRIES];
		char **syms;
		int i;
		size_t size;

		size = backtrace(buf, RFAPI_DEBUG_BACKTRACE_NENTRIES);
		syms = backtrace_symbols(buf, size);
		for (i = 0; i < size && i < RFAPI_DEBUG_BACKTRACE_NENTRIES;
		     ++i) {
			vnc_zlog_debug_verbose("backtrace[%2d]: %s", i,
					       syms[i]);
		}
		free(syms);
	}
#endif
#endif

	bgp = rfd->bgp;
	if (!bgp)
		return ENXIO;

	h = bgp->rfapi;
	if (!h)
		return ENXIO;

	if (!is_valid_rfd(rfd))
		return EBADF;

	if (h->flags & RFAPI_INCALLBACK) {
		/*
		 * Queue these close requests for processing after callback
		 * is finished
		 */
		if (!CHECK_FLAG(rfd->flags,
				RFAPI_HD_FLAG_CLOSING_ADMINISTRATIVELY)) {
			work_queue_add(h->deferred_close_q, handle);
			vnc_zlog_debug_verbose(
				"%s: added handle %p to deferred close queue",
				__func__, handle);
		}
		return 0;
	}

	if (CHECK_FLAG(rfd->flags, RFAPI_HD_FLAG_CLOSING_ADMINISTRATIVELY)) {

		vnc_zlog_debug_verbose("%s administrative close rfd=%p",
				       __func__, rfd);

		if (h->rfp_methods.close_cb) {
			vnc_zlog_debug_verbose(
				"%s calling close callback rfd=%p", __func__,
				rfd);

			/*
			 * call the callback fairly early so that it can still
			 * lookup un/vn
			 * from handle, etc.
			 *
			 * NB RFAPI_INCALLBACK is tested above, so if we reach
			 * this point
			 * we are not already in the context of a callback.
			 */
			h->flags |= RFAPI_INCALLBACK;
			(*h->rfp_methods.close_cb)(handle, EIDRM);
			h->flags &= ~RFAPI_INCALLBACK;
		}
	}

	if (rfd->rfg) {
		/*
		 * Orphaned descriptors have already done this part, so do
		 * only for non-orphaned descriptors.
		 */
		if ((rc = rfapi_close_inner(rfd, bgp)))
			return rc;
	}

	/*
	 * Remove descriptor from UN index
	 * (remove from chain at node)
	 */
	rc = rfapi_find_node(bgp, &rfd->vn_addr, &rfd->un_addr, &node);
	if (!rc) {
		struct rfapi_descriptor *hh;

		if (node->info == rfd) {
			node->info = rfd->next;
		} else {

			for (hh = node->info; hh; hh = hh->next) {
				if (hh->next == rfd) {
					hh->next = rfd->next;
					break;
				}
			}
		}
		agg_unlock_node(node);
	}

	/*
	 * remove from descriptor list
	 */
	listnode_delete(&h->descriptors, rfd);

	/*
	 * Delete monitor list items and free monitor structures
	 */
	(void)rfapiMonitorDelHd(rfd);

	/*
	 * release advertised prefix data
	 */
	rfapiApRelease(&rfd->advertised);

	/*
	 * Release RFP callback RIB
	 */
	rfapiRibFree(rfd);

	/*
	 * free descriptor
	 */
	memset(rfd, 0, sizeof(struct rfapi_descriptor));
	XFREE(MTYPE_RFAPI_DESC, rfd);

	return 0;
}

/*
 * Reopen a nve descriptor. If the descriptor's NVE-group
 * does not exist (e.g., if it has been administratively removed),
 * reassignment to a new NVE-group is attempted.
 *
 * If NVE-group reassignment fails, the descriptor becomes "stale"
 * (rfd->rfg == NULL implies "stale:). The only permissible API operation
 * on a stale descriptor is rfapi_close(). Any other rfapi_* API operation
 * on the descriptor will return ESTALE.
 *
 * Reopening a descriptor is a potentially expensive operation, because
 * it involves withdrawing any routes advertised by the NVE, withdrawing
 * the NVE's route queries, and then re-adding them all after a new
 * NVE-group is assigned. There are also possible route-export affects
 * caused by deleting and then adding the NVE: advertised prefixes
 * and nexthop lists for exported routes can turn over.
 */
int rfapi_reopen(struct rfapi_descriptor *rfd, struct bgp *bgp)
{
	struct rfapi *h;
	int rc;

	if ((rc = rfapi_close_inner(rfd, bgp))) {
		return rc;
	}
	if ((rc = rfapi_open_rfd(rfd, bgp))) {

		h = bgp->rfapi;

		assert(h != NULL && !CHECK_FLAG(h->flags, RFAPI_INCALLBACK));

		if (CHECK_FLAG(rfd->flags,
			       RFAPI_HD_FLAG_CLOSING_ADMINISTRATIVELY)
		    && h && h->rfp_methods.close_cb) {

			/*
			 * NB RFAPI_INCALLBACK is tested above, so if we reach
			 * this point
			 * we are not already in the context of a callback.
			 */
			h->flags |= RFAPI_INCALLBACK;
			(*h->rfp_methods.close_cb)((rfapi_handle)rfd, ESTALE);
			h->flags &= ~RFAPI_INCALLBACK;
		}
		return rc;
	}
	return 0;
}

/***********************************************************************
 *			NVE Routes
 ***********************************************************************/
/*
 * Announce reachability to this prefix via the NVE
 */
int rfapi_register(void *handle, struct rfapi_ip_prefix *prefix,
		   uint32_t lifetime, /* host byte order */
		   struct rfapi_un_option *options_un,
		   struct rfapi_vn_option *options_vn,
		   rfapi_register_action action)
{
	struct rfapi_descriptor *rfd = (struct rfapi_descriptor *)handle;
	struct bgp *bgp;
	struct prefix p;
	struct prefix *pfx_ip = NULL;
	struct prefix_rd prd;
	afi_t afi;
	struct prefix pfx_mac_buf;
	struct prefix *pfx_mac = NULL;
	struct prefix pfx_vn_buf;
	const char *action_str = NULL;
	uint32_t *label = NULL;
	struct rfapi_vn_option *vo;
	struct rfapi_l2address_option *l2o = NULL;
	struct prefix_rd *prd_override = NULL;

	switch (action) {
	case RFAPI_REGISTER_ADD:
		action_str = "add";
		break;
	case RFAPI_REGISTER_WITHDRAW:
		action_str = "withdraw";
		break;
	case RFAPI_REGISTER_KILL:
		action_str = "kill";
		break;
	default:
		assert(0);
		break;
	}

	/*
	 * Inspect VN options
	 */
	for (vo = options_vn; vo; vo = vo->next) {
		if (RFAPI_VN_OPTION_TYPE_L2ADDR == vo->type) {
			l2o = &vo->v.l2addr;
		}
		if (RFAPI_VN_OPTION_TYPE_INTERNAL_RD == vo->type) {
			prd_override = &vo->v.internal_rd;
		}
	}

	/*********************************************************************
	 *			advertise prefix
	 *********************************************************************/

	/*
	 * set <p> based on <prefix>
	 */
	assert(!rfapiRprefix2Qprefix(prefix, &p));

	afi = family2afi(prefix->prefix.addr_family);
	assert(afi);

	vnc_zlog_debug_verbose(
		"%s(rfd=%p, pfx=%pFX, lifetime=%d, opts_un=%p, opts_vn=%p, action=%s)",
		__func__, rfd, &p, lifetime, options_un, options_vn,
		action_str);

	/*
	 * These tests come after the prefix conversion so that we can
	 * print the prefix in a debug message before failing
	 */

	bgp = rfd->bgp;
	if (!bgp) {
		vnc_zlog_debug_verbose("%s: no BGP instance: returning ENXIO",
				       __func__);
		return ENXIO;
	}
	if (!bgp->rfapi) {
		vnc_zlog_debug_verbose("%s: no RFAPI instance: returning ENXIO",
				       __func__);
		return ENXIO;
	}
	if (!rfd->rfg) {
		if (RFAPI_REGISTER_ADD == action) {
			++bgp->rfapi->stat.count_registrations_failed;
		}
		vnc_zlog_debug_verbose(
			"%s: rfd=%p, no RF GRP instance: returning ESTALE",
			__func__, rfd);
		return ESTALE;
	}

	if (bgp->rfapi->flags & RFAPI_INCALLBACK) {
		if (RFAPI_REGISTER_ADD == action) {
			++bgp->rfapi->stat.count_registrations_failed;
		}
		vnc_zlog_debug_verbose("%s: in callback: returning EDEADLK",
				       __func__);
		return EDEADLK;
	}

	if (!is_valid_rfd(rfd)) {
		if (RFAPI_REGISTER_ADD == action) {
			++bgp->rfapi->stat.count_registrations_failed;
		}
		vnc_zlog_debug_verbose("%s: invalid handle: returning EBADF",
				       __func__);
		return EBADF;
	}

	/*
	 * Is there a MAC address in this registration?
	 */
	if (l2o && !RFAPI_0_ETHERADDR(&l2o->macaddr)) {
		rfapiL2o2Qprefix(l2o, &pfx_mac_buf);
		pfx_mac = &pfx_mac_buf;
	}

	/*
	 * Is there an IP prefix in this registration?
	 */
	if (!(RFAPI_0_PREFIX(&p) && RFAPI_HOST_PREFIX(&p))) {
		pfx_ip = &p;
	} else {
		if (!pfx_mac) {
			vnc_zlog_debug_verbose(
				"%s: missing mac addr that is required for host 0 pfx",
				__func__);
			if (RFAPI_REGISTER_ADD == action) {
				++bgp->rfapi->stat.count_registrations_failed;
			}
			return EINVAL;
		}
		if (rfapiRaddr2Qprefix(&rfd->vn_addr, &pfx_vn_buf)) {
			vnc_zlog_debug_verbose(
				"%s: handle has bad vn_addr: returning EBADF",
				__func__);
			if (RFAPI_REGISTER_ADD == action) {
				++bgp->rfapi->stat.count_registrations_failed;
			}
			return EBADF;
		}
	}

	if (RFAPI_REGISTER_ADD == action) {
		++bgp->rfapi->stat.count_registrations;
	}

	/*
	 * Figure out if this registration is missing an IP address
	 *
	 * MAC-addr based:
	 *
	 *  In RFAPI, we use prefixes in family AF_LINK to store
	 *  the MAC addresses. These prefixes are used for the
	 *  list of advertised prefixes and in the RFAPI import
	 *  tables.
	 *
	 *  In BGP proper, we use the prefix matching the NVE's
	 *  VN address with a host prefix-length (i.e., 32 or 128).
	 *
	 */
	if (l2o && l2o->logical_net_id && RFAPI_0_PREFIX(&p)
	    && RFAPI_HOST_PREFIX(&p)) {

		rfapiL2o2Qprefix(l2o, &pfx_mac_buf);
		pfx_mac = &pfx_mac_buf;
	}

	/*
	 * Construct route distinguisher
	 */
	if (prd_override) {
		prd = *prd_override;
	} else {
		memset(&prd, 0, sizeof(prd));
		if (pfx_mac) {
			prd.family = AF_UNSPEC;
			prd.prefixlen = 64;
			encode_rd_type(RD_TYPE_VNC_ETH, prd.val);
			if (l2o->local_nve_id
			    || !(rfd->rfg->flags & RFAPI_RFG_L2RD)) {
				/*
				 * If Local NVE ID is specified in message, use
				 * it.
				 * (if no local default configured, also use it
				 * even if 0)
				 */
				prd.val[1] = l2o->local_nve_id;
			} else {
				if (rfd->rfg->l2rd) {
					/*
					 * locally-configured literal value
					 */
					prd.val[1] = rfd->rfg->l2rd;
				} else {
					/*
					 * 0 means auto:vn, which means use LSB
					 * of VN addr
					 */
					if (rfd->vn_addr.addr_family
					    == AF_INET) {
						prd.val[1] =
							*(((char *)&rfd->vn_addr
								   .addr.v4
								   .s_addr)
							  + 3);
					} else {
						prd.val[1] =
							*(((char *)&rfd->vn_addr
								   .addr.v6
								   .s6_addr)
							  + 15);
					}
				}
			}
			memcpy(prd.val + 2, pfx_mac->u.prefix_eth.octet, 6);
		} else {
			prd = rfd->rd;
			prd.family = AF_UNSPEC;
			prd.prefixlen = 64;
		}
	}


	if (action == RFAPI_REGISTER_WITHDRAW
	    || action == RFAPI_REGISTER_KILL) {

		int adv_tunnel = 0;

		/*
		 * withdraw previous advertisement
		 */
		del_vnc_route(
			rfd, rfd->peer, bgp, SAFI_MPLS_VPN,
			pfx_ip ? pfx_ip
			       : &pfx_vn_buf, /* prefix being advertised */
			&prd, /* route distinguisher (0 for ENCAP) */
			ZEBRA_ROUTE_BGP, BGP_ROUTE_RFP, NULL,
			action == RFAPI_REGISTER_KILL);

		if (0 == rfapiApDelete(bgp, rfd, &p, pfx_mac, &prd,
				       &adv_tunnel)) {
			if (adv_tunnel)
				rfapiTunnelRouteAnnounce(
					bgp, rfd, &rfd->max_prefix_lifetime);
		}

	} else {

		int adv_tunnel = 0;
		uint32_t local_pref;
		struct ecommunity *rtlist = NULL;
		struct ecommunity_val ecom_value;

		if (!rfapiApCount(rfd)) {
			/*
			 * make sure we advertise tunnel route upon adding the
			 * first VPN route
			 */
			adv_tunnel = 1;
		}

		if (rfapiApAdd(bgp, rfd, &p, pfx_mac, &prd, lifetime,
			       prefix->cost, l2o)) {
			adv_tunnel = 1;
		}

		vnc_zlog_debug_verbose("%s: adv_tunnel = %d", __func__,
				       adv_tunnel);
		if (adv_tunnel) {
			vnc_zlog_debug_verbose("%s: announcing tunnel route",
					       __func__);
			rfapiTunnelRouteAnnounce(bgp, rfd,
						 &rfd->max_prefix_lifetime);
		}

		vnc_zlog_debug_verbose("%s: calling add_vnc_route", __func__);

		local_pref = rfp_cost_to_localpref(prefix->cost);

		if (l2o && l2o->label)
			label = &l2o->label;

		if (pfx_mac) {
			struct ecommunity *l2com = NULL;

			if (label) {
				l2com = bgp_rfapi_get_ecommunity_by_lni_label(
					bgp, 1, l2o->logical_net_id, *label);
			}
			if (l2com) {
				rtlist = ecommunity_dup(l2com);
			} else {
				/*
				 * If mac address is set, add an RT based on the
				 * registered LNI
				 */
				memset((char *)&ecom_value, 0,
				       sizeof(ecom_value));
				ecom_value.val[1] = ECOMMUNITY_ROUTE_TARGET;
				ecom_value.val[5] =
					(l2o->logical_net_id >> 16) & 0xff;
				ecom_value.val[6] =
					(l2o->logical_net_id >> 8) & 0xff;
				ecom_value.val[7] =
					(l2o->logical_net_id >> 0) & 0xff;
				rtlist = ecommunity_new();
				ecommunity_add_val(rtlist, &ecom_value,
						   false, false);
			}
			if (l2o->tag_id) {
				as_t as = bgp->as;
				uint16_t val = l2o->tag_id;
				memset((char *)&ecom_value, 0,
				       sizeof(ecom_value));
				ecom_value.val[1] = ECOMMUNITY_ROUTE_TARGET;
				if (as > BGP_AS_MAX) {
					ecom_value.val[0] =
						ECOMMUNITY_ENCODE_AS4;
					ecom_value.val[2] = (as >> 24) & 0xff;
					ecom_value.val[3] = (as >> 16) & 0xff;
					ecom_value.val[4] = (as >> 8) & 0xff;
					ecom_value.val[5] = as & 0xff;
				} else {
					ecom_value.val[0] =
						ECOMMUNITY_ENCODE_AS;
					ecom_value.val[2] = (as >> 8) & 0xff;
					ecom_value.val[3] = as & 0xff;
				}
				ecom_value.val[6] = (val >> 8) & 0xff;
				ecom_value.val[7] = val & 0xff;
				if (rtlist == NULL)
					rtlist = ecommunity_new();
				ecommunity_add_val(rtlist, &ecom_value,
						   false, false);
			}
		}

		/*
		 * advertise prefix via tunnel endpoint
		 */
		add_vnc_route(
			rfd, /* rfapi descr, for export list & backref */
			bgp, /* which bgp instance */
			SAFI_MPLS_VPN, /* which SAFI */
			(pfx_ip ? pfx_ip
				: &pfx_vn_buf), /* prefix being advertised */
			&prd, /* route distinguisher to use (0 for ENCAP) */
			&rfd->vn_addr, /* nexthop */
			&local_pref,
			&lifetime, /* prefix lifetime -> Tunnel Encap attr */
			NULL, options_un, /* rfapi un options */
			options_vn,       /* rfapi vn options */
			(rtlist ? rtlist : rfd->rt_export_list), NULL, /* med */
			label, /* label: default */
			ZEBRA_ROUTE_BGP, BGP_ROUTE_RFP, 0);

		if (rtlist)
			ecommunity_free(&rtlist); /* sets rtlist = NULL */
	}

	vnc_zlog_debug_verbose("%s: success", __func__);
	return 0;
}

int rfapi_query(void *handle, struct rfapi_ip_addr *target,
		struct rfapi_l2address_option *l2o, /* may be NULL */
		struct rfapi_next_hop_entry **ppNextHopEntry)
{
	struct rfapi_descriptor *rfd = (struct rfapi_descriptor *)handle;
	struct bgp *bgp = rfd->bgp;
	int rc;

	assert(ppNextHopEntry);
	*ppNextHopEntry = NULL;

	if (bgp && bgp->rfapi) {
		bgp->rfapi->stat.count_queries++;
	}

	if (!rfd->rfg) {
		if (bgp && bgp->rfapi)
			++bgp->rfapi->stat.count_queries_failed;
		return ESTALE;
	}

	if ((rc = rfapi_query_inner(handle, target, l2o, ppNextHopEntry))) {
		if (bgp && bgp->rfapi)
			++bgp->rfapi->stat.count_queries_failed;
	}
	return rc;
}

int rfapi_query_done(rfapi_handle handle, struct rfapi_ip_addr *target)
{
	struct prefix p;
	int rc;
	struct rfapi_descriptor *rfd = (struct rfapi_descriptor *)handle;
	struct bgp *bgp = rfd->bgp;

	if (!rfd->rfg)
		return ESTALE;

	assert(target);
	rc = rfapiRaddr2Qprefix(target, &p);
	assert(!rc);

	if (!is_valid_rfd(rfd))
		return EBADF;

	/* preemptive */
	if (!bgp || !bgp->rfapi)
		return ENXIO;

	if (bgp->rfapi->flags & RFAPI_INCALLBACK)
		return EDEADLK;

	rfapiMonitorDel(bgp, rfd, &p);

	return 0;
}

int rfapi_query_done_all(rfapi_handle handle, int *count)
{
	struct rfapi_descriptor *rfd = (struct rfapi_descriptor *)handle;
	struct bgp *bgp = rfd->bgp;
	;
	int num;

	if (!rfd->rfg)
		return ESTALE;

	if (!is_valid_rfd(rfd))
		return EBADF;

	/* preemptive */
	if (!bgp || !bgp->rfapi)
		return ENXIO;

	if (bgp->rfapi->flags & RFAPI_INCALLBACK)
		return EDEADLK;

	num = rfapiMonitorDelHd(rfd);

	if (count)
		*count = num;

	return 0;
}

void rfapi_free_next_hop_list(struct rfapi_next_hop_entry *list)
{
	struct rfapi_next_hop_entry *nh;
	struct rfapi_next_hop_entry *next;

	for (nh = list; nh; nh = next) {
		next = nh->next;
		rfapi_un_options_free(nh->un_options);
		nh->un_options = NULL;
		rfapi_vn_options_free(nh->vn_options);
		nh->vn_options = NULL;
		XFREE(MTYPE_RFAPI_NEXTHOP, nh);
	}
}

/*
 * NULL handle => return total count across all nves
 */
uint32_t rfapi_monitor_count(void *handle)
{
	struct bgp *bgp = bgp_get_default();
	uint32_t count;

	if (handle) {
		struct rfapi_descriptor *rfd =
			(struct rfapi_descriptor *)handle;
		count = rfd->monitor_count;
	} else {

		if (!bgp || !bgp->rfapi)
			return 0;

		count = bgp->rfapi->monitor_count;
	}

	return count;
}

/***********************************************************************
 *			CLI/CONFIG
 ***********************************************************************/

DEFUN (debug_rfapi_show_nves,
       debug_rfapi_show_nves_cmd,
       "debug rfapi-dev show nves",
       DEBUG_STR
       DEBUG_RFAPI_STR
       SHOW_STR
       "NVE Information\n")
{
	rfapiPrintMatchingDescriptors(vty, NULL, NULL);
	return CMD_SUCCESS;
}

DEFUN (
  debug_rfapi_show_nves_vn_un,
  debug_rfapi_show_nves_vn_un_cmd,
  "debug rfapi-dev show nves <vn|un> <A.B.C.D|X:X::X:X>", /* prefix also ok */
  DEBUG_STR
  DEBUG_RFAPI_STR
  SHOW_STR
  "NVE Information\n"
  "Specify virtual network\n"
  "Specify underlay network interface\n"
  "IPv4 address\n"
  "IPv6 address\n")
{
	struct prefix pfx;

	if (!str2prefix(argv[5]->arg, &pfx)) {
		vty_out(vty, "Malformed address \"%s\"\n", argv[5]->arg);
		return CMD_WARNING_CONFIG_FAILED;
	}
	if (pfx.family != AF_INET && pfx.family != AF_INET6) {
		vty_out(vty, "Invalid address \"%s\"\n", argv[5]->arg);
		return CMD_WARNING_CONFIG_FAILED;
	}

	if (argv[4]->arg[0] == 'u') {
		rfapiPrintMatchingDescriptors(vty, NULL, &pfx);
	} else {
		rfapiPrintMatchingDescriptors(vty, &pfx, NULL);
	}
	return CMD_SUCCESS;
}

/*
 * Note: this function does not flush vty output, so if it is called
 * with a stream pointing to a vty, the user will have to type something
 * before the callback output shows up
 */
static void test_nexthops_callback(
	//    struct rfapi_ip_addr        *target,
	struct rfapi_next_hop_entry *next_hops, void *userdata)
{
	void *stream = userdata;

	int (*fp)(void *, const char *, ...);
	struct vty *vty;
	void *out;
	const char *vty_newline;

	if (rfapiStream2Vty(stream, &fp, &vty, &out, &vty_newline) == 0)
		return;

	fp(out, "Nexthops Callback, Target=(");
	// rfapiPrintRfapiIpAddr(stream, target);
	fp(out, ")\n");

	rfapiPrintNhl(stream, next_hops);

	fp(out, "\n");

	rfapi_free_next_hop_list(next_hops);
}

DEFUN (debug_rfapi_open,
       debug_rfapi_open_cmd,
       "debug rfapi-dev open vn <A.B.C.D|X:X::X:X> un <A.B.C.D|X:X::X:X>",
       DEBUG_STR
       DEBUG_RFAPI_STR
       "rfapi_open\n"
       "indicate vn addr follows\n"
       "virtual network interface IPv4 address\n"
       "virtual network interface IPv6 address\n"
       "indicate xt addr follows\n"
       "underlay network interface IPv4 address\n"
       "underlay network interface IPv6 address\n")
{
	struct rfapi_ip_addr vn;
	struct rfapi_ip_addr un;
	uint32_t lifetime = 0;
	int rc;
	rfapi_handle handle;

	/*
	 * Get VN addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[4]->arg, &vn)))
		return rc;

	/*
	 * Get UN addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[6]->arg, &un)))
		return rc;

	rc = rfapi_open(rfapi_get_rfp_start_val_by_bgp(bgp_get_default()), &vn,
			&un, /*&uo */ NULL, &lifetime, NULL, &handle);

	vty_out(vty, "rfapi_open: status %d, handle %p, lifetime %d\n", rc,
		handle, lifetime);

	rc = rfapi_set_response_cb(handle, test_nexthops_callback);

	vty_out(vty, "rfapi_set_response_cb: status %d\n", rc);

	return CMD_SUCCESS;
}


DEFUN (debug_rfapi_close_vn_un,
       debug_rfapi_close_vn_un_cmd,
       "debug rfapi-dev close vn <A.B.C.D|X:X::X:X> un <A.B.C.D|X:X::X:X>",
       DEBUG_STR
       DEBUG_RFAPI_STR
       "rfapi_close\n"
       "indicate vn addr follows\n"
       "virtual network interface IPv4 address\n"
       "virtual network interface IPv6 address\n"
       "indicate xt addr follows\n"
       "underlay network interface IPv4 address\n"
       "underlay network interface IPv6 address\n")
{
	struct rfapi_ip_addr vn;
	struct rfapi_ip_addr un;
	rfapi_handle handle;
	int rc;

	/*
	 * Get VN addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[4]->arg, &vn)))
		return rc;


	/*
	 * Get UN addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[6]->arg, &un)))
		return rc;


	if (rfapi_find_handle_vty(vty, &vn, &un, &handle)) {
		vty_out(vty, "can't locate handle matching vn=%s, un=%s\n",
			argv[4]->arg, argv[6]->arg);
		return CMD_WARNING_CONFIG_FAILED;
	}

	rc = rfapi_close(handle);

	vty_out(vty, "rfapi_close(handle=%p): status %d\n", handle, rc);

	return CMD_SUCCESS;
}

DEFUN (debug_rfapi_close_rfd,
       debug_rfapi_close_rfd_cmd,
       "debug rfapi-dev close rfd HANDLE",
       DEBUG_STR
       DEBUG_RFAPI_STR
       "rfapi_close\n"
       "indicate handle follows\n" "rfapi handle in hexadecimal\n")
{
	rfapi_handle handle;
	int rc;
	char *endptr = NULL;

	handle = (rfapi_handle)(uintptr_t)(strtoull(argv[4]->arg, &endptr, 16));

	if (*endptr != '\0' || (uintptr_t)handle == UINTPTR_MAX) {
		vty_out(vty, "Invalid value: %s\n", argv[4]->arg);
		return CMD_WARNING_CONFIG_FAILED;
	}

	rc = rfapi_close(handle);

	vty_out(vty, "rfapi_close(handle=%p): status %d\n", handle, rc);

	return CMD_SUCCESS;
}

DEFUN (debug_rfapi_register_vn_un,
       debug_rfapi_register_vn_un_cmd,
       "debug rfapi-dev register vn <A.B.C.D|X:X::X:X> un <A.B.C.D|X:X::X:X> prefix <A.B.C.D/M|X:X::X:X/M> lifetime SECONDS [cost (0-255)]",
       DEBUG_STR
       DEBUG_RFAPI_STR
       "rfapi_register\n"
       "indicate vn addr follows\n"
       "virtual network IPv4 interface address\n"
       "virtual network IPv6 interface address\n"
       "indicate un addr follows\n"
       "underlay network IPv4 interface address\n"
       "underlay network IPv6 interface address\n"
       "indicate prefix follows\n"
       "IPv4 prefix\n"
       "IPv6 prefix\n"
       "indicate lifetime follows\n"
       "lifetime\n"
       "Cost (localpref = 255-cost)\n"
       "0-255\n")
{
	struct rfapi_ip_addr vn;
	struct rfapi_ip_addr un;
	rfapi_handle handle;
	struct prefix pfx;
	uint32_t lifetime;
	struct rfapi_ip_prefix hpfx;
	int rc;
	uint8_t cost = 100;

	/*
	 * Get VN addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[4]->arg, &vn)))
		return rc;


	/*
	 * Get UN addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[6]->arg, &un)))
		return rc;


	if (rfapi_find_handle_vty(vty, &vn, &un, &handle)) {
		vty_out(vty, "can't locate handle matching vn=%s, un=%s\n",
			argv[4]->arg, argv[6]->arg);
		return CMD_WARNING_CONFIG_FAILED;
	}

	/*
	 * Get prefix to advertise
	 */
	if (!str2prefix(argv[8]->arg, &pfx)) {
		vty_out(vty, "Malformed prefix \"%s\"\n", argv[8]->arg);
		return CMD_WARNING_CONFIG_FAILED;
	}
	if (pfx.family != AF_INET && pfx.family != AF_INET6) {
		vty_out(vty, "Bad family for prefix \"%s\"\n", argv[8]->arg);
		return CMD_WARNING_CONFIG_FAILED;
	}
	rfapiQprefix2Rprefix(&pfx, &hpfx);

	if (strmatch(argv[10]->text, "infinite")) {
		lifetime = RFAPI_INFINITE_LIFETIME;
	} else {
		lifetime = strtoul(argv[10]->arg, NULL, 10);
	}

	if (argc >= 13)
		cost = (uint8_t) strtoul(argv[12]->arg, NULL, 10);
	hpfx.cost = cost;

	rc = rfapi_register(handle, &hpfx, lifetime, NULL, NULL,
			    RFAPI_REGISTER_ADD);
	if (rc) {
		vty_out(vty, "rfapi_register failed with rc=%d (%s)\n", rc,
			strerror(rc));
	}

	return CMD_SUCCESS;
}

DEFUN (debug_rfapi_register_vn_un_l2o,
       debug_rfapi_register_vn_un_l2o_cmd,
       "debug rfapi-dev register vn <A.B.C.D|X:X::X:X> un <A.B.C.D|X:X::X:X> prefix <A.B.C.D/M|X:X::X:X/M> lifetime SECONDS macaddr X:X:X:X:X:X lni (0-16777215)",
       DEBUG_STR
       DEBUG_RFAPI_STR
       "rfapi_register\n"
       "indicate vn addr follows\n"
       "virtual network IPv4 interface address\n"
       "virtual network IPv6 interface address\n"
       "indicate un addr follows\n"
       "underlay network IPv4 interface address\n"
       "underlay network IPv6 interface address\n"
       "indicate prefix follows\n"
       "IPv4 prefix\n"
       "IPv6 prefix\n"
       "indicate lifetime follows\n"
       "Seconds of lifetime\n"
       "indicate MAC address follows\n"
       "MAC address\n"
       "indicate lni follows\n"
       "lni value range\n")
{
	struct rfapi_ip_addr vn;
	struct rfapi_ip_addr un;
	rfapi_handle handle;
	struct prefix pfx;
	uint32_t lifetime;
	struct rfapi_ip_prefix hpfx;
	int rc;
	struct rfapi_vn_option optary[10]; /* XXX must be big enough */
	struct rfapi_vn_option *opt = NULL;
	int opt_next = 0;

	/*
	 * Get VN addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[4]->arg, &vn)))
		return rc;


	/*
	 * Get UN addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[6]->arg, &un)))
		return rc;


	if (rfapi_find_handle_vty(vty, &vn, &un, &handle)) {
		vty_out(vty, "can't locate handle matching vn=%s, un=%s\n",
			argv[4]->arg, argv[6]->arg);
		return CMD_WARNING_CONFIG_FAILED;
	}

	/*
	 * Get prefix to advertise
	 */
	if (!str2prefix(argv[8]->arg, &pfx)) {
		vty_out(vty, "Malformed prefix \"%s\"\n", argv[8]->arg);
		return CMD_WARNING_CONFIG_FAILED;
	}
	if (pfx.family != AF_INET && pfx.family != AF_INET6) {
		vty_out(vty, "Bad family for prefix \"%s\"\n", argv[8]->arg);
		return CMD_WARNING_CONFIG_FAILED;
	}
	rfapiQprefix2Rprefix(&pfx, &hpfx);

	if (strmatch(argv[10]->text, "infinite")) {
		lifetime = RFAPI_INFINITE_LIFETIME;
	} else {
		lifetime = strtoul(argv[10]->arg, NULL, 10);
	}

	/* L2 option parsing START */
	memset(optary, 0, sizeof(optary));
	optary[opt_next].v.l2addr.logical_net_id =
		strtoul(argv[14]->arg, NULL, 10);
	if (rfapiStr2EthAddr(argv[12]->arg,
			     &optary[opt_next].v.l2addr.macaddr)) {
		vty_out(vty, "Bad mac address \"%s\"\n", argv[12]->arg);
		return CMD_WARNING_CONFIG_FAILED;
	}
	optary[opt_next].type = RFAPI_VN_OPTION_TYPE_L2ADDR;
	opt = optary;

	/* L2 option parsing END */

	/* TBD fixme */
	rc = rfapi_register(handle, &hpfx, lifetime, NULL /* &uo */, opt,
			    RFAPI_REGISTER_ADD);
	if (rc) {
		vty_out(vty, "rfapi_register failed with rc=%d (%s)\n", rc,
			strerror(rc));
	}

	return CMD_SUCCESS;
}


DEFUN (debug_rfapi_unregister_vn_un,
       debug_rfapi_unregister_vn_un_cmd,
       "debug rfapi-dev unregister vn <A.B.C.D|X:X::X:X> un <A.B.C.D|X:X::X:X> prefix <A.B.C.D/M|X:X::X:X/M> [kill]",
       DEBUG_STR
       DEBUG_RFAPI_STR
       "rfapi_unregister\n"
       "indicate vn addr follows\n"
       "virtual network interface address\n"
       "virtual network interface address\n"
       "indicate xt addr follows\n"
       "underlay network interface address\n"
       "underlay network interface address\n"
       "prefix to remove\n"
       "prefix to remove\n"
       "prefix to remove\n"
       "Remove without holddown\n")
{
	struct rfapi_ip_addr vn;
	struct rfapi_ip_addr un;
	rfapi_handle handle;
	struct prefix pfx;
	struct rfapi_ip_prefix hpfx;
	int rc;

	/*
	 * Get VN addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[4]->arg, &vn)))
		return rc;

	/*
	 * Get UN addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[6]->arg, &un)))
		return rc;


	if (rfapi_find_handle_vty(vty, &vn, &un, &handle)) {
		vty_out(vty, "can't locate handle matching vn=%s, un=%s\n",
			argv[4]->arg, argv[6]->arg);
		return CMD_WARNING_CONFIG_FAILED;
	}

	/*
	 * Get prefix to advertise
	 */
	if (!str2prefix(argv[8]->arg, &pfx)) {
		vty_out(vty, "Malformed prefix \"%s\"\n", argv[8]->arg);
		return CMD_WARNING_CONFIG_FAILED;
	}
	if (pfx.family != AF_INET && pfx.family != AF_INET6) {
		vty_out(vty, "Bad family for prefix \"%s\"\n", argv[8]->arg);
		return CMD_WARNING_CONFIG_FAILED;
	}
	rfapiQprefix2Rprefix(&pfx, &hpfx);

	rfapi_register(handle, &hpfx, 0, NULL, NULL,
		       (argc == 10 ?
			RFAPI_REGISTER_KILL : RFAPI_REGISTER_WITHDRAW));

	return CMD_SUCCESS;
}

DEFUN (debug_rfapi_query_vn_un,
       debug_rfapi_query_vn_un_cmd,
       "debug rfapi-dev query vn <A.B.C.D|X:X::X:X> un <A.B.C.D|X:X::X:X> target <A.B.C.D|X:X::X:X>",
       DEBUG_STR
       DEBUG_RFAPI_STR
       "rfapi_query\n"
       "indicate vn addr follows\n"
       "virtual network interface IPv4 address\n"
       "virtual network interface IPv6 address\n"
       "indicate un addr follows\n"
       "IPv4 un address\n"
       "IPv6 un address\n"
       "indicate target follows\n"
       "target IPv4 address\n"
       "target IPv6 address\n")
{
	struct rfapi_ip_addr vn;
	struct rfapi_ip_addr un;
	struct rfapi_ip_addr target;
	rfapi_handle handle;
	int rc;
	struct rfapi_next_hop_entry *pNextHopEntry;

	/*
	 * Get VN addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[4]->arg, &vn)))
		return rc;


	/*
	 * Get UN addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[6]->arg, &un)))
		return rc;


	/*
	 * Get target addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[8]->arg, &target)))
		return rc;


	if (rfapi_find_handle_vty(vty, &vn, &un, &handle)) {
		vty_out(vty, "can't locate handle matching vn=%s, un=%s\n",
			argv[4]->arg, argv[6]->arg);
		return CMD_WARNING_CONFIG_FAILED;
	}

	/*
	 * options parameter not used? Set to NULL for now
	 */
	rc = rfapi_query(handle, &target, NULL, &pNextHopEntry);

	if (rc) {
		vty_out(vty, "rfapi_query failed with rc=%d (%s)\n", rc,
			strerror(rc));
	} else {
		/*
		 * print nexthop list
		 */
		test_nexthops_callback(/*&target, */ pNextHopEntry,
				       vty); /* frees nh list! */
	}

	return CMD_SUCCESS;
}


DEFUN (debug_rfapi_query_vn_un_l2o,
       debug_rfapi_query_vn_un_l2o_cmd,
       "debug rfapi-dev query vn <A.B.C.D|X:X::X:X> un <A.B.C.D|X:X::X:X> lni LNI target X:X:X:X:X:X",
       DEBUG_STR
       DEBUG_RFAPI_STR
       "rfapi_query\n"
       "indicate vn addr follows\n"
       "virtual network interface IPv4 address\n"
       "virtual network interface IPv6 address\n"
       "indicate xt addr follows\n"
       "underlay network interface IPv4 address\n"
       "underlay network interface IPv6 address\n"
       "logical network ID follows\n"
       "logical network ID\n"
       "indicate target MAC addr follows\n"
       "target MAC addr\n")
{
	struct rfapi_ip_addr vn;
	struct rfapi_ip_addr un;
	int rc;

	/*
	 * Get VN addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[4]->arg, &vn)))
		return rc;


	/*
	 * Get UN addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[6]->arg, &un)))
		return rc;

	vty_out(vty, "%% This command is broken.\n");
	return CMD_WARNING_CONFIG_FAILED;
}


DEFUN (debug_rfapi_query_done_vn_un,
       debug_rfapi_query_vn_un_done_cmd,
       "debug rfapi-dev query done vn <A.B.C.D|X:X::X:X> un <A.B.C.D|X:X::X:X> target <A.B.C.D|X:X::X:X>",
       DEBUG_STR
       DEBUG_RFAPI_STR
       "rfapi_query_done\n"
       "rfapi_query_done\n"
       "indicate vn addr follows\n"
       "virtual network interface IPv4 address\n"
       "virtual network interface IPv6 address\n"
       "indicate xt addr follows\n"
       "underlay network interface IPv4 address\n"
       "underlay network interface IPv6 address\n"
       "indicate target follows\n"
       "Target IPv4 address\n"
       "Target IPv6 address\n")
{
	struct rfapi_ip_addr vn;
	struct rfapi_ip_addr un;
	struct rfapi_ip_addr target;
	rfapi_handle handle;
	int rc;

	/*
	 * Get VN addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[5]->arg, &vn)))
		return rc;


	/*
	 * Get UN addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[7]->arg, &un)))
		return rc;


	/*
	 * Get target addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[9]->arg, &target)))
		return rc;


	if (rfapi_find_handle_vty(vty, &vn, &un, &handle)) {
		vty_out(vty, "can't locate handle matching vn=%s, un=%s\n",
			argv[5]->arg, argv[7]->arg);
		return CMD_WARNING_CONFIG_FAILED;
	}

	/*
	 * options parameter not used? Set to NULL for now
	 */
	rc = rfapi_query_done(handle, &target);

	vty_out(vty, "rfapi_query_done returned %d\n", rc);

	return CMD_SUCCESS;
}

DEFUN (debug_rfapi_show_import,
       debug_rfapi_show_import_cmd,
       "debug rfapi-dev show import",
       DEBUG_STR
       DEBUG_RFAPI_STR
       SHOW_STR
       "import\n")
{
	struct bgp *bgp;
	struct rfapi *h;
	struct rfapi_import_table *it;
	char *s;
	int first_l2 = 1;

	/*
	 * Show all import tables
	 */

	bgp = bgp_get_default(); /* assume 1 instance for now */
	if (!bgp) {
		vty_out(vty, "No BGP instance\n");
		return CMD_WARNING_CONFIG_FAILED;
	}

	h = bgp->rfapi;
	if (!h) {
		vty_out(vty, "No RFAPI instance\n");
		return CMD_WARNING_CONFIG_FAILED;
	}

	/*
	 * Iterate over all import tables; do a filtered import
	 * for the afi/safi combination
	 */


	for (it = h->imports; it; it = it->next) {
		s = ecommunity_ecom2str(it->rt_import_list,
					ECOMMUNITY_FORMAT_ROUTE_MAP, 0);
		vty_out(vty, "Import Table %p, RTs: %s\n", it, s);
		XFREE(MTYPE_ECOMMUNITY_STR, s);

		rfapiShowImportTable(vty, "IP VPN", it->imported_vpn[AFI_IP],
				     1);
		rfapiShowImportTable(vty, "IP ENCAP",
				     it->imported_encap[AFI_IP], 0);
		rfapiShowImportTable(vty, "IP6 VPN", it->imported_vpn[AFI_IP6],
				     1);
		rfapiShowImportTable(vty, "IP6 ENCAP",
				     it->imported_encap[AFI_IP6], 0);
	}

	if (h->import_mac) {
		void *cursor = NULL;
		uint32_t lni;
		uintptr_t lni_as_ptr;
		int rc;
		char buf[BUFSIZ];

		for (rc = skiplist_next(h->import_mac, (void **)&lni_as_ptr,
					(void **)&it, &cursor);
		     !rc;
		     rc = skiplist_next(h->import_mac, (void **)&lni_as_ptr,
					(void **)&it, &cursor)) {

			if (it->imported_vpn[AFI_L2VPN]) {
				lni = lni_as_ptr;
				if (first_l2) {
					vty_out(vty,
						"\nLNI-based Ethernet Tables:\n");
					first_l2 = 0;
				}
				snprintf(buf, sizeof(buf), "L2VPN LNI=%u", lni);
				rfapiShowImportTable(
					vty, buf, it->imported_vpn[AFI_L2VPN],
					1);
			}
		}
	}

	rfapiShowImportTable(vty, "CE IT - IP VPN",
			     h->it_ce->imported_vpn[AFI_IP], 1);

	return CMD_SUCCESS;
}

DEFUN (debug_rfapi_show_import_vn_un,
       debug_rfapi_show_import_vn_un_cmd,
       "debug rfapi-dev show import vn <A.B.C.D|X:X::X:X> un <A.B.C.D|X:X::X:X>",
       DEBUG_STR
       DEBUG_RFAPI_STR
       SHOW_STR
       "import\n"
       "indicate vn addr follows\n"
       "virtual network interface IPv4 address\n"
       "virtual network interface IPv6 address\n"
       "indicate xt addr follows\n"
       "underlay network interface IPv4 address\n"
       "underlay network interface IPv6 address\n")
{
	struct rfapi_ip_addr vn;
	struct rfapi_ip_addr un;
	rfapi_handle handle;
	int rc;
	struct rfapi_descriptor *rfd;

	/*
	 * Get VN addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[5]->arg, &vn)))
		return rc;


	/*
	 * Get UN addr
	 */
	if ((rc = rfapiCliGetRfapiIpAddr(vty, argv[7]->arg, &un)))
		return rc;


	if (rfapi_find_handle_vty(vty, &vn, &un, &handle)) {
		vty_out(vty, "can't locate handle matching vn=%s, un=%s\n",
			argv[5]->arg, argv[7]->arg);
		return CMD_WARNING_CONFIG_FAILED;
	}

	rfd = (struct rfapi_descriptor *)handle;

	rfapiShowImportTable(vty, "IP VPN",
			     rfd->import_table->imported_vpn[AFI_IP], 1);
	rfapiShowImportTable(vty, "IP ENCAP",
			     rfd->import_table->imported_encap[AFI_IP], 0);
	rfapiShowImportTable(vty, "IP6 VPN",
			     rfd->import_table->imported_vpn[AFI_IP6], 1);
	rfapiShowImportTable(vty, "IP6 ENCAP",
			     rfd->import_table->imported_encap[AFI_IP6], 0);

	return CMD_SUCCESS;
}

DEFUN (debug_rfapi_response_omit_self,
       debug_rfapi_response_omit_self_cmd,
       "debug rfapi-dev response-omit-self <on|off>",
       DEBUG_STR
       DEBUG_RFAPI_STR
       "Omit self in RFP responses\n"
       "filter out self from responses\n" "leave self in responses\n")
{
	struct bgp *bgp = bgp_get_default();

	if (!bgp) {
		vty_out(vty, "No BGP process is configured\n");
		return CMD_WARNING_CONFIG_FAILED;
	}
	if (!bgp->rfapi_cfg) {
		vty_out(vty, "VNC not configured\n");
		return CMD_WARNING_CONFIG_FAILED;
	}

	if (strmatch(argv[3]->text, "on"))
		SET_FLAG(bgp->rfapi_cfg->flags,
			 BGP_VNC_CONFIG_FILTER_SELF_FROM_RSP);
	else
		UNSET_FLAG(bgp->rfapi_cfg->flags,
			   BGP_VNC_CONFIG_FILTER_SELF_FROM_RSP);

	return CMD_SUCCESS;
}


#ifdef RFAPI_DEBUG_SKIPLIST_CLI

#include "lib/skiplist.h"
DEFUN (skiplist_test_cli,
       skiplist_test_cli_cmd,
       "skiplist test",
       "skiplist command\n"
       "test\n")
{
	skiplist_test(vty);

	return CMD_SUCCESS;
}

DEFUN (skiplist_debug_cli,
       skiplist_debug_cli_cmd,
       "skiplist debug",
       "skiplist command\n"
       "debug\n")
{
	skiplist_debug(vty, NULL);
	return CMD_SUCCESS;
}

#endif /* RFAPI_DEBUG_SKIPLIST_CLI */

void rfapi_init(void)
{
	bgp_rfapi_cfg_init();
	vnc_debug_init();

	install_element(ENABLE_NODE, &debug_rfapi_show_import_cmd);
	install_element(ENABLE_NODE, &debug_rfapi_show_import_vn_un_cmd);

	install_element(ENABLE_NODE, &debug_rfapi_open_cmd);
	install_element(ENABLE_NODE, &debug_rfapi_close_vn_un_cmd);
	install_element(ENABLE_NODE, &debug_rfapi_close_rfd_cmd);
	install_element(ENABLE_NODE, &debug_rfapi_register_vn_un_cmd);
	install_element(ENABLE_NODE, &debug_rfapi_unregister_vn_un_cmd);
	install_element(ENABLE_NODE, &debug_rfapi_query_vn_un_cmd);
	install_element(ENABLE_NODE, &debug_rfapi_query_vn_un_done_cmd);
	install_element(ENABLE_NODE, &debug_rfapi_query_vn_un_l2o_cmd);

	install_element(ENABLE_NODE, &debug_rfapi_response_omit_self_cmd);

	/* Need the following show commands for gpz test scripts */
	install_element(ENABLE_NODE, &debug_rfapi_show_nves_cmd);
	install_element(ENABLE_NODE, &debug_rfapi_show_nves_vn_un_cmd);
	install_element(ENABLE_NODE, &debug_rfapi_register_vn_un_l2o_cmd);

#ifdef RFAPI_DEBUG_SKIPLIST_CLI
	install_element(ENABLE_NODE, &skiplist_test_cli_cmd);
	install_element(ENABLE_NODE, &skiplist_debug_cli_cmd);
#endif

	rfapi_vty_init();
}

#ifdef DEBUG_RFAPI
static void rfapi_print_exported(struct bgp *bgp)
{
	struct bgp_dest *destn;
	struct bgp_dest *dest;
	struct bgp_path_info *bpi;

	if (!bgp)
		return;

	for (destn = bgp_table_top(bgp->rib[AFI_IP][SAFI_MPLS_VPN]); destn;
	     destn = bgp_route_next(destn)) {
		struct bgp_table *table;

		table = bgp_dest_get_bgp_table_info(destn);
		if (!table)
			continue;
		fprintf(stderr, "%s: vpn destn=%p\n", __func__, destn);
		for (dest = bgp_table_top(table); dest;
		     dest = bgp_route_next(dest)) {
			bpi = bgp_dest_get_bgp_path_info(dest);

			if (!bpi)
				continue;
			fprintf(stderr, "%s: dest=%p\n", __func__, dest);
			for (; bpi; bpi = bpi->next) {
				rfapiPrintBi((void *)2, bpi); /* 2 => stderr */
			}
		}
	}
	for (destn = bgp_table_top(bgp->rib[AFI_IP][SAFI_ENCAP]); destn;
	     destn = bgp_route_next(destn)) {
		struct bgp_table *table;

		table = bgp_dest_get_bgp_table_info(destn);
		if (!table)
			continue;
		fprintf(stderr, "%s: encap destn=%p\n", __func__, destn);
		for (dest = bgp_table_top(table); dest;
		     dest = bgp_route_next(dest)) {
			bpi = bgp_dest_get_bgp_path_info(dest);
			if (!bpi)
				continue;
			fprintf(stderr, "%s: dest=%p\n", __func__, dest);
			for (; bpi; bpi = bpi->next) {
				rfapiPrintBi((void *)2, bpi); /* 2 => stderr */
			}
		}
	}
}
#endif /* defined(DEBUG_RFAPI) */

/*
 * Free all memory to prepare for clean exit as seen by valgrind memcheck
 */
void rfapi_delete(struct bgp *bgp)
{
	extern void rfp_clear_vnc_nve_all(void); /* can't fix correctly yet */

#if DEBUG_CLEANUP
	zlog_debug("%s: bgp %p", __func__, bgp);
#endif

	/*
	 * This clears queries and registered routes, and closes nves
	 */
	if (bgp->rfapi)
		rfp_clear_vnc_nve_all();

	/*
	 * close any remaining descriptors
	 */
	struct rfapi *h = bgp->rfapi;

	if (h && h->descriptors.count) {
		struct listnode *node, *nnode;
		struct rfapi_descriptor *rfd;
#if DEBUG_CLEANUP
		zlog_debug("%s: descriptor count %u", __func__,
			   h->descriptors.count);
#endif
		for (ALL_LIST_ELEMENTS(&h->descriptors, node, nnode, rfd)) {
#if DEBUG_CLEANUP
			zlog_debug("%s: closing rfd %p", __func__, rfd);
#endif
			(void)rfapi_close(rfd);
		}
	}

	bgp_rfapi_cfg_destroy(bgp, bgp->rfapi_cfg);
	bgp->rfapi_cfg = NULL;
	bgp_rfapi_destroy(bgp, bgp->rfapi);
	bgp->rfapi = NULL;
#ifdef DEBUG_RFAPI
	/*
	 * show what's left in the BGP MPLSVPN RIB
	 */
	rfapi_print_exported(bgp);
#endif
}

int rfapi_set_autord_from_vn(struct prefix_rd *rd, struct rfapi_ip_addr *vn)
{
	vnc_zlog_debug_verbose("%s: auto-assigning RD", __func__);
	if (vn->addr_family != AF_INET && vn->addr_family != AF_INET6) {
		vnc_zlog_debug_verbose(
			"%s: can't auto-assign RD, VN addr family is not IPv4|v6",
			__func__);
		return EAFNOSUPPORT;
	}
	rd->family = AF_UNSPEC;
	rd->prefixlen = 64;
	rd->val[1] = RD_TYPE_IP;
	if (vn->addr_family == AF_INET) {
		memcpy(rd->val + 2, &vn->addr.v4.s_addr, 4);
	} else { /* is v6 */
		memcpy(rd->val + 2, &vn->addr.v6.s6_addr32[3],
		       4); /* low order 4 bytes */
	}
	vnc_zlog_debug_verbose("%s: auto-RD is set to %pRDP", __func__, rd);
	return 0;
}

/*------------------------------------------
 * rfapi_bgp_lookup_by_rfp
 *
 * Find bgp instance pointer based on value returned by rfp_start
 *
 * input:
 *      rfp_start_val     value returned by rfp_startor
 *                        NULL (=get default instance)
 *
 * output:
 *	none
 *
 * return value:
 *	bgp             bgp instance pointer
 *      NULL = not found
 *
 --------------------------------------------*/
struct bgp *rfapi_bgp_lookup_by_rfp(void *rfp_start_val)
{
	struct bgp *bgp = NULL;
	struct listnode *node, *nnode;

	if (rfp_start_val == NULL)
		bgp = bgp_get_default();
	else
		for (ALL_LIST_ELEMENTS(bm->bgp, node, nnode, bgp))
			if (bgp->rfapi != NULL
			    && bgp->rfapi->rfp == rfp_start_val)
				return bgp;
	return bgp;
}

/*------------------------------------------
 * rfapi_get_rfp_start_val_by_bgp
 *
 * Find bgp instance pointer based on value returned by rfp_start
 *
 * input:
 *	bgp             bgp instance pointer
 *
 * output:
 *	none
 *
 * return value:
 *	rfp_start_val
 *      NULL = not found
 *
 --------------------------------------------*/
void *rfapi_get_rfp_start_val_by_bgp(struct bgp *bgp)
{
	if (!bgp || !bgp->rfapi)
		return NULL;
	return bgp->rfapi->rfp;
}

/***********************************************************************
 *		 RFP group specific configuration
 ***********************************************************************/
static void *rfapi_rfp_get_or_init_group_config_default(struct rfapi_cfg *rfc,
							struct vty *vty,
							uint32_t size)
{
	if (rfc->default_rfp_cfg == NULL && size > 0) {
		rfc->default_rfp_cfg = XCALLOC(MTYPE_RFAPI_RFP_GROUP_CFG, size);
		vnc_zlog_debug_verbose("%s: allocated, size=%d", __func__,
				       size);
	}
	return rfc->default_rfp_cfg;
}

static void *rfapi_rfp_get_or_init_group_config_nve(struct rfapi_cfg *rfc,
						    struct vty *vty,
						    uint32_t size)
{
	struct rfapi_nve_group_cfg *rfg =
		VTY_GET_CONTEXT_SUB(rfapi_nve_group_cfg);

	/* make sure group is still in list */
	if (!rfg || !listnode_lookup(rfc->nve_groups_sequential, rfg)) {
		/* Not in list anymore */
		vty_out(vty, "Current NVE group no longer exists\n");
		return NULL;
	}

	if (rfg->rfp_cfg == NULL && size > 0) {
		rfg->rfp_cfg = XCALLOC(MTYPE_RFAPI_RFP_GROUP_CFG, size);
		vnc_zlog_debug_verbose("%s: allocated, size=%d", __func__,
				       size);
	}
	return rfg->rfp_cfg;
}

static void *rfapi_rfp_get_or_init_group_config_l2(struct rfapi_cfg *rfc,
						   struct vty *vty,
						   uint32_t size)
{
	struct rfapi_l2_group_cfg *rfg =
		VTY_GET_CONTEXT_SUB(rfapi_l2_group_cfg);

	/* make sure group is still in list */
	if (!rfg || !listnode_lookup(rfc->l2_groups, rfg)) {
		/* Not in list anymore */
		vty_out(vty, "Current L2 group no longer exists\n");
		return NULL;
	}
	if (rfg->rfp_cfg == NULL && size > 0) {
		rfg->rfp_cfg = XCALLOC(MTYPE_RFAPI_RFP_GROUP_CFG, size);
		vnc_zlog_debug_verbose("%s: allocated, size=%d", __func__,
				       size);
	}
	return rfg->rfp_cfg;
}

/*------------------------------------------
 * rfapi_rfp_init_group_config_ptr_vty
 *
 * This is used to init or return a previously init'ed group specific
 * configuration pointer. Group is identified by vty context.
 * NOTE: size is ignored when a previously init'ed value is returned.
 * RFAPI frees rfp_cfg_group when group is deleted during reconfig,
 * bgp restart or shutdown.
 *
 * input:
 *    rfp_start_val     value returned by rfp_start
 *    type              group type
 *    vty               quagga vty context
 *    size              number of bytes to allocation
 *
 * output:
 *    none
 *
 * return value:
 *    rfp_cfg_group     NULL or Pointer to configuration structure
--------------------------------------------*/
void *rfapi_rfp_init_group_config_ptr_vty(void *rfp_start_val,
					  rfapi_rfp_cfg_group_type type,
					  struct vty *vty, uint32_t size)
{
	struct bgp *bgp;
	void *ret = NULL;

	if (rfp_start_val == NULL || vty == NULL)
		return NULL;

	bgp = rfapi_bgp_lookup_by_rfp(rfp_start_val);
	if (!bgp || !bgp->rfapi_cfg)
		return NULL;

	switch (type) {
	case RFAPI_RFP_CFG_GROUP_DEFAULT:
		ret = rfapi_rfp_get_or_init_group_config_default(bgp->rfapi_cfg,
								 vty, size);
		break;
	case RFAPI_RFP_CFG_GROUP_NVE:
		ret = rfapi_rfp_get_or_init_group_config_nve(bgp->rfapi_cfg,
							     vty, size);
		break;
	case RFAPI_RFP_CFG_GROUP_L2:
		ret = rfapi_rfp_get_or_init_group_config_l2(bgp->rfapi_cfg, vty,
							    size);
		break;
	default:
		flog_err(EC_LIB_DEVELOPMENT, "%s: Unknown group type=%d",
			 __func__, type);
		/* should never happen */
		assert("Unknown type" == NULL);
		break;
	}
	return ret;
}

/*------------------------------------------
 * rfapi_rfp_get_group_config_ptr_vty
 *
 * This is used to get group specific configuration pointer.
 * Group is identified by type and vty context.
 * RFAPI frees rfp_cfg_group when group is deleted during reconfig,
 * bgp restart or shutdown.
 *
 * input:
 *    rfp_start_val     value returned by rfp_start
 *    type              group type
 *    vty               quagga vty context
 *
 * output:
 *    none
 *
 * return value:
 *    rfp_cfg_group     Pointer to configuration structure
--------------------------------------------*/
void *rfapi_rfp_get_group_config_ptr_vty(void *rfp_start_val,
					 rfapi_rfp_cfg_group_type type,
					 struct vty *vty)
{
	return rfapi_rfp_init_group_config_ptr_vty(rfp_start_val, type, vty, 0);
}

static void *
rfapi_rfp_get_group_config_name_nve(struct rfapi_cfg *rfc, const char *name,
				    void *criteria,
				    rfp_group_config_search_cb_t *search_cb)
{
	struct rfapi_nve_group_cfg *rfg;
	struct listnode *node;

	for (ALL_LIST_ELEMENTS_RO(rfc->nve_groups_sequential, node, rfg)) {
		if (!strcmp(rfg->name, name) && /* name match */
		    (search_cb == NULL || !search_cb(criteria, rfg->rfp_cfg)))
			return rfg->rfp_cfg;
	}
	return NULL;
}

static void *
rfapi_rfp_get_group_config_name_l2(struct rfapi_cfg *rfc, const char *name,
				   void *criteria,
				   rfp_group_config_search_cb_t *search_cb)
{
	struct rfapi_l2_group_cfg *rfg;
	struct listnode *node;

	for (ALL_LIST_ELEMENTS_RO(rfc->l2_groups, node, rfg)) {
		if (!strcmp(rfg->name, name) && /* name match */
		    (search_cb == NULL || !search_cb(criteria, rfg->rfp_cfg)))
			return rfg->rfp_cfg;
	}
	return NULL;
}

/*------------------------------------------
 * rfapi_rfp_get_group_config_ptr_name
 *
 * This is used to get group specific configuration pointer.
 * Group is identified by type and name context.
 * RFAPI frees rfp_cfg_group when group is deleted during reconfig,
 * bgp restart or shutdown.
 *
 * input:
 *    rfp_start_val     value returned by rfp_start
 *    type              group type
 *    name              group name
 *    criteria          RFAPI caller provided search criteria
 *    search_cb         optional rfp_group_config_search_cb_t
 *
 * output:
 *    none
 *
 * return value:
 *    rfp_cfg_group     Pointer to configuration structure
--------------------------------------------*/
void *rfapi_rfp_get_group_config_ptr_name(
	void *rfp_start_val, rfapi_rfp_cfg_group_type type, const char *name,
	void *criteria, rfp_group_config_search_cb_t *search_cb)
{
	struct bgp *bgp;
	void *ret = NULL;

	if (rfp_start_val == NULL || name == NULL)
		return NULL;

	bgp = rfapi_bgp_lookup_by_rfp(rfp_start_val);
	if (!bgp || !bgp->rfapi_cfg)
		return NULL;

	switch (type) {
	case RFAPI_RFP_CFG_GROUP_DEFAULT:
		ret = bgp->rfapi_cfg->default_rfp_cfg;
		break;
	case RFAPI_RFP_CFG_GROUP_NVE:
		ret = rfapi_rfp_get_group_config_name_nve(bgp->rfapi_cfg, name,
							  criteria, search_cb);
		break;
	case RFAPI_RFP_CFG_GROUP_L2:
		ret = rfapi_rfp_get_group_config_name_l2(bgp->rfapi_cfg, name,
							 criteria, search_cb);
		break;
	default:
		flog_err(EC_LIB_DEVELOPMENT, "%s: Unknown group type=%d",
			 __func__, type);
		/* should never happen */
		assert("Unknown type" == NULL);
		break;
	}
	return ret;
}

/*------------------------------------------
 * rfapi_rfp_get_l2_group_config_ptr_lni
 *
 * This is used to get group specific configuration pointer.
 * Group is identified by type and logical network identifier.
 * RFAPI frees rfp_cfg_group when group is deleted during reconfig,
 * bgp restart or shutdown.
 *
 * input:
 *    rfp_start_val     value returned by rfp_start
 *    type              group type
 *    logical_net_id    group logical network identifier
 *    criteria          RFAPI caller provided search criteria
 *    search_cb         optional rfp_group_config_search_cb_t
 *
 * output:
 *    none
 *
 * return value:
 *    rfp_cfg_group     Pointer to configuration structure
--------------------------------------------*/
void *
rfapi_rfp_get_l2_group_config_ptr_lni(void *rfp_start_val,
				      uint32_t logical_net_id, void *criteria,
				      rfp_group_config_search_cb_t *search_cb)
{
	struct bgp *bgp;
	struct rfapi_l2_group_cfg *rfg;
	struct listnode *node;

	if (rfp_start_val == NULL)
		return NULL;

	bgp = rfapi_bgp_lookup_by_rfp(rfp_start_val);
	if (!bgp || !bgp->rfapi_cfg)
		return NULL;

	for (ALL_LIST_ELEMENTS_RO(bgp->rfapi_cfg->l2_groups, node, rfg)) {
		if (rfg->logical_net_id == logical_net_id
		    && (search_cb == NULL
			|| !search_cb(criteria, rfg->rfp_cfg))) {
			if (rfg->rfp_cfg == NULL)
				vnc_zlog_debug_verbose(
					"%s: returning rfp group config for lni=0",
					__func__);
			return rfg->rfp_cfg;
		}
	}
	return NULL;
}