processor.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. /*
  2. * Copyright (c) 2014, Peter Thorson. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions are met:
  6. * * Redistributions of source code must retain the above copyright
  7. * notice, this list of conditions and the following disclaimer.
  8. * * Redistributions in binary form must reproduce the above copyright
  9. * notice, this list of conditions and the following disclaimer in the
  10. * documentation and/or other materials provided with the distribution.
  11. * * Neither the name of the WebSocket++ Project nor the
  12. * names of its contributors may be used to endorse or promote products
  13. * derived from this software without specific prior written permission.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. * ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY
  19. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  20. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  21. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  22. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  24. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. *
  26. */
  27. #ifndef WEBSOCKETPP_PROCESSOR_HPP
  28. #define WEBSOCKETPP_PROCESSOR_HPP
  29. #include <websocketpp/processors/base.hpp>
  30. #include <websocketpp/common/system_error.hpp>
  31. #include <websocketpp/close.hpp>
  32. #include <websocketpp/utilities.hpp>
  33. #include <websocketpp/uri.hpp>
  34. #include <sstream>
  35. #include <string>
  36. #include <utility>
  37. #include <vector>
  38. namespace websocketpp {
  39. /// Processors encapsulate the protocol rules specific to each WebSocket version
  40. /**
  41. * The processors namespace includes a number of free functions that operate on
  42. * various WebSocket related data structures and perform processing that is not
  43. * related to specific versions of the protocol.
  44. *
  45. * It also includes the abstract interface for the protocol specific processing
  46. * engines. These engines wrap all of the logic necessary for parsing and
  47. * validating WebSocket handshakes and messages of specific protocol version
  48. * and set of allowed extensions.
  49. *
  50. * An instance of a processor represents the state of a single WebSocket
  51. * connection of the associated version. One processor instance is needed per
  52. * logical WebSocket connection.
  53. */
  54. namespace processor {
  55. /// Determine whether or not a generic HTTP request is a WebSocket handshake
  56. /**
  57. * @param r The HTTP request to read.
  58. *
  59. * @return True if the request is a WebSocket handshake, false otherwise
  60. */
  61. template <typename request_type>
  62. bool is_websocket_handshake(request_type& r) {
  63. using utility::ci_find_substr;
  64. std::string const & upgrade_header = r.get_header("Upgrade");
  65. if (ci_find_substr(upgrade_header, constants::upgrade_token,
  66. sizeof(constants::upgrade_token)-1) == upgrade_header.end())
  67. {
  68. return false;
  69. }
  70. std::string const & con_header = r.get_header("Connection");
  71. if (ci_find_substr(con_header, constants::connection_token,
  72. sizeof(constants::connection_token)-1) == con_header.end())
  73. {
  74. return false;
  75. }
  76. return true;
  77. }
  78. /// Extract the version from a WebSocket handshake request
  79. /**
  80. * A blank version header indicates a spec before versions were introduced.
  81. * The only such versions in shipping products are Hixie Draft 75 and Hixie
  82. * Draft 76. Draft 75 is present in Chrome 4-5 and Safari 5.0.0, Draft 76 (also
  83. * known as hybi 00 is present in Chrome 6-13 and Safari 5.0.1+. As
  84. * differentiating between these two sets of browsers is very difficult and
  85. * Safari 5.0.1+ accounts for the vast majority of cases in the wild this
  86. * function assumes that all handshakes without a valid version header are
  87. * Hybi 00.
  88. *
  89. * @param r The WebSocket handshake request to read.
  90. *
  91. * @return The WebSocket handshake version or -1 if there was an extraction
  92. * error.
  93. */
  94. template <typename request_type>
  95. int get_websocket_version(request_type& r) {
  96. if (!r.ready()) {
  97. return -2;
  98. }
  99. if (r.get_header("Sec-WebSocket-Version") == "") {
  100. return 0;
  101. }
  102. int version;
  103. std::istringstream ss(r.get_header("Sec-WebSocket-Version"));
  104. if ((ss >> version).fail()) {
  105. return -1;
  106. }
  107. return version;
  108. }
  109. /// Extract a URI ptr from the host header of the request
  110. /**
  111. * @param request The request to extract the Host header from.
  112. *
  113. * @param scheme The scheme under which this request was received (ws, wss,
  114. * http, https, etc)
  115. *
  116. * @return A uri_pointer that encodes the value of the host header.
  117. */
  118. template <typename request_type>
  119. uri_ptr get_uri_from_host(request_type & request, std::string scheme) {
  120. std::string h = request.get_header("Host");
  121. size_t last_colon = h.rfind(":");
  122. size_t last_sbrace = h.rfind("]");
  123. // no : = hostname with no port
  124. // last : before ] = ipv6 literal with no port
  125. // : with no ] = hostname with port
  126. // : after ] = ipv6 literal with port
  127. if (last_colon == std::string::npos ||
  128. (last_sbrace != std::string::npos && last_sbrace > last_colon))
  129. {
  130. return lib::make_shared<uri>(scheme, h, request.get_uri());
  131. } else {
  132. return lib::make_shared<uri>(scheme,
  133. h.substr(0,last_colon),
  134. h.substr(last_colon+1),
  135. request.get_uri());
  136. }
  137. }
  138. /// WebSocket protocol processor abstract base class
  139. template <typename config>
  140. class processor {
  141. public:
  142. typedef processor<config> type;
  143. typedef typename config::request_type request_type;
  144. typedef typename config::response_type response_type;
  145. typedef typename config::message_type::ptr message_ptr;
  146. typedef std::pair<lib::error_code,std::string> err_str_pair;
  147. explicit processor(bool secure, bool p_is_server)
  148. : m_secure(secure)
  149. , m_server(p_is_server)
  150. , m_max_message_size(config::max_message_size)
  151. {}
  152. virtual ~processor() {}
  153. /// Get the protocol version of this processor
  154. virtual int get_version() const = 0;
  155. /// Get maximum message size
  156. /**
  157. * Get maximum message size. Maximum message size determines the point at which the
  158. * processor will fail a connection with the message_too_big protocol error.
  159. *
  160. * The default is retrieved from the max_message_size value from the template config
  161. *
  162. * @since 0.3.0
  163. */
  164. size_t get_max_message_size() const {
  165. return m_max_message_size;
  166. }
  167. /// Set maximum message size
  168. /**
  169. * Set maximum message size. Maximum message size determines the point at which the
  170. * processor will fail a connection with the message_too_big protocol error.
  171. *
  172. * The default is retrieved from the max_message_size value from the template config
  173. *
  174. * @since 0.3.0
  175. *
  176. * @param new_value The value to set as the maximum message size.
  177. */
  178. void set_max_message_size(size_t new_value) {
  179. m_max_message_size = new_value;
  180. }
  181. /// Returns whether or not the permessage_compress extension is implemented
  182. /**
  183. * Compile time flag that indicates whether this processor has implemented
  184. * the permessage_compress extension. By default this is false.
  185. */
  186. virtual bool has_permessage_compress() const {
  187. return false;
  188. }
  189. /// Initializes extensions based on the Sec-WebSocket-Extensions header
  190. /**
  191. * Reads the Sec-WebSocket-Extensions header and determines if any of the
  192. * requested extensions are supported by this processor. If they are their
  193. * settings data is initialized.
  194. *
  195. * @param request The request headers to look at.
  196. */
  197. virtual err_str_pair negotiate_extensions(request_type const &) {
  198. return err_str_pair();
  199. }
  200. /// validate a WebSocket handshake request for this version
  201. /**
  202. * @param request The WebSocket handshake request to validate.
  203. * is_websocket_handshake(request) must be true and
  204. * get_websocket_version(request) must equal this->get_version().
  205. *
  206. * @return A status code, 0 on success, non-zero for specific sorts of
  207. * failure
  208. */
  209. virtual lib::error_code validate_handshake(request_type const & request) const = 0;
  210. /// Calculate the appropriate response for this websocket request
  211. /**
  212. * @param req The request to process
  213. *
  214. * @param subprotocol The subprotocol in use
  215. *
  216. * @param res The response to store the processed response in
  217. *
  218. * @return An error code, 0 on success, non-zero for other errors
  219. */
  220. virtual lib::error_code process_handshake(request_type const & req,
  221. std::string const & subprotocol, response_type& res) const = 0;
  222. /// Fill in an HTTP request for an outgoing connection handshake
  223. /**
  224. * @param req The request to process.
  225. *
  226. * @return An error code, 0 on success, non-zero for other errors
  227. */
  228. virtual lib::error_code client_handshake_request(request_type & req,
  229. uri_ptr uri, std::vector<std::string> const & subprotocols) const = 0;
  230. /// Validate the server's response to an outgoing handshake request
  231. /**
  232. * @param req The original request sent
  233. * @param res The reponse to generate
  234. * @return An error code, 0 on success, non-zero for other errors
  235. */
  236. virtual lib::error_code validate_server_handshake_response(request_type
  237. const & req, response_type & res) const = 0;
  238. /// Given a completed response, get the raw bytes to put on the wire
  239. virtual std::string get_raw(response_type const & request) const = 0;
  240. /// Return the value of the header containing the CORS origin.
  241. virtual std::string const & get_origin(request_type const & request) const = 0;
  242. /// Extracts requested subprotocols from a handshake request
  243. /**
  244. * Extracts a list of all subprotocols that the client has requested in the
  245. * given opening handshake request.
  246. *
  247. * @param [in] req The request to extract from
  248. * @param [out] subprotocol_list A reference to a vector of strings to store
  249. * the results in.
  250. */
  251. virtual lib::error_code extract_subprotocols(const request_type & req,
  252. std::vector<std::string> & subprotocol_list) = 0;
  253. /// Extracts client uri from a handshake request
  254. virtual uri_ptr get_uri(request_type const & request) const = 0;
  255. /// process new websocket connection bytes
  256. /**
  257. * WebSocket connections are a continous stream of bytes that must be
  258. * interpreted by a protocol processor into discrete frames.
  259. *
  260. * @param buf Buffer from which bytes should be read.
  261. * @param len Length of buffer
  262. * @param ec Reference to an error code to return any errors in
  263. * @return Number of bytes processed
  264. */
  265. virtual size_t consume(uint8_t *buf, size_t len, lib::error_code & ec) = 0;
  266. /// Checks if there is a message ready
  267. /**
  268. * Checks if the most recent consume operation processed enough bytes to
  269. * complete a new WebSocket message. The message can be retrieved by calling
  270. * get_message() which will reset the internal state to not-ready and allow
  271. * consume to read more bytes.
  272. *
  273. * @return Whether or not a message is ready.
  274. */
  275. virtual bool ready() const = 0;
  276. /// Retrieves the most recently processed message
  277. /**
  278. * Retrieves a shared pointer to the recently completed message if there is
  279. * one. If ready() returns true then there is a message available.
  280. * Retrieving the message with get_message will reset the state of ready.
  281. * As such, each new message may be retrieved only once. Calling get_message
  282. * when there is no message available will result in a null pointer being
  283. * returned.
  284. *
  285. * @return A pointer to the most recently processed message or a null shared
  286. * pointer.
  287. */
  288. virtual message_ptr get_message() = 0;
  289. /// Tests whether the processor is in a fatal error state
  290. virtual bool get_error() const = 0;
  291. /// Retrieves the number of bytes presently needed by the processor
  292. /// This value may be used as a hint to the transport layer as to how many
  293. /// bytes to wait for before running consume again.
  294. virtual size_t get_bytes_needed() const {
  295. return 1;
  296. }
  297. /// Prepare a data message for writing
  298. /**
  299. * Performs validation, masking, compression, etc. will return an error if
  300. * there was an error, otherwise msg will be ready to be written
  301. */
  302. virtual lib::error_code prepare_data_frame(message_ptr in, message_ptr out) = 0;
  303. /// Prepare a ping frame
  304. /**
  305. * Ping preparation is entirely state free. There is no payload validation
  306. * other than length. Payload need not be UTF-8.
  307. *
  308. * @param in The string to use for the ping payload
  309. * @param out The message buffer to prepare the ping in.
  310. * @return Status code, zero on success, non-zero on failure
  311. */
  312. virtual lib::error_code prepare_ping(std::string const & in, message_ptr out) const
  313. = 0;
  314. /// Prepare a pong frame
  315. /**
  316. * Pong preparation is entirely state free. There is no payload validation
  317. * other than length. Payload need not be UTF-8.
  318. *
  319. * @param in The string to use for the pong payload
  320. * @param out The message buffer to prepare the pong in.
  321. * @return Status code, zero on success, non-zero on failure
  322. */
  323. virtual lib::error_code prepare_pong(std::string const & in, message_ptr out) const
  324. = 0;
  325. /// Prepare a close frame
  326. /**
  327. * Close preparation is entirely state free. The code and reason are both
  328. * subject to validation. Reason must be valid UTF-8. Code must be a valid
  329. * un-reserved WebSocket close code. Use close::status::no_status to
  330. * indicate no code. If no code is supplied a reason may not be specified.
  331. *
  332. * @param code The close code to send
  333. * @param reason The reason string to send
  334. * @param out The message buffer to prepare the fame in
  335. * @return Status code, zero on success, non-zero on failure
  336. */
  337. virtual lib::error_code prepare_close(close::status::value code,
  338. std::string const & reason, message_ptr out) const = 0;
  339. protected:
  340. bool const m_secure;
  341. bool const m_server;
  342. size_t m_max_message_size;
  343. };
  344. } // namespace processor
  345. } // namespace websocketpp
  346. #endif //WEBSOCKETPP_PROCESSOR_HPP