check_ntp.c 30 KB

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