sntp.c 25 KB

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