check_ntp.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  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, bytes 6,7,8 determine clock selection status */
  129. #define PEER_SEL(x) (x&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. for(j=0; j<num_hosts; j++){ close(socklist[j]); }
  430. free(socklist);
  431. free(ufds);
  432. free(servers);
  433. free(req);
  434. freeaddrinfo(ai);
  435. if(verbose) printf("overall average offset: %.10g\n", avg_offset);
  436. return avg_offset;
  437. }
  438. void
  439. setup_control_request(ntp_control_message *p, uint8_t opcode, uint16_t seq){
  440. memset(p, 0, sizeof(ntp_control_message));
  441. LI_SET(p->flags, LI_NOWARNING);
  442. VN_SET(p->flags, VN_RESERVED);
  443. MODE_SET(p->flags, MODE_CONTROLMSG);
  444. OP_SET(p->op, opcode);
  445. p->seq = htons(seq);
  446. /* Remaining fields are zero for requests */
  447. }
  448. /* XXX handle responses with the error bit set */
  449. double jitter_request(const char *host, int *status){
  450. int conn=-1, i, npeers=0, num_candidates=0, syncsource_found=0;
  451. int run=0, min_peer_sel=PEER_INCLUDED, num_selected=0, num_valid=0;
  452. int peer_offset=0;
  453. ntp_assoc_status_pair *peers=NULL;
  454. ntp_control_message req;
  455. double rval = 0.0, jitter = -1.0;
  456. char *startofvalue=NULL, *nptr=NULL;
  457. void *tmp;
  458. /* Long-winded explanation:
  459. * Getting the jitter requires a number of steps:
  460. * 1) Send a READSTAT request.
  461. * 2) Interpret the READSTAT reply
  462. * a) The data section contains a list of peer identifiers (16 bits)
  463. * and associated status words (16 bits)
  464. * b) We want the value of 0x06 in the SEL (peer selection) value,
  465. * which means "current synchronizatin source". If that's missing,
  466. * we take anything better than 0x04 (see the rfc for details) but
  467. * set a minimum of warning.
  468. * 3) Send a READVAR request for information on each peer identified
  469. * in 2b greater than the minimum selection value.
  470. * 4) Extract the jitter value from the data[] (it's ASCII)
  471. */
  472. my_udp_connect(server_address, 123, &conn);
  473. /* keep sending requests until the server stops setting the
  474. * REM_MORE bit, though usually this is only 1 packet. */
  475. do{
  476. setup_control_request(&req, OP_READSTAT, 1);
  477. DBG(printf("sending READSTAT request"));
  478. write(conn, &req, SIZEOF_NTPCM(req));
  479. DBG(print_ntp_control_message(&req));
  480. /* Attempt to read the largest size packet possible */
  481. req.count=htons(MAX_CM_SIZE);
  482. DBG(printf("recieving READSTAT response"))
  483. read(conn, &req, SIZEOF_NTPCM(req));
  484. DBG(print_ntp_control_message(&req));
  485. /* Each peer identifier is 4 bytes in the data section, which
  486. * we represent as a ntp_assoc_status_pair datatype.
  487. */
  488. npeers+=(ntohs(req.count)/sizeof(ntp_assoc_status_pair));
  489. if((tmp=realloc(peers, sizeof(ntp_assoc_status_pair)*npeers)) == NULL)
  490. free(peers), die(STATE_UNKNOWN, "can not (re)allocate 'peers' buffer\n");
  491. peers=tmp;
  492. memcpy((void*)((ptrdiff_t)peers+peer_offset), (void*)req.data, ntohs(req.count));
  493. peer_offset+=ntohs(req.count);
  494. } while(req.op&REM_MORE);
  495. /* first, let's find out if we have a sync source, or if there are
  496. * at least some candidates. in the case of the latter we'll issue
  497. * a warning but go ahead with the check on them. */
  498. for (i = 0; i < npeers; i++){
  499. if (PEER_SEL(peers[i].status) >= PEER_INCLUDED){
  500. num_candidates++;
  501. if(PEER_SEL(peers[i].status) >= PEER_SYNCSOURCE){
  502. syncsource_found=1;
  503. min_peer_sel=PEER_SYNCSOURCE;
  504. }
  505. }
  506. }
  507. if(verbose) printf("%d candiate peers available\n", num_candidates);
  508. if(verbose && syncsource_found) printf("synchronization source found\n");
  509. if(! syncsource_found){
  510. *status = STATE_WARNING;
  511. if(verbose) printf("warning: no synchronization source found\n");
  512. }
  513. for (run=0; run<AVG_NUM; run++){
  514. if(verbose) printf("jitter run %d of %d\n", run+1, AVG_NUM);
  515. for (i = 0; i < npeers; i++){
  516. /* Only query this server if it is the current sync source */
  517. if (PEER_SEL(peers[i].status) >= min_peer_sel){
  518. num_selected++;
  519. setup_control_request(&req, OP_READVAR, 2);
  520. req.assoc = peers[i].assoc;
  521. /* By spec, putting the variable name "jitter" in the request
  522. * should cause the server to provide _only_ the jitter value.
  523. * thus reducing net traffic, guaranteeing us only a single
  524. * datagram in reply, and making intepretation much simpler
  525. */
  526. strncpy(req.data, "jitter", 6);
  527. req.count = htons(6);
  528. DBG(printf("sending READVAR request...\n"));
  529. write(conn, &req, SIZEOF_NTPCM(req));
  530. DBG(print_ntp_control_message(&req));
  531. req.count = htons(MAX_CM_SIZE);
  532. DBG(printf("recieving READVAR response...\n"));
  533. read(conn, &req, SIZEOF_NTPCM(req));
  534. DBG(print_ntp_control_message(&req));
  535. /* get to the float value */
  536. if(verbose) {
  537. printf("parsing jitter from peer %.2x: ", peers[i].assoc);
  538. }
  539. startofvalue = strchr(req.data, '=') + 1;
  540. if(startofvalue != NULL) {
  541. jitter = strtod(startofvalue, &nptr);
  542. }
  543. if(startofvalue == NULL || startofvalue==nptr){
  544. printf("warning: unable to read server jitter response.\n");
  545. *status = STATE_WARNING;
  546. } else {
  547. if(verbose) printf("%g\n", jitter);
  548. num_valid++;
  549. rval += jitter;
  550. }
  551. }
  552. }
  553. if(verbose){
  554. printf("jitter parsed from %d/%d peers\n", num_valid, num_selected);
  555. }
  556. }
  557. rval = num_valid ? rval / num_valid : -1.0;
  558. close(conn);
  559. free(peers);
  560. /* If we return -1.0, it means no synchronization source was found */
  561. return rval;
  562. }
  563. int process_arguments(int argc, char **argv){
  564. int c;
  565. int option=0;
  566. static struct option longopts[] = {
  567. {"version", no_argument, 0, 'V'},
  568. {"help", no_argument, 0, 'h'},
  569. {"verbose", no_argument, 0, 'v'},
  570. {"use-ipv4", no_argument, 0, '4'},
  571. {"use-ipv6", no_argument, 0, '6'},
  572. {"warning", required_argument, 0, 'w'},
  573. {"critical", required_argument, 0, 'c'},
  574. {"jwarn", required_argument, 0, 'j'},
  575. {"jcrit", required_argument, 0, 'k'},
  576. {"timeout", required_argument, 0, 't'},
  577. {"hostname", required_argument, 0, 'H'},
  578. {0, 0, 0, 0}
  579. };
  580. if (argc < 2)
  581. usage ("\n");
  582. while (1) {
  583. c = getopt_long (argc, argv, "Vhv46w:c:j:k:t:H:", longopts, &option);
  584. if (c == -1 || c == EOF || c == 1)
  585. break;
  586. switch (c) {
  587. case 'h':
  588. print_help();
  589. exit(STATE_OK);
  590. break;
  591. case 'V':
  592. print_revision(progname, revision);
  593. exit(STATE_OK);
  594. break;
  595. case 'v':
  596. verbose++;
  597. break;
  598. case 'w':
  599. owarn = atof(optarg);
  600. break;
  601. case 'c':
  602. ocrit = atof(optarg);
  603. break;
  604. case 'j':
  605. do_jitter=1;
  606. jwarn = atof(optarg);
  607. break;
  608. case 'k':
  609. do_jitter=1;
  610. jcrit = atof(optarg);
  611. break;
  612. case 'H':
  613. if(is_host(optarg) == FALSE)
  614. usage2(_("Invalid hostname/address"), optarg);
  615. server_address = strdup(optarg);
  616. break;
  617. case 't':
  618. socket_timeout=atoi(optarg);
  619. break;
  620. case '4':
  621. address_family = AF_INET;
  622. break;
  623. case '6':
  624. #ifdef USE_IPV6
  625. address_family = AF_INET6;
  626. #else
  627. usage4 (_("IPv6 support not available"));
  628. #endif
  629. break;
  630. case '?':
  631. /* print short usage statement if args not parsable */
  632. usage5 ();
  633. break;
  634. }
  635. }
  636. if (ocrit < owarn){
  637. usage4(_("Critical offset should be larger than warning offset"));
  638. }
  639. if (ocrit < owarn){
  640. usage4(_("Critical jitter should be larger than warning jitter"));
  641. }
  642. if(server_address == NULL){
  643. usage4(_("Hostname was not supplied"));
  644. }
  645. return 0;
  646. }
  647. int main(int argc, char *argv[]){
  648. int result, offset_result, jitter_result;
  649. double offset=0, jitter=0;
  650. result=offset_result=jitter_result=STATE_UNKNOWN;
  651. if (process_arguments (argc, argv) == ERROR)
  652. usage4 (_("Could not parse arguments"));
  653. /* initialize alarm signal handling */
  654. signal (SIGALRM, socket_timeout_alarm_handler);
  655. /* set socket timeout */
  656. alarm (socket_timeout);
  657. offset = offset_request(server_address, &offset_result);
  658. if(fabs(offset) > ocrit){
  659. result = STATE_CRITICAL;
  660. } else if(fabs(offset) > owarn) {
  661. result = STATE_WARNING;
  662. } else {
  663. result = STATE_OK;
  664. }
  665. result=max_state(result, offset_result);
  666. /* If not told to check the jitter, we don't even send packets.
  667. * jitter is checked using NTP control packets, which not all
  668. * servers recognize. Trying to check the jitter on OpenNTPD
  669. * (for example) will result in an error
  670. */
  671. if(do_jitter){
  672. jitter=jitter_request(server_address, &jitter_result);
  673. if(jitter > jcrit){
  674. result = max_state(result, STATE_CRITICAL);
  675. } else if(jitter > jwarn) {
  676. result = max_state(result, STATE_WARNING);
  677. } else if(jitter == -1.0 && result == STATE_OK){
  678. /* -1 indicates that we couldn't calculate the jitter
  679. * Only overrides STATE_OK from the offset */
  680. result = STATE_UNKNOWN;
  681. }
  682. }
  683. result=max_state(result, jitter_result);
  684. switch (result) {
  685. case STATE_CRITICAL :
  686. printf("NTP CRITICAL: ");
  687. break;
  688. case STATE_WARNING :
  689. printf("NTP WARNING: ");
  690. break;
  691. case STATE_OK :
  692. printf("NTP OK: ");
  693. break;
  694. default :
  695. printf("NTP UNKNOWN: ");
  696. break;
  697. }
  698. if(offset_result==STATE_CRITICAL){
  699. printf("Offset unknown|offset=unknown");
  700. } else {
  701. if(offset_result==STATE_WARNING){
  702. printf("Unable to fully sample sync server. ");
  703. }
  704. printf("Offset %.10g secs|offset=%.10g", offset, offset);
  705. }
  706. if (do_jitter) printf(" jitter=%f", jitter);
  707. printf("\n");
  708. if(server_address!=NULL) free(server_address);
  709. return result;
  710. }
  711. void print_help(void){
  712. print_revision(progname, revision);
  713. printf ("Copyright (c) 2006 Sean Finney\n");
  714. printf (COPYRIGHT, copyright, email);
  715. printf ("%s\n", _("This plugin checks the selected ntp server"));
  716. printf ("\n\n");
  717. print_usage();
  718. printf (_(UT_HELP_VRSN));
  719. printf (_(UT_HOST_PORT), 'p', "123");
  720. printf (_(UT_WARN_CRIT));
  721. printf (" %s\n", "-j, --warning=DOUBLE");
  722. printf (" %s\n", _("warning value for jitter"));
  723. printf (" %s\n", "-k, --critical=DOUBLE");
  724. printf (" %s\n", _("critical value for jitter"));
  725. printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
  726. printf (_(UT_VERBOSE));
  727. printf (_(UT_SUPPORT));
  728. }
  729. void
  730. print_usage(void)
  731. {
  732. printf (_("Usage:"));
  733. printf("%s -H <host> [-w <warn>] [-c <crit>] [-j <warn>] [-k <crit>] [-v verbose]\n", progname);
  734. }