ntp.c 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. /* Minimal SNTP client (RFC 4330).
  2. *
  3. * One 48-byte client request to UDP port 123, three tries one second apart.
  4. * The server is resolved through DNS (a dotted address skips it) and reached
  5. * through the shared ARP/routing helpers. The reply's origin timestamp must
  6. * match the request's transmit timestamp, and its transmit timestamp is
  7. * converted from NTP seconds (1900 epoch) to UTC `struct sys_datetime`.
  8. *
  9. * Like DNS and DHCP the polled caller owns the NIC; sys_ntp_sync() acquires
  10. * it for ring-3 callers. No NTP authentication/delay estimation is done:
  11. * the RTC only has one-second resolution. */
  12. #include "ntp.h"
  13. #include "dns.h"
  14. #include "net.h"
  15. #include "netdev.h"
  16. #include "timer.h"
  17. #define NTP_PORT 123
  18. #define NTP_PACKET_LEN 48
  19. #define NTP_RETRY_MS 1000
  20. #define NTP_RETRIES 3
  21. #define NTP_DEFAULT_TIMEOUT_MS (NTP_RETRIES * NTP_RETRY_MS)
  22. /* 1900-01-01 -> 1970-01-01, and the Unix time of the NTP 32-bit wrap. */
  23. #define NTP_UNIX_EPOCH 2208988800u
  24. #define NTP_ERA1_BASE 2085978496u
  25. static unsigned int rd32be(const unsigned char *p)
  26. {
  27. return ((unsigned int)p[0] << 24) | ((unsigned int)p[1] << 16) |
  28. ((unsigned int)p[2] << 8) | p[3];
  29. }
  30. static void wr32be(unsigned char *p, unsigned int v)
  31. {
  32. p[0] = (unsigned char)(v >> 24);
  33. p[1] = (unsigned char)(v >> 16);
  34. p[2] = (unsigned char)(v >> 8);
  35. p[3] = (unsigned char)v;
  36. }
  37. static int ip_eq(const unsigned char *a, const unsigned char *b)
  38. {
  39. return a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3];
  40. }
  41. /* NTP seconds/fraction -> Unix seconds. The 32-bit NTP seconds wrap in
  42. * 2036; values below the 1968 boundary belong to era 1 then. The RTC range
  43. * is 1970-2069, so the 1968-1970 era-0 window is simply rejected. */
  44. static int ntp_to_unix(unsigned int secs, unsigned int frac,
  45. unsigned int *out)
  46. {
  47. unsigned int t;
  48. if (secs >= NTP_UNIX_EPOCH)
  49. t = secs - NTP_UNIX_EPOCH; /* era 0: 1970..2036 */
  50. else if (secs < NTP_ERA1_BASE)
  51. t = secs + NTP_ERA1_BASE; /* era 1: 2036..2106 */
  52. else
  53. return -1; /* 1968..1970 */
  54. if (frac >= 0x80000000u) /* round to nearest */
  55. t++;
  56. *out = t;
  57. return 0;
  58. }
  59. /* Howard Hinnant's civil-from-days algorithm, all unsigned 32-bit. */
  60. static void unix_to_datetime(unsigned int t, struct sys_datetime *dt)
  61. {
  62. unsigned int days = t / 86400u;
  63. unsigned int rem = t % 86400u;
  64. unsigned int z = days + 719468u;
  65. unsigned int era = z / 146097u;
  66. unsigned int doe = z - era * 146097u;
  67. unsigned int yoe = (doe - doe / 1460u + doe / 36524u -
  68. doe / 146096u) / 365u;
  69. unsigned int y = yoe + era * 400u;
  70. unsigned int doy = doe - (365u * yoe + yoe / 4u - yoe / 100u);
  71. unsigned int mp = (5u * doy + 2u) / 153u;
  72. unsigned int d = doy - (153u * mp + 2u) / 5u + 1u;
  73. unsigned int m = mp < 10u ? mp + 3u : mp - 9u;
  74. if (m <= 2u)
  75. y++;
  76. dt->year = y;
  77. dt->month = m;
  78. dt->day = d;
  79. dt->hour = rem / 3600u;
  80. dt->minute = (rem % 3600u) / 60u;
  81. dt->second = rem % 60u;
  82. dt->wday = (days + 4u) % 7u; /* 1970-01-01 was a Thursday */
  83. }
  84. /* 1 = a valid reply and *out filled, 0 = not ours, <0 = ours but unusable. */
  85. static int ntp_parse(const unsigned char *frame, unsigned int len,
  86. const unsigned char *server_ip, unsigned int server_port,
  87. unsigned int nonce, unsigned int nfrac,
  88. struct sys_datetime *out)
  89. {
  90. unsigned char s_ip[4], d_ip[4];
  91. const unsigned char *p;
  92. unsigned int sport, dport, plen, secs, frac, unix_sec;
  93. int mode;
  94. if (!net_udp_parse(frame, len, s_ip, d_ip, &sport, &dport, &p, &plen))
  95. return 0;
  96. if (sport != NTP_PORT || dport != server_port ||
  97. !ip_eq(s_ip, server_ip))
  98. return 0;
  99. if (plen < NTP_PACKET_LEN)
  100. return 0;
  101. mode = p[0] & 0x07;
  102. if (mode != 4 && mode != 5) /* server or broadcast reply */
  103. return 0;
  104. if ((p[0] >> 6) == 3) /* LI: server unsynchronised */
  105. return -1;
  106. if (p[1] == 0 || p[1] > 15) /* kiss-o'-death / invalid */
  107. return -1;
  108. if (rd32be(p + 24) != nonce || rd32be(p + 28) != nfrac)
  109. return 0; /* not a reply to this request */
  110. secs = rd32be(p + 40);
  111. frac = rd32be(p + 44);
  112. if (!(secs | frac)) /* no transmit timestamp */
  113. return -1;
  114. if (ntp_to_unix(secs, frac, &unix_sec) != 0)
  115. return -1;
  116. unix_to_datetime(unix_sec, out);
  117. if (out->year < 1970 || out->year > 2069)
  118. return -1;
  119. return 1;
  120. }
  121. int ntp_sync(const char *server, unsigned int timeout_ms,
  122. struct sys_datetime *out)
  123. {
  124. const struct netdev *nd = netdev_active();
  125. unsigned char server_ip[4], hop[4], mac[6];
  126. unsigned char *rxbuf;
  127. unsigned char pkt[NTP_PACKET_LEN];
  128. unsigned int nonce, nfrac, sport, tries, start, deadline, i;
  129. char name[64];
  130. unsigned int n = 0, e = 0;
  131. int r;
  132. if (!nd || !nd->rx || !nd->tx || !nd->get_mac)
  133. return SYS_NTP_ENONIC;
  134. if (!out)
  135. return SYS_NTP_EREPLY;
  136. /* The text field may have accidental surrounding spaces. */
  137. if (server) {
  138. while (server[n] == ' ' || server[n] == '\t')
  139. n++;
  140. while (server[n] && e + 1 < sizeof(name))
  141. name[e++] = server[n++];
  142. while (e && (name[e - 1] == ' ' || name[e - 1] == '\t'))
  143. e--;
  144. }
  145. name[e] = '\0';
  146. if (!name[0]) {
  147. static const char fallback[] = NTP_DEFAULT_SERVER;
  148. for (i = 0; fallback[i] && i + 1 < sizeof(name); i++)
  149. name[i] = fallback[i];
  150. name[i] = '\0';
  151. }
  152. if (net_parse_ip(name, server_ip) != 0) {
  153. if (dns_resolve(name, server_ip) != 0)
  154. return SYS_NTP_ENAME;
  155. }
  156. net_next_hop(server_ip, hop);
  157. r = net_arp_resolve(hop, mac);
  158. if (r == -2)
  159. return SYS_NTP_ETX;
  160. if (r != 0)
  161. return SYS_NTP_EARP;
  162. nonce = get_ticks_ms() ^ 0x4E545000u; /* "NT" */
  163. if (!nonce)
  164. nonce = 1;
  165. nfrac = 0x4E420000u; /* "NB" */
  166. for (i = 0; i < NTP_PACKET_LEN; i++)
  167. pkt[i] = 0;
  168. pkt[0] = 0x23; /* LI 0, VN 4, mode 3 client */
  169. pkt[2] = 6; /* poll exponent: 64 s */
  170. pkt[3] = 0xEC; /* precision: -20 */
  171. wr32be(pkt + 40, nonce);
  172. wr32be(pkt + 44, nfrac);
  173. /* Ephemeral source port; the reply must come back to it. */
  174. sport = 49152u + (nonce & 0x3FFFu);
  175. if (timeout_ms == 0)
  176. timeout_ms = NTP_DEFAULT_TIMEOUT_MS;
  177. if (timeout_ms > 15000)
  178. timeout_ms = 15000;
  179. rxbuf = netdev_rx_scratch();
  180. start = get_ticks_ms();
  181. for (tries = 0; tries < NTP_RETRIES; tries++) {
  182. unsigned int now = get_ticks_ms();
  183. if ((int)(now - (start + timeout_ms)) >= 0)
  184. break;
  185. deadline = now + NTP_RETRY_MS;
  186. if ((int)(deadline - (start + timeout_ms)) > 0)
  187. deadline = start + timeout_ms;
  188. if (net_udp_send(mac, server_ip, sport, NTP_PORT,
  189. pkt, sizeof(pkt)) != 0)
  190. return SYS_NTP_ETX;
  191. while ((int)(get_ticks_ms() - deadline) < 0) {
  192. int len = nd->rx(rxbuf, NETDEV_FRAME_MAX);
  193. if (len < 0)
  194. continue;
  195. r = ntp_parse(rxbuf, (unsigned int)len, server_ip,
  196. sport, nonce, nfrac, out);
  197. if (r > 0)
  198. return SYS_NTP_OK;
  199. if (r < 0)
  200. return SYS_NTP_EREPLY;
  201. }
  202. }
  203. return SYS_NTP_ETIMEOUT;
  204. }