check_ntp.c 26 KB

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