check_ntp.c 28 KB

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