4
0

check_ntp.c 32 KB

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