processor.hpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /*
  2. * Copyright (c) 2015, 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").empty()) {
  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 and an extension string to send to the
  194. * is returned.
  195. *
  196. * @param request The request or response headers to look at.
  197. */
  198. virtual err_str_pair negotiate_extensions(request_type const &) {
  199. return err_str_pair();
  200. }
  201. /// Initializes extensions based on the Sec-WebSocket-Extensions header
  202. /**
  203. * Reads the Sec-WebSocket-Extensions header and determines if any of the
  204. * requested extensions were accepted by the server. If they are their
  205. * settings data is initialized. If they are not a list of required
  206. * extensions (if any) is returned. This list may be sent back to the server
  207. * as a part of the 1010/Extension required close code.
  208. *
  209. * @param response The request or response headers to look at.
  210. */
  211. virtual err_str_pair negotiate_extensions(response_type const &) {
  212. return err_str_pair();
  213. }
  214. /// validate a WebSocket handshake request for this version
  215. /**
  216. * @param request The WebSocket handshake request to validate.
  217. * is_websocket_handshake(request) must be true and
  218. * get_websocket_version(request) must equal this->get_version().
  219. *
  220. * @return A status code, 0 on success, non-zero for specific sorts of
  221. * failure
  222. */
  223. virtual lib::error_code validate_handshake(request_type const & request) const = 0;
  224. /// Calculate the appropriate response for this websocket request
  225. /**
  226. * @param req The request to process
  227. *
  228. * @param subprotocol The subprotocol in use
  229. *
  230. * @param res The response to store the processed response in
  231. *
  232. * @return An error code, 0 on success, non-zero for other errors
  233. */
  234. virtual lib::error_code process_handshake(request_type const & req,
  235. std::string const & subprotocol, response_type& res) const = 0;
  236. /// Fill in an HTTP request for an outgoing connection handshake
  237. /**
  238. * @param req The request to process.
  239. *
  240. * @return An error code, 0 on success, non-zero for other errors
  241. */
  242. virtual lib::error_code client_handshake_request(request_type & req,
  243. uri_ptr uri, std::vector<std::string> const & subprotocols) const = 0;
  244. /// Validate the server's response to an outgoing handshake request
  245. /**
  246. * @param req The original request sent
  247. * @param res The reponse to generate
  248. * @return An error code, 0 on success, non-zero for other errors
  249. */
  250. virtual lib::error_code validate_server_handshake_response(request_type
  251. const & req, response_type & res) const = 0;
  252. /// Given a completed response, get the raw bytes to put on the wire
  253. virtual std::string get_raw(response_type const & request) const = 0;
  254. /// Return the value of the header containing the CORS origin.
  255. virtual std::string const & get_origin(request_type const & request) const = 0;
  256. /// Extracts requested subprotocols from a handshake request
  257. /**
  258. * Extracts a list of all subprotocols that the client has requested in the
  259. * given opening handshake request.
  260. *
  261. * @param [in] req The request to extract from
  262. * @param [out] subprotocol_list A reference to a vector of strings to store
  263. * the results in.
  264. */
  265. virtual lib::error_code extract_subprotocols(const request_type & req,
  266. std::vector<std::string> & subprotocol_list) = 0;
  267. /// Extracts client uri from a handshake request
  268. virtual uri_ptr get_uri(request_type const & request) const = 0;
  269. /// process new websocket connection bytes
  270. /**
  271. * WebSocket connections are a continous stream of bytes that must be
  272. * interpreted by a protocol processor into discrete frames.
  273. *
  274. * @param buf Buffer from which bytes should be read.
  275. * @param len Length of buffer
  276. * @param ec Reference to an error code to return any errors in
  277. * @return Number of bytes processed
  278. */
  279. virtual size_t consume(uint8_t *buf, size_t len, lib::error_code & ec) = 0;
  280. /// Checks if there is a message ready
  281. /**
  282. * Checks if the most recent consume operation processed enough bytes to
  283. * complete a new WebSocket message. The message can be retrieved by calling
  284. * get_message() which will reset the internal state to not-ready and allow
  285. * consume to read more bytes.
  286. *
  287. * @return Whether or not a message is ready.
  288. */
  289. virtual bool ready() const = 0;
  290. /// Retrieves the most recently processed message
  291. /**
  292. * Retrieves a shared pointer to the recently completed message if there is
  293. * one. If ready() returns true then there is a message available.
  294. * Retrieving the message with get_message will reset the state of ready.
  295. * As such, each new message may be retrieved only once. Calling get_message
  296. * when there is no message available will result in a null pointer being
  297. * returned.
  298. *
  299. * @return A pointer to the most recently processed message or a null shared
  300. * pointer.
  301. */
  302. virtual message_ptr get_message() = 0;
  303. /// Tests whether the processor is in a fatal error state
  304. virtual bool get_error() const = 0;
  305. /// Retrieves the number of bytes presently needed by the processor
  306. /// This value may be used as a hint to the transport layer as to how many
  307. /// bytes to wait for before running consume again.
  308. virtual size_t get_bytes_needed() const {
  309. return 1;
  310. }
  311. /// Prepare a data message for writing
  312. /**
  313. * Performs validation, masking, compression, etc. will return an error if
  314. * there was an error, otherwise msg will be ready to be written
  315. */
  316. virtual lib::error_code prepare_data_frame(message_ptr in, message_ptr out) = 0;
  317. /// Prepare a ping frame
  318. /**
  319. * Ping preparation is entirely state free. There is no payload validation
  320. * other than length. Payload need not be UTF-8.
  321. *
  322. * @param in The string to use for the ping payload
  323. * @param out The message buffer to prepare the ping in.
  324. * @return Status code, zero on success, non-zero on failure
  325. */
  326. virtual lib::error_code prepare_ping(std::string const & in, message_ptr out) const
  327. = 0;
  328. /// Prepare a pong frame
  329. /**
  330. * Pong preparation is entirely state free. There is no payload validation
  331. * other than length. Payload need not be UTF-8.
  332. *
  333. * @param in The string to use for the pong payload
  334. * @param out The message buffer to prepare the pong in.
  335. * @return Status code, zero on success, non-zero on failure
  336. */
  337. virtual lib::error_code prepare_pong(std::string const & in, message_ptr out) const
  338. = 0;
  339. /// Prepare a close frame
  340. /**
  341. * Close preparation is entirely state free. The code and reason are both
  342. * subject to validation. Reason must be valid UTF-8. Code must be a valid
  343. * un-reserved WebSocket close code. Use close::status::no_status to
  344. * indicate no code. If no code is supplied a reason may not be specified.
  345. *
  346. * @param code The close code to send
  347. * @param reason The reason string to send
  348. * @param out The message buffer to prepare the fame in
  349. * @return Status code, zero on success, non-zero on failure
  350. */
  351. virtual lib::error_code prepare_close(close::status::value code,
  352. std::string const & reason, message_ptr out) const = 0;
  353. protected:
  354. bool const m_secure;
  355. bool const m_server;
  356. size_t m_max_message_size;
  357. };
  358. } // namespace processor
  359. } // namespace websocketpp
  360. #endif //WEBSOCKETPP_PROCESSOR_HPP