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
|
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 1996-2019. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
-module(snmpa_agent).
-include_lib("kernel/include/file.hrl").
-include("snmpa_internal.hrl").
-include("snmp_types.hrl").
-include("snmp_debug.hrl").
-include("snmp_verbosity.hrl").
-include("SNMP-FRAMEWORK-MIB.hrl").
%% External exports
-export([start_link/4, start_link/5, stop/1]).
-export([subagent_get/3, subagent_get_next/3,
subagent_set/2,
load_mibs/3, unload_mibs/3,
which_mibs/1, whereis_mib/2, info/1,
register_subagent/3, unregister_subagent/2,
send_notification/3,
register_notification_filter/5,
unregister_notification_filter/2,
which_notification_filter/1,
get_net_if/1]).
-export([
discovery/6,
is_originating_discovery_enabled/0,
is_terminating_discovery_enabled/0,
terminating_discovery_stage2/0,
terminating_trigger_username/0
]).
-export([verbosity/2, dump_mibs/1, dump_mibs/2]).
-export([validate_err/3, make_value_a_correct_value/3,
do_get/3, do_get/4,
get/2, get/3, get_next/2, get_next/3]).
-export([mib_of/1, mib_of/2, me_of/1, me_of/2,
invalidate_mibs_cache/1,
which_mibs_cache_size/1,
enable_mibs_cache/1, disable_mibs_cache/1,
gc_mibs_cache/1, gc_mibs_cache/2, gc_mibs_cache/3,
enable_mibs_cache_autogc/1, disable_mibs_cache_autogc/1,
update_mibs_cache_age/2,
update_mibs_cache_gclimit/2]).
-export([get_agent_mib_storage/0, db/1,
backup/2]).
-export([get_log_type/1, set_log_type/2]).
-export([get_request_limit/1, set_request_limit/2]).
-export([invalidate_ca_cache/0]).
-export([increment_counter/3]).
-export([restart_worker/1, restart_set_worker/1]).
%% For backward compatibillity
-export([send_trap/6, send_trap/7]).
%% Internal exports
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3, tr_var/2, tr_varbind/1,
handle_pdu/8, worker/2, worker_loop/1,
do_send_trap/7, do_send_trap/8]).
%% <BACKWARD-COMPAT>
-export([handle_pdu/7,
load_mibs/2, unload_mibs/2]).
%% </BACKWARD-COMPAT>
-include("snmpa_internal.hrl").
-ifndef(default_verbosity).
-define(default_verbosity,silence).
-endif.
-define(empty_pdu_size, 21).
-ifdef(snmp_extended_verbosity).
-define(vt(F,A), ?vtrace(F, A)).
-else.
-define(vt(_F, _A), ok).
-endif.
-define(DISCO_TERMINATING_TRIGGER_USERNAME, "").
-ifdef(snmp_debug).
-define(GS_START_LINK3(Prio, Parent, Ref, Opts),
gen_server:start_link(?MODULE, [Prio, Parent, Ref, Opts],
[{debug,[trace]}])).
-define(GS_START_LINK4(Prio, Name, Parent, Ref, Opts),
gen_server:start_link({local, Name}, ?MODULE,
[Prio, Parent, Ref, Opts],
[{debug,[trace]}])).
-else.
-define(GS_START_LINK3(Prio, Parent, Ref, Opts),
gen_server:start_link(?MODULE, [Prio, Parent, Ref, Opts],[])).
-define(GS_START_LINK4(Prio, Name, Parent, Ref, Opts),
gen_server:start_link({local, Name}, ?MODULE,
[Prio, Parent, Ref, Opts],[])).
-endif.
%% Increment this whenever a change is made to the worker interface
-define(WORKER_INTERFACE_VERSION, 1).
%% -- Utility macros for creating worker commands --
-define(mk_pdu_wreq(Vsn, Pdu, PduMS, ACMData, Address, GbMaxVBs, Extra),
#wrequest{cmd = handle_pdu,
info = [{vsn, Vsn},
{pdu, Pdu},
{pdu_ms, PduMS},
{acm_data, ACMData},
{addr, Address},
{gb_max_vbs, GbMaxVBs},
{extra, Extra}]}).
-define(mk_send_trap_wreq(TrapRec, NotifyName, ContextName,
Recv, Vbs, LocalEngineID, Extra),
#wrequest{cmd = send_trap,
info = [{trap_rec, TrapRec},
{notify_name, NotifyName},
{context_name, ContextName},
{receiver, Recv},
{varbinds, Vbs},
{local_engine_id, LocalEngineID},
{extra, Extra}]}).
-define(mk_terminate_wreq(), #wrequest{cmd = terminate, info = []}).
-define(mk_verbosity_wreq(V), #wrequest{cmd = verbosity,
info = [{verbosity, V}]}).
-record(notification_filter, {id, mod, data}).
-record(disco,
{from, rec, sender, target, engine_id,
sec_level, ctx, ivbs, stage, handler, extra}).
%% This record is used when sending requests to the worker processes
-record(wrequest,
{
version = ?WORKER_INTERFACE_VERSION,
cmd,
info
}
).
%%-----------------------------------------------------------------
%% The agent is multi-threaded, i.e. each request is handled
%% by a separate process. However, in the normal case, there
%% is just one request handled at the time. In order to improve
%% performance, there is always two worker processes alive. They are
%% created at initialization time. There is always one worker
%% dedicated to SET-handling. When a get*-request is received,
%% it is sent to the worker, and the worker is marked as busy.
%% If a request is received when the worker is busy, a new temporary
%% worker is spawned.
%%
%% Code change
%% ===========
%% Note that the worker(s) execute the same module as the master
%% agent. For code change we have two options - ignore the workers,
%% or send them a code change message.
%%
%%-----------------------------------------------------------------
-record(state, {type,
parent,
worker,
worker_state = ready,
set_worker,
multi_threaded,
ref,
vsns,
nfilters = [],
note_store,
mib_server, %% Currently unused
net_if, %% Currently unused
net_if_mod,
backup,
disco,
mibs_cache_request,
gb_max_vbs}).
%%%-----------------------------------------------------------------
%%% This module implements the agent machinery; both for the master
%%% agent and the subagents.
%%%-----------------------------------------------------------------
%%% Table of contents
%%% =================
%%% 1. Interface
%%% 2. Main loop
%%% 3. GET REQUEST
%%% 4. GET-NEXT REQUEST
%%% 5. GET-BULK REQUEST
%%% 6. SET REQUEST
%%% 7. Misc functions
%%%-----------------------------------------------------------------
%%-----------------------------------------------------------------
%% Parent is a Pid (of master_agent) or none
%% Options is a list of Option, where Option is
%% {mibs, Mibs}
%% {net_if, NetIfModule}
%% {priority, Prio}
%% {verbosity, Verbosity}
%% {multi_threaded, Bool} true means that SETs are serialized,
%% while GETs are concurrent, even with a SET.
%% {set_mechanism, SetModule} % undocumented feature
%%
%% The following options are now removed - they are not needed
%% anymore when VACM is standard for authentication, and works
%% with all versions, and trap sending is standardized too.
%% {authentication_service, AuthModule} % undocumented feature
%% {trap_mechanism, TrapModule} % undocumented feature
%% Note: authentication_service is reintroduced for AXD301 (OTP-3324).
%%-----------------------------------------------------------------
start_link(Prio, Parent, Ref, Options) ->
?d("start_link -> entry with"
"~n Prio: ~p"
"~n Parent: ~p"
"~n Ref: ~p"
"~n Options: ~p", [Prio, Parent, Ref, Options]),
?GS_START_LINK3(Prio, Parent, Ref, Options).
start_link(Prio, Name, Parent, Ref, Options) ->
?d("start_link -> entry with"
"~n Prio: ~p"
"~n Name: ~p"
"~n Parent: ~p"
"~n Ref: ~p"
"~n Options: ~p", [Prio, Name, Parent, Ref, Options]),
?GS_START_LINK4(Prio, Name, Parent, Ref, Options).
stop(Agent) -> call(Agent, stop).
restart_worker(Agent) ->
call(Agent, restart_worker).
restart_set_worker(Agent) ->
call(Agent, restart_set_worker).
get_log_type(Agent) ->
call(Agent, get_log_type).
set_log_type(Agent, NewType) ->
call(Agent, {set_log_type, NewType}).
get_request_limit(Agent) ->
call(Agent, get_request_limit).
set_request_limit(Agent, NewLimit) ->
call(Agent, {set_request_limit, NewLimit}).
mib_of(Oid) when is_list(Oid) ->
mib_of(snmp_master_agent, Oid).
mib_of(Agent, Oid) when is_list(Oid) ->
call(Agent, {mib_of, Oid}).
me_of(Oid) when is_list(Oid) ->
me_of(snmp_master_agent, Oid).
me_of(Agent, Oid) when is_list(Oid) ->
call(Agent, {me_of, Oid}).
invalidate_mibs_cache(Agent) ->
call(Agent, {mibs_cache_request, invalidate_cache}).
gc_mibs_cache(Agent) ->
call(Agent, {mibs_cache_request, gc_cache}).
gc_mibs_cache(Agent, Age) ->
call(Agent, {mibs_cache_request, {gc_cache, Age}}).
gc_mibs_cache(Agent, Age, GcLimit) ->
call(Agent, {mibs_cache_request, {gc_cache, Age, GcLimit}}).
enable_mibs_cache(Agent) ->
call(Agent, {mibs_cache_request, enable_cache}).
disable_mibs_cache(Agent) ->
call(Agent, {mibs_cache_request, disable_cache}).
which_mibs_cache_size(Agent) ->
call(Agent, {mibs_cache_request, cache_size}).
enable_mibs_cache_autogc(Agent) ->
call(Agent, {mibs_cache_request, enable_autogc}).
disable_mibs_cache_autogc(Agent) ->
call(Agent, {mibs_cache_request, disable_autogc}).
update_mibs_cache_gclimit(Agent, GcLimit) ->
call(Agent, {mibs_cache_request, {update_gclimit, GcLimit}}).
update_mibs_cache_age(Agent, Age) ->
call(Agent, {mibs_cache_request, {update_age, Age}}).
increment_counter(Counter, Initial, Max) ->
%% This is to make sure no one else increments our counter
Key = {Counter, self()},
%% Counter data
Position = 2,
Increment = 1,
Threshold = Max,
SetValue = Initial,
UpdateOp = {Position, Increment, Threshold, SetValue},
%% And now for the actual increment
Tab = snmp_agent_table,
case (catch ets:update_counter(Tab, Key, UpdateOp)) of
{'EXIT', {badarg, _}} ->
%% Oups, first time
ets:insert(Tab, {Key, Initial}),
Initial;
Next when is_integer(Next) ->
Next
end.
init([Prio, Parent, Ref, Options]) ->
?d("init -> entry with"
"~n Prio: ~p"
"~n Parent: ~p"
"~n Ref: ~p"
"~n Options: ~p", [Prio, Parent, Ref, Options]),
case (catch do_init(Prio, Parent, Ref, Options)) of
{ok, State} ->
?vdebug("started",[]),
{ok, State};
{error, Reason} ->
config_err("failed starting agent: ~n~p", [Reason]),
{stop, Reason}
end.
do_init(Prio, Parent, Ref, Options) ->
process_flag(priority, Prio),
put(sname,short_name(Parent)),
put(verbosity,get_verbosity(Options)),
?vlog("starting with: "
"~n Prio: ~p"
"~n Parent: ~p"
"~n Ref: ~p"
"~n Options: ~p",[Prio, Parent, Ref, Options]),
Mibs = get_mibs(Options),
SetModule = get_set_mechanism(Options),
put(set_module, SetModule),
?vtrace("set-module: ~w", [SetModule]),
GetModule = get_get_mechanism(Options),
put(get_module, GetModule),
?vtrace("get-module: ~w", [GetModule]),
%% OTP-3324. For AXD301.
AuthModule = get_authentication_service(Options),
put(auth_module, AuthModule),
?vtrace("auth-module: ~w", [AuthModule]),
MultiT = get_multi_threaded(Options),
Vsns = get_versions(Options),
GbMaxVbs = get_gb_max_vbs(Options),
NS = start_note_store(Prio, Ref, Options),
{Type, NetIfPid, NetIfMod} =
start_net_if(Parent, Prio, Ref, Vsns, NS, Options),
MibPid = start_mib_server(Prio, Ref, Mibs, Options),
put(net_if, NetIfPid),
put(mibserver, MibPid),
process_flag(trap_exit, true),
{Worker, SetWorker} = workers_start(MultiT),
{ok, #state{type = Type,
parent = Parent,
worker = Worker,
set_worker = SetWorker,
multi_threaded = MultiT,
ref = Ref,
vsns = Vsns,
note_store = NS,
net_if_mod = NetIfMod,
gb_max_vbs = GbMaxVbs}}.
start_note_store(Prio, Ref, Options) ->
?vdebug("start_note_store -> with Prio: ~p", [Prio]),
NsOpts = get_note_store_opt(Options),
?vtrace("start_note_store -> NsOpts: ~p", [NsOpts]),
case (catch snmpa_misc_sup:start_note_store(Prio, Ref, NsOpts)) of
{ok, Pid} ->
?vdebug("start_note_store -> Pid: ~p", [Pid]),
Pid;
{error, Reason} ->
?vinfo("error starting note store: ~n~p",[Reason]),
throw({error, {note_store_error, Reason}});
{'EXIT', Reason} ->
?vinfo("exit starting note store: ~n~p",[Reason]),
throw({error, {note_store_exit, Reason}});
Error ->
?vinfo("failed starting note store: ~n~p",[Error]),
throw({error, {note_store_failed, Error}})
end.
start_net_if(none, Prio, Ref, Vsns, NoteStore, Options) ->
?vdebug("start_net_if(none) -> with Prio: ~p", [Prio]),
NetIfOpts = get_net_if_opt(Options),
Verbosity = get_net_if_verbosity(NetIfOpts),
Mod = get_net_if_module(NetIfOpts),
NiOptions = get_net_if_options(NetIfOpts),
NiOpts = [{versions, Vsns},
{verbosity, Verbosity} | NiOptions],
?vtrace("start_net_if -> "
"~n Mod: ~p"
"~n NiOpts: ~p",[Mod, NiOpts]),
case (catch snmpa_misc_sup:start_net_if(Prio, NoteStore, Ref, self(),
Mod, NiOpts)) of
{ok, Pid} ->
?vdebug("start_net_if -> Pid: ~p", [Pid]),
{master_agent, Pid, Mod};
{error, Reason} ->
?vinfo("error starting net if: ~n~p",[Reason]),
throw({error, {net_if_error, Reason}});
{'EXIT', Reason} ->
?vinfo("exit starting net if: ~n~p",[Reason]),
throw({error, {net_if_exit, Reason}});
Error ->
?vinfo("failed starting net if: ~n~p",[Error]),
throw({error, {net_if_failed, Error}})
end;
start_net_if(Parent, _Prio, _Ref, _Vsns, _NoteStore, _Options)
when is_pid(Parent) ->
?vdebug("start_net_if(~p) -> subagent => ignore", [Parent]),
{subagent, undefined, undefined}.
start_mib_server(Prio, Ref, Mibs, Options) ->
?vdebug("start_mib_server -> with Prio: ~p", [Prio]),
MibStorage = get_mib_storage(Options),
MibsOpts = [{mib_storage, MibStorage} |
get_option(mib_server, Options, [])],
?vtrace("start_mib_server -> "
"~n Mibs: ~p"
"~n MibsOpts: ~p", [Mibs, MibsOpts]),
case (catch snmpa_misc_sup:start_mib_server(Prio, Ref, Mibs, MibsOpts)) of
{ok, Pid} ->
?vdebug("start_mib_server -> Pid: ~p", [Pid]),
Pid;
{error, Reason} ->
?vinfo("error starting mib server: ~n~p",[Reason]),
throw({error, {mib_server_error, Reason}});
{'EXIT', Reason} ->
?vinfo("exit starting mib server: ~n~p",[Reason]),
throw({error, {mib_server_exit, Reason}});
Error ->
?vinfo("failed starting mib server: ~n~p",[Error]),
throw({error, {mib_server_failed, Error}})
end.
%%-----------------------------------------------------------------
%% Purpose: We must calculate the length of an empty Pdu. This
%% length is used to calculate the max pdu size allowed
%% for each get-bulk-request. This size is
%% dependent on the varbinds. It is calculated
%% as EmptySize + 8. 8 comes from the fact that the
%% maximum pdu size needs 31 bits which needs 5 * 7 bits to be
%% expressed. One 7bit octet is already present in the
%% empty pdu, leaving 4 more 7bit octets. The length is
%% repeated twice, once for the varbinds, and once for the
%% entire pdu; 2 * 4 = 8.
%% Actually, this function is not used, we use a constant instead.
%%-----------------------------------------------------------------
%% Ret: 21
%% empty_pdu() ->
%% Pdu = #pdu{type = 'get-response',
%% request_id = 1,
%% error_status = noError,
%% error_index = 0,
%% varbinds = []},
%% length(snmp_pdus:enc_pdu(Pdu)) + 8.
%%%--------------------------------------------------
%%% 1. Interface
%%%--------------------------------------------------
%% Called by administrator (not subagent; deadlock could occur)
register_subagent(Agent, SubTreeOid, SubagentPid) ->
call(Agent, {register_subagent, SubTreeOid, SubagentPid}).
%% Called by administrator (not subagent; deadlock could occur)
unregister_subagent(Agent, SubagentOidOrPid) ->
call(Agent, {unregister_subagent, SubagentOidOrPid}).
%%-----------------------------------------------------------------
%% These subagent_ functions either return a value, or exits
%% with {nodedown, Node} | Reason.
%%-----------------------------------------------------------------
subagent_get(SubAgent, Varbinds, IsNotification) ->
PduData = get_pdu_data(),
call(SubAgent, {subagent_get, Varbinds, PduData, IsNotification}).
subagent_get_next(SubAgent, MibView, Varbinds) ->
PduData = get_pdu_data(),
call(SubAgent, {subagent_get_next, MibView, Varbinds, PduData}).
subagent_set(SubAgent, Arguments) ->
PduData = get_pdu_data(),
call(SubAgent, {subagent_set, Arguments, PduData}).
%% Called by administrator (not agent; deadlock would occur)
%% <BACKWARD-COMPAT>
load_mibs(Agent, Mibs) ->
load_mibs(Agent, Mibs, false).
%% </BACKWARD-COMPAT>
load_mibs(Agent, Mibs, Force) ->
call(Agent, {load_mibs, Mibs, Force}).
%% Called by administrator (not agent; deadlock would occur)
%% <BACKWARD-COMPAT>
unload_mibs(Agent, Mibs) ->
unload_mibs(Agent, Mibs, false).
%% </BACKWARD-COMPAT>
unload_mibs(Agent, Mibs, Force) ->
call(Agent, {unload_mibs, Mibs, Force}).
which_mibs(Agent) ->
call(Agent, which_mibs).
whereis_mib(Agent, Mib) ->
call(Agent, {whereis_mib, Mib}).
info(Agent) ->
call(Agent, info).
get_net_if(Agent) ->
call(Agent, get_net_if).
register_notification_filter(Agent, Id, Mod, Args, Where)
when (Where =:= first) orelse (Where =:= last) ->
case (catch verify_notification_filter_behaviour(Mod)) of
ok ->
call(Agent, {register_notification_filter, Id, Mod, Args, Where});
Error ->
Error
end;
register_notification_filter(Agent, Id, Mod, Args, {Loc, _Id} = Where)
when (Loc =:= insert_before) orelse (Loc =:= insert_after) ->
case (catch verify_notification_filter_behaviour(Mod)) of
ok ->
call(Agent, {register_notification_filter, Id, Mod, Args, Where});
Error ->
Error
end.
verify_notification_filter_behaviour(Mod) ->
snmp_misc:verify_behaviour(snmpa_notification_filter, Mod).
unregister_notification_filter(Agent, Id) ->
call(Agent, {unregister_notification_filter, Id}).
which_notification_filter(Agent) ->
call(Agent, which_notification_filter).
send_notification(Agent, Notification, SendOpts) ->
Msg = {send_notif, Notification, SendOpts},
maybe_call(Agent, Msg).
%% <BACKWARD-COMPAT>
send_trap(Agent, Trap, NotifyName, CtxName, Recv, Varbinds) ->
?d("send_trap -> entry with"
"~n self(): ~p"
"~n Agent: ~p [~p]"
"~n Trap: ~p"
"~n NotifyName: ~p"
"~n CtxName: ~p"
"~n Recv: ~p"
"~n Varbinds: ~p",
[self(), Agent, wis(Agent),
Trap, NotifyName, CtxName, Recv, Varbinds]),
SendOpts = [
{receiver, Recv},
{varbinds, Varbinds},
{name, NotifyName},
{context, CtxName},
{extra, ?DEFAULT_NOTIF_EXTRA_INFO}
],
send_notification(Agent, Trap, SendOpts).
send_trap(Agent, Trap, NotifyName, CtxName, Recv, Varbinds, LocalEngineID) ->
?d("send_trap -> entry with"
"~n self(): ~p"
"~n Agent: ~p [~p]"
"~n Trap: ~p"
"~n NotifyName: ~p"
"~n CtxName: ~p"
"~n Recv: ~p"
"~n Varbinds: ~p"
"~n LocalEngineID: ~p",
[self(), Agent, wis(Agent),
Trap, NotifyName, CtxName, Recv, Varbinds, LocalEngineID]),
SendOpts = [
{receiver, Recv},
{varbinds, Varbinds},
{name, NotifyName},
{context, CtxName},
{extra, ?DEFAULT_NOTIF_EXTRA_INFO},
{local_engine_id, LocalEngineID}
],
send_notification(Agent, Trap, SendOpts).
%% </BACKWARD-COMPAT>
%% -- Discovery functions --
disco_opts() ->
case ets:lookup(snmp_agent_table, discovery) of
[] ->
[];
[{discovery, DiscoOptions}] ->
DiscoOptions
end.
originating_disco_opts() ->
DiscoOpts = disco_opts(),
case lists:keysearch(originating, 1, DiscoOpts) of
{value, {originating, OrigDisco}} ->
OrigDisco;
_ ->
[]
end.
is_originating_discovery_enabled() ->
OrigDisco = originating_disco_opts(),
case lists:keysearch(enable, 1, OrigDisco) of
{value, {enable, false}} ->
false;
_ ->
true
end.
terminating_disco_opts() ->
DiscoOpts = disco_opts(),
case lists:keysearch(terminating, 1, DiscoOpts) of
{value, {terminating, TermDisco}} ->
TermDisco;
_ ->
[]
end.
is_terminating_discovery_enabled() ->
TermDisco = terminating_disco_opts(),
case lists:keysearch(enable, 1, TermDisco) of
{value, {enable, false}} ->
false;
_ ->
true
end.
terminating_discovery_stage2() ->
Default = discovery,
TermDisco = terminating_disco_opts(),
case lists:keysearch(stage2, 1, TermDisco) of
{value, {stage2, Stage2}} when ((Stage2 =:= discovery) orelse (Stage2 =:= plain)) ->
Stage2;
_ ->
Default
end.
terminating_trigger_username() ->
Default = ?DISCO_TERMINATING_TRIGGER_USERNAME,
TermDisco = terminating_disco_opts(),
case lists:keysearch(trigger_username, 1, TermDisco) of
{value, {trigger_username, Trigger}} when is_list(Trigger) ->
Trigger;
_ ->
Default
end.
discovery(TargetName, Notification, ContextName, Varbinds,
DiscoHandler, ExtraInfo) ->
case is_originating_discovery_enabled() of
true ->
Agent = snmp_master_agent,
call(Agent,
{discovery,
TargetName, Notification, ContextName, Varbinds,
DiscoHandler, ExtraInfo});
false ->
{error, not_enabled}
end.
wis(Pid) when is_pid(Pid) ->
Pid;
wis(Atom) when is_atom(Atom) ->
whereis(Atom).
forward_trap(Agent, TrapRecord, NotifyName, CtxName, Recv, Varbinds,
ExtraInfo) ->
Agent ! {forward_trap, TrapRecord, NotifyName, CtxName, Recv, Varbinds,
ExtraInfo}.
%%-----------------------------------------------------------------
%% Args: Vars = [Oid]
%% Returns: [Value]
%% Called from a program to get variables. Don't call this from
%% an instrumentation function; deadlock can occur!
%%-----------------------------------------------------------------
get(Agent, Vars) ->
call(Agent, {get, Vars, ""}).
get(Agent, Vars, Context) ->
call(Agent, {get, Vars, Context}).
get_next(Agent, Vars) ->
call(Agent, {get_next, Vars, ""}).
get_next(Agent, Vars, Context) ->
call(Agent, {get_next, Vars, Context}).
%%-----------------------------------------------------------------
backup(Agent, BackupDir) when is_list(BackupDir) ->
call(Agent, {backup, BackupDir}).
%%-----------------------------------------------------------------
%% Runtime debug support.
%%-----------------------------------------------------------------
dump_mibs(Agent) ->
call(Agent, dump_mibs).
dump_mibs(Agent, File) when is_list(File) ->
call(Agent, {dump_mibs, File}).
%%-----------------------------------------------------------------
%% Runtime debug (verbosity) support.
%%-----------------------------------------------------------------
verbosity(net_if,Verbosity) ->
cast(snmp_master_agent,{net_if_verbosity,Verbosity});
verbosity(mib_server,Verbosity) ->
cast(snmp_master_agent,{mib_server_verbosity,Verbosity});
verbosity(note_store,Verbosity) ->
cast(snmp_master_agent,{note_store_verbosity,Verbosity});
verbosity(sub_agents,Verbosity) ->
cast(snmp_master_agent,{sub_agents_verbosity,Verbosity});
verbosity(master_agent,Verbosity) ->
cast(snmp_master_agent,{verbosity,Verbosity});
verbosity(Agent,{sub_agents,Verbosity}) ->
cast(Agent,{sub_agents_verbosity,Verbosity});
verbosity(Agent,Verbosity) ->
cast(Agent,{verbosity,Verbosity}).
%%%--------------------------------------------------
get_agent_mib_storage() ->
ets:lookup_element(snmp_agent_table, agent_mib_storage, 2).
db(Tab) ->
{Tab, get_agent_mib_storage()}.
%%%--------------------------------------------------
%%% 2. Main loop
%%%--------------------------------------------------
%% gen_server:reply(From, Reply)
handle_info({discovery_response, Response}, S) ->
?vdebug("handle_info(discovery_response) -> entry with"
"~n Response: ~p", [Response]),
NewS = handle_discovery_response(S, Response),
{noreply, NewS};
handle_info({snmp_pdu, Vsn, Pdu, PduMS, ACMData, Address, Extra}, S) ->
?vdebug("handle_info(snmp_pdu) -> entry with"
"~n Vsn: ~p"
"~n Pdu: ~p"
"~n Address: ~p"
"~n Extra: ~p", [Vsn, Pdu, Address, Extra]),
NewS = handle_snmp_pdu(is_valid_pdu_type(Pdu#pdu.type),
Vsn, Pdu, PduMS, ACMData, Address, Extra, S),
{noreply, NewS};
handle_info(worker_available, S) ->
?vdebug("worker available",[]),
{noreply, S#state{worker_state = ready}};
handle_info({send_notif, Notification, SendOpts}, S) ->
?vlog("[handle_info] send notif request:"
"~n Notification: ~p"
"~n SendOpts: ~p",
[Notification, SendOpts]),
case (catch handle_send_trap(S, Notification, SendOpts)) of
{ok, NewS} ->
{noreply, NewS};
{'EXIT', R} ->
?vinfo("Trap not sent:~n ~p", [R]),
{noreply, S};
_ ->
{noreply, S}
end;
%% <BACKWARD-COMPAT>
handle_info({send_trap, Trap, NotifyName, ContextName, Recv, Varbinds}, S) ->
?vlog("[handle_info] send trap request:"
"~n Trap: ~p"
"~n NotifyName: ~p"
"~n ContextName: ~p"
"~n Recv: ~p"
"~n Varbinds: ~p",
[Trap, NotifyName, ContextName, Recv, Varbinds]),
ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
LocalEngineID = local_engine_id(S),
case (catch handle_send_trap(S, Trap, NotifyName, ContextName,
Recv, Varbinds, LocalEngineID, ExtraInfo)) of
{ok, NewS} ->
{noreply, NewS};
{'EXIT', R} ->
?vinfo("Trap not sent:~n ~p", [R]),
{noreply, S};
_ ->
{noreply, S}
end;
handle_info({send_trap, Trap, NotifyName, ContextName, Recv, Varbinds,
LocalEngineID}, S) ->
?vlog("[handle_info] send trap request:"
"~n Trap: ~p"
"~n NotifyName: ~p"
"~n ContextName: ~p"
"~n Recv: ~p"
"~n Varbinds: ~p"
"~n LocalEngineID: ~p",
[Trap, NotifyName, ContextName, Recv, Varbinds, LocalEngineID]),
ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
case (catch handle_send_trap(S, Trap, NotifyName, ContextName,
Recv, Varbinds, LocalEngineID, ExtraInfo)) of
{ok, NewS} ->
{noreply, NewS};
{'EXIT', R} ->
?vinfo("Trap not sent:~n ~p", [R]),
{noreply, S};
_ ->
{noreply, S}
end;
%% </BACKWARD-COMPAT>
handle_info({forward_trap, TrapRecord, NotifyName, ContextName,
Recv, Varbinds, ExtraInfo}, S) ->
?vlog("[handle_info] forward trap request:"
"~n TrapRecord: ~p"
"~n NotifyName: ~p"
"~n ContextName: ~p"
"~n Recv: ~p"
"~n Varbinds: ~p",
[TrapRecord, NotifyName, ContextName, Recv, Varbinds]),
LocalEngineID = ?DEFAULT_LOCAL_ENGINE_ID,
case (catch maybe_send_trap(S, TrapRecord, NotifyName, ContextName,
Recv, Varbinds, LocalEngineID, ExtraInfo)) of
{ok, NewS} ->
{noreply, NewS};
{'EXIT', R} ->
?vinfo("Trap not sent:~n ~p", [R]),
{noreply, S};
_ ->
{noreply, S}
end;
%% <BACKWARD-COMPAT>
handle_info({forward_trap, TrapRecord, NotifyName, ContextName,
Recv, Varbinds}, S) ->
?vlog("[handle_info] forward trap request:"
"~n TrapRecord: ~p"
"~n NotifyName: ~p"
"~n ContextName: ~p"
"~n Recv: ~p"
"~n Varbinds: ~p",
[TrapRecord, NotifyName, ContextName, Recv, Varbinds]),
ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
LocalEngineID = ?DEFAULT_LOCAL_ENGINE_ID,
case (catch maybe_send_trap(S, TrapRecord, NotifyName, ContextName,
Recv, Varbinds, LocalEngineID, ExtraInfo)) of
{ok, NewS} ->
{noreply, NewS};
{'EXIT', R} ->
?vinfo("Trap not sent:~n ~p", [R]),
{noreply, S};
_ ->
{noreply, S}
end;
%% </BACKWARD-COMPAT>
handle_info({backup_done, Reply}, #state{backup = {_, From}} = S) ->
?vlog("[handle_info] backup done:"
"~n Reply: ~p", [Reply]),
gen_server:reply(From, Reply),
{noreply, S#state{backup = undefined}};
handle_info(invalidate_ca_cache, S) ->
invalidate_ca_cache(),
{noreply, S};
%%-----------------------------------------------------------------
%% If a process crashes, we first check to see if it was the mib,
%% net-if or note-store.
%% Otherwise, we check to see if it was a subagent. In this case
%% we unregister the sa, and unlink us from the sa.
%%-----------------------------------------------------------------
handle_info({'EXIT', Pid, Reason}, #state{note_store = Pid} = S) ->
?vlog("note store (~p) exited for reason ~n~p", [Pid, Reason]),
error_msg("note-store exited: ~n~p", [Reason]),
{stop, {note_store_exit, Reason}, S#state{note_store = undefined}};
handle_info({'EXIT', Pid, Reason}, #state{worker = Pid} = S) ->
?vlog("worker (~p) exited -> create new ~n ~p", [Pid, Reason]),
NewWorker = worker_start(),
{noreply, S#state{worker = NewWorker}};
handle_info({'EXIT', Pid, Reason}, #state{set_worker = Pid} = S) ->
?vlog("set-worker (~p) exited -> create new ~n ~p", [Pid,Reason]),
NewWorker = set_worker_start(),
{noreply, S#state{set_worker = NewWorker}};
handle_info({'EXIT', Pid, Reason}, #state{parent = Pid} = S) ->
?vlog("parent (~p) exited for reason ~n~p", [Pid,Reason]),
{stop, {parent_died, Reason}, S};
handle_info({'EXIT', Pid, Reason}, #state{backup = {Pid, From}} = S) ->
?vlog("backup server (~p) exited for reason ~n~p", [Pid, Reason]),
case Reason of
normal ->
{noreply, S};
_ ->
gen_server:reply(From, {error, Reason}),
{noreply, S#state{backup = undefined}}
end;
handle_info({'EXIT', Pid, Reason}, S) ->
?vlog("~p exited for reason ~p", [Pid, Reason]),
Mib = get(mibserver),
NetIf = get(net_if),
case Pid of
Mib ->
error_msg("mib-server exited: ~n~p", [Reason]),
{stop, {mib_server_exit, Reason}, S};
NetIf ->
error_msg("net-if exited: ~n~p", [Reason]),
{stop, {net_if_exit, Reason}, S};
_ ->
%% Could be a sub-agent
SAs = snmpa_mib:info(Mib, subagents),
case lists:keysearch(Pid, 1, SAs) of
{value, _} ->
?vlog("subagent exit", []),
snmpa_mib:unregister_subagent(Mib, Pid),
unlink(Pid);
_ ->
%% Otherwise it was probably a worker thread - ignore
ok
end,
{noreply, S}
end;
handle_info({'DOWN', Ref, process, Pid, {mibs_cache_reply, Reply}},
#state{mibs_cache_request = {Pid, Ref, From}} = S) ->
?vlog("reply from the mibs cache request handler (~p): ~n~p",
[Pid, Reply]),
gen_server:reply(From, Reply),
{noreply, S#state{mibs_cache_request = undefined}};
handle_info(Info, S) ->
warning_msg("received unexpected info: ~n~p", [Info]),
{noreply, S}.
handle_call(restart_worker, _From, #state{worker = Pid} = S) ->
if
is_pid(Pid) ->
?vlog("[handle_call] restart worker ~p", [Pid]),
exit(Pid, kill);
true ->
?vlog("[handle_call] not multi-threaded => "
"ignoring restart request", []),
ok
end,
{reply, ok, S};
handle_call(restart_set_worker, _From, #state{set_worker = Pid} = S) ->
if
is_pid(Pid) ->
?vlog("[handle_call] restart set worker: ~p", [Pid]),
exit(Pid, kill);
true ->
?vlog("[handle_call] not multi-threaded => "
"ignoring restart request", []),
ok
end,
{reply, ok, S};
handle_call({send_notif, Notification, SendOpts}, _From, S) ->
?vlog("[handle_call] send notif request:"
"~n Notification: ~p"
"~n SendOpts: ~p",
[Notification, SendOpts]),
case (catch handle_send_trap(S, Notification, SendOpts)) of
{ok, NewS} ->
{reply, ok, NewS};
{'EXIT', Reason} ->
?vinfo("Trap not sent:~n ~p", [Reason]),
{reply, {error, {send_failed, Reason}}, S};
_ ->
?vinfo("Trap not sent", []),
{reply, {error, send_failed}, S}
end;
%% <BACKWARD-COMPAT>
handle_call({send_trap, Trap, NotifyName, ContextName, Recv, Varbinds},
_From, S) ->
?vlog("[handle_call] send trap request:"
"~n Trap: ~p"
"~n NotifyName: ~p"
"~n ContextName: ~p"
"~n Recv: ~p"
"~n Varbinds: ~p",
[Trap, NotifyName, ContextName, Recv, Varbinds]),
ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
LocalEngineID = local_engine_id(S),
case (catch handle_send_trap(S, Trap, NotifyName, ContextName,
Recv, Varbinds, LocalEngineID, ExtraInfo)) of
{ok, NewS} ->
{reply, ok, NewS};
{'EXIT', Reason} ->
?vinfo("Trap not sent:~n ~p", [Reason]),
{reply, {error, {send_failed, Reason}}, S};
_ ->
?vinfo("Trap not sent", []),
{reply, {error, send_failed}, S}
end;
handle_call({send_trap, Trap, NotifyName,
ContextName, Recv, Varbinds, LocalEngineID},
_From, S) ->
?vlog("[handle_call] send trap request:"
"~n Trap: ~p"
"~n NotifyName: ~p"
"~n ContextName: ~p"
"~n Recv: ~p"
"~n Varbinds: ~p"
"~n LocalEngineID: ~p",
[Trap, NotifyName, ContextName, Recv, Varbinds, LocalEngineID]),
ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
case (catch handle_send_trap(S, Trap, NotifyName, ContextName,
Recv, Varbinds, LocalEngineID, ExtraInfo)) of
{ok, NewS} ->
{reply, ok, NewS};
{'EXIT', Reason} ->
?vinfo("Trap not sent:~n ~p", [Reason]),
{reply, {error, {send_failed, Reason}}, S};
_ ->
?vinfo("Trap not sent", []),
{reply, {error, send_failed}, S}
end;
%% </BACKWARD-COMPAT>
handle_call({discovery,
TargetName, Notification, ContextName, Vbs, DiscoHandler,
ExtraInfo},
From,
#state{disco = undefined} = S) ->
?vlog("[handle_call] initiate discovery process:"
"~n TargetName: ~p"
"~n Notification: ~p"
"~n ContextName: ~p"
"~n Vbs: ~p"
"~n DiscoHandler: ~p"
"~n ExtraInfo: ~p",
[TargetName, Notification, ContextName, Vbs,
DiscoHandler, ExtraInfo]),
case handle_discovery(S, From, TargetName,
Notification, ContextName, Vbs, DiscoHandler,
ExtraInfo) of
{ok, NewS} ->
?vtrace("[handle_call] first stage of discovery process initiated",
[]),
{noreply, NewS};
{error, _} = Error ->
{reply, Error, S}
end;
handle_call({discovery, _TargetName, _Notification, _ContextName, _Vbs, _DiscoHandler, _ExtraInfo}, _From,
#state{disco = DiscoData} = S) ->
Reply = {error, {discovery_in_progress, DiscoData}},
{reply, Reply, S};
handle_call({subagent_get, Varbinds, PduData, IsNotification}, _From, S) ->
?vlog("[handle_call] subagent get:"
"~n Varbinds: ~p"
"~n PduData: ~p",
[Varbinds,PduData]),
put_pdu_data(PduData),
{reply, do_get(Varbinds, IsNotification), S};
handle_call({subagent_get_next, MibView, Varbinds, PduData}, _From, S) ->
?vlog("[handle_call] subagent get-next:"
"~n MibView: ~p"
"~n Varbinds: ~p"
"~n PduData: ~p",
[MibView,Varbinds,PduData]),
put_pdu_data(PduData),
{reply, do_get_next(MibView, Varbinds), S};
handle_call({subagent_set, Arguments, PduData}, _From, S) ->
?vlog("[handle_call] subagent set:"
"~n Arguments: ~p"
"~n PduData: ~p",
[Arguments,PduData]),
put_pdu_data(PduData),
{reply, do_subagent_set(Arguments), S};
handle_call({get, Vars, Context}, _From, S) ->
?vlog("[handle_call] get:"
"~n Vars: ~p"
"~n Context: ~p", [Vars, Context]),
put_pdu_data({undefined, undefined, undefined, undefined, Context}),
case catch mapfoldl(fun ?MODULE:tr_var/2, [], 1, Vars) of
{error, Reason} -> {reply, {error, Reason}, S};
{_, Varbinds} ->
?vdebug("Varbinds: ~p",[Varbinds]),
Reply =
case do_get(Varbinds, false) of
{noError, 0, NewVarbinds} ->
Vbs = lists:keysort(#varbind.org_index, NewVarbinds),
[Value || #varbind{value = Value} <- Vbs];
{ErrorStatus, ErrIndex, _} ->
N = lists:nth(ErrIndex, Vars),
{error, {ErrorStatus, N}}
end,
{reply, Reply, S}
end;
handle_call({get_next, Vars, Context}, _From, S) ->
?vlog("[handle_call] get_next:"
"~n Vars: ~p"
"~n Context: ~p",[Vars, Context]),
put_pdu_data({undefined, undefined, undefined, undefined, Context}),
case catch mapfoldl(fun ?MODULE:tr_var/2, [], 1, Vars) of
{error, Reason} -> {reply, {error, Reason}, S};
{_, Varbinds} ->
?vdebug("Varbinds: ~p",[Varbinds]),
MibView = snmpa_acm:get_root_mib_view(),
Reply =
case do_get_next(MibView, Varbinds) of
{noError, 0, NewVarbinds} ->
Vbs = lists:keysort(#varbind.org_index, NewVarbinds),
[{Oid,Val} || #varbind{oid = Oid, value = Val} <- Vbs];
{ErrorStatus, ErrIndex, _} ->
N = lists:nth(ErrIndex, Vars),
{error, {ErrorStatus, N}}
end,
{reply, Reply, S}
end;
handle_call({do_get, MibView, UnsortedVarbinds, IsNotification, PduData},
_From, S) ->
?vlog("[handle_call] do_get:"
"~n MibView: ~p"
"~n UnsortedVarbinds: ~p"
"~n IsNotification: ~p"
"~n PduData: ~p",
[MibView, UnsortedVarbinds, IsNotification, PduData]),
put_pdu_data(PduData),
Reply = do_get(MibView, UnsortedVarbinds, IsNotification),
{reply, Reply, S};
handle_call({register_subagent, SubTreeOid, SubagentPid}, _From, S) ->
Reply =
case snmpa_mib:register_subagent(get(mibserver),
SubTreeOid, SubagentPid) of
ok -> link(SubagentPid), ok;
Error -> Error
end,
{reply, Reply, S};
handle_call({unregister_subagent, SubagentPid}, _From, S)
when is_pid(SubagentPid) ->
?vlog("[handle_call] unregister subagent ~p", [SubagentPid]),
Reply = snmpa_mib:unregister_subagent(get(mibserver), SubagentPid),
unlink(SubagentPid),
{reply, Reply, S};
handle_call({unregister_subagent, SubTreeOid}, _From, S) ->
?vlog("[handle_call] unregister subagent ~p", [SubTreeOid]),
Reply =
case snmpa_mib:unregister_subagent(get(mibserver), SubTreeOid) of
{ok, DeletedSubagentPid} ->
SAs = snmpa_mib:info(get(mibserver), subagents),
case lists:keysearch(DeletedSubagentPid, 1, SAs) of
{value, _} -> ok;
_ -> unlink(DeletedSubagentPid)
end,
ok;
Error ->
Error
end,
{reply, Reply, S};
%% <BACKWARD-COMPAT>
handle_call({load_mibs, Mibs}, _From, S) ->
?vlog("load mibs ~p", [Mibs]),
{reply, snmpa_mib:load_mibs(get(mibserver), Mibs), S};
%% </BACKWARD-COMPAT>
handle_call({load_mibs, Mibs, Force}, _From, S) ->
?vlog("[~w] load mibs ~p", [Force, Mibs]),
{reply, snmpa_mib:load_mibs(get(mibserver), Mibs, Force), S};
%% <BACKWARD-COMPAT>
handle_call({unload_mibs, Mibs}, _From, S) ->
?vlog("unload mibs ~p", [Mibs]),
{reply, snmpa_mib:unload_mibs(get(mibserver), Mibs), S};
%% </BACKWARD-COMPAT>
handle_call({unload_mibs, Mibs, Force}, _From, S) ->
?vlog("[~w] unload mibs ~p", [Force, Mibs]),
{reply, snmpa_mib:unload_mibs(get(mibserver), Mibs, Force), S};
handle_call(which_mibs, _From, S) ->
?vlog("which mibs", []),
{reply, snmpa_mib:which_mibs(get(mibserver)), S};
handle_call({whereis_mib, Mib}, _From, S) ->
?vlog("whereis mib ~p", [Mib]),
{reply, snmpa_mib:whereis_mib(get(mibserver), Mib), S};
handle_call({mibs_cache_request, MibsCacheReq}, From, S) ->
?vlog("mibs_cache_request: ~p", [MibsCacheReq]),
{MibsCacheWorker, Ref} =
handle_mibs_cache_request(get(mibserver), MibsCacheReq),
NewS = S#state{mibs_cache_request = {MibsCacheWorker, Ref, From}},
{noreply, NewS};
handle_call(info, _From, S) ->
?vlog("info", []),
Vsns = S#state.vsns,
Stats = get_stats_counters(),
AI = agent_info(S),
NI = net_if_info(S),
NS = note_store_info(S),
SS = symbolic_store_info(),
LD = local_db_info(),
MS = mib_server_info(),
Info = [{vsns, Vsns},
{stats_counters, Stats},
{agent, AI},
{net_if, NI},
{note_store, NS},
{symbolic_store, SS},
{local_db, LD},
{mib_server, MS}],
{reply, Info, S};
handle_call(get_net_if, _From, S) ->
{reply, get(net_if), S};
%% Only accept a backup request if there is none already in progress
handle_call({backup, BackupDir}, From, #state{backup = undefined} = S) ->
?vlog("backup: ~p", [BackupDir]),
Pid = self(),
V = get(verbosity),
MS = get(mibserver),
BackupServer =
erlang:spawn_link(
fun() ->
put(sname, abs),
put(verbosity, V),
Dir = filename:join([BackupDir]),
Reply = handle_backup(Dir, MS),
Pid ! {backup_done, Reply},
unlink(Pid)
end),
?vtrace("backup server: ~p", [BackupServer]),
{noreply, S#state{backup = {BackupServer, From}}};
handle_call({backup, _BackupDir}, _From, #state{backup = Backup} = S) ->
?vinfo("backup already in progress: ~p", [Backup]),
{reply, {error, backup_in_progress}, S};
handle_call(dump_mibs, _From, S) ->
Reply = snmpa_mib:dump(get(mibserver)),
{reply, Reply, S};
handle_call({dump_mibs,File}, _From, S) ->
Reply = snmpa_mib:dump(get(mibserver),File),
{reply, Reply, S};
handle_call({register_notification_filter, Id, Mod, Data, Where}, _From,
#state{nfilters = NFs} = S) ->
?vlog("register_notification_filter -> "
"~n Id: ~p"
"~n Mod: ~p"
"~n Where: ~p", [Id, Mod, Where]),
case lists:keymember(Id, 2, NFs) of
true ->
{reply, {error, {already_registered, Id}}, S};
false ->
NF = #notification_filter{id = Id, mod = Mod, data = Data},
{Reply, NewNFs} = add_notification_filter(Where, NF, NFs),
{reply, Reply, S#state{nfilters = NewNFs}}
end;
handle_call({unregister_notification_filter, Id}, _From,
#state{nfilters = NFs} = S) ->
?vlog("unregister_notification_filter -> "
"~n Id: ~p", [Id]),
case lists:keydelete(Id, 2, NFs) of
NFs ->
{reply, {error, {not_found, Id}}, S};
NFs2 ->
{reply, ok, S#state{nfilters = NFs2}}
end;
handle_call(which_notification_filter, _From,
#state{nfilters = NFs} = S) ->
?vlog("which_notification_filter", []),
{reply, [Id || #notification_filter{id = Id} <- NFs], S};
handle_call({mib_of, Oid}, _From, S) ->
Reply = handle_mib_of(get(mibserver), Oid),
{reply, Reply, S};
handle_call({me_of, Oid}, _From, S) ->
Reply = handle_me_of(get(mibserver), Oid),
{reply, Reply, S};
handle_call(get_log_type, _From, S) ->
?vlog("handle_call(get_log_type) -> entry with", []),
Reply = handle_get_log_type(S),
{reply, Reply, S};
handle_call({set_log_type, NewType}, _From, S) ->
?vlog("handle_call(set_log_type) -> entry with"
"~n NewType: ~p", [NewType]),
Reply = handle_set_log_type(S, NewType),
{reply, Reply, S};
handle_call(get_request_limit, _From, S) ->
?vlog("handle_call(get_request_limit) -> entry with", []),
Reply = handle_get_request_limit(S),
{reply, Reply, S};
handle_call({set_request_limit, NewLimit}, _From, S) ->
?vlog("handle_call(set_request_limit) -> entry with"
"~n NewLimit: ~p", [NewLimit]),
Reply = handle_set_request_limit(S, NewLimit),
{reply, Reply, S};
handle_call(stop, _From, S) ->
{stop, normal, ok, S};
handle_call(Req, _From, S) ->
warning_msg("received unknown request: ~n~p", [Req]),
Reply = {error, {unknown, Req}},
{reply, Reply, S}.
handle_cast({verbosity, Verbosity}, S) ->
?vlog("verbosity: ~p -> ~p",[get(verbosity), Verbosity]),
put(verbosity,snmp_verbosity:validate(Verbosity)),
case S#state.worker of
Pid when is_pid(Pid) -> Pid ! ?mk_verbosity_wreq(Verbosity);
_ -> ok
end,
case S#state.set_worker of
Pid2 when is_pid(Pid2) -> Pid2 ! ?mk_verbosity_wreq(Verbosity);
_ -> ok
end,
{noreply, S};
handle_cast({sub_agents_verbosity,Verbosity}, S) ->
?vlog("sub_agents verbosity: ~p",[Verbosity]),
subagents_verbosity(Verbosity),
{noreply, S};
%% This should only happen if we are a master_agent
handle_cast({net_if_verbosity, Verbosity}, S) ->
net_if_verbosity(get(net_if), Verbosity),
{noreply, S};
handle_cast({mib_server_verbosity, Verbosity}, S) ->
mib_server_verbosity(get(mibserver),Verbosity),
{noreply, S};
handle_cast({note_store_verbosity, Verbosity}, #state{note_store = Pid} = S) ->
note_store_verbosity(Pid,Verbosity),
{noreply, S};
handle_cast(Msg, S) ->
warning_msg("received unknown message: ~n~p", [Msg]),
{noreply, S}.
terminate(shutdown, #state{worker = Worker,
set_worker = SetWorker,
backup = Backup,
ref = Ref}) ->
%% Ordered shutdown - stop misc-workers, net_if, mib-server and note-store.
backup_server_stop(Backup),
worker_stop(Worker, 100),
worker_stop(SetWorker, 100),
snmpa_misc_sup:stop_net_if(Ref),
snmpa_misc_sup:stop_mib_server(Ref);
terminate(_Reason, _S) ->
%% We crashed! We will reuse net_if and mib if we get restarted.
ok.
handle_mibs_cache_request(MibServer, Req) ->
{MibsCacheWorker, MibsCacheRef} =
spawn_monitor(
fun() ->
Reply =
case Req of
invalidate_cache ->
snmpa_mib:invalidate_cache(MibServer);
gc_cache ->
snmpa_mib:gc_cache(MibServer);
{gc_cache, Age} ->
snmpa_mib:gc_cache(MibServer, Age);
{gc_cache, Age, GcLimit} ->
snmpa_mib:gc_cache(MibServer, Age, GcLimit);
cache_size ->
snmpa_mib:which_cache_size(MibServer);
enable_cache ->
snmpa_mib:enable_cache(MibServer);
disable_cache ->
snmpa_mib:disable_cache(MibServer);
enable_autogc ->
snmpa_mib:enable_cache_autogc(MibServer);
disable_autogc ->
snmpa_mib:disable_cache_autogc(MibServer);
{update_gclimit, GcLimit} ->
snmpa_mib:update_cache_gclimit(MibServer,
GcLimit);
{update_age, Age} ->
snmpa_mib:update_cache_age(MibServer, Age);
_ ->
{error, {unknown_mibs_cache_request, Req}}
end,
exit({mibs_cache_reply, Reply})
end),
{MibsCacheWorker, MibsCacheRef}.
%%-----------------------------------------------------------------
%% Code replacement
%%
%%-----------------------------------------------------------------
%% Downgrade
%%
%% code_change({down, _Vsn}, S1, downgrade_to_pre_4_17_3) ->
%% #state{type = Type,
%% parent = Parent,
%% worker = Worker,
%% worker_state = WorkerState,
%% set_worker = SetWorker,
%% multi_threaded = MT,
%% ref = Ref,
%% vsns = Vsns,
%% nfilters = NF,
%% note_store = NoteStore,
%% mib_server = MS,
%% net_if = NetIf,
%% net_if_mod = NetIfMod,
%% backup = Backup,
%% disco = Disco,
%% mibs_cache_request = MCR} = S1,
%% S2 = {state,
%% type = Type,
%% parent = Parent,
%% worker = Worker,
%% worker_state = WorkerState,
%% set_worker = SetWorker,
%% multi_threaded = MT,
%% ref = Ref,
%% vsns = Vsns,
%% nfilters = NF,
%% note_store = NoteStore,
%% mib_server = MS,
%% net_if = NetIf,
%% net_if_mod = NetIfMod,
%% backup = Backup,
%% disco = Disco,
%% mibs_cache_request = MCR},
%% {ok, S2};
%% %% Upgrade
%% %%
%% code_change(_Vsn, S1, upgrade_from_pre_4_17_3) ->
%% {state,
%% type = Type,
%% parent = Parent,
%% worker = Worker,
%% worker_state = WorkerState,
%% set_worker = SetWorker,
%% multi_threaded = MT,
%% ref = Ref,
%% vsns = Vsns,
%% nfilters = NF,
%% note_store = NoteStore,
%% mib_server = MS,
%% net_if = NetIf,
%% net_if_mod = NetIfMod,
%% backup = Backup,
%% disco = Disco,
%% mibs_cache_request = MCR} = S1,
%% S2 = #state{type = Type,
%% parent = Parent,
%% worker = Worker,
%% worker_state = WorkerState,
%% set_worker = SetWorker,
%% multi_threaded = MT,
%% ref = Ref,
%% vsns = Vsns,
%% nfilters = NF,
%% note_store = NoteStore,
%% mib_server = MS,
%% net_if = NetIf,
%% net_if_mod = NetIfMod,
%% backup = Backup,
%% disco = Disco,
%% mibs_cache_request = MCR,
%% gb_max_vbs = ?DEFAULT_GB_MAX_VBS},
%% {ok, S2};
code_change(_Vsn, S, _Extra) ->
{ok, S}.
%% workers_restart(#state{worker = W, set_worker = SW} = S) ->
%% Worker = worker_restart(W),
%% SetWorker = set_worker_restart(SW),
%% S#state{worker = Worker,
%% set_worker = SetWorker}.
%%-----------------------------------------------------------------
backup_server_stop({Pid, _}) when is_pid(Pid) ->
exit(Pid, kill);
backup_server_stop(_) ->
ok.
workers_start(true) ->
?vdebug("start worker and set-worker",[]),
{worker_start(), set_worker_start()};
workers_start(_) ->
{undefined, undefined}.
worker_start() ->
worker_start(get()).
set_worker_start() ->
worker_start([{master, self()} | get()]).
worker_start(Dict) ->
proc_lib:spawn_link(?MODULE, worker, [self(), Dict]).
%% worker_stop(Pid) ->
%% worker_stop(Pid, infinity).
worker_stop(Pid, Timeout) when is_pid(Pid) ->
Pid ! ?mk_terminate_wreq(),
receive
{'EXIT', Pid, normal} ->
ok
after Timeout ->
(catch exit(Pid, kill)),
ok
end;
worker_stop(_, _) ->
ok.
%% set_worker_restart(Pid) ->
%% worker_restart(Pid, [{master, self()} | get()]).
%% worker_restart(Pid) ->
%% worker_restart(Pid, get()).
%% worker_restart(Pid, Dict) when is_pid(Pid) ->
%% worker_stop(Pid),
%% worker_start(Dict);
%% worker_restart(Any, _Dict) ->
%% Any.
%%-----------------------------------------------------------------
handle_backup(BackupDir, MibServer) ->
?vlog("handle_backup -> entry with"
"~n BackupDir: ~p", [BackupDir]),
case ets:lookup(snmp_agent_table, db_dir) of
[{db_dir, BackupDir}] ->
?vinfo("handle_backup -> backup dir and db dir the same", []),
{error, db_dir};
_ ->
case file:read_file_info(BackupDir) of
{ok, #file_info{type = directory}} ->
?vdebug("handle_backup -> backup dir ok", []),
VacmRes = (catch snmpa_vacm:backup(BackupDir)),
?vtrace("handle_backup -> "
"~n VacmRes: ~p", [VacmRes]),
LdbRes = (catch snmpa_local_db:backup(BackupDir)),
?vtrace("handle_backup -> "
"~n LdbRes: ~p", [LdbRes]),
MsRes = (catch snmpa_mib:backup(MibServer, BackupDir)),
?vtrace("handle_backup -> "
"~n MsRes: ~p", [MsRes]),
SsRes = (catch snmpa_symbolic_store:backup(BackupDir)),
?vtrace("handle_backup -> "
"~n SsRes: ~p", [SsRes]),
handle_backup_res([{vacm, VacmRes},
{local_db, LdbRes},
{mib_server, MsRes},
{symbolic_store, SsRes}]);
{ok, _} ->
?vinfo("handle_backup -> backup dir not a dir", []),
{error, not_a_directory};
Error ->
?vinfo("handle_backup -> Error: ~p", [Error]),
Error
end
end.
handle_backup_res(Results) ->
handle_backup_res(Results, []).
handle_backup_res([], []) ->
ok;
handle_backup_res([], Acc) ->
{error, lists:reverse(Acc)};
handle_backup_res([{_, ok}|Results], Acc) ->
handle_backup_res(Results, Acc);
handle_backup_res([{Who, {error, Reason}}|Results], Acc) ->
handle_backup_res(Results, [{Who, Reason}|Acc]);
handle_backup_res([{Who, Crap}|Results], Acc) ->
handle_backup_res(Results, [{Who, Crap}|Acc]).
%%-----------------------------------------------------------------
%% We must cheat to get the community string out of the ACM data,
%% because we (for some reason) support the function
%% snmpa:current_community().
%%-----------------------------------------------------------------
cheat({community, _SecModel, Community, _TAddress}, Address, ContextName) ->
{Community, Address, ContextName};
cheat({community, _SecModel, Community, _TDomain, _TAddress},
Address, ContextName) ->
{Community, Address, ContextName};
cheat(_, Address, ContextName) ->
{"", Address, ContextName}.
%% This function will either be in the context of the:
%% 1) master-agent
%% 2) set-worker
%% 3) user code
%% ( calling e.g. snmp_community_mib:snmpCommunityTable(set, ...) )
invalidate_ca_cache() ->
case get(master) of
undefined -> % 1 or 3
case get(auth_module) of
undefined -> % 3
%% Ouch, we are not running in the context of the
%% master agent either. Check if we are on the
%% master-agent node. If so, sent it there,
case whereis(snmp_master_agent) of
MasterAgent when is_pid(MasterAgent) ->
case node(MasterAgent) =:= node() of
true ->
%% Ok, we are on the node running the
%% master_agent process, so sent it there
MasterAgent ! invalidate_ca_cache;
false ->
%% This is running on a sub-agent node,
%% so skip it
ok
end;
_ -> % Not on this node
ok
end;
AuthMod -> % 1
AuthMod:invalidate_ca_cache()
end;
Pid -> % 2
Pid ! invalidate_ca_cache
end.
%%-----------------------------------------------------------------
%% Threads and workers
%%
%%-----------------------------------------------------------------
%% This functions spawns a temporary worker process,
%% that evaluates one request and then silently exits.
spawn_thread(Vsn, Pdu, PduMS, ACMData, Address, GbMaxVBs, Extra) ->
Dict = get(),
Args = [Vsn, Pdu, PduMS, ACMData, Address, GbMaxVBs, Extra, Dict],
proc_lib:spawn_link(?MODULE, handle_pdu, Args).
spawn_trap_thread(TrapRec, NotifyName, ContextName, Recv, Vbs,
LocalEngineID, ExtraInfo) ->
Dict = get(),
proc_lib:spawn_link(?MODULE, do_send_trap,
[TrapRec, NotifyName, ContextName,
Recv, Vbs, LocalEngineID, ExtraInfo, Dict]).
do_send_trap(TrapRec, NotifyName, ContextName, Recv, Vbs,
LocalEngineID, Dict) ->
ExtraInfo = ?DEFAULT_NOTIF_EXTRA_INFO,
do_send_trap(TrapRec, NotifyName, ContextName, Recv, Vbs,
LocalEngineID, ExtraInfo, Dict).
do_send_trap(TrapRec, NotifyName, ContextName, Recv, Vbs,
LocalEngineID, ExtraInfo, Dict) ->
lists:foreach(fun({Key, Val}) -> put(Key, Val) end, Dict),
put(sname, trap_sender_short_name(get(sname))),
?vlog("starting",[]),
snmpa_trap:send_trap(TrapRec, NotifyName, ContextName, Recv, Vbs,
LocalEngineID, ExtraInfo, get(net_if)).
worker(Master, Dict) ->
lists:foreach(fun({Key, Val}) -> put(Key, Val) end, Dict),
put(sname, worker_short_name(get(sname))),
?vlog("starting",[]),
worker_loop(Master).
worker_loop(Master) ->
Res =
receive
#wrequest{cmd = handle_pdu,
info = Info} = Req ->
?vtrace("worker_loop -> received handle_pdu request with"
"~n Info: ~p", [Info]),
Vsn = proplists:get_value(vsn, Info),
Pdu = proplists:get_value(pdu, Info),
PduMS = proplists:get_value(pdu_ms, Info),
ACMData = proplists:get_value(acm_data, Info),
Address = proplists:get_value(addr, Info),
GbMaxVBs = proplists:get_value(gb_max_vbs, Info),
Extra = proplists:get_value(extra, Info),
HandlePduRes =
try
begin
handle_pdu2(Vsn, Pdu, PduMS, ACMData, Address,
GbMaxVBs, Extra)
end
catch
C:E:S ->
exit({worker_crash, Req, C, E, S})
end,
Master ! worker_available,
HandlePduRes; % For debugging...
#wrequest{cmd = send_trap,
info = Info} = Req ->
?vtrace("worker_loop -> received send_trap request with"
"~n Info: ~p", [Info]),
TrapRec = proplists:get_value(trap_rec, Info),
NotifyName = proplists:get_value(notify_name, Info),
ContextName = proplists:get_value(context_name, Info),
Recv = proplists:get_value(receiver, Info),
Vbs = proplists:get_value(varbinds, Info),
LocalEngineID = proplists:get_value(local_engine_id, Info),
Extra = proplists:get_value(extra, Info),
SendTrapRes =
try
begin
snmpa_trap:send_trap(TrapRec, NotifyName,
ContextName, Recv, Vbs,
LocalEngineID, Extra,
get(net_if))
end
catch
C:E:S ->
exit({worker_crash, Req, C, E, S})
end,
Master ! worker_available,
SendTrapRes; % For debugging...
#wrequest{cmd = verbosity,
info = Info} ->
Verbosity = proplists:get_value(verbosity, Info),
put(verbosity, snmp_verbosity:validate(Verbosity));
#wrequest{cmd = terminate} ->
?vtrace("worker_loop -> received terminate request", []),
exit(normal);
%% *************************************************************
%%
%% Kept for backward compatibillity reasons
%%
%% *************************************************************
{Vsn, Pdu, PduMS, ACMData, Address, Extra} ->
?vtrace("worker_loop -> received request", []),
handle_pdu2(Vsn, Pdu, PduMS, ACMData, Address,
?DEFAULT_GB_MAX_VBS, Extra),
Master ! worker_available;
%% We don't trap exits!
{TrapRec, NotifyName, ContextName, Recv, Vbs} ->
?vtrace("worker_loop -> send trap:"
"~n ~p", [TrapRec]),
snmpa_trap:send_trap(TrapRec, NotifyName,
ContextName, Recv, Vbs, get(net_if)),
Master ! worker_available;
%% We don't trap exits!
{send_trap,
TrapRec, NotifyName, ContextName, Recv, Vbs, LocalEngineID,
ExtraInfo} ->
?vtrace("worker_loop -> send trap:"
"~n ~p", [TrapRec]),
snmpa_trap:send_trap(TrapRec, NotifyName,
ContextName, Recv, Vbs,
LocalEngineID, ExtraInfo,
get(net_if)),
Master ! worker_available;
{verbosity, Verbosity} ->
put(verbosity, snmp_verbosity:validate(Verbosity));
terminate ->
exit(normal);
_X ->
%% ignore
ignore_unknown
after 30000 ->
%% This is to assure that the worker process leaves a
%% possibly old version of this module.
ok
end,
?vtrace("worker_loop -> wrap with"
"~n ~p", [Res]),
?MODULE:worker_loop(Master).
%%-----------------------------------------------------------------
%%-----------------------------------------------------------------
handle_snmp_pdu(true, Vsn, Pdu, PduMS, ACMData, Address, Extra,
#state{multi_threaded = false,
gb_max_vbs = GbMaxVBs} = S) ->
?vtrace("handle_snmp_pdu -> single-thread agent",[]),
handle_pdu2(Vsn, Pdu, PduMS, ACMData, Address, GbMaxVBs, Extra),
S;
handle_snmp_pdu(true, Vsn, #pdu{type = 'set-request'} = Pdu, PduMS,
ACMData, Address, Extra,
#state{set_worker = Worker} = S) ->
?vtrace("handle_snmp_pdu -> multi-thread agent: "
"send set-request to main worker",[]),
WRequest = ?mk_pdu_wreq(Vsn, Pdu, PduMS, ACMData, Address, infinity, Extra),
Worker ! WRequest,
S#state{worker_state = busy};
handle_snmp_pdu(true, Vsn, Pdu, PduMS,
ACMData, Address, Extra,
#state{worker_state = busy,
gb_max_vbs = GbMaxVBs} = S) ->
?vtrace("handle_snmp_pdu -> multi-thread agent: "
"main worker busy - create new worker",[]),
spawn_thread(Vsn, Pdu, PduMS, ACMData, Address, GbMaxVBs, Extra),
S;
handle_snmp_pdu(true, Vsn, Pdu, PduMS, ACMData, Address, Extra,
#state{worker = Worker,
gb_max_vbs = GbMaxVBs} = S) ->
?vtrace("handle_snmp_pdu -> multi-thread agent: "
"send to main worker",[]),
WRequest = ?mk_pdu_wreq(Vsn, Pdu, PduMS, ACMData, Address, GbMaxVBs, Extra),
Worker ! WRequest,
S#state{worker_state = busy};
handle_snmp_pdu(_, _Vsn, _Pdu, _PduMS, _ACMData, _Address, _Extra, S) ->
S.
%% Called via the spawn_thread function
%% <BACKWARD-COMPAT>
handle_pdu(Vsn, Pdu, PduMS, ACMData, Address, Extra, Dict) ->
handle_pdu(Vsn, Pdu, PduMS, ACMData, Address, ?DEFAULT_GB_MAX_VBS, Extra,
Dict).
%% </BACKWARD-COMPAT>
handle_pdu(Vsn, Pdu, PduMS, ACMData, Address, GbMaxVBs, Extra, Dict) ->
lists:foreach(fun({Key, Val}) -> put(Key, Val) end, Dict),
put(sname, pdu_handler_short_name(get(sname))),
?vlog("new worker starting",[]),
handle_pdu2(Vsn, Pdu, PduMS, ACMData, Address, GbMaxVBs, Extra).
handle_pdu2(Vsn, Pdu, PduMS, ACMData, Address, GbMaxVBs, Extra) ->
%% OTP-3324
AuthMod = get(auth_module),
case AuthMod:init_check_access(Pdu, ACMData) of
{ok, MibView, ContextName} ->
?vlog("handle_pdu -> ok:"
"~n MibView: ~p"
"~n ContextName: ~p", [MibView, ContextName]),
AgentData = cheat(ACMData, Address, ContextName),
do_handle_pdu(MibView, Vsn, Pdu, PduMS, ACMData, AgentData,
GbMaxVBs, Extra);
{error, Reason} ->
?vlog("handle_pdu -> error:"
"~n Reason: ~p", [Reason]),
handle_acm_error(Vsn, Reason, Pdu, ACMData, Address, Extra);
{discarded, Variable, Reason} ->
?vlog("handle_pdu -> discarded:"
"~n Variable: ~p"
"~n Reason: ~p", [Variable, Reason]),
get(net_if) ! {discarded_pdu, Vsn, Pdu#pdu.request_id,
ACMData, Variable, Extra}
end.
do_handle_pdu(MibView, Vsn, Pdu, PduMS,
ACMData, {Community, Address, ContextName},
GbMaxVBs, Extra) ->
put(net_if_data, Extra),
RePdu = process_msg(MibView, Vsn, Pdu, PduMS, Community,
Address, ContextName, GbMaxVBs),
?vtrace("do_handle_pdu -> processed:"
"~n RePdu: ~p", [RePdu]),
NetIf = get(net_if),
NetIf ! {snmp_response, Vsn, RePdu,
RePdu#pdu.type, ACMData, Address, Extra}.
handle_acm_error(Vsn, Reason, Pdu, ACMData, Address, Extra) ->
#pdu{type = Type, request_id = ReqId, varbinds = Vbs} = Pdu,
RawErrStatus = snmpa_acm:error2status(Reason),
case is_valid_pdu_type(Type) of
true ->
%% RawErrStatus can be authorizationError or genErr. If it is
%% authorizationError, we'll have to do different things,
%% depending on which SNMP version is used.
%% v1 - noSuchName error
%% v2 - GET: all variables 'noSuchObject'
%% NEXT/BULK: all variables 'endOfMibView'
%% SET: noAccess error
%% v3 - authorizationError error
%%
%% NOTE: this procedure is not yet defined in the coex document!
?vdebug("~n Raw error status: ~w",[RawErrStatus]),
Idx = case Vbs of
[] -> 0;
_ -> 1
end,
RePdu =
if
Vsn =:= 'version-1' ->
ErrStatus = v2err_to_v1err(RawErrStatus),
make_response_pdu(ReqId, ErrStatus, Idx, Vbs, Vbs);
Vsn =:= 'version-3' ->
make_response_pdu(ReqId, RawErrStatus, Idx, Vbs, Vbs);
Type =:= 'get-request' -> % this is v2
ReVbs = lists:map(
fun(Vb) ->
Vb#varbind{value=noSuchObject}
end,
Vbs),
make_response_pdu(ReqId, noError, 0, Vbs, ReVbs);
Type =:= 'set-request' ->
make_response_pdu(ReqId, noAccess, Idx, Vbs, Vbs);
true -> % next or bulk
ReVbs = lists:map(
fun(Vb) ->
Vb#varbind{value=endOfMibView}
end,
Vbs),
make_response_pdu(ReqId, noError, 0, Vbs, ReVbs)
end,
get(net_if) ! {snmp_response, Vsn, RePdu,
'get-response', ACMData, Address, Extra};
false ->
?vdebug("~n Raw error status: ~w"
"~n invalid pdu type: ~w",
[RawErrStatus,Type]),
ok
end.
get_send_opt(Key, Default, SendOpts) ->
case lists:keysearch(Key, 1, SendOpts) of
{value, {Key, Value}} ->
Value;
false ->
Default
end.
handle_send_trap(S, Notification, SendOpts) ->
NotifyName = get_send_opt(name, "", SendOpts),
ContextName = get_send_opt(context, "", SendOpts),
Recv = get_send_opt(receiver, no_receiver, SendOpts),
Varbinds = get_send_opt(varbinds, [], SendOpts),
ExtraInfo = get_send_opt(extra, ?DEFAULT_NOTIF_EXTRA_INFO, SendOpts),
LocalEngineID =
case lists:keysearch(local_engine_id, 1, SendOpts) of
{value, {local_engine_id, Value}} ->
Value;
false ->
local_engine_id(S)
end,
handle_send_trap(S, Notification, NotifyName, ContextName, Recv, Varbinds,
LocalEngineID, ExtraInfo).
handle_send_trap(#state{type = Type} = S,
Notification, NotifyName, ContextName, Recv, Varbinds,
LocalEngineID, ExtraInfo) ->
?vtrace("handle_send_trap -> entry with"
"~n Agent type: ~p"
"~n TrapName: ~p"
"~n NotifyName: ~p"
"~n ContextName: ~p"
"~n LocalEngineID: ~p",
[Type, Notification, NotifyName, ContextName, LocalEngineID]),
case snmpa_trap:construct_trap(Notification, Varbinds) of
{ok, TrapRecord, VarList} ->
?vtrace("handle_send_trap -> construction complete: "
"~n TrapRecord: ~p"
"~n VarList: ~p",
[TrapRecord, VarList]),
case Type of
subagent ->
?vtrace("handle_send_trap -> [sub] forward trap",[]),
maybe_forward_trap(S, TrapRecord, NotifyName,
ContextName, Recv, VarList, ExtraInfo),
{ok, S};
master_agent ->
?vtrace("handle_send_trap -> "
"[master] handle send trap",[]),
maybe_send_trap(S, TrapRecord, NotifyName,
ContextName, Recv, VarList,
LocalEngineID, ExtraInfo)
end;
error ->
error
end.
maybe_forward_trap(#state{parent = Parent, nfilters = NFs} = S,
TrapRec, NotifyName, ContextName, Recv, V, ExtraInfo) ->
?vtrace("maybe_forward_trap -> entry with"
"~n NFs: ~p", [NFs]),
case filter_notification(NFs, [], TrapRec) of
{dont_send, [], Id} ->
?vdebug("trap not forwarded [filter ~p]", [Id]),
{ok, S};
{dont_send, Removed, Id} ->
?vdebug("trap not forwarded [filter ~p]", [Id]),
NFs2 = del_notification_filter(Removed, NFs),
{ok, S#state{nfilters = NFs2}};
{send, [], TrapRec2} ->
?vtrace("maybe_forward_trap -> forward trap:"
"~n ~p", [TrapRec2]),
forward_trap(Parent, TrapRec2, NotifyName, ContextName, Recv, V,
ExtraInfo),
{ok, S};
{send, Removed, TrapRec2} ->
?vtrace("maybe_forward_trap -> forward trap:"
"~n ~p", [TrapRec2]),
forward_trap(Parent, TrapRec2, NotifyName, ContextName, Recv, V,
ExtraInfo),
NFs2 = del_notification_filter(Removed, NFs),
{ok, S#state{nfilters = NFs2}}
end.
maybe_send_trap(#state{nfilters = NFs} = S,
TrapRec, NotifyName, ContextName, Recv, Varbinds,
LocalEngineID, ExtraInfo) ->
?vtrace("maybe_send_trap -> entry with"
"~n NFs: ~p", [NFs]),
case filter_notification(NFs, [], TrapRec) of
{dont_send, [], Id} ->
?vdebug("trap not sent [filter ~p]",[Id]),
{ok, S};
{dont_send, Removed, Id} ->
?vdebug("trap not sent [filter ~p]",[Id]),
NFs2 = del_notification_filter(Removed, NFs),
{ok, S#state{nfilters = NFs2}};
{send, [], TrapRec2} ->
?vtrace("maybe_send_trap -> send trap:"
"~n ~p", [TrapRec2]),
do_handle_send_trap(S, TrapRec2,
NotifyName, ContextName, Recv, Varbinds,
LocalEngineID, ExtraInfo);
{send, Removed, TrapRec2} ->
?vtrace("maybe_send_trap -> send trap:"
"~n ~p", [TrapRec2]),
NFs2 = del_notification_filter(Removed, NFs),
do_handle_send_trap(S#state{nfilters = NFs2}, TrapRec2,
NotifyName, ContextName, Recv, Varbinds,
LocalEngineID, ExtraInfo)
end.
do_handle_send_trap(S, TrapRec, NotifyName, ContextName, Recv, Varbinds,
LocalEngineID, ExtraInfo) ->
Vbs = snmpa_trap:try_initialise_vars(get(mibserver), Varbinds),
case S#state.type of
subagent ->
forward_trap(S#state.parent, TrapRec, NotifyName, ContextName,
Recv, Vbs, ExtraInfo),
{ok, S};
master_agent when S#state.multi_threaded =:= false ->
?vtrace("do_handle_send_trap -> send trap:"
"~n ~p", [TrapRec]),
snmpa_trap:send_trap(TrapRec, NotifyName, ContextName,
Recv, Vbs, LocalEngineID, ExtraInfo,
get(net_if)),
{ok, S};
master_agent when S#state.worker_state =:= busy ->
%% Main worker busy => create new worker
?vtrace("do_handle_send_trap -> main worker busy: "
"spawn a trap sender", []),
spawn_trap_thread(TrapRec, NotifyName, ContextName, Recv, Vbs,
LocalEngineID, ExtraInfo),
{ok, S};
master_agent ->
%% Send to main worker
?vtrace("do_handle_send_trap -> send to main worker",[]),
S#state.worker ! ?mk_send_trap_wreq(TrapRec, NotifyName,
ContextName, Recv, Vbs,
LocalEngineID, ExtraInfo),
{ok, S#state{worker_state = busy}}
end.
filter_notification([], RemoveNFs, Notif) ->
?vtrace("filter_notification -> done when"
"~n RemoveNFs: ~p"
"~n Notif: ~p", [RemoveNFs, Notif]),
{send, RemoveNFs, Notif};
filter_notification([NF|NFs], RemoveNFs, Notif0) ->
?vtrace("filter_notification -> entry with"
"~n NF: ~p"
"~n RemoveNFs: ~p"
"~n Notif0: ~p", [NF, RemoveNFs, Notif0]),
case do_filter_notification(NF, Notif0) of
{dont_send, Id} ->
{dont_send, RemoveNFs, Id};
{send, Notif} ->
filter_notification(NFs, RemoveNFs, Notif);
{error, Id} ->
filter_notification(NFs, [Id|RemoveNFs], Notif0)
end.
do_filter_notification(#notification_filter{id = Id, mod = Mod, data = Data},
Notif) ->
case (catch Mod:handle_notification(Notif, Data)) of
dont_send ->
{dont_send, Id};
send ->
{send, Notif};
{send, NewNotif} ->
{send, NewNotif};
Else ->
user_err("notification filter ~p removed: ~n~p", [Id, Else]),
{error, Id}
end.
add_notification_filter(first, NewNF, NFs) ->
{ok, [NewNF | NFs]};
add_notification_filter(last, NewNF, NFs) ->
{ok, lists:append(NFs, [NewNF])};
add_notification_filter(Where, NewNF, NFs) ->
case add_nf(Where, NewNF, NFs, []) of
{ok, NFs2} ->
{ok, NFs2};
Error ->
{Error, NFs}
end.
add_nf({_Loc, Id}, _NewNF, [], _Acc) ->
{error, {not_found, Id}};
add_nf({insert_before, Id}, NewNF, [NF|NFs], Acc)
when Id =:= NF#notification_filter.id ->
{ok, lists:reverse(Acc) ++ [NewNF,NF|NFs]};
add_nf({insert_after, Id}, NewNF, [NF|NFs], Acc)
when Id =:= NF#notification_filter.id ->
{ok, lists:reverse(Acc) ++ [NF,NewNF|NFs]};
add_nf(Where, NewNF, [NF|NFs], Acc) ->
add_nf(Where, NewNF, NFs, [NF|Acc]).
del_notification_filter(IDs, NFs) ->
Fun = fun(Id, NFilters) -> lists:keydelete(Id, 2, NFilters) end,
lists:foldl(Fun, NFs, IDs).
handle_discovery(#state{type = master_agent} = S, From,
TargetName, Notification, ContextName, Varbinds,
DiscoHandler, ExtraInfo) ->
?vtrace("handle_discovery -> entry with"
"~n TargetName: ~p"
"~n Notification: ~p"
"~n ContextName: ~p"
"~n Varbinds: ~p",
[TargetName, Notification, ContextName, Varbinds]),
case snmpa_trap:construct_trap(Notification, Varbinds) of
{ok, Record, InitVars} ->
?vtrace("handle_discovery -> trap construction complete: "
"~n Record: ~p"
"~n InitVars: ~p", [Record, InitVars]),
send_discovery(S, From, TargetName,
Record, ContextName, InitVars,
DiscoHandler, ExtraInfo);
error ->
{error, failed_constructing_notification}
end;
handle_discovery(_S, _From,
_TargetName, _Notification, _ContextName, _Varbinds,
_DiscoHandler, _ExtraInfo) ->
{error, only_master_discovery}.
%% We ignore if the master agent is multi-threaded or not.
%%
send_discovery(S, From,
TargetName, Record, ContextName, InitVars,
DiscoHandler, ExtraInfo) ->
case snmpa_trap:send_discovery(TargetName, Record, ContextName,
InitVars, get(net_if), ExtraInfo) of
{ok, Sender, SecLevel} ->
Disco = #disco{from = From,
rec = Record,
sender = Sender,
target = TargetName,
sec_level = SecLevel,
ctx = ContextName,
ivbs = InitVars,
stage = 1,
handler = DiscoHandler,
extra = ExtraInfo},
{ok, S#state{disco = Disco}};
Error ->
?vlog("send_discovery -> failed sending discovery: "
"~n Error: ~p", [Error]),
Error
end.
handle_discovery_response(#state{disco = #disco{from = From}} = S,
{error, _} = Error) ->
?vlog("handle_discovery_response -> entry with"
"~n From: ~p"
"~n Error: ~p", [From, Error]),
gen_server:reply(From, Error),
S#state{disco = undefined};
handle_discovery_response(#state{disco = #disco{target = TargetName,
stage = 1,
extra = ExtraInfo} = Disco} = S,
{ok, _Pdu, ManagerEngineId})
when is_record(Disco, disco) ->
?vlog("handle_discovery_response(1) -> entry with"
"~n TargetName: ~p"
"~n ManagerEngineId: ~p", [TargetName, ManagerEngineId]),
%% This is end of stage 1.
%% So, first we need to update the database with the EngineId of the
%% manager and then deside if we should continue with stage 2. E.g.
%% establish authenticated communication.
case snmp_target_mib:set_target_engine_id(TargetName, ManagerEngineId) of
true when Disco#disco.sec_level =:= ?'SnmpSecurityLevel_noAuthNoPriv' ->
%% Ok, we are done
From = Disco#disco.from,
Handler = Disco#disco.handler,
Reply =
case handle_discovery_stage1_finish(Handler,
TargetName,
ManagerEngineId,
ExtraInfo) of
{ok, _} ->
{ok, ManagerEngineId};
Error ->
Error
end,
gen_server:reply(From, Reply),
S#state{disco = undefined};
true when Disco#disco.sec_level =/= ?'SnmpSecurityLevel_noAuthNoPriv' ->
%% Ok, time for stage 2
%% Send the same inform again,
%% this time we have the proper EngineId
From = Disco#disco.from,
Handler = Disco#disco.handler,
case handle_discovery_stage1_finish(Handler,
TargetName,
ManagerEngineId,
ExtraInfo) of
{ok, NewExtraInfo} ->
?vdebug("handle_discovery_response(1) -> "
"we are done with stage 1 - "
"continue with stage 2", []),
#disco{rec = Record,
ctx = ContextName,
ivbs = InitVars} = Disco,
case snmpa_trap:send_discovery(TargetName,
Record,
ContextName,
InitVars,
get(net_if),
ExtraInfo) of
{ok, Sender, _SecLevel} ->
?vdebug("handle_discovery_response(1) -> "
"stage 2 trap sent", []),
Disco2 = Disco#disco{sender = Sender,
engine_id = ManagerEngineId,
stage = 2,
extra = NewExtraInfo},
S#state{disco = Disco2};
Error ->
?vlog("handle_discovery_response(1) -> "
"failed sending stage 2 trap: "
"~n ~p", [Error]),
error_msg("failed sending second "
"discovery message: "
"~n ~p", [Error]),
Reply = {error, {second_send_failed, Error}},
gen_server:reply(From, Reply),
S#state{disco = undefined}
end;
{error, Reason} = Error ->
?vlog("handle_discovery_response(1) -> "
"stage 1 finish failed: "
"~n ~p", [Reason]),
gen_server:reply(From, Error),
S#state{disco = undefined}
end;
false ->
?vinfo("handle_discovery_response(1) -> "
"failed setting doscovered engine-id - "
"inform the user", []),
From = Disco#disco.from,
Reason = {failed_setting_engine_id, TargetName, ManagerEngineId},
gen_server:reply(From, {error, Reason}),
S#state{disco = undefined}
end;
handle_discovery_response(#state{disco = #disco{from = From,
engine_id = EngineID,
stage = 2}} = S,
{ok, _Pdu}) ->
?vlog("handle_discovery_response(2) -> entry with"
"~n From: ~p", [From]),
gen_server:reply(From, {ok, EngineID}),
S#state{disco = undefined};
handle_discovery_response(#state{disco = #disco{from = From}} = S, Crap) ->
Reason = {invalid_response, Crap},
gen_server:reply(From, {error, Reason}),
S#state{disco = undefined};
handle_discovery_response(S, Crap) ->
warning_msg("Received unexpected discovery response: ~p", [Crap]),
S.
handle_discovery_stage1_finish(Handler, TargetName, ManagerEngineID,
ExtraInfo) ->
case (catch Handler:stage1_finish(TargetName, ManagerEngineID,
ExtraInfo)) of
ignore ->
?vtrace("handle_discovery_stage1_finish -> "
"we are done - [ignore] inform the user", []),
{ok, ExtraInfo};
{ok, UsmEntry} when is_tuple(UsmEntry) ->
?vtrace("handle_discovery_stage1_finish -> "
"received usm entry - attempt to add it", []),
case add_usm_users([UsmEntry]) of
ok ->
{ok, ExtraInfo};
Error ->
Error
end;
{ok, UsmEntry, NewExtraInfo} when is_tuple(UsmEntry) ->
?vtrace("handle_discovery_stage1_finish -> "
"received usm entry - attempt to add it", []),
case add_usm_users([UsmEntry]) of
ok ->
{ok, NewExtraInfo};
Error ->
Error
end;
{ok, UsmEntries} when is_list(UsmEntries) ->
?vtrace("handle_discovery_stage1_finish -> "
"received usm entries - attempt to add them", []),
case add_usm_users(UsmEntries) of
ok ->
{ok, ExtraInfo};
Error ->
Error
end;
{ok, UsmEntries, NewExtraInfo} when is_list(UsmEntries) ->
?vtrace("handle_discovery_stage1_finish -> "
"received usm entries - attempt to add them", []),
case add_usm_users(UsmEntries) of
ok ->
{ok, NewExtraInfo};
Error ->
Error
end;
{'EXIT', Reason} ->
?vlog("handle_discovery_stage1_finish -> stage 1 function exited: "
"~n ~p", [Reason]),
{error, {finish_exit, Reason, ManagerEngineID}};
{error, Reason} ->
?vlog("handle_discovery_stage1_finish -> stage 1 function error: "
"~n ~p", [Reason]),
{error, {finish_error, Reason, ManagerEngineID}};
Unknown ->
?vlog("handle_discovery_stage1_finish -> stage 1 function unknown: "
"~n ~p", [Unknown]),
{error, {finish_failed, Unknown, ManagerEngineID}}
end.
add_usm_users([]) ->
ok;
add_usm_users([UsmEntry|UsmEntries]) when is_tuple(UsmEntry) ->
?vtrace("add_usm_users -> attempt to add entry (~w)",
[element(1, UsmEntry)]),
case snmp_user_based_sm_mib:add_user(UsmEntry) of
{ok, _} ->
add_usm_users(UsmEntries);
{error, Reason} ->
?vlog("add_usm_users -> failed adding usm entry: "
"~n ~p", [Reason]),
{error, {failed_adding_entry, Reason, UsmEntry}}
end.
handle_me_of(MibServer, Oid) ->
case snmpa_mib:lookup(MibServer, Oid) of
{variable, ME} ->
{ok, ME};
{table_column, ME, _TableEntryOid} ->
{ok, ME};
{subagent, SubAgentPid, _SANextOid} ->
{error, {subagent, SubAgentPid}};
{false, Reason} ->
{error, Reason};
Else ->
{error, Else}
end.
handle_mib_of(MibServer, Oid) ->
snmpa_mib:which_mib(MibServer, Oid).
%%-----------------------------------------------------------------
%% Func: process_msg/7
%% Returns: RePdu
%%-----------------------------------------------------------------
process_msg(
MibView, Vsn, Pdu, PduMS, Community,
SourceAddress, ContextName, GbMaxVBs) ->
#pdu{request_id = ReqId} = Pdu,
put(
snmp_address,
case SourceAddress of
{Domain, _} when is_atom(Domain) ->
SourceAddress;
{Ip, Port} when is_integer(Port) ->
%% Legacy transport domain
{tuple_to_list(Ip), Port}
end),
put(snmp_request_id, ReqId),
put(snmp_community, Community),
put(snmp_context, ContextName),
?vtrace("process ~p",[Pdu#pdu.type]),
process_pdu(Pdu, PduMS, Vsn, MibView, GbMaxVBs).
process_pdu(#pdu{type='get-request', request_id = ReqId, varbinds=Vbs},
_PduMS, Vsn, MibView, _GbMaxVBs) ->
?vtrace("get ~p",[ReqId]),
OrigRes = do_get(MibView, Vbs, false),
Res = get_err(OrigRes),
{ErrStatus, ErrIndex, ResVarbinds} =
if
Vsn =:= 'version-1' -> validate_get_v1(Res);
true -> Res
end,
if
(ErrStatus =/= noError) ->
?vlog("get final result: "
"~n Error status: ~p"
"~n Error index: ~p"
"~n when"
"~n Original Result: "
"~n ~p", [ErrStatus, ErrIndex, OrigRes]);
true ->
?vtrace("get final result: "
"~n Error status: ~p"
"~n Error index: ~p"
"~n Varbinds: ~p",
[ErrStatus, ErrIndex, ResVarbinds])
end,
ResponseVarbinds = lists:keysort(#varbind.org_index, ResVarbinds),
?vtrace("response varbinds: "
"~n ~p", [ResponseVarbinds]),
make_response_pdu(ReqId, ErrStatus, ErrIndex, Vbs, ResponseVarbinds);
process_pdu(#pdu{type = 'get-next-request', request_id = ReqId, varbinds = Vbs},
_PduMS, Vsn, MibView, _GbMaxVBs) ->
?vtrace("process get-next-request -> entry with"
"~n ReqId: ~p"
"~n Vbs: ~p"
"~n MibView: ~p", [ReqId, Vbs, MibView]),
OrigRes = do_get_next(MibView, Vbs),
Res = get_err(OrigRes),
{ErrStatus, ErrIndex, ResVarbinds} =
if
Vsn =:= 'version-1' -> validate_next_v1(Res, MibView);
true -> Res
end,
if
(ErrStatus =/= noError) ->
?vlog("get-next final result: "
"~n Error status: ~p"
"~n Error index: ~p"
"~n when"
"~n Original Result: "
"~n ~p", [ErrStatus, ErrIndex, OrigRes]);
true ->
?vtrace("get-next final result:"
"~n Error status: ~p"
"~n Error index: ~p"
"~n Varbinds: ~p", [ErrStatus, ErrIndex, ResVarbinds])
end,
ResponseVarbinds = lists:keysort(#varbind.org_index, ResVarbinds),
?vtrace("get-next final result -> response varbinds: "
"~n ~p", [ResponseVarbinds]),
make_response_pdu(ReqId, ErrStatus, ErrIndex, Vbs, ResponseVarbinds);
process_pdu(#pdu{type = 'get-bulk-request',
request_id = ReqId,
varbinds = Vbs,
error_status = NonRepeaters,
error_index = MaxRepetitions},
PduMS, _Vsn, MibView, GbMaxVBs) ->
OrigRes = do_get_bulk(MibView, NonRepeaters, MaxRepetitions, PduMS, Vbs,
GbMaxVBs),
{ErrStatus, ErrIndex, ResponseVarbinds} = get_err(OrigRes),
if
(ErrStatus =/= noError) ->
?vlog("get-bulk final result: "
"~n Error Status: ~p"
"~n Error Index: ~p"
"~n when"
"~n Original Result: "
"~n ~p", [ErrStatus, ErrIndex, OrigRes]);
true ->
?vtrace("get-bulk final result: "
"~n Error status: ~p"
"~n Error index: ~p"
"~n Response Varbinds: ~p",
[ErrStatus, ErrIndex, ResponseVarbinds])
end,
make_response_pdu(ReqId, ErrStatus, ErrIndex, Vbs, ResponseVarbinds);
process_pdu(#pdu{type = 'set-request', request_id = ReqId, varbinds = Vbs},
_PduMS, Vsn, MibView, _GbMaxVbs) ->
OrigRes = do_set(MibView, Vbs),
{ErrStatus, ErrIndex} =
if
Vsn =:= 'version-1' -> validate_err(v2_to_v1, OrigRes);
true -> OrigRes
end,
if
(ErrStatus =/= noError) ->
?vlog("set final result: "
"~n Error Status: ~p"
"~n Error Index: ~p"
"~n when"
"~n Original Result: "
"~n ~p", [ErrStatus, ErrIndex, OrigRes]);
true ->
?vtrace("set final result: "
"~n Error Status: ~p"
"~n Error Index: ~p", [ErrStatus, ErrIndex])
end,
make_response_pdu(ReqId, ErrStatus, ErrIndex, Vbs, Vbs).
%%-----------------------------------------------------------------
%% Transform a value == noSuchInstance | noSuchObject or a
%% Counter64 type to a noSuchName error for the whole pdu.
%% Args: {Error, Index, Vbs}
%% Returns: {NewError, NewIndex, NewVbs}
%%-----------------------------------------------------------------
validate_get_v1({noError, _, ResponseVarbinds}) ->
case validate_get_v1_2(ResponseVarbinds) of
true -> {noError, 0, ResponseVarbinds};
{Error, Index} -> {Error, Index, []} % dummy vbs
end;
validate_get_v1({ErrStatus, ErrIndex, ResponseVarbinds}) ->
{v2err_to_v1err(ErrStatus), ErrIndex, ResponseVarbinds}.
validate_get_v1_2([Vb | Vbs])
when ((Vb#varbind.value =/= noSuchInstance) andalso
(Vb#varbind.value =/= noSuchObject) andalso
(Vb#varbind.variabletype =/= 'Counter64')) ->
validate_get_v1_2(Vbs);
validate_get_v1_2([Vb | _Vbs]) ->
{noSuchName, Vb#varbind.org_index};
validate_get_v1_2([]) ->
true.
%%-----------------------------------------------------------------
%% Transform a value == endOfMibView to a noSuchName for the
%% whole pdu, and do another get-next for any Counter64 value.
%% Args: {Error, Index, Vbs}
%% Returns: {NewError, NewIndex, NewVbs}
%%-----------------------------------------------------------------
validate_next_v1({noError, _, ResponseVarbinds}, MibView) ->
case validate_next_v1_2(ResponseVarbinds, MibView, []) of
{true, NVbs} -> {noError, 0, NVbs};
{Error, Index} -> {Error, Index, []} % dummy vbs
end;
validate_next_v1({ErrStatus, ErrIndex, ResponseVarbinds}, _MibView) ->
{v2err_to_v1err(ErrStatus), ErrIndex, ResponseVarbinds}.
validate_next_v1_2([Vb | _Vbs], _MibView, _Res)
when Vb#varbind.value =:= endOfMibView ->
{noSuchName, Vb#varbind.org_index};
validate_next_v1_2([Vb | Vbs], MibView, Res)
when Vb#varbind.variabletype =:= 'Counter64' ->
case validate_next_v1( do_get_next(MibView, [mk_next_oid(Vb)]), MibView) of
{noError, 0, [NVb]} ->
validate_next_v1_2(Vbs, MibView, [NVb | Res]);
{Error, Index, _OrgVb} ->
{Error, Index}
end;
validate_next_v1_2([Vb | Vbs], MibView, Res) ->
validate_next_v1_2(Vbs, MibView, [Vb | Res]);
validate_next_v1_2([], _MibView, Res) ->
{true, Res}.
%%-----------------------------------------------------------------
%% Optimization. When we get to a Counter64 object that is a table
%% column, we'll try to find the next instance. This will be the
%% next row in the table, which is a Counter64 value as well. This
%% means that we will loop through the entire table, until we find
%% a column that isn't a Counter64 column. We can optimze this by
%% adding 1 to the column-no in the oid of this instance.
%% If the table is implemented by a subagent this does not help,
%% we'll call that subagent many times. But it shouldn't be any
%% problems.
%%-----------------------------------------------------------------
mk_next_oid(Vb) ->
case snmpa_mib:lookup(get(mibserver), Oid = Vb#varbind.oid) of
{table_column, _MibEntry, TableEntryOid} ->
[Col | _] = Oid -- TableEntryOid,
Vb#varbind{oid = TableEntryOid ++ [Col+1]};
_ ->
Vb
end.
%%%-----------------------------------------------------------------
%%% 3. GET REQUEST
%%% --------------
%%% According to RFC1157, section 4.1.2 and RFC1905, section 4.2.1.
%%% In rfc1157:4.1.2 it isn't specified if noSuchName should be
%%% returned even if some other varbind generates a genErr.
%%% In rfc1905:4.2.1 this is not a problem since exceptions are
%%% used, and thus a genErr will be returned anyway.
%%%-----------------------------------------------------------------
%%-----------------------------------------------------------------
%% Func: do_get/2
%% Purpose: Handles all VBs in a request that is inside the
%% mibview (local).
%% Returns: {noError, 0, ListOfNewVarbinds} |
%% {ErrorStatus, ErrorIndex, []}
%%-----------------------------------------------------------------
do_get(UnsortedVarbinds, IsNotification) ->
Extra = get(net_if_data),
GetModule = get(get_module),
GetModule:do_get(UnsortedVarbinds, IsNotification, Extra).
%%-----------------------------------------------------------------
%% Func: do_get/3
%% Purpose: do_get handles "getRequests".
%% Pre: incoming varbinds have type == 'NULL', value == unSpecified
%% Returns: {noError, 0, ListOfNewVarbinds} |
%% {ErrorStatus, ErrorIndex, []}
%%-----------------------------------------------------------------
%% If this function is called from a worker-process (or other process),
%% we *may* need to tunnel into the master-agent and let it do the work.
do_get(MibView, UnsortedVarbinds, IsNotification) ->
Extra = get(net_if_data),
GetModule = get(get_module),
GetModule:do_get(MibView, UnsortedVarbinds, IsNotification, Extra).
do_get(MibView, UnsortedVarbinds, IsNotification, ForceMaster) ->
case (whereis(snmp_master_agent) =:= self()) of
false when (ForceMaster =:= true) ->
PduData = get_pdu_data(),
call(snmp_master_agent,
{do_get, MibView, UnsortedVarbinds, IsNotification, PduData});
_ ->
do_get(MibView, UnsortedVarbinds, IsNotification)
end.
%%%-----------------------------------------------------------------
%%% 4. GET-NEXT REQUEST
%%% --------------
%%% According to RFC1157, section 4.1.3 and RFC1905, section 4.2.2.
%%%-----------------------------------------------------------------
%%-----------------------------------------------------------------
%% Func: do_get_next/2
%% Purpose: do_get_next handles "getNextRequests".
%% Note: Even if it is SNMPv1, a varbind's value can be
%% endOfMibView. This is converted to noSuchName in process_pdu.
%% Returns: {noError, 0, ListOfNewVarbinds} |
%% {ErrorStatus, ErrorIndex, []}
%% Note2: ListOfNewVarbinds is not sorted in any order!!!
%% Alg: First, the variables are sorted in OID order.
%%
%% Second, next in the MIB is performed for each OID, and
%% the result is collected as: if next oid is a variable,
%% perform a get to retrieve its value; if next oid is in a
%% table, save this value and continue until we get an oid
%% outside this table. Then perform get_next on the table,
%% and continue with all endOfTables and the oid outside the
%% table; if next oid is an subagent, save this value and
%% continue as in the table case.
%%
%% Third, each response is checked for endOfMibView, or (for
%% subagents) that the Oid returned has the correct prefix.
%% (This is necessary since an SA can be registered under many
%% separated subtrees, and if the last variable in the first
%% subtree is requested in a next, the SA will return the first
%% variable in the second subtree. This might be working, since
%% there may be a variable in between these subtrees.) For each
%% of these, a new get-next is performed, one at a time.
%% This alg. might be optimised in several ways. The most
%% striking one is that the same SA might be called several
%% times, when one time should be enough. But it isn't clear
%% that this really matters, since many nexts across the same
%% subagent must be considered to be very rare.
%%-----------------------------------------------------------------
do_get_next(MibView, UnsortedVarbinds) ->
Extra = get(net_if_data),
GetModule = get(get_module),
GetModule:do_get_next(MibView, UnsortedVarbinds, Extra).
%%%-----------------------------------------------------------------
%%% 5. GET-BULK REQUEST
%%%
%%% In order to prevent excesses in reply sizes there are two
%%% preventive methods in place. One is to check that the encode
%%% size does not exceed Max PDU size (this is mentioned in the
%%% standard). The other is a simple VBs limit. That is, the
%%% resulting response cannot contain more then this number of VBs.
%%%-----------------------------------------------------------------
do_get_bulk(MibView, NonRepeaters, MaxRepetitions, PduMS, Varbinds, GbMaxVBs) ->
Extra = get(net_if_data),
GetModule = get(get_module),
GetModule:do_get_bulk(MibView, NonRepeaters, MaxRepetitions,
PduMS, Varbinds, GbMaxVBs,
Extra).
%%%--------------------------------------------------
%%% 6. SET REQUEST
%%%--------------------------------------------------
%% return: {ErrStatus, ErrIndex}
%% where ErrIndex is an index in Varbinds list (not org_index (user-functions
%% doesn't see org_index)).
do_set(MibView, UnsortedVarbinds) ->
SetModule = get(set_module),
?vtrace("set module: ~p",[SetModule]),
apply(SetModule, do_set, [MibView, UnsortedVarbinds]).
do_subagent_set(Arguments) ->
SetModule = get(set_module),
apply(SetModule, do_subagent_set, [Arguments]).
%%%-----------------------------------------------------------------
%%% 7. Misc functions
%%%-----------------------------------------------------------------
make_response_pdu(ReqId, ErrStatus, ErrIndex, OrgVarbinds, _ResponseVarbinds)
when ErrIndex =/= 0 ->
#pdu{type = 'get-response', request_id = ReqId, error_status = ErrStatus,
error_index = ErrIndex, varbinds = OrgVarbinds};
make_response_pdu(ReqId, ErrStatus, ErrIndex, _OrgVarbinds, ResponseVarbinds) ->
#pdu{type = 'get-response', request_id = ReqId, error_status = ErrStatus,
error_index = ErrIndex, varbinds = ResponseVarbinds}.
%% Valid errormsgs for different operations.
validate_err(consistency_check, {'EXIT', _Reason}, _) ->
{genErr, 0};
validate_err(consistency_check, X, _) ->
X;
validate_err(is_set_ok, noError, _) -> noError;
validate_err(is_set_ok, noCreation, _) -> noCreation;
validate_err(is_set_ok, inconsistentValue, _) -> inconsistentValue;
validate_err(is_set_ok, resourceUnavailable, _) -> resourceUnavailable;
validate_err(is_set_ok, inconsistentName, _) -> inconsistentName;
validate_err(is_set_ok, badValue, _) -> badValue;
validate_err(is_set_ok, wrongValue, _) -> wrongValue;
validate_err(is_set_ok, noSuchName, _) -> noSuchName;
validate_err(is_set_ok, noAccess, _) -> noAccess;
validate_err(is_set_ok, notWritable, _) -> notWritable;
validate_err(is_set_ok, genErr, _) -> genErr;
validate_err(is_set_ok, X, Mfa) ->
user_err("~w with is_set_ok, returned: ~w. Using genErr.",
[Mfa, X]),
genErr;
validate_err(set, commitFailed, _) -> commitFailed;
validate_err(set, undoFailed, _) -> undoFailed;
validate_err(set, noError, _) -> noError;
validate_err(set, genErr, _) -> genErr;
validate_err(set, X, Mfa) ->
user_err("~w with set, returned: ~w. Using genErr.",
[Mfa, X]),
genErr;
validate_err(undo, undoFailed, _) -> undoFailed;
validate_err(undo, noError, _) -> noError;
validate_err(undo, genErr, _) -> genErr;
validate_err(undo, X, Mfa) ->
user_err("~w with undo, returned: ~w. Using genErr.",
[Mfa, X]),
genErr;
validate_err(table_is_set_ok, {Err, Idx}, Mfa) when is_integer(Idx) ->
{validate_err(is_set_ok, Err, Mfa), Idx};
validate_err(table_is_set_ok, X, Mfa) ->
user_err("~w with is_set_ok (table), returned: ~w. Using genErr.",
[Mfa, X]),
{genErr, 0};
validate_err(row_is_set_ok, {Err, Idx}, _) when is_integer(Idx) ->
{Err, Idx};
validate_err(row_is_set_ok, {_Err, {false, BadCol}}, Mfa) ->
user_err("~w with is_set_ok (table), returned bad column: "
"~w. Using genErr.", [Mfa, BadCol]),
{genErr, 0};
validate_err(table_undo, {Err, Idx}, Mfa) when is_integer(Idx) ->
{validate_err(undo, Err, Mfa), Idx};
validate_err(table_undo, X, Mfa) ->
user_err("~w with undo (table), returned: ~w. Using genErr.",
[Mfa, X]),
{genErr, 0};
validate_err(row_undo, {Err, Idx}, _) when is_integer(Idx) ->
{Err, Idx};
validate_err(row_undo, {_Err, {false, BadCol}}, Mfa) ->
user_err("~w with undo (table), returned bad column: "
"~w. Using genErr.", [Mfa, BadCol]),
{genErr, 0};
validate_err(table_set, {Err, Idx}, Mfa) when is_integer(Idx) ->
{validate_err(set, Err, Mfa), Idx};
validate_err(table_set, X, Mfa) ->
user_err("~w with set (table), returned: ~w. Using genErr.",
[Mfa, X]),
{genErr, 0};
validate_err(row_set, {Err, Idx}, _) when is_integer(Idx) ->
{Err, Idx};
validate_err(row_set, {_Err, {false, BadCol}}, Mfa) ->
user_err("~w with set (table), returned bad column: "
"~w. Using genErr.", [Mfa, BadCol]),
{genErr, 0};
validate_err(table_next, {Err, Idx}, _Mfa) when is_integer(Idx) ->
{Err, Idx};
validate_err(table_next, {_Err, {false, BadCol}}, Mfa) ->
user_err("~w with get_next, returned bad column: "
"~w. Using genErr.", [Mfa, BadCol]),
{genErr, 0}.
validate_err(v2_to_v1, {V2Err, Index}) ->
{v2err_to_v1err(V2Err), Index};
validate_err(v2_to_v1, _) ->
{genErr, 0}.
get_err({ErrC, ErrI, Vbs}) ->
{get_err_i(ErrC), ErrI, Vbs}.
get_err_i(noError) -> noError;
get_err_i(tooBig) -> tooBig; % OTP-9700
get_err_i(ES) -> ?vtrace("convert ErrorStatus '~p' to 'genErr'", [ES]), genErr.
v2err_to_v1err(noError) -> noError;
v2err_to_v1err(noAccess) -> noSuchName;
v2err_to_v1err(noCreation) -> noSuchName;
v2err_to_v1err(notWritable) -> noSuchName;
v2err_to_v1err(wrongLength) -> badValue;
v2err_to_v1err(wrongEncoding) -> badValue;
v2err_to_v1err(wrongType) -> badValue;
v2err_to_v1err(wrongValue) -> badValue;
v2err_to_v1err(inconsistentValue) -> badValue;
v2err_to_v1err(inconsistentName) -> noSuchName;
v2err_to_v1err(noSuchName) -> noSuchName;
v2err_to_v1err(badValue) -> badValue;
v2err_to_v1err(authorizationError) -> noSuchName;
%% genErr | resourceUnavailable | undoFailed | commitFailed -> genErr
v2err_to_v1err(_Error) -> genErr.
%%-----------------------------------------------------------------
%% transforms a (hopefully correct) return value ((perhaps) from a
%% mib-function) to a typed and guaranteed correct return value.
%% An incorrect return value is transformed to {error, genErr}.
%% A correct return value is on the form:
%% {error, <error-msg>} | {value, <variable-type>, <value>}
%%-----------------------------------------------------------------
make_value_a_correct_value({value, Val}, Asn1, Mfa)
when Asn1#asn1_type.bertype =:= 'INTEGER' ->
check_integer(Val, Asn1, Mfa);
make_value_a_correct_value({value, Val}, Asn1, Mfa)
when Asn1#asn1_type.bertype =:= 'Counter32' ->
check_integer(Val, Asn1, Mfa);
make_value_a_correct_value({value, Val}, Asn1, Mfa)
when Asn1#asn1_type.bertype =:= 'Unsigned32' ->
check_integer(Val, Asn1, Mfa);
make_value_a_correct_value({value, Val}, Asn1, Mfa)
when Asn1#asn1_type.bertype =:= 'TimeTicks' ->
check_integer(Val, Asn1, Mfa);
make_value_a_correct_value({value, Val}, Asn1, Mfa)
when Asn1#asn1_type.bertype =:= 'Counter64' ->
check_integer(Val, Asn1, Mfa);
make_value_a_correct_value({value, Val}, Asn1, Mfa)
when (Asn1#asn1_type.bertype =:= 'BITS') andalso is_list(Val) ->
{value,Kibbles} = snmp_misc:assq(kibbles,Asn1#asn1_type.assocList),
case snmp_misc:bits_to_int(Val,Kibbles) of
error ->
wrongValue(Val, Mfa);
Int ->
make_value_a_correct_value({value,Int},Asn1,Mfa)
end;
make_value_a_correct_value({value, Val}, Asn1, Mfa)
when (Asn1#asn1_type.bertype =:= 'BITS') andalso is_integer(Val) ->
{value,Kibbles} = snmp_misc:assq(kibbles,Asn1#asn1_type.assocList),
{_Kibble,BitNo} = lists:last(Kibbles),
case (1 bsl (BitNo+1)) of
X when Val < X ->
{value,'BITS',Val};
_Big ->
wrongValue(Val, Mfa)
end;
make_value_a_correct_value({value, String},
#asn1_type{bertype = 'OCTET STRING',
hi = Hi, lo = Lo}, Mfa) ->
check_octet_string(String, Hi, Lo, Mfa, 'OCTET STRING');
make_value_a_correct_value({value, String},
#asn1_type{bertype = 'IpAddress',
hi = Hi, lo = Lo}, Mfa) ->
check_octet_string(String, Hi, Lo, Mfa, 'IpAddress');
make_value_a_correct_value({value, Oid},
#asn1_type{bertype = 'OBJECT IDENTIFIER'},
_Mfa) ->
case snmp_misc:is_oid(Oid) of
true -> {value, 'OBJECT IDENTIFIER', Oid};
_Else -> {error, wrongType}
end;
make_value_a_correct_value({value, Val}, Asn1, _Mfa)
when Asn1#asn1_type.bertype =:= 'Opaque' ->
if is_list(Val) -> {value, 'Opaque', Val};
true -> {error, wrongType}
end;
make_value_a_correct_value({noValue, noSuchObject}, _ASN1Type, _Mfa) ->
{value, noValue, noSuchObject};
make_value_a_correct_value({noValue, noSuchInstance}, _ASN1Type, _Mfa) ->
{value, noValue, noSuchInstance};
make_value_a_correct_value({noValue, noSuchName}, _ASN1Type, _Mfa) ->
%% Transform this into a v2 value. It is converted to noSuchName
%% later if it was v1. If it was v2, we use noSuchInstance.
{value, noValue, noSuchInstance};
%% For backwards compatibility only - we really shouldn't allow this;
%% it makes no sense to return unSpecified for a variable! But we did
%% allow it previously. -- We transform unSpecified to noSuchInstance
%% (OTP-3303).
make_value_a_correct_value({noValue, unSpecified}, _ASN1Type, _Mfa) ->
{value, noValue, noSuchInstance};
make_value_a_correct_value(genErr, _ASN1Type, _MFA) ->
{error, genErr};
make_value_a_correct_value(_WrongVal, _ASN1Type, undef) ->
{error, genErr};
make_value_a_correct_value(WrongVal, ASN1Type, Mfa) ->
user_err("Got ~w from ~w. (~w) Using genErr",
[WrongVal, Mfa, ASN1Type]),
{error, genErr}.
check_integer(Val, Asn1, Mfa) ->
case Asn1#asn1_type.assocList of
undefined -> check_size(Val, Asn1, Mfa);
Alist ->
case snmp_misc:assq(enums, Alist) of
{value, Enums} -> check_enums(Val, Asn1, Enums, Mfa);
false -> check_size(Val, Asn1, Mfa)
end
end.
check_octet_string(String, Hi, Lo, Mfa, Type) ->
Len = (catch length(String)), % it might not be a list
case snmp_misc:is_string(String) of
true when Lo =:= undefined -> {value, Type, String};
true when Len =< Hi, Len >= Lo ->
{value, Type, String};
true ->
wrongLength(String, Mfa);
_Else ->
wrongType(String, Mfa)
end.
check_size(Val, #asn1_type{lo = Lo, hi = Hi, bertype = Type}, Mfa)
when is_integer(Val) ->
?vtrace("check size of integer: "
"~n Value: ~p"
"~n Upper limit: ~p"
"~n Lower limit: ~p"
"~n BER-type: ~p",
[Val,Hi,Lo,Type]),
if
(Lo =:= undefined) andalso (Hi =:= undefined) -> {value, Type, Val};
(Lo =:= undefined) andalso is_integer(Hi) andalso (Val =< Hi) ->
{value, Type, Val};
is_integer(Lo) andalso (Val >= Lo) andalso (Hi =:= undefined) ->
{value, Type, Val};
is_integer(Lo) andalso is_integer(Hi) andalso (Val >= Lo) andalso (Val =< Hi) ->
{value, Type, Val};
true ->
wrongValue(Val, Mfa)
end;
check_size(Val, _, Mfa) ->
wrongType(Val, Mfa).
check_enums(Val, Asn1, Enums, Mfa) ->
Association =
if
is_integer(Val) -> lists:keysearch(Val, 2, Enums);
is_atom(Val) -> lists:keysearch(Val, 1, Enums);
true -> {error, wrongType}
end,
case Association of
{value, {_AliasIntName, Val2}} ->
{value, Asn1#asn1_type.bertype, Val2};
false ->
wrongValue(Val, Mfa);
{error, wrongType} ->
wrongType(Val, Mfa)
end.
wrongLength(Val, Mfa) ->
report_err(Val, Mfa, wrongLength).
wrongValue(Val, Mfa) ->
report_err(Val, Mfa, wrongValue).
wrongType(Val, Mfa) ->
report_err(Val, Mfa, wrongType).
report_err(_Val, undef, Err) ->
{error, Err};
report_err(Val, Mfa, Err) ->
user_err("Got ~p from ~w. Using ~w", [Val, Mfa, Err]),
{error, Err}.
is_valid_pdu_type('get-request') -> true;
is_valid_pdu_type('get-next-request') -> true;
is_valid_pdu_type('get-bulk-request') -> true;
is_valid_pdu_type('set-request') -> true;
is_valid_pdu_type(_) -> false.
get_pdu_data() ->
{get(net_if_data),
get(snmp_request_id),
get(snmp_address),
get(snmp_community),
get(snmp_context)}.
put_pdu_data({Extra, ReqId, Address, Community, ContextName}) ->
{put(net_if_data, Extra),
put(snmp_address, Address),
put(snmp_request_id, ReqId),
put(snmp_community, Community),
put(snmp_context, ContextName)}.
tr_var(Oid, Idx) ->
case snmp_misc:is_oid(Oid) of
true ->
{#varbind{oid = Oid, value = unSpecified, org_index = Idx},
Idx+1};
false -> throw({error, {bad_oid, Oid}})
end.
tr_varbind(#varbind{value = Value}) -> Value.
mapfoldl(F, Eas, Accu0, [Hd|Tail]) ->
{R,Accu1} = apply(F, [Hd,Accu0|Eas]),
{Accu2,Rs} = mapfoldl(F, Eas, Accu1, Tail),
{Accu2,[R|Rs]};
mapfoldl(_F, _Eas, Accu, []) -> {Accu,[]}.
%% ---------------------------------------------------------------------
short_name(none) -> ma;
short_name(_Pid) -> sa.
worker_short_name(ma) -> maw;
worker_short_name(_) -> saw.
trap_sender_short_name(ma) -> mats;
trap_sender_short_name(_) -> sats.
pdu_handler_short_name(ma) -> maph;
pdu_handler_short_name(_) -> saph.
mib_server_verbosity(Pid,Verbosity) when is_pid(Pid) ->
snmpa_mib:verbosity(Pid,Verbosity);
mib_server_verbosity(_Pid,_Verbosity) ->
ok.
note_store_verbosity(Pid,Verbosity) when is_pid(Pid) ->
snmp_note_store:verbosity(Pid,Verbosity);
note_store_verbosity(_Pid,_Verbosity) ->
ok.
subagents_verbosity(V) ->
subagents_verbosity(catch snmpa_mib:info(get(mibserver),subagents),V).
subagents_verbosity([],_V) ->
ok;
subagents_verbosity([{Pid,_Oid}|T],V) ->
catch verbosity(Pid,V), %% On the agent
catch verbosity(Pid,{subagents,V}), %% and it's subagents
subagents_verbosity(T,V);
subagents_verbosity(_,_V) ->
ok.
%% ---------------------------------------------------------------------
local_engine_id(#state{type = master_agent}) ->
?DEFAULT_LOCAL_ENGINE_ID;
local_engine_id(_) ->
%% subagent -
%% we don't need this now, eventually the trap send
%% request will reach the master-agent and then it
%% will look up the proper engine id.
ignore.
%% ---------------------------------------------------------------------
handle_get_log_type(#state{net_if_mod = Mod})
when Mod =/= undefined ->
case (catch Mod:get_log_type(get(net_if))) of
{'EXIT', _} ->
{error, not_supported};
Else ->
Else
end;
handle_get_log_type(_) ->
{error, not_supported}.
handle_set_log_type(#state{net_if_mod = Mod}, NewType)
when Mod =/= undefined ->
case (catch Mod:set_log_type(get(net_if), NewType)) of
{'EXIT', _} ->
{error, not_supported};
Else ->
Else
end;
handle_set_log_type(_, _) ->
{error, not_supported}.
handle_get_request_limit(#state{net_if_mod = Mod})
when Mod =/= undefined ->
case (catch Mod:get_request_limit(get(net_if))) of
{'EXIT', _} ->
{error, not_supported};
Else ->
Else
end;
handle_get_request_limit(_) ->
{error, not_supported}.
handle_set_request_limit(#state{net_if_mod = Mod}, NewLimit)
when Mod =/= undefined ->
case (catch Mod:set_request_limit(get(net_if), NewLimit)) of
{'EXIT', _} ->
{error, not_supported};
Else ->
Else
end;
handle_set_request_limit(_, _) ->
{error, not_supported}.
agent_info(#state{worker = W, set_worker = SW}) ->
case (catch get_agent_info(W, SW)) of
Info when is_list(Info) ->
Info;
E ->
[{error, E}]
end.
get_agent_info(W, SW) ->
MASz = proc_mem(self()),
WSz = proc_mem(W),
SWSz = proc_mem(SW),
ATSz = tab_mem(snmp_agent_table),
CCSz = tab_mem(snmp_community_cache),
VacmSz = tab_mem(snmpa_vacm),
[{process_memory, [{master_agent, MASz},
{worker, WSz},
{set_worker, SWSz}]},
{db_memory, [{agent, ATSz},
{community_cache, CCSz},
{vacm, VacmSz}]}].
proc_mem(P) when is_pid(P) ->
case (catch erlang:process_info(P, memory)) of
{memory, Sz} when is_integer(Sz) ->
Sz;
_ ->
undefined
end;
proc_mem(_) ->
undefined.
tab_mem(T) ->
case (catch ets:info(T, memory)) of
Sz when is_integer(Sz) ->
Sz;
_ ->
undefined
end.
net_if_info(#state{net_if_mod = Mod}) when Mod =/= undefined ->
case (catch Mod:info(get(net_if))) of
Info when is_list(Info) ->
Info;
E ->
[{error, E}]
end;
net_if_info(_) ->
%% This could be a result of a code upgrade
%% Make best effert
[{process_memory, proc_mem(get(net_if))}].
note_store_info(#state{note_store = NS}) ->
case (catch snmp_note_store:info(NS)) of
Info when is_list(Info) ->
Info;
E ->
[{error, E}]
end.
symbolic_store_info() ->
case (catch snmpa_symbolic_store:info()) of
Info when is_list(Info) ->
Info;
E ->
[{error, E}]
end.
local_db_info() ->
case (catch snmpa_local_db:info()) of
Info when is_list(Info) ->
Info;
E ->
[{error, E}]
end.
mib_server_info() ->
case (catch snmpa_mib:info(get(mibserver))) of
Info when is_list(Info) ->
Info;
E ->
[{error, E}]
end.
get_stats_counters() ->
Counters = snmpa_mpd:counters(),
get_stats_counters(Counters, []).
get_stats_counters([], Acc) ->
lists:reverse(Acc);
get_stats_counters([Counter|Counters], Acc) ->
case ets:lookup(snmp_agent_table, Counter) of
[CounterVal] ->
get_stats_counters(Counters, [CounterVal|Acc]);
_ ->
get_stats_counters(Counters, Acc)
end.
%% ---------------------------------------------------------------------
%% info_msg(F, A) ->
%% ?snmpa_info(F, A).
warning_msg(F, A) ->
?snmpa_warning(F, A).
error_msg(F, A) ->
?snmpa_error(F, A).
%% ---
config_err(F, A) ->
snmpa_error:config_err(F, A).
user_err(F, A) ->
snmpa_error:user_err(F, A).
%% ---------------------------------------------------------------------
maybe_call(Server, Req) ->
case (wis(Server) =:= self()) of
false ->
call(Server, Req);
true ->
Server ! Req
end.
call(Server, Req) ->
gen_server:call(Server, Req, infinity).
cast(Server, Msg) ->
gen_server:cast(Server, Msg).
%% ---------------------------------------------------------------------
get_verbosity(Opts) ->
get_option(verbosity, Opts, ?default_verbosity).
get_mibs(Opts) ->
get_option(mibs, Opts, []).
get_mib_storage(Opts) ->
get_option(mib_storage, Opts).
get_set_mechanism(Opts) ->
get_option(set_mechanism, Opts, snmpa_set).
get_get_mechanism(Opts) ->
get_option(get_mechanism, Opts, snmpa_get).
get_authentication_service(Opts) ->
get_option(authentication_service, Opts, snmpa_acm).
get_multi_threaded(Opts) ->
get_option(multi_threaded, Opts, false).
get_versions(Opts) ->
get_option(versions, Opts, [v1,v2,v3]).
get_gb_max_vbs(Opts) ->
get_option(gb_max_vbs, Opts, infinity).
get_note_store_opt(Opts) ->
get_option(note_store, Opts, []).
get_net_if_opt(Opts) ->
get_option(net_if, Opts, []).
get_net_if_verbosity(Opts) ->
get_option(verbosity, Opts, silence).
get_net_if_module(Opts) ->
get_option(module, Opts, snmpa_net_if).
get_net_if_options(Opts) ->
get_option(options, Opts, []).
net_if_verbosity(Pid,Verbosity) when is_pid(Pid) ->
Pid ! {verbosity,Verbosity};
net_if_verbosity(_Pid,_Verbosity) ->
ok.
get_option(Key, Opts) ->
snmp_misc:get_option(Key, Opts).
get_option(Key, Opts, Default) ->
snmp_misc:get_option(Key, Opts, Default).
%% ---------------------------------------------------------------------
%% i(F) ->
%% i(F, []).
%% i(F, A) ->
%% io:format("~p: " ++ F ++ "~n", [?MODULE|A]).
|