sntp.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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 "user_interface.h"
  43. #ifdef LUA_USE_MODULES_RTCTIME
  44. #include "rtc/rtctime.h"
  45. #endif
  46. #define max(a,b) ((a < b) ? b : a)
  47. #define NTP_PORT 123
  48. #define NTP_ANYCAST_ADDR(dst) IP4_ADDR(dst, 224, 0, 1, 1)
  49. #define MAX_ATTEMPTS 5
  50. #if 0
  51. # define sntp_dbg(...) dbg_printf(__VA_ARGS__)
  52. #else
  53. # define sntp_dbg(...)
  54. #endif
  55. #define US_TO_FRAC(us) ((((uint64_t) (us)) << 32) / 1000000)
  56. #define SUS_TO_FRAC(us) ((((int64_t) (us)) << 32) / 1000000)
  57. #define US_TO_FRAC16(us) ((((uint64_t) (us)) << 16) / 1000000)
  58. #define FRAC16_TO_US(frac) ((((uint64_t) (frac)) * 1000000) >> 16)
  59. typedef enum {
  60. NTP_NO_ERR = 0,
  61. NTP_DNS_ERR,
  62. NTP_MEM_ERR,
  63. NTP_SEND_ERR,
  64. NTP_TIMEOUT_ERR
  65. } ntp_err_t;
  66. typedef struct
  67. {
  68. uint32_t sec;
  69. uint32_t frac;
  70. } ntp_timestamp_t;
  71. typedef struct
  72. {
  73. uint8_t mode : 3;
  74. uint8_t ver : 3;
  75. uint8_t LI : 2;
  76. uint8_t stratum;
  77. uint8_t poll;
  78. uint8_t precision;
  79. uint32_t root_delay;
  80. uint32_t root_dispersion;
  81. uint32_t refid;
  82. ntp_timestamp_t ref;
  83. ntp_timestamp_t origin;
  84. ntp_timestamp_t recv;
  85. ntp_timestamp_t xmit;
  86. } ntp_frame_t;
  87. typedef struct
  88. {
  89. struct udp_pcb *pcb;
  90. ntp_timestamp_t cookie;
  91. os_timer_t timer;
  92. int sync_cb_ref;
  93. int err_cb_ref;
  94. uint8_t attempts; // Number of repeats of each entry
  95. uint8_t server_index; // index into server table
  96. uint8_t lookup_pos;
  97. bool is_on_timeout;
  98. int server_pos;
  99. int list_ref;
  100. struct {
  101. uint32_t delay_frac;
  102. uint32_t root_maxerr;
  103. uint32_t root_delay;
  104. uint32_t root_dispersion;
  105. uint8_t LI;
  106. uint8_t stratum;
  107. int when;
  108. int64_t delta;
  109. ip_addr_t server;
  110. } best;
  111. } sntp_state_t;
  112. typedef struct {
  113. int32_t sync_cb_ref;
  114. int32_t err_cb_ref;
  115. os_timer_t timer;
  116. } sntp_repeat_t;
  117. static sntp_state_t *state;
  118. static sntp_repeat_t *repeat;
  119. static ip_addr_t *serverp;
  120. static uint8_t server_count;
  121. static uint8_t using_offset;
  122. static uint8_t the_offset;
  123. static uint8_t pending_LI;
  124. static int32_t next_midnight;
  125. static uint64_t pll_increment;
  126. #define PLL_A (1 << (32 - 11))
  127. #define PLL_B (1 << (32 - 11 - 2))
  128. static void on_timeout(void *arg);
  129. static void on_long_timeout(void *arg);
  130. static void sntp_dolookups(lua_State *L);
  131. static void cleanup (lua_State *L)
  132. {
  133. os_timer_disarm (&state->timer);
  134. udp_remove (state->pcb);
  135. luaL_unref (L, LUA_REGISTRYINDEX, state->sync_cb_ref);
  136. luaL_unref (L, LUA_REGISTRYINDEX, state->err_cb_ref);
  137. luaL_unref (L, LUA_REGISTRYINDEX, state->list_ref);
  138. os_free (state);
  139. state = 0;
  140. }
  141. static ip_addr_t* get_free_server() {
  142. ip_addr_t* temp = (ip_addr_t *) c_malloc((server_count + 1) * sizeof(ip_addr_t));
  143. if (server_count > 0) {
  144. memcpy(temp, serverp, server_count * sizeof(ip_addr_t));
  145. }
  146. if (serverp) {
  147. c_free(serverp);
  148. }
  149. serverp = temp;
  150. return serverp + server_count;
  151. }
  152. static void handle_error (lua_State *L, ntp_err_t err, const char *msg)
  153. {
  154. sntp_dbg("sntp: handle_error\n");
  155. if (state->err_cb_ref != LUA_NOREF)
  156. {
  157. lua_rawgeti (L, LUA_REGISTRYINDEX, state->err_cb_ref);
  158. lua_pushinteger (L, err);
  159. lua_pushstring (L, msg);
  160. cleanup (L);
  161. lua_call (L, 2, 0);
  162. }
  163. else
  164. cleanup (L);
  165. }
  166. #ifdef LUA_USE_MODULES_RTCTIME
  167. static void get_zero_base_timeofday(struct rtc_timeval *tv) {
  168. uint32_t now = system_get_time();
  169. tv->tv_sec = now / 1000000;
  170. tv->tv_usec = now % 1000000;
  171. }
  172. #endif
  173. static void sntp_handle_result(lua_State *L) {
  174. const uint32_t MICROSECONDS = 1000000;
  175. if (state->best.stratum == 0) {
  176. handle_error(L, NTP_TIMEOUT_ERR, NULL);
  177. return;
  178. }
  179. bool have_cb = (state->sync_cb_ref != LUA_NOREF);
  180. // if we have rtctime, do higher resolution delta calc, else just use
  181. // the transmit timestamp
  182. #ifdef LUA_USE_MODULES_RTCTIME
  183. struct rtc_timeval tv;
  184. rtctime_gettimeofday (&tv);
  185. if (tv.tv_sec == 0) {
  186. get_zero_base_timeofday(&tv);
  187. }
  188. tv.tv_sec += (int)(state->best.delta >> 32);
  189. tv.tv_usec += (int) ((MICROSECONDS * (state->best.delta & 0xffffffff)) >> 32);
  190. while (tv.tv_usec >= 1000000) {
  191. tv.tv_usec -= 1000000;
  192. tv.tv_sec++;
  193. }
  194. if (state->is_on_timeout && state->best.delta > SUS_TO_FRAC(-200000) && state->best.delta < SUS_TO_FRAC(200000)) {
  195. // Adjust rate
  196. // f is frequency -- f should be 1 << 32 for nominal
  197. sntp_dbg("delta=%d, increment=%d, ", (int32_t) state->best.delta, (int32_t) pll_increment);
  198. int64_t f = ((state->best.delta * PLL_A) >> 32) + pll_increment;
  199. pll_increment += (state->best.delta * PLL_B) >> 32;
  200. sntp_dbg("f=%d, increment=%d\n", (int32_t) f, (int32_t) pll_increment);
  201. //rtctime_adjust_rate((int32_t) f);
  202. } else {
  203. rtctime_settimeofday (&tv);
  204. }
  205. #endif
  206. if (have_cb)
  207. {
  208. lua_rawgeti(L, LUA_REGISTRYINDEX, state->sync_cb_ref);
  209. #ifdef LUA_USE_MODULES_RTCTIME
  210. lua_pushnumber(L, tv.tv_sec);
  211. lua_pushnumber(L, tv.tv_usec);
  212. lua_pushstring(L, ipaddr_ntoa (&state->best.server));
  213. lua_newtable(L);
  214. int d40 = state->best.delta >> 40;
  215. if (d40 != 0 && d40 != -1) {
  216. lua_pushnumber(L, state->best.delta >> 32);
  217. lua_setfield(L, -2, "offset_s");
  218. } else {
  219. lua_pushnumber(L, (state->best.delta * MICROSECONDS) >> 32);
  220. lua_setfield(L, -2, "offset_us");
  221. }
  222. #else
  223. int adjust_us = system_get_time() - state->best.when;
  224. int tv_sec = state->best.delta >> 32;
  225. int tv_usec = (int) (((state->best.delta & 0xffffffff) * MICROSECONDS) >> 32) + adjust_us;
  226. while (tv_usec >= 1000000) {
  227. tv_usec -= 1000000;
  228. tv_sec++;
  229. }
  230. lua_pushnumber(L, tv_sec);
  231. lua_pushnumber(L, tv_usec);
  232. lua_pushstring(L, ipaddr_ntoa (&state->best.server));
  233. lua_newtable(L);
  234. #endif
  235. if (state->best.delay_frac > 0) {
  236. lua_pushnumber(L, FRAC16_TO_US(state->best.delay_frac));
  237. lua_setfield(L, -2, "delay_us");
  238. }
  239. lua_pushnumber(L, FRAC16_TO_US(state->best.root_delay));
  240. lua_setfield(L, -2, "root_delay_us");
  241. lua_pushnumber(L, FRAC16_TO_US(state->best.root_dispersion));
  242. lua_setfield(L, -2, "root_dispersion_us");
  243. lua_pushnumber(L, FRAC16_TO_US(state->best.root_maxerr + state->best.delay_frac / 2));
  244. lua_setfield(L, -2, "root_maxerr_us");
  245. lua_pushnumber(L, state->best.stratum);
  246. lua_setfield(L, -2, "stratum");
  247. lua_pushnumber(L, state->best.LI);
  248. lua_setfield(L, -2, "leap");
  249. lua_pushnumber(L, pending_LI);
  250. lua_setfield(L, -2, "pending_leap");
  251. }
  252. cleanup (L);
  253. if (have_cb)
  254. {
  255. lua_call (L, 4, 0);
  256. }
  257. }
  258. static void sntp_dosend (lua_State *L)
  259. {
  260. if (state->server_pos < 0) {
  261. os_timer_disarm(&state->timer);
  262. os_timer_setfn(&state->timer, on_timeout, NULL);
  263. state->server_pos = 0;
  264. } else {
  265. ++state->server_pos;
  266. }
  267. if (state->server_pos >= server_count) {
  268. state->server_pos = 0;
  269. ++state->attempts;
  270. }
  271. if (state->attempts >= MAX_ATTEMPTS || state->attempts * server_count > 10) {
  272. sntp_handle_result(L);
  273. return;
  274. }
  275. sntp_dbg("sntp: server %s (%d), attempt %d\n", ipaddr_ntoa(serverp + state->server_pos), state->server_pos, state->attempts);
  276. struct pbuf *p = pbuf_alloc (PBUF_TRANSPORT, sizeof (ntp_frame_t), PBUF_RAM);
  277. if (!p)
  278. handle_error (L, NTP_MEM_ERR, NULL);
  279. ntp_frame_t req;
  280. os_memset (&req, 0, sizeof (req));
  281. req.ver = 4;
  282. req.mode = 3; // client
  283. #ifdef LUA_USE_MODULES_RTCTIME
  284. const uint32_t NTP_TO_UNIX_EPOCH = 2208988800ul;
  285. struct rtc_timeval tv;
  286. rtctime_gettimeofday (&tv);
  287. if (tv.tv_sec == 0) {
  288. get_zero_base_timeofday(&tv);
  289. }
  290. req.xmit.sec = htonl (tv.tv_sec - the_offset + NTP_TO_UNIX_EPOCH);
  291. req.xmit.frac = htonl (US_TO_FRAC(tv.tv_usec));
  292. #else
  293. req.xmit.frac = htonl (system_get_time ());
  294. #endif
  295. state->cookie = req.xmit;
  296. os_memcpy (p->payload, &req, sizeof (req));
  297. int ret = udp_sendto (state->pcb, p, serverp + state->server_pos, NTP_PORT);
  298. sntp_dbg("sntp: send: %d\n", ret);
  299. pbuf_free (p);
  300. if (ret != ERR_OK)
  301. handle_error (L, NTP_SEND_ERR, NULL);
  302. os_timer_arm (&state->timer, 1000, 0);
  303. }
  304. static void sntp_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
  305. {
  306. (void)arg;
  307. lua_State *L = lua_getstate ();
  308. if (ipaddr == NULL)
  309. {
  310. sntp_dbg("DNS Fail!\n");
  311. handle_error(L, NTP_DNS_ERR, name);
  312. }
  313. else
  314. {
  315. serverp[server_count] = *ipaddr;
  316. server_count++;
  317. sntp_dolookups(L);
  318. }
  319. }
  320. static void on_timeout (void *arg)
  321. {
  322. (void)arg;
  323. sntp_dbg("sntp: timer\n");
  324. lua_State *L = lua_getstate ();
  325. sntp_dosend (L);
  326. }
  327. static void update_offset()
  328. {
  329. // This may insert or remove an offset second -- i.e. a leap second
  330. // This can only happen if it is at midnight UTC.
  331. #ifdef LUA_USE_MODULES_RTCTIME
  332. struct rtc_timeval tv;
  333. if (pending_LI && using_offset) {
  334. rtctime_gettimeofday (&tv);
  335. if (tv.tv_sec - the_offset >= next_midnight) {
  336. next_midnight = tv.tv_sec + 86400 - the_offset - (tv.tv_sec - the_offset) % 86400;
  337. // is this the first day of the month
  338. int day = (tv.tv_sec - the_offset) / 86400 + 1975 * 365 + 1970 / 4 - 74;
  339. int century = (4 * day + 3) / 146097;
  340. day = day - century * 146097 / 4;
  341. int year = (4 * day + 3) / 1461;
  342. day = day - year * 1461 / 4;
  343. int month = (5 * day + 2) / 153;
  344. day = day - (153 * month + 2) / 5;
  345. if (day == 0) {
  346. if (pending_LI == 1) {
  347. the_offset ++;
  348. } else {
  349. the_offset --;
  350. }
  351. }
  352. pending_LI = 0;
  353. }
  354. }
  355. #endif
  356. }
  357. static void record_result(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) {
  358. sntp_dbg("Recording %s: delta=%08x.%08x, stratum=%d, li=%d, delay=%dus, root_maxerr=%dus",
  359. 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));
  360. // I want to favor close by servers as they probably have a more consistent clock,
  361. if (!state->best.stratum || root_delay * 2 + delay_frac < state->best.root_delay * 2 + state->best.delay_frac) {
  362. sntp_dbg(" --BEST\n");
  363. state->best.server = *addr;
  364. state->best.delay_frac = delay_frac;
  365. state->best.root_maxerr = root_maxerr;
  366. state->best.root_dispersion = root_dispersion;
  367. state->best.root_delay = root_delay;
  368. state->best.delta = delta;
  369. state->best.stratum = stratum;
  370. state->best.LI = LI;
  371. state->best.when = system_get_time();
  372. } else {
  373. sntp_dbg("\n");
  374. }
  375. }
  376. static void on_recv (void *arg, struct udp_pcb *pcb, struct pbuf *p, struct ip_addr *addr, uint16_t port)
  377. {
  378. (void)port;
  379. #ifdef LUA_USE_MODULES_RTCTIME
  380. // Ideally this would be done when we receive the packet....
  381. struct rtc_timeval tv;
  382. rtctime_gettimeofday (&tv);
  383. if (tv.tv_sec == 0) {
  384. get_zero_base_timeofday(&tv);
  385. }
  386. #endif
  387. sntp_dbg("sntp: on_recv\n");
  388. lua_State *L = lua_getstate();
  389. if (!state || state->pcb != pcb)
  390. {
  391. // "impossible", but don't leak if it did happen somehow...
  392. udp_remove (pcb);
  393. pbuf_free (p);
  394. return;
  395. }
  396. if (!p)
  397. return;
  398. if (p->len < sizeof (ntp_frame_t))
  399. {
  400. pbuf_free (p);
  401. return; // not an ntp frame, ignore
  402. }
  403. // make sure we have an aligned copy to work from
  404. ntp_frame_t ntp;
  405. os_memcpy (&ntp, p->payload, sizeof (ntp));
  406. pbuf_free (p);
  407. sntp_dbg("sntp: transmit timestamp: %u, %u\n", ntp.xmit.sec, ntp.xmit.frac);
  408. // sanity checks before we touch our clocks
  409. ip_addr_t anycast;
  410. NTP_ANYCAST_ADDR(&anycast);
  411. if (serverp[state->server_pos].addr != anycast.addr && serverp[state->server_pos].addr != addr->addr)
  412. return; // unknown sender, ignore
  413. if (ntp.origin.sec != state->cookie.sec ||
  414. ntp.origin.frac != state->cookie.frac)
  415. return; // unsolicited message, ignore
  416. if (ntp.LI == 3)
  417. return; // server clock not synchronized (why did it even respond?!)
  418. os_timer_disarm(&state->timer);
  419. if (ntp.LI) {
  420. pending_LI = ntp.LI;
  421. }
  422. update_offset();
  423. ntp.origin.sec = ntohl (ntp.origin.sec);
  424. ntp.origin.frac = ntohl (ntp.origin.frac);
  425. ntp.recv.sec = ntohl (ntp.recv.sec);
  426. ntp.recv.frac = ntohl (ntp.recv.frac);
  427. ntp.xmit.sec = ntohl (ntp.xmit.sec);
  428. ntp.xmit.frac = ntohl (ntp.xmit.frac);
  429. const uint64_t MICROSECONDS = 1000000ull;
  430. const uint32_t NTP_TO_UNIX_EPOCH = 2208988800ul;
  431. uint32_t root_maxerr = ntohl(ntp.root_dispersion) + ntohl(ntp.root_delay) / 2;
  432. // if we have rtctime, do higher resolution delta calc, else just use
  433. // the transmit timestamp
  434. #ifdef LUA_USE_MODULES_RTCTIME
  435. ntp_timestamp_t dest;
  436. dest.sec = tv.tv_sec + NTP_TO_UNIX_EPOCH - the_offset;
  437. dest.frac = US_TO_FRAC(tv.tv_usec);
  438. uint64_t ntp_recv = (((uint64_t) ntp.recv.sec) << 32) + (uint64_t) ntp.recv.frac;
  439. uint64_t ntp_origin = (((uint64_t) ntp.origin.sec) << 32) + (uint64_t) ntp.origin.frac;
  440. uint64_t ntp_xmit = (((uint64_t) ntp.xmit.sec) << 32) + (uint64_t) ntp.xmit.frac;
  441. uint64_t ntp_dest = (((uint64_t) dest.sec) << 32) + (uint64_t) dest.frac;
  442. // Compensation as per RFC2030
  443. int64_t delta = (int64_t) (ntp_recv - ntp_origin) / 2 + (int64_t) (ntp_xmit - ntp_dest) / 2;
  444. record_result(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));
  445. #else
  446. uint64_t ntp_xmit = (((uint64_t) ntp.xmit.sec - NTP_TO_UNIX_EPOCH) << 32) + (uint64_t) ntp.xmit.frac;
  447. record_result(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));
  448. #endif
  449. sntp_dosend(L);
  450. }
  451. #ifdef LUA_USE_MODULES_RTCTIME
  452. static int sntp_setoffset(lua_State *L)
  453. {
  454. the_offset = luaL_checkinteger(L, 1);
  455. if (!using_offset) {
  456. struct rtc_timeval tv;
  457. rtctime_gettimeofday (&tv);
  458. next_midnight = tv.tv_sec + 86400 - the_offset - (tv.tv_sec - the_offset) % 86400;
  459. }
  460. using_offset = 1;
  461. return 0;
  462. }
  463. static int sntp_getoffset(lua_State *L)
  464. {
  465. update_offset();
  466. lua_pushnumber(L, the_offset);
  467. return 1;
  468. }
  469. #endif
  470. static void sntp_dolookups (lua_State *L) {
  471. // Step through each element of the table, converting it to an address
  472. // at the end, start the lookups
  473. //
  474. if (state->list_ref == LUA_NOREF) {
  475. sntp_dosend(L);
  476. }
  477. lua_rawgeti(L, LUA_REGISTRYINDEX, state->list_ref);
  478. while (1) {
  479. if (lua_objlen(L, -1) <= state->lookup_pos) {
  480. // We reached the end
  481. sntp_dosend(L);
  482. break;
  483. }
  484. state->lookup_pos++;
  485. lua_rawgeti(L, -1, state->lookup_pos);
  486. int l;
  487. const char *hostname = luaL_checklstring(L, -1, &l);
  488. lua_pop(L, 1);
  489. if (l>128 || hostname == NULL) {
  490. handle_error(L, NTP_DNS_ERR, hostname);
  491. break;
  492. }
  493. err_t err = dns_gethostbyname(hostname, get_free_server(), sntp_dns_found, state);
  494. if (err == ERR_INPROGRESS)
  495. break; // Callback function sntp_dns_found will handle sntp_dosend for us
  496. else if (err == ERR_ARG) {
  497. handle_error(L, NTP_DNS_ERR, hostname);
  498. break;
  499. }
  500. server_count++;
  501. }
  502. lua_pop(L, 1);
  503. }
  504. static char *state_init(lua_State *L) {
  505. state = (sntp_state_t *)c_malloc (sizeof (sntp_state_t));
  506. if (!state)
  507. return ("out of memory");
  508. memset (state, 0, sizeof (sntp_state_t));
  509. state->sync_cb_ref = LUA_NOREF;
  510. state->err_cb_ref = LUA_NOREF;
  511. state->list_ref = LUA_NOREF;
  512. state->pcb = udp_new ();
  513. if (!state->pcb)
  514. return ("out of memory");
  515. if (udp_bind (state->pcb, IP_ADDR_ANY, 0) != ERR_OK)
  516. return ("no port available");
  517. udp_recv (state->pcb, on_recv, L);
  518. state->server_pos = -1;
  519. return NULL;
  520. }
  521. static char *set_repeat_mode(lua_State *L, bool enable)
  522. {
  523. if (enable) {
  524. set_repeat_mode(L, FALSE);
  525. repeat = (sntp_repeat_t *) c_malloc(sizeof(sntp_repeat_t));
  526. if (!repeat) {
  527. return "no memory";
  528. }
  529. memset(repeat, 0, sizeof(repeat));
  530. lua_rawgeti(L, LUA_REGISTRYINDEX, state->sync_cb_ref);
  531. repeat->sync_cb_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  532. lua_rawgeti(L, LUA_REGISTRYINDEX, state->err_cb_ref);
  533. repeat->err_cb_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  534. os_timer_setfn(&repeat->timer, on_long_timeout, NULL);
  535. os_timer_arm(&repeat->timer, 1000 * 1000, 1);
  536. } else {
  537. if (repeat) {
  538. os_timer_disarm (&repeat->timer);
  539. luaL_unref (L, LUA_REGISTRYINDEX, repeat->sync_cb_ref);
  540. luaL_unref (L, LUA_REGISTRYINDEX, repeat->err_cb_ref);
  541. c_free(repeat);
  542. repeat = NULL;
  543. }
  544. }
  545. return NULL;
  546. }
  547. static void on_long_timeout (void *arg)
  548. {
  549. (void)arg;
  550. sntp_dbg("sntp: long timer\n");
  551. lua_State *L = lua_getstate ();
  552. if (!state) {
  553. if (!state_init(L)) {
  554. // Good.
  555. lua_rawgeti(L, LUA_REGISTRYINDEX, repeat->sync_cb_ref);
  556. state->sync_cb_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  557. lua_rawgeti(L, LUA_REGISTRYINDEX, repeat->err_cb_ref);
  558. state->err_cb_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  559. state->is_on_timeout = 1;
  560. sntp_dosend (L);
  561. }
  562. }
  563. }
  564. // sntp.sync (server or nil, syncfn or nil, errfn or nil)
  565. static int sntp_sync (lua_State *L)
  566. {
  567. // default to anycast address, then allow last server to stick
  568. if (server_count == 0) {
  569. NTP_ANYCAST_ADDR(get_free_server());
  570. server_count++;
  571. }
  572. set_repeat_mode(L, 0);
  573. const char *errmsg = 0;
  574. #define sync_err(x) do { errmsg = x; goto error; } while (0)
  575. if (state)
  576. return luaL_error (L, "sync in progress");
  577. char *state_err;
  578. state_err = state_init(L);
  579. if (state_err) {
  580. sync_err(state_err);
  581. }
  582. if (!lua_isnoneornil (L, 2))
  583. {
  584. lua_pushvalue (L, 2);
  585. state->sync_cb_ref = luaL_ref (L, LUA_REGISTRYINDEX);
  586. }
  587. if (!lua_isnoneornil (L, 3))
  588. {
  589. lua_pushvalue (L, 3);
  590. state->err_cb_ref = luaL_ref (L, LUA_REGISTRYINDEX);
  591. }
  592. // use last server, unless new one specified
  593. if (!lua_isnoneornil (L, 1))
  594. {
  595. server_count = 0;
  596. if (lua_istable(L, 1)) {
  597. // Save a reference to the table
  598. lua_pushvalue(L, 1);
  599. state->list_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  600. sntp_dolookups(L);
  601. goto good_ret;
  602. } else {
  603. size_t l;
  604. const char *hostname = luaL_checklstring(L, 1, &l);
  605. if (l>128 || hostname == NULL)
  606. sync_err("need <128 hostname");
  607. err_t err = dns_gethostbyname(hostname, get_free_server(), sntp_dns_found, state);
  608. if (err == ERR_INPROGRESS) {
  609. goto good_ret;
  610. } else if (err == ERR_ARG)
  611. sync_err("bad hostname");
  612. server_count++;
  613. }
  614. }
  615. sntp_dosend (L);
  616. good_ret:
  617. if (!lua_isnoneornil(L, 4)) {
  618. set_repeat_mode(L, 1);
  619. }
  620. return 0;
  621. error:
  622. if (state)
  623. {
  624. if (state->pcb)
  625. udp_remove (state->pcb);
  626. c_free (state);
  627. state = 0;
  628. }
  629. return luaL_error (L, errmsg);
  630. }
  631. // Module function map
  632. static const LUA_REG_TYPE sntp_map[] = {
  633. { LSTRKEY("sync"), LFUNCVAL(sntp_sync) },
  634. #ifdef LUA_USE_MODULES_RTCTIME
  635. { LSTRKEY("setoffset"), LFUNCVAL(sntp_setoffset) },
  636. { LSTRKEY("getoffset"), LFUNCVAL(sntp_getoffset) },
  637. #endif
  638. { LNILKEY, LNILVAL }
  639. };
  640. NODEMCU_MODULE(SNTP, "sntp", sntp_map, NULL);