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