sntp.c 23 KB

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