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