Merge pull request #2817 from rpv-tomsk/snmp-fix-2291-1
[collectd.git] / src / snmp.c
1 /**
2  * collectd - src/snmp.c
3  * Copyright (C) 2007-2012  Florian octo Forster
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Florian octo Forster <octo at collectd.org>
25  **/
26
27 #include "collectd.h"
28
29 #include "common.h"
30 #include "plugin.h"
31 #include "utils_complain.h"
32
33 #include <net-snmp/net-snmp-config.h>
34 #include <net-snmp/net-snmp-includes.h>
35
36 #include <fnmatch.h>
37
38 /*
39  * Private data structes
40  */
41 struct oid_s {
42   oid oid[MAX_OID_LEN];
43   size_t oid_len;
44 };
45 typedef struct oid_s oid_t;
46
47 struct instance_s {
48   bool configured;
49   bool is_plugin;
50   oid_t oid;
51 };
52 typedef struct instance_s instance_t;
53
54 struct data_definition_s {
55   char *name; /* used to reference this from the `Collect' option */
56   char *type; /* used to find the data_set */
57   bool is_table;
58   instance_t instance;
59   char *plugin_name;
60   char *plugin_instance;
61   char *type_instance;
62   char *instance_prefix;
63   oid_t *values;
64   size_t values_len;
65   double scale;
66   double shift;
67   struct data_definition_s *next;
68   char **ignores;
69   size_t ignores_len;
70   bool invert_match;
71 };
72 typedef struct data_definition_s data_definition_t;
73
74 struct host_definition_s {
75   char *name;
76   char *address;
77   int version;
78   cdtime_t timeout;
79   int retries;
80
81   /* snmpv1/2 options */
82   char *community;
83
84   /* snmpv3 security options */
85   char *username;
86   oid *auth_protocol;
87   size_t auth_protocol_len;
88   char *auth_passphrase;
89   oid *priv_protocol;
90   size_t priv_protocol_len;
91   char *priv_passphrase;
92   int security_level;
93   char *context;
94
95   void *sess_handle;
96   c_complain_t complaint;
97   cdtime_t interval;
98   data_definition_t **data_list;
99   int data_list_len;
100 };
101 typedef struct host_definition_s host_definition_t;
102
103 /* These two types are used to cache values in `csnmp_read_table' to handle
104  * gaps in tables. */
105 struct csnmp_list_instances_s {
106   oid_t suffix;
107   char instance[DATA_MAX_NAME_LEN];
108   struct csnmp_list_instances_s *next;
109 };
110 typedef struct csnmp_list_instances_s csnmp_list_instances_t;
111
112 struct csnmp_table_values_s {
113   oid_t suffix;
114   value_t value;
115   struct csnmp_table_values_s *next;
116 };
117 typedef struct csnmp_table_values_s csnmp_table_values_t;
118
119 /*
120  * Private variables
121  */
122 static data_definition_t *data_head;
123
124 /*
125  * Prototypes
126  */
127 static int csnmp_read_host(user_data_t *ud);
128
129 /*
130  * Private functions
131  */
132 static void csnmp_oid_init(oid_t *dst, oid const *src, size_t n) {
133   assert(n <= STATIC_ARRAY_SIZE(dst->oid));
134   memcpy(dst->oid, src, sizeof(*src) * n);
135   dst->oid_len = n;
136 }
137
138 static int csnmp_oid_compare(oid_t const *left, oid_t const *right) {
139   return snmp_oid_compare(left->oid, left->oid_len, right->oid, right->oid_len);
140 }
141
142 static int csnmp_oid_suffix(oid_t *dst, oid_t const *src, oid_t const *root) {
143   /* Make sure "src" is in "root"s subtree. */
144   if (src->oid_len <= root->oid_len)
145     return EINVAL;
146   if (snmp_oid_ncompare(root->oid, root->oid_len, src->oid, src->oid_len,
147                         /* n = */ root->oid_len) != 0)
148     return EINVAL;
149
150   memset(dst, 0, sizeof(*dst));
151   dst->oid_len = src->oid_len - root->oid_len;
152   memcpy(dst->oid, &src->oid[root->oid_len],
153          dst->oid_len * sizeof(dst->oid[0]));
154   return 0;
155 }
156
157 static int csnmp_oid_to_string(char *buffer, size_t buffer_size,
158                                oid_t const *o) {
159   char oid_str[MAX_OID_LEN][16];
160   char *oid_str_ptr[MAX_OID_LEN];
161
162   for (size_t i = 0; i < o->oid_len; i++) {
163     snprintf(oid_str[i], sizeof(oid_str[i]), "%lu", (unsigned long)o->oid[i]);
164     oid_str_ptr[i] = oid_str[i];
165   }
166
167   return strjoin(buffer, buffer_size, oid_str_ptr, o->oid_len, ".");
168 }
169
170 static void csnmp_host_close_session(host_definition_t *host) /* {{{ */
171 {
172   if (host->sess_handle == NULL)
173     return;
174
175   snmp_sess_close(host->sess_handle);
176   host->sess_handle = NULL;
177 } /* }}} void csnmp_host_close_session */
178
179 static void csnmp_host_definition_destroy(void *arg) /* {{{ */
180 {
181   host_definition_t *hd;
182
183   hd = arg;
184
185   if (hd == NULL)
186     return;
187
188   if (hd->name != NULL) {
189     DEBUG("snmp plugin: Destroying host definition for host `%s'.", hd->name);
190   }
191
192   csnmp_host_close_session(hd);
193
194   sfree(hd->name);
195   sfree(hd->address);
196   sfree(hd->community);
197   sfree(hd->username);
198   sfree(hd->auth_passphrase);
199   sfree(hd->priv_passphrase);
200   sfree(hd->context);
201   sfree(hd->data_list);
202
203   sfree(hd);
204 } /* }}} void csnmp_host_definition_destroy */
205
206 /* Many functions to handle the configuration. {{{ */
207 /* First there are many functions which do configuration stuff. It's a big
208  * bloated and messy, I'm afraid. */
209
210 /*
211  * Callgraph for the config stuff:
212  *  csnmp_config
213  *  +-> call_snmp_init_once
214  *  +-> csnmp_config_add_data
215  *  !   +-> csnmp_config_add_data_instance
216  *  !   +-> csnmp_config_add_data_values
217  *  +-> csnmp_config_add_host
218  *      +-> csnmp_config_add_host_version
219  *      +-> csnmp_config_add_host_collect
220  *      +-> csnmp_config_add_host_auth_protocol
221  *      +-> csnmp_config_add_host_priv_protocol
222  *      +-> csnmp_config_add_host_security_level
223  */
224 static void call_snmp_init_once(void) {
225   static int have_init;
226
227   if (have_init == 0)
228     init_snmp(PACKAGE_NAME);
229   have_init = 1;
230 } /* void call_snmp_init_once */
231
232 static int csnmp_config_add_data_instance_oid(data_definition_t *dd,
233                                               oconfig_item_t *ci,
234                                               bool is_plugin) {
235   char buffer[DATA_MAX_NAME_LEN];
236   int status;
237
238   status = cf_util_get_string_buffer(ci, buffer, sizeof(buffer));
239   if (status != 0)
240     return status;
241
242   if (dd->instance.configured) {
243     ERROR("snmp plugin: Only one of options `TypeInstanceOID', "
244           "`PluginInstanceOID' or `Instance' can be used in `Data' block.");
245     return -1;
246   }
247
248   dd->instance.is_plugin = is_plugin;
249   dd->instance.configured = true;
250
251   if (strlen(buffer) == 0) {
252     return 0;
253   }
254
255   dd->instance.oid.oid_len = MAX_OID_LEN;
256
257   if (!read_objid(buffer, dd->instance.oid.oid, &dd->instance.oid.oid_len)) {
258     ERROR("snmp plugin: read_objid (%s) failed.", buffer);
259     return -1;
260   }
261
262   return 0;
263 } /* int csnmp_config_add_data_instance_oid */
264
265 static int csnmp_config_add_data_values(data_definition_t *dd,
266                                         oconfig_item_t *ci) {
267   if (ci->values_num < 1) {
268     WARNING("snmp plugin: `Values' needs at least one argument.");
269     return -1;
270   }
271
272   for (int i = 0; i < ci->values_num; i++)
273     if (ci->values[i].type != OCONFIG_TYPE_STRING) {
274       WARNING("snmp plugin: `Values' needs only string argument.");
275       return -1;
276     }
277
278   sfree(dd->values);
279   dd->values_len = 0;
280   dd->values = malloc(sizeof(*dd->values) * ci->values_num);
281   if (dd->values == NULL)
282     return -1;
283   dd->values_len = (size_t)ci->values_num;
284
285   for (int i = 0; i < ci->values_num; i++) {
286     dd->values[i].oid_len = MAX_OID_LEN;
287
288     if (NULL == snmp_parse_oid(ci->values[i].value.string, dd->values[i].oid,
289                                &dd->values[i].oid_len)) {
290       ERROR("snmp plugin: snmp_parse_oid (%s) failed.",
291             ci->values[i].value.string);
292       free(dd->values);
293       dd->values = NULL;
294       dd->values_len = 0;
295       return -1;
296     }
297   }
298
299   return 0;
300 } /* int csnmp_config_add_data_instance */
301
302 static int csnmp_config_add_data_blacklist(data_definition_t *dd,
303                                            oconfig_item_t *ci) {
304   if (ci->values_num < 1)
305     return 0;
306
307   for (int i = 0; i < ci->values_num; i++) {
308     if (ci->values[i].type != OCONFIG_TYPE_STRING) {
309       WARNING("snmp plugin: `Ignore' needs only string argument.");
310       return -1;
311     }
312   }
313
314   for (int i = 0; i < ci->values_num; ++i) {
315     if (strarray_add(&(dd->ignores), &(dd->ignores_len),
316                      ci->values[i].value.string) != 0) {
317       ERROR("snmp plugin: Can't allocate memory");
318       strarray_free(dd->ignores, dd->ignores_len);
319       return ENOMEM;
320     }
321   }
322   return 0;
323 } /* int csnmp_config_add_data_blacklist */
324
325 static int csnmp_config_add_data(oconfig_item_t *ci) {
326   data_definition_t *dd = calloc(1, sizeof(*dd));
327   if (dd == NULL)
328     return -1;
329
330   int status = cf_util_get_string(ci, &dd->name);
331   if (status != 0) {
332     sfree(dd);
333     return -1;
334   }
335
336   dd->scale = 1.0;
337   dd->shift = 0.0;
338   dd->ignores_len = 0;
339   dd->ignores = NULL;
340
341   dd->plugin_name = strdup("snmp");
342   if (dd->plugin_name == NULL) {
343     ERROR("snmp plugin: Can't allocate memory");
344     return ENOMEM;
345   }
346
347   for (int i = 0; i < ci->children_num; i++) {
348     oconfig_item_t *option = ci->children + i;
349
350     if (strcasecmp("Type", option->key) == 0)
351       status = cf_util_get_string(option, &dd->type);
352     else if (strcasecmp("Table", option->key) == 0)
353       status = cf_util_get_boolean(option, &dd->is_table);
354     else if (strcasecmp("Plugin", option->key) == 0)
355       status = cf_util_get_string(option, &dd->plugin_name);
356     else if (strcasecmp("Instance", option->key) == 0) {
357       if (dd->is_table) {
358         /* Instance is OID */
359         WARNING("snmp plugin: Option `Instance' is deprecated, please update "
360                 "Data \"%s\" block to use option `TypeInstanceOID'.",
361                 dd->name);
362         status = csnmp_config_add_data_instance_oid(dd, option,
363                                                     false /* type instance */);
364       } else {
365         /* Instance is a simple string */
366         WARNING("snmp plugin: Option `Instance' is deprecated, please update "
367                 "Data \"%s\" block to use option `TypeInstance'.",
368                 dd->name);
369         status = cf_util_get_string(option, &dd->type_instance);
370       }
371     } else if (strcasecmp("PluginInstance", option->key) == 0)
372       status = cf_util_get_string(option, &dd->plugin_instance);
373     else if (strcasecmp("TypeInstance", option->key) == 0)
374       status = cf_util_get_string(option, &dd->type_instance);
375     else if (strcasecmp("PluginInstanceOID", option->key) == 0)
376       status = csnmp_config_add_data_instance_oid(dd, option,
377                                                   true /* plugin instance */);
378     else if (strcasecmp("TypeInstanceOID", option->key) == 0)
379       status = csnmp_config_add_data_instance_oid(dd, option,
380                                                   false /* type instance */);
381     else if (strcasecmp("InstancePrefix", option->key) == 0)
382       status = cf_util_get_string(option, &dd->instance_prefix);
383     else if (strcasecmp("Values", option->key) == 0)
384       status = csnmp_config_add_data_values(dd, option);
385     else if (strcasecmp("Shift", option->key) == 0)
386       status = cf_util_get_double(option, &dd->shift);
387     else if (strcasecmp("Scale", option->key) == 0)
388       status = cf_util_get_double(option, &dd->scale);
389     else if (strcasecmp("Ignore", option->key) == 0)
390       status = csnmp_config_add_data_blacklist(dd, option);
391     else if (strcasecmp("InvertMatch", option->key) == 0)
392       status = cf_util_get_boolean(option, &dd->invert_match);
393     else {
394       WARNING("snmp plugin: Option `%s' not allowed here.", option->key);
395       status = -1;
396     }
397
398     if (status != 0)
399       break;
400   } /* for (ci->children) */
401
402   while (status == 0) {
403     if (dd->is_table) {
404       if (dd->plugin_instance && dd->instance.is_plugin) {
405         WARNING("snmp plugin: Option `PluginInstance' will be ignored for "
406                 "Data `%s'",
407                 dd->name);
408       }
409       if (dd->type_instance && !dd->instance.is_plugin) {
410         WARNING("snmp plugin: Option `TypeInstance' will be ignored for Data "
411                 "`%s'",
412                 dd->name);
413       }
414     } else {
415       if (dd->instance.configured) {
416         if (dd->instance.is_plugin) {
417           WARNING("snmp plugin: Option `PluginInstanceOID' will be ignored for "
418                   "Data `%s'",
419                   dd->name);
420         } else {
421           WARNING("snmp plugin: Option `TypeInstanceOID' will be ignored for "
422                   "Data `%s'",
423                   dd->name);
424         }
425       }
426
427       if (dd->instance_prefix) {
428         WARNING("snmp plugin: data %s: InstancePrefix is ignored when `Table' "
429                 "is set to `false'.",
430                 dd->name);
431       }
432     }
433
434     if (dd->type == NULL) {
435       WARNING("snmp plugin: `Type' not given for data `%s'", dd->name);
436       status = -1;
437       break;
438     }
439     if (dd->values == NULL) {
440       WARNING("snmp plugin: No `Value' given for data `%s'", dd->name);
441       status = -1;
442       break;
443     }
444
445     break;
446   } /* while (status == 0) */
447
448   if (status != 0) {
449     sfree(dd->name);
450     sfree(dd->type);
451     sfree(dd->plugin_name);
452     sfree(dd->plugin_instance);
453     sfree(dd->type_instance);
454     sfree(dd->instance_prefix);
455     sfree(dd->values);
456     sfree(dd->ignores);
457     sfree(dd);
458     return -1;
459   }
460
461   DEBUG("snmp plugin: dd = { name = %s, type = %s, is_table = %s, values_len = "
462         "%" PRIsz ",",
463         dd->name, dd->type, (dd->is_table) ? "true" : "false", dd->values_len);
464
465   DEBUG("snmp plugin:        plugin_instance = %s, type_instance = %s,",
466         dd->plugin_instance, dd->type_instance);
467
468   DEBUG("snmp plugin:        instance_by_oid = %s, to_plugin_instance = %s }",
469         (dd->instance.oid.oid_len > 0) ? "true" : "SUBID",
470         (dd->instance.is_plugin) ? "true" : "false");
471
472   if (data_head == NULL)
473     data_head = dd;
474   else {
475     data_definition_t *last;
476     last = data_head;
477     while (last->next != NULL)
478       last = last->next;
479     last->next = dd;
480   }
481
482   return 0;
483 } /* int csnmp_config_add_data */
484
485 static int csnmp_config_add_host_version(host_definition_t *hd,
486                                          oconfig_item_t *ci) {
487   int version;
488
489   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER)) {
490     WARNING("snmp plugin: The `Version' config option needs exactly one number "
491             "argument.");
492     return -1;
493   }
494
495   version = (int)ci->values[0].value.number;
496   if ((version < 1) || (version > 3)) {
497     WARNING("snmp plugin: `Version' must either be `1', `2', or `3'.");
498     return -1;
499   }
500
501   hd->version = version;
502
503   return 0;
504 } /* int csnmp_config_add_host_address */
505
506 static int csnmp_config_add_host_collect(host_definition_t *host,
507                                          oconfig_item_t *ci) {
508   data_definition_t *data;
509   data_definition_t **data_list;
510   int data_list_len;
511
512   if (ci->values_num < 1) {
513     WARNING("snmp plugin: `Collect' needs at least one argument.");
514     return -1;
515   }
516
517   for (int i = 0; i < ci->values_num; i++)
518     if (ci->values[i].type != OCONFIG_TYPE_STRING) {
519       WARNING("snmp plugin: All arguments to `Collect' must be strings.");
520       return -1;
521     }
522
523   data_list_len = host->data_list_len + ci->values_num;
524   data_list =
525       realloc(host->data_list, sizeof(data_definition_t *) * data_list_len);
526   if (data_list == NULL)
527     return -1;
528   host->data_list = data_list;
529
530   for (int i = 0; i < ci->values_num; i++) {
531     for (data = data_head; data != NULL; data = data->next)
532       if (strcasecmp(ci->values[i].value.string, data->name) == 0)
533         break;
534
535     if (data == NULL) {
536       WARNING("snmp plugin: No such data configured: `%s'",
537               ci->values[i].value.string);
538       continue;
539     }
540
541     DEBUG("snmp plugin: Collect: host = %s, data[%i] = %s;", host->name,
542           host->data_list_len, data->name);
543
544     host->data_list[host->data_list_len] = data;
545     host->data_list_len++;
546   } /* for (values_num) */
547
548   return 0;
549 } /* int csnmp_config_add_host_collect */
550
551 static int csnmp_config_add_host_auth_protocol(host_definition_t *hd,
552                                                oconfig_item_t *ci) {
553   char buffer[4];
554   int status;
555
556   status = cf_util_get_string_buffer(ci, buffer, sizeof(buffer));
557   if (status != 0)
558     return status;
559
560   if (strcasecmp("MD5", buffer) == 0) {
561     hd->auth_protocol = usmHMACMD5AuthProtocol;
562     hd->auth_protocol_len = sizeof(usmHMACMD5AuthProtocol) / sizeof(oid);
563   } else if (strcasecmp("SHA", buffer) == 0) {
564     hd->auth_protocol = usmHMACSHA1AuthProtocol;
565     hd->auth_protocol_len = sizeof(usmHMACSHA1AuthProtocol) / sizeof(oid);
566   } else {
567     WARNING("snmp plugin: The `AuthProtocol' config option must be `MD5' or "
568             "`SHA'.");
569     return -1;
570   }
571
572   DEBUG("snmp plugin: host = %s; host->auth_protocol = %s;", hd->name,
573         hd->auth_protocol == usmHMACMD5AuthProtocol ? "MD5" : "SHA");
574
575   return 0;
576 } /* int csnmp_config_add_host_auth_protocol */
577
578 static int csnmp_config_add_host_priv_protocol(host_definition_t *hd,
579                                                oconfig_item_t *ci) {
580   char buffer[4];
581   int status;
582
583   status = cf_util_get_string_buffer(ci, buffer, sizeof(buffer));
584   if (status != 0)
585     return status;
586
587   if (strcasecmp("AES", buffer) == 0) {
588     hd->priv_protocol = usmAESPrivProtocol;
589     hd->priv_protocol_len = sizeof(usmAESPrivProtocol) / sizeof(oid);
590   } else if (strcasecmp("DES", buffer) == 0) {
591     hd->priv_protocol = usmDESPrivProtocol;
592     hd->priv_protocol_len = sizeof(usmDESPrivProtocol) / sizeof(oid);
593   } else {
594     WARNING("snmp plugin: The `PrivProtocol' config option must be `AES' or "
595             "`DES'.");
596     return -1;
597   }
598
599   DEBUG("snmp plugin: host = %s; host->priv_protocol = %s;", hd->name,
600         hd->priv_protocol == usmAESPrivProtocol ? "AES" : "DES");
601
602   return 0;
603 } /* int csnmp_config_add_host_priv_protocol */
604
605 static int csnmp_config_add_host_security_level(host_definition_t *hd,
606                                                 oconfig_item_t *ci) {
607   char buffer[16];
608   int status;
609
610   status = cf_util_get_string_buffer(ci, buffer, sizeof(buffer));
611   if (status != 0)
612     return status;
613
614   if (strcasecmp("noAuthNoPriv", buffer) == 0)
615     hd->security_level = SNMP_SEC_LEVEL_NOAUTH;
616   else if (strcasecmp("authNoPriv", buffer) == 0)
617     hd->security_level = SNMP_SEC_LEVEL_AUTHNOPRIV;
618   else if (strcasecmp("authPriv", buffer) == 0)
619     hd->security_level = SNMP_SEC_LEVEL_AUTHPRIV;
620   else {
621     WARNING("snmp plugin: The `SecurityLevel' config option must be "
622             "`noAuthNoPriv', `authNoPriv', or `authPriv'.");
623     return -1;
624   }
625
626   DEBUG("snmp plugin: host = %s; host->security_level = %d;", hd->name,
627         hd->security_level);
628
629   return 0;
630 } /* int csnmp_config_add_host_security_level */
631
632 static int csnmp_config_add_host(oconfig_item_t *ci) {
633   host_definition_t *hd;
634   int status = 0;
635
636   /* Registration stuff. */
637   char cb_name[DATA_MAX_NAME_LEN];
638
639   hd = calloc(1, sizeof(*hd));
640   if (hd == NULL)
641     return -1;
642   hd->version = 2;
643   C_COMPLAIN_INIT(&hd->complaint);
644
645   status = cf_util_get_string(ci, &hd->name);
646   if (status != 0) {
647     sfree(hd);
648     return status;
649   }
650
651   hd->sess_handle = NULL;
652   hd->interval = 0;
653
654   /* These mean that we have not set a timeout or retry value */
655   hd->timeout = 0;
656   hd->retries = -1;
657
658   for (int i = 0; i < ci->children_num; i++) {
659     oconfig_item_t *option = ci->children + i;
660
661     if (strcasecmp("Address", option->key) == 0)
662       status = cf_util_get_string(option, &hd->address);
663     else if (strcasecmp("Community", option->key) == 0)
664       status = cf_util_get_string(option, &hd->community);
665     else if (strcasecmp("Version", option->key) == 0)
666       status = csnmp_config_add_host_version(hd, option);
667     else if (strcasecmp("Timeout", option->key) == 0)
668       status = cf_util_get_cdtime(option, &hd->timeout);
669     else if (strcasecmp("Retries", option->key) == 0)
670       status = cf_util_get_int(option, &hd->retries);
671     else if (strcasecmp("Collect", option->key) == 0)
672       status = csnmp_config_add_host_collect(hd, option);
673     else if (strcasecmp("Interval", option->key) == 0)
674       status = cf_util_get_cdtime(option, &hd->interval);
675     else if (strcasecmp("Username", option->key) == 0)
676       status = cf_util_get_string(option, &hd->username);
677     else if (strcasecmp("AuthProtocol", option->key) == 0)
678       status = csnmp_config_add_host_auth_protocol(hd, option);
679     else if (strcasecmp("PrivacyProtocol", option->key) == 0)
680       status = csnmp_config_add_host_priv_protocol(hd, option);
681     else if (strcasecmp("AuthPassphrase", option->key) == 0)
682       status = cf_util_get_string(option, &hd->auth_passphrase);
683     else if (strcasecmp("PrivacyPassphrase", option->key) == 0)
684       status = cf_util_get_string(option, &hd->priv_passphrase);
685     else if (strcasecmp("SecurityLevel", option->key) == 0)
686       status = csnmp_config_add_host_security_level(hd, option);
687     else if (strcasecmp("Context", option->key) == 0)
688       status = cf_util_get_string(option, &hd->context);
689     else {
690       WARNING(
691           "snmp plugin: csnmp_config_add_host: Option `%s' not allowed here.",
692           option->key);
693       status = -1;
694     }
695
696     if (status != 0)
697       break;
698   } /* for (ci->children) */
699
700   while (status == 0) {
701     if (hd->address == NULL) {
702       WARNING("snmp plugin: `Address' not given for host `%s'", hd->name);
703       status = -1;
704       break;
705     }
706     if (hd->community == NULL && hd->version < 3) {
707       WARNING("snmp plugin: `Community' not given for host `%s'", hd->name);
708       status = -1;
709       break;
710     }
711     if (hd->version == 3) {
712       if (hd->username == NULL) {
713         WARNING("snmp plugin: `Username' not given for host `%s'", hd->name);
714         status = -1;
715         break;
716       }
717       if (hd->security_level == 0) {
718         WARNING("snmp plugin: `SecurityLevel' not given for host `%s'",
719                 hd->name);
720         status = -1;
721         break;
722       }
723       if (hd->security_level == SNMP_SEC_LEVEL_AUTHNOPRIV ||
724           hd->security_level == SNMP_SEC_LEVEL_AUTHPRIV) {
725         if (hd->auth_protocol == NULL) {
726           WARNING("snmp plugin: `AuthProtocol' not given for host `%s'",
727                   hd->name);
728           status = -1;
729           break;
730         }
731         if (hd->auth_passphrase == NULL) {
732           WARNING("snmp plugin: `AuthPassphrase' not given for host `%s'",
733                   hd->name);
734           status = -1;
735           break;
736         }
737       }
738       if (hd->security_level == SNMP_SEC_LEVEL_AUTHPRIV) {
739         if (hd->priv_protocol == NULL) {
740           WARNING("snmp plugin: `PrivacyProtocol' not given for host `%s'",
741                   hd->name);
742           status = -1;
743           break;
744         }
745         if (hd->priv_passphrase == NULL) {
746           WARNING("snmp plugin: `PrivacyPassphrase' not given for host `%s'",
747                   hd->name);
748           status = -1;
749           break;
750         }
751       }
752     }
753
754     break;
755   } /* while (status == 0) */
756
757   if (status != 0) {
758     csnmp_host_definition_destroy(hd);
759     return -1;
760   }
761
762   DEBUG("snmp plugin: hd = { name = %s, address = %s, community = %s, version "
763         "= %i }",
764         hd->name, hd->address, hd->community, hd->version);
765
766   snprintf(cb_name, sizeof(cb_name), "snmp-%s", hd->name);
767
768   status = plugin_register_complex_read(
769       /* group = */ NULL, cb_name, csnmp_read_host, hd->interval,
770       &(user_data_t){
771           .data = hd, .free_func = csnmp_host_definition_destroy,
772       });
773   if (status != 0) {
774     ERROR("snmp plugin: Registering complex read function failed.");
775     return -1;
776   }
777
778   return 0;
779 } /* int csnmp_config_add_host */
780
781 static int csnmp_config(oconfig_item_t *ci) {
782   call_snmp_init_once();
783
784   for (int i = 0; i < ci->children_num; i++) {
785     oconfig_item_t *child = ci->children + i;
786     if (strcasecmp("Data", child->key) == 0)
787       csnmp_config_add_data(child);
788     else if (strcasecmp("Host", child->key) == 0)
789       csnmp_config_add_host(child);
790     else {
791       WARNING("snmp plugin: Ignoring unknown config option `%s'.", child->key);
792     }
793   } /* for (ci->children) */
794
795   return 0;
796 } /* int csnmp_config */
797
798 /* }}} End of the config stuff. Now the interesting part begins */
799
800 static void csnmp_host_open_session(host_definition_t *host) {
801   struct snmp_session sess;
802   int error;
803
804   if (host->sess_handle != NULL)
805     csnmp_host_close_session(host);
806
807   snmp_sess_init(&sess);
808   sess.peername = host->address;
809   switch (host->version) {
810   case 1:
811     sess.version = SNMP_VERSION_1;
812     break;
813   case 3:
814     sess.version = SNMP_VERSION_3;
815     break;
816   default:
817     sess.version = SNMP_VERSION_2c;
818     break;
819   }
820
821   if (host->version == 3) {
822     sess.securityName = host->username;
823     sess.securityNameLen = strlen(host->username);
824     sess.securityLevel = host->security_level;
825
826     if (sess.securityLevel == SNMP_SEC_LEVEL_AUTHNOPRIV ||
827         sess.securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) {
828       sess.securityAuthProto = host->auth_protocol;
829       sess.securityAuthProtoLen = host->auth_protocol_len;
830       sess.securityAuthKeyLen = USM_AUTH_KU_LEN;
831       error = generate_Ku(sess.securityAuthProto, sess.securityAuthProtoLen,
832                           (u_char *)host->auth_passphrase,
833                           strlen(host->auth_passphrase), sess.securityAuthKey,
834                           &sess.securityAuthKeyLen);
835       if (error != SNMPERR_SUCCESS) {
836         ERROR("snmp plugin: host %s: Error generating Ku from auth_passphrase. "
837               "(Error %d)",
838               host->name, error);
839       }
840     }
841
842     if (sess.securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) {
843       sess.securityPrivProto = host->priv_protocol;
844       sess.securityPrivProtoLen = host->priv_protocol_len;
845       sess.securityPrivKeyLen = USM_PRIV_KU_LEN;
846       error = generate_Ku(sess.securityAuthProto, sess.securityAuthProtoLen,
847                           (u_char *)host->priv_passphrase,
848                           strlen(host->priv_passphrase), sess.securityPrivKey,
849                           &sess.securityPrivKeyLen);
850       if (error != SNMPERR_SUCCESS) {
851         ERROR("snmp plugin: host %s: Error generating Ku from priv_passphrase. "
852               "(Error %d)",
853               host->name, error);
854       }
855     }
856
857     if (host->context != NULL) {
858       sess.contextName = host->context;
859       sess.contextNameLen = strlen(host->context);
860     }
861   } else /* SNMPv1/2 "authenticates" with community string */
862   {
863     sess.community = (u_char *)host->community;
864     sess.community_len = strlen(host->community);
865   }
866
867   /* Set timeout & retries, if they have been changed from the default */
868   if (host->timeout != 0) {
869     /* net-snmp expects microseconds */
870     sess.timeout = CDTIME_T_TO_US(host->timeout);
871   }
872   if (host->retries >= 0) {
873     sess.retries = host->retries;
874   }
875
876   /* snmp_sess_open will copy the `struct snmp_session *'. */
877   host->sess_handle = snmp_sess_open(&sess);
878
879   if (host->sess_handle == NULL) {
880     char *errstr = NULL;
881
882     snmp_error(&sess, NULL, NULL, &errstr);
883
884     ERROR("snmp plugin: host %s: snmp_sess_open failed: %s", host->name,
885           (errstr == NULL) ? "Unknown problem" : errstr);
886     sfree(errstr);
887   }
888 } /* void csnmp_host_open_session */
889
890 /* TODO: Check if negative values wrap around. Problem: negative temperatures.
891  */
892 static value_t csnmp_value_list_to_value(struct variable_list *vl, int type,
893                                          double scale, double shift,
894                                          const char *host_name,
895                                          const char *data_name) {
896   value_t ret;
897   uint64_t tmp_unsigned = 0;
898   int64_t tmp_signed = 0;
899   bool defined = 1;
900   /* Set to true when the original SNMP type appears to have been signed. */
901   bool prefer_signed = 0;
902
903   if ((vl->type == ASN_INTEGER) || (vl->type == ASN_UINTEGER) ||
904       (vl->type == ASN_COUNTER)
905 #ifdef ASN_TIMETICKS
906       || (vl->type == ASN_TIMETICKS)
907 #endif
908       || (vl->type == ASN_GAUGE)) {
909     tmp_unsigned = (uint32_t)*vl->val.integer;
910     tmp_signed = (int32_t)*vl->val.integer;
911
912     if (vl->type == ASN_INTEGER)
913       prefer_signed = 1;
914
915     DEBUG("snmp plugin: Parsed int32 value is %" PRIu64 ".", tmp_unsigned);
916   } else if (vl->type == ASN_COUNTER64) {
917     tmp_unsigned = (uint32_t)vl->val.counter64->high;
918     tmp_unsigned = tmp_unsigned << 32;
919     tmp_unsigned += (uint32_t)vl->val.counter64->low;
920     tmp_signed = (int64_t)tmp_unsigned;
921     DEBUG("snmp plugin: Parsed int64 value is %" PRIu64 ".", tmp_unsigned);
922   } else if (vl->type == ASN_OCTET_STR) {
923     /* We'll handle this later.. */
924   } else {
925     char oid_buffer[1024] = {0};
926
927     snprint_objid(oid_buffer, sizeof(oid_buffer) - 1, vl->name,
928                   vl->name_length);
929
930 #ifdef ASN_NULL
931     if (vl->type == ASN_NULL)
932       INFO("snmp plugin: OID \"%s\" is undefined (type ASN_NULL)", oid_buffer);
933     else
934 #endif
935       WARNING("snmp plugin: I don't know the ASN type #%i "
936               "(OID: \"%s\", data block \"%s\", host block \"%s\")",
937               (int)vl->type, oid_buffer,
938               (data_name != NULL) ? data_name : "UNKNOWN",
939               (host_name != NULL) ? host_name : "UNKNOWN");
940
941     defined = 0;
942   }
943
944   if (vl->type == ASN_OCTET_STR) {
945     int status = -1;
946
947     if (vl->val.string != NULL) {
948       char string[64];
949       size_t string_length;
950
951       string_length = sizeof(string) - 1;
952       if (vl->val_len < string_length)
953         string_length = vl->val_len;
954
955       /* The strings we get from the Net-SNMP library may not be null
956        * terminated. That is why we're using `memcpy' here and not `strcpy'.
957        * `string_length' is set to `vl->val_len' which holds the length of the
958        * string.  -octo */
959       memcpy(string, vl->val.string, string_length);
960       string[string_length] = 0;
961
962       status = parse_value(string, &ret, type);
963       if (status != 0) {
964         ERROR("snmp plugin: host %s: csnmp_value_list_to_value: Parsing string "
965               "as %s failed: %s",
966               (host_name != NULL) ? host_name : "UNKNOWN",
967               DS_TYPE_TO_STRING(type), string);
968       }
969     }
970
971     if (status != 0) {
972       switch (type) {
973       case DS_TYPE_COUNTER:
974       case DS_TYPE_DERIVE:
975       case DS_TYPE_ABSOLUTE:
976         memset(&ret, 0, sizeof(ret));
977         break;
978
979       case DS_TYPE_GAUGE:
980         ret.gauge = NAN;
981         break;
982
983       default:
984         ERROR("snmp plugin: csnmp_value_list_to_value: Unknown "
985               "data source type: %i.",
986               type);
987         ret.gauge = NAN;
988       }
989     }
990   } /* if (vl->type == ASN_OCTET_STR) */
991   else if (type == DS_TYPE_COUNTER) {
992     ret.counter = tmp_unsigned;
993   } else if (type == DS_TYPE_GAUGE) {
994     if (!defined)
995       ret.gauge = NAN;
996     else if (prefer_signed)
997       ret.gauge = (scale * tmp_signed) + shift;
998     else
999       ret.gauge = (scale * tmp_unsigned) + shift;
1000   } else if (type == DS_TYPE_DERIVE) {
1001     if (prefer_signed)
1002       ret.derive = (derive_t)tmp_signed;
1003     else
1004       ret.derive = (derive_t)tmp_unsigned;
1005   } else if (type == DS_TYPE_ABSOLUTE) {
1006     ret.absolute = (absolute_t)tmp_unsigned;
1007   } else {
1008     ERROR("snmp plugin: csnmp_value_list_to_value: Unknown data source "
1009           "type: %i.",
1010           type);
1011     ret.gauge = NAN;
1012   }
1013
1014   return ret;
1015 } /* value_t csnmp_value_list_to_value */
1016
1017 /* csnmp_strvbcopy_hexstring converts the bit string contained in "vb" to a hex
1018  * representation and writes it to dst. Returns zero on success and ENOMEM if
1019  * dst is not large enough to hold the string. dst is guaranteed to be
1020  * nul-terminated. */
1021 static int csnmp_strvbcopy_hexstring(char *dst, /* {{{ */
1022                                      const struct variable_list *vb,
1023                                      size_t dst_size) {
1024   char *buffer_ptr;
1025   size_t buffer_free;
1026
1027   dst[0] = 0;
1028
1029   buffer_ptr = dst;
1030   buffer_free = dst_size;
1031
1032   for (size_t i = 0; i < vb->val_len; i++) {
1033     int status;
1034
1035     status = snprintf(buffer_ptr, buffer_free, (i == 0) ? "%02x" : ":%02x",
1036                       (unsigned int)vb->val.bitstring[i]);
1037     assert(status >= 0);
1038
1039     if (((size_t)status) >= buffer_free) /* truncated */
1040     {
1041       dst[dst_size - 1] = 0;
1042       return ENOMEM;
1043     } else /* if (status < buffer_free) */
1044     {
1045       buffer_ptr += (size_t)status;
1046       buffer_free -= (size_t)status;
1047     }
1048   }
1049
1050   return 0;
1051 } /* }}} int csnmp_strvbcopy_hexstring */
1052
1053 /* csnmp_strvbcopy copies the octet string or bit string contained in vb to
1054  * dst. If non-printable characters are detected, it will switch to a hex
1055  * representation of the string. Returns zero on success, EINVAL if vb does not
1056  * contain a string and ENOMEM if dst is not large enough to contain the
1057  * string. */
1058 static int csnmp_strvbcopy(char *dst, /* {{{ */
1059                            const struct variable_list *vb, size_t dst_size) {
1060   char *src;
1061   size_t num_chars;
1062
1063   if (vb->type == ASN_OCTET_STR)
1064     src = (char *)vb->val.string;
1065   else if (vb->type == ASN_BIT_STR)
1066     src = (char *)vb->val.bitstring;
1067   else if (vb->type == ASN_IPADDRESS) {
1068     return snprintf(dst, dst_size,
1069                     "%" PRIu8 ".%" PRIu8 ".%" PRIu8 ".%" PRIu8 "",
1070                     (uint8_t)vb->val.string[0], (uint8_t)vb->val.string[1],
1071                     (uint8_t)vb->val.string[2], (uint8_t)vb->val.string[3]);
1072   } else {
1073     dst[0] = 0;
1074     return EINVAL;
1075   }
1076
1077   num_chars = dst_size - 1;
1078   if (num_chars > vb->val_len)
1079     num_chars = vb->val_len;
1080
1081   for (size_t i = 0; i < num_chars; i++) {
1082     /* Check for control characters. */
1083     if ((unsigned char)src[i] < 32)
1084       return csnmp_strvbcopy_hexstring(dst, vb, dst_size);
1085     dst[i] = src[i];
1086   }
1087   dst[num_chars] = 0;
1088   dst[dst_size - 1] = 0;
1089
1090   if (dst_size <= vb->val_len)
1091     return ENOMEM;
1092
1093   return 0;
1094 } /* }}} int csnmp_strvbcopy */
1095
1096 static int csnmp_instance_list_add(csnmp_list_instances_t **head,
1097                                    csnmp_list_instances_t **tail,
1098                                    const struct snmp_pdu *res,
1099                                    const host_definition_t *hd,
1100                                    const data_definition_t *dd) {
1101   csnmp_list_instances_t *il;
1102   struct variable_list *vb;
1103   oid_t vb_name;
1104   int status;
1105
1106   /* Set vb on the last variable */
1107   for (vb = res->variables; (vb != NULL) && (vb->next_variable != NULL);
1108        vb = vb->next_variable)
1109     /* do nothing */;
1110   if (vb == NULL)
1111     return -1;
1112
1113   csnmp_oid_init(&vb_name, vb->name, vb->name_length);
1114
1115   il = calloc(1, sizeof(*il));
1116   if (il == NULL) {
1117     ERROR("snmp plugin: calloc failed.");
1118     return -1;
1119   }
1120   il->next = NULL;
1121
1122   status = csnmp_oid_suffix(&il->suffix, &vb_name, &dd->instance.oid);
1123   if (status != 0) {
1124     sfree(il);
1125     return status;
1126   }
1127
1128   /* Get instance name */
1129   if ((vb->type == ASN_OCTET_STR) || (vb->type == ASN_BIT_STR) ||
1130       (vb->type == ASN_IPADDRESS)) {
1131     char *ptr;
1132
1133     csnmp_strvbcopy(il->instance, vb, sizeof(il->instance));
1134     bool is_matched = 0;
1135     for (uint32_t i = 0; i < dd->ignores_len; i++) {
1136       status = fnmatch(dd->ignores[i], il->instance, 0);
1137       if (status == 0) {
1138         if (!dd->invert_match) {
1139           sfree(il);
1140           return 0;
1141         } else {
1142           is_matched = 1;
1143           break;
1144         }
1145       }
1146     }
1147     if (dd->invert_match && !is_matched) {
1148       sfree(il);
1149       return 0;
1150     }
1151     for (ptr = il->instance; *ptr != '\0'; ptr++) {
1152       if ((*ptr > 0) && (*ptr < 32))
1153         *ptr = ' ';
1154       else if (*ptr == '/')
1155         *ptr = '_';
1156     }
1157     DEBUG("snmp plugin: il->instance = `%s';", il->instance);
1158   } else {
1159     value_t val = csnmp_value_list_to_value(
1160         vb, DS_TYPE_COUNTER,
1161         /* scale = */ 1.0, /* shift = */ 0.0, hd->name, dd->name);
1162     snprintf(il->instance, sizeof(il->instance), "%" PRIu64,
1163              (uint64_t)val.counter);
1164   }
1165
1166   /* TODO: Debugging output */
1167
1168   if (*head == NULL)
1169     *head = il;
1170   else
1171     (*tail)->next = il;
1172   *tail = il;
1173
1174   return 0;
1175 } /* int csnmp_instance_list_add */
1176
1177 static int csnmp_dispatch_table(host_definition_t *host,
1178                                 data_definition_t *data,
1179                                 csnmp_list_instances_t *instance_list,
1180                                 csnmp_table_values_t **value_table) {
1181   const data_set_t *ds;
1182   value_list_t vl = VALUE_LIST_INIT;
1183
1184   csnmp_list_instances_t *instance_list_ptr;
1185   csnmp_table_values_t *value_table_ptr[data->values_len];
1186
1187   size_t i;
1188   bool have_more;
1189   oid_t current_suffix;
1190
1191   ds = plugin_get_ds(data->type);
1192   if (!ds) {
1193     ERROR("snmp plugin: DataSet `%s' not defined.", data->type);
1194     return -1;
1195   }
1196   assert(ds->ds_num == data->values_len);
1197   assert(data->values_len > 0);
1198
1199   instance_list_ptr = instance_list;
1200
1201   for (i = 0; i < data->values_len; i++)
1202     value_table_ptr[i] = value_table[i];
1203
1204   sstrncpy(vl.host, host->name, sizeof(vl.host));
1205   sstrncpy(vl.plugin, data->plugin_name, sizeof(vl.plugin));
1206
1207   vl.interval = host->interval;
1208
1209   have_more = 1;
1210   while (have_more) {
1211     bool suffix_skipped = 0;
1212
1213     /* Determine next suffix to handle. */
1214     if (instance_list != NULL) {
1215       if (instance_list_ptr == NULL) {
1216         have_more = 0;
1217         continue;
1218       }
1219
1220       memcpy(&current_suffix, &instance_list_ptr->suffix,
1221              sizeof(current_suffix));
1222     } else {
1223       /* no instance configured */
1224       csnmp_table_values_t *ptr = value_table_ptr[0];
1225       if (ptr == NULL) {
1226         have_more = 0;
1227         continue;
1228       }
1229
1230       memcpy(&current_suffix, &ptr->suffix, sizeof(current_suffix));
1231     }
1232
1233     /* Update all the value_table_ptr to point at the entry with the same
1234      * trailing partial OID */
1235     for (i = 0; i < data->values_len; i++) {
1236       while (
1237           (value_table_ptr[i] != NULL) &&
1238           (csnmp_oid_compare(&value_table_ptr[i]->suffix, &current_suffix) < 0))
1239         value_table_ptr[i] = value_table_ptr[i]->next;
1240
1241       if (value_table_ptr[i] == NULL) {
1242         have_more = 0;
1243         break;
1244       } else if (csnmp_oid_compare(&value_table_ptr[i]->suffix,
1245                                    &current_suffix) > 0) {
1246         /* This suffix is missing in the subtree. Indicate this with the
1247          * "suffix_skipped" flag and try the next instance / suffix. */
1248         suffix_skipped = 1;
1249         break;
1250       }
1251     } /* for (i = 0; i < columns; i++) */
1252
1253     if (!have_more)
1254       break;
1255
1256     /* Matching the values failed. Start from the beginning again. */
1257     if (suffix_skipped) {
1258       if (instance_list != NULL)
1259         instance_list_ptr = instance_list_ptr->next;
1260       else
1261         value_table_ptr[0] = value_table_ptr[0]->next;
1262
1263       continue;
1264     }
1265
1266 /* if we reach this line, all value_table_ptr[i] are non-NULL and are set
1267  * to the same subid. instance_list_ptr is either NULL or points to the
1268  * same subid, too. */
1269 #if COLLECT_DEBUG
1270     for (i = 1; i < data->values_len; i++) {
1271       assert(value_table_ptr[i] != NULL);
1272       assert(csnmp_oid_compare(&value_table_ptr[i - 1]->suffix,
1273                                &value_table_ptr[i]->suffix) == 0);
1274     }
1275     assert((instance_list_ptr == NULL) ||
1276            (csnmp_oid_compare(&instance_list_ptr->suffix,
1277                               &value_table_ptr[0]->suffix) == 0));
1278 #endif
1279
1280     sstrncpy(vl.type, data->type, sizeof(vl.type));
1281
1282     {
1283       char temp[DATA_MAX_NAME_LEN];
1284
1285       if (instance_list_ptr == NULL)
1286         csnmp_oid_to_string(temp, sizeof(temp), &current_suffix);
1287       else
1288         sstrncpy(temp, instance_list_ptr->instance, sizeof(temp));
1289
1290       if (data->instance.is_plugin) {
1291         if (data->instance_prefix == NULL)
1292           sstrncpy(vl.plugin_instance, temp, sizeof(vl.plugin_instance));
1293         else
1294           snprintf(vl.plugin_instance, sizeof(vl.plugin_instance), "%s%s",
1295                    data->instance_prefix, temp);
1296
1297         if (data->type_instance)
1298           sstrncpy(vl.type_instance, data->type_instance,
1299                    sizeof(vl.type_instance));
1300       } else {
1301         if (data->instance_prefix == NULL)
1302           sstrncpy(vl.type_instance, temp, sizeof(vl.type_instance));
1303         else
1304           snprintf(vl.type_instance, sizeof(vl.type_instance), "%s%s",
1305                    data->instance_prefix, temp);
1306
1307         if (data->plugin_instance)
1308           sstrncpy(vl.plugin_instance, data->plugin_instance,
1309                    sizeof(vl.plugin_instance));
1310       }
1311     }
1312
1313     vl.values_len = data->values_len;
1314     value_t values[vl.values_len];
1315     vl.values = values;
1316
1317     for (i = 0; i < data->values_len; i++)
1318       vl.values[i] = value_table_ptr[i]->value;
1319
1320     plugin_dispatch_values(&vl);
1321
1322     /* prevent leakage of pointer to local variable. */
1323     vl.values_len = 0;
1324     vl.values = NULL;
1325
1326     if (instance_list != NULL)
1327       instance_list_ptr = instance_list_ptr->next;
1328     else
1329       value_table_ptr[0] = value_table_ptr[0]->next;
1330   } /* while (have_more) */
1331
1332   return (0);
1333 } /* int csnmp_dispatch_table */
1334
1335 static int csnmp_read_table(host_definition_t *host, data_definition_t *data) {
1336   struct snmp_pdu *req;
1337   struct snmp_pdu *res = NULL;
1338   struct variable_list *vb;
1339
1340   const data_set_t *ds;
1341
1342   size_t oid_list_len = data->values_len + 1;
1343   /* Holds the last OID returned by the device. We use this in the GETNEXT
1344    * request to proceed. */
1345   oid_t oid_list[oid_list_len];
1346   /* Set to false when an OID has left its subtree so we don't re-request it
1347    * again. */
1348   bool oid_list_todo[oid_list_len];
1349
1350   int status;
1351   size_t i;
1352
1353   /* `value_list_head' and `value_list_tail' implement a linked list for each
1354    * value. `instance_list_head' and `instance_list_tail' implement a linked
1355    * list of
1356    * instance names. This is used to jump gaps in the table. */
1357   csnmp_list_instances_t *instance_list_head;
1358   csnmp_list_instances_t *instance_list_tail;
1359   csnmp_table_values_t **value_list_head;
1360   csnmp_table_values_t **value_list_tail;
1361
1362   DEBUG("snmp plugin: csnmp_read_table (host = %s, data = %s)", host->name,
1363         data->name);
1364
1365   if (host->sess_handle == NULL) {
1366     DEBUG("snmp plugin: csnmp_read_table: host->sess_handle == NULL");
1367     return -1;
1368   }
1369
1370   ds = plugin_get_ds(data->type);
1371   if (!ds) {
1372     ERROR("snmp plugin: DataSet `%s' not defined.", data->type);
1373     return -1;
1374   }
1375
1376   if (ds->ds_num != data->values_len) {
1377     ERROR("snmp plugin: DataSet `%s' requires %" PRIsz
1378           " values, but config talks "
1379           "about %" PRIsz,
1380           data->type, ds->ds_num, data->values_len);
1381     return -1;
1382   }
1383   assert(data->values_len > 0);
1384
1385   /* We need a copy of all the OIDs, because GETNEXT will destroy them. */
1386   memcpy(oid_list, data->values, data->values_len * sizeof(oid_t));
1387   if (data->instance.oid.oid_len > 0)
1388     memcpy(oid_list + data->values_len, &data->instance.oid, sizeof(oid_t));
1389   else /* no InstanceFrom option specified. */
1390     oid_list_len--;
1391
1392   for (i = 0; i < oid_list_len; i++)
1393     oid_list_todo[i] = 1;
1394
1395   /* We're going to construct n linked lists, one for each "value".
1396    * value_list_head will contain pointers to the heads of these linked lists,
1397    * value_list_tail will contain pointers to the tail of the lists. */
1398   value_list_head = calloc(data->values_len, sizeof(*value_list_head));
1399   value_list_tail = calloc(data->values_len, sizeof(*value_list_tail));
1400   if ((value_list_head == NULL) || (value_list_tail == NULL)) {
1401     ERROR("snmp plugin: csnmp_read_table: calloc failed.");
1402     sfree(value_list_head);
1403     sfree(value_list_tail);
1404     return -1;
1405   }
1406
1407   instance_list_head = NULL;
1408   instance_list_tail = NULL;
1409
1410   status = 0;
1411   while (status == 0) {
1412     req = snmp_pdu_create(SNMP_MSG_GETNEXT);
1413     if (req == NULL) {
1414       ERROR("snmp plugin: snmp_pdu_create failed.");
1415       status = -1;
1416       break;
1417     }
1418
1419     size_t oid_list_todo_num = 0;
1420     size_t var_idx[oid_list_len];
1421     memset(var_idx, 0, sizeof(var_idx));
1422
1423     for (i = 0; i < oid_list_len; i++) {
1424       /* Do not rerequest already finished OIDs */
1425       if (!oid_list_todo[i])
1426         continue;
1427       snmp_add_null_var(req, oid_list[i].oid, oid_list[i].oid_len);
1428       var_idx[oid_list_todo_num] = i;
1429       oid_list_todo_num++;
1430     }
1431
1432     if (oid_list_todo_num == 0) {
1433       /* The request is still empty - so we are finished */
1434       DEBUG("snmp plugin: all variables have left their subtree");
1435       snmp_free_pdu(req);
1436       status = 0;
1437       break;
1438     }
1439
1440     res = NULL;
1441     status = snmp_sess_synch_response(host->sess_handle, req, &res);
1442
1443     /* snmp_sess_synch_response always frees our req PDU */
1444     req = NULL;
1445
1446     if ((status != STAT_SUCCESS) || (res == NULL)) {
1447       char *errstr = NULL;
1448
1449       snmp_sess_error(host->sess_handle, NULL, NULL, &errstr);
1450
1451       c_complain(LOG_ERR, &host->complaint,
1452                  "snmp plugin: host %s: snmp_sess_synch_response failed: %s",
1453                  host->name, (errstr == NULL) ? "Unknown problem" : errstr);
1454
1455       if (res != NULL)
1456         snmp_free_pdu(res);
1457       res = NULL;
1458
1459       sfree(errstr);
1460       csnmp_host_close_session(host);
1461
1462       status = -1;
1463       break;
1464     }
1465
1466     status = 0;
1467     assert(res != NULL);
1468     c_release(LOG_INFO, &host->complaint,
1469               "snmp plugin: host %s: snmp_sess_synch_response successful.",
1470               host->name);
1471
1472     vb = res->variables;
1473     if (vb == NULL) {
1474       status = -1;
1475       break;
1476     }
1477
1478     if (res->errstat != SNMP_ERR_NOERROR) {
1479       if (res->errindex != 0) {
1480         /* Find the OID which caused error */
1481         for (i = 1, vb = res->variables; vb != NULL && i != res->errindex;
1482              vb = vb->next_variable, i++)
1483           /* do nothing */;
1484       }
1485
1486       if ((res->errindex == 0) || (vb == NULL)) {
1487         ERROR("snmp plugin: host %s; data %s: response error: %s (%li) ",
1488               host->name, data->name, snmp_errstring(res->errstat),
1489               res->errstat);
1490         status = -1;
1491         break;
1492       }
1493
1494       char oid_buffer[1024] = {0};
1495       snprint_objid(oid_buffer, sizeof(oid_buffer) - 1, vb->name,
1496                     vb->name_length);
1497       NOTICE("snmp plugin: host %s; data %s: OID `%s` failed: %s", host->name,
1498              data->name, oid_buffer, snmp_errstring(res->errstat));
1499
1500       /* Get value index from todo list and skip OID found */
1501       assert(res->errindex <= oid_list_todo_num);
1502       i = var_idx[res->errindex - 1];
1503       assert(i < oid_list_len);
1504       oid_list_todo[i] = 0;
1505
1506       snmp_free_pdu(res);
1507       res = NULL;
1508       continue;
1509     }
1510
1511     for (vb = res->variables, i = 0; (vb != NULL);
1512          vb = vb->next_variable, i++) {
1513       /* Calculate value index from todo list */
1514       while ((i < oid_list_len) && !oid_list_todo[i]) {
1515         i++;
1516       }
1517       if (i >= oid_list_len) {
1518         break;
1519       }
1520
1521       /* An instance is configured and the res variable we process is the
1522        * instance value (last index) */
1523       if ((data->instance.oid.oid_len > 0) && (i == data->values_len)) {
1524         if ((vb->type == SNMP_ENDOFMIBVIEW) ||
1525             (snmp_oid_ncompare(
1526                  data->instance.oid.oid, data->instance.oid.oid_len, vb->name,
1527                  vb->name_length, data->instance.oid.oid_len) != 0)) {
1528           DEBUG("snmp plugin: host = %s; data = %s; Instance left its subtree.",
1529                 host->name, data->name);
1530           oid_list_todo[i] = 0;
1531           continue;
1532         }
1533
1534         /* Allocate a new `csnmp_list_instances_t', insert the instance name and
1535          * add it to the list */
1536         if (csnmp_instance_list_add(&instance_list_head, &instance_list_tail,
1537                                     res, host, data) != 0) {
1538           ERROR("snmp plugin: host %s: csnmp_instance_list_add failed.",
1539                 host->name);
1540           status = -1;
1541           break;
1542         }
1543       } else /* The variable we are processing is a normal value */
1544       {
1545         csnmp_table_values_t *vt;
1546         oid_t vb_name;
1547         oid_t suffix;
1548         int ret;
1549
1550         csnmp_oid_init(&vb_name, vb->name, vb->name_length);
1551
1552         /* Calculate the current suffix. This is later used to check that the
1553          * suffix is increasing. This also checks if we left the subtree */
1554         ret = csnmp_oid_suffix(&suffix, &vb_name, data->values + i);
1555         if (ret != 0) {
1556           DEBUG("snmp plugin: host = %s; data = %s; i = %" PRIsz "; "
1557                 "Value probably left its subtree.",
1558                 host->name, data->name, i);
1559           oid_list_todo[i] = 0;
1560           continue;
1561         }
1562
1563         /* Make sure the OIDs returned by the agent are increasing. Otherwise
1564          * our
1565          * table matching algorithm will get confused. */
1566         if ((value_list_tail[i] != NULL) &&
1567             (csnmp_oid_compare(&suffix, &value_list_tail[i]->suffix) <= 0)) {
1568           DEBUG("snmp plugin: host = %s; data = %s; i = %" PRIsz "; "
1569                 "Suffix is not increasing.",
1570                 host->name, data->name, i);
1571           oid_list_todo[i] = 0;
1572           continue;
1573         }
1574
1575         vt = calloc(1, sizeof(*vt));
1576         if (vt == NULL) {
1577           ERROR("snmp plugin: calloc failed.");
1578           status = -1;
1579           break;
1580         }
1581
1582         vt->value =
1583             csnmp_value_list_to_value(vb, ds->ds[i].type, data->scale,
1584                                       data->shift, host->name, data->name);
1585         memcpy(&vt->suffix, &suffix, sizeof(vt->suffix));
1586         vt->next = NULL;
1587
1588         if (value_list_tail[i] == NULL)
1589           value_list_head[i] = vt;
1590         else
1591           value_list_tail[i]->next = vt;
1592         value_list_tail[i] = vt;
1593       }
1594
1595       /* Copy OID to oid_list[i] */
1596       memcpy(oid_list[i].oid, vb->name, sizeof(oid) * vb->name_length);
1597       oid_list[i].oid_len = vb->name_length;
1598
1599     } /* for (vb = res->variables ...) */
1600
1601     if (res != NULL)
1602       snmp_free_pdu(res);
1603     res = NULL;
1604   } /* while (status == 0) */
1605
1606   if (res != NULL)
1607     snmp_free_pdu(res);
1608   res = NULL;
1609
1610   if (status == 0)
1611     csnmp_dispatch_table(host, data, instance_list_head, value_list_head);
1612
1613   /* Free all allocated variables here */
1614   while (instance_list_head != NULL) {
1615     csnmp_list_instances_t *next = instance_list_head->next;
1616     sfree(instance_list_head);
1617     instance_list_head = next;
1618   }
1619
1620   for (i = 0; i < data->values_len; i++) {
1621     while (value_list_head[i] != NULL) {
1622       csnmp_table_values_t *next = value_list_head[i]->next;
1623       sfree(value_list_head[i]);
1624       value_list_head[i] = next;
1625     }
1626   }
1627
1628   sfree(value_list_head);
1629   sfree(value_list_tail);
1630
1631   return 0;
1632 } /* int csnmp_read_table */
1633
1634 static int csnmp_read_value(host_definition_t *host, data_definition_t *data) {
1635   struct snmp_pdu *req;
1636   struct snmp_pdu *res = NULL;
1637   struct variable_list *vb;
1638
1639   const data_set_t *ds;
1640   value_list_t vl = VALUE_LIST_INIT;
1641
1642   int status;
1643   size_t i;
1644
1645   DEBUG("snmp plugin: csnmp_read_value (host = %s, data = %s)", host->name,
1646         data->name);
1647
1648   if (host->sess_handle == NULL) {
1649     DEBUG("snmp plugin: csnmp_read_value: host->sess_handle == NULL");
1650     return -1;
1651   }
1652
1653   ds = plugin_get_ds(data->type);
1654   if (!ds) {
1655     ERROR("snmp plugin: DataSet `%s' not defined.", data->type);
1656     return -1;
1657   }
1658
1659   if (ds->ds_num != data->values_len) {
1660     ERROR("snmp plugin: DataSet `%s' requires %" PRIsz
1661           " values, but config talks "
1662           "about %" PRIsz,
1663           data->type, ds->ds_num, data->values_len);
1664     return -1;
1665   }
1666
1667   vl.values_len = ds->ds_num;
1668   vl.values = malloc(sizeof(*vl.values) * vl.values_len);
1669   if (vl.values == NULL)
1670     return -1;
1671   for (i = 0; i < vl.values_len; i++) {
1672     if (ds->ds[i].type == DS_TYPE_COUNTER)
1673       vl.values[i].counter = 0;
1674     else
1675       vl.values[i].gauge = NAN;
1676   }
1677
1678   sstrncpy(vl.host, host->name, sizeof(vl.host));
1679   sstrncpy(vl.plugin, data->plugin_name, sizeof(vl.plugin));
1680   sstrncpy(vl.type, data->type, sizeof(vl.type));
1681   if (data->type_instance)
1682     sstrncpy(vl.type_instance, data->type_instance, sizeof(vl.type_instance));
1683   if (data->plugin_instance)
1684     sstrncpy(vl.plugin_instance, data->plugin_instance,
1685              sizeof(vl.plugin_instance));
1686
1687   vl.interval = host->interval;
1688
1689   req = snmp_pdu_create(SNMP_MSG_GET);
1690   if (req == NULL) {
1691     ERROR("snmp plugin: snmp_pdu_create failed.");
1692     sfree(vl.values);
1693     return -1;
1694   }
1695
1696   for (i = 0; i < data->values_len; i++)
1697     snmp_add_null_var(req, data->values[i].oid, data->values[i].oid_len);
1698
1699   status = snmp_sess_synch_response(host->sess_handle, req, &res);
1700
1701   if ((status != STAT_SUCCESS) || (res == NULL)) {
1702     char *errstr = NULL;
1703
1704     snmp_sess_error(host->sess_handle, NULL, NULL, &errstr);
1705     ERROR("snmp plugin: host %s: snmp_sess_synch_response failed: %s",
1706           host->name, (errstr == NULL) ? "Unknown problem" : errstr);
1707
1708     if (res != NULL)
1709       snmp_free_pdu(res);
1710
1711     sfree(errstr);
1712     sfree(vl.values);
1713     csnmp_host_close_session(host);
1714
1715     return -1;
1716   }
1717
1718   for (vb = res->variables; vb != NULL; vb = vb->next_variable) {
1719 #if COLLECT_DEBUG
1720     char buffer[1024];
1721     snprint_variable(buffer, sizeof(buffer), vb->name, vb->name_length, vb);
1722     DEBUG("snmp plugin: Got this variable: %s", buffer);
1723 #endif /* COLLECT_DEBUG */
1724
1725     for (i = 0; i < data->values_len; i++)
1726       if (snmp_oid_compare(data->values[i].oid, data->values[i].oid_len,
1727                            vb->name, vb->name_length) == 0)
1728         vl.values[i] =
1729             csnmp_value_list_to_value(vb, ds->ds[i].type, data->scale,
1730                                       data->shift, host->name, data->name);
1731   } /* for (res->variables) */
1732
1733   snmp_free_pdu(res);
1734
1735   DEBUG("snmp plugin: -> plugin_dispatch_values (&vl);");
1736   plugin_dispatch_values(&vl);
1737   sfree(vl.values);
1738
1739   return 0;
1740 } /* int csnmp_read_value */
1741
1742 static int csnmp_read_host(user_data_t *ud) {
1743   host_definition_t *host;
1744   int status;
1745   int success;
1746   int i;
1747
1748   host = ud->data;
1749
1750   if (host->interval == 0)
1751     host->interval = plugin_get_interval();
1752
1753   if (host->sess_handle == NULL)
1754     csnmp_host_open_session(host);
1755
1756   if (host->sess_handle == NULL)
1757     return -1;
1758
1759   success = 0;
1760   for (i = 0; i < host->data_list_len; i++) {
1761     data_definition_t *data = host->data_list[i];
1762
1763     if (data->is_table)
1764       status = csnmp_read_table(host, data);
1765     else
1766       status = csnmp_read_value(host, data);
1767
1768     if (status == 0)
1769       success++;
1770   }
1771
1772   if (success == 0)
1773     return -1;
1774
1775   return 0;
1776 } /* int csnmp_read_host */
1777
1778 static int csnmp_init(void) {
1779   call_snmp_init_once();
1780
1781   return 0;
1782 } /* int csnmp_init */
1783
1784 static int csnmp_shutdown(void) {
1785   data_definition_t *data_this;
1786   data_definition_t *data_next;
1787
1788   /* When we get here, the read threads have been stopped and all the
1789    * `host_definition_t' will be freed. */
1790   DEBUG("snmp plugin: Destroying all data definitions.");
1791
1792   data_this = data_head;
1793   data_head = NULL;
1794   while (data_this != NULL) {
1795     data_next = data_this->next;
1796
1797     sfree(data_this->name);
1798     sfree(data_this->type);
1799     sfree(data_this->plugin_name);
1800     sfree(data_this->plugin_instance);
1801     sfree(data_this->type_instance);
1802     sfree(data_this->instance_prefix);
1803     sfree(data_this->values);
1804     sfree(data_this->ignores);
1805     sfree(data_this);
1806
1807     data_this = data_next;
1808   }
1809
1810   return 0;
1811 } /* int csnmp_shutdown */
1812
1813 void module_register(void) {
1814   plugin_register_complex_config("snmp", csnmp_config);
1815   plugin_register_init("snmp", csnmp_init);
1816   plugin_register_shutdown("snmp", csnmp_shutdown);
1817 } /* void module_register */