Sat, 27 Oct 2018 15:55:16 +0200
Boot now checks got IP status before installing the http and vnc servers.
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 VNC websocket events. | |
214 | */ | |
215 | void websockify_callback(uint8_t num, WEBSOCKET_TYPE_t type, char* msg, uint64_t len) | |
216 | { | |
217 | switch(type) { | |
218 | case WEBSOCKET_DISCONNECT_EXTERNAL: | |
219 | VncStopWS(num); | |
220 | break; | |
221 | ||
222 | case WEBSOCKET_DISCONNECT_INTERNAL: | |
223 | ESP_LOGI(TAG,"Websockify client %i was disconnected",num); | |
224 | VncStopWS(num); | |
225 | break; | |
226 | ||
227 | case WEBSOCKET_DISCONNECT_ERROR: | |
228 | ESP_LOGI(TAG,"Websockify client %i was disconnected due to an error",num); | |
229 | VncStopWS(num); | |
230 | break; | |
231 | ||
232 | case WEBSOCKET_BIN: | |
233 | VncGetWSmessage(msg, len); | |
234 | //dump_buf(msg, len); | |
235 | break; | |
236 | ||
21
9e4cce24f6ff
Removed some unused code from the vnc websocket connection
Michiel Broek <mbroek@mbse.eu>
parents:
1
diff
changeset
|
237 | default: break; |
0 | 238 | } |
239 | } | |
240 | ||
241 | ||
242 | ||
243 | /** | |
244 | * @brief Handle web ui websocket events. | |
245 | */ | |
246 | void websock_callback(uint8_t num, WEBSOCKET_TYPE_t type, char* msg, uint64_t len) | |
247 | { | |
248 | switch(type) { | |
249 | case WEBSOCKET_CONNECT: | |
250 | ESP_LOGI(TAG,"Websocket client %i connected!",num); | |
251 | break; | |
252 | ||
253 | case WEBSOCKET_DISCONNECT_EXTERNAL: | |
254 | ESP_LOGI(TAG,"Websocket client %i sent a disconnect message",num); | |
255 | break; | |
256 | ||
257 | case WEBSOCKET_DISCONNECT_INTERNAL: | |
258 | ESP_LOGI(TAG,"Websocket client %i was disconnected",num); | |
259 | break; | |
260 | ||
261 | case WEBSOCKET_DISCONNECT_ERROR: | |
262 | ESP_LOGI(TAG,"Websocket client %i was disconnected due to an error",num); | |
263 | break; | |
264 | ||
265 | case WEBSOCKET_TEXT: | |
266 | ESP_LOGI(TAG,"Websocket client %i sent text message of size %i:\n%s",num,(uint32_t)len,msg); | |
267 | dump_buf(msg, len); | |
268 | break; | |
269 | ||
270 | case WEBSOCKET_BIN: | |
271 | ESP_LOGI(TAG,"Websocket client %i sent bin message of size %i:\n",num,(uint32_t)len); | |
272 | dump_buf(msg, len); | |
273 | break; | |
274 | ||
275 | case WEBSOCKET_PING: | |
276 | ESP_LOGI(TAG,"client %i pinged us with message of size %i:\n%s",num,(uint32_t)len,msg); | |
277 | break; | |
278 | ||
279 | case WEBSOCKET_PONG: | |
280 | ESP_LOGI(TAG,"client %i responded to the ping",num); | |
281 | break; | |
282 | } | |
283 | } | |
284 | ||
285 | ||
286 | ||
287 | void dump_buf(char *buf, uint16_t buflen) | |
288 | { | |
289 | int i = 0, l = 1; | |
290 | ||
291 | printf("request length %d\n00: ", buflen); | |
292 | for (;;) { | |
293 | if (i >= buflen) | |
294 | break; | |
295 | if ((buf[i] < ' ') || (buf[i] > 126)) { | |
296 | if (buf[i] == '\n') { | |
297 | printf("\\n\n%02d: ", l); | |
298 | l++; | |
299 | } else if (buf[i] == '\r') { | |
300 | printf("\\r"); | |
301 | } else { | |
302 | printf("\\%02x", buf[i]); | |
303 | } | |
304 | } else { | |
305 | printf("%c", buf[i]); | |
306 | } | |
307 | i++; | |
308 | } | |
309 | printf("\n"); | |
310 | } | |
311 | ||
312 | ||
313 | ||
314 | /** | |
315 | * @brief Serve any client. | |
316 | * @param http_client_sock The socket on which the client is connected. | |
317 | */ | |
318 | static void http_serve(struct netconn *conn) | |
319 | { | |
320 | char ipstr[IPADDR_STRLEN_MAX]; | |
321 | struct netbuf *inbuf; | |
322 | static char *buf; | |
323 | static uint16_t buflen; | |
324 | static err_t err; | |
325 | char url[128], *p, *mod_since = NULL; | |
326 | ip_addr_t remote_addr; | |
327 | uint16_t remote_port; | |
328 | ||
329 | if (netconn_getaddr(conn, &remote_addr, &remote_port, 0) == ERR_OK) { | |
330 | strcpy(ipstr, ip4addr_ntoa(ip_2_ip4(&remote_addr))); | |
331 | } else { | |
332 | ipstr[0] = '\0'; | |
333 | } | |
334 | ||
335 | netconn_set_recvtimeout(conn,1000); // allow a connection timeout of 1 second | |
336 | err = netconn_recv(conn, &inbuf); | |
337 | ||
338 | if (err != ERR_OK) { | |
339 | if (err != ERR_TIMEOUT) { // Ignore timeout | |
340 | ESP_LOGI(TAG,"%s error %d on read", ipstr, err); | |
341 | } | |
342 | netconn_close(conn); | |
343 | netconn_delete(conn); | |
344 | netbuf_delete(inbuf); | |
345 | return; | |
346 | } | |
347 | ||
348 | netbuf_data(inbuf, (void**)&buf, &buflen); | |
349 | ||
350 | if (buf) { | |
351 | /* | |
352 | * Build url string from the data buffer. | |
353 | * It looks like: GET /app/localization.js HTTP/1.1 | |
354 | */ | |
355 | for (int i = 0; i < 10; i++) { | |
356 | if (buf[i] == ' ') { | |
357 | i++; | |
358 | for (int j = i; j < 128; j++) { | |
359 | url[j-i] = buf[j]; | |
360 | if (url[j-i] == ' ') { | |
361 | url[j-i] = '\0'; | |
362 | break; | |
363 | } | |
364 | } | |
365 | break; | |
366 | } | |
367 | } | |
368 | ||
369 | if (strstr(buf, "GET /logfiles.json")) { | |
370 | char temp[64]; | |
371 | FILE *dest = fopen("/spiffs/w/logfiles.json", "w"); | |
372 | if (dest) { | |
373 | fprintf(dest, "{\"Dir\":[{\"Folder\":\"/log\",\"Files\":["); | |
374 | DIR *dir = opendir("/sdcard/w/log"); | |
375 | if (dir) { | |
376 | struct dirent* de = readdir(dir); | |
377 | struct stat st; | |
378 | bool comma = false; | |
379 | while (de) { | |
380 | sprintf(temp, "/sdcard/w/log/%s", de->d_name); | |
381 | if (stat(temp, &st) == ESP_OK) { | |
382 | fprintf(dest, "%s{\"File\":\"%s\",\"Size\":%ld,\"Date\":%ld}", (comma)?",":"", de->d_name, st.st_size, st.st_mtime); | |
383 | comma = true; | |
384 | } | |
385 | de = readdir(dir); | |
386 | vTaskDelay(5 / portTICK_PERIOD_MS); | |
387 | } | |
388 | closedir(dir); | |
389 | } | |
390 | fprintf(dest, "]}]}"); | |
391 | fclose(dest); | |
392 | } | |
393 | http_sendfile(conn, "/logfiles.json", NULL, ipstr); | |
394 | netconn_close(conn); | |
395 | netconn_delete(conn); | |
396 | netbuf_delete(inbuf); | |
397 | unlink("/spiffs/w/logfiles.json"); | |
398 | return; | |
399 | } | |
400 | ||
401 | // http requests | |
402 | if (! strstr(buf,"Upgrade: websocket")) { // Not websocket | |
403 | p = strstr(buf, "If-Modified-Since:"); // May be cached | |
404 | if (p) { | |
405 | size_t mod_len = strcspn(p, " "); | |
406 | p += (int)(mod_len + 1); | |
407 | mod_len = strcspn(p, "\r\n"); | |
408 | mod_since = malloc(mod_len + 2); | |
409 | memcpy(mod_since, p, mod_len); | |
410 | mod_since[mod_len] = '\0'; | |
411 | } | |
412 | http_sendfile(conn, url, mod_since, ipstr); | |
413 | if (mod_since) | |
414 | free(mod_since); | |
415 | mod_since = NULL; | |
416 | netconn_close(conn); | |
417 | netconn_delete(conn); | |
418 | netbuf_delete(inbuf); | |
419 | return; | |
420 | } | |
421 | ||
422 | // websocket for noVNC. | |
423 | if ((strstr(buf,"GET /websockify ") && strstr(buf,"Upgrade: websocket"))) { | |
424 | int nr = ws_server_add_client_protocol(conn, buf, buflen, "/websockify", "binary", websockify_callback); | |
425 | ESP_LOGI(TAG, "%s new websocket on /websockify client: %d", ipstr, nr); | |
426 | netbuf_delete(inbuf); | |
427 | VncStartWS(nr); | |
428 | return; | |
429 | } | |
430 | ||
431 | // websocket for web UI. | |
432 | if ((strstr(buf,"GET /ws ") && strstr(buf,"Upgrade: websocket"))) { | |
433 | int nr = ws_server_add_client_protocol(conn, buf, buflen, "/ws", "binary", websock_callback); | |
434 | ESP_LOGI(TAG, "%s new websocket on /ws client: %d", ipstr, nr); | |
435 | netbuf_delete(inbuf); | |
436 | TFTstartWS(nr); | |
437 | // Startup something? Init webscreen? | |
438 | return; | |
439 | } | |
440 | ||
441 | dump_buf(buf, buflen); | |
442 | ||
443 | if (strstr(buf, "GET /")) { | |
444 | ESP_LOGI(TAG, "%s request: %s", ipstr, buf); | |
445 | http_error(conn, 404, "Not found", "Not found"); | |
446 | } else { | |
447 | http_error(conn, 405, "Invalid method", "Invalid method"); | |
448 | } | |
449 | } | |
450 | ||
451 | netconn_close(conn); | |
452 | netconn_delete(conn); | |
453 | netbuf_delete(inbuf); | |
454 | } | |
455 | ||
456 | ||
457 | ||
458 | /** | |
459 | * @brief Handles clients when they first connect. passes to a queue | |
460 | */ | |
461 | static void task_HTTPserver(void* pvParameters) | |
462 | { | |
463 | struct netconn *conn, *newconn; | |
464 | static err_t err; | |
465 | ||
466 | ESP_LOGI(TAG, "Starting http server_task"); | |
467 | client_queue = xQueueCreate(client_queue_size,sizeof(struct netconn*)); | |
468 | ||
469 | conn = netconn_new(NETCONN_TCP); | |
470 | netconn_bind(conn,NULL,80); | |
471 | netconn_listen(conn); | |
472 | ||
473 | do { | |
474 | err = netconn_accept(conn, &newconn); | |
475 | if (err == ERR_OK) { | |
476 | if (xQueueSendToBack(client_queue,&newconn,portMAX_DELAY) != pdTRUE) { | |
477 | ESP_LOGE(TAG, "xQueueSendToBack() queue full"); | |
478 | }; | |
479 | } | |
480 | vTaskDelay(5 / portTICK_PERIOD_MS); | |
481 | } while (err == ERR_OK); | |
482 | ||
483 | ESP_LOGE(TAG, "Stopping http server_task"); | |
484 | netconn_close(conn); | |
485 | netconn_delete(conn); | |
486 | vTaskDelete(NULL); | |
487 | } | |
488 | ||
489 | ||
490 | ||
491 | /** | |
492 | * @brief Receives clients from queue and handle them. | |
493 | */ | |
494 | static void task_Queue(void* pvParameters) | |
495 | { | |
496 | struct netconn* conn; | |
497 | ||
498 | ESP_LOGI(TAG, "Starting Queue task"); | |
499 | for(;;) { | |
500 | xQueueReceive(client_queue, &conn, portMAX_DELAY); | |
501 | if (!conn) | |
502 | continue; | |
503 | http_serve(conn); | |
504 | vTaskDelay(2 / portTICK_PERIOD_MS); | |
505 | } | |
506 | ESP_LOGE(TAG, "Stopping Queue task"); | |
507 | vTaskDelete(NULL); | |
508 | } | |
509 | ||
510 | ||
511 | ||
512 | void start_http_websocket(void) | |
513 | { | |
514 | ESP_LOGI(TAG, "Starting HTTP/Websocket server"); | |
515 | ||
516 | ws_server_start(); | |
517 | xTaskCreate(&task_HTTPserver, "HTTPserver", 3000, NULL, 9, &xTaskHTTP); | |
518 | xTaskCreate(&task_Queue, "Queue", 4000, NULL, 6, &xTaskQueue); | |
519 | } | |
520 |