Add timeout and retry config options for SNMP plugin
[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   int 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_timeout(host_definition_t *hd,
455                                          oconfig_item_t *ci) {
456   int timeout;
457
458   if (ci->values[0].type != OCONFIG_TYPE_NUMBER) {
459     WARNING("snmp plugin: `Timeout' must be a number");
460     return -1;
461   }
462
463   timeout = (int)ci->values[0].value.number;
464   if (timeout < 0) {
465     WARNING("snmp plugin: `Timeout' must not be negative");
466     return -1;
467   }
468
469   /* net-snmp library timeout is in microseconds */
470   hd->timeout = timeout * 1000000;
471
472   return 0;
473 } /* int csnmp_config_add_host_timeout */
474
475 static int csnmp_config_add_host_retries(host_definition_t *hd,
476                                          oconfig_item_t *ci) {
477   int retries;
478
479
480   if (ci->values[0].type != OCONFIG_TYPE_NUMBER) {
481     WARNING("snmp plugin: `Retries' must be a number");
482     return -1;
483   }
484
485   retries = (int)ci->values[0].value.number;
486   if (retries < 0) {
487     WARNING("snmp plugin: `Retries' must not be negative");
488     return -1;
489   }
490
491   hd->retries = retries;
492
493   return 0;
494 } /* int csnmp_config_add_host_retries */
495
496 static int csnmp_config_add_host_collect(host_definition_t *host,
497                                          oconfig_item_t *ci) {
498   data_definition_t *data;
499   data_definition_t **data_list;
500   int data_list_len;
501
502   if (ci->values_num < 1) {
503     WARNING("snmp plugin: `Collect' needs at least one argument.");
504     return -1;
505   }
506
507   for (int i = 0; i < ci->values_num; i++)
508     if (ci->values[i].type != OCONFIG_TYPE_STRING) {
509       WARNING("snmp plugin: All arguments to `Collect' must be strings.");
510       return -1;
511     }
512
513   data_list_len = host->data_list_len + ci->values_num;
514   data_list =
515       realloc(host->data_list, sizeof(data_definition_t *) * data_list_len);
516   if (data_list == NULL)
517     return -1;
518   host->data_list = data_list;
519
520   for (int i = 0; i < ci->values_num; i++) {
521     for (data = data_head; data != NULL; data = data->next)
522       if (strcasecmp(ci->values[i].value.string, data->name) == 0)
523         break;
524
525     if (data == NULL) {
526       WARNING("snmp plugin: No such data configured: `%s'",
527               ci->values[i].value.string);
528       continue;
529     }
530
531     DEBUG("snmp plugin: Collect: host = %s, data[%i] = %s;", host->name,
532           host->data_list_len, data->name);
533
534     host->data_list[host->data_list_len] = data;
535     host->data_list_len++;
536   } /* for (values_num) */
537
538   return 0;
539 } /* int csnmp_config_add_host_collect */
540
541 static int csnmp_config_add_host_auth_protocol(host_definition_t *hd,
542                                                oconfig_item_t *ci) {
543   char buffer[4];
544   int status;
545
546   status = cf_util_get_string_buffer(ci, buffer, sizeof(buffer));
547   if (status != 0)
548     return status;
549
550   if (strcasecmp("MD5", buffer) == 0) {
551     hd->auth_protocol = usmHMACMD5AuthProtocol;
552     hd->auth_protocol_len = sizeof(usmHMACMD5AuthProtocol) / sizeof(oid);
553   } else if (strcasecmp("SHA", buffer) == 0) {
554     hd->auth_protocol = usmHMACSHA1AuthProtocol;
555     hd->auth_protocol_len = sizeof(usmHMACSHA1AuthProtocol) / sizeof(oid);
556   } else {
557     WARNING("snmp plugin: The `AuthProtocol' config option must be `MD5' or "
558             "`SHA'.");
559     return -1;
560   }
561
562   DEBUG("snmp plugin: host = %s; host->auth_protocol = %s;", hd->name,
563         hd->auth_protocol == usmHMACMD5AuthProtocol ? "MD5" : "SHA");
564
565   return 0;
566 } /* int csnmp_config_add_host_auth_protocol */
567
568 static int csnmp_config_add_host_priv_protocol(host_definition_t *hd,
569                                                oconfig_item_t *ci) {
570   char buffer[4];
571   int status;
572
573   status = cf_util_get_string_buffer(ci, buffer, sizeof(buffer));
574   if (status != 0)
575     return status;
576
577   if (strcasecmp("AES", buffer) == 0) {
578     hd->priv_protocol = usmAESPrivProtocol;
579     hd->priv_protocol_len = sizeof(usmAESPrivProtocol) / sizeof(oid);
580   } else if (strcasecmp("DES", buffer) == 0) {
581     hd->priv_protocol = usmDESPrivProtocol;
582     hd->priv_protocol_len = sizeof(usmDESPrivProtocol) / sizeof(oid);
583   } else {
584     WARNING("snmp plugin: The `PrivProtocol' config option must be `AES' or "
585             "`DES'.");
586     return -1;
587   }
588
589   DEBUG("snmp plugin: host = %s; host->priv_protocol = %s;", hd->name,
590         hd->priv_protocol == usmAESPrivProtocol ? "AES" : "DES");
591
592   return 0;
593 } /* int csnmp_config_add_host_priv_protocol */
594
595 static int csnmp_config_add_host_security_level(host_definition_t *hd,
596                                                 oconfig_item_t *ci) {
597   char buffer[16];
598   int status;
599
600   status = cf_util_get_string_buffer(ci, buffer, sizeof(buffer));
601   if (status != 0)
602     return status;
603
604   if (strcasecmp("noAuthNoPriv", buffer) == 0)
605     hd->security_level = SNMP_SEC_LEVEL_NOAUTH;
606   else if (strcasecmp("authNoPriv", buffer) == 0)
607     hd->security_level = SNMP_SEC_LEVEL_AUTHNOPRIV;
608   else if (strcasecmp("authPriv", buffer) == 0)
609     hd->security_level = SNMP_SEC_LEVEL_AUTHPRIV;
610   else {
611     WARNING("snmp plugin: The `SecurityLevel' config option must be "
612             "`noAuthNoPriv', `authNoPriv', or `authPriv'.");
613     return -1;
614   }
615
616   DEBUG("snmp plugin: host = %s; host->security_level = %d;", hd->name,
617         hd->security_level);
618
619   return 0;
620 } /* int csnmp_config_add_host_security_level */
621
622 static int csnmp_config_add_host(oconfig_item_t *ci) {
623   host_definition_t *hd;
624   int status = 0;
625
626   /* Registration stuff. */
627   char cb_name[DATA_MAX_NAME_LEN];
628
629   hd = calloc(1, sizeof(*hd));
630   if (hd == NULL)
631     return -1;
632   hd->version = 2;
633   C_COMPLAIN_INIT(&hd->complaint);
634
635   status = cf_util_get_string(ci, &hd->name);
636   if (status != 0) {
637     sfree(hd);
638     return status;
639   }
640
641   hd->sess_handle = NULL;
642   hd->interval = 0;
643
644   for (int i = 0; i < ci->children_num; i++) {
645     oconfig_item_t *option = ci->children + i;
646     status = 0;
647
648     if (strcasecmp("Address", option->key) == 0)
649       status = cf_util_get_string(option, &hd->address);
650     else if (strcasecmp("Community", option->key) == 0)
651       status = cf_util_get_string(option, &hd->community);
652     else if (strcasecmp("Version", option->key) == 0)
653       status = csnmp_config_add_host_version(hd, option);
654     else if (strcasecmp("Timeout", option->key) == 0)
655       status = csnmp_config_add_host_timeout(hd, option);
656     else if (strcasecmp("Retries", option->key) == 0)
657       status = csnmp_config_add_host_retries(hd, option);
658     else if (strcasecmp("Collect", option->key) == 0)
659       csnmp_config_add_host_collect(hd, option);
660     else if (strcasecmp("Interval", option->key) == 0)
661       cf_util_get_cdtime(option, &hd->interval);
662     else if (strcasecmp("Username", option->key) == 0)
663       status = cf_util_get_string(option, &hd->username);
664     else if (strcasecmp("AuthProtocol", option->key) == 0)
665       status = csnmp_config_add_host_auth_protocol(hd, option);
666     else if (strcasecmp("PrivacyProtocol", option->key) == 0)
667       status = csnmp_config_add_host_priv_protocol(hd, option);
668     else if (strcasecmp("AuthPassphrase", option->key) == 0)
669       status = cf_util_get_string(option, &hd->auth_passphrase);
670     else if (strcasecmp("PrivacyPassphrase", option->key) == 0)
671       status = cf_util_get_string(option, &hd->priv_passphrase);
672     else if (strcasecmp("SecurityLevel", option->key) == 0)
673       status = csnmp_config_add_host_security_level(hd, option);
674     else if (strcasecmp("Context", option->key) == 0)
675       status = cf_util_get_string(option, &hd->context);
676     else {
677       WARNING(
678           "snmp plugin: csnmp_config_add_host: Option `%s' not allowed here.",
679           option->key);
680       status = -1;
681     }
682
683     if (status != 0)
684       break;
685   } /* for (ci->children) */
686
687   while (status == 0) {
688     if (hd->address == NULL) {
689       WARNING("snmp plugin: `Address' not given for host `%s'", hd->name);
690       status = -1;
691       break;
692     }
693     if (hd->community == NULL && hd->version < 3) {
694       WARNING("snmp plugin: `Community' not given for host `%s'", hd->name);
695       status = -1;
696       break;
697     }
698     if (hd->version == 3) {
699       if (hd->username == NULL) {
700         WARNING("snmp plugin: `Username' not given for host `%s'", hd->name);
701         status = -1;
702         break;
703       }
704       if (hd->security_level == 0) {
705         WARNING("snmp plugin: `SecurityLevel' not given for host `%s'",
706                 hd->name);
707         status = -1;
708         break;
709       }
710       if (hd->security_level == SNMP_SEC_LEVEL_AUTHNOPRIV ||
711           hd->security_level == SNMP_SEC_LEVEL_AUTHPRIV) {
712         if (hd->auth_protocol == NULL) {
713           WARNING("snmp plugin: `AuthProtocol' not given for host `%s'",
714                   hd->name);
715           status = -1;
716           break;
717         }
718         if (hd->auth_passphrase == NULL) {
719           WARNING("snmp plugin: `AuthPassphrase' not given for host `%s'",
720                   hd->name);
721           status = -1;
722           break;
723         }
724       }
725       if (hd->security_level == SNMP_SEC_LEVEL_AUTHPRIV) {
726         if (hd->priv_protocol == NULL) {
727           WARNING("snmp plugin: `PrivacyProtocol' not given for host `%s'",
728                   hd->name);
729           status = -1;
730           break;
731         }
732         if (hd->priv_passphrase == NULL) {
733           WARNING("snmp plugin: `PrivacyPassphrase' not given for host `%s'",
734                   hd->name);
735           status = -1;
736           break;
737         }
738       }
739     }
740
741     break;
742   } /* while (status == 0) */
743
744   if (status != 0) {
745     csnmp_host_definition_destroy(hd);
746     return -1;
747   }
748
749   DEBUG("snmp plugin: hd = { name = %s, address = %s, community = %s, version "
750         "= %i }",
751         hd->name, hd->address, hd->community, hd->version);
752
753   snprintf(cb_name, sizeof(cb_name), "snmp-%s", hd->name);
754
755   status = plugin_register_complex_read(
756       /* group = */ NULL, cb_name, csnmp_read_host, hd->interval,
757       &(user_data_t){
758           .data = hd, .free_func = csnmp_host_definition_destroy,
759       });
760   if (status != 0) {
761     ERROR("snmp plugin: Registering complex read function failed.");
762     return -1;
763   }
764
765   return 0;
766 } /* int csnmp_config_add_host */
767
768 static int csnmp_config(oconfig_item_t *ci) {
769   call_snmp_init_once();
770
771   for (int i = 0; i < ci->children_num; i++) {
772     oconfig_item_t *child = ci->children + i;
773     if (strcasecmp("Data", child->key) == 0)
774       csnmp_config_add_data(child);
775     else if (strcasecmp("Host", child->key) == 0)
776       csnmp_config_add_host(child);
777     else {
778       WARNING("snmp plugin: Ignoring unknown config option `%s'.", child->key);
779     }
780   } /* for (ci->children) */
781
782   return 0;
783 } /* int csnmp_config */
784
785 /* }}} End of the config stuff. Now the interesting part begins */
786
787 static void csnmp_host_open_session(host_definition_t *host) {
788   struct snmp_session sess;
789   int error;
790
791   if (host->sess_handle != NULL)
792     csnmp_host_close_session(host);
793
794   snmp_sess_init(&sess);
795   sess.peername = host->address;
796   switch (host->version) {
797   case 1:
798     sess.version = SNMP_VERSION_1;
799     break;
800   case 3:
801     sess.version = SNMP_VERSION_3;
802     break;
803   default:
804     sess.version = SNMP_VERSION_2c;
805     break;
806   }
807
808   if (host->version == 3) {
809     sess.securityName = host->username;
810     sess.securityNameLen = strlen(host->username);
811     sess.securityLevel = host->security_level;
812
813     if (sess.securityLevel == SNMP_SEC_LEVEL_AUTHNOPRIV ||
814         sess.securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) {
815       sess.securityAuthProto = host->auth_protocol;
816       sess.securityAuthProtoLen = host->auth_protocol_len;
817       sess.securityAuthKeyLen = USM_AUTH_KU_LEN;
818       error = generate_Ku(sess.securityAuthProto, sess.securityAuthProtoLen,
819                           (u_char *)host->auth_passphrase,
820                           strlen(host->auth_passphrase), sess.securityAuthKey,
821                           &sess.securityAuthKeyLen);
822       if (error != SNMPERR_SUCCESS) {
823         ERROR("snmp plugin: host %s: Error generating Ku from auth_passphrase. "
824               "(Error %d)",
825               host->name, error);
826       }
827     }
828
829     if (sess.securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) {
830       sess.securityPrivProto = host->priv_protocol;
831       sess.securityPrivProtoLen = host->priv_protocol_len;
832       sess.securityPrivKeyLen = USM_PRIV_KU_LEN;
833       error = generate_Ku(sess.securityAuthProto, sess.securityAuthProtoLen,
834                           (u_char *)host->priv_passphrase,
835                           strlen(host->priv_passphrase), sess.securityPrivKey,
836                           &sess.securityPrivKeyLen);
837       if (error != SNMPERR_SUCCESS) {
838         ERROR("snmp plugin: host %s: Error generating Ku from priv_passphrase. "
839               "(Error %d)",
840               host->name, error);
841       }
842     }
843
844     if (host->context != NULL) {
845       sess.contextName = host->context;
846       sess.contextNameLen = strlen(host->context);
847     }
848   } else /* SNMPv1/2 "authenticates" with community string */
849   {
850     sess.community = (u_char *)host->community;
851     sess.community_len = strlen(host->community);
852   }
853
854   /* Set timeout & retries */
855   sess.timeout = host->timeout;
856   sess.retries = host->retries;
857
858   /* snmp_sess_open will copy the `struct snmp_session *'. */
859   host->sess_handle = snmp_sess_open(&sess);
860
861   if (host->sess_handle == NULL) {
862     char *errstr = NULL;
863
864     snmp_error(&sess, NULL, NULL, &errstr);
865
866     ERROR("snmp plugin: host %s: snmp_sess_open failed: %s", host->name,
867           (errstr == NULL) ? "Unknown problem" : errstr);
868     sfree(errstr);
869   }
870 } /* void csnmp_host_open_session */
871
872 /* TODO: Check if negative values wrap around. Problem: negative temperatures.
873  */
874 static value_t csnmp_value_list_to_value(struct variable_list *vl, int type,
875                                          double scale, double shift,
876                                          const char *host_name,
877                                          const char *data_name) {
878   value_t ret;
879   uint64_t tmp_unsigned = 0;
880   int64_t tmp_signed = 0;
881   _Bool defined = 1;
882   /* Set to true when the original SNMP type appears to have been signed. */
883   _Bool prefer_signed = 0;
884
885   if ((vl->type == ASN_INTEGER) || (vl->type == ASN_UINTEGER) ||
886       (vl->type == ASN_COUNTER)
887 #ifdef ASN_TIMETICKS
888       || (vl->type == ASN_TIMETICKS)
889 #endif
890       || (vl->type == ASN_GAUGE)) {
891     tmp_unsigned = (uint32_t)*vl->val.integer;
892     tmp_signed = (int32_t)*vl->val.integer;
893
894     if (vl->type == ASN_INTEGER)
895       prefer_signed = 1;
896
897     DEBUG("snmp plugin: Parsed int32 value is %" PRIu64 ".", tmp_unsigned);
898   } else if (vl->type == ASN_COUNTER64) {
899     tmp_unsigned = (uint32_t)vl->val.counter64->high;
900     tmp_unsigned = tmp_unsigned << 32;
901     tmp_unsigned += (uint32_t)vl->val.counter64->low;
902     tmp_signed = (int64_t)tmp_unsigned;
903     DEBUG("snmp plugin: Parsed int64 value is %" PRIu64 ".", tmp_unsigned);
904   } else if (vl->type == ASN_OCTET_STR) {
905     /* We'll handle this later.. */
906   } else {
907     char oid_buffer[1024] = {0};
908
909     snprint_objid(oid_buffer, sizeof(oid_buffer) - 1, vl->name,
910                   vl->name_length);
911
912 #ifdef ASN_NULL
913     if (vl->type == ASN_NULL)
914       INFO("snmp plugin: OID \"%s\" is undefined (type ASN_NULL)", oid_buffer);
915     else
916 #endif
917       WARNING("snmp plugin: I don't know the ASN type #%i "
918               "(OID: \"%s\", data block \"%s\", host block \"%s\")",
919               (int)vl->type, oid_buffer,
920               (data_name != NULL) ? data_name : "UNKNOWN",
921               (host_name != NULL) ? host_name : "UNKNOWN");
922
923     defined = 0;
924   }
925
926   if (vl->type == ASN_OCTET_STR) {
927     int status = -1;
928
929     if (vl->val.string != NULL) {
930       char string[64];
931       size_t string_length;
932
933       string_length = sizeof(string) - 1;
934       if (vl->val_len < string_length)
935         string_length = vl->val_len;
936
937       /* The strings we get from the Net-SNMP library may not be null
938        * terminated. That is why we're using `memcpy' here and not `strcpy'.
939        * `string_length' is set to `vl->val_len' which holds the length of the
940        * string.  -octo */
941       memcpy(string, vl->val.string, string_length);
942       string[string_length] = 0;
943
944       status = parse_value(string, &ret, type);
945       if (status != 0) {
946         ERROR("snmp plugin: host %s: csnmp_value_list_to_value: Parsing string "
947               "as %s failed: %s",
948               (host_name != NULL) ? host_name : "UNKNOWN",
949               DS_TYPE_TO_STRING(type), string);
950       }
951     }
952
953     if (status != 0) {
954       switch (type) {
955       case DS_TYPE_COUNTER:
956       case DS_TYPE_DERIVE:
957       case DS_TYPE_ABSOLUTE:
958         memset(&ret, 0, sizeof(ret));
959         break;
960
961       case DS_TYPE_GAUGE:
962         ret.gauge = NAN;
963         break;
964
965       default:
966         ERROR("snmp plugin: csnmp_value_list_to_value: Unknown "
967               "data source type: %i.",
968               type);
969         ret.gauge = NAN;
970       }
971     }
972   } /* if (vl->type == ASN_OCTET_STR) */
973   else if (type == DS_TYPE_COUNTER) {
974     ret.counter = tmp_unsigned;
975   } else if (type == DS_TYPE_GAUGE) {
976     if (!defined)
977       ret.gauge = NAN;
978     else if (prefer_signed)
979       ret.gauge = (scale * tmp_signed) + shift;
980     else
981       ret.gauge = (scale * tmp_unsigned) + shift;
982   } else if (type == DS_TYPE_DERIVE) {
983     if (prefer_signed)
984       ret.derive = (derive_t)tmp_signed;
985     else
986       ret.derive = (derive_t)tmp_unsigned;
987   } else if (type == DS_TYPE_ABSOLUTE) {
988     ret.absolute = (absolute_t)tmp_unsigned;
989   } else {
990     ERROR("snmp plugin: csnmp_value_list_to_value: Unknown data source "
991           "type: %i.",
992           type);
993     ret.gauge = NAN;
994   }
995
996   return ret;
997 } /* value_t csnmp_value_list_to_value */
998
999 /* csnmp_strvbcopy_hexstring converts the bit string contained in "vb" to a hex
1000  * representation and writes it to dst. Returns zero on success and ENOMEM if
1001  * dst is not large enough to hold the string. dst is guaranteed to be
1002  * nul-terminated. */
1003 static int csnmp_strvbcopy_hexstring(char *dst, /* {{{ */
1004                                      const struct variable_list *vb,
1005                                      size_t dst_size) {
1006   char *buffer_ptr;
1007   size_t buffer_free;
1008
1009   dst[0] = 0;
1010
1011   buffer_ptr = dst;
1012   buffer_free = dst_size;
1013
1014   for (size_t i = 0; i < vb->val_len; i++) {
1015     int status;
1016
1017     status = snprintf(buffer_ptr, buffer_free, (i == 0) ? "%02x" : ":%02x",
1018                       (unsigned int)vb->val.bitstring[i]);
1019     assert(status >= 0);
1020
1021     if (((size_t)status) >= buffer_free) /* truncated */
1022     {
1023       dst[dst_size - 1] = 0;
1024       return ENOMEM;
1025     } else /* if (status < buffer_free) */
1026     {
1027       buffer_ptr += (size_t)status;
1028       buffer_free -= (size_t)status;
1029     }
1030   }
1031
1032   return 0;
1033 } /* }}} int csnmp_strvbcopy_hexstring */
1034
1035 /* csnmp_strvbcopy copies the octet string or bit string contained in vb to
1036  * dst. If non-printable characters are detected, it will switch to a hex
1037  * representation of the string. Returns zero on success, EINVAL if vb does not
1038  * contain a string and ENOMEM if dst is not large enough to contain the
1039  * string. */
1040 static int csnmp_strvbcopy(char *dst, /* {{{ */
1041                            const struct variable_list *vb, size_t dst_size) {
1042   char *src;
1043   size_t num_chars;
1044
1045   if (vb->type == ASN_OCTET_STR)
1046     src = (char *)vb->val.string;
1047   else if (vb->type == ASN_BIT_STR)
1048     src = (char *)vb->val.bitstring;
1049   else if (vb->type == ASN_IPADDRESS) {
1050     return snprintf(dst, dst_size,
1051                     "%" PRIu8 ".%" PRIu8 ".%" PRIu8 ".%" PRIu8 "",
1052                     (uint8_t)vb->val.string[0], (uint8_t)vb->val.string[1],
1053                     (uint8_t)vb->val.string[2], (uint8_t)vb->val.string[3]);
1054   } else {
1055     dst[0] = 0;
1056     return EINVAL;
1057   }
1058
1059   num_chars = dst_size - 1;
1060   if (num_chars > vb->val_len)
1061     num_chars = vb->val_len;
1062
1063   for (size_t i = 0; i < num_chars; i++) {
1064     /* Check for control characters. */
1065     if ((unsigned char)src[i] < 32)
1066       return csnmp_strvbcopy_hexstring(dst, vb, dst_size);
1067     dst[i] = src[i];
1068   }
1069   dst[num_chars] = 0;
1070   dst[dst_size - 1] = 0;
1071
1072   if (dst_size <= vb->val_len)
1073     return ENOMEM;
1074
1075   return 0;
1076 } /* }}} int csnmp_strvbcopy */
1077
1078 static int csnmp_instance_list_add(csnmp_list_instances_t **head,
1079                                    csnmp_list_instances_t **tail,
1080                                    const struct snmp_pdu *res,
1081                                    const host_definition_t *hd,
1082                                    const data_definition_t *dd) {
1083   csnmp_list_instances_t *il;
1084   struct variable_list *vb;
1085   oid_t vb_name;
1086   int status;
1087   uint32_t is_matched;
1088
1089   /* Set vb on the last variable */
1090   for (vb = res->variables; (vb != NULL) && (vb->next_variable != NULL);
1091        vb = vb->next_variable)
1092     /* do nothing */;
1093   if (vb == NULL)
1094     return -1;
1095
1096   csnmp_oid_init(&vb_name, vb->name, vb->name_length);
1097
1098   il = calloc(1, sizeof(*il));
1099   if (il == NULL) {
1100     ERROR("snmp plugin: calloc failed.");
1101     return -1;
1102   }
1103   il->next = NULL;
1104
1105   status = csnmp_oid_suffix(&il->suffix, &vb_name, &dd->instance.oid);
1106   if (status != 0) {
1107     sfree(il);
1108     return status;
1109   }
1110
1111   /* Get instance name */
1112   if ((vb->type == ASN_OCTET_STR) || (vb->type == ASN_BIT_STR) ||
1113       (vb->type == ASN_IPADDRESS)) {
1114     char *ptr;
1115
1116     csnmp_strvbcopy(il->instance, vb, sizeof(il->instance));
1117     is_matched = 0;
1118     for (uint32_t i = 0; i < dd->ignores_len; i++) {
1119       status = fnmatch(dd->ignores[i], il->instance, 0);
1120       if (status == 0) {
1121         if (dd->invert_match == 0) {
1122           sfree(il);
1123           return 0;
1124         } else {
1125           is_matched = 1;
1126           break;
1127         }
1128       }
1129     }
1130     if (dd->invert_match != 0 && is_matched == 0) {
1131       sfree(il);
1132       return 0;
1133     }
1134     for (ptr = il->instance; *ptr != '\0'; ptr++) {
1135       if ((*ptr > 0) && (*ptr < 32))
1136         *ptr = ' ';
1137       else if (*ptr == '/')
1138         *ptr = '_';
1139     }
1140     DEBUG("snmp plugin: il->instance = `%s';", il->instance);
1141   } else {
1142     value_t val = csnmp_value_list_to_value(
1143         vb, DS_TYPE_COUNTER,
1144         /* scale = */ 1.0, /* shift = */ 0.0, hd->name, dd->name);
1145     snprintf(il->instance, sizeof(il->instance), "%llu", val.counter);
1146   }
1147
1148   /* TODO: Debugging output */
1149
1150   if (*head == NULL)
1151     *head = il;
1152   else
1153     (*tail)->next = il;
1154   *tail = il;
1155
1156   return 0;
1157 } /* int csnmp_instance_list_add */
1158
1159 static int csnmp_dispatch_table(host_definition_t *host,
1160                                 data_definition_t *data,
1161                                 csnmp_list_instances_t *instance_list,
1162                                 csnmp_table_values_t **value_table) {
1163   const data_set_t *ds;
1164   value_list_t vl = VALUE_LIST_INIT;
1165
1166   csnmp_list_instances_t *instance_list_ptr;
1167   csnmp_table_values_t *value_table_ptr[data->values_len];
1168
1169   size_t i;
1170   _Bool have_more;
1171   oid_t current_suffix;
1172
1173   ds = plugin_get_ds(data->type);
1174   if (!ds) {
1175     ERROR("snmp plugin: DataSet `%s' not defined.", data->type);
1176     return -1;
1177   }
1178   assert(ds->ds_num == data->values_len);
1179   assert(data->values_len > 0);
1180
1181   instance_list_ptr = instance_list;
1182
1183   for (i = 0; i < data->values_len; i++)
1184     value_table_ptr[i] = value_table[i];
1185
1186   sstrncpy(vl.host, host->name, sizeof(vl.host));
1187   sstrncpy(vl.plugin, "snmp", sizeof(vl.plugin));
1188
1189   vl.interval = host->interval;
1190
1191   have_more = 1;
1192   while (have_more) {
1193     _Bool suffix_skipped = 0;
1194
1195     /* Determine next suffix to handle. */
1196     if (instance_list != NULL) {
1197       if (instance_list_ptr == NULL) {
1198         have_more = 0;
1199         continue;
1200       }
1201
1202       memcpy(&current_suffix, &instance_list_ptr->suffix,
1203              sizeof(current_suffix));
1204     } else {
1205       /* no instance configured */
1206       csnmp_table_values_t *ptr = value_table_ptr[0];
1207       if (ptr == NULL) {
1208         have_more = 0;
1209         continue;
1210       }
1211
1212       memcpy(&current_suffix, &ptr->suffix, sizeof(current_suffix));
1213     }
1214
1215     /* Update all the value_table_ptr to point at the entry with the same
1216      * trailing partial OID */
1217     for (i = 0; i < data->values_len; i++) {
1218       while (
1219           (value_table_ptr[i] != NULL) &&
1220           (csnmp_oid_compare(&value_table_ptr[i]->suffix, &current_suffix) < 0))
1221         value_table_ptr[i] = value_table_ptr[i]->next;
1222
1223       if (value_table_ptr[i] == NULL) {
1224         have_more = 0;
1225         break;
1226       } else if (csnmp_oid_compare(&value_table_ptr[i]->suffix,
1227                                    &current_suffix) > 0) {
1228         /* This suffix is missing in the subtree. Indicate this with the
1229          * "suffix_skipped" flag and try the next instance / suffix. */
1230         suffix_skipped = 1;
1231         break;
1232       }
1233     } /* for (i = 0; i < columns; i++) */
1234
1235     if (!have_more)
1236       break;
1237
1238     /* Matching the values failed. Start from the beginning again. */
1239     if (suffix_skipped) {
1240       if (instance_list != NULL)
1241         instance_list_ptr = instance_list_ptr->next;
1242       else
1243         value_table_ptr[0] = value_table_ptr[0]->next;
1244
1245       continue;
1246     }
1247
1248 /* if we reach this line, all value_table_ptr[i] are non-NULL and are set
1249  * to the same subid. instance_list_ptr is either NULL or points to the
1250  * same subid, too. */
1251 #if COLLECT_DEBUG
1252     for (i = 1; i < data->values_len; i++) {
1253       assert(value_table_ptr[i] != NULL);
1254       assert(csnmp_oid_compare(&value_table_ptr[i - 1]->suffix,
1255                                &value_table_ptr[i]->suffix) == 0);
1256     }
1257     assert((instance_list_ptr == NULL) ||
1258            (csnmp_oid_compare(&instance_list_ptr->suffix,
1259                               &value_table_ptr[0]->suffix) == 0));
1260 #endif
1261
1262     sstrncpy(vl.type, data->type, sizeof(vl.type));
1263
1264     {
1265       char temp[DATA_MAX_NAME_LEN];
1266
1267       if (instance_list_ptr == NULL)
1268         csnmp_oid_to_string(temp, sizeof(temp), &current_suffix);
1269       else
1270         sstrncpy(temp, instance_list_ptr->instance, sizeof(temp));
1271
1272       if (data->instance_prefix == NULL)
1273         sstrncpy(vl.type_instance, temp, sizeof(vl.type_instance));
1274       else
1275         snprintf(vl.type_instance, sizeof(vl.type_instance), "%s%s",
1276                  data->instance_prefix, temp);
1277     }
1278
1279     vl.values_len = data->values_len;
1280     value_t values[vl.values_len];
1281     vl.values = values;
1282
1283     for (i = 0; i < data->values_len; i++)
1284       vl.values[i] = value_table_ptr[i]->value;
1285
1286     /* If we get here `vl.type_instance' and all `vl.values' have been set
1287      * vl.type_instance can be empty, i.e. a blank port description on a
1288      * switch if you're using IF-MIB::ifDescr as Instance.
1289      */
1290     if (vl.type_instance[0] != '\0')
1291       plugin_dispatch_values(&vl);
1292
1293     /* prevent leakage of pointer to local variable. */
1294     vl.values_len = 0;
1295     vl.values = NULL;
1296
1297     if (instance_list != NULL)
1298       instance_list_ptr = instance_list_ptr->next;
1299     else
1300       value_table_ptr[0] = value_table_ptr[0]->next;
1301   } /* while (have_more) */
1302
1303   return (0);
1304 } /* int csnmp_dispatch_table */
1305
1306 static int csnmp_read_table(host_definition_t *host, data_definition_t *data) {
1307   struct snmp_pdu *req;
1308   struct snmp_pdu *res = NULL;
1309   struct variable_list *vb;
1310
1311   const data_set_t *ds;
1312
1313   size_t oid_list_len = data->values_len + 1;
1314   /* Holds the last OID returned by the device. We use this in the GETNEXT
1315    * request to proceed. */
1316   oid_t oid_list[oid_list_len];
1317   /* Set to false when an OID has left its subtree so we don't re-request it
1318    * again. */
1319   _Bool oid_list_todo[oid_list_len];
1320
1321   int status;
1322   size_t i;
1323
1324   /* `value_list_head' and `value_list_tail' implement a linked list for each
1325    * value. `instance_list_head' and `instance_list_tail' implement a linked
1326    * list of
1327    * instance names. This is used to jump gaps in the table. */
1328   csnmp_list_instances_t *instance_list_head;
1329   csnmp_list_instances_t *instance_list_tail;
1330   csnmp_table_values_t **value_list_head;
1331   csnmp_table_values_t **value_list_tail;
1332
1333   DEBUG("snmp plugin: csnmp_read_table (host = %s, data = %s)", host->name,
1334         data->name);
1335
1336   if (host->sess_handle == NULL) {
1337     DEBUG("snmp plugin: csnmp_read_table: host->sess_handle == NULL");
1338     return -1;
1339   }
1340
1341   ds = plugin_get_ds(data->type);
1342   if (!ds) {
1343     ERROR("snmp plugin: DataSet `%s' not defined.", data->type);
1344     return -1;
1345   }
1346
1347   if (ds->ds_num != data->values_len) {
1348     ERROR("snmp plugin: DataSet `%s' requires %zu values, but config talks "
1349           "about %zu",
1350           data->type, ds->ds_num, data->values_len);
1351     return -1;
1352   }
1353   assert(data->values_len > 0);
1354
1355   /* We need a copy of all the OIDs, because GETNEXT will destroy them. */
1356   memcpy(oid_list, data->values, data->values_len * sizeof(oid_t));
1357   if (data->instance.oid.oid_len > 0)
1358     memcpy(oid_list + data->values_len, &data->instance.oid, sizeof(oid_t));
1359   else /* no InstanceFrom option specified. */
1360     oid_list_len--;
1361
1362   for (i = 0; i < oid_list_len; i++)
1363     oid_list_todo[i] = 1;
1364
1365   /* We're going to construct n linked lists, one for each "value".
1366    * value_list_head will contain pointers to the heads of these linked lists,
1367    * value_list_tail will contain pointers to the tail of the lists. */
1368   value_list_head = calloc(data->values_len, sizeof(*value_list_head));
1369   value_list_tail = calloc(data->values_len, sizeof(*value_list_tail));
1370   if ((value_list_head == NULL) || (value_list_tail == NULL)) {
1371     ERROR("snmp plugin: csnmp_read_table: calloc failed.");
1372     sfree(value_list_head);
1373     sfree(value_list_tail);
1374     return -1;
1375   }
1376
1377   instance_list_head = NULL;
1378   instance_list_tail = NULL;
1379
1380   status = 0;
1381   while (status == 0) {
1382     req = snmp_pdu_create(SNMP_MSG_GETNEXT);
1383     if (req == NULL) {
1384       ERROR("snmp plugin: snmp_pdu_create failed.");
1385       status = -1;
1386       break;
1387     }
1388
1389     size_t oid_list_todo_num = 0;
1390     size_t var_idx[oid_list_len];
1391     memset(var_idx, 0, sizeof(var_idx));
1392
1393     for (i = 0; i < oid_list_len; i++) {
1394       /* Do not rerequest already finished OIDs */
1395       if (!oid_list_todo[i])
1396         continue;
1397       snmp_add_null_var(req, oid_list[i].oid, oid_list[i].oid_len);
1398       var_idx[oid_list_todo_num] = i;
1399       oid_list_todo_num++;
1400     }
1401
1402     if (oid_list_todo_num == 0) {
1403       /* The request is still empty - so we are finished */
1404       DEBUG("snmp plugin: all variables have left their subtree");
1405       snmp_free_pdu(req);
1406       status = 0;
1407       break;
1408     }
1409
1410     res = NULL;
1411     status = snmp_sess_synch_response(host->sess_handle, req, &res);
1412
1413     /* snmp_sess_synch_response always frees our req PDU */
1414     req = NULL;
1415
1416     if ((status != STAT_SUCCESS) || (res == NULL)) {
1417       char *errstr = NULL;
1418
1419       snmp_sess_error(host->sess_handle, NULL, NULL, &errstr);
1420
1421       c_complain(LOG_ERR, &host->complaint,
1422                  "snmp plugin: host %s: snmp_sess_synch_response failed: %s",
1423                  host->name, (errstr == NULL) ? "Unknown problem" : errstr);
1424
1425       if (res != NULL)
1426         snmp_free_pdu(res);
1427       res = NULL;
1428
1429       sfree(errstr);
1430       csnmp_host_close_session(host);
1431
1432       status = -1;
1433       break;
1434     }
1435
1436     status = 0;
1437     assert(res != NULL);
1438     c_release(LOG_INFO, &host->complaint,
1439               "snmp plugin: host %s: snmp_sess_synch_response successful.",
1440               host->name);
1441
1442     vb = res->variables;
1443     if (vb == NULL) {
1444       status = -1;
1445       break;
1446     }
1447
1448     if (res->errstat != SNMP_ERR_NOERROR) {
1449       if (res->errindex != 0) {
1450         /* Find the OID which caused error */
1451         for (i = 1, vb = res->variables; vb != NULL && i != res->errindex;
1452              vb = vb->next_variable, i++)
1453           /* do nothing */;
1454       }
1455
1456       if ((res->errindex == 0) || (vb == NULL)) {
1457         ERROR("snmp plugin: host %s; data %s: response error: %s (%li) ",
1458               host->name, data->name, snmp_errstring(res->errstat),
1459               res->errstat);
1460         status = -1;
1461         break;
1462       }
1463
1464       char oid_buffer[1024] = {0};
1465       snprint_objid(oid_buffer, sizeof(oid_buffer) - 1, vb->name,
1466                     vb->name_length);
1467       NOTICE("snmp plugin: host %s; data %s: OID `%s` failed: %s", host->name,
1468              data->name, oid_buffer, snmp_errstring(res->errstat));
1469
1470       /* Get value index from todo list and skip OID found */
1471       assert(res->errindex <= oid_list_todo_num);
1472       i = var_idx[res->errindex - 1];
1473       assert(i < oid_list_len);
1474       oid_list_todo[i] = 0;
1475
1476       snmp_free_pdu(res);
1477       res = NULL;
1478       continue;
1479     }
1480
1481     for (vb = res->variables, i = 0; (vb != NULL);
1482          vb = vb->next_variable, i++) {
1483       /* Calculate value index from todo list */
1484       while ((i < oid_list_len) && !oid_list_todo[i])
1485         i++;
1486
1487       /* An instance is configured and the res variable we process is the
1488        * instance value (last index) */
1489       if ((data->instance.oid.oid_len > 0) && (i == data->values_len)) {
1490         if ((vb->type == SNMP_ENDOFMIBVIEW) ||
1491             (snmp_oid_ncompare(
1492                  data->instance.oid.oid, data->instance.oid.oid_len, vb->name,
1493                  vb->name_length, data->instance.oid.oid_len) != 0)) {
1494           DEBUG("snmp plugin: host = %s; data = %s; Instance left its subtree.",
1495                 host->name, data->name);
1496           oid_list_todo[i] = 0;
1497           continue;
1498         }
1499
1500         /* Allocate a new `csnmp_list_instances_t', insert the instance name and
1501          * add it to the list */
1502         if (csnmp_instance_list_add(&instance_list_head, &instance_list_tail,
1503                                     res, host, data) != 0) {
1504           ERROR("snmp plugin: host %s: csnmp_instance_list_add failed.",
1505                 host->name);
1506           status = -1;
1507           break;
1508         }
1509       } else /* The variable we are processing is a normal value */
1510       {
1511         csnmp_table_values_t *vt;
1512         oid_t vb_name;
1513         oid_t suffix;
1514         int ret;
1515
1516         csnmp_oid_init(&vb_name, vb->name, vb->name_length);
1517
1518         /* Calculate the current suffix. This is later used to check that the
1519          * suffix is increasing. This also checks if we left the subtree */
1520         ret = csnmp_oid_suffix(&suffix, &vb_name, data->values + i);
1521         if (ret != 0) {
1522           DEBUG("snmp plugin: host = %s; data = %s; i = %zu; "
1523                 "Value probably left its subtree.",
1524                 host->name, data->name, i);
1525           oid_list_todo[i] = 0;
1526           continue;
1527         }
1528
1529         /* Make sure the OIDs returned by the agent are increasing. Otherwise
1530          * our
1531          * table matching algorithm will get confused. */
1532         if ((value_list_tail[i] != NULL) &&
1533             (csnmp_oid_compare(&suffix, &value_list_tail[i]->suffix) <= 0)) {
1534           DEBUG("snmp plugin: host = %s; data = %s; i = %zu; "
1535                 "Suffix is not increasing.",
1536                 host->name, data->name, i);
1537           oid_list_todo[i] = 0;
1538           continue;
1539         }
1540
1541         vt = calloc(1, sizeof(*vt));
1542         if (vt == NULL) {
1543           ERROR("snmp plugin: calloc failed.");
1544           status = -1;
1545           break;
1546         }
1547
1548         vt->value =
1549             csnmp_value_list_to_value(vb, ds->ds[i].type, data->scale,
1550                                       data->shift, host->name, data->name);
1551         memcpy(&vt->suffix, &suffix, sizeof(vt->suffix));
1552         vt->next = NULL;
1553
1554         if (value_list_tail[i] == NULL)
1555           value_list_head[i] = vt;
1556         else
1557           value_list_tail[i]->next = vt;
1558         value_list_tail[i] = vt;
1559       }
1560
1561       /* Copy OID to oid_list[i] */
1562       memcpy(oid_list[i].oid, vb->name, sizeof(oid) * vb->name_length);
1563       oid_list[i].oid_len = vb->name_length;
1564
1565     } /* for (vb = res->variables ...) */
1566
1567     if (res != NULL)
1568       snmp_free_pdu(res);
1569     res = NULL;
1570   } /* while (status == 0) */
1571
1572   if (res != NULL)
1573     snmp_free_pdu(res);
1574   res = NULL;
1575
1576
1577   if (status == 0)
1578     csnmp_dispatch_table(host, data, instance_list_head, value_list_head);
1579
1580   /* Free all allocated variables here */
1581   while (instance_list_head != NULL) {
1582     csnmp_list_instances_t *next = instance_list_head->next;
1583     sfree(instance_list_head);
1584     instance_list_head = next;
1585   }
1586
1587   for (i = 0; i < data->values_len; i++) {
1588     while (value_list_head[i] != NULL) {
1589       csnmp_table_values_t *next = value_list_head[i]->next;
1590       sfree(value_list_head[i]);
1591       value_list_head[i] = next;
1592     }
1593   }
1594
1595   sfree(value_list_head);
1596   sfree(value_list_tail);
1597
1598   return 0;
1599 } /* int csnmp_read_table */
1600
1601 static int csnmp_read_value(host_definition_t *host, data_definition_t *data) {
1602   struct snmp_pdu *req;
1603   struct snmp_pdu *res = NULL;
1604   struct variable_list *vb;
1605
1606   const data_set_t *ds;
1607   value_list_t vl = VALUE_LIST_INIT;
1608
1609   int status;
1610   size_t i;
1611
1612   DEBUG("snmp plugin: csnmp_read_value (host = %s, data = %s)", host->name,
1613         data->name);
1614
1615   if (host->sess_handle == NULL) {
1616     DEBUG("snmp plugin: csnmp_read_value: host->sess_handle == NULL");
1617     return -1;
1618   }
1619
1620   ds = plugin_get_ds(data->type);
1621   if (!ds) {
1622     ERROR("snmp plugin: DataSet `%s' not defined.", data->type);
1623     return -1;
1624   }
1625
1626   if (ds->ds_num != data->values_len) {
1627     ERROR("snmp plugin: DataSet `%s' requires %zu values, but config talks "
1628           "about %zu",
1629           data->type, ds->ds_num, data->values_len);
1630     return -1;
1631   }
1632
1633   vl.values_len = ds->ds_num;
1634   vl.values = malloc(sizeof(*vl.values) * vl.values_len);
1635   if (vl.values == NULL)
1636     return -1;
1637   for (i = 0; i < vl.values_len; i++) {
1638     if (ds->ds[i].type == DS_TYPE_COUNTER)
1639       vl.values[i].counter = 0;
1640     else
1641       vl.values[i].gauge = NAN;
1642   }
1643
1644   sstrncpy(vl.host, host->name, sizeof(vl.host));
1645   sstrncpy(vl.plugin, "snmp", sizeof(vl.plugin));
1646   sstrncpy(vl.type, data->type, sizeof(vl.type));
1647   sstrncpy(vl.type_instance, data->instance.string, sizeof(vl.type_instance));
1648
1649   vl.interval = host->interval;
1650
1651   req = snmp_pdu_create(SNMP_MSG_GET);
1652   if (req == NULL) {
1653     ERROR("snmp plugin: snmp_pdu_create failed.");
1654     sfree(vl.values);
1655     return -1;
1656   }
1657
1658   for (i = 0; i < data->values_len; i++)
1659     snmp_add_null_var(req, data->values[i].oid, data->values[i].oid_len);
1660
1661   status = snmp_sess_synch_response(host->sess_handle, req, &res);
1662
1663   if ((status != STAT_SUCCESS) || (res == NULL)) {
1664     char *errstr = NULL;
1665
1666     snmp_sess_error(host->sess_handle, NULL, NULL, &errstr);
1667     ERROR("snmp plugin: host %s: snmp_sess_synch_response failed: %s",
1668           host->name, (errstr == NULL) ? "Unknown problem" : errstr);
1669
1670     if (res != NULL)
1671       snmp_free_pdu(res);
1672
1673     sfree(errstr);
1674     sfree(vl.values);
1675     csnmp_host_close_session(host);
1676
1677     return -1;
1678   }
1679
1680   for (vb = res->variables; vb != NULL; vb = vb->next_variable) {
1681 #if COLLECT_DEBUG
1682     char buffer[1024];
1683     snprint_variable(buffer, sizeof(buffer), vb->name, vb->name_length, vb);
1684     DEBUG("snmp plugin: Got this variable: %s", buffer);
1685 #endif /* COLLECT_DEBUG */
1686
1687     for (i = 0; i < data->values_len; i++)
1688       if (snmp_oid_compare(data->values[i].oid, data->values[i].oid_len,
1689                            vb->name, vb->name_length) == 0)
1690         vl.values[i] =
1691             csnmp_value_list_to_value(vb, ds->ds[i].type, data->scale,
1692                                       data->shift, host->name, data->name);
1693   } /* for (res->variables) */
1694
1695   snmp_free_pdu(res);
1696
1697   DEBUG("snmp plugin: -> plugin_dispatch_values (&vl);");
1698   plugin_dispatch_values(&vl);
1699   sfree(vl.values);
1700
1701   return 0;
1702 } /* int csnmp_read_value */
1703
1704 static int csnmp_read_host(user_data_t *ud) {
1705   host_definition_t *host;
1706   int status;
1707   int success;
1708   int i;
1709
1710   host = ud->data;
1711
1712   if (host->interval == 0)
1713     host->interval = plugin_get_interval();
1714
1715   if (host->sess_handle == NULL)
1716     csnmp_host_open_session(host);
1717
1718   if (host->sess_handle == NULL)
1719     return -1;
1720
1721   success = 0;
1722   for (i = 0; i < host->data_list_len; i++) {
1723     data_definition_t *data = host->data_list[i];
1724
1725     if (data->is_table)
1726       status = csnmp_read_table(host, data);
1727     else
1728       status = csnmp_read_value(host, data);
1729
1730     if (status == 0)
1731       success++;
1732   }
1733
1734   if (success == 0)
1735     return -1;
1736
1737   return 0;
1738 } /* int csnmp_read_host */
1739
1740 static int csnmp_init(void) {
1741   call_snmp_init_once();
1742
1743   return 0;
1744 } /* int csnmp_init */
1745
1746 static int csnmp_shutdown(void) {
1747   data_definition_t *data_this;
1748   data_definition_t *data_next;
1749
1750   /* When we get here, the read threads have been stopped and all the
1751    * `host_definition_t' will be freed. */
1752   DEBUG("snmp plugin: Destroying all data definitions.");
1753
1754   data_this = data_head;
1755   data_head = NULL;
1756   while (data_this != NULL) {
1757     data_next = data_this->next;
1758
1759     sfree(data_this->name);
1760     sfree(data_this->type);
1761     sfree(data_this->values);
1762     sfree(data_this->ignores);
1763     sfree(data_this);
1764
1765     data_this = data_next;
1766   }
1767
1768   return 0;
1769 } /* int csnmp_shutdown */
1770
1771 void module_register(void) {
1772   plugin_register_complex_config("snmp", csnmp_config);
1773   plugin_register_init("snmp", csnmp_init);
1774   plugin_register_shutdown("snmp", csnmp_shutdown);
1775 } /* void module_register */