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