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

                      All Rights Reserved

Permission to use, copy, modify, and distribute this software and its 
documentation for any purpose and without fee is hereby granted, 
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in 
supporting documentation, and that the name of CMU not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.  

CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
******************************************************************/
/*
 * Portions of this file are copyrighted by:
 * Copyright © 2003 Sun Microsystems, Inc. All rights 
 * reserved.  Use is subject to license terms specified in the 
 * COPYING file distributed with the Net-SNMP package.
 */
/** @defgroup snmp_agent net-snmp agent related processing 
 *  @ingroup agent
 *
 * @{
 */
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-features.h>

#include <sys/types.h>
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#if HAVE_STRING_H
#include <string.h>
#endif
#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
#  include <sys/time.h>
# else
#  include <time.h>
# endif
#endif
#if HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#if HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#include <errno.h>

#define SNMP_NEED_REQUEST_LIST
#include <net-snmp/net-snmp-includes.h>
#include <net-snmp/agent/net-snmp-agent-includes.h>
#include <net-snmp/library/snmp_assert.h>

#if HAVE_SYSLOG_H
#include <syslog.h>
#endif

#ifdef NETSNMP_USE_LIBWRAP
#include <tcpd.h>
int             allow_severity = LOG_INFO;
int             deny_severity = LOG_WARNING;
#endif

#include "snmpd.h"
#include <net-snmp/agent/mib_module_config.h>
#include <net-snmp/agent/mib_modules.h>

#ifdef USING_AGENTX_PROTOCOL_MODULE
#include "agentx/protocol.h"
#endif

#ifdef USING_AGENTX_MASTER_MODULE
#include "agentx/master.h"
#endif

#ifdef USING_SMUX_MODULE
#include "smux/smux.h"
#endif

netsnmp_feature_child_of(snmp_agent, libnetsnmpagent)
netsnmp_feature_child_of(agent_debugging_utilities, libnetsnmpagent)

netsnmp_feature_child_of(allocate_globalcacheid, snmp_agent)
netsnmp_feature_child_of(free_agent_snmp_session_by_session, snmp_agent)
netsnmp_feature_child_of(check_all_requests_error, snmp_agent)
netsnmp_feature_child_of(check_requests_error, snmp_agent)
netsnmp_feature_child_of(request_set_error_idx, snmp_agent)
netsnmp_feature_child_of(set_agent_uptime, snmp_agent)
netsnmp_feature_child_of(agent_check_and_process, snmp_agent)

netsnmp_feature_child_of(dump_sess_list, agent_debugging_utilities)

netsnmp_feature_child_of(agent_remove_list_data, netsnmp_unused)
netsnmp_feature_child_of(set_all_requests_error, netsnmp_unused)
netsnmp_feature_child_of(addrcache_age, netsnmp_unused)
netsnmp_feature_child_of(delete_subtree_cache, netsnmp_unused)


NETSNMP_INLINE void
netsnmp_agent_add_list_data(netsnmp_agent_request_info *ari,
                            netsnmp_data_list *node)
{
    if (ari) {
	if (ari->agent_data) {
            netsnmp_add_list_data(&ari->agent_data, node);
        } else {
            ari->agent_data = node;
	}
    }
}

#ifndef NETSNMP_FEATURE_REMOVE_AGENT_REMOVE_LIST_DATA
NETSNMP_INLINE int
netsnmp_agent_remove_list_data(netsnmp_agent_request_info *ari,
                               const char * name)
{
    if ((NULL == ari) || (NULL == ari->agent_data))
        return 1;

    return netsnmp_remove_list_node(&ari->agent_data, name);
}
#endif /* NETSNMP_FEATURE_REMOVE_AGENT_REMOVE_LIST_DATA */

NETSNMP_INLINE void    *
netsnmp_agent_get_list_data(netsnmp_agent_request_info *ari,
                            const char *name)
{
    if (ari) {
        return netsnmp_get_list_data(ari->agent_data, name);
    }
    return NULL;
}

NETSNMP_INLINE void
netsnmp_free_agent_data_set(netsnmp_agent_request_info *ari)
{
    if (ari) {
        netsnmp_free_list_data(ari->agent_data);
    }
}

NETSNMP_INLINE void
netsnmp_free_agent_data_sets(netsnmp_agent_request_info *ari)
{
    if (ari) {
        netsnmp_free_all_list_data(ari->agent_data);
    }
}

NETSNMP_INLINE void
netsnmp_free_agent_request_info(netsnmp_agent_request_info *ari)
{
    if (ari) {
        if (ari->agent_data) {
            netsnmp_free_all_list_data(ari->agent_data);
	}
        SNMP_FREE(ari);
    }
}

oid      version_sysoid[] = { NETSNMP_SYSTEM_MIB };
int      version_sysoid_len = OID_LENGTH(version_sysoid);

#define SNMP_ADDRCACHE_SIZE 10
#define SNMP_ADDRCACHE_MAXAGE 300 /* in seconds */

enum {
    SNMP_ADDRCACHE_UNUSED = 0,
    SNMP_ADDRCACHE_USED = 1
};

struct addrCache {
    char           *addr;
    int            status;
    struct timeval lastHitM;
};

static struct addrCache addrCache[SNMP_ADDRCACHE_SIZE];
int             log_addresses = 0;



typedef struct _agent_nsap {
    int             handle;
    netsnmp_transport *t;
    void           *s;          /*  Opaque internal session pointer.  */
    struct _agent_nsap *next;
} agent_nsap;

static agent_nsap *agent_nsap_list = NULL;
static netsnmp_agent_session *agent_session_list = NULL;
netsnmp_agent_session *netsnmp_processing_set = NULL;
netsnmp_agent_session *agent_delegated_list = NULL;
netsnmp_agent_session *netsnmp_agent_queued_list = NULL;


int             netsnmp_agent_check_packet(netsnmp_session *,
                                           struct netsnmp_transport_s *,
                                           void *, int);
int             netsnmp_agent_check_parse(netsnmp_session *, netsnmp_pdu *,
                                          int);
void            delete_subnetsnmp_tree_cache(netsnmp_agent_session *asp);
int             handle_pdu(netsnmp_agent_session *asp);
int             netsnmp_handle_request(netsnmp_agent_session *asp,
                                       int status);
int             netsnmp_wrap_up_request(netsnmp_agent_session *asp,
                                        int status);
int             check_delayed_request(netsnmp_agent_session *asp);
int             handle_getnext_loop(netsnmp_agent_session *asp);
int             handle_set_loop(netsnmp_agent_session *asp);

int             netsnmp_check_queued_chain_for(netsnmp_agent_session *asp);
int             netsnmp_add_queued(netsnmp_agent_session *asp);
int             netsnmp_remove_from_delegated(netsnmp_agent_session *asp);


static int      current_globalid = 0;

int      netsnmp_running = 1;

#ifndef NETSNMP_FEATURE_REMOVE_ALLOCATE_GLOBALCACHEID
int
netsnmp_allocate_globalcacheid(void)
{
    return ++current_globalid;
}
#endif /* NETSNMP_FEATURE_REMOVE_ALLOCATE_GLOBALCACHEID */

int
netsnmp_get_local_cachid(netsnmp_cachemap *cache_store, int globalid)
{
    while (cache_store != NULL) {
        if (cache_store->globalid == globalid)
            return cache_store->cacheid;
        cache_store = cache_store->next;
    }
    return -1;
}

netsnmp_cachemap *
netsnmp_get_or_add_local_cachid(netsnmp_cachemap **cache_store,
                                int globalid, int localid)
{
    netsnmp_cachemap *tmpp;

    tmpp = SNMP_MALLOC_TYPEDEF(netsnmp_cachemap);
    if (tmpp != NULL) {
        if (*cache_store) {
            tmpp->next = *cache_store;
            *cache_store = tmpp;
        } else {
            *cache_store = tmpp;
        }

        tmpp->globalid = globalid;
        tmpp->cacheid = localid;
    }
    return tmpp;
}

void
netsnmp_free_cachemap(netsnmp_cachemap *cache_store)
{
    netsnmp_cachemap *tmpp;
    while (cache_store) {
        tmpp = cache_store;
        cache_store = cache_store->next;
        SNMP_FREE(tmpp);
    }
}


typedef struct agent_set_cache_s {
    /*
     * match on these 2 
     */
    int             transID;
    netsnmp_session *sess;

    /*
     * store this info 
     */
    netsnmp_tree_cache *treecache;
    int             treecache_len;
    int             treecache_num;

    int             vbcount;
    netsnmp_request_info *requests;
    netsnmp_variable_list *saved_vars;
    netsnmp_data_list *agent_data;

    /*
     * list 
     */
    struct agent_set_cache_s *next;
} agent_set_cache;

static agent_set_cache *Sets = NULL;

agent_set_cache *
save_set_cache(netsnmp_agent_session *asp)
{
    agent_set_cache *ptr;

    if (!asp || !asp->reqinfo || !asp->pdu)
        return NULL;

    ptr = SNMP_MALLOC_TYPEDEF(agent_set_cache);
    if (ptr == NULL)
        return NULL;

    /*
     * Save the important information 
     */
    DEBUGMSGTL(("verbose:asp", "asp %p reqinfo %p saved in cache (mode %d)\n",
                asp, asp->reqinfo, asp->pdu->command));
    ptr->transID = asp->pdu->transid;
    ptr->sess = asp->session;
    ptr->treecache = asp->treecache;
    ptr->treecache_len = asp->treecache_len;
    ptr->treecache_num = asp->treecache_num;
    ptr->agent_data = asp->reqinfo->agent_data;
    ptr->requests = asp->requests;
    ptr->saved_vars = asp->pdu->variables; /* requests contains pointers to variables */
    ptr->vbcount = asp->vbcount;

    /*
     * make the agent forget about what we've saved 
     */
    asp->treecache = NULL;
    asp->reqinfo->agent_data = NULL;
    asp->pdu->variables = NULL;
    asp->requests = NULL;

    ptr->next = Sets;
    Sets = ptr;

    return ptr;
}

int
get_set_cache(netsnmp_agent_session *asp)
{
    agent_set_cache *ptr, *prev = NULL;

    for (ptr = Sets; ptr != NULL; ptr = ptr->next) {
        if (ptr->sess == asp->session && ptr->transID == asp->pdu->transid) {
            /*
             * remove this item from list
             */
            if (prev)
                prev->next = ptr->next;
            else
                Sets = ptr->next;

            /*
             * found it.  Get the needed data 
             */
            asp->treecache = ptr->treecache;
            asp->treecache_len = ptr->treecache_len;
            asp->treecache_num = ptr->treecache_num;

            /*
             * Free previously allocated requests before overwriting by
             * cached ones, otherwise memory leaks!
             */
	    if (asp->requests) {
                /*
                 * I don't think this case should ever happen. Please email
                 * the net-snmp-coders@lists.sourceforge.net if you have
                 * a test case that hits this condition. -- rstory
                 */
		int i;
                netsnmp_assert(NULL == asp->requests); /* see note above */
		for (i = 0; i < asp->vbcount; i++) {
		    netsnmp_free_request_data_sets(&asp->requests[i]);
		}
		free(asp->requests);
	    }
	    /*
	     * If we replace asp->requests with the info from the set cache,
	     * we should replace asp->pdu->variables also with the cached
	     * info, as asp->requests contains pointers to them.  And we
	     * should also free the current asp->pdu->variables list...
	     */
	    if (ptr->saved_vars) {
		if (asp->pdu->variables)
		    snmp_free_varbind(asp->pdu->variables);
		asp->pdu->variables = ptr->saved_vars;
                asp->vbcount = ptr->vbcount;
	    } else {
                /*
                 * when would we not have saved variables? someone
                 * let me know if they hit this condition. -- rstory
                 */
                netsnmp_assert(NULL != ptr->saved_vars);
            }
            asp->requests = ptr->requests;

            netsnmp_assert(NULL != asp->reqinfo);
            asp->reqinfo->asp = asp;
            asp->reqinfo->agent_data = ptr->agent_data;
            
            /*
             * update request reqinfo, if it's out of date.
             * yyy-rks: investigate when/why sometimes they match,
             * sometimes they don't.
             */
            if(asp->requests->agent_req_info != asp->reqinfo) {
                /*
                 * - one don't match case: agentx subagents. prev asp & reqinfo
                 *   freed, request reqinfo ptrs not cleared.
                 */
                netsnmp_request_info *tmp = asp->requests;
                DEBUGMSGTL(("verbose:asp",
                            "  reqinfo %p doesn't match cached reqinfo %p\n",
                            asp->reqinfo, asp->requests->agent_req_info));
                for(; tmp; tmp = tmp->next)
                    tmp->agent_req_info = asp->reqinfo;
            } else {
                /*
                 * - match case: ?
                 */
                DEBUGMSGTL(("verbose:asp",
                            "  reqinfo %p matches cached reqinfo %p\n",
                            asp->reqinfo, asp->requests->agent_req_info));
            }

            SNMP_FREE(ptr);
            return SNMP_ERR_NOERROR;
        }
        prev = ptr;
    }
    return SNMP_ERR_GENERR;
}

/* Bulkcache holds the values for the *repeating* varbinds (only),
 *   but ordered "by column" - i.e. the repetitions for each
 *   repeating varbind follow on immediately from one another,
 *   rather than being interleaved, as required by the protocol.
 *
 * So we need to rearrange the varbind list so it's ordered "by row".
 *
 * In the following code chunk:
 *     n            = # non-repeating varbinds
 *     r            = # repeating varbinds
 *     asp->vbcount = # varbinds in the incoming PDU
 *         (So asp->vbcount = n+r)
 *
 *     repeats = Desired # of repetitions (of 'r' varbinds)
 */
NETSNMP_STATIC_INLINE void
_reorder_getbulk(netsnmp_agent_session *asp)
{
    int             i, n = 0, r = 0;
    int             repeats = asp->pdu->errindex;
    int             j, k;
    int             all_eoMib;
    netsnmp_variable_list *prev = NULL, *curr;
            
    if (asp->vbcount == 0)  /* Nothing to do! */
        return;

    if (asp->pdu->errstat < asp->vbcount) {
        n = asp->pdu->errstat;
    } else {
        n = asp->vbcount;
    }
    if ((r = asp->vbcount - n) < 0) {
        r = 0;
    }

    /* we do nothing if there is nothing repeated */
    if (r == 0)
        return;
            
    /* Fix endOfMibView entries. */
    for (i = 0; i < r; i++) {
        prev = NULL;
        for (j = 0; j < repeats; j++) {
	    curr = asp->bulkcache[i * repeats + j];
            /*
             *  If we don't have a valid name for a given repetition
             *   (and probably for all the ones that follow as well),
             *   extend the previous result to indicate 'endOfMibView'.
             *  Or if the repetition already has type endOfMibView make
             *   sure it has the correct objid (i.e. that of the previous
             *   entry or that of the original request).
             */
            if (curr->name_length == 0 || curr->type == SNMP_ENDOFMIBVIEW) {
		if (prev == NULL) {
		    /* Use objid from original pdu. */
		    prev = asp->orig_pdu->variables;
		    for (k = i; prev && k > 0; k--)
			prev = prev->next_variable;
		}
		if (prev) {
		    snmp_set_var_objid(curr, prev->name, prev->name_length);
		    snmp_set_var_typed_value(curr, SNMP_ENDOFMIBVIEW, NULL, 0);
		}
            }
            prev = curr;
        }
    }

    /*
     * For each of the original repeating varbinds (except the last),
     *  go through the block of results for that varbind,
     *  and link each instance to the corresponding instance
     *  in the next block.
     */
    for (i = 0; i < r - 1; i++) {
        for (j = 0; j < repeats; j++) {
            asp->bulkcache[i * repeats + j]->next_variable =
                asp->bulkcache[(i + 1) * repeats + j];
        }
    }

    /*
     * For the last of the original repeating varbinds,
     *  go through that block of results, and link each
     *  instance to the *next* instance in the *first* block.
     *
     * The very last instance of this block is left untouched
     *  since it (correctly) points to the end of the list.
     */
    for (j = 0; j < repeats - 1; j++) {
	asp->bulkcache[(r - 1) * repeats + j]->next_variable = 
	    asp->bulkcache[j + 1];
    }

    /*
     * If we've got a full row of endOfMibViews, then we
     *  can truncate the result varbind list after that.
     *
     * Look for endOfMibView exception values in the list of
     *  repetitions for the first varbind, and check the 
     *  corresponding instances for the other varbinds
     *  (following the next_variable links).
     *
     * If they're all endOfMibView too, then we can terminate
     *  the linked list there, and free any redundant varbinds.
     */
    all_eoMib = 0;
    for (i = 0; i < repeats; i++) {
        if (asp->bulkcache[i]->type == SNMP_ENDOFMIBVIEW) {
            all_eoMib = 1;
            for (j = 1, prev=asp->bulkcache[i];
                 j < r;
                 j++, prev=prev->next_variable) {
                if (prev->type != SNMP_ENDOFMIBVIEW) {
                    all_eoMib = 0;
                    break;	/* Found a real value */
                }
            }
            if (all_eoMib) {
                /*
                 * This is indeed a full endOfMibView row.
                 * Terminate the list here & free the rest.
                 */
                snmp_free_varbind( prev->next_variable );
                prev->next_variable = NULL;
                break;
            }
        }
    }
}


/* EndOfMibView replies to a GETNEXT request should according to RFC3416
 *  have the object ID set to that of the request. Our tree search 
 *  algorithm will sometimes break that requirement. This function will
 *  fix that.
 */
NETSNMP_STATIC_INLINE void
_fix_endofmibview(netsnmp_agent_session *asp)
{
    netsnmp_variable_list *vb, *ovb;

    if (asp->vbcount == 0)  /* Nothing to do! */
        return;

    for (vb = asp->pdu->variables, ovb = asp->orig_pdu->variables;
	 vb && ovb; vb = vb->next_variable, ovb = ovb->next_variable) {
	if (vb->type == SNMP_ENDOFMIBVIEW)
	    snmp_set_var_objid(vb, ovb->name, ovb->name_length);
    }
}

#ifndef NETSNMP_FEATURE_REMOVE_AGENT_CHECK_AND_PROCESS
/**
 * This function checks for packets arriving on the SNMP port and
 * processes them(snmp_read) if some are found, using the select(). If block
 * is non zero, the function call blocks until a packet arrives
 *
 * @param block used to control blocking in the select() function, 1 = block
 *        forever, and 0 = don't block
 *
 * @return  Returns a positive integer if packets were processed, and -1 if an
 * error was found.
 *
 */
int
agent_check_and_process(int block)
{
    int             numfds;
    fd_set          fdset;
    struct timeval  timeout = { LONG_MAX, 0 }, *tvp = &timeout;
    int             count;
    int             fakeblock = 0;

    numfds = 0;
    FD_ZERO(&fdset);
    snmp_select_info(&numfds, &fdset, tvp, &fakeblock);
    if (block != 0 && fakeblock != 0) {
        /*
         * There are no alarms registered, and the caller asked for blocking, so
         * let select() block forever.  
         */

        tvp = NULL;
    } else if (block != 0 && fakeblock == 0) {
        /*
         * The caller asked for blocking, but there is an alarm due sooner than
         * LONG_MAX seconds from now, so use the modified timeout returned by
         * snmp_select_info as the timeout for select().  
         */

    } else if (block == 0) {
        /*
         * The caller does not want us to block at all.  
         */

        timerclear(tvp);
    }

    count = select(numfds, &fdset, NULL, NULL, tvp);

    if (count > 0) {
        /*
         * packets found, process them 
         */
        snmp_read(&fdset);
    } else
        switch (count) {
        case 0:
            snmp_timeout();
            break;
        case -1:
            if (errno != EINTR) {
                snmp_log_perror("select");
            }
            return -1;
        default:
            snmp_log(LOG_ERR, "select returned %d\n", count);
            return -1;
        }                       /* endif -- count>0 */

    /*
     * see if persistent store needs to be saved
     */
    snmp_store_if_needed();

    /*
     * Run requested alarms.  
     */
    run_alarms();

    netsnmp_check_outstanding_agent_requests();

    return count;
}
#endif /* NETSNMP_FEATURE_REMOVE_AGENT_CHECK_AND_PROCESS */

/*
 * Set up the address cache.  
 */
void
netsnmp_addrcache_initialise(void)
{
    int             i = 0;

    for (i = 0; i < SNMP_ADDRCACHE_SIZE; i++) {
        addrCache[i].addr = NULL;
        addrCache[i].status = SNMP_ADDRCACHE_UNUSED;
    }
}

void netsnmp_addrcache_destroy(void)
{
    int             i = 0;

    for (i = 0; i < SNMP_ADDRCACHE_SIZE; i++) {
        if (addrCache[i].status == SNMP_ADDRCACHE_USED) {
            free(addrCache[i].addr);
            addrCache[i].status = SNMP_ADDRCACHE_UNUSED;
        }
    }
}

/*
 * Adds a new entry to the cache of addresses that
 * have recently made connections to the agent.
 * Returns 0 if the entry already exists (but updates
 * the entry with a new timestamp) and 1 if the
 * entry did not previously exist.
 *
 * Implements a simple LRU cache replacement
 * policy. Uses a linear search, which should be
 * okay, as long as SNMP_ADDRCACHE_SIZE remains
 * relatively small.
 *
 * @retval 0 : updated existing entry
 * @retval 1 : added new entry
 */
int
netsnmp_addrcache_add(const char *addr)
{
    int oldest = -1; /* Index of the oldest cache entry */
    int unused = -1; /* Index of the first free cache entry */
    int i; /* Looping variable */
    int rc = -1;
    struct timeval now; /* What time is it now? */
    struct timeval aged; /* Oldest allowable cache entry */

    /*
     * First get the current and oldest allowable timestamps
     */
    netsnmp_get_monotonic_clock(&now);
    aged.tv_sec = now.tv_sec - SNMP_ADDRCACHE_MAXAGE;
    aged.tv_usec = now.tv_usec;

    /*
     * Now look for a place to put this thing
     */
    for(i = 0; i < SNMP_ADDRCACHE_SIZE; i++) {
        if (addrCache[i].status == SNMP_ADDRCACHE_UNUSED) { /* If unused */
            /*
             * remember this location, in case addr isn't in the cache
             */
            if (unused < 0)
                unused = i;
        }
        else { /* If used */
            if ((NULL != addr) && (strcmp(addrCache[i].addr, addr) == 0)) {
                /*
                 * found a match
                 */
                addrCache[i].lastHitM = now;
                if (timercmp(&addrCache[i].lastHitM, &aged, <))
		    rc = 1; /* should have expired, so is new */
		else
		    rc = 0; /* not expired, so is existing entry */
                break;
            }
            else {
                /*
                 * Used, but not this address. check if it's stale.
                 */
                if (timercmp(&addrCache[i].lastHitM, &aged, <)) {
                    /*
                     * Stale, reuse
                     */
                    SNMP_FREE(addrCache[i].addr);
                    addrCache[i].status = SNMP_ADDRCACHE_UNUSED;
                    /*
                     * remember this location, in case addr isn't in the cache
                     */
		    if (unused < 0)
                        unused = i;
                }
	        else {
                    /*
                     * Still fresh, but a candidate for LRU replacement
                     */
                    if (oldest < 0)
                        oldest = i;
                    else if (timercmp(&addrCache[i].lastHitM,
                                      &addrCache[oldest].lastHitM, <))
                        oldest = i;
                } /* fresh */
            } /* used, no match */
        } /* used */
    } /* for loop */

    if ((-1 == rc) && (NULL != addr)) {
        /*
         * We didn't find the entry in the cache
         */
        if (unused >= 0) {
            /*
             * If we have a slot free anyway, use it
             */
            addrCache[unused].addr = strdup(addr);
            addrCache[unused].status = SNMP_ADDRCACHE_USED;
            addrCache[unused].lastHitM = now;
        }
        else { /* Otherwise, replace oldest entry */
            if (netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID,
                                       NETSNMP_DS_AGENT_VERBOSE))
                snmp_log(LOG_INFO, "Purging address from address cache: %s",
                         addrCache[oldest].addr);
            
            free(addrCache[oldest].addr);
            addrCache[oldest].addr = strdup(addr);
            addrCache[oldest].lastHitM = now;
        }
        rc = 1;
    }
    if ((log_addresses && (1 == rc)) ||
        netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID,
                               NETSNMP_DS_AGENT_VERBOSE)) {
        snmp_log(LOG_INFO, "Received SNMP packet(s) from %s\n", addr);
     }

    return rc;
}

/*
 * Age the entries in the address cache.  
 *
 * backwards compatability; not used anywhere
 */
#ifndef NETSNMP_FEATURE_REMOVE_ADDRCACHE_AGE
void
netsnmp_addrcache_age(void)
{
    (void)netsnmp_addrcache_add(NULL);
}
#endif /* NETSNMP_FEATURE_REMOVE_ADDRCACHE_AGE */

/*******************************************************************-o-******
 * netsnmp_agent_check_packet
 *
 * Parameters:
 *	session, transport, transport_data, transport_data_length
 *      
 * Returns:
 *	1	On success.
 *	0	On error.
 *
 * Handler for all incoming messages (a.k.a. packets) for the agent.  If using
 * the libwrap utility, log the connection and deny/allow the access. Print
 * output when appropriate, and increment the incoming counter.
 *
 */

int
netsnmp_agent_check_packet(netsnmp_session * session,
                           netsnmp_transport *transport,
                           void *transport_data, int transport_data_length)
{
    char           *addr_string = NULL;
#ifdef  NETSNMP_USE_LIBWRAP
    char *tcpudpaddr = NULL, *name;
    short not_log_connection;

    name = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
                                 NETSNMP_DS_LIB_APPTYPE);

    /* not_log_connection will be 1 if we should skip the messages */
    not_log_connection = netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID,
                                                NETSNMP_DS_AGENT_DONT_LOG_TCPWRAPPERS_CONNECTS);

    /*
     * handle the error case
     * default to logging the messages
     */
    if (not_log_connection == SNMPERR_GENERR) not_log_connection = 0;
#endif

    /*
     * Log the message and/or dump the message.
     * Optionally cache the network address of the sender.
     */

    if (transport != NULL && transport->f_fmtaddr != NULL) {
        /*
         * Okay I do know how to format this address for logging.  
         */
        addr_string = transport->f_fmtaddr(transport, transport_data,
                                           transport_data_length);
        /*
         * Don't forget to free() it.  
         */
    }
#ifdef  NETSNMP_USE_LIBWRAP
    /* Catch udp,udp6,tcp,tcp6 transports using "[" */
    if (addr_string)
        tcpudpaddr = strstr(addr_string, "[");
    if ( tcpudpaddr != 0 ) {
        char sbuf[64];
        char *xp;

        strlcpy(sbuf, tcpudpaddr + 1, sizeof(sbuf));
        xp = strstr(sbuf, "]");
        if (xp)
            *xp = '\0';
 
        if (hosts_ctl(name, STRING_UNKNOWN, sbuf, STRING_UNKNOWN)) {
            if (!not_log_connection) {
                snmp_log(allow_severity, "Connection from %s\n", addr_string);
            }
        } else {
            snmp_log(deny_severity, "Connection from %s REFUSED\n",
                     addr_string);
            SNMP_FREE(addr_string);
            return 0;
        }
    } else {
        /*
         * don't log callback connections.
         * What about 'Local IPC', 'IPX' and 'AAL5 PVC'?
         */
        if (0 == strncmp(addr_string, "callback", 8))
            ;
        else if (hosts_ctl(name, STRING_UNKNOWN, STRING_UNKNOWN, STRING_UNKNOWN)){
            if (!not_log_connection) {
                snmp_log(allow_severity, "Connection from <UNKNOWN> (%s)\n", addr_string);
            };
            SNMP_FREE(addr_string);
            addr_string = strdup("<UNKNOWN>");
        } else {
            snmp_log(deny_severity, "Connection from <UNKNOWN> (%s) REFUSED\n", addr_string);
            SNMP_FREE(addr_string);
            return 0;
        }
    }
#endif                          /*NETSNMP_USE_LIBWRAP */

    snmp_increment_statistic(STAT_SNMPINPKTS);

    if (addr_string != NULL) {
        netsnmp_addrcache_add(addr_string);
        SNMP_FREE(addr_string);
    }
    return 1;
}


int
netsnmp_agent_check_parse(netsnmp_session * session, netsnmp_pdu *pdu,
                          int result)
{
    if (result == 0) {
        if (snmp_get_do_logging() &&
	    netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_AGENT_VERBOSE)) {
            netsnmp_variable_list *var_ptr;

            switch (pdu->command) {
            case SNMP_MSG_GET:
                snmp_log(LOG_DEBUG, "  GET message\n");
                break;
            case SNMP_MSG_GETNEXT:
                snmp_log(LOG_DEBUG, "  GETNEXT message\n");
                break;
            case SNMP_MSG_RESPONSE:
                snmp_log(LOG_DEBUG, "  RESPONSE message\n");
                break;
#ifndef NETSNMP_NO_WRITE_SUPPORT
            case SNMP_MSG_SET:
                snmp_log(LOG_DEBUG, "  SET message\n");
                break;
#endif /* NETSNMP_NO_WRITE_SUPPORT */
            case SNMP_MSG_TRAP:
                snmp_log(LOG_DEBUG, "  TRAP message\n");
                break;
            case SNMP_MSG_GETBULK:
                snmp_log(LOG_DEBUG, "  GETBULK message, non-rep=%ld, max_rep=%ld\n",
                         pdu->errstat, pdu->errindex);
                break;
            case SNMP_MSG_INFORM:
                snmp_log(LOG_DEBUG, "  INFORM message\n");
                break;
            case SNMP_MSG_TRAP2:
                snmp_log(LOG_DEBUG, "  TRAP2 message\n");
                break;
            case SNMP_MSG_REPORT:
                snmp_log(LOG_DEBUG, "  REPORT message\n");
                break;

#ifndef NETSNMP_NO_WRITE_SUPPORT
            case SNMP_MSG_INTERNAL_SET_RESERVE1:
                snmp_log(LOG_DEBUG, "  INTERNAL RESERVE1 message\n");
                break;

            case SNMP_MSG_INTERNAL_SET_RESERVE2:
                snmp_log(LOG_DEBUG, "  INTERNAL RESERVE2 message\n");
                break;

            case SNMP_MSG_INTERNAL_SET_ACTION:
                snmp_log(LOG_DEBUG, "  INTERNAL ACTION message\n");
                break;

            case SNMP_MSG_INTERNAL_SET_COMMIT:
                snmp_log(LOG_DEBUG, "  INTERNAL COMMIT message\n");
                break;

            case SNMP_MSG_INTERNAL_SET_FREE:
                snmp_log(LOG_DEBUG, "  INTERNAL FREE message\n");
                break;

            case SNMP_MSG_INTERNAL_SET_UNDO:
                snmp_log(LOG_DEBUG, "  INTERNAL UNDO message\n");
                break;
#endif /* NETSNMP_NO_WRITE_SUPPORT */

            default:
                snmp_log(LOG_DEBUG, "  UNKNOWN message, type=%02X\n",
                         pdu->command);
                snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
                return 0;
            }

            for (var_ptr = pdu->variables; var_ptr != NULL;
                 var_ptr = var_ptr->next_variable) {
                size_t          c_oidlen = 256, c_outlen = 0;
                u_char         *c_oid = (u_char *) malloc(c_oidlen);

                if (c_oid) {
                    if (!sprint_realloc_objid
                        (&c_oid, &c_oidlen, &c_outlen, 1, var_ptr->name,
                         var_ptr->name_length)) {
                        snmp_log(LOG_DEBUG, "    -- %s [TRUNCATED]\n",
                                 c_oid);
                    } else {
                        snmp_log(LOG_DEBUG, "    -- %s\n", c_oid);
                    }
                    SNMP_FREE(c_oid);
                }
            }
        }
        return 1;
    }
    return 0;                   /* XXX: does it matter what the return value
                                 * is?  Yes: if we return 0, then the PDU is
                                 * dumped.  */
}


/*
 * Global access to the primary session structure for this agent.
 * for Index Allocation use initially. 
 */

/*
 * I don't understand what this is for at the moment.  AFAICS as long as it
 * gets set and points at a session, that's fine.  ???  
 */

netsnmp_session *main_session = NULL;



/*
 * Set up an agent session on the given transport.  Return a handle
 * which may later be used to de-register this transport.  A return
 * value of -1 indicates an error.  
 */

int
netsnmp_register_agent_nsap(netsnmp_transport *t)
{
    netsnmp_session *s, *sp = NULL;
    agent_nsap     *a = NULL, *n = NULL, **prevNext = &agent_nsap_list;
    int             handle = 0;
    void           *isp = NULL;

    if (t == NULL) {
        return -1;
    }

    DEBUGMSGTL(("netsnmp_register_agent_nsap", "fd %d\n", t->sock));

    n = (agent_nsap *) malloc(sizeof(agent_nsap));
    if (n == NULL) {
        return -1;
    }
    s = (netsnmp_session *) malloc(sizeof(netsnmp_session));
    if (s == NULL) {
        SNMP_FREE(n);
        return -1;
    }
    memset(s, 0, sizeof(netsnmp_session));
    snmp_sess_init(s);

    /*
     * Set up the session appropriately for an agent.  
     */

    s->version = SNMP_DEFAULT_VERSION;
    s->callback = handle_snmp_packet;
    s->authenticator = NULL;
    s->flags = netsnmp_ds_get_int(NETSNMP_DS_APPLICATION_ID, 
				  NETSNMP_DS_AGENT_FLAGS);
    s->isAuthoritative = SNMP_SESS_AUTHORITATIVE;

    /* Optional supplimental transport configuration information and
       final call to actually open the transport */
    if (netsnmp_sess_config_transport(s->transport_configuration, t)
        != SNMPERR_SUCCESS) {
        SNMP_FREE(s);
        SNMP_FREE(n);
        return -1;
    }


    if (t->f_open)
        t = t->f_open(t);

    if (NULL == t) {
        SNMP_FREE(s);
        SNMP_FREE(n);
        return -1;
    }

    t->flags |= NETSNMP_TRANSPORT_FLAG_OPENED;

    sp = snmp_add(s, t, netsnmp_agent_check_packet,
                  netsnmp_agent_check_parse);
    if (sp == NULL) {
        SNMP_FREE(s);
        SNMP_FREE(n);
        return -1;
    }

    isp = snmp_sess_pointer(sp);
    if (isp == NULL) {          /*  over-cautious  */
        SNMP_FREE(s);
        SNMP_FREE(n);
        return -1;
    }

    n->s = isp;
    n->t = t;

    if (main_session == NULL) {
        main_session = snmp_sess_session(isp);
    }

    for (a = agent_nsap_list; a != NULL && handle + 1 >= a->handle;
         a = a->next) {
        handle = a->handle;
        prevNext = &(a->next);
    }

    if (handle < INT_MAX) {
        n->handle = handle + 1;
        n->next = a;
        *prevNext = n;
        SNMP_FREE(s);
        return n->handle;
    } else {
        SNMP_FREE(s);
        SNMP_FREE(n);
        return -1;
    }
}

void
netsnmp_deregister_agent_nsap(int handle)
{
    agent_nsap     *a = NULL, **prevNext = &agent_nsap_list;
    int             main_session_deregistered = 0;

    DEBUGMSGTL(("netsnmp_deregister_agent_nsap", "handle %d\n", handle));

    for (a = agent_nsap_list; a != NULL && a->handle < handle; a = a->next) {
        prevNext = &(a->next);
    }

    if (a != NULL && a->handle == handle) {
        *prevNext = a->next;
	if (snmp_sess_session_lookup(a->s)) {
            if (main_session == snmp_sess_session(a->s)) {
                main_session_deregistered = 1;
            }
            snmp_close(snmp_sess_session(a->s));
            /*
             * The above free()s the transport and session pointers.  
             */
        }
        SNMP_FREE(a);
    }

    /*
     * If we've deregistered the session that main_session used to point to,
     * then make it point to another one, or in the last resort, make it equal
     * to NULL.  Basically this shouldn't ever happen in normal operation
     * because main_session starts off pointing at the first session added by
     * init_master_agent(), which then discards the handle.  
     */

    if (main_session_deregistered) {
        if (agent_nsap_list != NULL) {
            DEBUGMSGTL(("snmp_agent",
			"WARNING: main_session ptr changed from %p to %p\n",
                        main_session, snmp_sess_session(agent_nsap_list->s)));
            main_session = snmp_sess_session(agent_nsap_list->s);
        } else {
            DEBUGMSGTL(("snmp_agent",
			"WARNING: main_session ptr changed from %p to NULL\n",
                        main_session));
            main_session = NULL;
        }
    }
}



/*
 * 
 * This function has been modified to use the experimental
 * netsnmp_register_agent_nsap interface.  The major responsibility of this
 * function now is to interpret a string specified to the agent (via -p on the
 * command line, or from a configuration file) as a list of agent NSAPs on
 * which to listen for SNMP packets.  Typically, when you add a new transport
 * domain "foo", you add code here such that if the "foo" code is compiled
 * into the agent (SNMP_TRANSPORT_FOO_DOMAIN is defined), then a token of the
 * form "foo:bletch-3a0054ef%wob&wob" gets turned into the appropriate
 * transport descriptor.  netsnmp_register_agent_nsap is then called with that
 * transport descriptor and sets up a listening agent session on it.
 * 
 * Everything then works much as normal: the agent runs in an infinite loop
 * (in the snmpd.c/receive()routine), which calls snmp_read() when a request
 * is readable on any of the given transports.  This routine then traverses
 * the library 'Sessions' list to identify the relevant session and eventually
 * invokes '_sess_read'.  This then processes the incoming packet, calling the
 * pre_parse, parse, post_parse and callback routines in turn.
 * 
 * JBPN 20001117
 */

int
init_master_agent(void)
{
    netsnmp_transport *transport;
    char           *cptr;
    char           *buf = NULL;
    char           *st;

    /* default to a default cache size */
    netsnmp_set_lookup_cache_size(-1);

    if (netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, 
			       NETSNMP_DS_AGENT_ROLE) != MASTER_AGENT) {
        DEBUGMSGTL(("snmp_agent",
                    "init_master_agent; not master agent\n"));

        netsnmp_assert("agent role !master && !sub_agent");
        
        return 0;               /*  No error if ! MASTER_AGENT  */
    }

#ifndef NETSNMP_NO_LISTEN_SUPPORT
    /*
     * Have specific agent ports been specified?  
     */
    cptr = netsnmp_ds_get_string(NETSNMP_DS_APPLICATION_ID, 
				 NETSNMP_DS_AGENT_PORTS);

    if (cptr) {
        buf = strdup(cptr);
        if (!buf) {
            snmp_log(LOG_ERR,
                     "Error processing transport \"%s\"\n", cptr);
            return 1;
        }
    } else {
        /*
         * No, so just specify the default port.  
         */
        buf = strdup("");
    }

    DEBUGMSGTL(("snmp_agent", "final port spec: \"%s\"\n", buf));
    st = buf;
    do {
        /*
         * Specification format: 
         * 
         * NONE:                      (a pseudo-transport)
         * UDP:[address:]port        (also default if no transport is specified)
         * TCP:[address:]port         (if supported)
         * Unix:pathname              (if supported)
         * AAL5PVC:itf.vpi.vci        (if supported)
         * IPX:[network]:node[/port] (if supported)
         * 
         */

	cptr = st;
	st = strchr(st, ',');
	if (st)
	    *st++ = '\0';

        DEBUGMSGTL(("snmp_agent", "installing master agent on port %s\n",
                    cptr));

        if (strncasecmp(cptr, "none", 4) == 0) {
            DEBUGMSGTL(("snmp_agent",
                        "init_master_agent; pseudo-transport \"none\" "
			"requested\n"));
            break;
        }
        transport = netsnmp_transport_open_server("snmp", cptr);

        if (transport == NULL) {
            snmp_log(LOG_ERR, "Error opening specified endpoint \"%s\"\n",
                     cptr);
            return 1;
        }

        if (netsnmp_register_agent_nsap(transport) == 0) {
            snmp_log(LOG_ERR,
                     "Error registering specified transport \"%s\" as an "
		     "agent NSAP\n", cptr);
            return 1;
        } else {
            DEBUGMSGTL(("snmp_agent",
                        "init_master_agent; \"%s\" registered as an agent "
			"NSAP\n", cptr));
        }
    } while(st && *st != '\0');
    SNMP_FREE(buf);
#endif /* NETSNMP_NO_LISTEN_SUPPORT */

#ifdef USING_AGENTX_MASTER_MODULE
    if (netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, 
			       NETSNMP_DS_AGENT_AGENTX_MASTER) == 1)
        real_init_master();
#endif
#ifdef USING_SMUX_MODULE
    if(should_init("smux"))
    real_init_smux();
#endif

    return 0;
}

void
clear_nsap_list(void)
{
    DEBUGMSGTL(("clear_nsap_list", "clear the nsap list\n"));

    while (agent_nsap_list != NULL)
	netsnmp_deregister_agent_nsap(agent_nsap_list->handle);
}

void
shutdown_master_agent(void)
{
    clear_nsap_list();
}


netsnmp_agent_session *
init_agent_snmp_session(netsnmp_session * session, netsnmp_pdu *pdu)
{
    netsnmp_agent_session *asp = (netsnmp_agent_session *)
        calloc(1, sizeof(netsnmp_agent_session));

    if (asp == NULL) {
        return NULL;
    }

    DEBUGMSGTL(("snmp_agent","agent_sesion %8p created\n", asp));
    asp->session = session;
    asp->pdu = snmp_clone_pdu(pdu);
    asp->orig_pdu = snmp_clone_pdu(pdu);
    asp->rw = READ;
    asp->exact = TRUE;
    asp->next = NULL;
    asp->mode = RESERVE1;
    asp->status = SNMP_ERR_NOERROR;
    asp->index = 0;
    asp->oldmode = 0;
    asp->treecache_num = -1;
    asp->treecache_len = 0;
    asp->reqinfo = SNMP_MALLOC_TYPEDEF(netsnmp_agent_request_info);
    DEBUGMSGTL(("verbose:asp", "asp %p reqinfo %p created\n",
                asp, asp->reqinfo));

    return asp;
}

void
free_agent_snmp_session(netsnmp_agent_session *asp)
{
    if (!asp)
        return;

    DEBUGMSGTL(("snmp_agent","agent_session %8p released\n", asp));

    netsnmp_remove_from_delegated(asp);
    
    DEBUGMSGTL(("verbose:asp", "asp %p reqinfo %p freed\n",
                asp, asp->reqinfo));
    if (asp->orig_pdu)
        snmp_free_pdu(asp->orig_pdu);
    if (asp->pdu)
        snmp_free_pdu(asp->pdu);
    if (asp->reqinfo)
        netsnmp_free_agent_request_info(asp->reqinfo);
    SNMP_FREE(asp->treecache);
    SNMP_FREE(asp->bulkcache);
    if (asp->requests) {
        int             i;
        for (i = 0; i < asp->vbcount; i++) {
            netsnmp_free_request_data_sets(&asp->requests[i]);
        }
        SNMP_FREE(asp->requests);
    }
    if (asp->cache_store) {
        netsnmp_free_cachemap(asp->cache_store);
        asp->cache_store = NULL;
    }
    SNMP_FREE(asp);
}

int
netsnmp_check_for_delegated(netsnmp_agent_session *asp)
{
    int             i;
    netsnmp_request_info *request;

    if (NULL == asp->treecache)
        return 0;
    
    for (i = 0; i <= asp->treecache_num; i++) {
        for (request = asp->treecache[i].requests_begin; request;
             request = request->next) {
            if (request->delegated)
                return 1;
        }
    }
    return 0;
}

int
netsnmp_check_delegated_chain_for(netsnmp_agent_session *asp)
{
    netsnmp_agent_session *asptmp;
    for (asptmp = agent_delegated_list; asptmp; asptmp = asptmp->next) {
        if (asptmp == asp)
            return 1;
    }
    return 0;
}

int
netsnmp_check_for_delegated_and_add(netsnmp_agent_session *asp)
{
    if (netsnmp_check_for_delegated(asp)) {
        if (!netsnmp_check_delegated_chain_for(asp)) {
            /*
             * add to delegated request chain 
             */
            asp->next = agent_delegated_list;
            agent_delegated_list = asp;
            DEBUGMSGTL(("snmp_agent", "delegate session == %8p\n", asp));
        }
        return 1;
    }
    return 0;
}

int
netsnmp_remove_from_delegated(netsnmp_agent_session *asp)
{
    netsnmp_agent_session *curr, *prev = NULL;
    
    for (curr = agent_delegated_list; curr; prev = curr, curr = curr->next) {
        /*
         * is this us?
         */
        if (curr != asp)
            continue;
        
        /*
         * remove from queue 
         */
        if (prev != NULL)
            prev->next = asp->next;
        else
            agent_delegated_list = asp->next;

        DEBUGMSGTL(("snmp_agent", "remove delegated session == %8p\n", asp));

        return 1;
    }

    return 0;
}

/*
 * netsnmp_remove_delegated_requests_for_session
 *
 * called when a session is being closed. Check all delegated requests to
 * see if the are waiting on this session, and if set, set the status for
 * that request to GENERR.
 */
int
netsnmp_remove_delegated_requests_for_session(netsnmp_session *sess)
{
    netsnmp_agent_session *asp;
    int count = 0;
    
    for (asp = agent_delegated_list; asp; asp = asp->next) {
        /*
         * check each request
         */
        netsnmp_request_info *request;
        for(request = asp->requests; request; request = request->next) {
            /*
             * check session
             */
            netsnmp_assert(NULL!=request->subtree);
            if(request->subtree->session != sess)
                continue;

            /*
             * matched! mark request as done
             */
            netsnmp_request_set_error(request, SNMP_ERR_GENERR);
            ++count;
        }
    }

    /*
     * if we found any, that request may be finished now
     */
    if(count) {
        DEBUGMSGTL(("snmp_agent", "removed %d delegated request(s) for session "
                    "%8p\n", count, sess));
        netsnmp_check_outstanding_agent_requests();
    }
    
    return count;
}

int
netsnmp_check_queued_chain_for(netsnmp_agent_session *asp)
{
    netsnmp_agent_session *asptmp;
    for (asptmp = netsnmp_agent_queued_list; asptmp; asptmp = asptmp->next) {
        if (asptmp == asp)
            return 1;
    }
    return 0;
}

int
netsnmp_add_queued(netsnmp_agent_session *asp)
{
    netsnmp_agent_session *asp_tmp;

    /*
     * first item?
     */
    if (NULL == netsnmp_agent_queued_list) {
        netsnmp_agent_queued_list = asp;
        return 1;
    }


    /*
     * add to end of queued request chain 
     */
    asp_tmp = netsnmp_agent_queued_list;
    for (; asp_tmp; asp_tmp = asp_tmp->next) {
        /*
         * already in queue?
         */
        if (asp_tmp == asp)
            break;

        /*
         * end of queue?
         */
        if (NULL == asp_tmp->next)
            asp_tmp->next = asp;
    }
    return 1;
}


int
netsnmp_wrap_up_request(netsnmp_agent_session *asp, int status)
{
    /*
     * if this request was a set, clear the global now that we are
     * done.
     */
    if (asp == netsnmp_processing_set) {
        DEBUGMSGTL(("snmp_agent", "SET request complete, asp = %8p\n",
                    asp));
        netsnmp_processing_set = NULL;
    }

    if (asp->pdu) {
        /*
         * If we've got an error status, then this needs to be
         *  passed back up to the higher levels....
         */
        if ( status != 0  && asp->status == 0 )
            asp->status = status;

        switch (asp->pdu->command) {
#ifndef NETSNMP_NO_WRITE_SUPPORT
            case SNMP_MSG_INTERNAL_SET_BEGIN:
            case SNMP_MSG_INTERNAL_SET_RESERVE1:
            case SNMP_MSG_INTERNAL_SET_RESERVE2:
            case SNMP_MSG_INTERNAL_SET_ACTION:
                /*
                 * some stuff needs to be saved in special subagent cases 
                 */
                save_set_cache(asp);
                break;
#endif /* NETSNMP_NO_WRITE_SUPPORT */

            case SNMP_MSG_GETNEXT:
                _fix_endofmibview(asp);
                break;

            case SNMP_MSG_GETBULK:
                /*
                 * for a GETBULK response we need to rearrange the varbinds 
                 */
                _reorder_getbulk(asp);
                break;
        }

        /*
         * May need to "dumb down" a SET error status for a
         * v1 query.  See RFC2576 - section 4.3
         */
#ifndef NETSNMP_DISABLE_SNMPV1
#ifndef NETSNMP_NO_WRITE_SUPPORT
        if ((asp->pdu->command == SNMP_MSG_SET) &&
            (asp->pdu->version == SNMP_VERSION_1)) {
            switch (asp->status) {
                case SNMP_ERR_WRONGVALUE:
                case SNMP_ERR_WRONGENCODING:
                case SNMP_ERR_WRONGTYPE:
                case SNMP_ERR_WRONGLENGTH:
                case SNMP_ERR_INCONSISTENTVALUE:
                    status = SNMP_ERR_BADVALUE;
                    asp->status = SNMP_ERR_BADVALUE;
                    break;
                case SNMP_ERR_NOACCESS:
                case SNMP_ERR_NOTWRITABLE:
                case SNMP_ERR_NOCREATION:
                case SNMP_ERR_INCONSISTENTNAME:
                case SNMP_ERR_AUTHORIZATIONERROR:
                    status = SNMP_ERR_NOSUCHNAME;
                    asp->status = SNMP_ERR_NOSUCHNAME;
                    break;
                case SNMP_ERR_RESOURCEUNAVAILABLE:
                case SNMP_ERR_COMMITFAILED:
                case SNMP_ERR_UNDOFAILED:
                    status = SNMP_ERR_GENERR;
                    asp->status = SNMP_ERR_GENERR;
                    break;
            }
        }
        /*
         * Similarly we may need to "dumb down" v2 exception
         *  types to throw an error for a v1 query.
         *  See RFC2576 - section 4.1.2.3
         */
        if ((asp->pdu->command != SNMP_MSG_SET) &&
            (asp->pdu->version == SNMP_VERSION_1)) {
            netsnmp_variable_list *var_ptr = asp->pdu->variables;
            int                    i = 1;

            while (var_ptr != NULL) {
                switch (var_ptr->type) {
                    case SNMP_NOSUCHOBJECT:
                    case SNMP_NOSUCHINSTANCE:
                    case SNMP_ENDOFMIBVIEW:
                    case ASN_COUNTER64:
                        status = SNMP_ERR_NOSUCHNAME;
                        asp->status = SNMP_ERR_NOSUCHNAME;
                        asp->index = i;
                        break;
                }
                var_ptr = var_ptr->next_variable;
                ++i;
            }
        }
#endif /* NETSNMP_NO_WRITE_SUPPORT */
#endif /* snmpv1 support */
    } /** if asp->pdu */

    /*
     * Update the snmp error-count statistics
     *   XXX - should we include the V2 errors in this or not?
     */
#define INCLUDE_V2ERRORS_IN_V1STATS

    switch (status) {
#ifdef INCLUDE_V2ERRORS_IN_V1STATS
    case SNMP_ERR_WRONGVALUE:
    case SNMP_ERR_WRONGENCODING:
    case SNMP_ERR_WRONGTYPE:
    case SNMP_ERR_WRONGLENGTH:
    case SNMP_ERR_INCONSISTENTVALUE:
#endif
    case SNMP_ERR_BADVALUE:
        snmp_increment_statistic(STAT_SNMPOUTBADVALUES);
        break;
#ifdef INCLUDE_V2ERRORS_IN_V1STATS
    case SNMP_ERR_NOACCESS:
    case SNMP_ERR_NOTWRITABLE:
    case SNMP_ERR_NOCREATION:
    case SNMP_ERR_INCONSISTENTNAME:
    case SNMP_ERR_AUTHORIZATIONERROR:
#endif
    case SNMP_ERR_NOSUCHNAME:
        snmp_increment_statistic(STAT_SNMPOUTNOSUCHNAMES);
        break;
#ifdef INCLUDE_V2ERRORS_IN_V1STATS
    case SNMP_ERR_RESOURCEUNAVAILABLE:
    case SNMP_ERR_COMMITFAILED:
    case SNMP_ERR_UNDOFAILED:
#endif
    case SNMP_ERR_GENERR:
        snmp_increment_statistic(STAT_SNMPOUTGENERRS);
        break;

    case SNMP_ERR_TOOBIG:
        snmp_increment_statistic(STAT_SNMPOUTTOOBIGS);
        break;
    }

    if ((status == SNMP_ERR_NOERROR) && (asp->pdu)) {
#ifndef NETSNMP_NO_WRITE_SUPPORT
        snmp_increment_statistic_by((asp->pdu->command == SNMP_MSG_SET ?
                                     STAT_SNMPINTOTALSETVARS :
                                     STAT_SNMPINTOTALREQVARS),
                                    count_varbinds(asp->pdu->variables));
#else /* NETSNMP_NO_WRITE_SUPPORT */
        snmp_increment_statistic_by(STAT_SNMPINTOTALREQVARS,
                                    count_varbinds(asp->pdu->variables));
#endif /* NETSNMP_NO_WRITE_SUPPORT */

    } else {
        /*
         * Use a copy of the original request
         *   to report failures.
         */
        snmp_free_pdu(asp->pdu);
        asp->pdu = asp->orig_pdu;
        asp->orig_pdu = NULL;
    }
    if (asp->pdu) {
        asp->pdu->command = SNMP_MSG_RESPONSE;
        asp->pdu->errstat = asp->status;
        asp->pdu->errindex = asp->index;
        if (!snmp_send(asp->session, asp->pdu) &&
             asp->session->s_snmp_errno != SNMPERR_SUCCESS) {
            netsnmp_variable_list *var_ptr;
            snmp_perror("send response");
            for (var_ptr = asp->pdu->variables; var_ptr != NULL;
                     var_ptr = var_ptr->next_variable) {
                size_t  c_oidlen = 256, c_outlen = 0;
                u_char *c_oid = (u_char *) malloc(c_oidlen);

                if (c_oid) {
                    if (!sprint_realloc_objid (&c_oid, &c_oidlen, &c_outlen, 1,
 		                               var_ptr->name,
                                               var_ptr->name_length)) {
                        snmp_log(LOG_ERR, "    -- %s [TRUNCATED]\n", c_oid);
                    } else {
                        snmp_log(LOG_ERR, "    -- %s\n", c_oid);
                    }
                    SNMP_FREE(c_oid);
                }
            }
            snmp_free_pdu(asp->pdu);
            asp->pdu = NULL;
        }
        snmp_increment_statistic(STAT_SNMPOUTPKTS);
        snmp_increment_statistic(STAT_SNMPOUTGETRESPONSES);
        asp->pdu = NULL; /* yyy-rks: redundant, no? */
        netsnmp_remove_and_free_agent_snmp_session(asp);
    }
    return 1;
}

#ifndef NETSNMP_FEATURE_REMOVE_DUMP_SESS_LIST
void
dump_sess_list(void)
{
    netsnmp_agent_session *a;

    DEBUGMSGTL(("snmp_agent", "DUMP agent_sess_list -> "));
    for (a = agent_session_list; a != NULL; a = a->next) {
        DEBUGMSG(("snmp_agent", "%8p[session %8p] -> ", a, a->session));
    }
    DEBUGMSG(("snmp_agent", "[NIL]\n"));
}
#endif /* NETSNMP_FEATURE_REMOVE_DUMP_SESS_LIST */

void
netsnmp_remove_and_free_agent_snmp_session(netsnmp_agent_session *asp)
{
    netsnmp_agent_session *a, **prevNext = &agent_session_list;

    DEBUGMSGTL(("snmp_agent", "REMOVE session == %8p\n", asp));

    for (a = agent_session_list; a != NULL; a = *prevNext) {
        if (a == asp) {
            *prevNext = a->next;
            a->next = NULL;
            free_agent_snmp_session(a);
            asp = NULL;
            break;
        } else {
            prevNext = &(a->next);
        }
    }

    if (a == NULL && asp != NULL) {
        /*
         * We coulnd't find it on the list, so free it anyway.  
         */
        free_agent_snmp_session(asp);
    }
}

#ifndef NETSNMP_FEATURE_REMOVE_FREE_AGENT_SNMP_SESSION_BY_SESSION
void
netsnmp_free_agent_snmp_session_by_session(netsnmp_session * sess,
                                           void (*free_request)
                                           (netsnmp_request_list *))
{
    netsnmp_agent_session *a, *next, **prevNext = &agent_session_list;

    DEBUGMSGTL(("snmp_agent", "REMOVE session == %8p\n", sess));

    for (a = agent_session_list; a != NULL; a = next) {
        if (a->session == sess) {
            *prevNext = a->next;
            next = a->next;
            free_agent_snmp_session(a);
        } else {
            prevNext = &(a->next);
            next = a->next;
        }
    }
}
#endif /* NETSNMP_FEATURE_REMOVE_FREE_AGENT_SNMP_SESSION_BY_SESSION */

/** handles an incoming SNMP packet into the agent */
int
handle_snmp_packet(int op, netsnmp_session * session, int reqid,
                   netsnmp_pdu *pdu, void *magic)
{
    netsnmp_agent_session *asp;
    int             status, access_ret, rc;

    /*
     * We only support receiving here.  
     */
    if (op != NETSNMP_CALLBACK_OP_RECEIVED_MESSAGE) {
        return 1;
    }

    /*
     * RESPONSE messages won't get this far, but TRAP-like messages
     * might.  
     */
    if (pdu->command == SNMP_MSG_TRAP || pdu->command == SNMP_MSG_INFORM ||
        pdu->command == SNMP_MSG_TRAP2) {
        DEBUGMSGTL(("snmp_agent", "received trap-like PDU (%02x)\n",
                    pdu->command));
        pdu->command = SNMP_MSG_TRAP2;
        snmp_increment_statistic(STAT_SNMPUNKNOWNPDUHANDLERS);
        return 1;
    }

    /*
     * send snmpv3 authfail trap.
     */
    if (pdu->version  == SNMP_VERSION_3 && 
        session->s_snmp_errno == SNMPERR_USM_AUTHENTICATIONFAILURE) {
           send_easy_trap(SNMP_TRAP_AUTHFAIL, 0);
           return 1;
    } 
	
    if (magic == NULL) {
        asp = init_agent_snmp_session(session, pdu);
        status = SNMP_ERR_NOERROR;
    } else {
        asp = (netsnmp_agent_session *) magic;
        status = asp->status;
    }

    if ((access_ret = check_access(asp->pdu)) != 0) {
        if (access_ret == VACM_NOSUCHCONTEXT) {
            /*
             * rfc3413 section 3.2, step 5 says that we increment the
             * counter but don't return a response of any kind 
             */

            /*
             * we currently don't support unavailable contexts, as
             * there is no reason to that I currently know of 
             */
            snmp_increment_statistic(STAT_SNMPUNKNOWNCONTEXTS);

            /*
             * drop the request 
             */
            netsnmp_remove_and_free_agent_snmp_session(asp);
            return 0;
        } else {
            /*
             * access control setup is incorrect 
             */
            send_easy_trap(SNMP_TRAP_AUTHFAIL, 0);
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
#if defined(NETSNMP_DISABLE_SNMPV1)
            if (asp->pdu->version != SNMP_VERSION_2c) {
#else
#if defined(NETSNMP_DISABLE_SNMPV2C)
            if (asp->pdu->version != SNMP_VERSION_1) {
#else
            if (asp->pdu->version != SNMP_VERSION_1
                && asp->pdu->version != SNMP_VERSION_2c) {
#endif
#endif
                asp->pdu->errstat = SNMP_ERR_AUTHORIZATIONERROR;
                asp->pdu->command = SNMP_MSG_RESPONSE;
                snmp_increment_statistic(STAT_SNMPOUTPKTS);
                if (!snmp_send(asp->session, asp->pdu))
                    snmp_free_pdu(asp->pdu);
                asp->pdu = NULL;
                netsnmp_remove_and_free_agent_snmp_session(asp);
                return 1;
            } else {
#endif /* support for community based SNMP */
                /*
                 * drop the request 
                 */
                netsnmp_remove_and_free_agent_snmp_session(asp);
                return 0;
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
            }
#endif /* support for community based SNMP */
        }
    }

    rc = netsnmp_handle_request(asp, status);

    /*
     * done 
     */
    DEBUGMSGTL(("snmp_agent", "end of handle_snmp_packet, asp = %8p\n",
                asp));
    return rc;
}

netsnmp_request_info *
netsnmp_add_varbind_to_cache(netsnmp_agent_session *asp, int vbcount,
                             netsnmp_variable_list * varbind_ptr,
                             netsnmp_subtree *tp)
{
    netsnmp_request_info *request = NULL;

    DEBUGMSGTL(("snmp_agent", "add_vb_to_cache(%8p, %d, ", asp, vbcount));
    DEBUGMSGOID(("snmp_agent", varbind_ptr->name,
                 varbind_ptr->name_length));
    DEBUGMSG(("snmp_agent", ", %8p)\n", tp));

    if (tp &&
        (asp->pdu->command == SNMP_MSG_GETNEXT ||
         asp->pdu->command == SNMP_MSG_GETBULK)) {
        int result;
        int prefix_len;

        prefix_len = netsnmp_oid_find_prefix(tp->start_a,
                                             tp->start_len,
                                             tp->end_a, tp->end_len);
        if (prefix_len < 1) {
            result = VACM_NOTINVIEW; /* ack...  bad bad thing happened */
        } else {
            result =
                netsnmp_acm_check_subtree(asp->pdu, tp->start_a, prefix_len);
        }

        while (result == VACM_NOTINVIEW) {
            /* the entire subtree is not in view. Skip it. */
            /** @todo make this be more intelligent about ranges.
                Right now we merely take the highest level
                commonality of a registration range and use that.
                At times we might be able to be smarter about
                checking the range itself as opposed to the node
                above where the range exists, but I doubt this will
                come up all that frequently. */
            tp = tp->next;
            if (tp) {
                prefix_len = netsnmp_oid_find_prefix(tp->start_a,
                                                     tp->start_len,
                                                     tp->end_a,
                                                     tp->end_len);
                if (prefix_len < 1) {
                    /* ack...  bad bad thing happened */
                    result = VACM_NOTINVIEW;
                } else {
                    result =
                        netsnmp_acm_check_subtree(asp->pdu,
                                                  tp->start_a, prefix_len);
                }
            }
            else
                break;
        }
    }
    if (tp == NULL) {
        /*
         * no appropriate registration found 
         */
        /*
         * make up the response ourselves 
         */
        switch (asp->pdu->command) {
        case SNMP_MSG_GETNEXT:
        case SNMP_MSG_GETBULK:
            varbind_ptr->type = SNMP_ENDOFMIBVIEW;
            break;

#ifndef NETSNMP_NO_WRITE_SUPPORT
        case SNMP_MSG_SET:
#endif /* NETSNMP_NO_WRITE_SUPPORT */
        case SNMP_MSG_GET:
            varbind_ptr->type = SNMP_NOSUCHOBJECT;
            break;

        default:
            return NULL;        /* shouldn't get here */
        }
    } else {
        int cacheid;

        DEBUGMSGTL(("snmp_agent", "tp->start "));
        DEBUGMSGOID(("snmp_agent", tp->start_a, tp->start_len));
        DEBUGMSG(("snmp_agent", ", tp->end "));
        DEBUGMSGOID(("snmp_agent", tp->end_a, tp->end_len));
        DEBUGMSG(("snmp_agent", ", \n"));

        /*
         * malloc the request structure 
         */
        request = &(asp->requests[vbcount - 1]);
        request->index = vbcount;
        request->delegated = 0;
        request->processed = 0;
        request->status = 0;
        request->subtree = tp;
        request->agent_req_info = asp->reqinfo;
        if (request->parent_data) {
            netsnmp_free_request_data_sets(request);
        }
        DEBUGMSGTL(("verbose:asp", "asp %p reqinfo %p assigned to request\n",
                    asp, asp->reqinfo));

        /*
         * for non-SET modes, set the type to NULL 
         */
#ifndef NETSNMP_NO_WRITE_SUPPORT
        if (!MODE_IS_SET(asp->pdu->command)) {
#endif /* NETSNMP_NO_WRITE_SUPPORT */
            DEBUGMSGTL(("verbose:asp", "asp %p reqinfo %p assigned to request\n",
                    asp, asp->reqinfo));
            if (varbind_ptr->type == ASN_PRIV_INCL_RANGE) {
                DEBUGMSGTL(("snmp_agent", "varbind %d is inclusive\n",
                            request->index));
                request->inclusive = 1;
            }
            varbind_ptr->type = ASN_NULL;
#ifndef NETSNMP_NO_WRITE_SUPPORT
        }
#endif /* NETSNMP_NO_WRITE_SUPPORT */

        /*
         * place them in a cache 
         */
        if (tp->global_cacheid) {
            /*
             * we need to merge all marked subtrees together 
             */
            if (asp->cache_store && -1 !=
                (cacheid = netsnmp_get_local_cachid(asp->cache_store,
                                                    tp->global_cacheid))) {
            } else {
                cacheid = ++(asp->treecache_num);
                netsnmp_get_or_add_local_cachid(&asp->cache_store,
                                                tp->global_cacheid,
                                                cacheid);
                goto mallocslot;        /* XXX: ick */
            }
        } else if (tp->cacheid > -1 && tp->cacheid <= asp->treecache_num &&
                   asp->treecache[tp->cacheid].subtree == tp) {
            /*
             * we have already added a request to this tree
             * pointer before 
             */
            cacheid = tp->cacheid;
        } else {
            cacheid = ++(asp->treecache_num);
          mallocslot:
            /*
             * new slot needed 
             */
            if (asp->treecache_num >= asp->treecache_len) {
                /*
                 * exapand cache array 
                 */
                /*
                 * WWW: non-linear expansion needed (with cap) 
                 */
#define CACHE_GROW_SIZE 16
                asp->treecache_len =
                    (asp->treecache_len + CACHE_GROW_SIZE);
                asp->treecache =
                    (netsnmp_tree_cache *)realloc(asp->treecache,
                            sizeof(netsnmp_tree_cache) *
                            asp->treecache_len);
                if (asp->treecache == NULL)
                    return NULL;
                memset(&(asp->treecache[cacheid]), 0x00,
                       sizeof(netsnmp_tree_cache) * (CACHE_GROW_SIZE));
            }
            asp->treecache[cacheid].subtree = tp;
            asp->treecache[cacheid].requests_begin = request;
            tp->cacheid = cacheid;
        }

        /*
         * if this is a search type, get the ending range oid as well 
         */
        if (asp->pdu->command == SNMP_MSG_GETNEXT ||
            asp->pdu->command == SNMP_MSG_GETBULK) {
            request->range_end = tp->end_a;
            request->range_end_len = tp->end_len;
        } else {
            request->range_end = NULL;
            request->range_end_len = 0;
        }

        /*
         * link into chain 
         */
        if (asp->treecache[cacheid].requests_end)
            asp->treecache[cacheid].requests_end->next = request;
        request->next = NULL;
        request->prev = asp->treecache[cacheid].requests_end;
        asp->treecache[cacheid].requests_end = request;

        /*
         * add the given request to the list of requests they need
         * to handle results for 
         */
        request->requestvb = request->requestvb_start = varbind_ptr;
    }
    return request;
}

/*
 * check the ACM(s) for the results on each of the varbinds.
 * If ACM disallows it, replace the value with type
 * 
 * Returns number of varbinds with ACM errors
 */
int
check_acm(netsnmp_agent_session *asp, u_char type)
{
    int             view;
    int             i, j, k;
    netsnmp_request_info *request;
    int             ret = 0;
    netsnmp_variable_list *vb, *vb2, *vbc;
    int             earliest = 0;

    for (i = 0; i <= asp->treecache_num; i++) {
        for (request = asp->treecache[i].requests_begin;
             request; request = request->next) {
            /*
             * for each request, run it through in_a_view() 
             */
            earliest = 0;
            for(j = request->repeat, vb = request->requestvb_start;
                vb && j > -1;
                j--, vb = vb->next_variable) {
                if (vb->type != ASN_NULL &&
                    vb->type != ASN_PRIV_RETRY) { /* not yet processed */
                    view =
                        in_a_view(vb->name, &vb->name_length,
                                  asp->pdu, vb->type);

                    /*
                     * if a ACM error occurs, mark it as type passed in 
                     */
                    if (view != VACM_SUCCESS) {
                        ret++;
                        if (request->repeat < request->orig_repeat) {
                            /* basically this means a GETBULK */
                            request->repeat++;
                            if (!earliest) {
                                request->requestvb = vb;
                                earliest = 1;
                            }

                            /* ugh.  if a whole now exists, we need to
                               move the contents up the chain and fill
                               in at the end else we won't end up
                               lexographically sorted properly */
                            if (j > -1 && vb->next_variable &&
                                vb->next_variable->type != ASN_NULL &&
                                vb->next_variable->type != ASN_PRIV_RETRY) {
                                for(k = j, vbc = vb, vb2 = vb->next_variable;
                                    k > -2 && vbc && vb2;
                                    k--, vbc = vb2, vb2 = vb2->next_variable) {
                                    /* clone next into the current */
                                    snmp_clone_var(vb2, vbc);
                                    vbc->next_variable = vb2;
                                }
                            }
                        }
                        snmp_set_var_typed_value(vb, type, NULL, 0);
                    }
                }
            }
        }
    }
    return ret;
}


int
netsnmp_create_subtree_cache(netsnmp_agent_session *asp)
{
    netsnmp_subtree *tp;
    netsnmp_variable_list *varbind_ptr, *vbsave, *vbptr, **prevNext;
    int             view;
    int             vbcount = 0;
    int             bulkcount = 0, bulkrep = 0;
    int             i = 0, n = 0, r = 0;
    netsnmp_request_info *request;

    if (asp->treecache == NULL && asp->treecache_len == 0) {
        asp->treecache_len = SNMP_MAX(1 + asp->vbcount / 4, 16);
        asp->treecache =
            (netsnmp_tree_cache *)calloc(asp->treecache_len, sizeof(netsnmp_tree_cache));
        if (asp->treecache == NULL)
            return SNMP_ERR_GENERR;
    }
    asp->treecache_num = -1;

    if (asp->pdu->command == SNMP_MSG_GETBULK) {
        /*
         * getbulk prep 
         */
        int             count = count_varbinds(asp->pdu->variables);
        if (asp->pdu->errstat < 0) {
            asp->pdu->errstat = 0;
        }
        if (asp->pdu->errindex < 0) {
            asp->pdu->errindex = 0;
        }

        if (asp->pdu->errstat < count) {
            n = asp->pdu->errstat;
        } else {
            n = count;
        }
        if ((r = count - n) <= 0) {
            r = 0;
            asp->bulkcache = NULL;
        } else {
            int           maxbulk =
                netsnmp_ds_get_int(NETSNMP_DS_APPLICATION_ID,
                                   NETSNMP_DS_AGENT_MAX_GETBULKREPEATS);
            int maxresponses =
                netsnmp_ds_get_int(NETSNMP_DS_APPLICATION_ID,
                                   NETSNMP_DS_AGENT_MAX_GETBULKRESPONSES);

            if (maxresponses == 0)
                maxresponses = 100;   /* more than reasonable default */

            /* ensure that the total number of responses fits in a mallocable
             * result vector
             */
            if (maxresponses < 0 ||
                maxresponses > (int)(INT_MAX / sizeof(struct varbind_list *)))
                maxresponses = (int)(INT_MAX / sizeof(struct varbind_list *));

            /* ensure that the maximum number of repetitions will fit in the
             * result vector
             */
            if (maxbulk <= 0 || maxbulk > maxresponses / r)
                maxbulk = maxresponses / r;

            /* limit getbulk number of repeats to a configured size */
            if (asp->pdu->errindex > maxbulk) {
                asp->pdu->errindex = maxbulk;
                DEBUGMSGTL(("snmp_agent",
                            "truncating number of getbulk repeats to %ld\n",
                            asp->pdu->errindex));
            }

            asp->bulkcache =
                (netsnmp_variable_list **) malloc(
                    (n + asp->pdu->errindex * r) * sizeof(struct varbind_list *));

            if (!asp->bulkcache) {
                DEBUGMSGTL(("snmp_agent", "Bulkcache malloc failed\n"));
                return SNMP_ERR_GENERR;
            }
        }
        DEBUGMSGTL(("snmp_agent", "GETBULK N = %d, M = %ld, R = %d\n",
                    n, asp->pdu->errindex, r));
    }

    /*
     * collect varbinds into their registered trees 
     */
    prevNext = &(asp->pdu->variables);
    for (varbind_ptr = asp->pdu->variables; varbind_ptr;
         varbind_ptr = vbsave) {

        /*
         * getbulk mess with this pointer, so save it 
         */
        vbsave = varbind_ptr->next_variable;

        if (asp->pdu->command == SNMP_MSG_GETBULK) {
            if (n > 0) {
                n--;
            } else {
                /*
                 * repeate request varbinds on GETBULK.  These will
                 * have to be properly rearranged later though as
                 * responses are supposed to actually be interlaced
                 * with each other.  This is done with the asp->bulkcache. 
                 */
                bulkrep = asp->pdu->errindex - 1;
                if (asp->pdu->errindex > 0) {
                    vbptr = varbind_ptr;
                    asp->bulkcache[bulkcount++] = vbptr;

                    for (i = 1; i < asp->pdu->errindex; i++) {
                        vbptr->next_variable =
                            SNMP_MALLOC_STRUCT(variable_list);
                        /*
                         * don't clone the oid as it's got to be
                         * overwritten anyway 
                         */
                        if (!vbptr->next_variable) {
                            /*
                             * XXXWWW: ack!!! 
                             */
                            DEBUGMSGTL(("snmp_agent", "NextVar malloc failed\n"));
                        } else {
                            vbptr = vbptr->next_variable;
                            vbptr->name_length = 0;
                            vbptr->type = ASN_NULL;
                            asp->bulkcache[bulkcount++] = vbptr;
                        }
                    }
                    vbptr->next_variable = vbsave;
                } else {
                    /*
                     * 0 repeats requested for this varbind, so take it off
                     * the list.  
                     */
                    vbptr = varbind_ptr;
                    *prevNext = vbptr->next_variable;
                    vbptr->next_variable = NULL;
                    snmp_free_varbind(vbptr);
                    asp->vbcount--;
                    continue;
                }
            }
        }

        /*
         * count the varbinds 
         */
        ++vbcount;

        /*
         * find the owning tree 
         */
        tp = netsnmp_subtree_find(varbind_ptr->name, varbind_ptr->name_length,
				  NULL, asp->pdu->contextName);

        /*
         * check access control 
         */
        switch (asp->pdu->command) {
        case SNMP_MSG_GET:
            view = in_a_view(varbind_ptr->name, &varbind_ptr->name_length,
                             asp->pdu, varbind_ptr->type);
            if (view != VACM_SUCCESS)
                snmp_set_var_typed_value(varbind_ptr, SNMP_NOSUCHOBJECT,
                                         NULL, 0);
            break;

#ifndef NETSNMP_NO_WRITE_SUPPORT
        case SNMP_MSG_SET:
            view = in_a_view(varbind_ptr->name, &varbind_ptr->name_length,
                             asp->pdu, varbind_ptr->type);
            if (view != VACM_SUCCESS) {
                asp->index = vbcount;
                return SNMP_ERR_NOACCESS;
            }
            break;
#endif /* NETSNMP_NO_WRITE_SUPPORT */

        case SNMP_MSG_GETNEXT:
        case SNMP_MSG_GETBULK:
        default:
            view = VACM_SUCCESS;
            /*
             * XXXWWW: check VACM here to see if "tp" is even worthwhile 
             */
        }
        if (view == VACM_SUCCESS) {
            request = netsnmp_add_varbind_to_cache(asp, vbcount, varbind_ptr,
						   tp);
            if (request && asp->pdu->command == SNMP_MSG_GETBULK) {
                request->repeat = request->orig_repeat = bulkrep;
            }
        }

        prevNext = &(varbind_ptr->next_variable);
    }

    return SNMPERR_SUCCESS;
}

/*
 * this function is only applicable in getnext like contexts 
 */
int
netsnmp_reassign_requests(netsnmp_agent_session *asp)
{
    /*
     * assume all the requests have been filled or rejected by the
     * subtrees, so reassign the rejected ones to the next subtree in
     * the chain 
     */

    int             i;

    /*
     * get old info 
     */
    netsnmp_tree_cache *old_treecache = asp->treecache;

    /*
     * malloc new space 
     */
    asp->treecache =
        (netsnmp_tree_cache *) calloc(asp->treecache_len,
                                      sizeof(netsnmp_tree_cache));

    if (asp->treecache == NULL)
        return SNMP_ERR_GENERR;

    asp->treecache_num = -1;
    if (asp->cache_store) {
        netsnmp_free_cachemap(asp->cache_store);
        asp->cache_store = NULL;
    }

    for (i = 0; i < asp->vbcount; i++) {
        if (asp->requests[i].requestvb == NULL) {
            /*
             * Occurs when there's a mixture of still active
             *   and "endOfMibView" repetitions
             */
            continue;
        }
        if (asp->requests[i].requestvb->type == ASN_NULL) {
            if (!netsnmp_add_varbind_to_cache(asp, asp->requests[i].index,
                                              asp->requests[i].requestvb,
                                              asp->requests[i].subtree->next)) {
                SNMP_FREE(old_treecache);
            }
        } else if (asp->requests[i].requestvb->type == ASN_PRIV_RETRY) {
            /*
             * re-add the same subtree 
             */
            asp->requests[i].requestvb->type = ASN_NULL;
            if (!netsnmp_add_varbind_to_cache(asp, asp->requests[i].index,
                                              asp->requests[i].requestvb,
                                              asp->requests[i].subtree)) {
                SNMP_FREE(old_treecache);
            }
        }
    }

    SNMP_FREE(old_treecache);
    return SNMP_ERR_NOERROR;
}

void
netsnmp_delete_request_infos(netsnmp_request_info *reqlist)
{
    while (reqlist) {
        netsnmp_free_request_data_sets(reqlist);
        reqlist = reqlist->next;
    }
}

#ifndef NETSNMP_FEATURE_REMOVE_DELETE_SUBTREE_CACHE
void
netsnmp_delete_subtree_cache(netsnmp_agent_session *asp)
{
    while (asp->treecache_num >= 0) {
        /*
         * don't delete subtrees 
         */
        netsnmp_delete_request_infos(asp->treecache[asp->treecache_num].
                                     requests_begin);
        asp->treecache_num--;
    }
}
#endif /* NETSNMP_FEATURE_REMOVE_DELETE_SUBTREE_CACHE */

#ifndef NETSNMP_FEATURE_REMOVE_CHECK_ALL_REQUESTS_ERROR
/*
 * check all requests for errors
 *
 * @Note:
 * This function is a little different from the others in that
 * it does not use any linked lists, instead using the original
 * asp requests array. This is of particular importance for
 * cases where the linked lists are unreliable. One known instance
 * of this scenario occurs when the row_merge helper is used, which
 * may temporarily disrupts linked lists during its (and its childrens)
 * handling of requests.
 */
int
netsnmp_check_all_requests_error(netsnmp_agent_session *asp,
                                 int look_for_specific)
{
    int i;

    /*
     * find any errors marked in the requests 
     */
    for( i = 0; i < asp->vbcount; ++i ) {
        if ((SNMP_ERR_NOERROR != asp->requests[i].status) &&
            (!look_for_specific ||
             asp->requests[i].status == look_for_specific))
            return asp->requests[i].status;
    }

    return SNMP_ERR_NOERROR;
}
#endif /* NETSNMP_FEATURE_REMOVE_CHECK_ALL_REQUESTS_ERROR */

#ifndef NETSNMP_FEATURE_REMOVE_CHECK_REQUESTS_ERROR
int
netsnmp_check_requests_error(netsnmp_request_info *requests)
{
    /*
     * find any errors marked in the requests 
     */
    for (;requests;requests = requests->next) {
        if (requests->status != SNMP_ERR_NOERROR)
            return requests->status;
    }
    return SNMP_ERR_NOERROR;
}
#endif /* NETSNMP_FEATURE_REMOVE_CHECK_REQUESTS_ERROR */

int
netsnmp_check_requests_status(netsnmp_agent_session *asp,
                              netsnmp_request_info *requests,
                              int look_for_specific)
{
    /*
     * find any errors marked in the requests 
     */
    while (requests) {
        if(requests->agent_req_info != asp->reqinfo) {
            DEBUGMSGTL(("verbose:asp",
                        "**reqinfo %p doesn't match cached reqinfo %p\n",
                        asp->reqinfo, requests->agent_req_info));
        }
        if (requests->status != SNMP_ERR_NOERROR &&
            (!look_for_specific || requests->status == look_for_specific)
            && (look_for_specific || asp->index == 0
                || requests->index < asp->index)) {
            asp->index = requests->index;
            asp->status = requests->status;
        }
        requests = requests->next;
    }
    return asp->status;
}

int
netsnmp_check_all_requests_status(netsnmp_agent_session *asp,
                                  int look_for_specific)
{
    int             i;
    for (i = 0; i <= asp->treecache_num; i++) {
        netsnmp_check_requests_status(asp,
                                      asp->treecache[i].requests_begin,
                                      look_for_specific);
    }
    return asp->status;
}

int
handle_var_requests(netsnmp_agent_session *asp)
{
    int             i, retstatus = SNMP_ERR_NOERROR,
        status = SNMP_ERR_NOERROR, final_status = SNMP_ERR_NOERROR;
    netsnmp_handler_registration *reginfo;

    asp->reqinfo->asp = asp;
    asp->reqinfo->mode = asp->mode;

    /*
     * now, have the subtrees in the cache go search for their results 
     */
    for (i = 0; i <= asp->treecache_num; i++) {
        /*
         * don't call handlers w/null reginfo.
         * - when is this? sub agent disconnected while request processing?
         * - should this case encompass more of this subroutine?
         *   - does check_request_status make send if handlers weren't called?
         */
        if(NULL != asp->treecache[i].subtree->reginfo) {
            reginfo = asp->treecache[i].subtree->reginfo;
            status = netsnmp_call_handlers(reginfo, asp->reqinfo,
                                           asp->treecache[i].requests_begin);
        }
        else
            status = SNMP_ERR_GENERR;

        /*
         * find any errors marked in the requests.  For later parts of
         * SET processing, only check for new errors specific to that
         * set processing directive (which must superceed the previous
         * errors).
         */
        switch (asp->mode) {
#ifndef NETSNMP_NO_WRITE_SUPPORT
        case MODE_SET_COMMIT:
            retstatus = netsnmp_check_requests_status(asp,
						      asp->treecache[i].
						      requests_begin,
						      SNMP_ERR_COMMITFAILED);
            break;

        case MODE_SET_UNDO:
            retstatus = netsnmp_check_requests_status(asp,
						      asp->treecache[i].
						      requests_begin,
						      SNMP_ERR_UNDOFAILED);
            break;
#endif /* NETSNMP_NO_WRITE_SUPPORT */

        default:
            retstatus = netsnmp_check_requests_status(asp,
						      asp->treecache[i].
						      requests_begin, 0);
            break;
        }

        /*
         * always take lowest varbind if possible 
         */
        if (retstatus != SNMP_ERR_NOERROR) {
            status = retstatus;
	}

        /*
         * other things we know less about (no index) 
         */
        /*
         * WWW: drop support for this? 
         */
        if (final_status == SNMP_ERR_NOERROR && status != SNMP_ERR_NOERROR) {
            /*
             * we can't break here, since some processing needs to be
             * done for all requests anyway (IE, SET handling for UNDO
             * needs to be called regardless of previous status
             * results.
             * WWW:  This should be predictable though and
             * breaking should be possible in some cases (eg GET,
             * GETNEXT, ...) 
             */
            final_status = status;
        }
    }

    return final_status;
}

/*
 * loop through our sessions known delegated sessions and check to see
 * if they've completed yet. If there are no more delegated sessions,
 * check for and process any queued requests
 */
void
netsnmp_check_outstanding_agent_requests(void)
{
    netsnmp_agent_session *asp, *prev_asp = NULL, *next_asp = NULL;

    /*
     * deal with delegated requests
     */
    for (asp = agent_delegated_list; asp; asp = next_asp) {
        next_asp = asp->next;   /* save in case we clean up asp */
        if (!netsnmp_check_for_delegated(asp)) {

            /*
             * we're done with this one, remove from queue 
             */
            if (prev_asp != NULL)
                prev_asp->next = asp->next;
            else
                agent_delegated_list = asp->next;
            asp->next = NULL;

            /*
             * check request status
             */
            netsnmp_check_all_requests_status(asp, 0);
            
            /*
             * continue processing or finish up 
             */
            check_delayed_request(asp);

            /*
             * if head was removed, don't drop it if it
             * was it re-queued
             */
            if ((prev_asp == NULL) && (agent_delegated_list == asp)) {
                prev_asp = asp;
            }
        } else {

            /*
             * asp is still on the queue
             */
            prev_asp = asp;
        }
    }

    /*
     * if we are processing a set and there are more delegated
     * requests, keep waiting before getting to queued requests.
     */
    if (netsnmp_processing_set && (NULL != agent_delegated_list))
        return;

    while (netsnmp_agent_queued_list) {

        /*
         * if we are processing a set, the first item better be
         * the set being (or waiting to be) processed.
         */
        netsnmp_assert((!netsnmp_processing_set) ||
                       (netsnmp_processing_set == netsnmp_agent_queued_list));

        /*
         * if the top request is a set, don't pop it
         * off if there are delegated requests
         */
#ifndef NETSNMP_NO_WRITE_SUPPORT
        if ((netsnmp_agent_queued_list->pdu->command == SNMP_MSG_SET) &&
            (agent_delegated_list)) {

            netsnmp_assert(netsnmp_processing_set == NULL);

            netsnmp_processing_set = netsnmp_agent_queued_list;
            DEBUGMSGTL(("snmp_agent", "SET request remains queued while "
                        "delegated requests finish, asp = %8p\n", asp));
            break;
        }
#endif /* NETSNMP_NO_WRITE_SUPPORT */

        /*
         * pop the first request and process it
         */
        asp = netsnmp_agent_queued_list;
        netsnmp_agent_queued_list = asp->next;
        DEBUGMSGTL(("snmp_agent",
                    "processing queued request, asp = %8p\n", asp));

        netsnmp_handle_request(asp, asp->status);

        /*
         * if we hit a set, stop
         */
        if (NULL != netsnmp_processing_set)
            break;
    }
}

/** Decide if the requested transaction_id is still being processed
   within the agent.  This is used to validate whether a delayed cache
   (containing possibly freed pointers) is still usable.

   returns SNMPERR_SUCCESS if it's still valid, or SNMPERR_GENERR if not. */
int
netsnmp_check_transaction_id(int transaction_id)
{
    netsnmp_agent_session *asp;

    for (asp = agent_delegated_list; asp; asp = asp->next) {
        if (asp->pdu->transid == transaction_id)
            return SNMPERR_SUCCESS;
    }
    return SNMPERR_GENERR;
}


/*
 * check_delayed_request(asp)
 *
 * Called to rexamine a set of requests and continue processing them
 * once all the previous (delayed) requests have been handled one way
 * or another.
 */

int
check_delayed_request(netsnmp_agent_session *asp)
{
    int             status = SNMP_ERR_NOERROR;

    DEBUGMSGTL(("snmp_agent", "processing delegated request, asp = %8p\n",
                asp));

    switch (asp->mode) {
    case SNMP_MSG_GETBULK:
    case SNMP_MSG_GETNEXT:
        netsnmp_check_all_requests_status(asp, 0);
        handle_getnext_loop(asp);
        if (netsnmp_check_for_delegated(asp) &&
            netsnmp_check_transaction_id(asp->pdu->transid) !=
            SNMPERR_SUCCESS) {
            /*
             * add to delegated request chain 
             */
            if (!netsnmp_check_delegated_chain_for(asp)) {
                asp->next = agent_delegated_list;
                agent_delegated_list = asp;
            }
        }
        break;

#ifndef NETSNMP_NO_WRITE_SUPPORT
    case MODE_SET_COMMIT:
        netsnmp_check_all_requests_status(asp, SNMP_ERR_COMMITFAILED);
        goto settop;

    case MODE_SET_UNDO:
        netsnmp_check_all_requests_status(asp, SNMP_ERR_UNDOFAILED);
        goto settop;

    case MODE_SET_BEGIN:
    case MODE_SET_RESERVE1:
    case MODE_SET_RESERVE2:
    case MODE_SET_ACTION:
    case MODE_SET_FREE:
      settop:
        /* If we should do only one pass, this mean we */
        /* should not reenter this function */
        if ((asp->pdu->flags & UCD_MSG_FLAG_ONE_PASS_ONLY)) {
            /* We should have finished the processing after the first */
            /* handle_set_loop, so just wrap up */
            break;
        }
        handle_set_loop(asp);
        if (asp->mode != FINISHED_SUCCESS && asp->mode != FINISHED_FAILURE) {

            if (netsnmp_check_for_delegated_and_add(asp)) {
                /*
                 * add to delegated request chain 
                 */
                if (!asp->status)
                    asp->status = status;
            }

            return SNMP_ERR_NOERROR;
        }
        break;
#endif /* NETSNMP_NO_WRITE_SUPPORT */

    default:
        break;
    }

    /*
     * if we don't have anything outstanding (delegated), wrap up 
     */
    if (!netsnmp_check_for_delegated(asp))
        return netsnmp_wrap_up_request(asp, status);

    return 1;
}

/** returns 1 if there are valid GETNEXT requests left.  Returns 0 if not. */
int
check_getnext_results(netsnmp_agent_session *asp)
{
    /*
     * get old info 
     */
    netsnmp_tree_cache *old_treecache = asp->treecache;
    int             old_treecache_num = asp->treecache_num;
    int             count = 0;
    int             i, special = 0;
    netsnmp_request_info *request;

    if (asp->mode == SNMP_MSG_GET) {
        /*
         * Special case for doing INCLUSIVE getNext operations in
         * AgentX subagents.  
         */
        DEBUGMSGTL(("snmp_agent",
                    "asp->mode == SNMP_MSG_GET in ch_getnext\n"));
        asp->mode = asp->oldmode;
        special = 1;
    }

    for (i = 0; i <= old_treecache_num; i++) {
        for (request = old_treecache[i].requests_begin; request;
             request = request->next) {

            /*
             * If we have just done the special case AgentX GET, then any
             * requests which were not INCLUSIVE will now have a wrong
             * response, so junk them and retry from the same place (except
             * that this time the handler will be called in "inexact"
             * mode).  
             */

            if (special) {
                if (!request->inclusive) {
                    DEBUGMSGTL(("snmp_agent",
                                "request %d wasn't inclusive\n",
                                request->index));
                    snmp_set_var_typed_value(request->requestvb,
                                             ASN_PRIV_RETRY, NULL, 0);
                } else if (request->requestvb->type == ASN_NULL ||
                           request->requestvb->type == SNMP_NOSUCHINSTANCE ||
                           request->requestvb->type == SNMP_NOSUCHOBJECT) {
                    /*
                     * it was inclusive, but no results.  Still retry this
                     * search. 
                     */
                    snmp_set_var_typed_value(request->requestvb,
                                             ASN_PRIV_RETRY, NULL, 0);
                }
            }

            /*
             * out of range? 
             */
            if (snmp_oid_compare(request->requestvb->name,
                                 request->requestvb->name_length,
                                 request->range_end,
                                 request->range_end_len) >= 0) {
                /*
                 * ack, it's beyond the accepted end of range. 
                 */
                /*
                 * fix it by setting the oid to the end of range oid instead 
                 */
                DEBUGMSGTL(("check_getnext_results",
                            "request response %d out of range\n",
                            request->index));
                /*
                 * I'm not sure why inclusive is set unconditionally here (see
                 * comments for revision 1.161), but it causes a problem for
                 * GETBULK over an overridden variable. The bulk-to-next
                 * handler re-uses the same request for multiple varbinds,
                 * and once inclusive was set, it was never cleared. So, a
                 * hack. Instead of setting it to 1, set it to 2, so bulk-to
                 * next can clear it later. As of the time of this hack, all
                 * checks of this var are boolean checks (not == 1), so this
                 * should be safe. Cross your fingers.
                 */
                request->inclusive = 2;
                /*
                 * XXX: should set this to the original OID? 
                 */
                snmp_set_var_objid(request->requestvb,
                                   request->range_end,
                                   request->range_end_len);
                snmp_set_var_typed_value(request->requestvb, ASN_NULL,
                                         NULL, 0);
            }

            /*
             * mark any existent requests with illegal results as NULL 
             */
            if (request->requestvb->type == SNMP_ENDOFMIBVIEW) {
                /*
                 * illegal response from a subagent.  Change it back to NULL 
                 *  xxx-rks: err, how do we know this is a subagent?
                 */
                request->requestvb->type = ASN_NULL;
                request->inclusive = 1;
            }

            if (request->requestvb->type == ASN_NULL ||
                request->requestvb->type == ASN_PRIV_RETRY ||
                (asp->reqinfo->mode == MODE_GETBULK
                 && request->repeat > 0))
                count++;
        }
    }
    return count;
}

/** repeatedly calls getnext handlers looking for an answer till all
   requests are satisified.  It's expected that one pass has been made
   before entering this function */
int
handle_getnext_loop(netsnmp_agent_session *asp)
{
    int             status;
    netsnmp_variable_list *var_ptr;

    /*
     * loop 
     */
    while (netsnmp_running) {

        /*
         * bail for now if anything is delegated. 
         */
        if (netsnmp_check_for_delegated(asp)) {
            return SNMP_ERR_NOERROR;
        }

        /*
         * check vacm against results 
         */
        check_acm(asp, ASN_PRIV_RETRY);

        /*
         * need to keep going we're not done yet. 
         */
        if (!check_getnext_results(asp))
            /*
             * nothing left, quit now 
             */
            break;

        /*
         * never had a request (empty pdu), quit now 
         */
        /*
         * XXXWWW: huh?  this would be too late, no?  shouldn't we
         * catch this earlier? 
         */
        /*
         * if (count == 0)
         * break; 
         */

        DEBUGIF("results") {
            DEBUGMSGTL(("results",
                        "getnext results, before next pass:\n"));
            for (var_ptr = asp->pdu->variables; var_ptr;
                 var_ptr = var_ptr->next_variable) {
                DEBUGMSGTL(("results", "\t"));
                DEBUGMSGVAR(("results", var_ptr));
                DEBUGMSG(("results", "\n"));
            }
        }

        netsnmp_reassign_requests(asp);
        status = handle_var_requests(asp);
        if (status != SNMP_ERR_NOERROR) {
            return status;      /* should never really happen */
        }
    }
    return SNMP_ERR_NOERROR;
}

#ifndef NETSNMP_NO_WRITE_SUPPORT
int
handle_set(netsnmp_agent_session *asp)
{
    int             status;
    /*
     * SETS require 3-4 passes through the var_op_list.
     * The first two
     * passes verify that all types, lengths, and values are valid
     * and may reserve resources and the third does the set and a
     * fourth executes any actions.  Then the identical GET RESPONSE
     * packet is returned.
     * If either of the first two passes returns an error, another
     * pass is made so that any reserved resources can be freed.
     * If the third pass returns an error, another pass is
     * made so that
     * any changes can be reversed.
     * If the fourth pass (or any of the error handling passes)
     * return an error, we'd rather not know about it!
     */
    if (!(asp->pdu->flags & UCD_MSG_FLAG_ONE_PASS_ONLY)) {
        switch (asp->mode) {
        case MODE_SET_BEGIN:
            snmp_increment_statistic(STAT_SNMPINSETREQUESTS);
            asp->rw = WRITE;    /* WWW: still needed? */
            asp->mode = MODE_SET_RESERVE1;
            asp->status = SNMP_ERR_NOERROR;
            break;

        case MODE_SET_RESERVE1:

            if (asp->status != SNMP_ERR_NOERROR)
                asp->mode = MODE_SET_FREE;
            else
                asp->mode = MODE_SET_RESERVE2;
            break;

        case MODE_SET_RESERVE2:
            if (asp->status != SNMP_ERR_NOERROR)
                asp->mode = MODE_SET_FREE;
            else
                asp->mode = MODE_SET_ACTION;
            break;

        case MODE_SET_ACTION:
            if (asp->status != SNMP_ERR_NOERROR)
                asp->mode = MODE_SET_UNDO;
            else
                asp->mode = MODE_SET_COMMIT;
            break;

        case MODE_SET_COMMIT:
            if (asp->status != SNMP_ERR_NOERROR) {
                asp->mode = FINISHED_FAILURE;
            } else {
                asp->mode = FINISHED_SUCCESS;
            }
            break;

        case MODE_SET_UNDO:
            asp->mode = FINISHED_FAILURE;
            break;

        case MODE_SET_FREE:
            asp->mode = FINISHED_FAILURE;
            break;
        }
    }

    if (asp->mode != FINISHED_SUCCESS && asp->mode != FINISHED_FAILURE) {
        DEBUGMSGTL(("agent_set", "doing set mode = %d (%s)\n", asp->mode,
                    se_find_label_in_slist("agent_mode", asp->mode)));
        status = handle_var_requests(asp);
        DEBUGMSGTL(("agent_set", "did set mode = %d, status = %d\n",
                    asp->mode, status));
        if ((status != SNMP_ERR_NOERROR && asp->status == SNMP_ERR_NOERROR) ||
	    status == SNMP_ERR_COMMITFAILED || 
	    status == SNMP_ERR_UNDOFAILED) {
            asp->status = status;
        }
    }
    return asp->status;
}

int
handle_set_loop(netsnmp_agent_session *asp)
{
    while (asp->mode != FINISHED_FAILURE && asp->mode != FINISHED_SUCCESS) {
        handle_set(asp);
        if (netsnmp_check_for_delegated(asp)) {
            return SNMP_ERR_NOERROR;
	}
        if (asp->pdu->flags & UCD_MSG_FLAG_ONE_PASS_ONLY) {
            return asp->status;
	}
    }
    return asp->status;
}
#endif /* NETSNMP_NO_WRITE_SUPPORT */

int
netsnmp_handle_request(netsnmp_agent_session *asp, int status)
{
    /*
     * if this isn't a delegated request trying to finish,
     * processing of a set request should not start until all
     * delegated requests have completed, and no other new requests
     * should be processed until the set request completes.
     */
    if ((0 == netsnmp_check_delegated_chain_for(asp)) &&
        (asp != netsnmp_processing_set)) {
        /*
         * if we are processing a set and this is not a delegated
         * request, queue the request
         */
        if (netsnmp_processing_set) {
            netsnmp_add_queued(asp);
            DEBUGMSGTL(("snmp_agent",
                        "request queued while processing set, "
                        "asp = %8p\n", asp));
            return 1;
        }

        /*
         * check for set request
         */
#ifndef NETSNMP_NO_WRITE_SUPPORT
        if (asp->pdu->command == SNMP_MSG_SET) {
            netsnmp_processing_set = asp;

            /*
             * if there are delegated requests, we must wait for them
             * to finish.
             */
            if (agent_delegated_list) {
                DEBUGMSGTL(("snmp_agent", "SET request queued while "
                            "delegated requests finish, asp = %8p\n",
                            asp));
                netsnmp_add_queued(asp);
                return 1;
            }
        }
#endif /* NETSNMP_NO_WRITE_SUPPORT */
    }

    /*
     * process the request 
     */
    status = handle_pdu(asp);

    /*
     * print the results in appropriate debugging mode 
     */
    DEBUGIF("results") {
        netsnmp_variable_list *var_ptr;
        DEBUGMSGTL(("results", "request results (status = %d):\n",
                    status));
        for (var_ptr = asp->pdu->variables; var_ptr;
             var_ptr = var_ptr->next_variable) {
            DEBUGMSGTL(("results", "\t"));
            DEBUGMSGVAR(("results", var_ptr));
            DEBUGMSG(("results", "\n"));
        }
    }

    /*
     * check for uncompleted requests 
     */
    if (netsnmp_check_for_delegated_and_add(asp)) {
        /*
         * add to delegated request chain 
         */
        asp->status = status;
    } else {
        /*
         * if we don't have anything outstanding (delegated), wrap up
         */
        return netsnmp_wrap_up_request(asp, status);
    }

    return 1;
}

int
handle_pdu(netsnmp_agent_session *asp)
{
    int             status, inclusives = 0;
    netsnmp_variable_list *v = NULL;

    /*
     * for illegal requests, mark all nodes as ASN_NULL 
     */
    switch (asp->pdu->command) {

#ifndef NETSNMP_NO_WRITE_SUPPORT
    case SNMP_MSG_INTERNAL_SET_RESERVE2:
    case SNMP_MSG_INTERNAL_SET_ACTION:
    case SNMP_MSG_INTERNAL_SET_COMMIT:
    case SNMP_MSG_INTERNAL_SET_FREE:
    case SNMP_MSG_INTERNAL_SET_UNDO:
        status = get_set_cache(asp);
        if (status != SNMP_ERR_NOERROR)
            return status;
        break;
#endif /* NETSNMP_NO_WRITE_SUPPORT */

    case SNMP_MSG_GET:
    case SNMP_MSG_GETNEXT:
    case SNMP_MSG_GETBULK:
        for (v = asp->pdu->variables; v != NULL; v = v->next_variable) {
            if (v->type == ASN_PRIV_INCL_RANGE) {
                /*
                 * Leave the type for now (it gets set to
                 * ASN_NULL in netsnmp_add_varbind_to_cache,
                 * called by create_subnetsnmp_tree_cache below).
                 * If we set it to ASN_NULL now, we wouldn't be
                 * able to distinguish INCLUSIVE search
                 * ranges.  
                 */
                inclusives++;
            } else {
                snmp_set_var_typed_value(v, ASN_NULL, NULL, 0);
            }
        }
        /*
         * fall through 
         */

#ifndef NETSNMP_NO_WRITE_SUPPORT
    case SNMP_MSG_INTERNAL_SET_BEGIN:
    case SNMP_MSG_INTERNAL_SET_RESERVE1:
#endif /* NETSNMP_NO_WRITE_SUPPORT */
    default:
        asp->vbcount = count_varbinds(asp->pdu->variables);
        if (asp->vbcount) /* efence doesn't like 0 size allocs */
            asp->requests = (netsnmp_request_info *)
                calloc(asp->vbcount, sizeof(netsnmp_request_info));
        /*
         * collect varbinds 
         */
        status = netsnmp_create_subtree_cache(asp);
        if (status != SNMP_ERR_NOERROR)
            return status;
    }

    asp->mode = asp->pdu->command;
    switch (asp->mode) {
    case SNMP_MSG_GET:
        /*
         * increment the message type counter 
         */
        snmp_increment_statistic(STAT_SNMPINGETREQUESTS);

        /*
         * check vacm ahead of time 
         */
        check_acm(asp, SNMP_NOSUCHOBJECT);

        /*
         * get the results 
         */
        status = handle_var_requests(asp);

        /*
         * Deal with unhandled results -> noSuchInstance (rather
         * than noSuchObject -- in that case, the type will
         * already have been set to noSuchObject when we realised
         * we couldn't find an appropriate tree).  
         */
        if (status == SNMP_ERR_NOERROR)
            snmp_replace_var_types(asp->pdu->variables, ASN_NULL,
                                   SNMP_NOSUCHINSTANCE);
        break;

    case SNMP_MSG_GETNEXT:
        snmp_increment_statistic(STAT_SNMPINGETNEXTS);
        /*
         * fall through 
         */

    case SNMP_MSG_GETBULK:     /* note: there is no getbulk stat */
        /*
         * loop through our mib tree till we find an
         * appropriate response to return to the caller. 
         */

        if (inclusives) {
            /*
             * This is a special case for AgentX INCLUSIVE getNext
             * requests where a result lexi-equal to the request is okay
             * but if such a result does not exist, we still want the
             * lexi-next one.  So basically we do a GET first, and if any
             * of the INCLUSIVE requests are satisfied, we use that
             * value.  Then, unsatisfied INCLUSIVE requests, and
             * non-INCLUSIVE requests get done as normal.  
             */

            DEBUGMSGTL(("snmp_agent", "inclusive range(s) in getNext\n"));
            asp->oldmode = asp->mode;
            asp->mode = SNMP_MSG_GET;
        }

        /*
         * first pass 
         */
        status = handle_var_requests(asp);
        if (status != SNMP_ERR_NOERROR) {
            if (!inclusives)
                return status;  /* should never really happen */
            else
                asp->status = SNMP_ERR_NOERROR;
        }

        /*
         * loop through our mib tree till we find an
         * appropriate response to return to the caller. 
         */

        status = handle_getnext_loop(asp);
        break;

#ifndef NETSNMP_NO_WRITE_SUPPORT
    case SNMP_MSG_SET:
#ifdef NETSNMP_DISABLE_SET_SUPPORT
        return SNMP_ERR_NOTWRITABLE;
#else
        /*
         * check access permissions first 
         */
        if (check_acm(asp, SNMP_NOSUCHOBJECT))
            return SNMP_ERR_NOTWRITABLE;

        asp->mode = MODE_SET_BEGIN;
        status = handle_set_loop(asp);
#endif
        break;

    case SNMP_MSG_INTERNAL_SET_BEGIN:
    case SNMP_MSG_INTERNAL_SET_RESERVE1:
    case SNMP_MSG_INTERNAL_SET_RESERVE2:
    case SNMP_MSG_INTERNAL_SET_ACTION:
    case SNMP_MSG_INTERNAL_SET_COMMIT:
    case SNMP_MSG_INTERNAL_SET_FREE:
    case SNMP_MSG_INTERNAL_SET_UNDO:
        asp->pdu->flags |= UCD_MSG_FLAG_ONE_PASS_ONLY;
        status = handle_set_loop(asp);
        /*
         * asp related cache is saved in cleanup 
         */
        break;
#endif /* NETSNMP_NO_WRITE_SUPPORT */

    case SNMP_MSG_RESPONSE:
        snmp_increment_statistic(STAT_SNMPINGETRESPONSES);
        return SNMP_ERR_NOERROR;

    case SNMP_MSG_TRAP:
    case SNMP_MSG_TRAP2:
        snmp_increment_statistic(STAT_SNMPINTRAPS);
        return SNMP_ERR_NOERROR;

    default:
        /*
         * WWW: are reports counted somewhere ? 
         */
        snmp_increment_statistic(STAT_SNMPINASNPARSEERRS);
        return SNMPERR_GENERR;  /* shouldn't get here */
        /*
         * WWW 
         */
    }
    return status;
}

/** set error for a request
 * \internal external interface: netsnmp_request_set_error
 */
NETSNMP_STATIC_INLINE int
_request_set_error(netsnmp_request_info *request, int mode, int error_value)
{
    if (!request)
        return SNMPERR_NO_VARS;

    request->processed = 1;
    request->delegated = REQUEST_IS_NOT_DELEGATED;

    switch (error_value) {
    case SNMP_NOSUCHOBJECT:
    case SNMP_NOSUCHINSTANCE:
    case SNMP_ENDOFMIBVIEW:
        /*
         * these are exceptions that should be put in the varbind
         * in the case of a GET but should be translated for a SET
         * into a real error status code and put in the request 
         */
        switch (mode) {
        case MODE_GET:
        case MODE_GETNEXT:
        case MODE_GETBULK:
            request->requestvb->type = error_value;
            break;

            /*
             * These are technically illegal to set by the
             * client APIs for these modes.  But accepting
             * them here allows the 'sparse_table' helper to
             * provide some common table handling processing
             *
            snmp_log(LOG_ERR, "Illegal error_value %d for mode %d ignored\n",
                     error_value, mode);
            return SNMPERR_VALUE;
             */

#ifndef NETSNMP_NO_WRITE_SUPPORT
        case SNMP_MSG_INTERNAL_SET_RESERVE1:
            request->status = SNMP_ERR_NOCREATION;
            break;
#endif /* NETSNMP_NO_WRITE_SUPPORT */

        default:
            request->status = SNMP_ERR_NOSUCHNAME;      /* WWW: correct? */
            break;
        }
        break;                  /* never get here */

    default:
        if (error_value < 0) {
            /*
             * illegal local error code.  translate to generr 
             */
            /*
             * WWW: full translation map? 
             */
            snmp_log(LOG_ERR, "Illegal error_value %d translated to %d\n",
                     error_value, SNMP_ERR_GENERR);
            request->status = SNMP_ERR_GENERR;
        } else {
            /*
             * WWW: translations and mode checking? 
             */
            request->status = error_value;
        }
        break;
    }
    return SNMPERR_SUCCESS;
}

/** set error for a request
 * @param request request which has error
 * @param error_value error value for request
 */
int
netsnmp_request_set_error(netsnmp_request_info *request, int error_value)
{
    if (!request || !request->agent_req_info)
        return SNMPERR_NO_VARS;

    return _request_set_error(request, request->agent_req_info->mode,
                              error_value);
}

#ifndef NETSNMP_FEATURE_REMOVE_REQUEST_SET_ERROR_IDX
/** set error for a request within a request list
 * @param request head of the request list
 * @param error_value error value for request
 * @param idx index of the request which has the error
 */
int
netsnmp_request_set_error_idx(netsnmp_request_info *request,
                              int error_value, int idx)
{
    int i;
    netsnmp_request_info *req = request;

    if (!request || !request->agent_req_info)
        return SNMPERR_NO_VARS;

    /*
     * Skip to the indicated varbind
     */
    for ( i=2; i<idx; i++) {
        req = req->next;
        if (!req)
            return SNMPERR_NO_VARS;
    }
    
    return _request_set_error(req, request->agent_req_info->mode,
                              error_value);
}
#endif /* NETSNMP_FEATURE_REMOVE_REQUEST_SET_ERROR_IDX */

/** set error for all requests
 * @param requests request list
 * @param error error value for requests
 * @return SNMPERR_SUCCESS, or an error code
 */
NETSNMP_INLINE int
netsnmp_request_set_error_all( netsnmp_request_info *requests, int error)
{
    int mode, rc, result = SNMPERR_SUCCESS;

    if((NULL == requests) || (NULL == requests->agent_req_info))
        return SNMPERR_NO_VARS;
    
    mode = requests->agent_req_info->mode; /* every req has same mode */
    
    for(; requests ; requests = requests->next) {

        /** paranoid sanity checks */
        netsnmp_assert(NULL != requests->agent_req_info);
        netsnmp_assert(mode == requests->agent_req_info->mode);

        /*
         * set error for this request. Log any errors, save the last
         * to return to the user.
         */
        if((rc = _request_set_error(requests, mode, error))) {
            snmp_log(LOG_WARNING,"got %d while setting request error\n", rc);
            result = rc;
        }
    }
    return result;
}

/**
 * Return the difference between pm and the agent start time in hundredths of
 * a second.
 * \deprecated Don't use in new code.
 *
 * @param[in] pm An absolute time as e.g. reported by gettimeofday().
 */
u_long
netsnmp_marker_uptime(marker_t pm)
{
    u_long          res;
    const_marker_t  start = netsnmp_get_agent_starttime();

    res = uatime_hdiff(start, pm);
    return res;
}

/**
 * Return the difference between tv and the agent start time in hundredths of
 * a second.
 *
 * \deprecated Use netsnmp_get_agent_uptime() instead.
 *
 * @param[in] tv An absolute time as e.g. reported by gettimeofday().
 */
u_long
netsnmp_timeval_uptime(struct timeval * tv)
{
    return netsnmp_marker_uptime((marker_t) tv);
}


struct timeval  starttime;
static struct timeval starttimeM;

/**
 * Return a pointer to the variable in which the Net-SNMP start time has
 * been stored.
 *
 * @note Use netsnmp_get_agent_runtime() instead of this function if you need
 *   to know how much time elapsed since netsnmp_set_agent_starttime() has been
 *   called.
 */
const_marker_t        
netsnmp_get_agent_starttime(void)
{
    return &starttime;
}

/**
 * Report the time that elapsed since the agent start time in hundredths of a
 * second.
 *
 * @see See also netsnmp_set_agent_starttime().
 */
uint64_t
netsnmp_get_agent_runtime(void)
{
    struct timeval now, delta;

    netsnmp_get_monotonic_clock(&now);
    NETSNMP_TIMERSUB(&now, &starttimeM, &delta);
    return delta.tv_sec * (uint64_t)100 + delta.tv_usec / 10000;
}

/**
 * Set the time at which Net-SNMP started either to the current time
 * (if s == NULL) or to *s (if s is not NULL).
 *
 * @see See also netsnmp_set_agent_uptime().
 */
void            
netsnmp_set_agent_starttime(marker_t s)
{
    if (s) {
        struct timeval nowA, nowM;

        starttime = *(struct timeval*)s;
        gettimeofday(&nowA, NULL);
        netsnmp_get_monotonic_clock(&nowM);
        NETSNMP_TIMERSUB(&starttime, &nowA, &starttimeM);
        NETSNMP_TIMERADD(&starttimeM, &nowM, &starttimeM);
    } else {
        gettimeofday(&starttime, NULL);
        netsnmp_get_monotonic_clock(&starttimeM);
    }
}


/**
 * Return the current value of 'sysUpTime' 
 */
u_long
netsnmp_get_agent_uptime(void)
{
    struct timeval now, delta;

    netsnmp_get_monotonic_clock(&now);
    NETSNMP_TIMERSUB(&now, &starttimeM, &delta);
    return delta.tv_sec * 100UL + delta.tv_usec / 10000;
}

#ifndef NETSNMP_FEATURE_REMOVE_SET_AGENT_UPTIME
/**
 * Set the start time from which 'sysUpTime' is computed.
 *
 * @param[in] hsec New sysUpTime in hundredths of a second.
 *
 * @see See also netsnmp_set_agent_starttime().
 */
void
netsnmp_set_agent_uptime(u_long hsec)
{
    struct timeval  nowA, nowM;
    struct timeval  new_uptime;

    gettimeofday(&nowA, NULL);
    netsnmp_get_monotonic_clock(&nowM);
    new_uptime.tv_sec = hsec / 100;
    new_uptime.tv_usec = (uint32_t)(hsec - new_uptime.tv_sec * 100) * 10000L;
    NETSNMP_TIMERSUB(&nowA, &new_uptime, &starttime);
    NETSNMP_TIMERSUB(&nowM, &new_uptime, &starttimeM);
}
#endif /* NETSNMP_FEATURE_REMOVE_SET_AGENT_UPTIME */


/*************************************************************************
 *
 * deprecated functions
 *
 */

/** set error for a request
 * \deprecated, use netsnmp_request_set_error instead
 * @param reqinfo agent_request_info pointer for request
 * @param request request_info pointer
 * @param error_value error value for requests
 * @return error_value
 */
int
netsnmp_set_request_error(netsnmp_agent_request_info *reqinfo,
                          netsnmp_request_info *request, int error_value)
{
    if (!request || !reqinfo)
        return error_value;

    _request_set_error(request, reqinfo->mode, error_value);
    
    return error_value;
}

/** set error for a request
 * \deprecated, use netsnmp_request_set_error instead
 * @param mode Net-SNMP agent processing mode
 * @param request request_info pointer
 * @param error_value error value for requests
 * @return error_value
 */
int
netsnmp_set_mode_request_error(int mode, netsnmp_request_info *request,
                               int error_value)
{
    _request_set_error(request, mode, error_value);
    
    return error_value;
}

/** set error for all request
 * \deprecated use netsnmp_request_set_error_all
 * @param reqinfo agent_request_info pointer for requests
 * @param requests request list
 * @param error_value error value for requests
 * @return error_value
 */
#ifndef NETSNMP_FEATURE_REMOVE_SET_ALL_REQUESTS_ERROR
int
netsnmp_set_all_requests_error(netsnmp_agent_request_info *reqinfo,
                               netsnmp_request_info *requests,
                               int error_value)
{
    netsnmp_request_set_error_all(requests, error_value);
    return error_value;
}
#endif /* NETSNMP_FEATURE_REMOVE_SET_ALL_REQUESTS_ERROR */
/** @} */