enduser_setup.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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. #include "module.h"
  34. #include "lauxlib.h"
  35. #include "platform.h"
  36. #include "c_stdlib.h"
  37. #include "c_string.h"
  38. #include "ctype.h"
  39. #include "user_interface.h"
  40. #include "espconn.h"
  41. #include "flash_fs.h"
  42. #define MIN(x, y) (((x) < (y)) ? (x) : (y))
  43. #define ENDUSER_SETUP_ERR_FATAL (1 << 0)
  44. #define ENDUSER_SETUP_ERR_NONFATAL (1 << 1)
  45. #define ENDUSER_SETUP_ERR_NO_RETURN (1 << 2)
  46. #define ENDUSER_SETUP_ERR_OUT_OF_MEMORY 1
  47. #define ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND 2
  48. #define ENDUSER_SETUP_ERR_UNKOWN_ERROR 3
  49. #define ENDUSER_SETUP_ERR_SOCKET_ALREADY_OPEN 4
  50. /**
  51. * DNS Response Packet:
  52. *
  53. * |DNS ID - 16 bits|
  54. * |dns_header|
  55. * |QNAME|
  56. * |dns_body|
  57. * |ip - 32 bits|
  58. *
  59. * DNS Header Part | FLAGS | | Q COUNT | | A CNT | |AUTH CNT| | ADD CNT| */
  60. static const char dns_header[] = { 0x80, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00 };
  61. /* DNS Query Part | Q TYPE | | Q CLASS| */
  62. static const char dns_body[] = { 0x00, 0x01, 0x00, 0x01,
  63. /* DNS Answer Part |LBL OFFS| | TYPE | | CLASS | | TTL | | RD LEN | */
  64. 0xC0, 0x0C, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x04 };
  65. static const char http_html_filename[] = "index.html";
  66. static const char http_header_200[] = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
  67. static const char http_header_404[] = "HTTP/1.1 404 Not Found\r\n";
  68. static const char http_html_backup[] = "<!DOCTYPE html><html><head><meta charset=utf-8><meta name=viewport content='width=380'><title>Connect gadget to you WiFi</title><style media=screen type=text/css>*{margin:0;padding:0}html{height:100%;background:linear-gradient(rgba(196,102,0,.2),rgba(155,89,182,.2)),url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEYAAAA8AgMAAACm+SSwAAAADFBMVEVBR1FFS1VHTlg8Q0zU/YXIAAADVElEQVQ4yy1TTYvTUBQ9GTKiYNoodsCF4MK6U4TZChOhiguFWHyBFzqlLl4hoeNvEBeCrlrhBVKq1EUKLTP+hvi1GyguXqBdiZCBzGqg20K8L3hDQnK55+OeJNguHx6UujYl3dL5ALn4JOIUluAqeAWciyGaSdvngOWzNT+G0UyGUOxVOAdqkjXDCbBiUyjZ5QzYEbGadYAi6kHxth+kthXNVNCDofwhGv1D4QGGiM9iAjbCHgr2iUUpDJbs+VPQ4xAr2fX7KXbkOJMdok965Ksb+6lrjdkem8AshIuHm9Nyu19uTunYlOXDTQqi8VgeH0kBXH2xq/ouiMZPzuMukymutrBmulUTovC6HqNFW2ZOiqlpSXZOTvSUeUPxChjxol8BLbRy4gJuhV7OR4LRVBs3WQ9VVAU7SXgK2HeUrOj7bC8YsUgr3lEV/TXB7hK90EBnxaeg1Ov15bY80M736ekCGesGAaGvG0Ct4WRkVQVHIgIM9xJgvSFfPay8Q6GNv7VpR7xUnkvhnMQCJDYkYOtNLihV70tCU1Sk+BQrpoP+HLHUrJkuta40C6LP5GvBv+Hqo10ATxxFrTPvNdPr7XwgQud6RvQN/sXjBGzqbU27wcj9cgsyvSTrpyXV8gKpXeNJU3aFl7MOdldzV4+HfO19jBa5f2IjWwx1OLHIvFHkqbBj20ro1g7nDfY1DpScvDRUNARgjMMVO0zoMjKxJ6uWCPP+YRAWbGoaN8kXYHmLjB9FXLGOazfFVCvOgqzfnicNPrHtPKlex2ye824gMza0cTZ2sS2Xm7Qst/UfFw8O6vVtmUKxZy9xFgzMys5cJ5fxZw4y37Ufk1Dsfb8MqOjYxE3ZMWxiDcO0PYUaD2ys+8OW1pbB7/e3sfZeGVCL0Q2aMjjPdm2sxADuejZxHJAd8dO9DSUdA0V8/NggRRanDkBrANn8yHlEQOn/MmwoQfQF7xgmKDnv520bS/pgylP67vf3y2V5sCwfoCEMkZClgOfJAFX9eXefR2RpnmRs4CDVPceaRfoFzCkJVJX27vWZnoqyvmtXU3+dW1EIXIu8Qg5Qta4Zlv7drUCoWe8/8MXzaEwux7ESE9h6qnHj3mIO0/D9RvzfxPmjWiQ1vbeSk4rrHwhAre35EEVaAAAAAElFTkSuQmCC)}body{font-family:arial,verdana}div{position:absolute;margin:auto;top:0;right:0;bottom:0;left:0;width:320px;height:274px}form{width:320px;text-align:center;position:relative}form fieldset{background:#fff;border:0 none;border-radius:5px;box-shadow:0 0 15px 1px rgba(0,0,0,.4);padding:20px 30px;box-sizing:border-box}form input{padding:15px;border:1px solid #ccc;border-radius:3px;margin-bottom:10px;width:100%;box-sizing:border-box;font-family:montserrat;color:#2C3E50;font-size:13px}form .action-button{width:100px;background:#27AE60;font-weight:700;color:#fff;border:0 none;border-radius:3px;cursor:pointer;padding:10px 5px;margin:10px 5px}#msform .action-button:focus,form .action-button:hover{box-shadow:0 0 0 2px #fff,0 0 0 3px #27AE60}.fs-title{font-size:15px;text-transform:uppercase;color:#2C3E50;margin-bottom:10px}.fs-subtitle{font-weight:400;font-size:13px;color:#666;margin-bottom:20px}</style><body><div><form method='post'><fieldset><h2 class=fs-title>WiFi Login</h2><h3 class=fs-subtitle>Connect gadget to your WiFi</h3><input autocorrect=off autocapitalize=none name=wifi_ssid placeholder='WiFi Name'> <input type=password name=wifi_password placeholder='Password'1> <input type=submit name=save class='submit action-button' value='Save'></fieldset></form></div>";
  69. typedef struct
  70. {
  71. lua_State *lua_L;
  72. struct espconn *espconn_dns_udp;
  73. struct espconn *espconn_http_tcp;
  74. char *http_payload_data;
  75. uint32_t http_payload_len;
  76. os_timer_t check_station_timer;
  77. int lua_connected_cb_ref;
  78. int lua_err_cb_ref;
  79. int lua_dbg_cb_ref;
  80. } enduser_setup_state_t;
  81. static enduser_setup_state_t *state;
  82. static int enduser_setup_start(lua_State* L);
  83. static int enduser_setup_stop(lua_State* L);
  84. static void enduser_setup_station_start(void);
  85. static void enduser_setup_station_start(void);
  86. static void enduser_setup_ap_start(void);
  87. static void enduser_setup_ap_stop(void);
  88. static void enduser_setup_check_station(void *p);
  89. static void enduser_setup_debug(lua_State *L, const char *str);
  90. #define ENDUSER_SETUP_DEBUG_ENABLE 0
  91. #if ENDUSER_SETUP_DEBUG_ENABLE
  92. #define ENDUSER_SETUP_DEBUG(l, str) enduser_setup_debug(l, str)
  93. #else
  94. #define ENDUSER_SETUP_DEBUG(l, str)
  95. #endif
  96. static void enduser_setup_debug(lua_State *L, const char *str)
  97. {
  98. if(state != NULL && L != NULL && state->lua_dbg_cb_ref != LUA_NOREF)
  99. {
  100. lua_rawgeti(L, LUA_REGISTRYINDEX, state->lua_dbg_cb_ref);
  101. lua_pushstring(L, str);
  102. lua_call(L, 1, 0);
  103. }
  104. }
  105. #define ENDUSER_SETUP_ERROR(str, err, err_severity) if (err_severity & ENDUSER_SETUP_ERR_FATAL) enduser_setup_stop(state->lua_L);\
  106. enduser_setup_error(state->lua_L, str, err);\
  107. if (!(err_severity & ENDUSER_SETUP_ERR_NO_RETURN)) return err
  108. #define ENDUSER_SETUP_ERROR_VOID(str, err, err_severity) if (err_severity & ENDUSER_SETUP_ERR_FATAL) enduser_setup_stop(state->lua_L);\
  109. enduser_setup_error(state->lua_L, str, err);\
  110. if (!(err_severity & ENDUSER_SETUP_ERR_NO_RETURN)) return
  111. static void enduser_setup_error(lua_State *L, const char *str, int err)
  112. {
  113. ENDUSER_SETUP_DEBUG(L, "enduser_setup_error");
  114. if (state != NULL && L != NULL && state->lua_err_cb_ref != LUA_NOREF)
  115. {
  116. lua_rawgeti (L, LUA_REGISTRYINDEX, state->lua_err_cb_ref);
  117. lua_pushnumber(L, err);
  118. lua_pushstring(L, str);
  119. lua_call (L, 2, 0);
  120. }
  121. }
  122. static void enduser_setup_connected_callback(lua_State *L)
  123. {
  124. ENDUSER_SETUP_DEBUG(L, "enduser_setup_connected_callback");
  125. if(state != NULL && L != NULL && state->lua_connected_cb_ref != LUA_NOREF)
  126. {
  127. lua_rawgeti(L, LUA_REGISTRYINDEX, state->lua_connected_cb_ref);
  128. lua_call(L, 0, 0);
  129. }
  130. }
  131. static void enduser_setup_check_station_start(void)
  132. {
  133. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_check_station_start");
  134. os_timer_setfn(&(state->check_station_timer), enduser_setup_check_station, NULL);
  135. os_timer_arm(&(state->check_station_timer), 1*1000, TRUE);
  136. }
  137. static void enduser_setup_check_station_stop(void)
  138. {
  139. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_check_station_stop");
  140. os_timer_disarm(&(state->check_station_timer));
  141. }
  142. /**
  143. * Check Station
  144. *
  145. * Check that we've successfully entered station mode.
  146. */
  147. static void enduser_setup_check_station(void *p)
  148. {
  149. (void)p;
  150. struct ip_info ip;
  151. c_memset(&ip, 0, sizeof(struct ip_info));
  152. wifi_get_ip_info(STATION_IF, &ip);
  153. int i;
  154. char has_ip = 0;
  155. for (i = 0; i < sizeof(struct ip_info); ++i)
  156. {
  157. has_ip |= ((char *) &ip)[i];
  158. }
  159. if (has_ip == 0)
  160. {
  161. return;
  162. }
  163. struct station_config cnf;
  164. wifi_station_get_config(&cnf);
  165. enduser_setup_connected_callback(state->lua_L);
  166. enduser_setup_stop(NULL);
  167. }
  168. /**
  169. * Search String
  170. *
  171. * Search string for first occurance of any char in srch_str.
  172. *
  173. * @return -1 iff no occurance of char was found.
  174. */
  175. static int enduser_setup_srch_str(const char *str, const char *srch_str)
  176. {
  177. int srch_str_len = c_strlen(srch_str);
  178. int first_hit = INT_MAX;
  179. int i;
  180. for (i = 0; i < srch_str_len; ++i)
  181. {
  182. char *char_ptr = strchr(str, srch_str[i]);
  183. if (char_ptr == NULL)
  184. {
  185. continue;
  186. }
  187. int char_idx = char_ptr - str;
  188. first_hit = MIN(first_hit, char_idx);
  189. }
  190. if (first_hit == INT_MAX)
  191. {
  192. return -1;
  193. }
  194. return first_hit;
  195. }
  196. /**
  197. * Load HTTP Payload
  198. *
  199. * @return - 0 iff payload loaded successfully
  200. * 1 iff backup html was loaded
  201. * 2 iff out of memory
  202. */
  203. static int enduser_setup_http_load_payload(void)
  204. {
  205. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_load_payload");
  206. int f = fs_open(http_html_filename, fs_mode2flag("r"));
  207. int err = fs_seek(f, 0, FS_SEEK_END);
  208. int file_len = (int) fs_tell(f);
  209. int err2 = fs_seek(f, 0, FS_SEEK_SET);
  210. if (f == 0 || err == -1 || err2 == -1)
  211. {
  212. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_load_payload unable to load file index.html, loading backup HTML.");
  213. int payload_len = sizeof(http_header_200) + sizeof(http_html_backup);
  214. state->http_payload_len = payload_len;
  215. state->http_payload_data = (char *) c_malloc(payload_len);
  216. if (state->http_payload_data == NULL)
  217. {
  218. return 2;
  219. }
  220. int offset = 0;
  221. c_memcpy(&(state->http_payload_data[offset]), &(http_header_200), sizeof(http_header_200));
  222. offset += sizeof(http_header_200);
  223. c_memcpy(&(state->http_payload_data[offset]), &(http_html_backup), sizeof(http_html_backup));
  224. return 1;
  225. }
  226. int payload_len = sizeof(http_header_200) + file_len;
  227. state->http_payload_len = payload_len;
  228. state->http_payload_data = (char *) c_malloc(payload_len);
  229. if (state->http_payload_data == NULL)
  230. {
  231. return 2;
  232. }
  233. int offset = 0;
  234. c_memcpy(&(state->http_payload_data[offset]), &(http_header_200), sizeof(http_header_200));
  235. offset += sizeof(http_header_200);
  236. fs_read(f, &(state->http_payload_data[offset]), file_len);
  237. return 0;
  238. }
  239. /**
  240. * De-escape URL data
  241. *
  242. * Parse escaped and form encoded data of request.
  243. */
  244. static void enduser_setup_http_urldecode(char *dst, const char *src, int src_len)
  245. {
  246. char a, b;
  247. int i;
  248. for (i = 0; i < src_len && *src; ++i)
  249. {
  250. if ((*src == '%') && ((a = src[1]) && (b = src[2])) && (isxdigit(a) && isxdigit(b)))
  251. {
  252. if (a >= 'a')
  253. {
  254. a -= 'a'-'A';
  255. }
  256. if (a >= 'A')
  257. {
  258. a -= ('A' - 10);
  259. }
  260. else
  261. {
  262. a -= '0';
  263. }
  264. if (b >= 'a')
  265. {
  266. b -= 'a'-'A';
  267. }
  268. if (b >= 'A')
  269. {
  270. b -= ('A' - 10);
  271. }
  272. else
  273. {
  274. b -= '0';
  275. }
  276. *dst++ = 16 * a + b;
  277. src += 3;
  278. i += 2;
  279. } else {
  280. char c = *src++;
  281. if (c == '+')
  282. {
  283. c = ' ';
  284. }
  285. *dst++ = c;
  286. }
  287. }
  288. *dst++ = '\0';
  289. }
  290. /**
  291. * Handle HTTP Credentials
  292. *
  293. * @return - return 0 iff credentials are found and handled successfully
  294. * return 1 iff credentials aren't found
  295. * return 2 iff an error occured
  296. */
  297. static int enduser_setup_http_handle_credentials(char *data, unsigned short data_len)
  298. {
  299. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_handle_credentials");
  300. char *name_str = (char *) ((uint32_t)strstr(&(data[6]), "wifi_ssid="));
  301. char *pwd_str = (char *) ((uint32_t)strstr(&(data[6]), "wifi_password="));
  302. if (name_str == NULL || pwd_str == NULL)
  303. {
  304. return 1;
  305. }
  306. int name_field_len = sizeof("wifi_ssid=") - 1;
  307. int pwd_field_len = sizeof("wifi_password=") - 1;
  308. char *name_str_start = name_str + name_field_len;
  309. char *pwd_str_start = pwd_str + pwd_field_len;
  310. int name_str_len = enduser_setup_srch_str(name_str_start, "& ");
  311. int pwd_str_len = enduser_setup_srch_str(pwd_str_start, "& ");
  312. if (name_str_len == -1 || pwd_str_len == -1 || name_str_len > 31 || pwd_str_len > 63)
  313. {
  314. return 1;
  315. }
  316. struct station_config cnf;
  317. c_memset(&cnf, 0, sizeof(struct station_config));
  318. enduser_setup_http_urldecode(cnf.ssid, name_str_start, name_str_len);
  319. enduser_setup_http_urldecode(cnf.password, pwd_str_start, pwd_str_len);
  320. int err = wifi_set_opmode(STATION_MODE | wifi_get_opmode());
  321. if (err == FALSE)
  322. {
  323. wifi_set_opmode(~STATION_MODE & wifi_get_opmode());
  324. ENDUSER_SETUP_ERROR("enduser_setup_station_start failed. wifi_set_opmode failed.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  325. }
  326. err = wifi_station_set_config(&cnf);
  327. if (err == FALSE)
  328. {
  329. wifi_set_opmode(~STATION_MODE & wifi_get_opmode());
  330. ENDUSER_SETUP_ERROR("enduser_setup_station_start failed. wifi_station_set_config failed.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  331. }
  332. err = wifi_station_disconnect();
  333. if (err == FALSE)
  334. {
  335. ENDUSER_SETUP_ERROR("enduser_setup_station_start failed. wifi_station_disconnect failed.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
  336. }
  337. err = wifi_station_connect();
  338. if (err == FALSE)
  339. {
  340. ENDUSER_SETUP_ERROR("enduser_setup_station_start failed. wifi_station_connect failed.\n", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  341. }
  342. ENDUSER_SETUP_DEBUG(state->lua_L, "WiFi Credentials Stored");
  343. ENDUSER_SETUP_DEBUG(state->lua_L, "-----------------------");
  344. ENDUSER_SETUP_DEBUG(state->lua_L, "name: ");
  345. ENDUSER_SETUP_DEBUG(state->lua_L, cnf.ssid);
  346. ENDUSER_SETUP_DEBUG(state->lua_L, "pass: ");
  347. ENDUSER_SETUP_DEBUG(state->lua_L, cnf.password);
  348. ENDUSER_SETUP_DEBUG(state->lua_L, "-----------------------");
  349. return 0;
  350. }
  351. /**
  352. * Serve HTML
  353. *
  354. * @return - return 0 iff html was served successfully
  355. */
  356. static int enduser_setup_http_serve_header(struct espconn *http_client, char *header, uint32_t header_len)
  357. {
  358. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_serve_404");
  359. int8_t err = espconn_sent(http_client, header, header_len);
  360. if (err == ESPCONN_MEM)
  361. {
  362. ENDUSER_SETUP_ERROR("enduser_setup_http_serve_header failed. espconn_send out of memory", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_NONFATAL);
  363. }
  364. else if (err == ESPCONN_ARG)
  365. {
  366. ENDUSER_SETUP_ERROR("enduser_setup_http_serve_header failed. espconn_send can't find network transmission", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_NONFATAL);
  367. }
  368. else if (err != 0)
  369. {
  370. ENDUSER_SETUP_ERROR("enduser_setup_http_serve_header failed. espconn_send failed", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
  371. }
  372. return 0;
  373. }
  374. /**
  375. * Serve HTML
  376. *
  377. * @return - return 0 iff html was served successfully
  378. */
  379. static int enduser_setup_http_serve_html(struct espconn *http_client)
  380. {
  381. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_serve_html");
  382. if (state->http_payload_data == NULL)
  383. {
  384. enduser_setup_http_load_payload();
  385. }
  386. int8_t err = espconn_sent(http_client, state->http_payload_data, state->http_payload_len);
  387. if (err == ESPCONN_MEM)
  388. {
  389. ENDUSER_SETUP_ERROR("enduser_setup_http_serve_html failed. espconn_send out of memory", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_NONFATAL);
  390. }
  391. else if (err == ESPCONN_ARG)
  392. {
  393. ENDUSER_SETUP_ERROR("enduser_setup_http_serve_html failed. espconn_send can't find network transmission", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_NONFATAL);
  394. }
  395. else if (err != 0)
  396. {
  397. ENDUSER_SETUP_ERROR("enduser_setup_http_serve_html failed. espconn_send failed", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
  398. }
  399. return 0;
  400. }
  401. /**
  402. * Disconnect HTTP client
  403. *
  404. * End TCP connection and free up resources.
  405. */
  406. static void enduser_setup_http_disconnect(struct espconn *espconn)
  407. {
  408. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_disconnect");
  409. //TODO: Construct and maintain os task queue(?) to be able to issue system_os_task with espconn_disconnect.
  410. }
  411. static void enduser_setup_http_recvcb(void *arg, char *data, unsigned short data_len)
  412. {
  413. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_recvcb");
  414. struct espconn *http_client = (struct espconn *) arg;
  415. int retval;
  416. if (c_strncmp(data, "POST ", 5) == 0)
  417. {
  418. retval = enduser_setup_http_handle_credentials(data, data_len);
  419. if (retval == 0)
  420. {
  421. enduser_setup_http_serve_header(http_client, (char *) http_header_200, sizeof(http_header_200));
  422. enduser_setup_http_disconnect(http_client);
  423. return;
  424. }
  425. else if (retval == 2)
  426. {
  427. ENDUSER_SETUP_ERROR_VOID("enduser_setup_http_recvcb failed. Failed to handle wifi credentials.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
  428. }
  429. if (retval != 1)
  430. {
  431. ENDUSER_SETUP_ERROR_VOID("enduser_setup_http_recvcb failed. Unknown error code.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
  432. }
  433. }
  434. else if (c_strncmp(data, "GET ", 4) == 0)
  435. {
  436. /* Reject requests that probably aren't relevant to free up resources. */
  437. if (c_strncmp(data, "GET / ", 6) != 0)
  438. {
  439. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_recvcb received too specific request.");
  440. enduser_setup_http_serve_header(http_client, (char *) http_header_404, sizeof(http_header_404));
  441. enduser_setup_http_disconnect(http_client);
  442. return;
  443. }
  444. retval = enduser_setup_http_serve_html(http_client);
  445. if (retval != 0)
  446. {
  447. enduser_setup_http_disconnect(http_client);
  448. ENDUSER_SETUP_ERROR_VOID("enduser_setup_http_recvcb failed. Unable to send HTML.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
  449. }
  450. }
  451. else
  452. {
  453. enduser_setup_http_serve_header(http_client, (char *) http_header_404, sizeof(http_header_404));
  454. enduser_setup_http_disconnect(http_client);
  455. return;
  456. }
  457. }
  458. static void enduser_setup_http_connectcb(void *arg)
  459. {
  460. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_connectcb");
  461. struct espconn *callback_espconn = (struct espconn *) arg;
  462. int8_t err = 0;
  463. err |= espconn_regist_recvcb(callback_espconn, enduser_setup_http_recvcb);
  464. if (err != 0)
  465. {
  466. ENDUSER_SETUP_ERROR_VOID("enduser_setup_http_connectcb failed. Callback registration failed.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
  467. }
  468. }
  469. static int enduser_setup_http_start(void)
  470. {
  471. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_start");
  472. state->espconn_http_tcp = (struct espconn *) c_malloc(sizeof(struct espconn));
  473. if (state->espconn_http_tcp == NULL)
  474. {
  475. ENDUSER_SETUP_ERROR("enduser_setup_http_start failed. Memory allocation failed (espconn_http_tcp == NULL).", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  476. }
  477. esp_tcp *esp_tcp_data = (esp_tcp *) c_malloc(sizeof(esp_tcp));
  478. if (esp_tcp_data == NULL)
  479. {
  480. ENDUSER_SETUP_ERROR("enduser_setup_http_start failed. Memory allocation failed (esp_udp == NULL).", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  481. }
  482. c_memset(state->espconn_http_tcp, 0, sizeof(struct espconn));
  483. c_memset(esp_tcp_data, 0, sizeof(esp_tcp));
  484. state->espconn_http_tcp->proto.tcp = esp_tcp_data;
  485. state->espconn_http_tcp->type = ESPCONN_TCP;
  486. state->espconn_http_tcp->state = ESPCONN_NONE;
  487. esp_tcp_data->local_port = 80;
  488. int8_t err;
  489. err = espconn_regist_connectcb(state->espconn_http_tcp, enduser_setup_http_connectcb);
  490. if (err != 0)
  491. {
  492. ENDUSER_SETUP_ERROR("enduser_setup_http_start failed. Couldn't add receive callback.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  493. }
  494. err = espconn_accept(state->espconn_http_tcp);
  495. if (err == ESPCONN_ISCONN)
  496. {
  497. ENDUSER_SETUP_ERROR("enduser_setup_http_start failed. Couldn't create connection, already listening for that connection.", ENDUSER_SETUP_ERR_SOCKET_ALREADY_OPEN, ENDUSER_SETUP_ERR_FATAL);
  498. }
  499. else if (err == ESPCONN_MEM)
  500. {
  501. ENDUSER_SETUP_ERROR("enduser_setup_http_start failed. Couldn't create connection, out of memory.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  502. }
  503. else if (err == ESPCONN_ARG)
  504. {
  505. ENDUSER_SETUP_ERROR("enduser_setup_http_start failed. Can't find connection from espconn argument", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_FATAL);
  506. }
  507. else if (err != 0)
  508. {
  509. ENDUSER_SETUP_ERROR("enduser_setup_http_start failed. Unknown error", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  510. }
  511. err = espconn_regist_time(state->espconn_http_tcp, 2, 0);
  512. if (err == ESPCONN_ARG)
  513. {
  514. ENDUSER_SETUP_ERROR("enduser_setup_http_start failed. Unable to set TCP timeout.", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_NONFATAL | ENDUSER_SETUP_ERR_NO_RETURN);
  515. }
  516. err = enduser_setup_http_load_payload();
  517. if (err == 1)
  518. {
  519. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_start info. Loaded backup HTML.");
  520. }
  521. else if (err == 2)
  522. {
  523. ENDUSER_SETUP_ERROR("enduser_setup_http_start failed. Unable to allocate memory for HTTP payload.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  524. }
  525. return 0;
  526. }
  527. static void enduser_setup_http_stop(void)
  528. {
  529. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_http_stop");
  530. if (state != NULL && state->espconn_http_tcp != NULL)
  531. {
  532. espconn_delete(state->espconn_http_tcp);
  533. }
  534. }
  535. static void enduser_setup_ap_stop(void)
  536. {
  537. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_station_stop");
  538. wifi_set_opmode(~SOFTAP_MODE & wifi_get_opmode());
  539. }
  540. static void enduser_setup_ap_start(void)
  541. {
  542. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_ap_start");
  543. struct softap_config cnf;
  544. c_memset(&(cnf), 0, sizeof(struct softap_config));
  545. #ifndef ENDUSER_SETUP_AP_SSID
  546. #define ENDUSER_SETUP_AP_SSID "SetupGadget"
  547. #endif
  548. char ssid[] = ENDUSER_SETUP_AP_SSID;
  549. int ssid_name_len = c_strlen(ENDUSER_SETUP_AP_SSID);
  550. c_memcpy(&(cnf.ssid), ssid, ssid_name_len);
  551. uint8_t mac[6];
  552. wifi_get_macaddr(SOFTAP_IF, mac);
  553. cnf.ssid[ssid_name_len] = '_';
  554. cnf.ssid[ssid_name_len + 1] = (char) (65 + (0x0F & mac[3]));
  555. cnf.ssid[ssid_name_len + 2] = (char) (65 + ((0xF0 & mac[3]) >> 4));
  556. cnf.ssid[ssid_name_len + 3] = (char) (65 + (0x0F & mac[4]));
  557. cnf.ssid[ssid_name_len + 4] = (char) (65 + ((0xF0 & mac[4]) >> 4));
  558. cnf.ssid[ssid_name_len + 5] = (char) (65 + (0x0F & mac[5]));
  559. cnf.ssid[ssid_name_len + 6] = (char) (65 + ((0xF0 & mac[5]) >> 4));
  560. cnf.ssid_len = c_strlen(ssid) + 7;
  561. cnf.channel = 1;
  562. cnf.authmode = AUTH_OPEN;
  563. cnf.ssid_hidden = 0;
  564. cnf.max_connection = 5;
  565. cnf.beacon_interval = 100;
  566. wifi_softap_set_config(&cnf);
  567. wifi_set_opmode(SOFTAP_MODE | wifi_get_opmode());
  568. }
  569. static void enduser_setup_dns_recv_callback(void *arg, char *recv_data, unsigned short recv_len)
  570. {
  571. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_dns_recv_callback.");
  572. struct espconn *callback_espconn = arg;
  573. struct ip_info ip_info;
  574. uint32_t qname_len = c_strlen(&(recv_data[12])) + 1; // \0=1byte
  575. uint32_t dns_reply_static_len = (uint32_t) sizeof(dns_header) + (uint32_t) sizeof(dns_body) + 2 + 4; // dns_id=2bytes, ip=4bytes
  576. uint32_t dns_reply_len = dns_reply_static_len + qname_len;
  577. uint8_t if_mode = wifi_get_opmode();
  578. if ((if_mode & SOFTAP_MODE) == 0)
  579. {
  580. ENDUSER_SETUP_ERROR_VOID("enduser_setup_dns_recv_callback failed. Interface mode not supported.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  581. }
  582. uint8_t if_index = (if_mode == STATION_MODE? STATION_IF : SOFTAP_IF);
  583. if (wifi_get_ip_info(if_index , &ip_info) == false)
  584. {
  585. ENDUSER_SETUP_ERROR_VOID("enduser_setup_dns_recv_callback failed. Unable to get interface IP.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  586. }
  587. char *dns_reply = (char *) c_malloc(dns_reply_len);
  588. if (dns_reply == NULL)
  589. {
  590. ENDUSER_SETUP_ERROR_VOID("enduser_setup_dns_recv_callback failed. Failed to allocate memory.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_NONFATAL);
  591. }
  592. uint32_t insert_byte = 0;
  593. c_memcpy(&(dns_reply[insert_byte]), recv_data, 2);
  594. insert_byte += 2;
  595. c_memcpy(&(dns_reply[insert_byte]), dns_header, sizeof(dns_header));
  596. insert_byte += (uint32_t) sizeof(dns_header);
  597. c_memcpy(&(dns_reply[insert_byte]), &(recv_data[12]), qname_len);
  598. insert_byte += qname_len;
  599. c_memcpy(&(dns_reply[insert_byte]), dns_body, sizeof(dns_body));
  600. insert_byte += (uint32_t) sizeof(dns_body);
  601. c_memcpy(&(dns_reply[insert_byte]), &(ip_info.ip), 4);
  602. // SDK 1.4.0 changed behaviour, for UDP server need to look up remote ip/port
  603. remot_info *pr = 0;
  604. if (espconn_get_connection_info(callback_espconn, &pr, 0) != ESPCONN_OK)
  605. {
  606. ENDUSER_SETUP_ERROR_VOID("enduser_setup_dns_recv_callback failed. Unable to get IP of UDP sender.", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_FATAL);
  607. }
  608. callback_espconn->proto.udp->remote_port = pr->remote_port;
  609. os_memmove(callback_espconn->proto.udp->remote_ip, pr->remote_ip, 4);
  610. int8_t err;
  611. err = espconn_sent(callback_espconn, dns_reply, dns_reply_len);
  612. c_free(dns_reply);
  613. if (err == ESPCONN_MEM)
  614. {
  615. ENDUSER_SETUP_ERROR_VOID("enduser_setup_dns_recv_callback failed. Failed to allocate memory for send.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  616. }
  617. else if (err == ESPCONN_ARG)
  618. {
  619. ENDUSER_SETUP_ERROR_VOID("enduser_setup_dns_recv_callback failed. Can't execute transmission.", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_FATAL);
  620. }
  621. else if (err != 0)
  622. {
  623. ENDUSER_SETUP_ERROR_VOID("enduser_setup_dns_recv_callback failed. espconn_send failed", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  624. }
  625. }
  626. static void enduser_setup_free(void)
  627. {
  628. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_free");
  629. if (state == NULL)
  630. {
  631. return;
  632. }
  633. if (state->espconn_dns_udp != NULL)
  634. {
  635. if (state->espconn_dns_udp->proto.udp != NULL)
  636. {
  637. c_free(state->espconn_dns_udp->proto.udp);
  638. }
  639. c_free(state->espconn_dns_udp);
  640. }
  641. if (state->espconn_http_tcp != NULL)
  642. {
  643. if (state->espconn_http_tcp->proto.tcp != NULL)
  644. {
  645. c_free(state->espconn_http_tcp->proto.tcp);
  646. }
  647. c_free(state->espconn_http_tcp);
  648. }
  649. c_free(state->http_payload_data);
  650. c_free(state);
  651. state = NULL;
  652. }
  653. static int enduser_setup_dns_start(void)
  654. {
  655. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_dns_start");
  656. if (state->espconn_dns_udp != NULL)
  657. {
  658. ENDUSER_SETUP_ERROR("enduser_setup_dns_start failed. Appears to already be started (espconn_dns_udp != NULL).", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  659. }
  660. state->espconn_dns_udp = (struct espconn *) c_malloc(sizeof(struct espconn));
  661. if (state->espconn_dns_udp == NULL)
  662. {
  663. ENDUSER_SETUP_ERROR("enduser_setup_dns_start failed. Memory allocation failed (espconn_dns_udp == NULL).", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  664. }
  665. esp_udp *esp_udp_data = (esp_udp *) c_malloc(sizeof(esp_udp));
  666. if (esp_udp_data == NULL)
  667. {
  668. ENDUSER_SETUP_ERROR("enduser_setup_dns_start failed. Memory allocation failed (esp_udp == NULL).", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  669. }
  670. c_memset(state->espconn_dns_udp, 0, sizeof(struct espconn));
  671. c_memset(esp_udp_data, 0, sizeof(esp_udp));
  672. state->espconn_dns_udp->proto.udp = esp_udp_data;
  673. state->espconn_dns_udp->type = ESPCONN_UDP;
  674. state->espconn_dns_udp->state = ESPCONN_NONE;
  675. esp_udp_data->local_port = 53;
  676. int8_t err;
  677. err = espconn_regist_recvcb(state->espconn_dns_udp, enduser_setup_dns_recv_callback);
  678. if (err != 0)
  679. {
  680. ENDUSER_SETUP_ERROR("enduser_setup_dns_start failed. Couldn't add receive callback, unknown error.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  681. }
  682. err = espconn_create(state->espconn_dns_udp);
  683. if (err == ESPCONN_ISCONN)
  684. {
  685. ENDUSER_SETUP_ERROR("enduser_setup_dns_start failed. Couldn't create connection, already listening for that connection.", ENDUSER_SETUP_ERR_SOCKET_ALREADY_OPEN, ENDUSER_SETUP_ERR_FATAL);
  686. }
  687. else if (err == ESPCONN_MEM)
  688. {
  689. ENDUSER_SETUP_ERROR("enduser_setup_dns_start failed. Couldn't create connection, out of memory.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  690. }
  691. else if (err != 0)
  692. {
  693. ENDUSER_SETUP_ERROR("enduser_setup_dns_start failed. Couldn't create connection, unknown error.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  694. }
  695. return 0;
  696. }
  697. static void enduser_setup_dns_stop(void)
  698. {
  699. ENDUSER_SETUP_DEBUG(state->lua_L, "enduser_setup_dns_stop");
  700. if (state->espconn_dns_udp != NULL)
  701. {
  702. espconn_delete(state->espconn_dns_udp);
  703. }
  704. }
  705. static int enduser_setup_init(lua_State *L)
  706. {
  707. ENDUSER_SETUP_DEBUG(L, "enduser_setup_init");
  708. if (state != NULL)
  709. {
  710. enduser_setup_error(L, "enduser_setup_init failed. Appears to already be started.", ENDUSER_SETUP_ERR_UNKOWN_ERROR);
  711. return ENDUSER_SETUP_ERR_UNKOWN_ERROR;
  712. }
  713. state = (enduser_setup_state_t *) os_malloc(sizeof(enduser_setup_state_t));
  714. if (state == NULL)
  715. {
  716. enduser_setup_error(L, "enduser_setup_init failed. Unable to allocate memory.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY);
  717. return ENDUSER_SETUP_ERR_OUT_OF_MEMORY;
  718. }
  719. c_memset(state, 0, sizeof(enduser_setup_state_t));
  720. state->lua_L = L;
  721. state->lua_connected_cb_ref = LUA_NOREF;
  722. state->lua_err_cb_ref = LUA_NOREF;
  723. state->lua_dbg_cb_ref = LUA_NOREF;
  724. if (!lua_isnoneornil(L, 1))
  725. {
  726. lua_pushvalue(L, 1);
  727. state->lua_connected_cb_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  728. }
  729. else
  730. {
  731. state->lua_connected_cb_ref = LUA_NOREF;
  732. }
  733. if (!lua_isnoneornil(L, 2))
  734. {
  735. lua_pushvalue (L, 2);
  736. state->lua_err_cb_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  737. }
  738. else
  739. {
  740. state->lua_err_cb_ref = LUA_NOREF;
  741. }
  742. if (!lua_isnoneornil(L, 3))
  743. {
  744. lua_pushvalue (L, 3);
  745. state->lua_dbg_cb_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  746. }
  747. else
  748. {
  749. state->lua_dbg_cb_ref = LUA_NOREF;
  750. }
  751. return 0;
  752. }
  753. static int enduser_setup_start(lua_State *L)
  754. {
  755. ENDUSER_SETUP_DEBUG(L, "enduser_setup_start");
  756. if(enduser_setup_init(L))
  757. {
  758. enduser_setup_stop(L);
  759. return 0;
  760. }
  761. enduser_setup_check_station_start();
  762. enduser_setup_ap_start();
  763. if(enduser_setup_dns_start())
  764. {
  765. enduser_setup_stop(L);
  766. return 0;
  767. }
  768. if(enduser_setup_http_start())
  769. {
  770. enduser_setup_stop(L);
  771. return 0;
  772. }
  773. return 0;
  774. }
  775. static int enduser_setup_stop(lua_State* L)
  776. {
  777. enduser_setup_check_station_stop();
  778. enduser_setup_ap_stop();
  779. enduser_setup_dns_stop();
  780. enduser_setup_http_stop();
  781. enduser_setup_free();
  782. return 0;
  783. }
  784. static const LUA_REG_TYPE enduser_setup_map[] = {
  785. { LSTRKEY( "start" ), LFUNCVAL( enduser_setup_start )},
  786. { LSTRKEY( "stop" ), LFUNCVAL( enduser_setup_stop )},
  787. { LNILKEY, LNILVAL}
  788. };
  789. NODEMCU_MODULE(ENDUSER_SETUP, "enduser_setup", enduser_setup_map, NULL);