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