4
0

check_ntp_time.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. /*****************************************************************************
  2. *
  3. * Nagios check_ntp_time plugin
  4. *
  5. * License: GPL
  6. * Copyright (c) 2006 Sean Finney <seanius@seanius.net>
  7. * Copyright (c) 2006-2014 Nagios Plugins Development Team
  8. *
  9. * Description:
  10. *
  11. * This file contains the check_ntp_time plugin
  12. *
  13. * This plugin checks the clock offset between the local host and a
  14. * remote NTP server. It is independent of any commandline programs or
  15. * external libraries.
  16. *
  17. * If you'd rather want to monitor an NTP server, please use
  18. * check_ntp_peer.
  19. *
  20. *
  21. * This program is free software: you can redistribute it and/or modify
  22. * it under the terms of the GNU General Public License as published by
  23. * the Free Software Foundation, either version 3 of the License, or
  24. * (at your option) any later version.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU General Public License
  32. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  33. *
  34. *
  35. *****************************************************************************/
  36. const char *progname = "check_ntp_time";
  37. const char *copyright = "2006-2014";
  38. const char *email = "devel@nagios-plugins.org";
  39. #include "common.h"
  40. #include "netutils.h"
  41. #include "utils.h"
  42. static char *server_address=NULL;
  43. static char *port="123";
  44. static int verbose=0;
  45. static int quiet=0;
  46. static char *owarn="60";
  47. static char *ocrit="120";
  48. static char *swarn="16";
  49. static char *scrit="16";
  50. int time_offset=0;
  51. static int delay=2;
  52. int num_hosts;
  53. int process_arguments (int, char **);
  54. thresholds *offset_thresholds = NULL;
  55. void print_help (void);
  56. void print_usage (void);
  57. /* number of times to perform each request to get a good average. */
  58. #ifndef AVG_NUM
  59. #define AVG_NUM 4
  60. #endif
  61. /* max size of control message data */
  62. #define MAX_CM_SIZE 468
  63. /* this structure holds everything in an ntp request/response as per rfc1305 */
  64. typedef struct {
  65. uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
  66. uint8_t stratum; /* clock stratum */
  67. int8_t poll; /* polling interval */
  68. int8_t precision; /* precision of the local clock */
  69. union {
  70. int32_t rtdelay; /* total rt delay, as a fixed point num. see macros */
  71. struct {
  72. uint16_t rtdelay_l16;
  73. uint16_t rtdelay_r16;
  74. };
  75. };
  76. union {
  77. uint32_t rtdisp; /* like above, but for max err to primary src */
  78. struct {
  79. uint16_t rtdisp_l16;
  80. uint16_t rtdisp_r16;
  81. };
  82. };
  83. uint32_t refid; /* ref clock identifier */
  84. uint64_t refts; /* reference timestamp. local time local clock */
  85. uint64_t origts; /* time at which request departed client */
  86. uint64_t rxts; /* time at which request arrived at server */
  87. union {
  88. uint64_t txts; /* time at which request departed server */
  89. struct {
  90. uint32_t txts_l32;
  91. uint32_t txts_r32;
  92. };
  93. };
  94. } ntp_message;
  95. /* this structure holds data about results from querying offset from a peer */
  96. typedef struct {
  97. time_t waiting; /* ts set when we started waiting for a response */
  98. int connected; /* don't try to "write()" if "connect()" fails */
  99. int num_requests;
  100. int num_responses; /* number of successfully received responses */
  101. uint8_t stratum; /* copied verbatim from the ntp_message */
  102. double rtdelay; /* converted from the ntp_message */
  103. double rtdisp; /* converted from the ntp_message */
  104. double offset[AVG_NUM]; /* offsets from each response */
  105. uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
  106. } ntp_server_results;
  107. /* define this globally to be able to do other checks */
  108. ntp_server_results *servers=NULL;
  109. /* bits 1,2 are the leap indicator */
  110. #define LI_MASK 0xc0
  111. #define LI(x) ((x&LI_MASK)>>6)
  112. #define LI_SET(x,y) do{ x |= ((y<<6)&LI_MASK); }while(0)
  113. /* and these are the values of the leap indicator */
  114. #define LI_NOWARNING 0x00
  115. #define LI_EXTRASEC 0x01
  116. #define LI_MISSINGSEC 0x02
  117. #define LI_ALARM 0x03
  118. /* bits 3,4,5 are the ntp version */
  119. #define VN_MASK 0x38
  120. #define VN(x) ((x&VN_MASK)>>3)
  121. #define VN_SET(x,y) do{ x |= ((y<<3)&VN_MASK); }while(0)
  122. #define VN_RESERVED 0x02
  123. /* bits 6,7,8 are the ntp mode */
  124. #define MODE_MASK 0x07
  125. #define MODE(x) (x&MODE_MASK)
  126. #define MODE_SET(x,y) do{ x |= (y&MODE_MASK); }while(0)
  127. /* here are some values */
  128. #define MODE_CLIENT 0x03
  129. #define MODE_CONTROLMSG 0x06
  130. /* In control message, bits 8-10 are R,E,M bits */
  131. #define REM_MASK 0xe0
  132. #define REM_RESP 0x80
  133. #define REM_ERROR 0x40
  134. #define REM_MORE 0x20
  135. /* In control message, bits 11 - 15 are opcode */
  136. #define OP_MASK 0x1f
  137. #define OP_SET(x,y) do{ x |= (y&OP_MASK); }while(0)
  138. #define OP_READSTAT 0x01
  139. #define OP_READVAR 0x02
  140. /* In peer status bytes, bits 6,7,8 determine clock selection status */
  141. #define PEER_SEL(x) ((ntohs(x)>>8)&0x07)
  142. #define PEER_INCLUDED 0x04
  143. #define PEER_SYNCSOURCE 0x06
  144. /**
  145. ** a note about the 32-bit "fixed point" numbers:
  146. **
  147. they are divided into halves, each being a 16-bit int in network byte order:
  148. - the first 16 bits are an int on the left side of a decimal point.
  149. - the second 16 bits represent a fraction n/(2^16)
  150. likewise for the 64-bit "fixed point" numbers with everything doubled :)
  151. **/
  152. /* macros to access the left/right 16 bits of a 32-bit ntp "fixed point"
  153. number. note that these can be used as lvalues too */
  154. #define L16(x) (((uint16_t*)&x)[0])
  155. #define R16(x) (((uint16_t*)&x)[1])
  156. /* macros to access the left/right 32 bits of a 64-bit ntp "fixed point"
  157. number. these too can be used as lvalues */
  158. #define L32(x) (((uint32_t*)&x)[0])
  159. #define R32(x) (((uint32_t*)&x)[1])
  160. /* ntp wants seconds since 1/1/00, epoch is 1/1/70. this is the difference */
  161. #define EPOCHDIFF 0x83aa7e80UL
  162. /* extract double from 32-bit ntp fixed point number, without violating strict aliasing rules */
  163. double ntp32_to_double(uint32_t n) {
  164. double result = 0;
  165. if (n) {
  166. uint16_t l16 = ntohs((uint16_t) (n & ((1<<16) - 1)));
  167. uint16_t r16 = ntohs((uint16_t) (n >> 16));
  168. result = l16 + ((double) r16/65536.0);
  169. }
  170. return result;
  171. }
  172. /* extract a 32-bit ntp fixed point number into a double */
  173. /* #define NTP32asDOUBLE(x) (ntohs(L16(x)) + (double)ntohs(R16(x))/65536.0)*/
  174. /* extract double from 64-bit ntp fixed point number, without violating strict aliasing rules */
  175. double ntp64_to_double(uint64_t n) {
  176. double result = 0;
  177. if (n) {
  178. uint32_t l32 = ntohl((uint32_t) (n & ((1ul<<32) - 1)));
  179. uint32_t r32 = ntohl((uint32_t) (n >> 32));
  180. result = (l32 - EPOCHDIFF)
  181. + (.00000001*(0.5+(double)(r32/42.94967296)));
  182. }
  183. return result;
  184. }
  185. /* likewise for a 64-bit ntp fp number */
  186. /* #define NTP64asDOUBLE(n) (double)(((uint64_t)n)?\
  187. (ntohl(L32(n))-EPOCHDIFF) + \
  188. (.00000001*(0.5+(double)(ntohl(R32(n))/42.94967296))):\
  189. 0)*/
  190. /* convert a struct timeval to a double */
  191. #define TVasDOUBLE(x) (double)(x.tv_sec+(0.000001*x.tv_usec))
  192. struct timeval ntp64_to_tv(uint64_t n) {
  193. struct timeval result = {};
  194. if (n) {
  195. uint32_t l32 = ntohl((uint32_t) (n & ((1ul<<32) - 1)));
  196. uint32_t r32 = ntohl((uint32_t) (n >> 32));
  197. result.tv_sec = l32 - EPOCHDIFF;
  198. result.tv_usec = (int)(0.5+(double)(r32/4294.967296));
  199. }
  200. return result;
  201. }
  202. /* convert an ntp 64-bit fp number to a struct timeval */
  203. /* #define NTP64toTV(n,t) \
  204. do{ if(!n) t.tv_sec = t.tv_usec = 0; \
  205. else { \
  206. t.tv_sec=ntohl(L32(n))-EPOCHDIFF; \
  207. t.tv_usec=(int)(0.5+(double)(ntohl(R32(n))/4294.967296)); \
  208. } \
  209. }while(0) */
  210. /* convert a struct timeval to an ntp 64-bit fp number */
  211. /* #define TVtoNTP64(t,n) \
  212. do{ if(!t.tv_usec && !t.tv_sec) n=0x0UL; \
  213. else { \
  214. L32(n)=htonl(t.tv_sec + EPOCHDIFF); \
  215. R32(n)=htonl((uint64_t)((4294.967296*t.tv_usec)+.5)); \
  216. } \
  217. } while(0) */
  218. /* NTP control message header is 12 bytes, plus any data in the data
  219. * field, plus null padding to the nearest 32-bit boundary per rfc.
  220. */
  221. #define SIZEOF_NTPCM(m) (12+ntohs(m.count)+((m.count)?4-(ntohs(m.count)%4):0))
  222. /* finally, a little helper or two for debugging: */
  223. #define DBG(x) do{if(verbose>1){ x; }}while(0);
  224. #define PRINTSOCKADDR(x) \
  225. do{ \
  226. printf("%u.%u.%u.%u", (x>>24)&0xff, (x>>16)&0xff, (x>>8)&0xff, x&0xff);\
  227. }while(0);
  228. /* calculate the offset of the local clock */
  229. static inline double calc_offset(const ntp_message *m, const struct timeval *t){
  230. double client_tx, peer_rx, peer_tx, client_rx;
  231. client_tx = ntp64_to_double(m->origts);
  232. peer_rx = ntp64_to_double(m->rxts);
  233. peer_tx = ntp64_to_double(m->txts);
  234. client_rx=TVasDOUBLE((*t));
  235. return (.5*((peer_tx-client_rx)+(peer_rx-client_tx)));
  236. }
  237. /* print out a ntp packet in human readable/debuggable format */
  238. void print_ntp_message(const ntp_message *p){
  239. struct timeval ref, orig, rx, tx;
  240. ref = ntp64_to_tv(p->refts);
  241. orig = ntp64_to_tv(p->origts);
  242. rx = ntp64_to_tv(p->rxts);
  243. tx = ntp64_to_tv(p->txts);
  244. printf("packet contents:\n");
  245. printf("\tflags: 0x%.2x\n", p->flags);
  246. printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
  247. printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
  248. printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
  249. printf("\tstratum = %d\n", p->stratum);
  250. printf("\tpoll = %g\n", pow(2, p->poll));
  251. printf("\tprecision = %g\n", pow(2, p->precision));
  252. printf("\trtdelay = %-.16g\n", ntp32_to_double(p->rtdelay));
  253. printf("\trtdisp = %-.16g\n", ntp32_to_double(p->rtdisp));
  254. printf("\trefid = %x\n", p->refid);
  255. printf("\trefts = %-.16g\n", ntp64_to_double(p->refts));
  256. printf("\torigts = %-.16g\n", ntp64_to_double(p->origts));
  257. printf("\trxts = %-.16g\n", ntp64_to_double(p->rxts));
  258. printf("\ttxts = %-.16g\n", ntp64_to_double(p->txts));
  259. }
  260. void setup_request(ntp_message *p){
  261. struct timeval t;
  262. memset(p, 0, sizeof(ntp_message));
  263. LI_SET(p->flags, LI_ALARM);
  264. VN_SET(p->flags, 4);
  265. MODE_SET(p->flags, MODE_CLIENT);
  266. p->poll=4;
  267. p->precision=(int8_t)0xfa;
  268. p->rtdelay_l16=htons(1);
  269. p->rtdisp_l16=htons(1);
  270. gettimeofday(&t, NULL);
  271. /* This used to use TVtoNTP64 but we ran into issues with strict aliasing/type punning.
  272. * We only used the macro in one place, so it's inlined now */
  273. if (t.tv_usec || t.tv_sec) {
  274. p->txts_l32 = htonl(t.tv_sec + EPOCHDIFF);
  275. p->txts_r32 = htonl((uint64_t) ((4294.967296*t.tv_usec)+.5));
  276. }
  277. }
  278. /* select the "best" server from a list of servers, and return its index.
  279. * this is done by filtering servers based on stratum, dispersion, and
  280. * finally round-trip delay. */
  281. int best_offset_server(const ntp_server_results *slist, int nservers){
  282. int i=0, cserver=0, best_server=-1;
  283. /* for each server */
  284. for(cserver=0; cserver<nservers; cserver++){
  285. /* We don't want any servers that fails these tests */
  286. /* Sort out servers that didn't respond or responede with a 0 stratum;
  287. * stratum 0 is for reference clocks so no NTP server should ever report
  288. * a stratum 0 */
  289. if ( slist[cserver].stratum == 0){
  290. if (verbose) printf("discarding peer %d: stratum=%d\n", cserver, slist[cserver].stratum);
  291. continue;
  292. }
  293. /* Sort out servers with error flags */
  294. if ( LI(slist[cserver].flags) == LI_ALARM ){
  295. if (verbose) printf("discarding peer %d: flags=%d\n", cserver, LI(slist[cserver].flags));
  296. continue;
  297. }
  298. /* If we don't have a server yet, use the first one */
  299. if (best_server == -1) {
  300. best_server = cserver;
  301. DBG(printf("using peer %d as our first candidate\n", best_server));
  302. continue;
  303. }
  304. /* compare the server to the best one we've seen so far */
  305. /* does it have an equal or better stratum? */
  306. DBG(printf("comparing peer %d with peer %d\n", cserver, best_server));
  307. if(slist[cserver].stratum <= slist[best_server].stratum){
  308. DBG(printf("stratum for peer %d <= peer %d\n", cserver, best_server));
  309. /* does it have an equal or better dispersion? */
  310. if(slist[cserver].rtdisp <= slist[best_server].rtdisp){
  311. DBG(printf("dispersion for peer %d <= peer %d\n", cserver, best_server));
  312. /* does it have a better rtdelay? */
  313. if(slist[cserver].rtdelay < slist[best_server].rtdelay){
  314. DBG(printf("rtdelay for peer %d < peer %d\n", cserver, best_server));
  315. best_server = cserver;
  316. DBG(printf("peer %d is now our best candidate\n", best_server));
  317. }
  318. }
  319. }
  320. }
  321. if(best_server >= 0) {
  322. DBG(printf("best server selected: peer %d\n", best_server));
  323. return best_server;
  324. } else {
  325. DBG(printf("no peers meeting synchronization criteria :(\n"));
  326. return -1;
  327. }
  328. }
  329. /* do everything we need to get the total average offset
  330. * - we use a certain amount of parallelization with poll() to ensure
  331. * we don't waste time sitting around waiting for single packets.
  332. * - we also "manually" handle resolving host names and connecting, because
  333. * we have to do it in a way that our lazy macros don't handle currently :( */
  334. double offset_request(const char *host, int *status){
  335. int i=0, j=0, ga_result=0, *socklist=NULL, respnum=0;
  336. int servers_completed=0, one_read=0, servers_readable=0, best_index=-1;
  337. time_t now_time=0, start_ts=0;
  338. ntp_message *req=NULL;
  339. double avg_offset=0.;
  340. num_hosts = 0;
  341. struct timeval recv_time;
  342. struct addrinfo *ai=NULL, *ai_tmp=NULL, hints;
  343. struct pollfd *ufds=NULL;
  344. /* setup hints to only return results from getaddrinfo that we'd like */
  345. memset(&hints, 0, sizeof(struct addrinfo));
  346. hints.ai_family = address_family;
  347. hints.ai_protocol = IPPROTO_UDP;
  348. hints.ai_socktype = SOCK_DGRAM;
  349. /* fill in ai with the list of hosts resolved by the host name */
  350. ga_result = getaddrinfo(host, port, &hints, &ai);
  351. if(ga_result!=0){
  352. die(STATE_UNKNOWN, "error getting address for %s: %s\n",
  353. host, gai_strerror(ga_result));
  354. }
  355. /* count the number of returned hosts, and allocate stuff accordingly */
  356. for(ai_tmp=ai; ai_tmp!=NULL; ai_tmp=ai_tmp->ai_next){ num_hosts++; }
  357. req=(ntp_message*)malloc(sizeof(ntp_message)*num_hosts);
  358. if(req==NULL) die(STATE_UNKNOWN, "can not allocate ntp message array");
  359. socklist=(int*)malloc(sizeof(int)*num_hosts);
  360. if(socklist==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
  361. ufds=(struct pollfd*)malloc(sizeof(struct pollfd)*num_hosts);
  362. if(ufds==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
  363. servers=(ntp_server_results*)malloc(sizeof(ntp_server_results)*num_hosts);
  364. if(servers==NULL) die(STATE_UNKNOWN, "can not allocate server array");
  365. memset(servers, 0, sizeof(ntp_server_results)*num_hosts);
  366. DBG(printf("Found %d peers to check\n", num_hosts));
  367. /* setup each socket for writing, and the corresponding struct pollfd */
  368. ai_tmp=ai;
  369. for(i=0;ai_tmp;i++){
  370. socklist[i]=socket(ai_tmp->ai_family, SOCK_DGRAM, IPPROTO_UDP);
  371. if(socklist[i] == -1) {
  372. perror(NULL);
  373. die(STATE_UNKNOWN, "can not create new socket");
  374. }
  375. if(connect(socklist[i], ai_tmp->ai_addr, ai_tmp->ai_addrlen)){
  376. /* don't die here, because it is enough if there is one server
  377. answering in time. This also would break for dual ipv4/6 stacked
  378. ntp servers when the client only supports on of them.
  379. */
  380. DBG(printf("can't create socket connection on peer %i: %s\n", i, strerror(errno)));
  381. } else {
  382. ufds[i].fd=socklist[i];
  383. ufds[i].events=POLLIN;
  384. ufds[i].revents=0;
  385. servers[i].connected=1;
  386. }
  387. ai_tmp = ai_tmp->ai_next;
  388. }
  389. /* now do AVG_NUM checks to each host. We stop before timeout/2 seconds
  390. * have passed in order to ensure post-processing and jitter time. */
  391. now_time=start_ts=time(NULL);
  392. while(servers_completed<num_hosts && now_time-start_ts <= timeout_interval - 1){
  393. /* loop through each server and find each one which hasn't
  394. * timed out yet and is still lacking some responses. For each
  395. * of these servers, send a new request, and update the
  396. * "waiting" timestamp with the current time. */
  397. now_time=time(NULL);
  398. for(i=0; i<num_hosts; i++){
  399. if(servers[i].connected == 0)
  400. continue;
  401. if(servers[i].waiting<now_time && servers[i].num_responses<AVG_NUM){
  402. if(verbose && servers[i].num_requests != servers[i].num_responses) printf("re-");
  403. if(verbose) printf("sending request to peer %d\n", i);
  404. setup_request(&req[i]);
  405. write(socklist[i], &req[i], sizeof(ntp_message));
  406. servers[i].waiting=now_time+delay;
  407. if(servers[i].num_requests == servers[i].num_responses) {
  408. servers[i].num_requests++;
  409. }
  410. break;
  411. }
  412. }
  413. /* quickly poll for any sockets with pending data */
  414. servers_readable=poll(ufds, num_hosts, 100);
  415. if(servers_readable==-1){
  416. perror("polling ntp sockets");
  417. die(STATE_UNKNOWN, "communication errors");
  418. }
  419. /* read from any sockets with pending data */
  420. for(i=0; servers_readable && i<num_hosts; i++){
  421. if(ufds[i].revents&POLLIN && servers[i].num_responses < AVG_NUM){
  422. if(verbose) {
  423. printf("response from peer %d: ", i);
  424. }
  425. read(ufds[i].fd, &req[i], sizeof(ntp_message));
  426. gettimeofday(&recv_time, NULL);
  427. DBG(print_ntp_message(&req[i]));
  428. respnum=servers[i].num_responses++;
  429. servers[i].offset[respnum]=calc_offset(&req[i], &recv_time)+time_offset;
  430. if(verbose) {
  431. printf("offset %.10g\n", servers[i].offset[respnum]);
  432. }
  433. servers[i].stratum=req[i].stratum;
  434. servers[i].rtdisp=ntp32_to_double(req[i].rtdisp);
  435. servers[i].rtdelay=ntp32_to_double(req[i].rtdelay);
  436. servers[i].waiting--;
  437. servers[i].flags=req[i].flags;
  438. servers_readable--;
  439. one_read = 1;
  440. if(servers[i].num_responses==AVG_NUM) servers_completed++;
  441. }
  442. }
  443. /* lather, rinse, repeat. */
  444. /* break if we have one response but other ntp servers doesn't response */
  445. /* greater than timeout_interval/2 */
  446. if (servers_completed && now_time-start_ts > timeout_interval/2) break;
  447. }
  448. if (one_read == 0) {
  449. die(timeout_state, "%s: No response from NTP server\n", state_text(timeout_state));
  450. }
  451. /* now, pick the best server from the list */
  452. best_index=best_offset_server(servers, num_hosts);
  453. if(best_index < 0){
  454. *status=STATE_UNKNOWN;
  455. } else {
  456. /* finally, calculate the average offset */
  457. for(i=0; i<servers[best_index].num_responses;i++){
  458. avg_offset+=servers[best_index].offset[j];
  459. }
  460. avg_offset/=servers[best_index].num_responses;
  461. }
  462. /* cleanup */
  463. for(j=0; j<num_hosts; j++){ close(socklist[j]); }
  464. free(socklist);
  465. free(ufds);
  466. free(req);
  467. freeaddrinfo(ai);
  468. if(verbose) printf("overall average offset: %.10g\n", avg_offset);
  469. return avg_offset;
  470. }
  471. int process_arguments(int argc, char **argv){
  472. int c;
  473. int option=0;
  474. static struct option longopts[] = {
  475. {"version", no_argument, 0, 'V'},
  476. {"help", no_argument, 0, 'h'},
  477. {"verbose", no_argument, 0, 'v'},
  478. {"use-ipv4", no_argument, 0, '4'},
  479. {"use-ipv6", no_argument, 0, '6'},
  480. {"quiet", no_argument, 0, 'q'},
  481. {"time-offset", optional_argument, 0, 'o'},
  482. {"delay", optional_argument, 0, 'd'},
  483. {"warning", required_argument, 0, 'w'},
  484. {"critical", required_argument, 0, 'c'},
  485. {"stratum-warn", required_argument, 0, 'W'},
  486. {"stratum-crit", required_argument, 0, 'C'},
  487. {"timeout", required_argument, 0, 't'},
  488. {"hostname", required_argument, 0, 'H'},
  489. {"port", required_argument, 0, 'p'},
  490. {0, 0, 0, 0}
  491. };
  492. if (argc < 2)
  493. usage ("\n");
  494. while (1) {
  495. c = getopt_long (argc, argv, "Vhv46qw:c:t:H:p:o:d:C:W:", longopts, &option);
  496. if (c == -1 || c == EOF || c == 1)
  497. break;
  498. switch (c) {
  499. case 'h':
  500. print_help();
  501. exit(STATE_OK);
  502. break;
  503. case 'V':
  504. print_revision(progname, NP_VERSION);
  505. exit(STATE_OK);
  506. break;
  507. case 'v':
  508. verbose++;
  509. break;
  510. case 'q':
  511. quiet = 1;
  512. break;
  513. case 'w':
  514. owarn = optarg;
  515. break;
  516. case 'c':
  517. ocrit = optarg;
  518. break;
  519. case 'W':
  520. swarn = optarg;
  521. break;
  522. case 'C':
  523. scrit = optarg;
  524. break;
  525. case 'H':
  526. if(is_host(optarg) == FALSE)
  527. usage2(_("Invalid hostname/address"), optarg);
  528. server_address = strdup(optarg);
  529. break;
  530. case 'p':
  531. port = strdup(optarg);
  532. break;
  533. case 't':
  534. timeout_interval = parse_timeout_string(optarg);
  535. break;
  536. case 'o':
  537. time_offset=atoi(optarg);
  538. break;
  539. case 'd':
  540. delay=atoi(optarg);
  541. break;
  542. case '4':
  543. address_family = AF_INET;
  544. break;
  545. case '6':
  546. #ifdef USE_IPV6
  547. address_family = AF_INET6;
  548. #else
  549. usage4 (_("IPv6 support not available"));
  550. #endif
  551. break;
  552. case '?':
  553. /* print short usage statement if args not parsable */
  554. usage5 ();
  555. break;
  556. }
  557. }
  558. if(server_address == NULL){
  559. usage4(_("Hostname was not supplied"));
  560. }
  561. return 0;
  562. }
  563. char *perfd_offset (double offset)
  564. {
  565. return sperfdata ("offset", offset, "s",
  566. offset_thresholds->warning_string,
  567. offset_thresholds->critical_string,
  568. FALSE, 0, FALSE, 0);
  569. }
  570. int main(int argc, char *argv[]){
  571. int result, offset_result;
  572. double offset=0;
  573. char *result_line, *perfdata_line;
  574. setlocale (LC_ALL, "");
  575. setlocale (LC_NUMERIC, "C");
  576. bindtextdomain (PACKAGE, LOCALEDIR);
  577. textdomain (PACKAGE);
  578. offset_result = STATE_OK;
  579. /* Parse extra opts if any */
  580. argv=np_extra_opts (&argc, argv, progname);
  581. if (process_arguments (argc, argv) == ERROR)
  582. usage4 (_("Could not parse arguments"));
  583. set_thresholds(&offset_thresholds, owarn, ocrit);
  584. /* initialize alarm signal handling */
  585. signal (SIGALRM, socket_timeout_alarm_handler);
  586. /* set socket timeout */
  587. alarm (timeout_interval);
  588. offset = offset_request(server_address, &offset_result);
  589. if (offset_result == STATE_UNKNOWN) {
  590. result = (quiet == 1 ? STATE_UNKNOWN : STATE_CRITICAL);
  591. } else {
  592. result = get_status(fabs(offset), offset_thresholds);
  593. }
  594. int i;
  595. int servers_warn_stratum=0;
  596. int servers_crit_stratum=0;
  597. int servers_worst_stratum=0;
  598. int servers_best_stratum=16;
  599. for (i=0; i<num_hosts; i++) {
  600. // set best stratum
  601. if (servers[i].stratum < servers_best_stratum)
  602. servers_best_stratum = servers[i].stratum;
  603. // set worst stratum
  604. if (servers[i].stratum > servers_worst_stratum)
  605. servers_worst_stratum = servers[i].stratum;
  606. if (servers[i].stratum >= atoi(scrit))
  607. servers_crit_stratum++;
  608. if (servers[i].stratum >= atoi(swarn))
  609. servers_warn_stratum++;
  610. }
  611. // adjust result for stratum check
  612. if ((result == STATE_WARNING || result == STATE_OK) && servers_crit_stratum > 0)
  613. result = STATE_CRITICAL;
  614. if (result == STATE_OK && servers_warn_stratum > 0)
  615. result = STATE_WARNING;
  616. switch (result) {
  617. case STATE_CRITICAL :
  618. xasprintf(&result_line, _("NTP CRITICAL:"));
  619. break;
  620. case STATE_WARNING :
  621. xasprintf(&result_line, _("NTP WARNING:"));
  622. break;
  623. case STATE_OK :
  624. xasprintf(&result_line, _("NTP OK:"));
  625. break;
  626. default :
  627. xasprintf(&result_line, _("NTP UNKNOWN:"));
  628. break;
  629. }
  630. if(offset_result == STATE_UNKNOWN){
  631. xasprintf(&result_line, "%s %s", result_line, _("Offset unknown"));
  632. xasprintf(&perfdata_line, "");
  633. } else {
  634. xasprintf(&result_line, "%s %s %.10g secs, stratum best:%d worst:%d", result_line, _("Offset"), offset, servers_best_stratum, servers_worst_stratum);
  635. xasprintf(&perfdata_line, "%s stratum_best=%d stratum_worst=%d num_warn_stratum=%d num_crit_stratum=%d", perfd_offset(offset), servers_best_stratum, servers_worst_stratum, servers_warn_stratum, servers_crit_stratum);
  636. }
  637. printf("%s|%s\n", result_line, perfdata_line);
  638. free(servers);
  639. if(server_address!=NULL) free(server_address);
  640. return result;
  641. }
  642. void print_help(void){
  643. print_revision(progname, NP_VERSION);
  644. printf ("Copyright (c) 2006 Sean Finney\n");
  645. printf (COPYRIGHT, copyright, email);
  646. printf ("%s\n", _("This plugin checks the clock offset with the ntp server"));
  647. printf ("\n\n");
  648. print_usage();
  649. printf (UT_HELP_VRSN);
  650. printf (UT_EXTRA_OPTS);
  651. printf (UT_IPv46);
  652. printf (UT_HOST_PORT, 'p', "123");
  653. printf (" %s\n", "-q, --quiet");
  654. printf (" %s\n", _("Returns UNKNOWN instead of CRITICAL if offset cannot be found"));
  655. printf (" %s\n", "-w, --warning=THRESHOLD");
  656. printf (" %s\n", _("Offset to result in warning status (seconds)"));
  657. printf (" %s\n", "-c, --critical=THRESHOLD");
  658. printf (" %s\n", _("Offset to result in critical status (seconds)"));
  659. printf (" %s\n", "-o, --time_offset=INTEGER");
  660. printf (" %s\n", _("Expected offset of the ntp server relative to local server (seconds)"));
  661. printf (" %s\n", "-d, --delay=INTEGER");
  662. printf (" %s\n", _("Delay between each packet (seconds)"));
  663. printf (" %s\n", "-W, --stratum-warn=INTEGER");
  664. printf (" %s\n", _("Alert warning if stratum is worse (less) than specfied value"));
  665. printf (" %s\n", "-C, --stratum-crit=INTEGER");
  666. printf (" %s\n", _("Alert critical if stratum is worse (less) than specfied value"));
  667. printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
  668. printf (UT_VERBOSE);
  669. printf("\n");
  670. printf("%s\n", _("This plugin checks the clock offset between the local host and a"));
  671. printf("%s\n", _("remote NTP server. It is independent of any commandline programs or"));
  672. printf("%s\n", _("external libraries."));
  673. printf("\n");
  674. printf("%s\n", _("Notes:"));
  675. printf(" %s\n", _("If you'd rather want to monitor an NTP server, please use"));
  676. printf(" %s\n", _("check_ntp_peer."));
  677. printf(" %s\n", _("--time-offset is useful for compensating for servers with known"));
  678. printf(" %s\n", _("and expected clock skew."));
  679. printf(" %s\n", _("--delay is useful if you are triggering the anti-DOS for the"));
  680. printf(" %s\n", _("NTP server and need to leave a bigger gap between queries"));
  681. printf("\n");
  682. printf(UT_THRESHOLDS_NOTES);
  683. printf("\n");
  684. printf("%s\n", _("Examples:"));
  685. printf(" %s\n", ("./check_ntp_time -H ntpserv -w 0.5 -c 1"));
  686. printf (UT_SUPPORT);
  687. }
  688. void
  689. print_usage(void)
  690. {
  691. printf ("%s\n", _("Usage:"));
  692. printf(" %s -H <host> [-4|-6] [-w <warn>] [-c <crit>] [-v verbose] [-o <time offset>] [-d <delay>] [-W <stratum warn>] [-C <stratum crit>]\n", progname);
  693. }