summaryrefslogtreecommitdiffstats
path: root/web/attachments/282511-check_icmp.c
diff options
context:
space:
mode:
Diffstat (limited to 'web/attachments/282511-check_icmp.c')
-rw-r--r--web/attachments/282511-check_icmp.c1301
1 files changed, 1301 insertions, 0 deletions
diff --git a/web/attachments/282511-check_icmp.c b/web/attachments/282511-check_icmp.c
new file mode 100644
index 0000000..fc59f2a
--- /dev/null
+++ b/web/attachments/282511-check_icmp.c
@@ -0,0 +1,1301 @@
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* set TOS-bist (-T): Georg von Zengen <gvz@ciphron.de>
11*
12* Last Modified: $Date: 2008-06-24 17:06:35 +0000 (Tue, 24 JUN 2008) $
13*
14* Description:
15*
16* This file contains the check_icmp plugin
17*
18* Relevant RFC's: 792 (ICMP), 791 (IP)
19*
20* This program was modeled somewhat after the check_icmp program,
21* which was in turn a hack of fping (www.fping.org) but has been
22* completely rewritten since to generate higher precision rta values,
23* and support several different modes as well as setting ttl to control.
24* redundant routes. The only remainders of fping is currently a few
25* function names.
26*
27* License Information:
28*
29* This program is free software; you can redistribute it and/or modify
30* it under the terms of the GNU General Public License as published by
31* the Free Software Foundation; either version 2 of the License, or
32* (at your option) any later version.
33*
34* This program is distributed in the hope that it will be useful,
35* but WITHOUT ANY WARRANTY; without even the implied warranty of
36* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37* GNU General Public License for more details.
38*
39* You should have received a copy of the GNU General Public License
40* along with this program; if not, write to the Free Software
41* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
42*
43* $Id: check_icmp.c 1861 2007-12-11 05:57:35Z dermoth $
44*
45*****************************************************************************/
46
47/* progname may change */
48/* char *progname = "check_icmp"; */
49char *progname;
50const char *revision = "$Revision: 1861 $";
51const char *copyright = "2005-2007";
52const char *email = "nagiosplug-devel@lists.sourceforge.net";
53
54/** nagios plugins basic includes */
55#include "common.h"
56#include "netutils.h"
57#include "utils.h"
58
59#include <sys/time.h>
60#include <sys/types.h>
61#include <stdio.h>
62#include <stdlib.h>
63#include <stdarg.h>
64#include <unistd.h>
65#include <stddef.h>
66#include <errno.h>
67#include <string.h>
68#include <ctype.h>
69#include <netdb.h>
70#include <sys/socket.h>
71#include <netinet/in_systm.h>
72#include <netinet/in.h>
73#include <netinet/ip.h>
74#include <netinet/ip_icmp.h>
75#include <arpa/inet.h>
76#include <signal.h>
77
78
79/** sometimes undefined system macros (quite a few, actually) **/
80#ifndef MAXTTL
81# define MAXTTL 255
82#endif
83#ifndef INADDR_NONE
84# define INADDR_NONE 0xffffffU
85#endif
86
87#ifndef SOL_IP
88#define SOL_IP 0
89#endif
90
91/* we bundle these in one #ifndef, since they're all from BSD
92 * Put individual #ifndef's around those that bother you */
93#ifndef ICMP_UNREACH_NET_UNKNOWN
94# define ICMP_UNREACH_NET_UNKNOWN 6
95# define ICMP_UNREACH_HOST_UNKNOWN 7
96# define ICMP_UNREACH_ISOLATED 8
97# define ICMP_UNREACH_NET_PROHIB 9
98# define ICMP_UNREACH_HOST_PROHIB 10
99# define ICMP_UNREACH_TOSNET 11
100# define ICMP_UNREACH_TOSHOST 12
101#endif
102/* tru64 has the ones above, but not these */
103#ifndef ICMP_UNREACH_FILTER_PROHIB
104# define ICMP_UNREACH_FILTER_PROHIB 13
105# define ICMP_UNREACH_HOST_PRECEDENCE 14
106# define ICMP_UNREACH_PRECEDENCE_CUTOFF 15
107#endif
108
109
110typedef unsigned short range_t; /* type for get_range() -- unimplemented */
111
112typedef struct rta_host {
113 unsigned short id; /* id in **table, and icmp pkts */
114 char *name; /* arg used for adding this host */
115 char *msg; /* icmp error message, if any */
116 struct sockaddr_in saddr_in; /* the address of this host */
117 struct in_addr error_addr; /* stores address of error replies */
118 unsigned long long time_waited; /* total time waited, in usecs */
119 unsigned int icmp_sent, icmp_recv, icmp_lost; /* counters */
120 unsigned char icmp_type, icmp_code; /* type and code from errors */
121 unsigned short flags; /* control/status flags */
122 double rta; /* measured RTA */
123 unsigned char pl; /* measured packet loss */
124 struct rta_host *next; /* linked list */
125} rta_host;
126
127#define FLAG_LOST_CAUSE 0x01 /* decidedly dead target. */
128
129/* threshold structure. all values are maximum allowed, exclusive */
130typedef struct threshold {
131 unsigned char pl; /* max allowed packet loss in percent */
132 unsigned int rta; /* roundtrip time average, microseconds */
133} threshold;
134
135/* the data structure */
136typedef struct icmp_ping_data {
137 struct timeval stime; /* timestamp (saved in protocol struct as well) */
138 unsigned short ping_id;
139} icmp_ping_data;
140
141/* the different modes of this program are as follows:
142 * MODE_RTA: send all packets no matter what (mimic check_icmp and check_ping)
143 * MODE_HOSTCHECK: Return immediately upon any sign of life
144 * In addition, sends packets to ALL addresses assigned
145 * to this host (as returned by gethostbyname() or
146 * gethostbyaddr() and expects one host only to be checked at
147 * a time. Therefore, any packet response what so ever will
148 * count as a sign of life, even when received outside
149 * crit.rta limit. Do not misspell any additional IP's.
150 * MODE_ALL: Requires packets from ALL requested IP to return OK (default).
151 * MODE_ICMP: implement something similar to check_icmp (MODE_RTA without
152 * tcp and udp args does this)
153 */
154#define MODE_RTA 0
155#define MODE_HOSTCHECK 1
156#define MODE_ALL 2
157#define MODE_ICMP 3
158
159/* the different ping types we can do
160 * TODO: investigate ARP ping as well */
161#define HAVE_ICMP 1
162#define HAVE_UDP 2
163#define HAVE_TCP 4
164#define HAVE_ARP 8
165
166#define MIN_PING_DATA_SIZE sizeof(struct icmp_ping_data)
167#define MAX_IP_PKT_SIZE 65536 /* (theoretical) max IP packet size */
168#define IP_HDR_SIZE 20
169#define MAX_PING_DATA (MAX_IP_PKT_SIZE - IP_HDR_SIZE - ICMP_MINLEN)
170#define DEFAULT_PING_DATA_SIZE (MIN_PING_DATA_SIZE + 44)
171
172/* various target states */
173#define TSTATE_INACTIVE 0x01 /* don't ping this host anymore */
174#define TSTATE_WAITING 0x02 /* unanswered packets on the wire */
175#define TSTATE_ALIVE 0x04 /* target is alive (has answered something) */
176#define TSTATE_UNREACH 0x08
177
178/** prototypes **/
179void print_help (void);
180void print_usage (void);
181static u_int get_timevar(const char *);
182static u_int get_timevaldiff(struct timeval *, struct timeval *);
183static int wait_for_reply(int, u_int);
184static int recvfrom_wto(int, char *, unsigned int, struct sockaddr *, u_int *);
185static int send_icmp_ping(int, struct rta_host *);
186static int get_threshold(char *str, threshold *th);
187static void run_checks(void);
188static int add_target(char *);
189static int add_target_ip(char *, struct in_addr *);
190static int handle_random_icmp(struct icmp *, struct sockaddr_in *);
191static unsigned short icmp_checksum(unsigned short *, int);
192static void finish(int);
193static void crash(const char *, ...);
194
195/** external **/
196extern int optind, opterr, optopt;
197extern char *optarg;
198extern char **environ;
199
200/** global variables **/
201static struct rta_host **table, *cursor, *list;
202static threshold crit = {80, 500000}, warn = {40, 200000};
203static int mode, protocols, sockets, debug = 0, timeout = 10;
204static unsigned short icmp_pkt_size, icmp_data_size = DEFAULT_PING_DATA_SIZE;
205static unsigned int icmp_sent = 0, icmp_recv = 0, icmp_lost = 0;
206#define icmp_pkts_en_route (icmp_sent - (icmp_recv + icmp_lost))
207static unsigned short targets_down = 0, targets = 0, packets = 0;
208#define targets_alive (targets - targets_down)
209static unsigned int retry_interval, pkt_interval, target_interval;
210static int icmp_sock, tcp_sock, udp_sock, status = STATE_OK;
211static pid_t pid;
212static struct timezone tz;
213static struct timeval prog_start;
214static unsigned long long max_completion_time = 0;
215static unsigned char ttl = 0; /* outgoing ttl */
216static unsigned int warn_down = 1, crit_down = 1; /* host down threshold values */
217static int min_hosts_alive = -1;
218float pkt_backoff_factor = 1.5;
219float target_backoff_factor = 1.5;
220int tos=0;
221/** code start **/
222static void
223crash(const char *fmt, ...)
224{
225 va_list ap;
226
227 printf("%s: ", progname);
228
229 va_start(ap, fmt);
230 vprintf(fmt, ap);
231 va_end(ap);
232
233 if(errno) printf(": %s", strerror(errno));
234 puts("");
235
236 exit(3);
237}
238
239
240static char *
241get_icmp_error_msg(unsigned char icmp_type, unsigned char icmp_code)
242{
243 char *msg = "unreachable";
244
245 if(debug > 1) printf("get_icmp_error_msg(%u, %u)\n", icmp_type, icmp_code);
246 switch(icmp_type) {
247 case ICMP_UNREACH:
248 switch(icmp_code) {
249 case ICMP_UNREACH_NET: msg = "Net unreachable"; break;
250 case ICMP_UNREACH_HOST: msg = "Host unreachable"; break;
251 case ICMP_UNREACH_PROTOCOL: msg = "Protocol unreachable (firewall?)"; break;
252 case ICMP_UNREACH_PORT: msg = "Port unreachable (firewall?)"; break;
253 case ICMP_UNREACH_NEEDFRAG: msg = "Fragmentation needed"; break;
254 case ICMP_UNREACH_SRCFAIL: msg = "Source route failed"; break;
255 case ICMP_UNREACH_ISOLATED: msg = "Source host isolated"; break;
256 case ICMP_UNREACH_NET_UNKNOWN: msg = "Unknown network"; break;
257 case ICMP_UNREACH_HOST_UNKNOWN: msg = "Unknown host"; break;
258 case ICMP_UNREACH_NET_PROHIB: msg = "Network denied (firewall?)"; break;
259 case ICMP_UNREACH_HOST_PROHIB: msg = "Host denied (firewall?)"; break;
260 case ICMP_UNREACH_TOSNET: msg = "Bad TOS for network (firewall?)"; break;
261 case ICMP_UNREACH_TOSHOST: msg = "Bad TOS for host (firewall?)"; break;
262 case ICMP_UNREACH_FILTER_PROHIB: msg = "Prohibited by filter (firewall)"; break;
263 case ICMP_UNREACH_HOST_PRECEDENCE: msg = "Host precedence violation"; break;
264 case ICMP_UNREACH_PRECEDENCE_CUTOFF: msg = "Precedence cutoff"; break;
265 default: msg = "Invalid code"; break;
266 }
267 break;
268
269 case ICMP_TIMXCEED:
270 /* really 'out of reach', or non-existant host behind a router serving
271 * two different subnets */
272 switch(icmp_code) {
273 case ICMP_TIMXCEED_INTRANS: msg = "Time to live exceeded in transit"; break;
274 case ICMP_TIMXCEED_REASS: msg = "Fragment reassembly time exceeded"; break;
275 default: msg = "Invalid code"; break;
276 }
277 break;
278
279 case ICMP_SOURCEQUENCH: msg = "Transmitting too fast"; break;
280 case ICMP_REDIRECT: msg = "Redirect (change route)"; break;
281 case ICMP_PARAMPROB: msg = "Bad IP header (required option absent)"; break;
282
283 /* the following aren't error messages, so ignore */
284 case ICMP_TSTAMP:
285 case ICMP_TSTAMPREPLY:
286 case ICMP_IREQ:
287 case ICMP_IREQREPLY:
288 case ICMP_MASKREQ:
289 case ICMP_MASKREPLY:
290 default: msg = ""; break;
291 }
292
293 return msg;
294}
295
296static int
297handle_random_icmp(struct icmp *p, struct sockaddr_in *addr)
298{
299 struct icmp sent_icmp;
300 struct rta_host *host = NULL;
301 unsigned char *ptr;
302
303 if(p->icmp_type == ICMP_ECHO && p->icmp_id == pid) {
304 /* echo request from us to us (pinging localhost) */
305 return 0;
306 }
307
308 ptr = (unsigned char *)p;
309 if(debug) printf("handle_random_icmp(%p, %p)\n", (void *)p, (void *)addr);
310
311 /* only handle a few types, since others can't possibly be replies to
312 * us in a sane network (if it is anyway, it will be counted as lost
313 * at summary time, but not as quickly as a proper response */
314 /* TIMXCEED can be an unreach from a router with multiple IP's which
315 * serves two different subnets on the same interface and a dead host
316 * on one net is pinged from the other. The router will respond to
317 * itself and thus set TTL=0 so as to not loop forever. Even when
318 * TIMXCEED actually sends a proper icmp response we will have passed
319 * too many hops to have a hope of reaching it later, in which case it
320 * indicates overconfidence in the network, poor routing or both. */
321 if(p->icmp_type != ICMP_UNREACH && p->icmp_type != ICMP_TIMXCEED &&
322 p->icmp_type != ICMP_SOURCEQUENCH && p->icmp_type != ICMP_PARAMPROB)
323 {
324 return 0;
325 }
326
327 /* might be for us. At least it holds the original package (according
328 * to RFC 792). If it isn't, just ignore it */
329 memcpy(&sent_icmp, ptr + 28, sizeof(sent_icmp));
330 if(sent_icmp.icmp_type != ICMP_ECHO || sent_icmp.icmp_id != pid ||
331 sent_icmp.icmp_seq >= targets)
332 {
333 if(debug) printf("Packet is no response to a packet we sent\n");
334 return 0;
335 }
336
337 /* it is indeed a response for us */
338 host = table[sent_icmp.icmp_seq];
339 if(debug) {
340 printf("Received \"%s\" from %s for ICMP ECHO sent to %s.\n",
341 get_icmp_error_msg(p->icmp_type, p->icmp_code),
342 inet_ntoa(addr->sin_addr), host->name);
343 }
344
345 icmp_lost++;
346 host->icmp_lost++;
347 /* don't spend time on lost hosts any more */
348 if(host->flags & FLAG_LOST_CAUSE) return 0;
349
350 /* source quench means we're sending too fast, so increase the
351 * interval and mark this packet lost */
352 if(p->icmp_type == ICMP_SOURCEQUENCH) {
353 pkt_interval *= pkt_backoff_factor;
354 target_interval *= target_backoff_factor;
355 }
356 else {
357 targets_down++;
358 host->flags |= FLAG_LOST_CAUSE;
359 }
360 host->icmp_type = p->icmp_type;
361 host->icmp_code = p->icmp_code;
362 host->error_addr.s_addr = addr->sin_addr.s_addr;
363
364 return 0;
365}
366
367int
368main(int argc, char **argv)
369{
370 int i;
371 char *ptr;
372 long int arg;
373 int icmp_sockerrno, udp_sockerrno, tcp_sockerrno;
374 int result;
375 struct rta_host *host;
376
377 setlocale (LC_ALL, "");
378 bindtextdomain (PACKAGE, LOCALEDIR);
379 textdomain (PACKAGE);
380
381 /* print a helpful error message if geteuid != 0 */
382 np_warn_if_not_root();
383
384 /* we only need to be setsuid when we get the sockets, so do
385 * that before pointer magic (esp. on network data) */
386 icmp_sockerrno = udp_sockerrno = tcp_sockerrno = sockets = 0;
387
388 if((icmp_sock = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP)) != -1)
389 sockets |= HAVE_ICMP;
390 else icmp_sockerrno = errno;
391
392 /* if((udp_sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1) */
393 /* sockets |= HAVE_UDP; */
394 /* else udp_sockerrno = errno; */
395
396 /* if((tcp_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) != -1) */
397 /* sockets |= HAVE_TCP; */
398 /* else tcp_sockerrno = errno; */
399
400 /* now drop privileges (no effect if not setsuid or geteuid() == 0) */
401 setuid(getuid());
402
403 /* POSIXLY_CORRECT might break things, so unset it (the portable way) */
404 environ = NULL;
405
406 /* use the pid to mark packets as ours */
407 /* Some systems have 32-bit pid_t so mask off only 16 bits */
408 pid = getpid() & 0xffff;
409 /* printf("pid = %u\n", pid); */
410
411 /* get calling name the old-fashioned way for portability instead
412 * of relying on the glibc-ism __progname */
413 ptr = strrchr(argv[0], '/');
414 if(ptr) progname = &ptr[1];
415 else progname = argv[0];
416
417 /* now set defaults. Use progname to set them initially (allows for
418 * superfast check_host program when target host is up */
419 cursor = list = NULL;
420 table = NULL;
421
422 mode = MODE_RTA;
423 crit.rta = 500000;
424 crit.pl = 80;
425 warn.rta = 200000;
426 warn.pl = 40;
427 protocols = HAVE_ICMP | HAVE_UDP | HAVE_TCP;
428 pkt_interval = 80000; /* 80 msec packet interval by default */
429 packets = 5;
430
431 if(!strcmp(progname, "check_icmp") || !strcmp(progname, "check_ping")) {
432 mode = MODE_ICMP;
433 protocols = HAVE_ICMP;
434 }
435 else if(!strcmp(progname, "check_host")) {
436 mode = MODE_HOSTCHECK;
437 pkt_interval = 1000000;
438 packets = 5;
439 crit.rta = warn.rta = 1000000;
440 crit.pl = warn.pl = 100;
441 }
442 else if(!strcmp(progname, "check_rta_multi")) {
443 mode = MODE_ALL;
444 target_interval = 0;
445 pkt_interval = 50000;
446 packets = 5;
447 }
448
449 /* parse the arguments */
450 for(i = 1; i < argc; i++) {
451 while((arg = getopt(argc, argv, "vhVw:c:n:p:t:H:i:b:I:l:m:T:")) != EOF) {
452 switch(arg) {
453 case 'T':
454 //tos = strtoul(optarg, NULL, 0);
455 sscanf(optarg,"%x",&tos);
456 if (tos > 0xff){
457 crash("value of -T must not be greater than 0xFF\n");
458 }
459 if(tos < 0){
460 crash("value of -T must be greater than 0x00\n");
461 }
462 //tos = xtoi(tos, NULL, 0);
463 // printf("\n%d\n",tos);
464 break;
465 case 'v':
466 debug++;
467 break;
468 case 'b':
469 /* silently ignored for now */
470 break;
471 case 'i':
472 pkt_interval = get_timevar(optarg);
473 break;
474 case 'I':
475 target_interval = get_timevar(optarg);
476 break;
477 case 'w':
478 get_threshold(optarg, &warn);
479 break;
480 case 'c':
481 get_threshold(optarg, &crit);
482 break;
483 case 'n':
484 case 'p':
485 packets = strtoul(optarg, NULL, 0);
486 break;
487 case 't':
488 timeout = strtoul(optarg, NULL, 0);
489 if(!timeout) timeout = 10;
490 break;
491 case 'H':
492 add_target(optarg);
493 break;
494 case 'l':
495 ttl = (unsigned char)strtoul(optarg, NULL, 0);
496 break;
497 case 'm':
498 min_hosts_alive = (int)strtoul(optarg, NULL, 0);
499 break;
500 case 'd': /* implement later, for cluster checks */
501 warn_down = (unsigned char)strtoul(optarg, &ptr, 0);
502 if(ptr) {
503 crit_down = (unsigned char)strtoul(ptr + 1, NULL, 0);
504 }
505 break;
506 case 'V': /* version */
507 /*print_revision (progname, revision);*/ /* FIXME: Why? */
508 exit (STATE_OK);
509 case 'h': /* help */
510 print_help ();
511 exit (STATE_OK);
512 }
513 }
514 }
515
516 argv = &argv[optind];
517 while(*argv) {
518 add_target(*argv);
519 argv++;
520 }
521 if(!targets) {
522 errno = 0;
523 crash("No hosts to check");
524 exit(3);
525 }
526
527 if(!sockets) {
528 if(icmp_sock == -1) {
529 errno = icmp_sockerrno;
530 crash("Failed to obtain ICMP socket");
531 return -1;
532 }
533 /* if(udp_sock == -1) { */
534 /* errno = icmp_sockerrno; */
535 /* crash("Failed to obtain UDP socket"); */
536 /* return -1; */
537 /* } */
538 /* if(tcp_sock == -1) { */
539 /* errno = icmp_sockerrno; */
540 /* crash("Failed to obtain TCP socker"); */
541 /* return -1; */
542 /* } */
543 }
544 if(!ttl) ttl = 64;
545
546 if(icmp_sock) {
547 result = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
548 if(debug) {
549 if(result == -1) printf("setsockopt failed\n");
550 else printf("ttl set to %u\n", ttl);
551 }
552 }
553 if(tos > 0) {
554 result = setsockopt(icmp_sock, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
555 }
556 /* stupid users should be able to give whatever thresholds they want
557 * (nothing will break if they do), but some anal plugin maintainer
558 * will probably add some printf() thing here later, so it might be
559 * best to at least show them where to do it. ;) */
560 if(warn.pl > crit.pl) warn.pl = crit.pl;
561 if(warn.rta > crit.rta) warn.rta = crit.rta;
562 if(warn_down > crit_down) crit_down = warn_down;
563
564 signal(SIGINT, finish);
565 signal(SIGHUP, finish);
566 signal(SIGTERM, finish);
567 signal(SIGALRM, finish);
568 if(debug) printf("Setting alarm timeout to %u seconds\n", timeout);
569 alarm(timeout);
570
571 /* make sure we don't wait any longer than necessary */
572 gettimeofday(&prog_start, &tz);
573 max_completion_time =
574 ((targets * packets * pkt_interval) + (targets * target_interval)) +
575 (targets * packets * crit.rta) + crit.rta;
576
577 if(debug) {
578 printf("packets: %u, targets: %u\n"
579 "target_interval: %0.3f, pkt_interval %0.3f\n"
580 "crit.rta: %0.3f\n"
581 "max_completion_time: %0.3f\n",
582 packets, targets,
583 (float)target_interval / 1000, (float)pkt_interval / 1000,
584 (float)crit.rta / 1000,
585 (float)max_completion_time / 1000);
586 }
587
588 if(debug) {
589 if(max_completion_time > (u_int)timeout * 1000000) {
590 printf("max_completion_time: %llu timeout: %u\n",
591 max_completion_time, timeout);
592 printf("Timout must be at lest %llu\n",
593 max_completion_time / 1000000 + 1);
594 }
595 }
596
597 icmp_pkt_size = icmp_data_size + ICMP_MINLEN;
598 if(debug > 2) printf("icmp_pkt_size = %u\n", icmp_pkt_size);
599 if(icmp_pkt_size < sizeof(struct icmp) + sizeof(struct icmp_ping_data)) {
600 icmp_pkt_size = sizeof(struct icmp) + sizeof(struct icmp_ping_data);
601 }
602 if(debug > 2) printf("icmp_pkt_size = %u\n", icmp_pkt_size);
603
604 if(debug) {
605 printf("crit = {%u, %u%%}, warn = {%u, %u%%}\n",
606 crit.rta, crit.pl, warn.rta, warn.pl);
607 printf("pkt_interval: %u target_interval: %u retry_interval: %u\n",
608 pkt_interval, target_interval, retry_interval);
609 printf("icmp_pkt_size: %u timeout: %u\n",
610 icmp_pkt_size, timeout);
611 }
612
613 if(packets > 20) {
614 errno = 0;
615 crash("packets is > 20 (%d)", packets);
616 }
617
618 if(min_hosts_alive < -1) {
619 errno = 0;
620 crash("minimum alive hosts is negative (%i)", min_hosts_alive);
621 }
622
623 host = list;
624 table = malloc(sizeof(struct rta_host **) * (argc - 1));
625 i = 0;
626 while(host) {
627 host->id = i;
628 table[i] = host;
629 host = host->next;
630 i++;
631 }
632
633 run_checks();
634
635 errno = 0;
636 finish(0);
637
638 return(0);
639}
640
641static void
642run_checks()
643{
644 u_int i, t, result;
645 u_int final_wait, time_passed;
646
647 /* this loop might actually violate the pkt_interval or target_interval
648 * settings, but only if there aren't any packets on the wire which
649 * indicates that the target can handle an increased packet rate */
650 for(i = 0; i < packets; i++) {
651 for(t = 0; t < targets; t++) {
652 /* don't send useless packets */
653 if(!targets_alive) finish(0);
654 if(table[t]->flags & FLAG_LOST_CAUSE) {
655 if(debug) printf("%s is a lost cause. not sending any more\n",
656 table[t]->name);
657 continue;
658 }
659
660 /* we're still in the game, so send next packet */
661 (void)send_icmp_ping(icmp_sock, table[t]);
662 result = wait_for_reply(icmp_sock, target_interval);
663 }
664 result = wait_for_reply(icmp_sock, pkt_interval * targets);
665 }
666
667 if(icmp_pkts_en_route && targets_alive) {
668 time_passed = get_timevaldiff(NULL, NULL);
669 final_wait = max_completion_time - time_passed;
670
671 if(debug) {
672 printf("time_passed: %u final_wait: %u max_completion_time: %llu\n",
673 time_passed, final_wait, max_completion_time);
674 }
675 if(time_passed > max_completion_time) {
676 if(debug) printf("Time passed. Finishing up\n");
677 finish(0);
678 }
679
680 /* catch the packets that might come in within the timeframe, but
681 * haven't yet */
682 if(debug) printf("Waiting for %u micro-seconds (%0.3f msecs)\n",
683 final_wait, (float)final_wait / 1000);
684 result = wait_for_reply(icmp_sock, final_wait);
685 }
686}
687
688/* response structure:
689 * ip header : 20 bytes
690 * icmp header : 28 bytes
691 * icmp echo reply : the rest
692 */
693static int
694wait_for_reply(int sock, u_int t)
695{
696 int n, hlen;
697 static char buf[4096];
698 struct sockaddr_in resp_addr;
699 struct ip *ip;
700 struct icmp icp;
701 struct rta_host *host;
702 struct icmp_ping_data data;
703 struct timeval wait_start, now;
704 u_int tdiff, i, per_pkt_wait;
705
706 /* if we can't listen or don't have anything to listen to, just return */
707 if(!t || !icmp_pkts_en_route) return 0;
708
709 gettimeofday(&wait_start, &tz);
710
711 i = t;
712 per_pkt_wait = t / icmp_pkts_en_route;
713 while(icmp_pkts_en_route && get_timevaldiff(&wait_start, NULL) < i) {
714 t = per_pkt_wait;
715
716 /* wrap up if all targets are declared dead */
717 if(!targets_alive ||
718 get_timevaldiff(&prog_start, NULL) >= max_completion_time ||
719 (mode == MODE_HOSTCHECK && targets_down))
720 {
721 finish(0);
722 }
723
724 /* reap responses until we hit a timeout */
725 n = recvfrom_wto(sock, buf, sizeof(buf),
726 (struct sockaddr *)&resp_addr, &t);
727 if(!n) {
728 if(debug > 1) {
729 printf("recvfrom_wto() timed out during a %u usecs wait\n",
730 per_pkt_wait);
731 }
732 continue; /* timeout for this one, so keep trying */
733 }
734 if(n < 0) {
735 if(debug) printf("recvfrom_wto() returned errors\n");
736 return n;
737 }
738
739 ip = (struct ip *)buf;
740 if(debug > 1) printf("received %u bytes from %s\n",
741 ntohs(ip->ip_len), inet_ntoa(resp_addr.sin_addr));
742
743/* obsolete. alpha on tru64 provides the necessary defines, but isn't broken */
744/* #if defined( __alpha__ ) && __STDC__ && !defined( __GLIBC__ ) */
745 /* alpha headers are decidedly broken. Using an ansi compiler,
746 * they provide ip_vhl instead of ip_hl and ip_v, so we mask
747 * off the bottom 4 bits */
748/* hlen = (ip->ip_vhl & 0x0f) << 2; */
749/* #else */
750 hlen = ip->ip_hl << 2;
751/* #endif */
752
753 if(n < (hlen + ICMP_MINLEN)) {
754 crash("received packet too short for ICMP (%d bytes, expected %d) from %s\n",
755 n, hlen + icmp_pkt_size, inet_ntoa(resp_addr.sin_addr));
756 }
757 /* else if(debug) { */
758 /* printf("ip header size: %u, packet size: %u (expected %u, %u)\n", */
759 /* hlen, ntohs(ip->ip_len) - hlen, */
760 /* sizeof(struct ip), icmp_pkt_size); */
761 /* } */
762
763 /* check the response */
764 memcpy(&icp, buf + hlen, sizeof(icp));
765
766 if(icp.icmp_id != pid) {
767 handle_random_icmp(&icp, &resp_addr);
768 continue;
769 }
770
771 if(icp.icmp_type != ICMP_ECHOREPLY || icp.icmp_seq >= targets) {
772 if(debug > 2) printf("not a proper ICMP_ECHOREPLY\n");
773 handle_random_icmp(&icp, &resp_addr);
774 continue;
775 }
776
777 /* this is indeed a valid response */
778 memcpy(&data, icp.icmp_data, sizeof(data));
779
780 host = table[icp.icmp_seq];
781 gettimeofday(&now, &tz);
782 tdiff = get_timevaldiff(&data.stime, &now);
783
784 host->time_waited += tdiff;
785 host->icmp_recv++;
786 icmp_recv++;
787
788 if(debug) {
789 printf("%0.3f ms rtt from %s, outgoing ttl: %u, incoming ttl: %u\n",
790 (float)tdiff / 1000, inet_ntoa(resp_addr.sin_addr),
791 ttl, ip->ip_ttl);
792 }
793
794 /* if we're in hostcheck mode, exit with limited printouts */
795 if(mode == MODE_HOSTCHECK) {
796 printf("OK - %s responds to ICMP. Packet %u, rta %0.3fms|"
797 "pkt=%u;;0;%u rta=%0.3f;%0.3f;%0.3f;;\n",
798 host->name, icmp_recv, (float)tdiff / 1000,
799 icmp_recv, packets, (float)tdiff / 1000,
800 (float)warn.rta / 1000, (float)crit.rta / 1000);
801 exit(STATE_OK);
802 }
803 }
804
805 return 0;
806}
807
808/* the ping functions */
809static int
810send_icmp_ping(int sock, struct rta_host *host)
811{
812 static union {
813 char *buf; /* re-use so we prevent leaks */
814 struct icmp *icp;
815 u_short *cksum_in;
816 } packet = { NULL };
817 long int len;
818 struct icmp_ping_data data;
819 struct timeval tv;
820 struct sockaddr *addr;
821
822 if(sock == -1) {
823 errno = 0;
824 crash("Attempt to send on bogus socket");
825 return -1;
826 }
827 addr = (struct sockaddr *)&host->saddr_in;
828
829 if(!packet.buf) {
830 if (!(packet.buf = malloc(icmp_pkt_size))) {
831 crash("send_icmp_ping(): failed to malloc %d bytes for send buffer",
832 icmp_pkt_size);
833 return -1; /* might be reached if we're in debug mode */
834 }
835 }
836 memset(packet.buf, 0, icmp_pkt_size);
837
838 if((gettimeofday(&tv, &tz)) == -1) return -1;
839
840 data.ping_id = 10; /* host->icmp.icmp_sent; */
841 memcpy(&data.stime, &tv, sizeof(tv));
842 memcpy(&packet.icp->icmp_data, &data, sizeof(data));
843 packet.icp->icmp_type = ICMP_ECHO;
844 packet.icp->icmp_code = 0;
845 packet.icp->icmp_cksum = 0;
846 packet.icp->icmp_id = pid;
847 packet.icp->icmp_seq = host->id;
848 packet.icp->icmp_cksum = icmp_checksum(packet.cksum_in, icmp_pkt_size);
849
850 len = sendto(sock, packet.buf, icmp_pkt_size, 0, (struct sockaddr *)addr,
851 sizeof(struct sockaddr));
852
853 if(len < 0 || (unsigned int)len != icmp_pkt_size) {
854 if(debug) printf("Failed to send ping to %s\n",
855 inet_ntoa(host->saddr_in.sin_addr));
856 return -1;
857 }
858
859 icmp_sent++;
860 host->icmp_sent++;
861
862 return 0;
863}
864
865static int
866recvfrom_wto(int sock, char *buf, unsigned int len, struct sockaddr *saddr,
867 u_int *timo)
868{
869 u_int slen;
870 int n;
871 struct timeval to, then, now;
872 fd_set rd, wr;
873
874 if(!*timo) {
875 if(debug) printf("*timo is not\n");
876 return 0;
877 }
878
879 to.tv_sec = *timo / 1000000;
880 to.tv_usec = (*timo - (to.tv_sec * 1000000));
881
882 FD_ZERO(&rd);
883 FD_ZERO(&wr);
884 FD_SET(sock, &rd);
885 errno = 0;
886 gettimeofday(&then, &tz);
887 n = select(sock + 1, &rd, &wr, NULL, &to);
888 if(n < 0) crash("select() in recvfrom_wto");
889 gettimeofday(&now, &tz);
890 *timo = get_timevaldiff(&then, &now);
891
892 if(!n) return 0; /* timeout */
893
894 slen = sizeof(struct sockaddr);
895
896 return recvfrom(sock, buf, len, 0, saddr, &slen);
897}
898
899static void
900finish(int sig)
901{
902 u_int i = 0;
903 unsigned char pl;
904 double rta;
905 struct rta_host *host;
906 char *status_string[] =
907 {"OK", "WARNING", "CRITICAL", "UNKNOWN", "DEPENDENT"};
908 int hosts_ok = 0;
909 int hosts_warn = 0;
910
911 alarm(0);
912 if(debug > 1) printf("finish(%d) called\n", sig);
913
914 if(icmp_sock != -1) close(icmp_sock);
915 if(udp_sock != -1) close(udp_sock);
916 if(tcp_sock != -1) close(tcp_sock);
917
918 if(debug) {
919 printf("icmp_sent: %u icmp_recv: %u icmp_lost: %u\n",
920 icmp_sent, icmp_recv, icmp_lost);
921 printf("targets: %u targets_alive: %u\n", targets, targets_alive);
922 }
923
924 /* iterate thrice to calculate values, give output, and print perfparse */
925 host = list;
926 while(host) {
927 if(!host->icmp_recv) {
928 /* rta 0 is ofcourse not entirely correct, but will still show up
929 * conspicuosly as missing entries in perfparse and cacti */
930 pl = 100;
931 rta = 0;
932 status = STATE_CRITICAL;
933 /* up the down counter if not already counted */
934 if(!(host->flags & FLAG_LOST_CAUSE) && targets_alive) targets_down++;
935 }
936 else {
937 pl = ((host->icmp_sent - host->icmp_recv) * 100) / host->icmp_sent;
938 rta = (double)host->time_waited / host->icmp_recv;
939 }
940 host->pl = pl;
941 host->rta = rta;
942 if(pl >= crit.pl || rta >= crit.rta) {
943 status = STATE_CRITICAL;
944 }
945 else if(!status && (pl >= warn.pl || rta >= warn.rta)) {
946 status = STATE_WARNING;
947 hosts_warn++;
948 }
949 else {
950 hosts_ok++;
951 }
952
953 host = host->next;
954 }
955 /* this is inevitable */
956 if(!targets_alive) status = STATE_CRITICAL;
957 if(min_hosts_alive > -1) {
958 if(hosts_ok >= min_hosts_alive) status = STATE_OK;
959 else if((hosts_ok + hosts_warn) >= min_hosts_alive) status = STATE_WARNING;
960 }
961 printf("%s - ", status_string[status]);
962
963 host = list;
964 while(host) {
965 if(debug) puts("");
966 if(i) {
967 if(i < targets) printf(" :: ");
968 else printf("\n");
969 }
970 i++;
971 if(!host->icmp_recv) {
972 status = STATE_CRITICAL;
973 if(host->flags & FLAG_LOST_CAUSE) {
974 printf("%s: %s @ %s. rta nan, lost %d%%",
975 host->name,
976 get_icmp_error_msg(host->icmp_type, host->icmp_code),
977 inet_ntoa(host->error_addr),
978 100);
979 }
980 else { /* not marked as lost cause, so we have no flags for it */
981 printf("%s: rta nan, lost 100%%", host->name);
982 }
983 }
984 else { /* !icmp_recv */
985 printf("%s: rta %0.3fms, lost %u%%",
986 host->name, host->rta / 1000, host->pl);
987 }
988
989 host = host->next;
990 }
991
992 /* iterate once more for pretty perfparse output */
993 printf("|");
994 i = 0;
995 host = list;
996 while(host) {
997 if(debug) puts("");
998 printf("%srta=%0.3fms;%0.3f;%0.3f;0; %spl=%u%%;%u;%u;; ",
999 (targets > 1) ? host->name : "",
1000 host->rta / 1000, (float)warn.rta / 1000, (float)crit.rta / 1000,
1001 (targets > 1) ? host->name : "",
1002 host->pl, warn.pl, crit.pl);
1003
1004 host = host->next;
1005 }
1006
1007 if(min_hosts_alive > -1) {
1008 if(hosts_ok >= min_hosts_alive) status = STATE_OK;
1009 else if((hosts_ok + hosts_warn) >= min_hosts_alive) status = STATE_WARNING;
1010 }
1011
1012 /* finish with an empty line */
1013 puts("");
1014 if(debug) printf("targets: %u, targets_alive: %u, hosts_ok: %u, hosts_warn: %u, min_hosts_alive: %i\n",
1015 targets, targets_alive, hosts_ok, hosts_warn, min_hosts_alive);
1016
1017 exit(status);
1018}
1019
1020static u_int
1021get_timevaldiff(struct timeval *early, struct timeval *later)
1022{
1023 u_int ret;
1024 struct timeval now;
1025
1026 if(!later) {
1027 gettimeofday(&now, &tz);
1028 later = &now;
1029 }
1030 if(!early) early = &prog_start;
1031
1032 /* if early > later we return 0 so as to indicate a timeout */
1033 if(early->tv_sec > early->tv_sec ||
1034 (early->tv_sec == later->tv_sec && early->tv_usec > later->tv_usec))
1035 {
1036 return 0;
1037 }
1038
1039 ret = (later->tv_sec - early->tv_sec) * 1000000;
1040 ret += later->tv_usec - early->tv_usec;
1041
1042 return ret;
1043}
1044
1045static int
1046add_target_ip(char *arg, struct in_addr *in)
1047{
1048 struct rta_host *host;
1049
1050 /* disregard obviously stupid addresses */
1051 if(in->s_addr == INADDR_NONE || in->s_addr == INADDR_ANY)
1052 return -1;
1053
1054 /* no point in adding two identical IP's, so don't. ;) */
1055 host = list;
1056 while(host) {
1057 if(host->saddr_in.sin_addr.s_addr == in->s_addr) {
1058 if(debug) printf("Identical IP already exists. Not adding %s\n", arg);
1059 return -1;
1060 }
1061 host = host->next;
1062 }
1063
1064 /* add the fresh ip */
1065 host = malloc(sizeof(struct rta_host));
1066 if(!host) {
1067 crash("add_target_ip(%s, %s): malloc(%d) failed",
1068 arg, inet_ntoa(*in), sizeof(struct rta_host));
1069 }
1070 memset(host, 0, sizeof(struct rta_host));
1071
1072 /* set the values. use calling name for output */
1073 host->name = strdup(arg);
1074
1075 /* fill out the sockaddr_in struct */
1076 host->saddr_in.sin_family = AF_INET;
1077 host->saddr_in.sin_addr.s_addr = in->s_addr;
1078
1079 if(!list) list = cursor = host;
1080 else cursor->next = host;
1081
1082 cursor = host;
1083 targets++;
1084
1085 return 0;
1086}
1087
1088/* wrapper for add_target_ip */
1089static int
1090add_target(char *arg)
1091{
1092 int i;
1093 struct hostent *he;
1094 struct in_addr *in, ip;
1095
1096 /* don't resolve if we don't have to */
1097 if((ip.s_addr = inet_addr(arg)) != INADDR_NONE) {
1098 /* don't add all ip's if we were given a specific one */
1099 return add_target_ip(arg, &ip);
1100 /* he = gethostbyaddr((char *)in, sizeof(struct in_addr), AF_INET); */
1101 /* if(!he) return add_target_ip(arg, in); */
1102 }
1103 else {
1104 errno = 0;
1105 he = gethostbyname(arg);
1106 if(!he) {
1107 errno = 0;
1108 crash("Failed to resolve %s", arg);
1109 return -1;
1110 }
1111 }
1112
1113 /* possibly add all the IP's as targets */
1114 for(i = 0; he->h_addr_list[i]; i++) {
1115 in = (struct in_addr *)he->h_addr_list[i];
1116 add_target_ip(arg, in);
1117
1118 /* this is silly, but it works */
1119 if(mode == MODE_HOSTCHECK || mode == MODE_ALL) {
1120 printf("mode: %d\n", mode);
1121 continue;
1122 }
1123 break;
1124 }
1125
1126 return 0;
1127}
1128/*
1129 * u = micro
1130 * m = milli
1131 * s = seconds
1132 * return value is in microseconds
1133 */
1134static u_int
1135get_timevar(const char *str)
1136{
1137 char p, u, *ptr;
1138 unsigned int len;
1139 u_int i, d; /* integer and decimal, respectively */
1140 u_int factor = 1000; /* default to milliseconds */
1141
1142 if(!str) return 0;
1143 len = strlen(str);
1144 if(!len) return 0;
1145
1146 /* unit might be given as ms|m (millisec),
1147 * us|u (microsec) or just plain s, for seconds */
1148 u = p = '\0';
1149 u = str[len - 1];
1150 if(len >= 2 && !isdigit((int)str[len - 2])) p = str[len - 2];
1151 if(p && u == 's') u = p;
1152 else if(!p) p = u;
1153 if(debug > 2) printf("evaluating %s, u: %c, p: %c\n", str, u, p);
1154
1155 if(u == 'u') factor = 1; /* microseconds */
1156 else if(u == 'm') factor = 1000; /* milliseconds */
1157 else if(u == 's') factor = 1000000; /* seconds */
1158 if(debug > 2) printf("factor is %u\n", factor);
1159
1160 i = strtoul(str, &ptr, 0);
1161 if(!ptr || *ptr != '.' || strlen(ptr) < 2 || factor == 1)
1162 return i * factor;
1163
1164 /* time specified in usecs can't have decimal points, so ignore them */
1165 if(factor == 1) return i;
1166
1167 d = strtoul(ptr + 1, NULL, 0);
1168
1169 /* d is decimal, so get rid of excess digits */
1170 while(d >= factor) d /= 10;
1171
1172 /* the last parenthesis avoids floating point exceptions. */
1173 return ((i * factor) + (d * (factor / 10)));
1174}
1175
1176/* not too good at checking errors, but it'll do (main() should barfe on -1) */
1177static int
1178get_threshold(char *str, threshold *th)
1179{
1180 char *p = NULL, i = 0;
1181
1182 if(!str || !strlen(str) || !th) return -1;
1183
1184 /* pointer magic slims code by 10 lines. i is bof-stop on stupid libc's */
1185 p = &str[strlen(str) - 1];
1186 while(p != &str[1]) {
1187 if(*p == '%') *p = '\0';
1188 else if(*p == ',' && i) {
1189 *p = '\0'; /* reset it so get_timevar(str) works nicely later */
1190 th->pl = (unsigned char)strtoul(p+1, NULL, 0);
1191 break;
1192 }
1193 i = 1;
1194 p--;
1195 }
1196 th->rta = get_timevar(str);
1197
1198 if(!th->rta) return -1;
1199
1200 if(th->rta > MAXTTL * 1000000) th->rta = MAXTTL * 1000000;
1201 if(th->pl > 100) th->pl = 100;
1202
1203 return 0;
1204}
1205
1206unsigned short
1207icmp_checksum(unsigned short *p, int n)
1208{
1209 register unsigned short cksum;
1210 register long sum = 0;
1211
1212 while(n > 1) {
1213 sum += *p++;
1214 n -= 2;
1215 }
1216
1217 /* mop up the occasional odd byte */
1218 if(n == 1) sum += (unsigned char)*p;
1219
1220 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
1221 sum += (sum >> 16); /* add carry */
1222 cksum = ~sum; /* ones-complement, trunc to 16 bits */
1223
1224 return cksum;
1225}
1226
1227void
1228print_help(void)
1229{
1230
1231 /*print_revision (progname, revision);*/ /* FIXME: Why? */
1232
1233 printf ("Copyright (c) 2005 Andreas Ericsson <ae@op5.se>\n");
1234 printf (COPYRIGHT, copyright, email);
1235
1236 printf ("\n\n");
1237
1238 print_usage ();
1239
1240 printf (_(UT_HELP_VRSN));
1241
1242 printf (" %s\n", "-H");
1243 printf (" %s\n", _("specify a target"));
1244 printf (" %s\n", "-w");
1245 printf (" %s", _("warning threshold (currently "));
1246 printf ("%0.3fms,%u%%)\n", (float)warn.rta / 1000 , warn.pl / 1000);
1247 printf (" %s\n", "-c");
1248 printf (" %s", _("critical threshold (currently "));
1249 printf ("%0.3fms,%u%%)\n", (float)crit.rta, crit.pl);
1250 printf (" %s\n", "-n");
1251 printf (" %s", _("number of packets to send (currently "));
1252 printf ("%u)\n",packets);
1253 printf (" %s\n", "-i");
1254 printf (" %s", _("max packet interval (currently "));
1255 printf ("%0.3fms)\n",(float)pkt_interval / 1000);
1256 printf (" %s\n", "-I");
1257 printf (" %s", _("max target interval (currently "));
1258 printf ("%0.3fms)\n", (float)target_interval / 1000);
1259 printf (" %s\n", "-m");
1260 printf (" %s",_("number of alive hosts required for success"));
1261 printf ("\n");
1262 printf (" %s\n", "-l");
1263 printf (" %s", _("TTL on outgoing packets (currently "));
1264 printf ("%u)", ttl);
1265 printf (" %s\n", "-t");
1266 printf (" %s",_("timeout value (seconds, currently "));
1267 printf ("%u)\n", timeout);
1268 printf (" %s\n", "-b");
1269 printf (" %s\n", _("icmp packet size (currenly ignored)"));
1270 printf (" -T\n set TOS in Hex\n");
1271 printf (" %s\n", "-v");
1272 printf (" %s\n", _("verbose"));
1273
1274 printf ("\n");
1275 printf ("%s\n\n", _("The -H switch is optional. Naming a host (or several) to check is not."));
1276 printf ("%s\n", _("Threshold format for -w and -c is 200.25,60% for 200.25 msec RTA and 60%"));
1277 printf ("%s\n", _("packet loss. The default values should work well for most users."));
1278 printf ("%s\n", _("You can specify different RTA factors using the standardized abbreviations"));
1279 printf ("%s\n\n", _("us (microseconds), ms (milliseconds, default) or just plain s for seconds."));
1280/* -d not yet implemented */
1281/* printf ("%s\n", _("Threshold format for -d is warn,crit. 12,14 means WARNING if >= 12 hops"));
1282 printf ("%s\n", _("are spent and CRITICAL if >= 14 hops are spent."));
1283 printf ("%s\n\n", _("NOTE: Some systems decrease TTL when forming ICMP_ECHOREPLY, others do not."));*/
1284 printf ("%s\n\n", _("The -v switch can be specified several times for increased verbosity."));
1285
1286/* printf ("%s\n", _("Long options are currently unsupported."));
1287 printf ("%s\n", _("Options marked with * require an argument"));
1288*/
1289 printf (_(UT_SUPPORT));
1290
1291 printf (_(UT_NOWARRANTY));
1292}
1293
1294
1295
1296void
1297print_usage (void)
1298{
1299 printf (_("Usage:"));
1300 printf(" %s [options] [-H] host1 host2 hostn\n", progname);
1301}