Merge branch 'collectd-5.8'
[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[%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,
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   td->instance_index =
1121       c_avl_create((int (*)(const void *, const void *))strcmp);
1122   if (td->instance_index == NULL) {
1123     snmp_agent_free_table(&td);
1124     return -ENOMEM;
1125   }
1126
1127   td->index_instance =
1128       c_avl_create((int (*)(const void *, const void *))num_compare);
1129   if (td->index_instance == NULL) {
1130     snmp_agent_free_table(&td);
1131     return -ENOMEM;
1132   }
1133
1134   llentry_t *entry = llentry_create(td->name, td);
1135   if (entry == NULL) {
1136     snmp_agent_free_table(&td);
1137     return -ENOMEM;
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   snprintf(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 }