check_ntp.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. /******************************************************************************
  2. check_ntp.c: utility to check ntp servers independant of any commandline
  3. programs or external libraries.
  4. original author: sean finney <seanius@seanius.net>
  5. ******************************************************************************
  6. This program is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2 of the License, or
  9. (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with this program; if not, write to the Free Software
  16. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17. $Id$
  18. *****************************************************************************/
  19. const char *progname = "check_ntp";
  20. const char *revision = "$Revision$";
  21. const char *copyright = "2006";
  22. const char *email = "nagiosplug-devel@lists.sourceforge.net";
  23. #include "common.h"
  24. #include "netutils.h"
  25. #include "utils.h"
  26. static char *server_address=NULL;
  27. static int verbose=0;
  28. static int zero_offset_bad=0;
  29. static double owarn=0;
  30. static double ocrit=0;
  31. static short do_jitter=0;
  32. static double jwarn=0;
  33. static double jcrit=0;
  34. int process_arguments (int, char **);
  35. void print_help (void);
  36. void print_usage (void);
  37. /* this structure holds everything in an ntp request/response as per rfc1305 */
  38. typedef struct {
  39. uint8_t flags; /* byte with leapindicator,vers,mode. see macros */
  40. uint8_t stratum; /* clock stratum */
  41. int8_t poll; /* polling interval */
  42. int8_t precision; /* precision of the local clock */
  43. int32_t rtdelay; /* total rt delay, as a fixed point num. see macros */
  44. uint32_t rtdisp; /* like above, but for max err to primary src */
  45. uint32_t refid; /* ref clock identifier */
  46. uint64_t refts; /* reference timestamp. local time local clock */
  47. uint64_t origts; /* time at which request departed client */
  48. uint64_t rxts; /* time at which request arrived at server */
  49. uint64_t txts; /* time at which request departed server */
  50. } ntp_message;
  51. /* bits 1,2 are the leap indicator */
  52. #define LI_MASK 0xc0
  53. #define LI(x) ((x&LI_MASK)>>6)
  54. #define LI_SET(x,y) do{ x |= ((y<<6)&LI_MASK); }while(0)
  55. /* and these are the values of the leap indicator */
  56. #define LI_NOWARNING 0x00
  57. #define LI_EXTRASEC 0x01
  58. #define LI_MISSINGSEC 0x02
  59. #define LI_ALARM 0x03
  60. /* bits 3,4,5 are the ntp version */
  61. #define VN_MASK 0x38
  62. #define VN(x) ((x&VN_MASK)>>3)
  63. #define VN_SET(x,y) do{ x |= ((y<<3)&VN_MASK); }while(0)
  64. /* bits 6,7,8 are the ntp mode */
  65. #define MODE_MASK 0x07
  66. #define MODE(x) (x&MODE_MASK)
  67. #define MODE_SET(x,y) do{ x |= (y&MODE_MASK); }while(0)
  68. /* here are some values */
  69. #define MODE_CLIENT 0x03
  70. /**
  71. ** a note about the 32-bit "fixed point" numbers:
  72. **
  73. they are divided into halves, each being a 16-bit int in network byte order:
  74. - the first 16 bits are an int on the left side of a decimal point.
  75. - the second 16 bits represent a fraction n/(2^16)
  76. likewise for the 64-bit "fixed point" numbers with everything doubled :)
  77. **/
  78. /* macros to access the left/right 16 bits of a 32-bit ntp "fixed point"
  79. number. note that these can be used as lvalues too */
  80. #define L16(x) (((uint16_t*)&x)[0])
  81. #define R16(x) (((uint16_t*)&x)[1])
  82. /* macros to access the left/right 32 bits of a 64-bit ntp "fixed point"
  83. number. these too can be used as lvalues */
  84. #define L32(x) (((uint32_t*)&x)[0])
  85. #define R32(x) (((uint32_t*)&x)[1])
  86. /* ntp wants seconds since 1/1/00, epoch is 1/1/70. this is the difference */
  87. #define EPOCHDIFF 0x83aa7e80UL
  88. /* extract a 32-bit ntp fixed point number into a double */
  89. #define NTP32asDOUBLE(x) (ntohs(L16(x)) + (double)ntohs(R16(x))/65536.0)
  90. /* likewise for a 64-bit ntp fp number */
  91. #define NTP64asDOUBLE(n) (double)(((uint64_t)n)?\
  92. (ntohl(L32(n))-EPOCHDIFF) + \
  93. (.00000001*(0.5+(double)(ntohl(R32(n))/42.94967296))):\
  94. 0)
  95. /* convert a struct timeval to a double */
  96. #define TVasDOUBLE(x) (double)(x.tv_sec+(0.000001*x.tv_usec))
  97. /* convert an ntp 64-bit fp number to a struct timeval */
  98. #define NTP64toTV(n,t) \
  99. do{ if(!n) t.tv_sec = t.tv_usec = 0; \
  100. else { \
  101. t.tv_sec=ntohl(L32(n))-EPOCHDIFF; \
  102. t.tv_usec=(int)(0.5+(double)(ntohl(R32(n))/4294.967296)); \
  103. } \
  104. }while(0)
  105. /* convert a struct timeval to an ntp 64-bit fp number */
  106. #define TVtoNTP64(t,n) \
  107. do{ if(!t.tv_usec && !t.tv_sec) n=0x0UL; \
  108. else { \
  109. L32(n)=htonl(t.tv_sec + EPOCHDIFF); \
  110. R32(n)=htonl((4294.967296*t.tv_usec)+.5); \
  111. } \
  112. } while(0)
  113. /* calculate the offset of the local clock */
  114. static inline double calc_offset(const ntp_message *m, const struct timeval *t){
  115. double client_tx, peer_rx, peer_tx, client_rx, rtdelay;
  116. client_tx = NTP64asDOUBLE(m->origts);
  117. peer_rx = NTP64asDOUBLE(m->rxts);
  118. peer_tx = NTP64asDOUBLE(m->txts);
  119. client_rx=TVasDOUBLE((*t));
  120. rtdelay=NTP32asDOUBLE(m->rtdelay);
  121. return (.5*((peer_tx-client_rx)+(peer_rx-client_tx)))-rtdelay;
  122. }
  123. /* print out a ntp packet in human readable/debuggable format */
  124. void print_packet(const ntp_message *p){
  125. struct timeval ref, orig, rx, tx;
  126. NTP64toTV(p->refts,ref);
  127. NTP64toTV(p->origts,orig);
  128. NTP64toTV(p->rxts,rx);
  129. NTP64toTV(p->txts,tx);
  130. printf("packet contents:\n");
  131. printf("\tflags: 0x%.2x\n", p->flags);
  132. printf("\t li=%d (0x%.2x)\n", LI(p->flags), p->flags&LI_MASK);
  133. printf("\t vn=%d (0x%.2x)\n", VN(p->flags), p->flags&VN_MASK);
  134. printf("\t mode=%d (0x%.2x)\n", MODE(p->flags), p->flags&MODE_MASK);
  135. printf("\tstratum = %d\n", p->stratum);
  136. printf("\tpoll = %g\n", pow(2, p->poll));
  137. printf("\tprecision = %g\n", pow(2, p->precision));
  138. printf("\trtdelay = %-.16g\n", NTP32asDOUBLE(p->rtdelay));
  139. printf("\trtdisp = %-.16g\n", NTP32asDOUBLE(p->rtdisp));
  140. printf("\trefid = %x\n", p->refid);
  141. printf("\trefts = %-.16g\n", NTP64asDOUBLE(p->refts));
  142. printf("\torigts = %-.16g\n", NTP64asDOUBLE(p->origts));
  143. printf("\trxts = %-.16g\n", NTP64asDOUBLE(p->rxts));
  144. printf("\ttxts = %-.16g\n", NTP64asDOUBLE(p->txts));
  145. }
  146. void setup_request(ntp_message *p){
  147. struct timeval t;
  148. memset(p, 0, sizeof(ntp_message));
  149. LI_SET(p->flags, LI_ALARM);
  150. VN_SET(p->flags, 4);
  151. MODE_SET(p->flags, MODE_CLIENT);
  152. p->poll=4;
  153. p->precision=0xfa;
  154. L16(p->rtdelay)=htons(1);
  155. L16(p->rtdisp)=htons(1);
  156. gettimeofday(&t, NULL);
  157. TVtoNTP64(t,p->txts);
  158. }
  159. double offset_request(const char *host){
  160. int i=0, conn=-1;
  161. ntp_message req;
  162. double next_offset=0., avg_offset=0.;
  163. struct timeval recv_time;
  164. for(i=0; i<4; i++){
  165. setup_request(&req);
  166. my_udp_connect(server_address, 123, &conn);
  167. write(conn, &req, sizeof(ntp_message));
  168. read(conn, &req, sizeof(ntp_message));
  169. gettimeofday(&recv_time, NULL);
  170. /* if(verbose) print_packet(&req); */
  171. close(conn);
  172. next_offset=calc_offset(&req, &recv_time);
  173. if(verbose) printf("offset: %g\n", next_offset);
  174. avg_offset+=next_offset;
  175. }
  176. return avg_offset/4.;
  177. }
  178. /* not yet implemented yet */
  179. double jitter_request(const char *host){
  180. return 0.;
  181. }
  182. int process_arguments(int argc, char **argv){
  183. int c;
  184. int option=0;
  185. static struct option longopts[] = {
  186. {"version", no_argument, 0, 'V'},
  187. {"help", no_argument, 0, 'h'},
  188. {"verbose", no_argument, 0, 'v'},
  189. {"use-ipv4", no_argument, 0, '4'},
  190. {"use-ipv6", no_argument, 0, '6'},
  191. {"warning", required_argument, 0, 'w'},
  192. {"critical", required_argument, 0, 'c'},
  193. {"zero-offset", no_argument, 0, 'O'},
  194. {"jwarn", required_argument, 0, 'j'},
  195. {"jcrit", required_argument, 0, 'k'},
  196. {"timeout", required_argument, 0, 't'},
  197. {"hostname", required_argument, 0, 'H'},
  198. {0, 0, 0, 0}
  199. };
  200. if (argc < 2)
  201. usage ("\n");
  202. while (1) {
  203. c = getopt_long (argc, argv, "Vhv46w:c:Oj:k:t:H:", longopts, &option);
  204. if (c == -1 || c == EOF || c == 1)
  205. break;
  206. switch (c) {
  207. case 'h':
  208. print_help();
  209. exit(STATE_OK);
  210. break;
  211. case 'V':
  212. print_revision(progname, revision);
  213. exit(STATE_OK);
  214. break;
  215. case 'v':
  216. verbose = 1;
  217. break;
  218. case 'w':
  219. owarn = atof(optarg);
  220. break;
  221. case 'c':
  222. ocrit = atof(optarg);
  223. break;
  224. case 'j':
  225. do_jitter=1;
  226. jwarn = atof(optarg);
  227. break;
  228. case 'k':
  229. do_jitter=1;
  230. jcrit = atof(optarg);
  231. break;
  232. case 'H':
  233. if(is_host(optarg) == FALSE)
  234. usage2(_("Invalid hostname/address"), optarg);
  235. server_address = strdup(optarg);
  236. break;
  237. case 't':
  238. socket_timeout=atoi(optarg);
  239. break;
  240. case 'O':
  241. zero_offset_bad=1;
  242. break;
  243. case '4':
  244. address_family = AF_INET;
  245. break;
  246. case '6':
  247. #ifdef USE_IPV6
  248. address_family = AF_INET6;
  249. #else
  250. usage4 (_("IPv6 support not available"));
  251. #endif
  252. break;
  253. case '?':
  254. /* print short usage statement if args not parsable */
  255. usage2 (_("Unknown argument"), optarg);
  256. break;
  257. }
  258. }
  259. if (ocrit < owarn){
  260. usage4(_("Critical offset should be larger than warning offset"));
  261. }
  262. if (ocrit < owarn){
  263. usage4(_("Critical jitter should be larger than warning jitter"));
  264. }
  265. if(server_address == NULL){
  266. usage4(_("Hostname was not supplied"));
  267. }
  268. return 0;
  269. }
  270. int main(int argc, char *argv[]){
  271. int result = STATE_UNKNOWN;
  272. double offset=0, jitter=0;
  273. if (process_arguments (argc, argv) == ERROR)
  274. usage4 (_("Could not parse arguments"));
  275. /* initialize alarm signal handling */
  276. signal (SIGALRM, socket_timeout_alarm_handler);
  277. /* set socket timeout */
  278. alarm (socket_timeout);
  279. offset = offset_request(server_address);
  280. if(offset > ocrit){
  281. printf("NTP CRITICAL: ");
  282. result = STATE_CRITICAL;
  283. } else if(offset > owarn) {
  284. printf("NTP WARNING: ");
  285. result = STATE_WARNING;
  286. } else {
  287. printf("NTP OK: ");
  288. result = STATE_OK;
  289. }
  290. /* not implemented yet: */
  291. jitter=jitter_request(server_address);
  292. /* not implemented yet:
  293. if(do_jitter){
  294. if(jitter > jcrit){
  295. printf("NTP CRITICAL: ");
  296. result = STATE_CRITICAL;
  297. } else if(jitter > jwarn) {
  298. printf("NTP WARNING: ");
  299. result = STATE_WARNING;
  300. } else {
  301. printf("NTP OK: ");
  302. result = STATE_OK;
  303. }
  304. }
  305. */
  306. printf("Offset %g secs|offset=%g\n", offset, offset);
  307. if(server_address!=NULL) free(server_address);
  308. return result;
  309. }
  310. void print_usage(void){
  311. printf("\
  312. Usage: %s -H <host> [-O] [-w <warn>] [-c <crit>] [-j <warn>] [-k <crit>] [-v verbose]\
  313. \n", progname);
  314. }
  315. void print_help(void){
  316. print_revision(progname, revision);
  317. printf ("Copyright (c) 1999 Ethan Galstad\n");
  318. printf (COPYRIGHT, copyright, email);
  319. print_usage();
  320. printf (_(UT_HELP_VRSN));
  321. printf (_(UT_HOST_PORT), 'p', "123");
  322. printf (_(UT_WARN_CRIT));
  323. printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
  324. printf (_(UT_VERBOSE));
  325. printf(_(UT_SUPPORT));
  326. }