|
3 | 3 |
|
4 | 4 | #include <ESPAsyncWebServer.h> |
5 | 5 |
|
6 | | -AsyncWebHeader::AsyncWebHeader(const String &data) { |
| 6 | +const AsyncWebHeader AsyncWebHeader::parse(const char *data) { |
| 7 | + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers |
| 8 | + // In HTTP/1.X, a header is a case-insensitive name followed by a colon, then optional whitespace which will be ignored, and finally by its value |
7 | 9 | if (!data) { |
8 | | - return; |
| 10 | + return AsyncWebHeader(); // nullptr |
9 | 11 | } |
10 | | - int index = data.indexOf(':'); |
11 | | - if (index < 0) { |
12 | | - return; |
| 12 | + if (data[0] == '\0') { |
| 13 | + return AsyncWebHeader(); // empty string |
13 | 14 | } |
14 | | - if (data.indexOf('\r') >= 0 || data.indexOf('\n') >= 0) { |
15 | | -// Note: do not log as info, warn or error because this could flood the logs without being able to filter this out |
16 | | -#ifdef ESP32 |
17 | | - log_v("Invalid character in HTTP header"); |
18 | | -#endif |
19 | | - return; // Invalid header format |
| 15 | + if (strchr(data, '\n') || strchr(data, '\r')) { |
| 16 | + return AsyncWebHeader(); // Invalid header format |
20 | 17 | } |
21 | | - _name = data.substring(0, index); |
22 | | - _value = data.substring(index + 2); |
23 | | -} |
24 | | - |
25 | | -String AsyncWebHeader::toString() const { |
26 | | - String str; |
27 | | - if (str.reserve(_name.length() + _value.length() + 2)) { |
28 | | - str.concat(_name); |
29 | | - str.concat((char)0x3a); |
30 | | - str.concat((char)0x20); |
31 | | - str.concat(_value); |
32 | | - str.concat(asyncsrv::T_rn); |
33 | | - } else { |
34 | | -#ifdef ESP32 |
35 | | - log_e("Failed to allocate"); |
36 | | -#endif |
| 18 | + char *colon = strchr(data, ':'); |
| 19 | + if (!colon) { |
| 20 | + return AsyncWebHeader(); // separator not found |
| 21 | + } |
| 22 | + if (colon == data) { |
| 23 | + return AsyncWebHeader(); // Header name cannot be empty |
| 24 | + } |
| 25 | + char *startOfValue = colon + 1; // Skip the colon |
| 26 | + // skip one optional whitespace after the colon |
| 27 | + if (*startOfValue == ' ') { |
| 28 | + startOfValue++; |
37 | 29 | } |
38 | | - return str; |
| 30 | + String name; |
| 31 | + name.reserve(colon - data); |
| 32 | + name.concat(data, colon - data); |
| 33 | + return AsyncWebHeader(name, String(startOfValue)); |
39 | 34 | } |
0 commit comments