check_icmp.c 37 KB

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