4
0

check_ntp.c 30 KB

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