sntp.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. /*
  2. * Copyright 2015 Dius Computing Pty Ltd. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. *
  8. * - Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * - Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the
  13. * distribution.
  14. * - Neither the name of the copyright holders nor the names of
  15. * its contributors may be used to endorse or promote products derived
  16. * from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  21. * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
  22. * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  23. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  24. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  25. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  26. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  27. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  28. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  29. * OF THE POSSIBILITY OF SUCH DAMAGE.
  30. *
  31. * @author Johny Mattsson <jmattsson@dius.com.au>
  32. */
  33. // Module for Simple Network Time Protocol (SNTP)
  34. #include "module.h"
  35. #include "lauxlib.h"
  36. #include "os_type.h"
  37. #include "osapi.h"
  38. #include "lwip/udp.h"
  39. #include "c_stdlib.h"
  40. #include "user_modules.h"
  41. #include "lwip/dns.h"
  42. #include "task/task.h"
  43. #include "user_interface.h"
  44. #ifdef LUA_USE_MODULES_RTCTIME
  45. #include "rtc/rtctime.h"
  46. #endif
  47. #define max(a,b) ((a < b) ? b : a)
  48. #define NTP_PORT 123
  49. #define NTP_ANYCAST_ADDR(dst) IP4_ADDR(dst, 224, 0, 1, 1)
  50. #define MAX_ATTEMPTS 5
  51. #if 0
  52. # define sntp_dbg(...) dbg_printf(__VA_ARGS__)
  53. #else
  54. # define sntp_dbg(...)
  55. #endif
  56. //#define US_TO_FRAC(us) ((((uint64_t) (us)) << 32) / 1000000)
  57. #define US_TO_FRAC(us) (div1m(((uint64_t) (us)) << 32))
  58. #define SUS_TO_FRAC(us) ((((int64_t) (us)) << 32) / 1000000)
  59. //#define US_TO_FRAC16(us) ((((uint64_t) (us)) << 16) / 1000000)
  60. #define FRAC16_TO_US(frac) ((((uint64_t) (frac)) * 1000000) >> 16)
  61. typedef enum {
  62. NTP_NO_ERR = 0,
  63. NTP_DNS_ERR,
  64. NTP_MEM_ERR,
  65. NTP_SEND_ERR,
  66. NTP_TIMEOUT_ERR,
  67. NTP_MAX_ERR_ID // must be last
  68. } ntp_err_t;
  69. typedef struct
  70. {
  71. uint32_t sec;
  72. uint32_t frac;
  73. } ntp_timestamp_t;
  74. typedef struct
  75. {
  76. uint8_t mode : 3;
  77. uint8_t ver : 3;
  78. uint8_t LI : 2;
  79. uint8_t stratum;
  80. uint8_t poll;
  81. uint8_t precision;
  82. uint32_t root_delay;
  83. uint32_t root_dispersion;
  84. uint32_t refid;
  85. ntp_timestamp_t ref;
  86. ntp_timestamp_t origin;
  87. ntp_timestamp_t recv;
  88. ntp_timestamp_t xmit;
  89. } ntp_frame_t;
  90. typedef struct
  91. {
  92. struct udp_pcb *pcb;
  93. ntp_timestamp_t cookie;
  94. os_timer_t timer;
  95. int sync_cb_ref;
  96. int err_cb_ref;
  97. uint8_t attempts; // Number of repeats of each entry
  98. uint8_t server_index; // index into server table
  99. uint8_t lookup_pos;
  100. bool is_on_timeout;
  101. uint32_t kodbits; // Only for up to 32 servers (more than enough)
  102. int16_t server_pos;
  103. int16_t last_server_pos;
  104. int list_ref;
  105. struct {
  106. uint32_t delay_frac;
  107. uint32_t root_maxerr;
  108. uint32_t root_delay;
  109. uint32_t root_dispersion;
  110. uint16_t server_pos;
  111. uint8_t LI;
  112. uint8_t stratum;
  113. uint32_t delay;
  114. int when;
  115. int64_t delta;
  116. ip_addr_t server;
  117. } best;
  118. } sntp_state_t;
  119. typedef struct {
  120. int32_t sync_cb_ref;
  121. int32_t err_cb_ref;
  122. int32_t list_ref;
  123. os_timer_t timer;
  124. } sntp_repeat_t;
  125. static sntp_state_t *state;
  126. static sntp_repeat_t *repeat;
  127. static ip_addr_t *serverp;
  128. static uint8_t server_count;
  129. static uint8_t using_offset;
  130. static uint8_t the_offset;
  131. static uint8_t pending_LI;
  132. static int32_t next_midnight;
  133. static uint64_t pll_increment;
  134. #define PLL_A (1 << (32 - 11))
  135. #define PLL_B (1 << (32 - 11 - 2))
  136. static void on_timeout(void *arg);
  137. static void on_long_timeout(void *arg);
  138. static void sntp_dolookups(lua_State *L);
  139. // Value passed:
  140. // ntp_err_t or char pointer
  141. #define SNTP_HANDLE_RESULT_ID 20
  142. #define SNTP_DOLOOKUPS_ID 21
  143. static task_handle_t tasknumber;
  144. static uint64_t div1m(uint64_t n) {
  145. uint64_t q1 = (n >> 5) + (n >> 10);
  146. uint64_t q2 = (n >> 12) + (q1 >> 1);
  147. uint64_t q3 = (q2 >> 11) - (q2 >> 23);
  148. uint64_t q = n + q1 + q2 - q3;
  149. q = q >> 20;
  150. // Ignore the error term -- it is measured in pico seconds
  151. return q;
  152. }
  153. static void cleanup (lua_State *L)
  154. {
  155. os_timer_disarm (&state->timer);
  156. udp_remove (state->pcb);
  157. luaL_unref (L, LUA_REGISTRYINDEX, state->sync_cb_ref);
  158. luaL_unref (L, LUA_REGISTRYINDEX, state->err_cb_ref);
  159. luaL_unref (L, LUA_REGISTRYINDEX, state->list_ref);
  160. os_free (state);
  161. state = 0;
  162. }
  163. static ip_addr_t* get_free_server() {
  164. ip_addr_t* temp = (ip_addr_t *) c_malloc((server_count + 1) * sizeof(ip_addr_t));
  165. if (server_count > 0) {
  166. memcpy(temp, serverp, server_count * sizeof(ip_addr_t));
  167. }
  168. if (serverp) {
  169. c_free(serverp);
  170. }
  171. serverp = temp;
  172. return serverp + server_count;
  173. }
  174. static void handle_error (lua_State *L, ntp_err_t err, const char *msg)
  175. {
  176. sntp_dbg("sntp: handle_error\n");
  177. if (state->err_cb_ref != LUA_NOREF && state->err_cb_ref != LUA_REFNIL)
  178. {
  179. lua_rawgeti (L, LUA_REGISTRYINDEX, state->err_cb_ref);
  180. lua_pushinteger (L, err);
  181. lua_pushstring (L, msg);
  182. cleanup (L);
  183. lua_call (L, 2, 0);
  184. }
  185. else
  186. cleanup (L);
  187. }
  188. #ifdef LUA_USE_MODULES_RTCTIME
  189. static void get_zero_base_timeofday(struct rtc_timeval *tv) {
  190. uint32_t now = system_get_time();
  191. tv->tv_sec = now / 1000000;
  192. tv->tv_usec = now % 1000000;
  193. }
  194. #endif
  195. static void sntp_handle_result(lua_State *L) {
  196. const uint32_t MICROSECONDS = 1000000;
  197. if (state->best.stratum == 0) {
  198. // This could be because none of the servers are reachable, or maybe we haven't been able to look
  199. // them up.
  200. server_count = 0; // Reset for next time.
  201. handle_error(L, NTP_TIMEOUT_ERR, NULL);
  202. return;
  203. }
  204. bool have_cb = (state->sync_cb_ref != LUA_NOREF && state->sync_cb_ref != LUA_REFNIL);
  205. state->last_server_pos = state->best.server_pos; // Remember for next time
  206. // if we have rtctime, do higher resolution delta calc, else just use
  207. // the transmit timestamp
  208. #ifdef LUA_USE_MODULES_RTCTIME
  209. struct rtc_timeval tv;
  210. rtctime_gettimeofday (&tv);
  211. if (tv.tv_sec == 0) {
  212. get_zero_base_timeofday(&tv);
  213. }
  214. tv.tv_sec += (int)(state->best.delta >> 32);
  215. tv.tv_usec += (int) ((MICROSECONDS * (state->best.delta & 0xffffffff)) >> 32);
  216. while (tv.tv_usec >= 1000000) {
  217. tv.tv_usec -= 1000000;
  218. tv.tv_sec++;
  219. }
  220. if (state->is_on_timeout && state->best.delta > SUS_TO_FRAC(-200000) && state->best.delta < SUS_TO_FRAC(200000)) {
  221. // Adjust rate
  222. // f is frequency -- f should be 1 << 32 for nominal
  223. sntp_dbg("delta=%d, increment=%d, ", (int32_t) state->best.delta, (int32_t) pll_increment);
  224. int64_t f = ((state->best.delta * PLL_A) >> 32) + pll_increment;
  225. pll_increment += (state->best.delta * PLL_B) >> 32;
  226. sntp_dbg("f=%d, increment=%d\n", (int32_t) f, (int32_t) pll_increment);
  227. rtctime_adjust_rate((int32_t) f);
  228. } else {
  229. rtctime_settimeofday (&tv);
  230. }
  231. #endif
  232. if (have_cb)
  233. {
  234. lua_rawgeti(L, LUA_REGISTRYINDEX, state->sync_cb_ref);
  235. #ifdef LUA_USE_MODULES_RTCTIME
  236. lua_pushnumber(L, tv.tv_sec);
  237. lua_pushnumber(L, tv.tv_usec);
  238. lua_pushstring(L, ipaddr_ntoa (&state->best.server));
  239. lua_newtable(L);
  240. int d40 = state->best.delta >> 40;
  241. if (d40 != 0 && d40 != -1) {
  242. lua_pushnumber(L, state->best.delta >> 32);
  243. lua_setfield(L, -2, "offset_s");
  244. } else {
  245. lua_pushnumber(L, (state->best.delta * MICROSECONDS) >> 32);
  246. lua_setfield(L, -2, "offset_us");
  247. }
  248. #else
  249. int adjust_us = system_get_time() - state->best.when;
  250. int tv_sec = state->best.delta >> 32;
  251. int tv_usec = (int) (((state->best.delta & 0xffffffff) * MICROSECONDS) >> 32) + adjust_us;
  252. while (tv_usec >= 1000000) {
  253. tv_usec -= 1000000;
  254. tv_sec++;
  255. }
  256. lua_pushnumber(L, tv_sec);
  257. lua_pushnumber(L, tv_usec);
  258. lua_pushstring(L, ipaddr_ntoa (&state->best.server));
  259. lua_newtable(L);
  260. #endif
  261. if (state->best.delay_frac > 0) {
  262. lua_pushnumber(L, FRAC16_TO_US(state->best.delay_frac));
  263. lua_setfield(L, -2, "delay_us");
  264. }
  265. lua_pushnumber(L, FRAC16_TO_US(state->best.root_delay));
  266. lua_setfield(L, -2, "root_delay_us");
  267. lua_pushnumber(L, FRAC16_TO_US(state->best.root_dispersion));
  268. lua_setfield(L, -2, "root_dispersion_us");
  269. lua_pushnumber(L, FRAC16_TO_US(state->best.root_maxerr + state->best.delay_frac / 2));
  270. lua_setfield(L, -2, "root_maxerr_us");
  271. lua_pushnumber(L, state->best.stratum);
  272. lua_setfield(L, -2, "stratum");
  273. lua_pushnumber(L, state->best.LI);
  274. lua_setfield(L, -2, "leap");
  275. lua_pushnumber(L, pending_LI);
  276. lua_setfield(L, -2, "pending_leap");
  277. }
  278. cleanup (L);
  279. if (have_cb)
  280. {
  281. lua_call (L, 4, 0);
  282. }
  283. }
  284. static void sntp_dosend ()
  285. {
  286. do {
  287. if (state->server_pos < 0) {
  288. os_timer_disarm(&state->timer);
  289. os_timer_setfn(&state->timer, on_timeout, NULL);
  290. state->server_pos = 0;
  291. } else {
  292. ++state->server_pos;
  293. }
  294. if (state->server_pos >= server_count) {
  295. state->server_pos = 0;
  296. ++state->attempts;
  297. }
  298. if (state->attempts >= MAX_ATTEMPTS || state->attempts * server_count >= 8) {
  299. task_post_high(tasknumber, SNTP_HANDLE_RESULT_ID);
  300. return;
  301. }
  302. } while (serverp[state->server_pos].addr == 0 || (state->kodbits & (1 << state->server_pos)));
  303. sntp_dbg("sntp: server %s (%d), attempt %d\n", ipaddr_ntoa(serverp + state->server_pos), state->server_pos, state->attempts);
  304. struct pbuf *p = pbuf_alloc (PBUF_TRANSPORT, sizeof (ntp_frame_t), PBUF_RAM);
  305. if (!p) {
  306. task_post_low(tasknumber, NTP_MEM_ERR);
  307. return;
  308. }
  309. ntp_frame_t req;
  310. os_memset (&req, 0, sizeof (req));
  311. req.ver = 4;
  312. req.mode = 3; // client
  313. #ifdef LUA_USE_MODULES_RTCTIME
  314. const uint32_t NTP_TO_UNIX_EPOCH = 2208988800ul;
  315. struct rtc_timeval tv;
  316. rtctime_gettimeofday (&tv);
  317. if (tv.tv_sec == 0) {
  318. get_zero_base_timeofday(&tv);
  319. }
  320. req.xmit.sec = htonl (tv.tv_sec - the_offset + NTP_TO_UNIX_EPOCH);
  321. req.xmit.frac = htonl (US_TO_FRAC(tv.tv_usec));
  322. #else
  323. req.xmit.frac = htonl (system_get_time ());
  324. #endif
  325. state->cookie = req.xmit;
  326. os_memcpy (p->payload, &req, sizeof (req));
  327. int ret = udp_sendto (state->pcb, p, serverp + state->server_pos, NTP_PORT);
  328. sntp_dbg("sntp: send: %d\n", ret);
  329. pbuf_free (p);
  330. // Ignore send errors -- let the timeout handle it
  331. os_timer_arm (&state->timer, 1000, 0);
  332. }
  333. static void sntp_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
  334. {
  335. (void)arg;
  336. if (ipaddr == NULL)
  337. {
  338. sntp_dbg("DNS Fail!\n");
  339. }
  340. else
  341. {
  342. serverp[server_count] = *ipaddr;
  343. server_count++;
  344. }
  345. task_post_low(tasknumber, SNTP_DOLOOKUPS_ID);
  346. }
  347. static void on_timeout (void *arg)
  348. {
  349. (void)arg;
  350. sntp_dbg("sntp: timer\n");
  351. sntp_dosend ();
  352. }
  353. static int32_t get_next_midnight(int32_t now) {
  354. return now + 86400 - the_offset - (now - the_offset) % 86400;
  355. }
  356. static void update_offset()
  357. {
  358. // This may insert or remove an offset second -- i.e. a leap second
  359. // This can only happen if it is at midnight UTC.
  360. #ifdef LUA_USE_MODULES_RTCTIME
  361. struct rtc_timeval tv;
  362. if (pending_LI && using_offset) {
  363. rtctime_gettimeofday (&tv);
  364. sntp_dbg("Now=%d, next=%d\n", tv.tv_sec - the_offset, next_midnight);
  365. if (next_midnight < 100000) {
  366. next_midnight = get_next_midnight(tv.tv_sec);
  367. } else if (tv.tv_sec - the_offset >= next_midnight) {
  368. next_midnight = get_next_midnight(tv.tv_sec);
  369. // is this the first day of the month
  370. // Number of days since 1/mar/0000
  371. // 1970 * 365 is the number of days in full years
  372. // 1970 / 4 is the number of leap days (ignoring century rules)
  373. // 19 is the number of centuries
  374. // 4 is the number of 400 years (where there was a leap day)
  375. // 31 & 28 are the number of days in Jan 1970 and Feb 1970
  376. int day = (tv.tv_sec - the_offset) / 86400 + 1970 * 365 + 1970 / 4 - 19 + 4 - 31 - 28;
  377. int century = (4 * day + 3) / 146097;
  378. day = day - century * 146097 / 4;
  379. int year = (4 * day + 3) / 1461;
  380. day = day - year * 1461 / 4;
  381. int month = (5 * day + 2) / 153;
  382. day = day - (153 * month + 2) / 5;
  383. // Months 13 & 14 are really Jan and Feb in the following year.
  384. sntp_dbg("century=%d, year=%d, month=%d, day=%d\n", century, year, month + 3, day + 1);
  385. if (day == 0) {
  386. if (pending_LI == 1) {
  387. the_offset ++;
  388. } else {
  389. the_offset --;
  390. }
  391. }
  392. pending_LI = 0;
  393. }
  394. }
  395. #endif
  396. }
  397. static void record_result(int server_pos, ip_addr_t *addr, int64_t delta, int stratum, int LI, uint32_t delay_frac, uint32_t root_maxerr, uint32_t root_dispersion, uint32_t root_delay) {
  398. sntp_dbg("Recording %s: delta=%08x.%08x, stratum=%d, li=%d, delay=%dus, root_maxerr=%dus",
  399. ipaddr_ntoa(addr), (uint32_t) (delta >> 32), (uint32_t) (delta & 0xffffffff), stratum, LI, (int32_t) FRAC16_TO_US(delay_frac), (int32_t) FRAC16_TO_US(root_maxerr));
  400. // I want to favor close by servers as they probably have a more consistent clock,
  401. int delay = root_delay * 2 + delay_frac;
  402. if (state->last_server_pos == server_pos) {
  403. delay -= delay >> 2; // 25% bonus to last best server
  404. }
  405. if (!state->best.stratum || delay < state->best.delay) {
  406. sntp_dbg(" --BEST\n");
  407. state->best.server = *addr;
  408. state->best.server_pos = server_pos;
  409. state->best.delay = delay;
  410. state->best.delay_frac = delay_frac;
  411. state->best.root_maxerr = root_maxerr;
  412. state->best.root_dispersion = root_dispersion;
  413. state->best.root_delay = root_delay;
  414. state->best.delta = delta;
  415. state->best.stratum = stratum;
  416. state->best.LI = LI;
  417. state->best.when = system_get_time();
  418. } else {
  419. sntp_dbg("\n");
  420. }
  421. }
  422. static void on_recv (void *arg, struct udp_pcb *pcb, struct pbuf *p, struct ip_addr *addr, uint16_t port)
  423. {
  424. (void)port;
  425. #ifdef LUA_USE_MODULES_RTCTIME
  426. // Ideally this would be done when we receive the packet....
  427. struct rtc_timeval tv;
  428. rtctime_gettimeofday (&tv);
  429. if (tv.tv_sec == 0) {
  430. get_zero_base_timeofday(&tv);
  431. }
  432. #endif
  433. sntp_dbg("sntp: on_recv\n");
  434. if (!state || state->pcb != pcb)
  435. {
  436. // "impossible", but don't leak if it did happen somehow...
  437. udp_remove (pcb);
  438. pbuf_free (p);
  439. return;
  440. }
  441. if (!p)
  442. return;
  443. if (p->len < sizeof (ntp_frame_t))
  444. {
  445. pbuf_free (p);
  446. return; // not an ntp frame, ignore
  447. }
  448. // make sure we have an aligned copy to work from
  449. ntp_frame_t ntp;
  450. os_memcpy (&ntp, p->payload, sizeof (ntp));
  451. pbuf_free (p);
  452. sntp_dbg("sntp: transmit timestamp: %u, %u\n", ntp.xmit.sec, ntp.xmit.frac);
  453. // sanity checks before we touch our clocks
  454. ip_addr_t anycast;
  455. NTP_ANYCAST_ADDR(&anycast);
  456. if (serverp[state->server_pos].addr != anycast.addr && serverp[state->server_pos].addr != addr->addr)
  457. return; // unknown sender, ignore
  458. if (ntp.origin.sec != state->cookie.sec ||
  459. ntp.origin.frac != state->cookie.frac)
  460. return; // unsolicited message, ignore
  461. if (ntp.LI == 3) {
  462. if (memcmp(&ntp.refid, "DENY", 4) == 0) {
  463. // KoD packet
  464. if (state->kodbits & (1 << state->server_pos)) {
  465. // Oh dear -- two packets rxed. Kill this entry
  466. serverp[state->server_pos].addr = 0;
  467. } else {
  468. state->kodbits |= (1 << state->server_pos);
  469. }
  470. }
  471. return; // server clock not synchronized (why did it even respond?!)
  472. }
  473. // clear kod -- we got a good packet back
  474. state->kodbits &= ~(1 << state->server_pos);
  475. os_timer_disarm(&state->timer);
  476. if (ntp.LI) {
  477. pending_LI = ntp.LI;
  478. }
  479. update_offset();
  480. ntp.origin.sec = ntohl (ntp.origin.sec);
  481. ntp.origin.frac = ntohl (ntp.origin.frac);
  482. ntp.recv.sec = ntohl (ntp.recv.sec);
  483. ntp.recv.frac = ntohl (ntp.recv.frac);
  484. ntp.xmit.sec = ntohl (ntp.xmit.sec);
  485. ntp.xmit.frac = ntohl (ntp.xmit.frac);
  486. const uint64_t MICROSECONDS = 1000000ull;
  487. const uint32_t NTP_TO_UNIX_EPOCH = 2208988800ul;
  488. uint32_t root_maxerr = ntohl(ntp.root_dispersion) + ntohl(ntp.root_delay) / 2;
  489. bool same_as_last = state->server_pos == state->last_server_pos;
  490. // if we have rtctime, do higher resolution delta calc, else just use
  491. // the transmit timestamp
  492. #ifdef LUA_USE_MODULES_RTCTIME
  493. ntp_timestamp_t dest;
  494. dest.sec = tv.tv_sec + NTP_TO_UNIX_EPOCH - the_offset;
  495. dest.frac = US_TO_FRAC(tv.tv_usec);
  496. uint64_t ntp_recv = (((uint64_t) ntp.recv.sec) << 32) + (uint64_t) ntp.recv.frac;
  497. uint64_t ntp_origin = (((uint64_t) ntp.origin.sec) << 32) + (uint64_t) ntp.origin.frac;
  498. uint64_t ntp_xmit = (((uint64_t) ntp.xmit.sec) << 32) + (uint64_t) ntp.xmit.frac;
  499. uint64_t ntp_dest = (((uint64_t) dest.sec) << 32) + (uint64_t) dest.frac;
  500. // Compensation as per RFC2030
  501. int64_t delta = (int64_t) (ntp_recv - ntp_origin) / 2 + (int64_t) (ntp_xmit - ntp_dest) / 2;
  502. record_result(same_as_last, addr, delta, ntp.stratum, ntp.LI, ((int64_t)(ntp_dest - ntp_origin - (ntp_xmit - ntp_recv))) >> 16, root_maxerr, ntohl(ntp.root_dispersion), ntohl(ntp.root_delay));
  503. #else
  504. uint64_t ntp_xmit = (((uint64_t) ntp.xmit.sec - NTP_TO_UNIX_EPOCH) << 32) + (uint64_t) ntp.xmit.frac;
  505. record_result(same_as_last, addr, ntp_xmit, ntp.stratum, ntp.LI, (((int64_t) (system_get_time() - ntp.origin.frac)) << 16) / MICROSECONDS, root_maxerr, ntohl(ntp.root_dispersion), ntohl(ntp.root_delay));
  506. #endif
  507. sntp_dosend();
  508. }
  509. #ifdef LUA_USE_MODULES_RTCTIME
  510. static int sntp_setoffset(lua_State *L)
  511. {
  512. the_offset = luaL_checkinteger(L, 1);
  513. struct rtc_timeval tv;
  514. rtctime_gettimeofday (&tv);
  515. if (tv.tv_sec) {
  516. next_midnight = get_next_midnight(tv.tv_sec);
  517. }
  518. using_offset = 1;
  519. return 0;
  520. }
  521. static int sntp_getoffset(lua_State *L)
  522. {
  523. update_offset();
  524. lua_pushnumber(L, the_offset);
  525. return 1;
  526. }
  527. #endif
  528. static void sntp_dolookups (lua_State *L) {
  529. // Step through each element of the table, converting it to an address
  530. // at the end, start the lookups. If we have already looked everything up,
  531. // then move straight to sending the packets.
  532. if (state->list_ref == LUA_NOREF) {
  533. sntp_dosend();
  534. return;
  535. }
  536. lua_rawgeti(L, LUA_REGISTRYINDEX, state->list_ref);
  537. while (1) {
  538. int l;
  539. if (lua_objlen(L, -1) <= state->lookup_pos) {
  540. // We reached the end
  541. if (server_count == 0) {
  542. // Oh dear -- no valid entries -- generate an error
  543. // This means that all the arguments are invalid. Just pick the first
  544. lua_rawgeti(L, -1, 1);
  545. const char *hostname = luaL_checklstring(L, -1, &l);
  546. handle_error(L, NTP_DNS_ERR, hostname);
  547. lua_pop(L, 1);
  548. } else {
  549. sntp_dosend();
  550. }
  551. break;
  552. }
  553. state->lookup_pos++;
  554. lua_rawgeti(L, -1, state->lookup_pos);
  555. const char *hostname = luaL_checklstring(L, -1, &l);
  556. lua_pop(L, 1);
  557. if (l>128 || hostname == NULL) {
  558. handle_error(L, NTP_DNS_ERR, hostname);
  559. break;
  560. }
  561. err_t err = dns_gethostbyname(hostname, get_free_server(), sntp_dns_found, state);
  562. if (err == ERR_INPROGRESS)
  563. break; // Callback function sntp_dns_found will handle sntp_dosend for us
  564. else if (err == ERR_ARG) {
  565. handle_error(L, NTP_DNS_ERR, hostname);
  566. break;
  567. }
  568. server_count++;
  569. }
  570. lua_pop(L, 1);
  571. }
  572. static char *state_init(lua_State *L) {
  573. state = (sntp_state_t *)c_malloc (sizeof (sntp_state_t));
  574. if (!state)
  575. return ("out of memory");
  576. memset (state, 0, sizeof (sntp_state_t));
  577. state->sync_cb_ref = LUA_NOREF;
  578. state->err_cb_ref = LUA_NOREF;
  579. state->list_ref = LUA_NOREF;
  580. state->pcb = udp_new ();
  581. if (!state->pcb)
  582. return ("out of memory");
  583. if (udp_bind (state->pcb, IP_ADDR_ANY, 0) != ERR_OK)
  584. return ("no port available");
  585. udp_recv (state->pcb, on_recv, L);
  586. state->server_pos = -1;
  587. state->last_server_pos = -1;
  588. return NULL;
  589. }
  590. static char *set_repeat_mode(lua_State *L, bool enable)
  591. {
  592. if (enable) {
  593. set_repeat_mode(L, FALSE);
  594. repeat = (sntp_repeat_t *) c_malloc(sizeof(sntp_repeat_t));
  595. if (!repeat) {
  596. return "no memory";
  597. }
  598. memset(repeat, 0, sizeof(repeat));
  599. lua_rawgeti(L, LUA_REGISTRYINDEX, state->sync_cb_ref);
  600. repeat->sync_cb_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  601. lua_rawgeti(L, LUA_REGISTRYINDEX, state->err_cb_ref);
  602. repeat->err_cb_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  603. lua_rawgeti(L, LUA_REGISTRYINDEX, state->list_ref);
  604. repeat->list_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  605. os_timer_setfn(&repeat->timer, on_long_timeout, NULL);
  606. os_timer_arm(&repeat->timer, 1000 * 1000, 1);
  607. } else {
  608. if (repeat) {
  609. os_timer_disarm (&repeat->timer);
  610. luaL_unref (L, LUA_REGISTRYINDEX, repeat->sync_cb_ref);
  611. luaL_unref (L, LUA_REGISTRYINDEX, repeat->err_cb_ref);
  612. luaL_unref (L, LUA_REGISTRYINDEX, repeat->list_ref);
  613. c_free(repeat);
  614. repeat = NULL;
  615. }
  616. }
  617. return NULL;
  618. }
  619. static void on_long_timeout (void *arg)
  620. {
  621. (void)arg;
  622. sntp_dbg("sntp: long timer\n");
  623. lua_State *L = lua_getstate ();
  624. if (!state) {
  625. if (!state_init(L)) {
  626. // Good.
  627. lua_rawgeti(L, LUA_REGISTRYINDEX, repeat->sync_cb_ref);
  628. state->sync_cb_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  629. lua_rawgeti(L, LUA_REGISTRYINDEX, repeat->err_cb_ref);
  630. state->err_cb_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  631. if (server_count == 0) {
  632. lua_rawgeti(L, LUA_REGISTRYINDEX, repeat->list_ref);
  633. state->list_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  634. }
  635. state->is_on_timeout = 1;
  636. sntp_dolookups(L);
  637. }
  638. }
  639. }
  640. // sntp.sync (server or nil, syncfn or nil, errfn or nil)
  641. static int sntp_sync (lua_State *L)
  642. {
  643. set_repeat_mode(L, 0);
  644. const char *errmsg = 0;
  645. #define sync_err(x) do { errmsg = x; goto error; } while (0)
  646. if (state)
  647. return luaL_error (L, "sync in progress");
  648. char *state_err;
  649. state_err = state_init(L);
  650. if (state_err) {
  651. sync_err(state_err);
  652. }
  653. if (!lua_isnoneornil (L, 2))
  654. {
  655. lua_pushvalue (L, 2);
  656. state->sync_cb_ref = luaL_ref (L, LUA_REGISTRYINDEX);
  657. }
  658. if (!lua_isnoneornil (L, 3))
  659. {
  660. lua_pushvalue (L, 3);
  661. state->err_cb_ref = luaL_ref (L, LUA_REGISTRYINDEX);
  662. }
  663. // use last server, unless new one specified
  664. if (!lua_isnoneornil (L, 1))
  665. {
  666. server_count = 0;
  667. if (lua_istable(L, 1)) {
  668. // Save a reference to the table
  669. lua_pushvalue(L, 1);
  670. luaL_unref (L, LUA_REGISTRYINDEX, state->list_ref);
  671. state->list_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  672. sntp_dolookups(L);
  673. goto good_ret;
  674. } else {
  675. size_t l;
  676. const char *hostname = luaL_checklstring(L, 1, &l);
  677. if (l>128 || hostname == NULL)
  678. sync_err("need <128 hostname");
  679. err_t err = dns_gethostbyname(hostname, get_free_server(), sntp_dns_found, state);
  680. if (err == ERR_INPROGRESS) {
  681. goto good_ret;
  682. } else if (err == ERR_ARG)
  683. sync_err("bad hostname");
  684. server_count++;
  685. }
  686. } else if (server_count == 0) {
  687. // default to ntp pool
  688. lua_newtable(L);
  689. int i;
  690. for (i = 0; i < 4; i++) {
  691. lua_pushnumber(L, i + 1);
  692. char buf[64];
  693. c_sprintf(buf, "%d.nodemcu.pool.ntp.org", i);
  694. lua_pushstring(L, buf);
  695. lua_settable(L, -3);
  696. }
  697. luaL_unref (L, LUA_REGISTRYINDEX, state->list_ref);
  698. state->list_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  699. sntp_dolookups(L);
  700. goto good_ret;
  701. }
  702. sntp_dosend ();
  703. good_ret:
  704. if (!lua_isnoneornil(L, 4)) {
  705. set_repeat_mode(L, 1);
  706. }
  707. return 0;
  708. error:
  709. if (state)
  710. {
  711. if (state->pcb)
  712. udp_remove (state->pcb);
  713. c_free (state);
  714. state = 0;
  715. }
  716. return luaL_error (L, errmsg);
  717. }
  718. static void sntp_task(os_param_t param, uint8_t prio)
  719. {
  720. (void) param;
  721. (void) prio;
  722. lua_State *L = lua_getstate();
  723. if (param == SNTP_HANDLE_RESULT_ID) {
  724. sntp_handle_result(L);
  725. } else if (param == SNTP_DOLOOKUPS_ID) {
  726. sntp_dolookups(L);
  727. } else {
  728. handle_error(L, param, NULL);
  729. }
  730. }
  731. static int sntp_open(lua_State *L)
  732. {
  733. (void) L;
  734. tasknumber = task_get_id(sntp_task);
  735. return 0;
  736. }
  737. // Module function map
  738. static const LUA_REG_TYPE sntp_map[] = {
  739. { LSTRKEY("sync"), LFUNCVAL(sntp_sync) },
  740. #ifdef LUA_USE_MODULES_RTCTIME
  741. { LSTRKEY("setoffset"), LFUNCVAL(sntp_setoffset) },
  742. { LSTRKEY("getoffset"), LFUNCVAL(sntp_getoffset) },
  743. #endif
  744. { LNILKEY, LNILVAL }
  745. };
  746. NODEMCU_MODULE(SNTP, "sntp", sntp_map, sntp_open);