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