enduser_setup.c 61 KB

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