check_icmp.c 40 KB

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