-
Notifications
You must be signed in to change notification settings - Fork 7.5k
/
HTTPClient.cpp
1645 lines (1401 loc) · 41.6 KB
/
HTTPClient.cpp
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
#include <HardwareSerial.h>
/**
* HTTPClient.cpp
*
* Created on: 02.11.2015
*
* Copyright (c) 2015 Markus Sattler. All rights reserved.
* This file is part of the HTTPClient for Arduino.
* Port to ESP32 by Evandro Luis Copercini (2017),
* changed fingerprints to CA verification.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Adapted in October 2018
*/
#include <Arduino.h>
#include <esp32-hal-log.h>
#include <StreamString.h>
#include <base64.h>
#include "HTTPClient.h"
/// Cookie jar support
#include <time.h>
#ifdef HTTPCLIENT_1_1_COMPATIBLE
class TransportTraits {
public:
virtual ~TransportTraits() {}
virtual std::unique_ptr<NetworkClient> create() {
return std::unique_ptr<NetworkClient>(new NetworkClient());
}
virtual bool verify(NetworkClient &client, const char *host) {
return true;
}
};
#ifndef HTTPCLIENT_NOSECURE
class TLSTraits : public TransportTraits {
public:
TLSTraits(const char *CAcert, const char *clicert = nullptr, const char *clikey = nullptr) : _cacert(CAcert), _clicert(clicert), _clikey(clikey) {}
std::unique_ptr<NetworkClient> create() override {
return std::unique_ptr<NetworkClient>(new NetworkClientSecure());
}
bool verify(NetworkClient &client, const char *host) override {
NetworkClientSecure &wcs = static_cast<NetworkClientSecure &>(client);
if (_cacert == nullptr) {
wcs.setInsecure();
} else {
wcs.setCACert(_cacert);
wcs.setCertificate(_clicert);
wcs.setPrivateKey(_clikey);
}
return true;
}
protected:
const char *_cacert;
const char *_clicert;
const char *_clikey;
};
#endif // HTTPCLIENT_NOSECURE
#endif // HTTPCLIENT_1_1_COMPATIBLE
/**
* constructor
*/
HTTPClient::HTTPClient() {}
/**
* destructor
*/
HTTPClient::~HTTPClient() {
if (_client) {
_client->stop();
}
if (_currentHeaders) {
delete[] _currentHeaders;
}
if (_tcpDeprecated) {
_tcpDeprecated.reset(nullptr);
}
if (_transportTraits) {
_transportTraits.reset(nullptr);
}
}
void HTTPClient::clear() {
_returnCode = 0;
_size = -1;
_headers = "";
}
/**
* parsing the url for all needed parameters
* @param client Client&
* @param url String
* @param https bool
* @return success bool
*/
bool HTTPClient::begin(NetworkClient &client, String url) {
#ifdef HTTPCLIENT_1_1_COMPATIBLE
if (_tcpDeprecated) {
log_d("mix up of new and deprecated api");
_canReuse = false;
end();
}
#endif
_client = &client;
// check for : (http: or https:)
int index = url.indexOf(':');
if (index < 0) {
log_d("failed to parse protocol");
return false;
}
String protocol = url.substring(0, index);
if (protocol != "http" && protocol != "https") {
log_d("unknown protocol '%s'", protocol.c_str());
return false;
}
_port = (protocol == "https" ? 443 : 80);
_secure = (protocol == "https");
#ifdef HTTPCLIENT_NOSECURE
if (_secure) {
return false;
}
#endif // HTTPCLIENT_NOSECURE
return beginInternal(url, protocol.c_str());
}
/**
* directly supply all needed parameters
* @param client Client&
* @param host String
* @param port uint16_t
* @param uri String
* @param https bool
* @return success bool
*/
bool HTTPClient::begin(NetworkClient &client, String host, uint16_t port, String uri, bool https) {
#ifdef HTTPCLIENT_1_1_COMPATIBLE
if (_tcpDeprecated) {
log_d("mix up of new and deprecated api");
_canReuse = false;
end();
}
#endif
_client = &client;
clear();
_host = host;
_port = port;
_uri = uri;
_protocol = (https ? "https" : "http");
_secure = https;
#ifdef HTTPCLIENT_NOSECURE
return _secure ? false : true;
#else
return true;
#endif // HTTPCLIENT_NOSECURE
}
#ifdef HTTPCLIENT_1_1_COMPATIBLE
#ifndef HTTPCLIENT_NOSECURE
bool HTTPClient::begin(String url, const char *CAcert) {
if (_client && !_tcpDeprecated) {
log_d("mix up of new and deprecated api");
_canReuse = false;
end();
}
clear();
_port = 443;
if (!beginInternal(url, "https")) {
return false;
}
_secure = true;
_transportTraits = TransportTraitsPtr(new TLSTraits(CAcert));
if (!_transportTraits) {
log_e("could not create transport traits");
return false;
}
return true;
}
#endif // HTTPCLIENT_NOSECURE
/**
* parsing the url for all needed parameters
* @param url String
*/
bool HTTPClient::begin(String url) {
if (_client && !_tcpDeprecated) {
log_d("mix up of new and deprecated api");
_canReuse = false;
end();
}
clear();
_port = 80;
if (!beginInternal(url, "http")) {
#ifdef HTTPCLIENT_NOSECURE
return false;
#else
return begin(url, (const char *)NULL);
#endif // HTTPCLIENT_NOSECURE
}
_transportTraits = TransportTraitsPtr(new TransportTraits());
if (!_transportTraits) {
log_e("could not create transport traits");
return false;
}
return true;
}
#endif // HTTPCLIENT_1_1_COMPATIBLE
bool HTTPClient::beginInternal(String url, const char *expectedProtocol) {
log_v("url: %s", url.c_str());
// check for : (http: or https:
int index = url.indexOf(':');
if (index < 0) {
log_e("failed to parse protocol");
return false;
}
_protocol = url.substring(0, index);
if (_protocol != expectedProtocol) {
log_d("unexpected protocol: %s, expected %s", _protocol.c_str(), expectedProtocol);
return false;
}
url.remove(0, (index + 3)); // remove http:// or https://
index = url.indexOf('/');
if (index == -1) {
index = url.length();
url += '/';
}
String host = url.substring(0, index);
url.remove(0, index); // remove host part
// get Authorization
index = host.indexOf('@');
if (index >= 0) {
// auth info
String auth = host.substring(0, index);
host.remove(0, index + 1); // remove auth part including @
_base64Authorization = base64::encode(auth);
}
// get port
index = host.indexOf(':');
String the_host;
if (index >= 0) {
the_host = host.substring(0, index); // hostname
host.remove(0, (index + 1)); // remove hostname + :
_port = host.toInt(); // get port
} else {
the_host = host;
}
if (_host != the_host && connected()) {
log_d("switching host from '%s' to '%s'. disconnecting first", _host.c_str(), the_host.c_str());
_canReuse = false;
disconnect(true);
}
_host = the_host;
_uri = url;
log_d("protocol: %s, host: %s port: %d url: %s", _protocol.c_str(), _host.c_str(), _port, _uri.c_str());
return true;
}
#ifdef HTTPCLIENT_1_1_COMPATIBLE
bool HTTPClient::begin(String host, uint16_t port, String uri) {
if (_client && !_tcpDeprecated) {
log_d("mix up of new and deprecated api");
_canReuse = false;
end();
}
clear();
_host = host;
_port = port;
_uri = uri;
_transportTraits = TransportTraitsPtr(new TransportTraits());
log_d("host: %s port: %d uri: %s", host.c_str(), port, uri.c_str());
return true;
}
#ifndef HTTPCLIENT_NOSECURE
bool HTTPClient::begin(String host, uint16_t port, String uri, const char *CAcert) {
if (_client && !_tcpDeprecated) {
log_d("mix up of new and deprecated api");
_canReuse = false;
end();
}
clear();
_host = host;
_port = port;
_uri = uri;
if (strlen(CAcert) == 0) {
return false;
}
_secure = true;
_transportTraits = TransportTraitsPtr(new TLSTraits(CAcert));
return true;
}
bool HTTPClient::begin(String host, uint16_t port, String uri, const char *CAcert, const char *cli_cert, const char *cli_key) {
if (_client && !_tcpDeprecated) {
log_d("mix up of new and deprecated api");
_canReuse = false;
end();
}
clear();
_host = host;
_port = port;
_uri = uri;
if (strlen(CAcert) == 0) {
return false;
}
_secure = true;
_transportTraits = TransportTraitsPtr(new TLSTraits(CAcert, cli_cert, cli_key));
return true;
}
#endif // HTTPCLIENT_NOSECURE
#endif // HTTPCLIENT_1_1_COMPATIBLE
/**
* end
* called after the payload is handled
*/
void HTTPClient::end(void) {
disconnect(false);
clear();
}
/**
* disconnect
* close the TCP socket
*/
void HTTPClient::disconnect(bool preserveClient) {
if (connected()) {
if (_client->available() > 0) {
log_d("still data in buffer (%d), clean up.\n", _client->available());
_client->clear();
}
if (_reuse && _canReuse) {
log_d("tcp keep open for reuse");
} else {
log_d("tcp stop");
_client->stop();
if (!preserveClient) {
_client = nullptr;
#ifdef HTTPCLIENT_1_1_COMPATIBLE
if (_tcpDeprecated) {
_transportTraits.reset(nullptr);
_tcpDeprecated.reset(nullptr);
}
#endif
}
}
} else {
log_d("tcp is closed\n");
}
}
/**
* connected
* @return connected status
*/
bool HTTPClient::connected() {
if (_client) {
return ((_client->available() > 0) || _client->connected());
}
return false;
}
/**
* try to reuse the connection to the server
* keep-alive
* @param reuse bool
*/
void HTTPClient::setReuse(bool reuse) {
_reuse = reuse;
}
/**
* set User Agent
* @param userAgent const char *
*/
void HTTPClient::setUserAgent(const String &userAgent) {
_userAgent = userAgent;
}
/**
* set Accept Encoding Header
* @param acceptEncoding const char *
*/
void HTTPClient::setAcceptEncoding(const String &acceptEncoding) {
_acceptEncoding = acceptEncoding;
}
/**
* set the Authorizatio for the http request
* @param user const char *
* @param password const char *
*/
void HTTPClient::setAuthorization(const char *user, const char *password) {
if (user && password) {
String auth = user;
auth += ":";
auth += password;
_base64Authorization = base64::encode(auth);
}
}
/**
* set the Authorizatio for the http request
* @param auth const char * base64
*/
void HTTPClient::setAuthorization(const char *auth) {
if (auth) {
_base64Authorization = auth;
}
}
/**
* set the Authorization type for the http request
* @param authType const char *
*/
void HTTPClient::setAuthorizationType(const char *authType) {
if (authType) {
_authorizationType = authType;
}
}
/**
* set the timeout (ms) for establishing a connection to the server
* @param connectTimeout int32_t
*/
void HTTPClient::setConnectTimeout(int32_t connectTimeout) {
_connectTimeout = connectTimeout;
}
/**
* set the timeout for the TCP connection
* @param timeout unsigned int
*/
void HTTPClient::setTimeout(uint16_t timeout) {
_tcpTimeout = timeout;
if (connected()) {
_client->setTimeout(timeout);
}
}
/**
* use HTTP1.0
* @param use
*/
void HTTPClient::useHTTP10(bool useHTTP10) {
_useHTTP10 = useHTTP10;
_reuse = !useHTTP10;
}
/**
* send a GET request
* @return http code
*/
int HTTPClient::GET() {
return sendRequest("GET");
}
/**
* sends a post request to the server
* @param payload uint8_t *
* @param size size_t
* @return http code
*/
int HTTPClient::POST(uint8_t *payload, size_t size) {
return sendRequest("POST", payload, size);
}
int HTTPClient::POST(String payload) {
return POST((uint8_t *)payload.c_str(), payload.length());
}
/**
* sends a patch request to the server
* @param payload uint8_t *
* @param size size_t
* @return http code
*/
int HTTPClient::PATCH(uint8_t *payload, size_t size) {
return sendRequest("PATCH", payload, size);
}
int HTTPClient::PATCH(String payload) {
return PATCH((uint8_t *)payload.c_str(), payload.length());
}
/**
* sends a put request to the server
* @param payload uint8_t *
* @param size size_t
* @return http code
*/
int HTTPClient::PUT(uint8_t *payload, size_t size) {
return sendRequest("PUT", payload, size);
}
int HTTPClient::PUT(String payload) {
return PUT((uint8_t *)payload.c_str(), payload.length());
}
/**
* sendRequest
* @param type const char * "GET", "POST", ....
* @param payload String data for the message body
* @return
*/
int HTTPClient::sendRequest(const char *type, String payload) {
return sendRequest(type, (uint8_t *)payload.c_str(), payload.length());
}
/**
* sendRequest
* @param type const char * "GET", "POST", ....
* @param payload uint8_t * data for the message body if null not send
* @param size size_t size for the message body if 0 not send
* @return -1 if no info or > 0 when Content-Length is set by server
*/
int HTTPClient::sendRequest(const char *type, uint8_t *payload, size_t size) {
int code;
bool redirect = false;
uint16_t redirectCount = 0;
do {
// wipe out any existing headers from previous request
for (size_t i = 0; i < _headerKeysCount; i++) {
if (_currentHeaders[i].value.length() > 0) {
_currentHeaders[i].value.clear();
}
}
log_d("request type: '%s' redirCount: %d\n", type, redirectCount);
// connect to server
if (!connect()) {
return returnError(HTTPC_ERROR_CONNECTION_REFUSED);
}
if (payload && size > 0) {
addHeader(F("Content-Length"), String(size));
}
// add cookies to header, if present
String cookie_string;
if (generateCookieString(&cookie_string)) {
addHeader("Cookie", cookie_string);
}
// send Header
if (!sendHeader(type)) {
return returnError(HTTPC_ERROR_SEND_HEADER_FAILED);
}
// send Payload if needed
if (payload && size > 0) {
size_t sent_bytes = 0;
while (sent_bytes < size) {
size_t sent = _client->write(&payload[sent_bytes], size - sent_bytes);
if (sent == 0) {
log_w("Failed to send chunk! Lets wait a bit");
delay(100);
sent = _client->write(&payload[sent_bytes], size - sent_bytes);
if (sent == 0) {
log_e("Failed to send chunk!");
break;
}
}
sent_bytes += sent;
}
if (sent_bytes != size) {
return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED);
}
}
code = handleHeaderResponse();
log_d("sendRequest code=%d\n", code);
// Handle redirections as stated in RFC document:
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
//
// Implementing HTTP_CODE_FOUND as redirection with GET method,
// to follow most of existing user agent implementations.
//
redirect = false;
if (_followRedirects != HTTPC_DISABLE_FOLLOW_REDIRECTS && redirectCount < _redirectLimit && _location.length() > 0) {
switch (code) {
// redirecting using the same method
case HTTP_CODE_MOVED_PERMANENTLY:
case HTTP_CODE_TEMPORARY_REDIRECT:
{
if (
// allow to force redirections on other methods
// (the RFC require user to accept the redirection)
_followRedirects == HTTPC_FORCE_FOLLOW_REDIRECTS ||
// allow GET and HEAD methods without force
!strcmp(type, "GET") || !strcmp(type, "HEAD")) {
redirectCount += 1;
log_d("following redirect (the same method): '%s' redirCount: %d\n", _location.c_str(), redirectCount);
if (!setURL(_location)) {
log_d("failed setting URL for redirection\n");
// no redirection
break;
}
// redirect using the same request method and payload, different URL
redirect = true;
}
break;
}
// redirecting with method dropped to GET or HEAD
// note: it does not need `HTTPC_FORCE_FOLLOW_REDIRECTS` for any method
case HTTP_CODE_FOUND:
case HTTP_CODE_SEE_OTHER:
{
redirectCount += 1;
log_d("following redirect (dropped to GET/HEAD): '%s' redirCount: %d\n", _location.c_str(), redirectCount);
if (!setURL(_location)) {
log_d("failed setting URL for redirection\n");
// no redirection
break;
}
// redirect after changing method to GET/HEAD and dropping payload
type = "GET";
payload = nullptr;
size = 0;
redirect = true;
break;
}
default: break;
}
}
} while (redirect);
// handle Server Response (Header)
return returnError(code);
}
/**
* sendRequest
* @param type const char * "GET", "POST", ....
* @param stream Stream * data stream for the message body
* @param size size_t size for the message body if 0 not Content-Length is send
* @return -1 if no info or > 0 when Content-Length is set by server
*/
int HTTPClient::sendRequest(const char *type, Stream *stream, size_t size) {
if (!stream) {
return returnError(HTTPC_ERROR_NO_STREAM);
}
// connect to server
if (!connect()) {
return returnError(HTTPC_ERROR_CONNECTION_REFUSED);
}
if (size > 0) {
addHeader("Content-Length", String(size));
}
// add cookies to header, if present
String cookie_string;
if (generateCookieString(&cookie_string)) {
addHeader("Cookie", cookie_string);
}
// send Header
if (!sendHeader(type)) {
return returnError(HTTPC_ERROR_SEND_HEADER_FAILED);
}
int buff_size = HTTP_TCP_TX_BUFFER_SIZE;
int len = size;
int bytesWritten = 0;
if (len == 0) {
len = -1;
}
// if possible create smaller buffer then HTTP_TCP_TX_BUFFER_SIZE
if ((len > 0) && (len < buff_size)) {
buff_size = len;
}
// create buffer for read
uint8_t *buff = (uint8_t *)malloc(buff_size);
if (buff) {
// read all data from stream and send it to server
while (connected() && (stream->available() > -1) && (len > 0 || len == -1)) {
// get available data size
int sizeAvailable = stream->available();
if (sizeAvailable) {
int readBytes = sizeAvailable;
// read only the asked bytes
if (len > 0 && readBytes > len) {
readBytes = len;
}
// not read more the buffer can handle
if (readBytes > buff_size) {
readBytes = buff_size;
}
// read data
int bytesRead = stream->readBytes(buff, readBytes);
// write it to Stream
int bytesWrite = _client->write((const uint8_t *)buff, bytesRead);
bytesWritten += bytesWrite;
// are all Bytes a written to stream ?
if (bytesWrite != bytesRead) {
log_d("short write, asked for %d but got %d retry...", bytesRead, bytesWrite);
// check for write error
if (_client->getWriteError()) {
log_d("stream write error %d", _client->getWriteError());
//reset write error for retry
_client->clearWriteError();
}
// some time for the stream
delay(1);
int leftBytes = (readBytes - bytesWrite);
// retry to send the missed bytes
bytesWrite = _client->write((const uint8_t *)(buff + bytesWrite), leftBytes);
bytesWritten += bytesWrite;
if (bytesWrite != leftBytes) {
// failed again
log_d("short write, asked for %d but got %d failed.", leftBytes, bytesWrite);
free(buff);
return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED);
}
}
// check for write error
if (_client->getWriteError()) {
log_d("stream write error %d", _client->getWriteError());
free(buff);
return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED);
}
// count bytes to read left
if (len > 0) {
len -= readBytes;
}
delay(0);
} else {
delay(1);
}
}
free(buff);
if (size && (int)size != bytesWritten) {
log_d("Stream payload bytesWritten %d and size %d mismatch!.", bytesWritten, size);
log_d("ERROR SEND PAYLOAD FAILED!");
return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED);
} else {
log_d("Stream payload written: %d", bytesWritten);
}
} else {
log_d("too less ram! need %d", buff_size);
return returnError(HTTPC_ERROR_TOO_LESS_RAM);
}
// handle Server Response (Header)
return returnError(handleHeaderResponse());
}
/**
* size of message body / payload
* @return -1 if no info or > 0 when Content-Length is set by server
*/
int HTTPClient::getSize(void) {
return _size;
}
/**
* returns the stream of the tcp connection
* @return NetworkClient
*/
NetworkClient &HTTPClient::getStream(void) {
if (connected()) {
return *_client;
}
log_w("getStream: not connected");
static NetworkClient empty;
return empty;
}
/**
* returns a pointer to the stream of the tcp connection
* @return NetworkClient*
*/
NetworkClient *HTTPClient::getStreamPtr(void) {
if (connected()) {
return _client;
}
log_w("getStreamPtr: not connected");
return nullptr;
}
/**
* write all message body / payload to Stream
* @param stream Stream *
* @return bytes written ( negative values are error codes )
*/
int HTTPClient::writeToStream(Stream *stream) {
if (!stream) {
return returnError(HTTPC_ERROR_NO_STREAM);
}
if (!connected()) {
return returnError(HTTPC_ERROR_NOT_CONNECTED);
}
// get length of document (is -1 when Server sends no Content-Length header)
int len = _size;
int ret = 0;
if (_transferEncoding == HTTPC_TE_IDENTITY) {
ret = writeToStreamDataBlock(stream, len);
// have we an error?
if (ret < 0) {
return returnError(ret);
}
} else if (_transferEncoding == HTTPC_TE_CHUNKED) {
int size = 0;
while (1) {
if (!connected()) {
return returnError(HTTPC_ERROR_CONNECTION_LOST);
}
String chunkHeader = _client->readStringUntil('\n');
if (chunkHeader.length() <= 0) {
return returnError(HTTPC_ERROR_READ_TIMEOUT);
}
chunkHeader.trim(); // remove \r
// read size of chunk
len = (uint32_t)strtol((const char *)chunkHeader.c_str(), NULL, 16);
size += len;
log_v(" read chunk len: %d", len);
// data left?
if (len > 0) {
int r = writeToStreamDataBlock(stream, len);
if (r < 0) {
// error in writeToStreamDataBlock
return returnError(r);
}
ret += r;
} else {
// if no length Header use global chunk size
if (_size <= 0) {
_size = size;
}
// check if we have write all data out
if (ret != _size) {
return returnError(HTTPC_ERROR_STREAM_WRITE);
}
break;
}
// read trailing \r\n at the end of the chunk
char buf[2];
auto trailing_seq_len = _client->readBytes((uint8_t *)buf, 2);
if (trailing_seq_len != 2 || buf[0] != '\r' || buf[1] != '\n') {
return returnError(HTTPC_ERROR_READ_TIMEOUT);
}
delay(0);
}
} else {
return returnError(HTTPC_ERROR_ENCODING);
}
// end();
disconnect(true);
return ret;
}
/**
* return all payload as String (may need lot of ram or trigger out of memory!)
* @return String
*/
String HTTPClient::getString(void) {
// _size can be -1 when Server sends no Content-Length header
if (_size > 0 || _size == -1) {
StreamString sstring;
// try to reserve needed memory (noop if _size == -1)
if (sstring.reserve((_size + 1))) {
writeToStream(&sstring);
return sstring;
} else {
log_d("not enough memory to reserve a string! need: %d", (_size + 1));
}
}
return "";
}
/**
* converts error code to String
* @param error int
* @return String
*/
String HTTPClient::errorToString(int error) {
switch (error) {
case HTTPC_ERROR_CONNECTION_REFUSED: return F("connection refused");
case HTTPC_ERROR_SEND_HEADER_FAILED: return F("send header failed");
case HTTPC_ERROR_SEND_PAYLOAD_FAILED: return F("send payload failed");
case HTTPC_ERROR_NOT_CONNECTED: return F("not connected");
case HTTPC_ERROR_CONNECTION_LOST: return F("connection lost");
case HTTPC_ERROR_NO_STREAM: return F("no stream");
case HTTPC_ERROR_NO_HTTP_SERVER: return F("no HTTP server");
case HTTPC_ERROR_TOO_LESS_RAM: return F("too less ram");
case HTTPC_ERROR_ENCODING: return F("Transfer-Encoding not supported");
case HTTPC_ERROR_STREAM_WRITE: return F("Stream write error");
case HTTPC_ERROR_READ_TIMEOUT: return F("read Timeout");
default: return String();
}
}
/**
* adds Header to the request
* @param name
* @param value
* @param first
*/
void HTTPClient::addHeader(const String &name, const String &value, bool first, bool replace) {
// not allow set of Header handled by code
if (!name.equalsIgnoreCase(F("Connection")) && !name.equalsIgnoreCase(F("User-Agent")) && !name.equalsIgnoreCase(F("Accept-Encoding"))
&& !name.equalsIgnoreCase(F("Host")) && !(name.equalsIgnoreCase(F("Authorization")) && _base64Authorization.length())) {
String headerLine = name;
headerLine += ": ";
if (replace) {