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