forked from me-no-dev/ESPAsyncWebServer
-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathWebRequest.cpp
More file actions
1526 lines (1408 loc) · 51.2 KB
/
WebRequest.cpp
File metadata and controls
1526 lines (1408 loc) · 51.2 KB
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-License-Identifier: LGPL-3.0-or-later
// Copyright 2016-2026 Hristo Gochkov, Mathieu Carbou, Emil Muratov, Will Miles
#include "ESPAsyncWebServer.h"
#include "WebAuthentication.h"
#include "WebResponseImpl.h"
#include "AsyncWebServerLogging.h"
#include <algorithm>
#include <cstring>
#include <memory>
#include <utility>
#include "./literals.h"
static inline bool isParamChar(char c) {
return ((c) && ((c) != '{') && ((c) != '[') && ((c) != '&') && ((c) != '='));
}
static void doNotDelete(AsyncWebServerRequest *) {}
using namespace asyncsrv;
enum {
PARSE_REQ_START = 0,
PARSE_REQ_HEADERS = 1,
PARSE_REQ_BODY = 2,
PARSE_REQ_END = 3,
PARSE_REQ_FAIL = 4
};
enum {
CHUNK_NONE = 0, // Body transfer encoding is not chunked
CHUNK_LENGTH, // Getting chunk length - HHHH[;...] CR LF
CHUNK_EXTENSION, // Getting chunk extension - ;... CR LF
CHUNK_DATA, // Handling chunk data
CHUNK_ERROR, // Invalid chunk header
CHUNK_END, // Getting chunk end marker - CR LF
};
AsyncWebServerRequest::AsyncWebServerRequest(AsyncWebServer *s, AsyncClient *c)
: _client(c), _server(s), _handler(NULL), _response(NULL), _onDisconnectfn(NULL), _temp(), _parseState(PARSE_REQ_START), _version(0),
_method(AsyncWebRequestMethod::HTTP_UNKNOWN), _url(), _host(), _contentType(), _boundary(), _authorization(), _reqconntype(RCT_HTTP),
_authMethod(AsyncAuthType::AUTH_NONE), _isMultipart(false), _isPlainPost(false), _expectingContinue(false), _contentLength(0), _parsedLength(0),
_multiParseState(0), _boundaryPosition(0), _itemStartIndex(0), _itemSize(0), _itemName(), _itemFilename(), _itemType(), _itemValue(), _itemBuffer(0),
_itemBufferIndex(0), _itemIsFile(false), _chunkStartIndex(0), _chunkOffset(0), _chunkSize(0), _chunkedParseState(CHUNK_NONE), _chunkedLastChar(0),
_tempObject(NULL) {
c->onError(
[](void *r, AsyncClient *c, int8_t error) {
(void)c;
// async_ws_log_e("AsyncWebServerRequest::_onError");
static_cast<AsyncWebServerRequest *>(r)->_onError(error);
},
this
);
c->onAck(
[](void *r, AsyncClient *c, size_t len, uint32_t time) {
(void)c;
// async_ws_log_e("AsyncWebServerRequest::_onAck");
static_cast<AsyncWebServerRequest *>(r)->_onAck(len, time);
},
this
);
c->onDisconnect(
[](void *r, AsyncClient *c) {
// async_ws_log_e("AsyncWebServerRequest::_onDisconnect");
static_cast<AsyncWebServerRequest *>(r)->_onDisconnect();
},
this
);
c->onTimeout(
[](void *r, AsyncClient *c, uint32_t time) {
(void)c;
// async_ws_log_e("AsyncWebServerRequest::_onTimeout");
static_cast<AsyncWebServerRequest *>(r)->_onTimeout(time);
},
this
);
c->onData(
[](void *r, AsyncClient *c, void *buf, size_t len) {
(void)c;
// async_ws_log_e("AsyncWebServerRequest::_onData");
static_cast<AsyncWebServerRequest *>(r)->_onData(buf, len);
},
this
);
c->onPoll(
[](void *r, AsyncClient *c) {
(void)c;
// async_ws_log_e("AsyncWebServerRequest::_onPoll");
static_cast<AsyncWebServerRequest *>(r)->_onPoll();
},
this
);
}
AsyncWebServerRequest::~AsyncWebServerRequest() {
if (_client) {
// usually it is _client's disconnect triggers object destruct, but for completeness we define behavior
// if for some reason *this will be destructed while client is still connected
_client->onDisconnect(nullptr);
delete _client;
_client = nullptr;
}
if (_response) {
delete _response;
_response = nullptr;
}
_this.reset();
if (_tempObject != NULL) {
free(_tempObject);
}
if (_tempFile) {
_tempFile.close();
}
if (_itemBuffer) {
free(_itemBuffer);
}
}
void AsyncWebServerRequest::_onData(void *buf, size_t len) {
// SSL/TLS handshake detection
#ifndef ASYNC_TCP_SSL_ENABLED
if (_parseState == PARSE_REQ_START && len && ((uint8_t *)buf)[0] == 0x16) { // 0x16 indicates a Handshake message (SSL/TLS).
async_ws_log_d("SSL/TLS handshake detected: resetting connection");
_parseState = PARSE_REQ_FAIL;
abort();
return;
}
#endif
size_t i = 0;
while (true) {
if (_parseState < PARSE_REQ_BODY) {
// Find new line in buf
char *str = (char *)buf;
for (i = 0; i < len; i++) {
// Check for null characters in header
if (!str[i]) {
_parseState = PARSE_REQ_FAIL;
abort();
return;
}
if (str[i] == '\n') {
break;
}
}
if (i == len) { // No new line, just add the buffer in _temp
char ch = str[len - 1];
str[len - 1] = 0;
if (!_temp.reserve(_temp.length() + len)) {
async_ws_log_e("Failed to allocate");
_parseState = PARSE_REQ_FAIL;
abort();
return;
}
_temp.concat(str);
_temp.concat(ch);
} else { // Found new line - extract it and parse
str[i] = 0; // Terminate the string at the end of the line.
_temp.concat(str);
_temp.trim();
_parseLine();
if (++i < len) {
// Still have more buffer to process
buf = str + i;
len -= i;
continue;
}
}
} else if (_parseState == PARSE_REQ_BODY) {
if (_chunkedParseState != CHUNK_NONE) {
if (_parseChunkedBytes((uint8_t *)buf, len)) {
_parseState = PARSE_REQ_END;
_runMiddlewareChain();
_send();
}
break;
}
// A handler should be already attached at this point in _parseLine function.
// If handler does nothing (_onRequest is NULL), we don't need to really parse the body.
const bool needParse = _handler && !_handler->isRequestHandlerTrivial();
// Discard any bytes after content length; handlers may overrun their buffers
len = std::min(len, _contentLength - _parsedLength);
if (_isMultipart) {
if (needParse) {
size_t i;
for (i = 0; i < len; i++) {
_parseMultipartPostByte(((uint8_t *)buf)[i], i == len - 1);
_parsedLength++;
}
} else {
_parsedLength += len;
}
} else {
if (_parsedLength == 0) {
if (_contentType.startsWith(T_app_xform_urlencoded)) {
_isPlainPost = true;
} else if (_contentType == T_text_plain && isParamChar(((char *)buf)[0])) {
size_t i = 0;
char ch;
do {
ch = ((char *)buf)[i];
} while (i++ < len && isParamChar(ch));
if (i < len && ((char *)buf)[i - 1] == '=') {
_isPlainPost = true;
}
}
}
if (!_isPlainPost) {
// ESP_LOGD("AsyncWebServer", "_isPlainPost: %d, _handler: %p", _isPlainPost, _handler);
if (_handler) {
_handler->handleBody(this, (uint8_t *)buf, len, _parsedLength, _contentLength);
}
_parsedLength += len;
} else if (needParse) {
size_t i;
for (i = 0; i < len; i++) {
_parsedLength++;
_parsePlainPostChar(((uint8_t *)buf)[i]);
}
} else {
_parsedLength += len;
}
}
if (_parsedLength == _contentLength) {
_parseState = PARSE_REQ_END;
_runMiddlewareChain();
_send();
}
}
break;
}
}
void AsyncWebServerRequest::_onPoll() {
// os_printf("p\n");
if (_response && _client && _client->canSend()) {
_response->_ack(this, 0, 0);
}
}
void AsyncWebServerRequest::_onAck(size_t len, uint32_t time) {
// os_printf("a:%u:%u\n", len, time);
if (!_response) {
return;
}
if (!_response->_finished()) {
_response->_ack(this, len, time);
// recheck if response has just completed, close connection
if (_response->_finished()) {
_client->close(); // this will trigger _onDisconnect() and object destruction
}
} else {
// this will close responses that were complete via a single _send() call
_client->close(); // this will trigger _onDisconnect() and object destruction
}
}
void AsyncWebServerRequest::_onError(int8_t error) {
(void)error;
}
void AsyncWebServerRequest::_onTimeout(uint32_t time) {
(void)time;
// os_printf("TIMEOUT: %u, state: %s\n", time, _client->stateToString());
_client->close();
}
void AsyncWebServerRequest::onDisconnect(ArDisconnectHandler fn) {
_onDisconnectfn = fn;
}
void AsyncWebServerRequest::_onDisconnect() {
// os_printf("d\n");
if (_onDisconnectfn) {
_onDisconnectfn();
}
_server->_handleDisconnect(this);
}
void AsyncWebServerRequest::_addGetParams(const String ¶ms) {
size_t start = 0;
while (start < params.length()) {
int end = params.indexOf('&', start);
if (end < 0) {
end = params.length();
}
int equal = params.indexOf('=', start);
if (equal < 0 || equal > end) {
equal = end;
}
String name = urlDecode(params.substring(start, equal));
String value = urlDecode(equal + 1 < end ? params.substring(equal + 1, end) : asyncsrv::emptyString);
if (name.length()) {
_params.emplace_back(name, value);
}
start = end + 1;
}
}
bool AsyncWebServerRequest::_parseReqHead() {
// Split the head into method, url and version
int index = _temp.indexOf(' ');
String m = _temp.substring(0, index);
index = _temp.indexOf(' ', index + 1);
String u = _temp.substring(m.length() + 1, index);
_temp = _temp.substring(index + 1);
_method = asyncsrv::stringToMethod(m);
if (_method == AsyncWebRequestMethod::HTTP_INVALID) {
return false;
}
String g;
index = u.indexOf('?');
if (index > 0) {
g = u.substring(index + 1);
u = u.substring(0, index);
}
_url = urlDecode(u);
_addGetParams(g);
if (!_url.length()) {
return false;
}
if (!_temp.startsWith(T_HTTP_1_0)) {
_version = 1;
}
_temp = asyncsrv::emptyString;
return true;
}
// Returns true when done
bool AsyncWebServerRequest::_parseChunkedBytes(uint8_t *buf, size_t len) {
for (size_t i = 0; i < len;) {
if (_chunkedParseState == CHUNK_DATA) {
// In DATA state, we pass the bytes off to handleBody as a group
// In order to avoid allocating an extra buffer, the data
// blocks that we pass on do not necessarily correspond to
// whole chunks. We just send however much we already have,
// anticipating that more will arrive later. handleBody()
// cannot assume that it receives entire chunks at once.
// That should not be a problem because we do not attach
// any semantic meaning to chunks. That might change if
// we were to support chunk extensions, but that seems
// unlikely since RFC9112 suggests that they are only
// useful for very specialized purposes.
size_t curLen = std::min(_chunkSize - _chunkOffset, len - i);
// On the final zero-length chunk, _chunkSize - _chunkOffset
// will be zero, so we will call handleBody with a zero size,
// marking the end of the data stream.
if (_handler) {
_handler->handleBody(this, buf + i, curLen, _chunkStartIndex, _contentLength);
}
_chunkOffset += curLen;
_chunkStartIndex += curLen;
i += curLen;
if (_chunkOffset == _chunkSize) {
_chunkedParseState = CHUNK_END;
}
} else {
// In other states we process the bytes one by one
uint8_t data = buf[i++];
auto last_was_cr = _chunkedLastChar == '\r';
_chunkedLastChar = data;
if (_chunkedParseState == CHUNK_LENGTH) {
// Incrementally decode a hex number
if (data >= '0' && data <= '9') {
if (_chunkSize >= 0x1000000) {
_chunkedParseState = CHUNK_ERROR;
} else {
_chunkSize = (_chunkSize * 16) + (data - '0');
}
} else if (data >= 'A' && data <= 'F') {
if (_chunkSize >= 0x1000000) {
_chunkedParseState = CHUNK_ERROR;
} else {
_chunkSize = (_chunkSize * 16) + (data - 'A' + 10);
}
} else if (data >= 'a' && data <= 'f') {
if (_chunkSize >= 0x1000000) {
_chunkedParseState = CHUNK_ERROR;
} else {
_chunkSize = (_chunkSize * 16) + (data - 'a' + 10);
}
} else if (data == ';') {
_chunkedParseState = CHUNK_EXTENSION;
} else if (data == '\r') {
// Wait for LF
} else if (data == '\n') {
if (last_was_cr) {
_chunkOffset = 0;
_chunkedParseState = CHUNK_DATA;
} else {
_chunkedParseState = CHUNK_ERROR;
}
} else {
// Invalid hex character
_chunkedParseState = CHUNK_ERROR;
}
} else if (_chunkedParseState == CHUNK_EXTENSION) {
// Chunk extensions appear after a semicolon.
// We ignore them because their use cases are
// specialized and obscure.
if (data == '\r') {
// Wait for LF
} else if (data == '\n') {
if (last_was_cr) {
_chunkOffset = 0;
_chunkedParseState = CHUNK_DATA;
} else {
_chunkedParseState = CHUNK_ERROR;
}
}
} else if (_chunkedParseState == CHUNK_END) {
if (data == '\r') {
// Wait for LF
} else if (data == '\n') {
if (last_was_cr) {
// A zero length chunk marks the end of the chunk stream
if (_chunkSize == 0) {
// If we needed to support trailers, we would switch to
// TRAILER state, but since we have no use case for them,
// we just stop processing the body.
return true;
}
_chunkSize = 0;
_chunkedParseState = CHUNK_LENGTH;
} else {
_chunkedParseState = CHUNK_ERROR;
}
}
}
if (_chunkedParseState == CHUNK_ERROR) {
// If there was an error when parsing the chunk length, the
// rest of the data stream is unreliable. Ideally we should
// close the connection, but that risks leaving things dangling
// (e.g. an open file), so it is probably best to just ignore
// the rest of the data and give handleRequest a chance to
// clean up.
_chunkSize = 0;
abort();
return true;
}
}
}
return false;
}
bool AsyncWebServerRequest::_parseReqHeader() {
AsyncWebHeader header = AsyncWebHeader::parse(_temp);
if (header) {
const String &name = header.name();
const String &value = header.value();
if (name.equalsIgnoreCase(T_Host)) {
_host = value;
} else if (name.equalsIgnoreCase(T_Content_Type)) {
_contentType = value.substring(0, value.indexOf(';'));
// Trim _contentType defensively; AsyncWebHeader::parse now strips all
// leading OWS per RFC 7230, but trim() guards against any future change.
_contentType.trim();
// Media types are case-insensitive (RFC 2045 §5.1), so lowercase the
// entire header value once and reuse it for all subsequent searches.
String lowcase(value);
lowcase.toLowerCase();
if (lowcase.startsWith(T_MULTIPART_)) {
// Case-insensitive, quote-aware search for the boundary parameter.
// We scan forward tracking quoted-string state so that a 'boundary='
// substring inside a quoted parameter value (e.g. foo="x; boundary=y")
// is never mistaken for the real parameter delimiter. A ';' inside a
// quoted-string is not a parameter separator per RFC 2045 §5.1.
// We also require 'boundary=' to be immediately preceded by ';' (with
// optional OWS) so that e.g. 'x-boundary=' is not matched.
int bpos = -1;
bool inQuotes = false;
for (int i = 0; i < (int)lowcase.length(); i++) {
char c = lowcase.charAt(i);
if (inQuotes) {
if (c == '\\' && i + 1 < (int)lowcase.length()) {
i++; // skip quoted-pair — the escaped character cannot terminate the quoted-string
} else if (c == '"') {
inQuotes = false;
}
} else {
if (c == '"') {
inQuotes = true;
} else if (c == ';') {
// Skip OWS after the ';' and check for 'boundary='
int j = i + 1;
while (j < (int)lowcase.length() && (lowcase.charAt(j) == ' ' || lowcase.charAt(j) == '\t')) {
j++;
}
// Use strncmp on the raw C string to avoid a heap allocation
// from String::substring() — this code runs on attacker-controlled
// input in a scan loop, so zero-allocation is preferred.
if ((size_t)j + T_BOUNDARY_LEN <= lowcase.length() && std::strncmp(lowcase.c_str() + j, T_BOUNDARY, T_BOUNDARY_LEN) == 0) {
bpos = j;
break;
}
}
}
}
if (bpos < 0) {
// No valid boundary parameter found — cannot parse multipart body.
async_ws_log_d("Missing multipart boundary parameter, aborting");
_parseState = PARSE_REQ_FAIL;
abort();
return true;
}
// Extract the boundary value that follows "boundary=" and strip leading/
// trailing whitespace. The value may be either a token or a
// quoted-string (RFC 2045 §5.1 / RFC 2046 §5.1).
_boundary = value.substring(bpos + (int)T_BOUNDARY_LEN);
_boundary.trim();
if (_boundary.startsWith("\"")) {
// Quoted-string form: scan forward from position 1 for the closing
// double-quote. A quote is escaped only when preceded by an ODD
// number of consecutive backslashes (e.g. \" is escaped, \\" is not
// because the two backslashes escape each other, leaving the quote
// unescaped). Checking only the immediately preceding character
// would mishandle the \\" case.
int endQuote = 1;
while (true) {
endQuote = _boundary.indexOf('"', endQuote);
if (endQuote < 0) {
break; // string ran out — unterminated quote
}
// Count consecutive backslashes immediately before this quote.
int backslashes = 0;
while (endQuote - 1 - backslashes >= 0 && _boundary.charAt(endQuote - 1 - backslashes) == '\\') {
backslashes++;
}
if (backslashes % 2 == 0) {
break; // even number of backslashes → quote is real closing quote
}
endQuote++; // odd number → quote is escaped, keep scanning
}
if (endQuote < 0) {
// Opening quote was never closed — malformed header.
async_ws_log_d("Invalid multipart boundary (unterminated quote), aborting");
_parseState = PARSE_REQ_FAIL;
abort();
return true;
}
// Strip the surrounding quotes; content between them is the boundary.
_boundary = _boundary.substring(1, endQuote);
// Unescape quoted-pair sequences so the boundary matches the actual bytes on the wire.
String unescaped;
unescaped.reserve(_boundary.length());
for (size_t i = 0; i < _boundary.length(); ++i) {
char c = _boundary.charAt(i);
if (c == '\\' && (i + 1) < _boundary.length()) {
c = _boundary.charAt(++i);
}
unescaped += c;
}
_boundary = unescaped;
} else {
// Token form: the value ends at the next ';' (start of the next
// parameter) or at the end of the header field.
int semi = _boundary.indexOf(';');
if (semi >= 0) {
_boundary = _boundary.substring(0, semi);
}
_boundary.trim();
}
// CWE-190 / DoS fix: RFC 2046 §5.1 limits boundary strings to 70
// characters. _boundaryPosition was formerly uint8_t, so a boundary
// of exactly 256 bytes would overflow the counter to 0, preventing the
// BOUNDARY_OR_DATA loop from ever reaching the end of the boundary and
// causing unbounded CPU consumption (watchdog reset on ESP32/ESP8266).
// Reject boundaries outside the valid range before any parsing begins.
if (_boundary.length() == 0 || _boundary.length() > 70) {
async_ws_log_d("Invalid multipart boundary length (%u), aborting", _boundary.length());
_parseState = PARSE_REQ_FAIL;
abort();
return true;
}
_isMultipart = true;
}
} else if (name.equalsIgnoreCase(T_Content_Length) || name.equalsIgnoreCase(T_X_Expected_Entity_Length)) {
// MacOS WebDAVFS uses X-Expected-Entity-Length to indicate the
// total length of a chunked request body. It is useful to
// determine if a PUT can possibly fit in the available space.
_contentLength = atoi(value.c_str());
} else if (name.equalsIgnoreCase(T_EXPECT) && value.equalsIgnoreCase(T_100_CONTINUE)) {
_expectingContinue = true;
} else if (name.equalsIgnoreCase(T_AUTH)) {
int space = value.indexOf(' ');
if (space == -1) {
_authorization = value;
_authMethod = AsyncAuthType::AUTH_OTHER;
} else {
String method = value.substring(0, space);
if (method.equalsIgnoreCase(T_BASIC)) {
_authMethod = AsyncAuthType::AUTH_BASIC;
} else if (method.equalsIgnoreCase(T_DIGEST)) {
_authMethod = AsyncAuthType::AUTH_DIGEST;
} else if (method.equalsIgnoreCase(T_BEARER)) {
_authMethod = AsyncAuthType::AUTH_BEARER;
} else {
_authMethod = AsyncAuthType::AUTH_OTHER;
}
_authorization = value.substring(space + 1);
}
} else if (name.equalsIgnoreCase(T_UPGRADE) && value.equalsIgnoreCase(T_WS)) {
// WebSocket request can be uniquely identified by header: [Upgrade: websocket]
_reqconntype = RCT_WS;
} else if (name.equalsIgnoreCase(T_ACCEPT)) {
String lowcase(value);
lowcase.toLowerCase();
#ifndef ESP8266
const char *substr = std::strstr(lowcase.c_str(), T_text_event_stream);
#else
const char *substr = std::strstr(lowcase.c_str(), String(T_text_event_stream).c_str());
#endif
if (substr != NULL) {
// WebEvent request can be uniquely identified by header: [Accept: text/event-stream]
_reqconntype = RCT_EVENT;
}
} else if (name.equalsIgnoreCase(T_Transfer_Encoding)) {
String lowcase(value);
lowcase.toLowerCase();
String key;
while (lowcase.length()) {
auto pos = lowcase.indexOf(',');
if (pos >= 0) {
key = lowcase.substring(0, pos);
lowcase = lowcase.substring(pos + 1);
} else {
key = lowcase;
lowcase = "";
}
key.trim();
if (key == "chunked") {
_chunkSize = 0;
_chunkStartIndex = 0;
_chunkedParseState = CHUNK_LENGTH;
break;
}
}
}
_headers.emplace_back(std::move(header));
}
#if defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) || defined(LIBRETINY) || defined(HOST)
// ArduinoCore-API does not have String::clear() method 8-()
_temp = asyncsrv::emptyString;
#else
_temp.clear();
#endif
return true;
}
void AsyncWebServerRequest::_parsePlainPostChar(uint8_t data) {
if (data && (char)data != '&') {
_temp += (char)data;
}
if (!data || (char)data == '&' || _parsedLength == _contentLength) {
String name(T_BODY);
String value(_temp);
if (!(_temp.charAt(0) == '{') && !(_temp.charAt(0) == '[') && _temp.indexOf('=') > 0) {
name = _temp.substring(0, _temp.indexOf('='));
value = _temp.substring(_temp.indexOf('=') + 1);
}
name = urlDecode(name);
if (name.length()) {
_params.emplace_back(name, urlDecode(value), true);
}
#if defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350) || defined(LIBRETINY) || defined(HOST)
// ArduinoCore-API does not have String::clear() method 8-()
_temp = asyncsrv::emptyString;
#else
_temp.clear();
#endif
}
}
void AsyncWebServerRequest::_handleUploadByte(uint8_t data, bool last) {
_itemBuffer[_itemBufferIndex++] = data;
if (last || _itemBufferIndex == RESPONSE_STREAM_BUFFER_SIZE) {
// check if authenticated before calling the upload
if (_handler) {
_handler->handleUpload(this, _itemFilename, _itemSize - _itemBufferIndex, _itemBuffer, _itemBufferIndex, false);
}
_itemBufferIndex = 0;
}
}
enum {
EXPECT_BOUNDARY,
PARSE_HEADERS,
WAIT_FOR_RETURN1,
EXPECT_FEED1,
EXPECT_DASH1,
EXPECT_DASH2,
BOUNDARY_OR_DATA,
DASH3_OR_RETURN2,
EXPECT_FEED2,
PARSING_FINISHED,
PARSE_ERROR
};
void AsyncWebServerRequest::_parseMultipartPostByte(uint8_t data, bool last) {
#define itemWriteByte(b) \
do { \
_itemSize++; \
if (_itemIsFile) \
_handleUploadByte(b, last); \
else \
_itemValue += (char)(b); \
} while (0)
if (!_parsedLength) {
_multiParseState = EXPECT_BOUNDARY;
_temp = asyncsrv::emptyString;
_itemName = asyncsrv::emptyString;
_itemFilename = asyncsrv::emptyString;
_itemType = asyncsrv::emptyString;
}
if (_multiParseState == WAIT_FOR_RETURN1) {
if (data != '\r') {
itemWriteByte(data);
} else {
_multiParseState = EXPECT_FEED1;
}
} else if (_multiParseState == EXPECT_BOUNDARY) {
// Note: when _parsedLength < 2, the subtractions below (_parsedLength - 2
// and _parsedLength - 3) wrap around to very large size_t values. This is
// intentional: the wrapped values are always greater than _boundary.length()
// (which is at most 70), so those comparisons evaluate to false and the
// first two bytes (the '--' prefix) are consumed without error.
if (_parsedLength < 2 && data != '-') {
_multiParseState = PARSE_ERROR;
return;
} else if (_parsedLength - 2 < _boundary.length() && _boundary.c_str()[_parsedLength - 2] != data) {
_multiParseState = PARSE_ERROR;
return;
} else if (_parsedLength - 2 == _boundary.length() && data != '\r') {
_multiParseState = PARSE_ERROR;
return;
} else if (_parsedLength - 3 == _boundary.length()) {
if (data != '\n') {
_multiParseState = PARSE_ERROR;
return;
}
_multiParseState = PARSE_HEADERS;
_itemIsFile = false;
}
} else if (_multiParseState == PARSE_HEADERS) {
if ((char)data != '\r' && (char)data != '\n') {
_temp += (char)data;
}
if ((char)data == '\n') {
if (_temp.length()) {
if (_temp.length() > 12 && _temp.substring(0, 12).equalsIgnoreCase(T_Content_Type)) {
_itemType = _temp.substring(14);
_itemIsFile = true;
} else if (_temp.length() > 19 && _temp.substring(0, 19).equalsIgnoreCase(T_Content_Disposition)) {
_temp = _temp.substring(_temp.indexOf(';') + 2);
while (_temp.indexOf(';') > 0) {
String name = _temp.substring(0, _temp.indexOf('='));
String nameVal = _temp.substring(_temp.indexOf('=') + 2, _temp.indexOf(';') - 1);
if (name == T_name) {
_itemName = nameVal;
} else if (name == T_filename) {
_itemFilename = nameVal;
_itemIsFile = true;
}
_temp = _temp.substring(_temp.indexOf(';') + 2);
}
String name = _temp.substring(0, _temp.indexOf('='));
String nameVal = _temp.substring(_temp.indexOf('=') + 2, _temp.length() - 1);
if (name == T_name) {
_itemName = nameVal;
} else if (name == T_filename) {
_itemFilename = nameVal;
_itemIsFile = true;
}
// Add the parameters from the content-disposition header to the param list, flagged as POST and File,
// so that they can be retrieved using getParam(name, isPost=true, isFile=true)
// in the upload handler to correctly handle multiple file uploads within the same request.
// Example: Content-Disposition: form-data; name="fw"; filename="firmware.bin"
// See: https://github.com/ESP32Async/ESPAsyncWebServer/discussions/328
if (_itemIsFile && _itemName.length() && _itemFilename.length()) {
// add new parameters for this content-disposition
_params.emplace_back(T_name, _itemName, true, true);
_params.emplace_back(T_filename, _itemFilename, true, true);
}
}
_temp = asyncsrv::emptyString;
} else {
_multiParseState = WAIT_FOR_RETURN1;
// value starts from here
_itemSize = 0;
_itemStartIndex = _parsedLength;
_itemValue = asyncsrv::emptyString;
if (_itemIsFile) {
if (_itemBuffer) {
free(_itemBuffer);
}
_itemBuffer = (uint8_t *)malloc(RESPONSE_STREAM_BUFFER_SIZE);
if (_itemBuffer == NULL) {
async_ws_log_e("Failed to allocate");
_multiParseState = PARSE_ERROR;
abort();
return;
}
_itemBufferIndex = 0;
}
}
}
} else if (_multiParseState == EXPECT_FEED1) {
if (data != '\n') {
_multiParseState = WAIT_FOR_RETURN1;
itemWriteByte('\r');
_parseMultipartPostByte(data, last);
} else {
_multiParseState = EXPECT_DASH1;
}
} else if (_multiParseState == EXPECT_DASH1) {
if (data != '-') {
_multiParseState = WAIT_FOR_RETURN1;
itemWriteByte('\r');
itemWriteByte('\n');
_parseMultipartPostByte(data, last);
} else {
_multiParseState = EXPECT_DASH2;
}
} else if (_multiParseState == EXPECT_DASH2) {
if (data != '-') {
_multiParseState = WAIT_FOR_RETURN1;
itemWriteByte('\r');
itemWriteByte('\n');
itemWriteByte('-');
_parseMultipartPostByte(data, last);
} else {
_multiParseState = BOUNDARY_OR_DATA;
_boundaryPosition = 0;
}
} else if (_multiParseState == BOUNDARY_OR_DATA) {
if (_boundaryPosition < _boundary.length() && _boundary.c_str()[_boundaryPosition] != data) {
_multiParseState = WAIT_FOR_RETURN1;
itemWriteByte('\r');
itemWriteByte('\n');
itemWriteByte('-');
itemWriteByte('-');
// CWE-190 fix: loop variable was uint8_t, matching the old type of
// _boundaryPosition. Changed to size_t for consistency.
for (size_t i = 0; i < _boundaryPosition; i++) {
itemWriteByte(_boundary.c_str()[i]);
}
_parseMultipartPostByte(data, last);
} else if (_boundaryPosition == _boundary.length() - 1) {
_multiParseState = DASH3_OR_RETURN2;
if (!_itemIsFile) {
_params.emplace_back(_itemName, _itemValue, true);
} else {
if (_handler) {
_handler->handleUpload(this, _itemFilename, _itemSize - _itemBufferIndex, _itemBuffer, _itemBufferIndex, true);
}
_itemBufferIndex = 0;
_params.emplace_back(_itemName, _itemFilename, true, true, _itemSize);
// remove previous occurrence(s) of content-disposition parameters for this upload
_params.remove_if([this](const AsyncWebParameter &p) {
return p.isPost() && p.isFile() && (p.name() == T_name || p.name() == T_filename);
});
free(_itemBuffer);
_itemBuffer = NULL;
}
} else {
_boundaryPosition++;
}
} else if (_multiParseState == DASH3_OR_RETURN2) {
if (data == '-' && (_contentLength - _parsedLength - 4) != 0) {
// os_printf("ERROR: The parser got to the end of the POST but is expecting %u bytes more!\nDrop an issue so we can have more info on the matter!\n", _contentLength - _parsedLength - 4);
_contentLength = _parsedLength + 4; // lets close the request gracefully
}
if (data == '\r') {
_multiParseState = EXPECT_FEED2;
} else if (data == '-' && _contentLength == (_parsedLength + 4)) {
_multiParseState = PARSING_FINISHED;
} else {
_multiParseState = WAIT_FOR_RETURN1;
itemWriteByte('\r');
itemWriteByte('\n');
itemWriteByte('-');
itemWriteByte('-');
for (size_t i = 0; i < _boundary.length(); i++) {
itemWriteByte(_boundary.c_str()[i]);
}
_parseMultipartPostByte(data, last);
}
} else if (_multiParseState == EXPECT_FEED2) {
if (data == '\n') {
_multiParseState = PARSE_HEADERS;
_itemIsFile = false;
} else {
_multiParseState = WAIT_FOR_RETURN1;
itemWriteByte('\r');
itemWriteByte('\n');
itemWriteByte('-');
itemWriteByte('-');
for (size_t i = 0; i < _boundary.length(); i++) {
itemWriteByte(_boundary.c_str()[i]);
}
itemWriteByte('\r');
_parseMultipartPostByte(data, last);
}
}
}
void AsyncWebServerRequest::_parseLine() {
if (_parseState == PARSE_REQ_START) {
if (!_temp.length()) {
_parseState = PARSE_REQ_FAIL;
abort();
} else {
if (_parseReqHead()) {
_parseState = PARSE_REQ_HEADERS;
} else {
_parseState = PARSE_REQ_FAIL;
abort();
}
}
return;
}
if (_parseState == PARSE_REQ_HEADERS) {
if (!_temp.length()) {
// end of headers
_server->_rewriteRequest(this);
_server->_attachHandler(this);
if (_expectingContinue) {
String response(T_HTTP_100_CONT);
_client->write(response.c_str(), response.length());
}
if (_contentLength || _chunkedParseState != CHUNK_NONE) {
_parseState = PARSE_REQ_BODY;
} else {
_parseState = PARSE_REQ_END;
_runMiddlewareChain();
_send();
}
} else {
_parseReqHeader();
}
}
}
void AsyncWebServerRequest::_runMiddlewareChain() {
if (_handler && _handler->mustSkipServerMiddlewares()) {
_handler->_runChain(this, [this]() {
_handler->handleRequest(this);
});
} else {
_server->_runChain(this, [this]() {
if (_handler) {
_handler->_runChain(this, [this]() {
_handler->handleRequest(this);
});
}
});
}
}
void AsyncWebServerRequest::_send() {
if (!_sent && !_paused) {
// async_ws_log_d("AsyncWebServerRequest::_send()");
// user did not create a response ?
if (!_response) {
send(501, T_text_plain, "Handler did not handle the request");