WebSocket++  0.8.3-dev
C++ websocket client/server library
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Pages
connection.hpp
1 /*
2  * Copyright (c) 2014, Peter Thorson. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  * * Redistributions of source code must retain the above copyright
7  * notice, this list of conditions and the following disclaimer.
8  * * Redistributions in binary form must reproduce the above copyright
9  * notice, this list of conditions and the following disclaimer in the
10  * documentation and/or other materials provided with the distribution.
11  * * Neither the name of the WebSocket++ Project nor the
12  * names of its contributors may be used to endorse or promote products
13  * derived from this software without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY
19  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *
26  */
27 
28 #ifndef WEBSOCKETPP_TRANSPORT_DEBUG_CON_HPP
29 #define WEBSOCKETPP_TRANSPORT_DEBUG_CON_HPP
30 
31 #include <websocketpp/transport/debug/base.hpp>
32 
33 #include <websocketpp/transport/base/connection.hpp>
34 
35 #include <websocketpp/uri.hpp>
36 #include <websocketpp/logger/levels.hpp>
37 
38 #include <websocketpp/common/connection_hdl.hpp>
39 #include <websocketpp/common/memory.hpp>
40 #include <websocketpp/common/platforms.hpp>
41 
42 #include <string>
43 #include <vector>
44 
45 namespace websocketpp {
46 namespace transport {
47 namespace debug {
48 
49 /// Empty timer class to stub out for timer functionality that stub
50 /// transport doesn't support
51 struct timer {
52  void cancel() {}
53 };
54 
55 template <typename config>
56 class connection : public lib::enable_shared_from_this< connection<config> > {
57 public:
58  /// Type of this connection transport component
59  typedef connection<config> type;
60  /// Type of a shared pointer to this connection transport component
61  typedef lib::shared_ptr<type> ptr;
62 
63  /// transport concurrency policy
64  typedef typename config::concurrency_type concurrency_type;
65  /// Type of this transport's access logging policy
66  typedef typename config::alog_type alog_type;
67  /// Type of this transport's error logging policy
68  typedef typename config::elog_type elog_type;
69 
70  // Concurrency policy types
71  typedef typename concurrency_type::scoped_lock_type scoped_lock_type;
72  typedef typename concurrency_type::mutex_type mutex_type;
73 
74  typedef lib::shared_ptr<timer> timer_ptr;
75 
76  explicit connection(bool is_server, const lib::shared_ptr<alog_type> & alog, const lib::shared_ptr<elog_type> & elog)
77  : m_reading(false), m_is_server(is_server), m_alog(alog), m_elog(elog)
78  {
79  m_alog->write(log::alevel::devel,"debug con transport constructor");
80  }
81 
82  /// Get a shared pointer to this component
84  return type::shared_from_this();
85  }
86 
87  /// Set whether or not this connection is secure
88  /**
89  * Todo: docs
90  *
91  * @since 0.3.0-alpha4
92  *
93  * @param value Whether or not this connection is secure.
94  */
95  void set_secure(bool) {}
96 
97  /// Tests whether or not the underlying transport is secure
98  /**
99  * TODO: docs
100  *
101  * @return Whether or not the underlying transport is secure
102  */
103  bool is_secure() const {
104  return false;
105  }
106 
107  /// Set uri hook
108  /**
109  * Called by the endpoint as a connection is being established to provide
110  * the uri being connected to to the transport layer.
111  *
112  * Implementation is optional and can be ignored if the transport has no
113  * need for this information.
114  *
115  * @since 0.6.0
116  *
117  * @param u The uri to set
118  */
119  void set_uri(uri_ptr) {}
120 
121  /// Set human readable remote endpoint address
122  /**
123  * Sets the remote endpoint address returned by `get_remote_endpoint`. This
124  * value should be a human readable string that describes the remote
125  * endpoint. Typically an IP address or hostname, perhaps with a port. But
126  * may be something else depending on the nature of the underlying
127  * transport.
128  *
129  * If none is set a default is returned.
130  *
131  * @since 0.3.0-alpha4
132  *
133  * @param value The remote endpoint address to set.
134  */
136 
137  /// Get human readable remote endpoint address
138  /**
139  * TODO: docs
140  *
141  * This value is used in access and error logs and is available to the end
142  * application for including in user facing interfaces and messages.
143  *
144  * @return A string identifying the address of the remote endpoint
145  */
147  return "unknown (debug transport)";
148  }
149 
150  /// Get the connection handle
151  /**
152  * @return The handle for this connection.
153  */
155  return connection_hdl();
156  }
157 
158  /// Call back a function after a period of time.
159  /**
160  * Timers are not implemented in this transport. The timer pointer will
161  * always be empty. The handler will never be called.
162  *
163  * @param duration Length of time to wait in milliseconds
164  * @param callback The function to call back when the timer has expired
165  * @return A handle that can be used to cancel the timer if it is no longer
166  * needed.
167  */
169  m_alog->write(log::alevel::devel,"debug connection set timer");
170  m_timer_handler = handler;
171  return timer_ptr();
172  }
173 
174  /// Manual input supply (read all)
175  /**
176  * Similar to read_some, but continues to read until all bytes in the
177  * supplied buffer have been read or the connection runs out of read
178  * requests.
179  *
180  * This method still may not read all of the bytes in the input buffer. if
181  * it doesn't it indicates that the connection was most likely closed or
182  * is in an error state where it is no longer accepting new input.
183  *
184  * @since 0.3.0
185  *
186  * @param buf Char buffer to read into the websocket
187  * @param len Length of buf
188  * @return The number of characters from buf actually read.
189  */
190  size_t read_all(char const * buf, size_t len) {
191  size_t total_read = 0;
192  size_t temp_read = 0;
193 
194  do {
195  temp_read = this->read_some_impl(buf+total_read,len-total_read);
196  total_read += temp_read;
197  } while (temp_read != 0 && total_read < len);
198 
199  return total_read;
200  }
201 
202  // debug stuff to invoke the async handlers
203  void expire_timer(lib::error_code const & ec) {
204  m_timer_handler(ec);
205  }
206 
207  void fullfil_write() {
208  m_write_handler(lib::error_code());
209  }
210 protected:
211  /// Initialize the connection transport
212  /**
213  * Initialize the connection's transport component.
214  *
215  * @param handler The `init_handler` to call when initialization is done
216  */
217  void init(init_handler handler) {
218  m_alog->write(log::alevel::devel,"debug connection init");
219  handler(lib::error_code());
220  }
221 
222  /// Initiate an async_read for at least num_bytes bytes into buf
223  /**
224  * Initiates an async_read request for at least num_bytes bytes. The input
225  * will be read into buf. A maximum of len bytes will be input. When the
226  * operation is complete, handler will be called with the status and number
227  * of bytes read.
228  *
229  * This method may or may not call handler from within the initial call. The
230  * application should be prepared to accept either.
231  *
232  * The application should never call this method a second time before it has
233  * been called back for the first read. If this is done, the second read
234  * will be called back immediately with a double_read error.
235  *
236  * If num_bytes or len are zero handler will be called back immediately
237  * indicating success.
238  *
239  * @param num_bytes Don't call handler until at least this many bytes have
240  * been read.
241  * @param buf The buffer to read bytes into
242  * @param len The size of buf. At maximum, this many bytes will be read.
243  * @param handler The callback to invoke when the operation is complete or
244  * ends in an error
245  */
246  void async_read_at_least(size_t num_bytes, char * buf, size_t len,
247  read_handler handler)
248  {
249  std::stringstream s;
250  s << "debug_con async_read_at_least: " << num_bytes;
251  m_alog->write(log::alevel::devel,s.str());
252 
253  if (num_bytes > len) {
254  handler(make_error_code(error::invalid_num_bytes),size_t(0));
255  return;
256  }
257 
258  if (m_reading == true) {
259  handler(make_error_code(error::double_read),size_t(0));
260  return;
261  }
262 
263  if (num_bytes == 0 || len == 0) {
264  handler(lib::error_code(),size_t(0));
265  return;
266  }
267 
268  m_buf = buf;
269  m_len = len;
270  m_bytes_needed = num_bytes;
271  m_read_handler = handler;
272  m_cursor = 0;
273  m_reading = true;
274  }
275 
276  /// Asyncronous Transport Write
277  /**
278  * Write len bytes in buf to the output stream. Call handler to report
279  * success or failure. handler may or may not be called during async_write,
280  * but it must be safe for this to happen.
281  *
282  * Will return 0 on success.
283  *
284  * @param buf buffer to read bytes from
285  * @param len number of bytes to write
286  * @param handler Callback to invoke with operation status.
287  */
288  void async_write(char const *, size_t, write_handler handler) {
289  m_alog->write(log::alevel::devel,"debug_con async_write");
290  m_write_handler = handler;
291  }
292 
293  /// Asyncronous Transport Write (scatter-gather)
294  /**
295  * Write a sequence of buffers to the output stream. Call handler to report
296  * success or failure. handler may or may not be called during async_write,
297  * but it must be safe for this to happen.
298  *
299  * Will return 0 on success.
300  *
301  * @param bufs vector of buffers to write
302  * @param handler Callback to invoke with operation status.
303  */
305  m_alog->write(log::alevel::devel,"debug_con async_write buffer list");
306  m_write_handler = handler;
307  }
308 
309  /// Set Connection Handle
310  /**
311  * @param hdl The new handle
312  */
314 
315  /// Call given handler back within the transport's event system (if present)
316  /**
317  * Invoke a callback within the transport's event system if it has one. If
318  * it doesn't, the handler will be invoked immediately before this function
319  * returns.
320  *
321  * @param handler The callback to invoke
322  *
323  * @return Whether or not the transport was able to register the handler for
324  * callback.
325  */
327  handler();
328  return lib::error_code();
329  }
330 
331  /// Perform cleanup on socket shutdown_handler
332  /**
333  * @param h The `shutdown_handler` to call back when complete
334  */
335  void async_shutdown(shutdown_handler handler) {
336  handler(lib::error_code());
337  }
338 
339  size_t read_some_impl(char const * buf, size_t len) {
340  m_alog->write(log::alevel::devel,"debug_con read_some");
341 
342  if (!m_reading) {
343  m_elog->write(log::elevel::devel,"write while not reading");
344  return 0;
345  }
346 
347  size_t bytes_to_copy = (std::min)(len,m_len-m_cursor);
348 
349  std::copy(buf,buf+bytes_to_copy,m_buf+m_cursor);
350 
351  m_cursor += bytes_to_copy;
352 
353  if (m_cursor >= m_bytes_needed) {
354  complete_read(lib::error_code());
355  }
356 
357  return bytes_to_copy;
358  }
359 
360  /// Signal that a requested read is complete
361  /**
362  * Sets the reading flag to false and returns the handler that should be
363  * called back with the result of the read. The cursor position that is sent
364  * is whatever the value of m_cursor is.
365  *
366  * It MUST NOT be called when m_reading is false.
367  * it MUST be called while holding the read lock
368  *
369  * It is important to use this method rather than directly setting/calling
370  * m_read_handler back because this function makes sure to delete the
371  * locally stored handler which contains shared pointers that will otherwise
372  * cause circular reference based memory leaks.
373  *
374  * @param ec The error code to forward to the read handler
375  */
376  void complete_read(lib::error_code const & ec) {
377  m_reading = false;
378 
379  read_handler handler = m_read_handler;
380  m_read_handler = read_handler();
381 
382  handler(ec,m_cursor);
383  }
384 private:
385  timer_handler m_timer_handler;
386 
387  // Read space (Protected by m_read_mutex)
388  char * m_buf;
389  size_t m_len;
390  size_t m_bytes_needed;
391  read_handler m_read_handler;
392  size_t m_cursor;
393 
394  // transport resources
395  connection_hdl m_connection_hdl;
396  write_handler m_write_handler;
397  shutdown_handler m_shutdown_handler;
398 
399  bool m_reading;
400  bool const m_is_server;
401  bool m_is_secure;
402  lib::shared_ptr<alog_type> m_alog;
403  lib::shared_ptr<elog_type> m_elog;
404  std::string m_remote_endpoint;
405 };
406 
407 
408 } // namespace debug
409 } // namespace transport
410 } // namespace websocketpp
411 
412 #endif // WEBSOCKETPP_TRANSPORT_DEBUG_CON_HPP
websocketpp::transport::debug::connection::get_remote_endpoint
std::string get_remote_endpoint() const
Get human readable remote endpoint address.
Definition: connection.hpp:146
websocketpp::transport::debug::connection::set_remote_endpoint
void set_remote_endpoint(std::string)
Set human readable remote endpoint address.
Definition: connection.hpp:135
websocketpp::transport::debug::connection::concurrency_type
config::concurrency_type concurrency_type
transport concurrency policy
Definition: connection.hpp:64
websocketpp::transport::debug::connection::set_handle
void set_handle(connection_hdl)
Set Connection Handle.
Definition: connection.hpp:313
websocketpp::transport::debug::connection::async_read_at_least
void async_read_at_least(size_t num_bytes, char *buf, size_t len, read_handler handler)
Initiate an async_read for at least num_bytes bytes into buf.
Definition: connection.hpp:246
websocketpp::transport::debug::connection::alog_type
config::alog_type alog_type
Type of this transport's access logging policy.
Definition: connection.hpp:66
websocketpp::transport::debug::connection::async_write
void async_write(char const *, size_t, write_handler handler)
Asyncronous Transport Write.
Definition: connection.hpp:288
websocketpp::transport::debug::connection::complete_read
void complete_read(lib::error_code const &ec)
Signal that a requested read is complete.
Definition: connection.hpp:376
websocketpp::versions_supported
static std::vector< int > const versions_supported(helper, helper+4)
Container that stores the list of protocol versions supported.
websocketpp::transport::dispatch_handler
lib::function< void()> dispatch_handler
The type and signature of the callback passed to the dispatch method.
Definition: connection.hpp:135
websocketpp::transport::debug::connection::set_uri
void set_uri(uri_ptr)
Set uri hook.
Definition: connection.hpp:119
websocketpp::transport::debug
Definition: base.hpp:40
websocketpp::transport::debug::connection::set_timer
timer_ptr set_timer(long, timer_handler handler)
Call back a function after a period of time.
Definition: connection.hpp:168
websocketpp::transport::debug::connection::type
connection< config > type
Type of this connection transport component.
Definition: connection.hpp:59
websocketpp::transport::debug::connection::init
void init(init_handler handler)
Initialize the connection transport.
Definition: connection.hpp:217
websocketpp::transport::debug::connection::elog_type
config::elog_type elog_type
Type of this transport's error logging policy.
Definition: connection.hpp:68
websocketpp::transport::debug::connection::set_secure
void set_secure(bool)
Set whether or not this connection is secure.
Definition: connection.hpp:95
websocketpp::transport::debug::connection::async_shutdown
void async_shutdown(shutdown_handler handler)
Perform cleanup on socket shutdown_handler.
Definition: connection.hpp:335
websocketpp::transport::debug::connection::dispatch
lib::error_code dispatch(dispatch_handler handler)
Call given handler back within the transport's event system (if present)
Definition: connection.hpp:326
websocketpp::transport::debug::connection::async_write
void async_write(std::vector< buffer > const &, write_handler handler)
Asyncronous Transport Write (scatter-gather)
Definition: connection.hpp:304
websocketpp::transport::debug::timer
Definition: connection.hpp:51
websocketpp::transport::debug::connection::is_secure
bool is_secure() const
Tests whether or not the underlying transport is secure.
Definition: connection.hpp:103
websocketpp::transport::debug::connection::read_all
size_t read_all(char const *buf, size_t len)
Manual input supply (read all)
Definition: connection.hpp:190
websocketpp::transport::debug::connection::get_shared
ptr get_shared()
Get a shared pointer to this component.
Definition: connection.hpp:83
websocketpp::transport::debug::connection::get_handle
connection_hdl get_handle() const
Get the connection handle.
Definition: connection.hpp:154