1 /******************************************************************************
2 *
3 * Nagios check_icmp plugin
4 *
5 * License: GPL
6 * Copyright (c) 2005-2007 nagios-plugins team
7 *
8 * Original Author : Andreas Ericsson <ae@op5.se>
9 *
10 * Last Modified: $Date$
11 *
12 * Description:
13 *
14 * This file contains the check_icmp plugin
15 *
16 * Relevant RFC's: 792 (ICMP), 791 (IP)
17 *
18 * This program was modeled somewhat after the check_icmp program,
19 * which was in turn a hack of fping (www.fping.org) but has been
20 * completely rewritten since to generate higher precision rta values,
21 * and support several different modes as well as setting ttl to control.
22 * redundant routes. The only remainders of fping is currently a few
23 * function names.
24 *
25 * License Information:
26 *
27 * This program is free software; you can redistribute it and/or modify
28 * it under the terms of the GNU General Public License as published by
29 * the Free Software Foundation; either version 2 of the License, or
30 * (at your option) any later version.
31 *
32 * This program is distributed in the hope that it will be useful,
33 * but WITHOUT ANY WARRANTY; without even the implied warranty of
34 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 * GNU General Public License for more details.
36 *
37 * You should have received a copy of the GNU General Public License
38 * along with this program; if not, write to the Free Software
39 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
40 *
41 * $Id$
42 *
43 *****************************************************************************/
45 /* progname may change */
46 /* char *progname = "check_icmp"; */
47 char *progname;
48 const char *revision = "$Revision$";
49 const char *copyright = "2005-2007";
50 const char *email = "nagiosplug-devel@lists.sourceforge.net";
52 /** nagios plugins basic includes */
53 #include "common.h"
54 #include "netutils.h"
55 #include "utils.h"
57 #include <sys/time.h>
58 #include <sys/types.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <stdarg.h>
62 #include <unistd.h>
63 #include <stddef.h>
64 #include <errno.h>
65 #include <string.h>
66 #include <ctype.h>
67 #include <netdb.h>
68 #include <sys/socket.h>
69 #include <netinet/in_systm.h>
70 #include <netinet/in.h>
71 #include <netinet/ip.h>
72 #include <netinet/ip_icmp.h>
73 #include <arpa/inet.h>
74 #include <signal.h>
77 /** sometimes undefined system macros (quite a few, actually) **/
78 #ifndef MAXTTL
79 # define MAXTTL 255
80 #endif
81 #ifndef INADDR_NONE
82 # define INADDR_NONE 0xffffffU
83 #endif
85 #ifndef SOL_IP
86 #define SOL_IP 0
87 #endif
89 /* we bundle these in one #ifndef, since they're all from BSD
90 * Put individual #ifndef's around those that bother you */
91 #ifndef ICMP_UNREACH_NET_UNKNOWN
92 # define ICMP_UNREACH_NET_UNKNOWN 6
93 # define ICMP_UNREACH_HOST_UNKNOWN 7
94 # define ICMP_UNREACH_ISOLATED 8
95 # define ICMP_UNREACH_NET_PROHIB 9
96 # define ICMP_UNREACH_HOST_PROHIB 10
97 # define ICMP_UNREACH_TOSNET 11
98 # define ICMP_UNREACH_TOSHOST 12
99 #endif
100 /* tru64 has the ones above, but not these */
101 #ifndef ICMP_UNREACH_FILTER_PROHIB
102 # define ICMP_UNREACH_FILTER_PROHIB 13
103 # define ICMP_UNREACH_HOST_PRECEDENCE 14
104 # define ICMP_UNREACH_PRECEDENCE_CUTOFF 15
105 #endif
108 typedef unsigned short range_t; /* type for get_range() -- unimplemented */
110 typedef struct rta_host {
111 unsigned short id; /* id in **table, and icmp pkts */
112 char *name; /* arg used for adding this host */
113 char *msg; /* icmp error message, if any */
114 struct sockaddr_in saddr_in; /* the address of this host */
115 struct in_addr error_addr; /* stores address of error replies */
116 unsigned long long time_waited; /* total time waited, in usecs */
117 unsigned int icmp_sent, icmp_recv, icmp_lost; /* counters */
118 unsigned char icmp_type, icmp_code; /* type and code from errors */
119 unsigned short flags; /* control/status flags */
120 double rta; /* measured RTA */
121 unsigned char pl; /* measured packet loss */
122 struct rta_host *next; /* linked list */
123 } rta_host;
125 #define FLAG_LOST_CAUSE 0x01 /* decidedly dead target. */
127 /* threshold structure. all values are maximum allowed, exclusive */
128 typedef struct threshold {
129 unsigned char pl; /* max allowed packet loss in percent */
130 unsigned int rta; /* roundtrip time average, microseconds */
131 } threshold;
133 /* the data structure */
134 typedef struct icmp_ping_data {
135 struct timeval stime; /* timestamp (saved in protocol struct as well) */
136 unsigned short ping_id;
137 } icmp_ping_data;
139 /* the different modes of this program are as follows:
140 * MODE_RTA: send all packets no matter what (mimic check_icmp and check_ping)
141 * MODE_HOSTCHECK: Return immediately upon any sign of life
142 * In addition, sends packets to ALL addresses assigned
143 * to this host (as returned by gethostbyname() or
144 * gethostbyaddr() and expects one host only to be checked at
145 * a time. Therefore, any packet response what so ever will
146 * count as a sign of life, even when received outside
147 * crit.rta limit. Do not misspell any additional IP's.
148 * MODE_ALL: Requires packets from ALL requested IP to return OK (default).
149 * MODE_ICMP: implement something similar to check_icmp (MODE_RTA without
150 * tcp and udp args does this)
151 */
152 #define MODE_RTA 0
153 #define MODE_HOSTCHECK 1
154 #define MODE_ALL 2
155 #define MODE_ICMP 3
157 /* the different ping types we can do
158 * TODO: investigate ARP ping as well */
159 #define HAVE_ICMP 1
160 #define HAVE_UDP 2
161 #define HAVE_TCP 4
162 #define HAVE_ARP 8
164 #define MIN_PING_DATA_SIZE sizeof(struct icmp_ping_data)
165 #define MAX_IP_PKT_SIZE 65536 /* (theoretical) max IP packet size */
166 #define IP_HDR_SIZE 20
167 #define MAX_PING_DATA (MAX_IP_PKT_SIZE - IP_HDR_SIZE - ICMP_MINLEN)
168 #define DEFAULT_PING_DATA_SIZE (MIN_PING_DATA_SIZE + 44)
170 /* various target states */
171 #define TSTATE_INACTIVE 0x01 /* don't ping this host anymore */
172 #define TSTATE_WAITING 0x02 /* unanswered packets on the wire */
173 #define TSTATE_ALIVE 0x04 /* target is alive (has answered something) */
174 #define TSTATE_UNREACH 0x08
176 /** prototypes **/
177 void print_help (void);
178 void print_usage (void);
179 static u_int get_timevar(const char *);
180 static u_int get_timevaldiff(struct timeval *, struct timeval *);
181 static int wait_for_reply(int, u_int);
182 static int recvfrom_wto(int, char *, unsigned int, struct sockaddr *, u_int *);
183 static int send_icmp_ping(int, struct rta_host *);
184 static int get_threshold(char *str, threshold *th);
185 static void run_checks(void);
186 static int add_target(char *);
187 static int add_target_ip(char *, struct in_addr *);
188 static int handle_random_icmp(struct icmp *, struct sockaddr_in *);
189 static unsigned short icmp_checksum(unsigned short *, int);
190 static void finish(int);
191 static void crash(const char *, ...);
193 /** external **/
194 extern int optind, opterr, optopt;
195 extern char *optarg;
196 extern char **environ;
198 /** global variables **/
199 static struct rta_host **table, *cursor, *list;
200 static threshold crit = {80, 500000}, warn = {40, 200000};
201 static int mode, protocols, sockets, debug = 0, timeout = 10;
202 static unsigned short icmp_pkt_size, icmp_data_size = DEFAULT_PING_DATA_SIZE;
203 static unsigned int icmp_sent = 0, icmp_recv = 0, icmp_lost = 0;
204 #define icmp_pkts_en_route (icmp_sent - (icmp_recv + icmp_lost))
205 static unsigned short targets_down = 0, targets = 0, packets = 0;
206 #define targets_alive (targets - targets_down)
207 static unsigned int retry_interval, pkt_interval, target_interval;
208 static int icmp_sock, tcp_sock, udp_sock, status = STATE_OK;
209 static pid_t pid;
210 static struct timezone tz;
211 static struct timeval prog_start;
212 static unsigned long long max_completion_time = 0;
213 static unsigned char ttl = 0; /* outgoing ttl */
214 static unsigned int warn_down = 1, crit_down = 1; /* host down threshold values */
215 static int min_hosts_alive = -1;
216 float pkt_backoff_factor = 1.5;
217 float target_backoff_factor = 1.5;
219 /** code start **/
220 static void
221 crash(const char *fmt, ...)
222 {
223 va_list ap;
225 printf("%s: ", progname);
227 va_start(ap, fmt);
228 vprintf(fmt, ap);
229 va_end(ap);
231 if(errno) printf(": %s", strerror(errno));
232 puts("");
234 exit(3);
235 }
238 static char *
239 get_icmp_error_msg(unsigned char icmp_type, unsigned char icmp_code)
240 {
241 char *msg = "unreachable";
243 if(debug > 1) printf("get_icmp_error_msg(%u, %u)\n", icmp_type, icmp_code);
244 switch(icmp_type) {
245 case ICMP_UNREACH:
246 switch(icmp_code) {
247 case ICMP_UNREACH_NET: msg = "Net unreachable"; break;
248 case ICMP_UNREACH_HOST: msg = "Host unreachable"; break;
249 case ICMP_UNREACH_PROTOCOL: msg = "Protocol unreachable (firewall?)"; break;
250 case ICMP_UNREACH_PORT: msg = "Port unreachable (firewall?)"; break;
251 case ICMP_UNREACH_NEEDFRAG: msg = "Fragmentation needed"; break;
252 case ICMP_UNREACH_SRCFAIL: msg = "Source route failed"; break;
253 case ICMP_UNREACH_ISOLATED: msg = "Source host isolated"; break;
254 case ICMP_UNREACH_NET_UNKNOWN: msg = "Unknown network"; break;
255 case ICMP_UNREACH_HOST_UNKNOWN: msg = "Unknown host"; break;
256 case ICMP_UNREACH_NET_PROHIB: msg = "Network denied (firewall?)"; break;
257 case ICMP_UNREACH_HOST_PROHIB: msg = "Host denied (firewall?)"; break;
258 case ICMP_UNREACH_TOSNET: msg = "Bad TOS for network (firewall?)"; break;
259 case ICMP_UNREACH_TOSHOST: msg = "Bad TOS for host (firewall?)"; break;
260 case ICMP_UNREACH_FILTER_PROHIB: msg = "Prohibited by filter (firewall)"; break;
261 case ICMP_UNREACH_HOST_PRECEDENCE: msg = "Host precedence violation"; break;
262 case ICMP_UNREACH_PRECEDENCE_CUTOFF: msg = "Precedence cutoff"; break;
263 default: msg = "Invalid code"; break;
264 }
265 break;
267 case ICMP_TIMXCEED:
268 /* really 'out of reach', or non-existant host behind a router serving
269 * two different subnets */
270 switch(icmp_code) {
271 case ICMP_TIMXCEED_INTRANS: msg = "Time to live exceeded in transit"; break;
272 case ICMP_TIMXCEED_REASS: msg = "Fragment reassembly time exceeded"; break;
273 default: msg = "Invalid code"; break;
274 }
275 break;
277 case ICMP_SOURCEQUENCH: msg = "Transmitting too fast"; break;
278 case ICMP_REDIRECT: msg = "Redirect (change route)"; break;
279 case ICMP_PARAMPROB: msg = "Bad IP header (required option absent)"; break;
281 /* the following aren't error messages, so ignore */
282 case ICMP_TSTAMP:
283 case ICMP_TSTAMPREPLY:
284 case ICMP_IREQ:
285 case ICMP_IREQREPLY:
286 case ICMP_MASKREQ:
287 case ICMP_MASKREPLY:
288 default: msg = ""; break;
289 }
291 return msg;
292 }
294 static int
295 handle_random_icmp(struct icmp *p, struct sockaddr_in *addr)
296 {
297 struct icmp *sent_icmp = NULL;
298 struct rta_host *host = NULL;
299 unsigned char *ptr;
301 if(p->icmp_type == ICMP_ECHO && p->icmp_id == pid) {
302 /* echo request from us to us (pinging localhost) */
303 return 0;
304 }
306 ptr = (unsigned char *)p;
307 if(debug) printf("handle_random_icmp(%p, %p)\n", (void *)p, (void *)addr);
309 /* only handle a few types, since others can't possibly be replies to
310 * us in a sane network (if it is anyway, it will be counted as lost
311 * at summary time, but not as quickly as a proper response */
312 /* TIMXCEED can be an unreach from a router with multiple IP's which
313 * serves two different subnets on the same interface and a dead host
314 * on one net is pinged from the other. The router will respond to
315 * itself and thus set TTL=0 so as to not loop forever. Even when
316 * TIMXCEED actually sends a proper icmp response we will have passed
317 * too many hops to have a hope of reaching it later, in which case it
318 * indicates overconfidence in the network, poor routing or both. */
319 if(p->icmp_type != ICMP_UNREACH && p->icmp_type != ICMP_TIMXCEED &&
320 p->icmp_type != ICMP_SOURCEQUENCH && p->icmp_type != ICMP_PARAMPROB)
321 {
322 return 0;
323 }
325 /* might be for us. At least it holds the original package (according
326 * to RFC 792). If it isn't, just ignore it */
327 sent_icmp = (struct icmp *)(ptr + 28);
328 if(sent_icmp->icmp_type != ICMP_ECHO || sent_icmp->icmp_id != pid ||
329 sent_icmp->icmp_seq >= targets)
330 {
331 if(debug) printf("Packet is no response to a packet we sent\n");
332 return 0;
333 }
335 /* it is indeed a response for us */
336 host = table[sent_icmp->icmp_seq];
337 if(debug) {
338 printf("Received \"%s\" from %s for ICMP ECHO sent to %s.\n",
339 get_icmp_error_msg(p->icmp_type, p->icmp_code),
340 inet_ntoa(addr->sin_addr), host->name);
341 }
343 icmp_lost++;
344 host->icmp_lost++;
345 /* don't spend time on lost hosts any more */
346 if(host->flags & FLAG_LOST_CAUSE) return 0;
348 /* source quench means we're sending too fast, so increase the
349 * interval and mark this packet lost */
350 if(p->icmp_type == ICMP_SOURCEQUENCH) {
351 pkt_interval *= pkt_backoff_factor;
352 target_interval *= target_backoff_factor;
353 }
354 else {
355 targets_down++;
356 host->flags |= FLAG_LOST_CAUSE;
357 }
358 host->icmp_type = p->icmp_type;
359 host->icmp_code = p->icmp_code;
360 host->error_addr.s_addr = addr->sin_addr.s_addr;
362 return 0;
363 }
365 int
366 main(int argc, char **argv)
367 {
368 int i;
369 char *ptr;
370 long int arg;
371 int icmp_sockerrno, udp_sockerrno, tcp_sockerrno;
372 int result;
373 struct rta_host *host;
375 /* we only need to be setsuid when we get the sockets, so do
376 * that before pointer magic (esp. on network data) */
377 icmp_sockerrno = udp_sockerrno = tcp_sockerrno = sockets = 0;
379 if((icmp_sock = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP)) != -1)
380 sockets |= HAVE_ICMP;
381 else icmp_sockerrno = errno;
383 /* if((udp_sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1) */
384 /* sockets |= HAVE_UDP; */
385 /* else udp_sockerrno = errno; */
387 /* if((tcp_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) != -1) */
388 /* sockets |= HAVE_TCP; */
389 /* else tcp_sockerrno = errno; */
391 /* now drop privileges (no effect if not setsuid or geteuid() == 0) */
392 setuid(getuid());
394 /* POSIXLY_CORRECT might break things, so unset it (the portable way) */
395 environ = NULL;
397 /* use the pid to mark packets as ours */
398 pid = getpid();
399 /* printf("pid = %u\n", pid); */
401 /* get calling name the old-fashioned way for portability instead
402 * of relying on the glibc-ism __progname */
403 ptr = strrchr(argv[0], '/');
404 if(ptr) progname = &ptr[1];
405 else progname = argv[0];
407 /* now set defaults. Use progname to set them initially (allows for
408 * superfast check_host program when target host is up */
409 cursor = list = NULL;
410 table = NULL;
412 mode = MODE_RTA;
413 crit.rta = 500000;
414 crit.pl = 80;
415 warn.rta = 200000;
416 warn.pl = 40;
417 protocols = HAVE_ICMP | HAVE_UDP | HAVE_TCP;
418 pkt_interval = 80000; /* 80 msec packet interval by default */
419 packets = 5;
421 if(!strcmp(progname, "check_icmp") || !strcmp(progname, "check_ping")) {
422 mode = MODE_ICMP;
423 protocols = HAVE_ICMP;
424 }
425 else if(!strcmp(progname, "check_host")) {
426 mode = MODE_HOSTCHECK;
427 pkt_interval = 1000000;
428 packets = 5;
429 crit.rta = warn.rta = 1000000;
430 crit.pl = warn.pl = 100;
431 }
432 else if(!strcmp(progname, "check_rta_multi")) {
433 mode = MODE_ALL;
434 target_interval = 0;
435 pkt_interval = 50000;
436 packets = 5;
437 }
439 /* parse the arguments */
440 for(i = 1; i < argc; i++) {
441 while((arg = getopt(argc, argv, "vhVw:c:n:p:t:H:i:b:I:l:m:")) != EOF) {
442 switch(arg) {
443 case 'v':
444 debug++;
445 break;
446 case 'b':
447 /* silently ignored for now */
448 break;
449 case 'i':
450 pkt_interval = get_timevar(optarg);
451 break;
452 case 'I':
453 target_interval = get_timevar(optarg);
454 break;
455 case 'w':
456 get_threshold(optarg, &warn);
457 break;
458 case 'c':
459 get_threshold(optarg, &crit);
460 break;
461 case 'n':
462 case 'p':
463 packets = strtoul(optarg, NULL, 0);
464 break;
465 case 't':
466 timeout = strtoul(optarg, NULL, 0);
467 if(!timeout) timeout = 10;
468 break;
469 case 'H':
470 add_target(optarg);
471 break;
472 case 'l':
473 ttl = (unsigned char)strtoul(optarg, NULL, 0);
474 break;
475 case 'm':
476 min_hosts_alive = (int)strtoul(optarg, NULL, 0);
477 break;
478 case 'd': /* implement later, for cluster checks */
479 warn_down = (unsigned char)strtoul(optarg, &ptr, 0);
480 if(ptr) {
481 crit_down = (unsigned char)strtoul(ptr + 1, NULL, 0);
482 }
483 break;
484 case 'V': /* version */
485 /*print_revision (progname, revision);*/ /* FIXME: Why? */
486 exit (STATE_OK);
487 case 'h': /* help */
488 print_help ();
489 exit (STATE_OK);
490 }
491 }
492 }
494 argv = &argv[optind];
495 while(*argv) {
496 add_target(*argv);
497 argv++;
498 }
499 if(!targets) {
500 errno = 0;
501 crash("No hosts to check");
502 exit(3);
503 }
505 if(!sockets) {
506 if(icmp_sock == -1) {
507 errno = icmp_sockerrno;
508 crash("Failed to obtain ICMP socket");
509 return -1;
510 }
511 /* if(udp_sock == -1) { */
512 /* errno = icmp_sockerrno; */
513 /* crash("Failed to obtain UDP socket"); */
514 /* return -1; */
515 /* } */
516 /* if(tcp_sock == -1) { */
517 /* errno = icmp_sockerrno; */
518 /* crash("Failed to obtain TCP socker"); */
519 /* return -1; */
520 /* } */
521 }
522 if(!ttl) ttl = 64;
524 if(icmp_sock) {
525 result = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
526 if(debug) {
527 if(result == -1) printf("setsockopt failed\n");
528 else printf("ttl set to %u\n", ttl);
529 }
530 }
532 /* stupid users should be able to give whatever thresholds they want
533 * (nothing will break if they do), but some anal plugin maintainer
534 * will probably add some printf() thing here later, so it might be
535 * best to at least show them where to do it. ;) */
536 if(warn.pl > crit.pl) warn.pl = crit.pl;
537 if(warn.rta > crit.rta) warn.rta = crit.rta;
538 if(warn_down > crit_down) crit_down = warn_down;
540 signal(SIGINT, finish);
541 signal(SIGHUP, finish);
542 signal(SIGTERM, finish);
543 signal(SIGALRM, finish);
544 if(debug) printf("Setting alarm timeout to %u seconds\n", timeout);
545 alarm(timeout);
547 /* make sure we don't wait any longer than necessary */
548 gettimeofday(&prog_start, &tz);
549 max_completion_time =
550 ((targets * packets * pkt_interval) + (targets * target_interval)) +
551 (targets * packets * crit.rta) + crit.rta;
553 if(debug) {
554 printf("packets: %u, targets: %u\n"
555 "target_interval: %0.3f, pkt_interval %0.3f\n"
556 "crit.rta: %0.3f\n"
557 "max_completion_time: %0.3f\n",
558 packets, targets,
559 (float)target_interval / 1000, (float)pkt_interval / 1000,
560 (float)crit.rta / 1000,
561 (float)max_completion_time / 1000);
562 }
564 if(debug) {
565 if(max_completion_time > (u_int)timeout * 1000000) {
566 printf("max_completion_time: %llu timeout: %u\n",
567 max_completion_time, timeout);
568 printf("Timout must be at lest %llu\n",
569 max_completion_time / 1000000 + 1);
570 }
571 }
573 icmp_pkt_size = icmp_data_size + ICMP_MINLEN;
574 if(debug > 2) printf("icmp_pkt_size = %u\n", icmp_pkt_size);
575 if(icmp_pkt_size < sizeof(struct icmp) + sizeof(struct icmp_ping_data)) {
576 icmp_pkt_size = sizeof(struct icmp) + sizeof(struct icmp_ping_data);
577 }
578 if(debug > 2) printf("icmp_pkt_size = %u\n", icmp_pkt_size);
580 if(debug) {
581 printf("crit = {%u, %u%%}, warn = {%u, %u%%}\n",
582 crit.rta, crit.pl, warn.rta, warn.pl);
583 printf("pkt_interval: %u target_interval: %u retry_interval: %u\n",
584 pkt_interval, target_interval, retry_interval);
585 printf("icmp_pkt_size: %u timeout: %u\n",
586 icmp_pkt_size, timeout);
587 }
589 if(packets > 20) {
590 errno = 0;
591 crash("packets is > 20 (%d)", packets);
592 }
594 if(min_hosts_alive < -1) {
595 errno = 0;
596 crash("minimum alive hosts is negative (%i)", min_hosts_alive);
597 }
599 host = list;
600 table = malloc(sizeof(struct rta_host **) * (argc - 1));
601 i = 0;
602 while(host) {
603 host->id = i;
604 table[i] = host;
605 host = host->next;
606 i++;
607 }
609 run_checks();
611 errno = 0;
612 finish(0);
614 return(0);
615 }
617 static void
618 run_checks()
619 {
620 u_int i, t, result;
621 u_int final_wait, time_passed;
623 /* this loop might actually violate the pkt_interval or target_interval
624 * settings, but only if there aren't any packets on the wire which
625 * indicates that the target can handle an increased packet rate */
626 for(i = 0; i < packets; i++) {
627 for(t = 0; t < targets; t++) {
628 /* don't send useless packets */
629 if(!targets_alive) finish(0);
630 if(table[t]->flags & FLAG_LOST_CAUSE) {
631 if(debug) printf("%s is a lost cause. not sending any more\n",
632 table[t]->name);
633 continue;
634 }
636 /* we're still in the game, so send next packet */
637 (void)send_icmp_ping(icmp_sock, table[t]);
638 result = wait_for_reply(icmp_sock, target_interval);
639 }
640 result = wait_for_reply(icmp_sock, pkt_interval * targets);
641 }
643 if(icmp_pkts_en_route && targets_alive) {
644 time_passed = get_timevaldiff(NULL, NULL);
645 final_wait = max_completion_time - time_passed;
647 if(debug) {
648 printf("time_passed: %u final_wait: %u max_completion_time: %llu\n",
649 time_passed, final_wait, max_completion_time);
650 }
651 if(time_passed > max_completion_time) {
652 if(debug) printf("Time passed. Finishing up\n");
653 finish(0);
654 }
656 /* catch the packets that might come in within the timeframe, but
657 * haven't yet */
658 if(debug) printf("Waiting for %u micro-seconds (%0.3f msecs)\n",
659 final_wait, (float)final_wait / 1000);
660 result = wait_for_reply(icmp_sock, final_wait);
661 }
662 }
664 /* response structure:
665 * ip header : 20 bytes
666 * icmp header : 28 bytes
667 * icmp echo reply : the rest
668 */
669 static int
670 wait_for_reply(int sock, u_int t)
671 {
672 int n, hlen;
673 static char buf[4096];
674 struct sockaddr_in resp_addr;
675 struct ip *ip;
676 struct icmp *icp, *sent_icmp;
677 struct rta_host *host;
678 struct icmp_ping_data *data;
679 struct timeval wait_start, now;
680 u_int tdiff, i, per_pkt_wait;
682 /* if we can't listen or don't have anything to listen to, just return */
683 if(!t || !icmp_pkts_en_route) return 0;
685 gettimeofday(&wait_start, &tz);
687 i = t;
688 per_pkt_wait = t / icmp_pkts_en_route;
689 while(icmp_pkts_en_route && get_timevaldiff(&wait_start, NULL) < i) {
690 t = per_pkt_wait;
692 /* wrap up if all targets are declared dead */
693 if(!targets_alive ||
694 get_timevaldiff(&prog_start, NULL) >= max_completion_time ||
695 (mode == MODE_HOSTCHECK && targets_down))
696 {
697 finish(0);
698 }
700 /* reap responses until we hit a timeout */
701 n = recvfrom_wto(sock, buf, sizeof(buf),
702 (struct sockaddr *)&resp_addr, &t);
703 if(!n) {
704 if(debug > 1) {
705 printf("recvfrom_wto() timed out during a %u usecs wait\n",
706 per_pkt_wait);
707 }
708 continue; /* timeout for this one, so keep trying */
709 }
710 if(n < 0) {
711 if(debug) printf("recvfrom_wto() returned errors\n");
712 return n;
713 }
715 ip = (struct ip *)buf;
716 if(debug > 1) printf("received %u bytes from %s\n",
717 ntohs(ip->ip_len), inet_ntoa(resp_addr.sin_addr));
719 /* obsolete. alpha on tru64 provides the necessary defines, but isn't broken */
720 /* #if defined( __alpha__ ) && __STDC__ && !defined( __GLIBC__ ) */
721 /* alpha headers are decidedly broken. Using an ansi compiler,
722 * they provide ip_vhl instead of ip_hl and ip_v, so we mask
723 * off the bottom 4 bits */
724 /* hlen = (ip->ip_vhl & 0x0f) << 2; */
725 /* #else */
726 hlen = ip->ip_hl << 2;
727 /* #endif */
729 if(n < (hlen + ICMP_MINLEN)) {
730 crash("received packet too short for ICMP (%d bytes, expected %d) from %s\n",
731 n, hlen + icmp_pkt_size, inet_ntoa(resp_addr.sin_addr));
732 }
733 /* else if(debug) { */
734 /* printf("ip header size: %u, packet size: %u (expected %u, %u)\n", */
735 /* hlen, ntohs(ip->ip_len) - hlen, */
736 /* sizeof(struct ip), icmp_pkt_size); */
737 /* } */
739 /* check the response */
740 icp = (struct icmp *)(buf + hlen);
741 sent_icmp = (struct icmp *)(buf + hlen + ICMP_MINLEN);
742 /* printf("buf: %p, icp: %p, distance: %u (expected %u)\n", */
743 /* buf, icp, */
744 /* (u_int)icp - (u_int)buf, hlen); */
745 /* printf("buf: %p, sent_icmp: %p, distance: %u (expected %u)\n", */
746 /* buf, sent_icmp, */
747 /* (u_int)sent_icmp - (u_int)buf, hlen + ICMP_MINLEN); */
749 if(icp->icmp_id != pid) {
750 handle_random_icmp(icp, &resp_addr);
751 continue;
752 }
754 if(icp->icmp_type != ICMP_ECHOREPLY || icp->icmp_seq >= targets) {
755 if(debug > 2) printf("not a proper ICMP_ECHOREPLY\n");
756 handle_random_icmp(icp, &resp_addr);
757 continue;
758 }
760 /* this is indeed a valid response */
761 data = (struct icmp_ping_data *)(icp->icmp_data);
763 host = table[icp->icmp_seq];
764 gettimeofday(&now, &tz);
765 tdiff = get_timevaldiff(&data->stime, &now);
767 host->time_waited += tdiff;
768 host->icmp_recv++;
769 icmp_recv++;
771 if(debug) {
772 printf("%0.3f ms rtt from %s, outgoing ttl: %u, incoming ttl: %u\n",
773 (float)tdiff / 1000, inet_ntoa(resp_addr.sin_addr),
774 ttl, ip->ip_ttl);
775 }
777 /* if we're in hostcheck mode, exit with limited printouts */
778 if(mode == MODE_HOSTCHECK) {
779 printf("OK - %s responds to ICMP. Packet %u, rta %0.3fms|"
780 "pkt=%u;;0;%u rta=%0.3f;%0.3f;%0.3f;;\n",
781 host->name, icmp_recv, (float)tdiff / 1000,
782 icmp_recv, packets, (float)tdiff / 1000,
783 (float)warn.rta / 1000, (float)crit.rta / 1000);
784 exit(STATE_OK);
785 }
786 }
788 return 0;
789 }
791 /* the ping functions */
792 static int
793 send_icmp_ping(int sock, struct rta_host *host)
794 {
795 static char *buf = NULL; /* re-use so we prevent leaks */
796 long int len;
797 struct icmp *icp;
798 struct icmp_ping_data *data;
799 struct timeval tv;
800 struct sockaddr *addr;
803 if(sock == -1) {
804 errno = 0;
805 crash("Attempt to send on bogus socket");
806 return -1;
807 }
808 addr = (struct sockaddr *)&host->saddr_in;
810 if(!buf) {
811 buf = (char *)malloc(icmp_pkt_size + sizeof(struct ip));
812 if(!buf) {
813 crash("send_icmp_ping(): failed to malloc %d bytes for send buffer",
814 icmp_pkt_size);
815 return -1; /* might be reached if we're in debug mode */
816 }
817 }
818 memset(buf, 0, icmp_pkt_size + sizeof(struct ip));
820 if((gettimeofday(&tv, &tz)) == -1) return -1;
822 icp = (struct icmp *)buf;
823 icp->icmp_type = ICMP_ECHO;
824 icp->icmp_code = 0;
825 icp->icmp_cksum = 0;
826 icp->icmp_id = pid;
827 icp->icmp_seq = host->id;
828 data = (struct icmp_ping_data *)icp->icmp_data;
829 data->ping_id = 10; /* host->icmp.icmp_sent; */
830 memcpy(&data->stime, &tv, sizeof(struct timeval));
831 icp->icmp_cksum = icmp_checksum((u_short *)icp, icmp_pkt_size);
833 len = sendto(sock, buf, icmp_pkt_size, 0, (struct sockaddr *)addr,
834 sizeof(struct sockaddr));
836 if(len < 0 || (unsigned int)len != icmp_pkt_size) {
837 if(debug) printf("Failed to send ping to %s\n",
838 inet_ntoa(host->saddr_in.sin_addr));
839 return -1;
840 }
842 icmp_sent++;
843 host->icmp_sent++;
845 return 0;
846 }
848 static int
849 recvfrom_wto(int sock, char *buf, unsigned int len, struct sockaddr *saddr,
850 u_int *timo)
851 {
852 u_int slen;
853 int n;
854 struct timeval to, then, now;
855 fd_set rd, wr;
857 if(!*timo) {
858 if(debug) printf("*timo is not\n");
859 return 0;
860 }
862 to.tv_sec = *timo / 1000000;
863 to.tv_usec = (*timo - (to.tv_sec * 1000000));
865 FD_ZERO(&rd);
866 FD_ZERO(&wr);
867 FD_SET(sock, &rd);
868 errno = 0;
869 gettimeofday(&then, &tz);
870 n = select(sock + 1, &rd, &wr, NULL, &to);
871 if(n < 0) crash("select() in recvfrom_wto");
872 gettimeofday(&now, &tz);
873 *timo = get_timevaldiff(&then, &now);
875 if(!n) return 0; /* timeout */
877 slen = sizeof(struct sockaddr);
879 return recvfrom(sock, buf, len, 0, saddr, &slen);
880 }
882 static void
883 finish(int sig)
884 {
885 u_int i = 0;
886 unsigned char pl;
887 double rta;
888 struct rta_host *host;
889 char *status_string[] =
890 {"OK", "WARNING", "CRITICAL", "UNKNOWN", "DEPENDENT"};
891 int hosts_ok = 0;
892 int hosts_warn = 0;
894 alarm(0);
895 if(debug > 1) printf("finish(%d) called\n", sig);
897 if(icmp_sock != -1) close(icmp_sock);
898 if(udp_sock != -1) close(udp_sock);
899 if(tcp_sock != -1) close(tcp_sock);
901 if(debug) {
902 printf("icmp_sent: %u icmp_recv: %u icmp_lost: %u\n",
903 icmp_sent, icmp_recv, icmp_lost);
904 printf("targets: %u targets_alive: %u\n", targets, targets_alive);
905 }
907 /* iterate thrice to calculate values, give output, and print perfparse */
908 host = list;
909 while(host) {
910 if(!host->icmp_recv) {
911 /* rta 0 is ofcourse not entirely correct, but will still show up
912 * conspicuosly as missing entries in perfparse and cacti */
913 pl = 100;
914 rta = 0;
915 status = STATE_CRITICAL;
916 /* up the down counter if not already counted */
917 if(!(host->flags & FLAG_LOST_CAUSE) && targets_alive) targets_down++;
918 }
919 else {
920 pl = ((host->icmp_sent - host->icmp_recv) * 100) / host->icmp_sent;
921 rta = (double)host->time_waited / host->icmp_recv;
922 }
923 host->pl = pl;
924 host->rta = rta;
925 if(pl >= crit.pl || rta >= crit.rta) {
926 status = STATE_CRITICAL;
927 }
928 else if(!status && (pl >= warn.pl || rta >= warn.rta)) {
929 status = STATE_WARNING;
930 hosts_warn++;
931 }
932 else {
933 hosts_ok++;
934 }
936 host = host->next;
937 }
938 /* this is inevitable */
939 if(!targets_alive) status = STATE_CRITICAL;
940 if(min_hosts_alive > -1) {
941 if(hosts_ok >= min_hosts_alive) status = STATE_OK;
942 else if((hosts_ok + hosts_warn) >= min_hosts_alive) status = STATE_WARNING;
943 }
944 printf("%s - ", status_string[status]);
946 host = list;
947 while(host) {
948 if(debug) puts("");
949 if(i) {
950 if(i < targets) printf(" :: ");
951 else printf("\n");
952 }
953 i++;
954 if(!host->icmp_recv) {
955 status = STATE_CRITICAL;
956 if(host->flags & FLAG_LOST_CAUSE) {
957 printf("%s: %s @ %s. rta nan, lost %d%%",
958 host->name,
959 get_icmp_error_msg(host->icmp_type, host->icmp_code),
960 inet_ntoa(host->error_addr),
961 100);
962 }
963 else { /* not marked as lost cause, so we have no flags for it */
964 printf("%s: rta nan, lost 100%%", host->name);
965 }
966 }
967 else { /* !icmp_recv */
968 printf("%s: rta %0.3fms, lost %u%%",
969 host->name, host->rta / 1000, host->pl);
970 }
972 host = host->next;
973 }
975 /* iterate once more for pretty perfparse output */
976 printf("|");
977 i = 0;
978 host = list;
979 while(host) {
980 if(debug) puts("");
981 printf("%srta=%0.3fms;%0.3f;%0.3f;0; %spl=%u%%;%u;%u;; ",
982 (targets > 1) ? host->name : "",
983 host->rta / 1000, (float)warn.rta / 1000, (float)crit.rta / 1000,
984 (targets > 1) ? host->name : "",
985 host->pl, warn.pl, crit.pl);
987 host = host->next;
988 }
990 if(min_hosts_alive > -1) {
991 if(hosts_ok >= min_hosts_alive) status = STATE_OK;
992 else if((hosts_ok + hosts_warn) >= min_hosts_alive) status = STATE_WARNING;
993 }
995 /* finish with an empty line */
996 puts("");
997 if(debug) printf("targets: %u, targets_alive: %u, hosts_ok: %u, hosts_warn: %u, min_hosts_alive: %i\n",
998 targets, targets_alive, hosts_ok, hosts_warn, min_hosts_alive);
1000 exit(status);
1001 }
1003 static u_int
1004 get_timevaldiff(struct timeval *early, struct timeval *later)
1005 {
1006 u_int ret;
1007 struct timeval now;
1009 if(!later) {
1010 gettimeofday(&now, &tz);
1011 later = &now;
1012 }
1013 if(!early) early = &prog_start;
1015 /* if early > later we return 0 so as to indicate a timeout */
1016 if(early->tv_sec > early->tv_sec ||
1017 (early->tv_sec == later->tv_sec && early->tv_usec > later->tv_usec))
1018 {
1019 return 0;
1020 }
1022 ret = (later->tv_sec - early->tv_sec) * 1000000;
1023 ret += later->tv_usec - early->tv_usec;
1025 return ret;
1026 }
1028 static int
1029 add_target_ip(char *arg, struct in_addr *in)
1030 {
1031 struct rta_host *host;
1033 /* disregard obviously stupid addresses */
1034 if(in->s_addr == INADDR_NONE || in->s_addr == INADDR_ANY)
1035 return -1;
1037 /* no point in adding two identical IP's, so don't. ;) */
1038 host = list;
1039 while(host) {
1040 if(host->saddr_in.sin_addr.s_addr == in->s_addr) {
1041 if(debug) printf("Identical IP already exists. Not adding %s\n", arg);
1042 return -1;
1043 }
1044 host = host->next;
1045 }
1047 /* add the fresh ip */
1048 host = malloc(sizeof(struct rta_host));
1049 if(!host) {
1050 crash("add_target_ip(%s, %s): malloc(%d) failed",
1051 arg, inet_ntoa(*in), sizeof(struct rta_host));
1052 }
1053 memset(host, 0, sizeof(struct rta_host));
1055 /* set the values. use calling name for output */
1056 host->name = strdup(arg);
1058 /* fill out the sockaddr_in struct */
1059 host->saddr_in.sin_family = AF_INET;
1060 host->saddr_in.sin_addr.s_addr = in->s_addr;
1062 if(!list) list = cursor = host;
1063 else cursor->next = host;
1065 cursor = host;
1066 targets++;
1068 return 0;
1069 }
1071 /* wrapper for add_target_ip */
1072 static int
1073 add_target(char *arg)
1074 {
1075 int i;
1076 struct hostent *he;
1077 struct in_addr *in, ip;
1079 /* don't resolve if we don't have to */
1080 if((ip.s_addr = inet_addr(arg)) != INADDR_NONE) {
1081 /* don't add all ip's if we were given a specific one */
1082 return add_target_ip(arg, &ip);
1083 /* he = gethostbyaddr((char *)in, sizeof(struct in_addr), AF_INET); */
1084 /* if(!he) return add_target_ip(arg, in); */
1085 }
1086 else {
1087 errno = 0;
1088 he = gethostbyname(arg);
1089 if(!he) {
1090 errno = 0;
1091 crash("Failed to resolve %s", arg);
1092 return -1;
1093 }
1094 }
1096 /* possibly add all the IP's as targets */
1097 for(i = 0; he->h_addr_list[i]; i++) {
1098 in = (struct in_addr *)he->h_addr_list[i];
1099 add_target_ip(arg, in);
1101 /* this is silly, but it works */
1102 if(mode == MODE_HOSTCHECK || mode == MODE_ALL) {
1103 printf("mode: %d\n", mode);
1104 continue;
1105 }
1106 break;
1107 }
1109 return 0;
1110 }
1111 /*
1112 * u = micro
1113 * m = milli
1114 * s = seconds
1115 * return value is in microseconds
1116 */
1117 static u_int
1118 get_timevar(const char *str)
1119 {
1120 char p, u, *ptr;
1121 unsigned int len;
1122 u_int i, d; /* integer and decimal, respectively */
1123 u_int factor = 1000; /* default to milliseconds */
1125 if(!str) return 0;
1126 len = strlen(str);
1127 if(!len) return 0;
1129 /* unit might be given as ms|m (millisec),
1130 * us|u (microsec) or just plain s, for seconds */
1131 u = p = '\0';
1132 u = str[len - 1];
1133 if(len >= 2 && !isdigit((int)str[len - 2])) p = str[len - 2];
1134 if(p && u == 's') u = p;
1135 else if(!p) p = u;
1136 if(debug > 2) printf("evaluating %s, u: %c, p: %c\n", str, u, p);
1138 if(u == 'u') factor = 1; /* microseconds */
1139 else if(u == 'm') factor = 1000; /* milliseconds */
1140 else if(u == 's') factor = 1000000; /* seconds */
1141 if(debug > 2) printf("factor is %u\n", factor);
1143 i = strtoul(str, &ptr, 0);
1144 if(!ptr || *ptr != '.' || strlen(ptr) < 2 || factor == 1)
1145 return i * factor;
1147 /* time specified in usecs can't have decimal points, so ignore them */
1148 if(factor == 1) return i;
1150 d = strtoul(ptr + 1, NULL, 0);
1152 /* d is decimal, so get rid of excess digits */
1153 while(d >= factor) d /= 10;
1155 /* the last parenthesis avoids floating point exceptions. */
1156 return ((i * factor) + (d * (factor / 10)));
1157 }
1159 /* not too good at checking errors, but it'll do (main() should barfe on -1) */
1160 static int
1161 get_threshold(char *str, threshold *th)
1162 {
1163 char *p = NULL, i = 0;
1165 if(!str || !strlen(str) || !th) return -1;
1167 /* pointer magic slims code by 10 lines. i is bof-stop on stupid libc's */
1168 p = &str[strlen(str) - 1];
1169 while(p != &str[1]) {
1170 if(*p == '%') *p = '\0';
1171 else if(*p == ',' && i) {
1172 *p = '\0'; /* reset it so get_timevar(str) works nicely later */
1173 th->pl = (unsigned char)strtoul(p+1, NULL, 0);
1174 break;
1175 }
1176 i = 1;
1177 p--;
1178 }
1179 th->rta = get_timevar(str);
1181 if(!th->rta) return -1;
1183 if(th->rta > MAXTTL * 1000000) th->rta = MAXTTL * 1000000;
1184 if(th->pl > 100) th->pl = 100;
1186 return 0;
1187 }
1189 unsigned short
1190 icmp_checksum(unsigned short *p, int n)
1191 {
1192 register unsigned short cksum;
1193 register long sum = 0;
1195 while(n > 1) {
1196 sum += *p++;
1197 n -= 2;
1198 }
1200 /* mop up the occasional odd byte */
1201 if(n == 1) sum += (unsigned char)*p;
1203 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
1204 sum += (sum >> 16); /* add carry */
1205 cksum = ~sum; /* ones-complement, trunc to 16 bits */
1207 return cksum;
1208 }
1210 void
1211 print_help(void)
1212 {
1214 /*print_revision (progname, revision);*/ /* FIXME: Why? */
1216 printf ("Copyright (c) 2005 Andreas Ericsson <ae@op5.se>\n");
1217 printf (COPYRIGHT, copyright, email);
1219 printf ("\n\n");
1221 print_usage ();
1223 printf (_(UT_HELP_VRSN));
1225 printf (" %s\n", "-H");
1226 printf (" %s\n", _("specify a target"));
1227 printf (" %s\n", "-w");
1228 printf (" %s", _("warning threshold (currently "));
1229 printf ("%0.3fms,%u%%)\n", (float)warn.rta / 1000 , warn.pl / 1000);
1230 printf (" %s\n", "-c");
1231 printf (" %s", _("critical threshold (currently "));
1232 printf ("%0.3fms,%u%%)\n", (float)crit.rta, crit.pl);
1233 printf (" %s\n", "-n");
1234 printf (" %s", _("number of packets to send (currently "));
1235 printf ("%u)\n",packets);
1236 printf (" %s\n", "-i");
1237 printf (" %s", _("max packet interval (currently "));
1238 printf ("%0.3fms)\n",(float)pkt_interval / 1000);
1239 printf (" %s\n", "-I");
1240 printf (" %s", _("max target interval (currently "));
1241 printf ("%0.3fms)\n", (float)target_interval / 1000);
1242 printf (" %s\n", "-m");
1243 printf (" %s",_("number of alive hosts required for success"));
1244 printf ("\n");
1245 printf (" %s\n", "-l");
1246 printf (" %s", _("TTL on outgoing packets (currently "));
1247 printf ("%u)", ttl);
1248 printf (" %s\n", "-t");
1249 printf (" %s",_("timeout value (seconds, currently "));
1250 printf ("%u)\n", timeout);
1251 printf (" %s\n", "-b");
1252 printf (" %s\n", _("icmp packet size (currenly ignored)"));
1253 printf (" %s\n", "-v");
1254 printf (" %s\n", _("verbose"));
1256 printf ("\n");
1257 printf ("%s\n\n", _("The -H switch is optional. Naming a host (or several) to check is not."));
1258 printf ("%s\n", _("Threshold format for -w and -c is 200.25,60% for 200.25 msec RTA and 60%"));
1259 printf ("%s\n", _("packet loss. The default values should work well for most users."));
1260 printf ("%s\n", _("You can specify different RTA factors using the standardized abbreviations"));
1261 printf ("%s\n\n", _("us (microseconds), ms (milliseconds, default) or just plain s for seconds."));
1262 /* -d not yet implemented */
1263 /* printf ("%s\n", _("Threshold format for -d is warn,crit. 12,14 means WARNING if >= 12 hops"));
1264 printf ("%s\n", _("are spent and CRITICAL if >= 14 hops are spent."));
1265 printf ("%s\n\n", _("NOTE: Some systems decrease TTL when forming ICMP_ECHOREPLY, others do not."));*/
1266 printf ("%s\n\n", _("The -v switch can be specified several times for increased verbosity."));
1268 /* printf ("%s\n", _("Long options are currently unsupported."));
1269 printf ("%s\n", _("Options marked with * require an argument"));
1270 */
1271 printf (_(UT_SUPPORT));
1273 printf (_(UT_NOWARRANTY));
1274 }
1278 void
1279 print_usage (void)
1280 {
1281 printf (_("Usage:"));
1282 printf(" %s [options] [-H] host1 host2 hostn\n", progname);
1283 }