Code

Fix includes for gettext
[nagiosplug.git] / plugins / check_icmp.c
1 /*
2  * $Id$
3  *
4  * This is a hack of fping2 made to work with nagios.
5  * It's fast and removes the necessity of parsing another programs output.
6  *
7  * VIEWING NOTES:
8  * This file was formatted with tab indents at a tab stop of 4.
9  *
10  * It is highly recommended that your editor is set to this
11  * tab stop setting for viewing and editing.
12  *
13  * COPYLEFT;
14  * This programs copyright status is currently undetermined. Much of
15  * the code in it comes from the fping2 program which used to be licensed
16  * under the Stanford General Software License (available at
17  * http://graphics.stanford.edu/software/license.html). It is presently
18  * unclear what license (if any) applies to the original code at the
19  * moment.
20  *
21  * The fping website can be found at http://www.fping.com
22  */
24 #include <stdio.h>
25 #include <errno.h>
26 #include <time.h>
27 #include <signal.h>
29 #include <unistd.h>
31 #include <stdlib.h>
33 #include <string.h>
34 #include <stddef.h>
36 #include <sys/types.h>
37 #include <sys/time.h>
38 #include <sys/socket.h>
40 #include <sys/file.h>
42 #include <netinet/in_systm.h>
43 #include <netinet/in.h>
45 #include <netinet/ip.h>
46 #include <netinet/ip_icmp.h>
48 #include <arpa/inet.h>
49 #include <netdb.h>
51 /* RS6000 has sys/select.h */
52 #ifdef HAVE_SYS_SELECT_H
53 #include <sys/select.h>
54 #endif                                                  /* HAVE_SYS_SELECT_H */
56 /* rta threshold values can't be larger than MAXTTL seconds */
57 #ifndef MAXTTL
58 #  define MAXTTL        255
59 #endif
60 #ifndef IPDEFTTL
61 #  define IPDEFTTL      64
62 #endif
64 /*** externals ***/
65 extern char *optarg;
66 extern int optind, opterr;
68 /*** Constants ***/
69 #define EMAIL           "ae@op5.se"
70 #define VERSION         "0.8.1"
72 #ifndef INADDR_NONE
73 # define INADDR_NONE 0xffffffU
74 #endif
76 /*** Ping packet defines ***/
77 /* data added after ICMP header for our nefarious purposes */
78 typedef struct ping_data {
79         unsigned int ping_count;        /* counts up to -[n|p] count or 1 */
80         struct timeval ping_ts;         /* time sent */
81 } PING_DATA;
83 #define MIN_PING_DATA   sizeof(PING_DATA)
84 #define MAX_IP_PACKET   65536   /* (theoretical) max IP packet size */
85 #define SIZE_IP_HDR             20
86 #define SIZE_ICMP_HDR   ICMP_MINLEN     /* from ip_icmp.h */
87 #define MAX_PING_DATA   (MAX_IP_PACKET - SIZE_IP_HDR - SIZE_ICMP_HDR)
89 /*
90  *  Interval is the minimum amount of time between sending a ping packet to
91  *  any host.
92  *
93  *  Perhost_interval is the minimum amount of time between sending a ping
94  *  packet to a particular responding host
95  *
96  *  Timeout  is the initial amount of time between sending a ping packet to
97  *  a particular non-responding host.
98  *
99  *  Retry is the number of ping packets to send to a non-responding host
100  *  before giving up (in is-it-alive mode).
101  *
102  *  Backoff factor is how much longer to wait on successive retries.
103  */
104 #ifndef DEFAULT_INTERVAL
105 #define DEFAULT_INTERVAL 25             /* default time between packets (msec) */
106 #endif
108 #ifndef DEFAULT_RETRY
109 #define DEFAULT_RETRY   1                       /* number of times to retry a host */
110 #endif
112 #ifndef DEFAULT_TIMEOUT
113 # define DEFAULT_TIMEOUT 1000
114 #endif
116 #ifndef DEFAULT_BACKOFF_FACTOR
117 #define DEFAULT_BACKOFF_FACTOR 1.5      /* exponential timeout factor */
118 #endif
119 #define MIN_BACKOFF_FACTOR     1.0      /* exponential timeout factor */
120 #define MAX_BACKOFF_FACTOR     5.0      /* exponential timeout factor */
122 #ifndef DNS_TIMEOUT
123 #define DNS_TIMEOUT 1000                /* time in usec for dns retry */
124 #endif
126 #ifndef MAX_RTA_THRESHOLD_VALUE
127 # define MAX_RTA_THRESHOLD_VALUE 120*1000000 /* 2 minutes should be enough */
128 #endif
129 #ifndef MIN_RTA_THRESHOLD_VALUE
130 # define MIN_RTA_THRESHOLD_VALUE 10000  /* minimum RTA threshold value */
131 #endif
133 /* sized so as to be like traditional ping */
134 #define DEFAULT_PING_DATA_SIZE  (MIN_PING_DATA + 44)
136 /* maxima and minima */
137 #define MAX_COUNT                               50              /* max count even if we're root */
138 #define MAX_RETRY                               5
139 #define MIN_INTERVAL                    25      /* msecs */
140 #define MIN_TIMEOUT                             50      /* msecs */
142 /* response time array flags */
143 #define RESP_WAITING    -1
144 #define RESP_UNUSED             -2
146 #define ICMP_UNREACH_MAXTYPE    15
148 /* entry used to keep track of each host we are pinging */
149 struct host_entry {
150         int i;                                          /* index into array */
151         char *name;                                     /* name as given by user */
152         char *host;                                     /* text description of host */
153         struct sockaddr_in saddr;       /* internet address */
154         unsigned short **pr;            /* TCP port range to check for connectivity */
155         struct timeval last_send_time;  /* time of last packet sent */
156         unsigned int num_sent;          /* number of ping packets sent */
157         unsigned int num_recv;          /* number of pings received */
158         unsigned int total_time;        /* sum of response times */
159         unsigned int status;            /* this hosts status */
160         unsigned int running;           /* unset when through sending */
161         unsigned int waiting;           /* waiting for response */
162         int *resp_times;        /* individual response times */
163         struct host_entry *prev, *next; /* doubly linked list */
164 };
166 typedef struct host_entry HOST_ENTRY;
168 struct host_name_list {
169         char *entry;
170         struct host_name_list *next;
171 };
173 /* threshold structure */
174 struct threshold {
175         unsigned int pl;        /* packet loss */
176         unsigned int rta;       /* roundtrip time average */
177 };
178 typedef struct threshold threshold;
180 /*****************************************************************************
181  *                             Global Variables                              *
182  *****************************************************************************/
184 HOST_ENTRY *rrlist = NULL;              /* linked list of hosts be pinged */
185 HOST_ENTRY **table = NULL;              /* array of pointers to items in the list */
186 HOST_ENTRY *cursor;
188 char *prog;                                             /* our name */
189 int ident;                                              /* our pid, for marking icmp packets */
190 int sock;                                               /* socket */
191 u_int debug = 0;
193 /* threshold value defaults;
194  * WARNING;  60% packetloss or 200 msecs round trip average
195  * CRITICAL; 80% packetloss or 500 msecs round trip average */
196 threshold warn = {60, 200 * 1000};
197 threshold crit = {80, 500 * 1000};
199 /* times get *100 because all times are calculated in 10 usec units, not ms */
200 unsigned int retry = DEFAULT_RETRY;
201 u_int timeout = DEFAULT_TIMEOUT * 100;
202 u_int interval = DEFAULT_INTERVAL * 100;
203 float backoff = DEFAULT_BACKOFF_FACTOR;
204 u_int select_time;      /* calculated using maximum threshold rta value */
205 u_int ping_data_size = DEFAULT_PING_DATA_SIZE;
206 u_int ping_pkt_size;
207 unsigned int count = 5;
208 unsigned int trials = 1;
210 /* global stats */
211 int total_replies = 0;
212 int num_jobs = 0;                               /* number of hosts still to do */
213 int num_hosts = 0;                              /* total number of hosts */
214 int num_alive = 0;                              /* total number alive */
215 int num_unreachable = 0;                /* total number unreachable */
216 int num_noaddress = 0;                  /* total number of addresses not found */
217 int num_timeout = 0;                    /* number of timed out packets */
218 int num_pingsent = 0;                   /* total pings sent */
219 int num_pingreceived = 0;               /* total pings received */
220 int num_othericmprcvd = 0;              /* total non-echo-reply ICMP received */
222 struct timeval current_time;    /* current time (pseudo) */
223 struct timeval start_time;
224 struct timeval end_time;
225 struct timeval last_send_time;  /* time last ping was sent */
226 struct timezone tz;
228 /* switches */
229 int generate_flag = 0;                  /* flag for IP list generation */
230 int stats_flag, unreachable_flag, alive_flag;
231 int elapsed_flag, version_flag, count_flag;
232 int name_flag, addr_flag, backoff_flag;
233 int multif_flag;
235 /*** prototypes ***/
236 void add_name(char *);
237 void add_addr(char *, char *, struct in_addr);
238 char *na_cat(char *, struct in_addr);
239 char *cpystr(char *);
240 void crash(char *);
241 char *get_host_by_address(struct in_addr);
242 int in_cksum(u_short *, int);
243 void u_sleep(int);
244 int recvfrom_wto(int, char *, int, struct sockaddr *, int);
245 void remove_job(HOST_ENTRY *);
246 void send_ping(int, HOST_ENTRY *);
247 long timeval_diff(struct timeval *, struct timeval *);
248 void usage(void);
249 int wait_for_reply(int);
250 void finish(void);
251 int handle_random_icmp(struct icmp *, struct sockaddr_in *);
252 char *sprint_tm(int);
253 int get_threshold(char *, threshold *);
255 /*** the various exit-states */
256 enum {
257         STATE_OK = 0,
258         STATE_WARNING,
259         STATE_CRITICAL,
260         STATE_UNKNOWN,
261         STATE_DEPENDANT,
262         STATE_OOB
263 };
264 /* the strings that correspond to them */
265 char *status_string[STATE_OOB] = {
266         "OK",
267         "WARNING",
268         "CRITICAL",
269         "UNKNOWN",
270         "DEPENDANT"
271 };
273 int status = STATE_OK;
274 int fin_stat = STATE_OK;
276 /*****************************************************************************
277  *                           Code block start                                *
278  *****************************************************************************/
279 int main(int argc, char **argv)
281         int c;
282         u_int lt, ht;
283         int advance;
284         struct protoent *proto;
285         uid_t uid;
286         struct host_name_list *host_ptr, *host_base_ptr;
288         if(strchr(argv[0], '/')) prog = strrchr(argv[0], '/') + 1;
289         else prog = argv[0];
291         /* check if we are root */
292         if(geteuid()) {
293                 printf("Root access needed (for raw sockets)\n");
294                 exit(STATE_UNKNOWN);
295         }
297         /* confirm that ICMP is available on this machine */
298         if((proto = getprotobyname("icmp")) == NULL)
299                 crash("icmp: unknown protocol");
301         /* create raw socket for ICMP calls (ping) */
302         sock = socket(AF_INET, SOCK_RAW, proto->p_proto);
304         if(sock < 0)
305                 crash("can't create raw socket");
307         /* drop privileges now that we have the socket */
308         if((uid = getuid())) {
309                 seteuid(uid);
310         }
311         
312         if(argc < 2) usage();
314         ident = getpid() & 0xFFFF;
316         if(!(host_base_ptr = malloc(sizeof(struct host_name_list)))) {
317                 crash("Unable to allocate memory for host name list\n");
318         }
319         host_ptr = host_base_ptr;
321         backoff_flag = 0;
322         opterr = 1;
324         /* get command line options
325          * -H denotes a host (actually ignored and picked up later)
326          * -h for help
327          * -V or -v for version
328          * -d to display hostnames rather than addresses
329          * -t sets timeout for packets and tcp connects
330          * -r defines retries (persistence)
331          * -p or -n sets packet count (5)
332          * -b sets packet size (56)
333          * -w sets warning threshhold (200,40%)
334          * -c sets critical threshhold (500,80%)
335          * -i sets interval for both packet transmissions and connect attempts
336          */
337 #define OPT_STR "amH:hvVDdAp:n:b:r:t:i:w:c:"
338         while((c = getopt(argc, argv, OPT_STR)) != EOF) {
339                 switch (c) {
340                         case 'H':
341                                 if(!(host_ptr->entry = malloc(strlen(optarg) + 1))) {
342                                         crash("Failed to allocate memory for hostname");
343                                 }
344                                 memset(host_ptr->entry, 0, strlen(optarg) + 1);
345                                 host_ptr->entry = memcpy(host_ptr->entry, optarg, strlen(optarg));
346                                 if(!(host_ptr->next = malloc(sizeof(struct host_name_list))))
347                                         crash("Failed to allocate memory for hostname");
348                                 host_ptr = host_ptr->next;
349                                 host_ptr->next = NULL;
350 //                              add_name(optarg);
351                                 break;
352                                 /* this is recognized, but silently ignored.
353                                  * host(s) are added later on */
355                                 break;
356                         case 'w':
357                                 if(get_threshold(optarg, &warn)) {
358                                         printf("Illegal threshold pair specified for -%c", c);
359                                         usage();
360                                 }
361                                 break;
363                         case 'c':
364                                 if(get_threshold(optarg, &crit)) {
365                                         printf("Illegal threshold pair specified for -%c", c);
366                                         usage();
367                                 }
368                                 break;
370                         case 't':
371                                 if(!(timeout = (u_int) strtoul(optarg, NULL, 0) * 100)) {
372                                         printf("option -%c requires integer argument\n", c);
373                                         usage();
374                                 }
375                                 break;
377                         case 'r':
378                                 if(!(retry = (u_int) strtoul(optarg, NULL, 0))) {
379                                         printf("option -%c requires integer argument\n", c);
380                                         usage();
381                                 }
382                                 break;
384                         case 'i':
385                                 if(!(interval = (u_int) strtoul(optarg, NULL, 0) * 100)) {
386                                         printf("option -%c requires positive non-zero integer argument\n", c);
387                                         usage();
388                                 }
389                                 break;
391                         case 'p':
392                         case 'n':
393                                 if(!(count = (u_int) strtoul(optarg, NULL, 0))) {
394                                         printf("option -%c requires positive non-zero integer argument\n", c);
395                                         usage();
396                                 }
397                                 break;
399                         case 'b':
400                                 if(!(ping_data_size = (u_int) strtoul(optarg, NULL, 0))) {
401                                         printf("option -%c requires integer argument\n", c);
402                                         usage();
403                                 }
404                                 break;
406                         case 'h':
407                                 usage();
408                                 break;
410                         case 'e':
411                                 elapsed_flag = 1;
412                                 break;
413                                 
414                         case 'm':
415                                 multif_flag = 1;
416                                 break;
417                                 
418                         case 'd':
419                                 name_flag = 1;
420                                 break;
422                         case 'A':
423                                 addr_flag = 1;
424                                 break;
425                                 
426                         case 's':
427                                 stats_flag = 1;
428                                 break;
430                         case 'u':
431                                 unreachable_flag = 1;
432                                 break;
434                         case 'a':
435                                 alive_flag = 1;
436                                 break;
438                         case 'v':
439                                 printf("%s: Version %s $Date$\n", prog, VERSION);
440                                 printf("%s: comments to %s\n", prog, EMAIL);
441                                 exit(STATE_OK);
443                         case 'g':
444                                 /* use IP list generation */
445                                 /* mutex with file input or command line targets */
446                                 generate_flag = 1;
447                                 break;
449                         default:
450                                 printf("option flag -%c specified, but not recognized\n", c);
451                                 usage();
452                                 break;
453                 }
454         }
456         /* arguments are parsed, so now we validate them */
458         if(count > 1) count_flag = 1;
460         /* set threshold values to 10usec units (inherited from fping.c) */
461         crit.rta = crit.rta / 10;
462         warn.rta = warn.rta / 10;
463         select_time = crit.rta;
464         /* this isn't critical, but will most likely not be what the user expects
465          * so we tell him/her about it, but keep running anyways */
466         if(warn.pl > crit.pl || warn.rta > crit.rta) {
467                 select_time = warn.rta;
468                 printf("(WARNING threshold > CRITICAL threshold) :: ");
469                 fflush(stdout);
470         }
472         /* A timeout smaller than maximum rta threshold makes no sense */
473         if(timeout < crit.rta) timeout = crit.rta;
474         else if(timeout < warn.rta) timeout = warn.rta;
476         if((interval < MIN_INTERVAL * 100 || retry > MAX_RETRY) && getuid()) {
477                 printf("%s: these options are too risky for mere mortals.\n", prog);
478                 printf("%s: You need i >= %u and r < %u\n",
479                                 prog, MIN_INTERVAL, MAX_RETRY);
480                 printf("Current settings; i = %d, r = %d\n",
481                            interval / 100, retry);
482                 usage();
483         }
485         if((ping_data_size > MAX_PING_DATA) || (ping_data_size < MIN_PING_DATA)) {
486                 printf("%s: data size %u not valid, must be between %u and %u\n",
487                                 prog, ping_data_size, MIN_PING_DATA, MAX_PING_DATA);
488                 usage();
490         }
492         if((backoff > MAX_BACKOFF_FACTOR) || (backoff < MIN_BACKOFF_FACTOR)) {
493                 printf("%s: backoff factor %.1f not valid, must be between %.1f and %.1f\n",
494                                 prog, backoff, MIN_BACKOFF_FACTOR, MAX_BACKOFF_FACTOR);
495                 usage();
497         }
499         if(count > MAX_COUNT) {
500                 printf("%s: count %u not valid, must be less than %u\n",
501                                 prog, count, MAX_COUNT);
502                 usage();
503         }
505         if(count_flag) {
506                 alive_flag = unreachable_flag = 0;
507         }
509         trials = (count > retry + 1) ? count : retry + 1;
511         /* handle host names supplied on command line or in a file */
512         /* if the generate_flag is on, then generate the IP list */
513         argv = &argv[optind];
515         /* cover allowable conditions */
517         /* generate requires command line parameters beyond the switches */
518         if(generate_flag && !*argv) {
519                 printf("generate flag requires command line parameters beyond switches\n");
520                 usage();
521         }
523         if(*argv && !generate_flag) {
524                 while(*argv) {
525                         if(!(host_ptr->entry = malloc(strlen(*argv) + 1))) {
526                                 crash("Failed to allocate memory for hostname");
527                         }
528                         memset(host_ptr->entry, 0, strlen(*argv) + 1);
529                         host_ptr->entry = memcpy(host_ptr->entry, *argv, strlen(*argv));
530                         if(!(host_ptr->next = malloc(sizeof(struct host_name_list))))
531                                 crash("Failed to allocate memory for hostname");
532                         host_ptr = host_ptr->next;
533                         host_ptr->next = NULL;
535 //                      add_name(*argv);
536                         argv++;
537                 }
538         }
540         // now add all the hosts
541         host_ptr = host_base_ptr;
542         while(host_ptr->next) {
543                 add_name(host_ptr->entry);
544                 host_ptr = host_ptr->next;
545         }
547         if(!num_hosts) {
548                 printf("No hosts to work with!\n\n");
549                 usage();
550         }
552         /* allocate array to hold outstanding ping requests */
553         table = (HOST_ENTRY **) malloc(sizeof(HOST_ENTRY *) * num_hosts);
554         if(!table) crash("Can't malloc array of hosts");
556         cursor = rrlist;
558         for(num_jobs = 0; num_jobs < num_hosts; num_jobs++) {
559                 table[num_jobs] = cursor;
560                 cursor->i = num_jobs;
562                 cursor = cursor->next;
563         }                                                       /* FOR */
565         ping_pkt_size = ping_data_size + SIZE_ICMP_HDR;
567         signal(SIGINT, (void *)finish);
569         gettimeofday(&start_time, &tz);
570         current_time = start_time;
572         last_send_time.tv_sec = current_time.tv_sec - 10000;
574         cursor = rrlist;
575         advance = 0;
577         /* main loop */
578         while(num_jobs) {
579                 /* fetch all packets that receive within time boundaries */
580                 while(num_pingsent &&
581                           cursor &&
582                           cursor->num_sent > cursor->num_recv &&
583                           wait_for_reply(sock)) ;
585                 if(cursor && advance) {
586                         cursor = cursor->next;
587                 }
589                 gettimeofday(&current_time, &tz);
590                 lt = timeval_diff(&current_time, &last_send_time);
591                 ht = timeval_diff(&current_time, &cursor->last_send_time);
593                 advance = 1;
595                 /* if it's OK to send while counting or looping or starting */
596                 if(lt > interval) {
597                         /* send if starting or looping */
598                         if((cursor->num_sent == 0)) {
599                                 send_ping(sock, cursor);
600                                 continue;
601                         }                                       /* IF */
603                         /* send if counting and count not exceeded */
604                         if(count_flag) {
605                                 if(cursor->num_sent < count) {
606                                         send_ping(sock, cursor);
607                                         continue;
608                                 }                               /* IF */
609                         }                                       /* IF */
610                 }                                               /* IF */
612                 /* is-it-alive mode, and timeout exceeded while waiting for a reply */
613                 /*   and we haven't exceeded our retries                            */
614                 if((lt > interval) && !count_flag && !cursor->num_recv &&
615                    (ht > timeout) && (cursor->waiting < retry + 1)) {
616                         num_timeout++;
618                         /* try again */
619                         send_ping(sock, cursor);
620                         continue;
621                 }                                               /* IF */
623                 /* didn't send, can we remove? */
625                 /* remove if counting and count exceeded */
626                 if(count_flag) {
627                         if((cursor->num_sent >= count)) {
628                                 remove_job(cursor);
629                                 continue;
630                         }                                       /* IF */
631                 }                                               /* IF */
632                 else {
633                         /* normal mode, and we got one */
634                         if(cursor->num_recv) {
635                                 remove_job(cursor);
636                                 continue;
637                         }                                       /* IF */
639                         /* normal mode, and timeout exceeded while waiting for a reply */
640                         /* and we've run out of retries, so node is unreachable */
641                         if((ht > timeout) && (cursor->waiting >= retry + 1)) {
642                                 num_timeout++;
643                                 remove_job(cursor);
644                                 continue;
646                         }                                       /* IF */
647                 }                                               /* ELSE */
649                 /* could send to this host, so keep considering it */
650                 if(ht > interval) {
651                         advance = 0;
652                 }
653         }                                                       /* WHILE */
655         finish();
656         return 0;
657 }                                                               /* main() */
659 /************************************************************
660  * Description:
661  *
662  * Main program clean up and exit point
663  ************************************************************/
664 void finish()
666         int i;
667         HOST_ENTRY *h;
669         gettimeofday(&end_time, &tz);
671         /* tot up unreachables */
672         for(i=0; i<num_hosts; i++) {
673                 h = table[i];
675                 if(!h->num_recv) {
676                         num_unreachable++;
677                         status = fin_stat = STATE_CRITICAL;
678                         if(num_hosts == 1) {
679                                 printf("CRITICAL - %s is down (lost 100%%)|"
680                                            "rta=;%d;%d;; pl=100%%;%d;%d;;\n",
681                                            h->host,
682                                            warn.rta / 100, crit.rta / 100,
683                                            warn.pl, crit.pl);
684                         }
685                         else {
686                                 printf("%s is down (lost 100%%)", h->host);
687                         }
688                 }
689                 else {
690                         /* reset the status */
691                         status = STATE_OK;
693                         /* check for warning before critical, for debugging purposes */
694                         if(warn.rta <= h->total_time / h->num_recv) {
695 /*                              printf("warn.rta exceeded\n");
696 */                              status = STATE_WARNING;
697                         }
698                         if(warn.pl <= ((h->num_sent - h->num_recv) * 100) / h->num_sent) {
699 /*                              printf("warn.pl exceeded (pl=%d)\n",
700                                            ((h->num_sent - h->num_recv) * 100) / h->num_sent);
701 */                              status = STATE_WARNING;
702                         }
703                         if(crit.rta <= h->total_time / h->num_recv) {
704 /*                              printf("crit.rta exceeded\n");
705 */                              status = STATE_CRITICAL;
706                         }
707                         if(crit.pl <= ((h->num_sent - h->num_recv) * 100) / h->num_sent) {
708 /*                              printf("crit.pl exceeded (pl=%d)\n",
709                                            ((h->num_sent - h->num_recv) * 100) / h->num_sent);
710 */                              status = STATE_CRITICAL;
711                         }
713                         if(num_hosts == 1 || status != STATE_OK) {
714                                 printf("%s - %s: rta %s ms, lost %d%%",
715                                            status_string[status], h->host,
716                                            sprint_tm(h->total_time / h->num_recv),
717                                            h->num_sent > 0 ? ((h->num_sent - h->num_recv) * 100) / h->num_sent : 0
718                                            );
719                                 /* perfdata only available for single-host stuff */
720                                 if(num_hosts == 1) {
721                                         printf("|rta=%sms;%d;%d;; pl=%d%%;%d;%d;;\n",
722                                                    sprint_tm(h->total_time / h->num_recv), warn.rta / 100, crit.rta / 100,
723                                                    h->num_sent > 0 ? ((h->num_sent - h->num_recv) * 100) / h->num_sent : 0, warn.pl, crit.pl
724                                                    );
725                                 }
726                                 else printf(" :: ");
727                         }
729                         /* fin_stat should always hold the WORST state */
730                         if(fin_stat != STATE_CRITICAL && status != STATE_OK) {
731                                 fin_stat = status;
732                         }
733                 }
734         }
736         if(num_noaddress) {
737                 printf("No hostaddress specified.\n");
738                 usage();
739         }
740         else if(num_alive != num_hosts) {
741                 /* for future multi-check support */
742                 /*printf("num_alive != num_hosts (%d : %d)\n", num_alive, num_hosts);*/
743                 fin_stat = STATE_CRITICAL;
744         }
746         if(num_hosts > 1) {
747                 if(num_alive == num_hosts) {
748                         printf("OK - All %d hosts are alive\n", num_hosts);
749                 }
750                 else {
751                         printf("CRITICAL - %d of %d hosts are alive\n", num_alive, num_hosts);
752                 }
753         }
754         exit(fin_stat);
758 void send_ping(int lsock, HOST_ENTRY *h)
760         char *buffer;
761         struct icmp *icp;
762         PING_DATA *pdp;
763         int n;
765         buffer = (char *)malloc((size_t) ping_pkt_size);
766         if(!buffer)
767                 crash("can't malloc ping packet");
769         memset(buffer, 0, ping_pkt_size * sizeof(char));
770         icp = (struct icmp *)buffer;
772         gettimeofday(&h->last_send_time, &tz);
774         icp->icmp_type = ICMP_ECHO;
775         icp->icmp_code = 0;
776         icp->icmp_cksum = 0;
777         icp->icmp_seq = h->i;
778         icp->icmp_id = ident;
780         pdp = (PING_DATA *) (buffer + SIZE_ICMP_HDR);
781         pdp->ping_ts = h->last_send_time;
782         pdp->ping_count = h->num_sent;
784         icp->icmp_cksum = in_cksum((u_short *) icp, ping_pkt_size);
786         n = sendto(lsock, buffer, ping_pkt_size, 0,
787                            (struct sockaddr *)&h->saddr, sizeof(struct sockaddr_in));
789         if(n < 0 || (unsigned int)n != ping_pkt_size) {
790                 if(unreachable_flag) {
791                         printf("%s error while sending ping: %s\n",
792                                    h->host, strerror(errno));
793                 }                       /* IF */
795                 num_unreachable++;
796                 remove_job(h);
797         }                               /* IF */
798         else {
799                 /* mark this trial as outstanding */
800                 h->resp_times[h->num_sent] = RESP_WAITING;
802                 h->num_sent++;
803                 h->waiting++;
804                 num_pingsent++;
805                 last_send_time = h->last_send_time;
806         }                               /* ELSE */
808         free(buffer);
809 }                                       /* send_ping() */
811 int wait_for_reply(int lsock)
813         int result;
814         static char buffer[4096];
815         struct sockaddr_in response_addr;
816         struct ip *ip;
817         int hlen;
818         struct icmp *icp;
819         int n;
820         HOST_ENTRY *h = NULL;
821         long this_reply;
822         int this_count;
823         struct timeval sent_time;
825         result = recvfrom_wto(lsock, buffer, sizeof(buffer),
826                                                   (struct sockaddr *)&response_addr, select_time);
828         if(result < 0) return 0;                /* timeout */
830         ip = (struct ip *)buffer;
832 #if defined( __alpha__ ) && __STDC__ && !defined( __GLIBC__ )
833         /* The alpha headers are decidedly broken.
834          * Using an ANSI compiler, it provides ip_vhl instead of ip_hl and
835          * ip_v.  So, to get ip_hl, we mask off the bottom four bits.
836          */
837         hlen = (ip->ip_vhl & 0x0F) << 2;
838 #else
839         hlen = ip->ip_hl << 2;
840 #endif /* defined(__alpha__) && __STDC__ */
842         if(result < hlen + ICMP_MINLEN) {
843                 printf("received packet too short for ICMP (%d bytes from %s)\n", result,
844                            inet_ntoa(response_addr.sin_addr));
846                 return (1);                             /* too short */
847         }                                                       /* IF */
849         icp = (struct icmp *)(buffer + hlen);
850         if(icp->icmp_type != ICMP_ECHOREPLY) {
851                 /* handle some problem */
852                 if(handle_random_icmp(icp, &response_addr))
853                         num_othericmprcvd++;
855                 return 1;
856         }                                                       /* IF */
858         if(icp->icmp_id != ident)
859                 return 1;                               /* packet received, but not the one we are looking for! */
861         num_pingreceived++;
863         if(icp->icmp_seq >= (n_short) num_hosts)
864                 return(1);                              /* packet received, don't worry about it anymore */
866         n = icp->icmp_seq;
867         h = table[n];
868         
869         /* received ping is cool, so process it */
871         gettimeofday(&current_time, &tz);
872         h->waiting = 0;
873         h->num_recv++;
875         memcpy(&sent_time, icp->icmp_data + offsetof(PING_DATA, ping_ts),
876                    sizeof(sent_time));
877         memcpy(&this_count, icp->icmp_data, sizeof(this_count));
879         this_reply = timeval_diff(&current_time, &sent_time);
880         h->total_time += this_reply;
881         total_replies++;
883         /* note reply time in array, probably */
884         if((this_count >= 0) && ((unsigned int)this_count < trials)) {
885                 if(h->resp_times[this_count] != RESP_WAITING) {
886                         printf("%s : duplicate for [%d], %d bytes, %s ms",
887                                    h->host, this_count, result, sprint_tm(this_reply));
889                         if(response_addr.sin_addr.s_addr != h->saddr.sin_addr.s_addr)
890                                 printf(" [<- %s]\n", inet_ntoa(response_addr.sin_addr));
891                 }                                       /* IF */
892                 else h->resp_times[this_count] = this_reply;
893         }                                               /* IF */
894         else {
895                 /* count is out of bounds?? */
896                 printf("%s : duplicate for [%d], %d bytes, %s ms\n",
897                            h->host, this_count, result, sprint_tm(this_reply));
898                 }                                               /* ELSE */
899         
900         if(h->num_recv == 1) {
901                 num_alive++;
902         }                                                       /* IF */
904         return num_jobs;
905 }                                                               /* wait_for_reply() */
907 int handle_random_icmp(struct icmp *p, struct sockaddr_in *addr)
909         struct icmp *sent_icmp;
910         u_char *c;
911         HOST_ENTRY *h;
913         c = (u_char *) p;
914         switch (p->icmp_type) {
915         case ICMP_UNREACH:
916                 sent_icmp = (struct icmp *)(c + 28);
918                 if((sent_icmp->icmp_type == ICMP_ECHO) &&
919                    (sent_icmp->icmp_id == ident) &&
920                    (sent_icmp->icmp_seq < (n_short) num_hosts)) {
921                         /* this is a response to a ping we sent */
922                         h = table[sent_icmp->icmp_seq];
924                         if(p->icmp_code > ICMP_UNREACH_MAXTYPE) {
925                                 printf("ICMP Unreachable (Invalid Code) from %s for ICMP Echo sent to %s",
926                                                 inet_ntoa(addr->sin_addr), h->host);
928                         }                                       /* IF */
929                         else {
930                                 printf("ICMP Unreachable from %s for ICMP Echo sent to %s",
931                                            inet_ntoa(addr->sin_addr), h->host);
933                         }                                       /* ELSE */
935                         if(inet_addr(h->host) == INADDR_NONE)
936                                 printf(" (%s)", inet_ntoa(h->saddr.sin_addr));
938                         printf("\n");
940                 }                                               /* IF */
942                 return 1;
944         case ICMP_SOURCEQUENCH:
945         case ICMP_REDIRECT:
946         case ICMP_TIMXCEED:
947         case ICMP_PARAMPROB:
948                 sent_icmp = (struct icmp *)(c + 28);
949                 if((sent_icmp->icmp_type = ICMP_ECHO) &&
950                    (sent_icmp->icmp_id = ident) &&
951                    (sent_icmp->icmp_seq < (n_short) num_hosts)) {
952                         /* this is a response to a ping we sent */
953                         h = table[sent_icmp->icmp_seq];
954                         printf("ICMP Unreachable from %s for ICMP Echo sent to %s",
955                                         inet_ntoa(addr->sin_addr), h->host);
957                         if(inet_addr(h->host) == INADDR_NONE)
958                                 printf(" (%s)", inet_ntoa(h->saddr.sin_addr));
960                         printf("\n");
961                 }                                               /* IF */
963                 return 2;
965                 /* no way to tell whether any of these are sent due to our ping */
966                 /* or not (shouldn't be, of course), so just discard            */
967         case ICMP_TSTAMP:
968         case ICMP_TSTAMPREPLY:
969         case ICMP_IREQ:
970         case ICMP_IREQREPLY:
971         case ICMP_MASKREQ:
972         case ICMP_MASKREPLY:
973         default:
974                 return 0;
976         }                                                       /* SWITCH */
978 }                                                               /* handle_random_icmp() */
980 int in_cksum(u_short * p, int n)
982         register u_short answer;
983         register long sum = 0;
984         u_short odd_byte = 0;
986         while(n > 1) {
987                 sum += *p++;
988                 n -= 2;
989         }                                                       /* WHILE */
991         /* mop up an odd byte, if necessary */
992         if(n == 1) {
993                 *(u_char *) (&odd_byte) = *(u_char *) p;
994                 sum += odd_byte;
995         }                                                       /* IF */
997         sum = (sum >> 16) + (sum & 0xffff);     /* add hi 16 to low 16 */
998         sum += (sum >> 16);                     /* add carry */
999         answer = ~sum;                          /* ones-complement, truncate */
1001         return (answer);
1003 }                                                               /* in_cksum() */
1005 void add_name(char *name)
1007         struct hostent *host_ent;
1008         int ipaddress;
1009         struct in_addr *ipa = (struct in_addr *)&ipaddress;
1010         struct in_addr *host_add;
1011         char *nm;
1012         int i = 0;
1013         
1014         if((ipaddress = inet_addr(name)) != -1) {
1015                 /* input name is an IP addr, go with it */
1016                 if(name_flag) {
1017                         if(addr_flag)
1018                                 add_addr(name, na_cat(get_host_by_address(*ipa), *ipa), *ipa);
1019                         else {
1020                                 nm = cpystr(get_host_by_address(*ipa));
1021                                 add_addr(name, nm, *ipa);
1023                         }                                       /* ELSE */
1024                 }                                               /* IF */
1025                 else add_addr(name, name, *ipa);
1027                 return;
1028         }                                                       /* IF */
1030         /* input name is not an IP addr, maybe it's a host name */
1031         host_ent = gethostbyname(name);
1032         if(host_ent == NULL) {
1033                 if(h_errno == TRY_AGAIN) {
1034                         u_sleep(DNS_TIMEOUT);
1035                         host_ent = gethostbyname(name);
1036                 }                                               /* IF */
1038                 if(host_ent == NULL) {
1039                         printf("%s address not found\n", name);
1040                         num_noaddress++;
1041                         return;
1042                 }                                               /* IF */
1043         }                                                       /* IF */
1045         host_add = (struct in_addr *)*(host_ent->h_addr_list);
1046         if(host_add == NULL) {
1047                 printf("%s has no address data\n", name);
1048                 num_noaddress++;
1049                 return;
1050         }                                                       /* IF */
1051         else {
1052                 /* it is indeed a hostname with a real address */
1053                 while(host_add) {
1054                         if(name_flag && addr_flag)
1055                                 add_addr(name, na_cat(name, *host_add), *host_add);
1056                         else if(addr_flag) {
1057                                 nm = cpystr(inet_ntoa(*host_add));
1058                                 add_addr(name, nm, *host_add);
1059                         }                                       /* ELSE IF */
1060                         else {
1061                                 add_addr(name, name, *host_add);
1062                         }
1064                         if(!multif_flag) break;
1066                         host_add = (struct in_addr *)(host_ent->h_addr_list[++i]);
1067                 }                                               /* WHILE */
1068         }                                                       /* ELSE */
1069 }                                                               /* add_name() */
1072 char *na_cat(char *name, struct in_addr ipaddr)
1074         char *nm, *as;
1076         as = inet_ntoa(ipaddr);
1077         nm = (char *)malloc(strlen(name) + strlen(as) + 4);
1079         if(!nm)
1080                 crash("can't allocate some space for a string");
1082         strcpy(nm, name);
1083         strcat(nm, " (");
1084         strcat(nm, as);
1085         strcat(nm, ")");
1087         return (nm);
1089 }                                                               /* na_cat() */
1092 void add_addr(char *name, char *host, struct in_addr ipaddr)
1094         HOST_ENTRY *p;
1095         unsigned int n;
1096         int *i;
1098         if(!(p = (HOST_ENTRY *) malloc(sizeof(HOST_ENTRY)))) {
1099                 crash("can't allocate HOST_ENTRY");
1100         }
1102         memset((char *)p, 0, sizeof(HOST_ENTRY));
1104         p->name = name;
1105         p->host = host;
1106         p->saddr.sin_family = AF_INET;
1107         p->saddr.sin_addr = ipaddr;
1108         p->running = 1;
1110         /* array for response time results */
1111         if(!(i = (int *)malloc(trials * sizeof(int)))) {
1112                 crash("can't allocate resp_times array");
1113         }
1115         for(n = 1; n < trials; n++)
1116                 i[n] = RESP_UNUSED;
1118                 p->resp_times = i;
1120         if(!rrlist) {
1121                 rrlist = p;
1122                 p->next = p;
1123                 p->prev = p;
1124         }                                                       /* IF */
1125         else {
1126                 p->next = rrlist;
1127                 p->prev = rrlist->prev;
1128                 p->prev->next = p;
1129                 p->next->prev = p;
1130         }                                                       /* ELSE */
1132         num_hosts++;
1133 }                                                               /* add_addr() */
1136 void remove_job(HOST_ENTRY * h)
1138         h->running = 0;
1139         h->waiting = 0;
1140         num_jobs--;
1142         
1143         if(num_jobs) {
1144                 /* remove us from list of active jobs */
1145                 h->prev->next = h->next;
1146                 h->next->prev = h->prev;
1147                 if(h == cursor) cursor = h->next;
1148         }                                                       /* IF */
1149         else {
1150                 cursor = NULL;
1151                 rrlist = NULL;
1152         }                                                       /* ELSE */
1154 }                                                               /* remove_job() */
1157 char *get_host_by_address(struct in_addr in)
1159         struct hostent *h;
1160         h = gethostbyaddr((char *)&in, sizeof(struct in_addr), AF_INET);
1162         if(h == NULL || h->h_name == NULL)
1163                 return inet_ntoa(in);
1164         else
1165                 return (char *)h->h_name;
1167 }                                                               /* get_host_by_address() */
1170 char *cpystr(char *string)
1172         char *dst;
1174         if(string) {
1175                 dst = (char *)malloc(1 + strlen(string));
1176                 if(!dst) crash("malloc() failed!");
1178                 strcpy(dst, string);
1179                 return dst;
1181         }                                                       /* IF */
1182         else return NULL;
1184 }                                                               /* cpystr() */
1187 void crash(char *msg)
1189         if(errno || h_errno) {
1190                 if(errno)
1191                         printf("%s: %s : %s\n", prog, msg, strerror(errno));
1192                 if(h_errno)
1193                         printf("%s: %s : A network error occurred\n", prog, msg);
1194         }
1195         else printf("%s: %s\n", prog, msg);
1197         exit(STATE_UNKNOWN);
1198 }                                                               /* crash() */
1201 long timeval_diff(struct timeval *a, struct timeval *b)
1203         double temp;
1205         temp = (((a->tv_sec * 1000000) + a->tv_usec) -
1206                         ((b->tv_sec * 1000000) + b->tv_usec)) / 10;
1208         return (long)temp;
1210 }                                                               /* timeval_diff() */
1213 char *sprint_tm(int t)
1215         static char buf[10];
1217         /* <= 0.99 ms */
1218         if(t < 100) {
1219                 sprintf(buf, "0.%02d", t);
1220                 return (buf);
1221         }                                                       /* IF */
1223         /* 1.00 - 9.99 ms */
1224         if(t < 1000) {
1225                 sprintf(buf, "%d.%02d", t / 100, t % 100);
1226                 return (buf);
1227         }                                                       /* IF */
1229         /* 10.0 - 99.9 ms */
1230         if(t < 10000) {
1231                 sprintf(buf, "%d.%d", t / 100, (t % 100) / 10);
1232                 return (buf);
1233         }                                                       /* IF */
1235         /* >= 100 ms */
1236         sprintf(buf, "%d", t / 100);
1237         return (buf);
1238 }                                                               /* sprint_tm() */
1241 /*
1242  * select() is posix, so we expect it to be around
1243  */
1244 void u_sleep(int u_sec)
1246         int nfound;
1247         struct timeval to;
1248         fd_set readset, writeset;
1249         
1250         to.tv_sec = u_sec / 1000000;
1251         to.tv_usec = u_sec - (to.tv_sec * 1000000);
1252 /*      printf("u_sleep :: to.tv_sec: %d, to_tv_usec: %d\n",
1253                    (int)to.tv_sec, (int)to.tv_usec);
1254 */      
1255         FD_ZERO(&writeset);
1256         FD_ZERO(&readset);
1257         nfound = select(0, &readset, &writeset, NULL, &to);
1258         if(nfound < 0)
1259                 crash("select() in u_sleep:");
1261         return;
1262 }                                                               /* u_sleep() */
1265 /************************************************************
1266  * Description:
1267  *
1268  * receive with timeout
1269  * returns length of data read or -1 if timeout
1270  * crash on any other errrors
1271  ************************************************************/
1272 /* TODO: add MSG_DONTWAIT to recvfrom flags (currently 0) */
1273 int recvfrom_wto(int lsock, char *buf, int len, struct sockaddr *saddr, int timo)
1275         int nfound = 0, slen, n;
1276         struct timeval to;
1277         fd_set readset, writeset;
1279         to.tv_sec = timo / 1000000;
1280         to.tv_usec = (timo - (to.tv_sec * 1000000)) * 10;
1282 /*      printf("to.tv_sec: %d, to.tv_usec: %d\n", (int)to.tv_sec, (int)to.tv_usec);
1283 */
1285         FD_ZERO(&readset);
1286         FD_ZERO(&writeset);
1287         FD_SET(lsock, &readset);
1288         nfound = select(lsock + 1, &readset, &writeset, NULL, &to);
1289         if(nfound < 0) crash("select() in recvfrom_wto");
1291         if(nfound == 0) return -1;                              /* timeout */
1293         if(nfound) {
1294                 slen = sizeof(struct sockaddr);
1295                 n = recvfrom(sock, buf, len, 0, saddr, &slen);
1296                 if(n < 0) crash("recvfrom");
1297                 return(n);
1298         }
1300         return(0);      /* 0 bytes read, so return it */
1301 }                                                               /* recvfrom_wto() */
1304 /*
1305  * u = micro
1306  * m = milli
1307  * s = seconds
1308  */
1309 int get_threshold(char *str, threshold *th)
1311         unsigned int i, factor = 0;
1312         char *p = NULL;
1314         if(!str || !strlen(str) || !th) return -1;
1316         for(i=0; i<strlen(str); i++) {
1317                 /* we happily accept decimal points in round trip time thresholds,
1318                  * but we ignore them quite blandly. The new way of specifying higher
1319                  * precision is to specify 'u' (for microseconds),
1320                  * 'm' (for millisecs - default) or 's' for seconds. */
1321                 if(!p && !factor) {
1322                         if(str[i] == 's') factor = 1000000;             /* seconds */
1323                         else if(str[i] == 'm') factor = 1000;   /* milliseconds */
1324                         else if(str[i] == 'u') factor = 1;              /* microseconds */
1325                 }
1327                 if(str[i] == '%') str[i] = '\0';
1328                 else if(str[i] == ',' && !p && i != (strlen(str) - 1)) {
1329                         p = &str[i+1];
1330                         str[i] = '\0';
1331                 }
1332         }
1334         /* default to milliseconds */
1335         if(!factor) factor = 1000;
1337         if(!p || !strlen(p)) return -1;
1338         th->rta = (unsigned int)strtoul(str, NULL, 0) * factor;
1339         th->pl = (unsigned int)strtoul(p, NULL, 0);
1340         return 0;
1343 /* make a blahblah */
1344 void usage(void)
1346         printf("\nUsage: %s [options] [targets]\n", prog);
1347         printf("  -H host  target host\n");
1348         printf("  -b n     ping packet size in bytes (default %d)\n", ping_data_size);
1349         printf("  -n|p n   number of pings to send to each target (default %d)\n", count);
1350         printf("  -r n     number of retries (default %d)\n", retry);
1351         printf("  -t n     timeout value (in msec) (default %d)\n", timeout / 100);
1352         printf("  -i n     packet interval (in msec) (default %d)\n", DEFAULT_INTERVAL);
1353 /* XXX - possibly on todo-list
1354         printf("  -m       ping multiple interfaces on target host\n");
1355         printf("  -a       show targets that are alive\n");
1356         printf("  -d       show dead targets\n");
1357 */      printf("  -v       show version\n");
1358         printf("  -D       increase debug output level\n");
1359         printf("  -w       warning threshold pair, given as RTA[ums],PL[%%]\n");
1360         printf("  -c       critical threshold pair, given as RTA[ums],PL[%%]\n");
1361         printf("\n");
1362         printf("Note:\n");
1363         printf("* This program requires root privileges to run properly.\n");
1364         printf("  If it is run as setuid root it will halt with an error if;\n");
1365         printf("    interval < 25 || retries > 5\n\n");
1366         printf("* Threshold pairs are given as such;\n");
1367         printf("    100,40%%\n");
1368         printf("  to set a threshold value pair of 100 milliseconds and 40%% packetloss\n");
1369         printf("  The '%%' sign is optional, and if rta value is suffixed by;\n");
1370         printf("    s, rta time is set in seconds\n");
1371         printf("    m, rta time will be set in milliseconds (this is default)\n");
1372         printf("    u, rta time will be set in microseconds\n");
1373         printf("  Decimal points are silently ignored for sideways compatibility.\n");
1374         printf("\n");
1375         exit(3);
1376 }                                                               /* usage() */