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