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