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.

1146 lines
37 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_TRANSPORT_ASIO_CON_HPP
  28. #define WEBSOCKETPP_TRANSPORT_ASIO_CON_HPP
  29. #include <istream>
  30. #include <sstream>
  31. #include <string>
  32. #include <vector>
  33. #include <websocketpp/base64/base64.hpp>
  34. #include <websocketpp/common/asio.hpp>
  35. #include <websocketpp/common/chrono.hpp>
  36. #include <websocketpp/common/connection_hdl.hpp>
  37. #include <websocketpp/common/cpp11.hpp>
  38. #include <websocketpp/common/functional.hpp>
  39. #include <websocketpp/common/memory.hpp>
  40. #include <websocketpp/error.hpp>
  41. #include <websocketpp/http/constants.hpp>
  42. #include <websocketpp/logger/levels.hpp>
  43. #include <websocketpp/transport/asio/base.hpp>
  44. #include <websocketpp/transport/base/connection.hpp>
  45. #include <websocketpp/uri.hpp>
  46. namespace websocketpp
  47. {
  48. namespace transport
  49. {
  50. namespace asio
  51. {
  52. typedef lib::function<void(connection_hdl)> tcp_init_handler;
  53. /// Asio based connection transport component
  54. /**
  55. * transport::asio::connection implements a connection transport component using
  56. * Asio that works with the transport::asio::endpoint endpoint transport
  57. * component.
  58. */
  59. template <typename config> class connection : public config::socket_type::socket_con_type
  60. {
  61. public:
  62. /// Type of this connection transport component
  63. typedef connection<config> type;
  64. /// Type of a shared pointer to this connection transport component
  65. typedef lib::shared_ptr<type> ptr;
  66. /// Type of the socket connection component
  67. typedef typename config::socket_type::socket_con_type socket_con_type;
  68. /// Type of a shared pointer to the socket connection component
  69. typedef typename socket_con_type::ptr socket_con_ptr;
  70. /// Type of this transport's access logging policy
  71. typedef typename config::alog_type alog_type;
  72. /// Type of this transport's error logging policy
  73. typedef typename config::elog_type elog_type;
  74. typedef typename config::request_type request_type;
  75. typedef typename request_type::ptr request_ptr;
  76. typedef typename config::response_type response_type;
  77. typedef typename response_type::ptr response_ptr;
  78. /// Type of a pointer to the Asio io_service being used
  79. typedef lib::asio::io_service * io_service_ptr;
  80. /// Type of a pointer to the Asio io_service::strand being used
  81. typedef lib::shared_ptr<lib::asio::io_service::strand> strand_ptr;
  82. /// Type of a pointer to the Asio timer class
  83. typedef lib::shared_ptr<lib::asio::steady_timer> timer_ptr;
  84. // connection is friends with its associated endpoint to allow the endpoint
  85. // to call private/protected utility methods that we don't want to expose
  86. // to the public api.
  87. friend class endpoint<config>;
  88. // generate and manage our own io_service
  89. explicit connection(bool is_server, const lib::shared_ptr<alog_type> & alog, const lib::shared_ptr<elog_type> & elog) :
  90. m_is_server(is_server),
  91. m_alog(alog),
  92. m_elog(elog)
  93. {
  94. m_alog->write(log::alevel::devel, "asio con transport constructor");
  95. }
  96. /// Get a shared pointer to this component
  97. ptr get_shared()
  98. {
  99. return lib::static_pointer_cast<type>(socket_con_type::get_shared());
  100. }
  101. bool is_secure() const
  102. {
  103. return socket_con_type::is_secure();
  104. }
  105. /// Set uri hook
  106. /**
  107. * Called by the endpoint as a connection is being established to provide
  108. * the uri being connected to to the transport layer.
  109. *
  110. * This transport policy doesn't use the uri except to forward it to the
  111. * socket layer.
  112. *
  113. * @since 0.6.0
  114. *
  115. * @param u The uri to set
  116. */
  117. void set_uri(uri_ptr u)
  118. {
  119. socket_con_type::set_uri(u);
  120. }
  121. /// Sets the tcp pre init handler
  122. /**
  123. * The tcp pre init handler is called after the raw tcp connection has been
  124. * established but before any additional wrappers (proxy connects, TLS
  125. * handshakes, etc) have been performed.
  126. *
  127. * @since 0.3.0
  128. *
  129. * @param h The handler to call on tcp pre init.
  130. */
  131. void set_tcp_pre_init_handler(tcp_init_handler h)
  132. {
  133. m_tcp_pre_init_handler = h;
  134. }
  135. /// Sets the tcp pre init handler (deprecated)
  136. /**
  137. * The tcp pre init handler is called after the raw tcp connection has been
  138. * established but before any additional wrappers (proxy connects, TLS
  139. * handshakes, etc) have been performed.
  140. *
  141. * @deprecated Use set_tcp_pre_init_handler instead
  142. *
  143. * @param h The handler to call on tcp pre init.
  144. */
  145. void set_tcp_init_handler(tcp_init_handler h)
  146. {
  147. set_tcp_pre_init_handler(h);
  148. }
  149. /// Sets the tcp post init handler
  150. /**
  151. * The tcp post init handler is called after the tcp connection has been
  152. * established and all additional wrappers (proxy connects, TLS handshakes,
  153. * etc have been performed. This is fired before any bytes are read or any
  154. * WebSocket specific handshake logic has been performed.
  155. *
  156. * @since 0.3.0
  157. *
  158. * @param h The handler to call on tcp post init.
  159. */
  160. void set_tcp_post_init_handler(tcp_init_handler h)
  161. {
  162. m_tcp_post_init_handler = h;
  163. }
  164. /// Set the proxy to connect through (exception free)
  165. /**
  166. * The URI passed should be a complete URI including scheme. For example:
  167. * http://proxy.example.com:8080/
  168. *
  169. * The proxy must be set up as an explicit (CONNECT) proxy allowed to
  170. * connect to the port you specify. Traffic to the proxy is not encrypted.
  171. *
  172. * @param uri The full URI of the proxy to connect to.
  173. *
  174. * @param ec A status value
  175. */
  176. void set_proxy(const std::string & uri, lib::error_code & ec)
  177. {
  178. // TODO: return errors for illegal URIs here?
  179. // TODO: should https urls be illegal for the moment?
  180. m_proxy = uri;
  181. m_proxy_data = lib::make_shared<proxy_data>();
  182. ec = lib::error_code();
  183. }
  184. /// Set the proxy to connect through (exception)
  185. void set_proxy(const std::string & uri)
  186. {
  187. lib::error_code ec;
  188. set_proxy(uri, ec);
  189. if (ec)
  190. {
  191. throw exception(ec);
  192. }
  193. }
  194. /// Set the basic auth credentials to use (exception free)
  195. /**
  196. * The URI passed should be a complete URI including scheme. For example:
  197. * http://proxy.example.com:8080/
  198. *
  199. * The proxy must be set up as an explicit proxy
  200. *
  201. * @param username The username to send
  202. *
  203. * @param password The password to send
  204. *
  205. * @param ec A status value
  206. */
  207. void set_proxy_basic_auth(const std::string & username, const std::string & password, lib::error_code & ec)
  208. {
  209. if (! m_proxy_data)
  210. {
  211. ec = make_error_code(websocketpp::error::invalid_state);
  212. return;
  213. }
  214. // TODO: username can't contain ':'
  215. std::string val = "Basic " + base64_encode(username + ":" + password);
  216. m_proxy_data->req.replace_header("Proxy-Authorization", val);
  217. ec = lib::error_code();
  218. }
  219. /// Set the basic auth credentials to use (exception)
  220. void set_proxy_basic_auth(const std::string & username, const std::string & password)
  221. {
  222. lib::error_code ec;
  223. set_proxy_basic_auth(username, password, ec);
  224. if (ec)
  225. {
  226. throw exception(ec);
  227. }
  228. }
  229. /// Set the proxy timeout duration (exception free)
  230. /**
  231. * Duration is in milliseconds. Default value is based on the transport
  232. * config
  233. *
  234. * @param duration The number of milliseconds to wait before aborting the
  235. * proxy connection.
  236. *
  237. * @param ec A status value
  238. */
  239. void set_proxy_timeout(long duration, lib::error_code & ec)
  240. {
  241. if (! m_proxy_data)
  242. {
  243. ec = make_error_code(websocketpp::error::invalid_state);
  244. return;
  245. }
  246. m_proxy_data->timeout_proxy = duration;
  247. ec = lib::error_code();
  248. }
  249. /// Set the proxy timeout duration (exception)
  250. void set_proxy_timeout(long duration)
  251. {
  252. lib::error_code ec;
  253. set_proxy_timeout(duration, ec);
  254. if (ec)
  255. {
  256. throw exception(ec);
  257. }
  258. }
  259. const std::string & get_proxy() const
  260. {
  261. return m_proxy;
  262. }
  263. /// Get the remote endpoint address
  264. /**
  265. * The iostream transport has no information about the ultimate remote
  266. * endpoint. It will return the string "iostream transport". To indicate
  267. * this.
  268. *
  269. * TODO: allow user settable remote endpoint addresses if this seems useful
  270. *
  271. * @return A string identifying the address of the remote endpoint
  272. */
  273. std::string get_remote_endpoint() const
  274. {
  275. lib::error_code ec;
  276. std::string ret = socket_con_type::get_remote_endpoint(ec);
  277. if (ec)
  278. {
  279. m_elog->write(log::elevel::info, ret);
  280. return "Unknown";
  281. }
  282. else
  283. {
  284. return ret;
  285. }
  286. }
  287. /// Get the connection handle
  288. connection_hdl get_handle() const
  289. {
  290. return m_connection_hdl;
  291. }
  292. /// Call back a function after a period of time.
  293. /**
  294. * Sets a timer that calls back a function after the specified period of
  295. * milliseconds. Returns a handle that can be used to cancel the timer.
  296. * A cancelled timer will return the error code error::operation_aborted
  297. * A timer that expired will return no error.
  298. *
  299. * @param duration Length of time to wait in milliseconds
  300. *
  301. * @param callback The function to call back when the timer has expired
  302. *
  303. * @return A handle that can be used to cancel the timer if it is no longer
  304. * needed.
  305. */
  306. timer_ptr set_timer(long duration, timer_handler callback)
  307. {
  308. timer_ptr new_timer = lib::make_shared<lib::asio::steady_timer>(lib::ref(*m_io_service), lib::asio::milliseconds(duration));
  309. if (config::enable_multithreading)
  310. {
  311. new_timer->async_wait(m_strand->wrap(lib::bind(&type::handle_timer, get_shared(), new_timer, callback, lib::placeholders::_1)));
  312. }
  313. else
  314. {
  315. new_timer->async_wait(lib::bind(&type::handle_timer, get_shared(), new_timer, callback, lib::placeholders::_1));
  316. }
  317. return new_timer;
  318. }
  319. /// Timer callback
  320. /**
  321. * The timer pointer is included to ensure the timer isn't destroyed until
  322. * after it has expired.
  323. *
  324. * TODO: candidate for protected status
  325. *
  326. * @param post_timer Pointer to the timer in question
  327. * @param callback The function to call back
  328. * @param ec The status code
  329. */
  330. void handle_timer(timer_ptr, timer_handler callback, const lib::asio::error_code & ec)
  331. {
  332. if (ec)
  333. {
  334. if (ec == lib::asio::error::operation_aborted)
  335. {
  336. callback(make_error_code(transport::error::operation_aborted));
  337. }
  338. else
  339. {
  340. log_err(log::elevel::info, "asio handle_timer", ec);
  341. callback(make_error_code(error::pass_through));
  342. }
  343. }
  344. else
  345. {
  346. callback(lib::error_code());
  347. }
  348. }
  349. /// Get a pointer to this connection's strand
  350. strand_ptr get_strand()
  351. {
  352. return m_strand;
  353. }
  354. /// Get the internal transport error code for a closed/failed connection
  355. /**
  356. * Retrieves a machine readable detailed error code indicating the reason
  357. * that the connection was closed or failed. Valid only after the close or
  358. * fail handler is called.
  359. *
  360. * Primarily used if you are using mismatched asio / system_error
  361. * implementations such as `boost::asio` with `std::system_error`. In these
  362. * cases the transport error type is different than the library error type
  363. * and some WebSocket++ functions that return transport errors via the
  364. * library error code type will be coerced into a catch all `pass_through`
  365. * or `tls_error` error. This method will return the original machine
  366. * readable transport error in the native type.
  367. *
  368. * @since 0.7.0
  369. *
  370. * @return Error code indicating the reason the connection was closed or
  371. * failed
  372. */
  373. lib::asio::error_code get_transport_ec() const
  374. {
  375. return m_tec;
  376. }
  377. /// Initialize transport for reading
  378. /**
  379. * init_asio is called once immediately after construction to initialize
  380. * Asio components to the io_service
  381. *
  382. * The transport initialization sequence consists of the following steps:
  383. * - Pre-init: the underlying socket is initialized to the point where
  384. * bytes may be written. No bytes are actually written in this stage
  385. * - Proxy negotiation: if a proxy is set, a request is made to it to start
  386. * a tunnel to the final destination. This stage ends when the proxy is
  387. * ready to forward the
  388. * next byte to the remote endpoint.
  389. * - Post-init: Perform any i/o with the remote endpoint, such as setting up
  390. * tunnels for encryption. This stage ends when the connection is ready to
  391. * read or write the WebSocket handshakes. At this point the original
  392. * callback function is called.
  393. */
  394. protected:
  395. void init(init_handler callback)
  396. {
  397. if (m_alog->static_test(log::alevel::devel))
  398. {
  399. m_alog->write(log::alevel::devel, "asio connection init");
  400. }
  401. // TODO: pre-init timeout. Right now no implemented socket policies
  402. // actually have an asyncronous pre-init
  403. socket_con_type::pre_init(lib::bind(&type::handle_pre_init, get_shared(), callback, lib::placeholders::_1));
  404. }
  405. /// initialize the proxy buffers and http parsers
  406. /**
  407. *
  408. * @param authority The address of the server we want the proxy to tunnel to
  409. * in the format of a URI authority (host:port)
  410. *
  411. * @return Status code indicating what errors occurred, if any
  412. */
  413. lib::error_code proxy_init(const std::string & authority)
  414. {
  415. if (! m_proxy_data)
  416. {
  417. return websocketpp::error::make_error_code(websocketpp::error::invalid_state);
  418. }
  419. m_proxy_data->req.set_version("HTTP/1.1");
  420. m_proxy_data->req.set_method("CONNECT");
  421. m_proxy_data->req.set_uri(authority);
  422. m_proxy_data->req.replace_header("Host", authority);
  423. return lib::error_code();
  424. }
  425. /// Finish constructing the transport
  426. /**
  427. * init_asio is called once immediately after construction to initialize
  428. * Asio components to the io_service.
  429. *
  430. * @param io_service A pointer to the io_service to register with this
  431. * connection
  432. *
  433. * @return Status code for the success or failure of the initialization
  434. */
  435. lib::error_code init_asio(io_service_ptr io_service)
  436. {
  437. m_io_service = io_service;
  438. if (config::enable_multithreading)
  439. {
  440. m_strand = lib::make_shared<lib::asio::io_service::strand>(lib::ref(*io_service));
  441. }
  442. lib::error_code ec = socket_con_type::init_asio(io_service, m_strand, m_is_server);
  443. return ec;
  444. }
  445. void handle_pre_init(init_handler callback, const lib::error_code & ec)
  446. {
  447. if (m_alog->static_test(log::alevel::devel))
  448. {
  449. m_alog->write(log::alevel::devel, "asio connection handle pre_init");
  450. }
  451. if (m_tcp_pre_init_handler)
  452. {
  453. m_tcp_pre_init_handler(m_connection_hdl);
  454. }
  455. if (ec)
  456. {
  457. callback(ec);
  458. }
  459. // If we have a proxy set issue a proxy connect, otherwise skip to
  460. // post_init
  461. if (! m_proxy.empty())
  462. {
  463. proxy_write(callback);
  464. }
  465. else
  466. {
  467. post_init(callback);
  468. }
  469. }
  470. void post_init(init_handler callback)
  471. {
  472. if (m_alog->static_test(log::alevel::devel))
  473. {
  474. m_alog->write(log::alevel::devel, "asio connection post_init");
  475. }
  476. timer_ptr post_timer;
  477. if (config::timeout_socket_post_init > 0)
  478. {
  479. post_timer = set_timer(config::timeout_socket_post_init, lib::bind(&type::handle_post_init_timeout, get_shared(), post_timer, callback, lib::placeholders::_1));
  480. }
  481. socket_con_type::post_init(lib::bind(&type::handle_post_init, get_shared(), post_timer, callback, lib::placeholders::_1));
  482. }
  483. /// Post init timeout callback
  484. /**
  485. * The timer pointer is included to ensure the timer isn't destroyed until
  486. * after it has expired.
  487. *
  488. * @param post_timer Pointer to the timer in question
  489. * @param callback The function to call back
  490. * @param ec The status code
  491. */
  492. void handle_post_init_timeout(timer_ptr, init_handler callback, const lib::error_code & ec)
  493. {
  494. lib::error_code ret_ec;
  495. if (ec)
  496. {
  497. if (ec == transport::error::operation_aborted)
  498. {
  499. m_alog->write(log::alevel::devel, "asio post init timer cancelled");
  500. return;
  501. }
  502. log_err(log::elevel::devel, "asio handle_post_init_timeout", ec);
  503. ret_ec = ec;
  504. }
  505. else
  506. {
  507. if (socket_con_type::get_ec())
  508. {
  509. ret_ec = socket_con_type::get_ec();
  510. }
  511. else
  512. {
  513. ret_ec = make_error_code(transport::error::timeout);
  514. }
  515. }
  516. m_alog->write(log::alevel::devel, "Asio transport post-init timed out");
  517. cancel_socket_checked();
  518. callback(ret_ec);
  519. }
  520. /// Post init timeout callback
  521. /**
  522. * The timer pointer is included to ensure the timer isn't destroyed until
  523. * after it has expired.
  524. *
  525. * @param post_timer Pointer to the timer in question
  526. * @param callback The function to call back
  527. * @param ec The status code
  528. */
  529. void handle_post_init(timer_ptr post_timer, init_handler callback, const lib::error_code & ec)
  530. {
  531. if (ec == transport::error::operation_aborted || (post_timer && lib::asio::is_neg(post_timer->expires_from_now())))
  532. {
  533. m_alog->write(log::alevel::devel, "post_init cancelled");
  534. return;
  535. }
  536. if (post_timer)
  537. {
  538. post_timer->cancel();
  539. }
  540. if (m_alog->static_test(log::alevel::devel))
  541. {
  542. m_alog->write(log::alevel::devel, "asio connection handle_post_init");
  543. }
  544. if (m_tcp_post_init_handler)
  545. {
  546. m_tcp_post_init_handler(m_connection_hdl);
  547. }
  548. callback(ec);
  549. }
  550. void proxy_write(init_handler callback)
  551. {
  552. if (m_alog->static_test(log::alevel::devel))
  553. {
  554. m_alog->write(log::alevel::devel, "asio connection proxy_write");
  555. }
  556. if (! m_proxy_data)
  557. {
  558. m_elog->write(log::elevel::library, "assertion failed: !m_proxy_data in asio::connection::proxy_write");
  559. callback(make_error_code(error::general));
  560. return;
  561. }
  562. m_proxy_data->write_buf = m_proxy_data->req.raw();
  563. m_bufs.push_back(lib::asio::buffer(m_proxy_data->write_buf.data(), m_proxy_data->write_buf.size()));
  564. m_alog->write(log::alevel::devel, m_proxy_data->write_buf);
  565. // Set a timer so we don't wait forever for the proxy to respond
  566. m_proxy_data->timer = this->set_timer(m_proxy_data->timeout_proxy, lib::bind(&type::handle_proxy_timeout, get_shared(), callback, lib::placeholders::_1));
  567. // Send proxy request
  568. if (config::enable_multithreading)
  569. {
  570. lib::asio::async_write(socket_con_type::get_next_layer(), m_bufs, m_strand->wrap(lib::bind(&type::handle_proxy_write, get_shared(), callback, lib::placeholders::_1)));
  571. }
  572. else
  573. {
  574. lib::asio::async_write(socket_con_type::get_next_layer(), m_bufs, lib::bind(&type::handle_proxy_write, get_shared(), callback, lib::placeholders::_1));
  575. }
  576. }
  577. void handle_proxy_timeout(init_handler callback, const lib::error_code & ec)
  578. {
  579. if (ec == transport::error::operation_aborted)
  580. {
  581. m_alog->write(log::alevel::devel, "asio handle_proxy_write timer cancelled");
  582. return;
  583. }
  584. else if (ec)
  585. {
  586. log_err(log::elevel::devel, "asio handle_proxy_write", ec);
  587. callback(ec);
  588. }
  589. else
  590. {
  591. m_alog->write(log::alevel::devel, "asio handle_proxy_write timer expired");
  592. cancel_socket_checked();
  593. callback(make_error_code(transport::error::timeout));
  594. }
  595. }
  596. void handle_proxy_write(init_handler callback, const lib::asio::error_code & ec)
  597. {
  598. if (m_alog->static_test(log::alevel::devel))
  599. {
  600. m_alog->write(log::alevel::devel, "asio connection handle_proxy_write");
  601. }
  602. m_bufs.clear();
  603. // Timer expired or the operation was aborted for some reason.
  604. // Whatever aborted it will be issuing the callback so we are safe to
  605. // return
  606. if (ec == lib::asio::error::operation_aborted || lib::asio::is_neg(m_proxy_data->timer->expires_from_now()))
  607. {
  608. m_elog->write(log::elevel::devel, "write operation aborted");
  609. return;
  610. }
  611. if (ec)
  612. {
  613. log_err(log::elevel::info, "asio handle_proxy_write", ec);
  614. m_proxy_data->timer->cancel();
  615. callback(make_error_code(error::pass_through));
  616. return;
  617. }
  618. proxy_read(callback);
  619. }
  620. void proxy_read(init_handler callback)
  621. {
  622. if (m_alog->static_test(log::alevel::devel))
  623. {
  624. m_alog->write(log::alevel::devel, "asio connection proxy_read");
  625. }
  626. if (! m_proxy_data)
  627. {
  628. m_elog->write(log::elevel::library, "assertion failed: !m_proxy_data in asio::connection::proxy_read");
  629. m_proxy_data->timer->cancel();
  630. callback(make_error_code(error::general));
  631. return;
  632. }
  633. if (config::enable_multithreading)
  634. {
  635. lib::asio::async_read_until(socket_con_type::get_next_layer(), m_proxy_data->read_buf, "\r\n\r\n", m_strand->wrap(lib::bind(&type::handle_proxy_read, get_shared(), callback, lib::placeholders::_1, lib::placeholders::_2)));
  636. }
  637. else
  638. {
  639. lib::asio::async_read_until(socket_con_type::get_next_layer(), m_proxy_data->read_buf, "\r\n\r\n", lib::bind(&type::handle_proxy_read, get_shared(), callback, lib::placeholders::_1, lib::placeholders::_2));
  640. }
  641. }
  642. /// Proxy read callback
  643. /**
  644. * @param init_handler The function to call back
  645. * @param ec The status code
  646. * @param bytes_transferred The number of bytes read
  647. */
  648. void handle_proxy_read(init_handler callback, const lib::asio::error_code & ec, size_t)
  649. {
  650. if (m_alog->static_test(log::alevel::devel))
  651. {
  652. m_alog->write(log::alevel::devel, "asio connection handle_proxy_read");
  653. }
  654. // Timer expired or the operation was aborted for some reason.
  655. // Whatever aborted it will be issuing the callback so we are safe to
  656. // return
  657. if (ec == lib::asio::error::operation_aborted || lib::asio::is_neg(m_proxy_data->timer->expires_from_now()))
  658. {
  659. m_elog->write(log::elevel::devel, "read operation aborted");
  660. return;
  661. }
  662. // At this point there is no need to wait for the timer anymore
  663. m_proxy_data->timer->cancel();
  664. if (ec)
  665. {
  666. m_elog->write(log::elevel::info, "asio handle_proxy_read error: " + ec.message());
  667. callback(make_error_code(error::pass_through));
  668. }
  669. else
  670. {
  671. if (! m_proxy_data)
  672. {
  673. m_elog->write(log::elevel::library, "assertion failed: !m_proxy_data in asio::connection::handle_proxy_read");
  674. callback(make_error_code(error::general));
  675. return;
  676. }
  677. std::istream input(&m_proxy_data->read_buf);
  678. m_proxy_data->res.consume(input);
  679. if (! m_proxy_data->res.headers_ready())
  680. {
  681. // we read until the headers were done in theory but apparently
  682. // they aren't. Internal endpoint error.
  683. callback(make_error_code(error::general));
  684. return;
  685. }
  686. m_alog->write(log::alevel::devel, m_proxy_data->res.raw());
  687. if (m_proxy_data->res.get_status_code() != http::status_code::ok)
  688. {
  689. // got an error response back
  690. // TODO: expose this error in a programmatically accessible way?
  691. // if so, see below for an option on how to do this.
  692. std::stringstream s;
  693. s << "Proxy connection error: " << m_proxy_data->res.get_status_code() << " (" << m_proxy_data->res.get_status_msg() << ")";
  694. m_elog->write(log::elevel::info, s.str());
  695. callback(make_error_code(error::proxy_failed));
  696. return;
  697. }
  698. // we have successfully established a connection to the proxy, now
  699. // we can continue and the proxy will transparently forward the
  700. // WebSocket connection.
  701. // TODO: decide if we want an on_proxy callback that would allow
  702. // access to the proxy response.
  703. // free the proxy buffers and req/res objects as they aren't needed
  704. // anymore
  705. m_proxy_data.reset();
  706. // Continue with post proxy initialization
  707. post_init(callback);
  708. }
  709. }
  710. /// read at least num_bytes bytes into buf and then call handler.
  711. void async_read_at_least(size_t num_bytes, char * buf, size_t len, read_handler handler)
  712. {
  713. if (m_alog->static_test(log::alevel::devel))
  714. {
  715. std::stringstream s;
  716. s << "asio async_read_at_least: " << num_bytes;
  717. m_alog->write(log::alevel::devel, s.str());
  718. }
  719. // TODO: safety vs speed ?
  720. // maybe move into an if devel block
  721. /*if (num_bytes > len) {
  722. m_elog->write(log::elevel::devel,
  723. "asio async_read_at_least error::invalid_num_bytes");
  724. handler(make_error_code(transport::error::invalid_num_bytes),
  725. size_t(0));
  726. return;
  727. }*/
  728. if (config::enable_multithreading)
  729. {
  730. lib::asio::async_read(socket_con_type::get_socket(), lib::asio::buffer(buf, len), lib::asio::transfer_at_least(num_bytes),
  731. m_strand->wrap(make_custom_alloc_handler(m_read_handler_allocator, lib::bind(&type::handle_async_read, get_shared(), handler, lib::placeholders::_1, lib::placeholders::_2))));
  732. }
  733. else
  734. {
  735. lib::asio::async_read(socket_con_type::get_socket(), lib::asio::buffer(buf, len), lib::asio::transfer_at_least(num_bytes),
  736. make_custom_alloc_handler(m_read_handler_allocator, lib::bind(&type::handle_async_read, get_shared(), handler, lib::placeholders::_1, lib::placeholders::_2)));
  737. }
  738. }
  739. void handle_async_read(read_handler handler, const lib::asio::error_code & ec, size_t bytes_transferred)
  740. {
  741. m_alog->write(log::alevel::devel, "asio con handle_async_read");
  742. // translate asio error codes into more lib::error_codes
  743. lib::error_code tec;
  744. if (ec == lib::asio::error::eof)
  745. {
  746. tec = make_error_code(transport::error::eof);
  747. }
  748. else if (ec)
  749. {
  750. // We don't know much more about the error at this point. As our
  751. // socket/security policy if it knows more:
  752. tec = socket_con_type::translate_ec(ec);
  753. m_tec = ec;
  754. if (tec == transport::error::tls_error || tec == transport::error::pass_through)
  755. {
  756. // These are aggregate/catch all errors. Log some human readable
  757. // information to the info channel to give library users some
  758. // more details about why the upstream method may have failed.
  759. log_err(log::elevel::info, "asio async_read_at_least", ec);
  760. }
  761. }
  762. if (handler)
  763. {
  764. handler(tec, bytes_transferred);
  765. }
  766. else
  767. {
  768. // This can happen in cases where the connection is terminated while
  769. // the transport is waiting on a read.
  770. m_alog->write(log::alevel::devel, "handle_async_read called with null read handler");
  771. }
  772. }
  773. /// Initiate a potentially asyncronous write of the given buffer
  774. void async_write(const char * buf, size_t len, write_handler handler)
  775. {
  776. m_bufs.push_back(lib::asio::buffer(buf, len));
  777. if (config::enable_multithreading)
  778. {
  779. lib::asio::async_write(socket_con_type::get_socket(), m_bufs,
  780. m_strand->wrap(make_custom_alloc_handler(m_write_handler_allocator, lib::bind(&type::handle_async_write, get_shared(), handler, lib::placeholders::_1, lib::placeholders::_2))));
  781. }
  782. else
  783. {
  784. lib::asio::async_write(socket_con_type::get_socket(), m_bufs,
  785. make_custom_alloc_handler(m_write_handler_allocator, lib::bind(&type::handle_async_write, get_shared(), handler, lib::placeholders::_1, lib::placeholders::_2)));
  786. }
  787. }
  788. /// Initiate a potentially asyncronous write of the given buffers
  789. void async_write(const std::vector<buffer> & bufs, write_handler handler)
  790. {
  791. std::vector<buffer>::const_iterator it;
  792. for (it = bufs.begin(); it != bufs.end(); ++it)
  793. {
  794. m_bufs.push_back(lib::asio::buffer((*it).buf, (*it).len));
  795. }
  796. if (config::enable_multithreading)
  797. {
  798. lib::asio::async_write(socket_con_type::get_socket(), m_bufs,
  799. m_strand->wrap(make_custom_alloc_handler(m_write_handler_allocator, lib::bind(&type::handle_async_write, get_shared(), handler, lib::placeholders::_1, lib::placeholders::_2))));
  800. }
  801. else
  802. {
  803. lib::asio::async_write(socket_con_type::get_socket(), m_bufs,
  804. make_custom_alloc_handler(m_write_handler_allocator, lib::bind(&type::handle_async_write, get_shared(), handler, lib::placeholders::_1, lib::placeholders::_2)));
  805. }
  806. }
  807. /// Async write callback
  808. /**
  809. * @param ec The status code
  810. * @param bytes_transferred The number of bytes read
  811. */
  812. void handle_async_write(write_handler handler, const lib::asio::error_code & ec, size_t)
  813. {
  814. m_bufs.clear();
  815. lib::error_code tec;
  816. if (ec)
  817. {
  818. log_err(log::elevel::info, "asio async_write", ec);
  819. tec = make_error_code(transport::error::pass_through);
  820. }
  821. if (handler)
  822. {
  823. handler(tec);
  824. }
  825. else
  826. {
  827. // This can happen in cases where the connection is terminated while
  828. // the transport is waiting on a read.
  829. m_alog->write(log::alevel::devel, "handle_async_write called with null write handler");
  830. }
  831. }
  832. /// Set Connection Handle
  833. /**
  834. * See common/connection_hdl.hpp for information
  835. *
  836. * @param hdl A connection_hdl that the transport will use to refer
  837. * to itself
  838. */
  839. void set_handle(connection_hdl hdl)
  840. {
  841. m_connection_hdl = hdl;
  842. socket_con_type::set_handle(hdl);
  843. }
  844. /// Trigger the on_interrupt handler
  845. /**
  846. * This needs to be thread safe
  847. */
  848. lib::error_code interrupt(interrupt_handler handler)
  849. {
  850. if (config::enable_multithreading)
  851. {
  852. m_io_service->post(m_strand->wrap(handler));
  853. }
  854. else
  855. {
  856. m_io_service->post(handler);
  857. }
  858. return lib::error_code();
  859. }
  860. lib::error_code dispatch(dispatch_handler handler)
  861. {
  862. if (config::enable_multithreading)
  863. {
  864. m_io_service->post(m_strand->wrap(handler));
  865. }
  866. else
  867. {
  868. m_io_service->post(handler);
  869. }
  870. return lib::error_code();
  871. }
  872. /*void handle_interrupt(interrupt_handler handler) {
  873. handler();
  874. }*/
  875. /// close and clean up the underlying socket
  876. void async_shutdown(shutdown_handler callback)
  877. {
  878. if (m_alog->static_test(log::alevel::devel))
  879. {
  880. m_alog->write(log::alevel::devel, "asio connection async_shutdown");
  881. }
  882. timer_ptr shutdown_timer;
  883. shutdown_timer = set_timer(config::timeout_socket_shutdown, lib::bind(&type::handle_async_shutdown_timeout, get_shared(), shutdown_timer, callback, lib::placeholders::_1));
  884. socket_con_type::async_shutdown(lib::bind(&type::handle_async_shutdown, get_shared(), shutdown_timer, callback, lib::placeholders::_1));
  885. }
  886. /// Async shutdown timeout handler
  887. /**
  888. * @param shutdown_timer A pointer to the timer to keep it in scope
  889. * @param callback The function to call back
  890. * @param ec The status code
  891. */
  892. void handle_async_shutdown_timeout(timer_ptr, init_handler callback, const lib::error_code & ec)
  893. {
  894. lib::error_code ret_ec;
  895. if (ec)
  896. {
  897. if (ec == transport::error::operation_aborted)
  898. {
  899. m_alog->write(log::alevel::devel, "asio socket shutdown timer cancelled");
  900. return;
  901. }
  902. log_err(log::elevel::devel, "asio handle_async_shutdown_timeout", ec);
  903. ret_ec = ec;
  904. }
  905. else
  906. {
  907. ret_ec = make_error_code(transport::error::timeout);
  908. }
  909. m_alog->write(log::alevel::devel, "Asio transport socket shutdown timed out");
  910. cancel_socket_checked();
  911. callback(ret_ec);
  912. }
  913. void handle_async_shutdown(timer_ptr shutdown_timer, shutdown_handler callback, const lib::asio::error_code & ec)
  914. {
  915. if (ec == lib::asio::error::operation_aborted || lib::asio::is_neg(shutdown_timer->expires_from_now()))
  916. {
  917. m_alog->write(log::alevel::devel, "async_shutdown cancelled");
  918. return;
  919. }
  920. shutdown_timer->cancel();
  921. lib::error_code tec;
  922. if (ec)
  923. {
  924. if (ec == lib::asio::error::not_connected)
  925. {
  926. // The socket was already closed when we tried to close it. This
  927. // happens periodically (usually if a read or write fails
  928. // earlier and if it is a real error will be caught at another
  929. // level of the stack.
  930. }
  931. else
  932. {
  933. // We don't know anything more about this error, give our
  934. // socket/security policy a crack at it.
  935. tec = socket_con_type::translate_ec(ec);
  936. m_tec = ec;
  937. // all other errors are effectively pass through errors of
  938. // some sort so print some detail on the info channel for
  939. // library users to look up if needed.
  940. log_err(log::elevel::info, "asio async_shutdown", ec);
  941. }
  942. }
  943. else
  944. {
  945. if (m_alog->static_test(log::alevel::devel))
  946. {
  947. m_alog->write(log::alevel::devel, "asio con handle_async_shutdown");
  948. }
  949. }
  950. callback(tec);
  951. }
  952. /// Cancel the underlying socket and log any errors
  953. void cancel_socket_checked()
  954. {
  955. lib::asio::error_code cec = socket_con_type::cancel_socket();
  956. if (cec)
  957. {
  958. if (cec == lib::asio::error::operation_not_supported)
  959. {
  960. // cancel not supported on this OS, ignore and log at dev level
  961. m_alog->write(log::alevel::devel, "socket cancel not supported");
  962. }
  963. else
  964. {
  965. log_err(log::elevel::warn, "socket cancel failed", cec);
  966. }
  967. }
  968. }
  969. private:
  970. /// Convenience method for logging the code and message for an error_code
  971. template <typename error_type> void log_err(log::level l, const char * msg, const error_type & ec)
  972. {
  973. std::stringstream s;
  974. s << msg << " error: " << ec << " (" << ec.message() << ")";
  975. m_elog->write(l, s.str());
  976. }
  977. // static settings
  978. const bool m_is_server;
  979. lib::shared_ptr<alog_type> m_alog;
  980. lib::shared_ptr<elog_type> m_elog;
  981. struct proxy_data
  982. {
  983. proxy_data() :
  984. timeout_proxy(config::timeout_proxy)
  985. {
  986. }
  987. request_type req;
  988. response_type res;
  989. std::string write_buf;
  990. lib::asio::streambuf read_buf;
  991. long timeout_proxy;
  992. timer_ptr timer;
  993. };
  994. std::string m_proxy;
  995. lib::shared_ptr<proxy_data> m_proxy_data;
  996. // transport resources
  997. io_service_ptr m_io_service;
  998. strand_ptr m_strand;
  999. connection_hdl m_connection_hdl;
  1000. std::vector<lib::asio::const_buffer> m_bufs;
  1001. /// Detailed internal error code
  1002. lib::asio::error_code m_tec;
  1003. // Handlers
  1004. tcp_init_handler m_tcp_pre_init_handler;
  1005. tcp_init_handler m_tcp_post_init_handler;
  1006. handler_allocator m_read_handler_allocator;
  1007. handler_allocator m_write_handler_allocator;
  1008. };
  1009. } // namespace asio
  1010. } // namespace transport
  1011. } // namespace websocketpp
  1012. #endif // WEBSOCKETPP_TRANSPORT_ASIO_CON_HPP