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.

1186 lines
40 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_HPP
  28. #define WEBSOCKETPP_TRANSPORT_ASIO_HPP
  29. #include <websocketpp/transport/base/endpoint.hpp>
  30. #include <websocketpp/transport/asio/connection.hpp>
  31. #include <websocketpp/transport/asio/security/none.hpp>
  32. #include <websocketpp/uri.hpp>
  33. #include <websocketpp/logger/levels.hpp>
  34. #include <websocketpp/common/asio.hpp>
  35. #include <websocketpp/common/functional.hpp>
  36. #include <sstream>
  37. #include <string>
  38. namespace websocketpp {
  39. namespace transport {
  40. namespace asio {
  41. /// Asio based endpoint transport component
  42. /**
  43. * transport::asio::endpoint implements an endpoint transport component using
  44. * Asio.
  45. */
  46. template <typename config>
  47. class endpoint : public config::socket_type {
  48. public:
  49. /// Type of this endpoint transport component
  50. typedef endpoint<config> type;
  51. /// Type of the concurrency policy
  52. typedef typename config::concurrency_type concurrency_type;
  53. /// Type of the socket policy
  54. typedef typename config::socket_type socket_type;
  55. /// Type of the error logging policy
  56. typedef typename config::elog_type elog_type;
  57. /// Type of the access logging policy
  58. typedef typename config::alog_type alog_type;
  59. /// Type of the socket connection component
  60. typedef typename socket_type::socket_con_type socket_con_type;
  61. /// Type of a shared pointer to the socket connection component
  62. typedef typename socket_con_type::ptr socket_con_ptr;
  63. /// Type of the connection transport component associated with this
  64. /// endpoint transport component
  65. typedef asio::connection<config> transport_con_type;
  66. /// Type of a shared pointer to the connection transport component
  67. /// associated with this endpoint transport component
  68. typedef typename transport_con_type::ptr transport_con_ptr;
  69. /// Type of a pointer to the ASIO io_service being used
  70. typedef lib::asio::io_service * io_service_ptr;
  71. /// Type of a shared pointer to the acceptor being used
  72. typedef lib::shared_ptr<lib::asio::ip::tcp::acceptor> acceptor_ptr;
  73. /// Type of a shared pointer to the resolver being used
  74. typedef lib::shared_ptr<lib::asio::ip::tcp::resolver> resolver_ptr;
  75. /// Type of timer handle
  76. typedef lib::shared_ptr<lib::asio::steady_timer> timer_ptr;
  77. /// Type of a shared pointer to an io_service work object
  78. typedef lib::shared_ptr<lib::asio::io_service::work> work_ptr;
  79. /// Type of socket pre-bind handler
  80. typedef lib::function<lib::error_code(acceptor_ptr)> tcp_pre_bind_handler;
  81. // generate and manage our own io_service
  82. explicit endpoint()
  83. : m_io_service(NULL)
  84. , m_external_io_service(false)
  85. , m_listen_backlog(lib::asio::socket_base::max_connections)
  86. , m_reuse_addr(false)
  87. , m_state(UNINITIALIZED)
  88. {
  89. //std::cout << "transport::asio::endpoint constructor" << std::endl;
  90. }
  91. ~endpoint() {
  92. // clean up our io_service if we were initialized with an internal one.
  93. // Explicitly destroy local objects
  94. m_acceptor.reset();
  95. m_resolver.reset();
  96. m_work.reset();
  97. if (m_state != UNINITIALIZED && !m_external_io_service) {
  98. delete m_io_service;
  99. }
  100. }
  101. /// transport::asio objects are moveable but not copyable or assignable.
  102. /// The following code sets this situation up based on whether or not we
  103. /// have C++11 support or not
  104. #ifdef _WEBSOCKETPP_DEFAULT_DELETE_FUNCTIONS_
  105. endpoint(const endpoint & src) = delete;
  106. endpoint& operator= (const endpoint & rhs) = delete;
  107. #else
  108. private:
  109. endpoint(const endpoint & src);
  110. endpoint & operator= (const endpoint & rhs);
  111. public:
  112. #endif // _WEBSOCKETPP_DEFAULT_DELETE_FUNCTIONS_
  113. #ifdef _WEBSOCKETPP_MOVE_SEMANTICS_
  114. endpoint (endpoint && src)
  115. : config::socket_type(std::move(src))
  116. , m_tcp_pre_init_handler(src.m_tcp_pre_init_handler)
  117. , m_tcp_post_init_handler(src.m_tcp_post_init_handler)
  118. , m_io_service(src.m_io_service)
  119. , m_external_io_service(src.m_external_io_service)
  120. , m_acceptor(src.m_acceptor)
  121. , m_listen_backlog(lib::asio::socket_base::max_connections)
  122. , m_reuse_addr(src.m_reuse_addr)
  123. , m_elog(src.m_elog)
  124. , m_alog(src.m_alog)
  125. , m_state(src.m_state)
  126. {
  127. src.m_io_service = NULL;
  128. src.m_external_io_service = false;
  129. src.m_acceptor = NULL;
  130. src.m_state = UNINITIALIZED;
  131. }
  132. /*endpoint & operator= (const endpoint && rhs) {
  133. if (this != &rhs) {
  134. m_io_service = rhs.m_io_service;
  135. m_external_io_service = rhs.m_external_io_service;
  136. m_acceptor = rhs.m_acceptor;
  137. m_listen_backlog = rhs.m_listen_backlog;
  138. m_reuse_addr = rhs.m_reuse_addr;
  139. m_state = rhs.m_state;
  140. rhs.m_io_service = NULL;
  141. rhs.m_external_io_service = false;
  142. rhs.m_acceptor = NULL;
  143. rhs.m_listen_backlog = lib::asio::socket_base::max_connections;
  144. rhs.m_state = UNINITIALIZED;
  145. // TODO: this needs to be updated
  146. }
  147. return *this;
  148. }*/
  149. #endif // _WEBSOCKETPP_MOVE_SEMANTICS_
  150. /// Return whether or not the endpoint produces secure connections.
  151. bool is_secure() const {
  152. return socket_type::is_secure();
  153. }
  154. /// initialize asio transport with external io_service (exception free)
  155. /**
  156. * Initialize the ASIO transport policy for this endpoint using the provided
  157. * io_service object. asio_init must be called exactly once on any endpoint
  158. * that uses transport::asio before it can be used.
  159. *
  160. * @param ptr A pointer to the io_service to use for asio events
  161. * @param ec Set to indicate what error occurred, if any.
  162. */
  163. void init_asio(io_service_ptr ptr, lib::error_code & ec) {
  164. if (m_state != UNINITIALIZED) {
  165. m_elog->write(log::elevel::library,
  166. "asio::init_asio called from the wrong state");
  167. using websocketpp::error::make_error_code;
  168. ec = make_error_code(websocketpp::error::invalid_state);
  169. return;
  170. }
  171. m_alog->write(log::alevel::devel,"asio::init_asio");
  172. m_io_service = ptr;
  173. m_external_io_service = true;
  174. m_acceptor = lib::make_shared<lib::asio::ip::tcp::acceptor>(
  175. lib::ref(*m_io_service));
  176. m_state = READY;
  177. ec = lib::error_code();
  178. }
  179. /// initialize asio transport with external io_service
  180. /**
  181. * Initialize the ASIO transport policy for this endpoint using the provided
  182. * io_service object. asio_init must be called exactly once on any endpoint
  183. * that uses transport::asio before it can be used.
  184. *
  185. * @param ptr A pointer to the io_service to use for asio events
  186. */
  187. void init_asio(io_service_ptr ptr) {
  188. lib::error_code ec;
  189. init_asio(ptr,ec);
  190. if (ec) { throw exception(ec); }
  191. }
  192. /// Initialize asio transport with internal io_service (exception free)
  193. /**
  194. * This method of initialization will allocate and use an internally managed
  195. * io_service.
  196. *
  197. * @see init_asio(io_service_ptr ptr)
  198. *
  199. * @param ec Set to indicate what error occurred, if any.
  200. */
  201. void init_asio(lib::error_code & ec) {
  202. // Use a smart pointer until the call is successful and ownership has
  203. // successfully been taken. Use unique_ptr when available.
  204. // TODO: remove the use of auto_ptr when C++98/03 support is no longer
  205. // necessary.
  206. #ifdef _WEBSOCKETPP_CPP11_MEMORY_
  207. lib::unique_ptr<lib::asio::io_service> service(new lib::asio::io_service());
  208. #else
  209. lib::auto_ptr<lib::asio::io_service> service(new lib::asio::io_service());
  210. #endif
  211. init_asio(service.get(), ec);
  212. if( !ec ) service.release(); // Call was successful, transfer ownership
  213. m_external_io_service = false;
  214. }
  215. /// Initialize asio transport with internal io_service
  216. /**
  217. * This method of initialization will allocate and use an internally managed
  218. * io_service.
  219. *
  220. * @see init_asio(io_service_ptr ptr)
  221. */
  222. void init_asio() {
  223. // Use a smart pointer until the call is successful and ownership has
  224. // successfully been taken. Use unique_ptr when available.
  225. // TODO: remove the use of auto_ptr when C++98/03 support is no longer
  226. // necessary.
  227. #ifdef _WEBSOCKETPP_CPP11_MEMORY_
  228. lib::unique_ptr<lib::asio::io_service> service(new lib::asio::io_service());
  229. #else
  230. lib::auto_ptr<lib::asio::io_service> service(new lib::asio::io_service());
  231. #endif
  232. init_asio( service.get() );
  233. // If control got this far without an exception, then ownership has successfully been taken
  234. service.release();
  235. m_external_io_service = false;
  236. }
  237. /// Sets the tcp pre bind handler
  238. /**
  239. * The tcp pre bind handler is called after the listen acceptor has
  240. * been created but before the socket bind is performed.
  241. *
  242. * @since 0.8.0
  243. *
  244. * @param h The handler to call on tcp pre bind init.
  245. */
  246. void set_tcp_pre_bind_handler(tcp_pre_bind_handler h) {
  247. m_tcp_pre_bind_handler = h;
  248. }
  249. /// Sets the tcp pre init handler
  250. /**
  251. * The tcp pre init handler is called after the raw tcp connection has been
  252. * established but before any additional wrappers (proxy connects, TLS
  253. * handshakes, etc) have been performed.
  254. *
  255. * @since 0.3.0
  256. *
  257. * @param h The handler to call on tcp pre init.
  258. */
  259. void set_tcp_pre_init_handler(tcp_init_handler h) {
  260. m_tcp_pre_init_handler = h;
  261. }
  262. /// Sets the tcp pre init handler (deprecated)
  263. /**
  264. * The tcp pre init handler is called after the raw tcp connection has been
  265. * established but before any additional wrappers (proxy connects, TLS
  266. * handshakes, etc) have been performed.
  267. *
  268. * @deprecated Use set_tcp_pre_init_handler instead
  269. *
  270. * @param h The handler to call on tcp pre init.
  271. */
  272. void set_tcp_init_handler(tcp_init_handler h) {
  273. set_tcp_pre_init_handler(h);
  274. }
  275. /// Sets the tcp post init handler
  276. /**
  277. * The tcp post init handler is called after the tcp connection has been
  278. * established and all additional wrappers (proxy connects, TLS handshakes,
  279. * etc have been performed. This is fired before any bytes are read or any
  280. * WebSocket specific handshake logic has been performed.
  281. *
  282. * @since 0.3.0
  283. *
  284. * @param h The handler to call on tcp post init.
  285. */
  286. void set_tcp_post_init_handler(tcp_init_handler h) {
  287. m_tcp_post_init_handler = h;
  288. }
  289. /// Sets the maximum length of the queue of pending connections.
  290. /**
  291. * Sets the maximum length of the queue of pending connections. Increasing
  292. * this will allow WebSocket++ to queue additional incoming connections.
  293. * Setting it higher may prevent failed connections at high connection rates
  294. * but may cause additional latency.
  295. *
  296. * For this value to take effect you may need to adjust operating system
  297. * settings.
  298. *
  299. * New values affect future calls to listen only.
  300. *
  301. * The default value is specified as *::asio::socket_base::max_connections
  302. * which uses the operating system defined maximum queue length. Your OS
  303. * may restrict or silently lower this value. A value of zero may cause
  304. * all connections to be rejected.
  305. *
  306. * @since 0.3.0
  307. *
  308. * @param backlog The maximum length of the queue of pending connections
  309. */
  310. void set_listen_backlog(int backlog) {
  311. m_listen_backlog = backlog;
  312. }
  313. /// Sets whether to use the SO_REUSEADDR flag when opening listening sockets
  314. /**
  315. * Specifies whether or not to use the SO_REUSEADDR TCP socket option. What
  316. * this flag does depends on your operating system.
  317. *
  318. * Please consult operating system documentation for more details. There
  319. * may be security consequences to enabling this option.
  320. *
  321. * New values affect future calls to listen only so set this value prior to
  322. * calling listen.
  323. *
  324. * The default is false.
  325. *
  326. * @since 0.3.0
  327. *
  328. * @param value Whether or not to use the SO_REUSEADDR option
  329. */
  330. void set_reuse_addr(bool value) {
  331. m_reuse_addr = value;
  332. }
  333. /// Retrieve a reference to the endpoint's io_service
  334. /**
  335. * The io_service may be an internal or external one. This may be used to
  336. * call methods of the io_service that are not explicitly wrapped by the
  337. * endpoint.
  338. *
  339. * This method is only valid after the endpoint has been initialized with
  340. * `init_asio`. No error will be returned if it isn't.
  341. *
  342. * @return A reference to the endpoint's io_service
  343. */
  344. lib::asio::io_service & get_io_service() {
  345. return *m_io_service;
  346. }
  347. /// Get local TCP endpoint
  348. /**
  349. * Extracts the local endpoint from the acceptor. This represents the
  350. * address that WebSocket++ is listening on.
  351. *
  352. * Sets a bad_descriptor error if the acceptor is not currently listening
  353. * or otherwise unavailable.
  354. *
  355. * @since 0.7.0
  356. *
  357. * @param ec Set to indicate what error occurred, if any.
  358. * @return The local endpoint
  359. */
  360. lib::asio::ip::tcp::endpoint get_local_endpoint(lib::asio::error_code & ec) {
  361. if (m_acceptor) {
  362. return m_acceptor->local_endpoint(ec);
  363. } else {
  364. ec = lib::asio::error::make_error_code(lib::asio::error::bad_descriptor);
  365. return lib::asio::ip::tcp::endpoint();
  366. }
  367. }
  368. /// Set up endpoint for listening manually (exception free)
  369. /**
  370. * Bind the internal acceptor using the specified settings. The endpoint
  371. * must have been initialized by calling init_asio before listening.
  372. *
  373. * @param ep An endpoint to read settings from
  374. * @param ec Set to indicate what error occurred, if any.
  375. */
  376. void listen(lib::asio::ip::tcp::endpoint const & ep, lib::error_code & ec)
  377. {
  378. if (m_state != READY) {
  379. m_elog->write(log::elevel::library,
  380. "asio::listen called from the wrong state");
  381. using websocketpp::error::make_error_code;
  382. ec = make_error_code(websocketpp::error::invalid_state);
  383. return;
  384. }
  385. m_alog->write(log::alevel::devel,"asio::listen");
  386. lib::asio::error_code bec;
  387. m_acceptor->open(ep.protocol(),bec);
  388. if (bec) {ec = clean_up_listen_after_error(bec);return;}
  389. m_acceptor->set_option(lib::asio::socket_base::reuse_address(m_reuse_addr),bec);
  390. if (bec) {ec = clean_up_listen_after_error(bec);return;}
  391. // if a TCP pre-bind handler is present, run it
  392. if (m_tcp_pre_bind_handler) {
  393. ec = m_tcp_pre_bind_handler(m_acceptor);
  394. if (ec) {
  395. ec = clean_up_listen_after_error(ec);
  396. return;
  397. }
  398. }
  399. m_acceptor->bind(ep,bec);
  400. if (bec) {ec = clean_up_listen_after_error(bec);return;}
  401. m_acceptor->listen(m_listen_backlog,bec);
  402. if (bec) {ec = clean_up_listen_after_error(bec);return;}
  403. // Success
  404. m_state = LISTENING;
  405. ec = lib::error_code();
  406. }
  407. /// Set up endpoint for listening manually
  408. /**
  409. * Bind the internal acceptor using the settings specified by the endpoint e
  410. *
  411. * @param ep An endpoint to read settings from
  412. */
  413. void listen(lib::asio::ip::tcp::endpoint const & ep) {
  414. lib::error_code ec;
  415. listen(ep,ec);
  416. if (ec) { throw exception(ec); }
  417. }
  418. /// Set up endpoint for listening with protocol and port (exception free)
  419. /**
  420. * Bind the internal acceptor using the given internet protocol and port.
  421. * The endpoint must have been initialized by calling init_asio before
  422. * listening.
  423. *
  424. * Common options include:
  425. * - IPv6 with mapped IPv4 for dual stack hosts lib::asio::ip::tcp::v6()
  426. * - IPv4 only: lib::asio::ip::tcp::v4()
  427. *
  428. * @param internet_protocol The internet protocol to use.
  429. * @param port The port to listen on.
  430. * @param ec Set to indicate what error occurred, if any.
  431. */
  432. template <typename InternetProtocol>
  433. void listen(InternetProtocol const & internet_protocol, uint16_t port,
  434. lib::error_code & ec)
  435. {
  436. lib::asio::ip::tcp::endpoint ep(internet_protocol, port);
  437. listen(ep,ec);
  438. }
  439. /// Set up endpoint for listening with protocol and port
  440. /**
  441. * Bind the internal acceptor using the given internet protocol and port.
  442. * The endpoint must have been initialized by calling init_asio before
  443. * listening.
  444. *
  445. * Common options include:
  446. * - IPv6 with mapped IPv4 for dual stack hosts lib::asio::ip::tcp::v6()
  447. * - IPv4 only: lib::asio::ip::tcp::v4()
  448. *
  449. * @param internet_protocol The internet protocol to use.
  450. * @param port The port to listen on.
  451. */
  452. template <typename InternetProtocol>
  453. void listen(InternetProtocol const & internet_protocol, uint16_t port)
  454. {
  455. lib::asio::ip::tcp::endpoint ep(internet_protocol, port);
  456. listen(ep);
  457. }
  458. /// Set up endpoint for listening on a port (exception free)
  459. /**
  460. * Bind the internal acceptor using the given port. The IPv6 protocol with
  461. * mapped IPv4 for dual stack hosts will be used. If you need IPv4 only use
  462. * the overload that allows specifying the protocol explicitly.
  463. *
  464. * The endpoint must have been initialized by calling init_asio before
  465. * listening.
  466. *
  467. * @param port The port to listen on.
  468. * @param ec Set to indicate what error occurred, if any.
  469. */
  470. void listen(uint16_t port, lib::error_code & ec) {
  471. listen(lib::asio::ip::tcp::v6(), port, ec);
  472. }
  473. /// Set up endpoint for listening on a port
  474. /**
  475. * Bind the internal acceptor using the given port. The IPv6 protocol with
  476. * mapped IPv4 for dual stack hosts will be used. If you need IPv4 only use
  477. * the overload that allows specifying the protocol explicitly.
  478. *
  479. * The endpoint must have been initialized by calling init_asio before
  480. * listening.
  481. *
  482. * @param port The port to listen on.
  483. * @param ec Set to indicate what error occurred, if any.
  484. */
  485. void listen(uint16_t port) {
  486. listen(lib::asio::ip::tcp::v6(), port);
  487. }
  488. /// Set up endpoint for listening on a host and service (exception free)
  489. /**
  490. * Bind the internal acceptor using the given host and service. More details
  491. * about what host and service can be are available in the Asio
  492. * documentation for ip::basic_resolver_query::basic_resolver_query's
  493. * constructors.
  494. *
  495. * The endpoint must have been initialized by calling init_asio before
  496. * listening.
  497. *
  498. * @param host A string identifying a location. May be a descriptive name or
  499. * a numeric address string.
  500. * @param service A string identifying the requested service. This may be a
  501. * descriptive name or a numeric string corresponding to a port number.
  502. * @param ec Set to indicate what error occurred, if any.
  503. */
  504. void listen(std::string const & host, std::string const & service,
  505. lib::error_code & ec)
  506. {
  507. using lib::asio::ip::tcp;
  508. tcp::resolver r(*m_io_service);
  509. tcp::resolver::query query(host, service);
  510. tcp::resolver::iterator endpoint_iterator = r.resolve(query);
  511. tcp::resolver::iterator end;
  512. if (endpoint_iterator == end) {
  513. m_elog->write(log::elevel::library,
  514. "asio::listen could not resolve the supplied host or service");
  515. ec = make_error_code(error::invalid_host_service);
  516. return;
  517. }
  518. listen(*endpoint_iterator,ec);
  519. }
  520. /// Set up endpoint for listening on a host and service
  521. /**
  522. * Bind the internal acceptor using the given host and service. More details
  523. * about what host and service can be are available in the Asio
  524. * documentation for ip::basic_resolver_query::basic_resolver_query's
  525. * constructors.
  526. *
  527. * The endpoint must have been initialized by calling init_asio before
  528. * listening.
  529. *
  530. * @param host A string identifying a location. May be a descriptive name or
  531. * a numeric address string.
  532. * @param service A string identifying the requested service. This may be a
  533. * descriptive name or a numeric string corresponding to a port number.
  534. * @param ec Set to indicate what error occurred, if any.
  535. */
  536. void listen(std::string const & host, std::string const & service)
  537. {
  538. lib::error_code ec;
  539. listen(host,service,ec);
  540. if (ec) { throw exception(ec); }
  541. }
  542. /// Stop listening (exception free)
  543. /**
  544. * Stop listening and accepting new connections. This will not end any
  545. * existing connections.
  546. *
  547. * @since 0.3.0-alpha4
  548. * @param ec A status code indicating an error, if any.
  549. */
  550. void stop_listening(lib::error_code & ec) {
  551. if (m_state != LISTENING) {
  552. m_elog->write(log::elevel::library,
  553. "asio::listen called from the wrong state");
  554. using websocketpp::error::make_error_code;
  555. ec = make_error_code(websocketpp::error::invalid_state);
  556. return;
  557. }
  558. m_acceptor->close();
  559. m_state = READY;
  560. ec = lib::error_code();
  561. }
  562. /// Stop listening
  563. /**
  564. * Stop listening and accepting new connections. This will not end any
  565. * existing connections.
  566. *
  567. * @since 0.3.0-alpha4
  568. */
  569. void stop_listening() {
  570. lib::error_code ec;
  571. stop_listening(ec);
  572. if (ec) { throw exception(ec); }
  573. }
  574. /// Check if the endpoint is listening
  575. /**
  576. * @return Whether or not the endpoint is listening.
  577. */
  578. bool is_listening() const {
  579. return (m_state == LISTENING);
  580. }
  581. /// wraps the run method of the internal io_service object
  582. std::size_t run() {
  583. return m_io_service->run();
  584. }
  585. /// wraps the run_one method of the internal io_service object
  586. /**
  587. * @since 0.3.0-alpha4
  588. */
  589. std::size_t run_one() {
  590. return m_io_service->run_one();
  591. }
  592. /// wraps the stop method of the internal io_service object
  593. void stop() {
  594. m_io_service->stop();
  595. }
  596. /// wraps the poll method of the internal io_service object
  597. std::size_t poll() {
  598. return m_io_service->poll();
  599. }
  600. /// wraps the poll_one method of the internal io_service object
  601. std::size_t poll_one() {
  602. return m_io_service->poll_one();
  603. }
  604. /// wraps the reset method of the internal io_service object
  605. void reset() {
  606. m_io_service->reset();
  607. }
  608. /// wraps the stopped method of the internal io_service object
  609. bool stopped() const {
  610. return m_io_service->stopped();
  611. }
  612. /// Marks the endpoint as perpetual, stopping it from exiting when empty
  613. /**
  614. * Marks the endpoint as perpetual. Perpetual endpoints will not
  615. * automatically exit when they run out of connections to process. To stop
  616. * a perpetual endpoint call `end_perpetual`.
  617. *
  618. * An endpoint may be marked perpetual at any time by any thread. It must be
  619. * called either before the endpoint has run out of work or before it was
  620. * started
  621. *
  622. * @since 0.3.0
  623. */
  624. void start_perpetual() {
  625. m_work = lib::make_shared<lib::asio::io_service::work>(
  626. lib::ref(*m_io_service)
  627. );
  628. }
  629. /// Clears the endpoint's perpetual flag, allowing it to exit when empty
  630. /**
  631. * Clears the endpoint's perpetual flag. This will cause the endpoint's run
  632. * method to exit normally when it runs out of connections. If there are
  633. * currently active connections it will not end until they are complete.
  634. *
  635. * @since 0.3.0
  636. */
  637. void stop_perpetual() {
  638. m_work.reset();
  639. }
  640. /// Call back a function after a period of time.
  641. /**
  642. * Sets a timer that calls back a function after the specified period of
  643. * milliseconds. Returns a handle that can be used to cancel the timer.
  644. * A cancelled timer will return the error code error::operation_aborted
  645. * A timer that expired will return no error.
  646. *
  647. * @param duration Length of time to wait in milliseconds
  648. * @param callback The function to call back when the timer has expired
  649. * @return A handle that can be used to cancel the timer if it is no longer
  650. * needed.
  651. */
  652. timer_ptr set_timer(long duration, timer_handler callback) {
  653. timer_ptr new_timer = lib::make_shared<lib::asio::steady_timer>(
  654. *m_io_service,
  655. lib::asio::milliseconds(duration)
  656. );
  657. new_timer->async_wait(
  658. lib::bind(
  659. &type::handle_timer,
  660. this,
  661. new_timer,
  662. callback,
  663. lib::placeholders::_1
  664. )
  665. );
  666. return new_timer;
  667. }
  668. /// Timer handler
  669. /**
  670. * The timer pointer is included to ensure the timer isn't destroyed until
  671. * after it has expired.
  672. *
  673. * @param t Pointer to the timer in question
  674. * @param callback The function to call back
  675. * @param ec A status code indicating an error, if any.
  676. */
  677. void handle_timer(timer_ptr, timer_handler callback,
  678. lib::asio::error_code const & ec)
  679. {
  680. if (ec) {
  681. if (ec == lib::asio::error::operation_aborted) {
  682. callback(make_error_code(transport::error::operation_aborted));
  683. } else {
  684. m_elog->write(log::elevel::info,
  685. "asio handle_timer error: "+ec.message());
  686. log_err(log::elevel::info,"asio handle_timer",ec);
  687. callback(socket_con_type::translate_ec(ec));
  688. }
  689. } else {
  690. callback(lib::error_code());
  691. }
  692. }
  693. /// Accept the next connection attempt and assign it to con (exception free)
  694. /**
  695. * @param tcon The connection to accept into.
  696. * @param callback The function to call when the operation is complete.
  697. * @param ec A status code indicating an error, if any.
  698. */
  699. void async_accept(transport_con_ptr tcon, accept_handler callback,
  700. lib::error_code & ec)
  701. {
  702. if (m_state != LISTENING || !m_acceptor) {
  703. using websocketpp::error::make_error_code;
  704. ec = make_error_code(websocketpp::error::async_accept_not_listening);
  705. return;
  706. }
  707. m_alog->write(log::alevel::devel, "asio::async_accept");
  708. if (config::enable_multithreading) {
  709. m_acceptor->async_accept(
  710. tcon->get_raw_socket(),
  711. tcon->get_strand()->wrap(lib::bind(
  712. &type::handle_accept,
  713. this,
  714. callback,
  715. lib::placeholders::_1
  716. ))
  717. );
  718. } else {
  719. m_acceptor->async_accept(
  720. tcon->get_raw_socket(),
  721. lib::bind(
  722. &type::handle_accept,
  723. this,
  724. callback,
  725. lib::placeholders::_1
  726. )
  727. );
  728. }
  729. }
  730. /// Accept the next connection attempt and assign it to con.
  731. /**
  732. * @param tcon The connection to accept into.
  733. * @param callback The function to call when the operation is complete.
  734. */
  735. void async_accept(transport_con_ptr tcon, accept_handler callback) {
  736. lib::error_code ec;
  737. async_accept(tcon,callback,ec);
  738. if (ec) { throw exception(ec); }
  739. }
  740. protected:
  741. /// Initialize logging
  742. /**
  743. * The loggers are located in the main endpoint class. As such, the
  744. * transport doesn't have direct access to them. This method is called
  745. * by the endpoint constructor to allow shared logging from the transport
  746. * component. These are raw pointers to member variables of the endpoint.
  747. * In particular, they cannot be used in the transport constructor as they
  748. * haven't been constructed yet, and cannot be used in the transport
  749. * destructor as they will have been destroyed by then.
  750. */
  751. void init_logging(const lib::shared_ptr<alog_type>& a, const lib::shared_ptr<elog_type>& e) {
  752. m_alog = a;
  753. m_elog = e;
  754. }
  755. void handle_accept(accept_handler callback, lib::asio::error_code const &
  756. asio_ec)
  757. {
  758. lib::error_code ret_ec;
  759. m_alog->write(log::alevel::devel, "asio::handle_accept");
  760. if (asio_ec) {
  761. if (asio_ec == lib::asio::errc::operation_canceled) {
  762. ret_ec = make_error_code(websocketpp::error::operation_canceled);
  763. } else {
  764. log_err(log::elevel::info,"asio handle_accept",asio_ec);
  765. ret_ec = socket_con_type::translate_ec(asio_ec);
  766. }
  767. }
  768. callback(ret_ec);
  769. }
  770. /// Initiate a new connection
  771. // TODO: there have to be some more failure conditions here
  772. void async_connect(transport_con_ptr tcon, uri_ptr u, connect_handler cb) {
  773. using namespace lib::asio::ip;
  774. // Create a resolver
  775. if (!m_resolver) {
  776. m_resolver = lib::make_shared<lib::asio::ip::tcp::resolver>(
  777. lib::ref(*m_io_service));
  778. }
  779. tcon->set_uri(u);
  780. std::string proxy = tcon->get_proxy();
  781. std::string host;
  782. std::string port;
  783. if (proxy.empty()) {
  784. host = u->get_host();
  785. port = u->get_port_str();
  786. } else {
  787. lib::error_code ec;
  788. uri_ptr pu = lib::make_shared<uri>(proxy);
  789. if (!pu->get_valid()) {
  790. cb(make_error_code(error::proxy_invalid));
  791. return;
  792. }
  793. ec = tcon->proxy_init(u->get_authority());
  794. if (ec) {
  795. cb(ec);
  796. return;
  797. }
  798. host = pu->get_host();
  799. port = pu->get_port_str();
  800. }
  801. tcp::resolver::query query(host,port);
  802. if (m_alog->static_test(log::alevel::devel)) {
  803. m_alog->write(log::alevel::devel,
  804. "starting async DNS resolve for "+host+":"+port);
  805. }
  806. timer_ptr dns_timer;
  807. dns_timer = tcon->set_timer(
  808. config::timeout_dns_resolve,
  809. lib::bind(
  810. &type::handle_resolve_timeout,
  811. this,
  812. dns_timer,
  813. cb,
  814. lib::placeholders::_1
  815. )
  816. );
  817. if (config::enable_multithreading) {
  818. m_resolver->async_resolve(
  819. query,
  820. tcon->get_strand()->wrap(lib::bind(
  821. &type::handle_resolve,
  822. this,
  823. tcon,
  824. dns_timer,
  825. cb,
  826. lib::placeholders::_1,
  827. lib::placeholders::_2
  828. ))
  829. );
  830. } else {
  831. m_resolver->async_resolve(
  832. query,
  833. lib::bind(
  834. &type::handle_resolve,
  835. this,
  836. tcon,
  837. dns_timer,
  838. cb,
  839. lib::placeholders::_1,
  840. lib::placeholders::_2
  841. )
  842. );
  843. }
  844. }
  845. /// DNS resolution timeout handler
  846. /**
  847. * The timer pointer is included to ensure the timer isn't destroyed until
  848. * after it has expired.
  849. *
  850. * @param dns_timer Pointer to the timer in question
  851. * @param callback The function to call back
  852. * @param ec A status code indicating an error, if any.
  853. */
  854. void handle_resolve_timeout(timer_ptr, connect_handler callback,
  855. lib::error_code const & ec)
  856. {
  857. lib::error_code ret_ec;
  858. if (ec) {
  859. if (ec == transport::error::operation_aborted) {
  860. m_alog->write(log::alevel::devel,
  861. "asio handle_resolve_timeout timer cancelled");
  862. return;
  863. }
  864. log_err(log::elevel::devel,"asio handle_resolve_timeout",ec);
  865. ret_ec = ec;
  866. } else {
  867. ret_ec = make_error_code(transport::error::timeout);
  868. }
  869. m_alog->write(log::alevel::devel,"DNS resolution timed out");
  870. m_resolver->cancel();
  871. callback(ret_ec);
  872. }
  873. void handle_resolve(transport_con_ptr tcon, timer_ptr dns_timer,
  874. connect_handler callback, lib::asio::error_code const & ec,
  875. lib::asio::ip::tcp::resolver::iterator iterator)
  876. {
  877. if (ec == lib::asio::error::operation_aborted ||
  878. lib::asio::is_neg(dns_timer->expires_from_now()))
  879. {
  880. m_alog->write(log::alevel::devel,"async_resolve cancelled");
  881. return;
  882. }
  883. dns_timer->cancel();
  884. if (ec) {
  885. log_err(log::elevel::info,"asio async_resolve",ec);
  886. callback(socket_con_type::translate_ec(ec));
  887. return;
  888. }
  889. if (m_alog->static_test(log::alevel::devel)) {
  890. std::stringstream s;
  891. s << "Async DNS resolve successful. Results: ";
  892. lib::asio::ip::tcp::resolver::iterator it, end;
  893. for (it = iterator; it != end; ++it) {
  894. s << (*it).endpoint() << " ";
  895. }
  896. m_alog->write(log::alevel::devel,s.str());
  897. }
  898. m_alog->write(log::alevel::devel,"Starting async connect");
  899. timer_ptr con_timer;
  900. con_timer = tcon->set_timer(
  901. config::timeout_connect,
  902. lib::bind(
  903. &type::handle_connect_timeout,
  904. this,
  905. tcon,
  906. con_timer,
  907. callback,
  908. lib::placeholders::_1
  909. )
  910. );
  911. if (config::enable_multithreading) {
  912. lib::asio::async_connect(
  913. tcon->get_raw_socket(),
  914. iterator,
  915. tcon->get_strand()->wrap(lib::bind(
  916. &type::handle_connect,
  917. this,
  918. tcon,
  919. con_timer,
  920. callback,
  921. lib::placeholders::_1
  922. ))
  923. );
  924. } else {
  925. lib::asio::async_connect(
  926. tcon->get_raw_socket(),
  927. iterator,
  928. lib::bind(
  929. &type::handle_connect,
  930. this,
  931. tcon,
  932. con_timer,
  933. callback,
  934. lib::placeholders::_1
  935. )
  936. );
  937. }
  938. }
  939. /// Asio connect timeout handler
  940. /**
  941. * The timer pointer is included to ensure the timer isn't destroyed until
  942. * after it has expired.
  943. *
  944. * @param tcon Pointer to the transport connection that is being connected
  945. * @param con_timer Pointer to the timer in question
  946. * @param callback The function to call back
  947. * @param ec A status code indicating an error, if any.
  948. */
  949. void handle_connect_timeout(transport_con_ptr tcon, timer_ptr,
  950. connect_handler callback, lib::error_code const & ec)
  951. {
  952. lib::error_code ret_ec;
  953. if (ec) {
  954. if (ec == transport::error::operation_aborted) {
  955. m_alog->write(log::alevel::devel,
  956. "asio handle_connect_timeout timer cancelled");
  957. return;
  958. }
  959. log_err(log::elevel::devel,"asio handle_connect_timeout",ec);
  960. ret_ec = ec;
  961. } else {
  962. ret_ec = make_error_code(transport::error::timeout);
  963. }
  964. m_alog->write(log::alevel::devel,"TCP connect timed out");
  965. tcon->cancel_socket_checked();
  966. callback(ret_ec);
  967. }
  968. void handle_connect(transport_con_ptr tcon, timer_ptr con_timer,
  969. connect_handler callback, lib::asio::error_code const & ec)
  970. {
  971. if (ec == lib::asio::error::operation_aborted ||
  972. lib::asio::is_neg(con_timer->expires_from_now()))
  973. {
  974. m_alog->write(log::alevel::devel,"async_connect cancelled");
  975. return;
  976. }
  977. con_timer->cancel();
  978. if (ec) {
  979. log_err(log::elevel::info,"asio async_connect",ec);
  980. callback(socket_con_type::translate_ec(ec));
  981. return;
  982. }
  983. if (m_alog->static_test(log::alevel::devel)) {
  984. m_alog->write(log::alevel::devel,
  985. "Async connect to "+tcon->get_remote_endpoint()+" successful.");
  986. }
  987. callback(lib::error_code());
  988. }
  989. /// Initialize a connection
  990. /**
  991. * init is called by an endpoint once for each newly created connection.
  992. * It's purpose is to give the transport policy the chance to perform any
  993. * transport specific initialization that couldn't be done via the default
  994. * constructor.
  995. *
  996. * @param tcon A pointer to the transport portion of the connection.
  997. *
  998. * @return A status code indicating the success or failure of the operation
  999. */
  1000. lib::error_code init(transport_con_ptr tcon) {
  1001. m_alog->write(log::alevel::devel, "transport::asio::init");
  1002. // Initialize the connection socket component
  1003. socket_type::init(lib::static_pointer_cast<socket_con_type,
  1004. transport_con_type>(tcon));
  1005. lib::error_code ec;
  1006. ec = tcon->init_asio(m_io_service);
  1007. if (ec) {return ec;}
  1008. tcon->set_tcp_pre_init_handler(m_tcp_pre_init_handler);
  1009. tcon->set_tcp_post_init_handler(m_tcp_post_init_handler);
  1010. return lib::error_code();
  1011. }
  1012. private:
  1013. /// Convenience method for logging the code and message for an error_code
  1014. template <typename error_type>
  1015. void log_err(log::level l, char const * msg, error_type const & ec) {
  1016. std::stringstream s;
  1017. s << msg << " error: " << ec << " (" << ec.message() << ")";
  1018. m_elog->write(l,s.str());
  1019. }
  1020. /// Helper for cleaning up in the listen method after an error
  1021. template <typename error_type>
  1022. lib::error_code clean_up_listen_after_error(error_type const & ec) {
  1023. if (m_acceptor->is_open()) {
  1024. m_acceptor->close();
  1025. }
  1026. log_err(log::elevel::info,"asio listen",ec);
  1027. return socket_con_type::translate_ec(ec);
  1028. }
  1029. enum state {
  1030. UNINITIALIZED = 0,
  1031. READY = 1,
  1032. LISTENING = 2
  1033. };
  1034. // Handlers
  1035. tcp_pre_bind_handler m_tcp_pre_bind_handler;
  1036. tcp_init_handler m_tcp_pre_init_handler;
  1037. tcp_init_handler m_tcp_post_init_handler;
  1038. // Network Resources
  1039. io_service_ptr m_io_service;
  1040. bool m_external_io_service;
  1041. acceptor_ptr m_acceptor;
  1042. resolver_ptr m_resolver;
  1043. work_ptr m_work;
  1044. // Network constants
  1045. int m_listen_backlog;
  1046. bool m_reuse_addr;
  1047. lib::shared_ptr<elog_type> m_elog;
  1048. lib::shared_ptr<alog_type> m_alog;
  1049. // Transport state
  1050. state m_state;
  1051. };
  1052. } // namespace asio
  1053. } // namespace transport
  1054. } // namespace websocketpp
  1055. #endif // WEBSOCKETPP_TRANSPORT_ASIO_HPP