http_server.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. /*
  2. Copyright (c) 2017-2019 Tony Pottier
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in all
  10. copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  17. SOFTWARE.
  18. @file http_server.c
  19. @author Tony Pottier
  20. @brief Defines all functions necessary for the HTTP server to run.
  21. Contains the freeRTOS task for the HTTP listener and all necessary support
  22. function to process requests, decode URLs, serve files, etc. etc.
  23. @note http_server task cannot run without the wifi_manager task!
  24. @see https://idyl.io
  25. @see https://github.com/tonyp7/esp32-wifi-manager
  26. */
  27. #include "http_server.h"
  28. #include "cmd_system.h"
  29. /* @brief tag used for ESP serial console messages */
  30. static const char TAG[] = "http_server";
  31. static const char json_start[] = "{ \"autoexec\": %u, \"list\": [";
  32. static const char json_end[] = "]}";
  33. static const char template[] = "{ \"%s\": \"%s\" }";
  34. static const char array_separator[]=",";
  35. /* @brief task handle for the http server */
  36. static TaskHandle_t task_http_server = NULL;
  37. /**
  38. * @brief embedded binary data.
  39. * @see file "component.mk"
  40. * @see https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html#embedding-binary-data
  41. */
  42. extern const uint8_t style_css_start[] asm("_binary_style_css_start");
  43. extern const uint8_t style_css_end[] asm("_binary_style_css_end");
  44. extern const uint8_t jquery_gz_start[] asm("_binary_jquery_gz_start");
  45. extern const uint8_t jquery_gz_end[] asm("_binary_jquery_gz_end");
  46. extern const uint8_t code_js_start[] asm("_binary_code_js_start");
  47. extern const uint8_t code_js_end[] asm("_binary_code_js_end");
  48. extern const uint8_t index_html_start[] asm("_binary_index_html_start");
  49. extern const uint8_t index_html_end[] asm("_binary_index_html_end");
  50. /* const http headers stored in ROM */
  51. const static char http_html_hdr[] = "HTTP/1.1 200 OK\nContent-type: text/html\n\n";
  52. const static char http_css_hdr[] = "HTTP/1.1 200 OK\nContent-type: text/css\nCache-Control: public, max-age=31536000\n\n";
  53. const static char http_js_hdr[] = "HTTP/1.1 200 OK\nContent-type: text/javascript\n\n";
  54. const static char http_jquery_gz_hdr[] = "HTTP/1.1 200 OK\nContent-type: text/javascript\nAccept-Ranges: bytes\nContent-Length: 29995\nContent-Encoding: gzip\n\n";
  55. const static char http_400_hdr[] = "HTTP/1.1 400 Bad Request\nContent-Length: 0\n\n";
  56. const static char http_404_hdr[] = "HTTP/1.1 404 Not Found\nContent-Length: 0\n\n";
  57. const static char http_503_hdr[] = "HTTP/1.1 503 Service Unavailable\nContent-Length: 0\n\n";
  58. const static char http_ok_json_no_cache_hdr[] = "HTTP/1.1 200 OK\nContent-type: application/json\nCache-Control: no-store, no-cache, must-revalidate, max-age=0\nPragma: no-cache\n\n";
  59. const static char http_redirect_hdr_start[] = "HTTP/1.1 302 Found\nLocation: http://";
  60. const static char http_redirect_hdr_end[] = "/\n\n";
  61. void http_server_start(){
  62. if(task_http_server == NULL){
  63. xTaskCreate(&http_server, "http_server", 1024*3, NULL, WIFI_MANAGER_TASK_PRIORITY-1, &task_http_server);
  64. }
  65. }
  66. void http_server(void *pvParameters) {
  67. struct netconn *conn, *newconn;
  68. err_t err;
  69. conn = netconn_new(NETCONN_TCP);
  70. netconn_bind(conn, IP_ADDR_ANY, 80);
  71. netconn_listen(conn);
  72. ESP_LOGI(TAG, "HTTP Server listening on 80/tcp");
  73. do {
  74. err = netconn_accept(conn, &newconn);
  75. if (err == ERR_OK) {
  76. http_server_netconn_serve(newconn);
  77. netconn_delete(newconn);
  78. }
  79. else
  80. {
  81. ESP_LOGE(TAG,"Error accepting new connection. Terminating HTTP server");
  82. }
  83. taskYIELD(); /* allows the freeRTOS scheduler to take over if needed. */
  84. } while(err == ERR_OK);
  85. netconn_close(conn);
  86. netconn_delete(conn);
  87. vTaskDelete( NULL );
  88. }
  89. char* http_server_get_header(char *request, char *header_name, int *len) {
  90. *len = 0;
  91. char *ret = NULL;
  92. char *ptr = NULL;
  93. ptr = strstr(request, header_name);
  94. if (ptr) {
  95. ret = ptr + strlen(header_name);
  96. ptr = ret;
  97. while (*ptr != '\0' && *ptr != '\n' && *ptr != '\r') {
  98. (*len)++;
  99. ptr++;
  100. }
  101. return ret;
  102. }
  103. return NULL;
  104. }
  105. void http_server_netconn_serve(struct netconn *conn) {
  106. struct netbuf *inbuf;
  107. char *buf = NULL;
  108. u16_t buflen;
  109. err_t err;
  110. const char new_line[2] = "\n";
  111. err = netconn_recv(conn, &inbuf);
  112. if (err == ERR_OK) {
  113. netbuf_data(inbuf, (void**)&buf, &buflen);
  114. /* extract the first line of the request */
  115. char *save_ptr = buf;
  116. char *line = strtok_r(save_ptr, new_line, &save_ptr);
  117. ESP_LOGD(TAG,"Processing line %s",line);
  118. if(line) {
  119. /* captive portal functionality: redirect to access point IP for HOST that are not the access point IP OR the STA IP */
  120. int lenH = 0;
  121. char *host = http_server_get_header(save_ptr, "Host: ", &lenH);
  122. /* determine if Host is from the STA IP address */
  123. wifi_manager_lock_sta_ip_string(portMAX_DELAY);
  124. bool access_from_sta_ip = lenH > 0?strstr(host, wifi_manager_get_sta_ip_string()):false;
  125. wifi_manager_unlock_sta_ip_string();
  126. if (lenH > 0 && !strstr(host, DEFAULT_AP_IP) && !access_from_sta_ip) {
  127. ESP_LOGI(TAG,"Redirecting to default AP IP Address : %s", DEFAULT_AP_IP);
  128. netconn_write(conn, http_redirect_hdr_start, sizeof(http_redirect_hdr_start) - 1, NETCONN_NOCOPY);
  129. netconn_write(conn, DEFAULT_AP_IP, sizeof(DEFAULT_AP_IP) - 1, NETCONN_NOCOPY);
  130. netconn_write(conn, http_redirect_hdr_end, sizeof(http_redirect_hdr_end) - 1, NETCONN_NOCOPY);
  131. }
  132. else{
  133. /* default page */
  134. if(strstr(line, "GET / ")) {
  135. netconn_write(conn, http_html_hdr, sizeof(http_html_hdr) - 1, NETCONN_NOCOPY);
  136. netconn_write(conn, index_html_start, index_html_end - index_html_start, NETCONN_NOCOPY);
  137. }
  138. else if(strstr(line, "GET /jquery.js ")) {
  139. netconn_write(conn, http_jquery_gz_hdr, sizeof(http_jquery_gz_hdr) - 1, NETCONN_NOCOPY);
  140. netconn_write(conn, jquery_gz_start, jquery_gz_end - jquery_gz_start, NETCONN_NOCOPY);
  141. }
  142. else if(strstr(line, "GET /code.js ")) {
  143. netconn_write(conn, http_js_hdr, sizeof(http_js_hdr) - 1, NETCONN_NOCOPY);
  144. netconn_write(conn, code_js_start, code_js_end - code_js_start, NETCONN_NOCOPY);
  145. }
  146. else if(strstr(line, "GET /ap.json ")) {
  147. /* if we can get the mutex, write the last version of the AP list */
  148. ESP_LOGI(TAG,"Processing ap.json request");
  149. if(wifi_manager_lock_json_buffer(( TickType_t ) 10)){
  150. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY);
  151. char *buff = wifi_manager_get_ap_list_json();
  152. netconn_write(conn, buff, strlen(buff), NETCONN_NOCOPY);
  153. wifi_manager_unlock_json_buffer();
  154. }
  155. else{
  156. netconn_write(conn, http_503_hdr, sizeof(http_503_hdr) - 1, NETCONN_NOCOPY);
  157. ESP_LOGE(TAG, "http_server_netconn_serve: GET /ap.json failed to obtain mutex");
  158. }
  159. /* request a wifi scan */
  160. ESP_LOGI(TAG,"Starting wifi scan");
  161. wifi_manager_scan_async();
  162. }
  163. else if(strstr(line, "GET /style.css ")) {
  164. netconn_write(conn, http_css_hdr, sizeof(http_css_hdr) - 1, NETCONN_NOCOPY);
  165. netconn_write(conn, style_css_start, style_css_end - style_css_start, NETCONN_NOCOPY);
  166. }
  167. else if(strstr(line, "GET /status.json ")){
  168. ESP_LOGI(TAG,"Serving status.json");
  169. if(wifi_manager_lock_json_buffer(( TickType_t ) 10)){
  170. char *buff = wifi_manager_get_ip_info_json();
  171. if(buff){
  172. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY);
  173. netconn_write(conn, buff, strlen(buff), NETCONN_NOCOPY);
  174. wifi_manager_unlock_json_buffer();
  175. }
  176. else{
  177. netconn_write(conn, http_503_hdr, sizeof(http_503_hdr) - 1, NETCONN_NOCOPY);
  178. }
  179. }
  180. else{
  181. netconn_write(conn, http_503_hdr, sizeof(http_503_hdr) - 1, NETCONN_NOCOPY);
  182. ESP_LOGE(TAG, "http_server_netconn_serve: GET /status failed to obtain mutex");
  183. }
  184. }
  185. else if(strstr(line, "GET /config.json ")){
  186. ESP_LOGI(TAG,"Serving config.json");
  187. char autoexec_name[21]={0};
  188. char * autoexec_value=NULL;
  189. uint8_t autoexec_flag=0;
  190. int buflen=MAX_COMMAND_LINE_SIZE+strlen(template)+1;
  191. char * buff = malloc(buflen);
  192. char *s = "\"";
  193. char *r = "\\\"";
  194. if(!buff)
  195. {
  196. ESP_LOGE(TAG,"Unable to allocate buffer for config.json!");
  197. netconn_write(conn, http_503_hdr, sizeof(http_503_hdr) - 1, NETCONN_NOCOPY);
  198. }
  199. else
  200. {
  201. int i=1;
  202. size_t l = 0;
  203. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY);
  204. autoexec_flag = wifi_manager_get_flag();
  205. snprintf(buff,buflen-1, json_start, autoexec_flag);
  206. netconn_write(conn, buff, strlen(buff), NETCONN_NOCOPY);
  207. do {
  208. snprintf(autoexec_name,sizeof(autoexec_name)-1,"autoexec%u",i);
  209. ESP_LOGD(TAG,"Getting command name %s", autoexec_name);
  210. autoexec_value = wifi_manager_alloc_get_config(autoexec_name, &l);
  211. if(autoexec_value!=NULL ){
  212. if(i>1)
  213. {
  214. netconn_write(conn, array_separator, strlen(array_separator), NETCONN_NOCOPY);
  215. ESP_LOGD(TAG,"%s", array_separator);
  216. }
  217. ESP_LOGI(TAG,"found command %s = %s", autoexec_name, autoexec_value);
  218. strreplace(autoexec_value, s, r);
  219. snprintf(buff, buflen-1, template, autoexec_name, autoexec_value);
  220. netconn_write(conn, buff, strlen(buff), NETCONN_NOCOPY);
  221. ESP_LOGD(TAG,"%s", buff);
  222. ESP_LOGD(TAG,"Freeing memory for command %s name", autoexec_name);
  223. free(autoexec_value);
  224. }
  225. else {
  226. ESP_LOGD(TAG,"No matching command found for name %s", autoexec_name);
  227. break;
  228. }
  229. i++;
  230. } while(1);
  231. free(buff);
  232. netconn_write(conn, json_end, strlen(json_end), NETCONN_NOCOPY);
  233. ESP_LOGD(TAG,"%s", json_end);
  234. }
  235. }
  236. else if(strstr(line, "POST /factory.json ")){
  237. guided_factory();
  238. }
  239. else if(strstr(line, "POST /config.json ")){
  240. ESP_LOGI(TAG,"Serving POST config.json");
  241. if(wifi_manager_lock_json_buffer(( TickType_t ) 10)){
  242. int i=1;
  243. int lenS = 0, lenA=0;
  244. char autoexec_name[22]={0};
  245. char autoexec_key[12]={0};
  246. char * autoexec_value=NULL;
  247. char * autoexec_flag_s=NULL;
  248. uint8_t autoexec_flag=0;
  249. autoexec_flag_s = http_server_get_header(save_ptr, "X-Custom-autoexec: ", &lenA);
  250. if(autoexec_flag_s!=NULL && lenA > 0)
  251. {
  252. autoexec_flag = atoi(autoexec_flag_s);
  253. wifi_manager_save_autoexec_flag(autoexec_flag);
  254. }
  255. do {
  256. if(snprintf(autoexec_name,sizeof(autoexec_name)-1,"X-Custom-autoexec%u: ",i)<0)
  257. {
  258. ESP_LOGE(TAG,"Unable to process autoexec%u. Name length overflow.",i);
  259. break;
  260. }
  261. if(snprintf(autoexec_key,sizeof(autoexec_key)-1,"autoexec%u",i++)<0)
  262. {
  263. ESP_LOGE(TAG,"Unable to process autoexec%u. Name length overflow.",i);
  264. break;
  265. }
  266. ESP_LOGD(TAG,"Looking for command name %s.", autoexec_name);
  267. autoexec_value = http_server_get_header(save_ptr, autoexec_name, &lenS);
  268. if(autoexec_value ){
  269. if(lenS < MAX_COMMAND_LINE_SIZE ){
  270. ESP_LOGD(TAG, "http_server_netconn_serve: config.json/ call, with %s: %s, length %i", autoexec_key, autoexec_value, lenS);
  271. wifi_manager_save_autoexec_config(autoexec_value,autoexec_key,lenS);
  272. }
  273. else
  274. {
  275. ESP_LOGE(TAG,"command line length is too long : %s = %s", autoexec_name, autoexec_value);
  276. }
  277. }
  278. else {
  279. ESP_LOGD(TAG,"No matching command found for name %s", autoexec_name);
  280. break;
  281. }
  282. } while(1);
  283. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY); //200ok
  284. }
  285. else{
  286. netconn_write(conn, http_503_hdr, sizeof(http_503_hdr) - 1, NETCONN_NOCOPY);
  287. ESP_LOGE(TAG, "http_server_netconn_serve: GET /status failed to obtain mutex");
  288. }
  289. }
  290. else if(strstr(line, "DELETE /connect.json ")) {
  291. ESP_LOGI(TAG, "http_server_netconn_serve: DELETE /connect.json");
  292. /* request a disconnection from wifi and forget about it */
  293. wifi_manager_disconnect_async();
  294. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY); /* 200 ok */
  295. }
  296. else if(strstr(line, "POST /connect.json ")) {
  297. ESP_LOGI(TAG, "http_server_netconn_serve: POST /connect.json");
  298. bool found = false;
  299. int lenS = 0, lenP = 0;
  300. char *ssid = NULL, *password = NULL;
  301. ssid = http_server_get_header(save_ptr, "X-Custom-ssid: ", &lenS);
  302. password = http_server_get_header(save_ptr, "X-Custom-pwd: ", &lenP);
  303. if(ssid && lenS <= MAX_SSID_SIZE && password && lenP <= MAX_PASSWORD_SIZE){
  304. wifi_config_t* config = wifi_manager_get_wifi_sta_config();
  305. memset(config, 0x00, sizeof(wifi_config_t));
  306. memcpy(config->sta.ssid, ssid, lenS);
  307. memcpy(config->sta.password, password, lenP);
  308. ESP_LOGD(TAG, "http_server_netconn_serve: wifi_manager_connect_async() call, with ssid: %s, password: %s", ssid, password);
  309. wifi_manager_connect_async();
  310. netconn_write(conn, http_ok_json_no_cache_hdr, sizeof(http_ok_json_no_cache_hdr) - 1, NETCONN_NOCOPY); //200ok
  311. found = true;
  312. }
  313. if(!found){
  314. /* bad request the authentification header is not complete/not the correct format */
  315. netconn_write(conn, http_400_hdr, sizeof(http_400_hdr) - 1, NETCONN_NOCOPY);
  316. ESP_LOGE(TAG, "bad request the authentification header is not complete/not the correct format");
  317. }
  318. }
  319. else{
  320. netconn_write(conn, http_400_hdr, sizeof(http_400_hdr) - 1, NETCONN_NOCOPY);
  321. ESP_LOGE(TAG, "bad request");
  322. }
  323. }
  324. }
  325. else{
  326. ESP_LOGE(TAG, "URL Not found. Sending 404.");
  327. netconn_write(conn, http_404_hdr, sizeof(http_404_hdr) - 1, NETCONN_NOCOPY);
  328. }
  329. }
  330. /* free the buffer */
  331. netbuf_delete(inbuf);
  332. }
  333. void strreplace(char *src, char *str, char *rep)
  334. {
  335. char *p = strstr(src, str);
  336. if (p)
  337. {
  338. int len = strlen(src)+strlen(rep)-strlen(str);
  339. char r[len];
  340. memset(r, 0, len);
  341. if ( p >= src ){
  342. strncpy(r, src, p-src);
  343. r[p-src]='\0';
  344. strncat(r, rep, strlen(rep));
  345. strncat(r, p+strlen(str), p+strlen(str)-src+strlen(src));
  346. strcpy(src, r);
  347. strreplace(p+strlen(rep), str, rep);
  348. }
  349. }
  350. }