check_ntp.c 30 KB

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