9d14838fc8f5b9e98671bd53dc8d3f05086e0b88
[metze/wireshark/wip.git] / epan / oids.c
1 /* oids.c
2  * Object IDentifier Support
3  *
4  * (c) 2007, Luis E. Garcia Ontanon <luis@ontanon.org>
5  *
6  * Wireshark - Network traffic analyzer
7  * By Gerald Combs <gerald@wireshark.org>
8  * Copyright 1998 Gerald Combs
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23  */
24
25 #include "config.h"
26
27 #include <glib.h>
28 #include <stdio.h>
29 #include <string.h>
30
31 #include <wsutil/report_err.h>
32
33 #include "wmem/wmem.h"
34 #include "uat.h"
35 #include "prefs.h"
36 #include "proto.h"
37 #include "packet.h"
38 #include "wsutil/filesystem.h"
39 #include "dissectors/packet-ber.h"
40
41 #ifdef HAVE_LIBSMI
42 #include <smi.h>
43
44 static gboolean oids_init_done = FALSE;
45 static gboolean load_smi_modules = FALSE;
46 static gboolean suppress_smi_errors = FALSE;
47 #endif
48
49 #define D(level,args) do if (debuglevel >= level) { printf args; printf("\n"); fflush(stdout); } while(0)
50
51 #include "oids.h"
52
53 static int debuglevel = 0;
54
55 /*
56  * From SNMPv2-SMI and X.690
57  *
58  * Counter32  ::= [APPLICATION 1] IMPLICIT INTEGER (0..4294967295)
59  * Gauge32    ::= [APPLICATION 2] IMPLICIT INTEGER (0..4294967295)
60  * Unsigned32 ::= [APPLICATION 2] IMPLICIT INTEGER (0..4294967295) (alias of Gauge32)
61  * TimeTicks  ::= [APPLICATION 3] IMPLICIT INTEGER (0..4294967295)
62  *
63  * If the BER encoding should not have the top bit set as to not become a negative number
64  * the BER encoding may take 5 octets to encode.
65  */
66
67 #ifdef HAVE_LIBSMI
68 static const oid_value_type_t integer_type =    { FT_INT32,  BASE_DEC,  BER_CLASS_UNI, BER_UNI_TAG_INTEGER,     1,   4, OID_KEY_TYPE_INTEGER, 1};
69 static const oid_value_type_t bytes_type =      { FT_BYTES,  BASE_NONE, BER_CLASS_UNI, BER_UNI_TAG_OCTETSTRING, 0,  -1, OID_KEY_TYPE_BYTES,   0};
70 static const oid_value_type_t oid_type =        { FT_OID,    BASE_NONE, BER_CLASS_UNI, BER_UNI_TAG_OID,         1,  -1, OID_KEY_TYPE_OID,     0};
71 static const oid_value_type_t ipv4_type =       { FT_IPv4,   BASE_NONE, BER_CLASS_APP, 0,                       4,   4, OID_KEY_TYPE_IPADDR,  4};
72 static const oid_value_type_t counter32_type =  { FT_UINT64, BASE_DEC,  BER_CLASS_APP, 1,                       1,   5, OID_KEY_TYPE_INTEGER, 1};
73 static const oid_value_type_t unsigned32_type = { FT_UINT64, BASE_DEC,  BER_CLASS_APP, 2,                       1,   5, OID_KEY_TYPE_INTEGER, 1};
74 static const oid_value_type_t timeticks_type =  { FT_UINT64, BASE_DEC,  BER_CLASS_APP, 3,                       1,   5, OID_KEY_TYPE_INTEGER, 1};
75 #if 0
76 static const oid_value_type_t opaque_type =     { FT_BYTES,  BASE_NONE, BER_CLASS_APP, 4,                       1,   4, OID_KEY_TYPE_BYTES,   0};
77 #endif
78 static const oid_value_type_t nsap_type =       { FT_BYTES,  BASE_NONE, BER_CLASS_APP, 5,                       0,  -1, OID_KEY_TYPE_NSAP,    0};
79 static const oid_value_type_t counter64_type =  { FT_UINT64, BASE_DEC,  BER_CLASS_APP, 6,                       1,   8, OID_KEY_TYPE_INTEGER, 1};
80 static const oid_value_type_t ipv6_type =       { FT_IPv6,   BASE_NONE, BER_CLASS_UNI, BER_UNI_TAG_OCTETSTRING, 16, 16, OID_KEY_TYPE_BYTES,   16};
81 static const oid_value_type_t float_type =      { FT_FLOAT,  BASE_DEC,  BER_CLASS_UNI, BER_UNI_TAG_OCTETSTRING, 4,   4, OID_KEY_TYPE_WRONG,   0};
82 static const oid_value_type_t double_type =     { FT_DOUBLE, BASE_DEC,  BER_CLASS_UNI, BER_UNI_TAG_OCTETSTRING, 8,   8, OID_KEY_TYPE_WRONG,   0};
83 static const oid_value_type_t ether_type =      { FT_ETHER,  BASE_NONE, BER_CLASS_UNI, BER_UNI_TAG_OCTETSTRING, 6,   6, OID_KEY_TYPE_ETHER,   6};
84 static const oid_value_type_t string_type =     { FT_STRING, BASE_NONE, BER_CLASS_UNI, BER_UNI_TAG_OCTETSTRING, 0,  -1, OID_KEY_TYPE_STRING,  0};
85 static const oid_value_type_t date_and_time_type = { FT_STRING,  BASE_NONE, BER_CLASS_UNI, BER_UNI_TAG_OCTETSTRING, 8,  11, OID_KEY_TYPE_DATE_AND_TIME,   0};
86 #endif /* HAVE_LIBSMI */
87
88 static const oid_value_type_t unknown_type =    { FT_BYTES,  BASE_NONE, BER_CLASS_ANY, BER_TAG_ANY,             0,  -1, OID_KEY_TYPE_WRONG,   0};
89
90 static oid_info_t oid_root = { 0, NULL, OID_KIND_UNKNOWN, NULL, &unknown_type, -2, NULL, NULL, NULL};
91
92 static void prepopulate_oids(void) {
93         if (!oid_root.children) {
94                 char* debug_env = getenv("WIRESHARK_DEBUG_MIBS");
95                 guint32 subid;
96
97                 debuglevel = debug_env ? (int)strtoul(debug_env,NULL,10) : 0;
98
99                 oid_root.children = wmem_tree_new(wmem_epan_scope());
100
101                 /*
102                  * make sure we got strings at least in the three root-children oids
103                  * that way oid_resolved() will always have a string to print
104                  */
105                 subid = 0; oid_add("itu-t",1,&subid);
106                 subid = 1; oid_add("iso",1,&subid);
107                 subid = 2; oid_add("joint-iso-itu-t",1,&subid);
108         }
109 }
110
111
112
113 static oid_info_t* add_oid(const char* name, oid_kind_t kind, const oid_value_type_t* type, oid_key_t* key, guint oid_len, guint32 *subids) {
114         guint i = 0;
115         oid_info_t* c = &oid_root;
116
117         prepopulate_oids();
118         oid_len--;
119
120         do {
121                 oid_info_t* n = (oid_info_t *)wmem_tree_lookup32(c->children,subids[i]);
122
123                 if(n) {
124                         if (i == oid_len) {
125                                 if (n->name) {
126                                         if (!g_str_equal(n->name,name)) {
127                                                 D(2,("Renaming Oid from: %s -> %s, this means the same oid is registered more than once",n->name,name));
128                                         }
129                                         wmem_free(wmem_epan_scope(), n->name);
130                                 }
131
132                                 n->name = wmem_strdup(wmem_epan_scope(), name);
133
134                                 if (! n->value_type) {
135                                         n->value_type = type;
136                                 }
137
138                                 return n;
139                         }
140                 } else {
141                         n = wmem_new(wmem_epan_scope(), oid_info_t);
142                         n->subid = subids[i];
143                         n->kind = kind;
144                         n->children = wmem_tree_new(wmem_epan_scope());
145                         n->value_hfid = -2;
146                         n->key = key;
147                         n->parent = c;
148                         n->bits = NULL;
149
150                         wmem_tree_insert32(c->children,n->subid,n);
151
152                         if (i == oid_len) {
153                                 n->name = wmem_strdup(wmem_epan_scope(), name);
154                                 n->value_type = type;
155                                 n->kind = kind;
156                                 return n;
157                         } else {
158                                 n->name = NULL;
159                                 n->value_type = NULL;
160                                 n->kind = OID_KIND_UNKNOWN;
161                         }
162                 }
163                 c = n;
164         } while(++i);
165
166         g_assert_not_reached();
167         return NULL;
168 }
169
170 void oid_add(const char* name, guint oid_len, guint32 *subids) {
171         g_assert(subids && *subids <= 2);
172         if (oid_len) {
173                 gchar* sub = oid_subid2string(NULL, subids,oid_len);
174                 D(3,("\tOid (from subids): %s %s ",name?name:"NULL", sub));
175                 add_oid(name,OID_KIND_UNKNOWN,NULL,NULL,oid_len,subids);
176                 wmem_free(NULL, sub);
177         } else {
178                 D(1,("Failed to add Oid: %s (from subids)",name?name:"NULL"));
179         }
180 }
181
182 void oid_add_from_string(const char* name, const gchar *oid_str) {
183         guint32* subids;
184         guint oid_len = oid_string2subid(NULL, oid_str, &subids);
185
186         if (oid_len) {
187                 gchar* sub = oid_subid2string(NULL, subids,oid_len);
188                 D(3,("\tOid (from string): %s %s ",name?name:"NULL", sub));
189                 add_oid(name,OID_KIND_UNKNOWN,NULL,NULL,oid_len,subids);
190                 wmem_free(NULL, sub);
191         } else {
192                 D(1,("Failed to add Oid: %s %s ",name?name:"NULL", oid_str?oid_str:NULL));
193         }
194         wmem_free(NULL, subids);
195 }
196
197 extern void oid_add_from_encoded(const char* name, const guint8 *oid, gint oid_len) {
198         guint32* subids = NULL;
199         guint subids_len = oid_encoded2subid(NULL, oid, oid_len, &subids);
200
201         if (subids_len) {
202                 gchar* sub = oid_subid2string(NULL, subids,subids_len);
203                 D(3,("\tOid (from encoded): %s %s ",name, sub));
204                 add_oid(name,OID_KIND_UNKNOWN,NULL,NULL,subids_len,subids);
205                 wmem_free(NULL, sub);
206         } else {
207                 gchar* bytestr = bytestring_to_str(NULL, oid, oid_len, ':');
208                 D(1,("Failed to add Oid: %s [%d]%s ",name?name:"NULL", oid_len, bytestr));
209                 wmem_free(NULL, bytestr);
210         }
211         wmem_free(NULL, subids);
212 }
213
214 #ifdef HAVE_LIBSMI
215 /* de-allocate storage mallocated by libsmi                            */
216 /*                                                                     */
217 /* XXX: libsmi provides access to smiFree as of libsmi v 0.4.8.        */
218 /*      On Windows: Wireshark 1.01 and later is built and distributed  */
219 /*      with libsmi 0.4.8 (or newer).                                  */
220 /*      On non-Windows systems, free() should be OK for libsmi         */
221 /*       versions older than 0.4.8.                                    */
222
223 static void smi_free(void *ptr) {
224
225 #if (SMI_VERSION_MAJOR >= 0) && (SMI_VERSION_MINOR >= 4) && (SMI_VERSION_PATCHLEVEL >= 8)
226        smiFree(ptr);
227 #else
228  #ifdef _WIN32
229  #error Invalid Windows libsmi version ?? !!
230  #endif
231 #define xx_free free  /* hack so checkAPIs.pl doesn't complain */
232        xx_free(ptr);
233 #endif
234 }
235
236
237 typedef struct smi_module_t {
238         char* name;
239 } smi_module_t;
240
241 static smi_module_t* smi_paths = NULL;
242 static guint num_smi_paths = 0;
243 static uat_t* smi_paths_uat = NULL;
244
245 static smi_module_t* smi_modules = NULL;
246 static guint num_smi_modules = 0;
247 static uat_t* smi_modules_uat = NULL;
248
249 static GString* smi_errors;
250
251 UAT_DIRECTORYNAME_CB_DEF(smi_mod,name,smi_module_t)
252
253 static void smi_error_handler(char *path, int line, int severity, char *msg, char *tag) {
254                 g_string_append_printf(smi_errors,"%s:%d %d %s %s\n",
255                                                   path ? path : "-",
256                                                   line, severity,
257                                                   tag ? tag : "-",
258                                                   msg ? msg : "");
259 }
260
261
262 static void* smi_mod_copy_cb(void* dest, const void* orig, size_t len _U_) {
263         const smi_module_t* m = (const smi_module_t*)orig;
264         smi_module_t* d = (smi_module_t*)dest;
265
266         d->name = g_strdup(m->name);
267
268         return d;
269 }
270
271 static void smi_mod_free_cb(void* p) {
272         smi_module_t* m = (smi_module_t*)p;
273         g_free(m->name);
274 }
275
276
277 static char* alnumerize(const char* name) {
278         char* s = g_strdup(name);
279         char* r = s;
280         char* w = r;
281         char c;
282
283         for (;(c = *r); r++) {
284                 if (g_ascii_isalnum(c) || c == '_' || c == '-' || c == '.') {
285                         *(w++) = c;
286                 } else if (c == ':' && r[1] == ':') {
287                         *(w++) = '.';
288                 }
289         }
290
291         *w = '\0';
292
293         return s;
294 }
295
296 static const oid_value_type_t* get_typedata(SmiType* smiType) {
297         /*
298          * There has to be a better way to know if a given
299          * OCTETSTRING type is actually human readable text,
300          * an address of some type or some moe specific FT_
301          * Until that is found, this is the mappping between
302          * SNMP Types and our FT_s
303          */
304         static const struct _type_mapping_t {
305                 const char* name;
306                 SmiBasetype base;
307                 const oid_value_type_t* type;
308         } types[] =  {
309                 {"IpAddress", SMI_BASETYPE_UNKNOWN, &ipv4_type},
310                 {"InetAddressIPv4",SMI_BASETYPE_UNKNOWN,&ipv4_type},
311                 {"InetAddressIPv6",SMI_BASETYPE_UNKNOWN,&ipv6_type},
312                 {"NetworkAddress",SMI_BASETYPE_UNKNOWN,&ipv4_type},
313                 {"MacAddress",SMI_BASETYPE_UNKNOWN,&ether_type},
314                 {"TimeTicks",SMI_BASETYPE_UNKNOWN,&timeticks_type},
315                 {"Ipv6Address",SMI_BASETYPE_UNKNOWN,&ipv6_type},
316                 {"TimeStamp",SMI_BASETYPE_UNKNOWN,&timeticks_type},
317                 {"DisplayString",SMI_BASETYPE_UNKNOWN,&string_type},
318                 {"SnmpAdminString",SMI_BASETYPE_UNKNOWN,&string_type},
319                 {"DateAndTime",SMI_BASETYPE_UNKNOWN,&date_and_time_type},
320                 {"Counter",SMI_BASETYPE_UNKNOWN,&counter32_type},
321                 {"Counter32",SMI_BASETYPE_UNKNOWN,&counter32_type},
322                 {"Unsigned32",SMI_BASETYPE_UNKNOWN,&unsigned32_type},
323                 {"Gauge",SMI_BASETYPE_UNKNOWN,&unsigned32_type},
324                 {"Gauge32",SMI_BASETYPE_UNKNOWN,&unsigned32_type},
325                 {"NsapAddress",SMI_BASETYPE_UNKNOWN,&nsap_type},
326                 {"i32",SMI_BASETYPE_INTEGER32,&integer_type},
327                 {"octets",SMI_BASETYPE_OCTETSTRING,&bytes_type},
328                 {"oid",SMI_BASETYPE_OBJECTIDENTIFIER,&oid_type},
329                 {"u32",SMI_BASETYPE_UNSIGNED32,&unsigned32_type},
330                 {"u64",SMI_BASETYPE_UNSIGNED64,&counter64_type},
331                 {"f32",SMI_BASETYPE_FLOAT32,&float_type},
332                 {"f64",SMI_BASETYPE_FLOAT64,&double_type},
333                 {"f128",SMI_BASETYPE_FLOAT128,&bytes_type},
334                 {"enum",SMI_BASETYPE_ENUM,&integer_type},
335                 {"bits",SMI_BASETYPE_BITS,&bytes_type},
336                 {"unk",SMI_BASETYPE_UNKNOWN,&unknown_type},
337                 {NULL,SMI_BASETYPE_UNKNOWN,NULL} /* SMI_BASETYPE_UNKNOWN = 0 */
338         };
339         const struct _type_mapping_t* t;
340         SmiType* sT = smiType;
341
342         if (!smiType) return NULL;
343
344         do {
345                 for (t = types; t->type ; t++ ) {
346                         char* name = smiRenderType(sT, SMI_RENDER_NAME);
347                         if (name && t->name && g_str_equal(name, t->name )) {
348                                 smi_free(name);
349                                 return t->type;
350                         }
351                         if (name) {
352                                 smi_free (name);
353                         }
354                 }
355         } while(( sT  = smiGetParentType(sT) ));
356
357         for (t = types; t->type ; t++ ) {
358                 if(smiType->basetype == t->base) {
359                         return t->type;
360                 }
361         }
362
363         return &unknown_type;
364 }
365
366 static guint get_non_implicit_size(SmiType* sT) {
367         SmiRange *sR;
368         guint size = 0xffffffff;
369
370         switch (sT->basetype) {
371                 case SMI_BASETYPE_OCTETSTRING:
372                 case SMI_BASETYPE_OBJECTIDENTIFIER:
373                         break;
374                 default:
375                         return 0;
376         }
377
378         for ( ; sT; sT = smiGetParentType(sT) ) {
379                 for (sR = smiGetFirstRange(sT); sR ; sR = smiGetNextRange(sR)) {
380                         if (size == 0xffffffff) {
381                                 if (sR->minValue.value.unsigned32 == sR->maxValue.value.unsigned32) {
382                                         size = (guint32)sR->minValue.value.unsigned32;
383                                 } else {
384                                         return 0;
385                                 }
386                         } else {
387                                 if (sR->minValue.value.unsigned32 != size || sR->maxValue.value.unsigned32 != size) {
388                                         return 0;
389                                 }
390                         }
391                 }
392         }
393
394         return size == 0xffffffff ? 0 : size;
395 }
396
397
398 static inline oid_kind_t smikind(SmiNode* sN, oid_key_t** key_p) {
399         *key_p = NULL;
400
401         switch(sN->nodekind) {
402                 case SMI_NODEKIND_ROW: {
403                         SmiElement* sE;
404                         oid_key_t* kl = NULL;
405                         const oid_value_type_t* typedata = NULL;
406                         gboolean implied;
407
408                         switch (sN->indexkind) {
409                                 case SMI_INDEX_INDEX:
410                                         break;
411                                 case SMI_INDEX_AUGMENT:
412                                 case SMI_INDEX_REORDER:
413                                 case SMI_INDEX_SPARSE:
414                                 case SMI_INDEX_EXPAND:
415                                         sN = smiGetRelatedNode(sN);
416                                         break;
417                                 case SMI_INDEX_UNKNOWN:
418                                         return OID_KIND_UNKNOWN;
419                         };
420
421                         implied = sN->implied;
422
423                         for (sE = smiGetFirstElement(sN); sE; sE = smiGetNextElement(sE)) {
424                                 SmiNode* elNode =  smiGetElementNode(sE) ;
425                                 SmiType* elType = smiGetNodeType(elNode);
426                                 oid_key_t* k;
427                                 guint non_implicit_size = 0;
428                                 char *oid1, *oid2;
429
430                                 if (elType) {
431                                         non_implicit_size = get_non_implicit_size(elType);
432                                 }
433
434                                 typedata =  get_typedata(elType);
435
436                                 k = g_new(oid_key_t,1);
437
438                                 oid1 = smiRenderOID(sN->oidlen, sN->oid, SMI_RENDER_QUALIFIED);
439                                 oid2 = smiRenderOID(elNode->oidlen, elNode->oid, SMI_RENDER_NAME);
440                                 k->name = g_strdup_printf("%s.%s", oid1, oid2);
441                                 smi_free (oid1);
442                                 smi_free (oid2);
443
444                                 k->hfid = -2;
445                                 k->ft_type = typedata ? typedata->ft_type : FT_BYTES;
446                                 k->display = typedata ? typedata->display : BASE_NONE;
447                                 k->next = NULL;
448
449
450                                 if (typedata) {
451                                         k->key_type = typedata->keytype;
452                                         k->num_subids = typedata->keysize;
453                                 } else {
454                                         if (elType) {
455                                                 switch (elType->basetype) {
456                                                         case SMI_BASETYPE_BITS:
457                                                         case SMI_BASETYPE_OCTETSTRING: {
458                                                                 k->key_type = OID_KEY_TYPE_BYTES;
459                                                                 k->num_subids = non_implicit_size;
460                                                                 break;
461                                                         }
462                                                         case SMI_BASETYPE_ENUM:
463                                                         case SMI_BASETYPE_OBJECTIDENTIFIER:
464                                                         case SMI_BASETYPE_INTEGER32:
465                                                         case SMI_BASETYPE_UNSIGNED32:
466                                                         case SMI_BASETYPE_INTEGER64:
467                                                         case SMI_BASETYPE_UNSIGNED64:
468                                                                 k->key_type = OID_KEY_TYPE_INTEGER;
469                                                                 k->num_subids = 1;
470                                                                 break;
471                                                         default:
472                                                                 k->key_type = OID_KEY_TYPE_WRONG;
473                                                                 k->num_subids = 0;
474                                                                 break;
475                                                 }
476                                         } else {
477                                                 k->key_type = OID_KEY_TYPE_WRONG;
478                                                 k->num_subids = 0;
479                                                 break;
480                                         }
481                                 }
482
483                                 if (!*key_p) *key_p = k;
484                                 if (kl) kl->next = k;
485
486                                 kl = k;
487                         }
488
489                         if (implied && kl) {
490                                 switch (kl->key_type) {
491                                         case OID_KEY_TYPE_BYTES:  kl->key_type = OID_KEY_TYPE_IMPLIED_BYTES; break;
492                                         case OID_KEY_TYPE_STRING: kl->key_type = OID_KEY_TYPE_IMPLIED_STRING; break;
493                                         case OID_KEY_TYPE_OID:    kl->key_type = OID_KEY_TYPE_IMPLIED_OID; break;
494                                         default: break;
495                                 }
496                         }
497
498                         return OID_KIND_ROW;
499                 }
500                 case SMI_NODEKIND_NODE: return OID_KIND_NODE;
501                 case SMI_NODEKIND_SCALAR: return OID_KIND_SCALAR;
502                 case SMI_NODEKIND_TABLE: return OID_KIND_TABLE;
503                 case SMI_NODEKIND_COLUMN: return OID_KIND_COLUMN;
504                 case SMI_NODEKIND_NOTIFICATION: return OID_KIND_NOTIFICATION;
505                 case SMI_NODEKIND_GROUP: return OID_KIND_GROUP;
506                 case SMI_NODEKIND_COMPLIANCE: return OID_KIND_COMPLIANCE;
507                 case SMI_NODEKIND_CAPABILITIES: return OID_KIND_CAPABILITIES;
508                 default: return OID_KIND_UNKNOWN;
509         }
510 }
511
512 #define IS_ENUMABLE(ft) ( (ft == FT_UINT8) || (ft == FT_UINT16) || (ft == FT_UINT24) || (ft == FT_UINT32) \
513                                                    || (ft == FT_INT8) || (ft == FT_INT16) || (ft == FT_INT24) || (ft == FT_INT32) \
514                                                    || (ft == FT_UINT64) || (ft == FT_INT64) )
515
516 static void unregister_mibs(void) {
517         /* TODO: Unregister "MIBs" proto and clean up field array and subtree array.
518          * Wireshark does not support that yet. :-( */
519
520         /* smiExit(); */
521 }
522
523 static void restart_needed_warning(void) {
524         if (oids_init_done)
525                 report_failure("Wireshark needs to be restarted for these changes to take effect");
526 }
527
528 static void register_mibs(void) {
529         SmiModule *smiModule;
530         SmiNode *smiNode;
531         guint i;
532         int proto_mibs = -1;
533         wmem_array_t* hfa;
534         GArray* etta;
535         gchar* path_str;
536
537         if (!load_smi_modules) {
538                 D(1,("OID resolution not enabled"));
539                 return;
540         }
541
542         /* TODO: Remove this workaround when unregistration of "MIBs" proto is solved.
543          * Wireshark does not support that yet. :-( */
544         if (oids_init_done) {
545                 D(1,("Exiting register_mibs() to avoid double registration of MIBs proto."));
546                 return;
547         } else {
548                 oids_init_done = TRUE;
549         }
550
551         hfa = wmem_array_new(wmem_epan_scope(), sizeof(hf_register_info));
552         etta = g_array_new(FALSE,TRUE,sizeof(gint*));
553
554         smiInit(NULL);
555
556         smi_errors = g_string_new("");
557         smiSetErrorHandler(smi_error_handler);
558
559         path_str = oid_get_default_mib_path();
560         D(1,("SMI Path: '%s'",path_str));
561
562         smiSetPath(path_str);
563
564         for(i=0;i<num_smi_modules;i++) {
565                 if (!smi_modules[i].name) continue;
566
567                 if (smiIsLoaded(smi_modules[i].name)) {
568                         continue;
569                 } else {
570                         char* mod_name =  smiLoadModule(smi_modules[i].name);
571                         if (mod_name)
572                                 D(2,("Loaded: '%s'[%u] as %s",smi_modules[i].name,i,mod_name ));
573                         else
574                                 D(1,("Failed to load: '%s'[%u]",smi_modules[i].name,i));
575                 }
576         }
577
578         if (smi_errors->len) {
579                 if (!suppress_smi_errors) {
580                         report_failure("The following errors were found while loading the MIBS:\n%s\n\n"
581                                            "The Current Path is: %s\n\nYou can avoid this error message "
582                                            "by removing the missing MIB modules at Edit -> Preferences"
583                                            " -> Name Resolution -> SMI (MIB and PIB) modules or by "
584                                            "installing them.\n" , smi_errors->str , path_str);
585                 }
586                 D(1,("Errors while loading:\n%s\n",smi_errors->str));
587         }
588
589         g_free(path_str);
590         g_string_free(smi_errors,TRUE);
591
592         for (smiModule = smiGetFirstModule();
593                  smiModule;
594                  smiModule = smiGetNextModule(smiModule)) {
595
596                 D(3,("\tModule: %s", smiModule->name));
597
598                 /* TODO: Check libsmi version at compile time and disable this
599                  * workaround for libsmi versions where this problem is fixed.
600                  * Currently there is no such version. :-(
601                  */
602                 if (smiModule->conformance == 1) {
603                         if (!suppress_smi_errors) {
604                                 report_failure("Stopped processing module %s due to "
605                                         "error(s) to prevent potential crash in libsmi.\n"
606                                         "Module's conformance level: %d.\n"
607                                         "See details at: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=560325\n",
608                                          smiModule->name, smiModule->conformance);
609                         }
610                         continue;
611                 }
612                 for (smiNode = smiGetFirstNode(smiModule, SMI_NODEKIND_ANY);
613                          smiNode;
614                          smiNode = smiGetNextNode(smiNode, SMI_NODEKIND_ANY)) {
615
616                         SmiType* smiType =  smiGetNodeType(smiNode);
617                         const oid_value_type_t* typedata =  get_typedata(smiType);
618                         oid_key_t* key;
619                         oid_kind_t kind = smikind(smiNode,&key);
620                         char *sub;
621                         char *oid = smiRenderOID(smiNode->oidlen, smiNode->oid, SMI_RENDER_QUALIFIED);
622                         oid_info_t* oid_data = add_oid(oid,
623                                                        kind,
624                                                        typedata,
625                                                        key,
626                                                        smiNode->oidlen,
627                                                        smiNode->oid);
628                         smi_free (oid);
629
630                         sub = oid_subid2string(NULL, smiNode->oid, smiNode->oidlen);
631                         D(4,("\t\tNode: kind=%d oid=%s name=%s ",
632                                  oid_data->kind, sub, oid_data->name));
633                         wmem_free(NULL, sub);
634
635                         if ( typedata && oid_data->value_hfid == -2 ) {
636                                 SmiNamedNumber* smiEnum;
637                                 hf_register_info hf;
638
639                                 hf.p_id                     = &(oid_data->value_hfid);
640                                 hf.hfinfo.name              = g_strdup(oid_data->name);
641                                 hf.hfinfo.abbrev            = alnumerize(oid_data->name);
642                                 hf.hfinfo.type              = typedata->ft_type;
643                                 hf.hfinfo.display           = typedata->display;
644                                 hf.hfinfo.strings           = NULL;
645                                 hf.hfinfo.bitmask           = 0;
646                                 hf.hfinfo.blurb             = smiRenderOID(smiNode->oidlen, smiNode->oid, SMI_RENDER_ALL);
647                                 /* HFILL */
648                                 HFILL_INIT(hf);
649
650                                 /* Don't allow duplicate blurb/name */
651                                 if (strcmp(hf.hfinfo.blurb, hf.hfinfo.name) == 0) {
652                                         smi_free((void *) hf.hfinfo.blurb);
653                                         hf.hfinfo.blurb = NULL;
654                                 }
655
656                                 oid_data->value_hfid = -1;
657
658                                 if ( IS_ENUMABLE(hf.hfinfo.type) && (smiEnum = smiGetFirstNamedNumber(smiType))) {
659                                         GArray* vals = g_array_new(TRUE,TRUE,sizeof(value_string));
660
661                                         for(;smiEnum; smiEnum = smiGetNextNamedNumber(smiEnum)) {
662                                                 if (smiEnum->name) {
663                                                         value_string val;
664                                                         val.value  = (guint32)smiEnum->value.value.integer32;
665                                                         val.strptr = g_strdup(smiEnum->name);
666                                                         g_array_append_val(vals,val);
667                                                 }
668                                         }
669
670                                         hf.hfinfo.strings = vals->data;
671                                         g_array_free(vals,FALSE);
672                                 }
673 #if 0 /* packet-snmp does not handle bits yet */
674                         } else if (smiType->basetype == SMI_BASETYPE_BITS && ( smiEnum = smiGetFirstNamedNumber(smiType) )) {
675                                 guint n = 0;
676                                 oid_bits_info_t* bits = g_malloc(sizeof(oid_bits_info_t));
677                                 gint* ettp = &(bits->ett);
678
679                                 bits->num = 0;
680                                 bits->ett = -1;
681
682                                 g_array_append_val(etta,ettp);
683
684                                 for(;smiEnum; smiEnum = smiGetNextNamedNumber(smiEnum), bits->num++);
685
686                                 bits->data = g_malloc(sizeof(struct _oid_bit_t)*bits->num);
687
688                                 for(smiEnum = smiGetFirstNamedNumber(smiType),n=0;
689                                         smiEnum;
690                                         smiEnum = smiGetNextNamedNumber(smiEnum),n++) {
691                                         guint mask = 1 << (smiEnum->value.value.integer32 % 8);
692                                         char* base = alnumerize(oid_data->name);
693                                         char* ext = alnumerize(smiEnum->name);
694                                         hf_register_info hf2 = { &(bits->data[n].hfid), { NULL, NULL, FT_UINT8, BASE_HEX, NULL, mask, NULL, HFILL }};
695
696                                         bits->data[n].hfid = -1;
697                                         bits->data[n].offset = smiEnum->value.value.integer32 / 8;
698
699                                         hf2.hfinfo.name = g_strdup_printf("%s:%s",oid_data->name,smiEnum->name);
700                                         hf2.hfinfo.abbrev = g_strdup_printf("%s.%s",base,ext);
701
702                                         g_free(base);
703                                         g_free(ext);
704                                         g_array_append_val(hfa,hf2);
705                                 }
706 #endif /* packet-snmp does not use this yet */
707                                 wmem_array_append_one(hfa,hf);
708                         }
709
710                         if ((key = oid_data->key)) {
711                                 for(; key; key = key->next) {
712                                         hf_register_info hf;
713
714                                         hf.p_id                     = &(key->hfid);
715                                         hf.hfinfo.name              = key->name;
716                                         hf.hfinfo.abbrev            = alnumerize(key->name);
717                                         hf.hfinfo.type              = key->ft_type;
718                                         hf.hfinfo.display           = key->display;
719                                         hf.hfinfo.strings           = NULL;
720                                         hf.hfinfo.bitmask           = 0;
721                                         hf.hfinfo.blurb             = NULL;
722                                         /* HFILL */
723                                         HFILL_INIT(hf);
724
725                                         D(5,("\t\t\tIndex: name=%s subids=%u key_type=%d",
726                                                  key->name, key->num_subids, key->key_type ));
727
728                                         if (key->hfid == -2) {
729                                                 wmem_array_append_one(hfa,hf);
730                                                 key->hfid = -1;
731                                         } else {
732                                                 g_free((void*)hf.hfinfo.abbrev);
733                                         }
734                                 }
735                         }
736                 }
737         }
738
739         proto_mibs = proto_register_protocol("MIBs", "MIBS", "mibs");
740
741         proto_register_field_array(proto_mibs, (hf_register_info*)wmem_array_get_raw(hfa), wmem_array_get_count(hfa));
742
743         proto_register_subtree_array((gint**)(void*)etta->data, etta->len);
744
745         g_array_free(etta,TRUE);
746 }
747 #endif
748
749 void oid_pref_init(module_t *nameres)
750 {
751 #ifdef HAVE_LIBSMI
752         static uat_field_t smi_fields[] = {
753                 UAT_FLD_CSTRING(smi_mod,name,"Module name","The module's name"),
754                 UAT_END_FIELDS
755         };
756         static uat_field_t smi_paths_fields[] = {
757                 UAT_FLD_DIRECTORYNAME(smi_mod,name,"Directory path","The directory name"),
758                 UAT_END_FIELDS
759         };
760
761     prefs_register_bool_preference(nameres, "load_smi_modules",
762                                   "Enable OID resolution",
763                                   "You must restart Wireshark for this change to take effect",
764                                   &load_smi_modules);
765
766     prefs_register_bool_preference(nameres, "suppress_smi_errors",
767                                   "Suppress SMI errors",
768                                   "Some errors can be ignored. If unsure, set to false.",
769                                   &suppress_smi_errors);
770
771     smi_paths_uat = uat_new("SMI Paths",
772                             sizeof(smi_module_t),
773                             "smi_paths",
774                             FALSE,
775                             (void**)&smi_paths,
776                             &num_smi_paths,
777     /* affects dissection of packets (as the MIBs and PIBs affect the
778        interpretation of e.g. SNMP variable bindings), but not set of
779        named fields
780
781        XXX - if named fields are generated from the MIBs and PIBs
782        for particular variable bindings, this *does* affect the set
783        of named fields! */
784                             UAT_AFFECTS_DISSECTION,
785                             "ChSNMPSMIPaths",
786                             smi_mod_copy_cb,
787                             NULL,
788                             smi_mod_free_cb,
789                             restart_needed_warning,
790                             smi_paths_fields);
791
792     prefs_register_uat_preference(nameres,
793                                   "smi_paths",
794                                   "SMI (MIB and PIB) paths",
795                                   "Search paths for SMI (MIB and PIB) modules. You must\n"
796                                   "restart Wireshark for these changes to take effect.",
797                                   smi_paths_uat);
798
799     smi_modules_uat = uat_new("SMI Modules",
800                               sizeof(smi_module_t),
801                               "smi_modules",
802                               FALSE,
803                               (void**)&smi_modules,
804                               &num_smi_modules,
805     /* affects dissection of packets (as the MIBs and PIBs affect the
806        interpretation of e.g. SNMP variable bindings), but not set of
807        named fields
808
809        XXX - if named fields are generated from the MIBs and PIBs
810        for particular variable bindings, would this affect the set
811        of named fields? */
812                               UAT_AFFECTS_DISSECTION,
813                               "ChSNMPSMIModules",
814                               smi_mod_copy_cb,
815                               NULL,
816                               smi_mod_free_cb,
817                               restart_needed_warning,
818                               smi_fields);
819
820     prefs_register_uat_preference(nameres,
821                                   "smi_modules",
822                                   "SMI (MIB and PIB) modules",
823                                   "List of enabled SMI (MIB and PIB) modules. You must\n"
824                                   "restart Wireshark for these changes to take effect.",
825                                   smi_modules_uat);
826
827 #else
828     prefs_register_static_text_preference(nameres, "load_smi_modules_static",
829                             "Enable OID resolution: N/A",
830                             "Support for OID resolution was not compiled into this version of Wireshark");
831
832     prefs_register_static_text_preference(nameres, "suppress_smi_errors_static",
833                             "Suppress SMI errors: N/A",
834                             "Support for OID resolution was not compiled into this version of Wireshark");
835
836     prefs_register_static_text_preference(nameres, "smi_module_path",
837                             "SMI (MIB and PIB) modules and paths: N/A",
838                             "Support for OID resolution was not compiled into this version of Wireshark");
839 #endif
840 }
841
842 void oids_init(void) {
843         prepopulate_oids();
844 #ifdef HAVE_LIBSMI
845         register_mibs();
846 #else
847         D(1,("libsmi disabled oid resolution not enabled"));
848 #endif
849 }
850
851 void oids_cleanup(void) {
852 #ifdef HAVE_LIBSMI
853         unregister_mibs();
854 #else
855         D(1,("libsmi disabled oid resolution not enabled"));
856 #endif
857 }
858
859 char* oid_subid2string(wmem_allocator_t *scope, guint32* subids, guint len) {
860         return rel_oid_subid2string(scope, subids, len, TRUE);
861 }
862 char* rel_oid_subid2string(wmem_allocator_t *scope, guint32* subids, guint len, gboolean is_absolute) {
863         char *s, *w;
864
865         if(!subids || len == 0)
866                 return wmem_strdup(scope, "*** Empty OID ***");
867
868         s = (char *)wmem_alloc0(scope, ((len)*11)+2);
869         w = s;
870
871         if (!is_absolute)
872                 *w++ = '.';
873
874         do {
875                 w += g_snprintf(w,12,"%u.",*subids++);
876         } while(--len);
877
878         if (w!=s) *(w-1) = '\0'; else *(s) = '\0';
879
880         return s;
881 }
882
883 static guint check_num_oid(const char* str) {
884         const char* r = str;
885         char c = '.';
886         guint n = 0;
887
888         D(8,("check_num_oid: '%s'",str));
889         if (!r) return 0;
890
891         do {
892                 D(9,("\tcheck_num_oid: '%c' %u",*r,n));
893                 switch(*r) {
894                         case '.': case '\0':
895                                 n++;
896                                 if (c == '.') return 0;
897                                 break;
898                         case '1' : case '2' : case '3' : case '4' : case '5' :
899                         case '6' : case '7' : case '8' : case '9' : case '0' :
900                                 continue;
901                         default:
902                                 return 0;
903                 }
904         } while((c = *r++));
905
906         return n;
907 }
908
909 guint oid_string2subid(wmem_allocator_t *scope, const char* str, guint32** subids_p) {
910         const char* r = str;
911         guint32* subids;
912         guint32* subids_overflow;
913         guint n = check_num_oid(str);
914         /*
915          * we cannot handle sub-ids greater than 32bytes
916          * keep a pilot subid of 64 bytes to check the limit
917          */
918         guint64 subid = 0;
919
920         D(6,("oid_string2subid: str='%s'",str));
921
922         if (!n) {
923                 *subids_p = NULL;
924                 return 0;
925         }
926
927         *subids_p = subids = wmem_alloc0_array(scope, guint32, n);
928         subids_overflow = subids + n;
929         do switch(*r) {
930                 case '.':
931                         subid = 0;
932                         subids++;
933                         continue;
934                 case '1' : case '2' : case '3' : case '4' : case '5' :
935                 case '6' : case '7' : case '8' : case '9' : case '0' :
936                         subid *= 10;
937                         subid += *r - '0';
938
939                         if( subids >= subids_overflow ||  subid > 0xffffffff) {
940                                 *subids_p=NULL;
941                                 return 0;
942                         }
943
944                         *(subids) *= 10;
945                         *(subids) += *r - '0';
946                         continue;
947                 case '\0':
948                         break;
949                 default:
950                         return 0;
951         } while(*r++);
952
953         return n;
954 }
955
956
957 guint oid_encoded2subid(wmem_allocator_t *scope, const guint8 *oid_bytes, gint oid_len, guint32** subids_p) {
958         return oid_encoded2subid_sub(scope, oid_bytes, oid_len, subids_p, TRUE);
959 }
960 guint oid_encoded2subid_sub(wmem_allocator_t *scope, const guint8 *oid_bytes, gint oid_len, guint32** subids_p,
961                 gboolean is_first) {
962         gint i;
963         guint n = is_first ? 1 : 0;
964         guint32* subids;
965         guint32* subid_overflow;
966         /*
967          * we cannot handle sub-ids greater than 32bytes
968          * have the subid in 64 bytes to be able to check the limit
969          */
970         guint64 subid = 0;
971
972         for (i=0; i<oid_len; i++) { if (! (oid_bytes[i] & 0x80 )) n++; }
973
974         *subids_p = subids = (guint32 *)wmem_alloc(scope, sizeof(guint32)*n);
975         subid_overflow = subids+n;
976
977         /* If n is 0 or 1 (depending on how it was initialized) then we found
978          * no bytes in the OID with first bit cleared, so initialize our one
979          * byte (if any) to zero and return. This *seems* to be the right thing
980          * to do in this situation, and at the very least it avoids
981          * uninitialized memory errors that would otherwise occur. */
982         if (is_first && n == 1) {
983                 *subids = 0;
984                 return n;
985         }
986         else if (!is_first && n == 0) {
987                 return n;
988         }
989
990         for (i=0; i<oid_len; i++){
991                 guint8 byte = oid_bytes[i];
992
993                 subid <<= 7;
994                 subid |= byte & 0x7F;
995
996                 if (byte & 0x80) {
997                         continue;
998                 }
999
1000                 if (is_first) {
1001                         guint32 subid0 = 0;
1002
1003                         if (subid >= 40) { subid0++; subid-=40; }
1004                         if (subid >= 40) { subid0++; subid-=40; }
1005
1006                         *subids++ = subid0;
1007
1008                         is_first = FALSE;
1009                 }
1010
1011                 if( subids >= subid_overflow || subid > 0xffffffff) {
1012                         /* scope may be NULL in which case we must free our
1013                          * useless buffer before returning */
1014                         wmem_free(scope, *subids_p);
1015                         *subids_p = NULL;
1016                         return 0;
1017                 }
1018
1019                 *subids++ = (guint32)subid;
1020                 subid = 0;
1021         }
1022
1023         g_assert(subids == subid_overflow);
1024
1025         return n;
1026 }
1027
1028 oid_info_t* oid_get(guint len, guint32* subids, guint* matched, guint* left) {
1029         oid_info_t* curr_oid = &oid_root;
1030         guint i;
1031
1032         if(!(subids && *subids <= 2)) {
1033                 *matched = 0;
1034                 *left = len;
1035                 return curr_oid;
1036         }
1037
1038         for( i=0; i < len; i++) {
1039                 oid_info_t* next_oid = (oid_info_t *)wmem_tree_lookup32(curr_oid->children,subids[i]);
1040                 if (next_oid) {
1041                         curr_oid = next_oid;
1042                 } else {
1043                         goto done;
1044                 }
1045         }
1046 done:
1047         *matched = i;
1048         *left = len - i;
1049         return curr_oid;
1050 }
1051
1052
1053 oid_info_t* oid_get_from_encoded(wmem_allocator_t *scope, const guint8 *bytes, gint byteslen, guint32** subids_p, guint* matched_p, guint* left_p) {
1054         guint subids_len = oid_encoded2subid(scope, bytes, byteslen, subids_p);
1055         return oid_get(subids_len, *subids_p, matched_p, left_p);
1056 }
1057
1058 oid_info_t* oid_get_from_string(wmem_allocator_t *scope, const gchar *oid_str, guint32** subids_p, guint* matched, guint* left) {
1059         guint subids_len = oid_string2subid(scope, oid_str, subids_p);
1060         return oid_get(subids_len, *subids_p, matched, left);
1061 }
1062
1063 gchar *oid_resolved_from_encoded(wmem_allocator_t *scope, const guint8 *oid, gint oid_len) {
1064         guint32 *subid_oid = NULL;
1065         gchar * ret;
1066         guint subid_oid_length = oid_encoded2subid(NULL, oid, oid_len, &subid_oid);
1067
1068         ret = oid_resolved(scope, subid_oid_length, subid_oid);
1069         wmem_free(NULL, subid_oid);
1070         return ret;
1071 }
1072
1073 gchar *rel_oid_resolved_from_encoded(wmem_allocator_t *scope, const guint8 *oid, gint oid_len) {
1074         guint32 *subid_oid = NULL;
1075         gchar* ret;
1076         guint subid_oid_length = oid_encoded2subid_sub(NULL, oid, oid_len, &subid_oid, FALSE);
1077
1078         ret = rel_oid_subid2string(scope, subid_oid, subid_oid_length, FALSE);
1079         wmem_free(NULL, subid_oid);
1080         return ret;
1081 }
1082
1083
1084 guint oid_subid2encoded(wmem_allocator_t *scope, guint subids_len, guint32* subids, guint8** bytes_p) {
1085         guint bytelen = 0;
1086         guint i;
1087         guint32 subid;
1088         guint8* b;
1089
1090         if ( !subids || subids_len <= 1) {
1091                 *bytes_p = NULL;
1092                 return 0;
1093         }
1094
1095         for (subid=subids[0] * 40, i = 1; i<subids_len; i++, subid=0) {
1096                 subid += subids[i];
1097                 if (subid <= 0x0000007F) {
1098                         bytelen += 1;
1099                 } else if (subid <= 0x00003FFF ) {
1100                         bytelen += 2;
1101                 } else if (subid <= 0x001FFFFF ) {
1102                         bytelen += 3;
1103                 } else if (subid <= 0x0FFFFFFF ) {
1104                         bytelen += 4;
1105                 } else {
1106                         bytelen += 5;
1107                 }
1108         }
1109
1110         *bytes_p = b = (guint8 *)wmem_alloc(scope, bytelen);
1111
1112         for (subid=subids[0] * 40, i = 1; i<subids_len; i++, subid=0) {
1113                 guint len;
1114
1115                 subid += subids[i];
1116                 if ((subid <= 0x0000007F )) len = 1;
1117                 else if ((subid <= 0x00003FFF )) len = 2;
1118                 else if ((subid <= 0x001FFFFF )) len = 3;
1119                 else if ((subid <= 0x0FFFFFFF )) len = 4;
1120                 else len = 5;
1121
1122                 switch(len) {
1123                         default: *bytes_p=NULL; return 0;
1124                         case 5: *(b++) = ((subid & 0xF0000000) >> 28) | 0x80;
1125                         case 4: *(b++) = ((subid & 0x0FE00000) >> 21) | 0x80;
1126                         case 3: *(b++) = ((subid & 0x001FC000) >> 14) | 0x80;
1127                         case 2: *(b++) = ((subid & 0x00003F80) >> 7)  | 0x80;
1128                         case 1: *(b++) =   subid & 0x0000007F ; break;
1129                 }
1130         }
1131
1132         return bytelen;
1133 }
1134
1135 gchar* oid_encoded2string(wmem_allocator_t *scope, const guint8* encoded, guint len) {
1136         guint32* subids = NULL;
1137         gchar* ret;
1138         guint subids_len = oid_encoded2subid(NULL, encoded, len, &subids);
1139
1140         if (subids_len) {
1141                 ret = oid_subid2string(scope, subids,subids_len);
1142         } else {
1143                 ret = wmem_strdup(scope, "");
1144         }
1145
1146         wmem_free(NULL, subids);
1147         return ret;
1148 }
1149
1150 gchar* rel_oid_encoded2string(wmem_allocator_t *scope, const guint8* encoded, guint len) {
1151         guint32* subids = NULL;
1152         gchar* ret;
1153         guint subids_len = oid_encoded2subid_sub(NULL, encoded, len, &subids, FALSE);
1154
1155         if (subids_len) {
1156                 ret = rel_oid_subid2string(scope, subids,subids_len, FALSE);
1157         } else {
1158                 ret = wmem_strdup(scope, "");
1159         }
1160
1161         wmem_free(NULL, subids);
1162         return ret;
1163 }
1164
1165 guint oid_string2encoded(wmem_allocator_t *scope, const char *oid_str, guint8 **bytes) {
1166         guint32* subids;
1167         guint32 subids_len;
1168         guint byteslen;
1169
1170         if ( (subids_len = oid_string2subid(NULL, oid_str, &subids)) &&
1171              (byteslen   = oid_subid2encoded(scope, subids_len, subids, bytes)) ) {
1172                 wmem_free(NULL, subids);
1173                 return byteslen;
1174         }
1175         wmem_free(NULL, subids);
1176         return 0;
1177 }
1178
1179 gchar *oid_resolved_from_string(wmem_allocator_t *scope, const gchar *oid_str) {
1180         guint32     *subid_oid;
1181         guint        subid_oid_length;
1182         gchar *resolved;
1183
1184         subid_oid_length = oid_string2subid(NULL, oid_str, &subid_oid);
1185         resolved         = oid_resolved(scope, subid_oid_length, subid_oid);
1186
1187         wmem_free(NULL, subid_oid);
1188
1189         return resolved;
1190 }
1191
1192 gchar *oid_resolved(wmem_allocator_t *scope, guint32 num_subids, guint32* subids) {
1193         guint matched;
1194         guint left;
1195         oid_info_t* oid;
1196
1197         if(! (subids && *subids <= 2 ))
1198                 return wmem_strdup(scope, "*** Malformed OID ***");
1199
1200         oid = oid_get(num_subids, subids, &matched, &left);
1201
1202         while (! oid->name ) {
1203                 if (!(oid = oid->parent)) {
1204                         return oid_subid2string(scope, subids,num_subids);
1205                 }
1206                 left++;
1207                 matched--;
1208         }
1209
1210         if (left) {
1211                 gchar *ret,
1212                           *str1 = oid_subid2string(NULL, subids,matched),
1213                           *str2 = oid_subid2string(NULL, &(subids[matched]),left);
1214
1215                 ret = wmem_strdup_printf(scope, "%s.%s", oid->name ? oid->name : str1, str2);
1216                 wmem_free(NULL, str1);
1217                 wmem_free(NULL, str2);
1218                 return ret;
1219         } else {
1220                 return oid->name ? wmem_strdup(scope, oid->name) : oid_subid2string(scope, subids,matched);
1221         }
1222 }
1223
1224 extern void oid_both(wmem_allocator_t *scope, guint oid_len, guint32 *subids, gchar** resolved_p, gchar** numeric_p) {
1225         *resolved_p = oid_resolved(scope, oid_len,subids);
1226         *numeric_p = oid_subid2string(scope, subids,oid_len);
1227 }
1228
1229 extern void oid_both_from_encoded(wmem_allocator_t *scope, const guint8 *oid, gint oid_len, gchar** resolved_p, gchar** numeric_p) {
1230         guint32* subids = NULL;
1231         guint subids_len = oid_encoded2subid(NULL, oid, oid_len, &subids);
1232         *resolved_p = oid_resolved(scope, subids_len,subids);
1233         *numeric_p = oid_subid2string(scope, subids,subids_len);
1234         wmem_free(NULL, subids);
1235 }
1236
1237 void oid_both_from_string(wmem_allocator_t *scope, const gchar *oid_str, gchar** resolved_p, gchar** numeric_p) {
1238         guint32 *subids;
1239         guint    subids_len;
1240
1241         subids_len  = oid_string2subid(NULL, oid_str, &subids);
1242         *resolved_p = oid_resolved(scope, subids_len,subids);
1243         *numeric_p  = oid_subid2string(scope, subids,subids_len);
1244         wmem_free(NULL, subids);
1245 }
1246
1247 /**
1248  * Fetch the default OID path.
1249  */
1250 extern gchar *
1251 oid_get_default_mib_path(void) {
1252 #ifdef HAVE_LIBSMI
1253         GString* path_str;
1254         char *path;
1255         guint i;
1256
1257         path_str = g_string_new("");
1258
1259         if (!load_smi_modules) {
1260                 D(1,("OID resolution not enabled"));
1261                 return path_str->str;
1262         }
1263 #ifdef _WIN32
1264 #define PATH_SEPARATOR ";"
1265         path = get_datafile_path("snmp\\mibs");
1266         g_string_append_printf(path_str, "%s;", path);
1267         g_free (path);
1268
1269         path = get_persconffile_path("snmp\\mibs", FALSE);
1270         g_string_append_printf(path_str, "%s", path);
1271         g_free (path);
1272 #else
1273 #define PATH_SEPARATOR ":"
1274         path = smiGetPath();
1275         g_string_append(path_str, "/usr/share/snmp/mibs");
1276         if (strlen(path) > 0 ) {
1277                 g_string_append(path_str, PATH_SEPARATOR);
1278         }
1279         g_string_append_printf(path_str, "%s", path);
1280         smi_free(path);
1281 #endif
1282
1283         for(i=0;i<num_smi_paths;i++) {
1284                 if (!( smi_paths[i].name && *smi_paths[i].name))
1285                         continue;
1286
1287                 g_string_append_printf(path_str,PATH_SEPARATOR "%s",smi_paths[i].name);
1288         }
1289
1290         return g_string_free(path_str, FALSE);
1291 #else /* HAVE_LIBSMI */
1292         return g_strdup("");
1293 #endif
1294 }
1295
1296 #ifdef DEBUG_OIDS
1297 char* oid_test_a2b(guint32 num_subids, guint32* subids) {
1298         guint8* sub2enc = NULL;
1299         guint8* str2enc = NULL;
1300         guint32* enc2sub = NULL;
1301         guint32* str2sub;
1302         char* ret;
1303         char* sub2str = oid_subid2string(NULL, subids, num_subids);
1304         guint sub2enc_len = oid_subid2encoded(NULL, num_subids, subids,&sub2enc);
1305         guint enc2sub_len = oid_encoded2subid(NULL, sub2enc, sub2enc_len, &enc2sub);
1306         char* enc2str = oid_encoded2string(NULL, sub2enc, sub2enc_len);
1307         guint str2enc_len = oid_string2encoded(NULL, sub2str,&str2enc);
1308         guint str2sub_len = oid_string2subid(sub2str,&str2sub);
1309
1310         ret = wmem_strdup_printf(wmem_packet_scope(),
1311                                                         "oid_subid2string=%s \n"
1312                                                         "oid_subid2encoded=[%d]%s \n"
1313                                                         "oid_encoded2subid=%s \n "
1314                                                         "oid_encoded2string=%s \n"
1315                                                         "oid_string2encoded=[%d]%s \n"
1316                                                         "oid_string2subid=%s \n "
1317                                                         ,sub2str
1318                                                         ,sub2enc_len,bytestring_to_str(wmem_packet_scope(), sub2enc, sub2enc_len, ':')
1319                                                         ,enc2sub ? oid_subid2string(wmem_packet_scope(), enc2sub,enc2sub_len) : "-"
1320                                                         ,enc2str
1321                                                         ,str2enc_len,bytestring_to_str(wmem_packet_scope(), str2enc, str2enc_len, ':')
1322                                                         ,str2sub ? oid_subid2string(wmem_packet_scope(), str2sub,str2sub_len) : "-"
1323                                                         );
1324
1325         wmem_free(NULL, sub2str);
1326         wmem_free(NULL, enc2sub);
1327         wmem_free(NULL, sub2enc);
1328         wmem_free(NULL, str2enc);
1329         wmem_free(NULL, enc2str);
1330         return ret;
1331 }
1332
1333 void add_oid_debug_subtree(oid_info_t* oid_info, proto_tree *tree) {
1334         static const char* oid_kinds[] = { "Unknown", "Node", "Scalar", "Table", "Row", "Column", "Notification", "Group", "Compliance", "Capabilities"};
1335         static const char* key_types[] = {"OID_KEY_TYPE_WRONG","OID_KEY_TYPE_INTEGER",
1336                                                                                 "OID_KEY_TYPE_FIXED_STRING","OID_KEY_TYPE_FIXED_BYTES","OID_KEY_TYPE_STRING",
1337                                                                                 "OID_KEY_TYPE_BYTES","OID_KEY_TYPE_NSAP","OID_KEY_TYPE_OID","OID_KEY_TYPE_IPADDR"};
1338         proto_item* pi = proto_tree_add_debug_text(tree,NULL,0,0,
1339         "OidInfo: Name='%s' sub-id=%u  kind=%s  hfid=%d",
1340         oid_info->name ? oid_info->name : "",
1341         oid_info->subid,
1342         oid_info->kind <= OID_KIND_CAPABILITIES ? oid_kinds[oid_info->kind] : "BROKEN",
1343         oid_info->value_hfid);
1344         proto_tree* pt = proto_item_add_subtree(pi,0);
1345         oid_key_t* key;
1346
1347         for(key = oid_info->key; key; key = key->next) {
1348                 proto_tree_add_debug_text(pt,NULL,0,0,
1349                 "Key: name='%s' num_subids=%d type=%s",
1350                 key->name,
1351                 key->key_type <= OID_KEY_TYPE_IPADDR ? key_types[key->key_type] : "BROKEN"
1352                 );
1353         };
1354
1355         if (oid_info->parent) {
1356                 pi = proto_tree_add_debug_text(pt,NULL,0,0,"Parent:");
1357                 pt = proto_item_add_subtree(pi,0);
1358                 add_oid_debug_subtree(oid_info->parent, pt);
1359         }
1360 }
1361 #endif
1362
1363 /*
1364  * Editor modelines
1365  *
1366  * Local Variables:
1367  * c-basic-offset: 8
1368  * tab-width: 8
1369  * indent-tabs-mode: t
1370  * End:
1371  *
1372  * ex: set shiftwidth=8 tabstop=8 noexpandtab:
1373  * :indentSize=8:tabSize=8:noTabs=false:
1374  */