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