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