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.

1665 lines
55 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  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_CONNECTION_HPP
  28. #define WEBSOCKETPP_CONNECTION_HPP
  29. #include <queue>
  30. #include <sstream>
  31. #include <string>
  32. #include <vector>
  33. #include <websocketpp/close.hpp>
  34. #include <websocketpp/common/connection_hdl.hpp>
  35. #include <websocketpp/common/cpp11.hpp>
  36. #include <websocketpp/common/functional.hpp>
  37. #include <websocketpp/error.hpp>
  38. #include <websocketpp/frame.hpp>
  39. #include <websocketpp/http/constants.hpp>
  40. #include <websocketpp/logger/levels.hpp>
  41. #include <websocketpp/processors/processor.hpp>
  42. #include <websocketpp/transport/base/connection.hpp>
  43. namespace websocketpp
  44. {
  45. /// The type and function signature of an open handler
  46. /**
  47. * The open handler is called once for every successful WebSocket connection
  48. * attempt. Either the fail handler or the open handler will be called for each
  49. * WebSocket connection attempt. HTTP Connections that did not attempt to
  50. * upgrade the connection to the WebSocket protocol will trigger the http
  51. * handler instead of fail/open.
  52. */
  53. typedef lib::function<void(connection_hdl)> open_handler;
  54. /// The type and function signature of a close handler
  55. /**
  56. * The close handler is called once for every successfully established
  57. * connection after it is no longer capable of sending or receiving new messages
  58. *
  59. * The close handler will be called exactly once for every connection for which
  60. * the open handler was called.
  61. */
  62. typedef lib::function<void(connection_hdl)> close_handler;
  63. /// The type and function signature of a fail handler
  64. /**
  65. * The fail handler is called once for every unsuccessful WebSocket connection
  66. * attempt. Either the fail handler or the open handler will be called for each
  67. * WebSocket connection attempt. HTTP Connections that did not attempt to
  68. * upgrade the connection to the WebSocket protocol will trigger the http
  69. * handler instead of fail/open.
  70. */
  71. typedef lib::function<void(connection_hdl)> fail_handler;
  72. /// The type and function signature of an interrupt handler
  73. /**
  74. * The interrupt handler is called when a connection receives an interrupt
  75. * request from the application. Interrupts allow the application to trigger a
  76. * handler to be run in the absense of a WebSocket level handler trigger (like
  77. * a new message).
  78. *
  79. * This is typically used by another application thread to schedule some tasks
  80. * that can only be run from within the handler chain for thread safety reasons.
  81. */
  82. typedef lib::function<void(connection_hdl)> interrupt_handler;
  83. /// The type and function signature of a ping handler
  84. /**
  85. * The ping handler is called when the connection receives a WebSocket ping
  86. * control frame. The string argument contains the ping payload. The payload is
  87. * a binary string up to 126 bytes in length. The ping handler returns a bool,
  88. * true if a pong response should be sent, false if the pong response should be
  89. * suppressed.
  90. */
  91. typedef lib::function<bool(connection_hdl, std::string)> ping_handler;
  92. /// The type and function signature of a pong handler
  93. /**
  94. * The pong handler is called when the connection receives a WebSocket pong
  95. * control frame. The string argument contains the pong payload. The payload is
  96. * a binary string up to 126 bytes in length.
  97. */
  98. typedef lib::function<void(connection_hdl, std::string)> pong_handler;
  99. /// The type and function signature of a pong timeout handler
  100. /**
  101. * The pong timeout handler is called when a ping goes unanswered by a pong for
  102. * longer than the locally specified timeout period.
  103. */
  104. typedef lib::function<void(connection_hdl, std::string)> pong_timeout_handler;
  105. /// The type and function signature of a validate handler
  106. /**
  107. * The validate handler is called after a WebSocket handshake has been received
  108. * and processed but before it has been accepted. This gives the application a
  109. * chance to implement connection details specific policies for accepting
  110. * connections and the ability to negotiate extensions and subprotocols.
  111. *
  112. * The validate handler return value indicates whether or not the connection
  113. * should be accepted. Additional methods may be called during the function to
  114. * set response headers, set HTTP return/error codes, etc.
  115. */
  116. typedef lib::function<bool(connection_hdl)> validate_handler;
  117. /// The type and function signature of a http handler
  118. /**
  119. * The http handler is called when an HTTP connection is made that does not
  120. * attempt to upgrade the connection to the WebSocket protocol. This allows
  121. * WebSocket++ servers to respond to these requests with regular HTTP responses.
  122. *
  123. * This can be used to deliver error pages & dashboards and to deliver static
  124. * files such as the base HTML & JavaScript for an otherwise single page
  125. * WebSocket application.
  126. *
  127. * Note: WebSocket++ is designed to be a high performance WebSocket server. It
  128. * is not tuned to provide a full featured, high performance, HTTP web server
  129. * solution. The HTTP handler is appropriate only for low volume HTTP traffic.
  130. * If you expect to serve high volumes of HTTP traffic a dedicated HTTP web
  131. * server is strongly recommended.
  132. *
  133. * The default HTTP handler will return a 426 Upgrade Required error. Custom
  134. * handlers may override the response status code to deliver any type of
  135. * response.
  136. */
  137. typedef lib::function<void(connection_hdl)> http_handler;
  138. //
  139. typedef lib::function<void(const lib::error_code & ec, size_t bytes_transferred)> read_handler;
  140. typedef lib::function<void(const lib::error_code & ec)> write_frame_handler;
  141. // constants related to the default WebSocket protocol versions available
  142. #ifdef _WEBSOCKETPP_INITIALIZER_LISTS_ // simplified C++11 version
  143. /// Container that stores the list of protocol versions supported
  144. /**
  145. * @todo Move this to configs to allow compile/runtime disabling or enabling
  146. * of protocol versions
  147. */
  148. static const std::vector<int> versions_supported = {0, 7, 8, 13};
  149. #else
  150. /// Helper array to get around lack of initializer lists pre C++11
  151. static const int helper[] = {0, 7, 8, 13};
  152. /// Container that stores the list of protocol versions supported
  153. /**
  154. * @todo Move this to configs to allow compile/runtime disabling or enabling
  155. * of protocol versions
  156. */
  157. static const std::vector<int> versions_supported(helper, helper + 4);
  158. #endif
  159. namespace session
  160. {
  161. namespace state
  162. {
  163. // externally visible session state (states based on the RFC)
  164. enum value
  165. {
  166. connecting = 0,
  167. open = 1,
  168. closing = 2,
  169. closed = 3
  170. };
  171. } // namespace state
  172. namespace fail
  173. {
  174. namespace status
  175. {
  176. enum value
  177. {
  178. GOOD = 0, // no failure yet!
  179. SYSTEM = 1, // system call returned error, check that code
  180. WEBSOCKET = 2, // websocket close codes contain error
  181. UNKNOWN = 3, // No failure information is available
  182. TIMEOUT_TLS = 4, // TLS handshake timed out
  183. TIMEOUT_WS = 5 // WS handshake timed out
  184. };
  185. } // namespace status
  186. } // namespace fail
  187. namespace internal_state
  188. {
  189. // More granular internal states. These are used for multi-threaded
  190. // connection synchronization and preventing values that are not yet or no
  191. // longer available from being used.
  192. enum value
  193. {
  194. USER_INIT = 0,
  195. TRANSPORT_INIT = 1,
  196. READ_HTTP_REQUEST = 2,
  197. WRITE_HTTP_REQUEST = 3,
  198. READ_HTTP_RESPONSE = 4,
  199. WRITE_HTTP_RESPONSE = 5,
  200. PROCESS_HTTP_REQUEST = 6,
  201. PROCESS_CONNECTION = 7
  202. };
  203. } // namespace internal_state
  204. namespace http_state
  205. {
  206. // states to keep track of the progress of http connections
  207. enum value
  208. {
  209. init = 0,
  210. deferred = 1,
  211. headers_written = 2,
  212. body_written = 3,
  213. closed = 4
  214. };
  215. } // namespace http_state
  216. } // namespace session
  217. /// Represents an individual WebSocket connection
  218. template <typename config> class connection : public config::transport_type::transport_con_type, public config::connection_base
  219. {
  220. public:
  221. /// Type of this connection
  222. typedef connection<config> type;
  223. /// Type of a shared pointer to this connection
  224. typedef lib::shared_ptr<type> ptr;
  225. /// Type of a weak pointer to this connection
  226. typedef lib::weak_ptr<type> weak_ptr;
  227. /// Type of the concurrency component of this connection
  228. typedef typename config::concurrency_type concurrency_type;
  229. /// Type of the access logging policy
  230. typedef typename config::alog_type alog_type;
  231. /// Type of the error logging policy
  232. typedef typename config::elog_type elog_type;
  233. /// Type of the transport component of this connection
  234. typedef typename config::transport_type::transport_con_type transport_con_type;
  235. /// Type of a shared pointer to the transport component of this connection
  236. typedef typename transport_con_type::ptr transport_con_ptr;
  237. typedef lib::function<void(ptr)> termination_handler;
  238. typedef typename concurrency_type::scoped_lock_type scoped_lock_type;
  239. typedef typename concurrency_type::mutex_type mutex_type;
  240. typedef typename config::request_type request_type;
  241. typedef typename config::response_type response_type;
  242. typedef typename config::message_type message_type;
  243. typedef typename message_type::ptr message_ptr;
  244. typedef typename config::con_msg_manager_type con_msg_manager_type;
  245. typedef typename con_msg_manager_type::ptr con_msg_manager_ptr;
  246. /// Type of RNG
  247. typedef typename config::rng_type rng_type;
  248. typedef processor::processor<config> processor_type;
  249. typedef lib::shared_ptr<processor_type> processor_ptr;
  250. // Message handler (needs to know message type)
  251. typedef lib::function<void(connection_hdl, message_ptr)> message_handler;
  252. /// Type of a pointer to a transport timer handle
  253. typedef typename transport_con_type::timer_ptr timer_ptr;
  254. // Misc Convenience Types
  255. typedef session::internal_state::value istate_type;
  256. private:
  257. enum terminate_status
  258. {
  259. failed = 1,
  260. closed,
  261. unknown
  262. };
  263. public:
  264. explicit connection(bool p_is_server, const std::string & ua, const lib::shared_ptr<alog_type> & alog, const lib::shared_ptr<elog_type> & elog, rng_type & rng) :
  265. transport_con_type(p_is_server, alog, elog),
  266. m_handle_read_frame(lib::bind(&type::handle_read_frame, this, lib::placeholders::_1, lib::placeholders::_2)),
  267. m_write_frame_handler(lib::bind(&type::handle_write_frame, this, lib::placeholders::_1)),
  268. m_user_agent(ua),
  269. m_open_handshake_timeout_dur(config::timeout_open_handshake),
  270. m_close_handshake_timeout_dur(config::timeout_close_handshake),
  271. m_pong_timeout_dur(config::timeout_pong),
  272. m_max_message_size(config::max_message_size),
  273. m_state(session::state::connecting),
  274. m_internal_state(session::internal_state::USER_INIT),
  275. m_msg_manager(new con_msg_manager_type()),
  276. m_send_buffer_size(0),
  277. m_write_flag(false),
  278. m_read_flag(true),
  279. m_is_server(p_is_server),
  280. m_alog(alog),
  281. m_elog(elog),
  282. m_rng(rng),
  283. m_local_close_code(close::status::abnormal_close),
  284. m_remote_close_code(close::status::abnormal_close),
  285. m_is_http(false),
  286. m_http_state(session::http_state::init),
  287. m_was_clean(false)
  288. {
  289. m_alog->write(log::alevel::devel, "connection constructor");
  290. }
  291. /// Get a shared pointer to this component
  292. ptr get_shared()
  293. {
  294. return lib::static_pointer_cast<type>(transport_con_type::get_shared());
  295. }
  296. ///////////////////////////
  297. // Set Handler Callbacks //
  298. ///////////////////////////
  299. /// Set open handler
  300. /**
  301. * The open handler is called after the WebSocket handshake is complete and
  302. * the connection is considered OPEN.
  303. *
  304. * @param h The new open_handler
  305. */
  306. void set_open_handler(open_handler h)
  307. {
  308. m_open_handler = h;
  309. }
  310. /// Set close handler
  311. /**
  312. * The close handler is called immediately after the connection is closed.
  313. *
  314. * @param h The new close_handler
  315. */
  316. void set_close_handler(close_handler h)
  317. {
  318. m_close_handler = h;
  319. }
  320. /// Set fail handler
  321. /**
  322. * The fail handler is called whenever the connection fails while the
  323. * handshake is bring processed.
  324. *
  325. * @param h The new fail_handler
  326. */
  327. void set_fail_handler(fail_handler h)
  328. {
  329. m_fail_handler = h;
  330. }
  331. /// Set ping handler
  332. /**
  333. * The ping handler is called whenever the connection receives a ping
  334. * control frame. The ping payload is included.
  335. *
  336. * The ping handler's return time controls whether or not a pong is
  337. * sent in response to this ping. Returning false will suppress the
  338. * return pong. If no ping handler is set a pong will be sent.
  339. *
  340. * @param h The new ping_handler
  341. */
  342. void set_ping_handler(ping_handler h)
  343. {
  344. m_ping_handler = h;
  345. }
  346. /// Set pong handler
  347. /**
  348. * The pong handler is called whenever the connection receives a pong
  349. * control frame. The pong payload is included.
  350. *
  351. * @param h The new pong_handler
  352. */
  353. void set_pong_handler(pong_handler h)
  354. {
  355. m_pong_handler = h;
  356. }
  357. /// Set pong timeout handler
  358. /**
  359. * If the transport component being used supports timers, the pong timeout
  360. * handler is called whenever a pong control frame is not received with the
  361. * configured timeout period after the application sends a ping.
  362. *
  363. * The config setting `timeout_pong` controls the length of the timeout
  364. * period. It is specified in milliseconds.
  365. *
  366. * This can be used to probe the health of the remote endpoint's WebSocket
  367. * implementation. This does not guarantee that the remote application
  368. * itself is still healthy but can be a useful diagnostic.
  369. *
  370. * Note: receipt of this callback doesn't mean the pong will never come.
  371. * This functionality will not suppress delivery of the pong in question
  372. * should it arrive after the timeout.
  373. *
  374. * @param h The new pong_timeout_handler
  375. */
  376. void set_pong_timeout_handler(pong_timeout_handler h)
  377. {
  378. m_pong_timeout_handler = h;
  379. }
  380. /// Set interrupt handler
  381. /**
  382. * The interrupt handler is called whenever the connection is manually
  383. * interrupted by the application.
  384. *
  385. * @param h The new interrupt_handler
  386. */
  387. void set_interrupt_handler(interrupt_handler h)
  388. {
  389. m_interrupt_handler = h;
  390. }
  391. /// Set http handler
  392. /**
  393. * The http handler is called after an HTTP request other than a WebSocket
  394. * upgrade request is received. It allows a WebSocket++ server to respond
  395. * to regular HTTP requests on the same port as it processes WebSocket
  396. * connections. This can be useful for hosting error messages, flash
  397. * policy files, status pages, and other simple HTTP responses. It is not
  398. * intended to be used as a primary web server.
  399. *
  400. * @param h The new http_handler
  401. */
  402. void set_http_handler(http_handler h)
  403. {
  404. m_http_handler = h;
  405. }
  406. /// Set validate handler
  407. /**
  408. * The validate handler is called after a WebSocket handshake has been
  409. * parsed but before a response is returned. It provides the application
  410. * a chance to examine the request and determine whether or not it wants
  411. * to accept the connection.
  412. *
  413. * Returning false from the validate handler will reject the connection.
  414. * If no validate handler is present, all connections will be allowed.
  415. *
  416. * @param h The new validate_handler
  417. */
  418. void set_validate_handler(validate_handler h)
  419. {
  420. m_validate_handler = h;
  421. }
  422. /// Set message handler
  423. /**
  424. * The message handler is called after a new message has been received.
  425. *
  426. * @param h The new message_handler
  427. */
  428. void set_message_handler(message_handler h)
  429. {
  430. m_message_handler = h;
  431. }
  432. //////////////////////////////////////////
  433. // Connection timeouts and other limits //
  434. //////////////////////////////////////////
  435. /// Set open handshake timeout
  436. /**
  437. * Sets the length of time the library will wait after an opening handshake
  438. * has been initiated before cancelling it. This can be used to prevent
  439. * excessive wait times for outgoing clients or excessive resource usage
  440. * from broken clients or DoS attacks on servers.
  441. *
  442. * Connections that time out will have their fail handlers called with the
  443. * open_handshake_timeout error code.
  444. *
  445. * The default value is specified via the compile time config value
  446. * 'timeout_open_handshake'. The default value in the core config
  447. * is 5000ms. A value of 0 will disable the timer entirely.
  448. *
  449. * To be effective, the transport you are using must support timers. See
  450. * the documentation for your transport policy for details about its
  451. * timer support.
  452. *
  453. * @param dur The length of the open handshake timeout in ms
  454. */
  455. void set_open_handshake_timeout(long dur)
  456. {
  457. m_open_handshake_timeout_dur = dur;
  458. }
  459. /// Set close handshake timeout
  460. /**
  461. * Sets the length of time the library will wait after a closing handshake
  462. * has been initiated before cancelling it. This can be used to prevent
  463. * excessive wait times for outgoing clients or excessive resource usage
  464. * from broken clients or DoS attacks on servers.
  465. *
  466. * Connections that time out will have their close handlers called with the
  467. * close_handshake_timeout error code.
  468. *
  469. * The default value is specified via the compile time config value
  470. * 'timeout_close_handshake'. The default value in the core config
  471. * is 5000ms. A value of 0 will disable the timer entirely.
  472. *
  473. * To be effective, the transport you are using must support timers. See
  474. * the documentation for your transport policy for details about its
  475. * timer support.
  476. *
  477. * @param dur The length of the close handshake timeout in ms
  478. */
  479. void set_close_handshake_timeout(long dur)
  480. {
  481. m_close_handshake_timeout_dur = dur;
  482. }
  483. /// Set pong timeout
  484. /**
  485. * Sets the length of time the library will wait for a pong response to a
  486. * ping. This can be used as a keepalive or to detect broken connections.
  487. *
  488. * Pong responses that time out will have the pong timeout handler called.
  489. *
  490. * The default value is specified via the compile time config value
  491. * 'timeout_pong'. The default value in the core config
  492. * is 5000ms. A value of 0 will disable the timer entirely.
  493. *
  494. * To be effective, the transport you are using must support timers. See
  495. * the documentation for your transport policy for details about its
  496. * timer support.
  497. *
  498. * @param dur The length of the pong timeout in ms
  499. */
  500. void set_pong_timeout(long dur)
  501. {
  502. m_pong_timeout_dur = dur;
  503. }
  504. /// Get maximum message size
  505. /**
  506. * Get maximum message size. Maximum message size determines the point at
  507. * which the connection will fail with the message_too_big protocol error.
  508. *
  509. * The default is set by the endpoint that creates the connection.
  510. *
  511. * @since 0.3.0
  512. */
  513. size_t get_max_message_size() const
  514. {
  515. return m_max_message_size;
  516. }
  517. /// Set maximum message size
  518. /**
  519. * Set maximum message size. Maximum message size determines the point at
  520. * which the connection will fail with the message_too_big protocol error.
  521. * This value may be changed during the connection.
  522. *
  523. * The default is set by the endpoint that creates the connection.
  524. *
  525. * @since 0.3.0
  526. *
  527. * @param new_value The value to set as the maximum message size.
  528. */
  529. void set_max_message_size(size_t new_value)
  530. {
  531. m_max_message_size = new_value;
  532. if (m_processor)
  533. {
  534. m_processor->set_max_message_size(new_value);
  535. }
  536. }
  537. /// Get maximum HTTP message body size
  538. /**
  539. * Get maximum HTTP message body size. Maximum message body size determines
  540. * the point at which the connection will stop reading an HTTP request whose
  541. * body is too large.
  542. *
  543. * The default is set by the endpoint that creates the connection.
  544. *
  545. * @since 0.5.0
  546. *
  547. * @return The maximum HTTP message body size
  548. */
  549. size_t get_max_http_body_size() const
  550. {
  551. return m_request.get_max_body_size();
  552. }
  553. /// Set maximum HTTP message body size
  554. /**
  555. * Set maximum HTTP message body size. Maximum message body size determines
  556. * the point at which the connection will stop reading an HTTP request whose
  557. * body is too large.
  558. *
  559. * The default is set by the endpoint that creates the connection.
  560. *
  561. * @since 0.5.0
  562. *
  563. * @param new_value The value to set as the maximum message size.
  564. */
  565. void set_max_http_body_size(size_t new_value)
  566. {
  567. m_request.set_max_body_size(new_value);
  568. }
  569. //////////////////////////////////
  570. // Uncategorized public methods //
  571. //////////////////////////////////
  572. /// Get the size of the outgoing write buffer (in payload bytes)
  573. /**
  574. * Retrieves the number of bytes in the outgoing write buffer that have not
  575. * already been dispatched to the transport layer. This represents the bytes
  576. * that are presently cancelable without uncleanly ending the websocket
  577. * connection
  578. *
  579. * This method invokes the m_write_lock mutex
  580. *
  581. * @return The current number of bytes in the outgoing send buffer.
  582. */
  583. size_t get_buffered_amount() const;
  584. /// Get the size of the outgoing write buffer (in payload bytes)
  585. /**
  586. * @deprecated use `get_buffered_amount` instead
  587. */
  588. size_t buffered_amount() const
  589. {
  590. return get_buffered_amount();
  591. }
  592. ////////////////////
  593. // Action Methods //
  594. ////////////////////
  595. /// Create a message and then add it to the outgoing send queue
  596. /**
  597. * Convenience method to send a message given a payload string and
  598. * optionally an opcode. Default opcode is utf8 text.
  599. *
  600. * This method locks the m_write_lock mutex
  601. *
  602. * @param payload The payload string to generated the message with
  603. *
  604. * @param op The opcode to generated the message with. Default is
  605. * frame::opcode::text
  606. */
  607. lib::error_code send(const std::string & payload, frame::opcode::value op = frame::opcode::text);
  608. /// Send a message (raw array overload)
  609. /**
  610. * Convenience method to send a message given a raw array and optionally an
  611. * opcode. Default opcode is binary.
  612. *
  613. * This method locks the m_write_lock mutex
  614. *
  615. * @param payload A pointer to the array containing the bytes to send.
  616. *
  617. * @param len Length of the array.
  618. *
  619. * @param op The opcode to generated the message with. Default is
  620. * frame::opcode::binary
  621. */
  622. lib::error_code send(const void * payload, size_t len, frame::opcode::value op = frame::opcode::binary);
  623. /// Add a message to the outgoing send queue
  624. /**
  625. * If presented with a prepared message it is added without validation or
  626. * framing. If presented with an unprepared message it is validated, framed,
  627. * and then added
  628. *
  629. * Errors are returned via an exception
  630. * \todo make exception system_error rather than error_code
  631. *
  632. * This method invokes the m_write_lock mutex
  633. *
  634. * @param msg A message_ptr to the message to send.
  635. */
  636. lib::error_code send(message_ptr msg);
  637. /// Asyncronously invoke handler::on_inturrupt
  638. /**
  639. * Signals to the connection to asyncronously invoke the on_inturrupt
  640. * callback for this connection's handler once it is safe to do so.
  641. *
  642. * When the on_inturrupt handler callback is called it will be from
  643. * within the transport event loop with all the thread safety features
  644. * guaranteed by the transport to regular handlers
  645. *
  646. * Multiple inturrupt signals can be active at once on the same connection
  647. *
  648. * @return An error code
  649. */
  650. lib::error_code interrupt();
  651. /// Transport inturrupt callback
  652. void handle_interrupt();
  653. /// Pause reading of new data
  654. /**
  655. * Signals to the connection to halt reading of new data. While reading is paused,
  656. * the connection will stop reading from its associated socket. In turn this will
  657. * result in TCP based flow control kicking in and slowing data flow from the remote
  658. * endpoint.
  659. *
  660. * This is useful for applications that push new requests to a queue to be processed
  661. * by another thread and need a way to signal when their request queue is full without
  662. * blocking the network processing thread.
  663. *
  664. * Use `resume_reading()` to resume.
  665. *
  666. * If supported by the transport this is done asynchronously. As such reading may not
  667. * stop until the current read operation completes. Typically you can expect to
  668. * receive no more bytes after initiating a read pause than the size of the read
  669. * buffer.
  670. *
  671. * If reading is paused for this connection already nothing is changed.
  672. */
  673. lib::error_code pause_reading();
  674. /// Pause reading callback
  675. void handle_pause_reading();
  676. /// Resume reading of new data
  677. /**
  678. * Signals to the connection to resume reading of new data after it was paused by
  679. * `pause_reading()`.
  680. *
  681. * If reading is not paused for this connection already nothing is changed.
  682. */
  683. lib::error_code resume_reading();
  684. /// Resume reading callback
  685. void handle_resume_reading();
  686. /// Send a ping
  687. /**
  688. * Initiates a ping with the given payload/
  689. *
  690. * There is no feedback directly from ping except in cases of immediately
  691. * detectable errors. Feedback will be provided via on_pong or
  692. * on_pong_timeout callbacks.
  693. *
  694. * Ping locks the m_write_lock mutex
  695. *
  696. * @param payload Payload to be used for the ping
  697. */
  698. void ping(const std::string & payload);
  699. /// exception free variant of ping
  700. void ping(const std::string & payload, lib::error_code & ec);
  701. /// Utility method that gets called back when the ping timer expires
  702. void handle_pong_timeout(std::string payload, const lib::error_code & ec);
  703. /// Send a pong
  704. /**
  705. * Initiates a pong with the given payload.
  706. *
  707. * There is no feedback from a pong once sent.
  708. *
  709. * Pong locks the m_write_lock mutex
  710. *
  711. * @param payload Payload to be used for the pong
  712. */
  713. void pong(const std::string & payload);
  714. /// exception free variant of pong
  715. void pong(const std::string & payload, lib::error_code & ec);
  716. /// Close the connection
  717. /**
  718. * Initiates the close handshake process.
  719. *
  720. * If close returns successfully the connection will be in the closing
  721. * state and no additional messages may be sent. All messages sent prior
  722. * to calling close will be written out before the connection is closed.
  723. *
  724. * If no reason is specified none will be sent. If no code is specified
  725. * then no code will be sent.
  726. *
  727. * The handler's on_close callback will be called once the close handshake
  728. * is complete.
  729. *
  730. * Reasons will be automatically truncated to the maximum length (123 bytes)
  731. * if necessary.
  732. *
  733. * @param code The close code to send
  734. * @param reason The close reason to send
  735. */
  736. void close(const close::status::value code, const std::string & reason);
  737. /// exception free variant of close
  738. void close(const close::status::value code, const std::string & reason, lib::error_code & ec);
  739. ////////////////////////////////////////////////
  740. // Pass-through access to the uri information //
  741. ////////////////////////////////////////////////
  742. /// Returns the secure flag from the connection URI
  743. /**
  744. * This value is available after the HTTP request has been fully read and
  745. * may be called from any thread.
  746. *
  747. * @return Whether or not the connection URI is flagged secure.
  748. */
  749. bool get_secure() const;
  750. /// Returns the host component of the connection URI
  751. /**
  752. * This value is available after the HTTP request has been fully read and
  753. * may be called from any thread.
  754. *
  755. * @return The host component of the connection URI
  756. */
  757. const std::string & get_host() const;
  758. /// Returns the resource component of the connection URI
  759. /**
  760. * This value is available after the HTTP request has been fully read and
  761. * may be called from any thread.
  762. *
  763. * @return The resource component of the connection URI
  764. */
  765. const std::string & get_resource() const;
  766. /// Returns the port component of the connection URI
  767. /**
  768. * This value is available after the HTTP request has been fully read and
  769. * may be called from any thread.
  770. *
  771. * @return The port component of the connection URI
  772. */
  773. uint16_t get_port() const;
  774. /// Gets the connection URI
  775. /**
  776. * This should really only be called by internal library methods unless you
  777. * really know what you are doing.
  778. *
  779. * @return A pointer to the connection's URI
  780. */
  781. uri_ptr get_uri() const;
  782. /// Sets the connection URI
  783. /**
  784. * This should really only be called by internal library methods unless you
  785. * really know what you are doing.
  786. *
  787. * @param uri The new URI to set
  788. */
  789. void set_uri(uri_ptr uri);
  790. /////////////////////////////
  791. // Subprotocol negotiation //
  792. /////////////////////////////
  793. /// Gets the negotated subprotocol
  794. /**
  795. * Retrieves the subprotocol that was negotiated during the handshake. This
  796. * method is valid in the open handler and later.
  797. *
  798. * @return The negotiated subprotocol
  799. */
  800. const std::string & get_subprotocol() const;
  801. /// Gets all of the subprotocols requested by the client
  802. /**
  803. * Retrieves the subprotocols that were requested during the handshake. This
  804. * method is valid in the validate handler and later.
  805. *
  806. * @return A vector of the requested subprotocol
  807. */
  808. const std::vector<std::string> & get_requested_subprotocols() const;
  809. /// Adds the given subprotocol string to the request list (exception free)
  810. /**
  811. * Adds a subprotocol to the list to send with the opening handshake. This
  812. * may be called multiple times to request more than one. If the server
  813. * supports one of these, it may choose one. If so, it will return it
  814. * in it's handshake reponse and the value will be available via
  815. * get_subprotocol(). Subprotocol requests should be added in order of
  816. * preference.
  817. *
  818. * @param request The subprotocol to request
  819. * @param ec A reference to an error code that will be filled in the case of
  820. * errors
  821. */
  822. void add_subprotocol(const std::string & request, lib::error_code & ec);
  823. /// Adds the given subprotocol string to the request list
  824. /**
  825. * Adds a subprotocol to the list to send with the opening handshake. This
  826. * may be called multiple times to request more than one. If the server
  827. * supports one of these, it may choose one. If so, it will return it
  828. * in it's handshake reponse and the value will be available via
  829. * get_subprotocol(). Subprotocol requests should be added in order of
  830. * preference.
  831. *
  832. * @param request The subprotocol to request
  833. */
  834. void add_subprotocol(const std::string & request);
  835. /// Select a subprotocol to use (exception free)
  836. /**
  837. * Indicates which subprotocol should be used for this connection. Valid
  838. * only during the validate handler callback. Subprotocol selected must have
  839. * been requested by the client. Consult get_requested_subprotocols() for a
  840. * list of valid subprotocols.
  841. *
  842. * This member function is valid on server endpoints/connections only
  843. *
  844. * @param value The subprotocol to select
  845. * @param ec A reference to an error code that will be filled in the case of
  846. * errors
  847. */
  848. void select_subprotocol(const std::string & value, lib::error_code & ec);
  849. /// Select a subprotocol to use
  850. /**
  851. * Indicates which subprotocol should be used for this connection. Valid
  852. * only during the validate handler callback. Subprotocol selected must have
  853. * been requested by the client. Consult get_requested_subprotocols() for a
  854. * list of valid subprotocols.
  855. *
  856. * This member function is valid on server endpoints/connections only
  857. *
  858. * @param value The subprotocol to select
  859. */
  860. void select_subprotocol(const std::string & value);
  861. /////////////////////////////////////////////////////////////
  862. // Pass-through access to the request and response objects //
  863. /////////////////////////////////////////////////////////////
  864. /// Retrieve a request header
  865. /**
  866. * Retrieve the value of a header from the handshake HTTP request.
  867. *
  868. * @param key Name of the header to get
  869. * @return The value of the header
  870. */
  871. const std::string & get_request_header(const std::string & key) const;
  872. /// Retrieve a request body
  873. /**
  874. * Retrieve the value of the request body. This value is typically used with
  875. * PUT and POST requests to upload files or other data. Only HTTP
  876. * connections will ever have bodies. WebSocket connection's will always
  877. * have blank bodies.
  878. *
  879. * @return The value of the request body.
  880. */
  881. const std::string & get_request_body() const;
  882. /// Retrieve a response header
  883. /**
  884. * Retrieve the value of a header from the handshake HTTP request.
  885. *
  886. * @param key Name of the header to get
  887. * @return The value of the header
  888. */
  889. const std::string & get_response_header(const std::string & key) const;
  890. /// Get response HTTP status code
  891. /**
  892. * Gets the response status code
  893. *
  894. * @since 0.7.0
  895. *
  896. * @return The response status code sent
  897. */
  898. http::status_code::value get_response_code() const
  899. {
  900. return m_response.get_status_code();
  901. }
  902. /// Get response HTTP status message
  903. /**
  904. * Gets the response status message
  905. *
  906. * @since 0.7.0
  907. *
  908. * @return The response status message sent
  909. */
  910. const std::string & get_response_msg() const
  911. {
  912. return m_response.get_status_msg();
  913. }
  914. /// Set response status code and message
  915. /**
  916. * Sets the response status code to `code` and looks up the corresponding
  917. * message for standard codes. Non-standard codes will be entered as Unknown
  918. * use set_status(status_code::value,std::string) overload to set both
  919. * values explicitly.
  920. *
  921. * This member function is valid only from the http() and validate() handler
  922. * callbacks.
  923. *
  924. * @param code Code to set
  925. * @param msg Message to set
  926. * @see websocketpp::http::response::set_status
  927. */
  928. void set_status(http::status_code::value code);
  929. /// Set response status code and message
  930. /**
  931. * Sets the response status code and message to independent custom values.
  932. * use set_status(status_code::value) to set the code and have the standard
  933. * message be automatically set.
  934. *
  935. * This member function is valid only from the http() and validate() handler
  936. * callbacks.
  937. *
  938. * @param code Code to set
  939. * @param msg Message to set
  940. * @see websocketpp::http::response::set_status
  941. */
  942. void set_status(http::status_code::value code, const std::string & msg);
  943. /// Set response body content
  944. /**
  945. * Set the body content of the HTTP response to the parameter string. Note
  946. * set_body will also set the Content-Length HTTP header to the appropriate
  947. * value. If you want the Content-Length header to be something else set it
  948. * to something else after calling set_body
  949. *
  950. * This member function is valid only from the http() and validate() handler
  951. * callbacks.
  952. *
  953. * @param value String data to include as the body content.
  954. * @see websocketpp::http::response::set_body
  955. */
  956. void set_body(const std::string & value);
  957. /// Append a header
  958. /**
  959. * If a header with this name already exists the value will be appended to
  960. * the existing header to form a comma separated list of values. Use
  961. * `connection::replace_header` to overwrite existing values.
  962. *
  963. * This member function is valid only from the http() and validate() handler
  964. * callbacks, or to a client connection before connect has been called.
  965. *
  966. * @param key Name of the header to set
  967. * @param val Value to add
  968. * @see replace_header
  969. * @see websocketpp::http::parser::append_header
  970. */
  971. void append_header(const std::string & key, const std::string & val);
  972. /// Replace a header
  973. /**
  974. * If a header with this name already exists the old value will be replaced
  975. * Use `connection::append_header` to append to a list of existing values.
  976. *
  977. * This member function is valid only from the http() and validate() handler
  978. * callbacks, or to a client connection before connect has been called.
  979. *
  980. * @param key Name of the header to set
  981. * @param val Value to set
  982. * @see append_header
  983. * @see websocketpp::http::parser::replace_header
  984. */
  985. void replace_header(const std::string & key, const std::string & val);
  986. /// Remove a header
  987. /**
  988. * Removes a header from the response.
  989. *
  990. * This member function is valid only from the http() and validate() handler
  991. * callbacks, or to a client connection before connect has been called.
  992. *
  993. * @param key The name of the header to remove
  994. * @see websocketpp::http::parser::remove_header
  995. */
  996. void remove_header(const std::string & key);
  997. /// Get request object
  998. /**
  999. * Direct access to request object. This can be used to call methods of the
  1000. * request object that are not part of the standard request API that
  1001. * connection wraps.
  1002. *
  1003. * Note use of this method involves using behavior specific to the
  1004. * configured HTTP policy. Such behavior may not work with alternate HTTP
  1005. * policies.
  1006. *
  1007. * @since 0.3.0-alpha3
  1008. *
  1009. * @return A const reference to the raw request object
  1010. */
  1011. const request_type & get_request() const
  1012. {
  1013. return m_request;
  1014. }
  1015. /// Get response object
  1016. /**
  1017. * Direct access to the HTTP response sent or received as a part of the
  1018. * opening handshake. This can be used to call methods of the response
  1019. * object that are not part of the standard request API that connection
  1020. * wraps.
  1021. *
  1022. * Note use of this method involves using behavior specific to the
  1023. * configured HTTP policy. Such behavior may not work with alternate HTTP
  1024. * policies.
  1025. *
  1026. * @since 0.7.0
  1027. *
  1028. * @return A const reference to the raw response object
  1029. */
  1030. const response_type & get_response() const
  1031. {
  1032. return m_response;
  1033. }
  1034. /// Defer HTTP Response until later (Exception free)
  1035. /**
  1036. * Used in the http handler to defer the HTTP response for this connection
  1037. * until later. Handshake timers will be canceled and the connection will be
  1038. * left open until `send_http_response` or an equivalent is called.
  1039. *
  1040. * Warning: deferred connections won't time out and as a result can tie up
  1041. * resources.
  1042. *
  1043. * @since 0.6.0
  1044. *
  1045. * @return A status code, zero on success, non-zero otherwise
  1046. */
  1047. lib::error_code defer_http_response();
  1048. /// Send deferred HTTP Response (exception free)
  1049. /**
  1050. * Sends an http response to an HTTP connection that was deferred. This will
  1051. * send a complete response including all headers, status line, and body
  1052. * text. The connection will be closed afterwards.
  1053. *
  1054. * @since 0.6.0
  1055. *
  1056. * @param ec A status code, zero on success, non-zero otherwise
  1057. */
  1058. void send_http_response(lib::error_code & ec);
  1059. /// Send deferred HTTP Response
  1060. void send_http_response();
  1061. // TODO HTTPNBIO: write_headers
  1062. // function that processes headers + status so far and writes it to the wire
  1063. // beginning the HTTP response body state. This method will ignore anything
  1064. // in the response body.
  1065. // TODO HTTPNBIO: write_body_message
  1066. // queues the specified message_buffer for async writing
  1067. // TODO HTTPNBIO: finish connection
  1068. //
  1069. // TODO HTTPNBIO: write_response
  1070. // Writes the whole response, headers + body and closes the connection
  1071. /////////////////////////////////////////////////////////////
  1072. // Pass-through access to the other connection information //
  1073. /////////////////////////////////////////////////////////////
  1074. /// Get Connection Handle
  1075. /**
  1076. * The connection handle is a token that can be shared outside the
  1077. * WebSocket++ core for the purposes of identifying a connection and
  1078. * sending it messages.
  1079. *
  1080. * @return A handle to the connection
  1081. */
  1082. connection_hdl get_handle() const
  1083. {
  1084. return m_connection_hdl;
  1085. }
  1086. /// Get whether or not this connection is part of a server or client
  1087. /**
  1088. * @return whether or not the connection is attached to a server endpoint
  1089. */
  1090. bool is_server() const
  1091. {
  1092. return m_is_server;
  1093. }
  1094. /// Return the same origin policy origin value from the opening request.
  1095. /**
  1096. * This value is available after the HTTP request has been fully read and
  1097. * may be called from any thread.
  1098. *
  1099. * @return The connection's origin value from the opening handshake.
  1100. */
  1101. const std::string & get_origin() const;
  1102. /// Return the connection state.
  1103. /**
  1104. * Values can be connecting, open, closing, and closed
  1105. *
  1106. * @return The connection's current state.
  1107. */
  1108. session::state::value get_state() const;
  1109. /// Get the WebSocket close code sent by this endpoint.
  1110. /**
  1111. * @return The WebSocket close code sent by this endpoint.
  1112. */
  1113. close::status::value get_local_close_code() const
  1114. {
  1115. return m_local_close_code;
  1116. }
  1117. /// Get the WebSocket close reason sent by this endpoint.
  1118. /**
  1119. * @return The WebSocket close reason sent by this endpoint.
  1120. */
  1121. const std::string & get_local_close_reason() const
  1122. {
  1123. return m_local_close_reason;
  1124. }
  1125. /// Get the WebSocket close code sent by the remote endpoint.
  1126. /**
  1127. * @return The WebSocket close code sent by the remote endpoint.
  1128. */
  1129. close::status::value get_remote_close_code() const
  1130. {
  1131. return m_remote_close_code;
  1132. }
  1133. /// Get the WebSocket close reason sent by the remote endpoint.
  1134. /**
  1135. * @return The WebSocket close reason sent by the remote endpoint.
  1136. */
  1137. const std::string & get_remote_close_reason() const
  1138. {
  1139. return m_remote_close_reason;
  1140. }
  1141. /// Get the internal error code for a closed/failed connection
  1142. /**
  1143. * Retrieves a machine readable detailed error code indicating the reason
  1144. * that the connection was closed or failed. Valid only after the close or
  1145. * fail handler is called.
  1146. *
  1147. * @return Error code indicating the reason the connection was closed or
  1148. * failed
  1149. */
  1150. lib::error_code get_ec() const
  1151. {
  1152. return m_ec;
  1153. }
  1154. /// Get a message buffer
  1155. /**
  1156. * Warning: The API related to directly sending message buffers may change
  1157. * before the 1.0 release. If you plan to use it, please keep an eye on any
  1158. * breaking changes notifications in future release notes. Also if you have
  1159. * any feedback about usage and capabilities now is a great time to provide
  1160. * it.
  1161. *
  1162. * Message buffers are used to store message payloads and other message
  1163. * metadata.
  1164. *
  1165. * The size parameter is a hint only. Your final payload does not need to
  1166. * match it. There may be some performance benefits if the initial size
  1167. * guess is equal to or slightly higher than the final payload size.
  1168. *
  1169. * @param op The opcode for the new message
  1170. * @param size A hint to optimize the initial allocation of payload space.
  1171. * @return A new message buffer
  1172. */
  1173. message_ptr get_message(websocketpp::frame::opcode::value op, size_t size) const
  1174. {
  1175. return m_msg_manager->get_message(op, size);
  1176. }
  1177. ////////////////////////////////////////////////////////////////////////
  1178. // The remaining public member functions are for internal/policy use //
  1179. // only. Do not call from application code unless you understand what //
  1180. // you are doing. //
  1181. ////////////////////////////////////////////////////////////////////////
  1182. void read_handshake(size_t num_bytes);
  1183. void handle_read_handshake(const lib::error_code & ec, size_t bytes_transferred);
  1184. void handle_read_http_response(const lib::error_code & ec, size_t bytes_transferred);
  1185. void handle_write_http_response(const lib::error_code & ec);
  1186. void handle_send_http_request(const lib::error_code & ec);
  1187. void handle_open_handshake_timeout(const lib::error_code & ec);
  1188. void handle_close_handshake_timeout(const lib::error_code & ec);
  1189. void handle_read_frame(const lib::error_code & ec, size_t bytes_transferred);
  1190. void read_frame();
  1191. /// Get array of WebSocket protocol versions that this connection supports.
  1192. const std::vector<int> & get_supported_versions() const;
  1193. /// Sets the handler for a terminating connection. Should only be used
  1194. /// internally by the endpoint class.
  1195. void set_termination_handler(termination_handler new_handler);
  1196. void terminate(const lib::error_code & ec);
  1197. void handle_terminate(terminate_status tstat, const lib::error_code & ec);
  1198. /// Checks if there are frames in the send queue and if there are sends one
  1199. /**
  1200. * \todo unit tests
  1201. *
  1202. * This method locks the m_write_lock mutex
  1203. */
  1204. void write_frame();
  1205. /// Process the results of a frame write operation and start the next write
  1206. /**
  1207. * \todo unit tests
  1208. *
  1209. * This method locks the m_write_lock mutex
  1210. *
  1211. * @param terminate Whether or not to terminate the connection upon
  1212. * completion of this write.
  1213. *
  1214. * @param ec A status code from the transport layer, zero on success,
  1215. * non-zero otherwise.
  1216. */
  1217. void handle_write_frame(const lib::error_code & ec);
  1218. // protected:
  1219. // This set of methods would really like to be protected, but doing so
  1220. // requires that the endpoint be able to friend the connection. This is
  1221. // allowed with C++11, but not prior versions
  1222. /// Start the connection state machine
  1223. void start();
  1224. /// Set Connection Handle
  1225. /**
  1226. * The connection handle is a token that can be shared outside the
  1227. * WebSocket++ core for the purposes of identifying a connection and
  1228. * sending it messages.
  1229. *
  1230. * @param hdl A connection_hdl that the connection will use to refer
  1231. * to itself.
  1232. */
  1233. void set_handle(connection_hdl hdl)
  1234. {
  1235. m_connection_hdl = hdl;
  1236. transport_con_type::set_handle(hdl);
  1237. }
  1238. protected:
  1239. void handle_transport_init(const lib::error_code & ec);
  1240. /// Set m_processor based on information in m_request. Set m_response
  1241. /// status and return an error code indicating status.
  1242. lib::error_code initialize_processor();
  1243. /// Perform WebSocket handshake validation of m_request using m_processor.
  1244. /// set m_response and return an error code indicating status.
  1245. lib::error_code process_handshake_request();
  1246. private:
  1247. /// Completes m_response, serializes it, and sends it out on the wire.
  1248. void write_http_response(const lib::error_code & ec);
  1249. /// Sends an opening WebSocket connect request
  1250. void send_http_request();
  1251. /// Alternate path for write_http_response in error conditions
  1252. void write_http_response_error(const lib::error_code & ec);
  1253. /// Process control message
  1254. /**
  1255. *
  1256. */
  1257. void process_control_frame(message_ptr msg);
  1258. /// Send close acknowledgement
  1259. /**
  1260. * If no arguments are present no close code/reason will be specified.
  1261. *
  1262. * Note: the close code/reason values provided here may be overrided by
  1263. * other settings (such as silent close).
  1264. *
  1265. * @param code The close code to send
  1266. * @param reason The close reason to send
  1267. * @return A status code, zero on success, non-zero otherwise
  1268. */
  1269. lib::error_code send_close_ack(close::status::value code = close::status::blank, const std::string & reason = std::string());
  1270. /// Send close frame
  1271. /**
  1272. * If no arguments are present no close code/reason will be specified.
  1273. *
  1274. * Note: the close code/reason values provided here may be overrided by
  1275. * other settings (such as silent close).
  1276. *
  1277. * The ack flag determines what to do in the case of a blank status and
  1278. * whether or not to terminate the TCP connection after sending it.
  1279. *
  1280. * @param code The close code to send
  1281. * @param reason The close reason to send
  1282. * @param ack Whether or not this is an acknowledgement close frame
  1283. * @return A status code, zero on success, non-zero otherwise
  1284. */
  1285. lib::error_code send_close_frame(close::status::value code = close::status::blank, const std::string & reason = std::string(), bool ack = false, bool terminal = false);
  1286. /// Get a pointer to a new WebSocket protocol processor for a given version
  1287. /**
  1288. * @param version Version number of the WebSocket protocol to get a
  1289. * processor for. Negative values indicate invalid/unknown versions and will
  1290. * always return a null ptr
  1291. *
  1292. * @return A shared_ptr to a new instance of the appropriate processor or a
  1293. * null ptr if there is no installed processor that matches the version
  1294. * number.
  1295. */
  1296. processor_ptr get_processor(int version) const;
  1297. /// Add a message to the write queue
  1298. /**
  1299. * Adds a message to the write queue and updates any associated shared state
  1300. *
  1301. * Must be called while holding m_write_lock
  1302. *
  1303. * @todo unit tests
  1304. *
  1305. * @param msg The message to push
  1306. */
  1307. void write_push(message_ptr msg);
  1308. /// Pop a message from the write queue
  1309. /**
  1310. * Removes and returns a message from the write queue and updates any
  1311. * associated shared state.
  1312. *
  1313. * Must be called while holding m_write_lock
  1314. *
  1315. * @todo unit tests
  1316. *
  1317. * @return the message_ptr at the front of the queue
  1318. */
  1319. message_ptr write_pop();
  1320. /// Prints information about the incoming connection to the access log
  1321. /**
  1322. * Prints information about the incoming connection to the access log.
  1323. * Includes: connection type, websocket version, remote endpoint, user agent
  1324. * path, status code.
  1325. */
  1326. void log_open_result();
  1327. /// Prints information about a connection being closed to the access log
  1328. /**
  1329. * Includes: local and remote close codes and reasons
  1330. */
  1331. void log_close_result();
  1332. /// Prints information about a connection being failed to the access log
  1333. /**
  1334. * Includes: error code and message for why it was failed
  1335. */
  1336. void log_fail_result();
  1337. /// Prints information about HTTP connections
  1338. /**
  1339. * Includes: TODO
  1340. */
  1341. void log_http_result();
  1342. /// Prints information about an arbitrary error code on the specified channel
  1343. template <typename error_type> void log_err(log::level l, const char * msg, const error_type & ec)
  1344. {
  1345. std::stringstream s;
  1346. s << msg << " error: " << ec << " (" << ec.message() << ")";
  1347. m_elog->write(l, s.str());
  1348. }
  1349. // internal handler functions
  1350. read_handler m_handle_read_frame;
  1351. write_frame_handler m_write_frame_handler;
  1352. // static settings
  1353. const std::string m_user_agent;
  1354. /// Pointer to the connection handle
  1355. connection_hdl m_connection_hdl;
  1356. /// Handler objects
  1357. open_handler m_open_handler;
  1358. close_handler m_close_handler;
  1359. fail_handler m_fail_handler;
  1360. ping_handler m_ping_handler;
  1361. pong_handler m_pong_handler;
  1362. pong_timeout_handler m_pong_timeout_handler;
  1363. interrupt_handler m_interrupt_handler;
  1364. http_handler m_http_handler;
  1365. validate_handler m_validate_handler;
  1366. message_handler m_message_handler;
  1367. /// constant values
  1368. long m_open_handshake_timeout_dur;
  1369. long m_close_handshake_timeout_dur;
  1370. long m_pong_timeout_dur;
  1371. size_t m_max_message_size;
  1372. /// External connection state
  1373. /**
  1374. * Lock: m_connection_state_lock
  1375. */
  1376. session::state::value m_state;
  1377. /// Internal connection state
  1378. /**
  1379. * Lock: m_connection_state_lock
  1380. */
  1381. istate_type m_internal_state;
  1382. mutable mutex_type m_connection_state_lock;
  1383. /// The lock used to protect the message queue
  1384. /**
  1385. * Serializes access to the write queue as well as shared state within the
  1386. * processor.
  1387. */
  1388. mutex_type m_write_lock;
  1389. // connection resources
  1390. char m_buf[config::connection_read_buffer_size];
  1391. size_t m_buf_cursor;
  1392. termination_handler m_termination_handler;
  1393. con_msg_manager_ptr m_msg_manager;
  1394. timer_ptr m_handshake_timer;
  1395. timer_ptr m_ping_timer;
  1396. /// @todo this is not memory efficient. this value is not used after the
  1397. /// handshake.
  1398. std::string m_handshake_buffer;
  1399. /// Pointer to the processor object for this connection
  1400. /**
  1401. * The processor provides functionality that is specific to the WebSocket
  1402. * protocol version that the client has negotiated. It also contains all of
  1403. * the state necessary to encode and decode the incoming and outgoing
  1404. * WebSocket byte streams
  1405. *
  1406. * Use of the prepare_data_frame method requires lock: m_write_lock
  1407. */
  1408. processor_ptr m_processor;
  1409. /// Queue of unsent outgoing messages
  1410. /**
  1411. * Lock: m_write_lock
  1412. */
  1413. std::queue<message_ptr> m_send_queue;
  1414. /// Size in bytes of the outstanding payloads in the write queue
  1415. /**
  1416. * Lock: m_write_lock
  1417. */
  1418. size_t m_send_buffer_size;
  1419. /// buffer holding the various parts of the current message being writen
  1420. /**
  1421. * Lock m_write_lock
  1422. */
  1423. std::vector<transport::buffer> m_send_buffer;
  1424. /// a list of pointers to hold on to the messages being written to keep them
  1425. /// from going out of scope before the write is complete.
  1426. std::vector<message_ptr> m_current_msgs;
  1427. /// True if there is currently an outstanding transport write
  1428. /**
  1429. * Lock m_write_lock
  1430. */
  1431. bool m_write_flag;
  1432. /// True if this connection is presently reading new data
  1433. bool m_read_flag;
  1434. // connection data
  1435. request_type m_request;
  1436. response_type m_response;
  1437. uri_ptr m_uri;
  1438. std::string m_subprotocol;
  1439. // connection data that might not be necessary to keep around for the life
  1440. // of the whole connection.
  1441. std::vector<std::string> m_requested_subprotocols;
  1442. const bool m_is_server;
  1443. const lib::shared_ptr<alog_type> m_alog;
  1444. const lib::shared_ptr<elog_type> m_elog;
  1445. rng_type & m_rng;
  1446. // Close state
  1447. /// Close code that was sent on the wire by this endpoint
  1448. close::status::value m_local_close_code;
  1449. /// Close reason that was sent on the wire by this endpoint
  1450. std::string m_local_close_reason;
  1451. /// Close code that was received on the wire from the remote endpoint
  1452. close::status::value m_remote_close_code;
  1453. /// Close reason that was received on the wire from the remote endpoint
  1454. std::string m_remote_close_reason;
  1455. /// Detailed internal error code
  1456. lib::error_code m_ec;
  1457. /// A flag that gets set once it is determined that the connection is an
  1458. /// HTTP connection and not a WebSocket one.
  1459. bool m_is_http;
  1460. /// A flag that gets set when the completion of an http connection is
  1461. /// deferred until later.
  1462. session::http_state::value m_http_state;
  1463. bool m_was_clean;
  1464. };
  1465. } // namespace websocketpp
  1466. #include <websocketpp/impl/connection_impl.hpp>
  1467. #endif // WEBSOCKETPP_CONNECTION_HPP