Code

7636bc714a5fe5ecdde9e3b63e234686731a098f
[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;
375         setlocale (LC_ALL, "");
376         bindtextdomain (PACKAGE, LOCALEDIR);
377         textdomain (PACKAGE);
378         
379         /* print a helpful error message if geteuid != 0 */
380         np_warn_if_not_root();
382         /* we only need to be setsuid when we get the sockets, so do
383          * that before pointer magic (esp. on network data) */
384         icmp_sockerrno = udp_sockerrno = tcp_sockerrno = sockets = 0;
386         if((icmp_sock = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP)) != -1)
387                 sockets |= HAVE_ICMP;
388         else icmp_sockerrno = errno;
390         /* if((udp_sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1) */
391         /*      sockets |= HAVE_UDP; */
392         /* else udp_sockerrno = errno; */
394         /* if((tcp_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) != -1) */
395         /*      sockets |= HAVE_TCP; */
396         /* else tcp_sockerrno = errno; */
398         /* now drop privileges (no effect if not setsuid or geteuid() == 0) */
399         setuid(getuid());
401         /* POSIXLY_CORRECT might break things, so unset it (the portable way) */
402         environ = NULL;
404         /* use the pid to mark packets as ours */
405         /* Some systems have 32-bit pid_t so mask off only 16 bits */
406         pid = getpid() & 0xffff;
407         /* printf("pid = %u\n", pid); */
409         /* get calling name the old-fashioned way for portability instead
410          * of relying on the glibc-ism __progname */
411         ptr = strrchr(argv[0], '/');
412         if(ptr) progname = &ptr[1];
413         else progname = argv[0];
415         /* now set defaults. Use progname to set them initially (allows for
416          * superfast check_host program when target host is up */
417         cursor = list = NULL;
418         table = NULL;
420         mode = MODE_RTA;
421         crit.rta = 500000;
422         crit.pl = 80;
423         warn.rta = 200000;
424         warn.pl = 40;
425         protocols = HAVE_ICMP | HAVE_UDP | HAVE_TCP;
426         pkt_interval = 80000;  /* 80 msec packet interval by default */
427         packets = 5;
429         if(!strcmp(progname, "check_icmp") || !strcmp(progname, "check_ping")) {
430                 mode = MODE_ICMP;
431                 protocols = HAVE_ICMP;
432         }
433         else if(!strcmp(progname, "check_host")) {
434                 mode = MODE_HOSTCHECK;
435                 pkt_interval = 1000000;
436                 packets = 5;
437                 crit.rta = warn.rta = 1000000;
438                 crit.pl = warn.pl = 100;
439         }
440         else if(!strcmp(progname, "check_rta_multi")) {
441                 mode = MODE_ALL;
442                 target_interval = 0;
443                 pkt_interval = 50000;
444                 packets = 5;
445         }
447         /* parse the arguments */
448         for(i = 1; i < argc; i++) {
449                 while((arg = getopt(argc, argv, "vhVw:c:n:p:t:H:i:b:I:l:m:")) != EOF) {
450                         switch(arg) {
451                         case 'v':
452                                 debug++;
453                                 break;
454                         case 'b':
455                                 /* silently ignored for now */
456                                 break;
457                         case 'i':
458                                 pkt_interval = get_timevar(optarg);
459                                 break;
460                         case 'I':
461                                 target_interval = get_timevar(optarg);
462                                 break;
463                         case 'w':
464                                 get_threshold(optarg, &warn);
465                                 break;
466                         case 'c':
467                                 get_threshold(optarg, &crit);
468                                 break;
469                         case 'n':
470                         case 'p':
471                                 packets = strtoul(optarg, NULL, 0);
472                                 break;
473                         case 't':
474                                 timeout = strtoul(optarg, NULL, 0);
475                                 if(!timeout) timeout = 10;
476                                 break;
477                         case 'H':
478                                 add_target(optarg);
479                                 break;
480                         case 'l':
481                                 ttl = (unsigned char)strtoul(optarg, NULL, 0);
482                                 break;
483                         case 'm':
484                                 min_hosts_alive = (int)strtoul(optarg, NULL, 0);
485                                 break;
486                         case 'd': /* implement later, for cluster checks */
487                                 warn_down = (unsigned char)strtoul(optarg, &ptr, 0);
488                                 if(ptr) {
489                                         crit_down = (unsigned char)strtoul(ptr + 1, NULL, 0);
490                                 }
491                                 break;
492       case 'V':                 /* version */
493         /*print_revision (progname, revision);*/ /* FIXME: Why? */
494         exit (STATE_OK);
495       case 'h':                 /* help */
496         print_help ();
497         exit (STATE_OK);
498                         }
499                 }
500         }
502         argv = &argv[optind];
503         while(*argv) {
504                 add_target(*argv);
505                 argv++;
506         }
507         if(!targets) {
508                 errno = 0;
509                 crash("No hosts to check");
510                 exit(3);
511         }
513         if(!sockets) {
514                 if(icmp_sock == -1) {
515                         errno = icmp_sockerrno;
516                         crash("Failed to obtain ICMP socket");
517                         return -1;
518                 }
519                 /* if(udp_sock == -1) { */
520                 /*      errno = icmp_sockerrno; */
521                 /*      crash("Failed to obtain UDP socket"); */
522                 /*      return -1; */
523                 /* } */
524                 /* if(tcp_sock == -1) { */
525                 /*      errno = icmp_sockerrno; */
526                 /*      crash("Failed to obtain TCP socker"); */
527                 /*      return -1; */
528                 /* } */
529         }
530         if(!ttl) ttl = 64;
532         if(icmp_sock) {
533                 result = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
534                 if(debug) {
535                         if(result == -1) printf("setsockopt failed\n");
536                         else printf("ttl set to %u\n", ttl);
537                 }
538         }
540         /* stupid users should be able to give whatever thresholds they want
541          * (nothing will break if they do), but some anal plugin maintainer
542          * will probably add some printf() thing here later, so it might be
543          * best to at least show them where to do it. ;) */
544         if(warn.pl > crit.pl) warn.pl = crit.pl;
545         if(warn.rta > crit.rta) warn.rta = crit.rta;
546         if(warn_down > crit_down) crit_down = warn_down;
548         signal(SIGINT, finish);
549         signal(SIGHUP, finish);
550         signal(SIGTERM, finish);
551         signal(SIGALRM, finish);
552         if(debug) printf("Setting alarm timeout to %u seconds\n", timeout);
553         alarm(timeout);
555         /* make sure we don't wait any longer than necessary */
556         gettimeofday(&prog_start, &tz);
557         max_completion_time =
558                 ((targets * packets * pkt_interval) + (targets * target_interval)) +
559                 (targets * packets * crit.rta) + crit.rta;
561         if(debug) {
562                 printf("packets: %u, targets: %u\n"
563                            "target_interval: %0.3f, pkt_interval %0.3f\n"
564                            "crit.rta: %0.3f\n"
565                            "max_completion_time: %0.3f\n",
566                            packets, targets,
567                            (float)target_interval / 1000, (float)pkt_interval / 1000,
568                            (float)crit.rta / 1000,
569                            (float)max_completion_time / 1000);
570         }
572         if(debug) {
573                 if(max_completion_time > (u_int)timeout * 1000000) {
574                         printf("max_completion_time: %llu  timeout: %u\n",
575                                    max_completion_time, timeout);
576                         printf("Timout must be at lest %llu\n",
577                                    max_completion_time / 1000000 + 1);
578                 }
579         }
581         icmp_pkt_size = icmp_data_size + ICMP_MINLEN;
582         if(debug > 2) printf("icmp_pkt_size = %u\n", icmp_pkt_size);
583         if(icmp_pkt_size < sizeof(struct icmp) + sizeof(struct icmp_ping_data)) {
584                 icmp_pkt_size = sizeof(struct icmp) + sizeof(struct icmp_ping_data);
585         }
586         if(debug > 2) printf("icmp_pkt_size = %u\n", icmp_pkt_size);
588         if(debug) {
589                 printf("crit = {%u, %u%%}, warn = {%u, %u%%}\n",
590                            crit.rta, crit.pl, warn.rta, warn.pl);
591                 printf("pkt_interval: %u  target_interval: %u  retry_interval: %u\n",
592                            pkt_interval, target_interval, retry_interval);
593                 printf("icmp_pkt_size: %u  timeout: %u\n",
594                            icmp_pkt_size, timeout);
595         }
597         if(packets > 20) {
598                 errno = 0;
599                 crash("packets is > 20 (%d)", packets);
600         }
602         if(min_hosts_alive < -1) {
603                 errno = 0;
604                 crash("minimum alive hosts is negative (%i)", min_hosts_alive);
605         }
607         host = list;
608         table = malloc(sizeof(struct rta_host **) * (argc - 1));
609         i = 0;
610         while(host) {
611                 host->id = i;
612                 table[i] = host;
613                 host = host->next;
614                 i++;
615         }
617         run_checks();
619         errno = 0;
620         finish(0);
622         return(0);
625 static void
626 run_checks()
628         u_int i, t, result;
629         u_int final_wait, time_passed;
631         /* this loop might actually violate the pkt_interval or target_interval
632          * settings, but only if there aren't any packets on the wire which
633          * indicates that the target can handle an increased packet rate */
634         for(i = 0; i < packets; i++) {
635                 for(t = 0; t < targets; t++) {
636                         /* don't send useless packets */
637                         if(!targets_alive) finish(0);
638                         if(table[t]->flags & FLAG_LOST_CAUSE) {
639                                 if(debug) printf("%s is a lost cause. not sending any more\n",
640                                                                  table[t]->name);
641                                 continue;
642                         }
643                         
644                         /* we're still in the game, so send next packet */
645                         (void)send_icmp_ping(icmp_sock, table[t]);
646                         result = wait_for_reply(icmp_sock, target_interval);
647                 }
648                 result = wait_for_reply(icmp_sock, pkt_interval * targets);
649         }
651         if(icmp_pkts_en_route && targets_alive) {
652                 time_passed = get_timevaldiff(NULL, NULL);
653                 final_wait = max_completion_time - time_passed;
655                 if(debug) {
656                         printf("time_passed: %u  final_wait: %u  max_completion_time: %llu\n",
657                                    time_passed, final_wait, max_completion_time);
658                 }
659                 if(time_passed > max_completion_time) {
660                         if(debug) printf("Time passed. Finishing up\n");
661                         finish(0);
662                 }
664                 /* catch the packets that might come in within the timeframe, but
665                  * haven't yet */
666                 if(debug) printf("Waiting for %u micro-seconds (%0.3f msecs)\n",
667                                                  final_wait, (float)final_wait / 1000);
668                 result = wait_for_reply(icmp_sock, final_wait);
669         }
672 /* response structure:
673  * ip header   : 20 bytes
674  * icmp header : 28 bytes
675  * icmp echo reply : the rest
676  */
677 static int
678 wait_for_reply(int sock, u_int t)
680         int n, hlen;
681         static char buf[4096];
682         struct sockaddr_in resp_addr;
683         struct ip *ip;
684         struct icmp icp;
685         struct rta_host *host;
686         struct icmp_ping_data data;
687         struct timeval wait_start, now;
688         u_int tdiff, i, per_pkt_wait;
690         /* if we can't listen or don't have anything to listen to, just return */
691         if(!t || !icmp_pkts_en_route) return 0;
693         gettimeofday(&wait_start, &tz);
695         i = t;
696         per_pkt_wait = t / icmp_pkts_en_route;
697         while(icmp_pkts_en_route && get_timevaldiff(&wait_start, NULL) < i) {
698                 t = per_pkt_wait;
700                 /* wrap up if all targets are declared dead */
701                 if(!targets_alive ||
702                    get_timevaldiff(&prog_start, NULL) >= max_completion_time ||
703                    (mode == MODE_HOSTCHECK && targets_down))
704                 {
705                         finish(0);
706                 }
708                 /* reap responses until we hit a timeout */
709                 n = recvfrom_wto(sock, buf, sizeof(buf),
710                                                  (struct sockaddr *)&resp_addr, &t);
711                 if(!n) {
712                         if(debug > 1) {
713                                 printf("recvfrom_wto() timed out during a %u usecs wait\n",
714                                            per_pkt_wait);
715                         }
716                         continue;       /* timeout for this one, so keep trying */
717                 }
718                 if(n < 0) {
719                         if(debug) printf("recvfrom_wto() returned errors\n");
720                         return n;
721                 }
723                 ip = (struct ip *)buf;
724                 if(debug > 1) printf("received %u bytes from %s\n",
725                                                  ntohs(ip->ip_len), inet_ntoa(resp_addr.sin_addr));
727 /* obsolete. alpha on tru64 provides the necessary defines, but isn't broken */
728 /* #if defined( __alpha__ ) && __STDC__ && !defined( __GLIBC__ ) */
729                 /* alpha headers are decidedly broken. Using an ansi compiler,
730                  * they provide ip_vhl instead of ip_hl and ip_v, so we mask
731                  * off the bottom 4 bits */
732 /*              hlen = (ip->ip_vhl & 0x0f) << 2; */
733 /* #else */
734                 hlen = ip->ip_hl << 2;
735 /* #endif */
737                 if(n < (hlen + ICMP_MINLEN)) {
738                         crash("received packet too short for ICMP (%d bytes, expected %d) from %s\n",
739                                   n, hlen + icmp_pkt_size, inet_ntoa(resp_addr.sin_addr));
740                 }
741                 /* else if(debug) { */
742                 /*      printf("ip header size: %u, packet size: %u (expected %u, %u)\n", */
743                 /*                 hlen, ntohs(ip->ip_len) - hlen, */
744                 /*                 sizeof(struct ip), icmp_pkt_size); */
745                 /* } */
747                 /* check the response */
748                 memcpy(&icp, buf + hlen, sizeof(icp));
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                 memcpy(&data, icp.icmp_data, sizeof(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 union {
797                 char *buf; /* re-use so we prevent leaks */
798                 struct icmp *icp;
799                 u_short *cksum_in;
800         } packet = { NULL };
801         long int len;
802         struct icmp_ping_data data;
803         struct timeval tv;
804         struct sockaddr *addr;
806         if(sock == -1) {
807                 errno = 0;
808                 crash("Attempt to send on bogus socket");
809                 return -1;
810         }
811         addr = (struct sockaddr *)&host->saddr_in;
813         if(!packet.buf) {
814                 if (!(packet.buf = malloc(icmp_pkt_size))) {
815                         crash("send_icmp_ping(): failed to malloc %d bytes for send buffer",
816                                   icmp_pkt_size);
817                         return -1;      /* might be reached if we're in debug mode */
818                 }
819         }
820         memset(packet.buf, 0, icmp_pkt_size);
822         if((gettimeofday(&tv, &tz)) == -1) return -1;
824         data.ping_id = 10; /* host->icmp.icmp_sent; */
825         memcpy(&data.stime, &tv, sizeof(tv));
826         memcpy(&packet.icp->icmp_data, &data, sizeof(data));
827         packet.icp->icmp_type = ICMP_ECHO;
828         packet.icp->icmp_code = 0;
829         packet.icp->icmp_cksum = 0;
830         packet.icp->icmp_id = pid;
831         packet.icp->icmp_seq = host->id;
832         packet.icp->icmp_cksum = icmp_checksum(packet.cksum_in, icmp_pkt_size);
834         len = sendto(sock, packet.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);