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