enduser_setup.c 51 KB

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