Code

Added examples for new features to check_disk
[nagiosplug.git] / plugins-root / check_icmp.c
1  /******************************************************************************
2 *
3 * Nagios check_icmp plugin
4 *
5 * License: GPL
6 * Copyright (c) 2005-2007 nagios-plugins team
7 *
8 * Original Author : Andreas Ericsson <ae@op5.se>
9 *
10 * Last Modified: $Date$
11 *
12 * Description:
13 *
14 * This file contains the check_icmp plugin
15 *
16 *  Relevant RFC's: 792 (ICMP), 791 (IP)
17 *
18 *  This program was modeled somewhat after the check_icmp program,
19 *  which was in turn a hack of fping (www.fping.org) but has been
20 *  completely rewritten since to generate higher precision rta values,
21 *  and support several different modes as well as setting ttl to control.
22 *  redundant routes. The only remainders of fping is currently a few
23 *  function names.
24 *
25 * License Information:
26 *
27 * This program is free software; you can redistribute it and/or modify
28 * it under the terms of the GNU General Public License as published by
29 * the Free Software Foundation; either version 2 of the License, or
30 * (at your option) any later version.
31 *
32 * This program is distributed in the hope that it will be useful,
33 * but WITHOUT ANY WARRANTY; without even the implied warranty of
34 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
35 * GNU General Public License for more details.
36 *
37 * You should have received a copy of the GNU General Public License
38 * along with this program; if not, write to the Free Software
39 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
40 *
41 * $Id$
42
43 *****************************************************************************/
45 /* progname may change */
46 /* char *progname = "check_icmp"; */
47 char *progname;
48 const char *revision = "$Revision$";
49 const char *copyright = "2005-2007";
50 const char *email = "nagiosplug-devel@lists.sourceforge.net";
52 /** nagios plugins basic includes */
53 #include "common.h"
54 #include "netutils.h"
55 #include "utils.h"
57 #include <sys/time.h>
58 #include <sys/types.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <stdarg.h>
62 #include <unistd.h>
63 #include <stddef.h>
64 #include <errno.h>
65 #include <string.h>
66 #include <ctype.h>
67 #include <netdb.h>
68 #include <sys/socket.h>
69 #include <netinet/in_systm.h>
70 #include <netinet/in.h>
71 #include <netinet/ip.h>
72 #include <netinet/ip_icmp.h>
73 #include <arpa/inet.h>
74 #include <signal.h>
77 /** sometimes undefined system macros (quite a few, actually) **/
78 #ifndef MAXTTL
79 # define MAXTTL 255
80 #endif
81 #ifndef INADDR_NONE
82 # define INADDR_NONE 0xffffffU
83 #endif
85 #ifndef SOL_IP
86 #define SOL_IP 0
87 #endif
89 /* we bundle these in one #ifndef, since they're all from BSD
90  * Put individual #ifndef's around those that bother you */
91 #ifndef ICMP_UNREACH_NET_UNKNOWN
92 # define ICMP_UNREACH_NET_UNKNOWN 6
93 # define ICMP_UNREACH_HOST_UNKNOWN 7
94 # define ICMP_UNREACH_ISOLATED 8
95 # define ICMP_UNREACH_NET_PROHIB 9
96 # define ICMP_UNREACH_HOST_PROHIB 10
97 # define ICMP_UNREACH_TOSNET 11
98 # define ICMP_UNREACH_TOSHOST 12
99 #endif
100 /* tru64 has the ones above, but not these */
101 #ifndef ICMP_UNREACH_FILTER_PROHIB
102 # define ICMP_UNREACH_FILTER_PROHIB 13
103 # define ICMP_UNREACH_HOST_PRECEDENCE 14
104 # define ICMP_UNREACH_PRECEDENCE_CUTOFF 15
105 #endif
108 typedef unsigned short range_t;  /* type for get_range() -- unimplemented */
110 typedef struct rta_host {
111         unsigned short id;           /* id in **table, and icmp pkts */
112         char *name;                  /* arg used for adding this host */
113         char *msg;                   /* icmp error message, if any */
114         struct sockaddr_in saddr_in; /* the address of this host */
115         struct in_addr error_addr;   /* stores address of error replies */
116         unsigned long long time_waited; /* total time waited, in usecs */
117         unsigned int icmp_sent, icmp_recv, icmp_lost; /* counters */
118         unsigned char icmp_type, icmp_code; /* type and code from errors */
119         unsigned short flags;        /* control/status flags */
120         double rta;                  /* measured RTA */
121         unsigned char pl;            /* measured packet loss */
122         struct rta_host *next;       /* linked list */
123 } rta_host;
125 #define FLAG_LOST_CAUSE 0x01  /* decidedly dead target. */
127 /* threshold structure. all values are maximum allowed, exclusive */
128 typedef struct threshold {
129         unsigned char pl;    /* max allowed packet loss in percent */
130         unsigned int rta;  /* roundtrip time average, microseconds */
131 } threshold;
133 /* the data structure */
134 typedef struct icmp_ping_data {
135         struct timeval stime;   /* timestamp (saved in protocol struct as well) */
136         unsigned short ping_id;
137 } icmp_ping_data;
139 /* the different modes of this program are as follows:
140  * MODE_RTA: send all packets no matter what (mimic check_icmp and check_ping)
141  * MODE_HOSTCHECK: Return immediately upon any sign of life
142  *                 In addition, sends packets to ALL addresses assigned
143  *                 to this host (as returned by gethostbyname() or
144  *                 gethostbyaddr() and expects one host only to be checked at
145  *                 a time.  Therefore, any packet response what so ever will
146  *                 count as a sign of life, even when received outside
147  *                 crit.rta limit. Do not misspell any additional IP's.
148  * MODE_ALL:  Requires packets from ALL requested IP to return OK (default).
149  * MODE_ICMP: implement something similar to check_icmp (MODE_RTA without
150  *            tcp and udp args does this)
151  */
152 #define MODE_RTA 0
153 #define MODE_HOSTCHECK 1
154 #define MODE_ALL 2
155 #define MODE_ICMP 3
157 /* the different ping types we can do
158  * TODO: investigate ARP ping as well */
159 #define HAVE_ICMP 1
160 #define HAVE_UDP 2
161 #define HAVE_TCP 4
162 #define HAVE_ARP 8
164 #define MIN_PING_DATA_SIZE sizeof(struct icmp_ping_data)
165 #define MAX_IP_PKT_SIZE 65536   /* (theoretical) max IP packet size */
166 #define IP_HDR_SIZE 20
167 #define MAX_PING_DATA (MAX_IP_PKT_SIZE - IP_HDR_SIZE - ICMP_MINLEN)
168 #define DEFAULT_PING_DATA_SIZE (MIN_PING_DATA_SIZE + 44)
170 /* various target states */
171 #define TSTATE_INACTIVE 0x01    /* don't ping this host anymore */
172 #define TSTATE_WAITING 0x02             /* unanswered packets on the wire */
173 #define TSTATE_ALIVE 0x04       /* target is alive (has answered something) */
174 #define TSTATE_UNREACH 0x08
176 /** prototypes **/
177 void print_help (void);
178 void print_usage (void);
179 static u_int get_timevar(const char *);
180 static u_int get_timevaldiff(struct timeval *, struct timeval *);
181 static int wait_for_reply(int, u_int);
182 static int recvfrom_wto(int, char *, unsigned int, struct sockaddr *, u_int *);
183 static int send_icmp_ping(int, struct rta_host *);
184 static int get_threshold(char *str, threshold *th);
185 static void run_checks(void);
186 static int add_target(char *);
187 static int add_target_ip(char *, struct in_addr *);
188 static int handle_random_icmp(struct icmp *, struct sockaddr_in *);
189 static unsigned short icmp_checksum(unsigned short *, int);
190 static void finish(int);
191 static void crash(const char *, ...);
193 /** external **/
194 extern int optind, opterr, optopt;
195 extern char *optarg;
196 extern char **environ;
198 /** global variables **/
199 static struct rta_host **table, *cursor, *list;
200 static threshold crit = {80, 500000}, warn = {40, 200000};
201 static int mode, protocols, sockets, debug = 0, timeout = 10;
202 static unsigned short icmp_pkt_size, icmp_data_size = DEFAULT_PING_DATA_SIZE;
203 static unsigned int icmp_sent = 0, icmp_recv = 0, icmp_lost = 0;
204 #define icmp_pkts_en_route (icmp_sent - (icmp_recv + icmp_lost))
205 static unsigned short targets_down = 0, targets = 0, packets = 0;
206 #define targets_alive (targets - targets_down)
207 static unsigned int retry_interval, pkt_interval, target_interval;
208 static int icmp_sock, tcp_sock, udp_sock, status = STATE_OK;
209 static pid_t pid;
210 static struct timezone tz;
211 static struct timeval prog_start;
212 static unsigned long long max_completion_time = 0;
213 static unsigned char ttl = 0;   /* outgoing ttl */
214 static unsigned int warn_down = 1, crit_down = 1; /* host down threshold values */
215 static int min_hosts_alive = -1;
216 float pkt_backoff_factor = 1.5;
217 float target_backoff_factor = 1.5;
219 /** code start **/
220 static void
221 crash(const char *fmt, ...)
223         va_list ap;
225         printf("%s: ", progname);
227         va_start(ap, fmt);
228         vprintf(fmt, ap);
229         va_end(ap);
231         if(errno) printf(": %s", strerror(errno));
232         puts("");
234         exit(3);
238 static char *
239 get_icmp_error_msg(unsigned char icmp_type, unsigned char icmp_code)
241         char *msg = "unreachable";
243         if(debug > 1) printf("get_icmp_error_msg(%u, %u)\n", icmp_type, icmp_code);
244         switch(icmp_type) {
245         case ICMP_UNREACH:
246                 switch(icmp_code) {
247                 case ICMP_UNREACH_NET: msg = "Net unreachable"; break;
248                 case ICMP_UNREACH_HOST: msg = "Host unreachable"; break;
249                 case ICMP_UNREACH_PROTOCOL: msg = "Protocol unreachable (firewall?)"; break;
250                 case ICMP_UNREACH_PORT: msg = "Port unreachable (firewall?)"; break;
251                 case ICMP_UNREACH_NEEDFRAG: msg = "Fragmentation needed"; break;
252                 case ICMP_UNREACH_SRCFAIL: msg = "Source route failed"; break;
253                 case ICMP_UNREACH_ISOLATED: msg = "Source host isolated"; break;
254                 case ICMP_UNREACH_NET_UNKNOWN: msg = "Unknown network"; break;
255                 case ICMP_UNREACH_HOST_UNKNOWN: msg = "Unknown host"; break;
256                 case ICMP_UNREACH_NET_PROHIB: msg = "Network denied (firewall?)"; break;
257                 case ICMP_UNREACH_HOST_PROHIB: msg = "Host denied (firewall?)"; break;
258                 case ICMP_UNREACH_TOSNET: msg = "Bad TOS for network (firewall?)"; break;
259                 case ICMP_UNREACH_TOSHOST: msg = "Bad TOS for host (firewall?)"; break;
260                 case ICMP_UNREACH_FILTER_PROHIB: msg = "Prohibited by filter (firewall)"; break;
261                 case ICMP_UNREACH_HOST_PRECEDENCE: msg = "Host precedence violation"; break;
262                 case ICMP_UNREACH_PRECEDENCE_CUTOFF: msg = "Precedence cutoff"; break;
263                 default: msg = "Invalid code"; break;
264                 }
265                 break;
267         case ICMP_TIMXCEED:
268                 /* really 'out of reach', or non-existant host behind a router serving
269                  * two different subnets */
270                 switch(icmp_code) {
271                 case ICMP_TIMXCEED_INTRANS: msg = "Time to live exceeded in transit"; break;
272                 case ICMP_TIMXCEED_REASS: msg = "Fragment reassembly time exceeded"; break;
273                 default: msg = "Invalid code"; break;
274                 }
275                 break;
277         case ICMP_SOURCEQUENCH: msg = "Transmitting too fast"; break;
278         case ICMP_REDIRECT: msg = "Redirect (change route)"; break;
279         case ICMP_PARAMPROB: msg = "Bad IP header (required option absent)"; break;
281                 /* the following aren't error messages, so ignore */
282         case ICMP_TSTAMP:
283         case ICMP_TSTAMPREPLY:
284         case ICMP_IREQ:
285         case ICMP_IREQREPLY:
286         case ICMP_MASKREQ:
287         case ICMP_MASKREPLY:
288         default: msg = ""; break;
289         }
291         return msg;
294 static int
295 handle_random_icmp(struct icmp *p, struct sockaddr_in *addr)
297         struct icmp *sent_icmp = NULL;
298         struct rta_host *host = NULL;
299         unsigned char *ptr;
301         if(p->icmp_type == ICMP_ECHO && p->icmp_id == pid) {
302                 /* echo request from us to us (pinging localhost) */
303                 return 0;
304         }
306         ptr = (unsigned char *)p;
307         if(debug) printf("handle_random_icmp(%p, %p)\n", (void *)p, (void *)addr);
309         /* only handle a few types, since others can't possibly be replies to
310          * us in a sane network (if it is anyway, it will be counted as lost
311          * at summary time, but not as quickly as a proper response */
312         /* TIMXCEED can be an unreach from a router with multiple IP's which
313          * serves two different subnets on the same interface and a dead host
314          * on one net is pinged from the other. The router will respond to
315          * itself and thus set TTL=0 so as to not loop forever.  Even when
316          * TIMXCEED actually sends a proper icmp response we will have passed
317          * too many hops to have a hope of reaching it later, in which case it
318          * indicates overconfidence in the network, poor routing or both. */
319         if(p->icmp_type != ICMP_UNREACH && p->icmp_type != ICMP_TIMXCEED &&
320            p->icmp_type != ICMP_SOURCEQUENCH && p->icmp_type != ICMP_PARAMPROB)
321         {
322                 return 0;
323         }
325         /* might be for us. At least it holds the original package (according
326          * to RFC 792). If it isn't, just ignore it */
327         sent_icmp = (struct icmp *)(ptr + 28);
328         if(sent_icmp->icmp_type != ICMP_ECHO || sent_icmp->icmp_id != pid ||
329            sent_icmp->icmp_seq >= targets)
330         {
331                 if(debug) printf("Packet is no response to a packet we sent\n");
332                 return 0;
333         }
335         /* it is indeed a response for us */
336         host = table[sent_icmp->icmp_seq];
337         if(debug) {
338                 printf("Received \"%s\" from %s for ICMP ECHO sent to %s.\n",
339                            get_icmp_error_msg(p->icmp_type, p->icmp_code),
340                            inet_ntoa(addr->sin_addr), host->name);
341         }
343         icmp_lost++;
344         host->icmp_lost++;
345         /* don't spend time on lost hosts any more */
346         if(host->flags & FLAG_LOST_CAUSE) return 0;
348         /* source quench means we're sending too fast, so increase the
349          * interval and mark this packet lost */
350         if(p->icmp_type == ICMP_SOURCEQUENCH) {
351                 pkt_interval *= pkt_backoff_factor;
352                 target_interval *= target_backoff_factor;
353         }
354         else {
355                 targets_down++;
356                 host->flags |= FLAG_LOST_CAUSE;
357         }
358         host->icmp_type = p->icmp_type;
359         host->icmp_code = p->icmp_code;
360         host->error_addr.s_addr = addr->sin_addr.s_addr;
362         return 0;
365 int
366 main(int argc, char **argv)
368         int i;
369         char *ptr;
370         long int arg;
371         int icmp_sockerrno, udp_sockerrno, tcp_sockerrno;
372         int result;
373         struct rta_host *host;
374         
375         /* 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, *sent_icmp;
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                 icp = (struct icmp *)(buf + hlen);
745                 sent_icmp = (struct icmp *)(buf + hlen + ICMP_MINLEN);
746                 /* printf("buf: %p, icp: %p, distance: %u (expected %u)\n", */
747                 /*         buf, icp, */
748                 /*         (u_int)icp - (u_int)buf, hlen); */
749                 /* printf("buf: %p, sent_icmp: %p, distance: %u (expected %u)\n", */
750                 /*         buf, sent_icmp, */
751                 /*         (u_int)sent_icmp - (u_int)buf, hlen + ICMP_MINLEN); */
753                 if(icp->icmp_id != pid) {
754                         handle_random_icmp(icp, &resp_addr);
755                         continue;
756                 }
758                 if(icp->icmp_type != ICMP_ECHOREPLY || icp->icmp_seq >= targets) {
759                         if(debug > 2) printf("not a proper ICMP_ECHOREPLY\n");
760                         handle_random_icmp(icp, &resp_addr);
761                         continue;
762                 }
764                 /* this is indeed a valid response */
765                 data = (struct icmp_ping_data *)(icp->icmp_data);
767                 host = table[icp->icmp_seq];
768                 gettimeofday(&now, &tz);
769                 tdiff = get_timevaldiff(&data->stime, &now);
771                 host->time_waited += tdiff;
772                 host->icmp_recv++;
773                 icmp_recv++;
775                 if(debug) {
776                         printf("%0.3f ms rtt from %s, outgoing ttl: %u, incoming ttl: %u\n",
777                                    (float)tdiff / 1000, inet_ntoa(resp_addr.sin_addr),
778                                    ttl, ip->ip_ttl);
779                 }
781                 /* if we're in hostcheck mode, exit with limited printouts */
782                 if(mode == MODE_HOSTCHECK) {
783                         printf("OK - %s responds to ICMP. Packet %u, rta %0.3fms|"
784                                    "pkt=%u;;0;%u rta=%0.3f;%0.3f;%0.3f;;\n",
785                                    host->name, icmp_recv, (float)tdiff / 1000,
786                                    icmp_recv, packets, (float)tdiff / 1000,
787                                    (float)warn.rta / 1000, (float)crit.rta / 1000);
788                         exit(STATE_OK);
789                 }
790         }
792         return 0;
795 /* the ping functions */
796 static int
797 send_icmp_ping(int sock, struct rta_host *host)
799         static char *buf = NULL; /* re-use so we prevent leaks */
800         long int len;
801         struct icmp *icp;
802         struct icmp_ping_data *data;
803         struct timeval tv;
804         struct sockaddr *addr;
806         
807         if(sock == -1) {
808                 errno = 0;
809                 crash("Attempt to send on bogus socket");
810                 return -1;
811         }
812         addr = (struct sockaddr *)&host->saddr_in;
814         if(!buf) {
815                 buf = (char *)malloc(icmp_pkt_size + sizeof(struct ip));
816                 if(!buf) {
817                         crash("send_icmp_ping(): failed to malloc %d bytes for send buffer",
818                                   icmp_pkt_size);
819                         return -1;      /* might be reached if we're in debug mode */
820                 }
821         }
822         memset(buf, 0, icmp_pkt_size + sizeof(struct ip));
824         if((gettimeofday(&tv, &tz)) == -1) return -1;
826         icp = (struct icmp *)buf;
827         icp->icmp_type = ICMP_ECHO;
828         icp->icmp_code = 0;
829         icp->icmp_cksum = 0;
830         icp->icmp_id = pid;
831         icp->icmp_seq = host->id;
832         data = (struct icmp_ping_data *)icp->icmp_data;
833         data->ping_id = 10; /* host->icmp.icmp_sent; */
834         memcpy(&data->stime, &tv, sizeof(struct timeval));
835         icp->icmp_cksum = icmp_checksum((u_short *)icp, icmp_pkt_size);
837         len = sendto(sock, buf, icmp_pkt_size, 0, (struct sockaddr *)addr,
838                                  sizeof(struct sockaddr));
840         if(len < 0 || (unsigned int)len != icmp_pkt_size) {
841                 if(debug) printf("Failed to send ping to %s\n",
842                                                  inet_ntoa(host->saddr_in.sin_addr));
843                 return -1;
844         }
846         icmp_sent++;
847         host->icmp_sent++;
849         return 0;
852 static int
853 recvfrom_wto(int sock, char *buf, unsigned int len, struct sockaddr *saddr,
854                          u_int *timo)
856         u_int slen;
857         int n;
858         struct timeval to, then, now;
859         fd_set rd, wr;
861         if(!*timo) {
862                 if(debug) printf("*timo is not\n");
863                 return 0;
864         }
866         to.tv_sec = *timo / 1000000;
867         to.tv_usec = (*timo - (to.tv_sec * 1000000));
869         FD_ZERO(&rd);
870         FD_ZERO(&wr);
871         FD_SET(sock, &rd);
872         errno = 0;
873         gettimeofday(&then, &tz);
874         n = select(sock + 1, &rd, &wr, NULL, &to);
875         if(n < 0) crash("select() in recvfrom_wto");
876         gettimeofday(&now, &tz);
877         *timo = get_timevaldiff(&then, &now);
879         if(!n) return 0;                                /* timeout */
881         slen = sizeof(struct sockaddr);
883         return recvfrom(sock, buf, len, 0, saddr, &slen);
886 static void
887 finish(int sig)
889         u_int i = 0;
890         unsigned char pl;
891         double rta;
892         struct rta_host *host;
893         char *status_string[] =
894         {"OK", "WARNING", "CRITICAL", "UNKNOWN", "DEPENDENT"};
895         int hosts_ok = 0;
896         int hosts_warn = 0;
898         alarm(0);
899         if(debug > 1) printf("finish(%d) called\n", sig);
901         if(icmp_sock != -1) close(icmp_sock);
902         if(udp_sock != -1) close(udp_sock);
903         if(tcp_sock != -1) close(tcp_sock);
905         if(debug) {
906                 printf("icmp_sent: %u  icmp_recv: %u  icmp_lost: %u\n",
907                            icmp_sent, icmp_recv, icmp_lost);
908                 printf("targets: %u  targets_alive: %u\n", targets, targets_alive);
909         }
911         /* iterate thrice to calculate values, give output, and print perfparse */
912         host = list;
913         while(host) {
914                 if(!host->icmp_recv) {
915                         /* rta 0 is ofcourse not entirely correct, but will still show up
916                          * conspicuosly as missing entries in perfparse and cacti */
917                         pl = 100;
918                         rta = 0;
919                         status = STATE_CRITICAL;
920                         /* up the down counter if not already counted */
921                         if(!(host->flags & FLAG_LOST_CAUSE) && targets_alive) targets_down++;
922                 }
923                 else {
924                         pl = ((host->icmp_sent - host->icmp_recv) * 100) / host->icmp_sent;
925                         rta = (double)host->time_waited / host->icmp_recv;
926                 }
927                 host->pl = pl;
928                 host->rta = rta;
929                 if(pl >= crit.pl || rta >= crit.rta) {
930                         status = STATE_CRITICAL;
931                 }
932                 else if(!status && (pl >= warn.pl || rta >= warn.rta)) {
933                         status = STATE_WARNING;
934                         hosts_warn++;
935                 }
936                 else {
937                         hosts_ok++;
938                 }
940                 host = host->next;
941         }
942         /* this is inevitable */
943         if(!targets_alive) status = STATE_CRITICAL;
944         if(min_hosts_alive > -1) {
945                 if(hosts_ok >= min_hosts_alive) status = STATE_OK;
946                 else if((hosts_ok + hosts_warn) >= min_hosts_alive) status = STATE_WARNING;
947         }
948         printf("%s - ", status_string[status]);
950         host = list;
951         while(host) {
952                 if(debug) puts("");
953                 if(i) {
954                         if(i < targets) printf(" :: ");
955                         else printf("\n");
956                 }
957                 i++;
958                 if(!host->icmp_recv) {
959                         status = STATE_CRITICAL;
960                         if(host->flags & FLAG_LOST_CAUSE) {
961                                 printf("%s: %s @ %s. rta nan, lost %d%%",
962                                            host->name,
963                                            get_icmp_error_msg(host->icmp_type, host->icmp_code),
964                                            inet_ntoa(host->error_addr),
965                                            100);
966                         }
967                         else { /* not marked as lost cause, so we have no flags for it */
968                                 printf("%s: rta nan, lost 100%%", host->name);
969                         }
970                 }
971                 else {  /* !icmp_recv */
972                         printf("%s: rta %0.3fms, lost %u%%",
973                                    host->name, host->rta / 1000, host->pl);
974                 }
976                 host = host->next;
977         }
979         /* iterate once more for pretty perfparse output */
980         printf("|");
981         i = 0;
982         host = list;
983         while(host) {
984                 if(debug) puts("");
985                 printf("%srta=%0.3fms;%0.3f;%0.3f;0; %spl=%u%%;%u;%u;; ",
986                            (targets > 1) ? host->name : "",
987                            host->rta / 1000, (float)warn.rta / 1000, (float)crit.rta / 1000,
988                            (targets > 1) ? host->name : "",
989                            host->pl, warn.pl, crit.pl);
991                 host = host->next;
992         }
994         if(min_hosts_alive > -1) {
995                 if(hosts_ok >= min_hosts_alive) status = STATE_OK;
996                 else if((hosts_ok + hosts_warn) >= min_hosts_alive) status = STATE_WARNING;
997         }
999         /* finish with an empty line */
1000         puts("");
1001         if(debug) printf("targets: %u, targets_alive: %u, hosts_ok: %u, hosts_warn: %u, min_hosts_alive: %i\n",
1002                                          targets, targets_alive, hosts_ok, hosts_warn, min_hosts_alive);
1004         exit(status);
1007 static u_int
1008 get_timevaldiff(struct timeval *early, struct timeval *later)
1010         u_int ret;
1011         struct timeval now;
1013         if(!later) {
1014                 gettimeofday(&now, &tz);
1015                 later = &now;
1016         }
1017         if(!early) early = &prog_start;
1019         /* if early > later we return 0 so as to indicate a timeout */
1020         if(early->tv_sec > early->tv_sec ||
1021            (early->tv_sec == later->tv_sec && early->tv_usec > later->tv_usec))
1022         {
1023                 return 0;
1024         }
1026         ret = (later->tv_sec - early->tv_sec) * 1000000;
1027         ret += later->tv_usec - early->tv_usec;
1029         return ret;
1032 static int
1033 add_target_ip(char *arg, struct in_addr *in)
1035         struct rta_host *host;
1037         /* disregard obviously stupid addresses */
1038         if(in->s_addr == INADDR_NONE || in->s_addr == INADDR_ANY)
1039                 return -1;
1041         /* no point in adding two identical IP's, so don't. ;) */
1042         host = list;
1043         while(host) {
1044                 if(host->saddr_in.sin_addr.s_addr == in->s_addr) {
1045                         if(debug) printf("Identical IP already exists. Not adding %s\n", arg);
1046                         return -1;
1047                 }
1048                 host = host->next;
1049         }
1051         /* add the fresh ip */
1052         host = malloc(sizeof(struct rta_host));
1053         if(!host) {
1054                 crash("add_target_ip(%s, %s): malloc(%d) failed",
1055                           arg, inet_ntoa(*in), sizeof(struct rta_host));
1056         }
1057         memset(host, 0, sizeof(struct rta_host));
1059         /* set the values. use calling name for output */
1060         host->name = strdup(arg);
1062         /* fill out the sockaddr_in struct */
1063         host->saddr_in.sin_family = AF_INET;
1064         host->saddr_in.sin_addr.s_addr = in->s_addr;
1066         if(!list) list = cursor = host;
1067         else cursor->next = host;
1069         cursor = host;
1070         targets++;
1072         return 0;
1075 /* wrapper for add_target_ip */
1076 static int
1077 add_target(char *arg)
1079         int i;
1080         struct hostent *he;
1081         struct in_addr *in, ip;
1083         /* don't resolve if we don't have to */
1084         if((ip.s_addr = inet_addr(arg)) != INADDR_NONE) {
1085                 /* don't add all ip's if we were given a specific one */
1086                 return add_target_ip(arg, &ip);
1087                 /* he = gethostbyaddr((char *)in, sizeof(struct in_addr), AF_INET); */
1088                 /* if(!he) return add_target_ip(arg, in); */
1089         }
1090         else {
1091                 errno = 0;
1092                 he = gethostbyname(arg);
1093                 if(!he) {
1094                         errno = 0;
1095                         crash("Failed to resolve %s", arg);
1096                         return -1;
1097                 }
1098         }
1100         /* possibly add all the IP's as targets */
1101         for(i = 0; he->h_addr_list[i]; i++) {
1102                 in = (struct in_addr *)he->h_addr_list[i];
1103                 add_target_ip(arg, in);
1105                 /* this is silly, but it works */
1106                 if(mode == MODE_HOSTCHECK || mode == MODE_ALL) {
1107                         printf("mode: %d\n", mode);
1108                         continue;
1109                 }
1110                 break;
1111         }
1113         return 0;
1115 /*
1116  * u = micro
1117  * m = milli
1118  * s = seconds
1119  * return value is in microseconds
1120  */
1121 static u_int
1122 get_timevar(const char *str)
1124         char p, u, *ptr;
1125         unsigned int len;
1126         u_int i, d;                 /* integer and decimal, respectively */
1127         u_int factor = 1000;    /* default to milliseconds */
1129         if(!str) return 0;
1130         len = strlen(str);
1131         if(!len) return 0;
1133         /* unit might be given as ms|m (millisec),
1134          * us|u (microsec) or just plain s, for seconds */
1135         u = p = '\0';
1136         u = str[len - 1];
1137         if(len >= 2 && !isdigit((int)str[len - 2])) p = str[len - 2];
1138         if(p && u == 's') u = p;
1139         else if(!p) p = u;
1140         if(debug > 2) printf("evaluating %s, u: %c, p: %c\n", str, u, p);
1142         if(u == 'u') factor = 1;            /* microseconds */
1143         else if(u == 'm') factor = 1000;        /* milliseconds */
1144         else if(u == 's') factor = 1000000;     /* seconds */
1145         if(debug > 2) printf("factor is %u\n", factor);
1147         i = strtoul(str, &ptr, 0);
1148         if(!ptr || *ptr != '.' || strlen(ptr) < 2 || factor == 1)
1149                 return i * factor;
1151         /* time specified in usecs can't have decimal points, so ignore them */
1152         if(factor == 1) return i;
1154         d = strtoul(ptr + 1, NULL, 0);
1156         /* d is decimal, so get rid of excess digits */
1157         while(d >= factor) d /= 10;
1159         /* the last parenthesis avoids floating point exceptions. */
1160         return ((i * factor) + (d * (factor / 10)));
1163 /* not too good at checking errors, but it'll do (main() should barfe on -1) */
1164 static int
1165 get_threshold(char *str, threshold *th)
1167         char *p = NULL, i = 0;
1169         if(!str || !strlen(str) || !th) return -1;
1171         /* pointer magic slims code by 10 lines. i is bof-stop on stupid libc's */
1172         p = &str[strlen(str) - 1];
1173         while(p != &str[1]) {
1174                 if(*p == '%') *p = '\0';
1175                 else if(*p == ',' && i) {
1176                         *p = '\0';      /* reset it so get_timevar(str) works nicely later */
1177                         th->pl = (unsigned char)strtoul(p+1, NULL, 0);
1178                         break;
1179                 }
1180                 i = 1;
1181                 p--;
1182         }
1183         th->rta = get_timevar(str);
1185         if(!th->rta) return -1;
1187         if(th->rta > MAXTTL * 1000000) th->rta = MAXTTL * 1000000;
1188         if(th->pl > 100) th->pl = 100;
1190         return 0;
1193 unsigned short
1194 icmp_checksum(unsigned short *p, int n)
1196         register unsigned short cksum;
1197         register long sum = 0;
1199         while(n > 1) {
1200                 sum += *p++;
1201                 n -= 2;
1202         }
1204         /* mop up the occasional odd byte */
1205         if(n == 1) sum += (unsigned char)*p;
1207         sum = (sum >> 16) + (sum & 0xffff);     /* add hi 16 to low 16 */
1208         sum += (sum >> 16);                     /* add carry */
1209         cksum = ~sum;                           /* ones-complement, trunc to 16 bits */
1211         return cksum;
1214 void
1215 print_help(void)
1218   /*print_revision (progname, revision);*/ /* FIXME: Why? */
1219   
1220   printf ("Copyright (c) 2005 Andreas Ericsson <ae@op5.se>\n");
1221   printf (COPYRIGHT, copyright, email);
1222   
1223   printf ("\n\n");
1224   
1225   print_usage ();
1226   
1227   printf (_(UT_HELP_VRSN));
1228   
1229   printf (" %s\n", "-H");
1230   printf ("    %s\n", _("specify a target"));
1231   printf (" %s\n", "-w");
1232   printf ("    %s", _("warning threshold (currently "));
1233   printf ("%0.3fms,%u%%)\n", (float)warn.rta / 1000 , warn.pl / 1000);
1234   printf (" %s\n", "-c");
1235   printf ("    %s", _("critical threshold (currently "));
1236   printf ("%0.3fms,%u%%)\n", (float)crit.rta, crit.pl);
1237   printf (" %s\n", "-n");
1238   printf ("    %s", _("number of packets to send (currently "));
1239   printf ("%u)\n",packets);
1240   printf (" %s\n", "-i");
1241   printf ("    %s", _("max packet interval (currently "));
1242   printf ("%0.3fms)\n",(float)pkt_interval / 1000);
1243   printf (" %s\n", "-I");
1244   printf ("    %s", _("max target interval (currently "));
1245   printf ("%0.3fms)\n", (float)target_interval / 1000);
1246   printf (" %s\n", "-m");
1247   printf ("    %s",_("number of alive hosts required for success"));
1248   printf ("\n");
1249   printf (" %s\n", "-l");
1250   printf ("    %s", _("TTL on outgoing packets (currently "));
1251   printf ("%u)", ttl);
1252   printf (" %s\n", "-t");
1253   printf ("    %s",_("timeout value (seconds, currently  "));
1254   printf ("%u)\n", timeout);
1255   printf (" %s\n", "-b");
1256   printf ("    %s\n", _("icmp packet size (currenly ignored)"));
1257   printf (" %s\n", "-v");
1258   printf ("    %s\n", _("verbose"));
1260   printf ("\n");
1261         printf ("%s\n\n", _("The -H switch is optional. Naming a host (or several) to check is not."));
1262   printf ("%s\n", _("Threshold format for -w and -c is 200.25,60% for 200.25 msec RTA and 60%"));
1263   printf ("%s\n", _("packet loss.  The default values should work well for most users."));
1264   printf ("%s\n", _("You can specify different RTA factors using the standardized abbreviations"));
1265   printf ("%s\n\n", _("us (microseconds), ms (milliseconds, default) or just plain s for seconds."));
1266 /* -d not yet implemented */
1267 /*  printf ("%s\n", _("Threshold format for -d is warn,crit.  12,14 means WARNING if >= 12 hops"));
1268   printf ("%s\n", _("are spent and CRITICAL if >= 14 hops are spent."));
1269   printf ("%s\n\n", _("NOTE: Some systems decrease TTL when forming ICMP_ECHOREPLY, others do not."));*/
1270   printf ("%s\n\n", _("The -v switch can be specified several times for increased verbosity."));
1272 /*  printf ("%s\n", _("Long options are currently unsupported."));
1273   printf ("%s\n", _("Options marked with * require an argument"));
1274 */
1275   printf (_(UT_SUPPORT));
1276   
1277   printf (_(UT_NOWARRANTY));
1282 void
1283 print_usage (void)
1285   printf (_("Usage:"));
1286   printf(" %s [options] [-H] host1 host2 hostn\n", progname);