-
Notifications
You must be signed in to change notification settings - Fork 7k
/
esp_http_client.c
1767 lines (1589 loc) · 66.2 KB
/
esp_http_client.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
/*
* SPDX-FileCopyrightText: 2015-2023 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <string.h>
#include <inttypes.h>
#include "esp_log.h"
#include "esp_check.h"
#include "http_parser.h"
#include "http_header.h"
#include "esp_transport.h"
#include "esp_transport_tcp.h"
#include "http_utils.h"
#include "http_auth.h"
#include "sdkconfig.h"
#include "esp_http_client.h"
#include "errno.h"
#include "esp_random.h"
#ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS
#include "esp_transport_ssl.h"
#endif
ESP_EVENT_DEFINE_BASE(ESP_HTTP_CLIENT_EVENT);
static const char *TAG = "HTTP_CLIENT";
/**
* HTTP Buffer
*/
typedef struct {
char *data; /*!< The HTTP data received from the server */
int len; /*!< The HTTP data len received from the server */
char *raw_data; /*!< The HTTP data after decoding */
char *orig_raw_data;/*!< The Original pointer to HTTP data after decoding */
int raw_len; /*!< The HTTP data len after decoding */
char *output_ptr; /*!< The destination address of the data to be copied to after decoding */
} esp_http_buffer_t;
/**
* private HTTP Data structure
*/
typedef struct {
http_header_handle_t headers; /*!< http header */
esp_http_buffer_t *buffer; /*!< data buffer as linked list */
int status_code; /*!< status code (integer) */
int64_t content_length; /*!< data length */
int chunk_length; /*!< chunk length */
int data_offset; /*!< offset to http data (Skip header) */
int64_t data_process; /*!< data processed */
int method; /*!< http method */
bool is_chunked;
} esp_http_data_t;
typedef struct {
char *url;
char *scheme;
char *host;
int port;
char *username;
char *password;
char *path;
char *query;
char *cert_pem;
esp_http_client_method_t method;
esp_http_client_auth_type_t auth_type;
esp_http_client_transport_t transport_type;
int max_store_header_size;
} connection_info_t;
typedef enum {
HTTP_STATE_UNINIT = 0,
HTTP_STATE_INIT,
HTTP_STATE_CONNECTED,
HTTP_STATE_REQ_COMPLETE_HEADER,
HTTP_STATE_REQ_COMPLETE_DATA,
HTTP_STATE_RES_COMPLETE_HEADER,
HTTP_STATE_RES_ON_DATA_START,
HTTP_STATE_RES_COMPLETE_DATA,
HTTP_STATE_CLOSE
} esp_http_state_t;
/**
* HTTP client class
*/
struct esp_http_client {
int redirect_counter;
int max_redirection_count;
int max_authorization_retries;
int process_again;
struct http_parser *parser;
struct http_parser_settings *parser_settings;
esp_transport_list_handle_t transport_list;
esp_transport_handle_t transport;
esp_http_data_t *request;
esp_http_data_t *response;
void *user_data;
esp_http_auth_data_t *auth_data;
char *post_data;
char *location;
char *auth_header;
char *current_header_key;
char *current_header_value;
int post_len;
connection_info_t connection_info;
bool is_chunk_complete;
esp_http_state_t state;
http_event_handle_cb event_handler;
int timeout_ms;
int buffer_size_rx;
int buffer_size_tx;
bool disable_auto_redirect;
esp_http_client_event_t event;
int data_written_index;
int data_write_left;
bool first_line_prepared;
int header_index;
bool is_async;
esp_transport_keep_alive_t keep_alive_cfg;
struct ifreq *if_name;
unsigned cache_data_in_fetch_hdr: 1;
};
typedef struct esp_http_client esp_http_client_t;
static esp_err_t _clear_connection_info(esp_http_client_handle_t client);
/**
* Default settings
*/
#define DEFAULT_HTTP_PORT (80)
#define DEFAULT_HTTPS_PORT (443)
#define ASYNC_TRANS_CONNECT_FAIL -1
#define ASYNC_TRANS_CONNECTING 0
#define ASYNC_TRANS_CONNECT_PASS 1
static const char *DEFAULT_HTTP_USER_AGENT = "ESP32 HTTP Client/1.0";
static const char *DEFAULT_HTTP_PROTOCOL = "HTTP/1.1";
static const char *DEFAULT_HTTP_PATH = "/";
static const int DEFAULT_MAX_REDIRECT = 10;
static const int DEFAULT_MAX_AUTH_RETRIES = 10;
static const int DEFAULT_TIMEOUT_MS = 5000;
static const int DEFAULT_KEEP_ALIVE_IDLE = 5;
static const int DEFAULT_KEEP_ALIVE_INTERVAL= 5;
static const int DEFAULT_KEEP_ALIVE_COUNT= 3;
static const char *HTTP_METHOD_MAPPING[] = {
"GET",
"POST",
"PUT",
"PATCH",
"DELETE",
"HEAD",
"NOTIFY",
"SUBSCRIBE",
"UNSUBSCRIBE",
"OPTIONS",
"COPY",
"MOVE",
"LOCK",
"UNLOCK",
"PROPFIND",
"PROPPATCH",
"MKCOL"
};
static esp_err_t esp_http_client_request_send(esp_http_client_handle_t client, int write_len);
static esp_err_t esp_http_client_connect(esp_http_client_handle_t client);
static esp_err_t esp_http_client_send_post_data(esp_http_client_handle_t client);
static esp_err_t http_dispatch_event(esp_http_client_t *client, esp_http_client_event_id_t event_id, void *data, int len)
{
esp_http_client_event_t *event = &client->event;
if (client->event_handler) {
event->event_id = event_id;
event->user_data = client->user_data;
event->data = data;
event->data_len = len;
return client->event_handler(event);
}
return ESP_OK;
}
static void http_dispatch_event_to_event_loop(int32_t event_id, const void* event_data, size_t event_data_size)
{
esp_err_t err = esp_event_post(ESP_HTTP_CLIENT_EVENT, event_id, event_data, event_data_size, portMAX_DELAY);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to post https_ota event: %"PRId32", error: %s", event_id, esp_err_to_name(err));
}
}
static int http_on_message_begin(http_parser *parser)
{
esp_http_client_t *client = parser->data;
ESP_LOGD(TAG, "on_message_begin");
client->response->is_chunked = false;
client->is_chunk_complete = false;
return 0;
}
static int http_on_url(http_parser *parser, const char *at, size_t length)
{
ESP_LOGD(TAG, "http_on_url");
return 0;
}
static int http_on_status(http_parser *parser, const char *at, size_t length)
{
return 0;
}
static int http_on_header_event(esp_http_client_handle_t client)
{
if (client->current_header_key != NULL && client->current_header_value != NULL) {
ESP_LOGD(TAG, "HEADER=%s:%s", client->current_header_key, client->current_header_value);
client->event.header_key = client->current_header_key;
client->event.header_value = client->current_header_value;
http_dispatch_event(client, HTTP_EVENT_ON_HEADER, NULL, 0);
http_dispatch_event_to_event_loop(HTTP_EVENT_ON_HEADER, &client, sizeof(esp_http_client_handle_t));
free(client->current_header_key);
free(client->current_header_value);
client->current_header_key = NULL;
client->current_header_value = NULL;
}
return 0;
}
static int http_on_header_field(http_parser *parser, const char *at, size_t length)
{
esp_http_client_t *client = parser->data;
http_utils_append_string(&client->current_header_key, at, length);
return 0;
}
static int http_on_header_value(http_parser *parser, const char *at, size_t length)
{
esp_http_client_handle_t client = parser->data;
if (client->current_header_key == NULL) {
return 0;
}
if (strcasecmp(client->current_header_key, "Location") == 0) {
http_utils_append_string(&client->location, at, length);
} else if (strcasecmp(client->current_header_key, "Transfer-Encoding") == 0
&& memcmp(at, "chunked", length) == 0) {
client->response->is_chunked = true;
} else if (strcasecmp(client->current_header_key, "WWW-Authenticate") == 0) {
http_utils_append_string(&client->auth_header, at, length);
}
http_utils_append_string(&client->current_header_value, at, length);
http_on_header_event(client);
return 0;
}
static int http_on_headers_complete(http_parser *parser)
{
esp_http_client_handle_t client = parser->data;
http_on_header_event(client);
client->response->status_code = parser->status_code;
client->response->data_offset = parser->nread;
client->response->content_length = parser->content_length;
client->response->data_process = 0;
ESP_LOGD(TAG, "http_on_headers_complete, status=%d, offset=%d, nread=%" PRId32, parser->status_code, client->response->data_offset, parser->nread);
client->state = HTTP_STATE_RES_COMPLETE_HEADER;
if (client->connection_info.method == HTTP_METHOD_HEAD) {
/* In a HTTP_RESPONSE parser returning '1' from on_headers_complete will tell the
parser that it should not expect a body. This is used when receiving a response
to a HEAD request which may contain 'Content-Length' or 'Transfer-Encoding: chunked'
headers that indicate the presence of a body.*/
return 1;
}
return 0;
}
static int http_on_body(http_parser *parser, const char *at, size_t length)
{
esp_http_client_t *client = parser->data;
ESP_LOGD(TAG, "http_on_body %zu", length);
if (client->response->buffer->output_ptr) {
memcpy(client->response->buffer->output_ptr, (char *)at, length);
client->response->buffer->output_ptr += length;
} else {
/* Do not cache body when http_on_body is called from esp_http_client_perform */
if (client->state < HTTP_STATE_RES_ON_DATA_START && client->cache_data_in_fetch_hdr) {
ESP_LOGD(TAG, "Body received in fetch header state, %p, %zu", at, length);
esp_http_buffer_t *res_buffer = client->response->buffer;
assert(res_buffer->orig_raw_data == res_buffer->raw_data);
res_buffer->orig_raw_data = (char *)realloc(res_buffer->orig_raw_data, res_buffer->raw_len + length);
if (!res_buffer->orig_raw_data) {
ESP_LOGE(TAG, "Failed to allocate memory for storing decoded data");
return -1;
}
memcpy(res_buffer->orig_raw_data + res_buffer->raw_len, at, length);
res_buffer->raw_data = res_buffer->orig_raw_data;
}
}
client->response->data_process += length;
client->response->buffer->raw_len += length;
http_dispatch_event(client, HTTP_EVENT_ON_DATA, (void *)at, length);
esp_http_client_on_data_t evt_data = {};
evt_data.data_process = client->response->data_process;
evt_data.client = client;
http_dispatch_event_to_event_loop(HTTP_EVENT_ON_DATA, &evt_data, sizeof(esp_http_client_on_data_t));
return 0;
}
static int http_on_message_complete(http_parser *parser)
{
ESP_LOGD(TAG, "http_on_message_complete, parser=%p", parser);
esp_http_client_handle_t client = parser->data;
client->is_chunk_complete = true;
return 0;
}
static int http_on_chunk_complete(http_parser *parser)
{
ESP_LOGD(TAG, "http_on_chunk_complete");
return 0;
}
static int http_on_chunk_header(http_parser *parser)
{
esp_http_client_handle_t client = parser->data;
client->response->chunk_length = parser->content_length;
ESP_LOGD(TAG, "http_on_chunk_header, chunk_length");
return 0;
}
esp_err_t esp_http_client_set_header(esp_http_client_handle_t client, const char *key, const char *value)
{
return http_header_set(client->request->headers, key, value);
}
esp_err_t esp_http_client_get_header(esp_http_client_handle_t client, const char *key, char **value)
{
return http_header_get(client->request->headers, key, value);
}
esp_err_t esp_http_client_delete_header(esp_http_client_handle_t client, const char *key)
{
return http_header_delete(client->request->headers, key);
}
esp_err_t esp_http_client_get_username(esp_http_client_handle_t client, char **value)
{
if (client == NULL || value == NULL) {
ESP_LOGE(TAG, "client or value must not be NULL");
return ESP_ERR_INVALID_ARG;
}
*value = client->connection_info.username;
return ESP_OK;
}
esp_err_t esp_http_client_set_username(esp_http_client_handle_t client, const char *username)
{
if (client == NULL) {
ESP_LOGE(TAG, "client must not be NULL");
return ESP_ERR_INVALID_ARG;
}
if (client->connection_info.username != NULL) {
free(client->connection_info.username);
}
client->connection_info.username = username ? strdup(username) : NULL;
return ESP_OK;
}
esp_err_t esp_http_client_get_password(esp_http_client_handle_t client, char **value)
{
if (client == NULL || value == NULL) {
ESP_LOGE(TAG, "client or value must not be NULL");
return ESP_ERR_INVALID_ARG;
}
*value = client->connection_info.password;
return ESP_OK;
}
esp_err_t esp_http_client_cancel_request(esp_http_client_handle_t client)
{
if (client == NULL) {
ESP_LOGD(TAG, "Client handle is NULL");
return ESP_ERR_INVALID_ARG;
}
if (client->state < HTTP_STATE_CONNECTED) {
ESP_LOGD(TAG, "Invalid State: %d", client->state);
return ESP_ERR_INVALID_STATE;
}
if (esp_transport_close(client->transport) != 0) {
return ESP_FAIL;
}
esp_err_t err = esp_http_client_connect(client);
// esp_http_client_connect() will return ESP_ERR_HTTP_CONNECTING in case of non-blocking mode and if the connection has not been established.
if (err == ESP_OK || (client->is_async && err == ESP_ERR_HTTP_CONNECTING)) {
client->response->data_process = client->response->content_length;
return ESP_OK;
}
return ESP_FAIL;
}
esp_err_t esp_http_client_set_password(esp_http_client_handle_t client, const char *password)
{
if (client == NULL) {
ESP_LOGE(TAG, "client must not be NULL");
return ESP_ERR_INVALID_ARG;
}
if (client->connection_info.password != NULL) {
memset(client->connection_info.password, 0, strlen(client->connection_info.password));
free(client->connection_info.password);
}
client->connection_info.password = password ? strdup(password) : NULL;
return ESP_OK;
}
esp_err_t esp_http_client_set_authtype(esp_http_client_handle_t client, esp_http_client_auth_type_t auth_type)
{
if (client == NULL) {
ESP_LOGE(TAG, "client must not be NULL");
return ESP_ERR_INVALID_ARG;
}
client->connection_info.auth_type = auth_type;
return ESP_OK;
}
esp_err_t esp_http_client_get_user_data(esp_http_client_handle_t client, void **data)
{
if (NULL == client || NULL == data) {
ESP_LOGE(TAG, "client or data must not be NULL");
return ESP_ERR_INVALID_ARG;
}
*data = client->user_data;
return ESP_OK;
}
esp_err_t esp_http_client_set_user_data(esp_http_client_handle_t client, void *data)
{
if (NULL == client) {
ESP_LOGE(TAG, "client must not be NULL");
return ESP_ERR_INVALID_ARG;
}
client->user_data = data;
return ESP_OK;
}
static esp_err_t _set_config(esp_http_client_handle_t client, const esp_http_client_config_t *config)
{
esp_err_t ret = ESP_OK;
client->connection_info.method = config->method;
client->connection_info.port = config->port;
client->connection_info.auth_type = config->auth_type;
client->event_handler = config->event_handler;
client->timeout_ms = config->timeout_ms;
client->max_redirection_count = config->max_redirection_count;
client->max_authorization_retries = config->max_authorization_retries;
client->user_data = config->user_data;
client->buffer_size_rx = config->buffer_size;
client->buffer_size_tx = config->buffer_size_tx;
client->disable_auto_redirect = config->disable_auto_redirect;
if (config->buffer_size == 0) {
client->buffer_size_rx = DEFAULT_HTTP_BUF_SIZE;
}
if (config->buffer_size_tx == 0) {
client->buffer_size_tx = DEFAULT_HTTP_BUF_SIZE;
}
if (client->max_redirection_count == 0) {
client->max_redirection_count = DEFAULT_MAX_REDIRECT;
}
if (client->max_authorization_retries == 0) {
client->max_authorization_retries = DEFAULT_MAX_AUTH_RETRIES;
} else if (client->max_authorization_retries == -1) {
client->max_authorization_retries = 0;
}
if (config->path) {
client->connection_info.path = strdup(config->path);
} else {
client->connection_info.path = strdup(DEFAULT_HTTP_PATH);
}
ESP_RETURN_ON_FALSE(client->connection_info.path, ESP_ERR_NO_MEM, TAG, "Memory exhausted");
if (config->host) {
client->connection_info.host = strdup(config->host);
ESP_GOTO_ON_FALSE(client->connection_info.host, ESP_ERR_NO_MEM, error, TAG, "Memory exhausted");
}
if (config->query) {
client->connection_info.query = strdup(config->query);
ESP_GOTO_ON_FALSE(client->connection_info.query, ESP_ERR_NO_MEM, error, TAG, "Memory exhausted");
}
if (config->username) {
client->connection_info.username = strdup(config->username);
ESP_GOTO_ON_FALSE(client->connection_info.username, ESP_ERR_NO_MEM, error, TAG, "Memory exhausted");
}
if (config->password) {
client->connection_info.password = strdup(config->password);
ESP_GOTO_ON_FALSE(client->connection_info.password, ESP_ERR_NO_MEM, error, TAG, "Memory exhausted");
}
if (config->transport_type == HTTP_TRANSPORT_OVER_SSL) {
http_utils_assign_string(&client->connection_info.scheme, "https", -1);
if (client->connection_info.port == 0) {
client->connection_info.port = DEFAULT_HTTPS_PORT;
}
} else {
http_utils_assign_string(&client->connection_info.scheme, "http", -1);
if (client->connection_info.port == 0) {
client->connection_info.port = DEFAULT_HTTP_PORT;
}
}
if (client->timeout_ms == 0) {
client->timeout_ms = DEFAULT_TIMEOUT_MS;
}
if (config->is_async) {
client->is_async = true;
}
return ret;
error:
_clear_connection_info(client);
return ret;
}
static esp_err_t _clear_connection_info(esp_http_client_handle_t client)
{
free(client->connection_info.path);
free(client->connection_info.host);
free(client->connection_info.query);
free(client->connection_info.username);
if (client->connection_info.password) {
memset(client->connection_info.password, 0, strlen(client->connection_info.password));
free(client->connection_info.password);
}
free(client->connection_info.scheme);
free(client->connection_info.url);
memset(&client->connection_info, 0, sizeof(connection_info_t));
return ESP_OK;
}
static esp_err_t _clear_auth_data(esp_http_client_handle_t client)
{
if (client->auth_data == NULL) {
return ESP_FAIL;
}
free(client->auth_data->method);
free(client->auth_data->realm);
free(client->auth_data->algorithm);
free(client->auth_data->qop);
free(client->auth_data->nonce);
free(client->auth_data->opaque);
memset(client->auth_data, 0, sizeof(esp_http_auth_data_t));
return ESP_OK;
}
static esp_err_t esp_http_client_prepare(esp_http_client_handle_t client)
{
client->process_again = 0;
client->response->data_process = 0;
client->first_line_prepared = false;
/**
* Clear location field before making a new HTTP request. Location
* field should not be cleared in http_on_header* callbacks because
* callbacks can be invoked multiple times for same header, and
* hence can lead to data corruption.
*/
if (client->location != NULL) {
free(client->location);
client->location = NULL;
}
if (client->auth_header != NULL) {
free(client->auth_header);
client->auth_header = NULL;
}
http_parser_init(client->parser, HTTP_RESPONSE);
if (client->connection_info.username) {
char *auth_response = NULL;
if (client->connection_info.auth_type == HTTP_AUTH_TYPE_BASIC) {
auth_response = http_auth_basic(client->connection_info.username, client->connection_info.password);
#ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH
} else if (client->connection_info.auth_type == HTTP_AUTH_TYPE_DIGEST && client->auth_data) {
client->auth_data->uri = client->connection_info.path;
client->auth_data->cnonce = ((uint64_t)esp_random() << 32) + esp_random();
auth_response = http_auth_digest(client->connection_info.username, client->connection_info.password, client->auth_data);
client->auth_data->nc ++;
#endif
}
if (auth_response) {
ESP_LOGD(TAG, "auth_response=%s", auth_response);
esp_http_client_set_header(client, "Authorization", auth_response);
free(auth_response);
}
}
return ESP_OK;
}
static char *_get_host_header(char *host, int port)
{
int err = 0;
char *host_name;
if (port != DEFAULT_HTTP_PORT && port != DEFAULT_HTTPS_PORT) {
err = asprintf(&host_name, "%s:%d", host, port);
} else {
err = asprintf(&host_name, "%s", host);
}
if (err == -1) {
return NULL;
}
return host_name;
}
static bool init_common_tcp_transport(esp_http_client_handle_t client, const esp_http_client_config_t *config, esp_transport_handle_t transport)
{
if (config->keep_alive_enable == true) {
client->keep_alive_cfg.keep_alive_enable = true;
client->keep_alive_cfg.keep_alive_idle = (config->keep_alive_idle == 0) ? DEFAULT_KEEP_ALIVE_IDLE : config->keep_alive_idle;
client->keep_alive_cfg.keep_alive_interval = (config->keep_alive_interval == 0) ? DEFAULT_KEEP_ALIVE_INTERVAL : config->keep_alive_interval;
client->keep_alive_cfg.keep_alive_count = (config->keep_alive_count == 0) ? DEFAULT_KEEP_ALIVE_COUNT : config->keep_alive_count;
esp_transport_tcp_set_keep_alive(transport, &client->keep_alive_cfg);
}
if (config->if_name) {
client->if_name = calloc(1, sizeof(struct ifreq));
ESP_RETURN_ON_FALSE(client->if_name, false, TAG, "Memory exhausted");
memcpy(client->if_name, config->if_name, sizeof(struct ifreq));
esp_transport_tcp_set_interface_name(transport, client->if_name);
}
return true;
}
esp_http_client_handle_t esp_http_client_init(const esp_http_client_config_t *config)
{
esp_http_client_handle_t client;
esp_err_t ret = ESP_OK;
esp_transport_handle_t tcp = NULL;
char *host_name;
bool _success;
_success = (
(client = calloc(1, sizeof(esp_http_client_t))) &&
(client->parser = calloc(1, sizeof(struct http_parser))) &&
(client->parser_settings = calloc(1, sizeof(struct http_parser_settings))) &&
(client->auth_data = calloc(1, sizeof(esp_http_auth_data_t))) &&
(client->request = calloc(1, sizeof(esp_http_data_t))) &&
(client->request->headers = http_header_init()) &&
(client->request->buffer = calloc(1, sizeof(esp_http_buffer_t))) &&
(client->response = calloc(1, sizeof(esp_http_data_t))) &&
(client->response->headers = http_header_init()) &&
(client->response->buffer = calloc(1, sizeof(esp_http_buffer_t)))
);
if (!_success) {
ESP_LOGE(TAG, "Error allocate memory");
goto error;
}
_success = (
(client->transport_list = esp_transport_list_init()) &&
(tcp = esp_transport_tcp_init()) &&
(esp_transport_set_default_port(tcp, DEFAULT_HTTP_PORT) == ESP_OK) &&
(esp_transport_list_add(client->transport_list, tcp, "http") == ESP_OK)
);
if (!_success) {
ESP_LOGE(TAG, "Error initialize transport");
goto error;
}
ESP_GOTO_ON_FALSE(init_common_tcp_transport(client, config, tcp), ESP_FAIL, error, TAG, "Failed to set TCP config");
#ifdef CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS
esp_transport_handle_t ssl = NULL;
_success = (
(ssl = esp_transport_ssl_init()) &&
(esp_transport_set_default_port(ssl, DEFAULT_HTTPS_PORT) == ESP_OK) &&
(esp_transport_list_add(client->transport_list, ssl, "https") == ESP_OK)
);
if (!_success) {
ESP_LOGE(TAG, "Error initialize SSL Transport");
goto error;
}
ESP_GOTO_ON_FALSE(init_common_tcp_transport(client, config, ssl), ESP_FAIL, error, TAG, "Failed to set SSL config");
if (config->crt_bundle_attach != NULL) {
#ifdef CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
esp_transport_ssl_crt_bundle_attach(ssl, config->crt_bundle_attach);
#else //CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
ESP_LOGE(TAG, "use_crt_bundle configured but not enabled in menuconfig: Please enable MBEDTLS_CERTIFICATE_BUNDLE option");
#endif
} else if (config->use_global_ca_store == true) {
esp_transport_ssl_enable_global_ca_store(ssl);
} else if (config->cert_pem) {
if (!config->cert_len) {
esp_transport_ssl_set_cert_data(ssl, config->cert_pem, strlen(config->cert_pem));
} else {
esp_transport_ssl_set_cert_data_der(ssl, config->cert_pem, config->cert_len);
}
}
if (config->client_cert_pem) {
if (!config->client_cert_len) {
esp_transport_ssl_set_client_cert_data(ssl, config->client_cert_pem, strlen(config->client_cert_pem));
} else {
esp_transport_ssl_set_client_cert_data_der(ssl, config->client_cert_pem, config->client_cert_len);
}
}
#if CONFIG_ESP_TLS_USE_SECURE_ELEMENT
if (config->use_secure_element) {
esp_transport_ssl_use_secure_element(ssl);
}
#endif
#if CONFIG_ESP_TLS_USE_DS_PERIPHERAL
if (config->ds_data != NULL) {
esp_transport_ssl_set_ds_data(ssl, config->ds_data);
}
#endif
if (config->client_key_pem) {
if (!config->client_key_len) {
esp_transport_ssl_set_client_key_data(ssl, config->client_key_pem, strlen(config->client_key_pem));
} else {
esp_transport_ssl_set_client_key_data_der(ssl, config->client_key_pem, config->client_key_len);
}
}
#ifdef CONFIG_MBEDTLS_HARDWARE_ECDSA_SIGN
if (config->use_ecdsa_peripheral) {
esp_transport_ssl_set_client_key_ecdsa_peripheral(ssl, config->ecdsa_key_efuse_blk);
}
#endif
if (config->client_key_password && config->client_key_password_len > 0) {
esp_transport_ssl_set_client_key_password(ssl, config->client_key_password, config->client_key_password_len);
}
if (config->skip_cert_common_name_check) {
esp_transport_ssl_skip_common_name_check(ssl);
}
if (config->common_name) {
esp_transport_ssl_set_common_name(ssl, config->common_name);
}
#endif
if (_set_config(client, config) != ESP_OK) {
ESP_LOGE(TAG, "Error set configurations");
goto error;
}
_success = (
(client->request->buffer->data = malloc(client->buffer_size_tx)) &&
(client->response->buffer->data = malloc(client->buffer_size_rx))
);
if (!_success) {
ESP_LOGE(TAG, "Allocation failed");
goto error;
}
const char *user_agent = config->user_agent == NULL ? DEFAULT_HTTP_USER_AGENT : config->user_agent;
if (config->host != NULL && config->path != NULL) {
if (client->connection_info.host == NULL) {
ESP_LOGE(TAG, "invalid host");
goto error;
}
host_name = _get_host_header(client->connection_info.host, client->connection_info.port);
if (host_name == NULL) {
ESP_LOGE(TAG, "Failed to allocate memory for host header");
goto error;
}
_success = (
(esp_http_client_set_header(client, "User-Agent", user_agent) == ESP_OK) &&
(esp_http_client_set_header(client, "Host", host_name) == ESP_OK)
);
free(host_name);
if (!_success) {
ESP_LOGE(TAG, "Error while setting default configurations");
goto error;
}
} else if (config->url != NULL) {
if (esp_http_client_set_url(client, config->url) != ESP_OK) {
ESP_LOGE(TAG, "Failed to set URL");
goto error;
}
if (client->connection_info.host == NULL) {
ESP_LOGE(TAG, "invalid host");
goto error;
}
host_name = _get_host_header(client->connection_info.host, client->connection_info.port);
if (host_name == NULL) {
ESP_LOGE(TAG, "Failed to allocate memory for host header");
goto error;
}
_success = (
(esp_http_client_set_header(client, "User-Agent", user_agent) == ESP_OK) &&
(esp_http_client_set_header(client, "Host", host_name) == ESP_OK)
);
free(host_name);
if (!_success) {
ESP_LOGE(TAG, "Error while setting default configurations");
goto error;
}
} else {
ESP_LOGE(TAG, "config should have either URL or host & path");
goto error;
}
/* As default behavior, cache data received in fetch header state. This will be
* used in esp_http_client_read API only. For esp_http_perform we shall disable
* this as data will be processed by event handler */
client->cache_data_in_fetch_hdr = 1;
client->parser_settings->on_message_begin = http_on_message_begin;
client->parser_settings->on_url = http_on_url;
client->parser_settings->on_status = http_on_status;
client->parser_settings->on_header_field = http_on_header_field;
client->parser_settings->on_header_value = http_on_header_value;
client->parser_settings->on_headers_complete = http_on_headers_complete;
client->parser_settings->on_body = http_on_body;
client->parser_settings->on_message_complete = http_on_message_complete;
client->parser_settings->on_chunk_complete = http_on_chunk_complete;
client->parser_settings->on_chunk_header = http_on_chunk_header;
client->parser->data = client;
client->event.client = client;
client->state = HTTP_STATE_INIT;
if (ret == ESP_OK) {
return client;
}
error:
esp_http_client_cleanup(client);
return NULL;
}
static void esp_http_client_cached_buf_cleanup(esp_http_buffer_t *res_buffer)
{
/* Free cached data if any, that was received during fetch header stage */
if (res_buffer && res_buffer->orig_raw_data) {
free(res_buffer->orig_raw_data);
res_buffer->orig_raw_data = NULL;
res_buffer->raw_data = NULL;
res_buffer->raw_len = 0;
}
}
esp_err_t esp_http_client_cleanup(esp_http_client_handle_t client)
{
if (client == NULL) {
return ESP_FAIL;
}
esp_http_client_close(client);
if (client->transport_list) {
esp_transport_list_destroy(client->transport_list);
}
if (client->request) {
http_header_destroy(client->request->headers);
if (client->request->buffer) {
free(client->request->buffer->data);
}
free(client->request->buffer);
free(client->request);
}
if (client->response) {
http_header_destroy(client->response->headers);
if (client->response->buffer) {
free(client->response->buffer->data);
esp_http_client_cached_buf_cleanup(client->response->buffer);
}
free(client->response->buffer);
free(client->response);
}
if (client->if_name) {
free(client->if_name);
}
free(client->parser);
free(client->parser_settings);
_clear_connection_info(client);
_clear_auth_data(client);
free(client->auth_data);
free(client->current_header_key);
free(client->location);
free(client->auth_header);
free(client);
return ESP_OK;
}
esp_err_t esp_http_client_set_redirection(esp_http_client_handle_t client)
{
if (client == NULL) {
return ESP_ERR_INVALID_ARG;
}
if (client->location == NULL) {
return ESP_ERR_INVALID_ARG;
}
ESP_LOGD(TAG, "Redirect to %s", client->location);
esp_err_t err = esp_http_client_set_url(client, client->location);
if (err == ESP_OK) {
client->redirect_counter ++;
client->process_again = 1; // used only in the blocking mode (when esp_http_client_perform() is called)
}
return err;
}
static esp_err_t esp_http_check_response(esp_http_client_handle_t client)
{
if (client->response->status_code >= HttpStatus_Ok && client->response->status_code < HttpStatus_MultipleChoices) {
return ESP_OK;
}
if (client->redirect_counter >= client->max_redirection_count) {
ESP_LOGE(TAG, "Error, reach max_redirection_count count=%d", client->redirect_counter);
return ESP_ERR_HTTP_MAX_REDIRECT;
}
switch (client->response->status_code) {
case HttpStatus_MovedPermanently:
case HttpStatus_Found:
case HttpStatus_SeeOther:
case HttpStatus_TemporaryRedirect:
case HttpStatus_PermanentRedirect:
if (client->disable_auto_redirect) {
http_dispatch_event(client, HTTP_EVENT_REDIRECT, NULL, 0);
} else {
if (esp_http_client_set_redirection(client) != ESP_OK){
return ESP_FAIL;
};
}
esp_http_client_redirect_event_data_t evt_data = {
.status_code = client->response->status_code,
.client = client,
};
http_dispatch_event_to_event_loop(HTTP_EVENT_REDIRECT, &evt_data, sizeof(esp_http_client_redirect_event_data_t));
break;
case HttpStatus_Unauthorized:
esp_http_client_add_auth(client);
}
return ESP_OK;
}
esp_err_t esp_http_client_set_url(esp_http_client_handle_t client, const char *url)
{
esp_err_t ret = ESP_OK;
char *old_host = NULL;
struct http_parser_url purl;
int old_port;
if (client == NULL || url == NULL) {
ESP_LOGE(TAG, "client or url must not NULL");
return ESP_ERR_INVALID_ARG;
}
http_parser_url_init(&purl);
int parser_status = http_parser_parse_url(url, strlen(url), 0, &purl);
if (parser_status != 0) {
ESP_LOGE(TAG, "Error parse url %s", url);
return ESP_ERR_INVALID_ARG;
}
if (client->connection_info.host) {
old_host = strdup(client->connection_info.host);
}
old_port = client->connection_info.port;
if (purl.field_data[UF_HOST].len) {
http_utils_assign_string(&client->connection_info.host, url + purl.field_data[UF_HOST].off, purl.field_data[UF_HOST].len);
ESP_GOTO_ON_FALSE(client->connection_info.host, ESP_ERR_NO_MEM, error, TAG, "Memory exhausted");
}
// Close the connection if host was changed
if (old_host && client->connection_info.host
&& strcasecmp(old_host, (const void *)client->connection_info.host) != 0) {
ESP_LOGD(TAG, "New host assign = %s", client->connection_info.host);
if (esp_http_client_set_header(client, "Host", client->connection_info.host) != ESP_OK) {
free(old_host);
return ESP_ERR_NO_MEM;
}
/* Free cached data if any, as we are closing this connection */
esp_http_client_cached_buf_cleanup(client->response->buffer);
esp_http_client_close(client);