4 [![Build Status](https://travis-ci.org/joyent/http-parser.png?branch=master)](https://travis-ci.org/joyent/http-parser)
6 This is a parser for HTTP messages written in C. It parses both requests and
7 responses. The parser is designed to be used in performance HTTP
8 applications. It does not make any syscalls nor allocations, it does not
9 buffer data, it can be interrupted at anytime. Depending on your
10 architecture, it only requires about 40 bytes of data per message
11 stream (in a web server that is per connection).
16 * Handles persistent streams (keep-alive).
17 * Decodes chunked encoding.
19 * Defends against buffer overflow attacks.
21 The parser extracts the following information from HTTP messages:
23 * Header fields and values
26 * Response status code
36 One `http_parser` object is used per TCP connection. Initialize the struct
37 using `http_parser_init()` and set the callbacks. That might look something
38 like this for a request parser:
40 http_parser_settings settings;
41 settings.on_url = my_url_callback;
42 settings.on_header_field = my_header_field_callback;
45 http_parser *parser = malloc(sizeof(http_parser));
46 http_parser_init(parser, HTTP_REQUEST);
47 parser->data = my_socket;
50 When data is received on the socket execute the parser and check for errors.
53 size_t len = 80*1024, nparsed;
57 recved = recv(fd, buf, len, 0);
63 /* Start up / continue the parser.
64 * Note we pass recved==0 to signal that EOF has been received.
66 nparsed = http_parser_execute(parser, &settings, buf, recved);
68 if (parser->upgrade) {
69 /* handle new protocol */
70 } else if (nparsed != recved) {
71 /* Handle error. Usually just close the connection. */
75 HTTP needs to know where the end of the stream is. For example, sometimes
76 servers send responses without Content-Length and expect the client to
77 consume input (for the body) until EOF. To tell http_parser about EOF, give
78 `0` as the fourth parameter to `http_parser_execute()`. Callbacks and errors
79 can still be encountered during an EOF, so one must still be prepared
82 Scalar valued message information such as `status_code`, `method`, and the
83 HTTP version are stored in the parser structure. This data is only
84 temporally stored in `http_parser` and gets reset on each new message. If
85 this information is needed later, copy it out of the structure during the
86 `headers_complete` callback.
88 The parser decodes the transfer-encoding for both requests and responses
89 transparently. That is, a chunked encoding is decoded before being sent to
93 The Special Problem of Upgrade
94 ------------------------------
96 HTTP supports upgrading the connection to a different protocol. An
97 increasingly common example of this is the Web Socket protocol which sends
104 Origin: http://example.com
105 WebSocket-Protocol: sample
107 followed by non-HTTP data.
109 (See http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75 for more
110 information the Web Socket protocol.)
112 To support this, the parser will treat this as a normal HTTP message without a
113 body, issuing both on_headers_complete and on_message_complete callbacks. However
114 http_parser_execute() will stop parsing at the end of the headers and return.
116 The user is expected to check if `parser->upgrade` has been set to 1 after
117 `http_parser_execute()` returns. Non-HTTP data begins at the buffer supplied
118 offset by the return value of `http_parser_execute()`.
124 During the `http_parser_execute()` call, the callbacks set in
125 `http_parser_settings` will be executed. The parser maintains state and
126 never looks behind, so buffering the data is not necessary. If you need to
127 save certain data for later usage, you can do that from the callbacks.
129 There are two types of callbacks:
131 * notification `typedef int (*http_cb) (http_parser*);`
132 Callbacks: on_message_begin, on_headers_complete, on_message_complete.
133 * data `typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);`
134 Callbacks: (requests only) on_url,
135 (common) on_header_field, on_header_value, on_body;
137 Callbacks must return 0 on success. Returning a non-zero value indicates
138 error to the parser, making it exit immediately.
140 In case you parse HTTP message in chunks (i.e. `read()` request line
141 from socket, parse, read half headers, parse, etc) your data callbacks
142 may be called more than once. Http-parser guarantees that data pointer is only
143 valid for the lifetime of callback. You can also `read()` into a heap allocated
144 buffer to avoid copying memory around if this fits your application.
146 Reading headers may be a tricky task if you read/parse headers partially.
147 Basically, you need to remember whether last header callback was field or value
148 and apply the following logic:
150 (on_header_field and on_header_value shortened to on_h_*)
151 ------------------------ ------------ --------------------------------------------
152 | State (prev. callback) | Callback | Description/action |
153 ------------------------ ------------ --------------------------------------------
154 | nothing (first call) | on_h_field | Allocate new buffer and copy callback data |
156 ------------------------ ------------ --------------------------------------------
157 | value | on_h_field | New header started. |
158 | | | Copy current name,value buffers to headers |
159 | | | list and allocate new buffer for new name |
160 ------------------------ ------------ --------------------------------------------
161 | field | on_h_field | Previous name continues. Reallocate name |
162 | | | buffer and append callback data to it |
163 ------------------------ ------------ --------------------------------------------
164 | field | on_h_value | Value for current header started. Allocate |
165 | | | new buffer and copy callback data to it |
166 ------------------------ ------------ --------------------------------------------
167 | value | on_h_value | Value continues. Reallocate value buffer |
168 | | | and append callback data to it |
169 ------------------------ ------------ --------------------------------------------
175 A simplistic zero-copy URL parser is provided as `http_parser_parse_url()`.
176 Users of this library may wish to use it to parse URLs constructed from
177 consecutive `on_url` callbacks.
179 See examples of reading in headers:
181 * [partial example](http://gist.github.com/155877) in C
182 * [from http-parser tests](http://github.com/joyent/http-parser/blob/37a0ff8/test.c#L403) in C
183 * [from Node library](http://github.com/joyent/node/blob/842eaf4/src/http.js#L284) in Javascript