root/src/modules/snmp.c

Revision 6210da7ee0e2ed143d71a8e00b709f16e71059f8, 33.8 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 6 years ago)

various changes to avoid dereferencing type-punned pointers and breaking strict-aliasing rules, refs #34

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