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