check_icmp.c 39 KB

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