check_ntp.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. int process_arguments(int argc, char **argv){
  160. int c;
  161. int option=0;
  162. static struct option longopts[] = {
  163. {"version", no_argument, 0, 'V'},
  164. {"help", no_argument, 0, 'h'},
  165. {"verbose", no_argument, 0, 'v'},
  166. {"use-ipv4", no_argument, 0, '4'},
  167. {"use-ipv6", no_argument, 0, '6'},
  168. {"warning", required_argument, 0, 'w'},
  169. {"critical", required_argument, 0, 'c'},
  170. {"zero-offset", no_argument, 0, 'O'},
  171. {"jwarn", required_argument, 0, 'j'},
  172. {"jcrit", required_argument, 0, 'k'},
  173. {"timeout", required_argument, 0, 't'},
  174. {"hostname", required_argument, 0, 'H'},
  175. {0, 0, 0, 0}
  176. };
  177. if (argc < 2)
  178. usage ("\n");
  179. while (1) {
  180. c = getopt_long (argc, argv, "Vhv46w:c:Oj:k:t:H:", longopts, &option);
  181. if (c == -1 || c == EOF || c == 1)
  182. break;
  183. switch (c) {
  184. case 'h':
  185. print_help();
  186. exit(STATE_OK);
  187. break;
  188. case 'V':
  189. print_revision(progname, revision);
  190. exit(STATE_OK);
  191. break;
  192. case 'v':
  193. verbose = 1;
  194. break;
  195. case 'w':
  196. owarn = atof(optarg);
  197. break;
  198. case 'c':
  199. ocrit = atof(optarg);
  200. break;
  201. case 'j':
  202. do_jitter=1;
  203. jwarn = atof(optarg);
  204. break;
  205. case 'k':
  206. do_jitter=1;
  207. jcrit = atof(optarg);
  208. break;
  209. case 'H':
  210. if(is_host(optarg) == FALSE)
  211. usage2(_("Invalid hostname/address"), optarg);
  212. server_address = strdup(optarg);
  213. break;
  214. case 't':
  215. socket_timeout=atoi(optarg);
  216. break;
  217. case 'O':
  218. zero_offset_bad=1;
  219. break;
  220. case '4':
  221. address_family = AF_INET;
  222. break;
  223. case '6':
  224. #ifdef USE_IPV6
  225. address_family = AF_INET6;
  226. #else
  227. usage4 (_("IPv6 support not available"));
  228. #endif
  229. break;
  230. case '?':
  231. /* print short usage statement if args not parsable */
  232. usage2 (_("Unknown argument"), optarg);
  233. break;
  234. }
  235. }
  236. if (ocrit < owarn){
  237. usage4(_("Critical offset should be larger than warning offset"));
  238. }
  239. if (ocrit < owarn){
  240. usage4(_("Critical jitter should be larger than warning jitter"));
  241. }
  242. if(server_address == NULL){
  243. usage4(_("Hostname was not supplied"));
  244. }
  245. return 0;
  246. }
  247. int main(int argc, char *argv[]){
  248. int result = STATE_UNKNOWN;
  249. int conn;
  250. ntp_message m;
  251. struct timeval recv_time;
  252. double offset=0, jitter=0;
  253. if (process_arguments (argc, argv) == ERROR)
  254. usage4 (_("Could not parse arguments"));
  255. /* initialize alarm signal handling */
  256. signal (SIGALRM, socket_timeout_alarm_handler);
  257. /* set socket timeout */
  258. alarm (socket_timeout);
  259. setup_request(&m);
  260. if(verbose) print_packet(&m);
  261. my_udp_connect(server_address, 123, &conn);
  262. write(conn, &m, sizeof(ntp_message));
  263. read(conn, &m, sizeof(ntp_message));
  264. gettimeofday(&recv_time, NULL);
  265. if(verbose) print_packet(&m);
  266. close(conn);
  267. offset=calc_offset(&m, &recv_time);
  268. printf("total offset: %g\n", offset);
  269. if(offset > ocrit){
  270. printf("NTP CRITICAL: ");
  271. result = STATE_CRITICAL;
  272. } else if(offset > owarn) {
  273. printf("NTP WARNING: ");
  274. result = STATE_WARNING;
  275. } else {
  276. printf("NTP OK: ");
  277. result = STATE_OK;
  278. }
  279. /* not implemented yet:
  280. jitter=calc_jitter(&m, &recv_time);
  281. if(do_jitter){
  282. if(offset > ocrit){
  283. printf("NTP CRITICAL: ");
  284. result = STATE_CRITICAL;
  285. } else if(offset > owarn) {
  286. printf("NTP WARNING: ");
  287. result = STATE_WARNING;
  288. } else {
  289. printf("NTP OK: ");
  290. result = STATE_OK;
  291. }
  292. }
  293. */
  294. printf("Offset %g secs|offset=%g\n", offset, offset);
  295. if(server_address!=NULL) free(server_address);
  296. return result;
  297. }
  298. void print_usage(void){
  299. printf("\
  300. Usage: %s -H <host> [-O] [-w <warn>] [-c <crit>] [-j <warn>] [-k <crit>] [-v verbose]\
  301. \n", progname);
  302. }
  303. void print_help(void){
  304. print_revision(progname, revision);
  305. printf ("Copyright (c) 1999 Ethan Galstad\n");
  306. printf (COPYRIGHT, copyright, email);
  307. print_usage();
  308. printf (_(UT_HELP_VRSN));
  309. printf (_(UT_HOST_PORT), 'p', "123");
  310. printf (_(UT_WARN_CRIT));
  311. printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
  312. printf (_(UT_VERBOSE));
  313. printf(_(UT_SUPPORT));
  314. }