root/src/modules/snmp.c

Revision 374e7c3da4113ce22e1687b5f03fdba7845dab41, 33.8 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 5 years ago)

Working traps. refs #37

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