check_icmp.c 37 KB

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