Code

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