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