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