check_ntp.c 26 KB

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