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