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.

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