fd65b0f src: refactor method parsing 678a9e2 test: Assert against correct error messages e2e467b Update http-parser to 2.6.1 4e382f9 readme: fix build status badge bee4817 Bump version to 2.6.0 777ba4e src: introduce `http_parser_url_init` 483eca7 doc: updated README.md to include multi-threading example e557b62 src: support LINK/UNLINK (RFC 2068, draft-snell-link-method) e01811e src: fixed compile error C2143 for vs2012 b36c2a9 header: treat Wine like MinGW eb5e992 src: support ACL (WebDAV, RFC3744, Section 8.1). 4f69be2 readme: update WebSocket link to RFC6455 b5bcca8 test: `SEARCH`, `PURGE` and `MKCALENDAR` 8b1d652 src: support BIND/REBIND/UNBIND (WebDAV, RFC5842) 7d75dd7 src: support IPv6 Zone ID as per RFC 6874 ab0b162 src: use ARRAY_SIZE instead of sizeof() 39ff097 src: remove double check f6f436a src: fix invalid memory access in http_parse_host 2896229 make: fix dynamic library extension for OS X 39c2c1e Bump version to 2.5.0 dff604d src: support body in Upgrade requests d767545 src: callbacks chunk boundaries: header/complete 2872cb7 test: regression test for incomplete/corrupted hdr 5d414fc makefile: add un/install targets d547f3b url_parser: remove mixed declarations 7ecf775 src: partially revert 959f4cb to fix nread value 7ba3123 header: fix field sizes 53063b7 Add function to initialize http_parser_settings 1b31580 Bump version to 2.4.2 59569f2 src: skip lws between `connection` values 36f107f Bump version to 2.4.1 280af69 src: fix build on MSVC 956c8a0 Bump version to 2.4.0 167dcdf readme: fix typo 3f7ef50 src: annotate with likely/unlikely 265f9d0 bench: add chunked bytes 091ebb8 src: simple Connection header multi-value parsing 959f4cb src: remove reexecute goto 0097de5 src: use memchr() in h_general header value c6097e1 src: faster general header value loop 2630060 src: less loads in header_value loop 0cb0ee6 src: tighten header field/value loops 6132d1f src: save progress 3f1a05a benchmark: initial 94a55d1 send travis irc notifications to #node-ci 5fd51fd Fix warning on test suite found by Clang Analyzer 0b43367 http_parser: Follow RFC-7230 Sec 3.2.4 11ecb42 Docs fix 7bbb774 doc: add very basic docs for `http_parser_execute` 17ed7de header: typo fix in a comment 5b951d7 src: fix clang warning 1317eec Added support for MKCALENDAR 08a2cc3 very minor spelling/grammar changes in README.md 158dd3b signing the CLA is no longer a requirement 8d9e5db fix typo in README comment d19e129 contrib: fixed resource leak in parsertrace 24e2d2d Allow HTTP_MAX_HEADER_SIZE to be defined externally 56f7ad0 Bump version to 2.3.0 76f0f16 Fix issues around multi-line headers 5d9c382 Include separating ws when folding header values git-subtree-dir: src/beast/beast/http/impl/http-parser git-subtree-split: fd65b0fbbdb405425a14d0e49f5366667550b1c2
9.1 KiB
HTTP Parser
This is a parser for HTTP messages written in C. It parses both requests and responses. The parser is designed to be used in performance HTTP applications. It does not make any syscalls nor allocations, it does not buffer data, it can be interrupted at anytime. Depending on your architecture, it only requires about 40 bytes of data per message stream (in a web server that is per connection).
Features:
- No dependencies
- Handles persistent streams (keep-alive).
- Decodes chunked encoding.
- Upgrade support
- Defends against buffer overflow attacks.
The parser extracts the following information from HTTP messages:
- Header fields and values
- Content-Length
- Request method
- Response status code
- Transfer-Encoding
- HTTP version
- Request URL
- Message body
Usage
One http_parser object is used per TCP connection. Initialize the struct
using http_parser_init() and set the callbacks. That might look something
like this for a request parser:
http_parser_settings settings;
settings.on_url = my_url_callback;
settings.on_header_field = my_header_field_callback;
/* ... */
http_parser *parser = malloc(sizeof(http_parser));
http_parser_init(parser, HTTP_REQUEST);
parser->data = my_socket;
When data is received on the socket execute the parser and check for errors.
size_t len = 80*1024, nparsed;
char buf[len];
ssize_t recved;
recved = recv(fd, buf, len, 0);
if (recved < 0) {
/* Handle error. */
}
/* Start up / continue the parser.
* Note we pass recved==0 to signal that EOF has been received.
*/
nparsed = http_parser_execute(parser, &settings, buf, recved);
if (parser->upgrade) {
/* handle new protocol */
} else if (nparsed != recved) {
/* Handle error. Usually just close the connection. */
}
HTTP needs to know where the end of the stream is. For example, sometimes
servers send responses without Content-Length and expect the client to
consume input (for the body) until EOF. To tell http_parser about EOF, give
0 as the fourth parameter to http_parser_execute(). Callbacks and errors
can still be encountered during an EOF, so one must still be prepared
to receive them.
Scalar valued message information such as status_code, method, and the
HTTP version are stored in the parser structure. This data is only
temporally stored in http_parser and gets reset on each new message. If
this information is needed later, copy it out of the structure during the
headers_complete callback.
The parser decodes the transfer-encoding for both requests and responses transparently. That is, a chunked encoding is decoded before being sent to the on_body callback.
The Special Problem of Upgrade
HTTP supports upgrading the connection to a different protocol. An increasingly common example of this is the WebSocket protocol which sends a request like
GET /demo HTTP/1.1
Upgrade: WebSocket
Connection: Upgrade
Host: example.com
Origin: http://example.com
WebSocket-Protocol: sample
followed by non-HTTP data.
(See RFC6455 for more information the WebSocket protocol.)
To support this, the parser will treat this as a normal HTTP message without a body, issuing both on_headers_complete and on_message_complete callbacks. However http_parser_execute() will stop parsing at the end of the headers and return.
The user is expected to check if parser->upgrade has been set to 1 after
http_parser_execute() returns. Non-HTTP data begins at the buffer supplied
offset by the return value of http_parser_execute().
Callbacks
During the http_parser_execute() call, the callbacks set in
http_parser_settings will be executed. The parser maintains state and
never looks behind, so buffering the data is not necessary. If you need to
save certain data for later usage, you can do that from the callbacks.
There are two types of callbacks:
- notification
typedef int (*http_cb) (http_parser*);Callbacks: on_message_begin, on_headers_complete, on_message_complete. - data
typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);Callbacks: (requests only) on_url, (common) on_header_field, on_header_value, on_body;
Callbacks must return 0 on success. Returning a non-zero value indicates error to the parser, making it exit immediately.
For cases where it is necessary to pass local information to/from a callback,
the http_parser object's data field can be used.
An example of such a case is when using threads to handle a socket connection,
parse a request, and then give a response over that socket. By instantiation
of a thread-local struct containing relevant data (e.g. accepted socket,
allocated memory for callbacks to write into, etc), a parser's callbacks are
able to communicate data between the scope of the thread and the scope of the
callback in a threadsafe manner. This allows http-parser to be used in
multi-threaded contexts.
Example:
typedef struct {
socket_t sock;
void* buffer;
int buf_len;
} custom_data_t;
int my_url_callback(http_parser* parser, const char *at, size_t length) {
/* access to thread local custom_data_t struct.
Use this access save parsed data for later use into thread local
buffer, or communicate over socket
*/
parser->data;
...
return 0;
}
...
void http_parser_thread(socket_t sock) {
int nparsed = 0;
/* allocate memory for user data */
custom_data_t *my_data = malloc(sizeof(custom_data_t));
/* some information for use by callbacks.
* achieves thread -> callback information flow */
my_data->sock = sock;
/* instantiate a thread-local parser */
http_parser *parser = malloc(sizeof(http_parser));
http_parser_init(parser, HTTP_REQUEST); /* initialise parser */
/* this custom data reference is accessible through the reference to the
parser supplied to callback functions */
parser->data = my_data;
http_parser_settings settings; / * set up callbacks */
settings.on_url = my_url_callback;
/* execute parser */
nparsed = http_parser_execute(parser, &settings, buf, recved);
...
/* parsed information copied from callback.
can now perform action on data copied into thread-local memory from callbacks.
achieves callback -> thread information flow */
my_data->buffer;
...
}
In case you parse HTTP message in chunks (i.e. read() request line
from socket, parse, read half headers, parse, etc) your data callbacks
may be called more than once. Http-parser guarantees that data pointer is only
valid for the lifetime of callback. You can also read() into a heap allocated
buffer to avoid copying memory around if this fits your application.
Reading headers may be a tricky task if you read/parse headers partially. Basically, you need to remember whether last header callback was field or value and apply the following logic:
(on_header_field and on_header_value shortened to on_h_*)
------------------------ ------------ --------------------------------------------
| State (prev. callback) | Callback | Description/action |
------------------------ ------------ --------------------------------------------
| nothing (first call) | on_h_field | Allocate new buffer and copy callback data |
| | | into it |
------------------------ ------------ --------------------------------------------
| value | on_h_field | New header started. |
| | | Copy current name,value buffers to headers |
| | | list and allocate new buffer for new name |
------------------------ ------------ --------------------------------------------
| field | on_h_field | Previous name continues. Reallocate name |
| | | buffer and append callback data to it |
------------------------ ------------ --------------------------------------------
| field | on_h_value | Value for current header started. Allocate |
| | | new buffer and copy callback data to it |
------------------------ ------------ --------------------------------------------
| value | on_h_value | Value continues. Reallocate value buffer |
| | | and append callback data to it |
------------------------ ------------ --------------------------------------------
Parsing URLs
A simplistic zero-copy URL parser is provided as http_parser_parse_url().
Users of this library may wish to use it to parse URLs constructed from
consecutive on_url callbacks.
See examples of reading in headers:
- partial example in C
- from http-parser tests in C
- from Node library in Javascript