Thu, 02 May 2019 21:19:50 +0200
Use PROJECT_VER for version number. Updated README and info screen.
0 | 1 | /** |
2 | * @file task_http.c | |
3 | * @brief HTTP and Websocket server functions. | |
4 | * This uses some ESP32 Websocket code written by Blake Felt - blake.w.felt@gmail.com | |
5 | */ | |
6 | #include "config.h" | |
7 | #include "mbedtls/base64.h" | |
8 | #include "mbedtls/sha1.h" | |
9 | ||
10 | ||
1
ad2c8b13eb88
Updated lots of doxygen comments
Michiel Broek <mbroek@mbse.eu>
parents:
0
diff
changeset
|
11 | static const char *TAG = "task_http"; |
0 | 12 | static QueueHandle_t client_queue; |
13 | const static int client_queue_size = 10; | |
14 | static TaskHandle_t xTaskHTTP = NULL; | |
15 | static TaskHandle_t xTaskQueue = NULL; | |
16 | ||
17 | ||
18 | ||
1
ad2c8b13eb88
Updated lots of doxygen comments
Michiel Broek <mbroek@mbse.eu>
parents:
0
diff
changeset
|
19 | /** |
ad2c8b13eb88
Updated lots of doxygen comments
Michiel Broek <mbroek@mbse.eu>
parents:
0
diff
changeset
|
20 | * @brief Debug dump buffer |
ad2c8b13eb88
Updated lots of doxygen comments
Michiel Broek <mbroek@mbse.eu>
parents:
0
diff
changeset
|
21 | * @param buf The buffer |
ad2c8b13eb88
Updated lots of doxygen comments
Michiel Broek <mbroek@mbse.eu>
parents:
0
diff
changeset
|
22 | * @param buflen Length of the buffer |
ad2c8b13eb88
Updated lots of doxygen comments
Michiel Broek <mbroek@mbse.eu>
parents:
0
diff
changeset
|
23 | */ |
0 | 24 | void dump_buf(char *buf, uint16_t buflen); |
25 | ||
26 | ||
1
ad2c8b13eb88
Updated lots of doxygen comments
Michiel Broek <mbroek@mbse.eu>
parents:
0
diff
changeset
|
27 | |
0 | 28 | /** |
29 | * @brief Send HTTP error and message | |
30 | * @param conn The socket to send to. | |
31 | * @param error The HTTP error code. | |
32 | * @param message Yhe human readable explanation. | |
33 | * @paeam body The human readable explanation. | |
34 | */ | |
35 | static void http_error(struct netconn *conn, int error, char *message, char *body) | |
36 | { | |
37 | char *tmp = malloc(200); | |
38 | ||
39 | ESP_LOGI(TAG, "Http response %d - %s", error, message); | |
40 | if (strlen(body)) { | |
41 | snprintf(tmp, 199, "HTTP/1.1 %d %s\r\nContent-type: text/plain\r\n\r\n%s\n", error, message, body); | |
42 | } else { | |
43 | snprintf(tmp, 199, "HTTP/1.1 %d %s\r\n\r\n", error, message); | |
44 | } | |
45 | netconn_write(conn, tmp, strlen(tmp), NETCONN_NOCOPY); | |
46 | free(tmp); | |
47 | } | |
48 | ||
49 | ||
50 | ||
51 | /** | |
52 | * @brief Send HTTP file from the filesystem. | |
53 | * @param conn The network connection. | |
54 | * @param url The requested url. | |
55 | * @param mod_since The date/time of the file, or NULL. | |
56 | * @param ipstr The IP address of the remote. | |
57 | */ | |
58 | static void http_sendfile(struct netconn *conn, char *url, char *mod_since, char *ipstr) | |
59 | { | |
60 | char temp_url[128], temp_url_gz[128], header[128], c_type[32]; | |
61 | struct stat st; | |
62 | off_t filesize; | |
63 | size_t sentsize; | |
64 | char strftime_buf[64]; | |
65 | err_t err; | |
66 | bool send_gz; | |
67 | FILE *f; | |
68 | ||
69 | if (url[strlen(url) - 1] == '/') { | |
70 | // If no filename given, use index.html | |
71 | sprintf(temp_url, "/spiffs/w%sindex.html", url); | |
72 | } else if (strncmp(url, "/log/", 5) == 0) { | |
73 | // Logfiles are on the SD card. | |
74 | sprintf(temp_url, "/sdcard/w%s", url); | |
75 | } else { | |
76 | sprintf(temp_url, "/spiffs/w%s", url); | |
77 | for (int i = 0; i < 127; i++) { | |
78 | if (temp_url[i] == '?') | |
79 | temp_url[i] = '\0'; | |
80 | if (temp_url[i] == '\0') | |
81 | break; | |
82 | } | |
83 | } | |
84 | sprintf(temp_url_gz, "%s.gz", temp_url); | |
85 | ||
86 | /* | |
87 | * Get filesize and date for the response headers. | |
88 | * Note that the /spiffs filesystem doesn't support file timestamps | |
89 | * and returns the epoch for each file. Therefore we cannot use | |
90 | * the cache based on timestamps. | |
91 | */ | |
92 | filesize = 0; | |
93 | strftime_buf[0] = '\0'; | |
94 | send_gz = false; | |
95 | if (stat(temp_url_gz, &st) == 0) { | |
96 | filesize = st.st_size; | |
97 | strftime(strftime_buf, sizeof(strftime_buf), "%a, %d %b %Y %T %z", localtime(&(st.st_mtime))); | |
98 | send_gz = true; | |
99 | } else if (stat(temp_url, &st) == 0) { | |
100 | filesize = st.st_size; | |
101 | strftime(strftime_buf, sizeof(strftime_buf), "%a, %d %b %Y %T %z", localtime(&(st.st_mtime))); | |
102 | } | |
103 | ||
104 | /* | |
105 | * If we have a If-Modified-Since parameter, compare that with the current | |
106 | * filedate on disk. If It's the same send a 304 response. | |
107 | * Cannot work on /spiffs. | |
108 | */ | |
109 | #if 0 | |
110 | time_t Now; | |
111 | struct tm timeInfo; | |
112 | if (mod_since && strlen(strftime_buf)) { | |
113 | time(&Now); | |
114 | localtime_r(&Now, &timeInfo); | |
115 | strftime(strftime_buf, sizeof(strftime_buf), "%a, %d %b %Y %T %z", &timeInfo); | |
116 | sprintf(header, "HTTP/1.1 304 Not Modified\r\nDate: %s\r\n\r\n", strftime_buf); | |
117 | netconn_write(conn, header, strlen(header), NETCONN_NOCOPY); | |
118 | ESP_LOGI(TAG, "http_sendfile %s Not Modified, ok", temp_url); | |
119 | return; | |
120 | } | |
121 | #endif | |
122 | ||
123 | if (send_gz) { | |
124 | f = fopen(temp_url_gz, "r"); | |
125 | } else { | |
126 | f = fopen(temp_url, "r"); | |
127 | } | |
128 | if (f == NULL) { | |
129 | ESP_LOGI(TAG, "%s url \'%s\' file \'%s\' not found", ipstr, url, temp_url); | |
130 | http_error(conn, 404, "Not found", "Not found"); | |
131 | return; | |
132 | } | |
133 | ||
134 | if (strcmp(".html", &temp_url[strlen(temp_url) - 5]) == 0) { | |
135 | sprintf(c_type, "text/html"); | |
136 | } else if (strcmp(".css", &temp_url[strlen(temp_url) - 4]) == 0) { | |
137 | sprintf(c_type, "text/css"); | |
138 | } else if (strcmp(".js", &temp_url[strlen(temp_url) - 3]) == 0) { | |
139 | sprintf(c_type, "text/javascript"); | |
140 | } else if (strcmp(".json", &temp_url[strlen(temp_url) - 5]) == 0) { | |
141 | sprintf(c_type, "text/json"); | |
142 | } else if (strcmp(".gz", &temp_url[strlen(temp_url) - 3]) == 0) { | |
143 | sprintf(c_type, "application/x-gzip"); | |
144 | } else if (strcmp(".png", &temp_url[strlen(temp_url) - 4]) == 0) { | |
145 | sprintf(c_type, "image/png"); | |
146 | } else if (strcmp(".svg", &temp_url[strlen(temp_url) - 4]) == 0) { | |
147 | sprintf(c_type, "image/svg+xml"); | |
148 | } else if (strcmp(".oga", &temp_url[strlen(temp_url) - 4]) == 0) { | |
149 | sprintf(c_type, "audio/ogg"); | |
150 | } else if (strcmp(".ico", &temp_url[strlen(temp_url) - 4]) == 0) { | |
151 | sprintf(c_type, "image/x-icon"); | |
152 | } else if (strcmp(".xml", &temp_url[strlen(temp_url) - 4]) == 0) { | |
153 | sprintf(c_type, "text/xml"); | |
154 | } else { | |
155 | sprintf(c_type, "application/octet-stream"); | |
156 | printf("Unknown content type for %s\n", temp_url); | |
157 | } | |
158 | ||
159 | vTaskDelay(2 / portTICK_PERIOD_MS); | |
160 | // httpdHeader(connData, "Cache-Control", "max-age=3600, must-revalidate"); | |
161 | if (filesize) { | |
162 | sprintf(header, "HTTP/1.1 200 OK\r\nLast-Modified: %s\r\nContent-Length: %ld\r\nContent-type: %s\r\n", strftime_buf, filesize, c_type); | |
163 | } else { | |
164 | sprintf(header, "HTTP/1.1 200 OK\r\nContent-type: %s\r\n", c_type); | |
165 | } | |
166 | if (send_gz) { | |
167 | sprintf(header, "%sContent-Encoding: gzip\r\n", header); | |
168 | } | |
169 | sprintf(header, "%s\r\n", header); // Add last empty line. | |
170 | err = netconn_write(conn, header, strlen(header), NETCONN_NOCOPY); | |
171 | if (err != ERR_OK) { | |
172 | ESP_LOGE(TAG, "%s sendfile %s%s err=%d on header write", ipstr, temp_url, (send_gz) ? ".gz":"", err); | |
173 | fclose(f); | |
174 | return; | |
175 | } | |
176 | // if (strstr(acceptEncodingBuffer, "gzip") == NULL) | |
177 | // http_error(conn, 501, "Not implemented", "Your browser does not accept gzip-compressed data."); | |
178 | ||
179 | sentsize = 0; | |
180 | uint8_t *buff = malloc(1024); | |
181 | size_t bytes; | |
182 | int pause = 0; | |
183 | ||
184 | for (;;) { | |
185 | bytes = fread(buff, 1, 1024, f); | |
186 | if (bytes == 0) | |
187 | break; | |
188 | ||
189 | err = netconn_write(conn, buff, bytes, NETCONN_NOCOPY); | |
190 | if (err != ERR_OK) { | |
191 | ESP_LOGE(TAG, "%s sendfile %s%s err=%d send %u bytes of %ld bytes", ipstr, temp_url, (send_gz) ? ".gz":"", err, sentsize, filesize); | |
192 | break; | |
193 | } | |
194 | vTaskDelay(2 / portTICK_PERIOD_MS); | |
195 | sentsize += bytes; | |
196 | pause++; | |
197 | if (pause > 50) { // 50 K | |
198 | pause = 0; | |
199 | vTaskDelay(50 / portTICK_PERIOD_MS); | |
200 | } | |
201 | } | |
202 | fclose(f); | |
203 | free(buff); | |
204 | ||
205 | if (sentsize == filesize) { | |
206 | ESP_LOGI(TAG, "%s sendfile %s%s sent %u bytes, ok (%s)", ipstr, temp_url, (send_gz) ? ".gz":"", sentsize, url); | |
207 | } | |
208 | } | |
209 | ||
210 | ||
211 | ||
212 | /** | |
213 | * @brief Handle web ui websocket events. | |
214 | */ | |
215 | void websock_callback(uint8_t num, WEBSOCKET_TYPE_t type, char* msg, uint64_t len) | |
216 | { | |
217 | switch(type) { | |
218 | case WEBSOCKET_CONNECT: | |
219 | ESP_LOGI(TAG,"Websocket client %i connected!",num); | |
220 | break; | |
221 | ||
222 | case WEBSOCKET_DISCONNECT_EXTERNAL: | |
223 | ESP_LOGI(TAG,"Websocket client %i sent a disconnect message",num); | |
224 | break; | |
225 | ||
226 | case WEBSOCKET_DISCONNECT_INTERNAL: | |
227 | ESP_LOGI(TAG,"Websocket client %i was disconnected",num); | |
228 | break; | |
229 | ||
230 | case WEBSOCKET_DISCONNECT_ERROR: | |
231 | ESP_LOGI(TAG,"Websocket client %i was disconnected due to an error",num); | |
232 | break; | |
233 | ||
234 | case WEBSOCKET_TEXT: | |
235 | ESP_LOGI(TAG,"Websocket client %i sent text message of size %i:\n%s",num,(uint32_t)len,msg); | |
236 | dump_buf(msg, len); | |
237 | break; | |
238 | ||
239 | case WEBSOCKET_BIN: | |
240 | ESP_LOGI(TAG,"Websocket client %i sent bin message of size %i:\n",num,(uint32_t)len); | |
241 | dump_buf(msg, len); | |
242 | break; | |
243 | ||
244 | case WEBSOCKET_PING: | |
245 | ESP_LOGI(TAG,"client %i pinged us with message of size %i:\n%s",num,(uint32_t)len,msg); | |
246 | break; | |
247 | ||
248 | case WEBSOCKET_PONG: | |
249 | ESP_LOGI(TAG,"client %i responded to the ping",num); | |
250 | break; | |
251 | } | |
252 | } | |
253 | ||
254 | ||
255 | ||
256 | void dump_buf(char *buf, uint16_t buflen) | |
257 | { | |
258 | int i = 0, l = 1; | |
259 | ||
260 | printf("request length %d\n00: ", buflen); | |
261 | for (;;) { | |
262 | if (i >= buflen) | |
263 | break; | |
264 | if ((buf[i] < ' ') || (buf[i] > 126)) { | |
265 | if (buf[i] == '\n') { | |
266 | printf("\\n\n%02d: ", l); | |
267 | l++; | |
268 | } else if (buf[i] == '\r') { | |
269 | printf("\\r"); | |
270 | } else { | |
271 | printf("\\%02x", buf[i]); | |
272 | } | |
273 | } else { | |
274 | printf("%c", buf[i]); | |
275 | } | |
276 | i++; | |
277 | } | |
278 | printf("\n"); | |
279 | } | |
280 | ||
281 | ||
282 | ||
283 | /** | |
284 | * @brief Serve any client. | |
285 | * @param http_client_sock The socket on which the client is connected. | |
286 | */ | |
287 | static void http_serve(struct netconn *conn) | |
288 | { | |
289 | char ipstr[IPADDR_STRLEN_MAX]; | |
290 | struct netbuf *inbuf; | |
291 | static char *buf; | |
292 | static uint16_t buflen; | |
293 | static err_t err; | |
294 | char url[128], *p, *mod_since = NULL; | |
295 | ip_addr_t remote_addr; | |
296 | uint16_t remote_port; | |
297 | ||
298 | if (netconn_getaddr(conn, &remote_addr, &remote_port, 0) == ERR_OK) { | |
299 | strcpy(ipstr, ip4addr_ntoa(ip_2_ip4(&remote_addr))); | |
300 | } else { | |
301 | ipstr[0] = '\0'; | |
302 | } | |
303 | ||
304 | netconn_set_recvtimeout(conn,1000); // allow a connection timeout of 1 second | |
305 | err = netconn_recv(conn, &inbuf); | |
306 | ||
307 | if (err != ERR_OK) { | |
308 | if (err != ERR_TIMEOUT) { // Ignore timeout | |
309 | ESP_LOGI(TAG,"%s error %d on read", ipstr, err); | |
310 | } | |
311 | netconn_close(conn); | |
312 | netconn_delete(conn); | |
313 | netbuf_delete(inbuf); | |
314 | return; | |
315 | } | |
316 | ||
317 | netbuf_data(inbuf, (void**)&buf, &buflen); | |
318 | ||
319 | if (buf) { | |
320 | /* | |
321 | * Build url string from the data buffer. | |
322 | * It looks like: GET /app/localization.js HTTP/1.1 | |
323 | */ | |
324 | for (int i = 0; i < 10; i++) { | |
325 | if (buf[i] == ' ') { | |
326 | i++; | |
327 | for (int j = i; j < 128; j++) { | |
328 | url[j-i] = buf[j]; | |
329 | if (url[j-i] == ' ') { | |
330 | url[j-i] = '\0'; | |
331 | break; | |
332 | } | |
333 | } | |
334 | break; | |
335 | } | |
336 | } | |
337 | ||
338 | if (strstr(buf, "GET /logfiles.json")) { | |
339 | char temp[64]; | |
340 | FILE *dest = fopen("/spiffs/w/logfiles.json", "w"); | |
341 | if (dest) { | |
342 | fprintf(dest, "{\"Dir\":[{\"Folder\":\"/log\",\"Files\":["); | |
343 | DIR *dir = opendir("/sdcard/w/log"); | |
344 | if (dir) { | |
345 | struct dirent* de = readdir(dir); | |
346 | struct stat st; | |
347 | bool comma = false; | |
348 | while (de) { | |
349 | sprintf(temp, "/sdcard/w/log/%s", de->d_name); | |
350 | if (stat(temp, &st) == ESP_OK) { | |
351 | fprintf(dest, "%s{\"File\":\"%s\",\"Size\":%ld,\"Date\":%ld}", (comma)?",":"", de->d_name, st.st_size, st.st_mtime); | |
352 | comma = true; | |
353 | } | |
354 | de = readdir(dir); | |
355 | vTaskDelay(5 / portTICK_PERIOD_MS); | |
356 | } | |
357 | closedir(dir); | |
358 | } | |
359 | fprintf(dest, "]}]}"); | |
360 | fclose(dest); | |
361 | } | |
362 | http_sendfile(conn, "/logfiles.json", NULL, ipstr); | |
363 | netconn_close(conn); | |
364 | netconn_delete(conn); | |
365 | netbuf_delete(inbuf); | |
366 | unlink("/spiffs/w/logfiles.json"); | |
367 | return; | |
368 | } | |
369 | ||
370 | // http requests | |
371 | if (! strstr(buf,"Upgrade: websocket")) { // Not websocket | |
372 | p = strstr(buf, "If-Modified-Since:"); // May be cached | |
373 | if (p) { | |
374 | size_t mod_len = strcspn(p, " "); | |
375 | p += (int)(mod_len + 1); | |
376 | mod_len = strcspn(p, "\r\n"); | |
377 | mod_since = malloc(mod_len + 2); | |
378 | memcpy(mod_since, p, mod_len); | |
379 | mod_since[mod_len] = '\0'; | |
380 | } | |
381 | http_sendfile(conn, url, mod_since, ipstr); | |
382 | if (mod_since) | |
383 | free(mod_since); | |
384 | mod_since = NULL; | |
385 | netconn_close(conn); | |
386 | netconn_delete(conn); | |
387 | netbuf_delete(inbuf); | |
388 | return; | |
389 | } | |
390 | ||
391 | // websocket for web UI. | |
392 | if ((strstr(buf,"GET /ws ") && strstr(buf,"Upgrade: websocket"))) { | |
393 | int nr = ws_server_add_client_protocol(conn, buf, buflen, "/ws", "binary", websock_callback); | |
394 | ESP_LOGI(TAG, "%s new websocket on /ws client: %d", ipstr, nr); | |
395 | netbuf_delete(inbuf); | |
396 | TFTstartWS(nr); | |
397 | // Startup something? Init webscreen? | |
398 | return; | |
399 | } | |
400 | ||
401 | dump_buf(buf, buflen); | |
402 | ||
403 | if (strstr(buf, "GET /")) { | |
404 | ESP_LOGI(TAG, "%s request: %s", ipstr, buf); | |
405 | http_error(conn, 404, "Not found", "Not found"); | |
406 | } else { | |
407 | http_error(conn, 405, "Invalid method", "Invalid method"); | |
408 | } | |
409 | } | |
410 | ||
411 | netconn_close(conn); | |
412 | netconn_delete(conn); | |
413 | netbuf_delete(inbuf); | |
414 | } | |
415 | ||
416 | ||
417 | ||
418 | /** | |
419 | * @brief Handles clients when they first connect. passes to a queue | |
420 | */ | |
421 | static void task_HTTPserver(void* pvParameters) | |
422 | { | |
423 | struct netconn *conn, *newconn; | |
424 | static err_t err; | |
425 | ||
426 | ESP_LOGI(TAG, "Starting http server_task"); | |
427 | client_queue = xQueueCreate(client_queue_size,sizeof(struct netconn*)); | |
428 | ||
429 | conn = netconn_new(NETCONN_TCP); | |
430 | netconn_bind(conn,NULL,80); | |
431 | netconn_listen(conn); | |
432 | ||
433 | do { | |
434 | err = netconn_accept(conn, &newconn); | |
435 | if (err == ERR_OK) { | |
436 | if (xQueueSendToBack(client_queue,&newconn,portMAX_DELAY) != pdTRUE) { | |
437 | ESP_LOGE(TAG, "xQueueSendToBack() queue full"); | |
438 | }; | |
439 | } | |
440 | vTaskDelay(5 / portTICK_PERIOD_MS); | |
441 | } while (err == ERR_OK); | |
442 | ||
443 | ESP_LOGE(TAG, "Stopping http server_task"); | |
444 | netconn_close(conn); | |
445 | netconn_delete(conn); | |
446 | vTaskDelete(NULL); | |
447 | } | |
448 | ||
449 | ||
450 | ||
451 | /** | |
452 | * @brief Receives clients from queue and handle them. | |
453 | */ | |
454 | static void task_Queue(void* pvParameters) | |
455 | { | |
456 | struct netconn* conn; | |
457 | ||
458 | ESP_LOGI(TAG, "Starting Queue task"); | |
459 | for(;;) { | |
460 | xQueueReceive(client_queue, &conn, portMAX_DELAY); | |
461 | if (!conn) | |
462 | continue; | |
463 | http_serve(conn); | |
464 | vTaskDelay(2 / portTICK_PERIOD_MS); | |
465 | } | |
466 | ESP_LOGE(TAG, "Stopping Queue task"); | |
467 | vTaskDelete(NULL); | |
468 | } | |
469 | ||
470 | ||
471 | ||
472 | void start_http_websocket(void) | |
473 | { | |
474 | ESP_LOGI(TAG, "Starting HTTP/Websocket server"); | |
475 | ||
476 | ws_server_start(); | |
477 | xTaskCreate(&task_HTTPserver, "HTTPserver", 3000, NULL, 9, &xTaskHTTP); | |
478 | xTaskCreate(&task_Queue, "Queue", 4000, NULL, 6, &xTaskQueue); | |
479 | } | |
480 |