Merge pull request #2702 from elfiesmelfie/feat_snmp_agent
[collectd.git] / src / snmp_agent.c
1 /**
2  * collectd - src/snmp_agent.c
3  *
4  * Copyright(c) 2017-2018 Intel Corporation. All rights reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  *
24  * Authors:
25  *   Roman Korynkevych <romanx.korynkevych@intel.com>
26  *   Serhiy Pshyk <serhiyx.pshyk@intel.com>
27  *   Marcin Mozejko <marcinx.mozejko@intel.com>
28  **/
29
30 #include "collectd.h"
31
32 #include "common.h"
33 #include "utils_avltree.h"
34 #include "utils_cache.h"
35 #include "utils_llist.h"
36 #include <regex.h>
37
38 #include <net-snmp/net-snmp-config.h>
39
40 #include <net-snmp/net-snmp-includes.h>
41
42 #include <net-snmp/agent/net-snmp-agent-includes.h>
43
44 #define PLUGIN_NAME "snmp_agent"
45 #define TYPE_STRING -1
46 #define GROUP_UNUSED -1
47 #define OID_EXISTS 1
48 #define MAX_KEY_SOURCES 5
49 #define MAX_INDEX_KEYS 5
50 #define MAX_MATCHES 5
51
52 /* Identifies index key source */
53 enum index_key_src_e {
54   INDEX_HOST = 0,
55   INDEX_PLUGIN,
56   INDEX_PLUGIN_INSTANCE,
57   INDEX_TYPE,
58   INDEX_TYPE_INSTANCE
59 };
60 typedef enum index_key_src_e index_key_src_t;
61
62 struct index_key_s {
63   index_key_src_t source;
64   u_char type;
65   char *regex; /* Pattern used to parse index key source string */
66   int group;   /* If pattern gives more than one group we can specify which one
67                   we want to take */
68   regex_t regex_info;
69 };
70 typedef struct index_key_s index_key_t;
71
72 struct oid_s {
73   oid oid[MAX_OID_LEN];
74   size_t oid_len;
75   u_char type;
76 };
77 typedef struct oid_s oid_t;
78
79 struct token_s {
80   char *str;
81   netsnmp_variable_list *key; /* Points to succeeding key */
82 };
83 typedef struct token_s token_t;
84
85 struct table_definition_s {
86   char *name;
87   oid_t index_oid;
88   oid_t size_oid;
89   llist_t *columns;
90   c_avl_tree_t *instance_index;
91   c_avl_tree_t *index_instance;
92   c_avl_tree_t *instance_oids; /* Tells us how many OIDs registered for every
93                                   instance; */
94   index_key_t index_keys[MAX_INDEX_KEYS]; /* Stores information about what each
95                                              index key represents */
96   int index_keys_len;
97   netsnmp_variable_list *index_list_cont; /* Index key container used for
98                                              generating as well as parsing
99                                              OIDs, not thread-safe */
100   c_avl_tree_t *tokens[MAX_KEY_SOURCES];  /* Input string after regex execution
101                                              will be split into sepearate
102                                              tokens */
103
104   bool tokens_done; /* Set to true when all tokens are generated */
105 };
106 typedef struct table_definition_s table_definition_t;
107
108 struct data_definition_s {
109   char *name;
110   char *plugin;
111   char *plugin_instance;
112   char *type;
113   char *type_instance;
114   const table_definition_t *table;
115   bool is_index_key; /* indicates if table column is an index key */
116   int index_key_pos; /* position in indexes list */
117   oid_t *oids;
118   size_t oids_len;
119   double scale;
120   double shift;
121 };
122 typedef struct data_definition_s data_definition_t;
123
124 struct snmp_agent_ctx_s {
125   pthread_t thread;
126   pthread_mutex_t lock;
127   pthread_mutex_t agentx_lock;
128   struct tree *tp;
129
130   llist_t *tables;
131   llist_t *scalars;
132   c_avl_tree_t *registered_oids; /* AVL tree containing all registered OIDs */
133 };
134 typedef struct snmp_agent_ctx_s snmp_agent_ctx_t;
135
136 static snmp_agent_ctx_t *g_agent;
137 static const char *index_opts[MAX_KEY_SOURCES] = {
138     "Hostname", "Plugin", "PluginInstance", "Type", "TypeInstance"};
139
140 #define CHECK_DD_TYPE(_dd, _p, _pi, _t, _ti)                                   \
141   (_dd->plugin ? !strcmp(_dd->plugin, _p) : 0) &&                              \
142       (_dd->plugin_instance ? !strcmp(_dd->plugin_instance, _pi) : 1) &&       \
143       (_dd->type ? !strcmp(_dd->type, _t) : 0) &&                              \
144       (_dd->type_instance ? !strcmp(_dd->type_instance, _ti) : 1)
145
146 static int snmp_agent_shutdown(void);
147 static void *snmp_agent_thread_run(void *arg);
148 static int snmp_agent_register_oid(oid_t *oid, Netsnmp_Node_Handler *handler);
149 static int snmp_agent_set_vardata(void *dst_buf, size_t *dst_buf_len,
150                                   u_char asn_type, double scale, double shift,
151                                   const void *value, size_t len, int type);
152 static int snmp_agent_unregister_oid_index(oid_t *oid, int index);
153 static int snmp_agent_update_instance_oids(c_avl_tree_t *tree, oid_t *index_oid,
154                                            int value);
155 static int num_compare(const int *a, const int *b);
156
157 static u_char snmp_agent_get_asn_type(oid *oid, size_t oid_len) {
158   struct tree *node = get_tree(oid, oid_len, g_agent->tp);
159
160   return (node != NULL) ? mib_to_asn_type(node->type) : 0;
161 }
162
163 static char *snmp_agent_get_oid_name(oid *oid, size_t oid_len) {
164   struct tree *node = get_tree(oid, oid_len, g_agent->tp);
165
166   return (node != NULL) ? node->label : NULL;
167 }
168
169 static int snmp_agent_oid_to_string(char *buf, size_t buf_size,
170                                     oid_t const *o) {
171   char oid_str[MAX_OID_LEN][16];
172   char *oid_str_ptr[MAX_OID_LEN];
173
174   for (size_t i = 0; i < o->oid_len; i++) {
175     snprintf(oid_str[i], sizeof(oid_str[i]), "%lu", (unsigned long)o->oid[i]);
176     oid_str_ptr[i] = oid_str[i];
177   }
178
179   return strjoin(buf, buf_size, oid_str_ptr, o->oid_len, ".");
180 }
181
182 /* Prints a configuration storing list. It handles both table columns list
183    and scalars list */
184 #if COLLECT_DEBUG
185 static void snmp_agent_dump_data(llist_t *list) {
186   char oid_str[DATA_MAX_NAME_LEN];
187   for (llentry_t *de = llist_head(list); de != NULL; de = de->next) {
188     data_definition_t *dd = de->value;
189     table_definition_t const *td = dd->table;
190
191     if (dd->table != NULL)
192       DEBUG(PLUGIN_NAME ":   Column:");
193     else
194       DEBUG(PLUGIN_NAME ": Scalar:");
195
196     DEBUG(PLUGIN_NAME ":     Name: %s", dd->name);
197     if (dd->plugin)
198       DEBUG(PLUGIN_NAME ":     Plugin: %s", dd->plugin);
199     if (dd->plugin_instance)
200       DEBUG(PLUGIN_NAME ":     PluginInstance: %s", dd->plugin_instance);
201     if (dd->is_index_key) {
202       index_key_t const *index_key = &td->index_keys[dd->index_key_pos];
203
204       DEBUG(PLUGIN_NAME ":     IndexKey:");
205       DEBUG(PLUGIN_NAME ":       Source: %s", index_opts[index_key->source]);
206       DEBUG(PLUGIN_NAME ":       Type: %s",
207             (index_key->type == ASN_INTEGER) ? "Integer" : "String");
208       if (index_key->regex)
209         DEBUG(PLUGIN_NAME ":       Regex: %s", index_key->regex);
210       if (index_key->group != GROUP_UNUSED)
211         DEBUG(PLUGIN_NAME ":       Group: %d", index_key->group);
212     }
213     if (dd->type)
214       DEBUG(PLUGIN_NAME ":     Type: %s", dd->type);
215     if (dd->type_instance)
216       DEBUG(PLUGIN_NAME ":     TypeInstance: %s", dd->type_instance);
217     for (size_t i = 0; i < dd->oids_len; i++) {
218       snmp_agent_oid_to_string(oid_str, sizeof(oid_str), &dd->oids[i]);
219       DEBUG(PLUGIN_NAME ":     OID[%" PRIsz "]: %s", i, oid_str);
220     }
221     DEBUG(PLUGIN_NAME ":   Scale: %g", dd->scale);
222     DEBUG(PLUGIN_NAME ":   Shift: %g", dd->shift);
223   }
224 }
225
226 /* Prints parsed configuration */
227 static void snmp_agent_dump_config(void) {
228   char oid_str[DATA_MAX_NAME_LEN];
229
230   /* Printing tables */
231   for (llentry_t *te = llist_head(g_agent->tables); te != NULL; te = te->next) {
232     table_definition_t *td = te->value;
233
234     DEBUG(PLUGIN_NAME ": Table:");
235     DEBUG(PLUGIN_NAME ":   Name: %s", td->name);
236     if (td->index_oid.oid_len != 0) {
237       snmp_agent_oid_to_string(oid_str, sizeof(oid_str), &td->index_oid);
238       DEBUG(PLUGIN_NAME ":   IndexOID: %s", oid_str);
239     }
240     if (td->size_oid.oid_len != 0) {
241       snmp_agent_oid_to_string(oid_str, sizeof(oid_str), &td->size_oid);
242       DEBUG(PLUGIN_NAME ":   SizeOID: %s", oid_str);
243     }
244
245     snmp_agent_dump_data(td->columns);
246   }
247
248   /* Printing scalars */
249   snmp_agent_dump_data(g_agent->scalars);
250 }
251 #endif /* COLLECT_DEBUG */
252
253 static int snmp_agent_validate_config(void) {
254
255 #if COLLECT_DEBUG
256   snmp_agent_dump_config();
257 #endif
258
259   for (llentry_t *te = llist_head(g_agent->tables); te != NULL; te = te->next) {
260     table_definition_t *td = te->value;
261
262     if (!td->index_keys_len) {
263       ERROR(PLUGIN_NAME ": Index keys not defined for '%s'", td->name);
264       return -EINVAL;
265     }
266
267     for (llentry_t *de = llist_head(td->columns); de != NULL; de = de->next) {
268       data_definition_t *dd = de->value;
269
270       if (!dd->plugin) {
271         ERROR(PLUGIN_NAME ": Plugin not defined for '%s'.'%s'", td->name,
272               dd->name);
273         return -EINVAL;
274       }
275
276       if (dd->plugin_instance) {
277         ERROR(PLUGIN_NAME ": PluginInstance should not be defined for table "
278                           "data type '%s'.'%s'",
279               td->name, dd->name);
280         return -EINVAL;
281       }
282
283       if (dd->oids_len == 0) {
284         ERROR(PLUGIN_NAME ": No OIDs defined for '%s'.'%s'", td->name,
285               dd->name);
286         return -EINVAL;
287       }
288
289       if (dd->is_index_key) {
290         if (dd->type || dd->type_instance) {
291           ERROR(PLUGIN_NAME ": Type and TypeInstance are not valid for "
292                             "index data '%s'.'%s'",
293                 td->name, dd->name);
294           return -EINVAL;
295         }
296
297         if (dd->oids_len > 1) {
298           ERROR(
299               PLUGIN_NAME
300               ": Only one OID should be specified for instance data '%s'.'%s'",
301               td->name, dd->name);
302           return -EINVAL;
303         }
304       } else {
305
306         if (!dd->type) {
307           ERROR(PLUGIN_NAME ": Type not defined for data '%s'.'%s'", td->name,
308                 dd->name);
309           return -EINVAL;
310         }
311       }
312     }
313   }
314
315   for (llentry_t *e = llist_head(g_agent->scalars); e != NULL; e = e->next) {
316     data_definition_t *dd = e->value;
317
318     if (!dd->plugin) {
319       ERROR(PLUGIN_NAME ": Plugin not defined for '%s'", dd->name);
320       return -EINVAL;
321     }
322
323     if (dd->oids_len == 0) {
324       ERROR(PLUGIN_NAME ": No OIDs defined for '%s'", dd->name);
325       return -EINVAL;
326     }
327
328     if (dd->is_index_key) {
329       ERROR(PLUGIN_NAME ": Index field can't be specified for scalar data '%s'",
330             dd->name);
331       return -EINVAL;
332     }
333
334     if (!dd->type) {
335       ERROR(PLUGIN_NAME ": Type not defined for data '%s'", dd->name);
336       return -EINVAL;
337     }
338   }
339
340   return 0;
341 }
342
343 static int snmp_agent_parse_index_key(const char *input, regex_t *regex_info,
344                                       int gi, regmatch_t *m) {
345   regmatch_t matches[MAX_MATCHES];
346
347   int ret = regexec(regex_info, input, MAX_MATCHES, matches, 0);
348   if (!ret) {
349     if (gi > regex_info->re_nsub) {
350       ERROR(PLUGIN_NAME ": Group index %d not found. Check regex config", gi);
351       return -1;
352     }
353     *m = matches[gi];
354   } else if (ret == REG_NOMATCH) {
355     ERROR(PLUGIN_NAME ": No match found");
356     return -1;
357   } else {
358     char msgbuf[100];
359
360     regerror(ret, regex_info, msgbuf, sizeof(msgbuf));
361     ERROR(PLUGIN_NAME ": Regex match failed: %s", msgbuf);
362     return -1;
363   }
364
365   return 0;
366 }
367
368 static int snmp_agent_create_token(char const *input, int t_off, int n,
369                                    c_avl_tree_t *tree,
370                                    netsnmp_variable_list *index_key) {
371   assert(tree != NULL);
372
373   token_t *token = malloc(sizeof(*token));
374
375   if (token == NULL)
376     goto error;
377
378   int *offset = malloc(sizeof(*offset));
379
380   if (offset == NULL)
381     goto free_token_error;
382
383   int ret = 0;
384
385   token->key = index_key;
386   token->str = strndup(input + t_off, n);
387
388   if (token->str == NULL)
389     goto free_offset_error;
390
391   *offset = t_off;
392   ret = c_avl_insert(tree, (void *)offset, (void *)token);
393
394   if (ret == 0)
395     return 0;
396
397   sfree(token->str);
398
399 free_offset_error:
400   sfree(offset);
401
402 free_token_error:
403   sfree(token);
404
405 error:
406   ERROR(PLUGIN_NAME ": Could not allocate memory to create token");
407
408   return -1;
409 }
410
411 static int snmp_agent_delete_token(int t_off, c_avl_tree_t *tree) {
412   token_t *token = NULL;
413   int *offset = NULL;
414
415   int ret = c_avl_remove(tree, &t_off, (void **)&offset, (void **)&token);
416
417   if (ret != 0) {
418     ERROR(PLUGIN_NAME ": Could not delete token");
419     return -1;
420   }
421
422   sfree(token->str);
423   sfree(token);
424   sfree(offset);
425   return 0;
426 }
427
428 static int snmp_agent_get_token(c_avl_tree_t *tree, int mpos) {
429
430   int *pos;
431   char *token;
432   int prev_pos = 0;
433
434   c_avl_iterator_t *it = c_avl_get_iterator(tree);
435   while (c_avl_iterator_next(it, (void **)&pos, (void **)&token) == 0) {
436     if (*pos >= mpos)
437       break;
438     else
439       prev_pos = *pos;
440   }
441
442   c_avl_iterator_destroy(it);
443   return prev_pos;
444 }
445
446 static int snmp_agent_tokenize(const char *input, c_avl_tree_t *tokens,
447                                const regmatch_t *m,
448                                netsnmp_variable_list *key) {
449   assert(tokens != NULL);
450
451   int ret = 0;
452   int len = strlen(input);
453
454   /* Creating first token that is going to be split later */
455   if (c_avl_size(tokens) == 0) {
456     ret = snmp_agent_create_token(input, 0, len, tokens, NULL);
457     if (ret != 0)
458       return ret;
459   }
460
461   /* Divide token that contains current match into two */
462   int t_pos = snmp_agent_get_token(tokens, m->rm_so);
463   ret = snmp_agent_delete_token(t_pos, tokens);
464
465   if (ret != 0)
466     return -1;
467
468   ret = snmp_agent_create_token(input, t_pos, m->rm_so - t_pos, tokens, key);
469
470   if (ret != 0)
471     return -1;
472
473   if (len - m->rm_eo > 1) {
474     ret = snmp_agent_create_token(input, m->rm_eo, len - m->rm_eo + 1, tokens,
475                                   NULL);
476     if (ret != 0) {
477       snmp_agent_delete_token(t_pos, tokens);
478       return -1;
479     }
480   }
481
482   return 0;
483 }
484
485 static int snmp_agent_fill_index_list(table_definition_t *td,
486                                       value_list_t const *vl) {
487   int ret;
488   int i;
489   netsnmp_variable_list *key = td->index_list_cont;
490   char const *ptr;
491
492   for (i = 0; i < td->index_keys_len; i++) {
493     /* var should never be NULL */
494     assert(key != NULL);
495     ptr = NULL;
496     ret = 0;
497     const index_key_src_t source = td->index_keys[i].source;
498     c_avl_tree_t *const tokens = td->tokens[source];
499     /* Generating list filled with all data necessary to generate an OID */
500     switch (source) {
501     case INDEX_HOST:
502       ptr = vl->host;
503       break;
504     case INDEX_PLUGIN:
505       ptr = vl->plugin;
506       break;
507     case INDEX_PLUGIN_INSTANCE:
508       ptr = vl->plugin_instance;
509       break;
510     case INDEX_TYPE:
511       ptr = vl->type;
512       break;
513     case INDEX_TYPE_INSTANCE:
514       ptr = vl->type_instance;
515       break;
516     default:
517       ERROR(PLUGIN_NAME ": Unknown index key source provided");
518       return -EINVAL;
519     }
520     if (ret != 0)
521       return -EINVAL;
522
523     /* Parsing input string if necessary */
524     if (td->index_keys[i].regex) {
525       regmatch_t m = {-1, -1};
526
527       /* Parsing input string */
528       ret = snmp_agent_parse_index_key(ptr, &td->index_keys[i].regex_info,
529                                        td->index_keys[i].group, &m);
530       if (ret != 0) {
531         ERROR(PLUGIN_NAME ": Error executing regex");
532         return ret;
533       }
534
535       /* Tokenizing input string if not done yet */
536       if (td->tokens_done == false)
537         ret = snmp_agent_tokenize(ptr, tokens, &m, key);
538
539       if (ret != 0)
540         return -1;
541
542       if (td->index_keys[i].type == ASN_INTEGER) {
543         int val = strtol(ptr + m.rm_so, NULL, 0);
544
545 #ifdef HAVE_NETSNMP_OLD_API
546         ret = snmp_set_var_value(key, (const u_char *)&val, sizeof(val));
547 #else
548         ret = snmp_set_var_value(key, &val, sizeof(val));
549 #endif
550       } else
551 #ifdef HAVE_NETSNMP_OLD_API
552         ret = snmp_set_var_value(key, (const u_char *)(ptr + m.rm_so),
553                                  m.rm_eo - m.rm_so);
554 #else
555         ret = snmp_set_var_value(key, ptr + m.rm_so, m.rm_eo - m.rm_so);
556 #endif
557     } else
558 #ifdef HAVE_NETSNMP_OLD_API
559       ret = snmp_set_var_value(key, (const u_char *)ptr, strlen(ptr));
560 #else
561       ret = snmp_set_var_value(key, ptr, strlen(ptr));
562 #endif
563     key = key->next_variable;
564   }
565
566   /* Tokens for all source strings are generated */
567   for (i = 0; i < MAX_KEY_SOURCES; i++)
568     td->tokens_done = true;
569
570   return 0;
571 }
572
573 static int snmp_agent_prep_index_list(table_definition_t const *td,
574                                       netsnmp_variable_list **index_list) {
575   /* Generating list having only the structure (with no values) letting us
576    * know how to parse an OID*/
577   for (int i = 0; i < td->index_keys_len; i++) {
578     switch (td->index_keys[i].source) {
579     case INDEX_HOST:
580     case INDEX_PLUGIN:
581     case INDEX_PLUGIN_INSTANCE:
582     case INDEX_TYPE:
583     case INDEX_TYPE_INSTANCE:
584       snmp_varlist_add_variable(index_list, NULL, 0, td->index_keys[i].type,
585                                 NULL, 0);
586       break;
587     default:
588       ERROR(PLUGIN_NAME ": Unknown index key source provided");
589       return -EINVAL;
590     }
591   }
592   return 0;
593 }
594
595 static int snmp_agent_generate_index(table_definition_t *td,
596                                      value_list_t const *vl, oid_t *index_oid) {
597
598   /* According to given information by index_keys list
599    * index OID is going to be built
600    */
601   int ret = snmp_agent_fill_index_list(td, vl);
602   if (ret != 0)
603     return -EINVAL;
604
605   /* Building only index part OID (without table prefix OID) */
606   ret = build_oid_noalloc(index_oid->oid, sizeof(index_oid->oid),
607                           &index_oid->oid_len, NULL, 0, td->index_list_cont);
608   if (ret != SNMPERR_SUCCESS) {
609     ERROR(PLUGIN_NAME ": Error building index OID");
610     return -EINVAL;
611   }
612
613   return 0;
614 }
615
616 /* It appends one OID to the end of another */
617 static int snmp_agent_append_oid(oid_t *out, const oid_t *in) {
618
619   if (out->oid_len + in->oid_len > MAX_OID_LEN) {
620     ERROR(PLUGIN_NAME ": Cannot create OID. Output length is too long!");
621     return -EINVAL;
622   }
623   memcpy(&out->oid[out->oid_len], in->oid, in->oid_len * sizeof(oid));
624   out->oid_len += in->oid_len;
625
626   return 0;
627 }
628
629 static int snmp_agent_register_oid_string(const oid_t *oid,
630                                           const oid_t *index_oid,
631                                           Netsnmp_Node_Handler *handler) {
632   oid_t new_oid;
633
634   memcpy(&new_oid, oid, sizeof(*oid));
635   /* Concatenating two string oids */
636   int ret = snmp_agent_append_oid(&new_oid, index_oid);
637   if (ret != 0)
638     return ret;
639
640   return snmp_agent_register_oid(&new_oid, handler);
641 }
642
643 static int snmp_agent_unregister_oid(oid_t *oid) {
644   int ret = c_avl_remove(g_agent->registered_oids, (void *)oid, NULL, NULL);
645
646   if (ret != 0)
647     ERROR(PLUGIN_NAME ": Could not delete registration info");
648
649   return unregister_mib(oid->oid, oid->oid_len);
650 }
651
652 static int snmp_agent_unregister_oid_string(oid_t *oid,
653                                             const oid_t *index_oid) {
654   oid_t new_oid;
655   char oid_str[DATA_MAX_NAME_LEN];
656
657   memcpy(&new_oid, oid, sizeof(*oid));
658   /* Concatenating two string oids */
659   int ret = snmp_agent_append_oid(&new_oid, index_oid);
660   if (ret != 0)
661     return ret;
662
663   snmp_agent_oid_to_string(oid_str, sizeof(oid_str), &new_oid);
664   DEBUG(PLUGIN_NAME ": Unregistered handler for OID (%s)", oid_str);
665
666   return snmp_agent_unregister_oid(&new_oid);
667 }
668
669 static void snmp_agent_table_data_remove(data_definition_t *dd,
670                                          table_definition_t *td,
671                                          oid_t *index_oid) {
672   int *index = NULL;
673   oid_t *ind_oid = NULL;
674
675   if (td->index_oid.oid_len) {
676     if ((c_avl_get(td->instance_index, index_oid, (void **)&index) != 0) ||
677         (c_avl_get(td->index_instance, index, NULL) != 0))
678       return;
679   } else {
680     if (c_avl_get(td->instance_index, index_oid, NULL) != 0)
681       return;
682   }
683
684   pthread_mutex_lock(&g_agent->agentx_lock);
685
686   int reg_oids = -1; /* Number of registered oids for given instance */
687
688   for (size_t i = 0; i < dd->oids_len; i++) {
689     if (td->index_oid.oid_len)
690       snmp_agent_unregister_oid_index(&dd->oids[i], *index);
691     else
692       snmp_agent_unregister_oid_string(&dd->oids[i], index_oid);
693
694     reg_oids =
695         snmp_agent_update_instance_oids(td->instance_oids, index_oid, -1);
696   }
697
698   /* Checking if any metrics are left registered */
699   if (reg_oids != 0) {
700     pthread_mutex_unlock(&g_agent->agentx_lock);
701     return;
702   }
703
704   /* All metrics have been unregistered. Unregistering index key OIDs */
705   int keys_processed = 0;
706   for (llentry_t *de = llist_head(td->columns); de != NULL; de = de->next) {
707     data_definition_t *idd = de->value;
708
709     if (!idd->is_index_key)
710       continue;
711
712     for (size_t i = 0; i < idd->oids_len; i++)
713       if (td->index_oid.oid_len)
714         snmp_agent_unregister_oid_index(&idd->oids[i], *index);
715       else
716         snmp_agent_unregister_oid_string(&idd->oids[i], index_oid);
717
718     if (++keys_processed >= td->index_keys_len)
719       break;
720   }
721   pthread_mutex_unlock(&g_agent->agentx_lock);
722
723   /* All OIDs have been unregistered so we dont need this instance registered
724    * as well */
725   char index_str[DATA_MAX_NAME_LEN];
726
727   if (index == NULL)
728     snmp_agent_oid_to_string(index_str, sizeof(index_str), index_oid);
729   else
730     snprintf(index_str, sizeof(index_str), "%d", *index);
731
732   notification_t n = {
733       .severity = NOTIF_WARNING, .time = cdtime(), .plugin = PLUGIN_NAME};
734   sstrncpy(n.host, hostname_g, sizeof(n.host));
735   snprintf(n.message, sizeof(n.message),
736            "Removed data row from table %s with index %s", td->name, index_str);
737   DEBUG(PLUGIN_NAME ": %s", n.message);
738   plugin_dispatch_notification(&n);
739
740   int *val = NULL;
741
742   c_avl_remove(td->instance_oids, index_oid, NULL, (void **)&val);
743   sfree(val);
744
745   if (index != NULL) {
746     pthread_mutex_lock(&g_agent->agentx_lock);
747     snmp_agent_unregister_oid_index(&td->index_oid, *index);
748     pthread_mutex_unlock(&g_agent->agentx_lock);
749
750     c_avl_remove(td->index_instance, index, NULL, (void **)&ind_oid);
751     c_avl_remove(td->instance_index, index_oid, NULL, (void **)&index);
752     sfree(index);
753     sfree(ind_oid);
754   } else {
755     c_avl_remove(td->instance_index, index_oid, NULL, NULL);
756   }
757 }
758
759 static int snmp_agent_clear_missing(const value_list_t *vl,
760                                     __attribute__((unused)) user_data_t *ud) {
761   if (vl == NULL)
762     return -EINVAL;
763
764   for (llentry_t *te = llist_head(g_agent->tables); te != NULL; te = te->next) {
765     table_definition_t *td = te->value;
766
767     for (llentry_t *de = llist_head(td->columns); de != NULL; de = de->next) {
768       data_definition_t *dd = de->value;
769
770       if (!dd->is_index_key) {
771         if (CHECK_DD_TYPE(dd, vl->plugin, vl->plugin_instance, vl->type,
772                           vl->type_instance)) {
773           oid_t *index_oid = calloc(1, sizeof(*index_oid));
774
775           if (index_oid == NULL) {
776             ERROR(PLUGIN_NAME ": Could not allocate memory for index_oid");
777             return -ENOMEM;
778           }
779
780           int ret = snmp_agent_generate_index(td, vl, index_oid);
781
782           if (ret == 0)
783             snmp_agent_table_data_remove(dd, td, index_oid);
784           sfree(index_oid);
785
786           return ret;
787         }
788       }
789     }
790   }
791
792   return 0;
793 }
794
795 static void snmp_agent_free_data(data_definition_t **dd) {
796
797   if (dd == NULL || *dd == NULL)
798     return;
799
800   /* unregister scalar type OID */
801   if ((*dd)->table == NULL) {
802     for (size_t i = 0; i < (*dd)->oids_len; i++)
803       unregister_mib((*dd)->oids[i].oid, (*dd)->oids[i].oid_len);
804   }
805
806   sfree((*dd)->name);
807   sfree((*dd)->plugin);
808   sfree((*dd)->plugin_instance);
809   sfree((*dd)->type);
810   sfree((*dd)->type_instance);
811   sfree((*dd)->oids);
812
813   sfree(*dd);
814
815   return;
816 }
817
818 static void snmp_agent_free_table_columns(table_definition_t *td) {
819   if (td->columns == NULL)
820     return;
821
822   for (llentry_t *de = llist_head(td->columns); de != NULL; de = de->next) {
823     data_definition_t *dd = de->value;
824
825     if (td->index_oid.oid_len) {
826       int *index;
827       oid_t *index_oid;
828
829       c_avl_iterator_t *iter = c_avl_get_iterator(td->index_instance);
830       while (c_avl_iterator_next(iter, (void *)&index, (void *)&index_oid) ==
831              0) {
832         for (size_t i = 0; i < dd->oids_len; i++)
833           snmp_agent_unregister_oid_index(&dd->oids[i], *index);
834       }
835       c_avl_iterator_destroy(iter);
836     } else {
837       oid_t *index_oid;
838
839       c_avl_iterator_t *iter = c_avl_get_iterator(dd->table->instance_index);
840       while (c_avl_iterator_next(iter, (void *)&index_oid, NULL) == 0) {
841         for (size_t i = 0; i < dd->oids_len; i++)
842           snmp_agent_unregister_oid_string(&dd->oids[i], index_oid);
843       }
844       c_avl_iterator_destroy(iter);
845     }
846
847     snmp_agent_free_data(&dd);
848   }
849
850   llist_destroy(td->columns);
851   td->columns = NULL;
852 } /* void snmp_agent_free_table_columns */
853
854 static void snmp_agent_free_table(table_definition_t **td) {
855
856   if (td == NULL || *td == NULL)
857     return;
858
859   if ((*td)->size_oid.oid_len)
860     unregister_mib((*td)->size_oid.oid, (*td)->size_oid.oid_len);
861
862   oid_t *index_oid;
863
864   /* Unregister Index OIDs */
865   if ((*td)->index_oid.oid_len) {
866     int *index;
867
868     c_avl_iterator_t *iter = c_avl_get_iterator((*td)->index_instance);
869     while (c_avl_iterator_next(iter, (void **)&index, (void **)&index_oid) == 0)
870       snmp_agent_unregister_oid_index(&(*td)->index_oid, *index);
871
872     c_avl_iterator_destroy(iter);
873   }
874
875   /* Unregister all table columns and their registered OIDs */
876   snmp_agent_free_table_columns(*td);
877
878   void *key = NULL;
879   void *value = NULL;
880   int *num = NULL;
881
882   /* Removing data from instance_oids, leaving key pointers since they are still
883    * used in other AVL trees */
884   c_avl_iterator_t *iter = c_avl_get_iterator((*td)->instance_oids);
885   while (c_avl_iterator_next(iter, (void **)&index_oid, (void **)&num) == 0)
886     sfree(num);
887   c_avl_iterator_destroy(iter);
888   c_avl_destroy((*td)->instance_oids);
889
890   /* index_instance and instance_index contain the same pointers */
891   c_avl_destroy((*td)->index_instance);
892   (*td)->index_instance = NULL;
893
894   if ((*td)->instance_index != NULL) {
895     while (c_avl_pick((*td)->instance_index, &key, &value) == 0) {
896       if (key != value)
897         sfree(key);
898       sfree(value);
899     }
900     c_avl_destroy((*td)->instance_index);
901     (*td)->instance_index = NULL;
902   }
903   snmp_free_varbind((*td)->index_list_cont);
904
905   int i;
906   token_t *tok = NULL;
907
908   for (i = 0; i < (*td)->index_keys_len; i++) {
909     sfree((*td)->index_keys[i].regex);
910     regfree(&(*td)->index_keys[i].regex_info);
911   }
912   for (i = 0; i < MAX_KEY_SOURCES; i++)
913     if ((*td)->tokens[i] != NULL) {
914       while (c_avl_pick((*td)->tokens[i], &key, (void **)&tok) == 0) {
915         sfree(key);
916         sfree(tok->str);
917         sfree(tok);
918       }
919       c_avl_destroy((*td)->tokens[i]);
920       (*td)->tokens[i] = NULL;
921     }
922   sfree((*td)->name);
923   sfree(*td);
924
925   return;
926 }
927
928 static int snmp_agent_parse_oid_index_keys(const table_definition_t *td,
929                                            oid_t *index_oid) {
930   int ret = parse_oid_indexes(index_oid->oid, index_oid->oid_len,
931                               td->index_list_cont);
932   if (ret != SNMPERR_SUCCESS)
933     ERROR(PLUGIN_NAME ": index OID parse error!");
934   return ret;
935 }
936
937 static int snmp_agent_build_name(char **name, c_avl_tree_t *tokens) {
938
939   int *pos;
940   token_t *tok;
941   char str[DATA_MAX_NAME_LEN];
942   char out[DATA_MAX_NAME_LEN] = {0};
943   c_avl_iterator_t *it = c_avl_get_iterator(tokens);
944
945   if (it == NULL) {
946     ERROR(PLUGIN_NAME ": Error getting tokens list iterator");
947     return -1;
948   }
949
950   while (c_avl_iterator_next(it, (void **)&pos, (void **)&tok) == 0) {
951     strncat(out, tok->str, strlen(tok->str));
952     if (tok->key != NULL) {
953       if (tok->key->type == ASN_INTEGER) {
954         snprintf(str, sizeof(str), "%ld", *tok->key->val.integer);
955         strncat(out, str, strlen(str));
956       } else { /* OCTET_STR */
957         strncat(out, (char *)tok->key->val.string,
958                 strlen((char *)tok->key->val.string));
959       }
960     }
961   }
962   *name = strdup(out);
963   c_avl_iterator_destroy(it);
964
965   if (*name == NULL) {
966     ERROR(PLUGIN_NAME ": Could not allocate memory");
967     return -ENOMEM;
968   }
969
970   return 0;
971 }
972
973 static int snmp_agent_format_name(char *name, int name_len,
974                                   data_definition_t *dd, oid_t *index_oid) {
975
976   int ret = 0;
977
978   if (index_oid == NULL) {
979     /* It's a scalar */
980     format_name(name, name_len, hostname_g, dd->plugin, dd->plugin_instance,
981                 dd->type, dd->type_instance);
982   } else {
983     /* Need to parse string index OID */
984     const table_definition_t *td = dd->table;
985     ret = snmp_agent_parse_oid_index_keys(td, index_oid);
986     if (ret != 0)
987       return ret;
988
989     int i = 0;
990     netsnmp_variable_list *key = td->index_list_cont;
991     char str[DATA_MAX_NAME_LEN];
992     char *fields[MAX_KEY_SOURCES] = {hostname_g, dd->plugin,
993                                      dd->plugin_instance, dd->type,
994                                      dd->type_instance};
995
996     /* Looking for simple keys only */
997     while (key != NULL) {
998       if (!td->index_keys[i].regex) {
999         index_key_src_t source = td->index_keys[i].source;
1000
1001         if (source < INDEX_HOST || source > INDEX_TYPE_INSTANCE) {
1002           ERROR(PLUGIN_NAME ": Unkown index key source!");
1003           return -EINVAL;
1004         }
1005
1006         if (td->index_keys[i].type == ASN_INTEGER) {
1007           snprintf(str, sizeof(str), "%ld", *key->val.integer);
1008           fields[source] = str;
1009         } else /* OCTET_STR */
1010           fields[source] = (char *)key->val.string;
1011       }
1012       key = key->next_variable;
1013       i++;
1014     }
1015
1016     /* Keys with regexes */
1017     for (i = 0; i < MAX_KEY_SOURCES; i++) {
1018       if (td->tokens[i] == NULL)
1019         continue;
1020       ret = snmp_agent_build_name(&fields[i], td->tokens[i]);
1021       if (ret != 0)
1022         return ret;
1023     }
1024     format_name(name, name_len, fields[INDEX_HOST], fields[INDEX_PLUGIN],
1025                 fields[INDEX_PLUGIN_INSTANCE], fields[INDEX_TYPE],
1026                 fields[INDEX_TYPE_INSTANCE]);
1027     for (i = 0; i < MAX_KEY_SOURCES; i++) {
1028       if (td->tokens[i])
1029         sfree(fields[i]);
1030     }
1031   }
1032
1033   return 0;
1034 }
1035
1036 static int snmp_agent_form_reply(struct netsnmp_request_info_s *requests,
1037                                  data_definition_t *dd, oid_t *index_oid,
1038                                  int oid_index) {
1039   int ret;
1040
1041   if (dd->is_index_key) {
1042     const table_definition_t *td = dd->table;
1043     int ret = snmp_agent_parse_oid_index_keys(td, index_oid);
1044
1045     if (ret != 0)
1046       return ret;
1047
1048     netsnmp_variable_list *key = td->index_list_cont;
1049     /* Searching index key */
1050     for (int pos = 0; pos < dd->index_key_pos; pos++)
1051       key = key->next_variable;
1052
1053     requests->requestvb->type = td->index_keys[dd->index_key_pos].type;
1054
1055     if (requests->requestvb->type == ASN_INTEGER)
1056 #ifdef HAVE_NETSNMP_OLD_API
1057       snmp_set_var_typed_value(requests->requestvb, requests->requestvb->type,
1058                                (const u_char *)key->val.integer,
1059                                sizeof(*key->val.integer));
1060 #else
1061       snmp_set_var_typed_value(requests->requestvb, requests->requestvb->type,
1062                                key->val.integer, sizeof(*key->val.integer));
1063 #endif
1064     else /* OCTET_STR */
1065 #ifdef HAVE_NETSNMP_OLD_API
1066       snmp_set_var_typed_value(requests->requestvb, requests->requestvb->type,
1067                                (const u_char *)key->val.string,
1068                                strlen((const char *)key->val.string));
1069 #else
1070       snmp_set_var_typed_value(requests->requestvb, requests->requestvb->type,
1071                                key->val.string,
1072                                strlen((const char *)key->val.string));
1073 #endif
1074
1075     pthread_mutex_unlock(&g_agent->lock);
1076
1077     return SNMP_ERR_NOERROR;
1078   }
1079
1080   char name[DATA_MAX_NAME_LEN];
1081
1082   ret = snmp_agent_format_name(name, sizeof(name), dd, index_oid);
1083   if (ret != 0)
1084     return ret;
1085
1086   DEBUG(PLUGIN_NAME ": Identifier '%s'", name);
1087
1088   value_t *values;
1089   size_t values_num;
1090   const data_set_t *ds = plugin_get_ds(dd->type);
1091   if (ds == NULL) {
1092     ERROR(PLUGIN_NAME ": Data set not found for '%s' type", dd->type);
1093     return SNMP_NOSUCHINSTANCE;
1094   }
1095
1096   ret = uc_get_value_by_name(name, &values, &values_num);
1097
1098   if (ret != 0) {
1099     ERROR(PLUGIN_NAME ": Failed to get value for '%s'", name);
1100     return SNMP_NOSUCHINSTANCE;
1101   }
1102
1103   assert(ds->ds_num == values_num);
1104   assert(oid_index < (int)values_num);
1105
1106   char data[DATA_MAX_NAME_LEN];
1107   size_t data_len = sizeof(data);
1108   ret = snmp_agent_set_vardata(
1109       data, &data_len, dd->oids[oid_index].type, dd->scale, dd->shift,
1110       &values[oid_index], sizeof(values[oid_index]), ds->ds[oid_index].type);
1111
1112   sfree(values);
1113
1114   if (ret != 0) {
1115     ERROR(PLUGIN_NAME ": Failed to convert '%s' value to snmp data", name);
1116     return SNMP_NOSUCHINSTANCE;
1117   }
1118
1119   requests->requestvb->type = dd->oids[oid_index].type;
1120   snmp_set_var_typed_value(requests->requestvb, requests->requestvb->type,
1121                            (const u_char *)data, data_len);
1122
1123   return SNMP_ERR_NOERROR;
1124 }
1125
1126 static int
1127 snmp_agent_table_oid_handler(struct netsnmp_mib_handler_s *handler,
1128                              struct netsnmp_handler_registration_s *reginfo,
1129                              struct netsnmp_agent_request_info_s *reqinfo,
1130                              struct netsnmp_request_info_s *requests) {
1131
1132   if (reqinfo->mode != MODE_GET) {
1133     DEBUG(PLUGIN_NAME ": Not supported request mode (%d)", reqinfo->mode);
1134     return SNMP_ERR_NOERROR;
1135   }
1136
1137   pthread_mutex_lock(&g_agent->lock);
1138
1139   oid_t oid; /* Requested OID */
1140   memcpy(oid.oid, requests->requestvb->name,
1141          sizeof(oid.oid[0]) * requests->requestvb->name_length);
1142   oid.oid_len = requests->requestvb->name_length;
1143
1144 #if COLLECT_DEBUG
1145   char oid_str[DATA_MAX_NAME_LEN];
1146   snmp_agent_oid_to_string(oid_str, sizeof(oid_str), &oid);
1147   DEBUG(PLUGIN_NAME ": Get request received for table OID '%s'", oid_str);
1148 #endif
1149   oid_t index_oid; /* Index part of requested OID */
1150
1151   for (llentry_t *te = llist_head(g_agent->tables); te != NULL; te = te->next) {
1152     table_definition_t *td = te->value;
1153
1154     for (llentry_t *de = llist_head(td->columns); de != NULL; de = de->next) {
1155       data_definition_t *dd = de->value;
1156
1157       for (size_t i = 0; i < dd->oids_len; i++) {
1158         int ret = snmp_oid_ncompare(oid.oid, oid.oid_len, dd->oids[i].oid,
1159                                     dd->oids[i].oid_len,
1160                                     SNMP_MIN(oid.oid_len, dd->oids[i].oid_len));
1161         if (ret != 0)
1162           continue;
1163
1164         /* Calculating OID length for index part */
1165         index_oid.oid_len = oid.oid_len - dd->oids[i].oid_len;
1166         /* Fetching index part of the OID */
1167         memcpy(index_oid.oid, &oid.oid[dd->oids[i].oid_len],
1168                index_oid.oid_len * sizeof(*oid.oid));
1169
1170         char index_str[DATA_MAX_NAME_LEN];
1171         snmp_agent_oid_to_string(index_str, sizeof(index_str), &index_oid);
1172
1173         if (!td->index_oid.oid_len) {
1174           ret = c_avl_get(td->instance_index, &index_oid, NULL);
1175         } else {
1176           oid_t *temp_oid;
1177
1178           assert(index_oid.oid_len == 1);
1179           ret = c_avl_get(td->index_instance, (int *)&index_oid.oid[0],
1180                           (void **)&temp_oid);
1181           memcpy(&index_oid, temp_oid, sizeof(index_oid));
1182         }
1183
1184         if (ret != 0) {
1185           INFO(PLUGIN_NAME ": Non-existing index (%s) requested", index_str);
1186           pthread_mutex_unlock(&g_agent->lock);
1187           return SNMP_NOSUCHINSTANCE;
1188         }
1189
1190         ret = snmp_agent_form_reply(requests, dd, &index_oid, i);
1191         pthread_mutex_unlock(&g_agent->lock);
1192
1193         return ret;
1194       }
1195     }
1196   }
1197
1198   pthread_mutex_unlock(&g_agent->lock);
1199
1200   return SNMP_NOSUCHINSTANCE;
1201 }
1202
1203 static int snmp_agent_table_index_oid_handler(
1204     struct netsnmp_mib_handler_s *handler,
1205     struct netsnmp_handler_registration_s *reginfo,
1206     struct netsnmp_agent_request_info_s *reqinfo,
1207     struct netsnmp_request_info_s *requests) {
1208
1209   if (reqinfo->mode != MODE_GET) {
1210     DEBUG(PLUGIN_NAME ": Not supported request mode (%d)", reqinfo->mode);
1211     return SNMP_ERR_NOERROR;
1212   }
1213
1214   pthread_mutex_lock(&g_agent->lock);
1215
1216   oid_t oid;
1217   memcpy(oid.oid, requests->requestvb->name,
1218          sizeof(oid.oid[0]) * requests->requestvb->name_length);
1219   oid.oid_len = requests->requestvb->name_length;
1220
1221   for (llentry_t *te = llist_head(g_agent->tables); te != NULL; te = te->next) {
1222     table_definition_t *td = te->value;
1223
1224     if (td->index_oid.oid_len &&
1225         (snmp_oid_ncompare(
1226              oid.oid, oid.oid_len, td->index_oid.oid, td->index_oid.oid_len,
1227              SNMP_MIN(oid.oid_len, td->index_oid.oid_len)) == 0)) {
1228
1229       DEBUG(PLUGIN_NAME ": Handle '%s' table index OID", td->name);
1230
1231       int index = oid.oid[oid.oid_len - 1];
1232
1233       int ret = c_avl_get(td->index_instance, &index, NULL);
1234       if (ret != 0) {
1235         /* nonexisting index requested */
1236         pthread_mutex_unlock(&g_agent->lock);
1237         return SNMP_NOSUCHINSTANCE;
1238       }
1239
1240       requests->requestvb->type = ASN_INTEGER;
1241       snmp_set_var_typed_value(requests->requestvb, requests->requestvb->type,
1242                                (const u_char *)&index, sizeof(index));
1243
1244       pthread_mutex_unlock(&g_agent->lock);
1245
1246       return SNMP_ERR_NOERROR;
1247     }
1248   }
1249
1250   pthread_mutex_unlock(&g_agent->lock);
1251
1252   return SNMP_NOSUCHINSTANCE;
1253 }
1254
1255 static int snmp_agent_table_size_oid_handler(
1256     struct netsnmp_mib_handler_s *handler,
1257     struct netsnmp_handler_registration_s *reginfo,
1258     struct netsnmp_agent_request_info_s *reqinfo,
1259     struct netsnmp_request_info_s *requests) {
1260
1261   if (reqinfo->mode != MODE_GET) {
1262     DEBUG(PLUGIN_NAME ": Not supported request mode (%d)", reqinfo->mode);
1263     return SNMP_ERR_NOERROR;
1264   }
1265
1266   pthread_mutex_lock(&g_agent->lock);
1267
1268   oid_t oid;
1269   memcpy(oid.oid, requests->requestvb->name,
1270          sizeof(oid.oid[0]) * requests->requestvb->name_length);
1271   oid.oid_len = requests->requestvb->name_length;
1272
1273   DEBUG(PLUGIN_NAME ": Get request received for table size OID");
1274
1275   for (llentry_t *te = llist_head(g_agent->tables); te != NULL; te = te->next) {
1276     table_definition_t *td = te->value;
1277
1278     if (td->size_oid.oid_len &&
1279         (snmp_oid_ncompare(oid.oid, oid.oid_len, td->size_oid.oid,
1280                            td->size_oid.oid_len,
1281                            SNMP_MIN(oid.oid_len, td->size_oid.oid_len)) == 0)) {
1282       DEBUG(PLUGIN_NAME ": Handle '%s' table size OID", td->name);
1283
1284       long size;
1285       if (td->index_oid.oid_len)
1286         size = c_avl_size(td->index_instance);
1287       else
1288         size = c_avl_size(td->instance_index);
1289
1290       requests->requestvb->type = ASN_INTEGER;
1291       snmp_set_var_typed_value(requests->requestvb, requests->requestvb->type,
1292                                (const u_char *)&size, sizeof(size));
1293
1294       pthread_mutex_unlock(&g_agent->lock);
1295
1296       return SNMP_ERR_NOERROR;
1297     }
1298   }
1299
1300   pthread_mutex_unlock(&g_agent->lock);
1301
1302   return SNMP_NOSUCHINSTANCE;
1303 }
1304
1305 static int
1306 snmp_agent_scalar_oid_handler(struct netsnmp_mib_handler_s *handler,
1307                               struct netsnmp_handler_registration_s *reginfo,
1308                               struct netsnmp_agent_request_info_s *reqinfo,
1309                               struct netsnmp_request_info_s *requests) {
1310
1311   if (reqinfo->mode != MODE_GET) {
1312     DEBUG(PLUGIN_NAME ": Not supported request mode (%d)", reqinfo->mode);
1313     return SNMP_ERR_NOERROR;
1314   }
1315
1316   pthread_mutex_lock(&g_agent->lock);
1317
1318   oid_t oid;
1319   memcpy(oid.oid, requests->requestvb->name,
1320          sizeof(oid.oid[0]) * requests->requestvb->name_length);
1321   oid.oid_len = requests->requestvb->name_length;
1322
1323 #if COLLECT_DEBUG
1324   char oid_str[DATA_MAX_NAME_LEN];
1325   snmp_agent_oid_to_string(oid_str, sizeof(oid_str), &oid);
1326   DEBUG(PLUGIN_NAME ": Get request received for scalar OID '%s'", oid_str);
1327 #endif
1328
1329   for (llentry_t *de = llist_head(g_agent->scalars); de != NULL;
1330        de = de->next) {
1331     data_definition_t *dd = de->value;
1332
1333     for (size_t i = 0; i < dd->oids_len; i++) {
1334
1335       int ret = snmp_oid_compare(oid.oid, oid.oid_len, dd->oids[i].oid,
1336                                  dd->oids[i].oid_len);
1337       if (ret != 0)
1338         continue;
1339
1340       ret = snmp_agent_form_reply(requests, dd, NULL, i);
1341
1342       pthread_mutex_unlock(&g_agent->lock);
1343
1344       return ret;
1345     }
1346   }
1347
1348   pthread_mutex_unlock(&g_agent->lock);
1349
1350   return SNMP_NOSUCHINSTANCE;
1351 }
1352
1353 static int snmp_agent_register_table_oids(void) {
1354
1355   for (llentry_t *te = llist_head(g_agent->tables); te != NULL; te = te->next) {
1356     table_definition_t *td = te->value;
1357
1358     if (td->size_oid.oid_len != 0) {
1359       td->size_oid.type =
1360           snmp_agent_get_asn_type(td->size_oid.oid, td->size_oid.oid_len);
1361       td->size_oid.oid_len++;
1362       int ret = snmp_agent_register_oid(&td->size_oid,
1363                                         snmp_agent_table_size_oid_handler);
1364       if (ret != 0)
1365         return ret;
1366     }
1367
1368     for (llentry_t *de = llist_head(td->columns); de != NULL; de = de->next) {
1369       data_definition_t *dd = de->value;
1370
1371       for (size_t i = 0; i < dd->oids_len; i++) {
1372         dd->oids[i].type =
1373             snmp_agent_get_asn_type(dd->oids[i].oid, dd->oids[i].oid_len);
1374       }
1375     }
1376   }
1377
1378   return 0;
1379 }
1380
1381 static int snmp_agent_register_scalar_oids(void) {
1382
1383   for (llentry_t *e = llist_head(g_agent->scalars); e != NULL; e = e->next) {
1384     data_definition_t *dd = e->value;
1385
1386     for (size_t i = 0; i < dd->oids_len; i++) {
1387
1388       dd->oids[i].type =
1389           snmp_agent_get_asn_type(dd->oids[i].oid, dd->oids[i].oid_len);
1390
1391       int ret =
1392           snmp_agent_register_oid(&dd->oids[i], snmp_agent_scalar_oid_handler);
1393       if (ret != 0)
1394         return ret;
1395     }
1396   }
1397
1398   return 0;
1399 }
1400
1401 static int snmp_agent_config_data_oids(data_definition_t *dd,
1402                                        oconfig_item_t *ci) {
1403   if (ci->values_num < 1) {
1404     WARNING(PLUGIN_NAME ": `OIDs' needs at least one argument");
1405     return -EINVAL;
1406   }
1407
1408   for (int i = 0; i < ci->values_num; i++)
1409     if (ci->values[i].type != OCONFIG_TYPE_STRING) {
1410       WARNING(PLUGIN_NAME ": `OIDs' needs only string argument");
1411       return -EINVAL;
1412     }
1413
1414   if (dd->oids != NULL) {
1415     WARNING(PLUGIN_NAME ": OIDs can be configured only once for each data");
1416     return -EINVAL;
1417   }
1418
1419   dd->oids_len = 0;
1420   dd->oids = calloc(ci->values_num, sizeof(*dd->oids));
1421
1422   if (dd->oids == NULL)
1423     return -ENOMEM;
1424   dd->oids_len = (size_t)ci->values_num;
1425
1426   for (int i = 0; i < ci->values_num; i++) {
1427     dd->oids[i].oid_len = MAX_OID_LEN;
1428
1429     if (NULL == snmp_parse_oid(ci->values[i].value.string, dd->oids[i].oid,
1430                                &dd->oids[i].oid_len)) {
1431       ERROR(PLUGIN_NAME ": snmp_parse_oid (%s) failed",
1432             ci->values[i].value.string);
1433       sfree(dd->oids);
1434       dd->oids_len = 0;
1435       return -1;
1436     }
1437   }
1438
1439   return 0;
1440 }
1441
1442 static int snmp_agent_config_table_size_oid(table_definition_t *td,
1443                                             oconfig_item_t *ci) {
1444   if (ci->values_num < 1) {
1445     WARNING(PLUGIN_NAME ": `TableSizeOID' is empty");
1446     return -EINVAL;
1447   }
1448
1449   if (ci->values[0].type != OCONFIG_TYPE_STRING) {
1450     WARNING(PLUGIN_NAME ": `TableSizeOID' needs only string argument");
1451     return -EINVAL;
1452   }
1453
1454   td->size_oid.oid_len = MAX_OID_LEN;
1455
1456   if (NULL == snmp_parse_oid(ci->values[0].value.string, td->size_oid.oid,
1457                              &td->size_oid.oid_len)) {
1458     ERROR(PLUGIN_NAME ": Failed to parse table size OID (%s)",
1459           ci->values[0].value.string);
1460     td->size_oid.oid_len = 0;
1461     return -EINVAL;
1462   }
1463
1464   return 0;
1465 }
1466
1467 static int snmp_agent_config_table_index_oid(table_definition_t *td,
1468                                              oconfig_item_t *ci) {
1469
1470   if (ci->values_num < 1) {
1471     WARNING(PLUGIN_NAME ": `IndexOID' is empty");
1472     return -EINVAL;
1473   }
1474
1475   if (ci->values[0].type != OCONFIG_TYPE_STRING) {
1476     WARNING(PLUGIN_NAME ": `IndexOID' needs only string argument");
1477     return -EINVAL;
1478   }
1479
1480   td->index_oid.oid_len = MAX_OID_LEN;
1481
1482   if (NULL == snmp_parse_oid(ci->values[0].value.string, td->index_oid.oid,
1483                              &td->index_oid.oid_len)) {
1484     ERROR(PLUGIN_NAME ": Failed to parse table index OID (%s)",
1485           ci->values[0].value.string);
1486     td->index_oid.oid_len = 0;
1487     return -EINVAL;
1488   }
1489
1490   return 0;
1491 }
1492
1493 /* Getting index key source that will represent table row */
1494 static int snmp_agent_config_index_key_source(table_definition_t *td,
1495                                               data_definition_t *dd,
1496                                               oconfig_item_t *ci) {
1497   char *val = NULL;
1498
1499   int ret = cf_util_get_string(ci, &val);
1500   if (ret != 0)
1501     return -1;
1502
1503   bool match = false;
1504
1505   for (int i = 0; i < MAX_KEY_SOURCES; i++) {
1506     if (strcasecmp(index_opts[i], (const char *)val) == 0) {
1507       td->index_keys[td->index_keys_len].source = i;
1508       td->index_keys[td->index_keys_len].group = GROUP_UNUSED;
1509       td->index_keys[td->index_keys_len].regex = NULL;
1510       match = 1;
1511       break;
1512     }
1513   }
1514
1515   if (!match) {
1516     ERROR(PLUGIN_NAME ": Failed to parse index key source: '%s'", val);
1517     sfree(val);
1518     return -EINVAL;
1519   }
1520
1521   sfree(val);
1522   dd->index_key_pos = td->index_keys_len++;
1523   dd->is_index_key = true;
1524
1525   return 0;
1526 }
1527
1528 /* Getting format string used to parse values from index key source */
1529 static int snmp_agent_config_index_key_regex(table_definition_t *td,
1530                                              data_definition_t *dd,
1531                                              oconfig_item_t *ci) {
1532   index_key_t *index_key = &td->index_keys[dd->index_key_pos];
1533
1534   int ret = cf_util_get_string(ci, &index_key->regex);
1535   if (ret != 0)
1536     return -1;
1537
1538   ret = regcomp(&index_key->regex_info, index_key->regex, REG_EXTENDED);
1539   if (ret) {
1540     ERROR(PLUGIN_NAME ": Could not compile regex for %s", dd->name);
1541     return -1;
1542   }
1543
1544   index_key_src_t source = index_key->source;
1545   if (td->tokens[source] == NULL) {
1546     td->tokens[source] =
1547         c_avl_create((int (*)(const void *, const void *))num_compare);
1548     if (td->tokens[source] == NULL) {
1549       ERROR(PLUGIN_NAME ": Could not allocate memory for AVL tree");
1550       return -ENOMEM;
1551     }
1552   }
1553
1554   return 0;
1555 }
1556
1557 static int snmp_agent_config_index_key(table_definition_t *td,
1558                                        data_definition_t *dd,
1559                                        oconfig_item_t *ci) {
1560   int ret = 0;
1561
1562   for (int i = 0; (i < ci->children_num && ret == 0); i++) {
1563     oconfig_item_t *option = ci->children + i;
1564
1565     if (strcasecmp("Source", option->key) == 0)
1566       ret = snmp_agent_config_index_key_source(td, dd, option);
1567     else if (strcasecmp("Regex", option->key) == 0)
1568       ret = snmp_agent_config_index_key_regex(td, dd, option);
1569     else if (strcasecmp("Group", option->key) == 0)
1570       ret = cf_util_get_int(option, &td->index_keys[dd->index_key_pos].group);
1571   }
1572
1573   return ret;
1574 }
1575
1576 /* This function parses configuration of both scalar and table column
1577  * because they have nearly the same structure */
1578 static int snmp_agent_config_table_column(table_definition_t *td,
1579                                           oconfig_item_t *ci) {
1580   data_definition_t *dd;
1581   int ret = 0;
1582   oconfig_item_t *option_tmp = NULL;
1583
1584   assert(ci != NULL);
1585
1586   dd = calloc(1, sizeof(*dd));
1587   if (dd == NULL) {
1588     ERROR(PLUGIN_NAME ": Failed to allocate memory for table data definition");
1589     return -ENOMEM;
1590   }
1591
1592   ret = cf_util_get_string(ci, &dd->name);
1593   if (ret != 0) {
1594     sfree(dd);
1595     return -1;
1596   }
1597
1598   dd->scale = 1.0;
1599   dd->shift = 0.0;
1600   /* NULL if it's a scalar */
1601   dd->table = td;
1602   dd->is_index_key = false;
1603
1604   for (int i = 0; i < ci->children_num; i++) {
1605     oconfig_item_t *option = ci->children + i;
1606
1607     /* First 3 options are reserved for table entry only */
1608     if (td != NULL && strcasecmp("IndexKey", option->key) == 0) {
1609       dd->is_index_key = true;
1610       option_tmp = option;
1611     } else if (strcasecmp("Plugin", option->key) == 0)
1612       ret = cf_util_get_string(option, &dd->plugin);
1613     else if (strcasecmp("PluginInstance", option->key) == 0)
1614       ret = cf_util_get_string(option, &dd->plugin_instance);
1615     else if (strcasecmp("Type", option->key) == 0)
1616       ret = cf_util_get_string(option, &dd->type);
1617     else if (strcasecmp("TypeInstance", option->key) == 0)
1618       ret = cf_util_get_string(option, &dd->type_instance);
1619     else if (strcasecmp("Shift", option->key) == 0)
1620       ret = cf_util_get_double(option, &dd->shift);
1621     else if (strcasecmp("Scale", option->key) == 0)
1622       ret = cf_util_get_double(option, &dd->scale);
1623     else if (strcasecmp("OIDs", option->key) == 0)
1624       ret = snmp_agent_config_data_oids(dd, option);
1625     else {
1626       WARNING(PLUGIN_NAME ": Option `%s' not allowed here", option->key);
1627       ret = -1;
1628     }
1629
1630     if (ret != 0) {
1631       snmp_agent_free_data(&dd);
1632       return -1;
1633     }
1634   }
1635
1636   if (dd->is_index_key) {
1637     ret = snmp_agent_config_index_key(td, dd, option_tmp);
1638     td->index_keys[dd->index_key_pos].type =
1639         snmp_agent_get_asn_type(dd->oids[0].oid, dd->oids[0].oid_len);
1640
1641     if (ret != 0) {
1642       snmp_agent_free_data(&dd);
1643       return -1;
1644     }
1645   }
1646
1647   llentry_t *entry = llentry_create(dd->name, dd);
1648   if (entry == NULL) {
1649     snmp_agent_free_data(&dd);
1650     return -ENOMEM;
1651   }
1652
1653   /* Append to column list in parent table */
1654   if (td != NULL)
1655     llist_append(td->columns, entry);
1656   else
1657     llentry_destroy(entry);
1658
1659   return 0;
1660 }
1661
1662 /* Parses scalar configuration entry */
1663 static int snmp_agent_config_scalar(oconfig_item_t *ci) {
1664   return snmp_agent_config_table_column(NULL, ci);
1665 }
1666
1667 static int num_compare(const int *a, const int *b) {
1668   assert((a != NULL) && (b != NULL));
1669   if (*a < *b)
1670     return -1;
1671   else if (*a > *b)
1672     return 1;
1673   else
1674     return 0;
1675 }
1676
1677 static int oid_compare(const oid_t *a, const oid_t *b) {
1678   return snmp_oid_compare(a->oid, a->oid_len, b->oid, b->oid_len);
1679 }
1680
1681 static int snmp_agent_config_table(oconfig_item_t *ci) {
1682   table_definition_t *td;
1683   int ret = 0;
1684
1685   assert(ci != NULL);
1686
1687   td = calloc(1, sizeof(*td));
1688   if (td == NULL) {
1689     ERROR(PLUGIN_NAME ": Failed to allocate memory for table definition");
1690     return -ENOMEM;
1691   }
1692
1693   ret = cf_util_get_string(ci, &td->name);
1694   if (ret != 0) {
1695     sfree(td);
1696     return -1;
1697   }
1698
1699   td->columns = llist_create();
1700   if (td->columns == NULL) {
1701     ERROR(PLUGIN_NAME ": Failed to allocate memory for columns list");
1702     snmp_agent_free_table(&td);
1703     return -ENOMEM;
1704   }
1705
1706   for (int i = 0; i < MAX_KEY_SOURCES; i++)
1707     td->tokens[i] = NULL;
1708   td->tokens_done = false;
1709
1710   for (int i = 0; i < ci->children_num; i++) {
1711     oconfig_item_t *option = ci->children + i;
1712
1713     if (strcasecmp("IndexOID", option->key) == 0)
1714       ret = snmp_agent_config_table_index_oid(td, option);
1715     else if (strcasecmp("SizeOID", option->key) == 0)
1716       ret = snmp_agent_config_table_size_oid(td, option);
1717     else if (strcasecmp("Data", option->key) == 0)
1718       ret = snmp_agent_config_table_column(td, option);
1719     else {
1720       WARNING(PLUGIN_NAME ": Option `%s' not allowed here", option->key);
1721       ret = -1;
1722     }
1723
1724     if (ret != 0) {
1725       snmp_agent_free_table(&td);
1726       return -ENOMEM;
1727     }
1728   }
1729
1730   /* Preparing index list container */
1731   ret = snmp_agent_prep_index_list(td, &td->index_list_cont);
1732   if (ret != 0)
1733     return -EINVAL;
1734
1735   td->instance_index =
1736       c_avl_create((int (*)(const void *, const void *))oid_compare);
1737   if (td->instance_index == NULL) {
1738     snmp_agent_free_table(&td);
1739     return -ENOMEM;
1740   }
1741
1742   td->index_instance =
1743       c_avl_create((int (*)(const void *, const void *))num_compare);
1744   if (td->index_instance == NULL) {
1745     snmp_agent_free_table(&td);
1746     return -ENOMEM;
1747   }
1748
1749   td->instance_oids =
1750       c_avl_create((int (*)(const void *, const void *))oid_compare);
1751   if (td->instance_oids == NULL) {
1752     snmp_agent_free_table(&td);
1753     return -ENOMEM;
1754   }
1755
1756   llentry_t *entry = llentry_create(td->name, td);
1757   if (entry == NULL) {
1758     snmp_agent_free_table(&td);
1759     return -ENOMEM;
1760   }
1761
1762   llist_append(g_agent->tables, entry);
1763
1764   return 0;
1765 }
1766
1767 static int snmp_agent_get_value_from_ds_type(const value_t *val, int type,
1768                                              double scale, double shift,
1769                                              long *value) {
1770   switch (type) {
1771   case DS_TYPE_COUNTER:
1772     *value = (long)((val->counter * scale) + shift);
1773     break;
1774   case DS_TYPE_ABSOLUTE:
1775     *value = (long)((val->absolute * scale) + shift);
1776     break;
1777   case DS_TYPE_DERIVE:
1778     *value = (long)((val->derive * scale) + shift);
1779     break;
1780   case DS_TYPE_GAUGE:
1781     *value = (long)((val->gauge * scale) + shift);
1782     break;
1783   case TYPE_STRING:
1784     break;
1785   default:
1786     ERROR(PLUGIN_NAME ": Unknown data source type: %i", type);
1787     return -EINVAL;
1788   }
1789
1790   return 0;
1791 }
1792
1793 static int snmp_agent_set_vardata(void *data, size_t *data_len, u_char asn_type,
1794                                   double scale, double shift, const void *value,
1795                                   size_t len, int type) {
1796
1797   int ret;
1798   netsnmp_vardata var;
1799   const value_t *val;
1800   long new_value = 0;
1801
1802   val = value;
1803   var.string = (u_char *)data;
1804
1805   ret = snmp_agent_get_value_from_ds_type(val, type, scale, shift, &new_value);
1806   if (ret != 0)
1807     return ret;
1808
1809   switch (asn_type) {
1810   case ASN_INTEGER:
1811   case ASN_UINTEGER:
1812   case ASN_COUNTER:
1813   case ASN_TIMETICKS:
1814   case ASN_GAUGE:
1815     if (*data_len < sizeof(*var.integer))
1816       return -EINVAL;
1817     *var.integer = new_value;
1818     *data_len = sizeof(*var.integer);
1819     break;
1820   case ASN_COUNTER64:
1821     if (*data_len < sizeof(*var.counter64))
1822       return -EINVAL;
1823     var.counter64->high = (u_long)((int64_t)new_value >> 32);
1824     var.counter64->low = (u_long)((int64_t)new_value & 0xFFFFFFFF);
1825     *data_len = sizeof(*var.counter64);
1826     break;
1827   case ASN_OCTET_STR:
1828     if (type == DS_TYPE_GAUGE) {
1829       char buf[DATA_MAX_NAME_LEN];
1830       snprintf(buf, sizeof(buf), "%.2f", val->gauge);
1831       if (*data_len < strlen(buf))
1832         return -EINVAL;
1833       *data_len = strlen(buf);
1834       memcpy(var.string, buf, *data_len);
1835     } else {
1836       ERROR(PLUGIN_NAME ": Failed to convert %d ds type to %d asn type", type,
1837             asn_type);
1838       return -EINVAL;
1839     }
1840     break;
1841   default:
1842     ERROR(PLUGIN_NAME ": Failed to convert %d ds type to %d asn type", type,
1843           asn_type);
1844     return -EINVAL;
1845   }
1846
1847   return 0;
1848 }
1849
1850 static int snmp_agent_register_oid_index(oid_t *oid, int index,
1851                                          Netsnmp_Node_Handler *handler) {
1852   oid_t new_oid;
1853   memcpy(&new_oid, oid, sizeof(*oid));
1854   new_oid.oid[new_oid.oid_len++] = index;
1855   return snmp_agent_register_oid(&new_oid, handler);
1856 }
1857
1858 static int snmp_agent_unregister_oid_index(oid_t *oid, int index) {
1859   oid_t new_oid;
1860   memcpy(&new_oid, oid, sizeof(*oid));
1861   new_oid.oid[new_oid.oid_len++] = index;
1862   return snmp_agent_unregister_oid(&new_oid);
1863 }
1864
1865 static int snmp_agent_update_instance_oids(c_avl_tree_t *tree, oid_t *index_oid,
1866                                            int value) {
1867   int *oids_num; /* number of oids registered for instance */
1868
1869   if (c_avl_get(tree, index_oid, (void **)&oids_num) == 0) {
1870     *oids_num += value;
1871     return *oids_num;
1872   } else {
1873     ERROR(PLUGIN_NAME ": Error updating index data");
1874     return -1;
1875   }
1876 }
1877
1878 static int snmp_agent_update_index(data_definition_t *dd,
1879                                    table_definition_t *td, oid_t **index_oid) {
1880   int ret;
1881   int *index = NULL;
1882   int *value = NULL;
1883   bool do_free_index_oid = true;
1884
1885   if (c_avl_get(td->instance_index, (void *)*index_oid, (void **)&index) != 0) {
1886     /* Processing new instance */
1887     do_free_index_oid = false;
1888
1889     /* need to generate index for the table */
1890     if (td->index_oid.oid_len) {
1891       index = calloc(1, sizeof(*index));
1892       if (index == NULL) {
1893         ret = -ENOMEM;
1894         goto free_index_oid;
1895       }
1896
1897       *index = c_avl_size(td->instance_index) + 1;
1898
1899       ret = c_avl_insert(td->instance_index, *index_oid, index);
1900       if (ret != 0)
1901         goto free_index;
1902
1903       ret = c_avl_insert(td->index_instance, index, *index_oid);
1904       if (ret < 0) {
1905         DEBUG(PLUGIN_NAME ": Failed to update index_instance for '%s' table",
1906               td->name);
1907         goto remove_avl_index_oid;
1908       }
1909
1910       ret = snmp_agent_register_oid_index(&td->index_oid, *index,
1911                                           snmp_agent_table_index_oid_handler);
1912       if (ret != 0)
1913         goto remove_avl_index;
1914     } else {
1915       /* instance as a key is required for any table */
1916       ret = c_avl_insert(td->instance_index, *index_oid, NULL);
1917       if (ret != 0)
1918         goto free_index_oid;
1919     }
1920
1921     value = calloc(1, sizeof(*value));
1922
1923     if (value == NULL) {
1924       ERROR(PLUGIN_NAME ": Failed to allocate memory");
1925       ret = -ENOMEM;
1926       goto unregister_index;
1927     }
1928
1929     ret = c_avl_insert(td->instance_oids, *index_oid, value);
1930
1931     if (ret < 0) {
1932       DEBUG(PLUGIN_NAME ": Failed to update instance_oids for '%s' table",
1933             td->name);
1934       goto free_value;
1935     }
1936
1937     int keys_processed = 0;
1938
1939     /* Registering index keys OIDs */
1940     for (llentry_t *de = llist_head(td->columns); de != NULL; de = de->next) {
1941       data_definition_t *idd = de->value;
1942       if (!idd->is_index_key)
1943         continue;
1944
1945       for (size_t i = 0; i < idd->oids_len; i++) {
1946         if (td->index_oid.oid_len)
1947           ret = snmp_agent_register_oid_index(&idd->oids[i], *index,
1948                                               snmp_agent_table_oid_handler);
1949         else
1950           ret = snmp_agent_register_oid_string(&idd->oids[i], *index_oid,
1951                                                snmp_agent_table_oid_handler);
1952
1953         if (ret != 0) {
1954           ERROR(PLUGIN_NAME ": Could not register OID");
1955           goto free_index;
1956         }
1957       }
1958
1959       if (++keys_processed >= td->index_keys_len)
1960         break;
1961     }
1962   }
1963
1964   ret = 0;
1965
1966   for (size_t i = 0; i < dd->oids_len; i++) {
1967     if (td->index_oid.oid_len)
1968       ret = snmp_agent_register_oid_index(&dd->oids[i], *index,
1969                                           snmp_agent_table_oid_handler);
1970     else
1971       ret = snmp_agent_register_oid_string(&dd->oids[i], *index_oid,
1972                                            snmp_agent_table_oid_handler);
1973
1974     if (ret < 0)
1975       goto free_index;
1976     else if (ret == OID_EXISTS)
1977       break;
1978     else if (snmp_agent_update_instance_oids(td->instance_oids, *index_oid, 1) <
1979              0)
1980       goto free_index;
1981   }
1982
1983   if (ret != OID_EXISTS) {
1984     char index_str[DATA_MAX_NAME_LEN];
1985
1986     if (index == NULL)
1987       snmp_agent_oid_to_string(index_str, sizeof(index_str), *index_oid);
1988     else
1989       snprintf(index_str, sizeof(index_str), "%d", *index);
1990
1991     notification_t n = {
1992         .severity = NOTIF_OKAY, .time = cdtime(), .plugin = PLUGIN_NAME};
1993     sstrncpy(n.host, hostname_g, sizeof(n.host));
1994     snprintf(n.message, sizeof(n.message),
1995              "Data added to table %s with index %s", td->name, index_str);
1996     DEBUG(PLUGIN_NAME ": %s", n.message);
1997
1998     plugin_dispatch_notification(&n);
1999   }
2000
2001   if (do_free_index_oid)
2002     sfree(*index_oid);
2003
2004   return 0;
2005
2006 free_value:
2007   sfree(value);
2008 unregister_index:
2009   if (td->index_oid.oid_len)
2010     snmp_agent_unregister_oid_index(*index_oid, *index);
2011 remove_avl_index:
2012   if (td->index_oid.oid_len)
2013     c_avl_remove(td->index_instance, index, NULL, NULL);
2014 remove_avl_index_oid:
2015   c_avl_remove(td->instance_index, *index_oid, NULL, NULL);
2016 free_index:
2017   if (index != NULL)
2018     sfree(index);
2019 free_index_oid:
2020   sfree(*index_oid);
2021
2022   return ret;
2023 }
2024
2025 static int snmp_agent_write(value_list_t const *vl) {
2026   if (vl == NULL)
2027     return -EINVAL;
2028
2029   for (llentry_t *te = llist_head(g_agent->tables); te != NULL; te = te->next) {
2030     table_definition_t *td = te->value;
2031
2032     for (llentry_t *de = llist_head(td->columns); de != NULL; de = de->next) {
2033       data_definition_t *dd = de->value;
2034
2035       if (!dd->is_index_key) {
2036         if (CHECK_DD_TYPE(dd, vl->plugin, vl->plugin_instance, vl->type,
2037                           vl->type_instance)) {
2038           oid_t *index_oid = calloc(1, sizeof(*index_oid));
2039
2040           if (index_oid == NULL) {
2041             ERROR(PLUGIN_NAME ": Could not allocate memory for index_oid");
2042             return -ENOMEM;
2043           }
2044
2045           int ret = snmp_agent_generate_index(td, vl, index_oid);
2046
2047           if (ret == 0)
2048             ret = snmp_agent_update_index(dd, td, &index_oid);
2049
2050           return ret;
2051         }
2052       }
2053     }
2054   }
2055
2056   return 0;
2057 }
2058
2059 static int snmp_agent_collect(const data_set_t *ds, const value_list_t *vl,
2060                               user_data_t __attribute__((unused)) * user_data) {
2061
2062   pthread_mutex_lock(&g_agent->lock);
2063
2064   snmp_agent_write(vl);
2065
2066   pthread_mutex_unlock(&g_agent->lock);
2067
2068   return 0;
2069 }
2070
2071 static int snmp_agent_preinit(void) {
2072
2073   g_agent = calloc(1, sizeof(*g_agent));
2074   if (g_agent == NULL) {
2075     ERROR(PLUGIN_NAME ": Failed to allocate memory for snmp agent context");
2076     return -ENOMEM;
2077   }
2078
2079   g_agent->tables = llist_create();
2080   g_agent->scalars = llist_create();
2081   g_agent->registered_oids =
2082       c_avl_create((int (*)(const void *, const void *))oid_compare);
2083
2084   if (g_agent->tables == NULL || g_agent->scalars == NULL) {
2085     ERROR(PLUGIN_NAME ": llist_create() failed");
2086     llist_destroy(g_agent->scalars);
2087     llist_destroy(g_agent->tables);
2088     c_avl_destroy(g_agent->registered_oids);
2089     return -ENOMEM;
2090   }
2091
2092   int err;
2093   /* make us an agentx client. */
2094   err = netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_AGENT_ROLE,
2095                                1);
2096   if (err != 0) {
2097     ERROR(PLUGIN_NAME ": Failed to set agent role (%d)", err);
2098     llist_destroy(g_agent->scalars);
2099     llist_destroy(g_agent->tables);
2100     c_avl_destroy(g_agent->registered_oids);
2101     return -1;
2102   }
2103
2104   /*
2105    *  For SNMP debug purposes uses snmp_set_do_debugging(1);
2106    */
2107
2108   /* initialize the agent library */
2109   err = init_agent(PLUGIN_NAME);
2110   if (err != 0) {
2111     ERROR(PLUGIN_NAME ": Failed to initialize the agent library (%d)", err);
2112     llist_destroy(g_agent->scalars);
2113     llist_destroy(g_agent->tables);
2114     c_avl_destroy(g_agent->registered_oids);
2115     return -1;
2116   }
2117
2118   init_snmp(PLUGIN_NAME);
2119
2120   g_agent->tp = read_all_mibs();
2121
2122   return 0;
2123 }
2124
2125 static int snmp_agent_init(void) {
2126   int ret;
2127
2128   if (g_agent == NULL || ((llist_head(g_agent->scalars) == NULL) &&
2129                           (llist_head(g_agent->tables) == NULL))) {
2130     ERROR(PLUGIN_NAME ": snmp_agent_init: plugin not configured");
2131     return -EINVAL;
2132   }
2133
2134   plugin_register_shutdown(PLUGIN_NAME, snmp_agent_shutdown);
2135
2136   ret = snmp_agent_register_scalar_oids();
2137   if (ret != 0)
2138     return ret;
2139
2140   ret = snmp_agent_register_table_oids();
2141   if (ret != 0)
2142     return ret;
2143
2144   ret = pthread_mutex_init(&g_agent->lock, NULL);
2145   if (ret != 0) {
2146     ERROR(PLUGIN_NAME ": Failed to initialize mutex, err %u", ret);
2147     return ret;
2148   }
2149
2150   ret = pthread_mutex_init(&g_agent->agentx_lock, NULL);
2151   if (ret != 0) {
2152     ERROR(PLUGIN_NAME ": Failed to initialize AgentX mutex, err %u", ret);
2153     return ret;
2154   }
2155
2156   /* create a second thread to listen for requests from AgentX*/
2157   ret = pthread_create(&g_agent->thread, NULL, &snmp_agent_thread_run, NULL);
2158   if (ret != 0) {
2159     ERROR(PLUGIN_NAME ": Failed to create a separate thread, err %u", ret);
2160     return ret;
2161   }
2162
2163   if (llist_head(g_agent->tables) != NULL) {
2164     plugin_register_write(PLUGIN_NAME, snmp_agent_collect, NULL);
2165     plugin_register_missing(PLUGIN_NAME, snmp_agent_clear_missing, NULL);
2166   }
2167
2168   return 0;
2169 }
2170
2171 static void *snmp_agent_thread_run(void __attribute__((unused)) * arg) {
2172   INFO(PLUGIN_NAME ": Thread is up and running");
2173
2174   for (;;) {
2175     pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
2176
2177     pthread_mutex_lock(&g_agent->agentx_lock);
2178     agent_check_and_process(0); /* 0 == don't block */
2179     pthread_mutex_unlock(&g_agent->agentx_lock);
2180
2181     pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
2182     usleep(10);
2183   }
2184
2185   pthread_exit(0);
2186 }
2187
2188 static int snmp_agent_register_oid(oid_t *oid, Netsnmp_Node_Handler *handler) {
2189   netsnmp_handler_registration *reg;
2190
2191   if (c_avl_get(g_agent->registered_oids, (void *)oid, NULL) == 0)
2192     return OID_EXISTS;
2193   else {
2194     oid_t *new_oid = calloc(1, sizeof(*oid));
2195
2196     if (new_oid == NULL) {
2197       ERROR(PLUGIN_NAME ": Could not allocate memory to register new OID");
2198       return -ENOMEM;
2199     }
2200
2201     memcpy(new_oid, oid, sizeof(*oid));
2202
2203     int ret = c_avl_insert(g_agent->registered_oids, (void *)new_oid, NULL);
2204     if (ret != 0) {
2205       ERROR(PLUGIN_NAME ": Could not allocate memory to register new OID");
2206       sfree(new_oid);
2207       return -ENOMEM;
2208     }
2209   }
2210
2211   char *oid_name = snmp_agent_get_oid_name(oid->oid, oid->oid_len - 1);
2212   char oid_str[DATA_MAX_NAME_LEN];
2213
2214   snmp_agent_oid_to_string(oid_str, sizeof(oid_str), oid);
2215
2216   if (oid_name == NULL) {
2217     WARNING(PLUGIN_NAME
2218             ": Skipped registration: OID (%s) is not found in main tree",
2219             oid_str);
2220     return 0;
2221   }
2222
2223   reg = netsnmp_create_handler_registration(oid_name, handler, oid->oid,
2224                                             oid->oid_len, HANDLER_CAN_RONLY);
2225   if (reg == NULL) {
2226     ERROR(PLUGIN_NAME ": Failed to create handler registration for OID (%s)",
2227           oid_str);
2228     return -1;
2229   }
2230
2231   pthread_mutex_lock(&g_agent->agentx_lock);
2232
2233   if (netsnmp_register_instance(reg) != MIB_REGISTERED_OK) {
2234     ERROR(PLUGIN_NAME ": Failed to register handler for OID (%s)", oid_str);
2235     pthread_mutex_unlock(&g_agent->agentx_lock);
2236     return -1;
2237   }
2238
2239   pthread_mutex_unlock(&g_agent->agentx_lock);
2240
2241   DEBUG(PLUGIN_NAME ": Registered handler for OID (%s)", oid_str);
2242
2243   return 0;
2244 }
2245
2246 static int snmp_agent_free_config(void) {
2247
2248   if (g_agent == NULL)
2249     return -EINVAL;
2250
2251   for (llentry_t *te = llist_head(g_agent->tables); te != NULL; te = te->next)
2252     snmp_agent_free_table((table_definition_t **)&te->value);
2253   llist_destroy(g_agent->tables);
2254
2255   for (llentry_t *de = llist_head(g_agent->scalars); de != NULL; de = de->next)
2256     snmp_agent_free_data((data_definition_t **)&de->value);
2257   llist_destroy(g_agent->scalars);
2258
2259   return 0;
2260 }
2261
2262 static int snmp_agent_shutdown(void) {
2263   int ret = 0;
2264
2265   DEBUG(PLUGIN_NAME ": snmp_agent_shutdown");
2266
2267   if (g_agent == NULL) {
2268     ERROR(PLUGIN_NAME ": snmp_agent_shutdown: plugin not initialized");
2269     return -EINVAL;
2270   }
2271
2272   if (pthread_cancel(g_agent->thread) != 0)
2273     ERROR(PLUGIN_NAME ": snmp_agent_shutdown: failed to cancel the thread");
2274
2275   if (pthread_join(g_agent->thread, NULL) != 0)
2276     ERROR(PLUGIN_NAME ": snmp_agent_shutdown: failed to join the thread");
2277
2278   snmp_agent_free_config();
2279
2280   snmp_shutdown(PLUGIN_NAME);
2281
2282   pthread_mutex_destroy(&g_agent->lock);
2283   pthread_mutex_destroy(&g_agent->agentx_lock);
2284
2285   /* Freeing registered OIDs list */
2286   void *oid;
2287
2288   if (g_agent->registered_oids != NULL) {
2289     while (c_avl_pick(g_agent->registered_oids, &oid, NULL) == 0) {
2290       sfree(oid);
2291     }
2292     c_avl_destroy(g_agent->registered_oids);
2293   }
2294
2295   sfree(g_agent);
2296
2297   return ret;
2298 }
2299
2300 static int snmp_agent_config(oconfig_item_t *ci) {
2301   int ret = snmp_agent_preinit();
2302
2303   if (ret != 0) {
2304     sfree(g_agent);
2305     return -EINVAL;
2306   }
2307
2308   for (int i = 0; i < ci->children_num; i++) {
2309     oconfig_item_t *child = ci->children + i;
2310     if (strcasecmp("Data", child->key) == 0) {
2311       ret = snmp_agent_config_scalar(child);
2312     } else if (strcasecmp("Table", child->key) == 0) {
2313       ret = snmp_agent_config_table(child);
2314     } else {
2315       ERROR(PLUGIN_NAME ": Unknown configuration option `%s'", child->key);
2316       ret = (-EINVAL);
2317     }
2318
2319     if (ret != 0) {
2320       ERROR(PLUGIN_NAME ": Failed to parse configuration");
2321       snmp_agent_free_config();
2322       snmp_shutdown(PLUGIN_NAME);
2323       sfree(g_agent);
2324       return -EINVAL;
2325     }
2326   }
2327
2328   ret = snmp_agent_validate_config();
2329   if (ret != 0) {
2330     ERROR(PLUGIN_NAME ": Invalid configuration provided");
2331     snmp_agent_free_config();
2332     snmp_shutdown(PLUGIN_NAME);
2333     sfree(g_agent);
2334     return -EINVAL;
2335   }
2336
2337   return 0;
2338 }
2339
2340 void module_register(void) {
2341   plugin_register_init(PLUGIN_NAME, snmp_agent_init);
2342   plugin_register_complex_config(PLUGIN_NAME, snmp_agent_config);
2343 }