PageRenderTime 45ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/deps/http_parser/README.md

http://github.com/joyent/node
Markdown | 178 lines | 137 code | 41 blank | 0 comment | 0 complexity | 038ac7889a412803d39a1abe57c77fc7 MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause, MPL-2.0-no-copyleft-exception, GPL-2.0, ISC, Apache-2.0, MIT, AGPL-3.0
  1. HTTP Parser
  2. ===========
  3. This is a parser for HTTP messages written in C. It parses both requests and
  4. responses. The parser is designed to be used in performance HTTP
  5. applications. It does not make any syscalls nor allocations, it does not
  6. buffer data, it can be interrupted at anytime. Depending on your
  7. architecture, it only requires about 40 bytes of data per message
  8. stream (in a web server that is per connection).
  9. Features:
  10. * No dependencies
  11. * Handles persistent streams (keep-alive).
  12. * Decodes chunked encoding.
  13. * Upgrade support
  14. * Defends against buffer overflow attacks.
  15. The parser extracts the following information from HTTP messages:
  16. * Header fields and values
  17. * Content-Length
  18. * Request method
  19. * Response status code
  20. * Transfer-Encoding
  21. * HTTP version
  22. * Request URL
  23. * Message body
  24. Usage
  25. -----
  26. One `http_parser` object is used per TCP connection. Initialize the struct
  27. using `http_parser_init()` and set the callbacks. That might look something
  28. like this for a request parser:
  29. http_parser_settings settings;
  30. settings.on_path = my_path_callback;
  31. settings.on_header_field = my_header_field_callback;
  32. /* ... */
  33. http_parser *parser = malloc(sizeof(http_parser));
  34. http_parser_init(parser, HTTP_REQUEST);
  35. parser->data = my_socket;
  36. When data is received on the socket execute the parser and check for errors.
  37. size_t len = 80*1024, nparsed;
  38. char buf[len];
  39. ssize_t recved;
  40. recved = recv(fd, buf, len, 0);
  41. if (recved < 0) {
  42. /* Handle error. */
  43. }
  44. /* Start up / continue the parser.
  45. * Note we pass recved==0 to signal that EOF has been recieved.
  46. */
  47. nparsed = http_parser_execute(parser, &settings, buf, recved);
  48. if (parser->upgrade) {
  49. /* handle new protocol */
  50. } else if (nparsed != recved) {
  51. /* Handle error. Usually just close the connection. */
  52. }
  53. HTTP needs to know where the end of the stream is. For example, sometimes
  54. servers send responses without Content-Length and expect the client to
  55. consume input (for the body) until EOF. To tell http_parser about EOF, give
  56. `0` as the forth parameter to `http_parser_execute()`. Callbacks and errors
  57. can still be encountered during an EOF, so one must still be prepared
  58. to receive them.
  59. Scalar valued message information such as `status_code`, `method`, and the
  60. HTTP version are stored in the parser structure. This data is only
  61. temporally stored in `http_parser` and gets reset on each new message. If
  62. this information is needed later, copy it out of the structure during the
  63. `headers_complete` callback.
  64. The parser decodes the transfer-encoding for both requests and responses
  65. transparently. That is, a chunked encoding is decoded before being sent to
  66. the on_body callback.
  67. The Special Problem of Upgrade
  68. ------------------------------
  69. HTTP supports upgrading the connection to a different protocol. An
  70. increasingly common example of this is the Web Socket protocol which sends
  71. a request like
  72. GET /demo HTTP/1.1
  73. Upgrade: WebSocket
  74. Connection: Upgrade
  75. Host: example.com
  76. Origin: http://example.com
  77. WebSocket-Protocol: sample
  78. followed by non-HTTP data.
  79. (See http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75 for more
  80. information the Web Socket protocol.)
  81. To support this, the parser will treat this as a normal HTTP message without a
  82. body. Issuing both on_headers_complete and on_message_complete callbacks. However
  83. http_parser_execute() will stop parsing at the end of the headers and return.
  84. The user is expected to check if `parser->upgrade` has been set to 1 after
  85. `http_parser_execute()` returns. Non-HTTP data begins at the buffer supplied
  86. offset by the return value of `http_parser_execute()`.
  87. Callbacks
  88. ---------
  89. During the `http_parser_execute()` call, the callbacks set in
  90. `http_parser_settings` will be executed. The parser maintains state and
  91. never looks behind, so buffering the data is not necessary. If you need to
  92. save certain data for later usage, you can do that from the callbacks.
  93. There are two types of callbacks:
  94. * notification `typedef int (*http_cb) (http_parser*);`
  95. Callbacks: on_message_begin, on_headers_complete, on_message_complete.
  96. * data `typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);`
  97. Callbacks: (requests only) on_uri,
  98. (common) on_header_field, on_header_value, on_body;
  99. Callbacks must return 0 on success. Returning a non-zero value indicates
  100. error to the parser, making it exit immediately.
  101. In case you parse HTTP message in chunks (i.e. `read()` request line
  102. from socket, parse, read half headers, parse, etc) your data callbacks
  103. may be called more than once. Http-parser guarantees that data pointer is only
  104. valid for the lifetime of callback. You can also `read()` into a heap allocated
  105. buffer to avoid copying memory around if this fits your application.
  106. Reading headers may be a tricky task if you read/parse headers partially.
  107. Basically, you need to remember whether last header callback was field or value
  108. and apply following logic:
  109. (on_header_field and on_header_value shortened to on_h_*)
  110. ------------------------ ------------ --------------------------------------------
  111. | State (prev. callback) | Callback | Description/action |
  112. ------------------------ ------------ --------------------------------------------
  113. | nothing (first call) | on_h_field | Allocate new buffer and copy callback data |
  114. | | | into it |
  115. ------------------------ ------------ --------------------------------------------
  116. | value | on_h_field | New header started. |
  117. | | | Copy current name,value buffers to headers |
  118. | | | list and allocate new buffer for new name |
  119. ------------------------ ------------ --------------------------------------------
  120. | field | on_h_field | Previous name continues. Reallocate name |
  121. | | | buffer and append callback data to it |
  122. ------------------------ ------------ --------------------------------------------
  123. | field | on_h_value | Value for current header started. Allocate |
  124. | | | new buffer and copy callback data to it |
  125. ------------------------ ------------ --------------------------------------------
  126. | value | on_h_value | Value continues. Reallocate value buffer |
  127. | | | and append callback data to it |
  128. ------------------------ ------------ --------------------------------------------
  129. Parsing URLs
  130. ------------
  131. A simplistic zero-copy URL parser is provided as `http_parser_parse_url()`.
  132. Users of this library may wish to use it to parse URLs constructed from
  133. consecutive `on_url` callbacks.
  134. See examples of reading in headers:
  135. * [partial example](http://gist.github.com/155877) in C
  136. * [from http-parser tests](http://github.com/joyent/http-parser/blob/37a0ff8/test.c#L403) in C
  137. * [from Node library](http://github.com/joyent/node/blob/842eaf4/src/http.js#L284) in Javascript