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