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