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