root/src/modules/ping_icmp.c

Revision 1d69a01311e58ce6ddb007d690b4e9aa4ac08c8c, 15.8 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 6 years ago)

And make it all work on OpenBSD (ld -E ? sigh...)

  • 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 <netdb.h>
11 #include <errno.h>
12 #include <fcntl.h>
13 #include <sys/ioctl.h>
14 #ifdef HAVE_NETINET_IN_SYSTM_H
15 #include <netinet/in_systm.h>
16 #endif
17 #include <netinet/in.h>
18 #include <netinet/ip.h>
19 #include <netinet/ip_icmp.h>
20 #include <math.h>
21
22 #include "noit_module.h"
23 #include "noit_check.h"
24 #include "utils/noit_log.h"
25
26 #define PING_INTERVAL 2000 /* 2000ms = 2s */
27 #define PING_COUNT    5
28
29 struct check_info {
30   int check_no;
31   int check_seq_no;
32   int seq;
33   int expected_count;
34   float *turnaround;
35   eventer_t timeout_event;
36 };
37 struct ping_payload {
38   uuid_t checkid;
39   struct timeval whence;
40   int    check_no;
41   int    check_pack_no;
42   int    check_pack_cnt;
43 };
44 struct ping_closure {
45   noit_module_t *self;
46   noit_check_t *check;
47   void *payload;
48   int payload_len;
49 };
50 static noit_log_stream_t nlerr = NULL;
51 static noit_log_stream_t nldeb = NULL;
52 static int ping_icmp_recur_handler(eventer_t e, int mask, void *closure,
53                                    struct timeval *now);
54 static int in_cksum(u_short *addr, int len);
55
56 typedef struct  {
57   int ipv4_fd;
58   int ipv6_fd;
59 } ping_icmp_data_t;
60
61 static int ping_icmp_config(noit_module_t *self, noit_hash_table *options) {
62   return 0;
63 }
64 static int ping_icmp_is_complete(noit_module_t *self, noit_check_t *check) {
65   int i;
66   struct check_info *data;
67   data = (struct check_info *)check->closure;
68   for(i=0; i<data->expected_count; i++)
69     if(data->turnaround[i] == 0.0) {
70       noitL(nldeb, "ping_icmp: %s %d is still outstanding.\n",
71             check->target, i);
72       return 0;
73     }
74   return 1;
75 }
76 static void ping_icmp_log_results(noit_module_t *self, noit_check_t *check) {
77   struct check_info *data;
78   float avail, min = MAXFLOAT, max = 0.0, avg = 0.0, cnt;
79   int i, points = 0;
80   char human_buffer[256];
81   stats_t current;
82   struct timeval duration;
83
84   memset(&current, 0, sizeof(current));
85
86   data = (struct check_info *)check->closure;
87   for(i=0; i<data->expected_count; i++) {
88     if(data->turnaround[i] != 0) {
89       points++;
90       avg += data->turnaround[i];
91       if(data->turnaround[i] > max) max = data->turnaround[i];
92       if(data->turnaround[i] < min) min = data->turnaround[i];
93     }
94   }
95   if(points == 0) {
96     min = 0.0 / 0.0;
97     max = 0.0 / 0.0;
98   }
99   cnt = data->expected_count;
100   avail = (float)points /cnt;
101   avg /= (float)points;
102
103   snprintf(human_buffer, sizeof(human_buffer),
104            "cnt=%d,avail=%0.0f,min=%0.4f,max=%0.4f,avg=%0.4f",
105            (int)cnt, 100.0*avail, min, max, avg);
106   noitL(nldeb, "ping_icmp(%s) [%s]\n", check->target, human_buffer);
107
108   gettimeofday(&current.whence, NULL);
109   sub_timeval(current.whence, check->last_fire_time, &duration);
110   current.duration = duration.tv_sec * 1000 + duration.tv_usec / 1000;
111   current.available = (avail > 0.0) ? NP_AVAILABLE : NP_UNAVAILABLE;
112   current.state = (avail < 1.0) ? NP_BAD : NP_GOOD;
113   current.status = human_buffer;
114   noit_stats_set_metric_int(&current, "count", &data->expected_count);
115   avail *= 100.0;
116   noit_stats_set_metric_float(&current, "available", &avail);
117   noit_stats_set_metric_float(&current, "minimum", avail > 0.0 ? &min : NULL);
118   noit_stats_set_metric_float(&current, "maximum", avail > 0.0 ? &max : NULL);
119   noit_stats_set_metric_float(&current, "average", avail > 0.0 ? &avg : NULL);
120   noit_check_set_stats(self, check, &current);
121 }
122 static int ping_icmp_timeout(eventer_t e, int mask,
123                              void *closure, struct timeval *now) {
124   struct ping_closure *pcl = (struct ping_closure *)closure;
125   struct check_info *data;
126   ping_icmp_log_results(pcl->self, pcl->check);
127   data = (struct check_info *)pcl->check->closure;
128   data->timeout_event = NULL;
129   pcl->check->flags &= ~NP_RUNNING;
130   free(pcl);
131   return 0;
132 }
133 static int ping_icmp_handler(eventer_t e, int mask,
134                              void *closure, struct timeval *now) {
135   noit_module_t *self = (noit_module_t *)closure;
136   struct check_info *data;
137   char packet[1500];
138   int packet_len = sizeof(packet);
139   union {
140    struct sockaddr_in  in4;
141    struct sockaddr_in6 in6;
142   } from;
143   unsigned int from_len;
144   struct ip *ip = (struct ip *)packet;;
145   struct icmp *icp;
146   struct ping_payload *payload;
147
148   while(1) {
149     int inlen, iphlen;
150     noit_check_t *check;
151     struct timeval tt;
152
153     from_len = sizeof(from);
154
155     inlen = recvfrom(e->fd, packet, packet_len, 0,
156                      (struct sockaddr *)&from, &from_len);
157     gettimeofday(now, NULL); /* set it, as we care about accuracy */
158
159     if(inlen < 0) {
160       if(errno == EAGAIN || errno == EINTR) break;
161       noitLT(nlerr, now, "ping_icmp recvfrom: %s\n", strerror(errno));
162       break;
163     }
164     iphlen = ip->ip_hl << 2;
165     if((inlen-iphlen) != (sizeof(struct icmp)+sizeof(struct ping_payload))) {
166       noitLT(nlerr, now,
167              "ping_icmp bad size: %d+%d\n", iphlen, inlen-iphlen);
168       continue;
169     }
170     icp = (struct icmp *)(packet + iphlen);
171     payload = (struct ping_payload *)(icp + 1);
172     if(icp->icmp_type != ICMP_ECHOREPLY) {
173       continue;
174     }
175     if(icp->icmp_id != (((vpsized_uint)self) & 0xffff)) {
176       noitLT(nlerr, now,
177                "ping_icmp not sent from this instance (%d:%d) vs. %d\n",
178                icp->icmp_id, ntohs(icp->icmp_seq),
179                (((vpsized_uint)self) & 0xffff));
180       continue;
181     }
182     check = noit_poller_lookup(payload->checkid);
183     if(!check) {
184       char uuid_str[37];
185       uuid_unparse_lower(payload->checkid, uuid_str);
186       noitLT(nlerr, now,
187              "ping_icmp response for unknown check '%s'\n", uuid_str);
188       continue;
189     }
190     data = (struct check_info *)check->closure;
191
192     /* If there is no timeout_event, the check must have completed.
193      * We have nothing to do. */
194     if(!data->timeout_event) continue;
195
196     /* Sanity check the payload */
197     if(payload->check_no != data->check_no) continue;
198     if(payload->check_pack_cnt != data->expected_count) continue;
199     if(payload->check_pack_no < 0 ||
200        payload->check_pack_no >= data->expected_count) continue;
201
202     sub_timeval(*now, payload->whence, &tt);
203     data->turnaround[payload->check_pack_no] =
204       (float)tt.tv_sec + (float)tt.tv_usec / 1000000.0;
205     if(ping_icmp_is_complete(self, check)) {
206       ping_icmp_log_results(self, check);
207       eventer_remove(data->timeout_event);
208       free(data->timeout_event->closure);
209       eventer_free(data->timeout_event);
210       data->timeout_event = NULL;
211       check->flags &= ~NP_RUNNING;
212     }
213   }
214   return EVENTER_READ;
215 }
216
217 static int ping_icmp_init(noit_module_t *self) {
218   socklen_t on;
219   struct protoent *proto;
220   ping_icmp_data_t *data;
221
222   data = malloc(sizeof(*data));
223   data->ipv4_fd = data->ipv6_fd = -1;
224
225   if ((proto = getprotobyname("icmp")) == NULL) {
226     noitL(nlerr, "Couldn't find 'icmp' protocol\n");
227     return -1;
228   }
229
230   data->ipv4_fd = socket(AF_INET, SOCK_RAW, proto->p_proto);
231   if(data->ipv4_fd < 0) {
232     noitL(nlerr, "ping_icmp: socket failed: %s\n",
233           strerror(errno));
234   }
235   else {
236     on = 1;
237     if(ioctl(data->ipv4_fd, FIONBIO, &on)) {
238       close(data->ipv4_fd);
239       data->ipv4_fd = -1;
240       noitL(nlerr,
241             "ping_icmp: could not set socket non-blocking: %s\n",
242             strerror(errno));
243     }
244   }
245   if(data->ipv4_fd >= 0) {
246     eventer_t newe;
247     newe = eventer_alloc();
248     newe->fd = data->ipv4_fd;
249     newe->mask = EVENTER_READ;
250     newe->callback = ping_icmp_handler;
251     newe->closure = self;
252     eventer_add(newe);
253   }
254
255   data->ipv6_fd = socket(AF_INET6, SOCK_RAW, proto->p_proto);
256   if(data->ipv6_fd < 0) {
257     noitL(nlerr, "ping_icmp: socket failed: %s\n",
258           strerror(errno));
259   }
260   else {
261     on = 1;
262     if(ioctl(data->ipv6_fd, FIONBIO, &on)) {
263       close(data->ipv6_fd);
264       data->ipv6_fd = -1;
265       noitL(nlerr,
266             "ping_icmp: could not set socket non-blocking: %s\n",
267                strerror(errno));
268     }
269   }
270   if(data->ipv6_fd >= 0) {
271     eventer_t newe;
272     newe = eventer_alloc();
273     newe->fd = data->ipv6_fd;
274     newe->mask = EVENTER_READ;
275     newe->callback = ping_icmp_handler;
276     newe->closure = self;
277     eventer_add(newe);
278   }
279
280   noit_module_set_userdata(self, data);
281   return 0;
282 }
283
284 static int ping_icmp_real_send(eventer_t e, int mask,
285                                void *closure, struct timeval *now) {
286   struct ping_closure *pcl = (struct ping_closure *)closure;
287   struct icmp *icp;
288   struct ping_payload *payload;
289   ping_icmp_data_t *data;
290   int i;
291
292   noitLT(nldeb, now, "ping_icmp_real_send(%s)\n", pcl->check->target);
293   data = noit_module_get_userdata(pcl->self);
294   icp = (struct icmp *)pcl->payload;
295   payload = (struct ping_payload *)(icp + 1);
296   gettimeofday(&payload->whence, NULL); /* now isn't accurate enough */
297   icp->icmp_cksum = in_cksum(pcl->payload, pcl->payload_len);
298   if(pcl->check->target_family == AF_INET) {
299     struct sockaddr_in sin;
300     memset(&sin, 0, sizeof(sin));
301     sin.sin_family = AF_INET;
302     memcpy(&sin.sin_addr,
303            &pcl->check->target_addr.addr, sizeof(sin.sin_addr));
304     i = sendto(data->ipv4_fd,
305                pcl->payload, pcl->payload_len, 0,
306                (struct sockaddr *)&sin, sizeof(sin));
307   }
308   else {
309     struct sockaddr_in6 sin;
310     memset(&sin, 0, sizeof(sin));
311     sin.sin6_family = AF_INET6;
312     memcpy(&sin.sin6_addr,
313            &pcl->check->target_addr.addr6, sizeof(sin.sin6_addr));
314     i = sendto(data->ipv6_fd,
315                pcl->payload, pcl->payload_len, 0,
316                (struct sockaddr *)&sin, sizeof(sin));
317   }
318   if(i != pcl->payload_len) {
319     noitLT(nlerr, now, "Error sending ICMP packet to %s: %s\n",
320              pcl->check->target, strerror(errno));
321   }
322   free(pcl->payload);
323   free(pcl);
324   return 0;
325 }
326 static int ping_icmp_send(noit_module_t *self, noit_check_t *check) {
327   struct timeval when, p_int;
328   struct icmp *icp;
329   struct ping_payload *payload;
330   struct ping_closure *pcl;
331   struct check_info *ci = (struct check_info *)check->closure;
332   int packet_len, i;
333   eventer_t newe;
334   const char *config_val;
335
336   int interval = PING_INTERVAL;
337   int count = PING_COUNT;
338   if(noit_hash_retrieve(check->config, "interval", strlen("interval"),
339                         (void **)&config_val))
340     interval = atoi(config_val);
341   if(noit_hash_retrieve(check->config, "count", strlen("count"),
342                         (void **)&config_val))
343     count = atoi(config_val);
344
345   check->flags |= NP_RUNNING;
346   noitL(nldeb, "ping_icmp_send(%p,%s,%d,%d)\n",
347         self, check->target, interval, count);
348
349   /* remove a timeout if we still have one -- we should unless someone
350    * has set a lower timeout than the period.
351    */
352   if(ci->timeout_event) {
353     eventer_remove(ci->timeout_event);
354     free(ci->timeout_event->closure);
355     eventer_free(ci->timeout_event);
356     ci->timeout_event = NULL;
357   }
358
359   gettimeofday(&when, NULL);
360   memcpy(&check->last_fire_time, &when, sizeof(when));
361
362   /* Setup some stuff used in the loop */
363   p_int.tv_sec = interval / 1000;
364   p_int.tv_usec = (interval % 1000) * 1000;
365   packet_len = sizeof(*icp) + sizeof(*payload);
366
367   /* Prep holding spots for return info */
368   ci->expected_count = count;
369   if(ci->turnaround) free(ci->turnaround);
370   ci->turnaround = calloc(count, sizeof(*ci->turnaround));
371
372   ++ci->check_no;
373   for(i=0; i<count; i++) {
374     newe = eventer_alloc();
375     newe->callback = ping_icmp_real_send;
376     newe->mask = EVENTER_TIMER;
377     memcpy(&newe->whence, &when, sizeof(when));
378     add_timeval(when, p_int, &when); /* Next one is a bit later */
379
380     icp = malloc(packet_len);
381     payload = (struct ping_payload *)(icp + 1);
382
383     icp->icmp_type = ICMP_ECHO;
384     icp->icmp_code = 0;
385     icp->icmp_cksum = 0;
386     icp->icmp_seq = htons(ci->seq++);
387     icp->icmp_id = (((vpsized_uint)self) & 0xffff);
388
389     uuid_copy(payload->checkid, check->checkid);
390     payload->check_no = ci->check_no;
391     payload->check_pack_no = i;
392     payload->check_pack_cnt = count;
393
394     pcl = calloc(1, sizeof(*pcl));
395     pcl->self = self;
396     pcl->check = check;
397     pcl->payload = icp;
398     pcl->payload_len = packet_len;
399
400     newe->closure = pcl;
401     eventer_add(newe);
402   }
403   newe = eventer_alloc();
404   newe->mask = EVENTER_TIMER;
405   gettimeofday(&when, NULL);
406   p_int.tv_sec = check->timeout / 1000;
407   p_int.tv_usec = (check->timeout % 1000) * 1000;
408   add_timeval(when, p_int, &newe->whence);
409   pcl = calloc(1, sizeof(*pcl));
410   pcl->self = self;
411   pcl->check = check;
412   newe->closure = pcl;
413   newe->callback = ping_icmp_timeout;
414   eventer_add(newe);
415   ci->timeout_event = newe;
416
417   return 0;
418 }
419 static int ping_icmp_schedule_next(noit_module_t *self,
420                                    struct timeval *last_check,
421                                    noit_check_t *check,
422                                    struct timeval *now) {
423   eventer_t newe;
424   struct timeval period, earliest;
425   struct ping_closure *pcl;
426
427   if(check->period == 0) return 0;
428
429   /* If we have an event, we know when we intended it to fire.  This means
430    * we should schedule that point + period.
431    */
432   if(now)
433     memcpy(&earliest, now, sizeof(earliest));
434   else
435     gettimeofday(&earliest, NULL);
436   period.tv_sec = check->period / 1000;
437   period.tv_usec = (check->period % 1000) * 1000;
438
439   newe = eventer_alloc();
440   memcpy(&newe->whence, last_check, sizeof(*last_check));
441   add_timeval(newe->whence, period, &newe->whence);
442   if(compare_timeval(newe->whence, earliest) < 0)
443     memcpy(&newe->whence, &earliest, sizeof(earliest));
444   newe->mask = EVENTER_TIMER;
445   newe->callback = ping_icmp_recur_handler;
446   pcl = calloc(1, sizeof(*pcl));
447   pcl->self = self;
448   pcl->check = check;
449   newe->closure = pcl;
450
451   eventer_add(newe);
452   check->fire_event = newe;
453   return 0;
454 }
455 static int ping_icmp_recur_handler(eventer_t e, int mask, void *closure,
456                                    struct timeval *now) {
457   struct ping_closure *cl = (struct ping_closure *)closure;
458   ping_icmp_schedule_next(cl->self, &e->whence, cl->check, now);
459   ping_icmp_send(cl->self, cl->check);
460   free(cl);
461   return 0;
462 }
463 static int ping_icmp_initiate_check(noit_module_t *self, noit_check_t *check,
464                                     int once, noit_check_t *cause) {
465   if(!check->closure) check->closure = calloc(1, sizeof(struct check_info));
466   if(once) {
467     ping_icmp_send(self, check);
468     return 0;
469   }
470   if(!check->fire_event) {
471     struct timeval epoch;
472     noit_check_fake_last_check(check, &epoch, NULL);
473     ping_icmp_schedule_next(self, &epoch, check, NULL);
474   }
475   return 0;
476 }
477
478 /*
479  *      I N _ C K S U M
480  *          This is from Mike Muuss's Public Domain code.
481  * Checksum routine for Internet Protocol family headers (C Version)
482  *
483  */
484 static int in_cksum(u_short *addr, int len)
485 {
486   register int nleft = len;
487   register u_short *w = addr;
488   register u_short answer;
489   register int sum = 0;
490
491   /*
492    *  Our algorithm is simple, using a 32 bit accumulator (sum),
493    *  we add sequential 16 bit words to it, and at the end, fold
494    *  back all the carry bits from the top 16 bits into the lower
495    *  16 bits.
496    */
497   while( nleft > 1 )  {
498     sum += *w++;
499     nleft -= 2;
500   }
501
502   /* mop up an odd byte, if necessary */
503   if( nleft == 1 ) {
504     u_short  u = 0;
505
506     *(u_char *)(&u) = *(u_char *)w ;
507     sum += u;
508   }
509
510   /*
511    * add back carry outs from top 16 bits to low 16 bits
512    */
513   sum = (sum >> 16) + (sum & 0xffff);  /* add hi 16 to low 16 */
514   sum += (sum >> 16);      /* add carry */
515   answer = ~sum;        /* truncate to 16 bits */
516   return (answer);
517 }
518
519 static int ping_icmp_onload(noit_module_t *self) {
520   nlerr = noit_log_stream_find("error/ping_icmp");
521   nldeb = noit_log_stream_find("debug/ping_icmp");
522   if(!nlerr) nlerr = noit_stderr;
523   if(!nldeb) nldeb = noit_debug;
524   eventer_name_callback("ping_icmp/recur_handler", ping_icmp_recur_handler);
525   eventer_name_callback("ping_icmp/timeout", ping_icmp_timeout);
526   eventer_name_callback("ping_icmp/handler", ping_icmp_handler);
527   return 0;
528 }
529 noit_module_t ping_icmp = {
530   NOIT_MODULE_MAGIC,
531   NOIT_MODULE_ABI_VERSION,
532   "ping_icmp",
533   "ICMP based host availability detection",
534   ping_icmp_onload,
535   ping_icmp_config,
536   ping_icmp_init,
537   ping_icmp_initiate_check
538 };
539
Note: See TracBrowser for help on using the browser.