4
0

check_icmp.c 38 KB

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