sntp.c 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 NTP_PORT 123
  47. #define NTP_ANYCAST_ADDR(dst) IP4_ADDR(dst, 224, 0, 1, 1)
  48. #define MAX_ATTEMPTS 5
  49. #if 0
  50. # define sntp_dbg(...) dbg_printf(__VA_ARGS__)
  51. #else
  52. # define sntp_dbg(...)
  53. #endif
  54. typedef enum {
  55. NTP_NO_ERR = 0,
  56. NTP_DNS_ERR,
  57. NTP_MEM_ERR,
  58. NTP_SEND_ERR,
  59. NTP_TIMEOUT_ERR
  60. } ntp_err_t;
  61. typedef struct
  62. {
  63. uint32_t sec;
  64. uint32_t frac;
  65. } ntp_timestamp_t;
  66. typedef struct
  67. {
  68. uint8_t mode : 3;
  69. uint8_t ver : 3;
  70. uint8_t LI : 2;
  71. uint8_t stratum;
  72. uint8_t poll;
  73. uint8_t precision;
  74. uint32_t root_delay;
  75. uint32_t root_dispersion;
  76. uint32_t refid;
  77. ntp_timestamp_t ref;
  78. ntp_timestamp_t origin;
  79. ntp_timestamp_t recv;
  80. ntp_timestamp_t xmit;
  81. } ntp_frame_t;
  82. typedef struct
  83. {
  84. struct udp_pcb *pcb;
  85. ntp_timestamp_t cookie;
  86. os_timer_t timer;
  87. int sync_cb_ref;
  88. int err_cb_ref;
  89. uint8_t attempts;
  90. } sntp_state_t;
  91. static sntp_state_t *state;
  92. static ip_addr_t server;
  93. static void on_timeout (void *arg);
  94. static void cleanup (lua_State *L)
  95. {
  96. os_timer_disarm (&state->timer);
  97. udp_remove (state->pcb);
  98. luaL_unref (L, LUA_REGISTRYINDEX, state->sync_cb_ref);
  99. luaL_unref (L, LUA_REGISTRYINDEX, state->err_cb_ref);
  100. os_free (state);
  101. state = 0;
  102. }
  103. static void handle_error (lua_State *L, ntp_err_t err)
  104. {
  105. sntp_dbg("sntp: handle_error\n");
  106. if (state->err_cb_ref != LUA_NOREF)
  107. {
  108. lua_rawgeti (L, LUA_REGISTRYINDEX, state->err_cb_ref);
  109. lua_pushinteger (L, err);
  110. cleanup (L);
  111. lua_call (L, 1, 0);
  112. }
  113. else
  114. cleanup (L);
  115. }
  116. static void sntp_dosend (lua_State *L)
  117. {
  118. if (state->attempts == 0)
  119. {
  120. os_timer_disarm (&state->timer);
  121. os_timer_setfn (&state->timer, on_timeout, NULL);
  122. os_timer_arm (&state->timer, 1000, 1);
  123. }
  124. ++state->attempts;
  125. sntp_dbg("sntp: attempt %d\n", state->attempts);
  126. struct pbuf *p = pbuf_alloc (PBUF_TRANSPORT, sizeof (ntp_frame_t), PBUF_RAM);
  127. if (!p)
  128. handle_error (L, NTP_MEM_ERR);
  129. ntp_frame_t req;
  130. os_memset (&req, 0, sizeof (req));
  131. req.ver = 4;
  132. req.mode = 3; // client
  133. #ifdef LUA_USE_MODULES_RTCTIME
  134. struct rtc_timeval tv;
  135. rtctime_gettimeofday (&tv);
  136. req.xmit.sec = htonl (tv.tv_sec);
  137. req.xmit.frac = htonl (tv.tv_usec);
  138. #else
  139. req.xmit.frac = htonl (system_get_time ());
  140. #endif
  141. state->cookie = req.xmit;
  142. os_memcpy (p->payload, &req, sizeof (req));
  143. int ret = udp_sendto (state->pcb, p, &server, NTP_PORT);
  144. sntp_dbg("sntp: send: %d\n", ret);
  145. pbuf_free (p);
  146. if (ret != ERR_OK)
  147. handle_error (L, NTP_SEND_ERR);
  148. }
  149. static void sntp_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
  150. {
  151. (void)arg;
  152. lua_State *L = lua_getstate ();
  153. if (ipaddr == NULL)
  154. {
  155. sntp_dbg("DNS Fail!\n");
  156. handle_error(L, NTP_DNS_ERR);
  157. }
  158. else
  159. {
  160. server = *ipaddr;
  161. sntp_dosend(L);
  162. }
  163. }
  164. static void on_timeout (void *arg)
  165. {
  166. (void)arg;
  167. sntp_dbg("sntp: timer\n");
  168. lua_State *L = lua_getstate ();
  169. if (state->attempts >= MAX_ATTEMPTS)
  170. handle_error (L, NTP_TIMEOUT_ERR);
  171. else
  172. sntp_dosend (L);
  173. }
  174. static void on_recv (void *arg, struct udp_pcb *pcb, struct pbuf *p, struct ip_addr *addr, uint16_t port)
  175. {
  176. (void)port;
  177. sntp_dbg("sntp: on_recv\n");
  178. lua_State *L = lua_getstate();
  179. if (!state || state->pcb != pcb)
  180. {
  181. // "impossible", but don't leak if it did happen somehow...
  182. udp_remove (pcb);
  183. pbuf_free (p);
  184. return;
  185. }
  186. if (!p)
  187. return;
  188. if (p->len < sizeof (ntp_frame_t))
  189. {
  190. pbuf_free (p);
  191. return; // not an ntp frame, ignore
  192. }
  193. // make sure we have an aligned copy to work from
  194. ntp_frame_t ntp;
  195. os_memcpy (&ntp, p->payload, sizeof (ntp));
  196. pbuf_free (p);
  197. sntp_dbg("sntp: transmit timestamp: %u, %u\n", ntp.xmit.sec, ntp.xmit.frac);
  198. // sanity checks before we touch our clocks
  199. ip_addr_t anycast;
  200. NTP_ANYCAST_ADDR(&anycast);
  201. if (server.addr != anycast.addr && server.addr != addr->addr)
  202. return; // unknown sender, ignore
  203. if (ntp.origin.sec != state->cookie.sec ||
  204. ntp.origin.frac != state->cookie.frac)
  205. return; // unsolicited message, ignore
  206. if (ntp.LI == 3)
  207. return; // server clock not synchronized (why did it even respond?!)
  208. server.addr = addr->addr;
  209. ntp.origin.sec = ntohl (ntp.origin.sec);
  210. ntp.origin.frac = ntohl (ntp.origin.frac);
  211. ntp.recv.sec = ntohl (ntp.recv.sec);
  212. ntp.recv.frac = ntohl (ntp.recv.frac);
  213. ntp.xmit.sec = ntohl (ntp.xmit.sec);
  214. ntp.xmit.frac = ntohl (ntp.xmit.frac);
  215. const uint32_t UINT32_MAXI = (uint32_t)-1;
  216. const uint64_t MICROSECONDS = 1000000ull;
  217. const uint32_t NTP_TO_UNIX_EPOCH = 2208988800ul;
  218. bool have_cb = (state->sync_cb_ref != LUA_NOREF);
  219. // if we have rtctime, do higher resolution delta calc, else just use
  220. // the transmit timestamp
  221. #ifdef LUA_USE_MODULES_RTCTIME
  222. struct rtc_timeval tv;
  223. rtctime_gettimeofday (&tv);
  224. ntp_timestamp_t dest;
  225. dest.sec = tv.tv_sec;
  226. dest.frac = (MICROSECONDS * tv.tv_usec) / UINT32_MAXI;
  227. // Compensation as per RFC2030
  228. int64_t delta_s = (((int64_t)ntp.recv.sec - ntp.origin.sec) +
  229. ((int64_t)ntp.xmit.sec - dest.sec)) / 2;
  230. int64_t delta_f = (((int64_t)ntp.recv.frac - ntp.origin.frac) +
  231. ((int64_t)ntp.xmit.frac - dest.frac)) / 2;
  232. dest.sec += delta_s;
  233. if (delta_f + dest.frac < 0)
  234. {
  235. delta_f += UINT32_MAXI;
  236. --dest.sec;
  237. }
  238. else if (delta_f + dest.frac > UINT32_MAXI)
  239. {
  240. delta_f -= UINT32_MAXI;
  241. ++dest.sec;
  242. }
  243. dest.frac += delta_f;
  244. tv.tv_sec = dest.sec - NTP_TO_UNIX_EPOCH;
  245. tv.tv_usec = (MICROSECONDS * dest.frac) / UINT32_MAXI;
  246. rtctime_settimeofday (&tv);
  247. if (have_cb)
  248. {
  249. lua_rawgeti (L, LUA_REGISTRYINDEX, state->sync_cb_ref);
  250. lua_pushnumber (L, tv.tv_sec);
  251. lua_pushnumber (L, tv.tv_usec);
  252. }
  253. #else
  254. if (have_cb)
  255. {
  256. lua_rawgeti (L, LUA_REGISTRYINDEX, state->sync_cb_ref);
  257. lua_pushnumber (L, ntp.xmit.sec - NTP_TO_UNIX_EPOCH);
  258. lua_pushnumber (L, (MICROSECONDS * ntp.xmit.frac) / UINT32_MAXI);
  259. }
  260. #endif
  261. cleanup (L);
  262. if (have_cb)
  263. {
  264. lua_pushstring (L, ipaddr_ntoa (&server));
  265. lua_call (L, 3, 0);
  266. }
  267. }
  268. // sntp.sync (server or nil, syncfn or nil, errfn or nil)
  269. static int sntp_sync (lua_State *L)
  270. {
  271. // default to anycast address, then allow last server to stick
  272. if (server.addr == IPADDR_ANY)
  273. NTP_ANYCAST_ADDR(&server);
  274. const char *errmsg = 0;
  275. #define sync_err(x) do { errmsg = x; goto error; } while (0)
  276. if (state)
  277. return luaL_error (L, "sync in progress");
  278. state = (sntp_state_t *)c_malloc (sizeof (sntp_state_t));
  279. if (!state)
  280. sync_err ("out of memory");
  281. memset (state, 0, sizeof (sntp_state_t));
  282. state->sync_cb_ref = LUA_NOREF;
  283. state->err_cb_ref = LUA_NOREF;
  284. state->pcb = udp_new ();
  285. if (!state->pcb)
  286. sync_err ("out of memory");
  287. if (udp_bind (state->pcb, IP_ADDR_ANY, 0) != ERR_OK)
  288. sync_err ("no port available");
  289. udp_recv (state->pcb, on_recv, L);
  290. if (!lua_isnoneornil (L, 2))
  291. {
  292. lua_pushvalue (L, 2);
  293. state->sync_cb_ref = luaL_ref (L, LUA_REGISTRYINDEX);
  294. }
  295. else
  296. state->sync_cb_ref = LUA_NOREF;
  297. if (!lua_isnoneornil (L, 3))
  298. {
  299. lua_pushvalue (L, 3);
  300. state->err_cb_ref = luaL_ref (L, LUA_REGISTRYINDEX);
  301. }
  302. else
  303. state->err_cb_ref = LUA_NOREF;
  304. state->attempts = 0;
  305. // use last server, unless new one specified
  306. if (!lua_isnoneornil (L, 1))
  307. {
  308. size_t l;
  309. const char *hostname = luaL_checklstring(L, 1, &l);
  310. if (l>128 || hostname == NULL)
  311. sync_err("need <128 hostname");
  312. err_t err = dns_gethostbyname(hostname, &server, sntp_dns_found, state);
  313. if (err == ERR_INPROGRESS)
  314. return 0; // Callback function sntp_dns_found will handle sntp_dosend for us
  315. else if (err == ERR_ARG)
  316. sync_err("bad hostname");
  317. }
  318. sntp_dosend (L);
  319. return 0;
  320. error:
  321. if (state)
  322. {
  323. if (state->pcb)
  324. udp_remove (state->pcb);
  325. c_free (state);
  326. state = 0;
  327. }
  328. return luaL_error (L, errmsg);
  329. }
  330. // Module function map
  331. static const LUA_REG_TYPE sntp_map[] = {
  332. { LSTRKEY("sync"), LFUNCVAL(sntp_sync) },
  333. { LNILKEY, LNILVAL }
  334. };
  335. NODEMCU_MODULE(SNTP, "sntp", sntp_map, NULL);