Merge pull request #2874 from elfiesmelfie/feat_virt_block_info
[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     snprintf(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   snprintf(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, .free_func = csnmp_host_definition_destroy,
880       });
881   if (status != 0) {
882     ERROR("snmp plugin: Registering complex read function failed.");
883     return -1;
884   }
885
886   return 0;
887 } /* int csnmp_config_add_host */
888
889 static int csnmp_config(oconfig_item_t *ci) {
890   call_snmp_init_once();
891
892   for (int i = 0; i < ci->children_num; i++) {
893     oconfig_item_t *child = ci->children + i;
894     if (strcasecmp("Data", child->key) == 0)
895       csnmp_config_add_data(child);
896     else if (strcasecmp("Host", child->key) == 0)
897       csnmp_config_add_host(child);
898     else {
899       WARNING("snmp plugin: Ignoring unknown config option `%s'.", child->key);
900     }
901   } /* for (ci->children) */
902
903   return 0;
904 } /* int csnmp_config */
905
906 /* }}} End of the config stuff. Now the interesting part begins */
907
908 static void csnmp_host_open_session(host_definition_t *host) {
909   struct snmp_session sess;
910   int error;
911
912   if (host->sess_handle != NULL)
913     csnmp_host_close_session(host);
914
915   snmp_sess_init(&sess);
916   sess.peername = host->address;
917   switch (host->version) {
918   case 1:
919     sess.version = SNMP_VERSION_1;
920     break;
921   case 3:
922     sess.version = SNMP_VERSION_3;
923     break;
924   default:
925     sess.version = SNMP_VERSION_2c;
926     break;
927   }
928
929   if (host->version == 3) {
930     sess.securityName = host->username;
931     sess.securityNameLen = strlen(host->username);
932     sess.securityLevel = host->security_level;
933
934     if (sess.securityLevel == SNMP_SEC_LEVEL_AUTHNOPRIV ||
935         sess.securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) {
936       sess.securityAuthProto = host->auth_protocol;
937       sess.securityAuthProtoLen = host->auth_protocol_len;
938       sess.securityAuthKeyLen = USM_AUTH_KU_LEN;
939       error = generate_Ku(sess.securityAuthProto, sess.securityAuthProtoLen,
940                           (u_char *)host->auth_passphrase,
941                           strlen(host->auth_passphrase), sess.securityAuthKey,
942                           &sess.securityAuthKeyLen);
943       if (error != SNMPERR_SUCCESS) {
944         ERROR("snmp plugin: host %s: Error generating Ku from auth_passphrase. "
945               "(Error %d)",
946               host->name, error);
947       }
948     }
949
950     if (sess.securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) {
951       sess.securityPrivProto = host->priv_protocol;
952       sess.securityPrivProtoLen = host->priv_protocol_len;
953       sess.securityPrivKeyLen = USM_PRIV_KU_LEN;
954       error = generate_Ku(sess.securityAuthProto, sess.securityAuthProtoLen,
955                           (u_char *)host->priv_passphrase,
956                           strlen(host->priv_passphrase), sess.securityPrivKey,
957                           &sess.securityPrivKeyLen);
958       if (error != SNMPERR_SUCCESS) {
959         ERROR("snmp plugin: host %s: Error generating Ku from priv_passphrase. "
960               "(Error %d)",
961               host->name, error);
962       }
963     }
964
965     if (host->context != NULL) {
966       sess.contextName = host->context;
967       sess.contextNameLen = strlen(host->context);
968     }
969   } else /* SNMPv1/2 "authenticates" with community string */
970   {
971     sess.community = (u_char *)host->community;
972     sess.community_len = strlen(host->community);
973   }
974
975   /* Set timeout & retries, if they have been changed from the default */
976   if (host->timeout != 0) {
977     /* net-snmp expects microseconds */
978     sess.timeout = CDTIME_T_TO_US(host->timeout);
979   }
980   if (host->retries >= 0) {
981     sess.retries = host->retries;
982   }
983
984   /* snmp_sess_open will copy the `struct snmp_session *'. */
985   host->sess_handle = snmp_sess_open(&sess);
986
987   if (host->sess_handle == NULL) {
988     char *errstr = NULL;
989
990     snmp_error(&sess, NULL, NULL, &errstr);
991
992     ERROR("snmp plugin: host %s: snmp_sess_open failed: %s", host->name,
993           (errstr == NULL) ? "Unknown problem" : errstr);
994     sfree(errstr);
995   }
996 } /* void csnmp_host_open_session */
997
998 /* TODO: Check if negative values wrap around. Problem: negative temperatures.
999  */
1000 static value_t csnmp_value_list_to_value(const struct variable_list *vl,
1001                                          int type, double scale, double shift,
1002                                          const char *host_name,
1003                                          const char *data_name) {
1004   value_t ret;
1005   uint64_t tmp_unsigned = 0;
1006   int64_t tmp_signed = 0;
1007   bool defined = 1;
1008   /* Set to true when the original SNMP type appears to have been signed. */
1009   bool prefer_signed = 0;
1010
1011   if ((vl->type == ASN_INTEGER) || (vl->type == ASN_UINTEGER) ||
1012       (vl->type == ASN_COUNTER)
1013 #ifdef ASN_TIMETICKS
1014       || (vl->type == ASN_TIMETICKS)
1015 #endif
1016       || (vl->type == ASN_GAUGE)) {
1017     tmp_unsigned = (uint32_t)*vl->val.integer;
1018     tmp_signed = (int32_t)*vl->val.integer;
1019
1020     if (vl->type == ASN_INTEGER)
1021       prefer_signed = 1;
1022
1023     DEBUG("snmp plugin: Parsed int32 value is %" PRIu64 ".", tmp_unsigned);
1024   } else if (vl->type == ASN_COUNTER64) {
1025     tmp_unsigned = (uint32_t)vl->val.counter64->high;
1026     tmp_unsigned = tmp_unsigned << 32;
1027     tmp_unsigned += (uint32_t)vl->val.counter64->low;
1028     tmp_signed = (int64_t)tmp_unsigned;
1029     DEBUG("snmp plugin: Parsed int64 value is %" PRIu64 ".", tmp_unsigned);
1030   } else if (vl->type == ASN_OCTET_STR) {
1031     /* We'll handle this later.. */
1032   } else {
1033     char oid_buffer[1024] = {0};
1034
1035     snprint_objid(oid_buffer, sizeof(oid_buffer) - 1, vl->name,
1036                   vl->name_length);
1037
1038 #ifdef ASN_NULL
1039     if (vl->type == ASN_NULL)
1040       INFO("snmp plugin: OID \"%s\" is undefined (type ASN_NULL)", oid_buffer);
1041     else
1042 #endif
1043       WARNING("snmp plugin: I don't know the ASN type #%i "
1044               "(OID: \"%s\", data block \"%s\", host block \"%s\")",
1045               (int)vl->type, oid_buffer,
1046               (data_name != NULL) ? data_name : "UNKNOWN",
1047               (host_name != NULL) ? host_name : "UNKNOWN");
1048
1049     defined = 0;
1050   }
1051
1052   if (vl->type == ASN_OCTET_STR) {
1053     int status = -1;
1054
1055     if (vl->val.string != NULL) {
1056       char string[64];
1057       size_t string_length;
1058
1059       string_length = sizeof(string) - 1;
1060       if (vl->val_len < string_length)
1061         string_length = vl->val_len;
1062
1063       /* The strings we get from the Net-SNMP library may not be null
1064        * terminated. That is why we're using `memcpy' here and not `strcpy'.
1065        * `string_length' is set to `vl->val_len' which holds the length of the
1066        * string.  -octo */
1067       memcpy(string, vl->val.string, string_length);
1068       string[string_length] = 0;
1069
1070       status = parse_value(string, &ret, type);
1071       if (status != 0) {
1072         ERROR("snmp plugin: host %s: csnmp_value_list_to_value: Parsing string "
1073               "as %s failed: %s",
1074               (host_name != NULL) ? host_name : "UNKNOWN",
1075               DS_TYPE_TO_STRING(type), string);
1076       }
1077     }
1078
1079     if (status != 0) {
1080       switch (type) {
1081       case DS_TYPE_COUNTER:
1082       case DS_TYPE_DERIVE:
1083       case DS_TYPE_ABSOLUTE:
1084         memset(&ret, 0, sizeof(ret));
1085         break;
1086
1087       case DS_TYPE_GAUGE:
1088         ret.gauge = NAN;
1089         break;
1090
1091       default:
1092         ERROR("snmp plugin: csnmp_value_list_to_value: Unknown "
1093               "data source type: %i.",
1094               type);
1095         ret.gauge = NAN;
1096       }
1097     }
1098   } /* if (vl->type == ASN_OCTET_STR) */
1099   else if (type == DS_TYPE_COUNTER) {
1100     ret.counter = tmp_unsigned;
1101   } else if (type == DS_TYPE_GAUGE) {
1102     if (!defined)
1103       ret.gauge = NAN;
1104     else if (prefer_signed)
1105       ret.gauge = (scale * tmp_signed) + shift;
1106     else
1107       ret.gauge = (scale * tmp_unsigned) + shift;
1108   } else if (type == DS_TYPE_DERIVE) {
1109     if (prefer_signed)
1110       ret.derive = (derive_t)tmp_signed;
1111     else
1112       ret.derive = (derive_t)tmp_unsigned;
1113   } else if (type == DS_TYPE_ABSOLUTE) {
1114     ret.absolute = (absolute_t)tmp_unsigned;
1115   } else {
1116     ERROR("snmp plugin: csnmp_value_list_to_value: Unknown data source "
1117           "type: %i.",
1118           type);
1119     ret.gauge = NAN;
1120   }
1121
1122   return ret;
1123 } /* value_t csnmp_value_list_to_value */
1124
1125 /* csnmp_strvbcopy_hexstring converts the bit string contained in "vb" to a hex
1126  * representation and writes it to dst. Returns zero on success and ENOMEM if
1127  * dst is not large enough to hold the string. dst is guaranteed to be
1128  * nul-terminated. */
1129 static int csnmp_strvbcopy_hexstring(char *dst, /* {{{ */
1130                                      const struct variable_list *vb,
1131                                      size_t dst_size) {
1132   char *buffer_ptr;
1133   size_t buffer_free;
1134
1135   dst[0] = 0;
1136
1137   buffer_ptr = dst;
1138   buffer_free = dst_size;
1139
1140   for (size_t i = 0; i < vb->val_len; i++) {
1141     int status;
1142
1143     status = snprintf(buffer_ptr, buffer_free, (i == 0) ? "%02x" : ":%02x",
1144                       (unsigned int)vb->val.bitstring[i]);
1145     assert(status >= 0);
1146
1147     if (((size_t)status) >= buffer_free) /* truncated */
1148     {
1149       dst[dst_size - 1] = '\0';
1150       return ENOMEM;
1151     } else /* if (status < buffer_free) */
1152     {
1153       buffer_ptr += (size_t)status;
1154       buffer_free -= (size_t)status;
1155     }
1156   }
1157
1158   return 0;
1159 } /* }}} int csnmp_strvbcopy_hexstring */
1160
1161 /* csnmp_strvbcopy copies the octet string or bit string contained in vb to
1162  * dst. If non-printable characters are detected, it will switch to a hex
1163  * representation of the string. Returns zero on success, EINVAL if vb does not
1164  * contain a string and ENOMEM if dst is not large enough to contain the
1165  * string. */
1166 static int csnmp_strvbcopy(char *dst, /* {{{ */
1167                            const struct variable_list *vb, size_t dst_size) {
1168   char *src;
1169   size_t num_chars;
1170
1171   if (vb->type == ASN_OCTET_STR)
1172     src = (char *)vb->val.string;
1173   else if (vb->type == ASN_BIT_STR)
1174     src = (char *)vb->val.bitstring;
1175   else if (vb->type == ASN_IPADDRESS) {
1176     return snprintf(dst, dst_size,
1177                     "%" PRIu8 ".%" PRIu8 ".%" PRIu8 ".%" PRIu8 "",
1178                     (uint8_t)vb->val.string[0], (uint8_t)vb->val.string[1],
1179                     (uint8_t)vb->val.string[2], (uint8_t)vb->val.string[3]);
1180   } else {
1181     dst[0] = 0;
1182     return EINVAL;
1183   }
1184
1185   num_chars = dst_size - 1;
1186   if (num_chars > vb->val_len)
1187     num_chars = vb->val_len;
1188
1189   for (size_t i = 0; i < num_chars; i++) {
1190     /* Check for control characters. */
1191     if ((unsigned char)src[i] < 32)
1192       return csnmp_strvbcopy_hexstring(dst, vb, dst_size);
1193     dst[i] = src[i];
1194   }
1195   dst[num_chars] = 0;
1196   dst[dst_size - 1] = '\0';
1197
1198   if (dst_size <= vb->val_len)
1199     return ENOMEM;
1200
1201   return 0;
1202 } /* }}} int csnmp_strvbcopy */
1203
1204 static csnmp_cell_char_t *csnmp_get_char_cell(const struct variable_list *vb,
1205                                               const oid_t *root_oid,
1206                                               const host_definition_t *hd,
1207                                               const data_definition_t *dd) {
1208
1209   if (vb == NULL)
1210     return NULL;
1211
1212   csnmp_cell_char_t *il = calloc(1, sizeof(*il));
1213   if (il == NULL) {
1214     ERROR("snmp plugin: calloc failed.");
1215     return NULL;
1216   }
1217   il->next = NULL;
1218
1219   oid_t vb_name;
1220   csnmp_oid_init(&vb_name, vb->name, vb->name_length);
1221
1222   if (csnmp_oid_suffix(&il->suffix, &vb_name, root_oid) != 0) {
1223     sfree(il);
1224     return NULL;
1225   }
1226
1227   /* Get value */
1228   if ((vb->type == ASN_OCTET_STR) || (vb->type == ASN_BIT_STR) ||
1229       (vb->type == ASN_IPADDRESS)) {
1230
1231     csnmp_strvbcopy(il->value, vb, sizeof(il->value));
1232
1233   } else {
1234     value_t val = csnmp_value_list_to_value(
1235         vb, DS_TYPE_COUNTER,
1236         /* scale = */ 1.0, /* shift = */ 0.0, hd->name, dd->name);
1237     snprintf(il->value, sizeof(il->value), "%" PRIu64, (uint64_t)val.counter);
1238   }
1239
1240   return il;
1241 } /* csnmp_cell_char_t csnmp_get_char_cell */
1242
1243 static void csnmp_cells_append(csnmp_cell_char_t **head,
1244                                csnmp_cell_char_t **tail,
1245                                csnmp_cell_char_t *il) {
1246   if (*head == NULL)
1247     *head = il;
1248   else
1249     (*tail)->next = il;
1250   *tail = il;
1251 } /* void csnmp_cells_append */
1252
1253 static bool csnmp_ignore_instance(csnmp_cell_char_t *cell,
1254                                   const data_definition_t *dd) {
1255   bool is_matched = 0;
1256   for (uint32_t i = 0; i < dd->ignores_len; i++) {
1257     int status = fnmatch(dd->ignores[i], cell->value, 0);
1258     if (status == 0) {
1259       if (!dd->invert_match) {
1260         return 1;
1261       } else {
1262         is_matched = 1;
1263         break;
1264       }
1265     }
1266   }
1267   if (dd->invert_match && !is_matched) {
1268     return 1;
1269   }
1270   return 0;
1271 } /* bool csnmp_ignore_instance */
1272
1273 static void csnmp_cell_replace_reserved_chars(csnmp_cell_char_t *cell) {
1274   for (char *ptr = cell->value; *ptr != '\0'; ptr++) {
1275     if ((*ptr > 0) && (*ptr < 32))
1276       *ptr = ' ';
1277     else if (*ptr == '/')
1278       *ptr = '_';
1279   }
1280 } /* void csnmp_cell_replace_reserved_chars */
1281
1282 static int csnmp_dispatch_table(host_definition_t *host,
1283                                 data_definition_t *data,
1284                                 csnmp_cell_char_t *type_instance_cells,
1285                                 csnmp_cell_char_t *plugin_instance_cells,
1286                                 csnmp_cell_char_t *hostname_cells,
1287                                 csnmp_cell_char_t *filter_cells,
1288                                 csnmp_cell_value_t **value_cells) {
1289   const data_set_t *ds;
1290   value_list_t vl = VALUE_LIST_INIT;
1291
1292   csnmp_cell_char_t *type_instance_cell_ptr = type_instance_cells;
1293   csnmp_cell_char_t *plugin_instance_cell_ptr = plugin_instance_cells;
1294   csnmp_cell_char_t *hostname_cell_ptr = hostname_cells;
1295   csnmp_cell_char_t *filter_cell_ptr = filter_cells;
1296   csnmp_cell_value_t *value_cell_ptr[data->values_len];
1297
1298   size_t i;
1299   bool have_more;
1300   oid_t current_suffix;
1301
1302   ds = plugin_get_ds(data->type);
1303   if (!ds) {
1304     ERROR("snmp plugin: DataSet `%s' not defined.", data->type);
1305     return -1;
1306   }
1307   assert(ds->ds_num == data->values_len);
1308   assert(data->values_len > 0);
1309
1310   for (i = 0; i < data->values_len; i++)
1311     value_cell_ptr[i] = value_cells[i];
1312
1313   sstrncpy(vl.plugin, data->plugin_name, sizeof(vl.plugin));
1314   sstrncpy(vl.type, data->type, sizeof(vl.type));
1315
1316   have_more = 1;
1317   while (have_more) {
1318     bool suffix_skipped = 0;
1319
1320     /* Determine next suffix to handle. */
1321     if (type_instance_cells != NULL) {
1322       if (type_instance_cell_ptr == NULL) {
1323         have_more = 0;
1324         continue;
1325       }
1326
1327       memcpy(&current_suffix, &type_instance_cell_ptr->suffix,
1328              sizeof(current_suffix));
1329     } else {
1330       /* no instance configured */
1331       csnmp_cell_value_t *ptr = value_cell_ptr[0];
1332       if (ptr == NULL) {
1333         have_more = 0;
1334         continue;
1335       }
1336
1337       memcpy(&current_suffix, &ptr->suffix, sizeof(current_suffix));
1338     }
1339
1340     /*
1341     char oid_buffer[1024] = {0};
1342     snprint_objid(oid_buffer, sizeof(oid_buffer) - 1, current_suffix.oid,
1343                           current_suffix.oid_len);
1344     DEBUG("SNMP PLUGIN: SUFFIX %s", oid_buffer);
1345     */
1346
1347     /* Update plugin_instance_cell_ptr to point expected suffix */
1348     if (plugin_instance_cells != NULL) {
1349       while ((plugin_instance_cell_ptr != NULL) &&
1350              (csnmp_oid_compare(&plugin_instance_cell_ptr->suffix,
1351                                 &current_suffix) < 0))
1352         plugin_instance_cell_ptr = plugin_instance_cell_ptr->next;
1353
1354       if (plugin_instance_cell_ptr == NULL) {
1355         have_more = 0;
1356         continue;
1357       }
1358
1359       if (csnmp_oid_compare(&plugin_instance_cell_ptr->suffix,
1360                             &current_suffix) > 0) {
1361         /* This suffix is missing in the subtree. Indicate this with the
1362          * "suffix_skipped" flag and try the next instance / suffix. */
1363         suffix_skipped = 1;
1364       }
1365     }
1366
1367     /* Update hostname_cell_ptr to point expected suffix */
1368     if (hostname_cells != NULL) {
1369       while (
1370           (hostname_cell_ptr != NULL) &&
1371           (csnmp_oid_compare(&hostname_cell_ptr->suffix, &current_suffix) < 0))
1372         hostname_cell_ptr = hostname_cell_ptr->next;
1373
1374       if (hostname_cell_ptr == NULL) {
1375         have_more = 0;
1376         continue;
1377       }
1378
1379       if (csnmp_oid_compare(&hostname_cell_ptr->suffix, &current_suffix) > 0) {
1380         /* This suffix is missing in the subtree. Indicate this with the
1381          * "suffix_skipped" flag and try the next instance / suffix. */
1382         suffix_skipped = 1;
1383       }
1384     }
1385
1386     /* Update filter_cell_ptr to point expected suffix */
1387     if (filter_cells != NULL) {
1388       while ((filter_cell_ptr != NULL) &&
1389              (csnmp_oid_compare(&filter_cell_ptr->suffix, &current_suffix) < 0))
1390         filter_cell_ptr = filter_cell_ptr->next;
1391
1392       if (filter_cell_ptr == NULL) {
1393         have_more = 0;
1394         continue;
1395       }
1396
1397       if (csnmp_oid_compare(&filter_cell_ptr->suffix, &current_suffix) > 0) {
1398         /* This suffix is missing in the subtree. Indicate this with the
1399          * "suffix_skipped" flag and try the next instance / suffix. */
1400         suffix_skipped = 1;
1401       }
1402     }
1403
1404     /* Update all the value_cell_ptr to point at the entry with the same
1405      * trailing partial OID */
1406     for (i = 0; i < data->values_len; i++) {
1407       while (
1408           (value_cell_ptr[i] != NULL) &&
1409           (csnmp_oid_compare(&value_cell_ptr[i]->suffix, &current_suffix) < 0))
1410         value_cell_ptr[i] = value_cell_ptr[i]->next;
1411
1412       if (value_cell_ptr[i] == NULL) {
1413         have_more = 0;
1414         break;
1415       } else if (csnmp_oid_compare(&value_cell_ptr[i]->suffix,
1416                                    &current_suffix) > 0) {
1417         /* This suffix is missing in the subtree. Indicate this with the
1418          * "suffix_skipped" flag and try the next instance / suffix. */
1419         suffix_skipped = 1;
1420         break;
1421       }
1422     } /* for (i = 0; i < columns; i++) */
1423
1424     if (!have_more)
1425       break;
1426
1427     /* Matching the values failed. Start from the beginning again. */
1428     if (suffix_skipped) {
1429       if (type_instance_cells != NULL)
1430         type_instance_cell_ptr = type_instance_cell_ptr->next;
1431       else
1432         value_cell_ptr[0] = value_cell_ptr[0]->next;
1433
1434       continue;
1435     }
1436
1437 /* if we reach this line, all value_cell_ptr[i] are non-NULL and are set
1438  * to the same subid. type_instance_cell_ptr is either NULL or points to the
1439  * same subid, too. */
1440 #if COLLECT_DEBUG
1441     for (i = 1; i < data->values_len; i++) {
1442       assert(value_cell_ptr[i] != NULL);
1443       assert(csnmp_oid_compare(&value_cell_ptr[i - 1]->suffix,
1444                                &value_cell_ptr[i]->suffix) == 0);
1445     }
1446     assert((type_instance_cell_ptr == NULL) ||
1447            (csnmp_oid_compare(&type_instance_cell_ptr->suffix,
1448                               &value_cell_ptr[0]->suffix) == 0));
1449     assert((plugin_instance_cell_ptr == NULL) ||
1450            (csnmp_oid_compare(&plugin_instance_cell_ptr->suffix,
1451                               &value_cell_ptr[0]->suffix) == 0));
1452     assert((hostname_cell_ptr == NULL) ||
1453            (csnmp_oid_compare(&hostname_cell_ptr->suffix,
1454                               &value_cell_ptr[0]->suffix) == 0));
1455     assert((filter_cell_ptr == NULL) ||
1456            (csnmp_oid_compare(&filter_cell_ptr->suffix,
1457                               &value_cell_ptr[0]->suffix) == 0));
1458 #endif
1459
1460     /* Check the value in filter column */
1461     if (filter_cell_ptr &&
1462         ignorelist_match(data->ignorelist, filter_cell_ptr->value) != 0) {
1463       if (type_instance_cells != NULL)
1464         type_instance_cell_ptr = type_instance_cell_ptr->next;
1465       else
1466         value_cell_ptr[0] = value_cell_ptr[0]->next;
1467
1468       continue;
1469     }
1470
1471     /* set vl.host */
1472     if (data->host.configured) {
1473       char temp[DATA_MAX_NAME_LEN];
1474       if (hostname_cell_ptr == NULL)
1475         csnmp_oid_to_string(temp, sizeof(temp), &current_suffix);
1476       else
1477         sstrncpy(temp, hostname_cell_ptr->value, sizeof(temp));
1478
1479       if (data->host.prefix == NULL)
1480         sstrncpy(vl.host, temp, sizeof(vl.host));
1481       else
1482         snprintf(vl.host, sizeof(vl.host), "%s%s", data->host.prefix, temp);
1483     } else {
1484       sstrncpy(vl.host, host->name, sizeof(vl.host));
1485     }
1486
1487     /* set vl.type_instance */
1488     if (data->type_instance.configured) {
1489       char temp[DATA_MAX_NAME_LEN];
1490       if (type_instance_cell_ptr == NULL)
1491         csnmp_oid_to_string(temp, sizeof(temp), &current_suffix);
1492       else
1493         sstrncpy(temp, type_instance_cell_ptr->value, sizeof(temp));
1494
1495       if (data->type_instance.prefix == NULL)
1496         sstrncpy(vl.type_instance, temp, sizeof(vl.type_instance));
1497       else
1498         snprintf(vl.type_instance, sizeof(vl.type_instance), "%s%s",
1499                  data->type_instance.prefix, temp);
1500     } else if (data->type_instance.value) {
1501       sstrncpy(vl.type_instance, data->type_instance.value,
1502                sizeof(vl.type_instance));
1503     }
1504
1505     /* set vl.plugin_instance */
1506     if (data->plugin_instance.configured) {
1507       char temp[DATA_MAX_NAME_LEN];
1508       if (plugin_instance_cell_ptr == NULL)
1509         csnmp_oid_to_string(temp, sizeof(temp), &current_suffix);
1510       else
1511         sstrncpy(temp, plugin_instance_cell_ptr->value, sizeof(temp));
1512
1513       if (data->plugin_instance.prefix == NULL)
1514         sstrncpy(vl.plugin_instance, temp, sizeof(vl.plugin_instance));
1515       else
1516         snprintf(vl.plugin_instance, sizeof(vl.plugin_instance), "%s%s",
1517                  data->plugin_instance.prefix, temp);
1518     } else if (data->plugin_instance.value) {
1519       sstrncpy(vl.plugin_instance, data->plugin_instance.value,
1520                sizeof(vl.plugin_instance));
1521     }
1522
1523     vl.values_len = data->values_len;
1524     value_t values[vl.values_len];
1525     vl.values = values;
1526
1527     for (i = 0; i < data->values_len; i++)
1528       vl.values[i] = value_cell_ptr[i]->value;
1529
1530     plugin_dispatch_values(&vl);
1531
1532     /* prevent leakage of pointer to local variable. */
1533     vl.values_len = 0;
1534     vl.values = NULL;
1535
1536     if (type_instance_cells != NULL)
1537       type_instance_cell_ptr = type_instance_cell_ptr->next;
1538     else
1539       value_cell_ptr[0] = value_cell_ptr[0]->next;
1540   } /* while (have_more) */
1541
1542   return 0;
1543 } /* int csnmp_dispatch_table */
1544
1545 static int csnmp_read_table(host_definition_t *host, data_definition_t *data) {
1546   struct snmp_pdu *req;
1547   struct snmp_pdu *res = NULL;
1548   struct variable_list *vb;
1549
1550   const data_set_t *ds;
1551
1552   size_t oid_list_len = data->values_len;
1553
1554   if (data->type_instance.oid.oid_len > 0)
1555     oid_list_len++;
1556
1557   if (data->plugin_instance.oid.oid_len > 0)
1558     oid_list_len++;
1559
1560   if (data->host.oid.oid_len > 0)
1561     oid_list_len++;
1562
1563   if (data->filter_oid.oid_len > 0)
1564     oid_list_len++;
1565
1566   /* Holds the last OID returned by the device. We use this in the GETNEXT
1567    * request to proceed. */
1568   oid_t oid_list[oid_list_len];
1569   /* Set to false when an OID has left its subtree so we don't re-request it
1570    * again. */
1571   csnmp_oid_type_t oid_list_todo[oid_list_len];
1572
1573   int status;
1574   size_t i;
1575
1576   /* `value_list_head' and `value_cells_tail' implement a linked list for each
1577    * value. `instance_cells_head' and `instance_cells_tail' implement a linked
1578    * list of instance names. This is used to jump gaps in the table. */
1579   csnmp_cell_char_t *type_instance_cells_head = NULL;
1580   csnmp_cell_char_t *type_instance_cells_tail = NULL;
1581   csnmp_cell_char_t *plugin_instance_cells_head = NULL;
1582   csnmp_cell_char_t *plugin_instance_cells_tail = NULL;
1583   csnmp_cell_char_t *hostname_cells_head = NULL;
1584   csnmp_cell_char_t *hostname_cells_tail = NULL;
1585   csnmp_cell_char_t *filter_cells_head = NULL;
1586   csnmp_cell_char_t *filter_cells_tail = NULL;
1587   csnmp_cell_value_t **value_cells_head;
1588   csnmp_cell_value_t **value_cells_tail;
1589
1590   DEBUG("snmp plugin: csnmp_read_table (host = %s, data = %s)", host->name,
1591         data->name);
1592
1593   if (host->sess_handle == NULL) {
1594     DEBUG("snmp plugin: csnmp_read_table: host->sess_handle == NULL");
1595     return -1;
1596   }
1597
1598   ds = plugin_get_ds(data->type);
1599   if (!ds) {
1600     ERROR("snmp plugin: DataSet `%s' not defined.", data->type);
1601     return -1;
1602   }
1603
1604   if (ds->ds_num != data->values_len) {
1605     ERROR("snmp plugin: DataSet `%s' requires %" PRIsz
1606           " values, but config talks "
1607           "about %" PRIsz,
1608           data->type, ds->ds_num, data->values_len);
1609     return -1;
1610   }
1611   assert(data->values_len > 0);
1612
1613   for (i = 0; i < data->values_len; i++)
1614     oid_list_todo[i] = OID_TYPE_VARIABLE;
1615
1616   /* We need a copy of all the OIDs, because GETNEXT will destroy them. */
1617   memcpy(oid_list, data->values, data->values_len * sizeof(oid_t));
1618
1619   if (data->type_instance.oid.oid_len > 0) {
1620     memcpy(oid_list + i, &data->type_instance.oid, sizeof(oid_t));
1621     oid_list_todo[i] = OID_TYPE_TYPEINSTANCE;
1622     i++;
1623   }
1624
1625   if (data->plugin_instance.oid.oid_len > 0) {
1626     memcpy(oid_list + i, &data->plugin_instance.oid, sizeof(oid_t));
1627     oid_list_todo[i] = OID_TYPE_PLUGININSTANCE;
1628     i++;
1629   }
1630
1631   if (data->host.oid.oid_len > 0) {
1632     memcpy(oid_list + i, &data->host.oid, sizeof(oid_t));
1633     oid_list_todo[i] = OID_TYPE_HOST;
1634     i++;
1635   }
1636
1637   if (data->filter_oid.oid_len > 0) {
1638     memcpy(oid_list + i, &data->filter_oid, sizeof(oid_t));
1639     oid_list_todo[i] = OID_TYPE_FILTER;
1640     i++;
1641   }
1642
1643   /* We're going to construct n linked lists, one for each "value".
1644    * value_cells_head will contain pointers to the heads of these linked lists,
1645    * value_cells_tail will contain pointers to the tail of the lists. */
1646   value_cells_head = calloc(data->values_len, sizeof(*value_cells_head));
1647   value_cells_tail = calloc(data->values_len, sizeof(*value_cells_tail));
1648   if ((value_cells_head == NULL) || (value_cells_tail == NULL)) {
1649     ERROR("snmp plugin: csnmp_read_table: calloc failed.");
1650     sfree(value_cells_head);
1651     sfree(value_cells_tail);
1652     return -1;
1653   }
1654
1655   status = 0;
1656   while (status == 0) {
1657     req = snmp_pdu_create(SNMP_MSG_GETNEXT);
1658     if (req == NULL) {
1659       ERROR("snmp plugin: snmp_pdu_create failed.");
1660       status = -1;
1661       break;
1662     }
1663
1664     size_t oid_list_todo_num = 0;
1665     size_t var_idx[oid_list_len];
1666     memset(var_idx, 0, sizeof(var_idx));
1667
1668     for (i = 0; i < oid_list_len; i++) {
1669       /* Do not rerequest already finished OIDs */
1670       if (!oid_list_todo[i])
1671         continue;
1672       snmp_add_null_var(req, oid_list[i].oid, oid_list[i].oid_len);
1673       var_idx[oid_list_todo_num] = i;
1674       oid_list_todo_num++;
1675     }
1676
1677     if (oid_list_todo_num == 0) {
1678       /* The request is still empty - so we are finished */
1679       DEBUG("snmp plugin: all variables have left their subtree");
1680       snmp_free_pdu(req);
1681       status = 0;
1682       break;
1683     }
1684
1685     res = NULL;
1686     status = snmp_sess_synch_response(host->sess_handle, req, &res);
1687
1688     /* snmp_sess_synch_response always frees our req PDU */
1689     req = NULL;
1690
1691     if ((status != STAT_SUCCESS) || (res == NULL)) {
1692       char *errstr = NULL;
1693
1694       snmp_sess_error(host->sess_handle, NULL, NULL, &errstr);
1695
1696       c_complain(LOG_ERR, &host->complaint,
1697                  "snmp plugin: host %s: snmp_sess_synch_response failed: %s",
1698                  host->name, (errstr == NULL) ? "Unknown problem" : errstr);
1699
1700       if (res != NULL)
1701         snmp_free_pdu(res);
1702       res = NULL;
1703
1704       sfree(errstr);
1705       csnmp_host_close_session(host);
1706
1707       status = -1;
1708       break;
1709     }
1710
1711     status = 0;
1712     assert(res != NULL);
1713     c_release(LOG_INFO, &host->complaint,
1714               "snmp plugin: host %s: snmp_sess_synch_response successful.",
1715               host->name);
1716
1717     vb = res->variables;
1718     if (vb == NULL) {
1719       status = -1;
1720       break;
1721     }
1722
1723     if (res->errstat != SNMP_ERR_NOERROR) {
1724       if (res->errindex != 0) {
1725         /* Find the OID which caused error */
1726         for (i = 1, vb = res->variables; vb != NULL && i != res->errindex;
1727              vb = vb->next_variable, i++)
1728           /* do nothing */;
1729       }
1730
1731       if ((res->errindex == 0) || (vb == NULL)) {
1732         ERROR("snmp plugin: host %s; data %s: response error: %s (%li) ",
1733               host->name, data->name, snmp_errstring(res->errstat),
1734               res->errstat);
1735         status = -1;
1736         break;
1737       }
1738
1739       char oid_buffer[1024] = {0};
1740       snprint_objid(oid_buffer, sizeof(oid_buffer) - 1, vb->name,
1741                     vb->name_length);
1742       NOTICE("snmp plugin: host %s; data %s: OID `%s` failed: %s", host->name,
1743              data->name, oid_buffer, snmp_errstring(res->errstat));
1744
1745       /* Get value index from todo list and skip OID found */
1746       assert(res->errindex <= oid_list_todo_num);
1747       i = var_idx[res->errindex - 1];
1748       assert(i < oid_list_len);
1749       oid_list_todo[i] = 0;
1750
1751       snmp_free_pdu(res);
1752       res = NULL;
1753       continue;
1754     }
1755
1756     for (vb = res->variables, i = 0; (vb != NULL);
1757          vb = vb->next_variable, i++) {
1758       /* Calculate value index from todo list */
1759       while ((i < oid_list_len) && !oid_list_todo[i]) {
1760         i++;
1761       }
1762       if (i >= oid_list_len) {
1763         break;
1764       }
1765
1766       /* An instance is configured and the res variable we process is the
1767        * instance value */
1768       if (oid_list_todo[i] == OID_TYPE_TYPEINSTANCE) {
1769         if ((vb->type == SNMP_ENDOFMIBVIEW) ||
1770             (snmp_oid_ncompare(data->type_instance.oid.oid,
1771                                data->type_instance.oid.oid_len, vb->name,
1772                                vb->name_length,
1773                                data->type_instance.oid.oid_len) != 0)) {
1774           DEBUG("snmp plugin: host = %s; data = %s; TypeInstance left its "
1775                 "subtree.",
1776                 host->name, data->name);
1777           oid_list_todo[i] = 0;
1778           continue;
1779         }
1780
1781         /* Allocate a new `csnmp_cell_char_t', insert the instance name and
1782          * add it to the list */
1783         csnmp_cell_char_t *cell =
1784             csnmp_get_char_cell(vb, &data->type_instance.oid, host, data);
1785         if (cell == NULL) {
1786           ERROR("snmp plugin: host %s: csnmp_get_char_cell() failed.",
1787                 host->name);
1788           status = -1;
1789           break;
1790         }
1791
1792         if (csnmp_ignore_instance(cell, data)) {
1793           sfree(cell);
1794         } else {
1795           csnmp_cell_replace_reserved_chars(cell);
1796
1797           DEBUG("snmp plugin: il->type_instance = `%s';", cell->value);
1798           csnmp_cells_append(&type_instance_cells_head,
1799                              &type_instance_cells_tail, cell);
1800         }
1801       } else if (oid_list_todo[i] == OID_TYPE_PLUGININSTANCE) {
1802         if ((vb->type == SNMP_ENDOFMIBVIEW) ||
1803             (snmp_oid_ncompare(data->plugin_instance.oid.oid,
1804                                data->plugin_instance.oid.oid_len, vb->name,
1805                                vb->name_length,
1806                                data->plugin_instance.oid.oid_len) != 0)) {
1807           DEBUG("snmp plugin: host = %s; data = %s; TypeInstance left its "
1808                 "subtree.",
1809                 host->name, data->name);
1810           oid_list_todo[i] = 0;
1811           continue;
1812         }
1813
1814         /* Allocate a new `csnmp_cell_char_t', insert the instance name and
1815          * add it to the list */
1816         csnmp_cell_char_t *cell =
1817             csnmp_get_char_cell(vb, &data->plugin_instance.oid, host, data);
1818         if (cell == NULL) {
1819           ERROR("snmp plugin: host %s: csnmp_get_char_cell() failed.",
1820                 host->name);
1821           status = -1;
1822           break;
1823         }
1824
1825         csnmp_cell_replace_reserved_chars(cell);
1826
1827         DEBUG("snmp plugin: il->plugin_instance = `%s';", cell->value);
1828         csnmp_cells_append(&plugin_instance_cells_head,
1829                            &plugin_instance_cells_tail, cell);
1830       } else if (oid_list_todo[i] == OID_TYPE_HOST) {
1831         if ((vb->type == SNMP_ENDOFMIBVIEW) ||
1832             (snmp_oid_ncompare(data->host.oid.oid, data->host.oid.oid_len,
1833                                vb->name, vb->name_length,
1834                                data->host.oid.oid_len) != 0)) {
1835           DEBUG("snmp plugin: host = %s; data = %s; Host left its subtree.",
1836                 host->name, data->name);
1837           oid_list_todo[i] = 0;
1838           continue;
1839         }
1840
1841         /* Allocate a new `csnmp_cell_char_t', insert the instance name and
1842          * add it to the list */
1843         csnmp_cell_char_t *cell =
1844             csnmp_get_char_cell(vb, &data->host.oid, host, data);
1845         if (cell == NULL) {
1846           ERROR("snmp plugin: host %s: csnmp_get_char_cell() failed.",
1847                 host->name);
1848           status = -1;
1849           break;
1850         }
1851
1852         csnmp_cell_replace_reserved_chars(cell);
1853
1854         DEBUG("snmp plugin: il->hostname = `%s';", cell->value);
1855         csnmp_cells_append(&hostname_cells_head, &hostname_cells_tail, cell);
1856       } else if (oid_list_todo[i] == OID_TYPE_FILTER) {
1857         if ((vb->type == SNMP_ENDOFMIBVIEW) ||
1858             (snmp_oid_ncompare(data->filter_oid.oid, data->filter_oid.oid_len,
1859                                vb->name, vb->name_length,
1860                                data->filter_oid.oid_len) != 0)) {
1861           DEBUG("snmp plugin: host = %s; data = %s; Host left its subtree.",
1862                 host->name, data->name);
1863           oid_list_todo[i] = 0;
1864           continue;
1865         }
1866
1867         /* Allocate a new `csnmp_cell_char_t', insert the instance name and
1868          * add it to the list */
1869         csnmp_cell_char_t *cell =
1870             csnmp_get_char_cell(vb, &data->filter_oid, host, data);
1871         if (cell == NULL) {
1872           ERROR("snmp plugin: host %s: csnmp_get_char_cell() failed.",
1873                 host->name);
1874           status = -1;
1875           break;
1876         }
1877
1878         csnmp_cell_replace_reserved_chars(cell);
1879
1880         DEBUG("snmp plugin: il->filter = `%s';", cell->value);
1881         csnmp_cells_append(&filter_cells_head, &filter_cells_tail, cell);
1882       } else /* The variable we are processing is a normal value */
1883       {
1884         assert(oid_list_todo[i] == OID_TYPE_VARIABLE);
1885
1886         csnmp_cell_value_t *vt;
1887         oid_t vb_name;
1888         oid_t suffix;
1889         int ret;
1890
1891         csnmp_oid_init(&vb_name, vb->name, vb->name_length);
1892
1893         /* Calculate the current suffix. This is later used to check that the
1894          * suffix is increasing. This also checks if we left the subtree */
1895         ret = csnmp_oid_suffix(&suffix, &vb_name, data->values + i);
1896         if (ret != 0) {
1897           DEBUG("snmp plugin: host = %s; data = %s; i = %" PRIsz "; "
1898                 "Value probably left its subtree.",
1899                 host->name, data->name, i);
1900           oid_list_todo[i] = 0;
1901           continue;
1902         }
1903
1904         /* Make sure the OIDs returned by the agent are increasing. Otherwise
1905          * our table matching algorithm will get confused. */
1906         if ((value_cells_tail[i] != NULL) &&
1907             (csnmp_oid_compare(&suffix, &value_cells_tail[i]->suffix) <= 0)) {
1908           DEBUG("snmp plugin: host = %s; data = %s; i = %" PRIsz "; "
1909                 "Suffix is not increasing.",
1910                 host->name, data->name, i);
1911           oid_list_todo[i] = 0;
1912           continue;
1913         }
1914
1915         vt = calloc(1, sizeof(*vt));
1916         if (vt == NULL) {
1917           ERROR("snmp plugin: calloc failed.");
1918           status = -1;
1919           break;
1920         }
1921
1922         vt->value =
1923             csnmp_value_list_to_value(vb, ds->ds[i].type, data->scale,
1924                                       data->shift, host->name, data->name);
1925         memcpy(&vt->suffix, &suffix, sizeof(vt->suffix));
1926         vt->next = NULL;
1927
1928         if (value_cells_tail[i] == NULL)
1929           value_cells_head[i] = vt;
1930         else
1931           value_cells_tail[i]->next = vt;
1932         value_cells_tail[i] = vt;
1933       }
1934
1935       /* Copy OID to oid_list[i] */
1936       memcpy(oid_list[i].oid, vb->name, sizeof(oid) * vb->name_length);
1937       oid_list[i].oid_len = vb->name_length;
1938
1939     } /* for (vb = res->variables ...) */
1940
1941     if (res != NULL)
1942       snmp_free_pdu(res);
1943     res = NULL;
1944   } /* while (status == 0) */
1945
1946   if (res != NULL)
1947     snmp_free_pdu(res);
1948   res = NULL;
1949
1950   if (status == 0)
1951     csnmp_dispatch_table(host, data, type_instance_cells_head,
1952                          plugin_instance_cells_head, hostname_cells_head,
1953                          filter_cells_head, value_cells_head);
1954
1955   /* Free all allocated variables here */
1956   while (type_instance_cells_head != NULL) {
1957     csnmp_cell_char_t *next = type_instance_cells_head->next;
1958     sfree(type_instance_cells_head);
1959     type_instance_cells_head = next;
1960   }
1961
1962   while (plugin_instance_cells_head != NULL) {
1963     csnmp_cell_char_t *next = plugin_instance_cells_head->next;
1964     sfree(plugin_instance_cells_head);
1965     plugin_instance_cells_head = next;
1966   }
1967
1968   while (hostname_cells_head != NULL) {
1969     csnmp_cell_char_t *next = hostname_cells_head->next;
1970     sfree(hostname_cells_head);
1971     hostname_cells_head = next;
1972   }
1973
1974   while (filter_cells_head != NULL) {
1975     csnmp_cell_char_t *next = filter_cells_head->next;
1976     sfree(filter_cells_head);
1977     filter_cells_head = next;
1978   }
1979
1980   for (i = 0; i < data->values_len; i++) {
1981     while (value_cells_head[i] != NULL) {
1982       csnmp_cell_value_t *next = value_cells_head[i]->next;
1983       sfree(value_cells_head[i]);
1984       value_cells_head[i] = next;
1985     }
1986   }
1987
1988   sfree(value_cells_head);
1989   sfree(value_cells_tail);
1990
1991   return 0;
1992 } /* int csnmp_read_table */
1993
1994 static int csnmp_read_value(host_definition_t *host, data_definition_t *data) {
1995   struct snmp_pdu *req;
1996   struct snmp_pdu *res = NULL;
1997   struct variable_list *vb;
1998
1999   const data_set_t *ds;
2000   value_list_t vl = VALUE_LIST_INIT;
2001
2002   int status;
2003   size_t i;
2004
2005   DEBUG("snmp plugin: csnmp_read_value (host = %s, data = %s)", host->name,
2006         data->name);
2007
2008   if (host->sess_handle == NULL) {
2009     DEBUG("snmp plugin: csnmp_read_value: host->sess_handle == NULL");
2010     return -1;
2011   }
2012
2013   ds = plugin_get_ds(data->type);
2014   if (!ds) {
2015     ERROR("snmp plugin: DataSet `%s' not defined.", data->type);
2016     return -1;
2017   }
2018
2019   if (ds->ds_num != data->values_len) {
2020     ERROR("snmp plugin: DataSet `%s' requires %" PRIsz
2021           " values, but config talks "
2022           "about %" PRIsz,
2023           data->type, ds->ds_num, data->values_len);
2024     return -1;
2025   }
2026
2027   vl.values_len = ds->ds_num;
2028   vl.values = malloc(sizeof(*vl.values) * vl.values_len);
2029   if (vl.values == NULL)
2030     return -1;
2031   for (i = 0; i < vl.values_len; i++) {
2032     if (ds->ds[i].type == DS_TYPE_COUNTER)
2033       vl.values[i].counter = 0;
2034     else
2035       vl.values[i].gauge = NAN;
2036   }
2037
2038   sstrncpy(vl.host, host->name, sizeof(vl.host));
2039   sstrncpy(vl.plugin, data->plugin_name, sizeof(vl.plugin));
2040   sstrncpy(vl.type, data->type, sizeof(vl.type));
2041   if (data->type_instance.value)
2042     sstrncpy(vl.type_instance, data->type_instance.value,
2043              sizeof(vl.type_instance));
2044   if (data->plugin_instance.value)
2045     sstrncpy(vl.plugin_instance, data->plugin_instance.value,
2046              sizeof(vl.plugin_instance));
2047
2048   req = snmp_pdu_create(SNMP_MSG_GET);
2049   if (req == NULL) {
2050     ERROR("snmp plugin: snmp_pdu_create failed.");
2051     sfree(vl.values);
2052     return -1;
2053   }
2054
2055   for (i = 0; i < data->values_len; i++)
2056     snmp_add_null_var(req, data->values[i].oid, data->values[i].oid_len);
2057
2058   status = snmp_sess_synch_response(host->sess_handle, req, &res);
2059
2060   if ((status != STAT_SUCCESS) || (res == NULL)) {
2061     char *errstr = NULL;
2062
2063     snmp_sess_error(host->sess_handle, NULL, NULL, &errstr);
2064     ERROR("snmp plugin: host %s: snmp_sess_synch_response failed: %s",
2065           host->name, (errstr == NULL) ? "Unknown problem" : errstr);
2066
2067     if (res != NULL)
2068       snmp_free_pdu(res);
2069
2070     sfree(errstr);
2071     sfree(vl.values);
2072     csnmp_host_close_session(host);
2073
2074     return -1;
2075   }
2076
2077   for (vb = res->variables; vb != NULL; vb = vb->next_variable) {
2078 #if COLLECT_DEBUG
2079     char buffer[1024];
2080     snprint_variable(buffer, sizeof(buffer), vb->name, vb->name_length, vb);
2081     DEBUG("snmp plugin: Got this variable: %s", buffer);
2082 #endif /* COLLECT_DEBUG */
2083
2084     for (i = 0; i < data->values_len; i++)
2085       if (snmp_oid_compare(data->values[i].oid, data->values[i].oid_len,
2086                            vb->name, vb->name_length) == 0)
2087         vl.values[i] =
2088             csnmp_value_list_to_value(vb, ds->ds[i].type, data->scale,
2089                                       data->shift, host->name, data->name);
2090   } /* for (res->variables) */
2091
2092   snmp_free_pdu(res);
2093
2094   DEBUG("snmp plugin: -> plugin_dispatch_values (&vl);");
2095   plugin_dispatch_values(&vl);
2096   sfree(vl.values);
2097
2098   return 0;
2099 } /* int csnmp_read_value */
2100
2101 static int csnmp_read_host(user_data_t *ud) {
2102   host_definition_t *host;
2103   int status;
2104   int success;
2105   int i;
2106
2107   host = ud->data;
2108
2109   if (host->sess_handle == NULL)
2110     csnmp_host_open_session(host);
2111
2112   if (host->sess_handle == NULL)
2113     return -1;
2114
2115   success = 0;
2116   for (i = 0; i < host->data_list_len; i++) {
2117     data_definition_t *data = host->data_list[i];
2118
2119     if (data->is_table)
2120       status = csnmp_read_table(host, data);
2121     else
2122       status = csnmp_read_value(host, data);
2123
2124     if (status == 0)
2125       success++;
2126   }
2127
2128   if (success == 0)
2129     return -1;
2130
2131   return 0;
2132 } /* int csnmp_read_host */
2133
2134 static int csnmp_init(void) {
2135   call_snmp_init_once();
2136
2137   return 0;
2138 } /* int csnmp_init */
2139
2140 static int csnmp_shutdown(void) {
2141   data_definition_t *data_this;
2142   data_definition_t *data_next;
2143
2144   /* When we get here, the read threads have been stopped and all the
2145    * `host_definition_t' will be freed. */
2146   DEBUG("snmp plugin: Destroying all data definitions.");
2147
2148   data_this = data_head;
2149   data_head = NULL;
2150   while (data_this != NULL) {
2151     data_next = data_this->next;
2152
2153     csnmp_data_definition_destroy(data_this);
2154
2155     data_this = data_next;
2156   }
2157
2158   return 0;
2159 } /* int csnmp_shutdown */
2160
2161 void module_register(void) {
2162   plugin_register_complex_config("snmp", csnmp_config);
2163   plugin_register_init("snmp", csnmp_init);
2164   plugin_register_shutdown("snmp", csnmp_shutdown);
2165 } /* void module_register */