root/src/modules/snmp.c

Revision 651988747506d25414e2375c0eb1b41f0ca3aaf9, 41.4 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 2 years ago)

Various security fixes.

  • Property mode set to 100644
Line 
1 /*
2  * Copyright (c) 2007, OmniTI Computer Consulting, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  *       notice, this list of conditions and the following disclaimer.
11  *     * Redistributions in binary form must reproduce the above
12  *       copyright notice, this list of conditions and the following
13  *       disclaimer in the documentation and/or other materials provided
14  *       with the distribution.
15  *     * Neither the name OmniTI Computer Consulting, Inc. nor the names
16  *       of its contributors may be used to endorse or promote products
17  *       derived from this software without specific prior written
18  *       permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #include "noit_defines.h"
34
35 #include <stdio.h>
36 #include <unistd.h>
37 #include <errno.h>
38 #include <assert.h>
39 #include <math.h>
40 #include <ctype.h>
41
42 #include <net-snmp/net-snmp-config.h>
43 #include <net-snmp/net-snmp-includes.h>
44
45 #include "noit_module.h"
46 #include "noit_check.h"
47 #include "noit_check_tools.h"
48 #include "utils/noit_log.h"
49 #include "utils/noit_hash.h"
50
51 static noit_log_stream_t nlerr = NULL;
52 static noit_log_stream_t nldeb = NULL;
53 static int __snmp_initialize_once = 0;
54
55 #define SNMPV2_TRAPS_PREFIX     SNMP_OID_SNMPMODULES,1,1,5
56 oid trap_prefix[]    = { SNMPV2_TRAPS_PREFIX };
57 oid cold_start_oid[] = { SNMPV2_TRAPS_PREFIX, 1 };  /* SNMPv2-MIB */
58 oid warm_start_oid[] = { SNMPV2_TRAPS_PREFIX, 2 };  /* SNMPv2-MIB */
59 oid link_down_oid[]  = { SNMPV2_TRAPS_PREFIX, 3 };  /* IF-MIB */
60 oid link_up_oid[]    = { SNMPV2_TRAPS_PREFIX, 4 };  /* IF-MIB */
61 oid auth_fail_oid[]  = { SNMPV2_TRAPS_PREFIX, 5 };  /* SNMPv2-MIB */
62 oid egp_xxx_oid[]    = { SNMPV2_TRAPS_PREFIX, 99 }; /* ??? */
63
64 #define SNMPV2_TRAP_OBJS_PREFIX SNMP_OID_SNMPMODULES,1,1,4
65 oid snmptrap_oid[] = { SNMPV2_TRAP_OBJS_PREFIX, 1, 0 };
66 size_t snmptrap_oid_len = OID_LENGTH(snmptrap_oid);
67 oid snmptrapenterprise_oid[] = { SNMPV2_TRAP_OBJS_PREFIX, 3, 0 };
68 size_t snmptrapenterprise_oid_len = OID_LENGTH(snmptrapenterprise_oid);
69 oid sysuptime_oid[] = { SNMP_OID_MIB2, 1, 3, 0 };
70 size_t sysuptime_oid_len = OID_LENGTH(sysuptime_oid);
71
72 #define SNMPV2_COMM_OBJS_PREFIX SNMP_OID_SNMPMODULES,18,1
73 oid agentaddr_oid[] = { SNMPV2_COMM_OBJS_PREFIX, 3, 0 };
74 size_t agentaddr_oid_len = OID_LENGTH(agentaddr_oid);
75 oid community_oid[] = { SNMPV2_COMM_OBJS_PREFIX, 4, 0 };
76 size_t community_oid_len = OID_LENGTH(community_oid);
77
78 #define RECONNOITER_PREFIX     SNMP_OID_ENTERPRISES,32863,1
79 oid reconnoiter_oid[] = { RECONNOITER_PREFIX };
80 size_t reconnoiter_oid_len = OID_LENGTH(reconnoiter_oid);
81 oid reconnoiter_check_prefix_oid[] = { RECONNOITER_PREFIX,1,1 };
82 size_t reconnoiter_check_prefix_oid_len =
83   OID_LENGTH(reconnoiter_check_prefix_oid);
84 size_t reconnoiter_check_oid_len = OID_LENGTH(reconnoiter_check_prefix_oid) + 8;
85 oid reconnoiter_metric_prefix_oid[] = { RECONNOITER_PREFIX,1,2 };
86 size_t reconnoiter_metric_prefix_oid_len =
87   OID_LENGTH(reconnoiter_metric_prefix_oid);
88
89 oid reconnoiter_check_status_oid[] = { RECONNOITER_PREFIX,1,3};
90 size_t reconnoiter_check_status_oid_len =
91   OID_LENGTH(reconnoiter_check_status_oid);
92 oid reconnoiter_check_state_oid[] = { RECONNOITER_PREFIX,1,3,1};
93 size_t reconnoiter_check_state_oid_len =
94   OID_LENGTH(reconnoiter_check_state_oid);
95 oid reconnoiter_check_state_unknown_oid[] = { RECONNOITER_PREFIX,1,3,1,0};
96 oid reconnoiter_check_state_good_oid[] = { RECONNOITER_PREFIX,1,3,1,1};
97 oid reconnoiter_check_state_bad_oid[] = { RECONNOITER_PREFIX,1,3,1,2};
98 size_t reconnoiter_check_state_val_len =
99   OID_LENGTH(reconnoiter_check_state_unknown_oid);
100 /* Boolean */
101 oid reconnoiter_check_available_oid[] = { RECONNOITER_PREFIX,1,3,2};
102 size_t reconnoiter_check_available_oid_len =
103   OID_LENGTH(reconnoiter_check_available_oid);
104 oid reconnoiter_check_available_unknown_oid[] = { RECONNOITER_PREFIX,1,3,2,0};
105 oid reconnoiter_check_available_yes_oid[] = { RECONNOITER_PREFIX,1,3,2,1};
106 oid reconnoiter_check_available_no_oid[] = { RECONNOITER_PREFIX,1,3,2,2};
107 size_t reconnoiter_check_available_val_len =
108   OID_LENGTH(reconnoiter_check_available_unknown_oid);
109 /* timeticks? gauge/unsigned? */
110 oid reconnoiter_check_duration_oid[] = { RECONNOITER_PREFIX,1,3,3};
111 size_t reconnoiter_check_duration_oid_len =
112   OID_LENGTH(reconnoiter_check_duration_oid);
113 /* string */
114 oid reconnoiter_check_status_msg_oid[] = { RECONNOITER_PREFIX,1,3,4};
115 size_t reconnoiter_check_status_msg_oid_len =
116   OID_LENGTH(reconnoiter_check_status_msg_oid);
117
118 typedef struct _mod_config {
119   noit_hash_table *options;
120   noit_hash_table target_sessions;
121 } snmp_mod_config_t;
122
123 struct target_session {
124   void *sess_handle;
125   noit_module_t *self;
126   char *key;
127   char *target;
128   eventer_t timeoutevent;
129   int version;
130   int fd;
131   int in_table;
132   int refcnt;
133   struct timeval last_open;
134 };
135
136 struct snmp_check_closure {
137   noit_module_t *self;
138   noit_check_t *check;
139 };
140
141 struct check_info {
142   int reqid;
143   int timedout;
144   struct {
145      char *confname;
146      char *oidname;
147      oid oid[MAX_OID_LEN];
148      size_t oidlen;
149      metric_type_t type_override;
150      noit_boolean type_should_override;
151   } *oids;
152   int noids;
153   eventer_t timeoutevent;
154   noit_module_t *self;
155   noit_check_t *check;
156   struct target_session *ts;
157   int version;
158 };
159
160 /* We hold struct check_info's in there key's by their reqid.
161  *   If they timeout, we remove them.
162  *
163  *   When SNMP queries complete, we look them up, if we find them
164  *   then we know we can remove the timeout and  complete the check.
165  *   If we don't find them, the timeout fired and removed the check.
166  */
167 noit_hash_table active_checks = NOIT_HASH_EMPTY;
168 static void add_check(struct check_info *c) {
169   noit_hash_store(&active_checks, (char *)&c->reqid, sizeof(c->reqid), c);
170 }
171 static struct check_info *get_check(int reqid) {
172   void *vc;
173   if(noit_hash_retrieve(&active_checks, (char *)&reqid, sizeof(reqid), &vc))
174     return (struct check_info *)vc;
175   return NULL;
176 }
177 static void remove_check(struct check_info *c) {
178   noit_hash_delete(&active_checks, (char *)&c->reqid, sizeof(c->reqid),
179                    NULL, NULL);
180 }
181
182 struct target_session *
183 _get_target_session(noit_module_t *self, char *target, int version) {
184   char key[128];
185   void *vts;
186   struct target_session *ts;
187   snmp_mod_config_t *conf;
188   conf = noit_module_get_userdata(self);
189   snprintf(key, sizeof(key), "%s:v%d", target, version);
190   if(!noit_hash_retrieve(&conf->target_sessions,
191                          key, strlen(key), &vts)) {
192     ts = calloc(1, sizeof(*ts));
193     ts->self = self;
194     ts->version = version;
195     ts->fd = -1;
196     ts->refcnt = 0;
197     ts->target = strdup(target);
198     ts->key = strdup(key);
199     ts->in_table = 1;
200     noit_hash_store(&conf->target_sessions,
201                     ts->key, strlen(ts->key), ts);
202     vts = ts;
203   }
204   return (struct target_session *)vts;
205 }
206
207 /* Handling of results */
208 static void noit_snmp_log_results(noit_module_t *self, noit_check_t *check,
209                                   struct snmp_pdu *pdu) {
210   struct check_info *info = check->closure;
211   struct variable_list *vars;
212   struct timeval duration;
213   char buff[128];
214   stats_t current;
215   int nresults = 0;
216
217   noit_check_stats_clear(check, &current);
218
219   if(pdu)
220     for(vars = pdu->variables; vars; vars = vars->next_variable)
221       nresults++;
222
223   gettimeofday(&current.whence, NULL);
224   sub_timeval(current.whence, check->last_fire_time, &duration);
225   current.duration = duration.tv_sec * 1000 + duration.tv_usec / 1000;
226   current.available = pdu ? NP_AVAILABLE : NP_UNAVAILABLE;
227   current.state = (nresults == info->noids) ? NP_GOOD : NP_BAD;
228   snprintf(buff, sizeof(buff), "%d/%d gets", nresults, info->noids);
229   current.status = buff;
230
231   /* We have no results over which to iterate. */
232   if(!pdu) {
233     noit_check_set_stats(check, &current);
234     return;
235   }
236
237   /* manipulate the information ourselves */
238   nresults = 0;
239   for(vars = pdu->variables; vars; vars = vars->next_variable) {
240     char *sp;
241     int oid_idx;
242     double float_conv;
243     u_int64_t u64;
244     int64_t i64;
245     char *endptr;
246     char varbuff[256];
247
248     /* find the oid to which this is the response */
249     oid_idx = nresults; /* our current idx is the most likely */
250     if(info->oids[oid_idx].oidlen != vars->name_length ||
251        memcmp(info->oids[oid_idx].oid, vars->name,
252               vars->name_length * sizeof(oid))) {
253       /* Not the most obvious guess */
254       for(oid_idx = info->noids - 1; oid_idx >= 0; oid_idx--) {
255         if(info->oids[oid_idx].oidlen == vars->name_length &&
256            memcmp(info->oids[oid_idx].oid, vars->name,
257                   vars->name_length * sizeof(oid))) break;
258       }
259     }
260     if(oid_idx < 0) {
261       snprint_variable(varbuff, sizeof(varbuff),
262                        vars->name, vars->name_length, vars);
263       noitL(nlerr, "Unexpected oid results to %s`%s`%s: %s\n",
264             check->target, check->module, check->name, varbuff);
265       nresults++;
266       continue;
267     }
268
269 #define SETM(a,b) noit_stats_set_metric(check, &current, \
270                                         info->oids[oid_idx].confname, a, b)
271     if(info->oids[oid_idx].type_should_override) {
272       snprint_value(varbuff, sizeof(varbuff), vars->name, vars->name_length, vars);
273       sp = strchr(varbuff, ' ');
274       if(sp) sp++;
275       noit_stats_set_metric_coerce(check, &current, info->oids[oid_idx].confname,
276                                    info->oids[oid_idx].type_override,
277                                    sp);
278     }
279     else {
280       switch(vars->type) {
281         case ASN_OCTET_STR:
282           sp = malloc(1 + vars->val_len);
283           memcpy(sp, vars->val.string, vars->val_len);
284           sp[vars->val_len] = '\0';
285           SETM(METRIC_STRING, sp);
286           free(sp);
287           break;
288         case ASN_INTEGER:
289         case ASN_GAUGE:
290           SETM(METRIC_INT32, vars->val.integer);
291           break;
292         case ASN_TIMETICKS:
293         case ASN_COUNTER:
294           SETM(METRIC_UINT32, vars->val.integer);
295           break;
296         case ASN_INTEGER64:
297           printI64(varbuff, vars->val.counter64);
298           i64 = strtoll(varbuff, &endptr, 10);
299           SETM(METRIC_INT64, (varbuff == endptr) ? NULL : &i64);
300           break;
301         case ASN_COUNTER64:
302           printU64(varbuff, vars->val.counter64);
303           u64 = strtoull(varbuff, &endptr, 10);
304           SETM(METRIC_UINT64, (varbuff == endptr) ? NULL : &u64);
305           break;
306         case ASN_FLOAT:
307           if(vars->val.floatVal) float_conv = *(vars->val.floatVal);
308           SETM(METRIC_DOUBLE, vars->val.floatVal ? &float_conv : NULL);
309           break;
310         case ASN_DOUBLE:
311           SETM(METRIC_DOUBLE, vars->val.doubleVal);
312           break;
313         case SNMP_NOSUCHOBJECT:
314         case SNMP_NOSUCHINSTANCE:
315           SETM(METRIC_STRING, NULL);
316           break;
317         default:
318           snprint_variable(varbuff, sizeof(varbuff), vars->name, vars->name_length, vars);
319           /* Advance passed the first space and use that unless there
320            * is no space or we have no more string left.
321            */
322           sp = strchr(varbuff, ' ');
323           if(sp) sp++;
324           SETM(METRIC_STRING, (sp && *sp) ? sp : NULL);
325       }
326     }
327     nresults++;
328   }
329   noit_check_set_stats(check, &current);
330 }
331
332 static int noit_snmp_session_cleanse(struct target_session *ts,
333                                      int needs_free) {
334   if(ts->refcnt == 0 && ts->sess_handle) {
335     eventer_t e = eventer_remove_fd(ts->fd);
336     if(needs_free) eventer_free(e);
337     ts->fd = -1;
338     if(ts->timeoutevent) {
339       eventer_remove(ts->timeoutevent);
340       ts->timeoutevent = NULL;
341     }
342     snmp_sess_close(ts->sess_handle);
343     ts->sess_handle = NULL;
344     if(!ts->in_table) {
345       free(ts);
346     }
347     return 1;
348   }
349   return 0;
350 }
351
352 static int noit_snmp_session_timeout(eventer_t e, int mask, void *closure,
353                                      struct timeval *now) {
354   struct target_session *ts = closure;
355   snmp_sess_timeout(ts->sess_handle);
356   noit_snmp_session_cleanse(ts, 1);
357   if(ts->timeoutevent == e)
358     ts->timeoutevent = NULL; /* this will be freed on return */
359   return 0;
360 }
361
362 static int noit_snmp_check_timeout(eventer_t e, int mask, void *closure,
363                                    struct timeval *now) {
364   struct check_info *info = closure;
365   info->timedout = 1;
366   if(info->ts) {
367     info->ts->refcnt--;
368     noit_snmp_session_cleanse(info->ts, 1);
369     info->ts = NULL;
370   }
371   remove_check(info);
372   /* Log our findings */
373   noit_snmp_log_results(info->self, info->check, NULL);
374   info->check->flags &= ~NP_RUNNING;
375   return 0;
376 }
377
378 static void _set_ts_timeout(struct target_session *ts, struct timeval *t) {
379   struct timeval now;
380   eventer_t e = NULL;
381   if(ts->timeoutevent) {
382     e = eventer_remove(ts->timeoutevent);
383     ts->timeoutevent = NULL;
384   }
385   if(!t) return;
386
387   gettimeofday(&now, NULL);
388   if(!e) e = eventer_alloc();
389   e->callback = noit_snmp_session_timeout;
390   e->closure = ts;
391   e->mask = EVENTER_TIMER;
392   add_timeval(now, *t, &e->whence);
393   ts->timeoutevent = e;
394   eventer_add(e);
395 }
396
397 static int noit_snmp_handler(eventer_t e, int mask, void *closure,
398                              struct timeval *now) {
399   fd_set fdset;
400   int fds, block = 0;
401   struct timeval timeout = { 0, 0 };
402   struct target_session *ts = closure;
403   FD_ZERO(&fdset);
404   FD_SET(e->fd, &fdset);
405   fds = e->fd + 1;
406   snmp_sess_read(ts->sess_handle, &fdset);
407   if(noit_snmp_session_cleanse(ts, 0))
408     return 0;
409   snmp_sess_select_info(ts->sess_handle, &fds, &fdset, &timeout, &block);
410   _set_ts_timeout(ts, block ? &timeout : NULL);
411   return EVENTER_READ | EVENTER_EXCEPTION;
412 }
413
414 /* This 'convert_v1pdu_to_v2' was cribbed directly from netsnmp */
415 static netsnmp_pdu *
416 convert_v1pdu_to_v2( netsnmp_pdu* template_v1pdu ) {
417   netsnmp_pdu *template_v2pdu;
418   netsnmp_variable_list *var;
419   oid enterprise[MAX_OID_LEN];
420   size_t enterprise_len;
421
422   /*
423    * Make a copy of the v1 Trap PDU
424    *   before starting to convert this
425    *   into a v2 Trap PDU.
426    */
427   template_v2pdu = snmp_clone_pdu( template_v1pdu);
428   if(!template_v2pdu) {
429     snmp_log(LOG_WARNING,
430              "send_trap: failed to copy v2 template PDU\n");
431     return NULL;
432   }
433   template_v2pdu->command = SNMP_MSG_TRAP2;
434
435   /*
436    * Insert an snmpTrapOID varbind before the original v1 varbind list
437    *   either using one of the standard defined trap OIDs,
438    *   or constructing this from the PDU enterprise & specific trap fields
439    */
440   if(template_v1pdu->trap_type == SNMP_TRAP_ENTERPRISESPECIFIC) {
441     if(template_v1pdu->enterprise_length + 2 > MAX_OID_LEN) {
442       noitL(nlerr, "send_trap: enterprise_length too large\n");
443       snmp_free_pdu(template_v2pdu);
444       return NULL;
445     }
446     memcpy(enterprise, template_v1pdu->enterprise,
447            template_v1pdu->enterprise_length*sizeof(oid));
448     enterprise_len = template_v1pdu->enterprise_length;
449     enterprise[enterprise_len++] = 0;
450     enterprise[enterprise_len++] = template_v1pdu->specific_type;
451   } else {
452     memcpy(enterprise, cold_start_oid, sizeof(cold_start_oid));
453     enterprise[9]  = template_v1pdu->trap_type+1;
454     enterprise_len = sizeof(cold_start_oid)/sizeof(oid);
455   }
456
457   var = NULL;
458   if(!snmp_varlist_add_variable(&var,
459                                 snmptrap_oid, snmptrap_oid_len,
460                                 ASN_OBJECT_ID,
461                                 (u_char*)enterprise,
462                                 enterprise_len*sizeof(oid))) {
463     noitL(nlerr, "send_trap: failed to insert copied snmpTrapOID varbind\n");
464     snmp_free_pdu(template_v2pdu);
465     return NULL;
466   }
467   var->next_variable        = template_v2pdu->variables;
468   template_v2pdu->variables = var;
469
470   /*
471    * Insert a sysUptime varbind at the head of the v2 varbind list
472    */
473   var = NULL;
474   if(!snmp_varlist_add_variable(&var,
475                                 sysuptime_oid, sysuptime_oid_len,
476                                 ASN_TIMETICKS,
477                                 (u_char*)&(template_v1pdu->time),
478                                 sizeof(template_v1pdu->time))) {
479     noitL(nlerr, "send_trap: failed to insert copied sysUptime varbind\n");
480     snmp_free_pdu(template_v2pdu);
481     return NULL;
482   }
483   var->next_variable = template_v2pdu->variables;
484   template_v2pdu->variables = var;
485
486   /*
487    * Append the other three conversion varbinds,
488    *  (snmpTrapAgentAddr, snmpTrapCommunity & snmpTrapEnterprise)
489    *  if they're not already present.
490    *  But don't bomb out completely if there are problems.
491    */
492   var = find_varbind_in_list(template_v2pdu->variables,
493                              agentaddr_oid, agentaddr_oid_len);
494   if(!var && (template_v1pdu->agent_addr[0]
495               || template_v1pdu->agent_addr[1]
496               || template_v1pdu->agent_addr[2]
497               || template_v1pdu->agent_addr[3])) {
498     if(!snmp_varlist_add_variable(&(template_v2pdu->variables),
499                                   agentaddr_oid, agentaddr_oid_len,
500                                   ASN_IPADDRESS,
501                                   (u_char*)&(template_v1pdu->agent_addr),
502                                   sizeof(template_v1pdu->agent_addr)))
503       noitL(nlerr, "send_trap: failed to append snmpTrapAddr varbind\n");
504   }
505   var = find_varbind_in_list(template_v2pdu->variables,
506                              community_oid, community_oid_len);
507   if(!var && template_v1pdu->community) {
508     if(!snmp_varlist_add_variable(&(template_v2pdu->variables),
509                                   community_oid, community_oid_len,
510                                   ASN_OCTET_STR,
511                                   template_v1pdu->community,
512                                   template_v1pdu->community_len))
513       noitL(nlerr, "send_trap: failed to append snmpTrapCommunity varbind\n");
514   }
515   var = find_varbind_in_list(template_v2pdu->variables,
516                              snmptrapenterprise_oid,
517                              snmptrapenterprise_oid_len);
518   if(!var &&
519      template_v1pdu->trap_type != SNMP_TRAP_ENTERPRISESPECIFIC) {
520     if(!snmp_varlist_add_variable(&(template_v2pdu->variables),
521                                   snmptrapenterprise_oid,
522                                   snmptrapenterprise_oid_len,
523                                   ASN_OBJECT_ID,
524                                   (u_char*)template_v1pdu->enterprise,
525                                   template_v1pdu->enterprise_length*sizeof(oid)))
526       noitL(nlerr, "send_trap: failed to append snmpEnterprise varbind\n");
527   }
528   return template_v2pdu;
529 }
530
531 static int noit_snmp_oid_to_checkid(oid *o, int l, uuid_t checkid, char *out) {
532   int i;
533   char _uuid_str[UUID_STR_LEN+1], *cp, *uuid_str;
534
535   uuid_str = out ? out : _uuid_str;
536   if(l != reconnoiter_check_oid_len) {
537     noitL(nlerr, "unsupported (length) trap recieved\n");
538     return -1;
539   }
540   if(netsnmp_oid_equals(o,
541                         reconnoiter_check_prefix_oid_len,
542                         reconnoiter_check_prefix_oid,
543                         reconnoiter_check_prefix_oid_len) != 0) {
544     noitL(nlerr, "unsupported (wrong namespace) trap recieved\n");
545     return -1;
546   }
547   /* encode this as a uuid */
548   cp = uuid_str;
549   for(i=0;
550       i < reconnoiter_check_oid_len - reconnoiter_check_prefix_oid_len;
551       i++) {
552     oid v = o[i + reconnoiter_check_prefix_oid_len];
553     if(v > 0xffff) {
554       noitL(nlerr, "trap target oid [%ld] out of range\n", (long int)v);
555       return -1;
556     }
557     snprintf(cp, 5, "%04x", (unsigned short)(v & 0xffff));
558     cp += 4;
559     /* hyphens after index 1,2,3,4 */
560     if(i > 0 && i < 5) *cp++ = '-';
561   }
562   if(uuid_parse(uuid_str, checkid) != 0) {
563     noitL(nlerr, "unexpected error decoding trap uuid '%s'\n", uuid_str);
564     return -1;
565   }
566   return 0;
567 }
568
569 #define isoid(a,b,c,d) (netsnmp_oid_equals(a,b,c,d) == 0)
570 #define isoidprefix(a,b,c,d) (netsnmp_oid_equals(a,MIN(b,d),c,d) == 0)
571 #define setstatus(st,soid,sv) \
572   if(isoid(o,l,soid,reconnoiter_check_state_val_len)) current->st = sv
573
574 static int
575 noit_snmp_trapvars_to_stats(noit_check_t *check, stats_t *current,
576                             netsnmp_variable_list *var) {
577   if(isoidprefix(var->name, var->name_length, reconnoiter_check_status_oid,
578                  reconnoiter_check_status_oid_len)) {
579     if(var->type == ASN_OBJECT_ID) {
580       if(isoid(var->name, var->name_length,
581                reconnoiter_check_state_oid, reconnoiter_check_state_oid_len)) {
582         oid *o = var->val.objid;
583         size_t l = var->val_len / sizeof(*o);
584         setstatus(state, reconnoiter_check_state_unknown_oid, NP_UNKNOWN);
585         else setstatus(state, reconnoiter_check_state_good_oid, NP_GOOD);
586         else setstatus(state, reconnoiter_check_state_bad_oid, NP_BAD);
587         else return -1;
588       }
589       else if(isoid(var->name, var->name_length,
590                     reconnoiter_check_available_oid,
591                     reconnoiter_check_available_oid_len)) {
592         oid *o = var->val.objid;
593         size_t l = var->val_len / sizeof(*o);
594         setstatus(available, reconnoiter_check_available_unknown_oid, NP_UNKNOWN);
595         else setstatus(available, reconnoiter_check_available_yes_oid, NP_AVAILABLE);
596         else setstatus(available, reconnoiter_check_available_no_oid, NP_UNAVAILABLE);
597         else return -1;
598       }
599       else {
600         /* We don't unerstand any other OBJECT_ID types */
601         return -1;
602       }
603     }
604     else if(var->type == ASN_UNSIGNED) {
605       /* This is only for the duration (in ms) */
606       if(isoid(var->name, var->name_length,
607                reconnoiter_check_duration_oid,
608                reconnoiter_check_duration_oid_len)) {
609         current->duration = *(var->val.integer);
610       }
611       else
612         return -1;
613     }
614     else if(var->type == ASN_OCTET_STR) {
615       /* This is only for the status message */
616       if(isoid(var->name, var->name_length,
617                reconnoiter_check_status_msg_oid,
618                reconnoiter_check_status_msg_oid_len)) {
619         current->status = malloc(var->val_len + 1);
620         memcpy(current->status, var->val.string, var->val_len);
621         current->status[var->val_len] = '\0';
622       }
623       else
624         return -1;
625     }
626     else {
627       /* I don't understand any other type of status message */
628       return -1;
629     }
630   }
631   else if(isoidprefix(var->name, var->name_length,
632                       reconnoiter_metric_prefix_oid,
633                       reconnoiter_metric_prefix_oid_len)) {
634     /* decode the metric and store the value */
635     int i, len;
636     u_int64_t u64;
637     double doubleVal;
638     char metric_name[128], buff[128], *cp;
639     if(var->name_length <= reconnoiter_metric_prefix_oid_len) return -1;
640     len = var->name[reconnoiter_metric_prefix_oid_len];
641     if(var->name_length != (reconnoiter_metric_prefix_oid_len + 1 + len) ||
642        len > sizeof(metric_name) - 1) {
643       noitL(nlerr, "snmp trap, malformed metric name\n");
644       return -1;
645     }
646     for(i=0;i<len;i++) {
647       ((unsigned char *)metric_name)[i] =
648         (unsigned char)var->name[reconnoiter_metric_prefix_oid_len + 1 + i];
649       if(!isprint(metric_name[i])) {
650         noitL(nlerr, "metric_name contains unprintable characters\n");
651         return -1;
652       }
653     }
654     metric_name[i] = '\0';
655     switch(var->type) {
656       case ASN_INTEGER:
657       case ASN_UINTEGER:
658       case ASN_TIMETICKS:
659       case ASN_INTEGER64:
660         noit_stats_set_metric(check, current, metric_name,
661                               METRIC_INT64, var->val.integer);
662         break;
663       case ASN_COUNTER64:
664         u64 = ((u_int64_t)var->val.counter64->high) << 32;
665         u64 |= var->val.counter64->low;
666         noit_stats_set_metric(check, current, metric_name,
667                               METRIC_UINT64, &u64);
668         break;
669       case ASN_OPAQUE_FLOAT:
670         doubleVal = (double)*var->val.floatVal;
671         noit_stats_set_metric(check, current, metric_name,
672                               METRIC_DOUBLE, &doubleVal);
673         break;
674       case ASN_OPAQUE_DOUBLE:
675         noit_stats_set_metric(check, current, metric_name,
676                               METRIC_DOUBLE, var->val.doubleVal);
677         break;
678       case ASN_OCTET_STR:
679         snprint_value(buff, sizeof(buff), var->name, var->name_length, var);
680         /* Advance passed the first space and use that unless there
681          * is no space or we have no more string left.
682          */
683         cp = strchr(buff, ' ');
684         if(cp) {
685           char *ecp;
686           cp++;
687           if(*cp == '"') {
688             ecp = cp + strlen(cp) - 1;
689             if(*ecp == '"') {
690               cp++; *ecp = '\0';
691             }
692           }
693         }
694         noit_stats_set_metric(check, current, metric_name,
695                               METRIC_STRING, (cp && *cp) ? cp : NULL);
696         break;
697       default:
698         noitL(nlerr, "snmp trap unsupport data type %d\n", var->type);
699     }
700     noitL(nldeb, "metric_name -> '%s'\n", metric_name);
701   }
702   else {
703     /* No idea what this is */
704     return -1;
705   }
706   return 0;
707 }
708 static int noit_snmp_trapd_response(int operation, struct snmp_session *sp,
709                                     int reqid, struct snmp_pdu *pdu,
710                                     void *magic) {
711   /* the noit pieces */
712   noit_check_t *check;
713   struct target_session *ts = magic;
714   snmp_mod_config_t *conf;
715   const char *community = NULL;
716   stats_t current;
717   int success = 0;
718
719   /* parsing destination */
720   char uuid_str[UUID_STR_LEN + 1];
721   uuid_t checkid;
722
723   /* snmp oid parsing helper vars */
724   netsnmp_pdu *newpdu = pdu;
725   netsnmp_variable_list *var;
726
727   conf = noit_module_get_userdata(ts->self);
728
729   if(pdu->version == SNMP_VERSION_1)
730     newpdu = convert_v1pdu_to_v2(pdu);
731   if(!newpdu || newpdu->version != SNMP_VERSION_2c) goto cleanup;
732
733   for(var = newpdu->variables; var != NULL; var = var->next_variable) {
734     if(netsnmp_oid_equals(var->name, var->name_length,
735                           snmptrap_oid, snmptrap_oid_len) == 0)
736       break;
737   }
738
739   if (!var || var->type != ASN_OBJECT_ID) {
740     noitL(nlerr, "unsupport trap (not a trap?) received\n");
741     goto cleanup;
742   }
743
744   /* var is the oid on which we are trapping.
745    * It should be in the reconnoiter check prefix.
746    */
747   if(noit_snmp_oid_to_checkid(var->val.objid, var->val_len/sizeof(oid),
748                               checkid, uuid_str)) {
749     goto cleanup;
750   }
751   noitL(nldeb, "recieved trap for %s\n", uuid_str);
752   check = noit_poller_lookup(checkid);
753   if(!check) {
754     noitL(nlerr, "trap received for non-existent check '%s'\n", uuid_str);
755     goto cleanup;
756   }
757   if(!noit_hash_retr_str(check->config, "community", strlen("community"),
758                          &community) &&
759      !noit_hash_retr_str(conf->options, "community", strlen("community"),
760                          &community)) {
761     noitL(nlerr, "No community defined for check, dropping trap\n");
762     goto cleanup;
763   }
764
765   if(strlen(community) != newpdu->community_len ||
766      memcmp(community, newpdu->community, newpdu->community_len)) {
767     noitL(nlerr, "trap attempt with wrong community string\n");
768     goto cleanup;
769   }
770
771   /* We have a check. The trap is authorized. Now, extract everything. */
772   memset(&current, 0, sizeof(current));
773   gettimeofday(&current.whence, NULL);
774   current.available = NP_AVAILABLE;
775
776   /* Rate limit */
777   if(((current.whence.tv_sec * 1000 +
778        current.whence.tv_usec / 1000) -
779       (check->last_fire_time.tv_sec * 1000 +
780        check->last_fire_time.tv_usec / 1000)) < check->period) goto cleanup;
781
782   /* update the last fire time... */
783   gettimeofday(&check->last_fire_time, NULL);
784
785   for(; var != NULL; var = var->next_variable)
786     if(noit_snmp_trapvars_to_stats(check, &current, var) == 0) success++;
787   if(success) {
788     char buff[24];
789     snprintf(buff, sizeof(buff), "%d datum", success);
790     current.state = NP_GOOD;
791     current.status = strdup(buff);
792   }
793   else {
794     current.state = NP_BAD;
795     current.status = strdup("no data");
796   }
797   noit_check_set_stats(check, &current);
798
799  cleanup:
800   if(newpdu != pdu)
801     snmp_free_pdu(newpdu);
802   return 0;
803 }
804 static int noit_snmp_asynch_response(int operation, struct snmp_session *sp,
805                                      int reqid, struct snmp_pdu *pdu,
806                                      void *magic) {
807   struct check_info *info;
808   /* We don't deal with refcnt hitting zero here.  We could only be hit from
809    * the snmp read/timeout stuff.  Handle it there.
810    */
811
812   info = get_check(reqid);
813   if(!info) return 1;
814   if(info->ts) {
815     info->ts->refcnt--;
816     info->ts = NULL;
817   }
818   remove_check(info);
819   if(info->timeoutevent) {
820     eventer_remove(info->timeoutevent);
821     eventer_free(info->timeoutevent);
822     info->timeoutevent = NULL;
823   }
824
825   /* Log our findings */
826   noit_snmp_log_results(info->self, info->check, pdu);
827   info->check->flags &= ~NP_RUNNING;
828   return 1;
829 }
830
831 static void noit_snmp_sess_open(struct target_session *ts,
832                                 noit_check_t *check) {
833   const char *community;
834   struct snmp_session sess;
835   struct check_info *info = check->closure;
836   snmp_sess_init(&sess);
837   sess.version = info->version;
838   sess.peername = ts->target;
839   if(!noit_hash_retr_str(check->config, "community", strlen("community"),
840                          &community)) {
841     community = "public";
842   }
843   sess.community = (unsigned char *)community;
844   sess.community_len = strlen(community);
845   sess.callback = noit_snmp_asynch_response;
846   sess.callback_magic = ts;
847   ts->sess_handle = snmp_sess_open(&sess);
848   gettimeofday(&ts->last_open, NULL);
849 }
850
851 static int noit_snmp_fill_req(struct snmp_pdu *req, noit_check_t *check) {
852   int i, klen;
853   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
854   const char *name, *value;
855   struct check_info *info = check->closure;
856   noit_hash_table check_attrs_hash = NOIT_HASH_EMPTY;
857
858   /* Toss the old set and bail if we have zero */
859   if(info->oids) {
860     for(i=0; i<info->noids;i++) {
861       if(info->oids[i].confname) free(info->oids[i].confname);
862       if(info->oids[i].oidname) free(info->oids[i].oidname);
863     }
864     free(info->oids);
865   }
866   info->noids = 0;
867   info->oids = NULL;
868
869   /* Figure our how many. */
870   while(noit_hash_next_str(check->config, &iter, &name, &klen, &value)) {
871     if(!strncasecmp(name, "oid_", 4)) {
872       info->noids++;
873     }
874   }
875
876   if(info->noids == 0) return 0;
877
878   /* Create a hash of important check attributes */
879   noit_check_make_attrs(check, &check_attrs_hash);
880
881   /* Fill out the new set of required oids */
882   info->oids = calloc(info->noids, sizeof(*info->oids));
883   memset(&iter, 0, sizeof(iter));
884   i = 0;
885   while(noit_hash_next_str(check->config, &iter, &name, &klen, &value)) {
886     if(!strncasecmp(name, "oid_", 4)) {
887       const char *type_override;
888       char oidbuff[2048], typestr[256];
889       name += 4;
890       info->oids[i].confname = strdup(name);
891       noit_check_interpolate(oidbuff, sizeof(oidbuff), value,
892                              &check_attrs_hash, check->config);
893       info->oids[i].oidname = strdup(oidbuff);
894       info->oids[i].oidlen = MAX_OID_LEN;
895       if(oidbuff[0] == '.')
896         read_objid(oidbuff, info->oids[i].oid, &info->oids[i].oidlen);
897       else
898         get_node(oidbuff, info->oids[i].oid, &info->oids[i].oidlen);
899       snprintf(typestr, sizeof(typestr), "type_%s", name);
900       if(noit_hash_retr_str(check->config, typestr, strlen(typestr),
901                             &type_override)) {
902         int type_enum_fake = *type_override;
903
904         if(!strcasecmp(type_override, "guess"))
905           type_enum_fake = METRIC_GUESS;
906         else if(!strcasecmp(type_override, "int32"))
907           type_enum_fake = METRIC_INT32;
908         else if(!strcasecmp(type_override, "uint32"))
909           type_enum_fake = METRIC_UINT32;
910         else if(!strcasecmp(type_override, "int64"))
911           type_enum_fake = METRIC_INT64;
912         else if(!strcasecmp(type_override, "uint64"))
913           type_enum_fake = METRIC_UINT64;
914         else if(!strcasecmp(type_override, "double"))
915           type_enum_fake = METRIC_DOUBLE;
916         else if(!strcasecmp(type_override, "string"))
917           type_enum_fake = METRIC_STRING;
918
919         switch(type_enum_fake) {
920           case METRIC_GUESS:
921           case METRIC_INT32: case METRIC_UINT32:
922           case METRIC_INT64: case METRIC_UINT64:
923           case METRIC_DOUBLE: case METRIC_STRING:
924             info->oids[i].type_override = *type_override;
925             info->oids[i].type_should_override = noit_true;
926           default: break;
927         }
928       }
929       snmp_add_null_var(req, info->oids[i].oid, info->oids[i].oidlen);
930       i++;
931     }
932   }
933   assert(info->noids == i);
934   noit_hash_destroy(&check_attrs_hash, NULL, NULL);
935   return info->noids;
936 }
937 static int noit_snmp_send(noit_module_t *self, noit_check_t *check,
938                           noit_check_t *cause) {
939   struct snmp_pdu *req;
940   struct target_session *ts;
941   struct check_info *info = check->closure;
942   int port = 161;
943   const char *portstr, *versstr;
944   char target_port[64];
945
946   info->version = SNMP_VERSION_2c;
947   info->self = self;
948   info->check = check;
949   info->timedout = 0;
950
951   BAIL_ON_RUNNING_CHECK(check);
952   check->flags |= NP_RUNNING;
953
954   if(noit_hash_retr_str(check->config, "port", strlen("port"),
955                         &portstr)) {
956     port = atoi(portstr);
957   }
958   if(noit_hash_retr_str(check->config, "version", strlen("version"),
959                         &versstr)) {
960     /* We don't care about 2c or others... as they all default to 2c */
961     if(!strcmp(versstr, "1")) info->version = SNMP_VERSION_1;
962     if(!strcmp(versstr, "3")) info->version = SNMP_VERSION_3;
963   }
964   snprintf(target_port, sizeof(target_port), "%s:%d", check->target_ip, port);
965   ts = _get_target_session(self, target_port, info->version);
966   gettimeofday(&check->last_fire_time, NULL);
967   if(!ts->refcnt) {
968     eventer_t newe;
969     int fds, block;
970     struct timeval timeout;
971     fd_set fdset;
972     noit_snmp_sess_open(ts, check);
973     block = 0;
974     fds = 0;
975     FD_ZERO(&fdset);
976     snmp_sess_select_info(ts->sess_handle, &fds, &fdset, &timeout, &block);
977     assert(fds > 0);
978     ts->fd = fds-1;
979     newe = eventer_alloc();
980     newe->fd = ts->fd;
981     newe->callback = noit_snmp_handler;
982     newe->closure = ts;
983     newe->mask = EVENTER_READ | EVENTER_EXCEPTION;
984     eventer_add(newe);
985   }
986   if(!ts->sess_handle) {
987     /* Error */
988     /* No need to do anything, this will be handled in the else below */
989   }
990   ts->refcnt++; /* Increment here, decrement when this check completes */
991
992   req = snmp_pdu_create(SNMP_MSG_GET);
993   if(req) noit_snmp_fill_req(req, check);
994   req->version = info->version;
995   /* Setup out snmp requests */
996   if(ts->sess_handle && req &&
997      (info->reqid = snmp_sess_send(ts->sess_handle, req)) != 0) {
998     struct timeval when, to;
999     info->ts = ts;
1000     info->timeoutevent = eventer_alloc();
1001     info->timeoutevent->callback = noit_snmp_check_timeout;
1002     info->timeoutevent->closure = info;
1003     info->timeoutevent->mask = EVENTER_TIMER;
1004
1005     noitL(nldeb, "Sending snmp get\n");
1006     gettimeofday(&when, NULL);
1007     to.tv_sec = check->timeout / 1000;
1008     to.tv_usec = (check->timeout % 1000) * 1000;
1009     add_timeval(when, to, &info->timeoutevent->whence);
1010     eventer_add(info->timeoutevent);
1011     add_check(info);
1012   }
1013   else {
1014     ts->refcnt--;
1015     noitL(nlerr, "Error sending snmp get request.\n");
1016     noit_snmp_session_cleanse(ts, 1);
1017     /* Error */
1018     if(req) snmp_free_pdu(req);
1019     /* Log our findings */
1020     noit_snmp_log_results(self, check, NULL);
1021     check->flags &= ~NP_RUNNING;
1022   }
1023   return 0;
1024 }
1025
1026 static int noit_snmp_initiate_check(noit_module_t *self, noit_check_t *check,
1027                                     int once, noit_check_t *cause) {
1028   if(!check->closure) check->closure = calloc(1, sizeof(struct check_info));
1029   INITIATE_CHECK(noit_snmp_send, self, check, cause);
1030   return 0;
1031 }
1032
1033 static int noit_snmptrap_initiate_check(noit_module_t *self,
1034                                         noit_check_t *check,
1035                                         int once, noit_check_t *cause) {
1036   /* We don't do anything for snmptrap checks.  Not intuitive... but they
1037    * never "run."  We accept input out-of-band via snmp traps.
1038    */
1039   check->flags |= NP_PASSIVE_COLLECTION;
1040   return 0;
1041 }
1042
1043 static int noit_snmp_config(noit_module_t *self, noit_hash_table *options) {
1044   snmp_mod_config_t *conf;
1045   conf = noit_module_get_userdata(self);
1046   if(conf) {
1047     if(conf->options) {
1048       noit_hash_destroy(conf->options, free, free);
1049       free(conf->options);
1050     }
1051   }
1052   else
1053     conf = calloc(1, sizeof(*conf));
1054   conf->options = options;
1055   noit_module_set_userdata(self, conf);
1056   return 1;
1057 }
1058 static int noit_snmp_onload(noit_image_t *self) {
1059   if(!nlerr) nlerr = noit_log_stream_find("error/snmp");
1060   if(!nldeb) nldeb = noit_log_stream_find("debug/snmp");
1061   if(!nlerr) nlerr = noit_stderr;
1062   if(!nldeb) nldeb = noit_debug;
1063   eventer_name_callback("noit_snmp/check_timeout", noit_snmp_check_timeout);
1064   eventer_name_callback("noit_snmp/session_timeout", noit_snmp_session_timeout);
1065   eventer_name_callback("noit_snmp/handler", noit_snmp_handler);
1066   return 0;
1067 }
1068
1069 static int noit_snmptrap_onload(noit_image_t *self) {
1070   if(!nlerr) nlerr = noit_log_stream_find("error/snmp");
1071   if(!nldeb) nldeb = noit_log_stream_find("debug/snmp");
1072   if(!nlerr) nlerr = noit_stderr;
1073   if(!nldeb) nldeb = noit_debug;
1074   eventer_name_callback("noit_snmp/session_timeout", noit_snmp_session_timeout);
1075   eventer_name_callback("noit_snmp/handler", noit_snmp_handler);
1076   return 0;
1077 }
1078
1079 static void
1080 nc_printf_snmpts_brief(noit_console_closure_t ncct,
1081                        struct target_session *ts) {
1082   char fd[32];
1083   struct timeval now, diff;
1084   const char *snmpvers = "v(unknown)";
1085   gettimeofday(&now, NULL);
1086   sub_timeval(now, ts->last_open, &diff);
1087   if(ts->fd < 0)
1088     snprintf(fd, sizeof(fd), "%s", "(closed)");
1089   else
1090     snprintf(fd, sizeof(fd), "%d", ts->fd);
1091   switch(ts->version) {
1092     case SNMP_VERSION_1: snmpvers = "v1"; break;
1093     case SNMP_VERSION_2c: snmpvers = "v2c"; break;
1094     case SNMP_VERSION_3: snmpvers = "v3"; break;
1095   }
1096   nc_printf(ncct, "[%s %s]\n\topened: %0.3fs ago\n\tFD: %s\n\trefcnt: %d\n",
1097             ts->target, snmpvers, diff.tv_sec + (float)diff.tv_usec/1000000,
1098             fd, ts->refcnt);
1099 }
1100
1101 static int
1102 noit_console_show_snmp(noit_console_closure_t ncct,
1103                        int argc, char **argv,
1104                        noit_console_state_t *dstate,
1105                        void *closure) {
1106   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
1107   uuid_t key_id;
1108   int klen;
1109   void *vts;
1110   snmp_mod_config_t *conf = closure;
1111
1112   while(noit_hash_next(&conf->target_sessions, &iter,
1113                        (const char **)key_id, &klen,
1114                        &vts)) {
1115     struct target_session *ts = vts;
1116     nc_printf_snmpts_brief(ncct, ts);
1117   }
1118   return 0;
1119 }
1120
1121 static void
1122 register_console_snmp_commands(snmp_mod_config_t *conf) {
1123   noit_console_state_t *tl;
1124   cmd_info_t *showcmd;
1125
1126   tl = noit_console_state_initial();
1127   showcmd = noit_console_state_get_cmd(tl, "show");
1128   assert(showcmd && showcmd->dstate);
1129   noit_console_state_add_cmd(showcmd->dstate,
1130     NCSCMD("snmp", noit_console_show_snmp, NULL, NULL, conf));
1131 }
1132
1133 static int noit_snmp_init(noit_module_t *self) {
1134   const char *opt;
1135   snmp_mod_config_t *conf;
1136
1137   conf = noit_module_get_userdata(self);
1138
1139   if(!__snmp_initialize_once) {
1140     register_mib_handlers();
1141     read_premib_configs();
1142     read_configs();
1143     init_snmp("noitd");
1144     __snmp_initialize_once = 1;
1145   }
1146   if(strcmp(self->hdr.name, "snmp") == 0) {
1147     register_console_snmp_commands(conf);
1148   }
1149
1150   if(strcmp(self->hdr.name, "snmptrap") == 0) {
1151     eventer_t newe;
1152     int i, block = 0, fds = 0;
1153     fd_set fdset;
1154     struct timeval timeout = { 0, 0 };
1155     struct target_session *ts;
1156     netsnmp_transport *transport;
1157     netsnmp_session sess, *session = &sess;
1158
1159     if(!noit_hash_retrieve(conf->options,
1160                            "snmptrapd_port", strlen("snmptrapd_port"),
1161                            (void **)&opt))
1162       opt = "162";
1163
1164     transport = netsnmp_transport_open_server("snmptrap", opt);
1165     if(!transport) {
1166       noitL(nlerr, "cannot open netsnmp transport for trap daemon\n");
1167       return -1;
1168     }
1169     ts = _get_target_session(self, "snmptrapd", SNMP_DEFAULT_VERSION);
1170     snmp_sess_init(session);
1171     session->peername = SNMP_DEFAULT_PEERNAME;
1172     session->version = SNMP_DEFAULT_VERSION;
1173     session->community_len = SNMP_DEFAULT_COMMUNITY_LEN;
1174     session->retries = SNMP_DEFAULT_RETRIES;
1175     session->timeout = SNMP_DEFAULT_TIMEOUT;
1176     session->callback = noit_snmp_trapd_response;
1177     session->callback_magic = (void *) ts;
1178     session->authenticator = NULL;
1179     session->isAuthoritative = SNMP_SESS_UNKNOWNAUTH;
1180     ts->sess_handle = snmp_sess_add(session, transport, NULL, NULL);
1181
1182     FD_ZERO(&fdset);
1183     snmp_sess_select_info(ts->sess_handle, &fds, &fdset, &timeout, &block);
1184     assert(fds > 0);
1185     for(i=0; i<fds; i++) {
1186       if(FD_ISSET(i, &fdset)) {
1187         ts->refcnt++;
1188         ts->fd = i;
1189         newe = eventer_alloc();
1190         newe->fd = ts->fd;
1191         newe->callback = noit_snmp_handler;
1192         newe->closure = ts;
1193         newe->mask = EVENTER_READ | EVENTER_EXCEPTION;
1194         eventer_add(newe);
1195       }
1196     }
1197   }
1198   return 0;
1199 }
1200
1201 #include "snmp.xmlh"
1202 noit_module_t snmp = {
1203   {
1204     NOIT_MODULE_MAGIC,
1205     NOIT_MODULE_ABI_VERSION,
1206     "snmp",
1207     "SNMP collection",
1208     snmp_xml_description,
1209     noit_snmp_onload
1210   },
1211   noit_snmp_config,
1212   noit_snmp_init,
1213   noit_snmp_initiate_check,
1214   NULL /* noit_snmp_cleanup */
1215 };
1216
1217 #include "snmptrap.xmlh"
1218 noit_module_t snmptrap = {
1219   {
1220     NOIT_MODULE_MAGIC,
1221     NOIT_MODULE_ABI_VERSION,
1222     "snmptrap",
1223     "SNMP trap collection",
1224     snmptrap_xml_description,
1225     noit_snmptrap_onload
1226   },
1227   noit_snmp_config,
1228   noit_snmp_init,
1229   noit_snmptrap_initiate_check,
1230   NULL /* noit_snmp_cleanup */
1231 };
Note: See TracBrowser for help on using the browser.