1HTTP Parser 2=========== 3 4http-parser is [**not** actively maintained](https://github.com/nodejs/http-parser/issues/522). 5New projects and projects looking to migrate should consider [llhttp](https://github.com/nodejs/llhttp). 6 7[](https://travis-ci.org/nodejs/http-parser) 8 9This is a parser for HTTP messages written in C. It parses both requests and 10responses. The parser is designed to be used in performance HTTP 11applications. It does not make any syscalls nor allocations, it does not 12buffer data, it can be interrupted at anytime. Depending on your 13architecture, it only requires about 40 bytes of data per message 14stream (in a web server that is per connection). 15 16Features: 17 18 * No dependencies 19 * Handles persistent streams (keep-alive). 20 * Decodes chunked encoding. 21 * Upgrade support 22 * Defends against buffer overflow attacks. 23 24The parser extracts the following information from HTTP messages: 25 26 * Header fields and values 27 * Content-Length 28 * Request method 29 * Response status code 30 * Transfer-Encoding 31 * HTTP version 32 * Request URL 33 * Message body 34 35 36Usage 37----- 38 39One `http_parser` object is used per TCP connection. Initialize the struct 40using `http_parser_init()` and set the callbacks. That might look something 41like this for a request parser: 42```c 43http_parser_settings settings; 44settings.on_url = my_url_callback; 45settings.on_header_field = my_header_field_callback; 46/* ... */ 47 48http_parser *parser = malloc(sizeof(http_parser)); 49http_parser_init(parser, HTTP_REQUEST); 50parser->data = my_socket; 51``` 52 53When data is received on the socket execute the parser and check for errors. 54 55```c 56size_t len = 80*1024, nparsed; 57char buf[len]; 58ssize_t recved; 59 60recved = recv(fd, buf, len, 0); 61 62if (recved < 0) { 63 /* Handle error. */ 64} 65 66/* Start up / continue the parser. 67 * Note we pass recved==0 to signal that EOF has been received. 68 */ 69nparsed = http_parser_execute(parser, &settings, buf, recved); 70 71if (parser->upgrade) { 72 /* handle new protocol */ 73} else if (nparsed != recved) { 74 /* Handle error. Usually just close the connection. */ 75} 76``` 77 78`http_parser` needs to know where the end of the stream is. For example, sometimes 79servers send responses without Content-Length and expect the client to 80consume input (for the body) until EOF. To tell `http_parser` about EOF, give 81`0` as the fourth parameter to `http_parser_execute()`. Callbacks and errors 82can still be encountered during an EOF, so one must still be prepared 83to receive them. 84 85Scalar valued message information such as `status_code`, `method`, and the 86HTTP version are stored in the parser structure. This data is only 87temporally stored in `http_parser` and gets reset on each new message. If 88this information is needed later, copy it out of the structure during the 89`headers_complete` callback. 90 91The parser decodes the transfer-encoding for both requests and responses 92transparently. That is, a chunked encoding is decoded before being sent to 93the on_body callback. 94 95 96The Special Problem of Upgrade 97------------------------------ 98 99`http_parser` supports upgrading the connection to a different protocol. An 100increasingly common example of this is the WebSocket protocol which sends 101a request like 102 103 GET /demo HTTP/1.1 104 Upgrade: WebSocket 105 Connection: Upgrade 106 Host: example.com 107 Origin: http://example.com 108 WebSocket-Protocol: sample 109 110followed by non-HTTP data. 111 112(See [RFC6455](https://tools.ietf.org/html/rfc6455) for more information the 113WebSocket protocol.) 114 115To support this, the parser will treat this as a normal HTTP message without a 116body, issuing both on_headers_complete and on_message_complete callbacks. However 117http_parser_execute() will stop parsing at the end of the headers and return. 118 119The user is expected to check if `parser->upgrade` has been set to 1 after 120`http_parser_execute()` returns. Non-HTTP data begins at the buffer supplied 121offset by the return value of `http_parser_execute()`. 122 123 124Callbacks 125--------- 126 127During the `http_parser_execute()` call, the callbacks set in 128`http_parser_settings` will be executed. The parser maintains state and 129never looks behind, so buffering the data is not necessary. If you need to 130save certain data for later usage, you can do that from the callbacks. 131 132There are two types of callbacks: 133 134* notification `typedef int (*http_cb) (http_parser*);` 135 Callbacks: on_message_begin, on_headers_complete, on_message_complete. 136* data `typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);` 137 Callbacks: (requests only) on_url, 138 (common) on_header_field, on_header_value, on_body; 139 140Callbacks must return 0 on success. Returning a non-zero value indicates 141error to the parser, making it exit immediately. 142 143For cases where it is necessary to pass local information to/from a callback, 144the `http_parser` object's `data` field can be used. 145An example of such a case is when using threads to handle a socket connection, 146parse a request, and then give a response over that socket. By instantiation 147of a thread-local struct containing relevant data (e.g. accepted socket, 148allocated memory for callbacks to write into, etc), a parser's callbacks are 149able to communicate data between the scope of the thread and the scope of the 150callback in a threadsafe manner. This allows `http_parser` to be used in 151multi-threaded contexts. 152 153Example: 154```c 155 typedef struct { 156 socket_t sock; 157 void* buffer; 158 int buf_len; 159 } custom_data_t; 160 161 162int my_url_callback(http_parser* parser, const char *at, size_t length) { 163 /* access to thread local custom_data_t struct. 164 Use this access save parsed data for later use into thread local 165 buffer, or communicate over socket 166 */ 167 parser->data; 168 ... 169 return 0; 170} 171 172... 173 174void http_parser_thread(socket_t sock) { 175 int nparsed = 0; 176 /* allocate memory for user data */ 177 custom_data_t *my_data = malloc(sizeof(custom_data_t)); 178 179 /* some information for use by callbacks. 180 * achieves thread -> callback information flow */ 181 my_data->sock = sock; 182 183 /* instantiate a thread-local parser */ 184 http_parser *parser = malloc(sizeof(http_parser)); 185 http_parser_init(parser, HTTP_REQUEST); /* initialise parser */ 186 /* this custom data reference is accessible through the reference to the 187 parser supplied to callback functions */ 188 parser->data = my_data; 189 190 http_parser_settings settings; /* set up callbacks */ 191 settings.on_url = my_url_callback; 192 193 /* execute parser */ 194 nparsed = http_parser_execute(parser, &settings, buf, recved); 195 196 ... 197 /* parsed information copied from callback. 198 can now perform action on data copied into thread-local memory from callbacks. 199 achieves callback -> thread information flow */ 200 my_data->buffer; 201 ... 202} 203 204``` 205 206In case you parse HTTP message in chunks (i.e. `read()` request line 207from socket, parse, read half headers, parse, etc) your data callbacks 208may be called more than once. `http_parser` guarantees that data pointer is only 209valid for the lifetime of callback. You can also `read()` into a heap allocated 210buffer to avoid copying memory around if this fits your application. 211 212Reading headers may be a tricky task if you read/parse headers partially. 213Basically, you need to remember whether last header callback was field or value 214and apply the following logic: 215 216 (on_header_field and on_header_value shortened to on_h_*) 217 ------------------------ ------------ -------------------------------------------- 218 | State (prev. callback) | Callback | Description/action | 219 ------------------------ ------------ -------------------------------------------- 220 | nothing (first call) | on_h_field | Allocate new buffer and copy callback data | 221 | | | into it | 222 ------------------------ ------------ -------------------------------------------- 223 | value | on_h_field | New header started. | 224 | | | Copy current name,value buffers to headers | 225 | | | list and allocate new buffer for new name | 226 ------------------------ ------------ -------------------------------------------- 227 | field | on_h_field | Previous name continues. Reallocate name | 228 | | | buffer and append callback data to it | 229 ------------------------ ------------ -------------------------------------------- 230 | field | on_h_value | Value for current header started. Allocate | 231 | | | new buffer and copy callback data to it | 232 ------------------------ ------------ -------------------------------------------- 233 | value | on_h_value | Value continues. Reallocate value buffer | 234 | | | and append callback data to it | 235 ------------------------ ------------ -------------------------------------------- 236 237 238Parsing URLs 239------------ 240 241A simplistic zero-copy URL parser is provided as `http_parser_parse_url()`. 242Users of this library may wish to use it to parse URLs constructed from 243consecutive `on_url` callbacks. 244 245See examples of reading in headers: 246 247* [partial example](http://gist.github.com/155877) in C 248* [from http-parser tests](http://github.com/joyent/http-parser/blob/37a0ff8/test.c#L403) in C 249* [from Node library](http://github.com/joyent/node/blob/842eaf4/src/http.js#L284) in Javascript 250