enduser_setup.c 56 KB

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