Back to index

nagios-plugins  1.4.16
check_icmp.c
Go to the documentation of this file.
00001 /*****************************************************************************
00002 * 
00003 * Nagios check_icmp plugin
00004 * 
00005 * License: GPL
00006 * Copyright (c) 2005-2008 Nagios Plugins Development Team
00007 * Original Author : Andreas Ericsson <ae@op5.se>
00008 * 
00009 * Description:
00010 * 
00011 * This file contains the check_icmp plugin
00012 * 
00013 * Relevant RFC's: 792 (ICMP), 791 (IP)
00014 * 
00015 * This program was modeled somewhat after the check_icmp program,
00016 * which was in turn a hack of fping (www.fping.org) but has been
00017 * completely rewritten since to generate higher precision rta values,
00018 * and support several different modes as well as setting ttl to control.
00019 * redundant routes. The only remainders of fping is currently a few
00020 * function names.
00021 * 
00022 * 
00023 * This program is free software: you can redistribute it and/or modify
00024 * it under the terms of the GNU General Public License as published by
00025 * the Free Software Foundation, either version 3 of the License, or
00026 * (at your option) any later version.
00027 * 
00028 * This program is distributed in the hope that it will be useful,
00029 * but WITHOUT ANY WARRANTY; without even the implied warranty of
00030 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00031 * GNU General Public License for more details.
00032 * 
00033 * You should have received a copy of the GNU General Public License
00034 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
00035 * 
00036 * 
00037 *****************************************************************************/
00038 
00039 /* progname may change */
00040 /* char *progname = "check_icmp"; */
00041 char *progname;
00042 const char *copyright = "2005-2008";
00043 const char *email = "nagiosplug-devel@lists.sourceforge.net";
00044 
00046 #include "common.h"
00047 #include "netutils.h"
00048 #include "utils.h"
00049 
00050 #if HAVE_SYS_SOCKIO_H
00051 #include <sys/sockio.h>
00052 #endif
00053 #include <sys/ioctl.h>
00054 #include <sys/time.h>
00055 #include <sys/types.h>
00056 #include <stdio.h>
00057 #include <stdlib.h>
00058 #include <stdarg.h>
00059 #include <unistd.h>
00060 #include <stddef.h>
00061 #include <errno.h>
00062 #include <string.h>
00063 #include <ctype.h>
00064 #include <netdb.h>
00065 #include <sys/socket.h>
00066 #include <net/if.h>
00067 #include <netinet/in_systm.h>
00068 #include <netinet/in.h>
00069 #include <netinet/ip.h>
00070 #include <netinet/ip_icmp.h>
00071 #include <arpa/inet.h>
00072 #include <signal.h>
00073 #include <float.h>
00074 
00075 
00077 #ifndef MAXTTL
00078 # define MAXTTL      255
00079 #endif
00080 #ifndef INADDR_NONE
00081 # define INADDR_NONE (in_addr_t)(-1)
00082 #endif
00083 
00084 #ifndef SOL_IP
00085 #define SOL_IP 0
00086 #endif
00087 
00088 /* we bundle these in one #ifndef, since they're all from BSD
00089  * Put individual #ifndef's around those that bother you */
00090 #ifndef ICMP_UNREACH_NET_UNKNOWN
00091 # define ICMP_UNREACH_NET_UNKNOWN 6
00092 # define ICMP_UNREACH_HOST_UNKNOWN 7
00093 # define ICMP_UNREACH_ISOLATED 8
00094 # define ICMP_UNREACH_NET_PROHIB 9
00095 # define ICMP_UNREACH_HOST_PROHIB 10
00096 # define ICMP_UNREACH_TOSNET 11
00097 # define ICMP_UNREACH_TOSHOST 12
00098 #endif
00099 /* tru64 has the ones above, but not these */
00100 #ifndef ICMP_UNREACH_FILTER_PROHIB
00101 # define ICMP_UNREACH_FILTER_PROHIB 13
00102 # define ICMP_UNREACH_HOST_PRECEDENCE 14
00103 # define ICMP_UNREACH_PRECEDENCE_CUTOFF 15
00104 #endif
00105 
00106 #ifndef DBL_MAX
00107 # define DBL_MAX 9.9999999999e999
00108 #endif
00109 
00110 typedef unsigned short range_t;  /* type for get_range() -- unimplemented */
00111 
00112 typedef struct rta_host {
00113        unsigned short id;           /* id in **table, and icmp pkts */
00114        char *name;                  /* arg used for adding this host */
00115        char *msg;                   /* icmp error message, if any */
00116        struct sockaddr_in saddr_in; /* the address of this host */
00117        struct in_addr error_addr;   /* stores address of error replies */
00118        unsigned long long time_waited; /* total time waited, in usecs */
00119        unsigned int icmp_sent, icmp_recv, icmp_lost; /* counters */
00120        unsigned char icmp_type, icmp_code; /* type and code from errors */
00121        unsigned short flags;        /* control/status flags */
00122        double rta;                  /* measured RTA */
00123        double rtmax;                /* max rtt */
00124        double rtmin;                /* min rtt */
00125        unsigned char pl;            /* measured packet loss */
00126        struct rta_host *next;       /* linked list */
00127 } rta_host;
00128 
00129 #define FLAG_LOST_CAUSE 0x01  /* decidedly dead target. */
00130 
00131 /* threshold structure. all values are maximum allowed, exclusive */
00132 typedef struct threshold {
00133        unsigned char pl;    /* max allowed packet loss in percent */
00134        unsigned int rta;  /* roundtrip time average, microseconds */
00135 } threshold;
00136 
00137 /* the data structure */
00138 typedef struct icmp_ping_data {
00139        struct timeval stime;       /* timestamp (saved in protocol struct as well) */
00140        unsigned short ping_id;
00141 } icmp_ping_data;
00142 
00143 /* the different modes of this program are as follows:
00144  * MODE_RTA: send all packets no matter what (mimic check_icmp and check_ping)
00145  * MODE_HOSTCHECK: Return immediately upon any sign of life
00146  *                 In addition, sends packets to ALL addresses assigned
00147  *                 to this host (as returned by gethostbyname() or
00148  *                 gethostbyaddr() and expects one host only to be checked at
00149  *                 a time.  Therefore, any packet response what so ever will
00150  *                 count as a sign of life, even when received outside
00151  *                 crit.rta limit. Do not misspell any additional IP's.
00152  * MODE_ALL:  Requires packets from ALL requested IP to return OK (default).
00153  * MODE_ICMP: implement something similar to check_icmp (MODE_RTA without
00154  *            tcp and udp args does this)
00155  */
00156 #define MODE_RTA 0
00157 #define MODE_HOSTCHECK 1
00158 #define MODE_ALL 2
00159 #define MODE_ICMP 3
00160 
00161 /* the different ping types we can do
00162  * TODO: investigate ARP ping as well */
00163 #define HAVE_ICMP 1
00164 #define HAVE_UDP 2
00165 #define HAVE_TCP 4
00166 #define HAVE_ARP 8
00167 
00168 #define MIN_PING_DATA_SIZE sizeof(struct icmp_ping_data)
00169 #define MAX_IP_PKT_SIZE 65536      /* (theoretical) max IP packet size */
00170 #define IP_HDR_SIZE 20
00171 #define MAX_PING_DATA (MAX_IP_PKT_SIZE - IP_HDR_SIZE - ICMP_MINLEN)
00172 #define DEFAULT_PING_DATA_SIZE (MIN_PING_DATA_SIZE + 44)
00173 
00174 /* various target states */
00175 #define TSTATE_INACTIVE 0x01       /* don't ping this host anymore */
00176 #define TSTATE_WAITING 0x02        /* unanswered packets on the wire */
00177 #define TSTATE_ALIVE 0x04       /* target is alive (has answered something) */
00178 #define TSTATE_UNREACH 0x08
00179 
00181 void print_help (void);
00182 void print_usage (void);
00183 static u_int get_timevar(const char *);
00184 static u_int get_timevaldiff(struct timeval *, struct timeval *);
00185 static in_addr_t get_ip_address(const char *);
00186 static int wait_for_reply(int, u_int);
00187 static int recvfrom_wto(int, void *, unsigned int, struct sockaddr *, u_int *);
00188 static int send_icmp_ping(int, struct rta_host *);
00189 static int get_threshold(char *str, threshold *th);
00190 static void run_checks(void);
00191 static void set_source_ip(char *);
00192 static int add_target(char *);
00193 static int add_target_ip(char *, struct in_addr *);
00194 static int handle_random_icmp(unsigned char *, struct sockaddr_in *);
00195 static unsigned short icmp_checksum(unsigned short *, int);
00196 static void finish(int);
00197 static void crash(const char *, ...);
00198 
00200 extern int optind, opterr, optopt;
00201 extern char *optarg;
00202 extern char **environ;
00203 
00205 static struct rta_host **table, *cursor, *list;
00206 static threshold crit = {80, 500000}, warn = {40, 200000};
00207 static int mode, protocols, sockets, debug = 0, timeout = 10;
00208 static unsigned short icmp_data_size = DEFAULT_PING_DATA_SIZE;
00209 static unsigned short icmp_pkt_size = DEFAULT_PING_DATA_SIZE + ICMP_MINLEN;
00210 
00211 static unsigned int icmp_sent = 0, icmp_recv = 0, icmp_lost = 0;
00212 #define icmp_pkts_en_route (icmp_sent - (icmp_recv + icmp_lost))
00213 static unsigned short targets_down = 0, targets = 0, packets = 0;
00214 #define targets_alive (targets - targets_down)
00215 static unsigned int retry_interval, pkt_interval, target_interval;
00216 static int icmp_sock, tcp_sock, udp_sock, status = STATE_OK;
00217 static pid_t pid;
00218 static struct timezone tz;
00219 static struct timeval prog_start;
00220 static unsigned long long max_completion_time = 0;
00221 static unsigned char ttl = 0;      /* outgoing ttl */
00222 static unsigned int warn_down = 1, crit_down = 1; /* host down threshold values */
00223 static int min_hosts_alive = -1;
00224 float pkt_backoff_factor = 1.5;
00225 float target_backoff_factor = 1.5;
00226 
00228 static void
00229 crash(const char *fmt, ...)
00230 {
00231        va_list ap;
00232 
00233        printf("%s: ", progname);
00234 
00235        va_start(ap, fmt);
00236        vprintf(fmt, ap);
00237        va_end(ap);
00238 
00239        if(errno) printf(": %s", strerror(errno));
00240        puts("");
00241 
00242        exit(3);
00243 }
00244 
00245 
00246 static const char *
00247 get_icmp_error_msg(unsigned char icmp_type, unsigned char icmp_code)
00248 {
00249        const char *msg = "unreachable";
00250 
00251        if(debug > 1) printf("get_icmp_error_msg(%u, %u)\n", icmp_type, icmp_code);
00252        switch(icmp_type) {
00253        case ICMP_UNREACH:
00254               switch(icmp_code) {
00255               case ICMP_UNREACH_NET: msg = "Net unreachable"; break;
00256               case ICMP_UNREACH_HOST:     msg = "Host unreachable"; break;
00257               case ICMP_UNREACH_PROTOCOL: msg = "Protocol unreachable (firewall?)"; break;
00258               case ICMP_UNREACH_PORT: msg = "Port unreachable (firewall?)"; break;
00259               case ICMP_UNREACH_NEEDFRAG: msg = "Fragmentation needed"; break;
00260               case ICMP_UNREACH_SRCFAIL: msg = "Source route failed"; break;
00261               case ICMP_UNREACH_ISOLATED: msg = "Source host isolated"; break;
00262               case ICMP_UNREACH_NET_UNKNOWN: msg = "Unknown network"; break;
00263               case ICMP_UNREACH_HOST_UNKNOWN: msg = "Unknown host"; break;
00264               case ICMP_UNREACH_NET_PROHIB: msg = "Network denied (firewall?)"; break;
00265               case ICMP_UNREACH_HOST_PROHIB: msg = "Host denied (firewall?)"; break;
00266               case ICMP_UNREACH_TOSNET: msg = "Bad TOS for network (firewall?)"; break;
00267               case ICMP_UNREACH_TOSHOST: msg = "Bad TOS for host (firewall?)"; break;
00268               case ICMP_UNREACH_FILTER_PROHIB: msg = "Prohibited by filter (firewall)"; break;
00269               case ICMP_UNREACH_HOST_PRECEDENCE: msg = "Host precedence violation"; break;
00270               case ICMP_UNREACH_PRECEDENCE_CUTOFF: msg = "Precedence cutoff"; break;
00271               default: msg = "Invalid code"; break;
00272               }
00273               break;
00274 
00275        case ICMP_TIMXCEED:
00276               /* really 'out of reach', or non-existant host behind a router serving
00277                * two different subnets */
00278               switch(icmp_code) {
00279               case ICMP_TIMXCEED_INTRANS: msg = "Time to live exceeded in transit"; break;
00280               case ICMP_TIMXCEED_REASS: msg = "Fragment reassembly time exceeded"; break;
00281               default: msg = "Invalid code"; break;
00282               }
00283               break;
00284 
00285        case ICMP_SOURCEQUENCH: msg = "Transmitting too fast"; break;
00286        case ICMP_REDIRECT: msg = "Redirect (change route)"; break;
00287        case ICMP_PARAMPROB: msg = "Bad IP header (required option absent)"; break;
00288 
00289               /* the following aren't error messages, so ignore */
00290        case ICMP_TSTAMP:
00291        case ICMP_TSTAMPREPLY:
00292        case ICMP_IREQ:
00293        case ICMP_IREQREPLY:
00294        case ICMP_MASKREQ:
00295        case ICMP_MASKREPLY:
00296        default: msg = ""; break;
00297        }
00298 
00299        return msg;
00300 }
00301 
00302 static int
00303 handle_random_icmp(unsigned char *packet, struct sockaddr_in *addr)
00304 {
00305        struct icmp p, sent_icmp;
00306        struct rta_host *host = NULL;
00307 
00308        memcpy(&p, packet, sizeof(p));
00309        if(p.icmp_type == ICMP_ECHO && ntohs(p.icmp_id) == pid) {
00310               /* echo request from us to us (pinging localhost) */
00311               return 0;
00312        }
00313 
00314        if(debug) printf("handle_random_icmp(%p, %p)\n", (void *)&p, (void *)addr);
00315 
00316        /* only handle a few types, since others can't possibly be replies to
00317         * us in a sane network (if it is anyway, it will be counted as lost
00318         * at summary time, but not as quickly as a proper response */
00319        /* TIMXCEED can be an unreach from a router with multiple IP's which
00320         * serves two different subnets on the same interface and a dead host
00321         * on one net is pinged from the other. The router will respond to
00322         * itself and thus set TTL=0 so as to not loop forever.  Even when
00323         * TIMXCEED actually sends a proper icmp response we will have passed
00324         * too many hops to have a hope of reaching it later, in which case it
00325         * indicates overconfidence in the network, poor routing or both. */
00326        if(p.icmp_type != ICMP_UNREACH && p.icmp_type != ICMP_TIMXCEED &&
00327           p.icmp_type != ICMP_SOURCEQUENCH && p.icmp_type != ICMP_PARAMPROB)
00328        {
00329               return 0;
00330        }
00331 
00332        /* might be for us. At least it holds the original package (according
00333         * to RFC 792). If it isn't, just ignore it */
00334        memcpy(&sent_icmp, packet + 28, sizeof(sent_icmp));
00335        if(sent_icmp.icmp_type != ICMP_ECHO || ntohs(sent_icmp.icmp_id) != pid ||
00336           ntohs(sent_icmp.icmp_seq) >= targets*packets)
00337        {
00338               if(debug) printf("Packet is no response to a packet we sent\n");
00339               return 0;
00340        }
00341 
00342        /* it is indeed a response for us */
00343        host = table[ntohs(sent_icmp.icmp_seq)/packets];
00344        if(debug) {
00345               printf("Received \"%s\" from %s for ICMP ECHO sent to %s.\n",
00346                         get_icmp_error_msg(p.icmp_type, p.icmp_code),
00347                         inet_ntoa(addr->sin_addr), host->name);
00348        }
00349 
00350        icmp_lost++;
00351        host->icmp_lost++;
00352        /* don't spend time on lost hosts any more */
00353        if(host->flags & FLAG_LOST_CAUSE) return 0;
00354 
00355        /* source quench means we're sending too fast, so increase the
00356         * interval and mark this packet lost */
00357        if(p.icmp_type == ICMP_SOURCEQUENCH) {
00358               pkt_interval *= pkt_backoff_factor;
00359               target_interval *= target_backoff_factor;
00360        }
00361        else {
00362               targets_down++;
00363               host->flags |= FLAG_LOST_CAUSE;
00364        }
00365        host->icmp_type = p.icmp_type;
00366        host->icmp_code = p.icmp_code;
00367        host->error_addr.s_addr = addr->sin_addr.s_addr;
00368 
00369        return 0;
00370 }
00371 
00372 int
00373 main(int argc, char **argv)
00374 {
00375        int i;
00376        char *ptr;
00377        long int arg;
00378        int icmp_sockerrno, udp_sockerrno, tcp_sockerrno;
00379        int result;
00380        struct rta_host *host;
00381 
00382        setlocale (LC_ALL, "");
00383        bindtextdomain (PACKAGE, LOCALEDIR);
00384        textdomain (PACKAGE);
00385 
00386        /* print a helpful error message if geteuid != 0 */
00387        np_warn_if_not_root();
00388 
00389        /* we only need to be setsuid when we get the sockets, so do
00390         * that before pointer magic (esp. on network data) */
00391        icmp_sockerrno = udp_sockerrno = tcp_sockerrno = sockets = 0;
00392 
00393        if((icmp_sock = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP)) != -1)
00394               sockets |= HAVE_ICMP;
00395        else icmp_sockerrno = errno;
00396 
00397        /* if((udp_sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1) */
00398        /*     sockets |= HAVE_UDP; */
00399        /* else udp_sockerrno = errno; */
00400 
00401        /* if((tcp_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) != -1) */
00402        /*     sockets |= HAVE_TCP; */
00403        /* else tcp_sockerrno = errno; */
00404 
00405        /* now drop privileges (no effect if not setsuid or geteuid() == 0) */
00406        setuid(getuid());
00407 
00408        /* POSIXLY_CORRECT might break things, so unset it (the portable way) */
00409        environ = NULL;
00410 
00411        /* use the pid to mark packets as ours */
00412        /* Some systems have 32-bit pid_t so mask off only 16 bits */
00413        pid = getpid() & 0xffff;
00414        /* printf("pid = %u\n", pid); */
00415 
00416        /* get calling name the old-fashioned way for portability instead
00417         * of relying on the glibc-ism __progname */
00418        ptr = strrchr(argv[0], '/');
00419        if(ptr) progname = &ptr[1];
00420        else progname = argv[0];
00421 
00422        /* now set defaults. Use progname to set them initially (allows for
00423         * superfast check_host program when target host is up */
00424        cursor = list = NULL;
00425        table = NULL;
00426 
00427        mode = MODE_RTA;
00428        crit.rta = 500000;
00429        crit.pl = 80;
00430        warn.rta = 200000;
00431        warn.pl = 40;
00432        protocols = HAVE_ICMP | HAVE_UDP | HAVE_TCP;
00433        pkt_interval = 80000;  /* 80 msec packet interval by default */
00434        packets = 5;
00435 
00436        if(!strcmp(progname, "check_icmp") || !strcmp(progname, "check_ping")) {
00437               mode = MODE_ICMP;
00438               protocols = HAVE_ICMP;
00439        }
00440        else if(!strcmp(progname, "check_host")) {
00441               mode = MODE_HOSTCHECK;
00442               pkt_interval = 1000000;
00443               packets = 5;
00444               crit.rta = warn.rta = 1000000;
00445               crit.pl = warn.pl = 100;
00446        }
00447        else if(!strcmp(progname, "check_rta_multi")) {
00448               mode = MODE_ALL;
00449               target_interval = 0;
00450               pkt_interval = 50000;
00451               packets = 5;
00452        }
00453 
00454        /* Parse extra opts if any */
00455        argv=np_extra_opts(&argc, argv, progname);
00456 
00457        /* parse the arguments */
00458        for(i = 1; i < argc; i++) {
00459               while((arg = getopt(argc, argv, "vhVw:c:n:p:t:H:s:i:b:I:l:m:")) != EOF) {
00460                      long size;
00461                      switch(arg) {
00462                      case 'v':
00463                             debug++;
00464                             break;
00465                      case 'b':
00466                             size = strtol(optarg,NULL,0);
00467                             if (size >= (sizeof(struct icmp) + sizeof(struct icmp_ping_data)) &&
00468                                 size < MAX_PING_DATA) {
00469                                    icmp_data_size = size;
00470                                    icmp_pkt_size = size + ICMP_MINLEN;
00471                             } else
00472                                    usage_va("ICMP data length must be between: %d and %d",
00473                                             sizeof(struct icmp) + sizeof(struct icmp_ping_data),
00474                                             MAX_PING_DATA - 1);
00475 
00476                             break;
00477                      case 'i':
00478                             pkt_interval = get_timevar(optarg);
00479                             break;
00480                      case 'I':
00481                             target_interval = get_timevar(optarg);
00482                             break;
00483                      case 'w':
00484                             get_threshold(optarg, &warn);
00485                             break;
00486                      case 'c':
00487                             get_threshold(optarg, &crit);
00488                             break;
00489                      case 'n':
00490                      case 'p':
00491                             packets = strtoul(optarg, NULL, 0);
00492                             break;
00493                      case 't':
00494                             timeout = strtoul(optarg, NULL, 0);
00495                             if(!timeout) timeout = 10;
00496                             break;
00497                      case 'H':
00498                             add_target(optarg);
00499                             break;
00500                      case 'l':
00501                             ttl = (unsigned char)strtoul(optarg, NULL, 0);
00502                             break;
00503                      case 'm':
00504                             min_hosts_alive = (int)strtoul(optarg, NULL, 0);
00505                             break;
00506                      case 'd': /* implement later, for cluster checks */
00507                             warn_down = (unsigned char)strtoul(optarg, &ptr, 0);
00508                             if(ptr) {
00509                                    crit_down = (unsigned char)strtoul(ptr + 1, NULL, 0);
00510                             }
00511                             break;
00512                      case 's': /* specify source IP address */
00513                             set_source_ip(optarg);
00514                             break;
00515       case 'V':                 /* version */
00516         print_revision (progname, NP_VERSION);
00517         exit (STATE_OK);
00518       case 'h':                 /* help */
00519         print_help ();
00520         exit (STATE_OK);
00521                      }
00522               }
00523        }
00524 
00525        argv = &argv[optind];
00526        while(*argv) {
00527               add_target(*argv);
00528               argv++;
00529        }
00530        if(!targets) {
00531               errno = 0;
00532               crash("No hosts to check");
00533               exit(3);
00534        }
00535 
00536        if(!sockets) {
00537               if(icmp_sock == -1) {
00538                      errno = icmp_sockerrno;
00539                      crash("Failed to obtain ICMP socket");
00540                      return -1;
00541               }
00542               /* if(udp_sock == -1) { */
00543               /*     errno = icmp_sockerrno; */
00544               /*     crash("Failed to obtain UDP socket"); */
00545               /*     return -1; */
00546               /* } */
00547               /* if(tcp_sock == -1) { */
00548               /*     errno = icmp_sockerrno; */
00549               /*     crash("Failed to obtain TCP socker"); */
00550               /*     return -1; */
00551               /* } */
00552        }
00553        if(!ttl) ttl = 64;
00554 
00555        if(icmp_sock) {
00556               result = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
00557               if(debug) {
00558                      if(result == -1) printf("setsockopt failed\n");
00559                      else printf("ttl set to %u\n", ttl);
00560               }
00561        }
00562 
00563        /* stupid users should be able to give whatever thresholds they want
00564         * (nothing will break if they do), but some anal plugin maintainer
00565         * will probably add some printf() thing here later, so it might be
00566         * best to at least show them where to do it. ;) */
00567        if(warn.pl > crit.pl) warn.pl = crit.pl;
00568        if(warn.rta > crit.rta) warn.rta = crit.rta;
00569        if(warn_down > crit_down) crit_down = warn_down;
00570 
00571        signal(SIGINT, finish);
00572        signal(SIGHUP, finish);
00573        signal(SIGTERM, finish);
00574        signal(SIGALRM, finish);
00575        if(debug) printf("Setting alarm timeout to %u seconds\n", timeout);
00576        alarm(timeout);
00577 
00578        /* make sure we don't wait any longer than necessary */
00579        gettimeofday(&prog_start, &tz);
00580        max_completion_time =
00581               ((targets * packets * pkt_interval) + (targets * target_interval)) +
00582               (targets * packets * crit.rta) + crit.rta;
00583 
00584        if(debug) {
00585               printf("packets: %u, targets: %u\n"
00586                         "target_interval: %0.3f, pkt_interval %0.3f\n"
00587                         "crit.rta: %0.3f\n"
00588                         "max_completion_time: %0.3f\n",
00589                         packets, targets,
00590                         (float)target_interval / 1000, (float)pkt_interval / 1000,
00591                         (float)crit.rta / 1000,
00592                         (float)max_completion_time / 1000);
00593        }
00594 
00595        if(debug) {
00596               if(max_completion_time > (u_int)timeout * 1000000) {
00597                      printf("max_completion_time: %llu  timeout: %u\n",
00598                                max_completion_time, timeout);
00599                      printf("Timout must be at lest %llu\n",
00600                                max_completion_time / 1000000 + 1);
00601               }
00602        }
00603 
00604        if(debug) {
00605               printf("crit = {%u, %u%%}, warn = {%u, %u%%}\n",
00606                         crit.rta, crit.pl, warn.rta, warn.pl);
00607               printf("pkt_interval: %u  target_interval: %u  retry_interval: %u\n",
00608                         pkt_interval, target_interval, retry_interval);
00609               printf("icmp_pkt_size: %u  timeout: %u\n",
00610                         icmp_pkt_size, timeout);
00611        }
00612 
00613        if(packets > 20) {
00614               errno = 0;
00615               crash("packets is > 20 (%d)", packets);
00616        }
00617 
00618        if(min_hosts_alive < -1) {
00619               errno = 0;
00620               crash("minimum alive hosts is negative (%i)", min_hosts_alive);
00621        }
00622 
00623        host = list;
00624        table = malloc(sizeof(struct rta_host **) * targets);
00625        i = 0;
00626        while(host) {
00627               host->id = i*packets;
00628               table[i] = host;
00629               host = host->next;
00630               i++;
00631        }
00632 
00633        run_checks();
00634 
00635        errno = 0;
00636        finish(0);
00637 
00638        return(0);
00639 }
00640 
00641 static void
00642 run_checks()
00643 {
00644        u_int i, t, result;
00645        u_int final_wait, time_passed;
00646 
00647        /* this loop might actually violate the pkt_interval or target_interval
00648         * settings, but only if there aren't any packets on the wire which
00649         * indicates that the target can handle an increased packet rate */
00650        for(i = 0; i < packets; i++) {
00651               for(t = 0; t < targets; t++) {
00652                      /* don't send useless packets */
00653                      if(!targets_alive) finish(0);
00654                      if(table[t]->flags & FLAG_LOST_CAUSE) {
00655                             if(debug) printf("%s is a lost cause. not sending any more\n",
00656                                                          table[t]->name);
00657                             continue;
00658                      }
00659 
00660                      /* we're still in the game, so send next packet */
00661                      (void)send_icmp_ping(icmp_sock, table[t]);
00662                      result = wait_for_reply(icmp_sock, target_interval);
00663               }
00664               result = wait_for_reply(icmp_sock, pkt_interval * targets);
00665        }
00666 
00667        if(icmp_pkts_en_route && targets_alive) {
00668               time_passed = get_timevaldiff(NULL, NULL);
00669               final_wait = max_completion_time - time_passed;
00670 
00671               if(debug) {
00672                      printf("time_passed: %u  final_wait: %u  max_completion_time: %llu\n",
00673                                time_passed, final_wait, max_completion_time);
00674               }
00675               if(time_passed > max_completion_time) {
00676                      if(debug) printf("Time passed. Finishing up\n");
00677                      finish(0);
00678               }
00679 
00680               /* catch the packets that might come in within the timeframe, but
00681                * haven't yet */
00682               if(debug) printf("Waiting for %u micro-seconds (%0.3f msecs)\n",
00683                                            final_wait, (float)final_wait / 1000);
00684               result = wait_for_reply(icmp_sock, final_wait);
00685        }
00686 }
00687 
00688 /* response structure:
00689  * ip header   : 20 bytes
00690  * icmp header : 28 bytes
00691  * icmp echo reply : the rest
00692  */
00693 static int
00694 wait_for_reply(int sock, u_int t)
00695 {
00696        int n, hlen;
00697        static unsigned char buf[4096];
00698        struct sockaddr_in resp_addr;
00699        struct ip *ip;
00700        struct icmp icp;
00701        struct rta_host *host;
00702        struct icmp_ping_data data;
00703        struct timeval wait_start, now;
00704        u_int tdiff, i, per_pkt_wait;
00705 
00706        /* if we can't listen or don't have anything to listen to, just return */
00707        if(!t || !icmp_pkts_en_route) return 0;
00708 
00709        gettimeofday(&wait_start, &tz);
00710 
00711        i = t;
00712        per_pkt_wait = t / icmp_pkts_en_route;
00713        while(icmp_pkts_en_route && get_timevaldiff(&wait_start, NULL) < i) {
00714               t = per_pkt_wait;
00715 
00716               /* wrap up if all targets are declared dead */
00717               if(!targets_alive ||
00718                  get_timevaldiff(&prog_start, NULL) >= max_completion_time ||
00719                  (mode == MODE_HOSTCHECK && targets_down))
00720               {
00721                      finish(0);
00722               }
00723 
00724               /* reap responses until we hit a timeout */
00725               n = recvfrom_wto(sock, buf, sizeof(buf),
00726                                            (struct sockaddr *)&resp_addr, &t);
00727               if(!n) {
00728                      if(debug > 1) {
00729                             printf("recvfrom_wto() timed out during a %u usecs wait\n",
00730                                       per_pkt_wait);
00731                      }
00732                      continue;     /* timeout for this one, so keep trying */
00733               }
00734               if(n < 0) {
00735                      if(debug) printf("recvfrom_wto() returned errors\n");
00736                      return n;
00737               }
00738 
00739               ip = (struct ip *)buf;
00740               if(debug > 1) printf("received %u bytes from %s\n",
00741                                            ntohs(ip->ip_len), inet_ntoa(resp_addr.sin_addr));
00742 
00743 /* obsolete. alpha on tru64 provides the necessary defines, but isn't broken */
00744 /* #if defined( __alpha__ ) && __STDC__ && !defined( __GLIBC__ ) */
00745               /* alpha headers are decidedly broken. Using an ansi compiler,
00746                * they provide ip_vhl instead of ip_hl and ip_v, so we mask
00747                * off the bottom 4 bits */
00748 /*            hlen = (ip->ip_vhl & 0x0f) << 2; */
00749 /* #else */
00750               hlen = ip->ip_hl << 2;
00751 /* #endif */
00752 
00753               if(n < (hlen + ICMP_MINLEN)) {
00754                      crash("received packet too short for ICMP (%d bytes, expected %d) from %s\n",
00755                               n, hlen + icmp_pkt_size, inet_ntoa(resp_addr.sin_addr));
00756               }
00757               /* else if(debug) { */
00758               /*     printf("ip header size: %u, packet size: %u (expected %u, %u)\n", */
00759               /*               hlen, ntohs(ip->ip_len) - hlen, */
00760               /*               sizeof(struct ip), icmp_pkt_size); */
00761               /* } */
00762 
00763               /* check the response */
00764               memcpy(&icp, buf + hlen, sizeof(icp));
00765 
00766               if(ntohs(icp.icmp_id) != pid || icp.icmp_type != ICMP_ECHOREPLY ||
00767                  ntohs(icp.icmp_seq) >= targets*packets) {
00768                      if(debug > 2) printf("not a proper ICMP_ECHOREPLY\n");
00769                      handle_random_icmp(buf + hlen, &resp_addr);
00770                      continue;
00771               }
00772 
00773               /* this is indeed a valid response */
00774               memcpy(&data, icp.icmp_data, sizeof(data));
00775               if (debug > 2)
00776                      printf("ICMP echo-reply of len %u, id %u, seq %u, cksum 0x%X\n",
00777                             sizeof(data), ntohs(icp.icmp_id), ntohs(icp.icmp_seq), icp.icmp_cksum);
00778 
00779               host = table[ntohs(icp.icmp_seq)/packets];
00780               gettimeofday(&now, &tz);
00781               tdiff = get_timevaldiff(&data.stime, &now);
00782 
00783               host->time_waited += tdiff;
00784               host->icmp_recv++;
00785               icmp_recv++;
00786               if (tdiff > host->rtmax)
00787                      host->rtmax = tdiff;
00788               if (tdiff < host->rtmin)
00789                      host->rtmin = tdiff;
00790 
00791               if(debug) {
00792                      printf("%0.3f ms rtt from %s, outgoing ttl: %u, incoming ttl: %u, max: %0.3f, min: %0.3f\n",
00793                                (float)tdiff / 1000, inet_ntoa(resp_addr.sin_addr),
00794                                ttl, ip->ip_ttl, (float)host->rtmax / 1000, (float)host->rtmin / 1000);
00795               }
00796 
00797               /* if we're in hostcheck mode, exit with limited printouts */
00798               if(mode == MODE_HOSTCHECK) {
00799                      printf("OK - %s responds to ICMP. Packet %u, rta %0.3fms|"
00800                                "pkt=%u;;0;%u rta=%0.3f;%0.3f;%0.3f;;\n",
00801                                host->name, icmp_recv, (float)tdiff / 1000,
00802                                icmp_recv, packets, (float)tdiff / 1000,
00803                                (float)warn.rta / 1000, (float)crit.rta / 1000);
00804                      exit(STATE_OK);
00805               }
00806        }
00807 
00808        return 0;
00809 }
00810 
00811 /* the ping functions */
00812 static int
00813 send_icmp_ping(int sock, struct rta_host *host)
00814 {
00815        static union {
00816               void *buf; /* re-use so we prevent leaks */
00817               struct icmp *icp;
00818               u_short *cksum_in;
00819        } packet = { NULL };
00820        long int len;
00821        struct icmp_ping_data data;
00822        struct timeval tv;
00823        struct sockaddr *addr;
00824 
00825        if(sock == -1) {
00826               errno = 0;
00827               crash("Attempt to send on bogus socket");
00828               return -1;
00829        }
00830        addr = (struct sockaddr *)&host->saddr_in;
00831 
00832        if(!packet.buf) {
00833               if (!(packet.buf = malloc(icmp_pkt_size))) {
00834                      crash("send_icmp_ping(): failed to malloc %d bytes for send buffer",
00835                               icmp_pkt_size);
00836                      return -1;    /* might be reached if we're in debug mode */
00837               }
00838        }
00839        memset(packet.buf, 0, icmp_pkt_size);
00840 
00841        if((gettimeofday(&tv, &tz)) == -1) return -1;
00842 
00843        data.ping_id = 10; /* host->icmp.icmp_sent; */
00844        memcpy(&data.stime, &tv, sizeof(tv));
00845        memcpy(&packet.icp->icmp_data, &data, sizeof(data));
00846        packet.icp->icmp_type = ICMP_ECHO;
00847        packet.icp->icmp_code = 0;
00848        packet.icp->icmp_cksum = 0;
00849        packet.icp->icmp_id = htons(pid);
00850        packet.icp->icmp_seq = htons(host->id++);
00851        packet.icp->icmp_cksum = icmp_checksum(packet.cksum_in, icmp_pkt_size);
00852 
00853        if (debug > 2)
00854               printf("Sending ICMP echo-request of len %u, id %u, seq %u, cksum 0x%X to host %s\n",
00855                      sizeof(data), ntohs(packet.icp->icmp_id), ntohs(packet.icp->icmp_seq), packet.icp->icmp_cksum, host->name);
00856 
00857        len = sendto(sock, packet.buf, icmp_pkt_size, 0, (struct sockaddr *)addr,
00858                              sizeof(struct sockaddr));
00859 
00860        if(len < 0 || (unsigned int)len != icmp_pkt_size) {
00861               if(debug) printf("Failed to send ping to %s\n",
00862                                            inet_ntoa(host->saddr_in.sin_addr));
00863               return -1;
00864        }
00865 
00866        icmp_sent++;
00867        host->icmp_sent++;
00868 
00869        return 0;
00870 }
00871 
00872 static int
00873 recvfrom_wto(int sock, void *buf, unsigned int len, struct sockaddr *saddr,
00874                       u_int *timo)
00875 {
00876        u_int slen;
00877        int n;
00878        struct timeval to, then, now;
00879        fd_set rd, wr;
00880 
00881        if(!*timo) {
00882               if(debug) printf("*timo is not\n");
00883               return 0;
00884        }
00885 
00886        to.tv_sec = *timo / 1000000;
00887        to.tv_usec = (*timo - (to.tv_sec * 1000000));
00888 
00889        FD_ZERO(&rd);
00890        FD_ZERO(&wr);
00891        FD_SET(sock, &rd);
00892        errno = 0;
00893        gettimeofday(&then, &tz);
00894        n = select(sock + 1, &rd, &wr, NULL, &to);
00895        if(n < 0) crash("select() in recvfrom_wto");
00896        gettimeofday(&now, &tz);
00897        *timo = get_timevaldiff(&then, &now);
00898 
00899        if(!n) return 0;                          /* timeout */
00900 
00901        slen = sizeof(struct sockaddr);
00902 
00903        return recvfrom(sock, buf, len, 0, saddr, &slen);
00904 }
00905 
00906 static void
00907 finish(int sig)
00908 {
00909        u_int i = 0;
00910        unsigned char pl;
00911        double rta;
00912        struct rta_host *host;
00913        const char *status_string[] =
00914        {"OK", "WARNING", "CRITICAL", "UNKNOWN", "DEPENDENT"};
00915        int hosts_ok = 0;
00916        int hosts_warn = 0;
00917 
00918        alarm(0);
00919        if(debug > 1) printf("finish(%d) called\n", sig);
00920 
00921        if(icmp_sock != -1) close(icmp_sock);
00922        if(udp_sock != -1) close(udp_sock);
00923        if(tcp_sock != -1) close(tcp_sock);
00924 
00925        if(debug) {
00926               printf("icmp_sent: %u  icmp_recv: %u  icmp_lost: %u\n",
00927                         icmp_sent, icmp_recv, icmp_lost);
00928               printf("targets: %u  targets_alive: %u\n", targets, targets_alive);
00929        }
00930 
00931        /* iterate thrice to calculate values, give output, and print perfparse */
00932        host = list;
00933        while(host) {
00934               if(!host->icmp_recv) {
00935                      /* rta 0 is ofcourse not entirely correct, but will still show up
00936                       * conspicuosly as missing entries in perfparse and cacti */
00937                      pl = 100;
00938                      rta = 0;
00939                      status = STATE_CRITICAL;
00940                      /* up the down counter if not already counted */
00941                      if(!(host->flags & FLAG_LOST_CAUSE) && targets_alive) targets_down++;
00942               }
00943               else {
00944                      pl = ((host->icmp_sent - host->icmp_recv) * 100) / host->icmp_sent;
00945                      rta = (double)host->time_waited / host->icmp_recv;
00946               }
00947               host->pl = pl;
00948               host->rta = rta;
00949               if(pl >= crit.pl || rta >= crit.rta) {
00950                      status = STATE_CRITICAL;
00951               }
00952               else if(!status && (pl >= warn.pl || rta >= warn.rta)) {
00953                      status = STATE_WARNING;
00954                      hosts_warn++;
00955               }
00956               else {
00957                      hosts_ok++;
00958               }
00959 
00960               host = host->next;
00961        }
00962        /* this is inevitable */
00963        if(!targets_alive) status = STATE_CRITICAL;
00964        if(min_hosts_alive > -1) {
00965               if(hosts_ok >= min_hosts_alive) status = STATE_OK;
00966               else if((hosts_ok + hosts_warn) >= min_hosts_alive) status = STATE_WARNING;
00967        }
00968        printf("%s - ", status_string[status]);
00969 
00970        host = list;
00971        while(host) {
00972               if(debug) puts("");
00973               if(i) {
00974                      if(i < targets) printf(" :: ");
00975                      else printf("\n");
00976               }
00977               i++;
00978               if(!host->icmp_recv) {
00979                      status = STATE_CRITICAL;
00980                      if(host->flags & FLAG_LOST_CAUSE) {
00981                             printf("%s: %s @ %s. rta nan, lost %d%%",
00982                                       host->name,
00983                                       get_icmp_error_msg(host->icmp_type, host->icmp_code),
00984                                       inet_ntoa(host->error_addr),
00985                                       100);
00986                      }
00987                      else { /* not marked as lost cause, so we have no flags for it */
00988                             printf("%s: rta nan, lost 100%%", host->name);
00989                      }
00990               }
00991               else { /* !icmp_recv */
00992                      printf("%s: rta %0.3fms, lost %u%%",
00993                                host->name, host->rta / 1000, host->pl);
00994               }
00995 
00996               host = host->next;
00997        }
00998 
00999        /* iterate once more for pretty perfparse output */
01000        printf("|");
01001        i = 0;
01002        host = list;
01003        while(host) {
01004               if(debug) puts("");
01005               printf("%srta=%0.3fms;%0.3f;%0.3f;0; %spl=%u%%;%u;%u;; %srtmax=%0.3fms;;;; %srtmin=%0.3fms;;;; ",
01006                         (targets > 1) ? host->name : "",
01007                         host->rta / 1000, (float)warn.rta / 1000, (float)crit.rta / 1000,
01008                         (targets > 1) ? host->name : "", host->pl, warn.pl, crit.pl,
01009                         (targets > 1) ? host->name : "", (float)host->rtmax / 1000,
01010                         (targets > 1) ? host->name : "", (host->rtmin < DBL_MAX) ? (float)host->rtmin / 1000 : (float)0);
01011 
01012               host = host->next;
01013        }
01014 
01015        if(min_hosts_alive > -1) {
01016               if(hosts_ok >= min_hosts_alive) status = STATE_OK;
01017               else if((hosts_ok + hosts_warn) >= min_hosts_alive) status = STATE_WARNING;
01018        }
01019 
01020        /* finish with an empty line */
01021        puts("");
01022        if(debug) printf("targets: %u, targets_alive: %u, hosts_ok: %u, hosts_warn: %u, min_hosts_alive: %i\n",
01023                                     targets, targets_alive, hosts_ok, hosts_warn, min_hosts_alive);
01024 
01025        exit(status);
01026 }
01027 
01028 static u_int
01029 get_timevaldiff(struct timeval *early, struct timeval *later)
01030 {
01031        u_int ret;
01032        struct timeval now;
01033 
01034        if(!later) {
01035               gettimeofday(&now, &tz);
01036               later = &now;
01037        }
01038        if(!early) early = &prog_start;
01039 
01040        /* if early > later we return 0 so as to indicate a timeout */
01041        if(early->tv_sec > later->tv_sec ||
01042           (early->tv_sec == later->tv_sec && early->tv_usec > later->tv_usec))
01043        {
01044               return 0;
01045        }
01046 
01047        ret = (later->tv_sec - early->tv_sec) * 1000000;
01048        ret += later->tv_usec - early->tv_usec;
01049 
01050        return ret;
01051 }
01052 
01053 static int
01054 add_target_ip(char *arg, struct in_addr *in)
01055 {
01056        struct rta_host *host;
01057 
01058        /* disregard obviously stupid addresses */
01059        if(in->s_addr == INADDR_NONE || in->s_addr == INADDR_ANY)
01060               return -1;
01061 
01062        /* no point in adding two identical IP's, so don't. ;) */
01063        host = list;
01064        while(host) {
01065               if(host->saddr_in.sin_addr.s_addr == in->s_addr) {
01066                      if(debug) printf("Identical IP already exists. Not adding %s\n", arg);
01067                      return -1;
01068               }
01069               host = host->next;
01070        }
01071 
01072        /* add the fresh ip */
01073        host = malloc(sizeof(struct rta_host));
01074        if(!host) {
01075               crash("add_target_ip(%s, %s): malloc(%d) failed",
01076                        arg, inet_ntoa(*in), sizeof(struct rta_host));
01077        }
01078        memset(host, 0, sizeof(struct rta_host));
01079 
01080        /* set the values. use calling name for output */
01081        host->name = strdup(arg);
01082 
01083        /* fill out the sockaddr_in struct */
01084        host->saddr_in.sin_family = AF_INET;
01085        host->saddr_in.sin_addr.s_addr = in->s_addr;
01086 
01087        host->rtmin = DBL_MAX;
01088 
01089        if(!list) list = cursor = host;
01090        else cursor->next = host;
01091 
01092        cursor = host;
01093        targets++;
01094 
01095        return 0;
01096 }
01097 
01098 /* wrapper for add_target_ip */
01099 static int
01100 add_target(char *arg)
01101 {
01102        int i;
01103        struct hostent *he;
01104        struct in_addr *in, ip;
01105 
01106        /* don't resolve if we don't have to */
01107        if((ip.s_addr = inet_addr(arg)) != INADDR_NONE) {
01108               /* don't add all ip's if we were given a specific one */
01109               return add_target_ip(arg, &ip);
01110               /* he = gethostbyaddr((char *)in, sizeof(struct in_addr), AF_INET); */
01111               /* if(!he) return add_target_ip(arg, in); */
01112        }
01113        else {
01114               errno = 0;
01115               he = gethostbyname(arg);
01116               if(!he) {
01117                      errno = 0;
01118                      crash("Failed to resolve %s", arg);
01119                      return -1;
01120               }
01121        }
01122 
01123        /* possibly add all the IP's as targets */
01124        for(i = 0; he->h_addr_list[i]; i++) {
01125               in = (struct in_addr *)he->h_addr_list[i];
01126               add_target_ip(arg, in);
01127 
01128               /* this is silly, but it works */
01129               if(mode == MODE_HOSTCHECK || mode == MODE_ALL) {
01130                      if(debug > 2) printf("mode: %d\n", mode);
01131                      continue;
01132               }
01133               break;
01134        }
01135 
01136        return 0;
01137 }
01138 
01139 static void
01140 set_source_ip(char *arg)
01141 {
01142        struct sockaddr_in src;
01143 
01144        memset(&src, 0, sizeof(src));
01145        src.sin_family = AF_INET;
01146        if((src.sin_addr.s_addr = inet_addr(arg)) == INADDR_NONE)
01147               src.sin_addr.s_addr = get_ip_address(arg);
01148        if(bind(icmp_sock, (struct sockaddr *)&src, sizeof(src)) == -1)
01149               crash("Cannot bind to IP address %s", arg);
01150 }
01151 
01152 /* TODO: Move this to netutils.c and also change check_dhcp to use that. */
01153 static in_addr_t
01154 get_ip_address(const char *ifname)
01155 {
01156 #if defined(SIOCGIFADDR)
01157        struct ifreq ifr;
01158        struct sockaddr_in ip;
01159 
01160        strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name) - 1);
01161        ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = '\0';
01162        if(ioctl(icmp_sock, SIOCGIFADDR, &ifr) == -1)
01163               crash("Cannot determine IP address of interface %s", ifname);
01164        memcpy(&ip, &ifr.ifr_addr, sizeof(ip));
01165        return ip.sin_addr.s_addr;
01166 #else
01167        errno = 0;
01168        crash("Cannot get interface IP address on this platform.");
01169 #endif
01170 }
01171 
01172 /*
01173  * u = micro
01174  * m = milli
01175  * s = seconds
01176  * return value is in microseconds
01177  */
01178 static u_int
01179 get_timevar(const char *str)
01180 {
01181        char p, u, *ptr;
01182        unsigned int len;
01183        u_int i, d;               /* integer and decimal, respectively */
01184        u_int factor = 1000;    /* default to milliseconds */
01185 
01186        if(!str) return 0;
01187        len = strlen(str);
01188        if(!len) return 0;
01189 
01190        /* unit might be given as ms|m (millisec),
01191         * us|u (microsec) or just plain s, for seconds */
01192        u = p = '\0';
01193        u = str[len - 1];
01194        if(len >= 2 && !isdigit((int)str[len - 2])) p = str[len - 2];
01195        if(p && u == 's') u = p;
01196        else if(!p) p = u;
01197        if(debug > 2) printf("evaluating %s, u: %c, p: %c\n", str, u, p);
01198 
01199        if(u == 'u') factor = 1;            /* microseconds */
01200        else if(u == 'm') factor = 1000;   /* milliseconds */
01201        else if(u == 's') factor = 1000000;       /* seconds */
01202        if(debug > 2) printf("factor is %u\n", factor);
01203 
01204        i = strtoul(str, &ptr, 0);
01205        if(!ptr || *ptr != '.' || strlen(ptr) < 2 || factor == 1)
01206               return i * factor;
01207 
01208        /* time specified in usecs can't have decimal points, so ignore them */
01209        if(factor == 1) return i;
01210 
01211        d = strtoul(ptr + 1, NULL, 0);
01212 
01213        /* d is decimal, so get rid of excess digits */
01214        while(d >= factor) d /= 10;
01215 
01216        /* the last parenthesis avoids floating point exceptions. */
01217        return ((i * factor) + (d * (factor / 10)));
01218 }
01219 
01220 /* not too good at checking errors, but it'll do (main() should barfe on -1) */
01221 static int
01222 get_threshold(char *str, threshold *th)
01223 {
01224        char *p = NULL, i = 0;
01225 
01226        if(!str || !strlen(str) || !th) return -1;
01227 
01228        /* pointer magic slims code by 10 lines. i is bof-stop on stupid libc's */
01229        p = &str[strlen(str) - 1];
01230        while(p != &str[1]) {
01231               if(*p == '%') *p = '\0';
01232               else if(*p == ',' && i) {
01233                      *p = '\0';    /* reset it so get_timevar(str) works nicely later */
01234                      th->pl = (unsigned char)strtoul(p+1, NULL, 0);
01235                      break;
01236               }
01237               i = 1;
01238               p--;
01239        }
01240        th->rta = get_timevar(str);
01241 
01242        if(!th->rta) return -1;
01243 
01244        if(th->rta > MAXTTL * 1000000) th->rta = MAXTTL * 1000000;
01245        if(th->pl > 100) th->pl = 100;
01246 
01247        return 0;
01248 }
01249 
01250 unsigned short
01251 icmp_checksum(unsigned short *p, int n)
01252 {
01253        register unsigned short cksum;
01254        register long sum = 0;
01255 
01256        while(n > 1) {
01257               sum += *p++;
01258               n -= 2;
01259        }
01260 
01261        /* mop up the occasional odd byte */
01262        if(n == 1) sum += (unsigned char)*p;
01263 
01264        sum = (sum >> 16) + (sum & 0xffff);       /* add hi 16 to low 16 */
01265        sum += (sum >> 16);                /* add carry */
01266        cksum = ~sum;                      /* ones-complement, trunc to 16 bits */
01267 
01268        return cksum;
01269 }
01270 
01271 void
01272 print_help(void)
01273 {
01274 
01275   /*print_revision (progname);*/ /* FIXME: Why? */
01276 
01277   printf ("Copyright (c) 2005 Andreas Ericsson <ae@op5.se>\n");
01278   printf (COPYRIGHT, copyright, email);
01279 
01280   printf ("\n\n");
01281 
01282   print_usage ();
01283 
01284   printf (UT_HELP_VRSN);
01285   printf (UT_EXTRA_OPTS);
01286 
01287   printf (" %s\n", "-H");
01288   printf ("    %s\n", _("specify a target"));
01289   printf (" %s\n", "-w");
01290   printf ("    %s", _("warning threshold (currently "));
01291   printf ("%0.3fms,%u%%)\n", (float)warn.rta / 1000, warn.pl);
01292   printf (" %s\n", "-c");
01293   printf ("    %s", _("critical threshold (currently "));
01294   printf ("%0.3fms,%u%%)\n", (float)crit.rta / 1000, crit.pl);
01295   printf (" %s\n", "-s");
01296   printf ("    %s\n", _("specify a source IP address or device name"));
01297   printf (" %s\n", "-n");
01298   printf ("    %s", _("number of packets to send (currently "));
01299   printf ("%u)\n",packets);
01300   printf (" %s\n", "-i");
01301   printf ("    %s", _("max packet interval (currently "));
01302   printf ("%0.3fms)\n",(float)pkt_interval / 1000);
01303   printf (" %s\n", "-I");
01304   printf ("    %s", _("max target interval (currently "));
01305   printf ("%0.3fms)\n", (float)target_interval / 1000);
01306   printf (" %s\n", "-m");
01307   printf ("    %s",_("number of alive hosts required for success"));
01308   printf ("\n");
01309   printf (" %s\n", "-l");
01310   printf ("    %s", _("TTL on outgoing packets (currently "));
01311   printf ("%u)\n", ttl);
01312   printf (" %s\n", "-t");
01313   printf ("    %s",_("timeout value (seconds, currently  "));
01314   printf ("%u)\n", timeout);
01315   printf (" %s\n", "-b");
01316   printf ("    %s\n", _("Number of icmp data bytes to send"));
01317   printf ("    %s %u + %d)\n", _("Packet size will be data bytes + icmp header (currently"),icmp_data_size, ICMP_MINLEN);
01318   printf (" %s\n", "-v");
01319   printf ("    %s\n", _("verbose"));
01320 
01321   printf ("\n");
01322   printf ("%s\n", _("Notes:"));
01323   printf (" %s\n", _("The -H switch is optional. Naming a host (or several) to check is not."));
01324   printf ("\n");
01325   printf (" %s\n", _("Threshold format for -w and -c is 200.25,60% for 200.25 msec RTA and 60%"));
01326   printf (" %s\n", _("packet loss.  The default values should work well for most users."));
01327   printf (" %s\n", _("You can specify different RTA factors using the standardized abbreviations"));
01328   printf (" %s\n", _("us (microseconds), ms (milliseconds, default) or just plain s for seconds."));
01329 /* -d not yet implemented */
01330 /*  printf ("%s\n", _("Threshold format for -d is warn,crit.  12,14 means WARNING if >= 12 hops"));
01331   printf ("%s\n", _("are spent and CRITICAL if >= 14 hops are spent."));
01332   printf ("%s\n\n", _("NOTE: Some systems decrease TTL when forming ICMP_ECHOREPLY, others do not."));*/
01333   printf ("\n");
01334   printf (" %s\n", _("The -v switch can be specified several times for increased verbosity."));
01335 /*  printf ("%s\n", _("Long options are currently unsupported."));
01336   printf ("%s\n", _("Options marked with * require an argument"));
01337 */
01338 
01339   printf (UT_SUPPORT);
01340 }
01341 
01342 
01343 
01344 void
01345 print_usage (void)
01346 {
01347   printf ("%s\n", _("Usage:"));
01348   printf(" %s [options] [-H] host1 host2 hostN\n", progname);
01349 }