Pārlūkot izejas kodu

Fixed race-crash in SNTP module.

Johny Mattsson 8 gadi atpakaļ
vecāks
revīzija
d3bfdf3ac8
1 mainītis faili ar 15 papildinājumiem un 7 dzēšanām
  1. 15 7
      app/modules/sntp.c

+ 15 - 7
app/modules/sntp.c

@@ -94,6 +94,8 @@ typedef struct
 static sntp_state_t *state;
 static ip_addr_t server;
 
+static void on_timeout (void *arg);
+
 static void cleanup (lua_State *L)
 {
   os_timer_disarm (&state->timer);
@@ -121,6 +123,13 @@ static void handle_error (lua_State *L)
 
 static void sntp_dosend (lua_State *L)
 {
+  if (state->attempts == 0)
+  {
+    os_timer_disarm (&state->timer);
+    os_timer_setfn (&state->timer, on_timeout, NULL);
+    os_timer_arm (&state->timer, 1000, 1);
+  }
+
   ++state->attempts;
   sntp_dbg("sntp: attempt %d\n", state->attempts);
 
@@ -153,7 +162,9 @@ static void sntp_dosend (lua_State *L)
 
 static void sntp_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
 {
-  lua_State *L = arg;
+  (void)arg;
+
+  lua_State *L = lua_getstate ();
   if (ipaddr == NULL)
   {
     NODE_ERR("DNS Fail!\n");
@@ -169,8 +180,9 @@ static void sntp_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
 
 static void on_timeout (void *arg)
 {
+  (void)arg;
   sntp_dbg("sntp: timer\n");
-  lua_State *L = arg;
+  lua_State *L = lua_getstate ();
   if (state->attempts >= MAX_ATTEMPTS)
     handle_error (L);
   else
@@ -341,10 +353,6 @@ static int sntp_sync (lua_State *L)
   else
     state->err_cb_ref = LUA_NOREF;
 
-  os_timer_disarm (&state->timer);
-  os_timer_setfn (&state->timer, on_timeout, L);
-  os_timer_arm (&state->timer, 1000, 1);
-
   state->attempts = 0;
 
   // use last server, unless new one specified
@@ -354,7 +362,7 @@ static int sntp_sync (lua_State *L)
     const char *hostname = luaL_checklstring(L, 1, &l);
     if (l>128 || hostname == NULL)
       sync_err("need <128 hostname");
-    err_t err = dns_gethostbyname(hostname, &server, sntp_dns_found, &L);
+    err_t err = dns_gethostbyname(hostname, &server, sntp_dns_found, state);
     if (err == ERR_INPROGRESS)
       return 0;  // Callback function sntp_dns_found will handle sntp_dosend for us
     else if (err == ERR_ARG)