{"id":13429706,"url":"https://github.com/nodejs/http-parser","last_synced_at":"2025-12-16T18:08:57.155Z","repository":{"id":556041,"uuid":"186749","full_name":"nodejs/http-parser","owner":"nodejs","description":"http request/response parser for c","archived":true,"fork":false,"pushed_at":"2022-06-19T08:11:39.000Z","size":821,"stargazers_count":6344,"open_issues_count":80,"forks_count":1535,"subscribers_count":346,"default_branch":"main","last_synced_at":"2024-10-29T17:34:04.753Z","etag":null,"topics":["node","nodejs"],"latest_commit_sha":null,"homepage":"","language":"C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nodejs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE-MIT","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2009-04-27T15:09:51.000Z","updated_at":"2024-10-27T01:59:30.000Z","dependencies_parsed_at":"2022-07-08T07:50:51.419Z","dependency_job_id":null,"html_url":"https://github.com/nodejs/http-parser","commit_stats":null,"previous_names":["joyent/http-parser"],"tags_count":26,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nodejs%2Fhttp-parser","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nodejs%2Fhttp-parser/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nodejs%2Fhttp-parser/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nodejs%2Fhttp-parser/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nodejs","download_url":"https://codeload.github.com/nodejs/http-parser/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":234892010,"owners_count":18902873,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["node","nodejs"],"created_at":"2024-07-31T02:00:43.982Z","updated_at":"2025-10-03T20:31:14.493Z","avatar_url":"https://github.com/nodejs.png","language":"C","readme":"HTTP Parser\n===========\n\nhttp-parser is [**not** actively maintained](https://github.com/nodejs/http-parser/issues/522).\nNew projects and projects looking to migrate should consider [llhttp](https://github.com/nodejs/llhttp).\n\n[![Build Status](https://api.travis-ci.org/nodejs/http-parser.svg?branch=master)](https://travis-ci.org/nodejs/http-parser)\n\nThis is a parser for HTTP messages written in C. It parses both requests and\nresponses. The parser is designed to be used in performance HTTP\napplications. It does not make any syscalls nor allocations, it does not\nbuffer data, it can be interrupted at anytime. Depending on your\narchitecture, it only requires about 40 bytes of data per message\nstream (in a web server that is per connection).\n\nFeatures:\n\n  * No dependencies\n  * Handles persistent streams (keep-alive).\n  * Decodes chunked encoding.\n  * Upgrade support\n  * Defends against buffer overflow attacks.\n\nThe parser extracts the following information from HTTP messages:\n\n  * Header fields and values\n  * Content-Length\n  * Request method\n  * Response status code\n  * Transfer-Encoding\n  * HTTP version\n  * Request URL\n  * Message body\n\n\nUsage\n-----\n\nOne `http_parser` object is used per TCP connection. Initialize the struct\nusing `http_parser_init()` and set the callbacks. That might look something\nlike this for a request parser:\n```c\nhttp_parser_settings settings;\nsettings.on_url = my_url_callback;\nsettings.on_header_field = my_header_field_callback;\n/* ... */\n\nhttp_parser *parser = malloc(sizeof(http_parser));\nhttp_parser_init(parser, HTTP_REQUEST);\nparser-\u003edata = my_socket;\n```\n\nWhen data is received on the socket execute the parser and check for errors.\n\n```c\nsize_t len = 80*1024, nparsed;\nchar buf[len];\nssize_t recved;\n\nrecved = recv(fd, buf, len, 0);\n\nif (recved \u003c 0) {\n  /* Handle error. */\n}\n\n/* Start up / continue the parser.\n * Note we pass recved==0 to signal that EOF has been received.\n */\nnparsed = http_parser_execute(parser, \u0026settings, buf, recved);\n\nif (parser-\u003eupgrade) {\n  /* handle new protocol */\n} else if (nparsed != recved) {\n  /* Handle error. Usually just close the connection. */\n}\n```\n\n`http_parser` needs to know where the end of the stream is. For example, sometimes\nservers send responses without Content-Length and expect the client to\nconsume input (for the body) until EOF. To tell `http_parser` about EOF, give\n`0` as the fourth parameter to `http_parser_execute()`. Callbacks and errors\ncan still be encountered during an EOF, so one must still be prepared\nto receive them.\n\nScalar valued message information such as `status_code`, `method`, and the\nHTTP version are stored in the parser structure. This data is only\ntemporally stored in `http_parser` and gets reset on each new message. If\nthis information is needed later, copy it out of the structure during the\n`headers_complete` callback.\n\nThe parser decodes the transfer-encoding for both requests and responses\ntransparently. That is, a chunked encoding is decoded before being sent to\nthe on_body callback.\n\n\nThe Special Problem of Upgrade\n------------------------------\n\n`http_parser` supports upgrading the connection to a different protocol. An\nincreasingly common example of this is the WebSocket protocol which sends\na request like\n\n        GET /demo HTTP/1.1\n        Upgrade: WebSocket\n        Connection: Upgrade\n        Host: example.com\n        Origin: http://example.com\n        WebSocket-Protocol: sample\n\nfollowed by non-HTTP data.\n\n(See [RFC6455](https://tools.ietf.org/html/rfc6455) for more information the\nWebSocket protocol.)\n\nTo support this, the parser will treat this as a normal HTTP message without a\nbody, issuing both on_headers_complete and on_message_complete callbacks. However\nhttp_parser_execute() will stop parsing at the end of the headers and return.\n\nThe user is expected to check if `parser-\u003eupgrade` has been set to 1 after\n`http_parser_execute()` returns. Non-HTTP data begins at the buffer supplied\noffset by the return value of `http_parser_execute()`.\n\n\nCallbacks\n---------\n\nDuring the `http_parser_execute()` call, the callbacks set in\n`http_parser_settings` will be executed. The parser maintains state and\nnever looks behind, so buffering the data is not necessary. If you need to\nsave certain data for later usage, you can do that from the callbacks.\n\nThere are two types of callbacks:\n\n* notification `typedef int (*http_cb) (http_parser*);`\n    Callbacks: on_message_begin, on_headers_complete, on_message_complete.\n* data `typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);`\n    Callbacks: (requests only) on_url,\n               (common) on_header_field, on_header_value, on_body;\n\nCallbacks must return 0 on success. Returning a non-zero value indicates\nerror to the parser, making it exit immediately.\n\nFor cases where it is necessary to pass local information to/from a callback,\nthe `http_parser` object's `data` field can be used.\nAn example of such a case is when using threads to handle a socket connection,\nparse a request, and then give a response over that socket. By instantiation\nof a thread-local struct containing relevant data (e.g. accepted socket,\nallocated memory for callbacks to write into, etc), a parser's callbacks are\nable to communicate data between the scope of the thread and the scope of the\ncallback in a threadsafe manner. This allows `http_parser` to be used in\nmulti-threaded contexts.\n\nExample:\n```c\n typedef struct {\n  socket_t sock;\n  void* buffer;\n  int buf_len;\n } custom_data_t;\n\n\nint my_url_callback(http_parser* parser, const char *at, size_t length) {\n  /* access to thread local custom_data_t struct.\n  Use this access save parsed data for later use into thread local\n  buffer, or communicate over socket\n  */\n  parser-\u003edata;\n  ...\n  return 0;\n}\n\n...\n\nvoid http_parser_thread(socket_t sock) {\n int nparsed = 0;\n /* allocate memory for user data */\n custom_data_t *my_data = malloc(sizeof(custom_data_t));\n\n /* some information for use by callbacks.\n * achieves thread -\u003e callback information flow */\n my_data-\u003esock = sock;\n\n /* instantiate a thread-local parser */\n http_parser *parser = malloc(sizeof(http_parser));\n http_parser_init(parser, HTTP_REQUEST); /* initialise parser */\n /* this custom data reference is accessible through the reference to the\n parser supplied to callback functions */\n parser-\u003edata = my_data;\n\n http_parser_settings settings; /* set up callbacks */\n settings.on_url = my_url_callback;\n\n /* execute parser */\n nparsed = http_parser_execute(parser, \u0026settings, buf, recved);\n\n ...\n /* parsed information copied from callback.\n can now perform action on data copied into thread-local memory from callbacks.\n achieves callback -\u003e thread information flow */\n my_data-\u003ebuffer;\n ...\n}\n\n```\n\nIn case you parse HTTP message in chunks (i.e. `read()` request line\nfrom socket, parse, read half headers, parse, etc) your data callbacks\nmay be called more than once. `http_parser` guarantees that data pointer is only\nvalid for the lifetime of callback. You can also `read()` into a heap allocated\nbuffer to avoid copying memory around if this fits your application.\n\nReading headers may be a tricky task if you read/parse headers partially.\nBasically, you need to remember whether last header callback was field or value\nand apply the following logic:\n\n    (on_header_field and on_header_value shortened to on_h_*)\n     ------------------------ ------------ --------------------------------------------\n    | State (prev. callback) | Callback   | Description/action                         |\n     ------------------------ ------------ --------------------------------------------\n    | nothing (first call)   | on_h_field | Allocate new buffer and copy callback data |\n    |                        |            | into it                                    |\n     ------------------------ ------------ --------------------------------------------\n    | value                  | on_h_field | New header started.                        |\n    |                        |            | Copy current name,value buffers to headers |\n    |                        |            | list and allocate new buffer for new name  |\n     ------------------------ ------------ --------------------------------------------\n    | field                  | on_h_field | Previous name continues. Reallocate name   |\n    |                        |            | buffer and append callback data to it      |\n     ------------------------ ------------ --------------------------------------------\n    | field                  | on_h_value | Value for current header started. Allocate |\n    |                        |            | new buffer and copy callback data to it    |\n     ------------------------ ------------ --------------------------------------------\n    | value                  | on_h_value | Value continues. Reallocate value buffer   |\n    |                        |            | and append callback data to it             |\n     ------------------------ ------------ --------------------------------------------\n\n\nParsing URLs\n------------\n\nA simplistic zero-copy URL parser is provided as `http_parser_parse_url()`.\nUsers of this library may wish to use it to parse URLs constructed from\nconsecutive `on_url` callbacks.\n\nSee examples of reading in headers:\n\n* [partial example](http://gist.github.com/155877) in C\n* [from http-parser tests](http://github.com/joyent/http-parser/blob/37a0ff8/test.c#L403) in C\n* [from Node library](http://github.com/joyent/node/blob/842eaf4/src/http.js#L284) in Javascript\n","funding_links":[],"categories":["C","Networking","内存分配","Networking and Internet ##"],"sub_categories":["网络","Physical ###"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnodejs%2Fhttp-parser","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnodejs%2Fhttp-parser","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnodejs%2Fhttp-parser/lists"}