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/ioctl.h>
58 #include <sys/time.h>
59 #include <sys/types.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <stdarg.h>
63 #include <unistd.h>
64 #include <stddef.h>
65 #include <errno.h>
66 #include <string.h>
67 #include <ctype.h>
68 #include <netdb.h>
69 #include <sys/socket.h>
70 #include <net/if.h>
71 #include <netinet/in_systm.h>
72 #include <netinet/in.h>
73 #include <netinet/ip.h>
74 #include <netinet/ip_icmp.h>
75 #include <arpa/inet.h>
76 #include <signal.h>
79 /** sometimes undefined system macros (quite a few, actually) **/
80 #ifndef MAXTTL
81 # define MAXTTL 255
82 #endif
83 #ifndef INADDR_NONE
84 # define INADDR_NONE 0xffffffU
85 #endif
87 #ifndef SOL_IP
88 #define SOL_IP 0
89 #endif
91 /* we bundle these in one #ifndef, since they're all from BSD
92 * Put individual #ifndef's around those that bother you */
93 #ifndef ICMP_UNREACH_NET_UNKNOWN
94 # define ICMP_UNREACH_NET_UNKNOWN 6
95 # define ICMP_UNREACH_HOST_UNKNOWN 7
96 # define ICMP_UNREACH_ISOLATED 8
97 # define ICMP_UNREACH_NET_PROHIB 9
98 # define ICMP_UNREACH_HOST_PROHIB 10
99 # define ICMP_UNREACH_TOSNET 11
100 # define ICMP_UNREACH_TOSHOST 12
101 #endif
102 /* tru64 has the ones above, but not these */
103 #ifndef ICMP_UNREACH_FILTER_PROHIB
104 # define ICMP_UNREACH_FILTER_PROHIB 13
105 # define ICMP_UNREACH_HOST_PRECEDENCE 14
106 # define ICMP_UNREACH_PRECEDENCE_CUTOFF 15
107 #endif
110 typedef unsigned short range_t; /* type for get_range() -- unimplemented */
112 typedef struct rta_host {
113 unsigned short id; /* id in **table, and icmp pkts */
114 char *name; /* arg used for adding this host */
115 char *msg; /* icmp error message, if any */
116 struct sockaddr_in saddr_in; /* the address of this host */
117 struct in_addr error_addr; /* stores address of error replies */
118 unsigned long long time_waited; /* total time waited, in usecs */
119 unsigned int icmp_sent, icmp_recv, icmp_lost; /* counters */
120 unsigned char icmp_type, icmp_code; /* type and code from errors */
121 unsigned short flags; /* control/status flags */
122 double rta; /* measured RTA */
123 unsigned char pl; /* measured packet loss */
124 struct rta_host *next; /* linked list */
125 } rta_host;
127 #define FLAG_LOST_CAUSE 0x01 /* decidedly dead target. */
129 /* threshold structure. all values are maximum allowed, exclusive */
130 typedef struct threshold {
131 unsigned char pl; /* max allowed packet loss in percent */
132 unsigned int rta; /* roundtrip time average, microseconds */
133 } threshold;
135 /* the data structure */
136 typedef struct icmp_ping_data {
137 struct timeval stime; /* timestamp (saved in protocol struct as well) */
138 unsigned short ping_id;
139 } icmp_ping_data;
141 /* the different modes of this program are as follows:
142 * MODE_RTA: send all packets no matter what (mimic check_icmp and check_ping)
143 * MODE_HOSTCHECK: Return immediately upon any sign of life
144 * In addition, sends packets to ALL addresses assigned
145 * to this host (as returned by gethostbyname() or
146 * gethostbyaddr() and expects one host only to be checked at
147 * a time. Therefore, any packet response what so ever will
148 * count as a sign of life, even when received outside
149 * crit.rta limit. Do not misspell any additional IP's.
150 * MODE_ALL: Requires packets from ALL requested IP to return OK (default).
151 * MODE_ICMP: implement something similar to check_icmp (MODE_RTA without
152 * tcp and udp args does this)
153 */
154 #define MODE_RTA 0
155 #define MODE_HOSTCHECK 1
156 #define MODE_ALL 2
157 #define MODE_ICMP 3
159 /* the different ping types we can do
160 * TODO: investigate ARP ping as well */
161 #define HAVE_ICMP 1
162 #define HAVE_UDP 2
163 #define HAVE_TCP 4
164 #define HAVE_ARP 8
166 #define MIN_PING_DATA_SIZE sizeof(struct icmp_ping_data)
167 #define MAX_IP_PKT_SIZE 65536 /* (theoretical) max IP packet size */
168 #define IP_HDR_SIZE 20
169 #define MAX_PING_DATA (MAX_IP_PKT_SIZE - IP_HDR_SIZE - ICMP_MINLEN)
170 #define DEFAULT_PING_DATA_SIZE (MIN_PING_DATA_SIZE + 44)
172 /* various target states */
173 #define TSTATE_INACTIVE 0x01 /* don't ping this host anymore */
174 #define TSTATE_WAITING 0x02 /* unanswered packets on the wire */
175 #define TSTATE_ALIVE 0x04 /* target is alive (has answered something) */
176 #define TSTATE_UNREACH 0x08
178 /** prototypes **/
179 void print_help (void);
180 void print_usage (void);
181 static u_int get_timevar(const char *);
182 static u_int get_timevaldiff(struct timeval *, struct timeval *);
183 static in_addr_t get_ip_address(const char *);
184 static int wait_for_reply(int, u_int);
185 static int recvfrom_wto(int, char *, unsigned int, struct sockaddr *, u_int *);
186 static int send_icmp_ping(int, struct rta_host *);
187 static int get_threshold(char *str, threshold *th);
188 static void run_checks(void);
189 static void set_source_ip(char *);
190 static int add_target(char *);
191 static int add_target_ip(char *, struct in_addr *);
192 static int handle_random_icmp(struct icmp *, struct sockaddr_in *);
193 static unsigned short icmp_checksum(unsigned short *, int);
194 static void finish(int);
195 static void crash(const char *, ...);
197 /** external **/
198 extern int optind, opterr, optopt;
199 extern char *optarg;
200 extern char **environ;
202 /** global variables **/
203 static struct rta_host **table, *cursor, *list;
204 static threshold crit = {80, 500000}, warn = {40, 200000};
205 static int mode, protocols, sockets, debug = 0, timeout = 10;
206 static unsigned short icmp_pkt_size, icmp_data_size = DEFAULT_PING_DATA_SIZE;
207 static unsigned int icmp_sent = 0, icmp_recv = 0, icmp_lost = 0;
208 #define icmp_pkts_en_route (icmp_sent - (icmp_recv + icmp_lost))
209 static unsigned short targets_down = 0, targets = 0, packets = 0;
210 #define targets_alive (targets - targets_down)
211 static unsigned int retry_interval, pkt_interval, target_interval;
212 static int icmp_sock, tcp_sock, udp_sock, status = STATE_OK;
213 static pid_t pid;
214 static struct timezone tz;
215 static struct timeval prog_start;
216 static unsigned long long max_completion_time = 0;
217 static unsigned char ttl = 0; /* outgoing ttl */
218 static unsigned int warn_down = 1, crit_down = 1; /* host down threshold values */
219 static int min_hosts_alive = -1;
220 float pkt_backoff_factor = 1.5;
221 float target_backoff_factor = 1.5;
223 /** code start **/
224 static void
225 crash(const char *fmt, ...)
226 {
227 va_list ap;
229 printf("%s: ", progname);
231 va_start(ap, fmt);
232 vprintf(fmt, ap);
233 va_end(ap);
235 if(errno) printf(": %s", strerror(errno));
236 puts("");
238 exit(3);
239 }
242 static char *
243 get_icmp_error_msg(unsigned char icmp_type, unsigned char icmp_code)
244 {
245 char *msg = "unreachable";
247 if(debug > 1) printf("get_icmp_error_msg(%u, %u)\n", icmp_type, icmp_code);
248 switch(icmp_type) {
249 case ICMP_UNREACH:
250 switch(icmp_code) {
251 case ICMP_UNREACH_NET: msg = "Net unreachable"; break;
252 case ICMP_UNREACH_HOST: msg = "Host unreachable"; break;
253 case ICMP_UNREACH_PROTOCOL: msg = "Protocol unreachable (firewall?)"; break;
254 case ICMP_UNREACH_PORT: msg = "Port unreachable (firewall?)"; break;
255 case ICMP_UNREACH_NEEDFRAG: msg = "Fragmentation needed"; break;
256 case ICMP_UNREACH_SRCFAIL: msg = "Source route failed"; break;
257 case ICMP_UNREACH_ISOLATED: msg = "Source host isolated"; break;
258 case ICMP_UNREACH_NET_UNKNOWN: msg = "Unknown network"; break;
259 case ICMP_UNREACH_HOST_UNKNOWN: msg = "Unknown host"; break;
260 case ICMP_UNREACH_NET_PROHIB: msg = "Network denied (firewall?)"; break;
261 case ICMP_UNREACH_HOST_PROHIB: msg = "Host denied (firewall?)"; break;
262 case ICMP_UNREACH_TOSNET: msg = "Bad TOS for network (firewall?)"; break;
263 case ICMP_UNREACH_TOSHOST: msg = "Bad TOS for host (firewall?)"; break;
264 case ICMP_UNREACH_FILTER_PROHIB: msg = "Prohibited by filter (firewall)"; break;
265 case ICMP_UNREACH_HOST_PRECEDENCE: msg = "Host precedence violation"; break;
266 case ICMP_UNREACH_PRECEDENCE_CUTOFF: msg = "Precedence cutoff"; break;
267 default: msg = "Invalid code"; break;
268 }
269 break;
271 case ICMP_TIMXCEED:
272 /* really 'out of reach', or non-existant host behind a router serving
273 * two different subnets */
274 switch(icmp_code) {
275 case ICMP_TIMXCEED_INTRANS: msg = "Time to live exceeded in transit"; break;
276 case ICMP_TIMXCEED_REASS: msg = "Fragment reassembly time exceeded"; break;
277 default: msg = "Invalid code"; break;
278 }
279 break;
281 case ICMP_SOURCEQUENCH: msg = "Transmitting too fast"; break;
282 case ICMP_REDIRECT: msg = "Redirect (change route)"; break;
283 case ICMP_PARAMPROB: msg = "Bad IP header (required option absent)"; break;
285 /* the following aren't error messages, so ignore */
286 case ICMP_TSTAMP:
287 case ICMP_TSTAMPREPLY:
288 case ICMP_IREQ:
289 case ICMP_IREQREPLY:
290 case ICMP_MASKREQ:
291 case ICMP_MASKREPLY:
292 default: msg = ""; break;
293 }
295 return msg;
296 }
298 static int
299 handle_random_icmp(struct icmp *p, struct sockaddr_in *addr)
300 {
301 struct icmp sent_icmp;
302 struct rta_host *host = NULL;
303 unsigned char *ptr;
305 if(p->icmp_type == ICMP_ECHO && p->icmp_id == pid) {
306 /* echo request from us to us (pinging localhost) */
307 return 0;
308 }
310 ptr = (unsigned char *)p;
311 if(debug) printf("handle_random_icmp(%p, %p)\n", (void *)p, (void *)addr);
313 /* only handle a few types, since others can't possibly be replies to
314 * us in a sane network (if it is anyway, it will be counted as lost
315 * at summary time, but not as quickly as a proper response */
316 /* TIMXCEED can be an unreach from a router with multiple IP's which
317 * serves two different subnets on the same interface and a dead host
318 * on one net is pinged from the other. The router will respond to
319 * itself and thus set TTL=0 so as to not loop forever. Even when
320 * TIMXCEED actually sends a proper icmp response we will have passed
321 * too many hops to have a hope of reaching it later, in which case it
322 * indicates overconfidence in the network, poor routing or both. */
323 if(p->icmp_type != ICMP_UNREACH && p->icmp_type != ICMP_TIMXCEED &&
324 p->icmp_type != ICMP_SOURCEQUENCH && p->icmp_type != ICMP_PARAMPROB)
325 {
326 return 0;
327 }
329 /* might be for us. At least it holds the original package (according
330 * to RFC 792). If it isn't, just ignore it */
331 memcpy(&sent_icmp, ptr + 28, sizeof(sent_icmp));
332 if(sent_icmp.icmp_type != ICMP_ECHO || sent_icmp.icmp_id != pid ||
333 sent_icmp.icmp_seq >= targets)
334 {
335 if(debug) printf("Packet is no response to a packet we sent\n");
336 return 0;
337 }
339 /* it is indeed a response for us */
340 host = table[sent_icmp.icmp_seq];
341 if(debug) {
342 printf("Received \"%s\" from %s for ICMP ECHO sent to %s.\n",
343 get_icmp_error_msg(p->icmp_type, p->icmp_code),
344 inet_ntoa(addr->sin_addr), host->name);
345 }
347 icmp_lost++;
348 host->icmp_lost++;
349 /* don't spend time on lost hosts any more */
350 if(host->flags & FLAG_LOST_CAUSE) return 0;
352 /* source quench means we're sending too fast, so increase the
353 * interval and mark this packet lost */
354 if(p->icmp_type == ICMP_SOURCEQUENCH) {
355 pkt_interval *= pkt_backoff_factor;
356 target_interval *= target_backoff_factor;
357 }
358 else {
359 targets_down++;
360 host->flags |= FLAG_LOST_CAUSE;
361 }
362 host->icmp_type = p->icmp_type;
363 host->icmp_code = p->icmp_code;
364 host->error_addr.s_addr = addr->sin_addr.s_addr;
366 return 0;
367 }
369 int
370 main(int argc, char **argv)
371 {
372 int i;
373 char *ptr;
374 long int arg;
375 int icmp_sockerrno, udp_sockerrno, tcp_sockerrno;
376 int result;
377 struct rta_host *host;
379 setlocale (LC_ALL, "");
380 bindtextdomain (PACKAGE, LOCALEDIR);
381 textdomain (PACKAGE);
383 /* print a helpful error message if geteuid != 0 */
384 np_warn_if_not_root();
386 /* we only need to be setsuid when we get the sockets, so do
387 * that before pointer magic (esp. on network data) */
388 icmp_sockerrno = udp_sockerrno = tcp_sockerrno = sockets = 0;
390 if((icmp_sock = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP)) != -1)
391 sockets |= HAVE_ICMP;
392 else icmp_sockerrno = errno;
394 /* if((udp_sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1) */
395 /* sockets |= HAVE_UDP; */
396 /* else udp_sockerrno = errno; */
398 /* if((tcp_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) != -1) */
399 /* sockets |= HAVE_TCP; */
400 /* else tcp_sockerrno = errno; */
402 /* now drop privileges (no effect if not setsuid or geteuid() == 0) */
403 setuid(getuid());
405 /* POSIXLY_CORRECT might break things, so unset it (the portable way) */
406 environ = NULL;
408 /* use the pid to mark packets as ours */
409 /* Some systems have 32-bit pid_t so mask off only 16 bits */
410 pid = getpid() & 0xffff;
411 /* printf("pid = %u\n", pid); */
413 /* get calling name the old-fashioned way for portability instead
414 * of relying on the glibc-ism __progname */
415 ptr = strrchr(argv[0], '/');
416 if(ptr) progname = &ptr[1];
417 else progname = argv[0];
419 /* now set defaults. Use progname to set them initially (allows for
420 * superfast check_host program when target host is up */
421 cursor = list = NULL;
422 table = NULL;
424 mode = MODE_RTA;
425 crit.rta = 500000;
426 crit.pl = 80;
427 warn.rta = 200000;
428 warn.pl = 40;
429 protocols = HAVE_ICMP | HAVE_UDP | HAVE_TCP;
430 pkt_interval = 80000; /* 80 msec packet interval by default */
431 packets = 5;
433 if(!strcmp(progname, "check_icmp") || !strcmp(progname, "check_ping")) {
434 mode = MODE_ICMP;
435 protocols = HAVE_ICMP;
436 }
437 else if(!strcmp(progname, "check_host")) {
438 mode = MODE_HOSTCHECK;
439 pkt_interval = 1000000;
440 packets = 5;
441 crit.rta = warn.rta = 1000000;
442 crit.pl = warn.pl = 100;
443 }
444 else if(!strcmp(progname, "check_rta_multi")) {
445 mode = MODE_ALL;
446 target_interval = 0;
447 pkt_interval = 50000;
448 packets = 5;
449 }
451 /* parse the arguments */
452 for(i = 1; i < argc; i++) {
453 while((arg = getopt(argc, argv, "vhVw:c:n:p:t:H:s:i:b:I:l:m:")) != EOF) {
454 switch(arg) {
455 case 'v':
456 debug++;
457 break;
458 case 'b':
459 /* silently ignored for now */
460 break;
461 case 'i':
462 pkt_interval = get_timevar(optarg);
463 break;
464 case 'I':
465 target_interval = get_timevar(optarg);
466 break;
467 case 'w':
468 get_threshold(optarg, &warn);
469 break;
470 case 'c':
471 get_threshold(optarg, &crit);
472 break;
473 case 'n':
474 case 'p':
475 packets = strtoul(optarg, NULL, 0);
476 break;
477 case 't':
478 timeout = strtoul(optarg, NULL, 0);
479 if(!timeout) timeout = 10;
480 break;
481 case 'H':
482 add_target(optarg);
483 break;
484 case 'l':
485 ttl = (unsigned char)strtoul(optarg, NULL, 0);
486 break;
487 case 'm':
488 min_hosts_alive = (int)strtoul(optarg, NULL, 0);
489 break;
490 case 'd': /* implement later, for cluster checks */
491 warn_down = (unsigned char)strtoul(optarg, &ptr, 0);
492 if(ptr) {
493 crit_down = (unsigned char)strtoul(ptr + 1, NULL, 0);
494 }
495 break;
496 case 's': /* specify source IP address */
497 set_source_ip(optarg);
498 break;
499 case 'V': /* version */
500 /*print_revision (progname, revision);*/ /* FIXME: Why? */
501 exit (STATE_OK);
502 case 'h': /* help */
503 print_help ();
504 exit (STATE_OK);
505 }
506 }
507 }
509 argv = &argv[optind];
510 while(*argv) {
511 add_target(*argv);
512 argv++;
513 }
514 if(!targets) {
515 errno = 0;
516 crash("No hosts to check");
517 exit(3);
518 }
520 if(!sockets) {
521 if(icmp_sock == -1) {
522 errno = icmp_sockerrno;
523 crash("Failed to obtain ICMP socket");
524 return -1;
525 }
526 /* if(udp_sock == -1) { */
527 /* errno = icmp_sockerrno; */
528 /* crash("Failed to obtain UDP socket"); */
529 /* return -1; */
530 /* } */
531 /* if(tcp_sock == -1) { */
532 /* errno = icmp_sockerrno; */
533 /* crash("Failed to obtain TCP socker"); */
534 /* return -1; */
535 /* } */
536 }
537 if(!ttl) ttl = 64;
539 if(icmp_sock) {
540 result = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
541 if(debug) {
542 if(result == -1) printf("setsockopt failed\n");
543 else printf("ttl set to %u\n", ttl);
544 }
545 }
547 /* stupid users should be able to give whatever thresholds they want
548 * (nothing will break if they do), but some anal plugin maintainer
549 * will probably add some printf() thing here later, so it might be
550 * best to at least show them where to do it. ;) */
551 if(warn.pl > crit.pl) warn.pl = crit.pl;
552 if(warn.rta > crit.rta) warn.rta = crit.rta;
553 if(warn_down > crit_down) crit_down = warn_down;
555 signal(SIGINT, finish);
556 signal(SIGHUP, finish);
557 signal(SIGTERM, finish);
558 signal(SIGALRM, finish);
559 if(debug) printf("Setting alarm timeout to %u seconds\n", timeout);
560 alarm(timeout);
562 /* make sure we don't wait any longer than necessary */
563 gettimeofday(&prog_start, &tz);
564 max_completion_time =
565 ((targets * packets * pkt_interval) + (targets * target_interval)) +
566 (targets * packets * crit.rta) + crit.rta;
568 if(debug) {
569 printf("packets: %u, targets: %u\n"
570 "target_interval: %0.3f, pkt_interval %0.3f\n"
571 "crit.rta: %0.3f\n"
572 "max_completion_time: %0.3f\n",
573 packets, targets,
574 (float)target_interval / 1000, (float)pkt_interval / 1000,
575 (float)crit.rta / 1000,
576 (float)max_completion_time / 1000);
577 }
579 if(debug) {
580 if(max_completion_time > (u_int)timeout * 1000000) {
581 printf("max_completion_time: %llu timeout: %u\n",
582 max_completion_time, timeout);
583 printf("Timout must be at lest %llu\n",
584 max_completion_time / 1000000 + 1);
585 }
586 }
588 icmp_pkt_size = icmp_data_size + ICMP_MINLEN;
589 if(debug > 2) printf("icmp_pkt_size = %u\n", icmp_pkt_size);
590 if(icmp_pkt_size < sizeof(struct icmp) + sizeof(struct icmp_ping_data)) {
591 icmp_pkt_size = sizeof(struct icmp) + sizeof(struct icmp_ping_data);
592 }
593 if(debug > 2) printf("icmp_pkt_size = %u\n", icmp_pkt_size);
595 if(debug) {
596 printf("crit = {%u, %u%%}, warn = {%u, %u%%}\n",
597 crit.rta, crit.pl, warn.rta, warn.pl);
598 printf("pkt_interval: %u target_interval: %u retry_interval: %u\n",
599 pkt_interval, target_interval, retry_interval);
600 printf("icmp_pkt_size: %u timeout: %u\n",
601 icmp_pkt_size, timeout);
602 }
604 if(packets > 20) {
605 errno = 0;
606 crash("packets is > 20 (%d)", packets);
607 }
609 if(min_hosts_alive < -1) {
610 errno = 0;
611 crash("minimum alive hosts is negative (%i)", min_hosts_alive);
612 }
614 host = list;
615 table = malloc(sizeof(struct rta_host **) * (argc - 1));
616 i = 0;
617 while(host) {
618 host->id = i;
619 table[i] = host;
620 host = host->next;
621 i++;
622 }
624 run_checks();
626 errno = 0;
627 finish(0);
629 return(0);
630 }
632 static void
633 run_checks()
634 {
635 u_int i, t, result;
636 u_int final_wait, time_passed;
638 /* this loop might actually violate the pkt_interval or target_interval
639 * settings, but only if there aren't any packets on the wire which
640 * indicates that the target can handle an increased packet rate */
641 for(i = 0; i < packets; i++) {
642 for(t = 0; t < targets; t++) {
643 /* don't send useless packets */
644 if(!targets_alive) finish(0);
645 if(table[t]->flags & FLAG_LOST_CAUSE) {
646 if(debug) printf("%s is a lost cause. not sending any more\n",
647 table[t]->name);
648 continue;
649 }
651 /* we're still in the game, so send next packet */
652 (void)send_icmp_ping(icmp_sock, table[t]);
653 result = wait_for_reply(icmp_sock, target_interval);
654 }
655 result = wait_for_reply(icmp_sock, pkt_interval * targets);
656 }
658 if(icmp_pkts_en_route && targets_alive) {
659 time_passed = get_timevaldiff(NULL, NULL);
660 final_wait = max_completion_time - time_passed;
662 if(debug) {
663 printf("time_passed: %u final_wait: %u max_completion_time: %llu\n",
664 time_passed, final_wait, max_completion_time);
665 }
666 if(time_passed > max_completion_time) {
667 if(debug) printf("Time passed. Finishing up\n");
668 finish(0);
669 }
671 /* catch the packets that might come in within the timeframe, but
672 * haven't yet */
673 if(debug) printf("Waiting for %u micro-seconds (%0.3f msecs)\n",
674 final_wait, (float)final_wait / 1000);
675 result = wait_for_reply(icmp_sock, final_wait);
676 }
677 }
679 /* response structure:
680 * ip header : 20 bytes
681 * icmp header : 28 bytes
682 * icmp echo reply : the rest
683 */
684 static int
685 wait_for_reply(int sock, u_int t)
686 {
687 int n, hlen;
688 static char buf[4096];
689 struct sockaddr_in resp_addr;
690 struct ip *ip;
691 struct icmp icp;
692 struct rta_host *host;
693 struct icmp_ping_data data;
694 struct timeval wait_start, now;
695 u_int tdiff, i, per_pkt_wait;
697 /* if we can't listen or don't have anything to listen to, just return */
698 if(!t || !icmp_pkts_en_route) return 0;
700 gettimeofday(&wait_start, &tz);
702 i = t;
703 per_pkt_wait = t / icmp_pkts_en_route;
704 while(icmp_pkts_en_route && get_timevaldiff(&wait_start, NULL) < i) {
705 t = per_pkt_wait;
707 /* wrap up if all targets are declared dead */
708 if(!targets_alive ||
709 get_timevaldiff(&prog_start, NULL) >= max_completion_time ||
710 (mode == MODE_HOSTCHECK && targets_down))
711 {
712 finish(0);
713 }
715 /* reap responses until we hit a timeout */
716 n = recvfrom_wto(sock, buf, sizeof(buf),
717 (struct sockaddr *)&resp_addr, &t);
718 if(!n) {
719 if(debug > 1) {
720 printf("recvfrom_wto() timed out during a %u usecs wait\n",
721 per_pkt_wait);
722 }
723 continue; /* timeout for this one, so keep trying */
724 }
725 if(n < 0) {
726 if(debug) printf("recvfrom_wto() returned errors\n");
727 return n;
728 }
730 ip = (struct ip *)buf;
731 if(debug > 1) printf("received %u bytes from %s\n",
732 ntohs(ip->ip_len), inet_ntoa(resp_addr.sin_addr));
734 /* obsolete. alpha on tru64 provides the necessary defines, but isn't broken */
735 /* #if defined( __alpha__ ) && __STDC__ && !defined( __GLIBC__ ) */
736 /* alpha headers are decidedly broken. Using an ansi compiler,
737 * they provide ip_vhl instead of ip_hl and ip_v, so we mask
738 * off the bottom 4 bits */
739 /* hlen = (ip->ip_vhl & 0x0f) << 2; */
740 /* #else */
741 hlen = ip->ip_hl << 2;
742 /* #endif */
744 if(n < (hlen + ICMP_MINLEN)) {
745 crash("received packet too short for ICMP (%d bytes, expected %d) from %s\n",
746 n, hlen + icmp_pkt_size, inet_ntoa(resp_addr.sin_addr));
747 }
748 /* else if(debug) { */
749 /* printf("ip header size: %u, packet size: %u (expected %u, %u)\n", */
750 /* hlen, ntohs(ip->ip_len) - hlen, */
751 /* sizeof(struct ip), icmp_pkt_size); */
752 /* } */
754 /* check the response */
755 memcpy(&icp, buf + hlen, sizeof(icp));
757 if(icp.icmp_id != pid) {
758 handle_random_icmp(&icp, &resp_addr);
759 continue;
760 }
762 if(icp.icmp_type != ICMP_ECHOREPLY || icp.icmp_seq >= targets) {
763 if(debug > 2) printf("not a proper ICMP_ECHOREPLY\n");
764 handle_random_icmp(&icp, &resp_addr);
765 continue;
766 }
768 /* this is indeed a valid response */
769 memcpy(&data, icp.icmp_data, sizeof(data));
771 host = table[icp.icmp_seq];
772 gettimeofday(&now, &tz);
773 tdiff = get_timevaldiff(&data.stime, &now);
775 host->time_waited += tdiff;
776 host->icmp_recv++;
777 icmp_recv++;
779 if(debug) {
780 printf("%0.3f ms rtt from %s, outgoing ttl: %u, incoming ttl: %u\n",
781 (float)tdiff / 1000, inet_ntoa(resp_addr.sin_addr),
782 ttl, ip->ip_ttl);
783 }
785 /* if we're in hostcheck mode, exit with limited printouts */
786 if(mode == MODE_HOSTCHECK) {
787 printf("OK - %s responds to ICMP. Packet %u, rta %0.3fms|"
788 "pkt=%u;;0;%u rta=%0.3f;%0.3f;%0.3f;;\n",
789 host->name, icmp_recv, (float)tdiff / 1000,
790 icmp_recv, packets, (float)tdiff / 1000,
791 (float)warn.rta / 1000, (float)crit.rta / 1000);
792 exit(STATE_OK);
793 }
794 }
796 return 0;
797 }
799 /* the ping functions */
800 static int
801 send_icmp_ping(int sock, struct rta_host *host)
802 {
803 static union {
804 char *buf; /* re-use so we prevent leaks */
805 struct icmp *icp;
806 u_short *cksum_in;
807 } packet = { NULL };
808 long int len;
809 struct icmp_ping_data data;
810 struct timeval tv;
811 struct sockaddr *addr;
813 if(sock == -1) {
814 errno = 0;
815 crash("Attempt to send on bogus socket");
816 return -1;
817 }
818 addr = (struct sockaddr *)&host->saddr_in;
820 if(!packet.buf) {
821 if (!(packet.buf = malloc(icmp_pkt_size))) {
822 crash("send_icmp_ping(): failed to malloc %d bytes for send buffer",
823 icmp_pkt_size);
824 return -1; /* might be reached if we're in debug mode */
825 }
826 }
827 memset(packet.buf, 0, icmp_pkt_size);
829 if((gettimeofday(&tv, &tz)) == -1) return -1;
831 data.ping_id = 10; /* host->icmp.icmp_sent; */
832 memcpy(&data.stime, &tv, sizeof(tv));
833 memcpy(&packet.icp->icmp_data, &data, sizeof(data));
834 packet.icp->icmp_type = ICMP_ECHO;
835 packet.icp->icmp_code = 0;
836 packet.icp->icmp_cksum = 0;
837 packet.icp->icmp_id = pid;
838 packet.icp->icmp_seq = host->id;
839 packet.icp->icmp_cksum = icmp_checksum(packet.cksum_in, icmp_pkt_size);
841 len = sendto(sock, packet.buf, icmp_pkt_size, 0, (struct sockaddr *)addr,
842 sizeof(struct sockaddr));
844 if(len < 0 || (unsigned int)len != icmp_pkt_size) {
845 if(debug) printf("Failed to send ping to %s\n",
846 inet_ntoa(host->saddr_in.sin_addr));
847 return -1;
848 }
850 icmp_sent++;
851 host->icmp_sent++;
853 return 0;
854 }
856 static int
857 recvfrom_wto(int sock, char *buf, unsigned int len, struct sockaddr *saddr,
858 u_int *timo)
859 {
860 u_int slen;
861 int n;
862 struct timeval to, then, now;
863 fd_set rd, wr;
865 if(!*timo) {
866 if(debug) printf("*timo is not\n");
867 return 0;
868 }
870 to.tv_sec = *timo / 1000000;
871 to.tv_usec = (*timo - (to.tv_sec * 1000000));
873 FD_ZERO(&rd);
874 FD_ZERO(&wr);
875 FD_SET(sock, &rd);
876 errno = 0;
877 gettimeofday(&then, &tz);
878 n = select(sock + 1, &rd, &wr, NULL, &to);
879 if(n < 0) crash("select() in recvfrom_wto");
880 gettimeofday(&now, &tz);
881 *timo = get_timevaldiff(&then, &now);
883 if(!n) return 0; /* timeout */
885 slen = sizeof(struct sockaddr);
887 return recvfrom(sock, buf, len, 0, saddr, &slen);
888 }
890 static void
891 finish(int sig)
892 {
893 u_int i = 0;
894 unsigned char pl;
895 double rta;
896 struct rta_host *host;
897 char *status_string[] =
898 {"OK", "WARNING", "CRITICAL", "UNKNOWN", "DEPENDENT"};
899 int hosts_ok = 0;
900 int hosts_warn = 0;
902 alarm(0);
903 if(debug > 1) printf("finish(%d) called\n", sig);
905 if(icmp_sock != -1) close(icmp_sock);
906 if(udp_sock != -1) close(udp_sock);
907 if(tcp_sock != -1) close(tcp_sock);
909 if(debug) {
910 printf("icmp_sent: %u icmp_recv: %u icmp_lost: %u\n",
911 icmp_sent, icmp_recv, icmp_lost);
912 printf("targets: %u targets_alive: %u\n", targets, targets_alive);
913 }
915 /* iterate thrice to calculate values, give output, and print perfparse */
916 host = list;
917 while(host) {
918 if(!host->icmp_recv) {
919 /* rta 0 is ofcourse not entirely correct, but will still show up
920 * conspicuosly as missing entries in perfparse and cacti */
921 pl = 100;
922 rta = 0;
923 status = STATE_CRITICAL;
924 /* up the down counter if not already counted */
925 if(!(host->flags & FLAG_LOST_CAUSE) && targets_alive) targets_down++;
926 }
927 else {
928 pl = ((host->icmp_sent - host->icmp_recv) * 100) / host->icmp_sent;
929 rta = (double)host->time_waited / host->icmp_recv;
930 }
931 host->pl = pl;
932 host->rta = rta;
933 if(pl >= crit.pl || rta >= crit.rta) {
934 status = STATE_CRITICAL;
935 }
936 else if(!status && (pl >= warn.pl || rta >= warn.rta)) {
937 status = STATE_WARNING;
938 hosts_warn++;
939 }
940 else {
941 hosts_ok++;
942 }
944 host = host->next;
945 }
946 /* this is inevitable */
947 if(!targets_alive) status = STATE_CRITICAL;
948 if(min_hosts_alive > -1) {
949 if(hosts_ok >= min_hosts_alive) status = STATE_OK;
950 else if((hosts_ok + hosts_warn) >= min_hosts_alive) status = STATE_WARNING;
951 }
952 printf("%s - ", status_string[status]);
954 host = list;
955 while(host) {
956 if(debug) puts("");
957 if(i) {
958 if(i < targets) printf(" :: ");
959 else printf("\n");
960 }
961 i++;
962 if(!host->icmp_recv) {
963 status = STATE_CRITICAL;
964 if(host->flags & FLAG_LOST_CAUSE) {
965 printf("%s: %s @ %s. rta nan, lost %d%%",
966 host->name,
967 get_icmp_error_msg(host->icmp_type, host->icmp_code),
968 inet_ntoa(host->error_addr),
969 100);
970 }
971 else { /* not marked as lost cause, so we have no flags for it */
972 printf("%s: rta nan, lost 100%%", host->name);
973 }
974 }
975 else { /* !icmp_recv */
976 printf("%s: rta %0.3fms, lost %u%%",
977 host->name, host->rta / 1000, host->pl);
978 }
980 host = host->next;
981 }
983 /* iterate once more for pretty perfparse output */
984 printf("|");
985 i = 0;
986 host = list;
987 while(host) {
988 if(debug) puts("");
989 printf("%srta=%0.3fms;%0.3f;%0.3f;0; %spl=%u%%;%u;%u;; ",
990 (targets > 1) ? host->name : "",
991 host->rta / 1000, (float)warn.rta / 1000, (float)crit.rta / 1000,
992 (targets > 1) ? host->name : "",
993 host->pl, warn.pl, crit.pl);
995 host = host->next;
996 }
998 if(min_hosts_alive > -1) {
999 if(hosts_ok >= min_hosts_alive) status = STATE_OK;
1000 else if((hosts_ok + hosts_warn) >= min_hosts_alive) status = STATE_WARNING;
1001 }
1003 /* finish with an empty line */
1004 puts("");
1005 if(debug) printf("targets: %u, targets_alive: %u, hosts_ok: %u, hosts_warn: %u, min_hosts_alive: %i\n",
1006 targets, targets_alive, hosts_ok, hosts_warn, min_hosts_alive);
1008 exit(status);
1009 }
1011 static u_int
1012 get_timevaldiff(struct timeval *early, struct timeval *later)
1013 {
1014 u_int ret;
1015 struct timeval now;
1017 if(!later) {
1018 gettimeofday(&now, &tz);
1019 later = &now;
1020 }
1021 if(!early) early = &prog_start;
1023 /* if early > later we return 0 so as to indicate a timeout */
1024 if(early->tv_sec > early->tv_sec ||
1025 (early->tv_sec == later->tv_sec && early->tv_usec > later->tv_usec))
1026 {
1027 return 0;
1028 }
1030 ret = (later->tv_sec - early->tv_sec) * 1000000;
1031 ret += later->tv_usec - early->tv_usec;
1033 return ret;
1034 }
1036 static int
1037 add_target_ip(char *arg, struct in_addr *in)
1038 {
1039 struct rta_host *host;
1041 /* disregard obviously stupid addresses */
1042 if(in->s_addr == INADDR_NONE || in->s_addr == INADDR_ANY)
1043 return -1;
1045 /* no point in adding two identical IP's, so don't. ;) */
1046 host = list;
1047 while(host) {
1048 if(host->saddr_in.sin_addr.s_addr == in->s_addr) {
1049 if(debug) printf("Identical IP already exists. Not adding %s\n", arg);
1050 return -1;
1051 }
1052 host = host->next;
1053 }
1055 /* add the fresh ip */
1056 host = malloc(sizeof(struct rta_host));
1057 if(!host) {
1058 crash("add_target_ip(%s, %s): malloc(%d) failed",
1059 arg, inet_ntoa(*in), sizeof(struct rta_host));
1060 }
1061 memset(host, 0, sizeof(struct rta_host));
1063 /* set the values. use calling name for output */
1064 host->name = strdup(arg);
1066 /* fill out the sockaddr_in struct */
1067 host->saddr_in.sin_family = AF_INET;
1068 host->saddr_in.sin_addr.s_addr = in->s_addr;
1070 if(!list) list = cursor = host;
1071 else cursor->next = host;
1073 cursor = host;
1074 targets++;
1076 return 0;
1077 }
1079 /* wrapper for add_target_ip */
1080 static int
1081 add_target(char *arg)
1082 {
1083 int i;
1084 struct hostent *he;
1085 struct in_addr *in, ip;
1087 /* don't resolve if we don't have to */
1088 if((ip.s_addr = inet_addr(arg)) != INADDR_NONE) {
1089 /* don't add all ip's if we were given a specific one */
1090 return add_target_ip(arg, &ip);
1091 /* he = gethostbyaddr((char *)in, sizeof(struct in_addr), AF_INET); */
1092 /* if(!he) return add_target_ip(arg, in); */
1093 }
1094 else {
1095 errno = 0;
1096 he = gethostbyname(arg);
1097 if(!he) {
1098 errno = 0;
1099 crash("Failed to resolve %s", arg);
1100 return -1;
1101 }
1102 }
1104 /* possibly add all the IP's as targets */
1105 for(i = 0; he->h_addr_list[i]; i++) {
1106 in = (struct in_addr *)he->h_addr_list[i];
1107 add_target_ip(arg, in);
1109 /* this is silly, but it works */
1110 if(mode == MODE_HOSTCHECK || mode == MODE_ALL) {
1111 printf("mode: %d\n", mode);
1112 continue;
1113 }
1114 break;
1115 }
1117 return 0;
1118 }
1120 static void
1121 set_source_ip(char *arg)
1122 {
1123 struct sockaddr_in src;
1125 memset(&src, 0, sizeof(src));
1126 src.sin_family = AF_INET;
1127 if((src.sin_addr.s_addr = inet_addr(arg)) == INADDR_NONE)
1128 src.sin_addr.s_addr = get_ip_address(arg);
1129 if(bind(icmp_sock, (struct sockaddr *)&src, sizeof(src)) == -1)
1130 crash("Cannot bind to IP address %s", arg);
1131 }
1133 /* TODO: Move this to netutils.c and also change check_dhcp to use that. */
1134 static in_addr_t
1135 get_ip_address(const char *ifname)
1136 {
1137 #if defined(SIOCGIFADDR)
1138 struct ifreq ifr;
1140 strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name) - 1);
1141 ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = '\0';
1142 if(ioctl(icmp_sock, SIOCGIFADDR, &ifr) == -1)
1143 crash("Cannot determine IP address of interface %s", ifname);
1144 return ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr;
1145 #else
1146 errno = 0;
1147 crash("Cannot get interface IP address on this platform.");
1148 #endif
1149 }
1151 /*
1152 * u = micro
1153 * m = milli
1154 * s = seconds
1155 * return value is in microseconds
1156 */
1157 static u_int
1158 get_timevar(const char *str)
1159 {
1160 char p, u, *ptr;
1161 unsigned int len;
1162 u_int i, d; /* integer and decimal, respectively */
1163 u_int factor = 1000; /* default to milliseconds */
1165 if(!str) return 0;
1166 len = strlen(str);
1167 if(!len) return 0;
1169 /* unit might be given as ms|m (millisec),
1170 * us|u (microsec) or just plain s, for seconds */
1171 u = p = '\0';
1172 u = str[len - 1];
1173 if(len >= 2 && !isdigit((int)str[len - 2])) p = str[len - 2];
1174 if(p && u == 's') u = p;
1175 else if(!p) p = u;
1176 if(debug > 2) printf("evaluating %s, u: %c, p: %c\n", str, u, p);
1178 if(u == 'u') factor = 1; /* microseconds */
1179 else if(u == 'm') factor = 1000; /* milliseconds */
1180 else if(u == 's') factor = 1000000; /* seconds */
1181 if(debug > 2) printf("factor is %u\n", factor);
1183 i = strtoul(str, &ptr, 0);
1184 if(!ptr || *ptr != '.' || strlen(ptr) < 2 || factor == 1)
1185 return i * factor;
1187 /* time specified in usecs can't have decimal points, so ignore them */
1188 if(factor == 1) return i;
1190 d = strtoul(ptr + 1, NULL, 0);
1192 /* d is decimal, so get rid of excess digits */
1193 while(d >= factor) d /= 10;
1195 /* the last parenthesis avoids floating point exceptions. */
1196 return ((i * factor) + (d * (factor / 10)));
1197 }
1199 /* not too good at checking errors, but it'll do (main() should barfe on -1) */
1200 static int
1201 get_threshold(char *str, threshold *th)
1202 {
1203 char *p = NULL, i = 0;
1205 if(!str || !strlen(str) || !th) return -1;
1207 /* pointer magic slims code by 10 lines. i is bof-stop on stupid libc's */
1208 p = &str[strlen(str) - 1];
1209 while(p != &str[1]) {
1210 if(*p == '%') *p = '\0';
1211 else if(*p == ',' && i) {
1212 *p = '\0'; /* reset it so get_timevar(str) works nicely later */
1213 th->pl = (unsigned char)strtoul(p+1, NULL, 0);
1214 break;
1215 }
1216 i = 1;
1217 p--;
1218 }
1219 th->rta = get_timevar(str);
1221 if(!th->rta) return -1;
1223 if(th->rta > MAXTTL * 1000000) th->rta = MAXTTL * 1000000;
1224 if(th->pl > 100) th->pl = 100;
1226 return 0;
1227 }
1229 unsigned short
1230 icmp_checksum(unsigned short *p, int n)
1231 {
1232 register unsigned short cksum;
1233 register long sum = 0;
1235 while(n > 1) {
1236 sum += *p++;
1237 n -= 2;
1238 }
1240 /* mop up the occasional odd byte */
1241 if(n == 1) sum += (unsigned char)*p;
1243 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
1244 sum += (sum >> 16); /* add carry */
1245 cksum = ~sum; /* ones-complement, trunc to 16 bits */
1247 return cksum;
1248 }
1250 void
1251 print_help(void)
1252 {
1254 /*print_revision (progname, revision);*/ /* FIXME: Why? */
1256 printf ("Copyright (c) 2005 Andreas Ericsson <ae@op5.se>\n");
1257 printf (COPYRIGHT, copyright, email);
1259 printf ("\n\n");
1261 print_usage ();
1263 printf (_(UT_HELP_VRSN));
1265 printf (" %s\n", "-H");
1266 printf (" %s\n", _("specify a target"));
1267 printf (" %s\n", "-w");
1268 printf (" %s", _("warning threshold (currently "));
1269 printf ("%0.3fms,%u%%)\n", (float)warn.rta / 1000 , warn.pl / 1000);
1270 printf (" %s\n", "-c");
1271 printf (" %s", _("critical threshold (currently "));
1272 printf ("%0.3fms,%u%%)\n", (float)crit.rta, crit.pl);
1273 printf (" %s\n", "-s");
1274 printf (" %s\n", _("specify a source IP address or device name"));
1275 printf (" %s\n", "-n");
1276 printf (" %s", _("number of packets to send (currently "));
1277 printf ("%u)\n",packets);
1278 printf (" %s\n", "-i");
1279 printf (" %s", _("max packet interval (currently "));
1280 printf ("%0.3fms)\n",(float)pkt_interval / 1000);
1281 printf (" %s\n", "-I");
1282 printf (" %s", _("max target interval (currently "));
1283 printf ("%0.3fms)\n", (float)target_interval / 1000);
1284 printf (" %s\n", "-m");
1285 printf (" %s",_("number of alive hosts required for success"));
1286 printf ("\n");
1287 printf (" %s\n", "-l");
1288 printf (" %s", _("TTL on outgoing packets (currently "));
1289 printf ("%u)", ttl);
1290 printf (" %s\n", "-t");
1291 printf (" %s",_("timeout value (seconds, currently "));
1292 printf ("%u)\n", timeout);
1293 printf (" %s\n", "-b");
1294 printf (" %s\n", _("icmp packet size (currenly ignored)"));
1295 printf (" %s\n", "-v");
1296 printf (" %s\n", _("verbose"));
1298 printf ("\n");
1299 printf ("%s\n\n", _("The -H switch is optional. Naming a host (or several) to check is not."));
1300 printf ("%s\n", _("Threshold format for -w and -c is 200.25,60% for 200.25 msec RTA and 60%"));
1301 printf ("%s\n", _("packet loss. The default values should work well for most users."));
1302 printf ("%s\n", _("You can specify different RTA factors using the standardized abbreviations"));
1303 printf ("%s\n\n", _("us (microseconds), ms (milliseconds, default) or just plain s for seconds."));
1304 /* -d not yet implemented */
1305 /* printf ("%s\n", _("Threshold format for -d is warn,crit. 12,14 means WARNING if >= 12 hops"));
1306 printf ("%s\n", _("are spent and CRITICAL if >= 14 hops are spent."));
1307 printf ("%s\n\n", _("NOTE: Some systems decrease TTL when forming ICMP_ECHOREPLY, others do not."));*/
1308 printf ("%s\n\n", _("The -v switch can be specified several times for increased verbosity."));
1310 /* printf ("%s\n", _("Long options are currently unsupported."));
1311 printf ("%s\n", _("Options marked with * require an argument"));
1312 */
1313 printf (_(UT_SUPPORT));
1315 printf (_(UT_NOWARRANTY));
1316 }
1320 void
1321 print_usage (void)
1322 {
1323 printf (_("Usage:"));
1324 printf(" %s [options] [-H] host1 host2 hostn\n", progname);
1325 }