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