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