connection.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. #ifndef WEBSOCKETPP_TRANSPORT_DEBUG_CON_HPP
  28. #define WEBSOCKETPP_TRANSPORT_DEBUG_CON_HPP
  29. #include <websocketpp/transport/debug/base.hpp>
  30. #include <websocketpp/transport/base/connection.hpp>
  31. #include <websocketpp/uri.hpp>
  32. #include <websocketpp/logger/levels.hpp>
  33. #include <websocketpp/common/connection_hdl.hpp>
  34. #include <websocketpp/common/memory.hpp>
  35. #include <websocketpp/common/platforms.hpp>
  36. #include <string>
  37. #include <vector>
  38. namespace websocketpp {
  39. namespace transport {
  40. namespace debug {
  41. /// Empty timer class to stub out for timer functionality that stub
  42. /// transport doesn't support
  43. struct timer {
  44. void cancel() {}
  45. };
  46. template <typename config>
  47. class connection : public lib::enable_shared_from_this< connection<config> > {
  48. public:
  49. /// Type of this connection transport component
  50. typedef connection<config> type;
  51. /// Type of a shared pointer to this connection transport component
  52. typedef lib::shared_ptr<type> ptr;
  53. /// transport concurrency policy
  54. typedef typename config::concurrency_type concurrency_type;
  55. /// Type of this transport's access logging policy
  56. typedef typename config::alog_type alog_type;
  57. /// Type of this transport's error logging policy
  58. typedef typename config::elog_type elog_type;
  59. // Concurrency policy types
  60. typedef typename concurrency_type::scoped_lock_type scoped_lock_type;
  61. typedef typename concurrency_type::mutex_type mutex_type;
  62. typedef lib::shared_ptr<timer> timer_ptr;
  63. explicit connection(bool is_server, const lib::shared_ptr<alog_type> & alog, const lib::shared_ptr<elog_type> & elog)
  64. : m_reading(false), m_is_server(is_server), m_alog(alog), m_elog(elog)
  65. {
  66. m_alog->write(log::alevel::devel,"debug con transport constructor");
  67. }
  68. /// Get a shared pointer to this component
  69. ptr get_shared() {
  70. return type::shared_from_this();
  71. }
  72. /// Set whether or not this connection is secure
  73. /**
  74. * Todo: docs
  75. *
  76. * @since 0.3.0-alpha4
  77. *
  78. * @param value Whether or not this connection is secure.
  79. */
  80. void set_secure(bool) {}
  81. /// Tests whether or not the underlying transport is secure
  82. /**
  83. * TODO: docs
  84. *
  85. * @return Whether or not the underlying transport is secure
  86. */
  87. bool is_secure() const {
  88. return false;
  89. }
  90. /// Set uri hook
  91. /**
  92. * Called by the endpoint as a connection is being established to provide
  93. * the uri being connected to to the transport layer.
  94. *
  95. * Implementation is optional and can be ignored if the transport has no
  96. * need for this information.
  97. *
  98. * @since 0.6.0
  99. *
  100. * @param u The uri to set
  101. */
  102. void set_uri(uri_ptr) {}
  103. /// Set human readable remote endpoint address
  104. /**
  105. * Sets the remote endpoint address returned by `get_remote_endpoint`. This
  106. * value should be a human readable string that describes the remote
  107. * endpoint. Typically an IP address or hostname, perhaps with a port. But
  108. * may be something else depending on the nature of the underlying
  109. * transport.
  110. *
  111. * If none is set a default is returned.
  112. *
  113. * @since 0.3.0-alpha4
  114. *
  115. * @param value The remote endpoint address to set.
  116. */
  117. void set_remote_endpoint(std::string) {}
  118. /// Get human readable remote endpoint address
  119. /**
  120. * TODO: docs
  121. *
  122. * This value is used in access and error logs and is available to the end
  123. * application for including in user facing interfaces and messages.
  124. *
  125. * @return A string identifying the address of the remote endpoint
  126. */
  127. std::string get_remote_endpoint() const {
  128. return "unknown (debug transport)";
  129. }
  130. /// Get the connection handle
  131. /**
  132. * @return The handle for this connection.
  133. */
  134. connection_hdl get_handle() const {
  135. return connection_hdl();
  136. }
  137. /// Call back a function after a period of time.
  138. /**
  139. * Timers are not implemented in this transport. The timer pointer will
  140. * always be empty. The handler will never be called.
  141. *
  142. * @param duration Length of time to wait in milliseconds
  143. * @param callback The function to call back when the timer has expired
  144. * @return A handle that can be used to cancel the timer if it is no longer
  145. * needed.
  146. */
  147. timer_ptr set_timer(long, timer_handler handler) {
  148. m_alog->write(log::alevel::devel,"debug connection set timer");
  149. m_timer_handler = handler;
  150. return timer_ptr();
  151. }
  152. /// Manual input supply (read all)
  153. /**
  154. * Similar to read_some, but continues to read until all bytes in the
  155. * supplied buffer have been read or the connection runs out of read
  156. * requests.
  157. *
  158. * This method still may not read all of the bytes in the input buffer. if
  159. * it doesn't it indicates that the connection was most likely closed or
  160. * is in an error state where it is no longer accepting new input.
  161. *
  162. * @since 0.3.0
  163. *
  164. * @param buf Char buffer to read into the websocket
  165. * @param len Length of buf
  166. * @return The number of characters from buf actually read.
  167. */
  168. size_t read_all(char const * buf, size_t len) {
  169. size_t total_read = 0;
  170. size_t temp_read = 0;
  171. do {
  172. temp_read = this->read_some_impl(buf+total_read,len-total_read);
  173. total_read += temp_read;
  174. } while (temp_read != 0 && total_read < len);
  175. return total_read;
  176. }
  177. // debug stuff to invoke the async handlers
  178. void expire_timer(lib::error_code const & ec) {
  179. m_timer_handler(ec);
  180. }
  181. void fullfil_write() {
  182. m_write_handler(lib::error_code());
  183. }
  184. protected:
  185. /// Initialize the connection transport
  186. /**
  187. * Initialize the connection's transport component.
  188. *
  189. * @param handler The `init_handler` to call when initialization is done
  190. */
  191. void init(init_handler handler) {
  192. m_alog->write(log::alevel::devel,"debug connection init");
  193. handler(lib::error_code());
  194. }
  195. /// Initiate an async_read for at least num_bytes bytes into buf
  196. /**
  197. * Initiates an async_read request for at least num_bytes bytes. The input
  198. * will be read into buf. A maximum of len bytes will be input. When the
  199. * operation is complete, handler will be called with the status and number
  200. * of bytes read.
  201. *
  202. * This method may or may not call handler from within the initial call. The
  203. * application should be prepared to accept either.
  204. *
  205. * The application should never call this method a second time before it has
  206. * been called back for the first read. If this is done, the second read
  207. * will be called back immediately with a double_read error.
  208. *
  209. * If num_bytes or len are zero handler will be called back immediately
  210. * indicating success.
  211. *
  212. * @param num_bytes Don't call handler until at least this many bytes have
  213. * been read.
  214. * @param buf The buffer to read bytes into
  215. * @param len The size of buf. At maximum, this many bytes will be read.
  216. * @param handler The callback to invoke when the operation is complete or
  217. * ends in an error
  218. */
  219. void async_read_at_least(size_t num_bytes, char * buf, size_t len,
  220. read_handler handler)
  221. {
  222. std::stringstream s;
  223. s << "debug_con async_read_at_least: " << num_bytes;
  224. m_alog->write(log::alevel::devel,s.str());
  225. if (num_bytes > len) {
  226. handler(make_error_code(error::invalid_num_bytes),size_t(0));
  227. return;
  228. }
  229. if (m_reading == true) {
  230. handler(make_error_code(error::double_read),size_t(0));
  231. return;
  232. }
  233. if (num_bytes == 0 || len == 0) {
  234. handler(lib::error_code(),size_t(0));
  235. return;
  236. }
  237. m_buf = buf;
  238. m_len = len;
  239. m_bytes_needed = num_bytes;
  240. m_read_handler = handler;
  241. m_cursor = 0;
  242. m_reading = true;
  243. }
  244. /// Asyncronous Transport Write
  245. /**
  246. * Write len bytes in buf to the output stream. Call handler to report
  247. * success or failure. handler may or may not be called during async_write,
  248. * but it must be safe for this to happen.
  249. *
  250. * Will return 0 on success.
  251. *
  252. * @param buf buffer to read bytes from
  253. * @param len number of bytes to write
  254. * @param handler Callback to invoke with operation status.
  255. */
  256. void async_write(char const *, size_t, write_handler handler) {
  257. m_alog->write(log::alevel::devel,"debug_con async_write");
  258. m_write_handler = handler;
  259. }
  260. /// Asyncronous Transport Write (scatter-gather)
  261. /**
  262. * Write a sequence of buffers to the output stream. Call handler to report
  263. * success or failure. handler may or may not be called during async_write,
  264. * but it must be safe for this to happen.
  265. *
  266. * Will return 0 on success.
  267. *
  268. * @param bufs vector of buffers to write
  269. * @param handler Callback to invoke with operation status.
  270. */
  271. void async_write(std::vector<buffer> const &, write_handler handler) {
  272. m_alog->write(log::alevel::devel,"debug_con async_write buffer list");
  273. m_write_handler = handler;
  274. }
  275. /// Set Connection Handle
  276. /**
  277. * @param hdl The new handle
  278. */
  279. void set_handle(connection_hdl) {}
  280. /// Call given handler back within the transport's event system (if present)
  281. /**
  282. * Invoke a callback within the transport's event system if it has one. If
  283. * it doesn't, the handler will be invoked immediately before this function
  284. * returns.
  285. *
  286. * @param handler The callback to invoke
  287. *
  288. * @return Whether or not the transport was able to register the handler for
  289. * callback.
  290. */
  291. lib::error_code dispatch(dispatch_handler handler) {
  292. handler();
  293. return lib::error_code();
  294. }
  295. /// Perform cleanup on socket shutdown_handler
  296. /**
  297. * @param h The `shutdown_handler` to call back when complete
  298. */
  299. void async_shutdown(shutdown_handler handler) {
  300. handler(lib::error_code());
  301. }
  302. size_t read_some_impl(char const * buf, size_t len) {
  303. m_alog->write(log::alevel::devel,"debug_con read_some");
  304. if (!m_reading) {
  305. m_elog->write(log::elevel::devel,"write while not reading");
  306. return 0;
  307. }
  308. size_t bytes_to_copy = (std::min)(len,m_len-m_cursor);
  309. std::copy(buf,buf+bytes_to_copy,m_buf+m_cursor);
  310. m_cursor += bytes_to_copy;
  311. if (m_cursor >= m_bytes_needed) {
  312. complete_read(lib::error_code());
  313. }
  314. return bytes_to_copy;
  315. }
  316. /// Signal that a requested read is complete
  317. /**
  318. * Sets the reading flag to false and returns the handler that should be
  319. * called back with the result of the read. The cursor position that is sent
  320. * is whatever the value of m_cursor is.
  321. *
  322. * It MUST NOT be called when m_reading is false.
  323. * it MUST be called while holding the read lock
  324. *
  325. * It is important to use this method rather than directly setting/calling
  326. * m_read_handler back because this function makes sure to delete the
  327. * locally stored handler which contains shared pointers that will otherwise
  328. * cause circular reference based memory leaks.
  329. *
  330. * @param ec The error code to forward to the read handler
  331. */
  332. void complete_read(lib::error_code const & ec) {
  333. m_reading = false;
  334. read_handler handler = m_read_handler;
  335. m_read_handler = read_handler();
  336. handler(ec,m_cursor);
  337. }
  338. private:
  339. timer_handler m_timer_handler;
  340. // Read space (Protected by m_read_mutex)
  341. char * m_buf;
  342. size_t m_len;
  343. size_t m_bytes_needed;
  344. read_handler m_read_handler;
  345. size_t m_cursor;
  346. // transport resources
  347. connection_hdl m_connection_hdl;
  348. write_handler m_write_handler;
  349. shutdown_handler m_shutdown_handler;
  350. bool m_reading;
  351. bool const m_is_server;
  352. bool m_is_secure;
  353. lib::shared_ptr<alog_type> m_alog;
  354. lib::shared_ptr<elog_type> m_elog;
  355. std::string m_remote_endpoint;
  356. };
  357. } // namespace debug
  358. } // namespace transport
  359. } // namespace websocketpp
  360. #endif // WEBSOCKETPP_TRANSPORT_DEBUG_CON_HPP