1ea5cc97233c054ee2706cc966b897345caaeddc
[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  **/
28
29 #include "collectd.h"
30
31 #include "common.h"
32 #include "utils_avltree.h"
33 #include "utils_cache.h"
34 #include "utils_llist.h"
35
36 #include <net-snmp/net-snmp-config.h>
37
38 #include <net-snmp/net-snmp-includes.h>
39
40 #include <net-snmp/agent/net-snmp-agent-includes.h>
41
42 #define PLUGIN_NAME "snmp_agent"
43 #define ERR_BUF_SIZE 1024
44 #define TYPE_STRING -1
45
46 #ifndef MIN
47 #define MIN(x, y) ((x) < (y) ? (x) : (y))
48 #endif
49
50 struct oid_s {
51   oid oid[MAX_OID_LEN];
52   size_t oid_len;
53   u_char type;
54 };
55 typedef struct oid_s oid_t;
56
57 struct table_definition_s {
58   char *name;
59   oid_t index_oid;
60   oid_t size_oid;
61   llist_t *columns;
62   c_avl_tree_t *instance_index;
63   c_avl_tree_t *index_instance;
64 };
65 typedef struct table_definition_s table_definition_t;
66
67 struct data_definition_s {
68   char *name;
69   char *plugin;
70   char *plugin_instance;
71   char *type;
72   char *type_instance;
73   const table_definition_t *table;
74   _Bool is_instance;
75   oid_t *oids;
76   size_t oids_len;
77   double scale;
78   double shift;
79 };
80 typedef struct data_definition_s data_definition_t;
81
82 struct snmp_agent_ctx_s {
83   pthread_t thread;
84   pthread_mutex_t lock;
85   pthread_mutex_t agentx_lock;
86   struct tree *tp;
87
88   llist_t *tables;
89   llist_t *scalars;
90 };
91 typedef struct snmp_agent_ctx_s snmp_agent_ctx_t;
92
93 static snmp_agent_ctx_t *g_agent = NULL;
94
95 #define CHECK_DD_TYPE(_dd, _p, _pi, _t, _ti)                                   \
96   (_dd->plugin ? !strcmp(_dd->plugin, _p) : 0) &&                              \
97       (_dd->plugin_instance ? !strcmp(_dd->plugin_instance, _pi) : 1) &&       \
98       (_dd->type ? !strcmp(_dd->type, _t) : 0) &&                              \
99       (_dd->type_instance ? !strcmp(_dd->type_instance, _ti) : 1)
100
101 static void *snmp_agent_thread_run(void *arg);
102 static int snmp_agent_register_oid(oid_t *oid, Netsnmp_Node_Handler *handler);
103 static int snmp_agent_set_vardata(void *dst_buf, size_t *dst_buf_len,
104                                   u_char asn_type, double scale, double shift,
105                                   const void *value, size_t len, int type);
106 static int snmp_agent_unregister_oid_index(oid_t *oid, int index);
107
108 static u_char snmp_agent_get_asn_type(oid *oid, size_t oid_len) {
109   struct tree *node = get_tree(oid, oid_len, g_agent->tp);
110
111   return (node != NULL) ? mib_to_asn_type(node->type) : 0;
112 }
113
114 static char *snmp_agent_get_oid_name(oid *oid, size_t oid_len) {
115   struct tree *node = get_tree(oid, oid_len, g_agent->tp);
116
117   return (node != NULL) ? node->label : NULL;
118 }
119
120 static int snmp_agent_oid_to_string(char *buf, size_t buf_size,
121                                     oid_t const *o) {
122   char oid_str[MAX_OID_LEN][16];
123   char *oid_str_ptr[MAX_OID_LEN];
124
125   for (size_t i = 0; i < o->oid_len; i++) {
126     ssnprintf(oid_str[i], sizeof(oid_str[i]), "%lu", (unsigned long)o->oid[i]);
127     oid_str_ptr[i] = oid_str[i];
128   }
129
130   return strjoin(buf, buf_size, oid_str_ptr, o->oid_len, ".");
131 }
132
133 static void snmp_agent_dump_data(void) {
134 #if COLLECT_DEBUG
135   char oid_str[DATA_MAX_NAME_LEN];
136
137   for (llentry_t *te = llist_head(g_agent->tables); te != NULL; te = te->next) {
138     table_definition_t *td = te->value;
139
140     DEBUG(PLUGIN_NAME ": Table:");
141     DEBUG(PLUGIN_NAME ":   Name: %s", td->name);
142     if (td->index_oid.oid_len != 0) {
143       snmp_agent_oid_to_string(oid_str, sizeof(oid_str), &td->index_oid);
144       DEBUG(PLUGIN_NAME ":   IndexOID: %s", oid_str);
145     }
146     if (td->size_oid.oid_len != 0) {
147       snmp_agent_oid_to_string(oid_str, sizeof(oid_str), &td->size_oid);
148       DEBUG(PLUGIN_NAME ":   SizeOID: %s", oid_str);
149     }
150
151     for (llentry_t *de = llist_head(td->columns); de != NULL; de = de->next) {
152       data_definition_t *dd = de->value;
153
154       DEBUG(PLUGIN_NAME ":   Column:");
155       DEBUG(PLUGIN_NAME ":     Name: %s", dd->name);
156       if (dd->plugin)
157         DEBUG(PLUGIN_NAME ":     Plugin: %s", dd->plugin);
158       if (dd->plugin_instance)
159         DEBUG(PLUGIN_NAME ":     PluginInstance: %s", dd->plugin_instance);
160       if (dd->is_instance)
161         DEBUG(PLUGIN_NAME ":     Instance: true");
162       if (dd->type)
163         DEBUG(PLUGIN_NAME ":     Type: %s", dd->type);
164       if (dd->type_instance)
165         DEBUG(PLUGIN_NAME ":     TypeInstance: %s", dd->type_instance);
166       for (size_t i = 0; i < dd->oids_len; i++) {
167         snmp_agent_oid_to_string(oid_str, sizeof(oid_str), &dd->oids[i]);
168         DEBUG(PLUGIN_NAME ":     OID[%zu]: %s", i, oid_str);
169       }
170       DEBUG(PLUGIN_NAME ":   Scale: %g", dd->scale);
171       DEBUG(PLUGIN_NAME ":   Shift: %g", dd->shift);
172     }
173   }
174
175   for (llentry_t *e = llist_head(g_agent->scalars); e != NULL; e = e->next) {
176     data_definition_t *dd = e->value;
177
178     DEBUG(PLUGIN_NAME ": Scalar:");
179     DEBUG(PLUGIN_NAME ":   Name: %s", dd->name);
180     if (dd->plugin)
181       DEBUG(PLUGIN_NAME ":   Plugin: %s", dd->plugin);
182     if (dd->plugin_instance)
183       DEBUG(PLUGIN_NAME ":   PluginInstance: %s", dd->plugin_instance);
184     if (dd->is_instance)
185       DEBUG(PLUGIN_NAME ":   Instance: true");
186     if (dd->type)
187       DEBUG(PLUGIN_NAME ":   Type: %s", dd->type);
188     if (dd->type_instance)
189       DEBUG(PLUGIN_NAME ":   TypeInstance: %s", dd->type_instance);
190     for (size_t i = 0; i < dd->oids_len; i++) {
191       snmp_agent_oid_to_string(oid_str, sizeof(oid_str), &dd->oids[i]);
192       DEBUG(PLUGIN_NAME ":   OID[%zu]: %s", i, oid_str);
193     }
194     DEBUG(PLUGIN_NAME ":   Scale: %g", dd->scale);
195     DEBUG(PLUGIN_NAME ":   Shift: %g", dd->shift);
196   }
197 #endif /* COLLECT_DEBUG */
198 }
199
200 static int snmp_agent_validate_data(void) {
201
202   snmp_agent_dump_data();
203
204   for (llentry_t *te = llist_head(g_agent->tables); te != NULL; te = te->next) {
205     table_definition_t *td = te->value;
206
207     for (llentry_t *de = llist_head(td->columns); de != NULL; de = de->next) {
208       data_definition_t *dd = de->value;
209
210       if (!dd->plugin) {
211         ERROR(PLUGIN_NAME ": Plugin not defined for '%s'.'%s'", td->name,
212               dd->name);
213         return -EINVAL;
214       }
215
216       if (dd->plugin_instance) {
217         ERROR(PLUGIN_NAME ": PluginInstance should not be defined for table "
218                           "data type '%s'.'%s'",
219               td->name, dd->name);
220         return -EINVAL;
221       }
222
223       if (dd->oids_len == 0) {
224         ERROR(PLUGIN_NAME ": No OIDs defined for '%s'.'%s'", td->name,
225               dd->name);
226         return -EINVAL;
227       }
228
229       if (dd->is_instance) {
230
231         if (dd->type || dd->type_instance) {
232           ERROR(PLUGIN_NAME ": Type and TypeInstance are not valid for "
233                             "instance data '%s'.'%s'",
234                 td->name, dd->name);
235           return -EINVAL;
236         }
237
238         if (dd->oids_len > 1) {
239           ERROR(
240               PLUGIN_NAME
241               ": Only one OID should be specified for instance data '%s'.'%s'",
242               td->name, dd->name);
243           return -EINVAL;
244         }
245       } else {
246
247         if (!dd->type) {
248           ERROR(PLUGIN_NAME ": Type not defined for data '%s'.'%s'", td->name,
249                 dd->name);
250           return -EINVAL;
251         }
252       }
253     }
254   }
255
256   for (llentry_t *e = llist_head(g_agent->scalars); e != NULL; e = e->next) {
257     data_definition_t *dd = e->value;
258
259     if (!dd->plugin) {
260       ERROR(PLUGIN_NAME ": Plugin not defined for '%s'", dd->name);
261       return -EINVAL;
262     }
263
264     if (dd->oids_len == 0) {
265       ERROR(PLUGIN_NAME ": No OIDs defined for '%s'", dd->name);
266       return -EINVAL;
267     }
268
269     if (dd->is_instance) {
270       ERROR(PLUGIN_NAME
271             ": Instance flag can't be specified for scalar data '%s'",
272             dd->name);
273       return -EINVAL;
274     }
275
276     if (!dd->type) {
277       ERROR(PLUGIN_NAME ": Type not defined for data '%s'", dd->name);
278       return -EINVAL;
279     }
280   }
281
282   return 0;
283 }
284
285 static void snmp_agent_generate_oid2string(oid_t *oid, size_t offset, char *key) {
286   int key_len = oid->oid[offset];
287   int i;
288
289   for (i = 0; i < key_len && offset < oid->oid_len; i++)
290     key[i] = oid->oid[++offset];
291
292   key[i] = '\0';
293 }
294
295 static int snmp_agent_generate_string2oid(oid_t *oid, const char *key) {
296   int key_len = strlen(key);
297
298   oid->oid[oid->oid_len++] = key_len;
299   for (int i = 0; i < key_len; i++) {
300     oid->oid[oid->oid_len++] = key[i];
301     if (oid->oid_len >= MAX_OID_LEN) {
302       ERROR(PLUGIN_NAME ": Conversion key string %s to OID failed", key);
303       return -EINVAL;
304     }
305   }
306
307   return 0;
308 }
309
310 static int snmp_agent_register_oid_string(oid_t *oid, const char *key,
311                                           Netsnmp_Node_Handler *handler) {
312   oid_t new_oid;
313
314   memcpy(&new_oid, oid, sizeof(*oid));
315   int ret = snmp_agent_generate_string2oid(&new_oid, key);
316   if (ret != 0)
317     return ret;
318
319   return snmp_agent_register_oid(&new_oid, handler);
320 }
321
322 static int snmp_agent_unregister_oid_string(oid_t *oid, const char *key) {
323   oid_t new_oid;
324
325   memcpy(&new_oid, oid, sizeof(*oid));
326   int ret = snmp_agent_generate_string2oid(&new_oid, key);
327   if (ret != 0)
328     return ret;
329
330   return unregister_mib(new_oid.oid, new_oid.oid_len);
331 }
332
333 static int snmp_agent_table_row_remove(table_definition_t *td,
334                                        const char *instance) {
335   int *index = NULL;
336   char *ins = NULL;
337
338   if (td->index_oid.oid_len) {
339     if ((c_avl_get(td->instance_index, instance, (void **)&index) != 0) ||
340         (c_avl_get(td->index_instance, index, (void **)&ins) != 0))
341       return 0;
342   } else {
343     if (c_avl_get(td->instance_index, instance, (void **)&ins) != 0)
344       return 0;
345   }
346
347   pthread_mutex_lock(&g_agent->agentx_lock);
348
349   if (td->index_oid.oid_len)
350     snmp_agent_unregister_oid_index(&td->index_oid, *index);
351
352   for (llentry_t *de = llist_head(td->columns); de != NULL; de = de->next) {
353     data_definition_t *dd = de->value;
354
355     for (size_t i = 0; i < dd->oids_len; i++)
356       if (td->index_oid.oid_len)
357         snmp_agent_unregister_oid_index(&dd->oids[i], *index);
358       else
359         snmp_agent_unregister_oid_string(&dd->oids[i], ins);
360   }
361
362   pthread_mutex_unlock(&g_agent->agentx_lock);
363
364   DEBUG(PLUGIN_NAME ": Removed row for '%s' table [%d, %s]", td->name,
365         (index != NULL) ? *index : -1, ins);
366
367   notification_t n = {
368       .severity = NOTIF_WARNING, .time = cdtime(), .plugin = PLUGIN_NAME};
369   sstrncpy(n.host, hostname_g, sizeof(n.host));
370   sstrncpy(n.plugin_instance, ins, sizeof(n.plugin_instance));
371   ssnprintf(n.message, sizeof(n.message),
372             "Removed data row from table %s instance %s index %d", td->name,
373             ins, (index != NULL) ? *index : -1);
374   plugin_dispatch_notification(&n);
375
376   if (td->index_oid.oid_len) {
377     c_avl_remove(td->index_instance, index, NULL, (void **)&ins);
378     c_avl_remove(td->instance_index, instance, NULL, (void **)&index);
379     sfree(index);
380     sfree(ins);
381   } else {
382     c_avl_remove(td->instance_index, instance, NULL, (void **)&ins);
383     sfree(ins);
384   }
385
386   return 0;
387 }
388
389 static int snmp_agent_clear_missing(const value_list_t *vl,
390                                     __attribute__((unused)) user_data_t *ud) {
391   if (vl == NULL)
392     return -EINVAL;
393
394   for (llentry_t *te = llist_head(g_agent->tables); te != NULL; te = te->next) {
395     table_definition_t *td = te->value;
396
397     for (llentry_t *de = llist_head(td->columns); de != NULL; de = de->next) {
398       data_definition_t *dd = de->value;
399
400       if (!dd->is_instance) {
401         if (CHECK_DD_TYPE(dd, vl->plugin, vl->plugin_instance, vl->type,
402                           vl->type_instance)) {
403           snmp_agent_table_row_remove(td, vl->plugin_instance);
404           return 0;
405         }
406       }
407     }
408   }
409
410   return 0;
411 }
412
413 static void snmp_agent_free_data(data_definition_t **dd) {
414
415   if (dd == NULL || *dd == NULL)
416     return;
417
418   /* unregister scalar type OID */
419   if ((*dd)->table == NULL) {
420     for (size_t i = 0; i < (*dd)->oids_len; i++)
421       unregister_mib((*dd)->oids[i].oid, (*dd)->oids[i].oid_len);
422   }
423   if (!(*dd)->table->index_oid.oid_len) {
424     char *instance;
425
426     c_avl_iterator_t *iter = c_avl_get_iterator((*dd)->table->instance_index);
427     while (c_avl_iterator_next(iter, (void *)&instance, (void *)&instance) ==
428            0) {
429       for (size_t i = 0; i < (*dd)->oids_len; i++)
430         snmp_agent_unregister_oid_string(&(*dd)->oids[i], instance);
431     }
432     c_avl_iterator_destroy(iter);
433   } else {
434     /* unregister all table OIDs */
435     int *index;
436     char *value;
437
438     c_avl_iterator_t *iter = c_avl_get_iterator((*dd)->table->index_instance);
439     while (c_avl_iterator_next(iter, (void *)&index, (void *)&value) == 0) {
440       for (size_t i = 0; i < (*dd)->oids_len; i++)
441         snmp_agent_unregister_oid_index(&(*dd)->oids[i], *index);
442     }
443     c_avl_iterator_destroy(iter);
444   }
445
446   sfree((*dd)->name);
447   sfree((*dd)->plugin);
448   sfree((*dd)->plugin_instance);
449   sfree((*dd)->type);
450   sfree((*dd)->type_instance);
451   sfree((*dd)->oids);
452
453   sfree(*dd);
454
455   return;
456 }
457
458 static void snmp_agent_free_table(table_definition_t **td) {
459
460   if (td == NULL || *td == NULL)
461     return;
462
463   if ((*td)->size_oid.oid_len)
464     unregister_mib((*td)->size_oid.oid, (*td)->size_oid.oid_len);
465
466   if ((*td)->index_oid.oid_len) {
467     int *index;
468     char *value;
469
470     c_avl_iterator_t *iter = c_avl_get_iterator((*td)->index_instance);
471     while (c_avl_iterator_next(iter, (void *)&index, (void *)&value) == 0)
472       snmp_agent_unregister_oid_index(&(*td)->index_oid, *index);
473
474     c_avl_iterator_destroy(iter);
475   }
476
477   for (llentry_t *de = llist_head((*td)->columns); de != NULL; de = de->next) {
478     data_definition_t *dd = de->value;
479     snmp_agent_free_data(&dd);
480   }
481
482   llist_destroy((*td)->columns);
483
484   void *key = NULL;
485   void *value = NULL;
486
487   /* index_instance and instance_index contain the same pointers */
488   c_avl_destroy((*td)->index_instance);
489   (*td)->index_instance = NULL;
490
491   if ((*td)->instance_index != NULL) {
492     while (c_avl_pick((*td)->instance_index, &key, &value) == 0) {
493       if (key != value)
494         sfree(key);
495       sfree(value);
496     }
497     c_avl_destroy((*td)->instance_index);
498     (*td)->instance_index = NULL;
499   }
500
501   sfree((*td)->name);
502   sfree(*td);
503
504   return;
505 }
506
507 static int snmp_agent_form_reply(struct netsnmp_request_info_s *requests,
508                                  data_definition_t *dd, char *instance,
509                                  int oid_index) {
510   char name[DATA_MAX_NAME_LEN];
511   format_name(name, sizeof(name), hostname_g, dd->plugin,
512               instance ? instance : dd->plugin_instance, dd->type,
513               dd->type_instance);
514   DEBUG(PLUGIN_NAME ": Identifier '%s'", name);
515
516   value_t *values;
517   size_t values_num;
518   const data_set_t *ds = plugin_get_ds(dd->type);
519   if (ds == NULL) {
520     ERROR(PLUGIN_NAME ": Data set not found for '%s' type", dd->type);
521     return SNMP_NOSUCHINSTANCE;
522   }
523
524   int ret = uc_get_value_by_name(name, &values, &values_num);
525
526   if (ret != 0) {
527     ERROR(PLUGIN_NAME ": Failed to get value for '%s'", name);
528     return SNMP_NOSUCHINSTANCE;
529   }
530
531   assert(ds->ds_num == values_num);
532   assert(oid_index < (int)values_num);
533
534   char data[DATA_MAX_NAME_LEN];
535   size_t data_len = sizeof(data);
536   ret = snmp_agent_set_vardata(
537       data, &data_len, dd->oids[oid_index].type, dd->scale, dd->shift,
538       &values[oid_index], sizeof(values[oid_index]), ds->ds[oid_index].type);
539
540   sfree(values);
541
542   if (ret != 0) {
543     ERROR(PLUGIN_NAME ": Failed to convert '%s' value to snmp data", name);
544     return SNMP_NOSUCHINSTANCE;
545   }
546
547   requests->requestvb->type = dd->oids[oid_index].type;
548   snmp_set_var_typed_value(requests->requestvb, requests->requestvb->type,
549                            (const u_char *)data, data_len);
550
551   return SNMP_ERR_NOERROR;
552 }
553
554 static int
555 snmp_agent_table_oid_handler(struct netsnmp_mib_handler_s *handler,
556                              struct netsnmp_handler_registration_s *reginfo,
557                              struct netsnmp_agent_request_info_s *reqinfo,
558                              struct netsnmp_request_info_s *requests) {
559
560   if (reqinfo->mode != MODE_GET && reqinfo->mode != MODE_GETNEXT) {
561     DEBUG(PLUGIN_NAME ": Not supported request mode (%d)", reqinfo->mode);
562     return SNMP_ERR_NOERROR;
563   }
564
565   pthread_mutex_lock(&g_agent->lock);
566
567   oid_t oid;
568   memcpy(oid.oid, requests->requestvb->name,
569          sizeof(oid.oid[0]) * requests->requestvb->name_length);
570   oid.oid_len = requests->requestvb->name_length;
571
572 #if COLLECT_DEBUG
573   char oid_str[DATA_MAX_NAME_LEN];
574   snmp_agent_oid_to_string(oid_str, sizeof(oid_str), &oid);
575   DEBUG(PLUGIN_NAME ": Get request received for table OID '%s'", oid_str);
576 #endif
577
578   for (llentry_t *te = llist_head(g_agent->tables); te != NULL; te = te->next) {
579     table_definition_t *td = te->value;
580
581     for (llentry_t *de = llist_head(td->columns); de != NULL; de = de->next) {
582       data_definition_t *dd = de->value;
583
584       for (size_t i = 0; i < dd->oids_len; i++) {
585         int ret = snmp_oid_ncompare(oid.oid, oid.oid_len, dd->oids[i].oid,
586                                     dd->oids[i].oid_len,
587                                     MIN(oid.oid_len, dd->oids[i].oid_len));
588         if (ret != 0)
589           continue;
590
591         char *instance;
592
593         if (!td->index_oid.oid_len) {
594           char key[MAX_OID_LEN];
595
596           memset(key, 0, sizeof(key));
597           snmp_agent_generate_oid2string(
598               &oid, MIN(oid.oid_len, dd->oids[i].oid_len), key);
599
600           ret = c_avl_get(td->instance_index, key, (void **)&instance);
601           if (ret != 0) {
602             DEBUG(PLUGIN_NAME ": Nonexisting index string '%s' requested", key);
603             pthread_mutex_unlock(&g_agent->lock);
604             return SNMP_NOSUCHINSTANCE;
605           }
606         } else {
607           int index = oid.oid[oid.oid_len - 1];
608
609           ret = c_avl_get(td->index_instance, &index, (void **)&instance);
610           if (ret != 0) {
611             DEBUG(PLUGIN_NAME ": Nonexisting index '%d' requested", index);
612             pthread_mutex_unlock(&g_agent->lock);
613             return SNMP_NOSUCHINSTANCE;
614           }
615         }
616
617         if (dd->is_instance) {
618           requests->requestvb->type = ASN_OCTET_STR;
619           snmp_set_var_typed_value(requests->requestvb,
620                                    requests->requestvb->type, (const u_char *)instance,
621                                    strlen((instance)));
622
623           pthread_mutex_unlock(&g_agent->lock);
624
625           return SNMP_ERR_NOERROR;
626         }
627
628         ret = snmp_agent_form_reply(requests, dd, instance, i);
629
630         pthread_mutex_unlock(&g_agent->lock);
631
632         return ret;
633       }
634     }
635   }
636
637   pthread_mutex_unlock(&g_agent->lock);
638
639   return SNMP_NOSUCHINSTANCE;
640 }
641
642 static int snmp_agent_table_index_oid_handler(
643     struct netsnmp_mib_handler_s *handler,
644     struct netsnmp_handler_registration_s *reginfo,
645     struct netsnmp_agent_request_info_s *reqinfo,
646     struct netsnmp_request_info_s *requests) {
647
648   if (reqinfo->mode != MODE_GET && reqinfo->mode != MODE_GETNEXT) {
649     DEBUG(PLUGIN_NAME ": Not supported request mode (%d)", reqinfo->mode);
650     return SNMP_ERR_NOERROR;
651   }
652
653   pthread_mutex_lock(&g_agent->lock);
654
655   oid_t oid;
656   memcpy(oid.oid, requests->requestvb->name,
657          sizeof(oid.oid[0]) * requests->requestvb->name_length);
658   oid.oid_len = requests->requestvb->name_length;
659
660   for (llentry_t *te = llist_head(g_agent->tables); te != NULL; te = te->next) {
661     table_definition_t *td = te->value;
662
663     if (td->index_oid.oid_len &&
664         (snmp_oid_ncompare(oid.oid, oid.oid_len, td->index_oid.oid,
665                            td->index_oid.oid_len,
666                            MIN(oid.oid_len, td->index_oid.oid_len)) == 0)) {
667
668       DEBUG(PLUGIN_NAME ": Handle '%s' table index OID", td->name);
669
670       int index = oid.oid[oid.oid_len - 1];
671
672       int ret = c_avl_get(td->index_instance, &index, &(void *){NULL});
673       if (ret != 0) {
674         /* nonexisting index requested */
675         pthread_mutex_unlock(&g_agent->lock);
676         return SNMP_NOSUCHINSTANCE;
677       }
678
679       requests->requestvb->type = ASN_INTEGER;
680       snmp_set_var_typed_value(requests->requestvb, requests->requestvb->type,
681                                (const u_char *)&index, sizeof(index));
682
683       pthread_mutex_unlock(&g_agent->lock);
684
685       return SNMP_ERR_NOERROR;
686     }
687   }
688
689   pthread_mutex_unlock(&g_agent->lock);
690
691   return SNMP_NOSUCHINSTANCE;
692 }
693
694 static int snmp_agent_table_size_oid_handler(
695     struct netsnmp_mib_handler_s *handler,
696     struct netsnmp_handler_registration_s *reginfo,
697     struct netsnmp_agent_request_info_s *reqinfo,
698     struct netsnmp_request_info_s *requests) {
699
700   if (reqinfo->mode != MODE_GET && reqinfo->mode != MODE_GETNEXT) {
701     DEBUG(PLUGIN_NAME ": Not supported request mode (%d)", reqinfo->mode);
702     return SNMP_ERR_NOERROR;
703   }
704
705   pthread_mutex_lock(&g_agent->lock);
706
707   oid_t oid;
708   memcpy(oid.oid, requests->requestvb->name,
709          sizeof(oid.oid[0]) * requests->requestvb->name_length);
710   oid.oid_len = requests->requestvb->name_length;
711
712   DEBUG(PLUGIN_NAME ": Get request received for table size OID");
713
714   for (llentry_t *te = llist_head(g_agent->tables); te != NULL; te = te->next) {
715     table_definition_t *td = te->value;
716
717     if (td->size_oid.oid_len &&
718         (snmp_oid_ncompare(oid.oid, oid.oid_len, td->size_oid.oid,
719                            td->size_oid.oid_len,
720                            MIN(oid.oid_len, td->size_oid.oid_len)) == 0)) {
721       DEBUG(PLUGIN_NAME ": Handle '%s' table size OID", td->name);
722
723       long size = c_avl_size(td->index_instance);
724
725       requests->requestvb->type = td->size_oid.type;
726       snmp_set_var_typed_value(requests->requestvb, requests->requestvb->type,
727                                (const u_char *)&size, sizeof(size));
728
729       pthread_mutex_unlock(&g_agent->lock);
730
731       return SNMP_ERR_NOERROR;
732     }
733   }
734
735   pthread_mutex_unlock(&g_agent->lock);
736
737   return SNMP_NOSUCHINSTANCE;
738 }
739
740 static int
741 snmp_agent_scalar_oid_handler(struct netsnmp_mib_handler_s *handler,
742                               struct netsnmp_handler_registration_s *reginfo,
743                               struct netsnmp_agent_request_info_s *reqinfo,
744                               struct netsnmp_request_info_s *requests) {
745
746   if (reqinfo->mode != MODE_GET && reqinfo->mode != MODE_GETNEXT) {
747     DEBUG(PLUGIN_NAME ": Not supported request mode (%d)", reqinfo->mode);
748     return SNMP_ERR_NOERROR;
749   }
750
751   pthread_mutex_lock(&g_agent->lock);
752
753   oid_t oid;
754   memcpy(oid.oid, requests->requestvb->name,
755          sizeof(oid.oid[0]) * requests->requestvb->name_length);
756   oid.oid_len = requests->requestvb->name_length;
757
758 #if COLLECT_DEBUG
759   char oid_str[DATA_MAX_NAME_LEN];
760   snmp_agent_oid_to_string(oid_str, sizeof(oid_str), &oid);
761   DEBUG(PLUGIN_NAME ": Get request received for scalar OID '%s'", oid_str);
762 #endif
763
764   for (llentry_t *de = llist_head(g_agent->scalars); de != NULL;
765        de = de->next) {
766     data_definition_t *dd = de->value;
767
768     for (size_t i = 0; i < dd->oids_len; i++) {
769
770       int ret = snmp_oid_compare(oid.oid, oid.oid_len, dd->oids[i].oid,
771                                  dd->oids[i].oid_len);
772       if (ret != 0)
773         continue;
774
775       ret = snmp_agent_form_reply(requests, dd, NULL, i);
776
777       pthread_mutex_unlock(&g_agent->lock);
778
779       return ret;
780     }
781   }
782
783   pthread_mutex_unlock(&g_agent->lock);
784
785   return SNMP_NOSUCHINSTANCE;
786 }
787
788 static int snmp_agent_register_table_oids(void) {
789
790   for (llentry_t *te = llist_head(g_agent->tables); te != NULL; te = te->next) {
791     table_definition_t *td = te->value;
792
793     if (td->size_oid.oid_len != 0) {
794       td->size_oid.type =
795           snmp_agent_get_asn_type(td->size_oid.oid, td->size_oid.oid_len);
796       td->size_oid.oid_len++;
797       int ret = snmp_agent_register_oid(&td->size_oid,
798                                         snmp_agent_table_size_oid_handler);
799       if (ret != 0)
800         return ret;
801     }
802
803     for (llentry_t *de = llist_head(td->columns); de != NULL; de = de->next) {
804       data_definition_t *dd = de->value;
805
806       for (size_t i = 0; i < dd->oids_len; i++) {
807         dd->oids[i].type =
808             snmp_agent_get_asn_type(dd->oids[i].oid, dd->oids[i].oid_len);
809       }
810     }
811   }
812
813   return 0;
814 }
815
816 static int snmp_agent_register_scalar_oids(void) {
817
818   for (llentry_t *e = llist_head(g_agent->scalars); e != NULL; e = e->next) {
819     data_definition_t *dd = e->value;
820
821     for (size_t i = 0; i < dd->oids_len; i++) {
822
823       dd->oids[i].type =
824           snmp_agent_get_asn_type(dd->oids[i].oid, dd->oids[i].oid_len);
825
826       int ret =
827           snmp_agent_register_oid(&dd->oids[i], snmp_agent_scalar_oid_handler);
828       if (ret != 0)
829         return ret;
830     }
831   }
832
833   return 0;
834 }
835
836 static int snmp_agent_config_data_oids(data_definition_t *dd,
837                                        oconfig_item_t *ci) {
838   if (ci->values_num < 1) {
839     WARNING(PLUGIN_NAME ": `OIDs' needs at least one argument");
840     return -EINVAL;
841   }
842
843   for (int i = 0; i < ci->values_num; i++)
844     if (ci->values[i].type != OCONFIG_TYPE_STRING) {
845       WARNING(PLUGIN_NAME ": `OIDs' needs only string argument");
846       return -EINVAL;
847     }
848
849   if (dd->oids != NULL)
850     sfree(dd->oids);
851   dd->oids_len = 0;
852   dd->oids = calloc(ci->values_num, sizeof(*dd->oids));
853   if (dd->oids == NULL)
854     return -ENOMEM;
855   dd->oids_len = (size_t)ci->values_num;
856
857   for (int i = 0; i < ci->values_num; i++) {
858     dd->oids[i].oid_len = MAX_OID_LEN;
859
860     if (NULL == snmp_parse_oid(ci->values[i].value.string, dd->oids[i].oid,
861                                &dd->oids[i].oid_len)) {
862       ERROR(PLUGIN_NAME ": snmp_parse_oid (%s) failed",
863             ci->values[i].value.string);
864       sfree(dd->oids);
865       dd->oids_len = 0;
866       return -1;
867     }
868   }
869
870   return 0;
871 }
872
873 static int snmp_agent_config_table_size_oid(table_definition_t *td,
874                                             oconfig_item_t *ci) {
875   if (ci->values_num < 1) {
876     WARNING(PLUGIN_NAME ": `TableSizeOID' is empty");
877     return -EINVAL;
878   }
879
880   if (ci->values[0].type != OCONFIG_TYPE_STRING) {
881     WARNING(PLUGIN_NAME ": `TableSizeOID' needs only string argument");
882     return -EINVAL;
883   }
884
885   td->size_oid.oid_len = MAX_OID_LEN;
886
887   if (NULL == snmp_parse_oid(ci->values[0].value.string, td->size_oid.oid,
888                              &td->size_oid.oid_len)) {
889     ERROR(PLUGIN_NAME ": Failed to parse table size OID (%s)",
890           ci->values[0].value.string);
891     td->size_oid.oid_len = 0;
892     return -EINVAL;
893   }
894
895   return 0;
896 }
897
898 static int snmp_agent_config_table_index_oid(table_definition_t *td,
899                                              oconfig_item_t *ci) {
900
901   if (ci->values_num < 1) {
902     WARNING(PLUGIN_NAME ": `IndexOID' is empty");
903     return -EINVAL;
904   }
905
906   if (ci->values[0].type != OCONFIG_TYPE_STRING) {
907     WARNING(PLUGIN_NAME ": `IndexOID' needs only string argument");
908     return -EINVAL;
909   }
910
911   td->index_oid.oid_len = MAX_OID_LEN;
912
913   if (NULL == snmp_parse_oid(ci->values[0].value.string, td->index_oid.oid,
914                              &td->index_oid.oid_len)) {
915     ERROR(PLUGIN_NAME ": Failed to parse table index OID (%s)",
916           ci->values[0].value.string);
917     td->index_oid.oid_len = 0;
918     return -EINVAL;
919   }
920
921   return 0;
922 }
923
924 static int snmp_agent_config_table_data(table_definition_t *td,
925                                         oconfig_item_t *ci) {
926   data_definition_t *dd;
927   int ret = 0;
928
929   assert(ci != NULL);
930
931   dd = calloc(1, sizeof(*dd));
932   if (dd == NULL) {
933     ERROR(PLUGIN_NAME ": Failed to allocate memory for table data definition");
934     return -ENOMEM;
935   }
936
937   ret = cf_util_get_string(ci, &dd->name);
938   if (ret != 0) {
939     sfree(dd);
940     return -1;
941   }
942
943   dd->scale = 1.0;
944   dd->shift = 0.0;
945
946   dd->table = td;
947
948   for (int i = 0; i < ci->children_num; i++) {
949     oconfig_item_t *option = ci->children + i;
950
951     if (strcasecmp("Instance", option->key) == 0)
952       ret = cf_util_get_boolean(option, &dd->is_instance);
953     else if (strcasecmp("Plugin", option->key) == 0)
954       ret = cf_util_get_string(option, &dd->plugin);
955     else if (strcasecmp("PluginInstance", option->key) == 0)
956       ret = cf_util_get_string(option, &dd->plugin_instance);
957     else if (strcasecmp("Type", option->key) == 0)
958       ret = cf_util_get_string(option, &dd->type);
959     else if (strcasecmp("TypeInstance", option->key) == 0)
960       ret = cf_util_get_string(option, &dd->type_instance);
961     else if (strcasecmp("Shift", option->key) == 0)
962       ret = cf_util_get_double(option, &dd->shift);
963     else if (strcasecmp("Scale", option->key) == 0)
964       ret = cf_util_get_double(option, &dd->scale);
965     else if (strcasecmp("OIDs", option->key) == 0)
966       ret = snmp_agent_config_data_oids(dd, option);
967     else {
968       WARNING(PLUGIN_NAME ": Option `%s' not allowed here", option->key);
969       ret = -1;
970     }
971
972     if (ret != 0) {
973       snmp_agent_free_data(&dd);
974       return -1;
975     }
976   }
977
978   llentry_t *entry = llentry_create(dd->name, dd);
979   if (entry == NULL) {
980     snmp_agent_free_data(&dd);
981     return -ENOMEM;
982   }
983
984   llist_append(td->columns, entry);
985
986   return 0;
987 }
988
989 static int snmp_agent_config_data(oconfig_item_t *ci) {
990   data_definition_t *dd;
991   int ret = 0;
992
993   assert(ci != NULL);
994
995   dd = calloc(1, sizeof(*dd));
996   if (dd == NULL) {
997     ERROR(PLUGIN_NAME ": Failed to allocate memory for data definition");
998     return -ENOMEM;
999   }
1000
1001   ret = cf_util_get_string(ci, &dd->name);
1002   if (ret != 0) {
1003     free(dd);
1004     return -1;
1005   }
1006
1007   dd->scale = 1.0;
1008   dd->shift = 0.0;
1009
1010   for (int i = 0; i < ci->children_num; i++) {
1011     oconfig_item_t *option = ci->children + i;
1012
1013     if (strcasecmp("Instance", option->key) == 0)
1014       ret = cf_util_get_boolean(option, &dd->is_instance);
1015     else if (strcasecmp("Plugin", option->key) == 0)
1016       ret = cf_util_get_string(option, &dd->plugin);
1017     else if (strcasecmp("PluginInstance", option->key) == 0)
1018       ret = cf_util_get_string(option, &dd->plugin_instance);
1019     else if (strcasecmp("Type", option->key) == 0)
1020       ret = cf_util_get_string(option, &dd->type);
1021     else if (strcasecmp("TypeInstance", option->key) == 0)
1022       ret = cf_util_get_string(option, &dd->type_instance);
1023     else if (strcasecmp("Shift", option->key) == 0)
1024       ret = cf_util_get_double(option, &dd->shift);
1025     else if (strcasecmp("Scale", option->key) == 0)
1026       ret = cf_util_get_double(option, &dd->scale);
1027     else if (strcasecmp("OIDs", option->key) == 0)
1028       ret = snmp_agent_config_data_oids(dd, option);
1029     else {
1030       WARNING(PLUGIN_NAME ": Option `%s' not allowed here", option->key);
1031       ret = -1;
1032     }
1033
1034     if (ret != 0) {
1035       snmp_agent_free_data(&dd);
1036       return -1;
1037     }
1038   }
1039
1040   llentry_t *entry = llentry_create(dd->name, dd);
1041   if (entry == NULL) {
1042     snmp_agent_free_data(&dd);
1043     return -ENOMEM;
1044   }
1045
1046   llist_append(g_agent->scalars, entry);
1047
1048   return 0;
1049 }
1050
1051 static int num_compare(const int *a, const int *b) {
1052   assert((a != NULL) && (b != NULL));
1053   if (*a < *b)
1054     return -1;
1055   else if (*a > *b)
1056     return 1;
1057   else
1058     return 0;
1059 }
1060
1061 static int snmp_agent_config_table(oconfig_item_t *ci) {
1062   table_definition_t *td;
1063   int ret = 0;
1064
1065   assert(ci != NULL);
1066
1067   td = calloc(1, sizeof(*td));
1068   if (td == NULL) {
1069     ERROR(PLUGIN_NAME ": Failed to allocate memory for table definition");
1070     return -ENOMEM;
1071   }
1072
1073   ret = cf_util_get_string(ci, &td->name);
1074   if (ret != 0) {
1075     sfree(td);
1076     return -1;
1077   }
1078
1079   td->columns = llist_create();
1080   if (td->columns == NULL) {
1081     ERROR(PLUGIN_NAME ": Failed to allocate memory for columns list");
1082     snmp_agent_free_table(&td);
1083     return -ENOMEM;
1084   }
1085
1086   for (int i = 0; i < ci->children_num; i++) {
1087     oconfig_item_t *option = ci->children + i;
1088
1089     if (strcasecmp("IndexOID", option->key) == 0)
1090       ret = snmp_agent_config_table_index_oid(td, option);
1091     else if (strcasecmp("SizeOID", option->key) == 0)
1092       ret = snmp_agent_config_table_size_oid(td, option);
1093     else if (strcasecmp("Data", option->key) == 0)
1094       ret = snmp_agent_config_table_data(td, option);
1095     else {
1096       WARNING(PLUGIN_NAME ": Option `%s' not allowed here", option->key);
1097       ret = -1;
1098     }
1099
1100     if (ret != 0) {
1101       snmp_agent_free_table(&td);
1102       return -ENOMEM;
1103     }
1104   }
1105
1106   llentry_t *entry = llentry_create(td->name, td);
1107   if (entry == NULL) {
1108     snmp_agent_free_table(&td);
1109     return -ENOMEM;
1110   }
1111
1112   td->instance_index =
1113       c_avl_create((int (*)(const void *, const void *))strcmp);
1114   if (td->instance_index == NULL) {
1115     snmp_agent_free_table(&td);
1116     return -ENOMEM;
1117   }
1118
1119   td->index_instance =
1120       c_avl_create((int (*)(const void *, const void *))num_compare);
1121   if (td->index_instance == NULL) {
1122     snmp_agent_free_table(&td);
1123     return -ENOMEM;
1124   }
1125
1126   llist_append(g_agent->tables, entry);
1127
1128   return 0;
1129 }
1130
1131 static int snmp_agent_get_value_from_ds_type(const value_t *val, int type,
1132                                              double scale, double shift,
1133                                              long *value) {
1134   switch (type) {
1135   case DS_TYPE_COUNTER:
1136     *value = (long)((val->counter * scale) + shift);
1137     break;
1138   case DS_TYPE_ABSOLUTE:
1139     *value = (long)((val->absolute * scale) + shift);
1140     break;
1141   case DS_TYPE_DERIVE:
1142     *value = (long)((val->derive * scale) + shift);
1143     break;
1144   case DS_TYPE_GAUGE:
1145     *value = (long)((val->gauge * scale) + shift);
1146     break;
1147   case TYPE_STRING:
1148     break;
1149   default:
1150     ERROR(PLUGIN_NAME ": Unknown data source type: %i", type);
1151     return -EINVAL;
1152   }
1153
1154   return 0;
1155 }
1156
1157 static int snmp_agent_set_vardata(void *data, size_t *data_len, u_char asn_type,
1158                                   double scale, double shift, const void *value,
1159                                   size_t len, int type) {
1160
1161   int ret;
1162   netsnmp_vardata var;
1163   const value_t *val;
1164   long new_value = 0;
1165
1166   val = value;
1167   var.string = (u_char *)data;
1168
1169   ret = snmp_agent_get_value_from_ds_type(val, type, scale, shift, &new_value);
1170   if (ret != 0)
1171     return ret;
1172
1173   switch (asn_type) {
1174   case ASN_INTEGER:
1175   case ASN_UINTEGER:
1176   case ASN_COUNTER:
1177   case ASN_TIMETICKS:
1178   case ASN_GAUGE:
1179     if (*data_len < sizeof(*var.integer))
1180       return -EINVAL;
1181     *var.integer = new_value;
1182     *data_len = sizeof(*var.integer);
1183     break;
1184   case ASN_COUNTER64:
1185     if (*data_len < sizeof(*var.counter64))
1186       return -EINVAL;
1187     var.counter64->high = (u_long)((int64_t)new_value >> 32);
1188     var.counter64->low = (u_long)((int64_t)new_value & 0xFFFFFFFF);
1189     *data_len = sizeof(*var.counter64);
1190     break;
1191   case ASN_OCTET_STR:
1192     if (type == DS_TYPE_GAUGE) {
1193       char buf[DATA_MAX_NAME_LEN];
1194       snprintf(buf, sizeof(buf), "%.2f", val->gauge);
1195       if (*data_len < strlen(buf))
1196         return -EINVAL;
1197       *data_len = strlen(buf);
1198       memcpy(var.string, buf, *data_len);
1199     } else {
1200       ERROR(PLUGIN_NAME ": Failed to convert %d ds type to %d asn type", type,
1201             asn_type);
1202       return -EINVAL;
1203     }
1204     break;
1205   default:
1206     ERROR(PLUGIN_NAME ": Failed to convert %d ds type to %d asn type", type,
1207           asn_type);
1208     return -EINVAL;
1209   }
1210
1211   return 0;
1212 }
1213
1214 static int snmp_agent_register_oid_index(oid_t *oid, int index,
1215                                          Netsnmp_Node_Handler *handler) {
1216   oid_t new_oid;
1217   memcpy(&new_oid, oid, sizeof(*oid));
1218   new_oid.oid[new_oid.oid_len++] = index;
1219   return snmp_agent_register_oid(&new_oid, handler);
1220 }
1221
1222 static int snmp_agent_unregister_oid_index(oid_t *oid, int index) {
1223   oid_t new_oid;
1224   memcpy(&new_oid, oid, sizeof(*oid));
1225   new_oid.oid[new_oid.oid_len++] = index;
1226   return unregister_mib(new_oid.oid, new_oid.oid_len);
1227 }
1228
1229 static int snmp_agent_update_index(table_definition_t *td,
1230                                    const char *instance) {
1231
1232   if (c_avl_get(td->instance_index, instance, NULL) == 0)
1233     return 0;
1234
1235   int ret;
1236   int *index = NULL;
1237   char *ins;
1238
1239   ins = strdup(instance);
1240   if (ins == NULL)
1241     return -ENOMEM;
1242
1243   /* need to generate index for the table */
1244   if (td->index_oid.oid_len) {
1245     index = calloc(1, sizeof(*index));
1246     if (index == NULL) {
1247       sfree(ins);
1248       return -ENOMEM;
1249     }
1250
1251     *index = c_avl_size(td->instance_index) + 1;
1252
1253     ret = c_avl_insert(td->instance_index, ins, index);
1254     if (ret != 0) {
1255       sfree(ins);
1256       sfree(index);
1257       return ret;
1258     }
1259
1260     ret = c_avl_insert(td->index_instance, index, ins);
1261     if (ret < 0) {
1262       DEBUG(PLUGIN_NAME ": Failed to update index_instance for '%s' table",
1263             td->name);
1264       c_avl_remove(td->instance_index, ins, NULL, (void **)&index);
1265       sfree(ins);
1266       sfree(index);
1267       return ret;
1268     }
1269
1270     ret = snmp_agent_register_oid_index(&td->index_oid, *index,
1271                                         snmp_agent_table_index_oid_handler);
1272     if (ret != 0)
1273       return ret;
1274   } else {
1275     /* instance as a key is required for any table */
1276     ret = c_avl_insert(td->instance_index, ins, ins);
1277     if (ret != 0) {
1278       sfree(ins);
1279       return ret;
1280     }
1281   }
1282
1283   /* register new oids for all columns */
1284   for (llentry_t *de = llist_head(td->columns); de != NULL; de = de->next) {
1285     data_definition_t *dd = de->value;
1286
1287     for (size_t i = 0; i < dd->oids_len; i++) {
1288       if (td->index_oid.oid_len) {
1289         ret = snmp_agent_register_oid_index(&dd->oids[i], *index,
1290                                             snmp_agent_table_oid_handler);
1291       } else {
1292         ret = snmp_agent_register_oid_string(&dd->oids[i], ins,
1293                                              snmp_agent_table_oid_handler);
1294       }
1295
1296       if (ret != 0)
1297         return ret;
1298     }
1299   }
1300
1301   DEBUG(PLUGIN_NAME ": Updated index for '%s' table [%d, %s]", td->name,
1302         (index != NULL) ? *index : -1, ins);
1303
1304   notification_t n = {
1305       .severity = NOTIF_OKAY, .time = cdtime(), .plugin = PLUGIN_NAME};
1306   sstrncpy(n.host, hostname_g, sizeof(n.host));
1307   sstrncpy(n.plugin_instance, ins, sizeof(n.plugin_instance));
1308   ssnprintf(n.message, sizeof(n.message),
1309             "Data row added to table %s instance %s index %d", td->name, ins,
1310             (index != NULL) ? *index : -1);
1311   plugin_dispatch_notification(&n);
1312
1313   return 0;
1314 }
1315
1316 static int snmp_agent_write(value_list_t const *vl) {
1317
1318   if (vl == NULL)
1319     return -EINVAL;
1320
1321   for (llentry_t *te = llist_head(g_agent->tables); te != NULL; te = te->next) {
1322     table_definition_t *td = te->value;
1323
1324     for (llentry_t *de = llist_head(td->columns); de != NULL; de = de->next) {
1325       data_definition_t *dd = de->value;
1326
1327       if (!dd->is_instance) {
1328         if (CHECK_DD_TYPE(dd, vl->plugin, vl->plugin_instance, vl->type,
1329                           vl->type_instance)) {
1330           snmp_agent_update_index(td, vl->plugin_instance);
1331           return 0;
1332         }
1333       }
1334     }
1335   }
1336
1337   return 0;
1338 }
1339
1340 static int snmp_agent_collect(const data_set_t *ds, const value_list_t *vl,
1341                               user_data_t __attribute__((unused)) * user_data) {
1342
1343   pthread_mutex_lock(&g_agent->lock);
1344
1345   snmp_agent_write(vl);
1346
1347   pthread_mutex_unlock(&g_agent->lock);
1348
1349   return 0;
1350 }
1351
1352 static int snmp_agent_preinit(void) {
1353   if (g_agent != NULL) {
1354     /* already initialized if config callback was called before init callback */
1355     return 0;
1356   }
1357
1358   g_agent = calloc(1, sizeof(*g_agent));
1359   if (g_agent == NULL) {
1360     ERROR(PLUGIN_NAME ": Failed to allocate memory for snmp agent context");
1361     return -ENOMEM;
1362   }
1363
1364   g_agent->tables = llist_create();
1365   g_agent->scalars = llist_create();
1366
1367   int err;
1368   /* make us a agentx client. */
1369   err = netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_AGENT_ROLE,
1370                                1);
1371   if (err != 0) {
1372     ERROR(PLUGIN_NAME ": Failed to set agent role (%d)", err);
1373     return -1;
1374   }
1375
1376   /*
1377    *  For SNMP debug purposes uses snmp_set_do_debugging(1);
1378    */
1379
1380   /* initialize the agent library */
1381   err = init_agent(PLUGIN_NAME);
1382   if (err != 0) {
1383     ERROR(PLUGIN_NAME ": Failed to initialize the agent library (%d)", err);
1384     return -1;
1385   }
1386
1387   init_snmp(PLUGIN_NAME);
1388
1389   g_agent->tp = read_all_mibs();
1390
1391   return 0;
1392 }
1393
1394 static int snmp_agent_init(void) {
1395   int ret;
1396
1397   ret = snmp_agent_preinit();
1398   if (ret != 0)
1399     return ret;
1400
1401   ret = snmp_agent_register_scalar_oids();
1402   if (ret != 0)
1403     return ret;
1404
1405   ret = snmp_agent_register_table_oids();
1406   if (ret != 0)
1407     return ret;
1408
1409   ret = pthread_mutex_init(&g_agent->lock, NULL);
1410   if (ret != 0) {
1411     ERROR(PLUGIN_NAME ": Failed to initialize mutex, err %u", ret);
1412     return ret;
1413   }
1414
1415   ret = pthread_mutex_init(&g_agent->agentx_lock, NULL);
1416   if (ret != 0) {
1417     ERROR(PLUGIN_NAME ": Failed to initialize AgentX mutex, err %u", ret);
1418     return ret;
1419   }
1420
1421   /* create a second thread to listen for requests from AgentX*/
1422   ret = pthread_create(&g_agent->thread, NULL, &snmp_agent_thread_run, NULL);
1423   if (ret != 0) {
1424     ERROR(PLUGIN_NAME ": Failed to create a separate thread, err %u", ret);
1425     return ret;
1426   }
1427
1428   return 0;
1429 }
1430
1431 static void *snmp_agent_thread_run(void __attribute__((unused)) * arg) {
1432   INFO(PLUGIN_NAME ": Thread is up and running");
1433
1434   for (;;) {
1435     pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
1436
1437     pthread_mutex_lock(&g_agent->agentx_lock);
1438     agent_check_and_process(0); /* 0 == don't block */
1439     pthread_mutex_unlock(&g_agent->agentx_lock);
1440
1441     pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
1442     usleep(10);
1443   }
1444
1445   pthread_exit(0);
1446 }
1447
1448 static int snmp_agent_register_oid(oid_t *oid, Netsnmp_Node_Handler *handler) {
1449   netsnmp_handler_registration *reg;
1450   char *oid_name = snmp_agent_get_oid_name(oid->oid, oid->oid_len - 1);
1451   char oid_str[DATA_MAX_NAME_LEN];
1452
1453   snmp_agent_oid_to_string(oid_str, sizeof(oid_str), oid);
1454
1455   if (oid_name == NULL) {
1456     WARNING(PLUGIN_NAME
1457             ": Skipped registration: OID (%s) is not found in main tree",
1458             oid_str);
1459     return 0;
1460   }
1461
1462   reg = netsnmp_create_handler_registration(oid_name, handler, oid->oid,
1463                                             oid->oid_len, HANDLER_CAN_RONLY);
1464   if (reg == NULL) {
1465     ERROR(PLUGIN_NAME ": Failed to create handler registration for OID (%s)",
1466           oid_str);
1467     return -1;
1468   }
1469
1470   pthread_mutex_lock(&g_agent->agentx_lock);
1471
1472   if (netsnmp_register_instance(reg) != MIB_REGISTERED_OK) {
1473     ERROR(PLUGIN_NAME ": Failed to register handler for OID (%s)", oid_str);
1474     pthread_mutex_unlock(&g_agent->agentx_lock);
1475     return -1;
1476   }
1477
1478   pthread_mutex_unlock(&g_agent->agentx_lock);
1479
1480   DEBUG(PLUGIN_NAME ": Registered handler for OID (%s)", oid_str);
1481
1482   return 0;
1483 }
1484
1485 static int snmp_agent_free_config(void) {
1486
1487   if (g_agent == NULL)
1488     return -EINVAL;
1489
1490   for (llentry_t *te = llist_head(g_agent->tables); te != NULL; te = te->next)
1491     snmp_agent_free_table((table_definition_t **)&te->value);
1492   llist_destroy(g_agent->tables);
1493
1494   for (llentry_t *de = llist_head(g_agent->scalars); de != NULL; de = de->next)
1495     snmp_agent_free_data((data_definition_t **)&de->value);
1496   llist_destroy(g_agent->scalars);
1497
1498   return 0;
1499 }
1500
1501 static int snmp_agent_shutdown(void) {
1502   int ret = 0;
1503
1504   DEBUG(PLUGIN_NAME ": snmp_agent_shutdown");
1505
1506   if (g_agent == NULL) {
1507     ERROR(PLUGIN_NAME ": snmp_agent_shutdown: plugin not initialized");
1508     return -EINVAL;
1509   }
1510
1511   if (pthread_cancel(g_agent->thread) != 0)
1512     ERROR(PLUGIN_NAME ": snmp_agent_shutdown: failed to cancel the thread");
1513
1514   if (pthread_join(g_agent->thread, NULL) != 0)
1515     ERROR(PLUGIN_NAME ": snmp_agent_shutdown: failed to join the thread");
1516
1517   snmp_agent_free_config();
1518
1519   snmp_shutdown(PLUGIN_NAME);
1520
1521   pthread_mutex_destroy(&g_agent->lock);
1522   pthread_mutex_destroy(&g_agent->agentx_lock);
1523
1524   sfree(g_agent);
1525
1526   return ret;
1527 }
1528
1529 static int snmp_agent_config(oconfig_item_t *ci) {
1530
1531   int ret = snmp_agent_preinit();
1532
1533   if (ret != 0) {
1534     sfree(g_agent);
1535     return -EINVAL;
1536   }
1537
1538   for (int i = 0; i < ci->children_num; i++) {
1539     oconfig_item_t *child = ci->children + i;
1540     if (strcasecmp("Data", child->key) == 0) {
1541       ret = snmp_agent_config_data(child);
1542     } else if (strcasecmp("Table", child->key) == 0) {
1543       ret = snmp_agent_config_table(child);
1544     } else {
1545       ERROR(PLUGIN_NAME ": Unknown configuration option `%s'", child->key);
1546       ret = (-EINVAL);
1547     }
1548
1549     if (ret != 0) {
1550       ERROR(PLUGIN_NAME ": Failed to parse configuration");
1551       snmp_agent_free_config();
1552       snmp_shutdown(PLUGIN_NAME);
1553       sfree(g_agent);
1554       return -EINVAL;
1555     }
1556   }
1557
1558   ret = snmp_agent_validate_data();
1559   if (ret != 0) {
1560     ERROR(PLUGIN_NAME ": Invalid configuration provided");
1561     snmp_agent_free_config();
1562     snmp_shutdown(PLUGIN_NAME);
1563     sfree(g_agent);
1564     return -EINVAL;
1565   }
1566
1567   return 0;
1568 }
1569
1570 void module_register(void) {
1571   plugin_register_init(PLUGIN_NAME, snmp_agent_init);
1572   plugin_register_complex_config(PLUGIN_NAME, snmp_agent_config);
1573   plugin_register_write(PLUGIN_NAME, snmp_agent_collect, NULL);
1574   plugin_register_missing(PLUGIN_NAME, snmp_agent_clear_missing, NULL);
1575   plugin_register_shutdown(PLUGIN_NAME, snmp_agent_shutdown);
1576 }