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