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