Code

Fix bug #1494629 - check_icmp fails after some time on FreeBSD
[nagiosplug.git] / plugins-root / check_icmp.c
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, ...)
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);
238 static char *
239 get_icmp_error_msg(unsigned char icmp_type, unsigned char icmp_code)
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;
294 static int
295 handle_random_icmp(struct icmp *p, struct sockaddr_in *addr)
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;
365 int
366 main(int argc, char **argv)
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;
374         
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         /* Some systems have 32-bit pid_t so mask off only 16 bits */
399         pid = getpid() & 0xffff;
400         /* printf("pid = %u\n", pid); */
402         /* get calling name the old-fashioned way for portability instead
403          * of relying on the glibc-ism __progname */
404         ptr = strrchr(argv[0], '/');
405         if(ptr) progname = &ptr[1];
406         else progname = argv[0];
408         /* now set defaults. Use progname to set them initially (allows for
409          * superfast check_host program when target host is up */
410         cursor = list = NULL;
411         table = NULL;
413         mode = MODE_RTA;
414         crit.rta = 500000;
415         crit.pl = 80;
416         warn.rta = 200000;
417         warn.pl = 40;
418         protocols = HAVE_ICMP | HAVE_UDP | HAVE_TCP;
419         pkt_interval = 80000;  /* 80 msec packet interval by default */
420         packets = 5;
422         if(!strcmp(progname, "check_icmp") || !strcmp(progname, "check_ping")) {
423                 mode = MODE_ICMP;
424                 protocols = HAVE_ICMP;
425         }
426         else if(!strcmp(progname, "check_host")) {
427                 mode = MODE_HOSTCHECK;
428                 pkt_interval = 1000000;
429                 packets = 5;
430                 crit.rta = warn.rta = 1000000;
431                 crit.pl = warn.pl = 100;
432         }
433         else if(!strcmp(progname, "check_rta_multi")) {
434                 mode = MODE_ALL;
435                 target_interval = 0;
436                 pkt_interval = 50000;
437                 packets = 5;
438         }
440         /* parse the arguments */
441         for(i = 1; i < argc; i++) {
442                 while((arg = getopt(argc, argv, "vhVw:c:n:p:t:H:i:b:I:l:m:")) != EOF) {
443                         switch(arg) {
444                         case 'v':
445                                 debug++;
446                                 break;
447                         case 'b':
448                                 /* silently ignored for now */
449                                 break;
450                         case 'i':
451                                 pkt_interval = get_timevar(optarg);
452                                 break;
453                         case 'I':
454                                 target_interval = get_timevar(optarg);
455                                 break;
456                         case 'w':
457                                 get_threshold(optarg, &warn);
458                                 break;
459                         case 'c':
460                                 get_threshold(optarg, &crit);
461                                 break;
462                         case 'n':
463                         case 'p':
464                                 packets = strtoul(optarg, NULL, 0);
465                                 break;
466                         case 't':
467                                 timeout = strtoul(optarg, NULL, 0);
468                                 if(!timeout) timeout = 10;
469                                 break;
470                         case 'H':
471                                 add_target(optarg);
472                                 break;
473                         case 'l':
474                                 ttl = (unsigned char)strtoul(optarg, NULL, 0);
475                                 break;
476                         case 'm':
477                                 min_hosts_alive = (int)strtoul(optarg, NULL, 0);
478                                 break;
479                         case 'd': /* implement later, for cluster checks */
480                                 warn_down = (unsigned char)strtoul(optarg, &ptr, 0);
481                                 if(ptr) {
482                                         crit_down = (unsigned char)strtoul(ptr + 1, NULL, 0);
483                                 }
484                                 break;
485       case 'V':                 /* version */
486         /*print_revision (progname, revision);*/ /* FIXME: Why? */
487         exit (STATE_OK);
488       case 'h':                 /* help */
489         print_help ();
490         exit (STATE_OK);
491                         }
492                 }
493         }
495         argv = &argv[optind];
496         while(*argv) {
497                 add_target(*argv);
498                 argv++;
499         }
500         if(!targets) {
501                 errno = 0;
502                 crash("No hosts to check");
503                 exit(3);
504         }
506         if(!sockets) {
507                 if(icmp_sock == -1) {
508                         errno = icmp_sockerrno;
509                         crash("Failed to obtain ICMP socket");
510                         return -1;
511                 }
512                 /* if(udp_sock == -1) { */
513                 /*      errno = icmp_sockerrno; */
514                 /*      crash("Failed to obtain UDP socket"); */
515                 /*      return -1; */
516                 /* } */
517                 /* if(tcp_sock == -1) { */
518                 /*      errno = icmp_sockerrno; */
519                 /*      crash("Failed to obtain TCP socker"); */
520                 /*      return -1; */
521                 /* } */
522         }
523         if(!ttl) ttl = 64;
525         if(icmp_sock) {
526                 result = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
527                 if(debug) {
528                         if(result == -1) printf("setsockopt failed\n");
529                         else printf("ttl set to %u\n", ttl);
530                 }
531         }
533         /* stupid users should be able to give whatever thresholds they want
534          * (nothing will break if they do), but some anal plugin maintainer
535          * will probably add some printf() thing here later, so it might be
536          * best to at least show them where to do it. ;) */
537         if(warn.pl > crit.pl) warn.pl = crit.pl;
538         if(warn.rta > crit.rta) warn.rta = crit.rta;
539         if(warn_down > crit_down) crit_down = warn_down;
541         signal(SIGINT, finish);
542         signal(SIGHUP, finish);
543         signal(SIGTERM, finish);
544         signal(SIGALRM, finish);
545         if(debug) printf("Setting alarm timeout to %u seconds\n", timeout);
546         alarm(timeout);
548         /* make sure we don't wait any longer than necessary */
549         gettimeofday(&prog_start, &tz);
550         max_completion_time =
551                 ((targets * packets * pkt_interval) + (targets * target_interval)) +
552                 (targets * packets * crit.rta) + crit.rta;
554         if(debug) {
555                 printf("packets: %u, targets: %u\n"
556                            "target_interval: %0.3f, pkt_interval %0.3f\n"
557                            "crit.rta: %0.3f\n"
558                            "max_completion_time: %0.3f\n",
559                            packets, targets,
560                            (float)target_interval / 1000, (float)pkt_interval / 1000,
561                            (float)crit.rta / 1000,
562                            (float)max_completion_time / 1000);
563         }
565         if(debug) {
566                 if(max_completion_time > (u_int)timeout * 1000000) {
567                         printf("max_completion_time: %llu  timeout: %u\n",
568                                    max_completion_time, timeout);
569                         printf("Timout must be at lest %llu\n",
570                                    max_completion_time / 1000000 + 1);
571                 }
572         }
574         icmp_pkt_size = icmp_data_size + ICMP_MINLEN;
575         if(debug > 2) printf("icmp_pkt_size = %u\n", icmp_pkt_size);
576         if(icmp_pkt_size < sizeof(struct icmp) + sizeof(struct icmp_ping_data)) {
577                 icmp_pkt_size = sizeof(struct icmp) + sizeof(struct icmp_ping_data);
578         }
579         if(debug > 2) printf("icmp_pkt_size = %u\n", icmp_pkt_size);
581         if(debug) {
582                 printf("crit = {%u, %u%%}, warn = {%u, %u%%}\n",
583                            crit.rta, crit.pl, warn.rta, warn.pl);
584                 printf("pkt_interval: %u  target_interval: %u  retry_interval: %u\n",
585                            pkt_interval, target_interval, retry_interval);
586                 printf("icmp_pkt_size: %u  timeout: %u\n",
587                            icmp_pkt_size, timeout);
588         }
590         if(packets > 20) {
591                 errno = 0;
592                 crash("packets is > 20 (%d)", packets);
593         }
595         if(min_hosts_alive < -1) {
596                 errno = 0;
597                 crash("minimum alive hosts is negative (%i)", min_hosts_alive);
598         }
600         host = list;
601         table = malloc(sizeof(struct rta_host **) * (argc - 1));
602         i = 0;
603         while(host) {
604                 host->id = i;
605                 table[i] = host;
606                 host = host->next;
607                 i++;
608         }
610         run_checks();
612         errno = 0;
613         finish(0);
615         return(0);
618 static void
619 run_checks()
621         u_int i, t, result;
622         u_int final_wait, time_passed;
624         /* this loop might actually violate the pkt_interval or target_interval
625          * settings, but only if there aren't any packets on the wire which
626          * indicates that the target can handle an increased packet rate */
627         for(i = 0; i < packets; i++) {
628                 for(t = 0; t < targets; t++) {
629                         /* don't send useless packets */
630                         if(!targets_alive) finish(0);
631                         if(table[t]->flags & FLAG_LOST_CAUSE) {
632                                 if(debug) printf("%s is a lost cause. not sending any more\n",
633                                                                  table[t]->name);
634                                 continue;
635                         }
636                         
637                         /* we're still in the game, so send next packet */
638                         (void)send_icmp_ping(icmp_sock, table[t]);
639                         result = wait_for_reply(icmp_sock, target_interval);
640                 }
641                 result = wait_for_reply(icmp_sock, pkt_interval * targets);
642         }
644         if(icmp_pkts_en_route && targets_alive) {
645                 time_passed = get_timevaldiff(NULL, NULL);
646                 final_wait = max_completion_time - time_passed;
648                 if(debug) {
649                         printf("time_passed: %u  final_wait: %u  max_completion_time: %llu\n",
650                                    time_passed, final_wait, max_completion_time);
651                 }
652                 if(time_passed > max_completion_time) {
653                         if(debug) printf("Time passed. Finishing up\n");
654                         finish(0);
655                 }
657                 /* catch the packets that might come in within the timeframe, but
658                  * haven't yet */
659                 if(debug) printf("Waiting for %u micro-seconds (%0.3f msecs)\n",
660                                                  final_wait, (float)final_wait / 1000);
661                 result = wait_for_reply(icmp_sock, final_wait);
662         }
665 /* response structure:
666  * ip header   : 20 bytes
667  * icmp header : 28 bytes
668  * icmp echo reply : the rest
669  */
670 static int
671 wait_for_reply(int sock, u_int t)
673         int n, hlen;
674         static char buf[4096];
675         struct sockaddr_in resp_addr;
676         struct ip *ip;
677         struct icmp *icp, *sent_icmp;
678         struct rta_host *host;
679         struct icmp_ping_data *data;
680         struct timeval wait_start, now;
681         u_int tdiff, i, per_pkt_wait;
683         /* if we can't listen or don't have anything to listen to, just return */
684         if(!t || !icmp_pkts_en_route) return 0;
686         gettimeofday(&wait_start, &tz);
688         i = t;
689         per_pkt_wait = t / icmp_pkts_en_route;
690         while(icmp_pkts_en_route && get_timevaldiff(&wait_start, NULL) < i) {
691                 t = per_pkt_wait;
693                 /* wrap up if all targets are declared dead */
694                 if(!targets_alive ||
695                    get_timevaldiff(&prog_start, NULL) >= max_completion_time ||
696                    (mode == MODE_HOSTCHECK && targets_down))
697                 {
698                         finish(0);
699                 }
701                 /* reap responses until we hit a timeout */
702                 n = recvfrom_wto(sock, buf, sizeof(buf),
703                                                  (struct sockaddr *)&resp_addr, &t);
704                 if(!n) {
705                         if(debug > 1) {
706                                 printf("recvfrom_wto() timed out during a %u usecs wait\n",
707                                            per_pkt_wait);
708                         }
709                         continue;       /* timeout for this one, so keep trying */
710                 }
711                 if(n < 0) {
712                         if(debug) printf("recvfrom_wto() returned errors\n");
713                         return n;
714                 }
716                 ip = (struct ip *)buf;
717                 if(debug > 1) printf("received %u bytes from %s\n",
718                                                  ntohs(ip->ip_len), inet_ntoa(resp_addr.sin_addr));
720 /* obsolete. alpha on tru64 provides the necessary defines, but isn't broken */
721 /* #if defined( __alpha__ ) && __STDC__ && !defined( __GLIBC__ ) */
722                 /* alpha headers are decidedly broken. Using an ansi compiler,
723                  * they provide ip_vhl instead of ip_hl and ip_v, so we mask
724                  * off the bottom 4 bits */
725 /*              hlen = (ip->ip_vhl & 0x0f) << 2; */
726 /* #else */
727                 hlen = ip->ip_hl << 2;
728 /* #endif */
730                 if(n < (hlen + ICMP_MINLEN)) {
731                         crash("received packet too short for ICMP (%d bytes, expected %d) from %s\n",
732                                   n, hlen + icmp_pkt_size, inet_ntoa(resp_addr.sin_addr));
733                 }
734                 /* else if(debug) { */
735                 /*      printf("ip header size: %u, packet size: %u (expected %u, %u)\n", */
736                 /*                 hlen, ntohs(ip->ip_len) - hlen, */
737                 /*                 sizeof(struct ip), icmp_pkt_size); */
738                 /* } */
740                 /* check the response */
741                 icp = (struct icmp *)(buf + hlen);
742                 sent_icmp = (struct icmp *)(buf + hlen + ICMP_MINLEN);
743                 /* printf("buf: %p, icp: %p, distance: %u (expected %u)\n", */
744                 /*         buf, icp, */
745                 /*         (u_int)icp - (u_int)buf, hlen); */
746                 /* printf("buf: %p, sent_icmp: %p, distance: %u (expected %u)\n", */
747                 /*         buf, sent_icmp, */
748                 /*         (u_int)sent_icmp - (u_int)buf, hlen + ICMP_MINLEN); */
750                 if(icp->icmp_id != pid) {
751                         handle_random_icmp(icp, &resp_addr);
752                         continue;
753                 }
755                 if(icp->icmp_type != ICMP_ECHOREPLY || icp->icmp_seq >= targets) {
756                         if(debug > 2) printf("not a proper ICMP_ECHOREPLY\n");
757                         handle_random_icmp(icp, &resp_addr);
758                         continue;
759                 }
761                 /* this is indeed a valid response */
762                 data = (struct icmp_ping_data *)(icp->icmp_data);
764                 host = table[icp->icmp_seq];
765                 gettimeofday(&now, &tz);
766                 tdiff = get_timevaldiff(&data->stime, &now);
768                 host->time_waited += tdiff;
769                 host->icmp_recv++;
770                 icmp_recv++;
772                 if(debug) {
773                         printf("%0.3f ms rtt from %s, outgoing ttl: %u, incoming ttl: %u\n",
774                                    (float)tdiff / 1000, inet_ntoa(resp_addr.sin_addr),
775                                    ttl, ip->ip_ttl);
776                 }
778                 /* if we're in hostcheck mode, exit with limited printouts */
779                 if(mode == MODE_HOSTCHECK) {
780                         printf("OK - %s responds to ICMP. Packet %u, rta %0.3fms|"
781                                    "pkt=%u;;0;%u rta=%0.3f;%0.3f;%0.3f;;\n",
782                                    host->name, icmp_recv, (float)tdiff / 1000,
783                                    icmp_recv, packets, (float)tdiff / 1000,
784                                    (float)warn.rta / 1000, (float)crit.rta / 1000);
785                         exit(STATE_OK);
786                 }
787         }
789         return 0;
792 /* the ping functions */
793 static int
794 send_icmp_ping(int sock, struct rta_host *host)
796         static char *buf = NULL; /* re-use so we prevent leaks */
797         long int len;
798         struct icmp *icp;
799         struct icmp_ping_data *data;
800         struct timeval tv;
801         struct sockaddr *addr;
803         
804         if(sock == -1) {
805                 errno = 0;
806                 crash("Attempt to send on bogus socket");
807                 return -1;
808         }
809         addr = (struct sockaddr *)&host->saddr_in;
811         if(!buf) {
812                 buf = (char *)malloc(icmp_pkt_size + sizeof(struct ip));
813                 if(!buf) {
814                         crash("send_icmp_ping(): failed to malloc %d bytes for send buffer",
815                                   icmp_pkt_size);
816                         return -1;      /* might be reached if we're in debug mode */
817                 }
818         }
819         memset(buf, 0, icmp_pkt_size + sizeof(struct ip));
821         if((gettimeofday(&tv, &tz)) == -1) return -1;
823         icp = (struct icmp *)buf;
824         icp->icmp_type = ICMP_ECHO;
825         icp->icmp_code = 0;
826         icp->icmp_cksum = 0;
827         icp->icmp_id = pid;
828         icp->icmp_seq = host->id;
829         data = (struct icmp_ping_data *)icp->icmp_data;
830         data->ping_id = 10; /* host->icmp.icmp_sent; */
831         memcpy(&data->stime, &tv, sizeof(struct timeval));
832         icp->icmp_cksum = icmp_checksum((u_short *)icp, icmp_pkt_size);
834         len = sendto(sock, buf, icmp_pkt_size, 0, (struct sockaddr *)addr,
835                                  sizeof(struct sockaddr));
837         if(len < 0 || (unsigned int)len != icmp_pkt_size) {
838                 if(debug) printf("Failed to send ping to %s\n",
839                                                  inet_ntoa(host->saddr_in.sin_addr));
840                 return -1;
841         }
843         icmp_sent++;
844         host->icmp_sent++;
846         return 0;
849 static int
850 recvfrom_wto(int sock, char *buf, unsigned int len, struct sockaddr *saddr,
851                          u_int *timo)
853         u_int slen;
854         int n;
855         struct timeval to, then, now;
856         fd_set rd, wr;
858         if(!*timo) {
859                 if(debug) printf("*timo is not\n");
860                 return 0;
861         }
863         to.tv_sec = *timo / 1000000;
864         to.tv_usec = (*timo - (to.tv_sec * 1000000));
866         FD_ZERO(&rd);
867         FD_ZERO(&wr);
868         FD_SET(sock, &rd);
869         errno = 0;
870         gettimeofday(&then, &tz);
871         n = select(sock + 1, &rd, &wr, NULL, &to);
872         if(n < 0) crash("select() in recvfrom_wto");
873         gettimeofday(&now, &tz);
874         *timo = get_timevaldiff(&then, &now);
876         if(!n) return 0;                                /* timeout */
878         slen = sizeof(struct sockaddr);
880         return recvfrom(sock, buf, len, 0, saddr, &slen);
883 static void
884 finish(int sig)
886         u_int i = 0;
887         unsigned char pl;
888         double rta;
889         struct rta_host *host;
890         char *status_string[] =
891         {"OK", "WARNING", "CRITICAL", "UNKNOWN", "DEPENDENT"};
892         int hosts_ok = 0;
893         int hosts_warn = 0;
895         alarm(0);
896         if(debug > 1) printf("finish(%d) called\n", sig);
898         if(icmp_sock != -1) close(icmp_sock);
899         if(udp_sock != -1) close(udp_sock);
900         if(tcp_sock != -1) close(tcp_sock);
902         if(debug) {
903                 printf("icmp_sent: %u  icmp_recv: %u  icmp_lost: %u\n",
904                            icmp_sent, icmp_recv, icmp_lost);
905                 printf("targets: %u  targets_alive: %u\n", targets, targets_alive);
906         }
908         /* iterate thrice to calculate values, give output, and print perfparse */
909         host = list;
910         while(host) {
911                 if(!host->icmp_recv) {
912                         /* rta 0 is ofcourse not entirely correct, but will still show up
913                          * conspicuosly as missing entries in perfparse and cacti */
914                         pl = 100;
915                         rta = 0;
916                         status = STATE_CRITICAL;
917                         /* up the down counter if not already counted */
918                         if(!(host->flags & FLAG_LOST_CAUSE) && targets_alive) targets_down++;
919                 }
920                 else {
921                         pl = ((host->icmp_sent - host->icmp_recv) * 100) / host->icmp_sent;
922                         rta = (double)host->time_waited / host->icmp_recv;
923                 }
924                 host->pl = pl;
925                 host->rta = rta;
926                 if(pl >= crit.pl || rta >= crit.rta) {
927                         status = STATE_CRITICAL;
928                 }
929                 else if(!status && (pl >= warn.pl || rta >= warn.rta)) {
930                         status = STATE_WARNING;
931                         hosts_warn++;
932                 }
933                 else {
934                         hosts_ok++;
935                 }
937                 host = host->next;
938         }
939         /* this is inevitable */
940         if(!targets_alive) status = STATE_CRITICAL;
941         if(min_hosts_alive > -1) {
942                 if(hosts_ok >= min_hosts_alive) status = STATE_OK;
943                 else if((hosts_ok + hosts_warn) >= min_hosts_alive) status = STATE_WARNING;
944         }
945         printf("%s - ", status_string[status]);
947         host = list;
948         while(host) {
949                 if(debug) puts("");
950                 if(i) {
951                         if(i < targets) printf(" :: ");
952                         else printf("\n");
953                 }
954                 i++;
955                 if(!host->icmp_recv) {
956                         status = STATE_CRITICAL;
957                         if(host->flags & FLAG_LOST_CAUSE) {
958                                 printf("%s: %s @ %s. rta nan, lost %d%%",
959                                            host->name,
960                                            get_icmp_error_msg(host->icmp_type, host->icmp_code),
961                                            inet_ntoa(host->error_addr),
962                                            100);
963                         }
964                         else { /* not marked as lost cause, so we have no flags for it */
965                                 printf("%s: rta nan, lost 100%%", host->name);
966                         }
967                 }
968                 else {  /* !icmp_recv */
969                         printf("%s: rta %0.3fms, lost %u%%",
970                                    host->name, host->rta / 1000, host->pl);
971                 }
973                 host = host->next;
974         }
976         /* iterate once more for pretty perfparse output */
977         printf("|");
978         i = 0;
979         host = list;
980         while(host) {
981                 if(debug) puts("");
982                 printf("%srta=%0.3fms;%0.3f;%0.3f;0; %spl=%u%%;%u;%u;; ",
983                            (targets > 1) ? host->name : "",
984                            host->rta / 1000, (float)warn.rta / 1000, (float)crit.rta / 1000,
985                            (targets > 1) ? host->name : "",
986                            host->pl, warn.pl, crit.pl);
988                 host = host->next;
989         }
991         if(min_hosts_alive > -1) {
992                 if(hosts_ok >= min_hosts_alive) status = STATE_OK;
993                 else if((hosts_ok + hosts_warn) >= min_hosts_alive) status = STATE_WARNING;
994         }
996         /* finish with an empty line */
997         puts("");
998         if(debug) printf("targets: %u, targets_alive: %u, hosts_ok: %u, hosts_warn: %u, min_hosts_alive: %i\n",
999                                          targets, targets_alive, hosts_ok, hosts_warn, min_hosts_alive);
1001         exit(status);
1004 static u_int
1005 get_timevaldiff(struct timeval *early, struct timeval *later)
1007         u_int ret;
1008         struct timeval now;
1010         if(!later) {
1011                 gettimeofday(&now, &tz);
1012                 later = &now;
1013         }
1014         if(!early) early = &prog_start;
1016         /* if early > later we return 0 so as to indicate a timeout */
1017         if(early->tv_sec > early->tv_sec ||
1018            (early->tv_sec == later->tv_sec && early->tv_usec > later->tv_usec))
1019         {
1020                 return 0;
1021         }
1023         ret = (later->tv_sec - early->tv_sec) * 1000000;
1024         ret += later->tv_usec - early->tv_usec;
1026         return ret;
1029 static int
1030 add_target_ip(char *arg, struct in_addr *in)
1032         struct rta_host *host;
1034         /* disregard obviously stupid addresses */
1035         if(in->s_addr == INADDR_NONE || in->s_addr == INADDR_ANY)
1036                 return -1;
1038         /* no point in adding two identical IP's, so don't. ;) */
1039         host = list;
1040         while(host) {
1041                 if(host->saddr_in.sin_addr.s_addr == in->s_addr) {
1042                         if(debug) printf("Identical IP already exists. Not adding %s\n", arg);
1043                         return -1;
1044                 }
1045                 host = host->next;
1046         }
1048         /* add the fresh ip */
1049         host = malloc(sizeof(struct rta_host));
1050         if(!host) {
1051                 crash("add_target_ip(%s, %s): malloc(%d) failed",
1052                           arg, inet_ntoa(*in), sizeof(struct rta_host));
1053         }
1054         memset(host, 0, sizeof(struct rta_host));
1056         /* set the values. use calling name for output */
1057         host->name = strdup(arg);
1059         /* fill out the sockaddr_in struct */
1060         host->saddr_in.sin_family = AF_INET;
1061         host->saddr_in.sin_addr.s_addr = in->s_addr;
1063         if(!list) list = cursor = host;
1064         else cursor->next = host;
1066         cursor = host;
1067         targets++;
1069         return 0;
1072 /* wrapper for add_target_ip */
1073 static int
1074 add_target(char *arg)
1076         int i;
1077         struct hostent *he;
1078         struct in_addr *in, ip;
1080         /* don't resolve if we don't have to */
1081         if((ip.s_addr = inet_addr(arg)) != INADDR_NONE) {
1082                 /* don't add all ip's if we were given a specific one */
1083                 return add_target_ip(arg, &ip);
1084                 /* he = gethostbyaddr((char *)in, sizeof(struct in_addr), AF_INET); */
1085                 /* if(!he) return add_target_ip(arg, in); */
1086         }
1087         else {
1088                 errno = 0;
1089                 he = gethostbyname(arg);
1090                 if(!he) {
1091                         errno = 0;
1092                         crash("Failed to resolve %s", arg);
1093                         return -1;
1094                 }
1095         }
1097         /* possibly add all the IP's as targets */
1098         for(i = 0; he->h_addr_list[i]; i++) {
1099                 in = (struct in_addr *)he->h_addr_list[i];
1100                 add_target_ip(arg, in);
1102                 /* this is silly, but it works */
1103                 if(mode == MODE_HOSTCHECK || mode == MODE_ALL) {
1104                         printf("mode: %d\n", mode);
1105                         continue;
1106                 }
1107                 break;
1108         }
1110         return 0;
1112 /*
1113  * u = micro
1114  * m = milli
1115  * s = seconds
1116  * return value is in microseconds
1117  */
1118 static u_int
1119 get_timevar(const char *str)
1121         char p, u, *ptr;
1122         unsigned int len;
1123         u_int i, d;                 /* integer and decimal, respectively */
1124         u_int factor = 1000;    /* default to milliseconds */
1126         if(!str) return 0;
1127         len = strlen(str);
1128         if(!len) return 0;
1130         /* unit might be given as ms|m (millisec),
1131          * us|u (microsec) or just plain s, for seconds */
1132         u = p = '\0';
1133         u = str[len - 1];
1134         if(len >= 2 && !isdigit((int)str[len - 2])) p = str[len - 2];
1135         if(p && u == 's') u = p;
1136         else if(!p) p = u;
1137         if(debug > 2) printf("evaluating %s, u: %c, p: %c\n", str, u, p);
1139         if(u == 'u') factor = 1;            /* microseconds */
1140         else if(u == 'm') factor = 1000;        /* milliseconds */
1141         else if(u == 's') factor = 1000000;     /* seconds */
1142         if(debug > 2) printf("factor is %u\n", factor);
1144         i = strtoul(str, &ptr, 0);
1145         if(!ptr || *ptr != '.' || strlen(ptr) < 2 || factor == 1)
1146                 return i * factor;
1148         /* time specified in usecs can't have decimal points, so ignore them */
1149         if(factor == 1) return i;
1151         d = strtoul(ptr + 1, NULL, 0);
1153         /* d is decimal, so get rid of excess digits */
1154         while(d >= factor) d /= 10;
1156         /* the last parenthesis avoids floating point exceptions. */
1157         return ((i * factor) + (d * (factor / 10)));
1160 /* not too good at checking errors, but it'll do (main() should barfe on -1) */
1161 static int
1162 get_threshold(char *str, threshold *th)
1164         char *p = NULL, i = 0;
1166         if(!str || !strlen(str) || !th) return -1;
1168         /* pointer magic slims code by 10 lines. i is bof-stop on stupid libc's */
1169         p = &str[strlen(str) - 1];
1170         while(p != &str[1]) {
1171                 if(*p == '%') *p = '\0';
1172                 else if(*p == ',' && i) {
1173                         *p = '\0';      /* reset it so get_timevar(str) works nicely later */
1174                         th->pl = (unsigned char)strtoul(p+1, NULL, 0);
1175                         break;
1176                 }
1177                 i = 1;
1178                 p--;
1179         }
1180         th->rta = get_timevar(str);
1182         if(!th->rta) return -1;
1184         if(th->rta > MAXTTL * 1000000) th->rta = MAXTTL * 1000000;
1185         if(th->pl > 100) th->pl = 100;
1187         return 0;
1190 unsigned short
1191 icmp_checksum(unsigned short *p, int n)
1193         register unsigned short cksum;
1194         register long sum = 0;
1196         while(n > 1) {
1197                 sum += *p++;
1198                 n -= 2;
1199         }
1201         /* mop up the occasional odd byte */
1202         if(n == 1) sum += (unsigned char)*p;
1204         sum = (sum >> 16) + (sum & 0xffff);     /* add hi 16 to low 16 */
1205         sum += (sum >> 16);                     /* add carry */
1206         cksum = ~sum;                           /* ones-complement, trunc to 16 bits */
1208         return cksum;
1211 void
1212 print_help(void)
1215   /*print_revision (progname, revision);*/ /* FIXME: Why? */
1216   
1217   printf ("Copyright (c) 2005 Andreas Ericsson <ae@op5.se>\n");
1218   printf (COPYRIGHT, copyright, email);
1219   
1220   printf ("\n\n");
1221   
1222   print_usage ();
1223   
1224   printf (_(UT_HELP_VRSN));
1225   
1226   printf (" %s\n", "-H");
1227   printf ("    %s\n", _("specify a target"));
1228   printf (" %s\n", "-w");
1229   printf ("    %s", _("warning threshold (currently "));
1230   printf ("%0.3fms,%u%%)\n", (float)warn.rta / 1000 , warn.pl / 1000);
1231   printf (" %s\n", "-c");
1232   printf ("    %s", _("critical threshold (currently "));
1233   printf ("%0.3fms,%u%%)\n", (float)crit.rta, crit.pl);
1234   printf (" %s\n", "-n");
1235   printf ("    %s", _("number of packets to send (currently "));
1236   printf ("%u)\n",packets);
1237   printf (" %s\n", "-i");
1238   printf ("    %s", _("max packet interval (currently "));
1239   printf ("%0.3fms)\n",(float)pkt_interval / 1000);
1240   printf (" %s\n", "-I");
1241   printf ("    %s", _("max target interval (currently "));
1242   printf ("%0.3fms)\n", (float)target_interval / 1000);
1243   printf (" %s\n", "-m");
1244   printf ("    %s",_("number of alive hosts required for success"));
1245   printf ("\n");
1246   printf (" %s\n", "-l");
1247   printf ("    %s", _("TTL on outgoing packets (currently "));
1248   printf ("%u)", ttl);
1249   printf (" %s\n", "-t");
1250   printf ("    %s",_("timeout value (seconds, currently  "));
1251   printf ("%u)\n", timeout);
1252   printf (" %s\n", "-b");
1253   printf ("    %s\n", _("icmp packet size (currenly ignored)"));
1254   printf (" %s\n", "-v");
1255   printf ("    %s\n", _("verbose"));
1257   printf ("\n");
1258         printf ("%s\n\n", _("The -H switch is optional. Naming a host (or several) to check is not."));
1259   printf ("%s\n", _("Threshold format for -w and -c is 200.25,60% for 200.25 msec RTA and 60%"));
1260   printf ("%s\n", _("packet loss.  The default values should work well for most users."));
1261   printf ("%s\n", _("You can specify different RTA factors using the standardized abbreviations"));
1262   printf ("%s\n\n", _("us (microseconds), ms (milliseconds, default) or just plain s for seconds."));
1263 /* -d not yet implemented */
1264 /*  printf ("%s\n", _("Threshold format for -d is warn,crit.  12,14 means WARNING if >= 12 hops"));
1265   printf ("%s\n", _("are spent and CRITICAL if >= 14 hops are spent."));
1266   printf ("%s\n\n", _("NOTE: Some systems decrease TTL when forming ICMP_ECHOREPLY, others do not."));*/
1267   printf ("%s\n\n", _("The -v switch can be specified several times for increased verbosity."));
1269 /*  printf ("%s\n", _("Long options are currently unsupported."));
1270   printf ("%s\n", _("Options marked with * require an argument"));
1271 */
1272   printf (_(UT_SUPPORT));
1273   
1274   printf (_(UT_NOWARRANTY));
1279 void
1280 print_usage (void)
1282   printf (_("Usage:"));
1283   printf(" %s [options] [-H] host1 host2 hostn\n", progname);