ntpd_simple.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  1. /*
  2. * NTP client/server, based on OpenNTPD 3.9p1
  3. *
  4. * Author: Adam Tkac <vonsch@gmail.com>
  5. *
  6. * Licensed under GPLv2, see file LICENSE in this source tree.
  7. */
  8. #include "libbb.h"
  9. #include <netinet/ip.h> /* For IPTOS_LOWDELAY definition */
  10. #include <sys/resource.h> /* setpriority */
  11. #ifndef IPTOS_LOWDELAY
  12. # define IPTOS_LOWDELAY 0x10
  13. #endif
  14. #ifndef IP_PKTINFO
  15. # error "Sorry, your kernel has to support IP_PKTINFO"
  16. #endif
  17. /* Sync to peers every N secs */
  18. #define INTERVAL_QUERY_NORMAL 30
  19. #define INTERVAL_QUERY_PATHETIC 60
  20. #define INTERVAL_QUERY_AGRESSIVE 5
  21. /* Bad if *less than* TRUSTLEVEL_BADPEER */
  22. #define TRUSTLEVEL_BADPEER 6
  23. #define TRUSTLEVEL_PATHETIC 2
  24. #define TRUSTLEVEL_AGRESSIVE 8
  25. #define TRUSTLEVEL_MAX 10
  26. #define QSCALE_OFF_MIN 0.05
  27. #define QSCALE_OFF_MAX 0.50
  28. /* Single query might take N secs max */
  29. #define QUERYTIME_MAX 15
  30. /* Min offset for settime at start. "man ntpd" says it's 128 ms */
  31. #define STEPTIME_MIN_OFFSET 0.128
  32. typedef struct {
  33. uint32_t int_partl;
  34. uint32_t fractionl;
  35. } l_fixedpt_t;
  36. typedef struct {
  37. uint16_t int_parts;
  38. uint16_t fractions;
  39. } s_fixedpt_t;
  40. enum {
  41. NTP_DIGESTSIZE = 16,
  42. NTP_MSGSIZE_NOAUTH = 48,
  43. NTP_MSGSIZE = (NTP_MSGSIZE_NOAUTH + 4 + NTP_DIGESTSIZE),
  44. };
  45. typedef struct {
  46. uint8_t m_status; /* status of local clock and leap info */
  47. uint8_t m_stratum; /* stratum level */
  48. uint8_t m_ppoll; /* poll value */
  49. int8_t m_precision_exp;
  50. s_fixedpt_t m_rootdelay;
  51. s_fixedpt_t m_dispersion;
  52. uint32_t m_refid;
  53. l_fixedpt_t m_reftime;
  54. l_fixedpt_t m_orgtime;
  55. l_fixedpt_t m_rectime;
  56. l_fixedpt_t m_xmttime;
  57. uint32_t m_keyid;
  58. uint8_t m_digest[NTP_DIGESTSIZE];
  59. } msg_t;
  60. enum {
  61. NTP_VERSION = 4,
  62. NTP_MAXSTRATUM = 15,
  63. /* Status Masks */
  64. MODE_MASK = (7 << 0),
  65. VERSION_MASK = (7 << 3),
  66. VERSION_SHIFT = 3,
  67. LI_MASK = (3 << 6),
  68. /* Leap Second Codes (high order two bits of m_status) */
  69. LI_NOWARNING = (0 << 6), /* no warning */
  70. LI_PLUSSEC = (1 << 6), /* add a second (61 seconds) */
  71. LI_MINUSSEC = (2 << 6), /* minus a second (59 seconds) */
  72. LI_ALARM = (3 << 6), /* alarm condition */
  73. /* Mode values */
  74. MODE_RES0 = 0, /* reserved */
  75. MODE_SYM_ACT = 1, /* symmetric active */
  76. MODE_SYM_PAS = 2, /* symmetric passive */
  77. MODE_CLIENT = 3, /* client */
  78. MODE_SERVER = 4, /* server */
  79. MODE_BROADCAST = 5, /* broadcast */
  80. MODE_RES1 = 6, /* reserved for NTP control message */
  81. MODE_RES2 = 7, /* reserved for private use */
  82. };
  83. #define OFFSET_1900_1970 2208988800UL /* 1970 - 1900 in seconds */
  84. typedef struct {
  85. double d_offset;
  86. double d_delay;
  87. //UNUSED: double d_error;
  88. time_t d_rcv_time;
  89. uint32_t d_refid4;
  90. uint8_t d_leap;
  91. uint8_t d_stratum;
  92. uint8_t d_good;
  93. } datapoint_t;
  94. #define NUM_DATAPOINTS 8
  95. typedef struct {
  96. len_and_sockaddr *p_lsa;
  97. char *p_dotted;
  98. /* When to send new query (if p_fd == -1)
  99. * or when receive times out (if p_fd >= 0): */
  100. time_t next_action_time;
  101. int p_fd;
  102. uint8_t p_datapoint_idx;
  103. uint8_t p_trustlevel;
  104. double p_xmttime;
  105. datapoint_t update;
  106. datapoint_t p_datapoint[NUM_DATAPOINTS];
  107. msg_t p_xmt_msg;
  108. } peer_t;
  109. enum {
  110. OPT_n = (1 << 0),
  111. OPT_q = (1 << 1),
  112. OPT_N = (1 << 2),
  113. OPT_x = (1 << 3),
  114. /* Insert new options above this line. */
  115. /* Non-compat options: */
  116. OPT_p = (1 << 4),
  117. OPT_l = (1 << 5) * ENABLE_FEATURE_NTPD_SERVER,
  118. };
  119. struct globals {
  120. /* total round trip delay to currently selected reference clock */
  121. double rootdelay;
  122. /* reference timestamp: time when the system clock was last set or corrected */
  123. double reftime;
  124. llist_t *ntp_peers;
  125. #if ENABLE_FEATURE_NTPD_SERVER
  126. int listen_fd;
  127. #endif
  128. unsigned verbose;
  129. unsigned peer_cnt;
  130. unsigned scale;
  131. uint32_t refid;
  132. uint32_t refid4;
  133. uint8_t synced;
  134. uint8_t leap;
  135. #define G_precision_exp -6
  136. // int8_t precision_exp;
  137. uint8_t stratum;
  138. uint8_t time_was_stepped;
  139. uint8_t first_adj_done;
  140. };
  141. #define G (*ptr_to_globals)
  142. static const int const_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
  143. static void
  144. set_next(peer_t *p, unsigned t)
  145. {
  146. p->next_action_time = time(NULL) + t;
  147. }
  148. static void
  149. add_peers(char *s)
  150. {
  151. peer_t *p;
  152. p = xzalloc(sizeof(*p));
  153. p->p_lsa = xhost2sockaddr(s, 123);
  154. p->p_dotted = xmalloc_sockaddr2dotted_noport(&p->p_lsa->u.sa);
  155. p->p_fd = -1;
  156. p->p_xmt_msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
  157. p->p_trustlevel = TRUSTLEVEL_PATHETIC;
  158. p->next_action_time = time(NULL); /* = set_next(p, 0); */
  159. llist_add_to(&G.ntp_peers, p);
  160. G.peer_cnt++;
  161. }
  162. static double
  163. gettime1900d(void)
  164. {
  165. struct timeval tv;
  166. gettimeofday(&tv, NULL); /* never fails */
  167. return (tv.tv_sec + 1.0e-6 * tv.tv_usec + OFFSET_1900_1970);
  168. }
  169. static void
  170. d_to_tv(double d, struct timeval *tv)
  171. {
  172. tv->tv_sec = (long)d;
  173. tv->tv_usec = (d - tv->tv_sec) * 1000000;
  174. }
  175. static double
  176. lfp_to_d(l_fixedpt_t lfp)
  177. {
  178. double ret;
  179. lfp.int_partl = ntohl(lfp.int_partl);
  180. lfp.fractionl = ntohl(lfp.fractionl);
  181. ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
  182. return ret;
  183. }
  184. #if 0 //UNUSED
  185. static double
  186. sfp_to_d(s_fixedpt_t sfp)
  187. {
  188. double ret;
  189. sfp.int_parts = ntohs(sfp.int_parts);
  190. sfp.fractions = ntohs(sfp.fractions);
  191. ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
  192. return ret;
  193. }
  194. #endif
  195. #if ENABLE_FEATURE_NTPD_SERVER
  196. static l_fixedpt_t
  197. d_to_lfp(double d)
  198. {
  199. l_fixedpt_t lfp;
  200. lfp.int_partl = (uint32_t)d;
  201. lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
  202. lfp.int_partl = htonl(lfp.int_partl);
  203. lfp.fractionl = htonl(lfp.fractionl);
  204. return lfp;
  205. }
  206. static s_fixedpt_t
  207. d_to_sfp(double d)
  208. {
  209. s_fixedpt_t sfp;
  210. sfp.int_parts = (uint16_t)d;
  211. sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
  212. sfp.int_parts = htons(sfp.int_parts);
  213. sfp.fractions = htons(sfp.fractions);
  214. return sfp;
  215. }
  216. #endif
  217. static unsigned
  218. error_interval(void)
  219. {
  220. unsigned interval, r;
  221. interval = INTERVAL_QUERY_PATHETIC * QSCALE_OFF_MAX / QSCALE_OFF_MIN;
  222. r = (unsigned)random() % (unsigned)(interval / 10);
  223. return (interval + r);
  224. }
  225. static int
  226. do_sendto(int fd,
  227. const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
  228. msg_t *msg, ssize_t len)
  229. {
  230. ssize_t ret;
  231. errno = 0;
  232. if (!from) {
  233. ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
  234. } else {
  235. ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
  236. }
  237. if (ret != len) {
  238. bb_perror_msg("send failed");
  239. return -1;
  240. }
  241. return 0;
  242. }
  243. static int
  244. send_query_to_peer(peer_t *p)
  245. {
  246. // Why do we need to bind()?
  247. // See what happens when we don't bind:
  248. //
  249. // socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
  250. // setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
  251. // gettimeofday({1259071266, 327885}, NULL) = 0
  252. // sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
  253. // ^^^ we sent it from some source port picked by kernel.
  254. // time(NULL) = 1259071266
  255. // write(2, "ntpd: entering poll 15 secs\n", 28) = 28
  256. // poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
  257. // recv(3, "yyy", 68, MSG_DONTWAIT) = 48
  258. // ^^^ this recv will receive packets to any local port!
  259. //
  260. // Uncomment this and use strace to see it in action:
  261. #define PROBE_LOCAL_ADDR // { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); }
  262. if (p->p_fd == -1) {
  263. int fd, family;
  264. len_and_sockaddr *local_lsa;
  265. family = p->p_lsa->u.sa.sa_family;
  266. p->p_fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
  267. /* local_lsa has "null" address and port 0 now.
  268. * bind() ensures we have a *particular port* selected by kernel
  269. * and remembered in p->p_fd, thus later recv(p->p_fd)
  270. * receives only packets sent to this port.
  271. */
  272. PROBE_LOCAL_ADDR
  273. xbind(fd, &local_lsa->u.sa, local_lsa->len);
  274. PROBE_LOCAL_ADDR
  275. #if ENABLE_FEATURE_IPV6
  276. if (family == AF_INET)
  277. #endif
  278. setsockopt(fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
  279. free(local_lsa);
  280. }
  281. /*
  282. * Send out a random 64-bit number as our transmit time. The NTP
  283. * server will copy said number into the originate field on the
  284. * response that it sends us. This is totally legal per the SNTP spec.
  285. *
  286. * The impact of this is two fold: we no longer send out the current
  287. * system time for the world to see (which may aid an attacker), and
  288. * it gives us a (not very secure) way of knowing that we're not
  289. * getting spoofed by an attacker that can't capture our traffic
  290. * but can spoof packets from the NTP server we're communicating with.
  291. *
  292. * Save the real transmit timestamp locally.
  293. */
  294. p->p_xmt_msg.m_xmttime.int_partl = random();
  295. p->p_xmt_msg.m_xmttime.fractionl = random();
  296. p->p_xmttime = gettime1900d();
  297. if (do_sendto(p->p_fd, /*from:*/ NULL, /*to:*/ &p->p_lsa->u.sa, /*addrlen:*/ p->p_lsa->len,
  298. &p->p_xmt_msg, NTP_MSGSIZE_NOAUTH) == -1
  299. ) {
  300. close(p->p_fd);
  301. p->p_fd = -1;
  302. set_next(p, INTERVAL_QUERY_PATHETIC);
  303. return -1;
  304. }
  305. if (G.verbose)
  306. bb_error_msg("sent query to %s", p->p_dotted);
  307. set_next(p, QUERYTIME_MAX);
  308. return 0;
  309. }
  310. /* Time is stepped only once, when the first packet from a peer is received.
  311. */
  312. static void
  313. step_time_once(double offset)
  314. {
  315. double dtime;
  316. llist_t *item;
  317. struct timeval tv;
  318. char buf[80];
  319. time_t tval;
  320. if (G.time_was_stepped)
  321. goto bail;
  322. G.time_was_stepped = 1;
  323. /* if the offset is small, don't step, slew (later) */
  324. if (offset < STEPTIME_MIN_OFFSET && offset > -STEPTIME_MIN_OFFSET)
  325. goto bail;
  326. gettimeofday(&tv, NULL); /* never fails */
  327. dtime = offset + tv.tv_sec;
  328. dtime += 1.0e-6 * tv.tv_usec;
  329. d_to_tv(dtime, &tv);
  330. if (settimeofday(&tv, NULL) == -1)
  331. bb_perror_msg_and_die("settimeofday");
  332. tval = tv.tv_sec;
  333. strftime(buf, sizeof(buf), "%a %b %e %H:%M:%S %Z %Y", localtime(&tval));
  334. bb_error_msg("setting clock to %s (offset %fs)", buf, offset);
  335. for (item = G.ntp_peers; item != NULL; item = item->link) {
  336. peer_t *p = (peer_t *) item->data;
  337. p->next_action_time -= (time_t)offset;
  338. }
  339. bail:
  340. if (option_mask32 & OPT_q)
  341. exit(0);
  342. }
  343. /* Time is periodically slewed when we collect enough
  344. * good data points.
  345. */
  346. static int
  347. compare_offsets(const void *aa, const void *bb)
  348. {
  349. const peer_t *const *a = aa;
  350. const peer_t *const *b = bb;
  351. if ((*a)->update.d_offset < (*b)->update.d_offset)
  352. return -1;
  353. return ((*a)->update.d_offset > (*b)->update.d_offset);
  354. }
  355. static unsigned
  356. updated_scale(double offset)
  357. {
  358. if (offset < 0)
  359. offset = -offset;
  360. if (offset > QSCALE_OFF_MAX)
  361. return 1;
  362. if (offset < QSCALE_OFF_MIN)
  363. return QSCALE_OFF_MAX / QSCALE_OFF_MIN;
  364. return QSCALE_OFF_MAX / offset;
  365. }
  366. static void
  367. slew_time(void)
  368. {
  369. llist_t *item;
  370. double offset_median;
  371. struct timeval tv;
  372. {
  373. peer_t **peers = xzalloc(sizeof(peers[0]) * G.peer_cnt);
  374. unsigned goodpeer_cnt = 0;
  375. unsigned middle;
  376. for (item = G.ntp_peers; item != NULL; item = item->link) {
  377. peer_t *p = (peer_t *) item->data;
  378. if (p->p_trustlevel < TRUSTLEVEL_BADPEER)
  379. continue;
  380. if (!p->update.d_good) {
  381. free(peers);
  382. return;
  383. }
  384. peers[goodpeer_cnt++] = p;
  385. }
  386. if (goodpeer_cnt == 0) {
  387. free(peers);
  388. goto clear_good;
  389. }
  390. qsort(peers, goodpeer_cnt, sizeof(peers[0]), compare_offsets);
  391. middle = goodpeer_cnt / 2;
  392. if (middle != 0 && (goodpeer_cnt & 1) == 0) {
  393. offset_median = (peers[middle-1]->update.d_offset + peers[middle]->update.d_offset) / 2;
  394. G.rootdelay = (peers[middle-1]->update.d_delay + peers[middle]->update.d_delay) / 2;
  395. G.stratum = 1 + MAX(peers[middle-1]->update.d_stratum, peers[middle]->update.d_stratum);
  396. } else {
  397. offset_median = peers[middle]->update.d_offset;
  398. G.rootdelay = peers[middle]->update.d_delay;
  399. G.stratum = 1 + peers[middle]->update.d_stratum;
  400. }
  401. G.leap = peers[middle]->update.d_leap;
  402. G.refid4 = peers[middle]->update.d_refid4;
  403. G.refid =
  404. #if ENABLE_FEATURE_IPV6
  405. peers[middle]->p_lsa->u.sa.sa_family != AF_INET ?
  406. G.refid4 :
  407. #endif
  408. peers[middle]->p_lsa->u.sin.sin_addr.s_addr;
  409. free(peers);
  410. }
  411. //TODO: if (offset_median > BIG) step_time(offset_median)?
  412. G.scale = updated_scale(offset_median);
  413. bb_error_msg("adjusting clock by %fs, our stratum is %u, time scale %u",
  414. offset_median, G.stratum, G.scale);
  415. errno = 0;
  416. d_to_tv(offset_median, &tv);
  417. if (adjtime(&tv, &tv) == -1)
  418. bb_perror_msg_and_die("adjtime failed");
  419. if (G.verbose >= 2)
  420. bb_error_msg("old adjust: %d.%06u", (int)tv.tv_sec, (unsigned)tv.tv_usec);
  421. if (G.first_adj_done) {
  422. uint8_t synced = (tv.tv_sec == 0 && tv.tv_usec == 0);
  423. if (synced != G.synced) {
  424. G.synced = synced;
  425. bb_error_msg("clock is %ssynced", synced ? "" : "un");
  426. }
  427. }
  428. G.first_adj_done = 1;
  429. G.reftime = gettime1900d();
  430. clear_good:
  431. for (item = G.ntp_peers; item != NULL; item = item->link) {
  432. peer_t *p = (peer_t *) item->data;
  433. p->update.d_good = 0;
  434. }
  435. }
  436. static void
  437. update_peer_data(peer_t *p)
  438. {
  439. /* Clock filter.
  440. * Find the datapoint with the lowest delay.
  441. * Use that as the peer update.
  442. * Invalidate it and all older ones.
  443. */
  444. int i;
  445. int best = -1;
  446. int good = 0;
  447. for (i = 0; i < NUM_DATAPOINTS; i++) {
  448. if (p->p_datapoint[i].d_good) {
  449. good++;
  450. if (best < 0 || p->p_datapoint[i].d_delay < p->p_datapoint[best].d_delay)
  451. best = i;
  452. }
  453. }
  454. if (good < 8) //FIXME: was it meant to be NUM_DATAPOINTS, not 8?
  455. return;
  456. p->update = p->p_datapoint[best]; /* struct copy */
  457. slew_time();
  458. for (i = 0; i < NUM_DATAPOINTS; i++)
  459. if (p->p_datapoint[i].d_rcv_time <= p->p_datapoint[best].d_rcv_time)
  460. p->p_datapoint[i].d_good = 0;
  461. }
  462. static unsigned
  463. scale_interval(unsigned requested)
  464. {
  465. unsigned interval, r;
  466. interval = requested * G.scale;
  467. r = (unsigned)random() % (unsigned)(MAX(5, interval / 10));
  468. return (interval + r);
  469. }
  470. static void
  471. recv_and_process_peer_pkt(peer_t *p)
  472. {
  473. ssize_t size;
  474. msg_t msg;
  475. double T1, T2, T3, T4;
  476. unsigned interval;
  477. datapoint_t *datapoint;
  478. /* We can recvfrom here and check from.IP, but some multihomed
  479. * ntp servers reply from their *other IP*.
  480. * TODO: maybe we should check at least what we can: from.port == 123?
  481. */
  482. size = recv(p->p_fd, &msg, sizeof(msg), MSG_DONTWAIT);
  483. if (size == -1) {
  484. bb_perror_msg("recv(%s) error", p->p_dotted);
  485. if (errno == EHOSTUNREACH || errno == EHOSTDOWN
  486. || errno == ENETUNREACH || errno == ENETDOWN
  487. || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
  488. || errno == EAGAIN
  489. ) {
  490. //TODO: always do this?
  491. set_next(p, error_interval());
  492. goto close_sock;
  493. }
  494. xfunc_die();
  495. }
  496. if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
  497. bb_error_msg("malformed packet received from %s", p->p_dotted);
  498. goto bail;
  499. }
  500. if (msg.m_orgtime.int_partl != p->p_xmt_msg.m_xmttime.int_partl
  501. || msg.m_orgtime.fractionl != p->p_xmt_msg.m_xmttime.fractionl
  502. ) {
  503. goto bail;
  504. }
  505. if ((msg.m_status & LI_ALARM) == LI_ALARM
  506. || msg.m_stratum == 0
  507. || msg.m_stratum > NTP_MAXSTRATUM
  508. ) {
  509. // TODO: stratum 0 responses may have commands in 32-bit m_refid field:
  510. // "DENY", "RSTR" - peer does not like us at all
  511. // "RATE" - peer is overloaded, reduce polling freq
  512. interval = error_interval();
  513. bb_error_msg("reply from %s: not synced, next query in %us", p->p_dotted, interval);
  514. goto close_sock;
  515. }
  516. /*
  517. * From RFC 2030 (with a correction to the delay math):
  518. *
  519. * Timestamp Name ID When Generated
  520. * ------------------------------------------------------------
  521. * Originate Timestamp T1 time request sent by client
  522. * Receive Timestamp T2 time request received by server
  523. * Transmit Timestamp T3 time reply sent by server
  524. * Destination Timestamp T4 time reply received by client
  525. *
  526. * The roundtrip delay and local clock offset are defined as
  527. *
  528. * delay = (T4 - T1) - (T3 - T2); offset = ((T2 - T1) + (T3 - T4)) / 2
  529. */
  530. T1 = p->p_xmttime;
  531. T2 = lfp_to_d(msg.m_rectime);
  532. T3 = lfp_to_d(msg.m_xmttime);
  533. T4 = gettime1900d();
  534. datapoint = &p->p_datapoint[p->p_datapoint_idx];
  535. datapoint->d_offset = ((T2 - T1) + (T3 - T4)) / 2;
  536. datapoint->d_delay = (T4 - T1) - (T3 - T2);
  537. if (datapoint->d_delay < 0) {
  538. bb_error_msg("reply from %s: negative delay %f", p->p_dotted, datapoint->d_delay);
  539. interval = error_interval();
  540. set_next(p, interval);
  541. goto close_sock;
  542. }
  543. //UNUSED: datapoint->d_error = (T2 - T1) - (T3 - T4);
  544. datapoint->d_rcv_time = (time_t)(T4 - OFFSET_1900_1970); /* = time(NULL); */
  545. datapoint->d_good = 1;
  546. datapoint->d_leap = (msg.m_status & LI_MASK);
  547. //UNUSED: datapoint->o_precision = msg.m_precision_exp;
  548. //UNUSED: datapoint->o_rootdelay = sfp_to_d(msg.m_rootdelay);
  549. //UNUSED: datapoint->o_rootdispersion = sfp_to_d(msg.m_dispersion);
  550. //UNUSED: datapoint->d_refid = ntohl(msg.m_refid);
  551. datapoint->d_refid4 = msg.m_xmttime.fractionl;
  552. //UNUSED: datapoint->o_reftime = lfp_to_d(msg.m_reftime);
  553. //UNUSED: datapoint->o_poll = msg.m_ppoll;
  554. datapoint->d_stratum = msg.m_stratum;
  555. if (p->p_trustlevel < TRUSTLEVEL_PATHETIC)
  556. interval = scale_interval(INTERVAL_QUERY_PATHETIC);
  557. else if (p->p_trustlevel < TRUSTLEVEL_AGRESSIVE)
  558. interval = scale_interval(INTERVAL_QUERY_AGRESSIVE);
  559. else
  560. interval = scale_interval(INTERVAL_QUERY_NORMAL);
  561. set_next(p, interval);
  562. /* Every received reply which we do not discard increases trust */
  563. if (p->p_trustlevel < TRUSTLEVEL_MAX) {
  564. p->p_trustlevel++;
  565. if (p->p_trustlevel == TRUSTLEVEL_BADPEER)
  566. bb_error_msg("peer %s now valid", p->p_dotted);
  567. }
  568. if (G.verbose)
  569. bb_error_msg("reply from %s: offset %f delay %f, next query in %us", p->p_dotted,
  570. datapoint->d_offset, datapoint->d_delay, interval);
  571. update_peer_data(p);
  572. //TODO: do it after all peers had a chance to return at least one reply?
  573. step_time_once(datapoint->d_offset);
  574. p->p_datapoint_idx++;
  575. if (p->p_datapoint_idx >= NUM_DATAPOINTS)
  576. p->p_datapoint_idx = 0;
  577. close_sock:
  578. /* We do not expect any more packets from this peer for now.
  579. * Closing the socket informs kernel about it.
  580. * We open a new socket when we send a new query.
  581. */
  582. close(p->p_fd);
  583. p->p_fd = -1;
  584. bail:
  585. return;
  586. }
  587. #if ENABLE_FEATURE_NTPD_SERVER
  588. static void
  589. recv_and_process_client_pkt(void /*int fd*/)
  590. {
  591. ssize_t size;
  592. uint8_t version;
  593. double rectime;
  594. len_and_sockaddr *to;
  595. struct sockaddr *from;
  596. msg_t msg;
  597. uint8_t query_status;
  598. uint8_t query_ppoll;
  599. l_fixedpt_t query_xmttime;
  600. to = get_sock_lsa(G.listen_fd);
  601. from = xzalloc(to->len);
  602. size = recv_from_to(G.listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
  603. if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
  604. char *addr;
  605. if (size < 0) {
  606. if (errno == EAGAIN)
  607. goto bail;
  608. bb_perror_msg_and_die("recv");
  609. }
  610. addr = xmalloc_sockaddr2dotted_noport(from);
  611. bb_error_msg("malformed packet received from %s: size %u", addr, (int)size);
  612. free(addr);
  613. goto bail;
  614. }
  615. query_status = msg.m_status;
  616. query_ppoll = msg.m_ppoll;
  617. query_xmttime = msg.m_xmttime;
  618. /* Build a reply packet */
  619. memset(&msg, 0, sizeof(msg));
  620. msg.m_status = G.synced ? G.leap : LI_ALARM;
  621. msg.m_status |= (query_status & VERSION_MASK);
  622. msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
  623. MODE_SERVER : MODE_SYM_PAS;
  624. msg.m_stratum = G.stratum;
  625. msg.m_ppoll = query_ppoll;
  626. msg.m_precision_exp = G_precision_exp;
  627. rectime = gettime1900d();
  628. msg.m_xmttime = msg.m_rectime = d_to_lfp(rectime);
  629. msg.m_reftime = d_to_lfp(G.reftime);
  630. //msg.m_xmttime = d_to_lfp(gettime1900d()); // = msg.m_rectime
  631. msg.m_orgtime = query_xmttime;
  632. msg.m_rootdelay = d_to_sfp(G.rootdelay);
  633. version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
  634. msg.m_refid = (version > (3 << VERSION_SHIFT)) ? G.refid4 : G.refid;
  635. /* We reply from the local address packet was sent to,
  636. * this makes to/from look swapped here: */
  637. do_sendto(G.listen_fd,
  638. /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
  639. &msg, size);
  640. bail:
  641. free(to);
  642. free(from);
  643. }
  644. #endif
  645. /* Upstream ntpd's options:
  646. *
  647. * -4 Force DNS resolution of host names to the IPv4 namespace.
  648. * -6 Force DNS resolution of host names to the IPv6 namespace.
  649. * -a Require cryptographic authentication for broadcast client,
  650. * multicast client and symmetric passive associations.
  651. * This is the default.
  652. * -A Do not require cryptographic authentication for broadcast client,
  653. * multicast client and symmetric passive associations.
  654. * This is almost never a good idea.
  655. * -b Enable the client to synchronize to broadcast servers.
  656. * -c conffile
  657. * Specify the name and path of the configuration file,
  658. * default /etc/ntp.conf
  659. * -d Specify debugging mode. This option may occur more than once,
  660. * with each occurrence indicating greater detail of display.
  661. * -D level
  662. * Specify debugging level directly.
  663. * -f driftfile
  664. * Specify the name and path of the frequency file.
  665. * This is the same operation as the "driftfile FILE"
  666. * configuration command.
  667. * -g Normally, ntpd exits with a message to the system log
  668. * if the offset exceeds the panic threshold, which is 1000 s
  669. * by default. This option allows the time to be set to any value
  670. * without restriction; however, this can happen only once.
  671. * If the threshold is exceeded after that, ntpd will exit
  672. * with a message to the system log. This option can be used
  673. * with the -q and -x options. See the tinker command for other options.
  674. * -i jaildir
  675. * Chroot the server to the directory jaildir. This option also implies
  676. * that the server attempts to drop root privileges at startup
  677. * (otherwise, chroot gives very little additional security).
  678. * You may need to also specify a -u option.
  679. * -k keyfile
  680. * Specify the name and path of the symmetric key file,
  681. * default /etc/ntp/keys. This is the same operation
  682. * as the "keys FILE" configuration command.
  683. * -l logfile
  684. * Specify the name and path of the log file. The default
  685. * is the system log file. This is the same operation as
  686. * the "logfile FILE" configuration command.
  687. * -L Do not listen to virtual IPs. The default is to listen.
  688. * -n Don't fork.
  689. * -N To the extent permitted by the operating system,
  690. * run the ntpd at the highest priority.
  691. * -p pidfile
  692. * Specify the name and path of the file used to record the ntpd
  693. * process ID. This is the same operation as the "pidfile FILE"
  694. * configuration command.
  695. * -P priority
  696. * To the extent permitted by the operating system,
  697. * run the ntpd at the specified priority.
  698. * -q Exit the ntpd just after the first time the clock is set.
  699. * This behavior mimics that of the ntpdate program, which is
  700. * to be retired. The -g and -x options can be used with this option.
  701. * Note: The kernel time discipline is disabled with this option.
  702. * -r broadcastdelay
  703. * Specify the default propagation delay from the broadcast/multicast
  704. * server to this client. This is necessary only if the delay
  705. * cannot be computed automatically by the protocol.
  706. * -s statsdir
  707. * Specify the directory path for files created by the statistics
  708. * facility. This is the same operation as the "statsdir DIR"
  709. * configuration command.
  710. * -t key
  711. * Add a key number to the trusted key list. This option can occur
  712. * more than once.
  713. * -u user[:group]
  714. * Specify a user, and optionally a group, to switch to.
  715. * -v variable
  716. * -V variable
  717. * Add a system variable listed by default.
  718. * -x Normally, the time is slewed if the offset is less than the step
  719. * threshold, which is 128 ms by default, and stepped if above
  720. * the threshold. This option sets the threshold to 600 s, which is
  721. * well within the accuracy window to set the clock manually.
  722. * Note: since the slew rate of typical Unix kernels is limited
  723. * to 0.5 ms/s, each second of adjustment requires an amortization
  724. * interval of 2000 s. Thus, an adjustment as much as 600 s
  725. * will take almost 14 days to complete. This option can be used
  726. * with the -g and -q options. See the tinker command for other options.
  727. * Note: The kernel time discipline is disabled with this option.
  728. */
  729. /* By doing init in a separate function we decrease stack usage
  730. * in main loop.
  731. */
  732. static NOINLINE void ntp_init(char **argv)
  733. {
  734. unsigned opts;
  735. llist_t *peers;
  736. srandom(getpid());
  737. if (getuid())
  738. bb_error_msg_and_die(bb_msg_you_must_be_root);
  739. peers = NULL;
  740. opt_complementary = "dd:p::"; /* d: counter, p: list */
  741. opts = getopt32(argv,
  742. "nqNx" /* compat */
  743. "p:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
  744. "d" /* compat */
  745. "46aAbgL", /* compat, ignored */
  746. &peers, &G.verbose);
  747. if (!(opts & (OPT_p|OPT_l)))
  748. bb_show_usage();
  749. if (opts & OPT_x) /* disable stepping, only slew is allowed */
  750. G.time_was_stepped = 1;
  751. while (peers)
  752. add_peers(llist_pop(&peers));
  753. if (!(opts & OPT_n)) {
  754. bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
  755. logmode = LOGMODE_NONE;
  756. }
  757. #if ENABLE_FEATURE_NTPD_SERVER
  758. G.listen_fd = -1;
  759. if (opts & OPT_l) {
  760. G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
  761. socket_want_pktinfo(G.listen_fd);
  762. setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
  763. }
  764. #endif
  765. /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
  766. if (opts & OPT_N)
  767. setpriority(PRIO_PROCESS, 0, -15);
  768. /* Set some globals */
  769. #if 0
  770. /* With constant b = 100, G.precision_exp is also constant -6.
  771. * Uncomment this and you'll see */
  772. {
  773. int prec = 0;
  774. int b;
  775. # if 0
  776. struct timespec tp;
  777. /* We can use sys_clock_getres but assuming 10ms tick should be fine */
  778. clock_getres(CLOCK_REALTIME, &tp);
  779. tp.tv_sec = 0;
  780. tp.tv_nsec = 10000000;
  781. b = 1000000000 / tp.tv_nsec; /* convert to Hz */
  782. # else
  783. b = 100; /* b = 1000000000/10000000 = 100 */
  784. # endif
  785. while (b > 1)
  786. prec--, b >>= 1;
  787. //G.precision_exp = prec;
  788. bb_error_msg("G.precision_exp:%d", prec); /* -6 */
  789. }
  790. #endif
  791. G.scale = 1;
  792. bb_signals((1 << SIGTERM) | (1 << SIGINT), record_signo);
  793. bb_signals((1 << SIGPIPE) | (1 << SIGHUP), SIG_IGN);
  794. }
  795. int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
  796. int ntpd_main(int argc UNUSED_PARAM, char **argv)
  797. {
  798. struct globals g;
  799. struct pollfd *pfd;
  800. peer_t **idx2peer;
  801. memset(&g, 0, sizeof(g));
  802. SET_PTR_TO_GLOBALS(&g);
  803. ntp_init(argv);
  804. {
  805. /* if ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
  806. unsigned cnt = g.peer_cnt + ENABLE_FEATURE_NTPD_SERVER;
  807. idx2peer = xzalloc(sizeof(idx2peer[0]) * cnt);
  808. pfd = xzalloc(sizeof(pfd[0]) * cnt);
  809. }
  810. while (!bb_got_signal) {
  811. llist_t *item;
  812. unsigned i, j;
  813. unsigned sent_cnt, trial_cnt;
  814. int nfds, timeout;
  815. time_t cur_time, nextaction;
  816. /* Nothing between here and poll() blocks for any significant time */
  817. cur_time = time(NULL);
  818. nextaction = cur_time + 3600;
  819. i = 0;
  820. #if ENABLE_FEATURE_NTPD_SERVER
  821. if (g.listen_fd != -1) {
  822. pfd[0].fd = g.listen_fd;
  823. pfd[0].events = POLLIN;
  824. i++;
  825. }
  826. #endif
  827. /* Pass over peer list, send requests, time out on receives */
  828. sent_cnt = trial_cnt = 0;
  829. for (item = g.ntp_peers; item != NULL; item = item->link) {
  830. peer_t *p = (peer_t *) item->data;
  831. /* Overflow-safe "if (p->next_action_time <= cur_time) ..." */
  832. if ((int)(cur_time - p->next_action_time) >= 0) {
  833. if (p->p_fd == -1) {
  834. /* Time to send new req */
  835. trial_cnt++;
  836. if (send_query_to_peer(p) == 0)
  837. sent_cnt++;
  838. } else {
  839. /* Timed out waiting for reply */
  840. close(p->p_fd);
  841. p->p_fd = -1;
  842. timeout = error_interval();
  843. bb_error_msg("timed out waiting for %s, "
  844. "next query in %us", p->p_dotted, timeout);
  845. if (p->p_trustlevel >= TRUSTLEVEL_BADPEER) {
  846. p->p_trustlevel /= 2;
  847. if (p->p_trustlevel < TRUSTLEVEL_BADPEER)
  848. bb_error_msg("peer %s now invalid", p->p_dotted);
  849. }
  850. set_next(p, timeout);
  851. }
  852. }
  853. if (p->next_action_time < nextaction)
  854. nextaction = p->next_action_time;
  855. if (p->p_fd >= 0) {
  856. /* Wait for reply from this peer */
  857. pfd[i].fd = p->p_fd;
  858. pfd[i].events = POLLIN;
  859. idx2peer[i] = p;
  860. i++;
  861. }
  862. }
  863. if ((trial_cnt > 0 && sent_cnt == 0) || g.peer_cnt == 0)
  864. step_time_once(0); /* no good peers, don't wait */
  865. timeout = nextaction - cur_time;
  866. if (timeout < 1)
  867. timeout = 1;
  868. /* Here we may block */
  869. if (g.verbose >= 2)
  870. bb_error_msg("poll %us, sockets:%u", timeout, i);
  871. nfds = poll(pfd, i, timeout * 1000);
  872. if (nfds <= 0)
  873. continue;
  874. /* Process any received packets */
  875. j = 0;
  876. #if ENABLE_FEATURE_NTPD_SERVER
  877. if (g.listen_fd != -1) {
  878. if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
  879. nfds--;
  880. recv_and_process_client_pkt(/*g.listen_fd*/);
  881. }
  882. j = 1;
  883. }
  884. #endif
  885. for (; nfds != 0 && j < i; j++) {
  886. if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
  887. nfds--;
  888. recv_and_process_peer_pkt(idx2peer[j]);
  889. }
  890. }
  891. } /* while (!bb_got_signal) */
  892. kill_myself_with_sig(bb_got_signal);
  893. }