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