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