Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions examples/HTTPMethods/HTTPMethods.ino
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@
#include <WiFi.h>
#endif

#define ASYNCWEBSERVER_NO_GLOBAL_HTTP_METHODS 1
#undef HTTP_ANY
#include <ESPAsyncWebServer.h>

static AsyncWebServer server(80);
Expand All @@ -37,14 +35,19 @@ void setup() {
WiFi.softAP("esp-captive");
#endif

// curl -v http://192.168.4.1/get-or-post
// curl -v -X POST -d "a=b" http://192.168.4.1/get-or-post
server.on("/get-or-post", WebRequestMethod::HTTP_GET | WebRequestMethod::HTTP_POST, [](AsyncWebServerRequest *request) {
// curl -v http://192.168.4.1/get-or-post => Hello
// curl -v -X POST -d "a=b" http://192.168.4.1/get-or-post => Hello
// curl -v -X PUT -d "a=b" http://192.168.4.1/get-or-post => 404
// curl -v -X PATCH -d "a=b" http://192.168.4.1/get-or-post => 404
server.on("/get-or-post", HTTP_GET | HTTP_POST, [](AsyncWebServerRequest *request) {
request->send(200, "text/plain", "Hello");
});

// curl -v http://192.168.4.1/any
server.on("/any", WebRequestMethod::HTTP_ANY, [](AsyncWebServerRequest *request) {
// curl -v http://192.168.4.1/any => Hello
// curl -v -X POST -d "a=b" http://192.168.4.1/any => Hello
// curl -v -X PUT -d "a=b" http://192.168.4.1/any => Hello
// curl -v -X PATCH -d "a=b" http://192.168.4.1/any => Hello
server.on("/any", HTTP_ANY, [](AsyncWebServerRequest *request) {
request->send(200, "text/plain", "Hello");
});

Expand Down
15 changes: 6 additions & 9 deletions src/AsyncJson.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -115,14 +115,11 @@ size_t AsyncMessagePackResponse::_fillBuffer(uint8_t *data, size_t len) {

#if ARDUINOJSON_VERSION_MAJOR == 6
AsyncCallbackJsonWebHandler::AsyncCallbackJsonWebHandler(AsyncURIMatcher uri, ArJsonRequestHandlerFunction onRequest, size_t maxJsonBufferSize)
: _uri(std::move(uri)),
_method(AsyncWebRequestMethod::HTTP_GET | AsyncWebRequestMethod::HTTP_POST | AsyncWebRequestMethod::HTTP_PUT | AsyncWebRequestMethod::HTTP_PATCH),
_onRequest(onRequest), maxJsonBufferSize(maxJsonBufferSize), _maxContentLength(16384) {}
: _uri(std::move(uri)), _method(HTTP_GET | HTTP_POST | HTTP_PUT | HTTP_PATCH), _onRequest(onRequest), maxJsonBufferSize(maxJsonBufferSize),
_maxContentLength(16384) {}
#else
AsyncCallbackJsonWebHandler::AsyncCallbackJsonWebHandler(AsyncURIMatcher uri, ArJsonRequestHandlerFunction onRequest)
: _uri(std::move(uri)),
_method(AsyncWebRequestMethod::HTTP_GET | AsyncWebRequestMethod::HTTP_POST | AsyncWebRequestMethod::HTTP_PUT | AsyncWebRequestMethod::HTTP_PATCH),
_onRequest(onRequest), _maxContentLength(16384) {}
: _uri(std::move(uri)), _method(HTTP_GET | HTTP_POST | HTTP_PUT | HTTP_PATCH), _onRequest(onRequest), _maxContentLength(16384) {}
#endif

bool AsyncCallbackJsonWebHandler::canHandle(AsyncWebServerRequest *request) const {
Expand All @@ -135,17 +132,17 @@ bool AsyncCallbackJsonWebHandler::canHandle(AsyncWebServerRequest *request) cons
}

#if ASYNC_MSG_PACK_SUPPORT == 1
return request->method() == AsyncWebRequestMethod::HTTP_GET || request->contentType().equalsIgnoreCase(asyncsrv::T_application_json)
return request->method() == HTTP_GET || request->contentType().equalsIgnoreCase(asyncsrv::T_application_json)
|| request->contentType().equalsIgnoreCase(asyncsrv::T_application_msgpack);
#else
return request->method() == AsyncWebRequestMethod::HTTP_GET || request->contentType().equalsIgnoreCase(asyncsrv::T_application_json);
return request->method() == HTTP_GET || request->contentType().equalsIgnoreCase(asyncsrv::T_application_json);
#endif
}

void AsyncCallbackJsonWebHandler::handleRequest(AsyncWebServerRequest *request) {
if (_onRequest) {
// GET request:
if (request->method() == AsyncWebRequestMethod::HTTP_GET) {
if (request->method() == HTTP_GET) {
JsonVariant json;
_onRequest(request, json);
return;
Expand Down
230 changes: 191 additions & 39 deletions src/ESPAsyncWebServer.h
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,72 @@
#error Platform not supported
#endif

// HTTP method types from the platform's HTTP parser library.
// Arduino ESP32 core provides HTTP_Method.h which typedef's http_method as
// HTTPMethod and defines HTTP_ANY = (HTTPMethod)(255) as the "match any" sentinel.
// Fall back to the raw http_parser.h (always available via the TCP library) or,
// as a last resort, to a fully inline fallback definition.
#if __has_include(<HTTP_Method.h>)
#include <HTTP_Method.h>
// HTTP_Method.h provides: typedef enum http_method HTTPMethod;
// and: #define HTTP_ANY (HTTPMethod)(255)
#elif __has_include(<http_parser.h>)
#include <http_parser.h>
// http_parser.h provides enum http_method but not the HTTP_ANY sentinel.
// Define the sentinel here, matching the value used by Arduino's HTTP_Method.h.
#ifndef HTTP_ANY
#define HTTP_ANY ((http_method)(255))
#endif
#else
// Full fallback for toolchains that expose neither header.
// Enum values match the llhttp/http_parser spec used by all supported platforms.
typedef enum {
HTTP_DELETE = 0,
HTTP_GET = 1,
HTTP_HEAD = 2,
HTTP_POST = 3,
HTTP_PUT = 4,
/* pathological */
HTTP_CONNECT = 5,
HTTP_OPTIONS = 6,
HTTP_TRACE = 7,
/* WebDAV */
HTTP_COPY = 8,
HTTP_LOCK = 9,
HTTP_MKCOL = 10,
HTTP_MOVE = 11,
HTTP_PROPFIND = 12,
HTTP_PROPPATCH = 13,
HTTP_SEARCH = 14,
HTTP_UNLOCK = 15,
HTTP_BIND = 16,
HTTP_REBIND = 17,
HTTP_UNBIND = 18,
HTTP_ACL = 19,
/* subversion */
HTTP_REPORT = 20,
HTTP_MKACTIVITY = 21,
HTTP_CHECKOUT = 22,
HTTP_MERGE = 23,
/* upnp */
HTTP_MSEARCH = 24,
HTTP_NOTIFY = 25,
HTTP_SUBSCRIBE = 26,
HTTP_UNSUBSCRIBE = 27,
/* RFC-5789 */
HTTP_PATCH = 28,
HTTP_PURGE = 29,
/* CalDAV */
HTTP_MKCALENDAR = 30,
/* RFC-2068, section 19.6.1.2 */
HTTP_LINK = 31,
HTTP_UNLINK = 32,
/* icecast */
HTTP_SOURCE = 33,
} http_method;
#define HTTP_ANY ((http_method)(255))
#endif

#include "AsyncWebServerVersion.h"
#define ASYNCWEBSERVER_FORK_ESP32Async

Expand Down Expand Up @@ -78,44 +144,127 @@ 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 {
HTTP_GET = 0b0000000000000001,
HTTP_POST = 0b0000000000000010,
HTTP_DELETE = 0b0000000000000100,
HTTP_PUT = 0b0000000000001000,
HTTP_PATCH = 0b0000000000010000,
HTTP_HEAD = 0b0000000000100000,
HTTP_OPTIONS = 0b0000000001000000,
HTTP_PROPFIND = 0b0000000010000000,
HTTP_LOCK = 0b0000000100000000,
HTTP_UNLOCK = 0b0000001000000000,
HTTP_PROPPATCH = 0b0000010000000000,
HTTP_MKCOL = 0b0000100000000000,
HTTP_MOVE = 0b0001000000000000,
HTTP_COPY = 0b0010000000000000,
HTTP_RESERVED = 0b0100000000000000,
HTTP_ANY = 0b0111111111111111,
};
}; // namespace AsyncWebRequestMethod
// WebRequestMethod: a single HTTP request method, taken directly from the
// platform's http_parser enum. HTTP_GET, HTTP_POST, HTTP_DELETE, HTTP_PUT,
// HTTP_PATCH, HTTP_HEAD, HTTP_OPTIONS, HTTP_PROPFIND, HTTP_LOCK, HTTP_UNLOCK,
// HTTP_PROPPATCH, HTTP_MKCOL, HTTP_MOVE, HTTP_COPY and many others are already
// defined globally by the platform headers above — no redefinition needed here.
// HTTP_ANY (= 255) is the "match any method" sentinel, also from the platform.
typedef http_method WebRequestMethod;

// WebRequestMethodComposite: a compact, allocation-free set of HTTP methods
// that a handler accepts. Internally stored as a 64-bit bitmask (one bit per
// http_method enum value, which spans 0–33 in the current llhttp spec) plus a
// single boolean sentinel for HTTP_ANY (= 255, the "match anything" value).
// A uint64_t bitmask supports up to 64 distinct enum values; the http_method
// enum currently defines 34 values (0–33), so all methods fit with room to
// spare. An empty composite (no bits set, _any == false) matches *nothing*.
// A composite with _any == true matches *any* method.
class WebRequestMethodComposite {
public:
// Empty composite = match nothing.
WebRequestMethodComposite() : _bits(0), _any(false) {}

// Single-method composite.
WebRequestMethodComposite(WebRequestMethod m) : _bits(0), _any(false) {
_set(m);
}

typedef AsyncWebRequestMethod::AsyncWebRequestMethodType WebRequestMethod;
typedef uint16_t WebRequestMethodComposite;
// Append a method.
WebRequestMethodComposite &add(WebRequestMethod m) {
_set(m);
return *this;
}

// Type-safe helper functions for composite methods
extern constexpr inline WebRequestMethodComposite operator|(WebRequestMethodComposite l, WebRequestMethod r) {
return l | static_cast<WebRequestMethodComposite>(r);
};
extern constexpr inline WebRequestMethodComposite operator|(WebRequestMethod l, WebRequestMethod r) {
return static_cast<WebRequestMethodComposite>(l) | r;
// Returns true when this composite contains (or should match) the given
// method.
bool allows(WebRequestMethod m) const {
if (_any)
return true;
if (m == HTTP_ANY)
return false; // HTTP_ANY is not a real request method; only matches when _any is set
const unsigned idx = static_cast<unsigned>(m);
return idx < 64 && (_bits & (1ULL << idx)) != 0;
}

// Equality: true when the composite holds exactly this one method.
bool operator==(WebRequestMethod m) const {
if (m == HTTP_ANY)
return _any && _bits == 0;
const unsigned idx = static_cast<unsigned>(m);
if (idx >= 64)
return false;
return !_any && _bits == (1ULL << idx);
}
bool operator!=(WebRequestMethod m) const {
return !(*this == m);
}

// True when this is an empty (match-nothing) composite.
bool empty() const {
return _bits == 0 && !_any;
}

String toString() const {
if (empty()) {
return "<>";
}
String result = "<";
bool first = true;
if (_any) {
result.concat(static_cast<int>(HTTP_ANY));
first = false;
}
for (unsigned i = 0; i < 64; ++i) {
if (_bits & (1ULL << i)) {
if (!first) {
result += ",";
}
result.concat(static_cast<int>(i));
first = false;
}
}
result.concat(">");
return result;
}

private:
uint64_t _bits;
bool _any;

void _set(WebRequestMethod m) {
if (m == HTTP_ANY) {
_any = true;
} else {
const unsigned idx = static_cast<unsigned>(m);
if (idx < 64) {
_bits |= (1ULL << idx);
}
}
}
};

#if !defined(ASYNCWEBSERVER_NO_GLOBAL_HTTP_METHODS)
// Import the method enum values to the global namespace
using namespace AsyncWebRequestMethod;
#endif
// Build a composite from two individual methods: HTTP_GET | HTTP_POST
inline WebRequestMethodComposite operator|(WebRequestMethod l, WebRequestMethod r) {
WebRequestMethodComposite c;
c.add(l).add(r);
return c;
}

// Extend a composite with one more method: (HTTP_GET | HTTP_POST) | HTTP_PUT
inline WebRequestMethodComposite operator|(WebRequestMethodComposite c, WebRequestMethod r) {
c.add(r);
return c;
}

// Membership test: returns true when composite c contains method m.
// Usage: if (handler._method & request->method()) { /* matched */ }
inline bool operator&(const WebRequestMethodComposite &c, WebRequestMethod m) {
return c.allows(m);
}
inline bool operator&(WebRequestMethod m, const WebRequestMethodComposite &c) {
return c.allows(m);
}

#ifndef HAVE_FS_FILE_OPEN_MODE
namespace fs {
Expand Down Expand Up @@ -265,7 +414,7 @@ class AsyncWebServerRequest {
uint8_t _parseState;

uint8_t _version;
WebRequestMethodComposite _method;
WebRequestMethod _method;
String _url;
String _host;
String _contentType;
Expand Down Expand Up @@ -355,7 +504,7 @@ class AsyncWebServerRequest {
uint8_t version() const {
return _version;
}
WebRequestMethodComposite method() const {
WebRequestMethod method() const {
return _method;
}
const String &url() const {
Expand All @@ -374,6 +523,7 @@ class AsyncWebServerRequest {
return _isMultipart;
}

const char *methodToString(WebRequestMethod method) const;
const char *methodToString() const;
const char *requestedConnTypeToString() const;

Expand All @@ -383,10 +533,10 @@ class AsyncWebServerRequest {
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);
return _method == HTTP_GET && isExpectedRequestedConnType(RCT_WS);
}
bool isSSE() const {
return _method == AsyncWebRequestMethod::HTTP_GET && isExpectedRequestedConnType(RCT_EVENT);
return _method == HTTP_GET && isExpectedRequestedConnType(RCT_EVENT);
}
bool isHTTP() const {
return isExpectedRequestedConnType(RCT_DEFAULT, RCT_HTTP);
Expand Down Expand Up @@ -964,6 +1114,8 @@ class AsyncURIMatcher {
#endif

private:
friend class AsyncWebServer;

// fields
String _value;
union {
Expand Down Expand Up @@ -1556,7 +1708,7 @@ class AsyncWebServer : public AsyncMiddlewareChain {
bool removeHandler(AsyncWebHandler *handler);

AsyncCallbackWebHandler &on(AsyncURIMatcher uri, ArRequestHandlerFunction onRequest) {
return on(std::move(uri), AsyncWebRequestMethod::HTTP_ANY, onRequest);
return on(std::move(uri), HTTP_ANY, onRequest);
}
AsyncCallbackWebHandler &on(
AsyncURIMatcher uri, WebRequestMethodComposite method, ArRequestHandlerFunction onRequest, ArUploadHandlerFunction onUpload = nullptr,
Expand Down
2 changes: 1 addition & 1 deletion src/Middleware.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ void AsyncCorsMiddleware::run(AsyncWebServerRequest *request, ArMiddlewareNext n
// Origin header ? => CORS handling
if (request->hasHeader(asyncsrv::T_CORS_O)) {
// check if this is a preflight request => handle it and return
if (request->method() == AsyncWebRequestMethod::HTTP_OPTIONS) {
if (request->method() == HTTP_OPTIONS) {
AsyncWebServerResponse *response = request->beginResponse(200);
addCORSHeaders(request, response);
request->send(response);
Expand Down
2 changes: 1 addition & 1 deletion src/WebHandlerImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class AsyncCallbackWebHandler : public AsyncWebHandler {
bool _isRegex;

public:
AsyncCallbackWebHandler() : _uri(), _method(AsyncWebRequestMethod::HTTP_ANY), _onRequest(NULL), _onUpload(NULL), _onBody(NULL), _isRegex(false) {}
AsyncCallbackWebHandler() : _uri(), _method(HTTP_ANY), _onRequest(NULL), _onUpload(NULL), _onBody(NULL), _isRegex(false) {}
void setUri(AsyncURIMatcher uri);
void setMethod(WebRequestMethodComposite method) {
_method = method;
Expand Down
2 changes: 1 addition & 1 deletion src/WebHandlers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ AsyncStaticWebHandler &AsyncStaticWebHandler::setLastModified() {
}

bool AsyncStaticWebHandler::canHandle(AsyncWebServerRequest *request) const {
return request->isHTTP() && request->method() == AsyncWebRequestMethod::HTTP_GET && request->url().startsWith(_uri) && _getFile(request);
return request->isHTTP() && request->method() == HTTP_GET && request->url().startsWith(_uri) && _getFile(request);
}

bool AsyncStaticWebHandler::_getFile(AsyncWebServerRequest *request) const {
Expand Down
Loading