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