request_parser.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. // Copyright (C) 2016 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. #ifndef HTTP_REQUEST_PARSER_H
  7. #define HTTP_REQUEST_PARSER_H
  8. #include <exceptions/exceptions.h>
  9. #include <http/request.h>
  10. #include <util/state_model.h>
  11. #include <boost/function.hpp>
  12. #include <list>
  13. #include <stdint.h>
  14. #include <string>
  15. namespace isc {
  16. namespace http {
  17. /// @brief Exception thrown when an error during parsing HTTP request
  18. /// has occurred.
  19. ///
  20. /// The most common errors are due to receiving malformed requests.
  21. class HttpRequestParserError : public Exception {
  22. public:
  23. HttpRequestParserError(const char* file, size_t line, const char* what) :
  24. isc::Exception(file, line, what) { };
  25. };
  26. /// @brief A generic parser for HTTP requests.
  27. ///
  28. /// This class implements a parser for HTTP requests. The parser derives from
  29. /// @ref isc::util::StateModel class and implements its own state machine on
  30. /// top of it. The states of the parser reflect various parts of the HTTP
  31. /// message being parsed, e.g. parsing HTTP method, parsing URI, parsing
  32. /// message body etc. The descriptions of all parser states are provided
  33. /// below together with the constants defining these states.
  34. ///
  35. /// HTTP uses TCP as a transport which is asynchronous in nature, i.e. the
  36. /// HTTP message is received in chunks and multiple TCP connections can be
  37. /// established at the same time. Multiplexing between these connections
  38. /// requires providing a separate state machine per connection to "remember"
  39. /// the state of each transaction when the parser is waiting for asynchronous
  40. /// data to be delivered. While the parser is waiting for the data, it can
  41. /// parse requests received over other connections. This class provides means
  42. /// for parsing partial data received over the specific connection and
  43. /// interrupting data parsing to switch to a different context.
  44. ///
  45. /// The request parser validates the syntax of the received message as it
  46. /// progresses with parsing the data. Though, it doesn't interpret the received
  47. /// data until the whole message is parsed. In most cases we want to apply some
  48. /// restrictions on the message content, e.g. Kea Control API requires that
  49. /// commands are sent using HTTP POST, with a JSON command being carried in a
  50. /// message body. The parser doesn't verify if the message meets these
  51. /// restrictions until the whole message is parsed, i.e. stored in the
  52. /// @ref HttpRequestContext object. This object is associated with a
  53. /// @ref HttpRequest object (or its derivation). When the parsing is completed,
  54. /// the @ref HttpRequest::create method is called to retrieve the data from
  55. /// the @ref HttpRequestContext and interpret the data. In particular, the
  56. /// @ref HttpRequest or its derivation checks if the received message meets
  57. /// desired restrictions.
  58. ///
  59. /// Kea Control API uses @ref PostHttpRequestJson class (which derives from the
  60. /// @ref HttpRequest) to interpret received request. This class requires
  61. /// that the HTTP request uses POST method and contains the following headers:
  62. /// - Content-Type: application/json,
  63. /// - Content-Length
  64. ///
  65. /// If any of these restrictions is not met in the received message, an
  66. /// exception will be thrown, thereby @ref HttpRequestParser will fail parsing
  67. /// the message.
  68. ///
  69. /// A new method @ref HttpRequestParser::poll has been created to run the
  70. /// parser's state machine as long as there are unparsed data in the parser's
  71. /// internal buffer. This method returns control to the caller when the parser
  72. /// runs out of data in this buffer. The caller must feed the buffer by calling
  73. /// @ref HttpRequestParser::postBuffer and then run @ref HttpRequestParser::poll
  74. //// again.
  75. ///
  76. /// The @ref util::StateModel::runModel must not be used to run the
  77. /// @ref HttpRequestParser state machine, thus it is made private method.
  78. class HttpRequestParser : public util::StateModel {
  79. public:
  80. /// @name States supported by the HttpRequestParser.
  81. ///
  82. //@{
  83. /// @brief State indicating a beginning of parsing.
  84. static const int RECEIVE_START_ST = SM_DERIVED_STATE_MIN + 1;
  85. /// @brief Parsing HTTP method, e.g. GET, POST etc.
  86. static const int HTTP_METHOD_ST = SM_DERIVED_STATE_MIN + 2;
  87. /// @brief Parsing URI.
  88. static const int HTTP_URI_ST = SM_DERIVED_STATE_MIN + 3;
  89. /// @brief Parsing letter "H" of "HTTP".
  90. static const int HTTP_VERSION_H_ST = SM_DERIVED_STATE_MIN + 4;
  91. /// @brief Parsing first occurrence of "T" in "HTTP".
  92. static const int HTTP_VERSION_T1_ST = SM_DERIVED_STATE_MIN + 5;
  93. /// @brief Parsing second occurrence of "T" in "HTTP".
  94. static const int HTTP_VERSION_T2_ST = SM_DERIVED_STATE_MIN + 6;
  95. /// @brief Parsing letter "P" in "HTTP".
  96. static const int HTTP_VERSION_P_ST = SM_DERIVED_STATE_MIN + 7;
  97. /// @brief Parsing slash character in "HTTP/Y.X"
  98. static const int HTTP_VERSION_SLASH_ST = SM_DERIVED_STATE_MIN + 8;
  99. /// @brief Starting to parse major HTTP version number.
  100. static const int HTTP_VERSION_MAJOR_START_ST = SM_DERIVED_STATE_MIN + 9;
  101. /// @brief Parsing major HTTP version number.
  102. static const int HTTP_VERSION_MAJOR_ST = SM_DERIVED_STATE_MIN + 10;
  103. /// @brief Starting to parse minor HTTP version number.
  104. static const int HTTP_VERSION_MINOR_START_ST = SM_DERIVED_STATE_MIN + 11;
  105. /// @brief Parsing minor HTTP version number.
  106. static const int HTTP_VERSION_MINOR_ST = SM_DERIVED_STATE_MIN + 12;
  107. /// @brief Parsing first new line (after HTTP version number).
  108. static const int EXPECTING_NEW_LINE1_ST = SM_DERIVED_STATE_MIN + 13;
  109. /// @brief Starting to parse a header line.
  110. static const int HEADER_LINE_START_ST = SM_DERIVED_STATE_MIN + 14;
  111. /// @brief Parsing LWS (Linear White Space), i.e. new line with a space
  112. /// or tab character while parsing a HTTP header.
  113. static const int HEADER_LWS_ST = SM_DERIVED_STATE_MIN + 15;
  114. /// @brief Parsing header name.
  115. static const int HEADER_NAME_ST = SM_DERIVED_STATE_MIN + 16;
  116. /// @brief Parsing space before header value.
  117. static const int SPACE_BEFORE_HEADER_VALUE_ST = SM_DERIVED_STATE_MIN + 17;
  118. /// @brief Parsing header value.
  119. static const int HEADER_VALUE_ST = SM_DERIVED_STATE_MIN + 18;
  120. /// @brief Expecting new line after parsing header value.
  121. static const int EXPECTING_NEW_LINE2_ST = SM_DERIVED_STATE_MIN + 19;
  122. /// @brief Expecting second new line marking end of HTTP headers.
  123. static const int EXPECTING_NEW_LINE3_ST = SM_DERIVED_STATE_MIN + 20;
  124. /// @brief Parsing body of a HTTP message.
  125. static const int HTTP_BODY_ST = SM_DERIVED_STATE_MIN + 21;
  126. /// @brief Parsing successfully completed.
  127. static const int HTTP_PARSE_OK_ST = SM_DERIVED_STATE_MIN + 100;
  128. /// @brief Parsing failed.
  129. static const int HTTP_PARSE_FAILED_ST = SM_DERIVED_STATE_MIN + 101;
  130. //@}
  131. /// @name Events used during HTTP message parsing.
  132. ///
  133. //@{
  134. /// @brief Chunk of data successfully read and parsed.
  135. static const int DATA_READ_OK_EVT = SM_DERIVED_EVENT_MIN + 1;
  136. /// @brief Unable to proceed with parsing until new data is provided.
  137. static const int NEED_MORE_DATA_EVT = SM_DERIVED_EVENT_MIN + 2;
  138. /// @brief New data provided and parsing should continue.
  139. static const int MORE_DATA_PROVIDED_EVT = SM_DERIVED_EVENT_MIN + 3;
  140. /// @brief Parsing HTTP request successful.
  141. static const int HTTP_PARSE_OK_EVT = SM_DERIVED_EVENT_MIN + 100;
  142. /// @brief Parsing HTTP request failed.
  143. static const int HTTP_PARSE_FAILED_EVT = SM_DERIVED_EVENT_MIN + 101;
  144. //@}
  145. /// @brief Constructor.
  146. ///
  147. /// Creates new instance of the parser.
  148. ///
  149. /// @param request Reference to the @ref HttpRequest object or its
  150. /// derivation that should be used to validate the parsed request and
  151. /// to be used as a container for the parsed request.
  152. HttpRequestParser(HttpRequest& request);
  153. /// @brief Initialize the state model for parsing.
  154. ///
  155. /// This method must be called before parsing the request, i.e. before
  156. /// calling @ref HttpRequestParser::poll. It initializes dictionaries of
  157. /// states and events, and sets the initial model state to RECEIVE_START_ST.
  158. void initModel();
  159. /// @brief Run the parser as long as the amount of data is sufficient.
  160. ///
  161. /// The data to be parsed should be provided by calling
  162. /// @ref HttpRequestParser::postBuffer. When the parser reaches the end of
  163. /// the data buffer the @ref HttpRequestParser::poll sets the next event to
  164. /// @ref NEED_MORE_DATA_EVT and returns. The caller should then invoke
  165. /// @ref HttpRequestParser::postBuffer again to provide more data to the
  166. /// parser, and call @ref HttpRequestParser::poll to continue parsing.
  167. ///
  168. /// This method also returns when parsing completes or fails. The last
  169. /// event can be examined to check whether parsing was successful or not.
  170. void poll();
  171. /// @brief Returns true if the parser needs more data to continue.
  172. ///
  173. /// @return true if the next event is NEED_MORE_DATA_EVT.
  174. bool needData() const;
  175. /// @brief Returns true if a request has been parsed successfully.
  176. bool httpParseOk() const;
  177. /// @brief Returns error message.
  178. std::string getErrorMessage() const {
  179. return (error_message_);
  180. }
  181. /// @brief Provides more input data to the parser.
  182. ///
  183. /// This method must be called prior to calling @ref HttpRequestParser::poll
  184. /// to deliver data to be parsed. HTTP requests are received over TCP and
  185. /// multiple reads may be necessary to retrieve the entire request. There is
  186. /// no need to accumulate the entire request to start parsing it. A chunk
  187. /// of data can be provided to the parser using this method and parsed right
  188. /// away using @ref HttpRequestParser::poll.
  189. ///
  190. /// @param buf A pointer to the buffer holding the data.
  191. /// @param buf_size Size of the data within the buffer.
  192. void postBuffer(const void* buf, const size_t buf_size);
  193. private:
  194. /// @brief Make @ref runModel private to make sure that the caller uses
  195. /// @ref poll method instead.
  196. using StateModel::runModel;
  197. /// @brief Define events used by the parser.
  198. virtual void defineEvents();
  199. /// @brief Verifies events used by the parser.
  200. virtual void verifyEvents();
  201. /// @brief Defines states of the parser.
  202. virtual void defineStates();
  203. /// @brief Transition parser to failure state.
  204. ///
  205. /// This method transitions the parser to @ref HTTP_PARSE_FAILED_ST and
  206. /// sets next event to HTTP_PARSE_FAILED_EVT.
  207. ///
  208. /// @param error_msg Error message explaining the failure.
  209. void parseFailure(const std::string& error_msg);
  210. /// @brief A method called when parsing fails.
  211. ///
  212. /// @param explanation Error message explaining the reason for parsing
  213. /// failure.
  214. virtual void onModelFailure(const std::string& explanation);
  215. /// @brief Retrieves next byte of data from the buffer.
  216. ///
  217. /// During normal operation, when there is no more data in the buffer,
  218. /// the parser sets NEED_MORE_DATA_EVT as next event to signal the need for
  219. /// calling @ref HttpRequestParser::postBuffer.
  220. ///
  221. /// @throw HttpRequestParserError If current event is already set to
  222. /// NEED_MORE_DATA_EVT or MORE_DATA_PROVIDED_EVT. In the former case, it
  223. /// indicates that the caller failed to provide new data using
  224. /// @ref HttpRequestParser::postBuffer. The latter case is highly unlikely
  225. /// as it indicates that no new data were provided but the state of the
  226. /// parser was changed from NEED_MORE_DATA_EVT or the data were provided
  227. /// but the data buffer is empty. In both cases, it is an internal server
  228. /// error.
  229. char getNextFromBuffer();
  230. /// @brief This method is called when invalid event occurred in a particular
  231. /// parser state.
  232. ///
  233. /// This method simply throws @ref HttpRequestParserError informing about
  234. /// invalid event occurring for the particular parser state. The error
  235. /// message includes the name of the handler in which the exception
  236. /// has been thrown. It also includes the event which caused the
  237. /// exception.
  238. ///
  239. /// @param handler_name Name of the handler in which the exception is
  240. /// thrown.
  241. /// @param event An event which caused the exception.
  242. ///
  243. /// @throw HttpRequestParserError.
  244. void invalidEventError(const std::string& handler_name,
  245. const unsigned int event);
  246. /// @brief Generic parser handler which reads a single byte of data and
  247. /// parses it using specified callback function.
  248. ///
  249. /// This generic handler is used in most of the parser states to parse a
  250. /// single byte of input data. If there is no more data it simply returns.
  251. /// Otherwise, if the next event is DATA_READ_OK_EVT or
  252. /// MORE_DATA_PROVIDED_EVT, it calls the provided callback function to
  253. /// parse the new byte of data. For all other states it throws an exception.
  254. ///
  255. /// @param handler_name Name of the handler function which called this
  256. /// method.
  257. /// @param after_read_logic Callback function to parse the byte of data.
  258. /// This callback function implements state specific logic.
  259. ///
  260. /// @throw HttpRequestParserError when invalid event occurred.
  261. void stateWithReadHandler(const std::string& handler_name,
  262. boost::function<void(const char c)>
  263. after_read_logic);
  264. /// @name State handlers.
  265. ///
  266. //@{
  267. /// @brief Handler for RECEIVE_START_ST.
  268. void receiveStartHandler();
  269. /// @brief Handler for HTTP_METHOD_ST.
  270. void httpMethodHandler();
  271. /// @brief Handler for HTTP_URI_ST.
  272. void uriHandler();
  273. /// @brief Handler for states parsing "HTTP" string within the first line
  274. /// of the HTTP request.
  275. ///
  276. /// @param expected_letter One of the 'H', 'T', 'P'.
  277. /// @param next_state A state to which the parser should transition after
  278. /// parsing the character.
  279. void versionHTTPHandler(const char expected_letter,
  280. const unsigned int next_state);
  281. /// @brief Handler for HTTP_VERSION_MAJOR_START_ST and
  282. /// HTTP_VERSION_MINOR_START_ST.
  283. ///
  284. /// This handler calculates version number using the following equation:
  285. /// @code
  286. /// storage = storage * 10 + c - '0';
  287. /// @endcode
  288. ///
  289. /// @param next_state State to which the parser should transition.
  290. /// @param [out] storage Reference to a number holding current product of
  291. /// parsing major or minor version number.
  292. void versionNumberStartHandler(const unsigned int next_state,
  293. unsigned int* storage);
  294. /// @brief Handler for HTTP_VERSION_MAJOR_ST and HTTP_VERSION_MINOR_ST.
  295. ///
  296. /// This handler calculates version number using the following equation:
  297. /// @code
  298. /// storage = storage * 10 + c - '0';
  299. /// @endcode
  300. ///
  301. /// @param following_character Character following the version number, i.e.
  302. /// '.' for major version, \r for minor version.
  303. /// @param next_state State to which the parser should transition.
  304. /// @param [out] storage Pointer to a number holding current product of
  305. /// parsing major or minor version number.
  306. void versionNumberHandler(const char following_character,
  307. const unsigned int next_state,
  308. unsigned int* const storage);
  309. /// @brief Handler for states related to new lines.
  310. ///
  311. /// If the next_state is HTTP_PARSE_OK_ST it indicates that the parsed
  312. /// value is a 3rd new line within request HTTP message. In this case the
  313. /// handler calls @ref HttpRequest::create to validate the received message
  314. /// (excluding body). The hander then reads the "Content-Length" header to
  315. /// check if the request contains a body. If the "Content-Length" is greater
  316. /// than zero, the parser transitions to HTTP_BODY_ST. If the
  317. /// "Content-Length" doesn't exist the parser transitions to
  318. /// HTTP_PARSE_OK_ST.
  319. ///
  320. /// @param next_state A state to which parser should transition.
  321. void expectingNewLineHandler(const unsigned int next_state);
  322. /// @brief Handler for HEADER_LINE_START_ST.
  323. void headerLineStartHandler();
  324. /// @brief Handler for HEADER_LWS_ST.
  325. void headerLwsHandler();
  326. /// @brief Handler for HEADER_NAME_ST.
  327. void headerNameHandler();
  328. /// @brief Handler for SPACE_BEFORE_HEADER_VALUE_ST.
  329. void spaceBeforeHeaderValueHandler();
  330. /// @brief Handler for HEADER_VALUE_ST.
  331. void headerValueHandler();
  332. /// @brief Handler for HTTP_BODY_ST.
  333. void bodyHandler();
  334. /// @brief Handler for HTTP_PARSE_OK_ST and HTTP_PARSE_FAILED_ST.
  335. ///
  336. /// If parsing is successful, it calls @ref HttpRequest::create to validate
  337. /// the HTTP request. In both cases it transitions the parser to the END_ST.
  338. void parseEndedHandler();
  339. /// @brief Tries to read next byte from buffer.
  340. ///
  341. /// @param [out] next A reference to the variable where read data should be
  342. /// stored.
  343. ///
  344. /// @return true if character was successfully read, false otherwise.
  345. bool popNextFromBuffer(char& next);
  346. /// @brief Checks if specified value is a character.
  347. ///
  348. /// @return true, if specified value is a character.
  349. bool isChar(const char c) const;
  350. /// @brief Checks if specified value is a control value.
  351. ///
  352. /// @return true, if specified value is a control value.
  353. bool isCtl(const char c) const;
  354. /// @brief Checks if specified value is a special character.
  355. ///
  356. /// @return true, if specified value is a special character.
  357. bool isSpecial(const char c) const;
  358. /// @brief Internal buffer from which parser reads data.
  359. std::list<char> buffer_;
  360. /// @brief Reference to the request object specified in the constructor.
  361. HttpRequest& request_;
  362. /// @brief Pointer to the internal context of the @ref HttpRequest object.
  363. HttpRequestContextPtr context_;
  364. /// @brief Error message set by @ref onModelFailure.
  365. std::string error_message_;
  366. };
  367. } // namespace http
  368. } // namespace isc
  369. #endif // HTTP_REQUEST_PARSER_H