check_ntp.c 29 KB

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