forked from igrr/esp32-http-server
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttp_server.c
1569 lines (1391 loc) · 47.1 KB
/
http_server.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Simple HTTP server for ESP32.
* Copyright Ivan Grokhotkov, 2017.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include MBEDTLS_CONFIG_FILE
#include <http_server.h>
#include <stdlib.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "rom/queue.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "lwip/sys.h"
#include "lwip/netdb.h"
#include "lwip/api.h"
#include "http_parser.h"
#include "mbedtls/platform.h"
#include "mbedtls/net_sockets.h"
#include "mbedtls/esp_debug.h"
#include "mbedtls/ssl.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/error.h"
#include "mbedtls/certs.h"
#include "mbedtls/ssl_ticket.h"
#if defined(MBEDTLS_SSL_CACHE_C)
#include "mbedtls/ssl_cache.h"
#endif
#define HTTP_PARSE_BUF_MAX_LEN 256
#define MBEDTLS_EXAMPLE_RECV_BUF_LEN 1024
typedef enum {
HTTP_PARSING_URI, //!< HTTP_PARSING_URI
HTTP_PARSING_HEADER_NAME, //!< HTTP_PARSING_HEADER_NAME
HTTP_PARSING_HEADER_VALUE, //!< HTTP_PARSING_HEADER_VALUE
HTTP_PARSING_REQUEST_BODY, //!< HTTP_PARSING_REQUEST_BODY
HTTP_REQUEST_DONE, //!< HTTP_REQUEST_DONE
HTTP_COLLECTING_RESPONSE_HEADERS,//!< HTTP_COLLECTING_RESPONSE_HEADERS
HTTP_SENDING_RESPONSE_BODY, //!< HTTP_SENDING_RESPONSE_BODY
HTTP_DONE, //!< HTTP_DONE
} http_state_t;
typedef struct http_header_t {
char* name;
char* value;
SLIST_ENTRY(http_header_t) list_entry;
} http_header_t;
typedef SLIST_HEAD(http_header_list_t, http_header_t) http_header_list_t;
typedef struct {
http_handler_fn_t cb;
void* ctx;
} http_form_handler_t;
typedef struct http_handler_t{
char* uri_pattern;
int method;
int events;
http_handler_fn_t cb;
void* ctx;
SLIST_ENTRY(http_handler_t) list_entry;
} http_handler_t;
struct http_context_ {
http_server_t server;
http_state_t state;
int event;
char* uri;
char parse_buffer[HTTP_PARSE_BUF_MAX_LEN];
char* request_header_tmp;
http_parser parser;
http_header_list_t request_headers;
int response_code;
http_header_list_t response_headers;
size_t expected_response_size;
size_t accumulated_response_size;
http_handler_t* handler;
const char* data_ptr;
size_t data_size;
http_header_list_t request_args;
#ifdef HTTPS_SERVER
mbedtls_ssl_context *ssl_conn;
mbedtls_net_context *client_fd;
#else
struct netconn *conn;
#endif
};
struct http_server_context_ {
int port;
TaskHandle_t task;
EventGroupHandle_t start_done;
err_t server_task_err;
SLIST_HEAD(, http_handler_t) handlers;
_lock_t handlers_lock;
struct http_context_ connection_context;
#ifdef HTTPS_SERVER
mbedtls_net_context *listen_fd;
mbedtls_entropy_context *entropy;
mbedtls_ctr_drbg_context *ctr_drbg;
mbedtls_ssl_config *conf;
mbedtls_x509_crt *srvcerts;
mbedtls_pk_context *pkey;
mbedtls_ssl_cache_context *cache;
mbedtls_ssl_ticket_context *ticket_ctx;
#else
struct netconn* server_conn;
#endif
};
/** Return true if \p ret is a status code indicating that there is an
* operation in progress on an SSL connection, and false if it indicates
* success or a fatal error.
*
* The possible operations in progress are:
*
* - A read, when the SSL input buffer does not contain a full message.
* - A write, when the SSL output buffer contains some data that has not
* been sent over the network yet.
* - An asynchronous callback that has not completed yet. */
static int mbedtls_status_is_ssl_in_progress( int ret )
{
return( ret == MBEDTLS_ERR_SSL_WANT_READ ||
ret == MBEDTLS_ERR_SSL_WANT_WRITE );
}
static const char* http_response_code_to_str(int code);
static esp_err_t add_keyval_pair(http_header_list_t *list, const char* name, const char* val);
static const char* TAG = "http_server";
esp_err_t http_register_handler(http_server_t server,
const char* uri_pattern, int method,
int events, http_handler_fn_t callback, void* callback_arg)
{
http_handler_t* new_handler = (http_handler_t*) calloc(1, sizeof(*new_handler));
if (new_handler == NULL) {
return ESP_ERR_NO_MEM;
}
new_handler->uri_pattern = strdup(uri_pattern);
new_handler->cb = callback;
new_handler->ctx = callback_arg;
new_handler->method = method;
new_handler->events = events;
_lock_acquire(&server->handlers_lock);
/* FIXME: Handlers will be checked in the reverse order */
SLIST_INSERT_HEAD(&server->handlers, new_handler, list_entry);
_lock_release(&server->handlers_lock);
return ESP_OK;
}
static http_handler_t* http_find_handler(http_server_t server, const char* uri, int method)
{
http_handler_t* it;
_lock_acquire(&server->handlers_lock);
SLIST_FOREACH(it, &server->handlers, list_entry) {
if (strcasecmp(uri, it->uri_pattern) == 0
&& method == it->method) {
break;
}
}
_lock_release(&server->handlers_lock);
return it;
}
static int append_parse_buffer(http_context_t ctx, const char* at, size_t length)
{
if (length > HTTP_PARSE_BUF_MAX_LEN - strlen(ctx->parse_buffer) - 1) {
ESP_LOGW(TAG, "%s: len=%d > %d", __func__, length, HTTP_PARSE_BUF_MAX_LEN - strlen(ctx->parse_buffer) - 1);
return 1;
}
strncat(ctx->parse_buffer, at, length);
ESP_LOGV(TAG, "%s: len=%d, '%s'", __func__, length, ctx->parse_buffer);
return 0;
}
static void clear_parse_buffer(http_context_t ctx)
{
#ifdef NDEBUG
ctx->parse_buffer[0] = 0;
#else
memset(ctx->parse_buffer, 0, sizeof(ctx->parse_buffer));
#endif
}
static void header_name_done(http_context_t ctx)
{
ctx->request_header_tmp = strdup(ctx->parse_buffer);
clear_parse_buffer(ctx);
}
static void header_value_done(http_context_t ctx)
{
const char* value = ctx->parse_buffer;
const char* name = ctx->request_header_tmp;
ESP_LOGI(TAG, "Got header: '%s': '%s'", name, value);
add_keyval_pair(&ctx->request_headers, name, value);
free(ctx->request_header_tmp);
ctx->request_header_tmp = NULL;
clear_parse_buffer(ctx);
}
static int http_url_cb(http_parser* parser, const char *at, size_t length)
{
ESP_LOGD(TAG, "Called %s", __func__);
http_context_t ctx = (http_context_t) parser->data;
return append_parse_buffer(ctx, at, length);
}
static bool invoke_handler(http_context_t ctx, int event)
{
if (ctx->handler && (ctx->handler->events & event) != 0) {
ctx->event = event;
(*ctx->handler->cb)(ctx, ctx->handler->ctx);
ctx->event = 0;
return true;
}
return false;
}
static int http_headers_done_cb(http_parser* parser)
{
ESP_LOGD(TAG, "Called %s", __func__);
http_context_t ctx = (http_context_t) parser->data;
if (ctx->state == HTTP_PARSING_HEADER_VALUE) {
header_value_done(ctx);
}
invoke_handler(ctx, HTTP_HANDLE_HEADERS);
ctx->state = HTTP_PARSING_REQUEST_BODY;
return 0;
}
static int parse_hex_digit(char hex)
{
switch (hex) {
case '0' ... '9': return hex - '0';
case 'a' ... 'f': return hex - 'a' + 0xa;
case 'A' ... 'F': return hex - 'A' + 0xA;
default:
return -1;
}
}
static char* urldecode(const char* str, size_t len)
{
ESP_LOGV(TAG, "urldecode: '%.*s'", len, str);
const char* end = str + len;
char* out = calloc(1, len + 1);
char* p_out = out;
while (str != end) {
char c = *str++;
if (c != '%') {
*p_out = c;
} else {
if (str + 2 > end) {
/* Unexpected end of string */
return NULL;
}
int high = parse_hex_digit(*str++);
int low = parse_hex_digit(*str++);
if (high == -1 || low == -1) {
/* Unexpected character */
return NULL;
}
*p_out = high * 16 + low;
}
++p_out;
}
*p_out = 0;
ESP_LOGV(TAG, "urldecode result: '%s'", out);
return out;
}
static void parse_urlencoded_args(http_context_t ctx, const char* str, size_t len)
{
const char* end = str + len;
const int READING_KEY = 1;
const int READING_VAL = 2;
int state = READING_KEY;
const char* token_start = str;
char* key = NULL;
char* value = NULL;
for (const char* pos = str; pos < end; ++pos) {
char c = *pos;
if (c == '=' && state == READING_KEY) {
key = urldecode(token_start, pos - token_start);
state = READING_VAL;
token_start = pos + 1;
} else if (c == '&' && state == READING_VAL) {
value = urldecode(token_start, pos - token_start);
state = READING_KEY;
token_start = pos + 1;
ESP_LOGI(TAG, "Got request argument, '%s': '%s'", key, value);
add_keyval_pair(&ctx->request_args, key, value);
free(key);
key = NULL;
free(value);
value = NULL;
}
}
if (state == READING_VAL) {
value = urldecode(token_start, end - token_start);
ESP_LOGI(TAG, "Got request argument, '%s': '%s'", key, value);
add_keyval_pair(&ctx->request_args, key, value);
free(key);
key = NULL;
free(value);
value = NULL;
}
}
static void uri_done(http_context_t ctx)
{
/* Check for query argument string */
char* query_str = strchr(ctx->parse_buffer, '?');
if (query_str != NULL) {
*query_str = 0;
++query_str;
}
ctx->uri = strdup(ctx->parse_buffer);
ESP_LOGI(TAG, "Got URI: '%s'", ctx->uri);
if (query_str) {
parse_urlencoded_args(ctx, query_str, strlen(query_str));
}
ctx->handler = http_find_handler(ctx->server, ctx->uri, (int) ctx->parser.method);
invoke_handler(ctx, HTTP_HANDLE_URI);
clear_parse_buffer(ctx);
}
static int http_header_name_cb(http_parser* parser, const char *at, size_t length)
{
ESP_LOGD(TAG, "Called %s", __func__);
http_context_t ctx = (http_context_t) parser->data;
if (ctx->state == HTTP_PARSING_URI) {
uri_done(ctx);
ctx->state = HTTP_PARSING_HEADER_NAME;
} else if (ctx->state == HTTP_PARSING_HEADER_VALUE) {
header_value_done(ctx);
ctx->state = HTTP_PARSING_HEADER_NAME;
}
return append_parse_buffer(ctx, at, length);
}
static int http_header_value_cb(http_parser* parser, const char *at, size_t length)
{
ESP_LOGD(TAG, "Called %s", __func__);
http_context_t ctx = (http_context_t) parser->data;
if (ctx->state == HTTP_PARSING_HEADER_NAME) {
header_name_done(ctx);
ctx->state = HTTP_PARSING_HEADER_VALUE;
}
return append_parse_buffer(ctx, at, length);
}
static int http_body_cb(http_parser* parser, const char *at, size_t length)
{
ESP_LOGD(TAG, "Called %s", __func__);
http_context_t ctx = (http_context_t) parser->data;
ctx->data_ptr = at;
ctx->data_size = length;
invoke_handler(ctx, HTTP_HANDLE_DATA);
ctx->data_ptr = NULL;
ctx->data_size = 0;
return 0;
}
static int http_message_done_cb(http_parser* parser)
{
ESP_LOGD(TAG, "Called %s", __func__);
http_context_t ctx = (http_context_t) parser->data;
ctx->state = HTTP_REQUEST_DONE;
return 0;
}
const char* http_request_get_header(http_context_t ctx, const char* name)
{
http_header_t* it;
SLIST_FOREACH(it, &ctx->request_headers, list_entry) {
if (strcasecmp(name, it->name) == 0) {
return it->value;
}
}
return NULL;
}
int http_request_get_event(http_context_t ctx)
{
return ctx->event;
}
const char* http_request_get_uri(http_context_t ctx)
{
return ctx->uri;
}
int http_request_get_method(http_context_t ctx)
{
return (int) ctx->parser.method;
}
const char* http_request_get_arg_value(http_context_t ctx, const char* name)
{
http_header_t* it;
SLIST_FOREACH(it, &ctx->request_args, list_entry) {
ESP_LOGI(TAG, "Key %s: %s", it->name, it->value);
if (strcasecmp(name, it->name) == 0) {
return it->value;
}
}
return NULL;
}
esp_err_t http_request_get_data(http_context_t ctx, const char** out_data_ptr, size_t* out_size)
{
if (ctx->event != HTTP_HANDLE_DATA) {
return ESP_ERR_INVALID_STATE;
}
*out_data_ptr = ctx->data_ptr;
*out_size = ctx->data_size;
return ESP_OK;
}
static void form_data_handler_cb(http_context_t http_ctx, void* ctx)
{
http_form_handler_t* form_ctx = (http_form_handler_t*) ctx;
int event = http_request_get_event(http_ctx);
if (event != HTTP_HANDLE_DATA) {
(*form_ctx->cb)(http_ctx, form_ctx->ctx);
} else {
const char* str;
size_t len;
http_request_get_data(http_ctx, &str, &len);
parse_urlencoded_args(http_ctx, str, len);
}
}
esp_err_t http_register_form_handler(http_server_t server, const char* uri_pattern, int method,
int events, http_handler_fn_t callback, void* callback_arg)
{
http_form_handler_t* inner_handler = calloc(1, sizeof(*inner_handler));
if (inner_handler == NULL) {
return ESP_ERR_NO_MEM;
}
inner_handler->cb = callback;
inner_handler->ctx = callback_arg;
esp_err_t res = http_register_handler(server, uri_pattern, method,
events | HTTP_HANDLE_DATA, &form_data_handler_cb, inner_handler);
if (res != ESP_OK) {
free(inner_handler);
}
return res;
}
#ifndef HTTPS_SERVER
static esp_err_t lwip_err_to_esp_err(err_t e)
{
switch (e) {
case ERR_OK: return ESP_OK;
case ERR_MEM: return ESP_ERR_NO_MEM;
case ERR_TIMEOUT: return ESP_ERR_TIMEOUT;
default:
return ESP_FAIL;
}
}
#endif
static void headers_list_clear(http_header_list_t* list)
{
http_header_t *it, *next;
SLIST_FOREACH_SAFE(it, list, list_entry, next) {
SLIST_REMOVE(list, it, http_header_t, list_entry);
free(it); /* frees memory allocated for header, name, and value */
}
}
static esp_err_t http_add_content_length_header(http_context_t http_ctx, size_t value)
{
char size_str[11];
itoa(value, size_str, 10);
return http_response_set_header(http_ctx, "Content-length", size_str);
}
static esp_err_t http_send_response_headers(http_context_t http_ctx)
{
assert(http_ctx->state == HTTP_COLLECTING_RESPONSE_HEADERS);
/* Calculate total size of all the headers, allocate a buffer */
size_t total_headers_size = 0;
/* response_code may be == 0, if we are sending headers for multipart
* response part. In this case, don't send the response code line.
*/
if (http_ctx->response_code > 0) {
total_headers_size += 16 /* HTTP/1.1, code, CRLF */
+ strlen(http_response_code_to_str(http_ctx->response_code));
}
http_header_t* it;
SLIST_FOREACH(it, &http_ctx->response_headers, list_entry) {
total_headers_size += strlen(it->name) + strlen(it->value) + 4 /* ": ", CRLF */;
}
total_headers_size += 3; /* Final CRLF, '\0' terminator */
char* headers_buf = calloc(1, total_headers_size);
if (headers_buf == NULL) {
return ESP_ERR_NO_MEM;
}
/* Write response */
size_t buf_size = total_headers_size;
char* buf_ptr = headers_buf;
int len = 0, actual_len = 0;
if (http_ctx->response_code > 0) {
len = snprintf(buf_ptr, buf_size, "HTTP/1.1 %d %s\r\n",
http_ctx->response_code, http_response_code_to_str(http_ctx->response_code));
assert(len < buf_size);
buf_size -= len;
buf_ptr += len;
}
/* Write response headers */
SLIST_FOREACH(it, &http_ctx->response_headers, list_entry) {
len = snprintf(buf_ptr, buf_size, "%s: %s\r\n", it->name, it->value);
assert(len < buf_size);
buf_size -= len;
buf_ptr += len;
}
/* Final CRLF */
len = snprintf(buf_ptr, buf_size, "\r\n");
assert(len < buf_size);
buf_size -= len;
buf_ptr += len;
headers_list_clear(&http_ctx->response_headers);
esp_err_t ret;
ESP_LOGV(TAG, "Writing response headers..." );
#ifdef HTTPS_SERVER
len = strlen(headers_buf);
ret = 0;
do
{
len = len - ret;
ret = mbedtls_ssl_write( http_ctx->ssl_conn, ((const unsigned char *)headers_buf + ret), len);
if( ret == MBEDTLS_ERR_NET_CONN_RESET )
{
ESP_LOGE(TAG, "ERROR: peer closed the connection\n\n" );
break;
}
if( ret < 0 && ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE )
{
ESP_LOGE(TAG, "ERROR: mbedtls_ssl_write returned %d\n\n", ret );
break;
}
if (ret > 0)
actual_len += ret;
}while( ret < 0 || ret < len );
#ifdef MBEDTLS_ERROR_C
if( ret < ERR_OK )
{
char *error_buf = malloc(sizeof(char)*ERROR_BUF_LENGTH);
mbedtls_strerror( ret, error_buf, sizeof(char)*ERROR_BUF_LENGTH );
ESP_LOGE(TAG, "Error during writing response: %d - %s\n\n", ret, error_buf );
free(error_buf);
}else
{
ret = ERR_OK;
}
#endif
#else
actual_len = strlen(headers_buf);
ret = netconn_write(http_ctx->conn, headers_buf, actual_len, NETCONN_COPY);
ret = lwip_err_to_esp_err(ret);
if (ret != ERR_OK)
ESP_LOGE(TAG, "netconn_write ret=%d", ret);
#endif
if (ret == ERR_OK)
ESP_LOGI(TAG, "%d bytes written:\n%s", actual_len, (char *)headers_buf);
free(headers_buf);
http_ctx->state = HTTP_SENDING_RESPONSE_BODY;
return ret;
}
/* Common function called by http_response_begin and http_response_begin_multipart */
static esp_err_t http_response_begin_common(http_context_t http_ctx, const char* content_type, size_t response_size)
{
esp_err_t err = http_response_set_header(http_ctx, "Content-type", content_type);
if (err != ESP_OK) {
return err;
}
http_ctx->expected_response_size = response_size;
http_ctx->accumulated_response_size = 0;
if (response_size != HTTP_RESPONSE_SIZE_UNKNOWN) {
err = http_add_content_length_header(http_ctx, response_size);
if (err != ESP_OK) {
return err;
}
}
return ESP_OK;
}
esp_err_t http_response_begin(http_context_t http_ctx, int code, const char* content_type, size_t response_size)
{
if (http_ctx->state != HTTP_COLLECTING_RESPONSE_HEADERS) {
return ESP_ERR_INVALID_STATE;
}
http_ctx->response_code = code;
return http_response_begin_common(http_ctx, content_type, response_size);
}
esp_err_t http_response_write(http_context_t http_ctx, const http_buffer_t* buffer)
{
size_t len;
esp_err_t ret;
if (http_ctx->state == HTTP_COLLECTING_RESPONSE_HEADERS) {
ret = http_send_response_headers(http_ctx);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "ERROR: in http_send_response_headers function...");
return ret;
}
}
len = buffer->size ? buffer->size : strlen((const char*) buffer->data);
ESP_LOGV(TAG, "Writing to client:" );
#ifdef HTTPS_SERVER
ret = 0;
do
{
len = len - ret;
ret = mbedtls_ssl_write( http_ctx->ssl_conn, (buffer->data + ret), len);
if( ret == MBEDTLS_ERR_NET_CONN_RESET )
{
ESP_LOGE(TAG, "ERROR: peer closed the connection\n\n" );
break;
}
if( ret < 0 && ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE )
{
ESP_LOGE(TAG, "ERROR: mbedtls_ssl_write returned %d\n\n", ret );
break;
}
if (ret > 0)
http_ctx->accumulated_response_size += ret;
}while( ret < 0 || ret < len );
#ifdef MBEDTLS_ERROR_C
if( ret < ERR_OK )
{
char *error_buf = malloc(sizeof(char)*ERROR_BUF_LENGTH);
mbedtls_strerror( ret, error_buf, sizeof(char)*ERROR_BUF_LENGTH );
ESP_LOGE(TAG, "Error during writing response: %d - %s", ret, error_buf );
free(error_buf);
}else{
ret = ERR_OK;
}
#endif
#else
const int flag = buffer->data_is_persistent ? NETCONN_NOCOPY : NETCONN_COPY;
len = buffer->size ? buffer->size : strlen((const char*) buffer->data);
ret = netconn_write(http_ctx->conn, buffer->data, len, flag);
ret = lwip_err_to_esp_err(ret);
if (ret != ERR_OK)
{
ESP_LOGE(TAG, "netconn_write ret=%d", ret);
}else{
http_ctx->accumulated_response_size += len;
}
#endif
ESP_LOGD(TAG, "%d bytes written:%s", http_ctx->accumulated_response_size, (char *)buffer->data);
return ret;
}
esp_err_t http_response_end(http_context_t http_ctx)
{
size_t expected = http_ctx->expected_response_size;
size_t actual = http_ctx->accumulated_response_size;
if (expected != HTTP_RESPONSE_SIZE_UNKNOWN && expected != actual) {
ESP_LOGW(TAG, "Expected response size: %d, actual: %d", expected, actual);
}
http_ctx->state = HTTP_DONE;
return ESP_OK;
}
esp_err_t http_response_begin_multipart(http_context_t http_ctx, const char* content_type, size_t response_size)
{
if (http_ctx->state == HTTP_COLLECTING_RESPONSE_HEADERS) {
http_send_response_headers(http_ctx);
http_ctx->response_code = 0;
}
http_ctx->state = HTTP_COLLECTING_RESPONSE_HEADERS;
return http_response_begin_common(http_ctx, content_type, response_size);
}
esp_err_t http_response_end_multipart(http_context_t http_ctx, const char* boundary)
{
size_t expected = http_ctx->expected_response_size;
size_t actual = http_ctx->accumulated_response_size;
if (expected != HTTP_RESPONSE_SIZE_UNKNOWN && expected != actual) {
ESP_LOGW(TAG, "Expected response size: %d, actual: %d", expected, actual);
}
/* reset expected_response_size so that http_response_end doesn't complain */
http_ctx->expected_response_size = HTTP_RESPONSE_SIZE_UNKNOWN;
const http_buffer_t buf = { .data = boundary };
esp_err_t ret = http_response_write(http_ctx, &buf);
http_ctx->state = HTTP_COLLECTING_RESPONSE_HEADERS;
return ret;
}
static esp_err_t add_keyval_pair(http_header_list_t *list, const char* name, const char* val)
{
size_t name_len = strlen(name) + 1;
size_t val_len = strlen(val) + 1;
/* Allocate memory for the structure, name, and value, in one go */
size_t buf_len = sizeof(http_header_t) + name_len + val_len;
char* buf = (char*) calloc(1, buf_len);
if (buf == NULL) {
return ESP_ERR_NO_MEM;
}
http_header_t* new_header = (http_header_t*) buf;
new_header->name = buf + sizeof(http_header_t);
new_header->value = new_header->name + name_len;
strcpy(new_header->name, name);
strcpy(new_header->value, val);
SLIST_INSERT_HEAD(list, new_header, list_entry);
return ESP_OK;
}
esp_err_t http_response_set_header(http_context_t http_ctx, const char* name, const char* val)
{
return add_keyval_pair(&http_ctx->response_headers, name, val);
}
static void http_send_not_found_response(http_context_t http_ctx)
{
ESP_LOGD(TAG, "Called %s", __func__);
http_response_begin(http_ctx, 404, "text/plain", HTTP_RESPONSE_SIZE_UNKNOWN);
const http_buffer_t buf = {
.data = "Not found",
.data_is_persistent = true
};
ESP_LOGD(TAG, "Calling http_response_write function...");
http_response_write(http_ctx, &buf);
ESP_LOGD(TAG, "Calling http_response_end function...");
http_response_end(http_ctx);
}
static const char* http_response_code_to_str(int code)
{
switch (code) {
case 200: return "OK";
case 204: return "No Content";
case 301: return "Moved Permanently";
case 302: return "Found";
case 400: return "Bad Request";
case 404: return "Not Found";
case 405: return "Method Not Allowed";
case 500: return "Internal Server Error";
default: return "";
}
}
static int http_handle_connection(http_server_t server, void *arg_conn)
{
char *buf;
/* Single threaded server, one context only */
http_context_t ctx = &server->connection_context;
/* Initialize context */
ctx->state = HTTP_PARSING_URI;
#ifdef HTTPS_SERVER
#else
struct netbuf *inbuf = NULL;
int err = ERR_OK;
ctx->conn = (struct netconn *)arg_conn;
#endif
http_parser_init(&ctx->parser, HTTP_REQUEST);
ctx->parser.data = ctx;
ctx->server = server;
const http_parser_settings parser_settings = {
.on_url = &http_url_cb,
.on_headers_complete = &http_headers_done_cb,
.on_header_field = &http_header_name_cb,
.on_header_value = &http_header_value_cb,
.on_body = &http_body_cb,
.on_message_complete = &http_message_done_cb
};
#ifdef HTTPS_SERVER
int ret;
char *larger_buf;
size_t len = 0;
size_t parsed_bytes = 0;
/*
* 6. Read the HTTP Request
*/
ret = 0;
buf = malloc(sizeof(char)*MBEDTLS_EXAMPLE_RECV_BUF_LEN);
while (ctx->state != HTTP_REQUEST_DONE) {
ESP_LOGV(TAG, "Reading from client..." );
do
{
int terminated = 0;
len = sizeof(char)*MBEDTLS_EXAMPLE_RECV_BUF_LEN - 1;
memset( buf, 0, sizeof(char)*MBEDTLS_EXAMPLE_RECV_BUF_LEN);
ret = mbedtls_ssl_read( server->connection_context.ssl_conn, (unsigned char*)buf, len );
if( mbedtls_status_is_ssl_in_progress( ret ) )
{
continue;
}
if( ret <= 0 )
{
switch( ret )
{
case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
ESP_LOGW(TAG, "Error: connection was closed gracefully" );
ret = MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY;
goto close_notify;
case 0:
case MBEDTLS_ERR_NET_CONN_RESET:
ESP_LOGW(TAG, "Error: connection was reset by peer" );
ret = MBEDTLS_ERR_NET_CONN_RESET;
break;
default:
ESP_LOGW(TAG, "Error: mbedtls_ssl_read returned -0x%x\n", -ret );
break;
}
}
if( mbedtls_ssl_get_bytes_avail( server->connection_context.ssl_conn ) == 0 )
{
len = ret;
buf[len] = '\0';
ESP_LOGI(TAG, "%d bytes read: \n%s", len, (char *) buf );
}
else
{
size_t extra_len, ori_len;
ori_len = ret;
extra_len = (size_t) mbedtls_ssl_get_bytes_avail( server->connection_context.ssl_conn );
larger_buf = mbedtls_calloc( 1, ori_len + extra_len + 1 );
if( larger_buf == NULL )
{
ESP_LOGE(TAG, "Failed to allocate larger_buf");
len = 0;
break;
}
memset( larger_buf, 0, ori_len + extra_len );
memcpy( larger_buf, buf, ori_len );
free(buf);
/* This read should never fail and get the whole cached data */
ret = mbedtls_ssl_read( server->connection_context.ssl_conn, (unsigned char*)larger_buf + ori_len, extra_len );
if( ret != extra_len ||
mbedtls_ssl_get_bytes_avail( server->connection_context.ssl_conn ) != 0 )
{
ESP_LOGE(TAG, "Failed on cached data");
ret = 1;
len = 0;
break;
}
larger_buf[ori_len + extra_len] = '\0';
/* End of message should be detected according to the syntax of the
* application protocol (eg HTTP), just use a dummy test here. */
buf = larger_buf;
len = ori_len + extra_len;
ESP_LOGI(TAG, "%d bytes read (%d + %d): \n%s", len,
ori_len, extra_len, (char *) buf );
}
ESP_LOGI(TAG, "Calling http_parser_execute...");
parsed_bytes = http_parser_execute(&ctx->parser, &parser_settings, (char *)buf, len);
//TODO: check content-length to properly terminate HTTP request
terminated = 1;
if( terminated )
{
break;
}
}
while( 1 );
if( len == 0 || ret <=0 ) //If output buffer length is 0 (indicating a error), finishes processing of this request
{
ESP_LOGW(TAG, "WARNING: len = %d, ret = %d", len, ret);
free(buf);
return ret;
}
}
ESP_LOGD(TAG, "Read looping returned: %d", parsed_bytes);
#else //HTPPS SERVER OFF
u16_t buflen = 0;
while (ctx->state != HTTP_REQUEST_DONE) {
err = netconn_recv(ctx->conn, &inbuf);
if (err != ERR_OK) {
break;
}
do
{
err = netbuf_data(inbuf, (void**) &buf, &buflen);
if (err != ERR_OK) {
break;
}
//FIXME: check content-length to properly terminate HTTP request
size_t parsed_bytes = http_parser_execute(&ctx->parser, &parser_settings, (char *)buf, buflen);
if (parsed_bytes < buflen) {
break;
}
} while(netbuf_next(inbuf) >= 0);
}
#endif
#ifdef HTTPS_SERVER
if (len > 0) {
ctx->state = HTTP_COLLECTING_RESPONSE_HEADERS;
if (ctx->handler == NULL) {
ESP_LOGD(TAG, "No registered Handler!");
http_send_not_found_response(ctx);
} else {
ESP_LOGD(TAG, "Registered Handler Found!");
invoke_handler(ctx, HTTP_HANDLE_RESPONSE);
}
}
#else
if (err == ERR_OK) {
ctx->state = HTTP_COLLECTING_RESPONSE_HEADERS;
if (ctx->handler == NULL) {
ESP_LOGD(TAG, "No registered Handler!");
http_send_not_found_response(ctx);
} else {
ESP_LOGD(TAG, "Registered Handler Found!");
invoke_handler(ctx, HTTP_HANDLE_RESPONSE);
}
}
#endif
headers_list_clear(&ctx->request_headers);
headers_list_clear(&ctx->request_args);
free(ctx->uri);
ctx->uri = NULL;
ctx->handler = NULL;
#ifdef HTTPS_SERVER