forked from me-no-dev/ESPAsyncWebServer
-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathESPAsyncWebServer.h
More file actions
1756 lines (1507 loc) · 59.3 KB
/
ESPAsyncWebServer.h
File metadata and controls
1756 lines (1507 loc) · 59.3 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
#pragma once
#include <Arduino.h>
#include <FS.h>
#include <lwip/tcpbase.h>
#include <algorithm>
#include <deque>
#include <functional>
#include <list>
#include <memory>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <vector>
#if __has_include("ArduinoJson.h")
#include <ArduinoJson.h>
#if ARDUINOJSON_VERSION_MAJOR >= 5
#define ASYNC_JSON_SUPPORT 1
#else
#define ASYNC_JSON_SUPPORT 0
#endif // ARDUINOJSON_VERSION_MAJOR >= 5
#if ARDUINOJSON_VERSION_MAJOR >= 6
#define ASYNC_MSG_PACK_SUPPORT 1
#else
#define ASYNC_MSG_PACK_SUPPORT 0
#endif // ARDUINOJSON_VERSION_MAJOR >= 6
#endif // __has_include("ArduinoJson.h")
#if defined(ESP32) || defined(LIBRETINY)
#include <AsyncTCP.h>
#include <assert.h>
#elif defined(ESP8266)
#include <ESPAsyncTCP.h>
#elif defined(TARGET_RP2040) || defined(TARGET_RP2350) || defined(PICO_RP2040) || defined(PICO_RP2350)
#include <RPAsyncTCP.h>
#else
#error Platform not supported
#endif
#include "AsyncWebServerVersion.h"
#define ASYNCWEBSERVER_FORK_ESP32Async
#ifdef ASYNCWEBSERVER_REGEX
#include <regex>
#endif
#include "./literals.h"
// See https://github.com/ESP32Async/ESPAsyncWebServer/commit/3d3456e9e81502a477f6498c44d0691499dda8f9#diff-646b25b11691c11dce25529e3abce843f0ba4bd07ab75ec9eee7e72b06dbf13fR388-R392
// This setting slowdown chunk serving but avoids crashing or deadlocks in the case where slow chunk responses are created, like file serving form SD Card
#ifndef ASYNCWEBSERVER_USE_CHUNK_INFLIGHT
#define ASYNCWEBSERVER_USE_CHUNK_INFLIGHT 1
#endif
#if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED || LT_ARD_HAS_WIFI || CONFIG_ESP32_WIFI_ENABLED || defined(ESP8266)
#define ASYNCWEBSERVER_WIFI_SUPPORTED 1
#else
#define ASYNCWEBSERVER_WIFI_SUPPORTED 0
#endif
// Enable integration with other HTTP libraries
#if defined(HTTP_ANY) || defined(http_parser_h)
#define ASYNCWEBSERVER_HTTP_METHOD_INTEGRATION
#define ASYNCWEBSERVER_NO_GLOBAL_HTTP_METHODS
#endif
class AsyncWebServer;
class AsyncWebServerRequest;
class AsyncWebServerResponse;
class AsyncWebHeader;
class AsyncWebParameter;
class AsyncWebRewrite;
class AsyncWebHandler;
class AsyncStaticWebHandler;
class AsyncCallbackWebHandler;
class AsyncResponseStream;
class AsyncMiddlewareChain;
// Namespace for web request method defines
namespace AsyncWebRequestMethod {
// The long name here is because we sometimes include this in the global namespace
enum AsyncWebRequestMethodType : uint32_t {
HTTP_UNKNOWN = 0u,
HTTP_DELETE = 1u << 0,
HTTP_GET = 1u << 1,
HTTP_HEAD = 1u << 2,
HTTP_POST = 1u << 3,
HTTP_PUT = 1u << 4,
/* pathological */
HTTP_CONNECT = 1u << 5,
HTTP_OPTIONS = 1u << 6,
HTTP_TRACE = 1u << 7,
/* WebDAV */
HTTP_COPY = 1u << 8,
HTTP_LOCK = 1u << 9,
HTTP_MKCOL = 1u << 10,
HTTP_MOVE = 1u << 11,
HTTP_PROPFIND = 1u << 12,
HTTP_PROPPATCH = 1u << 13,
HTTP_SEARCH = 1u << 14,
HTTP_UNLOCK = 1u << 15,
HTTP_BIND = 1u << 16,
HTTP_REBIND = 1u << 17,
HTTP_UNBIND = 1u << 18,
HTTP_ACL = 1u << 19,
/* subversion */
// HTTP_REPORT
// HTTP_MKACTIVITY
// HTTP_CHECKOUT
// HTTP_MERGE
/* upnp */
// HTTP_MSEARCH
// HTTP_NOTIFY
// HTTP_SUBSCRIBE
// HTTP_UNSUBSCRIBE
/* RFC-5789 */
HTTP_PATCH = 1u << 20,
HTTP_PURGE = 1u << 21,
/* CalDAV */
// HTTP_MKCALENDAR
/* RFC-2068, section 19.6.1.2 */
HTTP_LINK = 1u << 22,
HTTP_UNLINK = 1u << 23,
/* icecast */
// HTTP_SOURCE
HTTP_INVALID = 1u << 31 // Sentinel
};
}; // namespace AsyncWebRequestMethod
typedef AsyncWebRequestMethod::AsyncWebRequestMethodType WebRequestMethod;
class WebRequestMethodComposite {
uint32_t mask;
private:
constexpr WebRequestMethodComposite(uint32_t m) : mask(m){};
public:
// Default constructor: by default, matches nothing
constexpr WebRequestMethodComposite() : mask(0){};
// Constructor: allows implicit conversion from WebRequestMethod
constexpr WebRequestMethodComposite(WebRequestMethod m) : mask(static_cast<uint32_t>(m)){};
// Combine composites
constexpr inline WebRequestMethodComposite operator|(const WebRequestMethodComposite &r) const {
return WebRequestMethodComposite(mask | r.mask);
};
// == operator for composite
constexpr inline bool operator==(const WebRequestMethodComposite &r) const {
return mask == r.mask;
};
constexpr inline bool operator!=(const WebRequestMethodComposite &r) const {
return mask != r.mask;
};
// Check for a match
constexpr inline bool matches(WebRequestMethod m) const {
return mask & static_cast<uint32_t>(m);
};
constexpr inline bool operator&(WebRequestMethod m) const {
return matches(m);
}
// Super cool feature: integration with platform `http_method` enum
#ifdef ASYNCWEBSERVER_HTTP_METHOD_INTEGRATION
// Conversion function for integration with external libraries.
// Horrible ternary implementation for C++11 compatibility.
#define MAP_EXTERNAL_TERNARY(x) (t == http_method::x) ? static_cast<uint32_t>(WebRequestMethod::x)
constexpr static inline uint32_t map_http_method(http_method t) {
return MAP_EXTERNAL_TERNARY(HTTP_DELETE)
: MAP_EXTERNAL_TERNARY(HTTP_GET)
: MAP_EXTERNAL_TERNARY(HTTP_HEAD)
: MAP_EXTERNAL_TERNARY(HTTP_POST)
: MAP_EXTERNAL_TERNARY(HTTP_PUT)
: MAP_EXTERNAL_TERNARY(HTTP_CONNECT)
: MAP_EXTERNAL_TERNARY(HTTP_OPTIONS)
: MAP_EXTERNAL_TERNARY(HTTP_TRACE)
: MAP_EXTERNAL_TERNARY(HTTP_COPY)
: MAP_EXTERNAL_TERNARY(HTTP_LOCK)
: MAP_EXTERNAL_TERNARY(HTTP_MKCOL)
: MAP_EXTERNAL_TERNARY(HTTP_MOVE)
: MAP_EXTERNAL_TERNARY(HTTP_PROPFIND)
: MAP_EXTERNAL_TERNARY(HTTP_PROPPATCH)
: MAP_EXTERNAL_TERNARY(HTTP_SEARCH)
: MAP_EXTERNAL_TERNARY(HTTP_UNLOCK)
: MAP_EXTERNAL_TERNARY(HTTP_BIND)
: MAP_EXTERNAL_TERNARY(HTTP_REBIND)
: MAP_EXTERNAL_TERNARY(HTTP_UNBIND)
: MAP_EXTERNAL_TERNARY(HTTP_ACL)
: MAP_EXTERNAL_TERNARY(HTTP_PATCH)
: MAP_EXTERNAL_TERNARY(HTTP_PURGE)
: MAP_EXTERNAL_TERNARY(HTTP_LINK)
: MAP_EXTERNAL_TERNARY(HTTP_UNLINK)
#if defined(HTTP_ANY)
: (t == HTTP_ANY) ? static_cast<uint32_t>(WebRequestMethod::HTTP_INVALID) - 1
#endif
: static_cast<uint32_t>(WebRequestMethod::HTTP_INVALID);
}
#undef MAP_EXTERNAL_TERNARY
constexpr WebRequestMethodComposite(http_method m) : mask(map_http_method(m)){};
#endif
}; // WebRequestMethodComposite
// Operator| for WebRequestMethod: combine to a WebRequestMethodComposite
constexpr inline WebRequestMethodComposite operator|(WebRequestMethod l, WebRequestMethod r) {
return static_cast<WebRequestMethodComposite>(l) | r;
};
namespace AsyncWebRequestMethod {
constexpr WebRequestMethodComposite HTTP_ALL = static_cast<WebRequestMethod>(static_cast<uint32_t>(HTTP_INVALID) - 1);
// Support HTTP_ANY if we can
#ifndef HTTP_ANY
constexpr WebRequestMethodComposite HTTP_ANY = HTTP_ALL;
#endif
} // namespace AsyncWebRequestMethod
// WebRequestMethod string conversion functions
namespace asyncsrv {
WebRequestMethod stringToMethod(const String &);
const char *methodToString(WebRequestMethod);
} // namespace asyncsrv
#if !defined(ASYNCWEBSERVER_NO_GLOBAL_HTTP_METHODS)
// Import the method enum values to the global namespace
using namespace AsyncWebRequestMethod;
#endif
#ifndef HAVE_FS_FILE_OPEN_MODE
namespace fs {
class FileOpenMode {
public:
static const char *read;
static const char *write;
static const char *append;
};
}; // namespace fs
#else
#include "FileOpenMode.h"
#endif
// if this value is returned when asked for data, packet will not be sent and you will be asked for data again
#define RESPONSE_TRY_AGAIN 0xFFFFFFFF
#define RESPONSE_STREAM_BUFFER_SIZE 1460
typedef std::function<void(void)> ArDisconnectHandler;
/*
* PARAMETER :: Chainable object to hold GET/POST and FILE parameters
* */
class AsyncWebParameter {
private:
String _name;
String _value;
size_t _size;
bool _isForm;
bool _isFile;
public:
AsyncWebParameter(const String &name, const String &value, bool form = false, bool file = false, size_t size = 0)
: _name(name), _value(value), _size(size), _isForm(form), _isFile(file) {}
const String &name() const {
return _name;
}
const String &value() const {
return _value;
}
size_t size() const {
return _size;
}
bool isPost() const {
return _isForm;
}
bool isFile() const {
return _isFile;
}
};
/*
* HEADER :: Chainable object to hold the headers
* */
class AsyncWebHeader {
private:
String _name;
String _value;
public:
AsyncWebHeader() {}
AsyncWebHeader(const AsyncWebHeader &) = default;
AsyncWebHeader(AsyncWebHeader &&) = default;
AsyncWebHeader(const char *name, const char *value) : _name(name), _value(value) {}
AsyncWebHeader(const String &name, const String &value) : _name(name), _value(value) {}
#ifndef ESP8266
[[deprecated("Use AsyncWebHeader::parse(data) instead")]]
#endif
AsyncWebHeader(const String &data)
: AsyncWebHeader(parse(data)){};
AsyncWebHeader &operator=(const AsyncWebHeader &) = default;
AsyncWebHeader &operator=(AsyncWebHeader &&other) = default;
const String &name() const {
return _name;
}
const String &value() const {
return _value;
}
String toString() const;
// returns true if the header is valid
operator bool() const {
return _name.length();
}
static const AsyncWebHeader parse(const String &data) {
return parse(data.c_str());
}
static const AsyncWebHeader parse(const char *data);
};
/*
* REQUEST :: Each incoming Client is wrapped inside a Request and both live together until disconnect
* */
typedef enum {
RCT_NOT_USED = -1,
RCT_DEFAULT = 0,
RCT_HTTP,
RCT_WS,
RCT_EVENT,
RCT_MAX
} RequestedConnectionType;
// this enum is similar to Arduino WebServer's AsyncAuthType and PsychicHttp
typedef enum {
AUTH_NONE = 0, // always allow
AUTH_BASIC = 1,
AUTH_DIGEST = 2,
AUTH_BEARER = 3,
AUTH_OTHER = 4,
AUTH_DENIED = 255, // always returns 401
} AsyncAuthType;
typedef std::function<size_t(uint8_t *, size_t, size_t)> AwsResponseFiller;
typedef std::function<String(const String &)> AwsTemplateProcessor;
using AsyncWebServerRequestPtr = std::weak_ptr<AsyncWebServerRequest>;
class AsyncWebServerRequest {
using File = fs::File;
using FS = fs::FS;
friend class AsyncWebServer;
friend class AsyncCallbackWebHandler;
friend class AsyncFileResponse;
friend class AsyncStaticWebHandler;
friend class AsyncURIMatcher;
private:
AsyncClient *_client;
AsyncWebServer *_server;
AsyncWebHandler *_handler;
AsyncWebServerResponse *_response;
ArDisconnectHandler _onDisconnectfn;
bool _sent = false; // response is sent
bool _paused = false; // request is paused (request continuation)
std::shared_ptr<AsyncWebServerRequest> _this; // shared pointer to this request
String _temp;
uint8_t _parseState;
uint8_t _version;
WebRequestMethod _method;
String _url;
String _host;
String _contentType;
String _boundary;
String _authorization;
RequestedConnectionType _reqconntype;
AsyncAuthType _authMethod = AsyncAuthType::AUTH_NONE;
bool _isMultipart;
bool _isPlainPost;
bool _expectingContinue;
size_t _contentLength;
size_t _parsedLength;
std::list<AsyncWebHeader> _headers;
std::list<AsyncWebParameter> _params;
#ifdef ASYNCWEBSERVER_REGEX
std::list<String> _pathParams;
#endif
std::unordered_map<const char *, String, std::hash<const char *>, std::equal_to<const char *>> _attributes;
uint8_t _multiParseState;
uint8_t _boundaryPosition;
size_t _itemStartIndex;
size_t _itemSize;
String _itemName;
String _itemFilename;
String _itemType;
String _itemValue;
uint8_t *_itemBuffer;
size_t _itemBufferIndex;
bool _itemIsFile;
size_t _chunkStartIndex; // Offset from start of the chunked data stream
size_t _chunkOffset; // Offset into the current chunk
size_t _chunkSize; // Size of the current chunk
uint8_t _chunkedParseState;
uint8_t _chunkedLastChar;
bool _parseChunkedBytes(uint8_t *data, size_t len);
void _onPoll();
void _onAck(size_t len, uint32_t time);
void _onError(int8_t error);
void _onTimeout(uint32_t time);
void _onDisconnect();
void _onData(void *buf, size_t len);
bool _parseReqHead();
bool _parseReqHeader();
void _parseLine();
void _parsePlainPostChar(uint8_t data);
void _parseMultipartPostByte(uint8_t data, bool last);
void _addGetParams(const String ¶ms);
void _handleUploadStart();
void _handleUploadByte(uint8_t data, bool last);
void _handleUploadEnd();
void _send();
void _runMiddlewareChain();
static bool _getEtag(File gzFile, char *eTag);
public:
File _tempFile;
void *_tempObject;
AsyncWebServerRequest(AsyncWebServer *, AsyncClient *);
~AsyncWebServerRequest();
AsyncClient *client() {
return _client;
}
/**
* @brief release owned AsyncClient object
* AsyncClient pointer will be abandoned in this instance,
* the further ownership of the connection should be managed out of request's life-time scope
* could be used for long lived connection like SSE or WebSockets
* @note do not call this method unless you know what you are doing, otherwise it may lead to
* memory leaks and connections lingering
*
* @return AsyncClient* pointer to released connection object
*/
AsyncClient *clientRelease();
uint8_t version() const {
return _version;
}
WebRequestMethod method() const {
return _method;
}
const String &url() const {
return _url;
}
const String &host() const {
return _host;
}
const String &contentType() const {
return _contentType;
}
size_t contentLength() const {
return _contentLength;
}
bool multipart() const {
return _isMultipart;
}
inline const char *methodToString() const {
return asyncsrv::methodToString(_method);
};
const char *requestedConnTypeToString() const;
RequestedConnectionType requestedConnType() const {
return _reqconntype;
}
bool isExpectedRequestedConnType(RequestedConnectionType erct1, RequestedConnectionType erct2 = RCT_NOT_USED, RequestedConnectionType erct3 = RCT_NOT_USED)
const;
bool isWebSocketUpgrade() const {
return _method == AsyncWebRequestMethod::HTTP_GET && isExpectedRequestedConnType(RCT_WS);
}
bool isSSE() const {
return _method == AsyncWebRequestMethod::HTTP_GET && isExpectedRequestedConnType(RCT_EVENT);
}
bool isHTTP() const {
return isExpectedRequestedConnType(RCT_DEFAULT, RCT_HTTP);
}
void onDisconnect(ArDisconnectHandler fn);
// hash is the string representation of:
// base64(user:pass) for basic or
// user:realm:md5(user:realm:pass) for digest
bool authenticate(const char *hash) const;
bool authenticate(const char *username, const char *credentials, const char *realm = NULL, bool isHash = false) const;
void requestAuthentication(const char *realm = nullptr, bool isDigest = true) {
requestAuthentication(isDigest ? AsyncAuthType::AUTH_DIGEST : AsyncAuthType::AUTH_BASIC, realm);
}
void requestAuthentication(AsyncAuthType method, const char *realm = nullptr, const char *_authFailMsg = nullptr);
// detected Authentication type from "Authorization" request header during request parsing
AsyncAuthType authType() const {
return _authMethod;
}
// raw value of "Authorization" request header after the auth type
// For example, for header "Authorization: Bearer <token>", <token> is the value returned
const String &authChallenge() const {
return _authorization;
}
// IMPORTANT: this method is for internal use ONLY
// Please do not use it!
// It can be removed or modified at any time without notice
void setHandler(AsyncWebHandler *handler) {
_handler = handler;
}
#ifndef ESP8266
[[deprecated("All headers are now collected. Use removeHeader(name) or AsyncHeaderFreeMiddleware if you really need to free some headers.")]]
#endif
void addInterestingHeader(__unused const char *name) {
}
#ifndef ESP8266
[[deprecated("All headers are now collected. Use removeHeader(name) or AsyncHeaderFreeMiddleware if you really need to free some headers.")]]
#endif
void addInterestingHeader(__unused const String &name) {
}
/**
* @brief issue HTTP redirect response with Location header
*
* @param url - url to redirect to
* @param code - response code, default is 302 : temporary redirect
*/
void redirect(const char *url, int code = 302);
void redirect(const String &url, int code = 302) {
return redirect(url.c_str(), code);
};
void send(AsyncWebServerResponse *response);
AsyncWebServerResponse *getResponse() const {
return _response;
}
void send(int code, const char *contentType = asyncsrv::empty, const char *content = asyncsrv::empty, AwsTemplateProcessor callback = nullptr) {
send(beginResponse(code, contentType, content, callback));
}
void send(int code, const String &contentType, const char *content = asyncsrv::empty, AwsTemplateProcessor callback = nullptr) {
send(beginResponse(code, contentType.c_str(), content, callback));
}
void send(int code, const String &contentType, const String &content, AwsTemplateProcessor callback = nullptr) {
send(beginResponse(code, contentType.c_str(), content.c_str(), callback));
}
void send(int code, const char *contentType, const uint8_t *content, size_t len, AwsTemplateProcessor callback = nullptr) {
send(beginResponse(code, contentType, content, len, callback));
}
void send(int code, const String &contentType, const uint8_t *content, size_t len, AwsTemplateProcessor callback = nullptr) {
send(beginResponse(code, contentType, content, len, callback));
}
void send(FS &fs, const String &path, const char *contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr);
void send(FS &fs, const String &path, const String &contentType, bool download = false, AwsTemplateProcessor callback = nullptr) {
send(fs, path, contentType.c_str(), download, callback);
}
void send(File content, const String &path, const char *contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr) {
if (content) {
send(beginResponse(content, path, contentType, download, callback));
} else {
send(404);
}
}
void send(File content, const String &path, const String &contentType, bool download = false, AwsTemplateProcessor callback = nullptr) {
send(content, path, contentType.c_str(), download, callback);
}
void send(Stream &stream, const char *contentType, size_t len, AwsTemplateProcessor callback = nullptr) {
send(beginResponse(stream, contentType, len, callback));
}
void send(Stream &stream, const String &contentType, size_t len, AwsTemplateProcessor callback = nullptr) {
send(beginResponse(stream, contentType, len, callback));
}
void send(const char *contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) {
send(beginResponse(contentType, len, callback, templateCallback));
}
void send(const String &contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) {
send(beginResponse(contentType, len, callback, templateCallback));
}
void sendChunked(const char *contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) {
send(beginChunkedResponse(contentType, callback, templateCallback));
}
void sendChunked(const String &contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) {
send(beginChunkedResponse(contentType, callback, templateCallback));
}
#ifndef ESP8266
[[deprecated("Replaced by send(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr)")]]
#endif
void send_P(int code, const String &contentType, const uint8_t *content, size_t len, AwsTemplateProcessor callback = nullptr) {
send(code, contentType, content, len, callback);
}
#ifndef ESP8266
[[deprecated("Replaced by send(int code, const String& contentType, const char* content = asyncsrv::empty, AwsTemplateProcessor callback = nullptr)")]]
void send_P(int code, const String &contentType, PGM_P content, AwsTemplateProcessor callback = nullptr) {
send(code, contentType, content, callback);
}
#else
void send_P(int code, const String &contentType, PGM_P content, AwsTemplateProcessor callback = nullptr) {
send(beginResponse_P(code, contentType, content, callback));
}
#endif
AsyncWebServerResponse *
beginResponse(int code, const char *contentType = asyncsrv::empty, const char *content = asyncsrv::empty, AwsTemplateProcessor callback = nullptr);
AsyncWebServerResponse *beginResponse(int code, const String &contentType, const char *content = asyncsrv::empty, AwsTemplateProcessor callback = nullptr) {
return beginResponse(code, contentType.c_str(), content, callback);
}
AsyncWebServerResponse *beginResponse(int code, const String &contentType, const String &content, AwsTemplateProcessor callback = nullptr) {
return beginResponse(code, contentType.c_str(), content.c_str(), callback);
}
AsyncWebServerResponse *beginResponse(int code, const char *contentType, const uint8_t *content, size_t len, AwsTemplateProcessor callback = nullptr);
AsyncWebServerResponse *beginResponse(int code, const String &contentType, const uint8_t *content, size_t len, AwsTemplateProcessor callback = nullptr) {
return beginResponse(code, contentType.c_str(), content, len, callback);
}
AsyncWebServerResponse *
beginResponse(FS &fs, const String &path, const char *contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr);
AsyncWebServerResponse *
beginResponse(FS &fs, const String &path, const String &contentType = emptyString, bool download = false, AwsTemplateProcessor callback = nullptr) {
return beginResponse(fs, path, contentType.c_str(), download, callback);
}
AsyncWebServerResponse *
beginResponse(File content, const String &path, const char *contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr);
AsyncWebServerResponse *
beginResponse(File content, const String &path, const String &contentType = emptyString, bool download = false, AwsTemplateProcessor callback = nullptr) {
return beginResponse(content, path, contentType.c_str(), download, callback);
}
AsyncWebServerResponse *beginResponse(Stream &stream, const char *contentType, size_t len, AwsTemplateProcessor callback = nullptr);
AsyncWebServerResponse *beginResponse(Stream &stream, const String &contentType, size_t len, AwsTemplateProcessor callback = nullptr) {
return beginResponse(stream, contentType.c_str(), len, callback);
}
AsyncWebServerResponse *beginResponse(const char *contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr);
AsyncWebServerResponse *beginResponse(const String &contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) {
return beginResponse(contentType.c_str(), len, callback, templateCallback);
}
AsyncWebServerResponse *beginChunkedResponse(const char *contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr);
AsyncWebServerResponse *beginChunkedResponse(const String &contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) {
return beginChunkedResponse(contentType.c_str(), callback, templateCallback);
}
AsyncResponseStream *beginResponseStream(const char *contentType, size_t bufferSize = RESPONSE_STREAM_BUFFER_SIZE);
AsyncResponseStream *beginResponseStream(const String &contentType, size_t bufferSize = RESPONSE_STREAM_BUFFER_SIZE) {
return beginResponseStream(contentType.c_str(), bufferSize);
}
#ifndef ESP8266
[[deprecated("Replaced by beginResponse(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr)")]]
#endif
AsyncWebServerResponse *beginResponse_P(int code, const String &contentType, const uint8_t *content, size_t len, AwsTemplateProcessor callback = nullptr) {
return beginResponse(code, contentType.c_str(), content, len, callback);
}
#ifndef ESP8266
[[deprecated("Replaced by beginResponse(int code, const String& contentType, const char* content = asyncsrv::empty, AwsTemplateProcessor callback = nullptr)"
)]]
#endif
AsyncWebServerResponse *beginResponse_P(int code, const String &contentType, PGM_P content, AwsTemplateProcessor callback = nullptr);
/**
* @brief Request Continuation: this function pauses the current request and returns a weak pointer (AsyncWebServerRequestPtr is a std::weak_ptr) to the request in order to reuse it later on.
* The middelware chain will continue to be processed until the end, but no response will be sent.
* To resume operations (send the request), the request must be retrieved from the weak pointer and a send() function must be called.
* AsyncWebServerRequestPtr is the only object allowed to exist the scope of the request handler.
* @warning This function should be called from within the context of a request (in a handler or middleware for example).
* @warning While the request is paused, if the client aborts the request, the latter will be disconnected and deleted.
* So it is the responsibility of the user to check the validity of the request pointer (AsyncWebServerRequestPtr) before using it by calling lock() and/or expired().
*/
AsyncWebServerRequestPtr pause();
bool isPaused() const {
return _paused;
}
/**
* @brief Aborts the request and close the client (RST).
* Mark the request as sent.
* If it was paused, it will be unpaused and it won't be possible to resume it.
*/
void abort();
bool isSent() const {
return _sent;
}
/**
* @brief Get the Request parameter by name
*
* @param name
* @param post
* @param file
* @return const AsyncWebParameter*
*/
const AsyncWebParameter *getParam(const char *name, bool post = false, bool file = false) const;
const AsyncWebParameter *getParam(const String &name, bool post = false, bool file = false) const {
return getParam(name.c_str(), post, file);
};
#ifdef ESP8266
const AsyncWebParameter *getParam(const __FlashStringHelper *data, bool post, bool file) const;
#endif
/**
* @brief Get request parameter by number
* i.e., n-th parameter
* @param num
* @return const AsyncWebParameter*
*/
const AsyncWebParameter *getParam(size_t num) const;
const AsyncWebParameter *getParam(int num) const {
return num < 0 ? nullptr : getParam((size_t)num);
}
size_t args() const {
return params();
} // get arguments count
// get request argument value by name
const String &arg(const char *name) const;
// get request argument value by name
const String &arg(const String &name) const {
return arg(name.c_str());
};
#ifdef ESP8266
const String &arg(const __FlashStringHelper *data) const; // get request argument value by F(name)
#endif
const String &arg(size_t i) const; // get request argument value by number
const String &arg(int i) const {
return i < 0 ? emptyString : arg((size_t)i);
};
const String &argName(size_t i) const; // get request argument name by number
const String &argName(int i) const {
return i < 0 ? emptyString : argName((size_t)i);
};
bool hasArg(const char *name) const; // check if argument exists
bool hasArg(const String &name) const {
return hasArg(name.c_str());
};
#ifdef ESP8266
bool hasArg(const __FlashStringHelper *data) const; // check if F(argument) exists
#endif
#ifdef ASYNCWEBSERVER_REGEX
const String &pathArg(size_t i) const {
if (i >= _pathParams.size()) {
return emptyString;
}
auto it = _pathParams.begin();
std::advance(it, i);
return *it;
}
const String &pathArg(int i) const {
return i < 0 ? emptyString : pathArg((size_t)i);
}
#else
const String &pathArg(size_t i) const __attribute__((error("ERR: pathArg() requires -D ASYNCWEBSERVER_REGEX and only works on regex handlers")));
const String &pathArg(int i) const __attribute__((error("ERR: pathArg() requires -D ASYNCWEBSERVER_REGEX and only works on regex handlers")));
#endif
// get request header value by name
const String &header(const char *name) const;
const String &header(const String &name) const {
return header(name.c_str());
};
#ifdef ESP8266
const String &header(const __FlashStringHelper *data) const; // get request header value by F(name)
#endif
const String &header(size_t i) const; // get request header value by number
const String &header(int i) const {
return i < 0 ? emptyString : header((size_t)i);
};
const String &headerName(size_t i) const; // get request header name by number
const String &headerName(int i) const {
return i < 0 ? emptyString : headerName((size_t)i);
};
size_t headers() const; // get header count
// check if header exists
bool hasHeader(const char *name) const;
bool hasHeader(const String &name) const {
return hasHeader(name.c_str());
};
#ifdef ESP8266
bool hasHeader(const __FlashStringHelper *data) const; // check if header exists
#endif
const AsyncWebHeader *getHeader(const char *name) const;
const AsyncWebHeader *getHeader(const String &name) const {
return getHeader(name.c_str());
};
#ifdef ESP8266
const AsyncWebHeader *getHeader(const __FlashStringHelper *data) const;
#endif
const AsyncWebHeader *getHeader(size_t num) const;
const AsyncWebHeader *getHeader(int num) const {
return num < 0 ? nullptr : getHeader((size_t)num);
};
const std::list<AsyncWebHeader> &getHeaders() const {
return _headers;
}
size_t getHeaderNames(std::vector<const char *> &names) const;
// Remove a header from the request.
// It will free the memory and prevent the header to be seen during request processing.
bool removeHeader(const char *name);
// Remove all request headers.
void removeHeaders() {
_headers.clear();
}
size_t params() const; // get arguments count
bool hasParam(const char *name, bool post = false, bool file = false) const;
bool hasParam(const String &name, bool post = false, bool file = false) const {
return hasParam(name.c_str(), post, file);
};
#ifdef ESP8266
bool hasParam(const __FlashStringHelper *data, bool post = false, bool file = false) const {
return hasParam(String(data).c_str(), post, file);
};
#endif
// REQUEST ATTRIBUTES
void setAttribute(const char *name, const char *value) {
_attributes[name] = value;
}
void setAttribute(const char *name, bool value) {
_attributes[name] = value ? "1" : emptyString;
}
void setAttribute(const char *name, long value) {
_attributes[name] = String(value);
}
void setAttribute(const char *name, float value, unsigned int decimalPlaces = 2) {
_attributes[name] = String(value, decimalPlaces);
}
void setAttribute(const char *name, double value, unsigned int decimalPlaces = 2) {
_attributes[name] = String(value, decimalPlaces);
}
bool hasAttribute(const char *name) const {
return _attributes.find(name) != _attributes.end();
}
const String &getAttribute(const char *name, const String &defaultValue = emptyString) const;
bool getAttribute(const char *name, bool defaultValue) const;
long getAttribute(const char *name, long defaultValue) const;
float getAttribute(const char *name, float defaultValue) const;
double getAttribute(const char *name, double defaultValue) const;
String urlDecode(const String &text) const;
};
class AsyncURIMatcher {
private:
// Matcher types are internal, not part of public API
enum class Type {
None, // default state: matcher does not match anything
All, // matches everything
Exact, // matches equivalent to regex: ^{_uri}$
Prefix, // matches equivalent to regex: ^{_uri}.*
Extension, // non-regular match: /pattern../*.ext
BackwardCompatible, // matches equivalent to regex: ^{_uri}(/.*)?$
Regex, // matches _url as regex
};
public:
/**
* @brief No special matching behavior (default)
*/
static constexpr uint16_t None = 0;
/**
* @brief Enable case-insensitive URI matching
*
* When CaseInsensitive is specified:
* - The URI pattern is converted to lowercase during construction
* - Incoming request URLs are converted to lowercase before matching
* - For regex matchers, the std::regex::icase flag is used
*
* Example usage:
* ```cpp
* // Matches /login, /LOGIN, /Login, /LoGiN, etc.
* server.on(AsyncURIMatcher::exact("/login", AsyncURIMatcher::CaseInsensitive), handler);
*
* // Matches /api/\*, /API/\*, /Api/\*, etc.
* server.on(AsyncURIMatcher::prefix("/api", AsyncURIMatcher::CaseInsensitive), handler);
*
* // Regex with case insensitive matching
* server.on(AsyncURIMatcher::regex("^/user/([a-z]+)$", AsyncURIMatcher::CaseInsensitive), handler);
* ```
*
* Performance note: Case conversion adds minimal overhead during construction and matching.
*/
static constexpr uint16_t CaseInsensitive = (1 << 0);
// public constructors
AsyncURIMatcher() : AsyncURIMatcher({}, Type::None, None) {}
AsyncURIMatcher(const char *uri, uint16_t modifiers = None) : AsyncURIMatcher(String(uri), modifiers) {}
AsyncURIMatcher(String uri, uint16_t modifiers = None);
#ifdef ASYNCWEBSERVER_REGEX
AsyncURIMatcher(const AsyncURIMatcher &c);
AsyncURIMatcher(AsyncURIMatcher &&c);
~AsyncURIMatcher();
AsyncURIMatcher &operator=(const AsyncURIMatcher &r);
AsyncURIMatcher &operator=(AsyncURIMatcher &&r);
#else
AsyncURIMatcher(const AsyncURIMatcher &) = default;
AsyncURIMatcher(AsyncURIMatcher &&) = default;
~AsyncURIMatcher() = default;
AsyncURIMatcher &operator=(const AsyncURIMatcher &) = default;
AsyncURIMatcher &operator=(AsyncURIMatcher &&) = default;
#endif
bool matches(AsyncWebServerRequest *request) const;
// static factory methods for common match types:
// - AsyncURIMatcher::all() - matches everything
// - AsyncURIMatcher::none() - matches nothing
// - AsyncURIMatcher::exact(uri, modifiers) - exact match
// - AsyncURIMatcher::prefix(uri, modifiers) - prefix match
// - AsyncURIMatcher::dir(uri, modifiers) - directory/folder match (trailing slash added automatically)
// - AsyncURIMatcher::ext(uri, modifiers) - extension match (pattern with wildcard)
// - AsyncURIMatcher::regex(uri, modifiers) - regex match (requires ASYNCWEBSERVER_REGEX)
/**
* @brief Create a matcher that matches all URIs unconditionally
* @return AsyncURIMatcher that accepts any request URL
*
* Usage: server.on(AsyncURIMatcher::all(), handler);
*/
static inline AsyncURIMatcher all() {
return AsyncURIMatcher{{}, Type::All, None};
}