root/src/modules/snmp.c

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

dead assignments, refs #283

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