Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Nov 6, 2022. It is now read-only.
/http-parserPublic archive

http request/response parser for c

License

NotificationsYou must be signed in to change notification settings

nodejs/http-parser

Repository files navigation

http-parser isnot actively maintained.New projects and projects looking to migrate should considerllhttp.

Build Status

This is a parser for HTTP messages written in C. It parses both requests andresponses. The parser is designed to be used in performance HTTPapplications. It does not make any syscalls nor allocations, it does notbuffer data, it can be interrupted at anytime. Depending on yourarchitecture, it only requires about 40 bytes of data per messagestream (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

Onehttp_parser object is used per TCP connection. Initialize the structusinghttp_parser_init() and set the callbacks. That might look somethinglike this for a request parser:

http_parser_settingssettings;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_tlen=80*1024,nparsed;charbuf[len];ssize_trecved;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 */}elseif (nparsed!=recved) {/* Handle error. Usually just close the connection. */}

http_parser needs to know where the end of the stream is. For example, sometimesservers send responses without Content-Length and expect the client toconsume input (for the body) until EOF. To tellhttp_parser about EOF, give0 as the fourth parameter tohttp_parser_execute(). Callbacks and errorscan still be encountered during an EOF, so one must still be preparedto receive them.

Scalar valued message information such asstatus_code,method, and theHTTP version are stored in the parser structure. This data is onlytemporally stored inhttp_parser and gets reset on each new message. Ifthis information is needed later, copy it out of the structure during theheaders_complete callback.

The parser decodes the transfer-encoding for both requests and responsestransparently. That is, a chunked encoding is decoded before being sent tothe on_body callback.

The Special Problem of Upgrade

http_parser supports upgrading the connection to a different protocol. Anincreasingly common example of this is the WebSocket protocol which sendsa 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.

(SeeRFC6455 for more information theWebSocket protocol.)

To support this, the parser will treat this as a normal HTTP message without abody, issuing both on_headers_complete and on_message_complete callbacks. Howeverhttp_parser_execute() will stop parsing at the end of the headers and return.

The user is expected to check ifparser->upgrade has been set to 1 afterhttp_parser_execute() returns. Non-HTTP data begins at the buffer suppliedoffset by the return value ofhttp_parser_execute().

Callbacks

During thehttp_parser_execute() call, the callbacks set inhttp_parser_settings will be executed. The parser maintains state andnever looks behind, so buffering the data is not necessary. If you need tosave certain data for later usage, you can do that from the callbacks.

There are two types of callbacks:

  • notificationtypedef int (*http_cb) (http_parser*);Callbacks: on_message_begin, on_headers_complete, on_message_complete.
  • datatypedef 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 indicateserror to the parser, making it exit immediately.

For cases where it is necessary to pass local information to/from a callback,thehttp_parser object'sdata 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 instantiationof a thread-local struct containing relevant data (e.g. accepted socket,allocated memory for callbacks to write into, etc), a parser's callbacks areable to communicate data between the scope of the thread and the scope of thecallback in a threadsafe manner. This allowshttp_parser to be used inmulti-threaded contexts.

Example:

typedefstruct {socket_tsock;void*buffer;intbuf_len; }custom_data_t;intmy_url_callback(http_parser*parser,constchar*at,size_tlength) {/* 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;  ...return0;}...voidhttp_parser_thread(socket_tsock) {intnparsed=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_settingssettings;/* 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 linefrom socket, parse, read half headers, parse, etc) your data callbacksmay be called more than once.http_parser guarantees that data pointer is onlyvalid for the lifetime of callback. You can alsoread() into a heap allocatedbuffer 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 valueand 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 ashttp_parser_parse_url().Users of this library may wish to use it to parse URLs constructed fromconsecutiveon_url callbacks.

See examples of reading in headers:

About

http request/response parser for c

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Sponsor this project

  •  

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp