check_icmp.c 39 KB

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