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