summaryrefslogtreecommitdiff
path: root/agent/agent_registry.c
blob: 1e2482ab0eda614c2715505053c1b1a8ebdfc807 (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
/*
 * agent_registry.c
 */
/* 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 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 agent_registry Registry of MIB subtrees, modules, sessions, etc
 *     Maintain a registry of MIB subtrees, together with related information
 *     regarding MIB modules, sessions, etc
 *   @ingroup agent
 *
 * @{
 */

#define IN_SNMP_VARS_C

#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-features.h>

#include <signal.h>
#if HAVE_STRING_H
#include <string.h>
#endif
#if HAVE_STDLIB_H
#include <stdlib.h>
#endif
#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
#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_NETINET_IN_H
#include <netinet/in.h>
#endif

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

#include "snmpd.h"
#include "mibgroup/struct.h"
#include <net-snmp/agent/old_api.h>
#include <net-snmp/agent/null.h>
#include <net-snmp/agent/table.h>
#include <net-snmp/agent/table_iterator.h>
#include <net-snmp/agent/agent_registry.h>
#include "mib_module_includes.h"

#ifdef USING_AGENTX_SUBAGENT_MODULE
#include "agentx/subagent.h"
#include "agentx/client.h"
#endif

netsnmp_feature_child_of(agent_registry_all, libnetsnmpagent)

netsnmp_feature_child_of(unregister_mib_table_row, agent_registry_all)

/** @defgroup agent_lookup_cache Lookup cache, storing the registered OIDs.
 *     Maintain the cache used for locating sub-trees and OIDs.
 *   @ingroup agent_registry
 *
 * @{
 */

/**  Lookup cache - default size.*/
#define SUBTREE_DEFAULT_CACHE_SIZE 8
/**  Lookup cache - max acceptable size.*/
#define SUBTREE_MAX_CACHE_SIZE     32
int lookup_cache_size = 0; /*enabled later after registrations are loaded */

typedef struct lookup_cache_s {
   netsnmp_subtree *next;
   netsnmp_subtree *previous;
} lookup_cache;

typedef struct lookup_cache_context_s {
   char *context;
   struct lookup_cache_context_s *next;
   int thecachecount;
   int currentpos;
   lookup_cache cache[SUBTREE_MAX_CACHE_SIZE];
} lookup_cache_context;

static lookup_cache_context *thecontextcache = NULL;

/** Set the lookup cache size for optimized agent registration performance.
 * Note that it is only used by master agent - sub-agent doesn't need the cache.
 * The rough guide is that the cache size should be equal to the maximum
 * number of simultaneous managers you expect to talk to the agent (M) times 80%
 * (or so, he says randomly) the average number (N) of varbinds you
 * expect to receive in a given request for a manager.  ie, M times N.
 * Bigger does NOT necessarily mean better.  Certainly 16 should be an
 * upper limit.  32 is the hard coded limit.
 *
 * @param newsize set to the maximum size of a cache for a given
 * context.  Set to 0 to completely disable caching, or to -1 to set
 * to the default cache size (8), or to a number of your chosing.  The
 */
void
netsnmp_set_lookup_cache_size(int newsize) {
    if (newsize < 0)
        lookup_cache_size = SUBTREE_DEFAULT_CACHE_SIZE;
    else if (newsize < SUBTREE_MAX_CACHE_SIZE)
        lookup_cache_size = newsize;
    else
        lookup_cache_size = SUBTREE_MAX_CACHE_SIZE;
}

/** Retrieves the current value of the lookup cache size
 *  Should be called from master agent only - sub-agent doesn't need the cache.
 *
 *  @return the current lookup cache size
 */
int
netsnmp_get_lookup_cache_size(void) {
    return lookup_cache_size;
}

/** Returns lookup cache entry for the context of given name.
 *
 *  @param context Name of the context. Name is case sensitive.
 *
 *  @return the lookup cache context
 */
NETSNMP_STATIC_INLINE lookup_cache_context *
get_context_lookup_cache(const char *context) {
    lookup_cache_context *ptr;
    if (!context)
        context = "";

    for(ptr = thecontextcache; ptr; ptr = ptr->next) {
        if (strcmp(ptr->context, context) == 0)
            break;
    }
    if (!ptr) {
        if (netsnmp_subtree_find_first(context)) {
            ptr = SNMP_MALLOC_TYPEDEF(lookup_cache_context);
            ptr->next = thecontextcache;
            ptr->context = strdup(context);
            thecontextcache = ptr;
        } else {
            return NULL;
        }
    }
    return ptr;
}

/** Adds an entry to the Lookup Cache under specified context name.
 *
 *  @param context  Name of the context. Name is case sensitive.
 *
 *  @param next     Next subtree item.
 *
 *  @param previous Previous subtree item.
 */
NETSNMP_STATIC_INLINE void
lookup_cache_add(const char *context,
                 netsnmp_subtree *next, netsnmp_subtree *previous) {
    lookup_cache_context *cptr;

    if ((cptr = get_context_lookup_cache(context)) == NULL)
        return;

    if (cptr->thecachecount < lookup_cache_size)
        cptr->thecachecount++;

    cptr->cache[cptr->currentpos].next = next;
    cptr->cache[cptr->currentpos].previous = previous;

    if (++cptr->currentpos >= lookup_cache_size)
        cptr->currentpos = 0;
}

/** @private
 *  Replaces next and previous pointer in given Lookup Cache.
 *
 *  @param ptr      Lookup Cache pointer.
 *
 *  @param next     Next subtree item.
 *
 *  @param previous Previous subtree item.
 */
NETSNMP_STATIC_INLINE void
lookup_cache_replace(lookup_cache *ptr,
                     netsnmp_subtree *next, netsnmp_subtree *previous) {

    ptr->next = next;
    ptr->previous = previous;
}

/** Finds an entry in the Lookup Cache.
 *
 *  @param context  Case sensitive name of the context.
 *
 *  @param name     The OID we're searching for.
 *
 *  @param name_len Number of sub-ids (single integers) in the OID.
 *
 *  @param retcmp   Value set to snmp_oid_compare() call result.
 *                  The value, if set, is always nonnegative.
 *
 *  @return gives Lookup Cache entry, or NULL if not found.
 *
 *  @see snmp_oid_compare()
 */
NETSNMP_STATIC_INLINE lookup_cache *
lookup_cache_find(const char *context, const oid *name, size_t name_len,
                  int *retcmp) {
    lookup_cache_context *cptr;
    lookup_cache *ret = NULL;
    int cmp;
    int i;

    if ((cptr = get_context_lookup_cache(context)) == NULL)
        return NULL;

    for(i = 0; i < cptr->thecachecount && i < lookup_cache_size; i++) {
        if (cptr->cache[i].previous->start_a)
            cmp = snmp_oid_compare(name, name_len,
                                   cptr->cache[i].previous->start_a,
                                   cptr->cache[i].previous->start_len);
        else
            cmp = 1;
        if (cmp >= 0) {
            *retcmp = cmp;
            ret = &(cptr->cache[i]);
        }
    }
    return ret;
}

/** @private
 *  Clears cache count and position in Lookup Cache.
 */
NETSNMP_STATIC_INLINE void
invalidate_lookup_cache(const char *context) {
    lookup_cache_context *cptr;
    if ((cptr = get_context_lookup_cache(context)) != NULL) {
        cptr->thecachecount = 0;
        cptr->currentpos = 0;
    }
}

void
clear_lookup_cache(void) {

    lookup_cache_context *ptr = NULL, *next = NULL;

    ptr = thecontextcache;
    while (ptr) {
	next = ptr->next;
	SNMP_FREE(ptr->context);
	SNMP_FREE(ptr);
	ptr = next;
    }
    thecontextcache = NULL; /* !!! */
}

/**  @} */
/* End of Lookup cache code */

/** @defgroup agent_context_cache Context cache, storing the OIDs under their contexts.
 *     Maintain the cache used for locating sub-trees registered under different contexts.
 *   @ingroup agent_registry
 *
 * @{
 */
subtree_context_cache *context_subtrees = NULL;

/** Returns the top element of context subtrees cache.
 *  Use it if you wish to sweep through the cache elements.
 *  Note that the return may be NULL (cache may be empty).
 *
 *  @return pointer to topmost context subtree cache element.
 */
subtree_context_cache *
get_top_context_cache(void)
{
    return context_subtrees;
}

/** Finds the first subtree registered under given context.
 *
 *  @param context_name Text name of the context we're searching for.
 *
 *  @return pointer to the first subtree element, or NULL if not found.
 */
netsnmp_subtree *
netsnmp_subtree_find_first(const char *context_name)
{
    subtree_context_cache *ptr;

    if (!context_name) {
        context_name = "";
    }

    DEBUGMSGTL(("subtree", "looking for subtree for context: \"%s\"\n", 
		context_name));
    for (ptr = context_subtrees; ptr != NULL; ptr = ptr->next) {
        if (ptr->context_name != NULL && 
	    strcmp(ptr->context_name, context_name) == 0) {
            DEBUGMSGTL(("subtree", "found one for: \"%s\"\n", context_name));
            return ptr->first_subtree;
        }
    }
    DEBUGMSGTL(("subtree", "didn't find a subtree for context: \"%s\"\n", 
		context_name));
    return NULL;
}

/** Adds the subtree to Context Cache under given context name.
 *
 *  @param context_name Text name of the context we're adding.
 *
 *  @param new_tree The subtree to be added.
 *
 *  @return copy of the new_tree pointer, or NULL if cannot add.
 */
netsnmp_subtree *
add_subtree(netsnmp_subtree *new_tree, const char *context_name)
{
    subtree_context_cache *ptr = SNMP_MALLOC_TYPEDEF(subtree_context_cache);
    
    if (!context_name) {
        context_name = "";
    }

    if (!ptr) {
        return NULL;
    }
    
    DEBUGMSGTL(("subtree", "adding subtree for context: \"%s\"\n",	
		context_name));

    ptr->next = context_subtrees;
    ptr->first_subtree = new_tree;
    ptr->context_name = strdup(context_name);
    context_subtrees = ptr;

    return ptr->first_subtree;
}

void
netsnmp_remove_subtree(netsnmp_subtree *tree)
{
    subtree_context_cache *ptr;

    if (!tree->prev) {
        for (ptr = context_subtrees; ptr; ptr = ptr->next)
            if (ptr->first_subtree == tree)
                break;
        netsnmp_assert(ptr);
        if (ptr)
            ptr->first_subtree = tree->next;
    } else
        tree->prev->next = tree->next;

    if (tree->next)
        tree->next->prev = tree->prev;
}

/** Replaces first subtree registered under given context name.
 *  Overwrites a subtree pointer in Context Cache for the context name.
 *  The previous subtree pointer is lost. If there's no subtree
 *  under the supplied name, then a new cache item is created.
 *
 *  @param new_tree     The new subtree to be set.
 *
 *  @param context_name Text name of the context we're replacing.
 *                      It is case sensitive.
 *
 * @return copy of the new_tree pointer, or NULL on error.
 */
netsnmp_subtree *
netsnmp_subtree_replace_first(netsnmp_subtree *new_tree, 
			      const char *context_name)
{
    subtree_context_cache *ptr;
    if (!context_name) {
        context_name = "";
    }
    for (ptr = context_subtrees; ptr != NULL; ptr = ptr->next) {
        if (ptr->context_name != NULL &&
	    strcmp(ptr->context_name, context_name) == 0) {
            ptr->first_subtree = new_tree;
            return ptr->first_subtree;
        }
    }
    return add_subtree(new_tree, context_name);
}


void clear_subtree (netsnmp_subtree *sub);

/** Completely clears both the Context cache and the Lookup cache.
 */
void
clear_context(void) {

    subtree_context_cache *ptr = NULL, *next = NULL;
    netsnmp_subtree *t, *u;

    DEBUGMSGTL(("agent_registry", "clear context\n"));

    ptr = get_top_context_cache(); 
    while (ptr) {
	next = ptr->next;

	for (t = ptr->first_subtree; t; t = u) {
            u = t->next;
	    clear_subtree(t);
	}

        free(NETSNMP_REMOVE_CONST(char*, ptr->context_name));
        SNMP_FREE(ptr);

	ptr = next;
    }
    context_subtrees = NULL; /* !!! */
    clear_lookup_cache();
}

/**  @} */
/* End of Context cache code */

/** @defgroup agent_mib_subtree Maintaining MIB subtrees.
 *     Maintaining MIB nodes and subtrees.
 *   @ingroup agent_registry
 *
 * @{
 */

static void register_mib_detach_node(netsnmp_subtree *s);

/** Frees single subtree item.
 *  Deallocated memory for given netsnmp_subtree item, including
 *  Handle Registration structure stored inside this item.
 *  After calling this function, the pointer is invalid
 *  and should be set to NULL.
 *
 *  @param a The subtree item to dispose.
 */
void
netsnmp_subtree_free(netsnmp_subtree *a)
{
  if (a != NULL) {
    if (a->variables != NULL && netsnmp_oid_equals(a->name_a, a->namelen, 
					     a->start_a, a->start_len) == 0) {
      SNMP_FREE(a->variables);
    }
    SNMP_FREE(a->name_a);
    a->namelen = 0;
    SNMP_FREE(a->start_a);
    a->start_len = 0;
    SNMP_FREE(a->end_a);
    a->end_len = 0;
    SNMP_FREE(a->label_a);
    netsnmp_handler_registration_free(a->reginfo);
    a->reginfo = NULL;
    SNMP_FREE(a);
  }
}

/** Creates deep copy of a subtree item.
 *  Duplicates all properties stored in the structure, including
 *  Handle Registration structure stored inside the item.
 *
 *  @param a The subtree item to copy.
 *
 *  @return deep copy of the subtree item, or NULL on error.
 */
netsnmp_subtree *
netsnmp_subtree_deepcopy(netsnmp_subtree *a)
{
  netsnmp_subtree *b = (netsnmp_subtree *)calloc(1, sizeof(netsnmp_subtree));

  if (b != NULL) {
    memcpy(b, a, sizeof(netsnmp_subtree));
    b->name_a  = snmp_duplicate_objid(a->name_a,  a->namelen);
    b->start_a = snmp_duplicate_objid(a->start_a, a->start_len);
    b->end_a   = snmp_duplicate_objid(a->end_a,   a->end_len);
    b->label_a = strdup(a->label_a);
    
    if (b->name_a == NULL || b->start_a == NULL || 
	b->end_a  == NULL || b->label_a == NULL) {
      netsnmp_subtree_free(b);
      return NULL;
    }

    if (a->variables != NULL) {
      b->variables = (struct variable *)malloc(a->variables_len * 
					       a->variables_width);
      if (b->variables != NULL) {
	memcpy(b->variables, a->variables,a->variables_len*a->variables_width);
      } else {
	netsnmp_subtree_free(b);
	return NULL;
      }
    }

    if (a->reginfo != NULL) {
      b->reginfo = netsnmp_handler_registration_dup(a->reginfo);
      if (b->reginfo == NULL) {
	netsnmp_subtree_free(b);
	return NULL;
      }
    }
  }
  return b;
}

/** @private
 *  Replaces next subtree pointer in given subtree.
 */
NETSNMP_INLINE void
netsnmp_subtree_change_next(netsnmp_subtree *ptr, netsnmp_subtree *thenext)
{
    ptr->next = thenext;
    if (thenext)
        netsnmp_oid_compare_ll(ptr->start_a,
                               ptr->start_len,
                               thenext->start_a,
                               thenext->start_len,
                               &thenext->oid_off);
}

/** @private
 *  Replaces previous subtree pointer in given subtree.
 */
NETSNMP_INLINE void
netsnmp_subtree_change_prev(netsnmp_subtree *ptr, netsnmp_subtree *theprev)
{
    ptr->prev = theprev;
    if (theprev)
        netsnmp_oid_compare_ll(theprev->start_a,
                               theprev->start_len,
                               ptr->start_a,
                               ptr->start_len,
                               &ptr->oid_off);
}

netsnmp_feature_child_of(netsnmp_subtree_compare,netsnmp_unused)
#ifndef NETSNMP_FEATURE_REMOVE_NETSNMP_SUBTREE_COMPARE
/** Compares OIDs of given subtrees.
 *
 *  @param ap,bp Pointers to the subtrees to be compared.
 *
 *  @return OIDs lexicographical comparison result.
 *
 *  @see snmp_oid_compare()
 */
int
netsnmp_subtree_compare(const netsnmp_subtree *ap, const netsnmp_subtree *bp)
{
    return snmp_oid_compare(ap->name_a, ap->namelen, bp->name_a, bp->namelen);
}
#endif /* NETSNMP_FEATURE_REMOVE_NETSNMP_SUBTREE_COMPARE */

/** Joins the given subtree with the current tree.
 *  Trees are joined and the one supplied as parameter is freed.
 *
 *  @param root The subtree to be merged with current subtree.
 *              Do not use the pointer after joining - it may be invalid.
 */
void
netsnmp_subtree_join(netsnmp_subtree *root)
{
    netsnmp_subtree *s, *tmp, *c, *d;

    while (root != NULL) {
        s = root->next;
        while (s != NULL && root->reginfo == s->reginfo) {
            tmp = s->next;
            DEBUGMSGTL(("subtree", "root start "));
            DEBUGMSGOID(("subtree", root->start_a, root->start_len));
            DEBUGMSG(("subtree", " (original end "));
            DEBUGMSGOID(("subtree", root->end_a, root->end_len));
            DEBUGMSG(("subtree", ")\n"));
            DEBUGMSGTL(("subtree", "  JOINING to "));
            DEBUGMSGOID(("subtree", s->start_a, s->start_len));

	    SNMP_FREE(root->end_a);
	    root->end_a   = s->end_a;
            root->end_len = s->end_len;
	    s->end_a      = NULL;

            for (c = root; c != NULL; c = c->children) {
                netsnmp_subtree_change_next(c, s->next);
            }
            for (c = s; c != NULL; c = c->children) {
                netsnmp_subtree_change_prev(c, root);
            }
            DEBUGMSG(("subtree", " so new end "));
            DEBUGMSGOID(("subtree", root->end_a, root->end_len));
            DEBUGMSG(("subtree", "\n"));
            /*
             * Probably need to free children too?  
             */
            for (c = s->children; c != NULL; c = d) {
                d = c->children;
                netsnmp_subtree_free(c);
            }
            netsnmp_subtree_free(s);
            s = tmp;
        }
        root = root->next;
    }
}


/** Split the subtree into two at the specified point.
 *  Subtrees of the given OID and separated and formed into the
 *  returned subtree.
 *
 *  @param current The element at which splitting is started.
 *
 *  @param name The OID we'd like to split.
 *
 *  @param name_len Length of the OID.
 *
 *  @return head of the new (second) subtree.
 */
netsnmp_subtree *
netsnmp_subtree_split(netsnmp_subtree *current, oid name[], int name_len)
{
    struct variable *vp = NULL;
    netsnmp_subtree *new_sub, *ptr;
    int i = 0, rc = 0, rc2 = 0;
    size_t common_len = 0;
    char *cp;
    oid *tmp_a, *tmp_b;

    if (snmp_oid_compare(name, name_len, current->end_a, current->end_len)>0) {
	/* Split comes after the end of this subtree */
        return NULL;
    }

    new_sub = netsnmp_subtree_deepcopy(current);
    if (new_sub == NULL) {
        return NULL;
    }

    /*  Set up the point of division.  */
    tmp_a = snmp_duplicate_objid(name, name_len);
    if (tmp_a == NULL) {
	netsnmp_subtree_free(new_sub);
	return NULL;
    }
    tmp_b = snmp_duplicate_objid(name, name_len);
    if (tmp_b == NULL) {
	netsnmp_subtree_free(new_sub);
	SNMP_FREE(tmp_a);
	return NULL;
    }

    SNMP_FREE(current->end_a);
    current->end_a = tmp_a;
    current->end_len = name_len;
    if (new_sub->start_a != NULL) {
	SNMP_FREE(new_sub->start_a);
    }
    new_sub->start_a = tmp_b;
    new_sub->start_len = name_len;

    /*  Split the variables between the two new subtrees.  */
    i = current->variables_len;
    current->variables_len = 0;

    for (vp = current->variables; i > 0; i--) {
	/*  Note that the variable "name" field omits the prefix common to the
	    whole registration, hence the strange comparison here.  */

	rc = snmp_oid_compare(vp->name, vp->namelen,
			      name     + current->namelen, 
			      name_len - current->namelen);

        if (name_len - current->namelen > vp->namelen) {
            common_len = vp->namelen;
        } else {
            common_len = name_len - current->namelen;
        }

        rc2 = snmp_oid_compare(vp->name, common_len,
                               name + current->namelen, common_len);

        if (rc >= 0) {
            break;  /* All following variables belong to the second subtree */
	}

        current->variables_len++;
        if (rc2 < 0) {
            new_sub->variables_len--;
            cp = (char *) new_sub->variables;
            new_sub->variables = (struct variable *)(cp + 
						     new_sub->variables_width);
        }
        vp = (struct variable *) ((char *) vp + current->variables_width);
    }

    /* Delegated trees should retain their variables regardless */
    if (current->variables_len > 0 &&
        IS_DELEGATED((u_char) current->variables[0].type)) {
        new_sub->variables_len = 1;
        new_sub->variables = current->variables;
    }

    /* Propogate this split down through any children */
    if (current->children) {
        new_sub->children = netsnmp_subtree_split(current->children, 
						  name, name_len);
    }

    /* Retain the correct linking of the list */
    for (ptr = current; ptr != NULL; ptr = ptr->children) {
        netsnmp_subtree_change_next(ptr, new_sub);
    }
    for (ptr = new_sub; ptr != NULL; ptr = ptr->children) {
        netsnmp_subtree_change_prev(ptr, current);
    }
    for (ptr = new_sub->next; ptr != NULL; ptr=ptr->children) {
        netsnmp_subtree_change_prev(ptr, new_sub);
    }

    return new_sub;
}

/** Loads the subtree under given context name.
 *
 *  @param new_sub The subtree to be loaded into current subtree.
 *
 *  @param context_name Text name of the context we're searching for.
 *
 *  @return gives MIB_REGISTERED_OK on success, error code otherwise.
 */
int
netsnmp_subtree_load(netsnmp_subtree *new_sub, const char *context_name)
{
    netsnmp_subtree *tree1, *tree2;
    netsnmp_subtree *prev, *next;

    if (new_sub == NULL) {
        return MIB_REGISTERED_OK;       /* Degenerate case */
    }

    if (!netsnmp_subtree_find_first(context_name)) {
        static int inloop = 0;
        if (!inloop) {
            oid ccitt[1]           = { 0 };
            oid iso[1]             = { 1 };
            oid joint_ccitt_iso[1] = { 2 };
            inloop = 1;
            netsnmp_register_null_context(snmp_duplicate_objid(ccitt, 1), 1,
                                          context_name);
            netsnmp_register_null_context(snmp_duplicate_objid(iso, 1), 1,
                                          context_name);
            netsnmp_register_null_context(snmp_duplicate_objid(joint_ccitt_iso, 1),
                                          1, context_name);
            inloop = 0;
        }
    }

    /*  Find the subtree that contains the start of the new subtree (if
	any)...*/

    tree1 = netsnmp_subtree_find(new_sub->start_a, new_sub->start_len, 
				 NULL, context_name);

    /*  ... and the subtree that follows the new one (NULL implies this is the
	final region covered).  */

    if (tree1 == NULL) {
	tree2 = netsnmp_subtree_find_next(new_sub->start_a, new_sub->start_len,
					  NULL, context_name);
    } else {
	tree2 = tree1->next;
    }

    /*  Handle new subtrees that start in virgin territory.  */

    if (tree1 == NULL) {
        netsnmp_subtree *new2 = NULL;
	/*  Is there any overlap with later subtrees?  */
	if (tree2 && snmp_oid_compare(new_sub->end_a, new_sub->end_len,
				      tree2->start_a, tree2->start_len) > 0) {
	    new2 = netsnmp_subtree_split(new_sub, 
					 tree2->start_a, tree2->start_len);
	}

	/*  Link the new subtree (less any overlapping region) with the list of
	    existing registrations.  */

	if (tree2) {
            netsnmp_subtree_change_prev(new_sub, tree2->prev);
            netsnmp_subtree_change_prev(tree2, new_sub);
	} else {
            netsnmp_subtree_change_prev(new_sub,
                                        netsnmp_subtree_find_prev(new_sub->start_a,
                                                                  new_sub->start_len, NULL, context_name));

	    if (new_sub->prev) {
                netsnmp_subtree_change_next(new_sub->prev, new_sub);
	    } else {
		netsnmp_subtree_replace_first(new_sub, context_name);
	    }

            netsnmp_subtree_change_next(new_sub, tree2);

	    /* If there was any overlap, recurse to merge in the overlapping
	       region (including anything that may follow the overlap).  */
	    if (new2) {
		return netsnmp_subtree_load(new2, context_name);
	    }
	}
    } else {
	/*  If the new subtree starts *within* an existing registration
	    (rather than at the same point as it), then split the existing
	    subtree at this point.  */

	if (netsnmp_oid_equals(new_sub->start_a, new_sub->start_len, 
			     tree1->start_a,   tree1->start_len) != 0) {
	    tree1 = netsnmp_subtree_split(tree1, new_sub->start_a, 
					  new_sub->start_len);
	}

        if (tree1 == NULL) {
            return MIB_REGISTRATION_FAILED;
	}

	/*  Now consider the end of this existing subtree:
	    
	    If it matches the new subtree precisely,
	            simply merge the new one into the list of children

	    If it includes the whole of the new subtree,
		    split it at the appropriate point, and merge again
     
	    If the new subtree extends beyond this existing region,
	            split it, and recurse to merge the two parts.  */

	switch (snmp_oid_compare(new_sub->end_a, new_sub->end_len,
                                 tree1->end_a, tree1->end_len)) {

	case -1:
	    /*  Existing subtree contains new one.  */
	    netsnmp_subtree_split(tree1, new_sub->end_a, new_sub->end_len);
	    /* Fall Through */

	case  0:
	    /*  The two trees match precisely.  */

	    /*  Note: This is the only point where the original registration
	        OID ("name") is used.  */

	    prev = NULL;
	    next = tree1;
	
	    while (next && next->namelen > new_sub->namelen) {
		prev = next;
		next = next->children;
	    }

	    while (next && next->namelen == new_sub->namelen &&
		   next->priority < new_sub->priority ) {
		prev = next;
		next = next->children;
	    }
	
	    if (next && (next->namelen  == new_sub->namelen) &&
		(next->priority == new_sub->priority)) {
                if (new_sub->namelen != 1) {    /* ignore root OID dups */
                    size_t          out_len = 0;
                    size_t          buf_len = 0;
                    char           *buf = NULL;
                    int             buf_overflow = 0;

                    netsnmp_sprint_realloc_objid((u_char **) &buf, &buf_len, &out_len,
                                                 1, &buf_overflow,
                                                 new_sub->start_a,
                                                 new_sub->start_len);
                    snmp_log(LOG_ERR,
                             "duplicate registration: MIB modules %s and %s (oid %s%s).\n",
                             next->label_a, new_sub->label_a,
                             buf ? buf : "",
                             buf_overflow ? " [TRUNCATED]" : "");
                    free(buf);
                }
		return MIB_DUPLICATE_REGISTRATION;
	    }

	    if (prev) {
		prev->children    = new_sub;
		new_sub->children = next;
                netsnmp_subtree_change_prev(new_sub, prev->prev);
                netsnmp_subtree_change_next(new_sub, prev->next);
	    } else {
		new_sub->children = next;
                netsnmp_subtree_change_prev(new_sub, next->prev);
                netsnmp_subtree_change_next(new_sub, next->next);
	
		for (next = new_sub->next; next != NULL;next = next->children){
                    netsnmp_subtree_change_prev(next, new_sub);
		}

		for (prev = new_sub->prev; prev != NULL;prev = prev->children){
                    netsnmp_subtree_change_next(prev, new_sub);
		}
	    }
	    break;

	case  1:
	    /*  New subtree contains the existing one.  */
            {
                netsnmp_subtree *new2 =
                    netsnmp_subtree_split(new_sub, tree1->end_a,tree1->end_len);
                int res = netsnmp_subtree_load(new_sub, context_name);
                if (res != MIB_REGISTERED_OK) {
                    netsnmp_remove_subtree(new2);
                    netsnmp_subtree_free(new2);
                    return res;
                }
                return netsnmp_subtree_load(new2, context_name);
            }
        }
    }
    return 0;
}

/** Free the given subtree and all its children.
 *
 *  @param sub Subtree branch to be cleared and freed.
 *             After the call, this pointer is invalid
 *             and should be set to NULL.
 */
void
clear_subtree (netsnmp_subtree *sub) {

    netsnmp_subtree *c;
    
    if (sub == NULL)
	return;

    for(c = sub; c;) {
        sub = c;
        c = c->children;
        netsnmp_subtree_free(sub);
    }

}

netsnmp_subtree *
netsnmp_subtree_find_prev(const oid *name, size_t len, netsnmp_subtree *subtree,
			  const char *context_name)
{
    lookup_cache *lookup_cache = NULL;
    netsnmp_subtree *myptr = NULL, *previous = NULL;
    int cmp = 1;
    size_t ll_off = 0;

    if (subtree) {
        myptr = subtree;
    } else {
	/* look through everything */
        if (lookup_cache_size) {
            lookup_cache = lookup_cache_find(context_name, name, len, &cmp);
            if (lookup_cache) {
                myptr = lookup_cache->next;
                previous = lookup_cache->previous;
            }
            if (!myptr)
                myptr = netsnmp_subtree_find_first(context_name);
        } else {
            myptr = netsnmp_subtree_find_first(context_name);
        }
    }

    /*
     * this optimization causes a segfault on sf cf alpha-linux1.
     * ifdef out until someone figures out why and fixes it. xxx-rks 20051117
     */
#ifndef __alpha
#define WTEST_OPTIMIZATION 1
#endif
#ifdef WTEST_OPTIMIZATION
    DEBUGMSGTL(("wtest","oid in: "));
    DEBUGMSGOID(("wtest", name, len));
    DEBUGMSG(("wtest","\n"));
#endif
    for (; myptr != NULL; previous = myptr, myptr = myptr->next) {
#ifdef WTEST_OPTIMIZATION
        /* Compare the incoming oid with the linked list.  If we have
           results of previous compares, its faster to make sure the
           length we differed in the last check is greater than the
           length between this pointer and the last then we don't need
           to actually perform a comparison */
        DEBUGMSGTL(("wtest","oid cmp: "));
        DEBUGMSGOID(("wtest", myptr->start_a, myptr->start_len));
        DEBUGMSG(("wtest","  --- off = %lu, in off = %lu test = %d\n",
                  (unsigned long)myptr->oid_off, (unsigned long)ll_off,
                  !(ll_off && myptr->oid_off &&
                    myptr->oid_off > ll_off)));
        if (!(ll_off && myptr->oid_off && myptr->oid_off > ll_off) &&
            netsnmp_oid_compare_ll(name, len,
                                   myptr->start_a, myptr->start_len,
                                   &ll_off) < 0) {
#else
        if (snmp_oid_compare(name, len, myptr->start_a, myptr->start_len) < 0) {
#endif
            if (lookup_cache_size && previous && cmp) {
                if (lookup_cache) {
                    lookup_cache_replace(lookup_cache, myptr, previous);
                } else {
                    lookup_cache_add(context_name, myptr, previous);
                }
            }
            return previous;
        }
    }
    return previous;
}

netsnmp_subtree *
netsnmp_subtree_find_next(const oid *name, size_t len,
			  netsnmp_subtree *subtree, const char *context_name)
{
    netsnmp_subtree *myptr = NULL;

    myptr = netsnmp_subtree_find_prev(name, len, subtree, context_name);

    if (myptr != NULL) {
        myptr = myptr->next;
        while (myptr != NULL && (myptr->variables == NULL || 
				 myptr->variables_len == 0)) {
            myptr = myptr->next;
        }
        return myptr;
    } else if (subtree != NULL && snmp_oid_compare(name, len, 
				   subtree->start_a, subtree->start_len) < 0) {
        return subtree;
    } else {
        return NULL;
    }
}

netsnmp_subtree *
netsnmp_subtree_find(const oid *name, size_t len, netsnmp_subtree *subtree, 
		     const char *context_name)
{
    netsnmp_subtree *myptr;

    myptr = netsnmp_subtree_find_prev(name, len, subtree, context_name);
    if (myptr && myptr->end_a &&
        snmp_oid_compare(name, len, myptr->end_a, myptr->end_len)<0) {
        return myptr;
    }

    return NULL;
}

/**  @} */
/* End of Subtrees maintaining code */

/** @defgroup agent_mib_registering Registering and unregistering MIB subtrees.
 *     Adding and removing MIB nodes to the database under their contexts.
 *   @ingroup agent_registry
 *
 * @{
 */


/** Registers a MIB handler.
 *
 *  @param moduleName
 *  @param var
 *  @param varsize
 *  @param numvars
 *  @param  mibloc
 *  @param mibloclen
 *  @param priority
 *  @param range_subid
 *  @param range_ubound
 *  @param  ss
 *  @param context
 *  @param timeout
 *  @param flags
 *  @param reginfo Registration handler structure.
 *                 In a case of failure, it will be freed.
 *  @param perform_callback
 *
 *  @return gives MIB_REGISTERED_OK or MIB_* error code.
 *
 *  @see netsnmp_register_handler()
 *  @see register_agentx_list()
 *  @see netsnmp_handler_registration_free()
 */
int
netsnmp_register_mib(const char *moduleName,
                     struct variable *var,
                     size_t varsize,
                     size_t numvars,
                     oid * mibloc,
                     size_t mibloclen,
                     int priority,
                     int range_subid,
                     oid range_ubound,
                     netsnmp_session * ss,
                     const char *context,
                     int timeout,
                     int flags,
                     netsnmp_handler_registration *reginfo,
                     int perform_callback)
{
    netsnmp_subtree *subtree, *sub2;
    int             res;
    struct register_parameters reg_parms;
    int old_lookup_cache_val = netsnmp_get_lookup_cache_size();

    if (moduleName == NULL ||
        mibloc     == NULL) {
        /* Shouldn't happen ??? */
        netsnmp_handler_registration_free(reginfo);
        return MIB_REGISTRATION_FAILED;
    }
    subtree = (netsnmp_subtree *)calloc(1, sizeof(netsnmp_subtree));
    if (subtree == NULL) {
        netsnmp_handler_registration_free(reginfo);
        return MIB_REGISTRATION_FAILED;
    }

    DEBUGMSGTL(("register_mib", "registering \"%s\" at ", moduleName));
    DEBUGMSGOIDRANGE(("register_mib", mibloc, mibloclen, range_subid,
                      range_ubound));
    DEBUGMSG(("register_mib", " with context \"%s\"\n",
              SNMP_STRORNULL(context)));

    /*
     * verify that the passed context is equal to the context
     * in the reginfo.
     * (which begs the question, why do we have both? It appears that the
     *  reginfo item didn't appear til 5.2)
     */
    if( ((NULL == context) && (NULL != reginfo->contextName)) ||
        ((NULL != context) && (NULL == reginfo->contextName)) ||
        ( ((NULL != context) && (NULL != reginfo->contextName)) &&
          (0 != strcmp(context, reginfo->contextName))) ) {
        snmp_log(LOG_WARNING,"context passed during registration does not "
                 "equal the reginfo contextName! ('%s' != '%s')\n",
                 context, reginfo->contextName);
        netsnmp_assert(!"register context == reginfo->contextName"); /* always false */
    }

    /*  Create the new subtree node being registered.  */

    subtree->reginfo = reginfo;
    subtree->name_a  = snmp_duplicate_objid(mibloc, mibloclen);
    subtree->start_a = snmp_duplicate_objid(mibloc, mibloclen);
    subtree->end_a   = snmp_duplicate_objid(mibloc, mibloclen);
    subtree->label_a = strdup(moduleName);
    if (subtree->name_a == NULL || subtree->start_a == NULL || 
	subtree->end_a  == NULL || subtree->label_a == NULL) {
	netsnmp_subtree_free(subtree); /* also frees reginfo */
	return MIB_REGISTRATION_FAILED;
    }
    subtree->namelen   = (u_char)mibloclen;
    subtree->start_len = (u_char)mibloclen;
    subtree->end_len   = (u_char)mibloclen;
    subtree->end_a[mibloclen - 1]++;

    if (var != NULL) {
	subtree->variables = (struct variable *)malloc(varsize*numvars);
	if (subtree->variables == NULL) {
	    netsnmp_subtree_free(subtree); /* also frees reginfo */
	    return MIB_REGISTRATION_FAILED;
	}
	memcpy(subtree->variables, var, numvars*varsize);
	subtree->variables_len = numvars;
	subtree->variables_width = varsize;
    }
    subtree->priority = priority;
    subtree->timeout = timeout;
    subtree->range_subid = range_subid;
    subtree->range_ubound = range_ubound;
    subtree->session = ss;
    subtree->flags = (u_char)flags;    /*  used to identify instance oids  */
    subtree->flags |= SUBTREE_ATTACHED;
    subtree->global_cacheid = reginfo->global_cacheid;

    netsnmp_set_lookup_cache_size(0);
    res = netsnmp_subtree_load(subtree, context);

    /*  If registering a range, use the first subtree as a template for the
	rest of the range.  */

    if (res == MIB_REGISTERED_OK && range_subid != 0) {
        int i;
	for (i = mibloc[range_subid - 1] + 1; i <= (int)range_ubound; i++) {
	    sub2 = netsnmp_subtree_deepcopy(subtree);

	    if (sub2 == NULL) {
                unregister_mib_context(mibloc, mibloclen, priority,
                                       range_subid, range_ubound, context);
                netsnmp_set_lookup_cache_size(old_lookup_cache_val);
                invalidate_lookup_cache(context);
                return MIB_REGISTRATION_FAILED;
            }

            sub2->name_a[range_subid - 1]  = i;
            sub2->start_a[range_subid - 1] = i;
            sub2->end_a[range_subid - 1]   = i;     /* XXX - ???? */
            if (range_subid == (int)mibloclen) {
                ++sub2->end_a[range_subid - 1];
            }
            sub2->flags |= SUBTREE_ATTACHED;
            sub2->global_cacheid = reginfo->global_cacheid;
            /* FRQ This is essential for requests to succeed! */
            sub2->reginfo->rootoid[range_subid - 1]  = i;

            res = netsnmp_subtree_load(sub2, context);
            if (res != MIB_REGISTERED_OK) {
                unregister_mib_context(mibloc, mibloclen, priority,
                                       range_subid, range_ubound, context);
                netsnmp_remove_subtree(sub2);
		netsnmp_subtree_free(sub2);
                netsnmp_set_lookup_cache_size(old_lookup_cache_val);
                invalidate_lookup_cache(context);
                return res;
            }
        }
    } else if (res == MIB_DUPLICATE_REGISTRATION ||
               res == MIB_REGISTRATION_FAILED) {
        netsnmp_set_lookup_cache_size(old_lookup_cache_val);
        invalidate_lookup_cache(context);
        netsnmp_subtree_free(subtree);
        return res;
    }

    /*
     * mark the MIB as detached, if there's no master agent present as of now 
     */
    if (netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, 
			       NETSNMP_DS_AGENT_ROLE) != MASTER_AGENT) {
        extern struct snmp_session *main_session;
        if (main_session == NULL) {
            register_mib_detach_node(subtree);
	}
    }

    if (res == MIB_REGISTERED_OK && perform_callback) {
        memset(&reg_parms, 0x0, sizeof(reg_parms));
        reg_parms.name = mibloc;
        reg_parms.namelen = mibloclen;
        reg_parms.priority = priority;
        reg_parms.range_subid = range_subid;
        reg_parms.range_ubound = range_ubound;
        reg_parms.timeout = timeout;
        reg_parms.flags = (u_char) flags;
        reg_parms.contextName = context;
        reg_parms.session = ss;
        reg_parms.reginfo = reginfo;
        reg_parms.contextName = context;
        snmp_call_callbacks(SNMP_CALLBACK_APPLICATION,
                            SNMPD_CALLBACK_REGISTER_OID, &reg_parms);
    }

    netsnmp_set_lookup_cache_size(old_lookup_cache_val);
    invalidate_lookup_cache(context);
    return res;
}

/** @private
 *  Reattach a particular node.  
 */
static void
register_mib_reattach_node(netsnmp_subtree *s)
{
    if ((s != NULL) && (s->namelen > 1) && !(s->flags & SUBTREE_ATTACHED)) {
        struct register_parameters reg_parms;
        /*
         * only do registrations that are not the top level nodes 
         */
        memset(&reg_parms, 0x0, sizeof(reg_parms));

        /*
         * XXX: do this better 
         */
        reg_parms.name = s->name_a;
        reg_parms.namelen = s->namelen;
        reg_parms.priority = s->priority;
        reg_parms.range_subid = s->range_subid;
        reg_parms.range_ubound = s->range_ubound;
        reg_parms.timeout = s->timeout;
        reg_parms.flags = s->flags;
        reg_parms.session = s->session;
        reg_parms.reginfo = s->reginfo;
        /* XXX: missing in subtree: reg_parms.contextName = s->context; */
        if ((NULL != s->reginfo) && (NULL != s->reginfo->contextName))
            reg_parms.contextName = s->reginfo->contextName;
        snmp_call_callbacks(SNMP_CALLBACK_APPLICATION,
                            SNMPD_CALLBACK_REGISTER_OID, &reg_parms);
        s->flags |= SUBTREE_ATTACHED;
    }
}

/** Call callbacks to reattach all our nodes.  
 */
void
register_mib_reattach(void)
{
    netsnmp_subtree *s, *t;
    subtree_context_cache *ptr;

    for (ptr = context_subtrees; ptr; ptr = ptr->next) {
        for (s = ptr->first_subtree; s != NULL; s = s->next) {
            register_mib_reattach_node(s);
            for (t = s->children; t != NULL; t = t->children) {
                register_mib_reattach_node(t);
            }
        }
    }
}

/** @private
 *  Mark a node as detached.
 *
 *  @param s The note to be marked
 */
static void
register_mib_detach_node(netsnmp_subtree *s)
{
    if (s != NULL) {
        s->flags = s->flags & ~SUBTREE_ATTACHED;
    }
}

/** Mark all our registered OIDs as detached.
 *  This is only really useful for subagent protocols, when
 *  a connection is lost or the subagent is being shut down.  
 */
void
register_mib_detach(void)
{
    netsnmp_subtree *s, *t;
    subtree_context_cache *ptr;
    for (ptr = context_subtrees; ptr; ptr = ptr->next) {
        for (s = ptr->first_subtree; s != NULL; s = s->next) {
            register_mib_detach_node(s);
            for (t = s->children; t != NULL; t = t->children) {
                register_mib_detach_node(t);
            }
        }
    }
}

/** Register a new module into the MIB database, with all possible custom options
 *
 *  @param  moduleName Text name of the module.
 *                     The given name will be used to identify the module
 *                     inside the agent.
 *
 *  @param  var        Array of variables to be registered in the module.
 *
 *  @param  varsize    Size of a single variable in var array.
 *                     The size is normally equal to sizeof(struct variable),
 *                     but if we wish to use shorter (or longer) OIDs, then we
 *                     could use different variant of the variable structure.
 *
 *  @param  numvars    Number of variables in the var array.
 *                     This is how many variables the function will try to register.
 *
 *  @param  mibloc     Base OID of the module.
 *                     All OIDs in var array should be sub-oids of the base OID.
 *
 *  @param  mibloclen  Length of the base OID.
 *                     Number of integers making up the base OID.
 *
 *  @param  priority   Registration priority.
 *                     Used to achieve a desired configuration when different
 *                     sessions register identical or overlapping regions.
 *                     Primarily used with AgentX subagent registrations.
 *
 *  @param range_subid If non-zero, the module is registered against a range
 *                     of OIDs, with this parameter identifying the relevant
 *                     subidentifier - see RFC 2741 for details.
 *                     Typically used to register a single row of a table.
 *                     If zero, then register the module against the full OID subtree.
 *
 *  @param range_ubound The end of the range being registered (see RFC 2741)
 *                     If range_subid is zero, then this parameter is ignored.
 *
 *  @param ss 
 *  @param context
 *  @param timeout 
 *  @param flags 
 *
 *  @return gives SNMPERR_SUCCESS or SNMPERR_* error code.
 *
 *  @see register_mib()
 *  @see register_mib_priority()
 *  @see register_mib_range()
 *  @see unregister_mib()
 */
int
register_mib_context(const char *moduleName,
                     struct variable *var,
                     size_t varsize,
                     size_t numvars,
                     const oid * mibloc,
                     size_t mibloclen,
                     int priority,
                     int range_subid,
                     oid range_ubound,
                     netsnmp_session * ss,
                     const char *context, int timeout, int flags)
{
    return netsnmp_register_old_api(moduleName, var, varsize, numvars,
                                    mibloc, mibloclen, priority,
                                    range_subid, range_ubound, ss, context,
                                    timeout, flags);
}

/** Register a new module into the MIB database, as being responsible
 *   for a range of OIDs (typically a single row of a table).
 *
 *  @param  moduleName Text name of the module.
 *                     The given name will be used to identify the module
 *                     inside the agent.
 *
 *  @param  var        Array of variables to be registered in the module.
 *
 *  @param  varsize    Size of a single variable in var array.
 *                     The size is normally equal to sizeof(struct variable),
 *                     but if we wish to use shorter (or longer) OIDs, then we
 *                     could use different variant of the variable structure.
 *
 *  @param  numvars    Number of variables in the var array.
 *                     This is how many variables the function will try to register.
 *
 *  @param  mibloc     Base OID of the module.
 *                     All OIDs in var array should be sub-oids of the base OID.
 *
 *  @param  mibloclen  Length of the base OID.
 *                     Number of integers making up the base OID.
 *
 *  @param  priority   Registration priority.
 *                     Used to achieve a desired configuration when different
 *                     sessions register identical or overlapping regions.
 *                     Primarily used with AgentX subagent registrations.
 *
 *  @param range_subid If non-zero, the module is registered against a range
 *                     of OIDs, with this parameter identifying the relevant
 *                     subidentifier - see RFC 2741 for details.
 *                     Typically used to register a single row of a table.
 *                     If zero, then register the module against the full OID subtree.
 *
 *  @param range_ubound The end of the range being registered (see RFC 2741)
 *                     If range_subid is zero, then this parameter is ignored.
 *
 *  @param ss 
 *
 *  @return gives SNMPERR_SUCCESS or SNMPERR_* error code.
 *
 *  @see register_mib()
 *  @see register_mib_priority()
 *  @see register_mib_context()
 *  @see unregister_mib()
 */
int
register_mib_range(const char *moduleName,
                   struct variable *var,
                   size_t varsize,
                   size_t numvars,
                   const oid * mibloc,
                   size_t mibloclen,
                   int priority,
                   int range_subid, oid range_ubound, netsnmp_session * ss)
{
    return register_mib_context(moduleName, var, varsize, numvars,
                                mibloc, mibloclen, priority,
                                range_subid, range_ubound, ss, "", -1, 0);
}

/** Register a new module into the MIB database, with a non-default priority
 *
 *  @param  moduleName Text name of the module.
 *                     The given name will be used to identify the module
 *                     inside the agent.
 *
 *  @param  var        Array of variables to be registered in the module.
 *
 *  @param  varsize    Size of a single variable in var array.
 *                     The size is normally equal to sizeof(struct variable),
 *                     but if we wish to use shorter (or longer) OIDs, then we
 *                     could use different variant of the variable structure.
 *
 *  @param  numvars    Number of variables in the var array.
 *                     This is how many variables the function will try to register.
 *
 *  @param  mibloc     Base OID of the module.
 *                     All OIDs in var array should be sub-oids of the base OID.
 *
 *  @param  mibloclen  Length of the base OID.
 *                     Number of integers making up the base OID.
 *
 *  @param  priority   Registration priority.
 *                     Used to achieve a desired configuration when different
 *                     sessions register identical or overlapping regions.
 *                     Primarily used with AgentX subagent registrations.
 *
 *  @return gives SNMPERR_SUCCESS or SNMPERR_* error code.
 *
 *  @see register_mib()
 *  @see register_mib_range()
 *  @see register_mib_context()
 *  @see unregister_mib()
 */
int
register_mib_priority(const char *moduleName,
                      struct variable *var,
                      size_t varsize,
                      size_t numvars,
                      const oid * mibloc, size_t mibloclen, int priority)
{
    return register_mib_range(moduleName, var, varsize, numvars,
                              mibloc, mibloclen, priority, 0, 0, NULL);
}

/** Register a new module into the MIB database, using default priority and context
 *
 *  @param  moduleName Text name of the module.
 *                     The given name will be used to identify the module
 *                     inside the agent.
 *
 *  @param  var        Array of variables to be registered in the module.
 *
 *  @param  varsize    Size of a single variable in var array.
 *                     The size is normally equal to sizeof(struct variable),
 *                     but if we wish to use shorter (or longer) OIDs, then we
 *                     could use different variant of the variable structure.
 *
 *  @param  numvars    Number of variables in the var array.
 *                     This is how many variables the function will try to register.
 *
 *  @param  mibloc     Base OID of the module.
 *                     All OIDs in var array should be sub-oids of the base OID.
 *
 *  @param  mibloclen  Length of the base OID.
 *                     Number of integers making up the base OID.
 *
 *  @return gives SNMPERR_SUCCESS or SNMPERR_* error code.
 *
 *  @see register_mib_priority()
 *  @see register_mib_range()
 *  @see register_mib_context()
 *  @see unregister_mib()
 */
int
register_mib(const char *moduleName,
             struct variable *var,
             size_t varsize,
             size_t numvars, const oid * mibloc, size_t mibloclen)
{
    return register_mib_priority(moduleName, var, varsize, numvars,
                                 mibloc, mibloclen, DEFAULT_MIB_PRIORITY);
}

/** @private
 *  Unloads a subtree from MIB tree.
 *
 *  @param  sub     The sub-tree which is being removed.
 *
 *  @param  prev    Previous entry, before the unloaded one.
 *
 *  @param  context Name of the context which is being removed.
 *
 *  @see unregister_mib_context()
 */
void
netsnmp_subtree_unload(netsnmp_subtree *sub, netsnmp_subtree *prev, const char *context)
{
    netsnmp_subtree *ptr;

    DEBUGMSGTL(("register_mib", "unload("));
    if (sub != NULL) {
        DEBUGMSGOID(("register_mib", sub->start_a, sub->start_len));
    } else {
        DEBUGMSG(("register_mib", "[NIL]"));
        return;
    }
    DEBUGMSG(("register_mib", ", "));
    if (prev != NULL) {
        DEBUGMSGOID(("register_mib", prev->start_a, prev->start_len));
    } else {
        DEBUGMSG(("register_mib", "[NIL]"));
    }
    DEBUGMSG(("register_mib", ")\n"));

    if (prev != NULL) {         /* non-leading entries are easy */
        prev->children = sub->children;
        invalidate_lookup_cache(context);
        return;
    }
    /*
     * otherwise, we need to amend our neighbours as well 
     */

    if (sub->children == NULL) {        /* just remove this node completely */
        for (ptr = sub->prev; ptr; ptr = ptr->children) {
            netsnmp_subtree_change_next(ptr, sub->next);
        }
        for (ptr = sub->next; ptr; ptr = ptr->children) {
            netsnmp_subtree_change_prev(ptr, sub->prev);
        }

	if (sub->prev == NULL) {
	    netsnmp_subtree_replace_first(sub->next, context);
	}

    } else {
        for (ptr = sub->prev; ptr; ptr = ptr->children)
            netsnmp_subtree_change_next(ptr, sub->children);
        for (ptr = sub->next; ptr; ptr = ptr->children)
            netsnmp_subtree_change_prev(ptr, sub->children);

	if (sub->prev == NULL) {
	    netsnmp_subtree_replace_first(sub->children, context);
	}
    }
    invalidate_lookup_cache(context);
}

/**
 * Unregisters a module registered against a given OID (or range) in a specified context. 
 * Typically used when a module has multiple contexts defined.
 * The parameters priority, range_subid, range_ubound and context
 * should match those used to register the module originally.
 *
 * @param name  the specific OID to unregister if it conatins the associated
 *              context.
 *
 * @param len   the length of the OID, use  OID_LENGTH macro.
 *
 * @param priority  a value between 1 and 255, used to achieve a desired
 *                  configuration when different sessions register identical or
 *                  overlapping regions.  Subagents with no particular
 *                  knowledge of priority should register with the default
 *                  value of 127.
 *
 * @param range_subid  permits specifying a range in place of one of a subtree
 *                     sub-identifiers.  When this value is zero, no range is
 *                     being specified.
 *
 * @param range_ubound  the upper bound of a sub-identifier's range.
 *                      This field is present only if range_subid is not 0.
 *
 * @param context  a context name that has been created
 *
 * @return gives MIB_UNREGISTERED_OK or MIB_* error code.
 * 
 * @see unregister_mib()
 * @see unregister_mib_priority()
 * @see unregister_mib_range()
 */
int
unregister_mib_context(oid * name, size_t len, int priority,
                       int range_subid, oid range_ubound,
                       const char *context)
{
    netsnmp_subtree *list, *myptr = NULL;
    netsnmp_subtree *prev, *child, *next; /* loop through children */
    struct register_parameters reg_parms;
    int old_lookup_cache_val = netsnmp_get_lookup_cache_size();
    int unregistering = 1;
    int orig_subid_val = -1;

    netsnmp_set_lookup_cache_size(0);

    if ((range_subid > 0) &&  ((size_t)range_subid <= len))
        orig_subid_val = name[range_subid-1];

    while(unregistering){
        DEBUGMSGTL(("register_mib", "unregistering "));
        DEBUGMSGOIDRANGE(("register_mib", name, len, range_subid, range_ubound));
        DEBUGMSG(("register_mib", "\n"));

        list = netsnmp_subtree_find(name, len, netsnmp_subtree_find_first(context),
                    context);
        if (list == NULL) {
            return MIB_NO_SUCH_REGISTRATION;
        }

        for (child = list, prev = NULL; child != NULL;
            prev = child, child = child->children) {
            if (netsnmp_oid_equals(child->name_a, child->namelen, name, len) == 0 &&
                child->priority == priority) {
                break;              /* found it */
             }
        }

        if (child == NULL) {
            return MIB_NO_SUCH_REGISTRATION;
        }

        netsnmp_subtree_unload(child, prev, context);
        myptr = child;              /* remember this for later */

        /*
        *  Now handle any occurances in the following subtrees,
        *      as a result of splitting this range.  Due to the
        *      nature of the way such splits work, the first
        *      subtree 'slice' that doesn't refer to the given
        *      name marks the end of the original region.
        *
        *  This should also serve to register ranges.
        */

        for (list = myptr->next; list != NULL; list = next) {
            next = list->next; /* list gets freed sometimes; cache next */
            for (child = list, prev = NULL; child != NULL;
                prev = child, child = child->children) {
                if ((netsnmp_oid_equals(child->name_a, child->namelen,
                    name, len) == 0) &&
            (child->priority == priority)) {
                    netsnmp_subtree_unload(child, prev, context);
                    netsnmp_subtree_free(child);
                    break;
                }
            }
            if (child == NULL)      /* Didn't find the given name */
                break;
        }

        /* Maybe we are in a range... */
        if (orig_subid_val != -1){
            if (++name[range_subid-1] >= orig_subid_val+range_ubound)
                {
                unregistering=0;
                name[range_subid-1] = orig_subid_val;
                }
        }
        else {
            unregistering=0;
        }
    }

    memset(&reg_parms, 0x0, sizeof(reg_parms));
    reg_parms.name = name;
    reg_parms.namelen = len;
    reg_parms.priority = priority;
    reg_parms.range_subid = range_subid;
    reg_parms.range_ubound = range_ubound;
    reg_parms.flags = 0x00;     /*  this is okay I think  */
    reg_parms.contextName = context;
    snmp_call_callbacks(SNMP_CALLBACK_APPLICATION,
                        SNMPD_CALLBACK_UNREGISTER_OID, &reg_parms);

    netsnmp_subtree_free(myptr);
    netsnmp_set_lookup_cache_size(old_lookup_cache_val);
    invalidate_lookup_cache(context);
    return MIB_UNREGISTERED_OK;
}

#ifndef NETSNMP_FEATURE_REMOVE_UNREGISTER_MIB_TABLE_ROW
int
netsnmp_unregister_mib_table_row(oid * name, size_t len, int priority,
                                 int var_subid, oid range_ubound,
                                 const char *context)
{
    netsnmp_subtree *list, *myptr, *futureptr;
    netsnmp_subtree *prev, *child;       /* loop through children */
    struct register_parameters reg_parms;
    oid             range_lbound = name[var_subid - 1];

    DEBUGMSGTL(("register_mib", "unregistering "));
    DEBUGMSGOIDRANGE(("register_mib", name, len, var_subid, range_ubound));
    DEBUGMSG(("register_mib", "\n"));

    for (; name[var_subid - 1] <= range_ubound; name[var_subid - 1]++) {
        list = netsnmp_subtree_find(name, len, 
				netsnmp_subtree_find_first(context), context);

        if (list == NULL) {
            continue;
        }

        for (child = list, prev = NULL; child != NULL;
             prev = child, child = child->children) {

            if (netsnmp_oid_equals(child->name_a, child->namelen, 
				 name, len) == 0 && 
		(child->priority == priority)) {
                break;          /* found it */
            }
        }

        if (child == NULL) {
            continue;
        }

        netsnmp_subtree_unload(child, prev, context);
        myptr = child;          /* remember this for later */

        for (list = myptr->next; list != NULL; list = futureptr) {
            /* remember the next spot in the list in case we free this node */
            futureptr = list->next;

            /* check each child */
            for (child = list, prev = NULL; child != NULL;
                 prev = child, child = child->children) {

                if (netsnmp_oid_equals(child->name_a, child->namelen, 
				      name, len) == 0 &&
                    (child->priority == priority)) {
                    netsnmp_subtree_unload(child, prev, context);
                    netsnmp_subtree_free(child);
                    break;
                }
            }

            /* XXX: wjh: not sure why we're bailing here */
            if (child == NULL) {        /* Didn't find the given name */
                break;
            }
        }
        netsnmp_subtree_free(myptr);
    }

    name[var_subid - 1] = range_lbound;
    memset(&reg_parms, 0x0, sizeof(reg_parms));
    reg_parms.name = name;
    reg_parms.namelen = len;
    reg_parms.priority = priority;
    reg_parms.range_subid = var_subid;
    reg_parms.range_ubound = range_ubound;
    reg_parms.flags = 0x00;     /*  this is okay I think  */
    reg_parms.contextName = context;
    snmp_call_callbacks(SNMP_CALLBACK_APPLICATION,
                        SNMPD_CALLBACK_UNREGISTER_OID, &reg_parms);

    return 0;
}
#endif /* NETSNMP_FEATURE_REMOVE_UNREGISTER_MIB_TABLE_ROW */

/**
 * Unregisters a module registered against a given OID (or range) in the default context. 
 * Typically used when a module has multiple contexts defined.
 * The parameters priority, range_subid, and range_ubound should
 * match those used to register the module originally.
 *
 * @param name  the specific OID to unregister if it conatins the associated
 *              context.
 *
 * @param len   the length of the OID, use  OID_LENGTH macro.
 *
 * @param priority  a value between 1 and 255, used to achieve a desired
 *                  configuration when different sessions register identical or
 *                  overlapping regions.  Subagents with no particular
 *                  knowledge of priority should register with the default
 *                  value of 127.
 *
 * @param range_subid  permits specifying a range in place of one of a subtree
 *                     sub-identifiers.  When this value is zero, no range is
 *                     being specified.
 *
 * @param range_ubound  the upper bound of a sub-identifier's range.
 *                      This field is present only if range_subid is not 0.
 *
 * @return gives MIB_UNREGISTERED_OK or MIB_* error code.
 * 
 * @see unregister_mib()
 * @see unregister_mib_priority()
 * @see unregister_mib_context()
 */
int
unregister_mib_range(oid * name, size_t len, int priority,
                     int range_subid, oid range_ubound)
{
    return unregister_mib_context(name, len, priority, range_subid,
                                  range_ubound, "");
}

/**
 * Unregisters a module registered against a given OID at the specified priority.
 * The priority parameter should match that used to register the module originally.
 *
 * @param name  the specific OID to unregister if it conatins the associated
 *              context.
 *
 * @param len   the length of the OID, use  OID_LENGTH macro.
 *
 * @param priority  a value between 1 and 255, used to achieve a desired
 *                  configuration when different sessions register identical or
 *                  overlapping regions.  Subagents with no particular
 *                  knowledge of priority should register with the default
 *                  value of 127.
 *
 * @return gives MIB_UNREGISTERED_OK or MIB_* error code.
 * 
 * @see unregister_mib()
 * @see unregister_mib_range()
 * @see unregister_mib_context()
 */
int
unregister_mib_priority(oid * name, size_t len, int priority)
{
    return unregister_mib_range(name, len, priority, 0, 0);
}

/**
 * Unregisters a module registered against a given OID at the default priority.
 *
 * @param name  the specific OID to unregister if it conatins the associated
 *              context.
 *
 * @param len   the length of the OID, use  OID_LENGTH macro.
 *
 * @return gives MIB_UNREGISTERED_OK or MIB_* error code.
 * 
 * @see unregister_mib_priority()
 * @see unregister_mib_context()
 * @see unregister_mib_range()
 * @see unregister_agentx_list()
 */
int
unregister_mib(oid * name, size_t len)
{
    return unregister_mib_priority(name, len, DEFAULT_MIB_PRIORITY);
}

/** Unregisters subtree of OIDs bounded to given session.
 *
 *  @param ss Session which OIDs will be removed from tree.
 *
 *  @see unregister_mib()
 *  @see unregister_agentx_list()
 */
void
unregister_mibs_by_session(netsnmp_session * ss)
{
    netsnmp_subtree *list, *list2;
    netsnmp_subtree *child, *prev, *next_child;
    struct register_parameters rp;
    subtree_context_cache *contextptr;

    DEBUGMSGTL(("register_mib", "unregister_mibs_by_session(%p) ctxt \"%s\"\n",
		ss, (ss && ss->contextName) ? ss->contextName : "[NIL]"));

    for (contextptr = get_top_context_cache(); contextptr != NULL;
         contextptr = contextptr->next) {
        for (list = contextptr->first_subtree; list != NULL; list = list2) {
            list2 = list->next;

            for (child = list, prev = NULL; child != NULL; child = next_child){
                next_child = child->children;

                if (((!ss || ss->flags & SNMP_FLAGS_SUBSESSION) &&
		     child->session == ss) ||
                    (!(!ss || ss->flags & SNMP_FLAGS_SUBSESSION) && child->session &&
                     child->session->subsession == ss)) {

                    memset(&rp,0x0,sizeof(rp));
                    rp.name = child->name_a;
		    child->name_a = NULL;
                    rp.namelen = child->namelen;
                    rp.priority = child->priority;
                    rp.range_subid = child->range_subid;
                    rp.range_ubound = child->range_ubound;
                    rp.timeout = child->timeout;
                    rp.flags = child->flags;
                    if ((NULL != child->reginfo) &&
                        (NULL != child->reginfo->contextName))
                        rp.contextName = child->reginfo->contextName;

                    if (child->reginfo != NULL) {
                        /*
                         * Don't let's free the session pointer just yet!  
                         */
                        child->reginfo->handler->myvoid = NULL;
                        netsnmp_handler_registration_free(child->reginfo);
			child->reginfo = NULL;
                    }

                    netsnmp_subtree_unload(child, prev, contextptr->context_name);
                    netsnmp_subtree_free(child);

                    snmp_call_callbacks(SNMP_CALLBACK_APPLICATION,
                                        SNMPD_CALLBACK_UNREGISTER_OID, &rp);
		    SNMP_FREE(rp.name);
                } else {
                    prev = child;
                }
            }
        }
        netsnmp_subtree_join(contextptr->first_subtree);
    }
}

/** Determines if given PDU is allowed to see (or update) a given OID.
 *
 * @param name    The OID to check access for.
 *                On return, this parameter holds the OID actually matched
 *
 * @param namelen Number of sub-identifiers in the OID.
 *                On return, this parameter holds the length of the matched OID
 *
 * @param pdu     PDU requesting access to the OID.
 *
 * @param type    ANS.1 type of the value at given OID.
 *                (Used for catching SNMPv1 requests for SMIv2-only objects)
 *
 * @return gives VACM_SUCCESS if the OID is in the PDU, otherwise error code.
 */
int
in_a_view(oid *name, size_t *namelen, netsnmp_pdu *pdu, int type)
{
    struct view_parameters view_parms;

    if (pdu->flags & UCD_MSG_FLAG_ALWAYS_IN_VIEW) {
	/* Enable bypassing of view-based access control */
        return VACM_SUCCESS;
    }

    /*
     * check for v1 and counter64s, since snmpv1 doesn't support it 
     */
#ifndef NETSNMP_DISABLE_SNMPV1
    if (pdu->version == SNMP_VERSION_1 && type == ASN_COUNTER64) {
        return VACM_NOTINVIEW;
    }
#endif

    view_parms.pdu = pdu;
    view_parms.name = name;
    if (namelen != NULL) {
        view_parms.namelen = *namelen;
    } else {
        view_parms.namelen = 0;
    }
    view_parms.errorcode = 0;
    view_parms.check_subtree = 0;

    switch (pdu->version) {
#ifndef NETSNMP_DISABLE_SNMPV1
    case SNMP_VERSION_1:
#endif
#ifndef NETSNMP_DISABLE_SNMPV2C
    case SNMP_VERSION_2c:
#endif
    case SNMP_VERSION_3:
        snmp_call_callbacks(SNMP_CALLBACK_APPLICATION,
                            SNMPD_CALLBACK_ACM_CHECK, &view_parms);
        return view_parms.errorcode;
    }
    return VACM_NOSECNAME;
}

/** Determines if the given PDU request could potentially succeed.
 *  (Preliminary, OID-independent validation)
 *
 * @param pdu     PDU requesting access
 *
 * @return gives VACM_SUCCESS   if the entire MIB tree is accessible
 *               VACM_NOTINVIEW if the entire MIB tree is inaccessible
 *               VACM_SUBTREE_UNKNOWN if some portions are accessible
 *               other codes may returned on error
 */
int
check_access(netsnmp_pdu *pdu)
{                               /* IN - pdu being checked */
    struct view_parameters view_parms;
    view_parms.pdu = pdu;
    view_parms.name = NULL;
    view_parms.namelen = 0;
    view_parms.errorcode = 0;
    view_parms.check_subtree = 0;

    if (pdu->flags & UCD_MSG_FLAG_ALWAYS_IN_VIEW) {
	/* Enable bypassing of view-based access control */
        return 0;
    }

    switch (pdu->version) {
#ifndef NETSNMP_DISABLE_SNMPV1
    case SNMP_VERSION_1:
#endif
#ifndef NETSNMP_DISABLE_SNMPV2C
    case SNMP_VERSION_2c:
#endif
    case SNMP_VERSION_3:
        snmp_call_callbacks(SNMP_CALLBACK_APPLICATION,
                            SNMPD_CALLBACK_ACM_CHECK_INITIAL, &view_parms);
        return view_parms.errorcode;
    }
    return 1;
}

/** Determines if the given PDU request could potentially access
 *   the specified MIB subtree
 *
 * @param pdu     PDU requesting access
 *
 * @param name    The OID to check access for.
 *
 * @param namelen Number of sub-identifiers in the OID.
 *
 * @return gives VACM_SUCCESS   if the entire MIB tree is accessible
 *               VACM_NOTINVIEW if the entire MIB tree is inaccessible
 *               VACM_SUBTREE_UNKNOWN if some portions are accessible
 *               other codes may returned on error
 */
int
netsnmp_acm_check_subtree(netsnmp_pdu *pdu, oid *name, size_t namelen)
{                               /* IN - pdu being checked */
    struct view_parameters view_parms;
    view_parms.pdu = pdu;
    view_parms.name = name;
    view_parms.namelen = namelen;
    view_parms.errorcode = 0;
    view_parms.check_subtree = 1;

    if (pdu->flags & UCD_MSG_FLAG_ALWAYS_IN_VIEW) {
	/* Enable bypassing of view-based access control */
        return 0;
    }

    switch (pdu->version) {
#ifndef NETSNMP_DISABLE_SNMPV1
    case SNMP_VERSION_1:
#endif
#ifndef NETSNMP_DISABLE_SNMPV2C
    case SNMP_VERSION_2c:
#endif
    case SNMP_VERSION_3:
        snmp_call_callbacks(SNMP_CALLBACK_APPLICATION,
                            SNMPD_CALLBACK_ACM_CHECK_SUBTREE, &view_parms);
        return view_parms.errorcode;
    }
    return 1;
}

netsnmp_feature_child_of(get_session_for_oid,netsnmp_unused)
#ifndef NETSNMP_FEATURE_REMOVE_GET_SESSION_FOR_OID
netsnmp_session *
get_session_for_oid(const oid *name, size_t len, const char *context_name)
{
    netsnmp_subtree *myptr;

    myptr = netsnmp_subtree_find_prev(name, len, 
				      netsnmp_subtree_find_first(context_name),
				      context_name);

    while (myptr && myptr->variables == NULL) {
        myptr = myptr->next;
    }

    if (myptr == NULL) {
        return NULL;
    } else {
        return myptr->session;
    }
}
#endif /* NETSNMP_FEATURE_REMOVE_GET_SESSION_FOR_OID */

void
setup_tree(void)
{
    oid ccitt[1]           = { 0 };
    oid iso[1]             = { 1 };
    oid joint_ccitt_iso[1] = { 2 };

#ifdef USING_AGENTX_SUBAGENT_MODULE
    int role =  netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID, 
				       NETSNMP_DS_AGENT_ROLE);

    netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_AGENT_ROLE, 
			   MASTER_AGENT);
#endif

    /* 
     * we need to have the oid's in the heap, that we can *free* it for every case, 
     * thats the purpose of the duplicate_objid's
     */
    netsnmp_register_null(snmp_duplicate_objid(ccitt, 1), 1);
    netsnmp_register_null(snmp_duplicate_objid(iso, 1), 1);
    netsnmp_register_null(snmp_duplicate_objid(joint_ccitt_iso, 1), 1);

#ifdef USING_AGENTX_SUBAGENT_MODULE
    netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_AGENT_ROLE, 
			   role);
#endif
}

int 
remove_tree_entry (oid *name, size_t len) {

    netsnmp_subtree *sub = NULL;

    if ((sub = netsnmp_subtree_find(name, len, NULL, "")) == NULL) {
	return MIB_NO_SUCH_REGISTRATION;
    }

    return unregister_mib_context(name, len, sub->priority,
				  sub->range_subid, sub->range_ubound, "");

}


void
shutdown_tree(void) {
    oid ccitt[1]           = { 0 };
    oid iso[1]             = { 1 };
    oid joint_ccitt_iso[1] = { 2 };

    DEBUGMSGTL(("agent_registry", "shut down tree\n"));

    remove_tree_entry(joint_ccitt_iso, 1);
    remove_tree_entry(iso, 1);
    remove_tree_entry(ccitt, 1);

}

extern void     dump_idx_registry(void);
void
dump_registry(void)
{
    struct variable *vp = NULL;
    netsnmp_subtree *myptr, *myptr2;
    u_char *s = NULL, *e = NULL, *v = NULL;
    size_t sl = 256, el = 256, vl = 256, sl_o = 0, el_o = 0, vl_o = 0;
    int i = 0;

    if ((s = (u_char *) calloc(sl, 1)) != NULL &&
        (e = (u_char *) calloc(sl, 1)) != NULL &&
        (v = (u_char *) calloc(sl, 1)) != NULL) {

        subtree_context_cache *ptr;
        for (ptr = context_subtrees; ptr; ptr = ptr->next) {
            printf("Subtrees for Context: %s\n", ptr->context_name);
            for (myptr = ptr->first_subtree; myptr != NULL;
                 myptr = myptr->next) {
                sl_o = el_o = vl_o = 0;

                if (!sprint_realloc_objid(&s, &sl, &sl_o, 1,
                                          myptr->start_a,
                                          myptr->start_len)) {
                    break;
                }
                if (!sprint_realloc_objid(&e, &el, &el_o, 1,
                                          myptr->end_a,
					  myptr->end_len)) {
                    break;
                }

                if (myptr->variables) {
                    printf("%02x ( %s - %s ) [", myptr->flags, s, e);
                    for (i = 0, vp = myptr->variables;
                         i < myptr->variables_len; i++) {
                        vl_o = 0;
                        if (!sprint_realloc_objid
                            (&v, &vl, &vl_o, 1, vp->name, vp->namelen)) {
                            break;
                        }
                        printf("%s, ", v);
                        vp = (struct variable *) ((char *) vp +
                                                  myptr->variables_width);
                    }
                    printf("]\n");
                } else {
                    printf("%02x   %s - %s  \n", myptr->flags, s, e);
                }
                for (myptr2 = myptr; myptr2 != NULL;
                     myptr2 = myptr2->children) {
                    if (myptr2->label_a && myptr2->label_a[0]) {
                        if (strcmp(myptr2->label_a, "old_api") == 0) {
                            struct variable *vp =
                                (struct variable*)myptr2->reginfo->handler->myvoid;

                            if (!sprint_realloc_objid(&s, &sl, &sl_o, 1,
                                                 vp->name, vp->namelen)) {
                                continue;
                            }
                            printf("\t%s[%s] %p var %s\n", myptr2->label_a,
                                   myptr2->reginfo->handlerName ?
                                   myptr2->reginfo->handlerName : "no-name",
                                   myptr2->reginfo, s);
                        } else {
                            printf("\t%s %s %p\n", myptr2->label_a,
                                   myptr2->reginfo->handlerName ?
                                   myptr2->reginfo->handlerName : "no-handler-name",
                                   myptr2->reginfo);
                        }
                    }
                }
            }
        }
    }

    SNMP_FREE(s);
    SNMP_FREE(e);
    SNMP_FREE(v);

    dump_idx_registry();
}

/**  @} */
/* End of MIB registration code */


/** @defgroup agent_signals POSIX signals support for agents.
 *     Registering and unregistering signal handlers.
 *   @ingroup agent_registry
 *
 * @{
 */

int             external_signal_scheduled[NUM_EXTERNAL_SIGS];
void            (*external_signal_handler[NUM_EXTERNAL_SIGS]) (int);

#ifndef WIN32

/*
 * TODO: add agent_SIGXXX_handler functions and `case SIGXXX: ...' lines
 *       below for every single that might be handled by register_signal().
 */

RETSIGTYPE
agent_SIGCHLD_handler(int sig)
{
    external_signal_scheduled[SIGCHLD]++;
#ifndef HAVE_SIGACTION
    /*
     * signal() sucks. It *might* have SysV semantics, which means that
     * * a signal handler is reset once it gets called. Ensure that it
     * * remains active.
     */
    signal(SIGCHLD, agent_SIGCHLD_handler);
#endif
}

/** Registers a POSIX Signal handler.
 *  Implements the signal registering process for POSIX and non-POSIX
 *  systems. Also, unifies the way signals work.
 *  Note that the signal handler should register itself again with
 *  signal() call before end of execution to prevent possible problems.
 *
 *  @param sig POSIX Signal ID number, as defined in signal.h.
 *
 *  @param func New signal handler function.
 *
 *  @return value is SIG_REGISTERED_OK for success and
 *        SIG_REGISTRATION_FAILED if the registration can't
 *        be handled.
 */
int
register_signal(int sig, void (*func) (int))
{

    switch (sig) {
#if defined(SIGCHLD)
    case SIGCHLD:
#ifdef HAVE_SIGACTION
        {
            static struct sigaction act;
            act.sa_handler = agent_SIGCHLD_handler;
            sigemptyset(&act.sa_mask);
            act.sa_flags = 0;
            sigaction(SIGCHLD, &act, NULL);
        }
#else
        signal(SIGCHLD, agent_SIGCHLD_handler);
#endif
        break;
#endif
    default:
        snmp_log(LOG_CRIT,
                 "register_signal: signal %d cannot be handled\n", sig);
        return SIG_REGISTRATION_FAILED;
    }

    external_signal_handler[sig] = func;
    external_signal_scheduled[sig] = 0;

    DEBUGMSGTL(("register_signal", "registered signal %d\n", sig));
    return SIG_REGISTERED_OK;
}

/** Unregisters a POSIX Signal handler.
 *
 *  @param sig POSIX Signal ID number, as defined in signal.h.
 *
 *  @return value is SIG_UNREGISTERED_OK for success, or error code.
 */
int
unregister_signal(int sig)
{
    signal(sig, SIG_DFL);
    DEBUGMSGTL(("unregister_signal", "unregistered signal %d\n", sig));
    return SIG_UNREGISTERED_OK;
}

#endif                          /* !WIN32 */

/**  @} */
/* End of signals support code */

/**  @} */