You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

410 lines
15 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  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 <sstream>
  30. #include <string>
  31. #include <utility>
  32. #include <vector>
  33. #include <websocketpp/close.hpp>
  34. #include <websocketpp/common/system_error.hpp>
  35. #include <websocketpp/processors/base.hpp>
  36. #include <websocketpp/uri.hpp>
  37. #include <websocketpp/utilities.hpp>
  38. namespace websocketpp
  39. {
  40. /// Processors encapsulate the protocol rules specific to each WebSocket version
  41. /**
  42. * The processors namespace includes a number of free functions that operate on
  43. * various WebSocket related data structures and perform processing that is not
  44. * related to specific versions of the protocol.
  45. *
  46. * It also includes the abstract interface for the protocol specific processing
  47. * engines. These engines wrap all of the logic necessary for parsing and
  48. * validating WebSocket handshakes and messages of specific protocol version
  49. * and set of allowed extensions.
  50. *
  51. * An instance of a processor represents the state of a single WebSocket
  52. * connection of the associated version. One processor instance is needed per
  53. * logical WebSocket connection.
  54. */
  55. namespace processor
  56. {
  57. /// Determine whether or not a generic HTTP request is a WebSocket handshake
  58. /**
  59. * @param r The HTTP request to read.
  60. *
  61. * @return True if the request is a WebSocket handshake, false otherwise
  62. */
  63. template <typename request_type> bool is_websocket_handshake(request_type & r)
  64. {
  65. using utility::ci_find_substr;
  66. const std::string & upgrade_header = r.get_header("Upgrade");
  67. if (ci_find_substr(upgrade_header, constants::upgrade_token, sizeof(constants::upgrade_token) - 1) == upgrade_header.end())
  68. {
  69. return false;
  70. }
  71. const std::string & con_header = r.get_header("Connection");
  72. if (ci_find_substr(con_header, constants::connection_token, 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> int get_websocket_version(request_type & r)
  95. {
  96. if (! r.ready())
  97. {
  98. return -2;
  99. }
  100. if (r.get_header("Sec-WebSocket-Version").empty())
  101. {
  102. return 0;
  103. }
  104. int version;
  105. std::istringstream ss(r.get_header("Sec-WebSocket-Version"));
  106. if ((ss >> version).fail())
  107. {
  108. return -1;
  109. }
  110. return version;
  111. }
  112. /// Extract a URI ptr from the host header of the request
  113. /**
  114. * @param request The request to extract the Host header from.
  115. *
  116. * @param scheme The scheme under which this request was received (ws, wss,
  117. * http, https, etc)
  118. *
  119. * @return A uri_pointer that encodes the value of the host header.
  120. */
  121. template <typename request_type> uri_ptr get_uri_from_host(request_type & request, std::string scheme)
  122. {
  123. std::string h = request.get_header("Host");
  124. size_t last_colon = h.rfind(":");
  125. size_t last_sbrace = h.rfind("]");
  126. // no : = hostname with no port
  127. // last : before ] = ipv6 literal with no port
  128. // : with no ] = hostname with port
  129. // : after ] = ipv6 literal with port
  130. if (last_colon == std::string::npos || (last_sbrace != std::string::npos && last_sbrace > last_colon))
  131. {
  132. return lib::make_shared<uri>(scheme, h, request.get_uri());
  133. }
  134. else
  135. {
  136. return lib::make_shared<uri>(scheme, h.substr(0, last_colon), h.substr(last_colon + 1), request.get_uri());
  137. }
  138. }
  139. /// WebSocket protocol processor abstract base class
  140. template <typename config> class processor
  141. {
  142. public:
  143. typedef processor<config> type;
  144. typedef typename config::request_type request_type;
  145. typedef typename config::response_type response_type;
  146. typedef typename config::message_type::ptr message_ptr;
  147. typedef std::pair<lib::error_code, std::string> err_str_pair;
  148. explicit processor(bool secure, bool p_is_server) :
  149. m_secure(secure),
  150. m_server(p_is_server),
  151. m_max_message_size(config::max_message_size)
  152. {
  153. }
  154. virtual ~processor() {}
  155. /// Get the protocol version of this processor
  156. virtual int get_version() const = 0;
  157. /// Get maximum message size
  158. /**
  159. * Get maximum message size. Maximum message size determines the point at which the
  160. * processor will fail a connection with the message_too_big protocol error.
  161. *
  162. * The default is retrieved from the max_message_size value from the template config
  163. *
  164. * @since 0.3.0
  165. */
  166. size_t get_max_message_size() const
  167. {
  168. return m_max_message_size;
  169. }
  170. /// Set maximum message size
  171. /**
  172. * Set maximum message size. Maximum message size determines the point at which the
  173. * processor will fail a connection with the message_too_big protocol error.
  174. *
  175. * The default is retrieved from the max_message_size value from the template config
  176. *
  177. * @since 0.3.0
  178. *
  179. * @param new_value The value to set as the maximum message size.
  180. */
  181. void set_max_message_size(size_t new_value)
  182. {
  183. m_max_message_size = new_value;
  184. }
  185. /// Returns whether or not the permessage_compress extension is implemented
  186. /**
  187. * Compile time flag that indicates whether this processor has implemented
  188. * the permessage_compress extension. By default this is false.
  189. */
  190. virtual bool has_permessage_compress() const
  191. {
  192. return false;
  193. }
  194. /// Initializes extensions based on the Sec-WebSocket-Extensions header
  195. /**
  196. * Reads the Sec-WebSocket-Extensions header and determines if any of the
  197. * requested extensions are supported by this processor. If they are their
  198. * settings data is initialized and an extension string to send to the
  199. * is returned.
  200. *
  201. * @param request The request or response headers to look at.
  202. */
  203. virtual err_str_pair negotiate_extensions(const request_type &)
  204. {
  205. return err_str_pair();
  206. }
  207. /// Initializes extensions based on the Sec-WebSocket-Extensions header
  208. /**
  209. * Reads the Sec-WebSocket-Extensions header and determines if any of the
  210. * requested extensions were accepted by the server. If they are their
  211. * settings data is initialized. If they are not a list of required
  212. * extensions (if any) is returned. This list may be sent back to the server
  213. * as a part of the 1010/Extension required close code.
  214. *
  215. * @param response The request or response headers to look at.
  216. */
  217. virtual err_str_pair negotiate_extensions(const response_type &)
  218. {
  219. return err_str_pair();
  220. }
  221. /// validate a WebSocket handshake request for this version
  222. /**
  223. * @param request The WebSocket handshake request to validate.
  224. * is_websocket_handshake(request) must be true and
  225. * get_websocket_version(request) must equal this->get_version().
  226. *
  227. * @return A status code, 0 on success, non-zero for specific sorts of
  228. * failure
  229. */
  230. virtual lib::error_code validate_handshake(const request_type & request) const = 0;
  231. /// Calculate the appropriate response for this websocket request
  232. /**
  233. * @param req The request to process
  234. *
  235. * @param subprotocol The subprotocol in use
  236. *
  237. * @param res The response to store the processed response in
  238. *
  239. * @return An error code, 0 on success, non-zero for other errors
  240. */
  241. virtual lib::error_code process_handshake(const request_type & req, const std::string & subprotocol, response_type & res) const = 0;
  242. /// Fill in an HTTP request for an outgoing connection handshake
  243. /**
  244. * @param req The request to process.
  245. *
  246. * @return An error code, 0 on success, non-zero for other errors
  247. */
  248. virtual lib::error_code client_handshake_request(request_type & req, uri_ptr uri, const std::vector<std::string> & subprotocols) const = 0;
  249. /// Validate the server's response to an outgoing handshake request
  250. /**
  251. * @param req The original request sent
  252. * @param res The reponse to generate
  253. * @return An error code, 0 on success, non-zero for other errors
  254. */
  255. virtual lib::error_code validate_server_handshake_response(const request_type & req, response_type & res) const = 0;
  256. /// Given a completed response, get the raw bytes to put on the wire
  257. virtual std::string get_raw(const response_type & request) const = 0;
  258. /// Return the value of the header containing the CORS origin.
  259. virtual const std::string & get_origin(const request_type & request) const = 0;
  260. /// Extracts requested subprotocols from a handshake request
  261. /**
  262. * Extracts a list of all subprotocols that the client has requested in the
  263. * given opening handshake request.
  264. *
  265. * @param [in] req The request to extract from
  266. * @param [out] subprotocol_list A reference to a vector of strings to store
  267. * the results in.
  268. */
  269. virtual lib::error_code extract_subprotocols(const request_type & req, std::vector<std::string> & subprotocol_list) = 0;
  270. /// Extracts client uri from a handshake request
  271. virtual uri_ptr get_uri(const request_type & request) const = 0;
  272. /// process new websocket connection bytes
  273. /**
  274. * WebSocket connections are a continous stream of bytes that must be
  275. * interpreted by a protocol processor into discrete frames.
  276. *
  277. * @param buf Buffer from which bytes should be read.
  278. * @param len Length of buffer
  279. * @param ec Reference to an error code to return any errors in
  280. * @return Number of bytes processed
  281. */
  282. virtual size_t consume(uint8_t * buf, size_t len, lib::error_code & ec) = 0;
  283. /// Checks if there is a message ready
  284. /**
  285. * Checks if the most recent consume operation processed enough bytes to
  286. * complete a new WebSocket message. The message can be retrieved by calling
  287. * get_message() which will reset the internal state to not-ready and allow
  288. * consume to read more bytes.
  289. *
  290. * @return Whether or not a message is ready.
  291. */
  292. virtual bool ready() const = 0;
  293. /// Retrieves the most recently processed message
  294. /**
  295. * Retrieves a shared pointer to the recently completed message if there is
  296. * one. If ready() returns true then there is a message available.
  297. * Retrieving the message with get_message will reset the state of ready.
  298. * As such, each new message may be retrieved only once. Calling get_message
  299. * when there is no message available will result in a null pointer being
  300. * returned.
  301. *
  302. * @return A pointer to the most recently processed message or a null shared
  303. * pointer.
  304. */
  305. virtual message_ptr get_message() = 0;
  306. /// Tests whether the processor is in a fatal error state
  307. virtual bool get_error() const = 0;
  308. /// Retrieves the number of bytes presently needed by the processor
  309. /// This value may be used as a hint to the transport layer as to how many
  310. /// bytes to wait for before running consume again.
  311. virtual size_t get_bytes_needed() const
  312. {
  313. return 1;
  314. }
  315. /// Prepare a data message for writing
  316. /**
  317. * Performs validation, masking, compression, etc. will return an error if
  318. * there was an error, otherwise msg will be ready to be written
  319. */
  320. virtual lib::error_code prepare_data_frame(message_ptr in, message_ptr out) = 0;
  321. /// Prepare a ping frame
  322. /**
  323. * Ping preparation is entirely state free. There is no payload validation
  324. * other than length. Payload need not be UTF-8.
  325. *
  326. * @param in The string to use for the ping payload
  327. * @param out The message buffer to prepare the ping in.
  328. * @return Status code, zero on success, non-zero on failure
  329. */
  330. virtual lib::error_code prepare_ping(const std::string & in, message_ptr out) const = 0;
  331. /// Prepare a pong frame
  332. /**
  333. * Pong preparation is entirely state free. There is no payload validation
  334. * other than length. Payload need not be UTF-8.
  335. *
  336. * @param in The string to use for the pong payload
  337. * @param out The message buffer to prepare the pong in.
  338. * @return Status code, zero on success, non-zero on failure
  339. */
  340. virtual lib::error_code prepare_pong(const std::string & in, message_ptr out) const = 0;
  341. /// Prepare a close frame
  342. /**
  343. * Close preparation is entirely state free. The code and reason are both
  344. * subject to validation. Reason must be valid UTF-8. Code must be a valid
  345. * un-reserved WebSocket close code. Use close::status::no_status to
  346. * indicate no code. If no code is supplied a reason may not be specified.
  347. *
  348. * @param code The close code to send
  349. * @param reason The reason string to send
  350. * @param out The message buffer to prepare the fame in
  351. * @return Status code, zero on success, non-zero on failure
  352. */
  353. virtual lib::error_code prepare_close(close::status::value code, const std::string & reason, message_ptr out) const = 0;
  354. protected:
  355. const bool m_secure;
  356. const bool m_server;
  357. size_t m_max_message_size;
  358. };
  359. } // namespace processor
  360. } // namespace websocketpp
  361. #endif // WEBSOCKETPP_PROCESSOR_HPP