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