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