enduser_setup.c 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786
  1. /*
  2. * Copyright 2015 Robert Foss. 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 Robert Foss <dev@robertfoss.se>
  32. *
  33. * Additions & fixes: Johny Mattsson <jmattsson@dius.com.au>
  34. * Jason Follas <jfollas@gmail.com>
  35. */
  36. #include "module.h"
  37. #include "lauxlib.h"
  38. #include "lmem.h"
  39. #include "platform.h"
  40. #include "c_stdlib.h"
  41. #include "c_stdio.h"
  42. #include "c_string.h"
  43. #include "ctype.h"
  44. #include "user_interface.h"
  45. #include "espconn.h"
  46. #include "lwip/tcp.h"
  47. #include "lwip/pbuf.h"
  48. #include "vfs.h"
  49. #include "task/task.h"
  50. /* Set this to 1 to generate debug messages. Uses debug callback provided by Lua. Example: enduser_setup.start(successFn, print, print) */
  51. #define ENDUSER_SETUP_DEBUG_ENABLE 0
  52. /* Set this to 1 to output the contents of HTTP requests when debugging. Useful if you need it, but can get pretty noisy */
  53. #define ENDUSER_SETUP_DEBUG_SHOW_HTTP_REQUEST 0
  54. #define MIN(x, y) (((x) < (y)) ? (x) : (y))
  55. #define LITLEN(strliteral) (sizeof (strliteral) -1)
  56. #define STRINGIFY(x) #x
  57. #define NUMLEN(x) (sizeof(STRINGIFY(x)) - 1)
  58. #define ENDUSER_SETUP_ERR_FATAL (1 << 0)
  59. #define ENDUSER_SETUP_ERR_NONFATAL (1 << 1)
  60. #define ENDUSER_SETUP_ERR_NO_RETURN (1 << 2)
  61. #define ENDUSER_SETUP_ERR_OUT_OF_MEMORY 1
  62. #define ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND 2
  63. #define ENDUSER_SETUP_ERR_UNKOWN_ERROR 3
  64. #define ENDUSER_SETUP_ERR_SOCKET_ALREADY_OPEN 4
  65. #define ENDUSER_SETUP_ERR_MAX_NUMBER 5
  66. #define ENDUSER_SETUP_ERR_ALREADY_INITIALIZED 6
  67. /**
  68. * DNS Response Packet:
  69. *
  70. * |DNS ID - 16 bits|
  71. * |dns_header|
  72. * |QNAME|
  73. * |dns_body|
  74. * |ip - 32 bits|
  75. *
  76. * DNS Header Part | FLAGS | | Q COUNT | | A CNT | |AUTH CNT| | ADD CNT| */
  77. static const char dns_header[] = { 0x80, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00 };
  78. /* DNS Query Part | Q TYPE | | Q CLASS| */
  79. static const char dns_body[] = { 0x00, 0x01, 0x00, 0x01,
  80. /* DNS Answer Part |LBL OFFS| | TYPE | | CLASS | | TTL | | RD LEN | */
  81. 0xC0, 0x0C, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x04 };
  82. static const char http_html_gz_filename[] = "enduser_setup.html.gz";
  83. static const char http_html_filename[] = "enduser_setup.html";
  84. static const char http_header_200[] = "HTTP/1.1 200 OK\r\nCache-control:no-cache\r\nConnection:close\r\nContent-Type:text/html\r\n"; /* Note single \r\n here! */
  85. static const char http_header_204[] = "HTTP/1.1 204 No Content\r\nContent-Length:0\r\nConnection:close\r\n\r\n";
  86. static const char http_header_302[] = "HTTP/1.1 302 Moved\r\nLocation: /\r\nContent-Length:0\r\nConnection:close\r\n\r\n";
  87. static const char http_header_400[] = "HTTP/1.1 400 Bad request\r\nContent-Length:0\r\nConnection:close\r\n\r\n";
  88. static const char http_header_404[] = "HTTP/1.1 404 Not found\r\nContent-Length:0\r\nConnection:close\r\n\r\n";
  89. static const char http_header_405[] = "HTTP/1.1 405 Method Not Allowed\r\nContent-Length:0\r\nConnection:close\r\n\r\n";
  90. static const char http_header_500[] = "HTTP/1.1 500 Internal Error\r\nContent-Length:0\r\nConnection:close\r\n\r\n";
  91. static const char http_header_content_len_fmt[] = "Content-length:%5d\r\n\r\n";
  92. static const char http_html_gzip_contentencoding[] = "Content-Encoding: gzip\r\n";
  93. /* Externally defined: static const char http_html_backup[] = ... */
  94. #include "eus/http_html_backup.def"
  95. typedef struct scan_listener
  96. {
  97. struct tcp_pcb *conn;
  98. struct scan_listener *next;
  99. } scan_listener_t;
  100. typedef struct
  101. {
  102. struct espconn *espconn_dns_udp;
  103. struct tcp_pcb *http_pcb;
  104. char *http_payload_data;
  105. uint32_t http_payload_len;
  106. os_timer_t check_station_timer;
  107. os_timer_t shutdown_timer;
  108. int lua_connected_cb_ref;
  109. int lua_err_cb_ref;
  110. int lua_dbg_cb_ref;
  111. scan_listener_t *scan_listeners;
  112. uint8_t softAPchannel;
  113. uint8_t success;
  114. uint8_t callbackDone;
  115. uint8_t lastStationStatus;
  116. uint8_t connecting;
  117. } enduser_setup_state_t;
  118. static enduser_setup_state_t *state;
  119. static bool manual = false;
  120. static task_handle_t do_station_cfg_handle;
  121. static int enduser_setup_manual(lua_State* L);
  122. static int enduser_setup_start(lua_State* L);
  123. static int enduser_setup_stop(lua_State* L);
  124. static void enduser_setup_stop_callback(void *ptr);
  125. static void enduser_setup_station_start(void);
  126. static void enduser_setup_ap_start(void);
  127. static void enduser_setup_ap_stop(void);
  128. static void enduser_setup_check_station(void *p);
  129. static void enduser_setup_debug(int line, const char *str);
  130. static char ipaddr[16];
  131. #if ENDUSER_SETUP_DEBUG_ENABLE
  132. #define ENDUSER_SETUP_DEBUG(str) enduser_setup_debug(__LINE__, str)
  133. #else
  134. #define ENDUSER_SETUP_DEBUG(str) do {} while(0)
  135. #endif
  136. #define ENDUSER_SETUP_ERROR(str, err, err_severity) \
  137. do { \
  138. ENDUSER_SETUP_DEBUG(str); \
  139. if (err_severity & ENDUSER_SETUP_ERR_FATAL) enduser_setup_stop(lua_getstate());\
  140. enduser_setup_error(__LINE__, str, err);\
  141. if (!(err_severity & ENDUSER_SETUP_ERR_NO_RETURN)) \
  142. return err; \
  143. } while (0)
  144. #define ENDUSER_SETUP_ERROR_VOID(str, err, err_severity) \
  145. do { \
  146. ENDUSER_SETUP_DEBUG(str); \
  147. if (err_severity & ENDUSER_SETUP_ERR_FATAL) enduser_setup_stop(lua_getstate());\
  148. enduser_setup_error(__LINE__, str, err);\
  149. if (!(err_severity & ENDUSER_SETUP_ERR_NO_RETURN)) \
  150. return; \
  151. } while (0)
  152. static void enduser_setup_debug(int line, const char *str)
  153. {
  154. lua_State *L = lua_getstate();
  155. if(state != NULL && state->lua_dbg_cb_ref != LUA_NOREF)
  156. {
  157. lua_rawgeti(L, LUA_REGISTRYINDEX, state->lua_dbg_cb_ref);
  158. lua_pushfstring(L, "%d: \t%s", line, str);
  159. lua_call(L, 1, 0);
  160. }
  161. }
  162. static void enduser_setup_error(int line, const char *str, int err)
  163. {
  164. ENDUSER_SETUP_DEBUG("enduser_setup_error");
  165. lua_State *L = lua_getstate();
  166. if (state != NULL && state->lua_err_cb_ref != LUA_NOREF)
  167. {
  168. lua_rawgeti (L, LUA_REGISTRYINDEX, state->lua_err_cb_ref);
  169. lua_pushnumber(L, err);
  170. lua_pushfstring(L, "%d: \t%s", line, str);
  171. lua_call (L, 2, 0);
  172. }
  173. }
  174. static void enduser_setup_connected_callback()
  175. {
  176. ENDUSER_SETUP_DEBUG("enduser_setup_connected_callback");
  177. lua_State *L = lua_getstate();
  178. if (state != NULL && state->lua_connected_cb_ref != LUA_NOREF)
  179. {
  180. lua_rawgeti(L, LUA_REGISTRYINDEX, state->lua_connected_cb_ref);
  181. lua_call(L, 0, 0);
  182. }
  183. }
  184. static void enduser_setup_check_station_start(void)
  185. {
  186. ENDUSER_SETUP_DEBUG("enduser_setup_check_station_start");
  187. os_timer_setfn(&(state->check_station_timer), enduser_setup_check_station, NULL);
  188. os_timer_arm(&(state->check_station_timer), 3*1000, TRUE);
  189. }
  190. static void enduser_setup_check_station_stop(void)
  191. {
  192. ENDUSER_SETUP_DEBUG("enduser_setup_check_station_stop");
  193. if (state != NULL)
  194. {
  195. os_timer_disarm(&(state->check_station_timer));
  196. }
  197. }
  198. /**
  199. * Check Station
  200. *
  201. * Check that we've successfully entered station mode.
  202. */
  203. static void enduser_setup_check_station(void *p)
  204. {
  205. ENDUSER_SETUP_DEBUG("enduser_setup_check_station");
  206. (void)p;
  207. struct ip_info ip;
  208. c_memset(&ip, 0, sizeof(struct ip_info));
  209. wifi_get_ip_info(STATION_IF, &ip);
  210. int i;
  211. char has_ip = 0;
  212. for (i = 0; i < sizeof(struct ip_info); ++i)
  213. {
  214. has_ip |= ((char *) &ip)[i];
  215. }
  216. uint8_t currChan = wifi_get_channel();
  217. if (has_ip == 0)
  218. {
  219. /* No IP Address yet, so check the reported status */
  220. uint8_t curr_status = wifi_station_get_connect_status();
  221. char buf[20];
  222. c_sprintf(buf, "status=%d,chan=%d", curr_status, currChan);
  223. ENDUSER_SETUP_DEBUG(buf);
  224. if (curr_status == 2 || curr_status == 3 || curr_status == 4)
  225. {
  226. state->connecting = 0;
  227. /* If the status is an error status and the channel changed, then cache the
  228. * status to state since the Station won't be able to report the same status
  229. * after switching the channel back to the SoftAP's
  230. */
  231. if (currChan != state->softAPchannel) {
  232. state->lastStationStatus = curr_status;
  233. ENDUSER_SETUP_DEBUG("Turning off Station due to different channel than AP");
  234. wifi_station_disconnect();
  235. wifi_set_opmode(SOFTAP_MODE);
  236. enduser_setup_ap_start();
  237. }
  238. }
  239. return;
  240. }
  241. c_sprintf (ipaddr, "%d.%d.%d.%d", IP2STR(&ip.ip.addr));
  242. state->success = 1;
  243. state->lastStationStatus = 5; /* We have an IP Address, so the status is 5 (as of SDK 1.5.1) */
  244. state->connecting = 0;
  245. #if ENDUSER_SETUP_DEBUG_ENABLE
  246. char debuginfo[100];
  247. c_sprintf(debuginfo, "AP_CHAN: %d, STA_CHAN: %d", state->softAPchannel, currChan);
  248. ENDUSER_SETUP_DEBUG(debuginfo);
  249. #endif
  250. if (currChan == state->softAPchannel)
  251. {
  252. enduser_setup_connected_callback();
  253. state->callbackDone = 1;
  254. }
  255. else
  256. {
  257. ENDUSER_SETUP_DEBUG("Turning off Station due to different channel than AP");
  258. wifi_station_disconnect();
  259. wifi_set_opmode(SOFTAP_MODE);
  260. enduser_setup_ap_start();
  261. }
  262. enduser_setup_check_station_stop();
  263. /* Trigger shutdown, but allow time for HTTP client to fetch last status. */
  264. if (!manual)
  265. {
  266. os_timer_setfn(&(state->shutdown_timer), enduser_setup_stop_callback, NULL);
  267. os_timer_arm(&(state->shutdown_timer), 10*1000, FALSE);
  268. }
  269. }
  270. /* --- Connection closing handling ----------------------------------------- */
  271. /* It is far more memory efficient to let the other end close the connection
  272. * first and respond to that, than us initiating the closing. The latter
  273. * seems to leave the pcb in a fin_wait state for a long time, which can
  274. * starve us of memory over time.
  275. *
  276. * By instead using the poll function to schedule a hard abort a few seconds
  277. * from now we achieve a deadline close. The downside is a (very) slight
  278. * risk of dropping the connection early, but in this application that's
  279. * hidden by the retries on the JavaScript side anyway.
  280. */
  281. /* Callback on timeout to hard-close a connection */
  282. static err_t force_abort (void *arg, struct tcp_pcb *pcb)
  283. {
  284. ENDUSER_SETUP_DEBUG("force_abort");
  285. (void)arg;
  286. tcp_poll (pcb, 0, 0);
  287. tcp_abort (pcb);
  288. return ERR_ABRT;
  289. }
  290. /* Callback to detect a remote-close of a connection */
  291. static err_t handle_remote_close (void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
  292. {
  293. ENDUSER_SETUP_DEBUG("handle_remote_close");
  294. (void)arg; (void)err;
  295. if (p) /* server sent us data, just ACK and move on */
  296. {
  297. tcp_recved (pcb, p->tot_len);
  298. pbuf_free (p);
  299. }
  300. else /* hey, remote end closed, we can do a soft close safely, yay! */
  301. {
  302. tcp_recv (pcb, 0);
  303. tcp_poll (pcb, 0, 0);
  304. tcp_close (pcb);
  305. }
  306. return ERR_OK;
  307. }
  308. /* Set up a deferred close of a connection, as discussed above. */
  309. static inline void deferred_close (struct tcp_pcb *pcb)
  310. {
  311. ENDUSER_SETUP_DEBUG("deferred_close");
  312. tcp_poll (pcb, force_abort, 15); /* ~3sec from now */
  313. tcp_recv (pcb, handle_remote_close);
  314. tcp_sent (pcb, 0);
  315. }
  316. /* Convenience function to queue up a close-after-send. */
  317. static err_t close_once_sent (void *arg, struct tcp_pcb *pcb, u16_t len)
  318. {
  319. ENDUSER_SETUP_DEBUG("close_once_sent");
  320. (void)arg; (void)len;
  321. deferred_close (pcb);
  322. return ERR_OK;
  323. }
  324. /* ------------------------------------------------------------------------- */
  325. /**
  326. * Search String
  327. *
  328. * Search string for first occurance of any char in srch_str.
  329. *
  330. * @return -1 iff no occurance of char was found.
  331. */
  332. static int enduser_setup_srch_str(const char *str, const char *srch_str)
  333. {
  334. char *found = strpbrk (str, srch_str);
  335. if (!found)
  336. {
  337. return -1;
  338. }
  339. else
  340. {
  341. return found - str;
  342. }
  343. }
  344. /**
  345. * Load HTTP Payload
  346. *
  347. * @return - 0 iff payload loaded successfully
  348. * 1 iff backup html was loaded
  349. * 2 iff out of memory
  350. */
  351. static int enduser_setup_http_load_payload(void)
  352. {
  353. ENDUSER_SETUP_DEBUG("enduser_setup_http_load_payload");
  354. int err = VFS_RES_ERR;
  355. int err2 = VFS_RES_ERR;
  356. int file_len = 0;
  357. /* Try to open enduser_setup.html.gz from SPIFFS first */
  358. int f = vfs_open(http_html_gz_filename, "r");
  359. if (f)
  360. {
  361. err = vfs_lseek(f, 0, VFS_SEEK_END);
  362. file_len = (int) vfs_tell(f);
  363. err2 = vfs_lseek(f, 0, VFS_SEEK_SET);
  364. }
  365. if (!f || err == VFS_RES_ERR || err2 == VFS_RES_ERR)
  366. {
  367. if (f)
  368. {
  369. vfs_close(f);
  370. }
  371. /* If that didn't work, try to open enduser_setup.html from SPIFFS */
  372. f = vfs_open(http_html_filename, "r");
  373. if (f)
  374. {
  375. err = vfs_lseek(f, 0, VFS_SEEK_END);
  376. file_len = (int) vfs_tell(f);
  377. err2 = vfs_lseek(f, 0, VFS_SEEK_SET);
  378. }
  379. }
  380. char cl_hdr[30];
  381. size_t ce_len = 0;
  382. c_sprintf(cl_hdr, http_header_content_len_fmt, file_len);
  383. size_t cl_len = c_strlen(cl_hdr);
  384. if (!f || err == VFS_RES_ERR || err2 == VFS_RES_ERR)
  385. {
  386. ENDUSER_SETUP_DEBUG("Unable to load file enduser_setup.html, loading backup HTML...");
  387. c_sprintf(cl_hdr, http_header_content_len_fmt, sizeof(http_html_backup));
  388. cl_len = c_strlen(cl_hdr);
  389. int html_len = LITLEN(http_html_backup);
  390. if (http_html_backup[0] == 0x1f && http_html_backup[1] == 0x8b)
  391. {
  392. ce_len = c_strlen(http_html_gzip_contentencoding);
  393. html_len = http_html_backup_len; /* Defined in eus/http_html_backup.def by xxd -i */
  394. ENDUSER_SETUP_DEBUG("Content is gzipped");
  395. }
  396. int payload_len = LITLEN(http_header_200) + cl_len + ce_len + html_len;
  397. state->http_payload_len = payload_len;
  398. state->http_payload_data = (char *) c_malloc(payload_len);
  399. if (state->http_payload_data == NULL)
  400. {
  401. return 2;
  402. }
  403. int offset = 0;
  404. c_memcpy(&(state->http_payload_data[offset]), &(http_header_200), LITLEN(http_header_200));
  405. offset += LITLEN(http_header_200);
  406. if (ce_len > 0)
  407. {
  408. offset += c_sprintf(state->http_payload_data + offset, http_html_gzip_contentencoding, ce_len);
  409. }
  410. c_memcpy(&(state->http_payload_data[offset]), &(cl_hdr), cl_len);
  411. offset += cl_len;
  412. c_memcpy(&(state->http_payload_data[offset]), &(http_html_backup), sizeof(http_html_backup));
  413. return 1;
  414. }
  415. char magic[2];
  416. vfs_read(f, magic, 2);
  417. if (magic[0] == 0x1f && magic[1] == 0x8b)
  418. {
  419. ce_len = c_strlen(http_html_gzip_contentencoding);
  420. ENDUSER_SETUP_DEBUG("Content is gzipped");
  421. }
  422. int payload_len = LITLEN(http_header_200) + cl_len + ce_len + file_len;
  423. state->http_payload_len = payload_len;
  424. state->http_payload_data = (char *) c_malloc(payload_len);
  425. if (state->http_payload_data == NULL)
  426. {
  427. return 2;
  428. }
  429. vfs_lseek(f, 0, VFS_SEEK_SET);
  430. int offset = 0;
  431. c_memcpy(&(state->http_payload_data[offset]), &(http_header_200), LITLEN(http_header_200));
  432. offset += LITLEN(http_header_200);
  433. if (ce_len > 0)
  434. {
  435. offset += c_sprintf(state->http_payload_data + offset, http_html_gzip_contentencoding, ce_len);
  436. }
  437. c_memcpy(&(state->http_payload_data[offset]), &(cl_hdr), cl_len);
  438. offset += cl_len;
  439. vfs_read(f, &(state->http_payload_data[offset]), file_len);
  440. vfs_close(f);
  441. return 0;
  442. }
  443. /**
  444. * De-escape URL data
  445. *
  446. * Parse escaped and form encoded data of request.
  447. *
  448. * @return - return 0 iff the HTTP parameter is decoded into a valid string.
  449. */
  450. static int enduser_setup_http_urldecode(char *dst, const char *src, int src_len, int dst_len)
  451. {
  452. ENDUSER_SETUP_DEBUG("enduser_setup_http_urldecode");
  453. char *dst_start = dst;
  454. char *dst_last = dst + dst_len - 1; /* -1 to reserve space for last \0 */
  455. char a, b;
  456. int i;
  457. for (i = 0; i < src_len && *src && dst < dst_last; ++i)
  458. {
  459. if ((*src == '%') && ((a = src[1]) && (b = src[2])) && (isxdigit(a) && isxdigit(b)))
  460. {
  461. if (a >= 'a')
  462. {
  463. a -= 'a'-'A';
  464. }
  465. if (a >= 'A')
  466. {
  467. a -= ('A' - 10);
  468. }
  469. else
  470. {
  471. a -= '0';
  472. }
  473. if (b >= 'a')
  474. {
  475. b -= 'a'-'A';
  476. }
  477. if (b >= 'A')
  478. {
  479. b -= ('A' - 10);
  480. }
  481. else
  482. {
  483. b -= '0';
  484. }
  485. *dst++ = 16 * a + b;
  486. src += 3;
  487. i += 2;
  488. } else {
  489. char c = *src++;
  490. if (c == '+')
  491. {
  492. c = ' ';
  493. }
  494. *dst++ = c;
  495. }
  496. }
  497. *dst++ = '\0';
  498. return (i < src_len); /* did we fail to process all the input? */
  499. }
  500. /**
  501. * Task to do the actual station configuration.
  502. * This config *cannot* be done in the network receive callback or serious
  503. * issues like memory corruption occur.
  504. */
  505. static void do_station_cfg (task_param_t param, uint8_t prio)
  506. {
  507. ENDUSER_SETUP_DEBUG("do_station_cfg");
  508. state->connecting = 1;
  509. struct station_config *cnf = (struct station_config *)param;
  510. (void)prio;
  511. /* Best-effort disconnect-reconfig-reconnect. If the device is currently
  512. * connected, the disconnect will work but the connect will report failure
  513. * (though it will actually start connecting). If the devices is not
  514. * connected, the disconnect may fail but the connect will succeed. A
  515. * solid head-in-the-sand approach seems to be the best tradeoff on
  516. * functionality-vs-code-size.
  517. * TODO: maybe use an error callback to at least report if the set config
  518. * call fails.
  519. */
  520. wifi_station_disconnect ();
  521. wifi_station_set_config (cnf);
  522. wifi_station_connect ();
  523. luaM_free(lua_getstate(), cnf);
  524. }
  525. /**
  526. * Handle HTTP Credentials
  527. *
  528. * @return - return 0 iff credentials are found and handled successfully
  529. * return 1 iff credentials aren't found
  530. * return 2 iff an error occured
  531. */
  532. static int enduser_setup_http_handle_credentials(char *data, unsigned short data_len)
  533. {
  534. ENDUSER_SETUP_DEBUG("enduser_setup_http_handle_credentials");
  535. state->success = 0;
  536. state->lastStationStatus = 0;
  537. char *name_str = (char *) ((uint32_t)strstr(&(data[6]), "wifi_ssid="));
  538. char *pwd_str = (char *) ((uint32_t)strstr(&(data[6]), "wifi_password="));
  539. if (name_str == NULL || pwd_str == NULL)
  540. {
  541. ENDUSER_SETUP_DEBUG("Password or SSID string not found");
  542. return 1;
  543. }
  544. int name_field_len = LITLEN("wifi_ssid=");
  545. int pwd_field_len = LITLEN("wifi_password=");
  546. char *name_str_start = name_str + name_field_len;
  547. char *pwd_str_start = pwd_str + pwd_field_len;
  548. int name_str_len = enduser_setup_srch_str(name_str_start, "& ");
  549. int pwd_str_len = enduser_setup_srch_str(pwd_str_start, "& ");
  550. if (name_str_len == -1 || pwd_str_len == -1)
  551. {
  552. ENDUSER_SETUP_DEBUG("Password or SSID HTTP paramter divider not found");
  553. return 1;
  554. }
  555. struct station_config *cnf = luaM_malloc(lua_getstate(), sizeof(struct station_config));
  556. c_memset(cnf, 0, sizeof(struct station_config));
  557. int err;
  558. err = enduser_setup_http_urldecode(cnf->ssid, name_str_start, name_str_len, sizeof(cnf->ssid));
  559. err |= enduser_setup_http_urldecode(cnf->password, pwd_str_start, pwd_str_len, sizeof(cnf->password));
  560. if (err != 0 || c_strlen(cnf->ssid) == 0)
  561. {
  562. ENDUSER_SETUP_DEBUG("Unable to decode HTTP parameter to valid password or SSID");
  563. return 1;
  564. }
  565. ENDUSER_SETUP_DEBUG("");
  566. ENDUSER_SETUP_DEBUG("WiFi Credentials Stored");
  567. ENDUSER_SETUP_DEBUG("-----------------------");
  568. ENDUSER_SETUP_DEBUG("name: ");
  569. ENDUSER_SETUP_DEBUG(cnf->ssid);
  570. ENDUSER_SETUP_DEBUG("pass: ");
  571. ENDUSER_SETUP_DEBUG(cnf->password);
  572. ENDUSER_SETUP_DEBUG("-----------------------");
  573. ENDUSER_SETUP_DEBUG("");
  574. task_post_medium(do_station_cfg_handle, (task_param_t) cnf);
  575. return 0;
  576. }
  577. /**
  578. * Serve HTML
  579. *
  580. * @return - return 0 iff html was served successfully
  581. */
  582. static int enduser_setup_http_serve_header(struct tcp_pcb *http_client, const char *header, uint32_t header_len)
  583. {
  584. ENDUSER_SETUP_DEBUG("enduser_setup_http_serve_header");
  585. err_t err = tcp_write (http_client, header, header_len, TCP_WRITE_FLAG_COPY);
  586. if (err != ERR_OK)
  587. {
  588. deferred_close (http_client);
  589. ENDUSER_SETUP_ERROR("http_serve_header failed on tcp_write", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
  590. }
  591. return 0;
  592. }
  593. static err_t streamout_sent (void *arg, struct tcp_pcb *pcb, u16_t len)
  594. {
  595. ENDUSER_SETUP_DEBUG("streamout_sent");
  596. (void)len;
  597. unsigned offs = (unsigned)arg;
  598. if (!state || !state->http_payload_data)
  599. {
  600. tcp_abort (pcb);
  601. return ERR_ABRT;
  602. }
  603. unsigned wanted_len = state->http_payload_len - offs;
  604. unsigned buf_free = tcp_sndbuf (pcb);
  605. if (buf_free < wanted_len)
  606. wanted_len = buf_free;
  607. /* no-copy write */
  608. err_t err = tcp_write (pcb, state->http_payload_data + offs, wanted_len, 0);
  609. if (err != ERR_OK)
  610. {
  611. ENDUSER_SETUP_DEBUG("streaming out html failed");
  612. tcp_abort (pcb);
  613. return ERR_ABRT;
  614. }
  615. offs += wanted_len;
  616. if (offs >= state->http_payload_len)
  617. {
  618. tcp_sent (pcb, 0);
  619. deferred_close (pcb);
  620. }
  621. else
  622. tcp_arg (pcb, (void *)offs);
  623. return ERR_OK;
  624. }
  625. /**
  626. * Serve HTML
  627. *
  628. * @return - return 0 iff html was served successfully
  629. */
  630. static int enduser_setup_http_serve_html(struct tcp_pcb *http_client)
  631. {
  632. ENDUSER_SETUP_DEBUG("enduser_setup_http_serve_html");
  633. if (state->http_payload_data == NULL)
  634. {
  635. enduser_setup_http_load_payload();
  636. }
  637. unsigned chunklen = tcp_sndbuf (http_client);
  638. tcp_arg (http_client, (void *)chunklen);
  639. tcp_recv (http_client, 0); /* avoid confusion about the tcp_arg */
  640. tcp_sent (http_client, streamout_sent);
  641. /* Begin the no-copy stream-out here */
  642. err_t err = tcp_write (http_client, state->http_payload_data, chunklen, 0);
  643. if (err != 0)
  644. {
  645. ENDUSER_SETUP_ERROR("http_serve_html failed. tcp_write failed", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
  646. }
  647. return 0;
  648. }
  649. static void enduser_setup_serve_status(struct tcp_pcb *conn)
  650. {
  651. ENDUSER_SETUP_DEBUG("enduser_setup_serve_status");
  652. const char fmt[] =
  653. "HTTP/1.1 200 OK\r\n"
  654. "Cache-control:no-cache\r\n"
  655. "Connection:close\r\n"
  656. "Access-Control-Allow-Origin: *\r\n"
  657. "Content-type:text/plain\r\n"
  658. "Content-length: %d\r\n"
  659. "\r\n"
  660. "%s";
  661. const char *states[] =
  662. {
  663. "Idle.",
  664. "Connecting to \"%s\".",
  665. "Failed to connect to \"%s\" - Wrong password.",
  666. "Failed to connect to \"%s\" - Network not found.",
  667. "Failed to connect.",
  668. "Connected to \"%s\" (%s)."
  669. };
  670. const size_t num_states = sizeof(states)/sizeof(states[0]);
  671. uint8_t curr_state = state->lastStationStatus > 0 ? state->lastStationStatus : wifi_station_get_connect_status ();
  672. if (curr_state < num_states)
  673. {
  674. switch (curr_state)
  675. {
  676. case STATION_CONNECTING:
  677. case STATION_WRONG_PASSWORD:
  678. case STATION_NO_AP_FOUND:
  679. case STATION_GOT_IP:
  680. {
  681. const char *s = states[curr_state];
  682. struct station_config config;
  683. wifi_station_get_config(&config);
  684. config.ssid[31] = '\0';
  685. struct ip_info ip_info;
  686. wifi_get_ip_info(STATION_IF , &ip_info);
  687. char ip_addr[16];
  688. ip_addr[0] = '\0';
  689. if (curr_state == STATION_GOT_IP)
  690. {
  691. c_sprintf (ip_addr, "%d.%d.%d.%d", IP2STR(&ip_info.ip.addr));
  692. }
  693. int state_len = c_strlen(s);
  694. int ip_len = c_strlen(ip_addr);
  695. int ssid_len = c_strlen(config.ssid);
  696. int status_len = state_len + ssid_len + ip_len + 1;
  697. char status_buf[status_len];
  698. memset(status_buf, 0, status_len);
  699. status_len = c_sprintf(status_buf, s, config.ssid, ip_addr);
  700. int buf_len = sizeof(fmt) + status_len + 10; /* 10 = (9+1), 1 byte is '\0' and 9 are reserved for length field */
  701. char buf[buf_len];
  702. memset(buf, 0, buf_len);
  703. int output_len = c_sprintf(buf, fmt, status_len, status_buf);
  704. enduser_setup_http_serve_header(conn, buf, output_len);
  705. }
  706. break;
  707. /* Handle non-formatted strings */
  708. default:
  709. {
  710. const char *s = states[curr_state];
  711. int status_len = c_strlen(s);
  712. int buf_len = sizeof(fmt) + status_len + 10; /* 10 = (9+1), 1 byte is '\0' and 9 are reserved for length field */
  713. char buf[buf_len];
  714. memset(buf, 0, buf_len);
  715. int output_len = c_sprintf(buf, fmt, status_len, s);
  716. enduser_setup_http_serve_header(conn, buf, output_len);
  717. }
  718. break;
  719. }
  720. }
  721. else
  722. {
  723. enduser_setup_http_serve_header(conn, http_header_500, LITLEN(http_header_500));
  724. }
  725. }
  726. static void enduser_setup_serve_status_as_json (struct tcp_pcb *http_client)
  727. {
  728. ENDUSER_SETUP_DEBUG("enduser_setup_serve_status_as_json");
  729. /* If the station is currently shut down because of wi-fi channel issue, use the cached status */
  730. uint8_t curr_status = state->lastStationStatus > 0 ? state->lastStationStatus : wifi_station_get_connect_status ();
  731. char json_payload[64];
  732. struct ip_info ip_info;
  733. if (curr_status == 5)
  734. {
  735. wifi_get_ip_info(STATION_IF , &ip_info);
  736. /* If IP address not yet available, get now */
  737. if (strlen(ipaddr) == 0)
  738. {
  739. c_sprintf(ipaddr, "%d.%d.%d.%d", IP2STR(&ip_info.ip.addr));
  740. }
  741. c_sprintf(json_payload, "{\"deviceid\":\"%s\", \"status\":%d}", ipaddr, curr_status);
  742. }
  743. else
  744. {
  745. c_sprintf(json_payload, "{\"deviceid\":\"%06X\", \"status\":%d}", system_get_chip_id(), curr_status);
  746. }
  747. const char fmt[] =
  748. "HTTP/1.1 200 OK\r\n"
  749. "Cache-Control: no-cache\r\n"
  750. "Connection: close\r\n"
  751. "Access-Control-Allow-Origin: *\r\n"
  752. "Content-Type: application/json\r\n"
  753. "Content-Length: %d\r\n"
  754. "\r\n"
  755. "%s";
  756. int len = c_strlen(json_payload);
  757. char buf[c_strlen(fmt) + NUMLEN(len) + len - 4];
  758. len = c_sprintf (buf, fmt, len, json_payload);
  759. enduser_setup_http_serve_header (http_client, buf, len);
  760. }
  761. static void enduser_setup_handle_OPTIONS (struct tcp_pcb *http_client, char *data, unsigned short data_len)
  762. {
  763. ENDUSER_SETUP_DEBUG("enduser_setup_handle_OPTIONS");
  764. const char json[] =
  765. "HTTP/1.1 200 OK\r\n"
  766. "Cache-Control: no-cache\r\n"
  767. "Connection: close\r\n"
  768. "Content-Type: application/json\r\n"
  769. "Content-Length: 0\r\n"
  770. "Access-Control-Allow-Origin: *\r\n"
  771. "Access-Control-Allow-Methods: GET\r\n"
  772. "Access-Control-Allow-Age: 300\r\n"
  773. "\r\n";
  774. const char others[] =
  775. "HTTP/1.1 200 OK\r\n"
  776. "Cache-Control: no-cache\r\n"
  777. "Connection: close\r\n"
  778. "Content-Length: 0\r\n"
  779. "\r\n";
  780. int type = 0;
  781. if (c_strncmp(data, "GET ", 4) == 0)
  782. {
  783. if (c_strncmp(data + 4, "/aplist", 7) == 0 || c_strncmp(data + 4, "/setwifi?", 9) == 0 || c_strncmp(data + 4, "/status.json", 12) == 0)
  784. {
  785. enduser_setup_http_serve_header (http_client, json, c_strlen(json));
  786. return;
  787. }
  788. }
  789. enduser_setup_http_serve_header (http_client, others, c_strlen(others));
  790. return;
  791. }
  792. /* --- WiFi AP scanning support -------------------------------------------- */
  793. static void free_scan_listeners (void)
  794. {
  795. ENDUSER_SETUP_DEBUG("free_scan_listeners");
  796. if (!state || !state->scan_listeners)
  797. {
  798. return;
  799. }
  800. scan_listener_t *l = state->scan_listeners , *next = 0;
  801. while (l)
  802. {
  803. next = l->next;
  804. c_free (l);
  805. l = next;
  806. }
  807. state->scan_listeners = 0;
  808. }
  809. static void remove_scan_listener (scan_listener_t *l)
  810. {
  811. ENDUSER_SETUP_DEBUG("remove_scan_listener");
  812. if (state)
  813. {
  814. scan_listener_t **sl = &state->scan_listeners;
  815. while (*sl)
  816. {
  817. /* Remove any and all references to the closed conn from the scan list */
  818. if (*sl == l)
  819. {
  820. *sl = l->next;
  821. c_free (l);
  822. /* No early exit to guard against multi-entry on list */
  823. }
  824. else
  825. sl = &(*sl)->next;
  826. }
  827. }
  828. }
  829. static char *escape_ssid (char *dst, const char *src)
  830. {
  831. for (int i = 0; i < 32 && src[i]; ++i)
  832. {
  833. if (src[i] == '\\' || src[i] == '"')
  834. {
  835. *dst++ = '\\';
  836. }
  837. *dst++ = src[i];
  838. }
  839. return dst;
  840. }
  841. static void notify_scan_listeners (const char *payload, size_t sz)
  842. {
  843. ENDUSER_SETUP_DEBUG("notify_scan_listeners");
  844. if (!state)
  845. {
  846. return;
  847. }
  848. for (scan_listener_t *l = state->scan_listeners; l; l = l->next)
  849. {
  850. if (tcp_write (l->conn, payload, sz, TCP_WRITE_FLAG_COPY) != ERR_OK)
  851. {
  852. ENDUSER_SETUP_DEBUG("failed to send wifi list");
  853. tcp_abort (l->conn);
  854. }
  855. else
  856. tcp_sent (l->conn, close_once_sent); /* TODO: time-out sends? */
  857. l->conn = 0;
  858. }
  859. free_scan_listeners ();
  860. }
  861. static void on_scan_done (void *arg, STATUS status)
  862. {
  863. ENDUSER_SETUP_DEBUG("on_scan_done");
  864. if (!state || !state->scan_listeners)
  865. {
  866. return;
  867. }
  868. if (status == OK)
  869. {
  870. unsigned num_nets = 0;
  871. for (struct bss_info *wn = arg; wn; wn = wn->next.stqe_next)
  872. {
  873. ++num_nets;
  874. }
  875. const char header_fmt[] =
  876. "HTTP/1.1 200 OK\r\n"
  877. "Connection:close\r\n"
  878. "Cache-control:no-cache\r\n"
  879. "Access-Control-Allow-Origin: *\r\n"
  880. "Content-type:application/json\r\n"
  881. "Content-length:%4d\r\n"
  882. "\r\n";
  883. const size_t hdr_sz = sizeof (header_fmt) +1 -1; /* +expand %4d, -\0 */
  884. /* To be able to safely escape a pathological SSID, we need 2*32 bytes */
  885. const size_t max_entry_sz = 27 + 2*32 + 6; /* {"ssid":"","rssi":,"chan":} */
  886. const size_t alloc_sz = hdr_sz + num_nets * max_entry_sz + 3;
  887. char *http = os_zalloc (alloc_sz);
  888. if (!http)
  889. {
  890. goto serve_500;
  891. }
  892. char *p = http + hdr_sz; /* start body where we know it will be */
  893. /* p[0] will be clobbered when we print the header, so fill it in last */
  894. ++p;
  895. for (struct bss_info *wn = arg; wn; wn = wn->next.stqe_next)
  896. {
  897. if (wn != arg)
  898. {
  899. *p++ = ',';
  900. }
  901. const char entry_start[] = "{\"ssid\":\"";
  902. strcpy (p, entry_start);
  903. p += sizeof (entry_start) -1;
  904. p = escape_ssid (p, wn->ssid);
  905. const char entry_mid[] = "\",\"rssi\":";
  906. strcpy (p, entry_mid);
  907. p += sizeof (entry_mid) -1;
  908. p += c_sprintf (p, "%d", wn->rssi);
  909. const char entry_chan[] = ",\"chan\":";
  910. strcpy (p, entry_chan);
  911. p += sizeof (entry_chan) -1;
  912. p += c_sprintf (p, "%d", wn->channel);
  913. *p++ = '}';
  914. }
  915. *p++ = ']';
  916. size_t body_sz = (p - http) - hdr_sz;
  917. c_sprintf (http, header_fmt, body_sz);
  918. http[hdr_sz] = '['; /* Rewrite the \0 with the correct start of body */
  919. notify_scan_listeners (http, hdr_sz + body_sz);
  920. ENDUSER_SETUP_DEBUG(http + hdr_sz);
  921. c_free (http);
  922. return;
  923. }
  924. serve_500:
  925. notify_scan_listeners (http_header_500, LITLEN(http_header_500));
  926. }
  927. /* ---- end WiFi AP scan support ------------------------------------------- */
  928. static err_t enduser_setup_http_recvcb(void *arg, struct tcp_pcb *http_client, struct pbuf *p, err_t err)
  929. {
  930. ENDUSER_SETUP_DEBUG("enduser_setup_http_recvcb");
  931. if (!state || err != ERR_OK)
  932. {
  933. if (!state)
  934. ENDUSER_SETUP_DEBUG("ignoring received data while stopped");
  935. tcp_abort (http_client);
  936. return ERR_ABRT;
  937. }
  938. if (!p) /* remote side closed, close our end too */
  939. {
  940. ENDUSER_SETUP_DEBUG("connection closed");
  941. scan_listener_t *l = arg; /* if it's waiting for scan, we have a ptr here */
  942. if (l)
  943. remove_scan_listener (l);
  944. deferred_close (http_client);
  945. return ERR_OK;
  946. }
  947. char *data = os_zalloc (p->tot_len + 1);
  948. if (!data)
  949. return ERR_MEM;
  950. unsigned data_len = pbuf_copy_partial (p, data, p->tot_len, 0);
  951. tcp_recved (http_client, p->tot_len);
  952. pbuf_free (p);
  953. err_t ret = ERR_OK;
  954. #if ENDUSER_SETUP_DEBUG_SHOW_HTTP_REQUEST
  955. ENDUSER_SETUP_DEBUG(data);
  956. #endif
  957. if (c_strncmp(data, "GET ", 4) == 0)
  958. {
  959. if (c_strncmp(data + 4, "/ ", 2) == 0)
  960. {
  961. if (enduser_setup_http_serve_html(http_client) != 0)
  962. {
  963. ENDUSER_SETUP_ERROR("http_recvcb failed. Unable to send HTML.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
  964. }
  965. else
  966. {
  967. goto free_out; /* streaming now in progress */
  968. }
  969. }
  970. else if (c_strncmp(data + 4, "/aplist", 7) == 0)
  971. {
  972. /* Don't do an AP Scan while station is trying to connect to Wi-Fi */
  973. if (state->connecting == 0)
  974. {
  975. scan_listener_t *l = os_malloc (sizeof (scan_listener_t));
  976. if (!l)
  977. {
  978. ENDUSER_SETUP_ERROR("out of memory", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_NONFATAL);
  979. }
  980. bool already = (state->scan_listeners != NULL);
  981. tcp_arg (http_client, l);
  982. /* TODO: check if also need a tcp_err() cb, or if recv() is enough */
  983. l->conn = http_client;
  984. l->next = state->scan_listeners;
  985. state->scan_listeners = l;
  986. if (!already)
  987. {
  988. if (!wifi_station_scan(NULL, on_scan_done))
  989. {
  990. enduser_setup_http_serve_header(http_client, http_header_500, LITLEN(http_header_500));
  991. deferred_close (l->conn);
  992. l->conn = 0;
  993. free_scan_listeners();
  994. }
  995. }
  996. goto free_out; /* request queued */
  997. }
  998. else
  999. {
  1000. /* Return No Content status to the caller */
  1001. enduser_setup_http_serve_header(http_client, http_header_204, LITLEN(http_header_204));
  1002. }
  1003. }
  1004. else if (c_strncmp(data + 4, "/status.json", 12) == 0)
  1005. {
  1006. enduser_setup_serve_status_as_json(http_client);
  1007. }
  1008. else if (c_strncmp(data + 4, "/status", 7) == 0)
  1009. {
  1010. enduser_setup_serve_status(http_client);
  1011. }
  1012. else if (c_strncmp(data + 4, "/update?", 8) == 0)
  1013. {
  1014. switch (enduser_setup_http_handle_credentials(data, data_len))
  1015. {
  1016. case 0:
  1017. enduser_setup_http_serve_header(http_client, http_header_302, LITLEN(http_header_302));
  1018. break;
  1019. case 1:
  1020. enduser_setup_http_serve_header(http_client, http_header_400, LITLEN(http_header_400));
  1021. break;
  1022. default:
  1023. ENDUSER_SETUP_ERROR("http_recvcb failed. Failed to handle wifi credentials.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
  1024. break;
  1025. }
  1026. }
  1027. else if (c_strncmp(data + 4, "/setwifi?", 9) == 0)
  1028. {
  1029. switch (enduser_setup_http_handle_credentials(data, data_len))
  1030. {
  1031. case 0:
  1032. enduser_setup_serve_status_as_json(http_client);
  1033. break;
  1034. case 1:
  1035. enduser_setup_http_serve_header(http_client, http_header_400, LITLEN(http_header_400));
  1036. break;
  1037. default:
  1038. ENDUSER_SETUP_ERROR("http_recvcb failed. Failed to handle wifi credentials.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
  1039. break;
  1040. }
  1041. }
  1042. else if (c_strncmp(data + 4, "/generate_204", 13) == 0)
  1043. {
  1044. /* Convince Android devices that they have internet access to avoid pesky dialogues. */
  1045. enduser_setup_http_serve_header(http_client, http_header_204, LITLEN(http_header_204));
  1046. }
  1047. else
  1048. {
  1049. ENDUSER_SETUP_DEBUG("serving 404");
  1050. enduser_setup_http_serve_header(http_client, http_header_404, LITLEN(http_header_404));
  1051. }
  1052. }
  1053. else if (c_strncmp(data, "OPTIONS ", 8) == 0)
  1054. {
  1055. enduser_setup_handle_OPTIONS(http_client, data, data_len);
  1056. }
  1057. else /* not GET or OPTIONS */
  1058. {
  1059. enduser_setup_http_serve_header(http_client, http_header_405, LITLEN(http_header_405));
  1060. }
  1061. deferred_close (http_client);
  1062. free_out:
  1063. os_free (data);
  1064. return ret;
  1065. }
  1066. static err_t enduser_setup_http_connectcb(void *arg, struct tcp_pcb *pcb, err_t err)
  1067. {
  1068. ENDUSER_SETUP_DEBUG("enduser_setup_http_connectcb");
  1069. if (!state)
  1070. {
  1071. ENDUSER_SETUP_DEBUG("connect callback but no state?!");
  1072. tcp_abort (pcb);
  1073. return ERR_ABRT;
  1074. }
  1075. tcp_accepted (state->http_pcb);
  1076. tcp_recv (pcb, enduser_setup_http_recvcb);
  1077. tcp_nagle_disable (pcb);
  1078. return ERR_OK;
  1079. }
  1080. static int enduser_setup_http_start(void)
  1081. {
  1082. ENDUSER_SETUP_DEBUG("enduser_setup_http_start");
  1083. struct tcp_pcb *pcb = tcp_new ();
  1084. if (pcb == NULL)
  1085. {
  1086. ENDUSER_SETUP_ERROR("http_start failed. Memory allocation failed (http_pcb == NULL).", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  1087. }
  1088. if (tcp_bind (pcb, IP_ADDR_ANY, 80) != ERR_OK)
  1089. {
  1090. ENDUSER_SETUP_ERROR("http_start bind failed", ENDUSER_SETUP_ERR_SOCKET_ALREADY_OPEN, ENDUSER_SETUP_ERR_FATAL);
  1091. }
  1092. state->http_pcb = tcp_listen (pcb);
  1093. if (!state->http_pcb)
  1094. {
  1095. tcp_abort(pcb); /* original wasn't freed for us */
  1096. ENDUSER_SETUP_ERROR("http_start listen failed", ENDUSER_SETUP_ERR_SOCKET_ALREADY_OPEN, ENDUSER_SETUP_ERR_FATAL);
  1097. }
  1098. tcp_accept (state->http_pcb, enduser_setup_http_connectcb);
  1099. /* TODO: check lwip tcp timeouts */
  1100. #if 0
  1101. err = espconn_regist_time(state->espconn_http_tcp, 2, 0);
  1102. if (err == ESPCONN_ARG)
  1103. {
  1104. ENDUSER_SETUP_ERROR("http_start failed. Unable to set TCP timeout.", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_NONFATAL | ENDUSER_SETUP_ERR_NO_RETURN);
  1105. }
  1106. #endif
  1107. int err = enduser_setup_http_load_payload();
  1108. if (err == 1)
  1109. {
  1110. ENDUSER_SETUP_DEBUG("enduser_setup_http_start info. Loaded backup HTML.");
  1111. }
  1112. else if (err == 2)
  1113. {
  1114. ENDUSER_SETUP_ERROR("http_start failed. Unable to allocate memory for HTTP payload.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  1115. }
  1116. return 0;
  1117. }
  1118. static void enduser_setup_http_stop(void)
  1119. {
  1120. ENDUSER_SETUP_DEBUG("enduser_setup_http_stop");
  1121. if (state && state->http_pcb)
  1122. {
  1123. tcp_close (state->http_pcb); /* cannot fail for listening sockets */
  1124. state->http_pcb = 0;
  1125. }
  1126. }
  1127. static void enduser_setup_ap_stop(void)
  1128. {
  1129. ENDUSER_SETUP_DEBUG("enduser_setup_ap_stop");
  1130. wifi_set_opmode(~SOFTAP_MODE & wifi_get_opmode());
  1131. }
  1132. static void enduser_setup_ap_start(void)
  1133. {
  1134. ENDUSER_SETUP_DEBUG("enduser_setup_ap_start");
  1135. struct softap_config cnf;
  1136. c_memset(&(cnf), 0, sizeof(struct softap_config));
  1137. #ifndef ENDUSER_SETUP_AP_SSID
  1138. #define ENDUSER_SETUP_AP_SSID "SetupGadget"
  1139. #endif
  1140. char ssid[] = ENDUSER_SETUP_AP_SSID;
  1141. int ssid_name_len = c_strlen(ssid);
  1142. c_memcpy(&(cnf.ssid), ssid, ssid_name_len);
  1143. uint8_t mac[6];
  1144. wifi_get_macaddr(SOFTAP_IF, mac);
  1145. cnf.ssid[ssid_name_len] = '_';
  1146. c_sprintf(cnf.ssid + ssid_name_len + 1, "%02X%02X%02X", mac[3], mac[4], mac[5]);
  1147. cnf.ssid_len = ssid_name_len + 7;
  1148. cnf.channel = state == NULL? 1 : state->softAPchannel;
  1149. cnf.authmode = AUTH_OPEN;
  1150. cnf.ssid_hidden = 0;
  1151. cnf.max_connection = 5;
  1152. cnf.beacon_interval = 100;
  1153. wifi_set_opmode(STATIONAP_MODE);
  1154. wifi_softap_set_config(&cnf);
  1155. #if ENDUSER_SETUP_DEBUG_ENABLE
  1156. char debuginfo[100];
  1157. c_sprintf(debuginfo, "SSID: %s, CHAN: %d", cnf.ssid, cnf.channel);
  1158. ENDUSER_SETUP_DEBUG(debuginfo);
  1159. #endif
  1160. }
  1161. static void on_initial_scan_done (void *arg, STATUS status)
  1162. {
  1163. ENDUSER_SETUP_DEBUG("on_initial_scan_done");
  1164. if (state == NULL)
  1165. {
  1166. return;
  1167. }
  1168. int8_t rssi = -100;
  1169. if (status == OK)
  1170. {
  1171. /* Find the strongest signal and use the same wi-fi channel for the SoftAP. This is based on an assumption that end-user
  1172. * will likely be choosing that AP to connect to. Since ESP only has one radio, STA and AP must share same channel. This
  1173. * algorithm tries to minimize the SoftAP unavailability when the STA is connecting to verify. If the STA must switch to
  1174. * another wi-fi channel, then the SoftAP will follow it, but the end-user's device will not know that the SoftAP is no
  1175. * longer there until it times out. To mitigate, we try to prevent the need to switch channels, and if a switch does occur,
  1176. * be quick about returning to this channel so that status info can be delivered to the end-user's device before shutting
  1177. * down EUS.
  1178. */
  1179. for (struct bss_info *wn = arg; wn; wn = wn->next.stqe_next)
  1180. {
  1181. if (wn->rssi > rssi)
  1182. {
  1183. state->softAPchannel = wn->channel;
  1184. rssi = wn->rssi;
  1185. }
  1186. }
  1187. }
  1188. enduser_setup_ap_start();
  1189. enduser_setup_check_station_start();
  1190. }
  1191. static void enduser_setup_dns_recv_callback(void *arg, char *recv_data, unsigned short recv_len)
  1192. {
  1193. ENDUSER_SETUP_DEBUG("enduser_setup_dns_recv_callback.");
  1194. struct espconn *callback_espconn = arg;
  1195. struct ip_info ip_info;
  1196. uint32_t qname_len = c_strlen(&(recv_data[12])) + 1; /* \0=1byte */
  1197. uint32_t dns_reply_static_len = (uint32_t) sizeof(dns_header) + (uint32_t) sizeof(dns_body) + 2 + 4; /* dns_id=2bytes, ip=4bytes */
  1198. uint32_t dns_reply_len = dns_reply_static_len + qname_len;
  1199. #if ENDUSER_SETUP_DEBUG_ENABLE
  1200. char *qname = c_malloc(qname_len + 12);
  1201. if (qname != NULL)
  1202. {
  1203. c_sprintf(qname, "DNS QUERY = %s", &(recv_data[12]));
  1204. uint32_t p;
  1205. int i, j;
  1206. for(i=12;i<(int)strlen(qname);i++)
  1207. {
  1208. p=qname[i];
  1209. for(j=0;j<(int)p;j++)
  1210. {
  1211. qname[i]=qname[i+1];
  1212. i=i+1;
  1213. }
  1214. qname[i]='.';
  1215. }
  1216. qname[i-1]='\0';
  1217. ENDUSER_SETUP_DEBUG(qname);
  1218. c_free(qname);
  1219. }
  1220. #endif
  1221. uint8_t if_mode = wifi_get_opmode();
  1222. if ((if_mode & SOFTAP_MODE) == 0)
  1223. {
  1224. ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Interface mode not supported.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  1225. }
  1226. uint8_t if_index = (if_mode == STATION_MODE? STATION_IF : SOFTAP_IF);
  1227. if (wifi_get_ip_info(if_index , &ip_info) == false)
  1228. {
  1229. ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Unable to get interface IP.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  1230. }
  1231. char *dns_reply = (char *) c_malloc(dns_reply_len);
  1232. if (dns_reply == NULL)
  1233. {
  1234. ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Failed to allocate memory.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_NONFATAL);
  1235. }
  1236. uint32_t insert_byte = 0;
  1237. c_memcpy(&(dns_reply[insert_byte]), recv_data, 2);
  1238. insert_byte += 2;
  1239. c_memcpy(&(dns_reply[insert_byte]), dns_header, sizeof(dns_header));
  1240. insert_byte += (uint32_t) sizeof(dns_header);
  1241. c_memcpy(&(dns_reply[insert_byte]), &(recv_data[12]), qname_len);
  1242. insert_byte += qname_len;
  1243. c_memcpy(&(dns_reply[insert_byte]), dns_body, sizeof(dns_body));
  1244. insert_byte += (uint32_t) sizeof(dns_body);
  1245. c_memcpy(&(dns_reply[insert_byte]), &(ip_info.ip), 4);
  1246. /* SDK 1.4.0 changed behaviour, for UDP server need to look up remote ip/port */
  1247. remot_info *pr = 0;
  1248. if (espconn_get_connection_info(callback_espconn, &pr, 0) != ESPCONN_OK)
  1249. {
  1250. ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Unable to get IP of UDP sender.", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_FATAL);
  1251. }
  1252. callback_espconn->proto.udp->remote_port = pr->remote_port;
  1253. os_memmove(callback_espconn->proto.udp->remote_ip, pr->remote_ip, 4);
  1254. int8_t err;
  1255. err = espconn_send(callback_espconn, dns_reply, dns_reply_len);
  1256. c_free(dns_reply);
  1257. if (err == ESPCONN_MEM)
  1258. {
  1259. ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Failed to allocate memory for send.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  1260. }
  1261. else if (err == ESPCONN_ARG)
  1262. {
  1263. ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Can't execute transmission.", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_FATAL);
  1264. }
  1265. else if (err == ESPCONN_MAXNUM)
  1266. {
  1267. ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Buffer full. Discarding...", ENDUSER_SETUP_ERR_MAX_NUMBER, ENDUSER_SETUP_ERR_NONFATAL);
  1268. }
  1269. else if (err == ESPCONN_IF)
  1270. {
  1271. ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Send UDP data failed", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
  1272. }
  1273. else if (err != 0)
  1274. {
  1275. ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. espconn_send failed", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  1276. }
  1277. }
  1278. static void enduser_setup_free(void)
  1279. {
  1280. ENDUSER_SETUP_DEBUG("enduser_setup_free");
  1281. if (state == NULL)
  1282. {
  1283. return;
  1284. }
  1285. /* Make sure no running timers are left. */
  1286. os_timer_disarm(&(state->check_station_timer));
  1287. os_timer_disarm(&(state->shutdown_timer));
  1288. if (state->espconn_dns_udp != NULL)
  1289. {
  1290. if (state->espconn_dns_udp->proto.udp != NULL)
  1291. {
  1292. c_free(state->espconn_dns_udp->proto.udp);
  1293. }
  1294. c_free(state->espconn_dns_udp);
  1295. }
  1296. c_free(state->http_payload_data);
  1297. free_scan_listeners ();
  1298. c_free(state);
  1299. state = NULL;
  1300. }
  1301. static int enduser_setup_dns_start(void)
  1302. {
  1303. ENDUSER_SETUP_DEBUG("enduser_setup_dns_start");
  1304. if (state->espconn_dns_udp != NULL)
  1305. {
  1306. ENDUSER_SETUP_ERROR("dns_start failed. Appears to already be started (espconn_dns_udp != NULL).", ENDUSER_SETUP_ERR_ALREADY_INITIALIZED, ENDUSER_SETUP_ERR_FATAL);
  1307. }
  1308. state->espconn_dns_udp = (struct espconn *) c_malloc(sizeof(struct espconn));
  1309. if (state->espconn_dns_udp == NULL)
  1310. {
  1311. ENDUSER_SETUP_ERROR("dns_start failed. Memory allocation failed (espconn_dns_udp == NULL).", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  1312. }
  1313. esp_udp *esp_udp_data = (esp_udp *) c_malloc(sizeof(esp_udp));
  1314. if (esp_udp_data == NULL)
  1315. {
  1316. ENDUSER_SETUP_ERROR("dns_start failed. Memory allocation failed (esp_udp == NULL).", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  1317. }
  1318. c_memset(state->espconn_dns_udp, 0, sizeof(struct espconn));
  1319. c_memset(esp_udp_data, 0, sizeof(esp_udp));
  1320. state->espconn_dns_udp->proto.udp = esp_udp_data;
  1321. state->espconn_dns_udp->type = ESPCONN_UDP;
  1322. state->espconn_dns_udp->state = ESPCONN_NONE;
  1323. esp_udp_data->local_port = 53;
  1324. int8_t err;
  1325. err = espconn_regist_recvcb(state->espconn_dns_udp, enduser_setup_dns_recv_callback);
  1326. if (err != 0)
  1327. {
  1328. ENDUSER_SETUP_ERROR("dns_start failed. Couldn't add receive callback, unknown error.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  1329. }
  1330. err = espconn_create(state->espconn_dns_udp);
  1331. if (err == ESPCONN_ISCONN)
  1332. {
  1333. ENDUSER_SETUP_ERROR("dns_start failed. Couldn't create connection, already listening for that connection.", ENDUSER_SETUP_ERR_SOCKET_ALREADY_OPEN, ENDUSER_SETUP_ERR_FATAL);
  1334. }
  1335. else if (err == ESPCONN_MEM)
  1336. {
  1337. ENDUSER_SETUP_ERROR("dns_start failed. Couldn't create connection, out of memory.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  1338. }
  1339. else if (err != 0)
  1340. {
  1341. ENDUSER_SETUP_ERROR("dns_start failed. Couldn't create connection, unknown error.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  1342. }
  1343. return 0;
  1344. }
  1345. static void enduser_setup_dns_stop(void)
  1346. {
  1347. ENDUSER_SETUP_DEBUG("enduser_setup_dns_stop");
  1348. if (state != NULL && state->espconn_dns_udp != NULL)
  1349. {
  1350. espconn_delete(state->espconn_dns_udp);
  1351. }
  1352. }
  1353. static int enduser_setup_init(lua_State *L)
  1354. {
  1355. /* Note: Normal to not see this debug message on first invocation because debug callback is set below */
  1356. ENDUSER_SETUP_DEBUG("enduser_setup_init");
  1357. /* Defer errors until the bottom, so that callbacks can be set, if applicable, to handle debug and error messages */
  1358. int ret = 0;
  1359. if (state != NULL)
  1360. {
  1361. ret = ENDUSER_SETUP_ERR_ALREADY_INITIALIZED;
  1362. }
  1363. else
  1364. {
  1365. state = (enduser_setup_state_t *) os_zalloc(sizeof(enduser_setup_state_t));
  1366. if (state == NULL)
  1367. {
  1368. ret = ENDUSER_SETUP_ERR_OUT_OF_MEMORY;
  1369. }
  1370. else
  1371. {
  1372. c_memset(state, 0, sizeof(enduser_setup_state_t));
  1373. state->lua_connected_cb_ref = LUA_NOREF;
  1374. state->lua_err_cb_ref = LUA_NOREF;
  1375. state->lua_dbg_cb_ref = LUA_NOREF;
  1376. state->softAPchannel = 1;
  1377. state->success = 0;
  1378. state->callbackDone = 0;
  1379. state->lastStationStatus = 0;
  1380. state->connecting = 0;
  1381. }
  1382. }
  1383. if (!lua_isnoneornil(L, 1))
  1384. {
  1385. lua_pushvalue(L, 1);
  1386. state->lua_connected_cb_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  1387. }
  1388. if (!lua_isnoneornil(L, 2))
  1389. {
  1390. lua_pushvalue (L, 2);
  1391. state->lua_err_cb_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  1392. }
  1393. if (!lua_isnoneornil(L, 3))
  1394. {
  1395. lua_pushvalue (L, 3);
  1396. state->lua_dbg_cb_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  1397. ENDUSER_SETUP_DEBUG("enduser_setup_init: Debug callback has been set");
  1398. }
  1399. if (ret == ENDUSER_SETUP_ERR_ALREADY_INITIALIZED)
  1400. {
  1401. ENDUSER_SETUP_ERROR("init failed. Appears to already be started. EUS will shut down now.", ENDUSER_SETUP_ERR_ALREADY_INITIALIZED, ENDUSER_SETUP_ERR_FATAL);
  1402. }
  1403. else if (ret == ENDUSER_SETUP_ERR_OUT_OF_MEMORY)
  1404. {
  1405. ENDUSER_SETUP_ERROR("init failed. Unable to allocate memory.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  1406. }
  1407. return ret;
  1408. }
  1409. static int enduser_setup_manual(lua_State *L)
  1410. {
  1411. if (!lua_isnoneornil (L, 1))
  1412. {
  1413. manual = lua_toboolean (L, 1);
  1414. }
  1415. lua_pushboolean (L, manual);
  1416. return 1;
  1417. }
  1418. static int enduser_setup_start(lua_State *L)
  1419. {
  1420. /* Note: The debug callback is set in enduser_setup_init. It's normal to not see this debug message on first invocation. */
  1421. ENDUSER_SETUP_DEBUG("enduser_setup_start");
  1422. ipaddr[0] = '\0';
  1423. if (!do_station_cfg_handle)
  1424. {
  1425. do_station_cfg_handle = task_get_id(do_station_cfg);
  1426. }
  1427. if(enduser_setup_init(L))
  1428. {
  1429. goto failed;
  1430. }
  1431. if (!manual)
  1432. {
  1433. ENDUSER_SETUP_DEBUG("Performing AP Scan to identify likely AP's channel. Enabling Station if it wasn't already.");
  1434. wifi_set_opmode(STATION_MODE | wifi_get_opmode());
  1435. wifi_station_scan(NULL, on_initial_scan_done);
  1436. }
  1437. else
  1438. {
  1439. enduser_setup_check_station_start();
  1440. }
  1441. if(enduser_setup_dns_start())
  1442. {
  1443. goto failed;
  1444. }
  1445. if(enduser_setup_http_start())
  1446. {
  1447. goto failed;
  1448. }
  1449. goto out;
  1450. failed:
  1451. enduser_setup_stop(lua_getstate());
  1452. out:
  1453. return 0;
  1454. }
  1455. /**
  1456. * A wrapper needed for type-reasons strictness reasons.
  1457. */
  1458. static void enduser_setup_stop_callback(void *ptr)
  1459. {
  1460. enduser_setup_stop(lua_getstate());
  1461. }
  1462. static int enduser_setup_stop(lua_State* L)
  1463. {
  1464. ENDUSER_SETUP_DEBUG("enduser_setup_stop");
  1465. if (!manual)
  1466. {
  1467. enduser_setup_ap_stop();
  1468. }
  1469. if (state != NULL && state->success && !state->callbackDone)
  1470. {
  1471. wifi_set_opmode(STATION_MODE | wifi_get_opmode());
  1472. wifi_station_connect();
  1473. enduser_setup_connected_callback();
  1474. }
  1475. enduser_setup_dns_stop();
  1476. enduser_setup_http_stop();
  1477. enduser_setup_free();
  1478. return 0;
  1479. }
  1480. static const LUA_REG_TYPE enduser_setup_map[] = {
  1481. { LSTRKEY( "manual" ), LFUNCVAL( enduser_setup_manual )},
  1482. { LSTRKEY( "start" ), LFUNCVAL( enduser_setup_start )},
  1483. { LSTRKEY( "stop" ), LFUNCVAL( enduser_setup_stop )},
  1484. { LNILKEY, LNILVAL}
  1485. };
  1486. NODEMCU_MODULE(ENDUSER_SETUP, "enduser_setup", enduser_setup_map, NULL);