check_icmp.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436
  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. #ifdef __sun
  44. #define _XPG4_2
  45. #endif
  46. /** nagios plugins basic includes */
  47. #include "common.h"
  48. #include "netutils.h"
  49. #include "utils.h"
  50. #if HAVE_SYS_SOCKIO_H
  51. #include <sys/sockio.h>
  52. #endif
  53. #include <sys/ioctl.h>
  54. #include <sys/time.h>
  55. #include <sys/types.h>
  56. #include <stdio.h>
  57. #include <stdlib.h>
  58. #include <stdarg.h>
  59. #include <unistd.h>
  60. #include <stddef.h>
  61. #include <errno.h>
  62. #include <string.h>
  63. #include <ctype.h>
  64. #include <netdb.h>
  65. #include <sys/socket.h>
  66. #include <net/if.h>
  67. #include <netinet/in_systm.h>
  68. #include <netinet/in.h>
  69. #include <netinet/ip.h>
  70. #include <netinet/ip_icmp.h>
  71. #include <arpa/inet.h>
  72. #include <signal.h>
  73. #include <float.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, void *, unsigned int, struct sockaddr *, u_int *, struct timeval*);
  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(unsigned 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(unsigned 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 && ntohs(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 || ntohs(sent_icmp.icmp_id) != pid ||
  301. ntohs(sent_icmp.icmp_seq) >= targets*packets)
  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[ntohs(sent_icmp.icmp_seq)/packets];
  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. #ifdef HAVE_SIGACTION
  342. struct sigaction sig_action;
  343. #endif
  344. #ifdef SO_TIMESTAMP
  345. int on = 1;
  346. #endif
  347. setlocale (LC_ALL, "");
  348. bindtextdomain (PACKAGE, LOCALEDIR);
  349. textdomain (PACKAGE);
  350. /* print a helpful error message if geteuid != 0 */
  351. np_warn_if_not_root();
  352. /* we only need to be setsuid when we get the sockets, so do
  353. * that before pointer magic (esp. on network data) */
  354. icmp_sockerrno = udp_sockerrno = tcp_sockerrno = sockets = 0;
  355. if((icmp_sock = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP)) != -1)
  356. sockets |= HAVE_ICMP;
  357. else icmp_sockerrno = errno;
  358. /* if((udp_sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1) */
  359. /* sockets |= HAVE_UDP; */
  360. /* else udp_sockerrno = errno; */
  361. /* if((tcp_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) != -1) */
  362. /* sockets |= HAVE_TCP; */
  363. /* else tcp_sockerrno = errno; */
  364. /* now drop privileges (no effect if not setsuid or geteuid() == 0) */
  365. setuid(getuid());
  366. #ifdef SO_TIMESTAMP
  367. if(setsockopt(icmp_sock, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)))
  368. if(debug) printf("Warning: no SO_TIMESTAMP support\n");
  369. #endif // SO_TIMESTAMP
  370. /* POSIXLY_CORRECT might break things, so unset it (the portable way) */
  371. environ = NULL;
  372. /* use the pid to mark packets as ours */
  373. /* Some systems have 32-bit pid_t so mask off only 16 bits */
  374. pid = getpid() & 0xffff;
  375. /* printf("pid = %u\n", pid); */
  376. /* get calling name the old-fashioned way for portability instead
  377. * of relying on the glibc-ism __progname */
  378. ptr = strrchr(argv[0], '/');
  379. if(ptr) progname = &ptr[1];
  380. else progname = argv[0];
  381. /* now set defaults. Use progname to set them initially (allows for
  382. * superfast check_host program when target host is up */
  383. cursor = list = NULL;
  384. table = NULL;
  385. mode = MODE_RTA;
  386. crit.rta = 500000;
  387. crit.pl = 80;
  388. warn.rta = 200000;
  389. warn.pl = 40;
  390. protocols = HAVE_ICMP | HAVE_UDP | HAVE_TCP;
  391. pkt_interval = 80000; /* 80 msec packet interval by default */
  392. packets = 5;
  393. if(!strcmp(progname, "check_icmp") || !strcmp(progname, "check_ping")) {
  394. mode = MODE_ICMP;
  395. protocols = HAVE_ICMP;
  396. }
  397. else if(!strcmp(progname, "check_host")) {
  398. mode = MODE_HOSTCHECK;
  399. pkt_interval = 1000000;
  400. packets = 5;
  401. crit.rta = warn.rta = 1000000;
  402. crit.pl = warn.pl = 100;
  403. }
  404. else if(!strcmp(progname, "check_rta_multi")) {
  405. mode = MODE_ALL;
  406. target_interval = 0;
  407. pkt_interval = 50000;
  408. packets = 5;
  409. }
  410. /* Parse extra opts if any */
  411. argv=np_extra_opts(&argc, argv, progname);
  412. /* support "--help" and "--version" */
  413. if(argc == 2) {
  414. if(!strcmp(argv[1], "--help"))
  415. strcpy(argv[1], "-h");
  416. if(!strcmp(argv[1], "--version"))
  417. strcpy(argv[1], "-V");
  418. }
  419. /* parse the arguments */
  420. for(i = 1; i < argc; i++) {
  421. while((arg = getopt(argc, argv, "vhVw:c:n:p:t:H:s:i:b:I:l:m:")) != EOF) {
  422. unsigned short size;
  423. switch(arg) {
  424. case 'v':
  425. debug++;
  426. break;
  427. case 'b':
  428. size = (unsigned short)strtol(optarg,NULL,0);
  429. if (size >= (sizeof(struct icmp) + sizeof(struct icmp_ping_data)) &&
  430. size < MAX_PING_DATA) {
  431. icmp_data_size = size;
  432. icmp_pkt_size = size + ICMP_MINLEN;
  433. } else
  434. usage_va("ICMP data length must be between: %d and %d",
  435. sizeof(struct icmp) + sizeof(struct icmp_ping_data),
  436. MAX_PING_DATA - 1);
  437. break;
  438. case 'i':
  439. pkt_interval = get_timevar(optarg);
  440. break;
  441. case 'I':
  442. target_interval = get_timevar(optarg);
  443. break;
  444. case 'w':
  445. get_threshold(optarg, &warn);
  446. break;
  447. case 'c':
  448. get_threshold(optarg, &crit);
  449. break;
  450. case 'n':
  451. case 'p':
  452. packets = strtoul(optarg, NULL, 0);
  453. break;
  454. case 't':
  455. timeout = strtoul(optarg, NULL, 0);
  456. if(!timeout) timeout = 10;
  457. break;
  458. case 'H':
  459. add_target(optarg);
  460. break;
  461. case 'l':
  462. ttl = (unsigned char)strtoul(optarg, NULL, 0);
  463. break;
  464. case 'm':
  465. min_hosts_alive = (int)strtoul(optarg, NULL, 0);
  466. break;
  467. case 'd': /* implement later, for cluster checks */
  468. warn_down = (unsigned char)strtoul(optarg, &ptr, 0);
  469. if(ptr) {
  470. crit_down = (unsigned char)strtoul(ptr + 1, NULL, 0);
  471. }
  472. break;
  473. case 's': /* specify source IP address */
  474. set_source_ip(optarg);
  475. break;
  476. case 'V': /* version */
  477. print_revision (progname, NP_VERSION);
  478. exit (STATE_OK);
  479. case 'h': /* help */
  480. print_help ();
  481. exit (STATE_OK);
  482. }
  483. }
  484. }
  485. argv = &argv[optind];
  486. while(*argv) {
  487. add_target(*argv);
  488. argv++;
  489. }
  490. if(!targets) {
  491. errno = 0;
  492. crash("No hosts to check");
  493. exit(3);
  494. }
  495. if(!sockets) {
  496. if(icmp_sock == -1) {
  497. errno = icmp_sockerrno;
  498. crash("Failed to obtain ICMP socket");
  499. return -1;
  500. }
  501. /* if(udp_sock == -1) { */
  502. /* errno = icmp_sockerrno; */
  503. /* crash("Failed to obtain UDP socket"); */
  504. /* return -1; */
  505. /* } */
  506. /* if(tcp_sock == -1) { */
  507. /* errno = icmp_sockerrno; */
  508. /* crash("Failed to obtain TCP socker"); */
  509. /* return -1; */
  510. /* } */
  511. }
  512. if(!ttl) ttl = 64;
  513. if(icmp_sock) {
  514. result = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
  515. if(debug) {
  516. if(result == -1) printf("setsockopt failed\n");
  517. else printf("ttl set to %u\n", ttl);
  518. }
  519. }
  520. /* stupid users should be able to give whatever thresholds they want
  521. * (nothing will break if they do), but some anal plugin maintainer
  522. * will probably add some printf() thing here later, so it might be
  523. * best to at least show them where to do it. ;) */
  524. if(warn.pl > crit.pl) warn.pl = crit.pl;
  525. if(warn.rta > crit.rta) warn.rta = crit.rta;
  526. if(warn_down > crit_down) crit_down = warn_down;
  527. #ifdef HAVE_SIGACTION
  528. sig_action.sa_sigaction = NULL;
  529. sig_action.sa_handler = finish;
  530. sigfillset(&sig_action.sa_mask);
  531. sig_action.sa_flags = SA_NODEFER|SA_RESTART;
  532. sigaction(SIGINT, &sig_action, NULL);
  533. sigaction(SIGHUP, &sig_action, NULL);
  534. sigaction(SIGTERM, &sig_action, NULL);
  535. sigaction(SIGALRM, &sig_action, NULL);
  536. #else /* HAVE_SIGACTION */
  537. signal(SIGINT, finish);
  538. signal(SIGHUP, finish);
  539. signal(SIGTERM, finish);
  540. signal(SIGALRM, finish);
  541. #endif /* HAVE_SIGACTION */
  542. if(debug) printf("Setting alarm timeout to %u seconds\n", timeout);
  543. alarm(timeout);
  544. /* make sure we don't wait any longer than necessary */
  545. gettimeofday(&prog_start, &tz);
  546. max_completion_time =
  547. ((targets * packets * pkt_interval) + (targets * target_interval)) +
  548. (targets * packets * crit.rta) + crit.rta;
  549. if(debug) {
  550. printf("packets: %u, targets: %u\n"
  551. "target_interval: %0.3f, pkt_interval %0.3f\n"
  552. "crit.rta: %0.3f\n"
  553. "max_completion_time: %0.3f\n",
  554. packets, targets,
  555. (float)target_interval / 1000, (float)pkt_interval / 1000,
  556. (float)crit.rta / 1000,
  557. (float)max_completion_time / 1000);
  558. }
  559. if(debug) {
  560. if(max_completion_time > (u_int)timeout * 1000000) {
  561. printf("max_completion_time: %llu timeout: %u\n",
  562. max_completion_time, timeout);
  563. printf("Timout must be at lest %llu\n",
  564. max_completion_time / 1000000 + 1);
  565. }
  566. }
  567. if(debug) {
  568. printf("crit = {%u, %u%%}, warn = {%u, %u%%}\n",
  569. crit.rta, crit.pl, warn.rta, warn.pl);
  570. printf("pkt_interval: %u target_interval: %u retry_interval: %u\n",
  571. pkt_interval, target_interval, retry_interval);
  572. printf("icmp_pkt_size: %u timeout: %u\n",
  573. icmp_pkt_size, timeout);
  574. }
  575. if(packets > 20) {
  576. errno = 0;
  577. crash("packets is > 20 (%d)", packets);
  578. }
  579. if(min_hosts_alive < -1) {
  580. errno = 0;
  581. crash("minimum alive hosts is negative (%i)", min_hosts_alive);
  582. }
  583. host = list;
  584. table = malloc(sizeof(struct rta_host **) * targets);
  585. i = 0;
  586. while(host) {
  587. host->id = i*packets;
  588. table[i] = host;
  589. host = host->next;
  590. i++;
  591. }
  592. run_checks();
  593. errno = 0;
  594. finish(0);
  595. return(0);
  596. }
  597. static void
  598. run_checks()
  599. {
  600. u_int i, t, result;
  601. u_int final_wait, time_passed;
  602. /* this loop might actually violate the pkt_interval or target_interval
  603. * settings, but only if there aren't any packets on the wire which
  604. * indicates that the target can handle an increased packet rate */
  605. for(i = 0; i < packets; i++) {
  606. for(t = 0; t < targets; t++) {
  607. /* don't send useless packets */
  608. if(!targets_alive) finish(0);
  609. if(table[t]->flags & FLAG_LOST_CAUSE) {
  610. if(debug) printf("%s is a lost cause. not sending any more\n",
  611. table[t]->name);
  612. continue;
  613. }
  614. /* we're still in the game, so send next packet */
  615. (void)send_icmp_ping(icmp_sock, table[t]);
  616. result = wait_for_reply(icmp_sock, target_interval);
  617. }
  618. result = wait_for_reply(icmp_sock, pkt_interval * targets);
  619. }
  620. if(icmp_pkts_en_route && targets_alive) {
  621. time_passed = get_timevaldiff(NULL, NULL);
  622. final_wait = max_completion_time - time_passed;
  623. if(debug) {
  624. printf("time_passed: %u final_wait: %u max_completion_time: %llu\n",
  625. time_passed, final_wait, max_completion_time);
  626. }
  627. if(time_passed > max_completion_time) {
  628. if(debug) printf("Time passed. Finishing up\n");
  629. finish(0);
  630. }
  631. /* catch the packets that might come in within the timeframe, but
  632. * haven't yet */
  633. if(debug) printf("Waiting for %u micro-seconds (%0.3f msecs)\n",
  634. final_wait, (float)final_wait / 1000);
  635. result = wait_for_reply(icmp_sock, final_wait);
  636. }
  637. }
  638. /* response structure:
  639. * ip header : 20 bytes
  640. * icmp header : 28 bytes
  641. * icmp echo reply : the rest
  642. */
  643. static int
  644. wait_for_reply(int sock, u_int t)
  645. {
  646. int n, hlen;
  647. static unsigned char buf[4096];
  648. struct sockaddr_in resp_addr;
  649. struct ip *ip;
  650. struct icmp icp;
  651. struct rta_host *host;
  652. struct icmp_ping_data data;
  653. struct timeval wait_start, now;
  654. u_int tdiff, i, per_pkt_wait;
  655. /* if we can't listen or don't have anything to listen to, just return */
  656. if(!t || !icmp_pkts_en_route) return 0;
  657. gettimeofday(&wait_start, &tz);
  658. i = t;
  659. per_pkt_wait = t / icmp_pkts_en_route;
  660. while(icmp_pkts_en_route && get_timevaldiff(&wait_start, NULL) < i) {
  661. t = per_pkt_wait;
  662. /* wrap up if all targets are declared dead */
  663. if(!targets_alive ||
  664. get_timevaldiff(&prog_start, NULL) >= max_completion_time ||
  665. (mode == MODE_HOSTCHECK && targets_down))
  666. {
  667. finish(0);
  668. }
  669. /* reap responses until we hit a timeout */
  670. n = recvfrom_wto(sock, buf, sizeof(buf),
  671. (struct sockaddr *)&resp_addr, &t, &now);
  672. if(!n) {
  673. if(debug > 1) {
  674. printf("recvfrom_wto() timed out during a %u usecs wait\n",
  675. per_pkt_wait);
  676. }
  677. continue; /* timeout for this one, so keep trying */
  678. }
  679. if(n < 0) {
  680. if(debug) printf("recvfrom_wto() returned errors\n");
  681. return n;
  682. }
  683. ip = (struct ip *)buf;
  684. if(debug > 1) printf("received %u bytes from %s\n",
  685. ntohs(ip->ip_len), inet_ntoa(resp_addr.sin_addr));
  686. /* obsolete. alpha on tru64 provides the necessary defines, but isn't broken */
  687. /* #if defined( __alpha__ ) && __STDC__ && !defined( __GLIBC__ ) */
  688. /* alpha headers are decidedly broken. Using an ansi compiler,
  689. * they provide ip_vhl instead of ip_hl and ip_v, so we mask
  690. * off the bottom 4 bits */
  691. /* hlen = (ip->ip_vhl & 0x0f) << 2; */
  692. /* #else */
  693. hlen = ip->ip_hl << 2;
  694. /* #endif */
  695. if(n < (hlen + ICMP_MINLEN)) {
  696. crash("received packet too short for ICMP (%d bytes, expected %d) from %s\n",
  697. n, hlen + icmp_pkt_size, inet_ntoa(resp_addr.sin_addr));
  698. }
  699. /* else if(debug) { */
  700. /* printf("ip header size: %u, packet size: %u (expected %u, %u)\n", */
  701. /* hlen, ntohs(ip->ip_len) - hlen, */
  702. /* sizeof(struct ip), icmp_pkt_size); */
  703. /* } */
  704. /* check the response */
  705. memcpy(&icp, buf + hlen, sizeof(icp));
  706. if(ntohs(icp.icmp_id) != pid || icp.icmp_type != ICMP_ECHOREPLY ||
  707. ntohs(icp.icmp_seq) >= targets*packets) {
  708. if(debug > 2) printf("not a proper ICMP_ECHOREPLY\n");
  709. handle_random_icmp(buf + hlen, &resp_addr);
  710. continue;
  711. }
  712. /* this is indeed a valid response */
  713. memcpy(&data, icp.icmp_data, sizeof(data));
  714. if (debug > 2)
  715. printf("ICMP echo-reply of len %lu, id %u, seq %u, cksum 0x%X\n",
  716. (unsigned long)sizeof(data), ntohs(icp.icmp_id),
  717. ntohs(icp.icmp_seq), icp.icmp_cksum);
  718. host = table[ntohs(icp.icmp_seq)/packets];
  719. tdiff = get_timevaldiff(&data.stime, &now);
  720. host->time_waited += tdiff;
  721. host->icmp_recv++;
  722. icmp_recv++;
  723. if (tdiff > host->rtmax)
  724. host->rtmax = tdiff;
  725. if (tdiff < host->rtmin)
  726. host->rtmin = tdiff;
  727. if(debug) {
  728. printf("%0.3f ms rtt from %s, outgoing ttl: %u, incoming ttl: %u, max: %0.3f, min: %0.3f\n",
  729. (float)tdiff / 1000, inet_ntoa(resp_addr.sin_addr),
  730. ttl, ip->ip_ttl, (float)host->rtmax / 1000, (float)host->rtmin / 1000);
  731. }
  732. /* if we're in hostcheck mode, exit with limited printouts */
  733. if(mode == MODE_HOSTCHECK) {
  734. printf("OK - %s responds to ICMP. Packet %u, rta %0.3fms|"
  735. "pkt=%u;;0;%u rta=%0.3f;%0.3f;%0.3f;;\n",
  736. host->name, icmp_recv, (float)tdiff / 1000,
  737. icmp_recv, packets, (float)tdiff / 1000,
  738. (float)warn.rta / 1000, (float)crit.rta / 1000);
  739. exit(STATE_OK);
  740. }
  741. }
  742. return 0;
  743. }
  744. /* the ping functions */
  745. static int
  746. send_icmp_ping(int sock, struct rta_host *host)
  747. {
  748. static union {
  749. void *buf; /* re-use so we prevent leaks */
  750. struct icmp *icp;
  751. u_short *cksum_in;
  752. } packet = { NULL };
  753. long int len;
  754. struct icmp_ping_data data;
  755. struct msghdr hdr;
  756. struct iovec iov;
  757. struct timeval tv;
  758. struct sockaddr *addr;
  759. if(sock == -1) {
  760. errno = 0;
  761. crash("Attempt to send on bogus socket");
  762. return -1;
  763. }
  764. addr = (struct sockaddr *)&host->saddr_in;
  765. if(!packet.buf) {
  766. if (!(packet.buf = malloc(icmp_pkt_size))) {
  767. crash("send_icmp_ping(): failed to malloc %d bytes for send buffer",
  768. icmp_pkt_size);
  769. return -1; /* might be reached if we're in debug mode */
  770. }
  771. }
  772. memset(packet.buf, 0, icmp_pkt_size);
  773. if((gettimeofday(&tv, &tz)) == -1) return -1;
  774. data.ping_id = 10; /* host->icmp.icmp_sent; */
  775. memcpy(&data.stime, &tv, sizeof(tv));
  776. memcpy(&packet.icp->icmp_data, &data, sizeof(data));
  777. packet.icp->icmp_type = ICMP_ECHO;
  778. packet.icp->icmp_code = 0;
  779. packet.icp->icmp_cksum = 0;
  780. packet.icp->icmp_id = htons(pid);
  781. packet.icp->icmp_seq = htons(host->id++);
  782. packet.icp->icmp_cksum = icmp_checksum(packet.cksum_in, icmp_pkt_size);
  783. if (debug > 2)
  784. printf("Sending ICMP echo-request of len %lu, id %u, seq %u, cksum 0x%X to host %s\n",
  785. (unsigned long)sizeof(data), ntohs(packet.icp->icmp_id),
  786. ntohs(packet.icp->icmp_seq), packet.icp->icmp_cksum,
  787. host->name);
  788. memset(&iov, 0, sizeof(iov));
  789. iov.iov_base = packet.buf;
  790. iov.iov_len = icmp_pkt_size;
  791. memset(&hdr, 0, sizeof(hdr));
  792. hdr.msg_name = addr;
  793. hdr.msg_namelen = sizeof(struct sockaddr);
  794. hdr.msg_iov = &iov;
  795. hdr.msg_iovlen = 1;
  796. /* MSG_CONFIRM is a linux thing and only available on linux kernels >= 2.3.15, see send(2) */
  797. #ifdef MSG_CONFIRM
  798. len = sendmsg(sock, &hdr, MSG_CONFIRM);
  799. #else
  800. len = sendmsg(sock, &hdr, 0);
  801. #endif
  802. if(len < 0 || (unsigned int)len != icmp_pkt_size) {
  803. if(debug) printf("Failed to send ping to %s\n",
  804. inet_ntoa(host->saddr_in.sin_addr));
  805. return -1;
  806. }
  807. icmp_sent++;
  808. host->icmp_sent++;
  809. return 0;
  810. }
  811. static int
  812. recvfrom_wto(int sock, void *buf, unsigned int len, struct sockaddr *saddr,
  813. u_int *timo, struct timeval* tv)
  814. {
  815. u_int slen;
  816. int n, ret;
  817. struct timeval to, then, now;
  818. fd_set rd, wr;
  819. char ans_data[4096];
  820. struct msghdr hdr;
  821. struct iovec iov;
  822. #ifdef SO_TIMESTAMP
  823. struct cmsghdr* chdr;
  824. #endif
  825. if(!*timo) {
  826. if(debug) printf("*timo is not\n");
  827. return 0;
  828. }
  829. to.tv_sec = *timo / 1000000;
  830. to.tv_usec = (*timo - (to.tv_sec * 1000000));
  831. FD_ZERO(&rd);
  832. FD_ZERO(&wr);
  833. FD_SET(sock, &rd);
  834. errno = 0;
  835. gettimeofday(&then, &tz);
  836. n = select(sock + 1, &rd, &wr, NULL, &to);
  837. if(n < 0) crash("select() in recvfrom_wto");
  838. gettimeofday(&now, &tz);
  839. *timo = get_timevaldiff(&then, &now);
  840. if(!n) return 0; /* timeout */
  841. slen = sizeof(struct sockaddr);
  842. memset(&iov, 0, sizeof(iov));
  843. iov.iov_base = buf;
  844. iov.iov_len = len;
  845. memset(&hdr, 0, sizeof(hdr));
  846. hdr.msg_name = saddr;
  847. hdr.msg_namelen = slen;
  848. hdr.msg_iov = &iov;
  849. hdr.msg_iovlen = 1;
  850. #ifdef HAVE_MSGHDR_MSG_CONTROL
  851. hdr.msg_control = ans_data;
  852. hdr.msg_controllen = sizeof(ans_data);
  853. #endif
  854. ret = recvmsg(sock, &hdr, 0);
  855. #ifdef SO_TIMESTAMP
  856. for(chdr = CMSG_FIRSTHDR(&hdr); chdr; chdr = CMSG_NXTHDR(&hdr, chdr)) {
  857. if(chdr->cmsg_level == SOL_SOCKET
  858. && chdr->cmsg_type == SO_TIMESTAMP
  859. && chdr->cmsg_len >= CMSG_LEN(sizeof(struct timeval))) {
  860. memcpy(tv, CMSG_DATA(chdr), sizeof(*tv));
  861. break ;
  862. }
  863. }
  864. if (!chdr)
  865. #endif // SO_TIMESTAMP
  866. gettimeofday(tv, &tz);
  867. return (ret);
  868. }
  869. static void
  870. finish(int sig)
  871. {
  872. u_int i = 0;
  873. unsigned char pl;
  874. double rta;
  875. struct rta_host *host;
  876. const char *status_string[] =
  877. {"OK", "WARNING", "CRITICAL", "UNKNOWN", "DEPENDENT"};
  878. int hosts_ok = 0;
  879. int hosts_warn = 0;
  880. alarm(0);
  881. if(debug > 1) printf("finish(%d) called\n", sig);
  882. if(icmp_sock != -1) close(icmp_sock);
  883. if(udp_sock != -1) close(udp_sock);
  884. if(tcp_sock != -1) close(tcp_sock);
  885. if(debug) {
  886. printf("icmp_sent: %u icmp_recv: %u icmp_lost: %u\n",
  887. icmp_sent, icmp_recv, icmp_lost);
  888. printf("targets: %u targets_alive: %u\n", targets, targets_alive);
  889. }
  890. /* iterate thrice to calculate values, give output, and print perfparse */
  891. host = list;
  892. while(host) {
  893. if(!host->icmp_recv) {
  894. /* rta 0 is ofcourse not entirely correct, but will still show up
  895. * conspicuosly as missing entries in perfparse and cacti */
  896. pl = 100;
  897. rta = 0;
  898. status = STATE_CRITICAL;
  899. /* up the down counter if not already counted */
  900. if(!(host->flags & FLAG_LOST_CAUSE) && targets_alive) targets_down++;
  901. }
  902. else {
  903. pl = ((host->icmp_sent - host->icmp_recv) * 100) / host->icmp_sent;
  904. rta = (double)host->time_waited / host->icmp_recv;
  905. }
  906. host->pl = pl;
  907. host->rta = rta;
  908. if(pl >= crit.pl || rta >= crit.rta) {
  909. status = STATE_CRITICAL;
  910. }
  911. else if(!status && (pl >= warn.pl || rta >= warn.rta)) {
  912. status = STATE_WARNING;
  913. hosts_warn++;
  914. }
  915. else {
  916. hosts_ok++;
  917. }
  918. host = host->next;
  919. }
  920. /* this is inevitable */
  921. if(!targets_alive) status = STATE_CRITICAL;
  922. if(min_hosts_alive > -1) {
  923. if(hosts_ok >= min_hosts_alive) status = STATE_OK;
  924. else if((hosts_ok + hosts_warn) >= min_hosts_alive) status = STATE_WARNING;
  925. }
  926. printf("%s - ", status_string[status]);
  927. host = list;
  928. while(host) {
  929. if(debug) write(STDOUT_FILENO, "\n", 1);
  930. if(i) {
  931. if(i < targets) write(STDOUT_FILENO, " :: ", 4);
  932. else write(STDOUT_FILENO, "\n", 1);
  933. }
  934. i++;
  935. if(!host->icmp_recv) {
  936. status = STATE_CRITICAL;
  937. if(host->flags & FLAG_LOST_CAUSE) {
  938. printf("%s: %s @ %s. rta nan, lost %d%%",
  939. host->name,
  940. get_icmp_error_msg(host->icmp_type, host->icmp_code),
  941. inet_ntoa(host->error_addr),
  942. 100);
  943. }
  944. else { /* not marked as lost cause, so we have no flags for it */
  945. printf("%s: rta nan, lost 100%%", host->name);
  946. }
  947. }
  948. else { /* !icmp_recv */
  949. printf("%s: rta %0.3fms, lost %u%%",
  950. host->name, host->rta / 1000, host->pl);
  951. }
  952. host = host->next;
  953. }
  954. /* iterate once more for pretty perfparse output */
  955. printf("|");
  956. i = 0;
  957. host = list;
  958. while(host) {
  959. if(debug) write(STDOUT_FILENO, "\n", 1);
  960. printf("%srta=%0.3fms;%0.3f;%0.3f;0; %spl=%u%%;%u;%u;; %srtmax=%0.3fms;;;; %srtmin=%0.3fms;;;; ",
  961. (targets > 1) ? host->name : "",
  962. host->rta / 1000, (float)warn.rta / 1000, (float)crit.rta / 1000,
  963. (targets > 1) ? host->name : "", host->pl, warn.pl, crit.pl,
  964. (targets > 1) ? host->name : "", (float)host->rtmax / 1000,
  965. (targets > 1) ? host->name : "", (host->rtmin < DBL_MAX) ? (float)host->rtmin / 1000 : (float)0);
  966. host = host->next;
  967. }
  968. if(min_hosts_alive > -1) {
  969. if(hosts_ok >= min_hosts_alive) status = STATE_OK;
  970. else if((hosts_ok + hosts_warn) >= min_hosts_alive) status = STATE_WARNING;
  971. }
  972. /* finish with an empty line */
  973. puts("");
  974. if(debug) printf("targets: %u, targets_alive: %u, hosts_ok: %u, hosts_warn: %u, min_hosts_alive: %i\n",
  975. targets, targets_alive, hosts_ok, hosts_warn, min_hosts_alive);
  976. exit(status);
  977. }
  978. static u_int
  979. get_timevaldiff(struct timeval *early, struct timeval *later)
  980. {
  981. u_int ret;
  982. struct timeval now;
  983. if(!later) {
  984. gettimeofday(&now, &tz);
  985. later = &now;
  986. }
  987. if(!early) early = &prog_start;
  988. /* if early > later we return 0 so as to indicate a timeout */
  989. if(early->tv_sec > later->tv_sec ||
  990. (early->tv_sec == later->tv_sec && early->tv_usec > later->tv_usec))
  991. {
  992. return 0;
  993. }
  994. ret = (later->tv_sec - early->tv_sec) * 1000000;
  995. ret += later->tv_usec - early->tv_usec;
  996. return ret;
  997. }
  998. static int
  999. add_target_ip(char *arg, struct in_addr *in)
  1000. {
  1001. struct rta_host *host;
  1002. /* disregard obviously stupid addresses */
  1003. if(in->s_addr == INADDR_NONE || in->s_addr == INADDR_ANY)
  1004. return -1;
  1005. /* no point in adding two identical IP's, so don't. ;) */
  1006. host = list;
  1007. while(host) {
  1008. if(host->saddr_in.sin_addr.s_addr == in->s_addr) {
  1009. if(debug) printf("Identical IP already exists. Not adding %s\n", arg);
  1010. return -1;
  1011. }
  1012. host = host->next;
  1013. }
  1014. /* add the fresh ip */
  1015. host = malloc(sizeof(struct rta_host));
  1016. if(!host) {
  1017. crash("add_target_ip(%s, %s): malloc(%d) failed",
  1018. arg, inet_ntoa(*in), sizeof(struct rta_host));
  1019. }
  1020. memset(host, 0, sizeof(struct rta_host));
  1021. /* set the values. use calling name for output */
  1022. host->name = strdup(arg);
  1023. /* fill out the sockaddr_in struct */
  1024. host->saddr_in.sin_family = AF_INET;
  1025. host->saddr_in.sin_addr.s_addr = in->s_addr;
  1026. host->rtmin = DBL_MAX;
  1027. if(!list) list = cursor = host;
  1028. else cursor->next = host;
  1029. cursor = host;
  1030. targets++;
  1031. return 0;
  1032. }
  1033. /* wrapper for add_target_ip */
  1034. static int
  1035. add_target(char *arg)
  1036. {
  1037. int i;
  1038. struct hostent *he;
  1039. struct in_addr *in, ip;
  1040. /* don't resolve if we don't have to */
  1041. if((ip.s_addr = inet_addr(arg)) != INADDR_NONE) {
  1042. /* don't add all ip's if we were given a specific one */
  1043. return add_target_ip(arg, &ip);
  1044. /* he = gethostbyaddr((char *)in, sizeof(struct in_addr), AF_INET); */
  1045. /* if(!he) return add_target_ip(arg, in); */
  1046. }
  1047. else {
  1048. errno = 0;
  1049. he = gethostbyname(arg);
  1050. if(!he) {
  1051. errno = 0;
  1052. crash("Failed to resolve %s", arg);
  1053. return -1;
  1054. }
  1055. }
  1056. /* possibly add all the IP's as targets */
  1057. for(i = 0; he->h_addr_list[i]; i++) {
  1058. in = (struct in_addr *)he->h_addr_list[i];
  1059. add_target_ip(arg, in);
  1060. /* this is silly, but it works */
  1061. if(mode == MODE_HOSTCHECK || mode == MODE_ALL) {
  1062. if(debug > 2) printf("mode: %d\n", mode);
  1063. continue;
  1064. }
  1065. break;
  1066. }
  1067. return 0;
  1068. }
  1069. static void
  1070. set_source_ip(char *arg)
  1071. {
  1072. struct sockaddr_in src;
  1073. memset(&src, 0, sizeof(src));
  1074. src.sin_family = AF_INET;
  1075. if((src.sin_addr.s_addr = inet_addr(arg)) == INADDR_NONE)
  1076. src.sin_addr.s_addr = get_ip_address(arg);
  1077. if(bind(icmp_sock, (struct sockaddr *)&src, sizeof(src)) == -1)
  1078. crash("Cannot bind to IP address %s", arg);
  1079. }
  1080. /* TODO: Move this to netutils.c and also change check_dhcp to use that. */
  1081. static in_addr_t
  1082. get_ip_address(const char *ifname)
  1083. {
  1084. #if defined(SIOCGIFADDR)
  1085. struct ifreq ifr;
  1086. struct sockaddr_in ip;
  1087. strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name) - 1);
  1088. ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = '\0';
  1089. if(ioctl(icmp_sock, SIOCGIFADDR, &ifr) == -1)
  1090. crash("Cannot determine IP address of interface %s", ifname);
  1091. memcpy(&ip, &ifr.ifr_addr, sizeof(ip));
  1092. return ip.sin_addr.s_addr;
  1093. #else
  1094. errno = 0;
  1095. crash("Cannot get interface IP address on this platform.");
  1096. #endif
  1097. }
  1098. /*
  1099. * u = micro
  1100. * m = milli
  1101. * s = seconds
  1102. * return value is in microseconds
  1103. */
  1104. static u_int
  1105. get_timevar(const char *str)
  1106. {
  1107. char p, u, *ptr;
  1108. size_t len;
  1109. u_int i, d; /* integer and decimal, respectively */
  1110. u_int factor = 1000; /* default to milliseconds */
  1111. if(!str) return 0;
  1112. len = strlen(str);
  1113. if(!len) return 0;
  1114. /* unit might be given as ms|m (millisec),
  1115. * us|u (microsec) or just plain s, for seconds */
  1116. u = p = '\0';
  1117. u = str[len - 1];
  1118. if(len >= 2 && !isdigit((int)str[len - 2])) p = str[len - 2];
  1119. if(p && u == 's') u = p;
  1120. else if(!p) p = u;
  1121. if(debug > 2) printf("evaluating %s, u: %c, p: %c\n", str, u, p);
  1122. if(u == 'u') factor = 1; /* microseconds */
  1123. else if(u == 'm') factor = 1000; /* milliseconds */
  1124. else if(u == 's') factor = 1000000; /* seconds */
  1125. if(debug > 2) printf("factor is %u\n", factor);
  1126. i = strtoul(str, &ptr, 0);
  1127. if(!ptr || *ptr != '.' || strlen(ptr) < 2 || factor == 1)
  1128. return i * factor;
  1129. /* time specified in usecs can't have decimal points, so ignore them */
  1130. if(factor == 1) return i;
  1131. d = strtoul(ptr + 1, NULL, 0);
  1132. /* d is decimal, so get rid of excess digits */
  1133. while(d >= factor) d /= 10;
  1134. /* the last parenthesis avoids floating point exceptions. */
  1135. return ((i * factor) + (d * (factor / 10)));
  1136. }
  1137. /* not too good at checking errors, but it'll do (main() should barfe on -1) */
  1138. static int
  1139. get_threshold(char *str, threshold *th)
  1140. {
  1141. char *p = NULL, i = 0;
  1142. if(!str || !strlen(str) || !th) return -1;
  1143. /* pointer magic slims code by 10 lines. i is bof-stop on stupid libc's */
  1144. p = &str[strlen(str) - 1];
  1145. while(p != &str[1]) {
  1146. if(*p == '%') *p = '\0';
  1147. else if(*p == ',' && i) {
  1148. *p = '\0'; /* reset it so get_timevar(str) works nicely later */
  1149. th->pl = (unsigned char)strtoul(p+1, NULL, 0);
  1150. break;
  1151. }
  1152. i = 1;
  1153. p--;
  1154. }
  1155. th->rta = get_timevar(str);
  1156. if(!th->rta) return -1;
  1157. if(th->rta > MAXTTL * 1000000) th->rta = MAXTTL * 1000000;
  1158. if(th->pl > 100) th->pl = 100;
  1159. return 0;
  1160. }
  1161. unsigned short
  1162. icmp_checksum(unsigned short *p, int n)
  1163. {
  1164. register unsigned short cksum;
  1165. register long sum = 0;
  1166. while(n > 1) {
  1167. sum += *p++;
  1168. n -= 2;
  1169. }
  1170. /* mop up the occasional odd byte */
  1171. if(n == 1) sum += (unsigned char)*p;
  1172. sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
  1173. sum += (sum >> 16); /* add carry */
  1174. cksum = ~sum; /* ones-complement, trunc to 16 bits */
  1175. return cksum;
  1176. }
  1177. void
  1178. print_help(void)
  1179. {
  1180. /*print_revision (progname);*/ /* FIXME: Why? */
  1181. printf ("Copyright (c) 2005 Andreas Ericsson <ae@op5.se>\n");
  1182. printf (COPYRIGHT, copyright, email);
  1183. printf ("\n\n");
  1184. print_usage ();
  1185. printf (UT_HELP_VRSN);
  1186. printf (UT_EXTRA_OPTS);
  1187. printf (" %s\n", "-H");
  1188. printf (" %s\n", _("specify a target"));
  1189. printf (" %s\n", "-w");
  1190. printf (" %s", _("warning threshold (currently "));
  1191. printf ("%0.3fms,%u%%)\n", (float)warn.rta / 1000, warn.pl);
  1192. printf (" %s\n", "-c");
  1193. printf (" %s", _("critical threshold (currently "));
  1194. printf ("%0.3fms,%u%%)\n", (float)crit.rta / 1000, crit.pl);
  1195. printf (" %s\n", "-s");
  1196. printf (" %s\n", _("specify a source IP address or device name"));
  1197. printf (" %s\n", "-n");
  1198. printf (" %s", _("number of packets to send (currently "));
  1199. printf ("%u)\n",packets);
  1200. printf (" %s\n", "-p");
  1201. printf (" %s", _("number of packets to send (currently "));
  1202. printf ("%u)\n",packets);
  1203. printf (" %s\n", "-i");
  1204. printf (" %s", _("max packet interval (currently "));
  1205. printf ("%0.3fms)\n",(float)pkt_interval / 1000);
  1206. printf (" %s\n", "-I");
  1207. printf (" %s", _("max target interval (currently "));
  1208. printf ("%0.3fms)\n", (float)target_interval / 1000);
  1209. printf (" %s\n", "-m");
  1210. printf (" %s",_("number of alive hosts required for success"));
  1211. printf ("\n");
  1212. printf (" %s\n", "-l");
  1213. printf (" %s", _("TTL on outgoing packets (currently "));
  1214. printf ("%u)\n", ttl);
  1215. printf (" %s\n", "-t");
  1216. printf (" %s",_("timeout value (seconds, currently "));
  1217. printf ("%u)\n", timeout);
  1218. printf (" %s\n", "-b");
  1219. printf (" %s\n", _("Number of icmp data bytes to send"));
  1220. printf (" %s %u + %d)\n", _("Packet size will be data bytes + icmp header (currently"),icmp_data_size, ICMP_MINLEN);
  1221. printf (" %s\n", "-v");
  1222. printf (" %s\n", _("verbose"));
  1223. printf ("\n");
  1224. printf ("%s\n", _("Notes:"));
  1225. printf (" %s\n", _("The -H switch is optional. Naming a host (or several) to check is not."));
  1226. printf ("\n");
  1227. printf (" %s\n", _("Threshold format for -w and -c is 200.25,60% for 200.25 msec RTA and 60%"));
  1228. printf (" %s\n", _("packet loss. The default values should work well for most users."));
  1229. printf (" %s\n", _("You can specify different RTA factors using the standardized abbreviations"));
  1230. printf (" %s\n", _("us (microseconds), ms (milliseconds, default) or just plain s for seconds."));
  1231. /* -d not yet implemented */
  1232. /* printf ("%s\n", _("Threshold format for -d is warn,crit. 12,14 means WARNING if >= 12 hops"));
  1233. printf ("%s\n", _("are spent and CRITICAL if >= 14 hops are spent."));
  1234. printf ("%s\n\n", _("NOTE: Some systems decrease TTL when forming ICMP_ECHOREPLY, others do not."));*/
  1235. printf ("\n");
  1236. printf (" %s\n", _("The -v switch can be specified several times for increased verbosity."));
  1237. /* printf ("%s\n", _("Long options are currently unsupported."));
  1238. printf ("%s\n", _("Options marked with * require an argument"));
  1239. */
  1240. printf (UT_SUPPORT);
  1241. }
  1242. void
  1243. print_usage (void)
  1244. {
  1245. printf ("%s\n", _("Usage:"));
  1246. printf(" %s [options] [-H] host1 host2 hostN\n", progname);
  1247. }