check_ntp.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. /*****************************************************************************
  2. *
  3. * Nagios check_ntp 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 plugin
  12. *
  13. * This plugin to check ntp servers independent of any commandline
  14. * programs or external libraries.
  15. *
  16. *
  17. * This program is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU General Public License as published by
  19. * the Free Software Foundation, either version 3 of the License, or
  20. * (at your option) any later version.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU General Public License
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  29. *
  30. *
  31. *****************************************************************************/
  32. const char *progname = "check_ntp";
  33. const char *copyright = "2006-2014";
  34. const char *email = "devel@nagios-plugins.org";
  35. #include "common.h"
  36. #include "netutils.h"
  37. #include "utils.h"
  38. static char *server_address=NULL;
  39. static int verbose=0;
  40. static short do_offset=0;
  41. static char *owarn="60";
  42. static char *ocrit="120";
  43. static short do_jitter=0;
  44. static char *jwarn="5000";
  45. static char *jcrit="10000";
  46. static int delay=2;
  47. int process_arguments (int, char **);
  48. thresholds *offset_thresholds = NULL;
  49. thresholds *jitter_thresholds = NULL;
  50. void print_help (void);
  51. void print_usage (void);
  52. /* number of times to perform each request to get a good average. */
  53. #ifndef AVG_NUM
  54. #define AVG_NUM 4
  55. #endif
  56. /* max size of control message data */
  57. #define MAX_CM_SIZE 468
  58. /* this structure holds everything in an ntp request/response as per rfc1305 */
  59. typedef struct {
  60. uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
  61. uint8_t stratum; /* clock stratum */
  62. int8_t poll; /* polling interval */
  63. int8_t precision; /* precision of the local clock */
  64. int32_t rtdelay; /* total rt delay, as a fixed point num. see macros */
  65. uint32_t rtdisp; /* like above, but for max err to primary src */
  66. uint32_t refid; /* ref clock identifier */
  67. uint64_t refts; /* reference timestamp. local time local clock */
  68. uint64_t origts; /* time at which request departed client */
  69. uint64_t rxts; /* time at which request arrived at server */
  70. uint64_t txts; /* time at which request departed server */
  71. } ntp_message;
  72. /* this structure holds data about results from querying offset from a peer */
  73. typedef struct {
  74. time_t waiting; /* ts set when we started waiting for a response */
  75. int num_requests;
  76. int num_responses; /* number of successfully received responses */
  77. uint8_t stratum; /* copied verbatim from the ntp_message */
  78. double rtdelay; /* converted from the ntp_message */
  79. double rtdisp; /* converted from the ntp_message */
  80. double offset[AVG_NUM]; /* offsets from each response */
  81. uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
  82. } ntp_server_results;
  83. /* this structure holds everything in an ntp control message as per rfc1305 */
  84. typedef struct {
  85. uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
  86. uint8_t op; /* R,E,M bits and Opcode */
  87. uint16_t seq; /* Packet sequence */
  88. uint16_t status; /* Clock status */
  89. uint16_t assoc; /* Association */
  90. uint16_t offset; /* Similar to TCP sequence # */
  91. uint16_t count; /* # bytes of data */
  92. char data[MAX_CM_SIZE]; /* ASCII data of the request */
  93. /* NB: not necessarily NULL terminated! */
  94. } ntp_control_message;
  95. /* this is an association/status-word pair found in control packet responses */
  96. typedef struct {
  97. uint16_t assoc;
  98. uint16_t status;
  99. } ntp_assoc_status_pair;
  100. /* bits 1,2 are the leap indicator */
  101. #define LI_MASK 0xc0
  102. #define LI(x) ((x&LI_MASK)>>6)
  103. #define LI_SET(x,y) do{ x |= ((y<<6)&LI_MASK); }while(0)
  104. /* and these are the values of the leap indicator */
  105. #define LI_NOWARNING 0x00
  106. #define LI_EXTRASEC 0x01
  107. #define LI_MISSINGSEC 0x02
  108. #define LI_ALARM 0x03
  109. /* bits 3,4,5 are the ntp version */
  110. #define VN_MASK 0x38
  111. #define VN(x) ((x&VN_MASK)>>3)
  112. #define VN_SET(x,y) do{ x |= ((y<<3)&VN_MASK); }while(0)
  113. #define VN_RESERVED 0x02
  114. /* bits 6,7,8 are the ntp mode */
  115. #define MODE_MASK 0x07
  116. #define MODE(x) (x&MODE_MASK)
  117. #define MODE_SET(x,y) do{ x |= (y&MODE_MASK); }while(0)
  118. /* here are some values */
  119. #define MODE_CLIENT 0x03
  120. #define MODE_CONTROLMSG 0x06
  121. /* In control message, bits 8-10 are R,E,M bits */
  122. #define REM_MASK 0xe0
  123. #define REM_RESP 0x80
  124. #define REM_ERROR 0x40
  125. #define REM_MORE 0x20
  126. /* In control message, bits 11 - 15 are opcode */
  127. #define OP_MASK 0x1f
  128. #define OP_SET(x,y) do{ x |= (y&OP_MASK); }while(0)
  129. #define OP_READSTAT 0x01
  130. #define OP_READVAR 0x02
  131. /* In peer status bytes, bits 6,7,8 determine clock selection status */
  132. #define PEER_SEL(x) ((ntohs(x)>>8)&0x07)
  133. #define PEER_INCLUDED 0x04
  134. #define PEER_SYNCSOURCE 0x06
  135. /**
  136. ** a note about the 32-bit "fixed point" numbers:
  137. **
  138. they are divided into halves, each being a 16-bit int in network byte order:
  139. - the first 16 bits are an int on the left side of a decimal point.
  140. - the second 16 bits represent a fraction n/(2^16)
  141. likewise for the 64-bit "fixed point" numbers with everything doubled :)
  142. **/
  143. /* macros to access the left/right 16 bits of a 32-bit ntp "fixed point"
  144. number. note that these can be used as lvalues too */
  145. #define L16(x) (((uint16_t*)&x)[0])
  146. #define R16(x) (((uint16_t*)&x)[1])
  147. /* macros to access the left/right 32 bits of a 64-bit ntp "fixed point"
  148. number. these too can be used as lvalues */
  149. #define L32(x) (((uint32_t*)&x)[0])
  150. #define R32(x) (((uint32_t*)&x)[1])
  151. /* ntp wants seconds since 1/1/00, epoch is 1/1/70. this is the difference */
  152. #define EPOCHDIFF 0x83aa7e80UL
  153. /* extract a 32-bit ntp fixed point number into a double */
  154. #define NTP32asDOUBLE(x) (ntohs(L16(x)) + (double)ntohs(R16(x))/65536.0)
  155. /* likewise for a 64-bit ntp fp number */
  156. #define NTP64asDOUBLE(n) (double)(((uint64_t)n)?\
  157. (ntohl(L32(n))-EPOCHDIFF) + \
  158. (.00000001*(0.5+(double)(ntohl(R32(n))/42.94967296))):\
  159. 0)
  160. /* convert a struct timeval to a double */
  161. #define TVasDOUBLE(x) (double)(x.tv_sec+(0.000001*x.tv_usec))
  162. /* convert an ntp 64-bit fp number to a struct timeval */
  163. #define NTP64toTV(n,t) \
  164. do{ if(!n) t.tv_sec = t.tv_usec = 0; \
  165. else { \
  166. t.tv_sec=ntohl(L32(n))-EPOCHDIFF; \
  167. t.tv_usec=(int)(0.5+(double)(ntohl(R32(n))/4294.967296)); \
  168. } \
  169. }while(0)
  170. /* convert a struct timeval to an ntp 64-bit fp number */
  171. #define TVtoNTP64(t,n) \
  172. do{ if(!t.tv_usec && !t.tv_sec) n=0x0UL; \
  173. else { \
  174. L32(n)=htonl(t.tv_sec + EPOCHDIFF); \
  175. R32(n)=htonl((uint64_t)((4294.967296*t.tv_usec)+.5)); \
  176. } \
  177. } while(0)
  178. /* NTP control message header is 12 bytes, plus any data in the data
  179. * field, plus null padding to the nearest 32-bit boundary per rfc.
  180. */
  181. #define SIZEOF_NTPCM(m) (12+ntohs(m.count)+((ntohs(m.count)%4)?4-(ntohs(m.count)%4):0))
  182. /* finally, a little helper or two for debugging: */
  183. #define DBG(x) do{if(verbose>1){ x; }}while(0);
  184. #define PRINTSOCKADDR(x) \
  185. do{ \
  186. printf("%u.%u.%u.%u", (x>>24)&0xff, (x>>16)&0xff, (x>>8)&0xff, x&0xff);\
  187. }while(0);
  188. /* calculate the offset of the local clock */
  189. static inline double calc_offset(const ntp_message *m, const struct timeval *t){
  190. double client_tx, peer_rx, peer_tx, client_rx;
  191. client_tx = NTP64asDOUBLE(m->origts);
  192. peer_rx = NTP64asDOUBLE(m->rxts);
  193. peer_tx = NTP64asDOUBLE(m->txts);
  194. client_rx=TVasDOUBLE((*t));
  195. return (.5*((peer_tx-client_rx)+(peer_rx-client_tx)));
  196. }
  197. /* print out a ntp packet in human readable/debuggable format */
  198. void print_ntp_message(const ntp_message *p){
  199. struct timeval ref, orig, rx, tx;
  200. NTP64toTV(p->refts,ref);
  201. NTP64toTV(p->origts,orig);
  202. NTP64toTV(p->rxts,rx);
  203. NTP64toTV(p->txts,tx);
  204. printf("packet contents:\n");
  205. printf("\tflags: 0x%.2x\n", p->flags);
  206. printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
  207. printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
  208. printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
  209. printf("\tstratum = %d\n", p->stratum);
  210. printf("\tpoll = %g\n", pow(2, p->poll));
  211. printf("\tprecision = %g\n", pow(2, p->precision));
  212. printf("\trtdelay = %-.16g\n", NTP32asDOUBLE(p->rtdelay));
  213. printf("\trtdisp = %-.16g\n", NTP32asDOUBLE(p->rtdisp));
  214. printf("\trefid = %x\n", p->refid);
  215. printf("\trefts = %-.16g\n", NTP64asDOUBLE(p->refts));
  216. printf("\torigts = %-.16g\n", NTP64asDOUBLE(p->origts));
  217. printf("\trxts = %-.16g\n", NTP64asDOUBLE(p->rxts));
  218. printf("\ttxts = %-.16g\n", NTP64asDOUBLE(p->txts));
  219. }
  220. void print_ntp_control_message(const ntp_control_message *p){
  221. int i=0, numpeers=0;
  222. const ntp_assoc_status_pair *peer=NULL;
  223. printf("control packet contents:\n");
  224. printf("\tflags: 0x%.2x , 0x%.2x\n", p->flags, p->op);
  225. printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
  226. printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
  227. printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
  228. printf("\t response=%d (0x%.2x)\n", (p->op&REM_RESP)>0, p->op&REM_RESP);
  229. printf("\t more=%d (0x%.2x)\n", (p->op&REM_MORE)>0, p->op&REM_MORE);
  230. printf("\t error=%d (0x%.2x)\n", (p->op&REM_ERROR)>0, p->op&REM_ERROR);
  231. printf("\t op=%d (0x%.2x)\n", p->op&OP_MASK, p->op&OP_MASK);
  232. printf("\tsequence: %d (0x%.2x)\n", ntohs(p->seq), ntohs(p->seq));
  233. printf("\tstatus: %d (0x%.2x)\n", ntohs(p->status), ntohs(p->status));
  234. printf("\tassoc: %d (0x%.2x)\n", ntohs(p->assoc), ntohs(p->assoc));
  235. printf("\toffset: %d (0x%.2x)\n", ntohs(p->offset), ntohs(p->offset));
  236. printf("\tcount: %d (0x%.2x)\n", ntohs(p->count), ntohs(p->count));
  237. numpeers=ntohs(p->count)/(sizeof(ntp_assoc_status_pair));
  238. if(p->op&REM_RESP && p->op&OP_READSTAT){
  239. peer=(ntp_assoc_status_pair*)p->data;
  240. for(i=0;i<numpeers;i++){
  241. printf("\tpeer id %.2x status %.2x",
  242. ntohs(peer[i].assoc), ntohs(peer[i].status));
  243. if (PEER_SEL(peer[i].status) >= PEER_INCLUDED){
  244. if(PEER_SEL(peer[i].status) >= PEER_SYNCSOURCE){
  245. printf(" <-- current sync source");
  246. } else {
  247. printf(" <-- current sync candidate");
  248. }
  249. }
  250. printf("\n");
  251. }
  252. }
  253. }
  254. void setup_request(ntp_message *p){
  255. struct timeval t;
  256. memset(p, 0, sizeof(ntp_message));
  257. LI_SET(p->flags, LI_ALARM);
  258. VN_SET(p->flags, 4);
  259. MODE_SET(p->flags, MODE_CLIENT);
  260. p->poll=4;
  261. p->precision=(int8_t)0xfa;
  262. L16(p->rtdelay)=htons(1);
  263. L16(p->rtdisp)=htons(1);
  264. gettimeofday(&t, NULL);
  265. TVtoNTP64(t,p->txts);
  266. }
  267. /* select the "best" server from a list of servers, and return its index.
  268. * this is done by filtering servers based on stratum, dispersion, and
  269. * finally round-trip delay. */
  270. int best_offset_server(const ntp_server_results *slist, int nservers){
  271. int i=0, cserver=0, best_server=-1;
  272. /* for each server */
  273. for(cserver=0; cserver<nservers; cserver++){
  274. /* We don't want any servers that fails these tests */
  275. /* Sort out servers that didn't respond or responede with a 0 stratum;
  276. * stratum 0 is for reference clocks so no NTP server should ever report
  277. * a stratum 0 */
  278. if ( slist[cserver].stratum == 0){
  279. if (verbose) printf("discarding peer %d: stratum=%d\n", cserver, slist[cserver].stratum);
  280. continue;
  281. }
  282. /* Sort out servers with error flags */
  283. if ( LI(slist[cserver].flags) == LI_ALARM ){
  284. if (verbose) printf("discarding peer %d: flags=%d\n", cserver, LI(slist[cserver].flags));
  285. continue;
  286. }
  287. /* If we don't have a server yet, use the first one */
  288. if (best_server == -1) {
  289. best_server = cserver;
  290. DBG(printf("using peer %d as our first candidate\n", best_server));
  291. continue;
  292. }
  293. /* compare the server to the best one we've seen so far */
  294. /* does it have an equal or better stratum? */
  295. DBG(printf("comparing peer %d with peer %d\n", cserver, best_server));
  296. if(slist[cserver].stratum <= slist[best_server].stratum){
  297. DBG(printf("stratum for peer %d <= peer %d\n", cserver, best_server));
  298. /* does it have an equal or better dispersion? */
  299. if(slist[cserver].rtdisp <= slist[best_server].rtdisp){
  300. DBG(printf("dispersion for peer %d <= peer %d\n", cserver, best_server));
  301. /* does it have a better rtdelay? */
  302. if(slist[cserver].rtdelay < slist[best_server].rtdelay){
  303. DBG(printf("rtdelay for peer %d < peer %d\n", cserver, best_server));
  304. best_server = cserver;
  305. DBG(printf("peer %d is now our best candidate\n", best_server));
  306. }
  307. }
  308. }
  309. }
  310. if(best_server >= 0) {
  311. DBG(printf("best server selected: peer %d\n", best_server));
  312. return best_server;
  313. } else {
  314. DBG(printf("no peers meeting synchronization criteria :(\n"));
  315. return -1;
  316. }
  317. }
  318. /* do everything we need to get the total average offset
  319. * - we use a certain amount of parallelization with poll() to ensure
  320. * we don't waste time sitting around waiting for single packets.
  321. * - we also "manually" handle resolving host names and connecting, because
  322. * we have to do it in a way that our lazy macros don't handle currently :( */
  323. double offset_request(const char *host, int *status){
  324. int i=0, j=0, ga_result=0, num_hosts=0, *socklist=NULL, respnum=0;
  325. int servers_completed=0, one_read=0, servers_readable=0, best_index=-1;
  326. time_t now_time=0, start_ts=0;
  327. ntp_message *req=NULL;
  328. double avg_offset=0.;
  329. struct timeval recv_time;
  330. struct addrinfo *ai=NULL, *ai_tmp=NULL, hints;
  331. struct pollfd *ufds=NULL;
  332. ntp_server_results *servers=NULL;
  333. /* setup hints to only return results from getaddrinfo that we'd like */
  334. memset(&hints, 0, sizeof(struct addrinfo));
  335. hints.ai_family = address_family;
  336. hints.ai_protocol = IPPROTO_UDP;
  337. hints.ai_socktype = SOCK_DGRAM;
  338. /* fill in ai with the list of hosts resolved by the host name */
  339. ga_result = getaddrinfo(host, "123", &hints, &ai);
  340. if(ga_result!=0){
  341. die(STATE_UNKNOWN, "error getting address for %s: %s\n",
  342. host, gai_strerror(ga_result));
  343. }
  344. /* count the number of returned hosts, and allocate stuff accordingly */
  345. for(ai_tmp=ai; ai_tmp!=NULL; ai_tmp=ai_tmp->ai_next){ num_hosts++; }
  346. req=(ntp_message*)malloc(sizeof(ntp_message)*num_hosts);
  347. if(req==NULL) die(STATE_UNKNOWN, "can not allocate ntp message array");
  348. socklist=(int*)malloc(sizeof(int)*num_hosts);
  349. if(socklist==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
  350. ufds=(struct pollfd*)malloc(sizeof(struct pollfd)*num_hosts);
  351. if(ufds==NULL) die(STATE_UNKNOWN, "can not allocate socket array");
  352. servers=(ntp_server_results*)malloc(sizeof(ntp_server_results)*num_hosts);
  353. if(servers==NULL) die(STATE_UNKNOWN, "can not allocate server array");
  354. memset(servers, 0, sizeof(ntp_server_results)*num_hosts);
  355. DBG(printf("Found %d peers to check\n", num_hosts));
  356. /* setup each socket for writing, and the corresponding struct pollfd */
  357. ai_tmp=ai;
  358. for(i=0;ai_tmp;i++){
  359. socklist[i]=socket(ai_tmp->ai_family, SOCK_DGRAM, IPPROTO_UDP);
  360. if(socklist[i] == -1) {
  361. perror(NULL);
  362. die(STATE_UNKNOWN, "can not create new socket");
  363. }
  364. if(connect(socklist[i], ai_tmp->ai_addr, ai_tmp->ai_addrlen)){
  365. /* don't die here, because it is enough if there is one server
  366. answering in time. This also would break for dual ipv4/6 stacked
  367. ntp servers when the client only supports on of them.
  368. */
  369. DBG(printf("can't create socket connection on peer %i: %s\n", i, strerror(errno)));
  370. } else {
  371. ufds[i].fd=socklist[i];
  372. ufds[i].events=POLLIN;
  373. ufds[i].revents=0;
  374. }
  375. ai_tmp = ai_tmp->ai_next;
  376. }
  377. /* now do AVG_NUM checks to each host. we stop before timeout/2 seconds
  378. * have passed in order to ensure post-processing and jitter time. */
  379. now_time=start_ts=time(NULL);
  380. while(servers_completed<num_hosts && now_time-start_ts <= timeout_interval/2){
  381. /* loop through each server and find each one which hasn't
  382. * timed out yet and is still lacking some responses. For each
  383. * of these servers, send a new request, and update the
  384. * "waiting" timestamp with the current time. */
  385. now_time=time(NULL);
  386. for(i=0; i<num_hosts; i++){
  387. if(servers[i].waiting<now_time && servers[i].num_responses<AVG_NUM){
  388. if(verbose && servers[i].num_requests != servers[i].num_responses) printf("re-");
  389. if(verbose) printf("sending request to peer %d\n", i);
  390. setup_request(&req[i]);
  391. write(socklist[i], &req[i], sizeof(ntp_message));
  392. servers[i].waiting=now_time+delay;
  393. if(servers[i].num_requests == servers[i].num_responses) {
  394. servers[i].num_requests++;
  395. }
  396. break;
  397. }
  398. }
  399. /* quickly poll for any sockets with pending data */
  400. servers_readable=poll(ufds, num_hosts, 100);
  401. if(servers_readable==-1){
  402. perror("polling ntp sockets");
  403. die(STATE_UNKNOWN, "communication errors");
  404. }
  405. /* read from any sockets with pending data */
  406. for(i=0; servers_readable && i<num_hosts; i++){
  407. if(ufds[i].revents&POLLIN && servers[i].num_responses < AVG_NUM){
  408. if(verbose) {
  409. printf("response from peer %d: ", i);
  410. }
  411. read(ufds[i].fd, &req[i], sizeof(ntp_message));
  412. gettimeofday(&recv_time, NULL);
  413. DBG(print_ntp_message(&req[i]));
  414. respnum=servers[i].num_responses++;
  415. servers[i].offset[respnum]=calc_offset(&req[i], &recv_time);
  416. if(verbose) {
  417. printf("offset %.10g\n", servers[i].offset[respnum]);
  418. }
  419. servers[i].stratum=req[i].stratum;
  420. servers[i].rtdisp=NTP32asDOUBLE(req[i].rtdisp);
  421. servers[i].rtdelay=NTP32asDOUBLE(req[i].rtdelay);
  422. servers[i].waiting--;
  423. servers[i].flags=req[i].flags;
  424. servers_readable--;
  425. one_read = 1;
  426. if(servers[i].num_responses==AVG_NUM) servers_completed++;
  427. }
  428. }
  429. /* lather, rinse, repeat. */
  430. }
  431. if (one_read == 0) {
  432. die(timeout_state, "%s: No response from NTP server\n", state_text(timeout_state));
  433. }
  434. /* now, pick the best server from the list */
  435. best_index=best_offset_server(servers, num_hosts);
  436. if(best_index < 0){
  437. *status=STATE_UNKNOWN;
  438. } else {
  439. /* finally, calculate the average offset */
  440. for(i=0; i<servers[best_index].num_responses;i++){
  441. avg_offset+=servers[best_index].offset[i];
  442. }
  443. avg_offset/=servers[best_index].num_responses;
  444. }
  445. /* cleanup */
  446. /* FIXME: Not closing the socket to avoid re-use of the local port
  447. * which can cause old NTP packets to be read instead of NTP control
  448. * pactets in jitter_request(). THERE MUST BE ANOTHER WAY...
  449. * for(j=0; j<num_hosts; j++){ close(socklist[j]); } */
  450. free(socklist);
  451. free(ufds);
  452. free(servers);
  453. free(req);
  454. freeaddrinfo(ai);
  455. if(verbose) printf("overall average offset: %.10g\n", avg_offset);
  456. return avg_offset;
  457. }
  458. void
  459. setup_control_request(ntp_control_message *p, uint8_t opcode, uint16_t seq){
  460. memset(p, 0, sizeof(ntp_control_message));
  461. LI_SET(p->flags, LI_NOWARNING);
  462. VN_SET(p->flags, VN_RESERVED);
  463. MODE_SET(p->flags, MODE_CONTROLMSG);
  464. OP_SET(p->op, opcode);
  465. p->seq = htons(seq);
  466. /* Remaining fields are zero for requests */
  467. }
  468. /* XXX handle responses with the error bit set */
  469. double jitter_request(const char *host, int *status){
  470. int conn=-1, i, npeers=0, num_candidates=0, syncsource_found=0;
  471. int run=0, min_peer_sel=PEER_INCLUDED, num_selected=0, num_valid=0;
  472. int peers_size=0, peer_offset=0;
  473. ntp_assoc_status_pair *peers=NULL;
  474. ntp_control_message req;
  475. const char *getvar = "jitter";
  476. double rval = 0.0, jitter = -1.0;
  477. char *startofvalue=NULL, *nptr=NULL;
  478. void *tmp;
  479. /* Long-winded explanation:
  480. * Getting the jitter requires a number of steps:
  481. * 1) Send a READSTAT request.
  482. * 2) Interpret the READSTAT reply
  483. * a) The data section contains a list of peer identifiers (16 bits)
  484. * and associated status words (16 bits)
  485. * b) We want the value of 0x06 in the SEL (peer selection) value,
  486. * which means "current synchronizatin source". If that's missing,
  487. * we take anything better than 0x04 (see the rfc for details) but
  488. * set a minimum of warning.
  489. * 3) Send a READVAR request for information on each peer identified
  490. * in 2b greater than the minimum selection value.
  491. * 4) Extract the jitter value from the data[] (it's ASCII)
  492. */
  493. my_udp_connect(server_address, 123, &conn);
  494. /* keep sending requests until the server stops setting the
  495. * REM_MORE bit, though usually this is only 1 packet. */
  496. do{
  497. setup_control_request(&req, OP_READSTAT, 1);
  498. DBG(printf("sending READSTAT request"));
  499. write(conn, &req, SIZEOF_NTPCM(req));
  500. DBG(print_ntp_control_message(&req));
  501. /* Attempt to read the largest size packet possible */
  502. req.count=htons(MAX_CM_SIZE);
  503. DBG(printf("receiving READSTAT response"))
  504. read(conn, &req, SIZEOF_NTPCM(req));
  505. DBG(print_ntp_control_message(&req));
  506. /* Each peer identifier is 4 bytes in the data section, which
  507. * we represent as a ntp_assoc_status_pair datatype.
  508. */
  509. peers_size+=ntohs(req.count);
  510. if((tmp=realloc(peers, peers_size)) == NULL)
  511. free(peers), die(STATE_UNKNOWN, "can not (re)allocate 'peers' buffer\n");
  512. peers=tmp;
  513. memcpy((void*)((ptrdiff_t)peers+peer_offset), (void*)req.data, ntohs(req.count));
  514. npeers=peers_size/sizeof(ntp_assoc_status_pair);
  515. peer_offset+=ntohs(req.count);
  516. } while(req.op&REM_MORE);
  517. /* first, let's find out if we have a sync source, or if there are
  518. * at least some candidates. in the case of the latter we'll issue
  519. * a warning but go ahead with the check on them. */
  520. for (i = 0; i < npeers; i++){
  521. if (PEER_SEL(peers[i].status) >= PEER_INCLUDED){
  522. num_candidates++;
  523. if(PEER_SEL(peers[i].status) >= PEER_SYNCSOURCE){
  524. syncsource_found=1;
  525. min_peer_sel=PEER_SYNCSOURCE;
  526. }
  527. }
  528. }
  529. if(verbose) printf("%d candidate peers available\n", num_candidates);
  530. if(verbose && syncsource_found) printf("synchronization source found\n");
  531. if(! syncsource_found){
  532. *status = STATE_UNKNOWN;
  533. if(verbose) printf("warning: no synchronization source found\n");
  534. }
  535. for (run=0; run<AVG_NUM; run++){
  536. if(verbose) printf("jitter run %d of %d\n", run+1, AVG_NUM);
  537. for (i = 0; i < npeers; i++){
  538. /* Only query this server if it is the current sync source */
  539. if (PEER_SEL(peers[i].status) >= min_peer_sel){
  540. char jitter_data[MAX_CM_SIZE+1];
  541. size_t jitter_data_count;
  542. num_selected++;
  543. setup_control_request(&req, OP_READVAR, 2);
  544. req.assoc = peers[i].assoc;
  545. /* By spec, putting the variable name "jitter" in the request
  546. * should cause the server to provide _only_ the jitter value.
  547. * thus reducing net traffic, guaranteeing us only a single
  548. * datagram in reply, and making interpretation much simpler
  549. */
  550. /* Older servers doesn't know what jitter is, so if we get an
  551. * error on the first pass we redo it with "dispersion" */
  552. strncpy(req.data, getvar, MAX_CM_SIZE-1);
  553. req.count = htons(strlen(getvar));
  554. DBG(printf("sending READVAR request...\n"));
  555. write(conn, &req, SIZEOF_NTPCM(req));
  556. DBG(print_ntp_control_message(&req));
  557. req.count = htons(MAX_CM_SIZE);
  558. DBG(printf("receiving READVAR response...\n"));
  559. read(conn, &req, SIZEOF_NTPCM(req));
  560. DBG(print_ntp_control_message(&req));
  561. if(req.op&REM_ERROR && strstr(getvar, "jitter")) {
  562. if(verbose) printf("The 'jitter' command failed (old ntp server?)\nRestarting with 'dispersion'...\n");
  563. getvar = "dispersion";
  564. num_selected--;
  565. i--;
  566. continue;
  567. }
  568. /* get to the float value */
  569. if(verbose) {
  570. printf("parsing jitter from peer %.2x: ", ntohs(peers[i].assoc));
  571. }
  572. if((jitter_data_count = ntohs(req.count)) >= sizeof(jitter_data)){
  573. die(STATE_UNKNOWN,
  574. _("jitter response too large (%lu bytes)\n"),
  575. (unsigned long)jitter_data_count);
  576. }
  577. memcpy(jitter_data, req.data, jitter_data_count);
  578. jitter_data[jitter_data_count] = '\0';
  579. startofvalue = strchr(jitter_data, '=');
  580. if(startofvalue != NULL) {
  581. startofvalue++;
  582. jitter = strtod(startofvalue, &nptr);
  583. }
  584. if(startofvalue == NULL || startofvalue==nptr){
  585. printf("warning: unable to read server jitter response.\n");
  586. *status = STATE_UNKNOWN;
  587. } else {
  588. if(verbose) printf("%g\n", jitter);
  589. num_valid++;
  590. rval += jitter;
  591. }
  592. }
  593. }
  594. if(verbose){
  595. printf("jitter parsed from %d/%d peers\n", num_valid, num_selected);
  596. }
  597. }
  598. rval = num_valid ? rval / num_valid : -1.0;
  599. close(conn);
  600. if(peers!=NULL) free(peers);
  601. /* If we return -1.0, it means no synchronization source was found */
  602. return rval;
  603. }
  604. int process_arguments(int argc, char **argv){
  605. int c;
  606. int option=0;
  607. static struct option longopts[] = {
  608. {"version", no_argument, 0, 'V'},
  609. {"help", no_argument, 0, 'h'},
  610. {"verbose", no_argument, 0, 'v'},
  611. {"use-ipv4", no_argument, 0, '4'},
  612. {"use-ipv6", no_argument, 0, '6'},
  613. {"delay", optional_argument, 0, 'd'},
  614. {"warning", required_argument, 0, 'w'},
  615. {"critical", required_argument, 0, 'c'},
  616. {"jwarn", required_argument, 0, 'j'},
  617. {"jcrit", required_argument, 0, 'k'},
  618. {"timeout", required_argument, 0, 't'},
  619. {"hostname", required_argument, 0, 'H'},
  620. {0, 0, 0, 0}
  621. };
  622. if (argc < 2)
  623. usage ("\n");
  624. while (1) {
  625. c = getopt_long (argc, argv, "Vhv46w:c:j:k:t:H:d:", longopts, &option);
  626. if (c == -1 || c == EOF || c == 1)
  627. break;
  628. switch (c) {
  629. case 'h':
  630. print_help();
  631. exit(STATE_OK);
  632. break;
  633. case 'V':
  634. print_revision(progname, NP_VERSION);
  635. exit(STATE_OK);
  636. break;
  637. case 'v':
  638. verbose++;
  639. break;
  640. case 'w':
  641. do_offset=1;
  642. owarn = optarg;
  643. break;
  644. case 'c':
  645. do_offset=1;
  646. ocrit = optarg;
  647. break;
  648. case 'j':
  649. do_jitter=1;
  650. jwarn = optarg;
  651. break;
  652. case 'k':
  653. do_jitter=1;
  654. jcrit = optarg;
  655. break;
  656. case 'd':
  657. delay=atoi(optarg);
  658. break;
  659. case 'H':
  660. if(is_host(optarg) == FALSE)
  661. usage2(_("Invalid hostname/address"), optarg);
  662. server_address = strdup(optarg);
  663. break;
  664. case 't':
  665. timeout_interval = parse_timeout_string(optarg);
  666. break;
  667. case '4':
  668. address_family = AF_INET;
  669. break;
  670. case '6':
  671. #ifdef USE_IPV6
  672. address_family = AF_INET6;
  673. #else
  674. usage4 (_("IPv6 support not available"));
  675. #endif
  676. break;
  677. case '?':
  678. /* print short usage statement if args not parsable */
  679. usage5 ();
  680. break;
  681. }
  682. }
  683. if(server_address == NULL){
  684. usage4(_("Hostname was not supplied"));
  685. }
  686. return 0;
  687. }
  688. char *perfd_offset (double offset)
  689. {
  690. return fperfdata ("offset", offset, "s",
  691. TRUE, offset_thresholds->warning->end,
  692. TRUE, offset_thresholds->critical->end,
  693. FALSE, 0, FALSE, 0);
  694. }
  695. char *perfd_jitter (double jitter)
  696. {
  697. return fperfdata ("jitter", jitter, "s",
  698. do_jitter, jitter_thresholds->warning->end,
  699. do_jitter, jitter_thresholds->critical->end,
  700. TRUE, 0, FALSE, 0);
  701. }
  702. int main(int argc, char *argv[]){
  703. int result, offset_result, jitter_result;
  704. double offset=0, jitter=0;
  705. char *result_line, *perfdata_line;
  706. setlocale (LC_ALL, "");
  707. bindtextdomain (PACKAGE, LOCALEDIR);
  708. textdomain (PACKAGE);
  709. offset_result = jitter_result = STATE_OK;
  710. /* Parse extra opts if any */
  711. argv=np_extra_opts (&argc, argv, progname);
  712. if (process_arguments (argc, argv) == ERROR)
  713. usage4 (_("Could not parse arguments"));
  714. set_thresholds(&offset_thresholds, owarn, ocrit);
  715. set_thresholds(&jitter_thresholds, jwarn, jcrit);
  716. /* initialize alarm signal handling */
  717. signal (SIGALRM, socket_timeout_alarm_handler);
  718. /* set socket timeout */
  719. alarm (timeout_interval);
  720. offset = offset_request(server_address, &offset_result);
  721. /* check_ntp used to always return CRITICAL if offset_result == STATE_UNKNOWN.
  722. * Now we'll only do that is the offset thresholds were set */
  723. if (do_offset && offset_result == STATE_UNKNOWN) {
  724. result = STATE_CRITICAL;
  725. } else {
  726. result = get_status(fabs(offset), offset_thresholds);
  727. }
  728. /* If not told to check the jitter, we don't even send packets.
  729. * jitter is checked using NTP control packets, which not all
  730. * servers recognize. Trying to check the jitter on OpenNTPD
  731. * (for example) will result in an error
  732. */
  733. if(do_jitter){
  734. jitter=jitter_request(server_address, &jitter_result);
  735. result = max_state_alt(result, get_status(jitter, jitter_thresholds));
  736. /* -1 indicates that we couldn't calculate the jitter
  737. * Only overrides STATE_OK from the offset */
  738. if(jitter == -1.0 && result == STATE_OK)
  739. result = STATE_UNKNOWN;
  740. }
  741. result = max_state_alt(result, jitter_result);
  742. switch (result) {
  743. case STATE_CRITICAL :
  744. xasprintf(&result_line, _("NTP CRITICAL:"));
  745. break;
  746. case STATE_WARNING :
  747. xasprintf(&result_line, _("NTP WARNING:"));
  748. break;
  749. case STATE_OK :
  750. xasprintf(&result_line, _("NTP OK:"));
  751. break;
  752. default :
  753. xasprintf(&result_line, _("NTP UNKNOWN:"));
  754. break;
  755. }
  756. if(offset_result == STATE_UNKNOWN){
  757. xasprintf(&result_line, "%s %s", result_line, _("Offset unknown"));
  758. xasprintf(&perfdata_line, "");
  759. } else {
  760. xasprintf(&result_line, "%s %s %.10g secs", result_line, _("Offset"), offset);
  761. xasprintf(&perfdata_line, "%s", perfd_offset(offset));
  762. }
  763. if (do_jitter) {
  764. xasprintf(&result_line, "%s, jitter=%f", result_line, jitter);
  765. xasprintf(&perfdata_line, "%s %s", perfdata_line, perfd_jitter(jitter));
  766. }
  767. printf("%s|%s\n", result_line, perfdata_line);
  768. if(server_address!=NULL) free(server_address);
  769. return result;
  770. }
  771. void print_help(void){
  772. print_revision(progname, NP_VERSION);
  773. printf ("Copyright (c) 2006 Sean Finney\n");
  774. printf (COPYRIGHT, copyright, email);
  775. printf ("%s\n", _("This plugin checks the selected ntp server"));
  776. printf ("\n\n");
  777. print_usage();
  778. printf (UT_HELP_VRSN);
  779. printf (UT_EXTRA_OPTS);
  780. printf (UT_HOST_PORT, 'p', "123");
  781. printf (UT_IPv46);
  782. printf (" %s\n", "-w, --warning=THRESHOLD");
  783. printf (" %s\n", _("Offset to result in warning status (seconds)"));
  784. printf (" %s\n", "-c, --critical=THRESHOLD");
  785. printf (" %s\n", _("Offset to result in critical status (seconds)"));
  786. printf (" %s\n", "-j, --jwarn=THRESHOLD");
  787. printf (" %s\n", _("Warning threshold for jitter"));
  788. printf (" %s\n", "-k, --jcrit=THRESHOLD");
  789. printf (" %s\n", _("Critical threshold for jitter"));
  790. printf (" %s\n", "-d, --delay=INTEGER");
  791. printf (" %s\n", _("Delay between each packet (seconds)"));
  792. printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
  793. printf (UT_VERBOSE);
  794. printf("\n");
  795. printf("%s\n", _("Notes:"));
  796. printf(" %s\n", _("--delay is useful if you are triggering the anti-DOS for the"));
  797. printf(" %s\n", _("NTP server and need to leave a bigger gap between queries"));
  798. printf(UT_THRESHOLDS_NOTES);
  799. printf("\n");
  800. printf("%s\n", _("Examples:"));
  801. printf(" %s\n", _("Normal offset check:"));
  802. printf(" %s\n", ("./check_ntp -H ntpserv -w 0.5 -c 1"));
  803. printf("\n");
  804. printf(" %s\n", _("Check jitter too, avoiding critical notifications if jitter isn't available"));
  805. printf(" %s\n", _("(See Notes above for more details on thresholds formats):"));
  806. printf(" %s\n", ("./check_ntp -H ntpserv -w 0.5 -c 1 -j -1:100 -k -1:200"));
  807. printf (UT_SUPPORT);
  808. printf ("%s\n", _("WARNING: check_ntp is deprecated. Please use check_ntp_peer or"));
  809. printf ("%s\n\n", _("check_ntp_time instead."));
  810. }
  811. void
  812. print_usage(void)
  813. {
  814. printf ("%s\n", _("WARNING: check_ntp is deprecated. Please use check_ntp_peer or"));
  815. printf ("%s\n\n", _("check_ntp_time instead."));
  816. printf ("%s\n", _("Usage:"));
  817. printf(" %s -H <host> [-w <warn>] [-c <crit>] [-j <warn>] [-k <crit>] [-4|-6] [-v verbose] [-d <delay>]\n", progname);
  818. }