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