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