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