enduser_setup.c 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534
  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. */
  35. // No espconn on ESP32
  36. #ifdef __ESP8266__
  37. #include "module.h"
  38. #include "lauxlib.h"
  39. #include "lwip/tcp.h"
  40. #include "lwip/pbuf.h"
  41. #include "lmem.h"
  42. #include "platform.h"
  43. #include <stdlib.h>
  44. #include <stdio.h>
  45. #include <string.h>
  46. #include "ctype.h"
  47. #include "espconn.h"
  48. #include "flash_fs.h"
  49. #include "task/task.h"
  50. #include "esp_wifi.h"
  51. #include "esp_sta.h"
  52. #include "esp_softap.h"
  53. #define MIN(x, y) (((x) < (y)) ? (x) : (y))
  54. #define LITLEN(strliteral) (sizeof (strliteral) -1)
  55. #define ENDUSER_SETUP_ERR_FATAL (1 << 0)
  56. #define ENDUSER_SETUP_ERR_NONFATAL (1 << 1)
  57. #define ENDUSER_SETUP_ERR_NO_RETURN (1 << 2)
  58. #define ENDUSER_SETUP_ERR_OUT_OF_MEMORY 1
  59. #define ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND 2
  60. #define ENDUSER_SETUP_ERR_UNKOWN_ERROR 3
  61. #define ENDUSER_SETUP_ERR_SOCKET_ALREADY_OPEN 4
  62. /**
  63. * DNS Response Packet:
  64. *
  65. * |DNS ID - 16 bits|
  66. * |dns_header|
  67. * |QNAME|
  68. * |dns_body|
  69. * |ip - 32 bits|
  70. *
  71. * DNS Header Part | FLAGS | | Q COUNT | | A CNT | |AUTH CNT| | ADD CNT| */
  72. static const char dns_header[] = { 0x80, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00 };
  73. /* DNS Query Part | Q TYPE | | Q CLASS| */
  74. static const char dns_body[] = { 0x00, 0x01, 0x00, 0x01,
  75. /* DNS Answer Part |LBL OFFS| | TYPE | | CLASS | | TTL | | RD LEN | */
  76. 0xC0, 0x0C, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x04 };
  77. static const char http_html_filename[] = "enduser_setup.html";
  78. static const char http_header_200[] = "HTTP/1.1 200 OK\r\nCache-control:no-cache\r\nContent-Type: text/html\r\n"; /* Note single \r\n here! */
  79. static const char http_header_204[] = "HTTP/1.1 204 No Content\r\n\r\n";
  80. static const char http_header_302[] = "HTTP/1.1 302 Moved\r\nLocation: /\r\n\r\n";
  81. static const char http_header_401[] = "HTTP/1.1 401 Bad request\r\n\r\n";
  82. static const char http_header_404[] = "HTTP/1.1 404 Not found\r\n\r\n";
  83. static const char http_header_500[] = "HTTP/1.1 500 Internal Error\r\n\r\n";
  84. /* The below is the un-minified version of the http_html_backup[] string.
  85. * Minified using https://kangax.github.io/html-minifier/
  86. * Note: using method="get" due to iOS not always sending body in same
  87. * packet as the HTTP header, and us thus missing it in that case
  88. */
  89. #if 0
  90. <!DOCTYPE html>
  91. <html>
  92. <head>
  93. <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  94. <meta charset="utf-8">
  95. <meta name="viewport" content="width=380">
  96. <title>WiFi Login</title>
  97. <style media="screen" type="text/css">
  98. *{margin:0;padding:0}
  99. 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)}
  100. body{font-family:arial,verdana}
  101. div{position:absolute;margin:auto;top:-150px;right:0;bottom:0;left:0;width:320px;height:304px}
  102. form{width:320px;text-align:center;position:relative}
  103. 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}
  104. 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}
  105. form .action-button{border:0 none;border-radius:3px;cursor:pointer;}
  106. #msform .submit:focus,form .action-button:hover{box-shadow:0 0 0 2px #fff,0 0 0 3px #27AE60;}
  107. #formFrame{display: none;}
  108. #aplist{display: block;}
  109. select{width:100%;margin-bottom: 20px;padding: 10px 5px; border:1px solid #ccc;display:none;}
  110. .fs-title{font-size:15px;text-transform:uppercase;color:#2C3E50;margin-bottom:10px}
  111. .fs-subtitle{font-weight:400;font-size:13px;color:#666;margin-bottom:20px}
  112. .fs-status{font-weight:400;font-size:13px;color:#666;margin-bottom:10px;padding-top:20px; border-top:1px solid #ccc}
  113. .submit{width:100px;background: #27AE60; color: #fff;font-weight:700;margin:10px 5px; padding: 10px 5px; }
  114. </style>
  115. </head>
  116. <body>
  117. <div>
  118. <form id="credentialsForm" method="get" action="/update" target="formFrame">
  119. <fieldset>
  120. <iframe id="formFrame" src="" name="formFrame"></iframe> <!-- Used to submit data, needed to prevent re-direction after submission -->
  121. <h2 class="fs-title">WiFi Login</h2>
  122. <h3 class="fs-subtitle">Connect gadget to your WiFi network</h3>
  123. <input id="wifi_ssid" autocorrect="off" autocapitalize="none" name="wifi_ssid" placeholder="WiFi Name">
  124. <select id="aplist" name="aplist" size="1" disabled>
  125. <option>Scanning for networks...</option>
  126. </select>
  127. <input name="wifi_password" placeholder="Password" type="password">
  128. <input type=submit name=save class="action-button submit" value="Save">
  129. <h3 class="fs-status">Status: <span id="status">Updating...</span></h3>
  130. </fieldset>
  131. <h3 id="dbg"></h3>
  132. </form>
  133. </div>
  134. <script>
  135. function fetch(url, method, callback)
  136. {
  137. var xhr = new XMLHttpRequest();
  138. xhr.onreadystatechange=check_ready;
  139. function check_ready()
  140. {
  141. if (xhr.readyState === 4)
  142. {
  143. callback(xhr.status === 200 ? xhr.responseText : null);
  144. }
  145. }
  146. xhr.open(method, url, true);
  147. xhr.send();
  148. }
  149. function new_status(stat)
  150. {
  151. if (stat)
  152. {
  153. var e = document.getElementById("status");
  154. e.innerHTML = stat;
  155. }
  156. }
  157. function new_status_repeat(stat)
  158. {
  159. new_status(stat);
  160. setTimeout(refresh_status, 750);
  161. }
  162. function new_ap_list(json)
  163. {
  164. if (json)
  165. {
  166. var list = JSON.parse(json);
  167. list.sort(function(a, b){ return b.rssi - a.rssi; });
  168. var ssids = list.map(function(a) { return a.ssid; }).filter(function(item, pos, self) { return self.indexOf(item)==pos; });
  169. var sel = document.getElementById("aplist");
  170. sel.innerHTML = "";
  171. sel.setAttribute("size", Math.max(Math.min(3, list.length), 1));
  172. sel.removeAttribute("disabled");
  173. for (var i = 0; i < ssids.length; ++i)
  174. {
  175. var o = document.createElement("option");
  176. o.innerHTML = ssids[i];
  177. sel.options.add(o);
  178. }
  179. sel.style.display = 'block';
  180. }
  181. }
  182. function new_ap_list_repeat(json)
  183. {
  184. new_ap_list(json);
  185. setTimeout(refresh_ap_list, 3000);
  186. }
  187. function refresh_status()
  188. {
  189. fetch('/status','GET', new_status_repeat);
  190. }
  191. function refresh_ap_list()
  192. {
  193. fetch('/aplist','GET', new_ap_list_repeat);
  194. }
  195. function set_ssid_field() {
  196. var sel = document.getElementById("aplist");
  197. document.getElementById("wifi_ssid").value = sel.value;
  198. }
  199. window.onload = function()
  200. {
  201. refresh_status();
  202. refresh_ap_list();
  203. document.getElementById("aplist").onclick = set_ssid_field;
  204. document.getElementById("aplist").onchange = set_ssid_field;
  205. document.getElementById("credentialsForm").addEventListener("submit", function(){
  206. fetch('/status','GET', new_status);
  207. });
  208. }
  209. </script>
  210. </body>
  211. </html>
  212. #endif
  213. static const char http_html_backup[] =
  214. "<!DOCTYPE html><meta http-equiv=content-type content='text/html; charset=UTF-8'><meta charset=utf-8><meta name=viewport content='width=380'><title>WiFi Login</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:-150px;right:0;bottom:0;left:0;width:320px;height:304px}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{border:0 none;border-radius:3px;cursor:pointer}#msform .submit:focus,form .action-button:hover{box-shadow:0 0 0 2px #fff,0 0 0 3px #27AE60}#formFrame{display:none}#aplist{display:block}select{width:100%;margin-bottom:20px;padding:10px 5px;border:1px solid #ccc;display:none}.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}.fs-status{font-weight:400;font-size:13px;color:#666;margin-bottom:10px;padding-top:20px;border-top:1px solid #ccc}.submit{width:100px;background:#27AE60;color:#fff;font-weight:700;margin:10px 5px;padding:10px 5px}</style><div><form id=credentialsForm action=/update target=formFrame><fieldset><iframe id=formFrame src=''name=formFrame></iframe><h2 class=fs-title>WiFi Login</h2><h3 class=fs-subtitle>Connect gadget to your WiFi network</h3><input id=wifi_ssid autocorrect=off autocapitalize=none name=wifi_ssid placeholder='WiFi Name'><select id=aplist name=aplist size=1 disabled><option>Scanning for networks...</select><input name=wifi_password placeholder=Password type=password> <input type=submit name=save class='action-button submit'value=Save><h3 class=fs-status>Status: <span id=status>Updating...</span></h3></fieldset><h3 id=dbg></h3></form></div><script>function fetch(t,e,n){function s(){4===i.readyState&&n(200===i.status?i.responseText:null)}var i=new XMLHttpRequest;i.onreadystatechange=s,i.open(e,t,!0),i.send()}function new_status(t){if(t){var e=document.getElementById('status');e.innerHTML=t}}function new_status_repeat(t){new_status(t),setTimeout(refresh_status,750)}function new_ap_list(t){if(t){var e=JSON.parse(t);e.sort(function(t,e){return e.rssi-t.rssi});var n=e.map(function(t){return t.ssid}).filter(function(t,e,n){return n.indexOf(t)==e}),s=document.getElementById('aplist');s.innerHTML='',s.setAttribute('size',Math.max(Math.min(3,e.length),1)),s.removeAttribute('disabled');for(var i=0;i<n.length;++i){var a=document.createElement('option');a.innerHTML=n[i],s.options.add(a)}s.style.display='block'}}function new_ap_list_repeat(t){new_ap_list(t),setTimeout(refresh_ap_list,3e3)}function refresh_status(){fetch('/status','GET',new_status_repeat)}function refresh_ap_list(){fetch('/aplist','GET',new_ap_list_repeat)}function set_ssid_field(){var t=document.getElementById('aplist');document.getElementById('wifi_ssid').value=t.value}window.onload=function(){refresh_status(),refresh_ap_list(),document.getElementById('aplist').onclick=set_ssid_field,document.getElementById('aplist').onchange=set_ssid_field,document.getElementById('credentialsForm').addEventListener('submit',function(){fetch('/status','GET',new_status)})}</script>";
  215. typedef struct scan_listener
  216. {
  217. struct tcp_pcb *conn;
  218. struct scan_listener *next;
  219. } scan_listener_t;
  220. typedef struct
  221. {
  222. struct espconn *espconn_dns_udp;
  223. struct tcp_pcb *http_pcb;
  224. char *http_payload_data;
  225. uint32_t http_payload_len;
  226. os_timer_t check_station_timer;
  227. os_timer_t shutdown_timer;
  228. int lua_connected_cb_ref;
  229. int lua_err_cb_ref;
  230. int lua_dbg_cb_ref;
  231. scan_listener_t *scan_listeners;
  232. } enduser_setup_state_t;
  233. static enduser_setup_state_t *state;
  234. static bool manual = false;
  235. static task_handle_t do_station_cfg_handle;
  236. static int enduser_setup_manual(lua_State* L);
  237. static int enduser_setup_start(lua_State* L);
  238. static int enduser_setup_stop(lua_State* L);
  239. static void enduser_setup_stop_callback(void *ptr);
  240. static void enduser_setup_station_start(void);
  241. static void enduser_setup_ap_start(void);
  242. static void enduser_setup_ap_stop(void);
  243. static void enduser_setup_check_station(void *p);
  244. static void enduser_setup_debug(int line, const char *str);
  245. #define ENDUSER_SETUP_DEBUG_ENABLE 0
  246. #if ENDUSER_SETUP_DEBUG_ENABLE
  247. #define ENDUSER_SETUP_DEBUG(str) enduser_setup_debug(__LINE__, str)
  248. #else
  249. #define ENDUSER_SETUP_DEBUG(str) do {} while(0)
  250. #endif
  251. #define ENDUSER_SETUP_ERROR(str, err, err_severity) \
  252. do { \
  253. ENDUSER_SETUP_DEBUG(str); \
  254. if (err_severity & ENDUSER_SETUP_ERR_FATAL) enduser_setup_stop(lua_getstate());\
  255. enduser_setup_error(__LINE__, str, err);\
  256. if (!(err_severity & ENDUSER_SETUP_ERR_NO_RETURN)) \
  257. return err; \
  258. } while (0)
  259. #define ENDUSER_SETUP_ERROR_VOID(str, err, err_severity) \
  260. do { \
  261. ENDUSER_SETUP_DEBUG(str); \
  262. if (err_severity & ENDUSER_SETUP_ERR_FATAL) enduser_setup_stop(lua_getstate());\
  263. enduser_setup_error(__LINE__, str, err);\
  264. if (!(err_severity & ENDUSER_SETUP_ERR_NO_RETURN)) \
  265. return; \
  266. } while (0)
  267. static void enduser_setup_debug(int line, const char *str)
  268. {
  269. lua_State *L = lua_getstate();
  270. if(state != NULL && state->lua_dbg_cb_ref != LUA_NOREF)
  271. {
  272. lua_rawgeti(L, LUA_REGISTRYINDEX, state->lua_dbg_cb_ref);
  273. lua_pushfstring(L, "%d: \t%s", line, str);
  274. lua_call(L, 1, 0);
  275. }
  276. }
  277. static void enduser_setup_error(int line, const char *str, int err)
  278. {
  279. ENDUSER_SETUP_DEBUG("enduser_setup_error");
  280. lua_State *L = lua_getstate();
  281. if (state != NULL && state->lua_err_cb_ref != LUA_NOREF)
  282. {
  283. lua_rawgeti (L, LUA_REGISTRYINDEX, state->lua_err_cb_ref);
  284. lua_pushnumber(L, err);
  285. lua_pushfstring(L, "%d: \t%s", line, str);
  286. lua_call (L, 2, 0);
  287. }
  288. }
  289. static void enduser_setup_connected_callback()
  290. {
  291. ENDUSER_SETUP_DEBUG("enduser_setup_connected_callback");
  292. lua_State *L = lua_getstate();
  293. if (state != NULL && state->lua_connected_cb_ref != LUA_NOREF)
  294. {
  295. lua_rawgeti(L, LUA_REGISTRYINDEX, state->lua_connected_cb_ref);
  296. lua_call(L, 0, 0);
  297. }
  298. }
  299. static void enduser_setup_check_station_start(void)
  300. {
  301. ENDUSER_SETUP_DEBUG("enduser_setup_check_station_start");
  302. os_timer_setfn(&(state->check_station_timer), enduser_setup_check_station, NULL);
  303. os_timer_arm(&(state->check_station_timer), 1*1000, TRUE);
  304. }
  305. static void enduser_setup_check_station_stop(void)
  306. {
  307. ENDUSER_SETUP_DEBUG("enduser_setup_check_station_stop");
  308. if (state != NULL)
  309. {
  310. os_timer_disarm(&(state->check_station_timer));
  311. }
  312. }
  313. /**
  314. * Check Station
  315. *
  316. * Check that we've successfully entered station mode.
  317. */
  318. static void enduser_setup_check_station(void *p)
  319. {
  320. ENDUSER_SETUP_DEBUG("enduser_setup_check_station");
  321. (void)p;
  322. struct ip_info ip;
  323. memset(&ip, 0, sizeof(struct ip_info));
  324. wifi_get_ip_info(STATION_IF, &ip);
  325. int i;
  326. char has_ip = 0;
  327. for (i = 0; i < sizeof(struct ip_info); ++i)
  328. {
  329. has_ip |= ((char *) &ip)[i];
  330. }
  331. if (has_ip == 0)
  332. {
  333. return;
  334. }
  335. enduser_setup_check_station_stop();
  336. enduser_setup_connected_callback();
  337. /* Trigger shutdown, but allow time for HTTP client to fetch last status. */
  338. if (!manual)
  339. {
  340. os_timer_setfn(&(state->shutdown_timer), enduser_setup_stop_callback, NULL);
  341. os_timer_arm(&(state->shutdown_timer), 10*1000, FALSE);
  342. }
  343. }
  344. /* --- Connection closing handling ----------------------------------------- */
  345. /* It is far more memory efficient to let the other end close the connection
  346. * first and respond to that, than us initiating the closing. The latter
  347. * seems to leave the pcb in a fin_wait state for a long time, which can
  348. * starve us of memory over time.
  349. *
  350. * By instead using the poll function to schedule a hard abort a few seconds
  351. * from now we achieve a deadline close. The downside is a (very) slight
  352. * risk of dropping the connection early, but in this application that's
  353. * hidden by the retries on the JavaScript side anyway.
  354. */
  355. /* Callback on timeout to hard-close a connection */
  356. static err_t force_abort (void *arg, struct tcp_pcb *pcb)
  357. {
  358. (void)arg;
  359. tcp_poll (pcb, 0, 0);
  360. tcp_abort (pcb);
  361. return ERR_ABRT;
  362. }
  363. /* Callback to detect a remote-close of a connection */
  364. static err_t handle_remote_close (void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
  365. {
  366. (void)arg; (void)err;
  367. if (p) /* server sent us data, just ACK and move on */
  368. {
  369. tcp_recved (pcb, p->tot_len);
  370. pbuf_free (p);
  371. }
  372. else /* hey, remote end closed, we can do a soft close safely, yay! */
  373. {
  374. tcp_recv (pcb, 0);
  375. tcp_poll (pcb, 0, 0);
  376. tcp_close (pcb);
  377. }
  378. return ERR_OK;
  379. }
  380. /* Set up a deferred close of a connection, as discussed above. */
  381. static inline void deferred_close (struct tcp_pcb *pcb)
  382. {
  383. tcp_poll (pcb, force_abort, 15); /* ~3sec from now */
  384. tcp_recv (pcb, handle_remote_close);
  385. tcp_sent (pcb, 0);
  386. }
  387. /* Convenience function to queue up a close-after-send. */
  388. static err_t close_once_sent (void *arg, struct tcp_pcb *pcb, u16_t len)
  389. {
  390. (void)arg; (void)len;
  391. deferred_close (pcb);
  392. return ERR_OK;
  393. }
  394. /* ------------------------------------------------------------------------- */
  395. /**
  396. * Search String
  397. *
  398. * Search string for first occurance of any char in srch_str.
  399. *
  400. * @return -1 iff no occurance of char was found.
  401. */
  402. static int enduser_setup_srch_str(const char *str, const char *srch_str)
  403. {
  404. char *found = strpbrk (str, srch_str);
  405. if (!found)
  406. {
  407. return -1;
  408. }
  409. else
  410. {
  411. return found - str;
  412. }
  413. }
  414. /**
  415. * Load HTTP Payload
  416. *
  417. * @return - 0 iff payload loaded successfully
  418. * 1 iff backup html was loaded
  419. * 2 iff out of memory
  420. */
  421. static int enduser_setup_http_load_payload(void)
  422. {
  423. ENDUSER_SETUP_DEBUG("enduser_setup_http_load_payload");
  424. int f = fs_open(http_html_filename, fs_mode2flag("r"));
  425. int err = fs_seek(f, 0, FS_SEEK_END);
  426. int file_len = (int) fs_tell(f);
  427. int err2 = fs_seek(f, 0, FS_SEEK_SET);
  428. const char cl_hdr[] = "Content-length:%5d\r\n\r\n";
  429. const size_t cl_len = LITLEN(cl_hdr) + 3; /* room to expand %4d */
  430. if (f == 0 || err == -1 || err2 == -1)
  431. {
  432. ENDUSER_SETUP_DEBUG("enduser_setup_http_load_payload unable to load file enduser_setup.html, loading backup HTML.");
  433. int payload_len = LITLEN(http_header_200) + cl_len + LITLEN(http_html_backup);
  434. state->http_payload_len = payload_len;
  435. state->http_payload_data = (char *) malloc(payload_len);
  436. if (state->http_payload_data == NULL)
  437. {
  438. return 2;
  439. }
  440. int offset = 0;
  441. memcpy(&(state->http_payload_data[offset]), &(http_header_200), LITLEN(http_header_200));
  442. offset += LITLEN(http_header_200);
  443. offset += sprintf(state->http_payload_data + offset, cl_hdr, LITLEN(http_html_backup));
  444. memcpy(&(state->http_payload_data[offset]), &(http_html_backup), LITLEN(http_html_backup));
  445. return 1;
  446. }
  447. int payload_len = LITLEN(http_header_200) + cl_len + file_len;
  448. state->http_payload_len = payload_len;
  449. state->http_payload_data = (char *) malloc(payload_len);
  450. if (state->http_payload_data == NULL)
  451. {
  452. return 2;
  453. }
  454. int offset = 0;
  455. memcpy(&(state->http_payload_data[offset]), &(http_header_200), LITLEN(http_header_200));
  456. offset += LITLEN(http_header_200);
  457. offset += sprintf(state->http_payload_data + offset, cl_hdr, file_len);
  458. fs_read(f, &(state->http_payload_data[offset]), file_len);
  459. return 0;
  460. }
  461. /**
  462. * De-escape URL data
  463. *
  464. * Parse escaped and form encoded data of request.
  465. *
  466. * @return - return 0 iff the HTTP parameter is decoded into a valid string.
  467. */
  468. static int enduser_setup_http_urldecode(char *dst, const char *src, int src_len, int dst_len)
  469. {
  470. ENDUSER_SETUP_DEBUG("enduser_setup_http_urldecode");
  471. char *dst_start = dst;
  472. char *dst_last = dst + dst_len - 1; /* -1 to reserve space for last \0 */
  473. char a, b;
  474. int i;
  475. for (i = 0; i < src_len && *src && dst < dst_last; ++i)
  476. {
  477. if ((*src == '%') && ((a = src[1]) && (b = src[2])) && (isxdigit(a) && isxdigit(b)))
  478. {
  479. if (a >= 'a')
  480. {
  481. a -= 'a'-'A';
  482. }
  483. if (a >= 'A')
  484. {
  485. a -= ('A' - 10);
  486. }
  487. else
  488. {
  489. a -= '0';
  490. }
  491. if (b >= 'a')
  492. {
  493. b -= 'a'-'A';
  494. }
  495. if (b >= 'A')
  496. {
  497. b -= ('A' - 10);
  498. }
  499. else
  500. {
  501. b -= '0';
  502. }
  503. *dst++ = 16 * a + b;
  504. src += 3;
  505. i += 2;
  506. } else {
  507. char c = *src++;
  508. if (c == '+')
  509. {
  510. c = ' ';
  511. }
  512. *dst++ = c;
  513. }
  514. }
  515. *dst++ = '\0';
  516. return (i < src_len); /* did we fail to process all the input? */
  517. }
  518. /**
  519. * Task to do the actual station configuration.
  520. * This config *cannot* be done in the network receive callback or serious
  521. * issues like memory corruption occur.
  522. */
  523. static void do_station_cfg (task_param_t param, task_prio_t prio)
  524. {
  525. struct station_config *cnf = (struct station_config *)param;
  526. (void)prio;
  527. /* Best-effort disconnect-reconfig-reconnect. If the device is currently
  528. * connected, the disconnect will work but the connect will report failure
  529. * (though it will actually start connecting). If the devices is not
  530. * connected, the disconnect may fail but the connect will succeed. A
  531. * solid head-in-the-sand approach seems to be the best tradeoff on
  532. * functionality-vs-code-size.
  533. * TODO: maybe use an error callback to at least report if the set config
  534. * call fails.
  535. */
  536. wifi_station_disconnect ();
  537. wifi_station_set_config (cnf);
  538. wifi_station_connect ();
  539. luaM_free(lua_getstate(), cnf);
  540. }
  541. /**
  542. * Handle HTTP Credentials
  543. *
  544. * @return - return 0 iff credentials are found and handled successfully
  545. * return 1 iff credentials aren't found
  546. * return 2 iff an error occured
  547. */
  548. static int enduser_setup_http_handle_credentials(char *data, unsigned short data_len)
  549. {
  550. ENDUSER_SETUP_DEBUG("enduser_setup_http_handle_credentials");
  551. char *name_str = (char *) ((uint32_t)strstr(&(data[6]), "wifi_ssid="));
  552. char *pwd_str = (char *) ((uint32_t)strstr(&(data[6]), "wifi_password="));
  553. if (name_str == NULL || pwd_str == NULL)
  554. {
  555. ENDUSER_SETUP_DEBUG("Password or SSID string not found");
  556. return 1;
  557. }
  558. int name_field_len = LITLEN("wifi_ssid=");
  559. int pwd_field_len = LITLEN("wifi_password=");
  560. char *name_str_start = name_str + name_field_len;
  561. char *pwd_str_start = pwd_str + pwd_field_len;
  562. int name_str_len = enduser_setup_srch_str(name_str_start, "& ");
  563. int pwd_str_len = enduser_setup_srch_str(pwd_str_start, "& ");
  564. if (name_str_len == -1 || pwd_str_len == -1)
  565. {
  566. ENDUSER_SETUP_DEBUG("Password or SSID HTTP paramter divider not found");
  567. return 1;
  568. }
  569. struct station_config *cnf = luaM_malloc(lua_getstate(), sizeof(struct station_config));
  570. memset(cnf, 0, sizeof(struct station_config));
  571. int err;
  572. err = enduser_setup_http_urldecode(cnf->ssid, name_str_start, name_str_len, sizeof(cnf->ssid));
  573. err |= enduser_setup_http_urldecode(cnf->password, pwd_str_start, pwd_str_len, sizeof(cnf->password));
  574. if (err != 0)
  575. {
  576. ENDUSER_SETUP_DEBUG("Unable to decode HTTP parameter to valid password or SSID");
  577. return 1;
  578. }
  579. ENDUSER_SETUP_DEBUG("");
  580. ENDUSER_SETUP_DEBUG("WiFi Credentials Stored");
  581. ENDUSER_SETUP_DEBUG("-----------------------");
  582. ENDUSER_SETUP_DEBUG("name: ");
  583. ENDUSER_SETUP_DEBUG(cnf->ssid);
  584. ENDUSER_SETUP_DEBUG("pass: ");
  585. ENDUSER_SETUP_DEBUG(cnf->password);
  586. ENDUSER_SETUP_DEBUG("-----------------------");
  587. ENDUSER_SETUP_DEBUG("");
  588. task_post_medium(do_station_cfg_handle, (task_param_t) cnf);
  589. return 0;
  590. }
  591. /**
  592. * Serve HTML
  593. *
  594. * @return - return 0 iff html was served successfully
  595. */
  596. static int enduser_setup_http_serve_header(struct tcp_pcb *http_client, const char *header, uint32_t header_len)
  597. {
  598. ENDUSER_SETUP_DEBUG("enduser_setup_http_serve_header");
  599. err_t err = tcp_write (http_client, header, header_len, TCP_WRITE_FLAG_COPY);
  600. if (err != ERR_OK)
  601. {
  602. deferred_close (http_client);
  603. ENDUSER_SETUP_ERROR("http_serve_header failed on tcp_write", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
  604. }
  605. return 0;
  606. }
  607. static err_t streamout_sent (void *arg, struct tcp_pcb *pcb, u16_t len)
  608. {
  609. (void)len;
  610. unsigned offs = (unsigned)arg;
  611. if (!state || !state->http_payload_data)
  612. {
  613. tcp_abort (pcb);
  614. return ERR_ABRT;
  615. }
  616. unsigned wanted_len = state->http_payload_len - offs;
  617. unsigned buf_free = tcp_sndbuf (pcb);
  618. if (buf_free < wanted_len)
  619. wanted_len = buf_free;
  620. /* no-copy write */
  621. err_t err = tcp_write (pcb, state->http_payload_data + offs, wanted_len, 0);
  622. if (err != ERR_OK)
  623. {
  624. ENDUSER_SETUP_DEBUG("streaming out html failed");
  625. tcp_abort (pcb);
  626. return ERR_ABRT;
  627. }
  628. offs += wanted_len;
  629. if (offs >= state->http_payload_len)
  630. {
  631. tcp_sent (pcb, 0);
  632. deferred_close (pcb);
  633. }
  634. else
  635. tcp_arg (pcb, (void *)offs);
  636. return ERR_OK;
  637. }
  638. /**
  639. * Serve HTML
  640. *
  641. * @return - return 0 iff html was served successfully
  642. */
  643. static int enduser_setup_http_serve_html(struct tcp_pcb *http_client)
  644. {
  645. ENDUSER_SETUP_DEBUG("enduser_setup_http_serve_html");
  646. if (state->http_payload_data == NULL)
  647. {
  648. enduser_setup_http_load_payload();
  649. }
  650. unsigned chunklen = tcp_sndbuf (http_client);
  651. tcp_arg (http_client, (void *)chunklen);
  652. tcp_recv (http_client, 0); /* avoid confusion about the tcp_arg */
  653. tcp_sent (http_client, streamout_sent);
  654. /* Begin the no-copy stream-out here */
  655. err_t err = tcp_write (http_client, state->http_payload_data, chunklen, 0);
  656. if (err != 0)
  657. {
  658. ENDUSER_SETUP_ERROR("http_serve_html failed. tcp_write failed", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
  659. }
  660. return 0;
  661. }
  662. static void serve_status(struct tcp_pcb *conn)
  663. {
  664. ENDUSER_SETUP_DEBUG("enduser_setup_serve_status");
  665. const char fmt[] =
  666. "HTTP/1.1 200 OK\r\n"
  667. "Cache-control:no-cache\r\n"
  668. "Connection:close\r\n"
  669. "Content-type:text/plain\r\n"
  670. "Content-length: %d\r\n"
  671. "\r\n"
  672. "%s%s";
  673. const char *state[] =
  674. {
  675. "Idle.",
  676. "Connecting to \"%s\".",
  677. "Failed to connect to \"%s\" - Wrong password.",
  678. "Failed to connect to \"%s\" - Network not found.",
  679. "Failed to connect.",
  680. "Connected to \"%s\"."
  681. };
  682. const size_t num_states = sizeof(state)/sizeof(state[0]);
  683. uint8_t curr_state = wifi_station_get_connect_status ();
  684. if (curr_state < num_states)
  685. {
  686. switch (curr_state)
  687. {
  688. case STATION_CONNECTING:
  689. case STATION_WRONG_PASSWORD:
  690. case STATION_NO_AP_FOUND:
  691. case STATION_GOT_IP:
  692. {
  693. const char *s = state[curr_state];
  694. struct station_config config;
  695. wifi_station_get_config(&config);
  696. config.ssid[31] = '\0';
  697. int state_len = strlen(s);
  698. int ssid_len = strlen(config.ssid);
  699. int status_len = state_len + ssid_len + 1;
  700. char status_buf[status_len];
  701. memset(status_buf, 0, status_len);
  702. status_len = sprintf(status_buf, s, config.ssid);
  703. int buf_len = sizeof(fmt) + status_len + 10; //10 = (9+1), 1 byte is '\0' and 9 are reserved for length field
  704. char buf[buf_len];
  705. memset(buf, 0, buf_len);
  706. int output_len = sprintf(buf, fmt, status_len, status_buf);
  707. enduser_setup_http_serve_header(conn, buf, output_len);
  708. }
  709. break;
  710. /* Handle non-formatted strings */
  711. default:
  712. {
  713. const char *s = state[curr_state];
  714. int status_len = strlen(s);
  715. int buf_len = sizeof(fmt) + status_len + 10; //10 = (9+1), 1 byte is '\0' and 9 are reserved for length field
  716. char buf[buf_len];
  717. memset(buf, 0, buf_len);
  718. int output_len = sprintf(buf, fmt, status_len, s);
  719. enduser_setup_http_serve_header(conn, buf, output_len);
  720. }
  721. break;
  722. }
  723. }
  724. else
  725. {
  726. enduser_setup_http_serve_header(conn, http_header_500, LITLEN(http_header_500));
  727. }
  728. }
  729. /* --- WiFi AP scanning support -------------------------------------------- */
  730. static void free_scan_listeners (void)
  731. {
  732. if (!state || !state->scan_listeners)
  733. {
  734. return;
  735. }
  736. scan_listener_t *l = state->scan_listeners , *next = 0;
  737. while (l)
  738. {
  739. next = l->next;
  740. free (l);
  741. l = next;
  742. }
  743. state->scan_listeners = 0;
  744. }
  745. static void remove_scan_listener (scan_listener_t *l)
  746. {
  747. if (state)
  748. {
  749. scan_listener_t **sl = &state->scan_listeners;
  750. while (*sl)
  751. {
  752. /* Remove any and all references to the closed conn from the scan list */
  753. if (*sl == l)
  754. {
  755. *sl = l->next;
  756. free (l);
  757. /* No early exit to guard against multi-entry on list */
  758. }
  759. else
  760. sl = &(*sl)->next;
  761. }
  762. }
  763. }
  764. static char *escape_ssid (char *dst, const char *src)
  765. {
  766. for (int i = 0; i < 32 && src[i]; ++i)
  767. {
  768. if (src[i] == '\\' || src[i] == '"')
  769. {
  770. *dst++ = '\\';
  771. }
  772. *dst++ = src[i];
  773. }
  774. return dst;
  775. }
  776. static void notify_scan_listeners (const char *payload, size_t sz)
  777. {
  778. if (!state)
  779. {
  780. return;
  781. }
  782. for (scan_listener_t *l = state->scan_listeners; l; l = l->next)
  783. {
  784. if (tcp_write (l->conn, payload, sz, TCP_WRITE_FLAG_COPY) != ERR_OK)
  785. {
  786. ENDUSER_SETUP_DEBUG("failed to send wifi list");
  787. tcp_abort (l->conn);
  788. }
  789. else
  790. tcp_sent (l->conn, close_once_sent); /* TODO: time-out sends? */
  791. l->conn = 0;
  792. }
  793. free_scan_listeners ();
  794. }
  795. static void on_scan_done (void *arg, STATUS status)
  796. {
  797. if (!state || !state->scan_listeners)
  798. {
  799. return;
  800. }
  801. if (status == OK)
  802. {
  803. unsigned num_nets = 0;
  804. for (struct bss_info *wn = arg; wn; wn = wn->next.stqe_next)
  805. {
  806. ++num_nets;
  807. }
  808. const char header_fmt[] =
  809. "HTTP/1.1 200 OK\r\n"
  810. "Connection:close\r\n"
  811. "Cache-control:no-cache\r\n"
  812. "Content-type:application/json\r\n"
  813. "Content-length:%4d\r\n"
  814. "\r\n";
  815. const size_t hdr_sz = sizeof (header_fmt) +1 -1; /* +expand %4d, -\0 */
  816. /* To be able to safely escape a pathological SSID, we need 2*32 bytes */
  817. const size_t max_entry_sz = sizeof("{\"ssid\":\"\",\"rssi\":},") + 2*32 + 6;
  818. const size_t alloc_sz = hdr_sz + num_nets * max_entry_sz + 3;
  819. char *http = zalloc (alloc_sz);
  820. if (!http)
  821. {
  822. goto serve_500;
  823. }
  824. char *p = http + hdr_sz; /* start body where we know it will be */
  825. /* p[0] will be clobbered when we print the header, so fill it in last */
  826. ++p;
  827. for (struct bss_info *wn = arg; wn; wn = wn->next.stqe_next)
  828. {
  829. if (wn != arg)
  830. {
  831. *p++ = ',';
  832. }
  833. const char entry_start[] = "{\"ssid\":\"";
  834. strcpy (p, entry_start);
  835. p += sizeof (entry_start) -1;
  836. p = escape_ssid (p, wn->ssid);
  837. const char entry_mid[] = "\",\"rssi\":";
  838. strcpy (p, entry_mid);
  839. p += sizeof (entry_mid) -1;
  840. p += sprintf (p, "%d", wn->rssi);
  841. *p++ = '}';
  842. }
  843. *p++ = ']';
  844. size_t body_sz = (p - http) - hdr_sz;
  845. sprintf (http, header_fmt, body_sz);
  846. http[hdr_sz] = '['; /* Rewrite the \0 with the correct start of body */
  847. notify_scan_listeners (http, hdr_sz + body_sz);
  848. free (http);
  849. return;
  850. }
  851. serve_500:
  852. notify_scan_listeners (http_header_500, LITLEN(http_header_500));
  853. }
  854. /* ---- end WiFi AP scan support ------------------------------------------- */
  855. static err_t enduser_setup_http_recvcb(void *arg, struct tcp_pcb *http_client, struct pbuf *p, err_t err)
  856. {
  857. ENDUSER_SETUP_DEBUG("enduser_setup_http_recvcb");
  858. if (!state || err != ERR_OK)
  859. {
  860. if (!state)
  861. ENDUSER_SETUP_DEBUG("ignoring received data while stopped");
  862. tcp_abort (http_client);
  863. return ERR_ABRT;
  864. }
  865. if (!p) /* remote side closed, close our end too */
  866. {
  867. ENDUSER_SETUP_DEBUG("connection closed");
  868. scan_listener_t *l = arg; /* if it's waiting for scan, we have a ptr here */
  869. if (l)
  870. remove_scan_listener (l);
  871. deferred_close (http_client);
  872. return ERR_OK;
  873. }
  874. char *data = zalloc (p->tot_len + 1);
  875. if (!data)
  876. return ERR_MEM;
  877. unsigned data_len = pbuf_copy_partial (p, data, p->tot_len, 0);
  878. tcp_recved (http_client, p->tot_len);
  879. pbuf_free (p);
  880. err_t ret = ERR_OK;
  881. if (strncmp(data, "GET ", 4) == 0)
  882. {
  883. if (strncmp(data + 4, "/ ", 2) == 0)
  884. {
  885. if (enduser_setup_http_serve_html(http_client) != 0)
  886. {
  887. ENDUSER_SETUP_ERROR("http_recvcb failed. Unable to send HTML.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
  888. }
  889. else
  890. {
  891. goto free_out; /* streaming now in progress */
  892. }
  893. }
  894. else if (strncmp(data + 4, "/aplist ", 8) == 0)
  895. {
  896. scan_listener_t *l = malloc (sizeof (scan_listener_t));
  897. if (!l)
  898. {
  899. ENDUSER_SETUP_ERROR("out of memory", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_NONFATAL);
  900. }
  901. bool already = (state->scan_listeners != NULL);
  902. tcp_arg (http_client, l);
  903. /* TODO: check if also need a tcp_err() cb, or if recv() is enough */
  904. l->conn = http_client;
  905. l->next = state->scan_listeners;
  906. state->scan_listeners = l;
  907. if (!already)
  908. {
  909. if (!wifi_station_scan(NULL, on_scan_done))
  910. {
  911. enduser_setup_http_serve_header(http_client, http_header_500, LITLEN(http_header_500));
  912. deferred_close (l->conn);
  913. l->conn = 0;
  914. free_scan_listeners();
  915. }
  916. }
  917. goto free_out; /* request queued */
  918. }
  919. else if (strncmp(data + 4, "/status ", 8) == 0)
  920. {
  921. serve_status(http_client);
  922. }
  923. else if (strncmp(data + 4, "/update?", 8) == 0)
  924. {
  925. switch (enduser_setup_http_handle_credentials(data, data_len))
  926. {
  927. case 0:
  928. enduser_setup_http_serve_header(http_client, http_header_302, LITLEN(http_header_302));
  929. break;
  930. case 1:
  931. enduser_setup_http_serve_header(http_client, http_header_401, LITLEN(http_header_401));
  932. break;
  933. default:
  934. ENDUSER_SETUP_ERROR("http_recvcb failed. Failed to handle wifi credentials.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_NONFATAL);
  935. break;
  936. }
  937. }
  938. else if (strncmp(data + 4, "/generate_204 ", 14) == 0)
  939. {
  940. /* Convince Android devices that they have internet access to avoid pesky dialogues. */
  941. enduser_setup_http_serve_header(http_client, http_header_204, LITLEN(http_header_204));
  942. }
  943. else
  944. {
  945. ENDUSER_SETUP_DEBUG("serving 404");
  946. ENDUSER_SETUP_DEBUG(data + 4);
  947. enduser_setup_http_serve_header(http_client, http_header_404, LITLEN(http_header_404));
  948. }
  949. }
  950. else /* not GET */
  951. {
  952. enduser_setup_http_serve_header(http_client, http_header_401, LITLEN(http_header_401));
  953. }
  954. deferred_close (http_client);
  955. free_out:
  956. free (data);
  957. return ret;
  958. }
  959. static err_t enduser_setup_http_connectcb(void *arg, struct tcp_pcb *pcb, err_t err)
  960. {
  961. ENDUSER_SETUP_DEBUG("enduser_setup_http_connectcb");
  962. if (!state)
  963. {
  964. ENDUSER_SETUP_DEBUG("connect callback but no state?!");
  965. tcp_abort (pcb);
  966. return ERR_ABRT;
  967. }
  968. tcp_accepted (state->http_pcb);
  969. tcp_recv (pcb, enduser_setup_http_recvcb);
  970. tcp_nagle_disable (pcb);
  971. return ERR_OK;
  972. }
  973. static int enduser_setup_http_start(void)
  974. {
  975. ENDUSER_SETUP_DEBUG("enduser_setup_http_start");
  976. struct tcp_pcb *pcb = tcp_new ();
  977. if (pcb == NULL)
  978. {
  979. ENDUSER_SETUP_ERROR("http_start failed. Memory allocation failed (http_pcb == NULL).", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  980. }
  981. if (tcp_bind (pcb, IP_ADDR_ANY, 80) != ERR_OK)
  982. {
  983. ENDUSER_SETUP_ERROR("http_start bind failed", ENDUSER_SETUP_ERR_SOCKET_ALREADY_OPEN, ENDUSER_SETUP_ERR_FATAL);
  984. }
  985. state->http_pcb = tcp_listen (pcb);
  986. if (!state->http_pcb)
  987. {
  988. tcp_abort(pcb); /* original wasn't freed for us */
  989. ENDUSER_SETUP_ERROR("http_start listen failed", ENDUSER_SETUP_ERR_SOCKET_ALREADY_OPEN, ENDUSER_SETUP_ERR_FATAL);
  990. }
  991. tcp_accept (state->http_pcb, enduser_setup_http_connectcb);
  992. /* TODO: check lwip tcp timeouts */
  993. #if 0
  994. err = espconn_regist_time(state->espconn_http_tcp, 2, 0);
  995. if (err == ESPCONN_ARG)
  996. {
  997. 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);
  998. }
  999. #endif
  1000. int err = enduser_setup_http_load_payload();
  1001. if (err == 1)
  1002. {
  1003. ENDUSER_SETUP_DEBUG("enduser_setup_http_start info. Loaded backup HTML.");
  1004. }
  1005. else if (err == 2)
  1006. {
  1007. ENDUSER_SETUP_ERROR("http_start failed. Unable to allocate memory for HTTP payload.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  1008. }
  1009. return 0;
  1010. }
  1011. static void enduser_setup_http_stop(void)
  1012. {
  1013. ENDUSER_SETUP_DEBUG("enduser_setup_http_stop");
  1014. if (state && state->http_pcb)
  1015. {
  1016. tcp_close (state->http_pcb); /* cannot fail for listening sockets */
  1017. state->http_pcb = 0;
  1018. }
  1019. }
  1020. static void enduser_setup_ap_stop(void)
  1021. {
  1022. ENDUSER_SETUP_DEBUG("enduser_setup_station_stop");
  1023. wifi_set_opmode(~SOFTAP_MODE & wifi_get_opmode());
  1024. }
  1025. static void enduser_setup_ap_start(void)
  1026. {
  1027. ENDUSER_SETUP_DEBUG("enduser_setup_ap_start");
  1028. struct softap_config cnf;
  1029. memset(&(cnf), 0, sizeof(struct softap_config));
  1030. #ifndef ENDUSER_SETUP_AP_SSID
  1031. #define ENDUSER_SETUP_AP_SSID "SetupGadget"
  1032. #endif
  1033. char ssid[] = ENDUSER_SETUP_AP_SSID;
  1034. int ssid_name_len = strlen(ssid);
  1035. memcpy(&(cnf.ssid), ssid, ssid_name_len);
  1036. uint8_t mac[6];
  1037. wifi_get_macaddr(SOFTAP_IF, mac);
  1038. cnf.ssid[ssid_name_len] = '_';
  1039. sprintf(cnf.ssid + ssid_name_len + 1, "%02X%02X%02X", mac[3], mac[4], mac[5]);
  1040. cnf.ssid_len = ssid_name_len + 7;
  1041. cnf.channel = 1;
  1042. cnf.authmode = AUTH_OPEN;
  1043. cnf.ssid_hidden = 0;
  1044. cnf.max_connection = 5;
  1045. cnf.beacon_interval = 100;
  1046. wifi_set_opmode(STATIONAP_MODE);
  1047. wifi_softap_set_config(&cnf);
  1048. }
  1049. static void enduser_setup_dns_recv_callback(void *arg, char *recv_data, unsigned short recv_len)
  1050. {
  1051. ENDUSER_SETUP_DEBUG("enduser_setup_dns_recv_callback.");
  1052. struct espconn *callback_espconn = arg;
  1053. struct ip_info ip_info;
  1054. uint32_t qname_len = strlen(&(recv_data[12])) + 1; // \0=1byte
  1055. uint32_t dns_reply_static_len = (uint32_t) sizeof(dns_header) + (uint32_t) sizeof(dns_body) + 2 + 4; // dns_id=2bytes, ip=4bytes
  1056. uint32_t dns_reply_len = dns_reply_static_len + qname_len;
  1057. uint8_t if_mode = wifi_get_opmode();
  1058. if ((if_mode & SOFTAP_MODE) == 0)
  1059. {
  1060. ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Interface mode not supported.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  1061. }
  1062. uint8_t if_index = (if_mode == STATION_MODE? STATION_IF : SOFTAP_IF);
  1063. if (wifi_get_ip_info(if_index , &ip_info) == false)
  1064. {
  1065. ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Unable to get interface IP.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  1066. }
  1067. char *dns_reply = (char *) malloc(dns_reply_len);
  1068. if (dns_reply == NULL)
  1069. {
  1070. ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Failed to allocate memory.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_NONFATAL);
  1071. }
  1072. uint32_t insert_byte = 0;
  1073. memcpy(&(dns_reply[insert_byte]), recv_data, 2);
  1074. insert_byte += 2;
  1075. memcpy(&(dns_reply[insert_byte]), dns_header, sizeof(dns_header));
  1076. insert_byte += (uint32_t) sizeof(dns_header);
  1077. memcpy(&(dns_reply[insert_byte]), &(recv_data[12]), qname_len);
  1078. insert_byte += qname_len;
  1079. memcpy(&(dns_reply[insert_byte]), dns_body, sizeof(dns_body));
  1080. insert_byte += (uint32_t) sizeof(dns_body);
  1081. memcpy(&(dns_reply[insert_byte]), &(ip_info.ip), 4);
  1082. // SDK 1.4.0 changed behaviour, for UDP server need to look up remote ip/port
  1083. remot_info *pr = 0;
  1084. if (espconn_get_connection_info(callback_espconn, &pr, 0) != ESPCONN_OK)
  1085. {
  1086. 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);
  1087. }
  1088. callback_espconn->proto.udp->remote_port = pr->remote_port;
  1089. memmove(callback_espconn->proto.udp->remote_ip, pr->remote_ip, 4);
  1090. int8_t err;
  1091. err = espconn_send(callback_espconn, dns_reply, dns_reply_len);
  1092. free(dns_reply);
  1093. if (err == ESPCONN_MEM)
  1094. {
  1095. ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Failed to allocate memory for send.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  1096. }
  1097. else if (err == ESPCONN_ARG)
  1098. {
  1099. ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. Can't execute transmission.", ENDUSER_SETUP_ERR_CONNECTION_NOT_FOUND, ENDUSER_SETUP_ERR_FATAL);
  1100. }
  1101. else if (err != 0)
  1102. {
  1103. ENDUSER_SETUP_ERROR_VOID("dns_recv_callback failed. espconn_send failed", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  1104. }
  1105. }
  1106. static void enduser_setup_free(void)
  1107. {
  1108. ENDUSER_SETUP_DEBUG("enduser_setup_free");
  1109. if (state == NULL)
  1110. {
  1111. return;
  1112. }
  1113. /* Make sure no running timers are left. */
  1114. os_timer_disarm(&(state->check_station_timer));
  1115. os_timer_disarm(&(state->shutdown_timer));
  1116. if (state->espconn_dns_udp != NULL)
  1117. {
  1118. if (state->espconn_dns_udp->proto.udp != NULL)
  1119. {
  1120. free(state->espconn_dns_udp->proto.udp);
  1121. }
  1122. free(state->espconn_dns_udp);
  1123. }
  1124. free(state->http_payload_data);
  1125. free_scan_listeners ();
  1126. free(state);
  1127. state = NULL;
  1128. }
  1129. static int enduser_setup_dns_start(void)
  1130. {
  1131. ENDUSER_SETUP_DEBUG("enduser_setup_dns_start");
  1132. if (state->espconn_dns_udp != NULL)
  1133. {
  1134. ENDUSER_SETUP_ERROR("dns_start failed. Appears to already be started (espconn_dns_udp != NULL).", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  1135. }
  1136. state->espconn_dns_udp = (struct espconn *) malloc(sizeof(struct espconn));
  1137. if (state->espconn_dns_udp == NULL)
  1138. {
  1139. ENDUSER_SETUP_ERROR("dns_start failed. Memory allocation failed (espconn_dns_udp == NULL).", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  1140. }
  1141. esp_udp *esp_udp_data = (esp_udp *) malloc(sizeof(esp_udp));
  1142. if (esp_udp_data == NULL)
  1143. {
  1144. ENDUSER_SETUP_ERROR("dns_start failed. Memory allocation failed (esp_udp == NULL).", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  1145. }
  1146. memset(state->espconn_dns_udp, 0, sizeof(struct espconn));
  1147. memset(esp_udp_data, 0, sizeof(esp_udp));
  1148. state->espconn_dns_udp->proto.udp = esp_udp_data;
  1149. state->espconn_dns_udp->type = ESPCONN_UDP;
  1150. state->espconn_dns_udp->state = ESPCONN_NONE;
  1151. esp_udp_data->local_port = 53;
  1152. int8_t err;
  1153. err = espconn_regist_recvcb(state->espconn_dns_udp, enduser_setup_dns_recv_callback);
  1154. if (err != 0)
  1155. {
  1156. ENDUSER_SETUP_ERROR("dns_start failed. Couldn't add receive callback, unknown error.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  1157. }
  1158. err = espconn_create(state->espconn_dns_udp);
  1159. if (err == ESPCONN_ISCONN)
  1160. {
  1161. 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);
  1162. }
  1163. else if (err == ESPCONN_MEM)
  1164. {
  1165. ENDUSER_SETUP_ERROR("dns_start failed. Couldn't create connection, out of memory.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  1166. }
  1167. else if (err != 0)
  1168. {
  1169. ENDUSER_SETUP_ERROR("dns_start failed. Couldn't create connection, unknown error.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  1170. }
  1171. return 0;
  1172. }
  1173. static void enduser_setup_dns_stop(void)
  1174. {
  1175. ENDUSER_SETUP_DEBUG("enduser_setup_dns_stop");
  1176. if (state != NULL && state->espconn_dns_udp != NULL)
  1177. {
  1178. espconn_delete(state->espconn_dns_udp);
  1179. }
  1180. }
  1181. static int enduser_setup_init(lua_State *L)
  1182. {
  1183. ENDUSER_SETUP_DEBUG("enduser_setup_init");
  1184. if (state != NULL)
  1185. {
  1186. ENDUSER_SETUP_ERROR("init failed. Appears to already be started.", ENDUSER_SETUP_ERR_UNKOWN_ERROR, ENDUSER_SETUP_ERR_FATAL);
  1187. return ENDUSER_SETUP_ERR_UNKOWN_ERROR;
  1188. }
  1189. state = (enduser_setup_state_t *) zalloc(sizeof(enduser_setup_state_t));
  1190. if (state == NULL)
  1191. {
  1192. ENDUSER_SETUP_ERROR("init failed. Unable to allocate memory.", ENDUSER_SETUP_ERR_OUT_OF_MEMORY, ENDUSER_SETUP_ERR_FATAL);
  1193. return ENDUSER_SETUP_ERR_OUT_OF_MEMORY;
  1194. }
  1195. memset(state, 0, sizeof(enduser_setup_state_t));
  1196. state->lua_connected_cb_ref = LUA_NOREF;
  1197. state->lua_err_cb_ref = LUA_NOREF;
  1198. state->lua_dbg_cb_ref = LUA_NOREF;
  1199. if (!lua_isnoneornil(L, 1))
  1200. {
  1201. lua_pushvalue(L, 1);
  1202. state->lua_connected_cb_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  1203. }
  1204. else
  1205. {
  1206. state->lua_connected_cb_ref = LUA_NOREF;
  1207. }
  1208. if (!lua_isnoneornil(L, 2))
  1209. {
  1210. lua_pushvalue (L, 2);
  1211. state->lua_err_cb_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  1212. }
  1213. else
  1214. {
  1215. state->lua_err_cb_ref = LUA_NOREF;
  1216. }
  1217. if (!lua_isnoneornil(L, 3))
  1218. {
  1219. lua_pushvalue (L, 3);
  1220. state->lua_dbg_cb_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  1221. }
  1222. else
  1223. {
  1224. state->lua_dbg_cb_ref = LUA_NOREF;
  1225. }
  1226. return 0;
  1227. }
  1228. static int enduser_setup_manual(lua_State *L)
  1229. {
  1230. if (!lua_isnoneornil (L, 1))
  1231. {
  1232. manual = lua_toboolean (L, 1);
  1233. }
  1234. lua_pushboolean (L, manual);
  1235. return 1;
  1236. }
  1237. static int enduser_setup_start(lua_State *L)
  1238. {
  1239. ENDUSER_SETUP_DEBUG("enduser_setup_start");
  1240. if (!do_station_cfg_handle)
  1241. {
  1242. do_station_cfg_handle = task_get_id(do_station_cfg);
  1243. }
  1244. if(enduser_setup_init(L))
  1245. {
  1246. goto failed;
  1247. }
  1248. enduser_setup_check_station_start();
  1249. if (!manual)
  1250. {
  1251. enduser_setup_ap_start();
  1252. }
  1253. if(enduser_setup_dns_start())
  1254. {
  1255. goto failed;
  1256. }
  1257. if(enduser_setup_http_start())
  1258. {
  1259. goto failed;
  1260. }
  1261. goto out;
  1262. failed:
  1263. enduser_setup_stop(lua_getstate());
  1264. out:
  1265. return 0;
  1266. }
  1267. /**
  1268. * A wrapper needed for type-reasons strictness reasons.
  1269. */
  1270. static void enduser_setup_stop_callback(void *ptr)
  1271. {
  1272. enduser_setup_stop(lua_getstate());
  1273. }
  1274. static int enduser_setup_stop(lua_State* L)
  1275. {
  1276. ENDUSER_SETUP_DEBUG("enduser_setup_stop");
  1277. if (!manual)
  1278. {
  1279. enduser_setup_ap_stop();
  1280. }
  1281. enduser_setup_dns_stop();
  1282. enduser_setup_http_stop();
  1283. enduser_setup_free();
  1284. return 0;
  1285. }
  1286. static const LUA_REG_TYPE enduser_setup_map[] = {
  1287. { LSTRKEY( "manual" ), LFUNCVAL( enduser_setup_manual )},
  1288. { LSTRKEY( "start" ), LFUNCVAL( enduser_setup_start )},
  1289. { LSTRKEY( "stop" ), LFUNCVAL( enduser_setup_stop )},
  1290. { LNILKEY, LNILVAL}
  1291. };
  1292. NODEMCU_MODULE(ENDUSER_SETUP, "enduser_setup", enduser_setup_map, NULL);
  1293. #endif