63295da225bdd23b868bb9405fa7833371171039
[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       }
1278     }
1279
1280     /* Update all the value_cell_ptr to point at the entry with the same
1281      * trailing partial OID */
1282     for (i = 0; i < data->values_len; i++) {
1283       while (
1284           (value_cell_ptr[i] != NULL) &&
1285           (csnmp_oid_compare(&value_cell_ptr[i]->suffix, &current_suffix) < 0))
1286         value_cell_ptr[i] = value_cell_ptr[i]->next;
1287
1288       if (value_cell_ptr[i] == NULL) {
1289         have_more = 0;
1290         break;
1291       } else if (csnmp_oid_compare(&value_cell_ptr[i]->suffix,
1292                                    &current_suffix) > 0) {
1293         /* This suffix is missing in the subtree. Indicate this with the
1294          * "suffix_skipped" flag and try the next instance / suffix. */
1295         suffix_skipped = 1;
1296         break;
1297       }
1298     } /* for (i = 0; i < columns; i++) */
1299
1300     if (!have_more)
1301       break;
1302
1303     /* Matching the values failed. Start from the beginning again. */
1304     if (suffix_skipped) {
1305       if (instance_cells != NULL)
1306         instance_cell_ptr = instance_cell_ptr->next;
1307       else
1308         value_cell_ptr[0] = value_cell_ptr[0]->next;
1309
1310       continue;
1311     }
1312
1313 /* if we reach this line, all value_cell_ptr[i] are non-NULL and are set
1314  * to the same subid. instance_cell_ptr is either NULL or points to the
1315  * same subid, too. */
1316 #if COLLECT_DEBUG
1317     for (i = 1; i < data->values_len; i++) {
1318       assert(value_cell_ptr[i] != NULL);
1319       assert(csnmp_oid_compare(&value_cell_ptr[i - 1]->suffix,
1320                                &value_cell_ptr[i]->suffix) == 0);
1321     }
1322     assert((instance_cell_ptr == NULL) ||
1323            (csnmp_oid_compare(&instance_cell_ptr->suffix,
1324                               &value_cell_ptr[0]->suffix) == 0));
1325     assert((hostname_cell_ptr == NULL) ||
1326            (csnmp_oid_compare(&hostname_cell_ptr->suffix,
1327                               &value_cell_ptr[0]->suffix) == 0));
1328 #endif
1329
1330     sstrncpy(vl.type, data->type, sizeof(vl.type));
1331
1332     if (hostname_cell_ptr) {
1333       sstrncpy(vl.host, hostname_cell_ptr->value, sizeof(vl.host));
1334     } else {
1335       sstrncpy(vl.host, host->name, sizeof(vl.host));
1336     }
1337
1338     {
1339       char temp[DATA_MAX_NAME_LEN];
1340
1341       if (instance_cell_ptr == NULL)
1342         csnmp_oid_to_string(temp, sizeof(temp), &current_suffix);
1343       else
1344         sstrncpy(temp, instance_cell_ptr->value, sizeof(temp));
1345
1346       if (data->instance.is_plugin) {
1347         if (data->instance_prefix == NULL)
1348           sstrncpy(vl.plugin_instance, temp, sizeof(vl.plugin_instance));
1349         else
1350           snprintf(vl.plugin_instance, sizeof(vl.plugin_instance), "%s%s",
1351                    data->instance_prefix, temp);
1352
1353         if (data->type_instance)
1354           sstrncpy(vl.type_instance, data->type_instance,
1355                    sizeof(vl.type_instance));
1356       } else {
1357         if (data->instance_prefix == NULL)
1358           sstrncpy(vl.type_instance, temp, sizeof(vl.type_instance));
1359         else
1360           snprintf(vl.type_instance, sizeof(vl.type_instance), "%s%s",
1361                    data->instance_prefix, temp);
1362
1363         if (data->plugin_instance)
1364           sstrncpy(vl.plugin_instance, data->plugin_instance,
1365                    sizeof(vl.plugin_instance));
1366       }
1367     }
1368
1369     vl.values_len = data->values_len;
1370     value_t values[vl.values_len];
1371     vl.values = values;
1372
1373     for (i = 0; i < data->values_len; i++)
1374       vl.values[i] = value_cell_ptr[i]->value;
1375
1376     plugin_dispatch_values(&vl);
1377
1378     /* prevent leakage of pointer to local variable. */
1379     vl.values_len = 0;
1380     vl.values = NULL;
1381
1382     if (instance_cells != NULL)
1383       instance_cell_ptr = instance_cell_ptr->next;
1384     else
1385       value_cell_ptr[0] = value_cell_ptr[0]->next;
1386   } /* while (have_more) */
1387
1388   return (0);
1389 } /* int csnmp_dispatch_table */
1390
1391 static int csnmp_read_table(host_definition_t *host, data_definition_t *data) {
1392   struct snmp_pdu *req;
1393   struct snmp_pdu *res = NULL;
1394   struct variable_list *vb;
1395
1396   const data_set_t *ds;
1397
1398   size_t oid_list_len = data->values_len;
1399
1400   if (data->instance.oid.oid_len > 0)
1401     oid_list_len++;
1402
1403   if (data->hostname_oid.oid_len > 0)
1404     oid_list_len++;
1405
1406   /* Holds the last OID returned by the device. We use this in the GETNEXT
1407    * request to proceed. */
1408   oid_t oid_list[oid_list_len];
1409   /* Set to false when an OID has left its subtree so we don't re-request it
1410    * again. */
1411   csnmp_oid_type_t oid_list_todo[oid_list_len];
1412
1413   int status;
1414   size_t i;
1415
1416   /* `value_list_head' and `value_cells_tail' implement a linked list for each
1417    * value. `instance_cells_head' and `instance_cells_tail' implement a linked
1418    * list of instance names. This is used to jump gaps in the table. */
1419   csnmp_cell_char_t *instance_cells_head = NULL;
1420   csnmp_cell_char_t *instance_cells_tail = NULL;
1421   csnmp_cell_char_t *hostname_cells_head = NULL;
1422   csnmp_cell_char_t *hostname_cells_tail = NULL;
1423   csnmp_cell_value_t **value_cells_head;
1424   csnmp_cell_value_t **value_cells_tail;
1425
1426   DEBUG("snmp plugin: csnmp_read_table (host = %s, data = %s)", host->name,
1427         data->name);
1428
1429   if (host->sess_handle == NULL) {
1430     DEBUG("snmp plugin: csnmp_read_table: host->sess_handle == NULL");
1431     return -1;
1432   }
1433
1434   ds = plugin_get_ds(data->type);
1435   if (!ds) {
1436     ERROR("snmp plugin: DataSet `%s' not defined.", data->type);
1437     return -1;
1438   }
1439
1440   if (ds->ds_num != data->values_len) {
1441     ERROR("snmp plugin: DataSet `%s' requires %" PRIsz
1442           " values, but config talks "
1443           "about %" PRIsz,
1444           data->type, ds->ds_num, data->values_len);
1445     return -1;
1446   }
1447   assert(data->values_len > 0);
1448
1449   for (i = 0; i < data->values_len; i++)
1450     oid_list_todo[i] = OID_TYPE_VARIABLE;
1451
1452   /* We need a copy of all the OIDs, because GETNEXT will destroy them. */
1453   memcpy(oid_list, data->values, data->values_len * sizeof(oid_t));
1454
1455   if (data->instance.oid.oid_len > 0) {
1456     memcpy(oid_list + i, &data->instance.oid, sizeof(oid_t));
1457     oid_list_todo[i] = OID_TYPE_INSTANCE;
1458     i++;
1459   }
1460
1461   if (data->hostname_oid.oid_len > 0) {
1462     memcpy(oid_list + i, &data->hostname_oid, sizeof(oid_t));
1463     oid_list_todo[i] = OID_TYPE_HOST;
1464     i++;
1465   }
1466
1467   /* We're going to construct n linked lists, one for each "value".
1468    * value_cells_head will contain pointers to the heads of these linked lists,
1469    * value_cells_tail will contain pointers to the tail of the lists. */
1470   value_cells_head = calloc(data->values_len, sizeof(*value_cells_head));
1471   value_cells_tail = calloc(data->values_len, sizeof(*value_cells_tail));
1472   if ((value_cells_head == NULL) || (value_cells_tail == NULL)) {
1473     ERROR("snmp plugin: csnmp_read_table: calloc failed.");
1474     sfree(value_cells_head);
1475     sfree(value_cells_tail);
1476     return -1;
1477   }
1478
1479   status = 0;
1480   while (status == 0) {
1481     req = snmp_pdu_create(SNMP_MSG_GETNEXT);
1482     if (req == NULL) {
1483       ERROR("snmp plugin: snmp_pdu_create failed.");
1484       status = -1;
1485       break;
1486     }
1487
1488     size_t oid_list_todo_num = 0;
1489     size_t var_idx[oid_list_len];
1490     memset(var_idx, 0, sizeof(var_idx));
1491
1492     for (i = 0; i < oid_list_len; i++) {
1493       /* Do not rerequest already finished OIDs */
1494       if (!oid_list_todo[i])
1495         continue;
1496       snmp_add_null_var(req, oid_list[i].oid, oid_list[i].oid_len);
1497       var_idx[oid_list_todo_num] = i;
1498       oid_list_todo_num++;
1499     }
1500
1501     if (oid_list_todo_num == 0) {
1502       /* The request is still empty - so we are finished */
1503       DEBUG("snmp plugin: all variables have left their subtree");
1504       snmp_free_pdu(req);
1505       status = 0;
1506       break;
1507     }
1508
1509     res = NULL;
1510     status = snmp_sess_synch_response(host->sess_handle, req, &res);
1511
1512     /* snmp_sess_synch_response always frees our req PDU */
1513     req = NULL;
1514
1515     if ((status != STAT_SUCCESS) || (res == NULL)) {
1516       char *errstr = NULL;
1517
1518       snmp_sess_error(host->sess_handle, NULL, NULL, &errstr);
1519
1520       c_complain(LOG_ERR, &host->complaint,
1521                  "snmp plugin: host %s: snmp_sess_synch_response failed: %s",
1522                  host->name, (errstr == NULL) ? "Unknown problem" : errstr);
1523
1524       if (res != NULL)
1525         snmp_free_pdu(res);
1526       res = NULL;
1527
1528       sfree(errstr);
1529       csnmp_host_close_session(host);
1530
1531       status = -1;
1532       break;
1533     }
1534
1535     status = 0;
1536     assert(res != NULL);
1537     c_release(LOG_INFO, &host->complaint,
1538               "snmp plugin: host %s: snmp_sess_synch_response successful.",
1539               host->name);
1540
1541     vb = res->variables;
1542     if (vb == NULL) {
1543       status = -1;
1544       break;
1545     }
1546
1547     if (res->errstat != SNMP_ERR_NOERROR) {
1548       if (res->errindex != 0) {
1549         /* Find the OID which caused error */
1550         for (i = 1, vb = res->variables; vb != NULL && i != res->errindex;
1551              vb = vb->next_variable, i++)
1552           /* do nothing */;
1553       }
1554
1555       if ((res->errindex == 0) || (vb == NULL)) {
1556         ERROR("snmp plugin: host %s; data %s: response error: %s (%li) ",
1557               host->name, data->name, snmp_errstring(res->errstat),
1558               res->errstat);
1559         status = -1;
1560         break;
1561       }
1562
1563       char oid_buffer[1024] = {0};
1564       snprint_objid(oid_buffer, sizeof(oid_buffer) - 1, vb->name,
1565                     vb->name_length);
1566       NOTICE("snmp plugin: host %s; data %s: OID `%s` failed: %s", host->name,
1567              data->name, oid_buffer, snmp_errstring(res->errstat));
1568
1569       /* Get value index from todo list and skip OID found */
1570       assert(res->errindex <= oid_list_todo_num);
1571       i = var_idx[res->errindex - 1];
1572       assert(i < oid_list_len);
1573       oid_list_todo[i] = 0;
1574
1575       snmp_free_pdu(res);
1576       res = NULL;
1577       continue;
1578     }
1579
1580     for (vb = res->variables, i = 0; (vb != NULL);
1581          vb = vb->next_variable, i++) {
1582       /* Calculate value index from todo list */
1583       while ((i < oid_list_len) && !oid_list_todo[i]) {
1584         i++;
1585       }
1586       if (i >= oid_list_len) {
1587         break;
1588       }
1589
1590       /* An instance is configured and the res variable we process is the
1591        * instance value */
1592       if (oid_list_todo[i] == OID_TYPE_INSTANCE) {
1593         if ((vb->type == SNMP_ENDOFMIBVIEW) ||
1594             (snmp_oid_ncompare(
1595                  data->instance.oid.oid, data->instance.oid.oid_len, vb->name,
1596                  vb->name_length, data->instance.oid.oid_len) != 0)) {
1597           DEBUG("snmp plugin: host = %s; data = %s; Instance left its subtree.",
1598                 host->name, data->name);
1599           oid_list_todo[i] = 0;
1600           continue;
1601         }
1602
1603         /* Allocate a new `csnmp_cell_char_t', insert the instance name and
1604          * add it to the list */
1605         csnmp_cell_char_t *cell =
1606             csnmp_get_char_cell(vb, &data->instance.oid, host, data);
1607         if (cell == NULL) {
1608           ERROR("snmp plugin: host %s: csnmp_get_char_cell() failed.",
1609                 host->name);
1610           status = -1;
1611           break;
1612         }
1613
1614         if (csnmp_ignore_instance(cell, data)) {
1615           sfree(cell);
1616         } else {
1617           /**/
1618           for (char *ptr = cell->value; *ptr != '\0'; ptr++) {
1619             if ((*ptr > 0) && (*ptr < 32))
1620               *ptr = ' ';
1621             else if (*ptr == '/')
1622               *ptr = '_';
1623           }
1624
1625           DEBUG("snmp plugin: il->instance = `%s';", cell->value);
1626           csnmp_cells_append(&instance_cells_head, &instance_cells_tail, cell);
1627         }
1628       } else if (oid_list_todo[i] == OID_TYPE_HOST) {
1629         if ((vb->type == SNMP_ENDOFMIBVIEW) ||
1630             (snmp_oid_ncompare(
1631                  data->hostname_oid.oid, data->hostname_oid.oid_len, vb->name,
1632                  vb->name_length, data->hostname_oid.oid_len) != 0)) {
1633           DEBUG("snmp plugin: host = %s; data = %s; Instance left its subtree.",
1634                 host->name, data->name);
1635           oid_list_todo[i] = 0;
1636           continue;
1637         }
1638
1639         /* Allocate a new `csnmp_cell_char_t', insert the instance name and
1640          * add it to the list */
1641         csnmp_cell_char_t *cell =
1642             csnmp_get_char_cell(vb, &data->hostname_oid, host, data);
1643         if (cell == NULL) {
1644           ERROR("snmp plugin: host %s: csnmp_get_char_cell() failed.",
1645                 host->name);
1646           status = -1;
1647           break;
1648         }
1649
1650         DEBUG("snmp plugin: il->hostname = `%s';", cell->value);
1651         csnmp_cells_append(&hostname_cells_head, &hostname_cells_tail, cell);
1652       } else /* The variable we are processing is a normal value */
1653       {
1654         assert(oid_list_todo[i] == OID_TYPE_VARIABLE);
1655
1656         csnmp_cell_value_t *vt;
1657         oid_t vb_name;
1658         oid_t suffix;
1659         int ret;
1660
1661         csnmp_oid_init(&vb_name, vb->name, vb->name_length);
1662
1663         DEBUG(
1664             "snmp plugin: src.oid_len = %d root.oid_len = %d is_endofmib = %s",
1665             vb_name.oid_len, (data->values + i)->oid_len,
1666             (vb->type == SNMP_ENDOFMIBVIEW) ? "true" : "false");
1667
1668         /* Calculate the current suffix. This is later used to check that the
1669          * suffix is increasing. This also checks if we left the subtree */
1670         ret = csnmp_oid_suffix(&suffix, &vb_name, data->values + i);
1671         if (ret != 0) {
1672           DEBUG("snmp plugin: host = %s; data = %s; i = %" PRIsz "; "
1673                 "Value probably left its subtree.",
1674                 host->name, data->name, i);
1675           oid_list_todo[i] = 0;
1676           continue;
1677         }
1678
1679         /* Make sure the OIDs returned by the agent are increasing. Otherwise
1680          * our table matching algorithm will get confused. */
1681         if ((value_cells_tail[i] != NULL) &&
1682             (csnmp_oid_compare(&suffix, &value_cells_tail[i]->suffix) <= 0)) {
1683           DEBUG("snmp plugin: host = %s; data = %s; i = %" PRIsz "; "
1684                 "Suffix is not increasing.",
1685                 host->name, data->name, i);
1686           oid_list_todo[i] = 0;
1687           continue;
1688         }
1689
1690         vt = calloc(1, sizeof(*vt));
1691         if (vt == NULL) {
1692           ERROR("snmp plugin: calloc failed.");
1693           status = -1;
1694           break;
1695         }
1696
1697         vt->value =
1698             csnmp_value_list_to_value(vb, ds->ds[i].type, data->scale,
1699                                       data->shift, host->name, data->name);
1700         memcpy(&vt->suffix, &suffix, sizeof(vt->suffix));
1701         vt->next = NULL;
1702
1703         if (value_cells_tail[i] == NULL)
1704           value_cells_head[i] = vt;
1705         else
1706           value_cells_tail[i]->next = vt;
1707         value_cells_tail[i] = vt;
1708       }
1709
1710       /* Copy OID to oid_list[i] */
1711       memcpy(oid_list[i].oid, vb->name, sizeof(oid) * vb->name_length);
1712       oid_list[i].oid_len = vb->name_length;
1713
1714     } /* for (vb = res->variables ...) */
1715
1716     if (res != NULL)
1717       snmp_free_pdu(res);
1718     res = NULL;
1719   } /* while (status == 0) */
1720
1721   if (res != NULL)
1722     snmp_free_pdu(res);
1723   res = NULL;
1724
1725   if (status == 0)
1726     csnmp_dispatch_table(host, data, instance_cells_head, hostname_cells_head,
1727                          value_cells_head);
1728
1729   /* Free all allocated variables here */
1730   while (instance_cells_head != NULL) {
1731     csnmp_cell_char_t *next = instance_cells_head->next;
1732     sfree(instance_cells_head);
1733     instance_cells_head = next;
1734   }
1735
1736   while (hostname_cells_head != NULL) {
1737     csnmp_cell_char_t *next = hostname_cells_head->next;
1738     sfree(hostname_cells_head);
1739     hostname_cells_head = next;
1740   }
1741
1742   for (i = 0; i < data->values_len; i++) {
1743     while (value_cells_head[i] != NULL) {
1744       csnmp_cell_value_t *next = value_cells_head[i]->next;
1745       sfree(value_cells_head[i]);
1746       value_cells_head[i] = next;
1747     }
1748   }
1749
1750   sfree(value_cells_head);
1751   sfree(value_cells_tail);
1752
1753   return 0;
1754 } /* int csnmp_read_table */
1755
1756 static int csnmp_read_value(host_definition_t *host, data_definition_t *data) {
1757   struct snmp_pdu *req;
1758   struct snmp_pdu *res = NULL;
1759   struct variable_list *vb;
1760
1761   const data_set_t *ds;
1762   value_list_t vl = VALUE_LIST_INIT;
1763
1764   int status;
1765   size_t i;
1766
1767   DEBUG("snmp plugin: csnmp_read_value (host = %s, data = %s)", host->name,
1768         data->name);
1769
1770   if (host->sess_handle == NULL) {
1771     DEBUG("snmp plugin: csnmp_read_value: host->sess_handle == NULL");
1772     return -1;
1773   }
1774
1775   ds = plugin_get_ds(data->type);
1776   if (!ds) {
1777     ERROR("snmp plugin: DataSet `%s' not defined.", data->type);
1778     return -1;
1779   }
1780
1781   if (ds->ds_num != data->values_len) {
1782     ERROR("snmp plugin: DataSet `%s' requires %" PRIsz
1783           " values, but config talks "
1784           "about %" PRIsz,
1785           data->type, ds->ds_num, data->values_len);
1786     return -1;
1787   }
1788
1789   vl.values_len = ds->ds_num;
1790   vl.values = malloc(sizeof(*vl.values) * vl.values_len);
1791   if (vl.values == NULL)
1792     return -1;
1793   for (i = 0; i < vl.values_len; i++) {
1794     if (ds->ds[i].type == DS_TYPE_COUNTER)
1795       vl.values[i].counter = 0;
1796     else
1797       vl.values[i].gauge = NAN;
1798   }
1799
1800   sstrncpy(vl.host, host->name, sizeof(vl.host));
1801   sstrncpy(vl.plugin, data->plugin_name, sizeof(vl.plugin));
1802   sstrncpy(vl.type, data->type, sizeof(vl.type));
1803   if (data->type_instance)
1804     sstrncpy(vl.type_instance, data->type_instance, sizeof(vl.type_instance));
1805   if (data->plugin_instance)
1806     sstrncpy(vl.plugin_instance, data->plugin_instance,
1807              sizeof(vl.plugin_instance));
1808
1809   vl.interval = host->interval;
1810
1811   req = snmp_pdu_create(SNMP_MSG_GET);
1812   if (req == NULL) {
1813     ERROR("snmp plugin: snmp_pdu_create failed.");
1814     sfree(vl.values);
1815     return -1;
1816   }
1817
1818   for (i = 0; i < data->values_len; i++)
1819     snmp_add_null_var(req, data->values[i].oid, data->values[i].oid_len);
1820
1821   status = snmp_sess_synch_response(host->sess_handle, req, &res);
1822
1823   if ((status != STAT_SUCCESS) || (res == NULL)) {
1824     char *errstr = NULL;
1825
1826     snmp_sess_error(host->sess_handle, NULL, NULL, &errstr);
1827     ERROR("snmp plugin: host %s: snmp_sess_synch_response failed: %s",
1828           host->name, (errstr == NULL) ? "Unknown problem" : errstr);
1829
1830     if (res != NULL)
1831       snmp_free_pdu(res);
1832
1833     sfree(errstr);
1834     sfree(vl.values);
1835     csnmp_host_close_session(host);
1836
1837     return -1;
1838   }
1839
1840   for (vb = res->variables; vb != NULL; vb = vb->next_variable) {
1841 #if COLLECT_DEBUG
1842     char buffer[1024];
1843     snprint_variable(buffer, sizeof(buffer), vb->name, vb->name_length, vb);
1844     DEBUG("snmp plugin: Got this variable: %s", buffer);
1845 #endif /* COLLECT_DEBUG */
1846
1847     for (i = 0; i < data->values_len; i++)
1848       if (snmp_oid_compare(data->values[i].oid, data->values[i].oid_len,
1849                            vb->name, vb->name_length) == 0)
1850         vl.values[i] =
1851             csnmp_value_list_to_value(vb, ds->ds[i].type, data->scale,
1852                                       data->shift, host->name, data->name);
1853   } /* for (res->variables) */
1854
1855   snmp_free_pdu(res);
1856
1857   DEBUG("snmp plugin: -> plugin_dispatch_values (&vl);");
1858   plugin_dispatch_values(&vl);
1859   sfree(vl.values);
1860
1861   return 0;
1862 } /* int csnmp_read_value */
1863
1864 static int csnmp_read_host(user_data_t *ud) {
1865   host_definition_t *host;
1866   int status;
1867   int success;
1868   int i;
1869
1870   host = ud->data;
1871
1872   if (host->interval == 0)
1873     host->interval = plugin_get_interval();
1874
1875   if (host->sess_handle == NULL)
1876     csnmp_host_open_session(host);
1877
1878   if (host->sess_handle == NULL)
1879     return -1;
1880
1881   success = 0;
1882   for (i = 0; i < host->data_list_len; i++) {
1883     data_definition_t *data = host->data_list[i];
1884
1885     if (data->is_table)
1886       status = csnmp_read_table(host, data);
1887     else
1888       status = csnmp_read_value(host, data);
1889
1890     if (status == 0)
1891       success++;
1892   }
1893
1894   if (success == 0)
1895     return -1;
1896
1897   return 0;
1898 } /* int csnmp_read_host */
1899
1900 static int csnmp_init(void) {
1901   call_snmp_init_once();
1902
1903   return 0;
1904 } /* int csnmp_init */
1905
1906 static int csnmp_shutdown(void) {
1907   data_definition_t *data_this;
1908   data_definition_t *data_next;
1909
1910   /* When we get here, the read threads have been stopped and all the
1911    * `host_definition_t' will be freed. */
1912   DEBUG("snmp plugin: Destroying all data definitions.");
1913
1914   data_this = data_head;
1915   data_head = NULL;
1916   while (data_this != NULL) {
1917     data_next = data_this->next;
1918
1919     sfree(data_this->name);
1920     sfree(data_this->type);
1921     sfree(data_this->plugin_name);
1922     sfree(data_this->plugin_instance);
1923     sfree(data_this->type_instance);
1924     sfree(data_this->instance_prefix);
1925     sfree(data_this->values);
1926     sfree(data_this->ignores);
1927     sfree(data_this);
1928
1929     data_this = data_next;
1930   }
1931
1932   return 0;
1933 } /* int csnmp_shutdown */
1934
1935 void module_register(void) {
1936   plugin_register_complex_config("snmp", csnmp_config);
1937   plugin_register_init("snmp", csnmp_init);
1938   plugin_register_shutdown("snmp", csnmp_shutdown);
1939 } /* void module_register */