ntpd_simple.c 28 KB

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