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.

2400 lines
68 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  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_CONNECTION_IMPL_HPP
  28. #define WEBSOCKETPP_CONNECTION_IMPL_HPP
  29. #include <algorithm>
  30. #include <exception>
  31. #include <sstream>
  32. #include <string>
  33. #include <utility>
  34. #include <vector>
  35. #include <websocketpp/common/platforms.hpp>
  36. #include <websocketpp/common/system_error.hpp>
  37. #include <websocketpp/processors/hybi00.hpp>
  38. #include <websocketpp/processors/hybi07.hpp>
  39. #include <websocketpp/processors/hybi08.hpp>
  40. #include <websocketpp/processors/hybi13.hpp>
  41. #include <websocketpp/processors/processor.hpp>
  42. namespace websocketpp
  43. {
  44. namespace istate = session::internal_state;
  45. template <typename config> void connection<config>::set_termination_handler(termination_handler new_handler)
  46. {
  47. m_alog->write(log::alevel::devel, "connection set_termination_handler");
  48. // scoped_lock_type lock(m_connection_state_lock);
  49. m_termination_handler = new_handler;
  50. }
  51. template <typename config> const std::string & connection<config>::get_origin() const
  52. {
  53. // scoped_lock_type lock(m_connection_state_lock);
  54. return m_processor->get_origin(m_request);
  55. }
  56. template <typename config> size_t connection<config>::get_buffered_amount() const
  57. {
  58. // scoped_lock_type lock(m_connection_state_lock);
  59. return m_send_buffer_size;
  60. }
  61. template <typename config> session::state::value connection<config>::get_state() const
  62. {
  63. // scoped_lock_type lock(m_connection_state_lock);
  64. return m_state;
  65. }
  66. template <typename config> lib::error_code connection<config>::send(const std::string & payload, frame::opcode::value op)
  67. {
  68. message_ptr msg = m_msg_manager->get_message(op, payload.size());
  69. msg->append_payload(payload);
  70. msg->set_compressed(true);
  71. return send(msg);
  72. }
  73. template <typename config> lib::error_code connection<config>::send(const void * payload, size_t len, frame::opcode::value op)
  74. {
  75. message_ptr msg = m_msg_manager->get_message(op, len);
  76. msg->append_payload(payload, len);
  77. return send(msg);
  78. }
  79. template <typename config> lib::error_code connection<config>::send(typename config::message_type::ptr msg)
  80. {
  81. if (m_alog->static_test(log::alevel::devel))
  82. {
  83. m_alog->write(log::alevel::devel, "connection send");
  84. }
  85. {
  86. scoped_lock_type lock(m_connection_state_lock);
  87. if (m_state != session::state::open)
  88. {
  89. return error::make_error_code(error::invalid_state);
  90. }
  91. }
  92. message_ptr outgoing_msg;
  93. bool needs_writing = false;
  94. if (msg->get_prepared())
  95. {
  96. outgoing_msg = msg;
  97. scoped_lock_type lock(m_write_lock);
  98. write_push(outgoing_msg);
  99. needs_writing = ! m_write_flag && ! m_send_queue.empty();
  100. }
  101. else
  102. {
  103. outgoing_msg = m_msg_manager->get_message();
  104. if (! outgoing_msg)
  105. {
  106. return error::make_error_code(error::no_outgoing_buffers);
  107. }
  108. scoped_lock_type lock(m_write_lock);
  109. lib::error_code ec = m_processor->prepare_data_frame(msg, outgoing_msg);
  110. if (ec)
  111. {
  112. return ec;
  113. }
  114. write_push(outgoing_msg);
  115. needs_writing = ! m_write_flag && ! m_send_queue.empty();
  116. }
  117. if (needs_writing)
  118. {
  119. transport_con_type::dispatch(lib::bind(&type::write_frame, type::get_shared()));
  120. }
  121. return lib::error_code();
  122. }
  123. template <typename config> void connection<config>::ping(const std::string & payload, lib::error_code & ec)
  124. {
  125. if (m_alog->static_test(log::alevel::devel))
  126. {
  127. m_alog->write(log::alevel::devel, "connection ping");
  128. }
  129. {
  130. scoped_lock_type lock(m_connection_state_lock);
  131. if (m_state != session::state::open)
  132. {
  133. std::stringstream ss;
  134. ss << "connection::ping called from invalid state " << m_state;
  135. m_alog->write(log::alevel::devel, ss.str());
  136. ec = error::make_error_code(error::invalid_state);
  137. return;
  138. }
  139. }
  140. message_ptr msg = m_msg_manager->get_message();
  141. if (! msg)
  142. {
  143. ec = error::make_error_code(error::no_outgoing_buffers);
  144. return;
  145. }
  146. ec = m_processor->prepare_ping(payload, msg);
  147. if (ec)
  148. {
  149. return;
  150. }
  151. // set ping timer if we are listening for one
  152. if (m_pong_timeout_handler)
  153. {
  154. // Cancel any existing timers
  155. if (m_ping_timer)
  156. {
  157. m_ping_timer->cancel();
  158. }
  159. if (m_pong_timeout_dur > 0)
  160. {
  161. m_ping_timer = transport_con_type::set_timer(m_pong_timeout_dur, lib::bind(&type::handle_pong_timeout, type::get_shared(), payload, lib::placeholders::_1));
  162. }
  163. if (! m_ping_timer)
  164. {
  165. // Our transport doesn't support timers
  166. m_elog->write(log::elevel::warn,
  167. "Warning: a pong_timeout_handler is \
  168. set but the transport in use does not support timeouts.");
  169. }
  170. }
  171. bool needs_writing = false;
  172. {
  173. scoped_lock_type lock(m_write_lock);
  174. write_push(msg);
  175. needs_writing = ! m_write_flag && ! m_send_queue.empty();
  176. }
  177. if (needs_writing)
  178. {
  179. transport_con_type::dispatch(lib::bind(&type::write_frame, type::get_shared()));
  180. }
  181. ec = lib::error_code();
  182. }
  183. template <typename config> void connection<config>::ping(const std::string & payload)
  184. {
  185. lib::error_code ec;
  186. ping(payload, ec);
  187. if (ec)
  188. {
  189. throw exception(ec);
  190. }
  191. }
  192. template <typename config> void connection<config>::handle_pong_timeout(std::string payload, const lib::error_code & ec)
  193. {
  194. if (ec)
  195. {
  196. if (ec == transport::error::operation_aborted)
  197. {
  198. // ignore, this is expected
  199. return;
  200. }
  201. m_elog->write(log::elevel::devel, "pong_timeout error: " + ec.message());
  202. return;
  203. }
  204. if (m_pong_timeout_handler)
  205. {
  206. m_pong_timeout_handler(m_connection_hdl, payload);
  207. }
  208. }
  209. template <typename config> void connection<config>::pong(const std::string & payload, lib::error_code & ec)
  210. {
  211. if (m_alog->static_test(log::alevel::devel))
  212. {
  213. m_alog->write(log::alevel::devel, "connection pong");
  214. }
  215. {
  216. scoped_lock_type lock(m_connection_state_lock);
  217. if (m_state != session::state::open)
  218. {
  219. std::stringstream ss;
  220. ss << "connection::pong called from invalid state " << m_state;
  221. m_alog->write(log::alevel::devel, ss.str());
  222. ec = error::make_error_code(error::invalid_state);
  223. return;
  224. }
  225. }
  226. message_ptr msg = m_msg_manager->get_message();
  227. if (! msg)
  228. {
  229. ec = error::make_error_code(error::no_outgoing_buffers);
  230. return;
  231. }
  232. ec = m_processor->prepare_pong(payload, msg);
  233. if (ec)
  234. {
  235. return;
  236. }
  237. bool needs_writing = false;
  238. {
  239. scoped_lock_type lock(m_write_lock);
  240. write_push(msg);
  241. needs_writing = ! m_write_flag && ! m_send_queue.empty();
  242. }
  243. if (needs_writing)
  244. {
  245. transport_con_type::dispatch(lib::bind(&type::write_frame, type::get_shared()));
  246. }
  247. ec = lib::error_code();
  248. }
  249. template <typename config> void connection<config>::pong(const std::string & payload)
  250. {
  251. lib::error_code ec;
  252. pong(payload, ec);
  253. if (ec)
  254. {
  255. throw exception(ec);
  256. }
  257. }
  258. template <typename config> void connection<config>::close(const close::status::value code, const std::string & reason, lib::error_code & ec)
  259. {
  260. if (m_alog->static_test(log::alevel::devel))
  261. {
  262. m_alog->write(log::alevel::devel, "connection close");
  263. }
  264. // Truncate reason to maximum size allowable in a close frame.
  265. std::string tr(reason, 0, std::min<size_t>(reason.size(), frame::limits::close_reason_size));
  266. scoped_lock_type lock(m_connection_state_lock);
  267. if (m_state != session::state::open)
  268. {
  269. ec = error::make_error_code(error::invalid_state);
  270. return;
  271. }
  272. ec = this->send_close_frame(code, tr, false, close::status::terminal(code));
  273. }
  274. template <typename config> void connection<config>::close(const close::status::value code, const std::string & reason)
  275. {
  276. lib::error_code ec;
  277. close(code, reason, ec);
  278. if (ec)
  279. {
  280. throw exception(ec);
  281. }
  282. }
  283. /// Trigger the on_interrupt handler
  284. /**
  285. * This is thread safe if the transport is thread safe
  286. */
  287. template <typename config> lib::error_code connection<config>::interrupt()
  288. {
  289. m_alog->write(log::alevel::devel, "connection connection::interrupt");
  290. return transport_con_type::interrupt(lib::bind(&type::handle_interrupt, type::get_shared()));
  291. }
  292. template <typename config> void connection<config>::handle_interrupt()
  293. {
  294. if (m_interrupt_handler)
  295. {
  296. m_interrupt_handler(m_connection_hdl);
  297. }
  298. }
  299. template <typename config> lib::error_code connection<config>::pause_reading()
  300. {
  301. m_alog->write(log::alevel::devel, "connection connection::pause_reading");
  302. return transport_con_type::dispatch(lib::bind(&type::handle_pause_reading, type::get_shared()));
  303. }
  304. /// Pause reading handler. Not safe to call directly
  305. template <typename config> void connection<config>::handle_pause_reading()
  306. {
  307. m_alog->write(log::alevel::devel, "connection connection::handle_pause_reading");
  308. m_read_flag = false;
  309. }
  310. template <typename config> lib::error_code connection<config>::resume_reading()
  311. {
  312. m_alog->write(log::alevel::devel, "connection connection::resume_reading");
  313. return transport_con_type::dispatch(lib::bind(&type::handle_resume_reading, type::get_shared()));
  314. }
  315. /// Resume reading helper method. Not safe to call directly
  316. template <typename config> void connection<config>::handle_resume_reading()
  317. {
  318. m_read_flag = true;
  319. read_frame();
  320. }
  321. template <typename config> bool connection<config>::get_secure() const
  322. {
  323. // scoped_lock_type lock(m_connection_state_lock);
  324. return m_uri->get_secure();
  325. }
  326. template <typename config> const std::string & connection<config>::get_host() const
  327. {
  328. // scoped_lock_type lock(m_connection_state_lock);
  329. return m_uri->get_host();
  330. }
  331. template <typename config> const std::string & connection<config>::get_resource() const
  332. {
  333. // scoped_lock_type lock(m_connection_state_lock);
  334. return m_uri->get_resource();
  335. }
  336. template <typename config> uint16_t connection<config>::get_port() const
  337. {
  338. // scoped_lock_type lock(m_connection_state_lock);
  339. return m_uri->get_port();
  340. }
  341. template <typename config> uri_ptr connection<config>::get_uri() const
  342. {
  343. // scoped_lock_type lock(m_connection_state_lock);
  344. return m_uri;
  345. }
  346. template <typename config> void connection<config>::set_uri(uri_ptr uri)
  347. {
  348. // scoped_lock_type lock(m_connection_state_lock);
  349. m_uri = uri;
  350. }
  351. template <typename config> const std::string & connection<config>::get_subprotocol() const
  352. {
  353. return m_subprotocol;
  354. }
  355. template <typename config> const std::vector<std::string> & connection<config>::get_requested_subprotocols() const
  356. {
  357. return m_requested_subprotocols;
  358. }
  359. template <typename config> void connection<config>::add_subprotocol(const std::string & value, lib::error_code & ec)
  360. {
  361. if (m_is_server)
  362. {
  363. ec = error::make_error_code(error::client_only);
  364. return;
  365. }
  366. // If the value is empty or has a non-RFC2616 token character it is invalid.
  367. if (value.empty() || std::find_if(value.begin(), value.end(), http::is_not_token_char) != value.end())
  368. {
  369. ec = error::make_error_code(error::invalid_subprotocol);
  370. return;
  371. }
  372. m_requested_subprotocols.push_back(value);
  373. }
  374. template <typename config> void connection<config>::add_subprotocol(const std::string & value)
  375. {
  376. lib::error_code ec;
  377. this->add_subprotocol(value, ec);
  378. if (ec)
  379. {
  380. throw exception(ec);
  381. }
  382. }
  383. template <typename config> void connection<config>::select_subprotocol(const std::string & value, lib::error_code & ec)
  384. {
  385. if (! m_is_server)
  386. {
  387. ec = error::make_error_code(error::server_only);
  388. return;
  389. }
  390. if (value.empty())
  391. {
  392. ec = lib::error_code();
  393. return;
  394. }
  395. std::vector<std::string>::iterator it;
  396. it = std::find(m_requested_subprotocols.begin(), m_requested_subprotocols.end(), value);
  397. if (it == m_requested_subprotocols.end())
  398. {
  399. ec = error::make_error_code(error::unrequested_subprotocol);
  400. return;
  401. }
  402. m_subprotocol = value;
  403. }
  404. template <typename config> void connection<config>::select_subprotocol(const std::string & value)
  405. {
  406. lib::error_code ec;
  407. this->select_subprotocol(value, ec);
  408. if (ec)
  409. {
  410. throw exception(ec);
  411. }
  412. }
  413. template <typename config> const std::string & connection<config>::get_request_header(const std::string & key) const
  414. {
  415. return m_request.get_header(key);
  416. }
  417. template <typename config> const std::string & connection<config>::get_request_body() const
  418. {
  419. return m_request.get_body();
  420. }
  421. template <typename config> const std::string & connection<config>::get_response_header(const std::string & key) const
  422. {
  423. return m_response.get_header(key);
  424. }
  425. // TODO: EXCEPTION_FREE
  426. template <typename config> void connection<config>::set_status(http::status_code::value code)
  427. {
  428. if (m_internal_state != istate::PROCESS_HTTP_REQUEST)
  429. {
  430. throw exception("Call to set_status from invalid state", error::make_error_code(error::invalid_state));
  431. }
  432. m_response.set_status(code);
  433. }
  434. // TODO: EXCEPTION_FREE
  435. template <typename config> void connection<config>::set_status(http::status_code::value code, const std::string & msg)
  436. {
  437. if (m_internal_state != istate::PROCESS_HTTP_REQUEST)
  438. {
  439. throw exception("Call to set_status from invalid state", error::make_error_code(error::invalid_state));
  440. }
  441. m_response.set_status(code, msg);
  442. }
  443. // TODO: EXCEPTION_FREE
  444. template <typename config> void connection<config>::set_body(const std::string & value)
  445. {
  446. if (m_internal_state != istate::PROCESS_HTTP_REQUEST)
  447. {
  448. throw exception("Call to set_status from invalid state", error::make_error_code(error::invalid_state));
  449. }
  450. m_response.set_body(value);
  451. }
  452. // TODO: EXCEPTION_FREE
  453. template <typename config> void connection<config>::append_header(const std::string & key, const std::string & val)
  454. {
  455. if (m_is_server)
  456. {
  457. if (m_internal_state == istate::PROCESS_HTTP_REQUEST)
  458. {
  459. // we are setting response headers for an incoming server connection
  460. m_response.append_header(key, val);
  461. }
  462. else
  463. {
  464. throw exception("Call to append_header from invalid state", error::make_error_code(error::invalid_state));
  465. }
  466. }
  467. else
  468. {
  469. if (m_internal_state == istate::USER_INIT)
  470. {
  471. // we are setting initial headers for an outgoing client connection
  472. m_request.append_header(key, val);
  473. }
  474. else
  475. {
  476. throw exception("Call to append_header from invalid state", error::make_error_code(error::invalid_state));
  477. }
  478. }
  479. }
  480. // TODO: EXCEPTION_FREE
  481. template <typename config> void connection<config>::replace_header(const std::string & key, const std::string & val)
  482. {
  483. if (m_is_server)
  484. {
  485. if (m_internal_state == istate::PROCESS_HTTP_REQUEST)
  486. {
  487. // we are setting response headers for an incoming server connection
  488. m_response.replace_header(key, val);
  489. }
  490. else
  491. {
  492. throw exception("Call to replace_header from invalid state", error::make_error_code(error::invalid_state));
  493. }
  494. }
  495. else
  496. {
  497. if (m_internal_state == istate::USER_INIT)
  498. {
  499. // we are setting initial headers for an outgoing client connection
  500. m_request.replace_header(key, val);
  501. }
  502. else
  503. {
  504. throw exception("Call to replace_header from invalid state", error::make_error_code(error::invalid_state));
  505. }
  506. }
  507. }
  508. // TODO: EXCEPTION_FREE
  509. template <typename config> void connection<config>::remove_header(const std::string & key)
  510. {
  511. if (m_is_server)
  512. {
  513. if (m_internal_state == istate::PROCESS_HTTP_REQUEST)
  514. {
  515. // we are setting response headers for an incoming server connection
  516. m_response.remove_header(key);
  517. }
  518. else
  519. {
  520. throw exception("Call to remove_header from invalid state", error::make_error_code(error::invalid_state));
  521. }
  522. }
  523. else
  524. {
  525. if (m_internal_state == istate::USER_INIT)
  526. {
  527. // we are setting initial headers for an outgoing client connection
  528. m_request.remove_header(key);
  529. }
  530. else
  531. {
  532. throw exception("Call to remove_header from invalid state", error::make_error_code(error::invalid_state));
  533. }
  534. }
  535. }
  536. /// Defer HTTP Response until later
  537. /**
  538. * Used in the http handler to defer the HTTP response for this connection
  539. * until later. Handshake timers will be canceled and the connection will be
  540. * left open until `send_http_response` or an equivalent is called.
  541. *
  542. * Warning: deferred connections won't time out and as a result can tie up
  543. * resources.
  544. *
  545. * @return A status code, zero on success, non-zero otherwise
  546. */
  547. template <typename config> lib::error_code connection<config>::defer_http_response()
  548. {
  549. // Cancel handshake timer, otherwise the connection will time out and we'll
  550. // close the connection before the app has a chance to send a response.
  551. if (m_handshake_timer)
  552. {
  553. m_handshake_timer->cancel();
  554. m_handshake_timer.reset();
  555. }
  556. // Do something to signal deferral
  557. m_http_state = session::http_state::deferred;
  558. return lib::error_code();
  559. }
  560. /// Send deferred HTTP Response (exception free)
  561. /**
  562. * Sends an http response to an HTTP connection that was deferred. This will
  563. * send a complete response including all headers, status line, and body
  564. * text. The connection will be closed afterwards.
  565. *
  566. * @since 0.6.0
  567. *
  568. * @param ec A status code, zero on success, non-zero otherwise
  569. */
  570. template <typename config> void connection<config>::send_http_response(lib::error_code & ec)
  571. {
  572. {
  573. scoped_lock_type lock(m_connection_state_lock);
  574. if (m_http_state != session::http_state::deferred)
  575. {
  576. ec = error::make_error_code(error::invalid_state);
  577. return;
  578. }
  579. m_http_state = session::http_state::body_written;
  580. }
  581. this->write_http_response(lib::error_code());
  582. ec = lib::error_code();
  583. }
  584. template <typename config> void connection<config>::send_http_response()
  585. {
  586. lib::error_code ec;
  587. this->send_http_response(ec);
  588. if (ec)
  589. {
  590. throw exception(ec);
  591. }
  592. }
  593. /******** logic thread ********/
  594. template <typename config> void connection<config>::start()
  595. {
  596. m_alog->write(log::alevel::devel, "connection start");
  597. if (m_internal_state != istate::USER_INIT)
  598. {
  599. m_alog->write(log::alevel::devel, "Start called in invalid state");
  600. this->terminate(error::make_error_code(error::invalid_state));
  601. return;
  602. }
  603. m_internal_state = istate::TRANSPORT_INIT;
  604. // Depending on how the transport implements init this function may return
  605. // immediately and call handle_transport_init later or call
  606. // handle_transport_init from this function.
  607. transport_con_type::init(lib::bind(&type::handle_transport_init, type::get_shared(), lib::placeholders::_1));
  608. }
  609. template <typename config> void connection<config>::handle_transport_init(const lib::error_code & ec)
  610. {
  611. m_alog->write(log::alevel::devel, "connection handle_transport_init");
  612. lib::error_code ecm = ec;
  613. if (m_internal_state != istate::TRANSPORT_INIT)
  614. {
  615. m_alog->write(log::alevel::devel, "handle_transport_init must be called from transport init state");
  616. ecm = error::make_error_code(error::invalid_state);
  617. }
  618. if (ecm)
  619. {
  620. std::stringstream s;
  621. s << "handle_transport_init received error: " << ecm.message();
  622. m_elog->write(log::elevel::rerror, s.str());
  623. this->terminate(ecm);
  624. return;
  625. }
  626. // At this point the transport is ready to read and write bytes.
  627. if (m_is_server)
  628. {
  629. m_internal_state = istate::READ_HTTP_REQUEST;
  630. this->read_handshake(1);
  631. }
  632. else
  633. {
  634. // We are a client. Set the processor to the version specified in the
  635. // config file and send a handshake request.
  636. m_internal_state = istate::WRITE_HTTP_REQUEST;
  637. m_processor = get_processor(config::client_version);
  638. this->send_http_request();
  639. }
  640. }
  641. template <typename config> void connection<config>::read_handshake(size_t num_bytes)
  642. {
  643. m_alog->write(log::alevel::devel, "connection read_handshake");
  644. if (m_open_handshake_timeout_dur > 0)
  645. {
  646. m_handshake_timer = transport_con_type::set_timer(m_open_handshake_timeout_dur, lib::bind(&type::handle_open_handshake_timeout, type::get_shared(), lib::placeholders::_1));
  647. }
  648. transport_con_type::async_read_at_least(num_bytes, m_buf, config::connection_read_buffer_size, lib::bind(&type::handle_read_handshake, type::get_shared(), lib::placeholders::_1, lib::placeholders::_2));
  649. }
  650. // All exit paths for this function need to call write_http_response() or submit
  651. // a new read request with this function as the handler.
  652. template <typename config> void connection<config>::handle_read_handshake(const lib::error_code & ec, size_t bytes_transferred)
  653. {
  654. m_alog->write(log::alevel::devel, "connection handle_read_handshake");
  655. lib::error_code ecm = ec;
  656. if (! ecm)
  657. {
  658. scoped_lock_type lock(m_connection_state_lock);
  659. if (m_state == session::state::connecting)
  660. {
  661. if (m_internal_state != istate::READ_HTTP_REQUEST)
  662. {
  663. ecm = error::make_error_code(error::invalid_state);
  664. }
  665. }
  666. else if (m_state == session::state::closed)
  667. {
  668. // The connection was canceled while the response was being sent,
  669. // usually by the handshake timer. This is basically expected
  670. // (though hopefully rare) and there is nothing we can do so ignore.
  671. m_alog->write(log::alevel::devel, "handle_read_handshake invoked after connection was closed");
  672. return;
  673. }
  674. else
  675. {
  676. ecm = error::make_error_code(error::invalid_state);
  677. }
  678. }
  679. if (ecm)
  680. {
  681. if (ecm == transport::error::eof && m_state == session::state::closed)
  682. {
  683. // we expect to get eof if the connection is closed already
  684. m_alog->write(log::alevel::devel, "got (expected) eof/state error from closed con");
  685. return;
  686. }
  687. log_err(log::elevel::rerror, "handle_read_handshake", ecm);
  688. this->terminate(ecm);
  689. return;
  690. }
  691. // Boundaries checking. TODO: How much of this should be done?
  692. if (bytes_transferred > config::connection_read_buffer_size)
  693. {
  694. m_elog->write(log::elevel::fatal, "Fatal boundaries checking error.");
  695. this->terminate(make_error_code(error::general));
  696. return;
  697. }
  698. size_t bytes_processed = 0;
  699. try
  700. {
  701. bytes_processed = m_request.consume(m_buf, bytes_transferred);
  702. }
  703. catch (http::exception & e)
  704. {
  705. // All HTTP exceptions will result in this request failing and an error
  706. // response being returned. No more bytes will be read in this con.
  707. m_response.set_status(e.m_error_code, e.m_error_msg);
  708. this->write_http_response_error(error::make_error_code(error::http_parse_error));
  709. return;
  710. }
  711. // More paranoid boundaries checking.
  712. // TODO: Is this overkill?
  713. if (bytes_processed > bytes_transferred)
  714. {
  715. m_elog->write(log::elevel::fatal, "Fatal boundaries checking error.");
  716. this->terminate(make_error_code(error::general));
  717. return;
  718. }
  719. if (m_alog->static_test(log::alevel::devel))
  720. {
  721. std::stringstream s;
  722. s << "bytes_transferred: " << bytes_transferred << " bytes, bytes processed: " << bytes_processed << " bytes";
  723. m_alog->write(log::alevel::devel, s.str());
  724. }
  725. if (m_request.ready())
  726. {
  727. lib::error_code processor_ec = this->initialize_processor();
  728. if (processor_ec)
  729. {
  730. this->write_http_response_error(processor_ec);
  731. return;
  732. }
  733. if (m_processor && m_processor->get_version() == 0)
  734. {
  735. // Version 00 has an extra requirement to read some bytes after the
  736. // handshake
  737. if (bytes_transferred - bytes_processed >= 8)
  738. {
  739. m_request.replace_header("Sec-WebSocket-Key3", std::string(m_buf + bytes_processed, m_buf + bytes_processed + 8));
  740. bytes_processed += 8;
  741. }
  742. else
  743. {
  744. // TODO: need more bytes
  745. m_alog->write(log::alevel::devel, "short key3 read");
  746. m_response.set_status(http::status_code::internal_server_error);
  747. this->write_http_response_error(processor::error::make_error_code(processor::error::short_key3));
  748. return;
  749. }
  750. }
  751. if (m_alog->static_test(log::alevel::devel))
  752. {
  753. m_alog->write(log::alevel::devel, m_request.raw());
  754. if (! m_request.get_header("Sec-WebSocket-Key3").empty())
  755. {
  756. m_alog->write(log::alevel::devel, utility::to_hex(m_request.get_header("Sec-WebSocket-Key3")));
  757. }
  758. }
  759. // The remaining bytes in m_buf are frame data. Copy them to the
  760. // beginning of the buffer and note the length. They will be read after
  761. // the handshake completes and before more bytes are read.
  762. std::copy(m_buf + bytes_processed, m_buf + bytes_transferred, m_buf);
  763. m_buf_cursor = bytes_transferred - bytes_processed;
  764. m_internal_state = istate::PROCESS_HTTP_REQUEST;
  765. // We have the complete request. Process it.
  766. lib::error_code handshake_ec = this->process_handshake_request();
  767. // Write a response if this is a websocket connection or if it is an
  768. // HTTP connection for which the response has not been deferred or
  769. // started yet by a different system (i.e. still in init state).
  770. if (! m_is_http || m_http_state == session::http_state::init)
  771. {
  772. this->write_http_response(handshake_ec);
  773. }
  774. }
  775. else
  776. {
  777. // read at least 1 more byte
  778. transport_con_type::async_read_at_least(1, m_buf, config::connection_read_buffer_size, lib::bind(&type::handle_read_handshake, type::get_shared(), lib::placeholders::_1, lib::placeholders::_2));
  779. }
  780. }
  781. // write_http_response requires the request to be fully read and the connection
  782. // to be in the PROCESS_HTTP_REQUEST state. In some cases we can detect errors
  783. // before the request is fully read (specifically at a point where we aren't
  784. // sure if the hybi00 key3 bytes need to be read). This method sets the correct
  785. // state and calls write_http_response
  786. template <typename config> void connection<config>::write_http_response_error(const lib::error_code & ec)
  787. {
  788. if (m_internal_state != istate::READ_HTTP_REQUEST)
  789. {
  790. m_alog->write(log::alevel::devel, "write_http_response_error called in invalid state");
  791. this->terminate(error::make_error_code(error::invalid_state));
  792. return;
  793. }
  794. m_internal_state = istate::PROCESS_HTTP_REQUEST;
  795. this->write_http_response(ec);
  796. }
  797. // All exit paths for this function need to call write_http_response() or submit
  798. // a new read request with this function as the handler.
  799. template <typename config> void connection<config>::handle_read_frame(const lib::error_code & ec, size_t bytes_transferred)
  800. {
  801. // m_alog->write(log::alevel::devel,"connection handle_read_frame");
  802. lib::error_code ecm = ec;
  803. if (! ecm && m_internal_state != istate::PROCESS_CONNECTION)
  804. {
  805. ecm = error::make_error_code(error::invalid_state);
  806. }
  807. if (ecm)
  808. {
  809. log::level echannel = log::elevel::rerror;
  810. if (ecm == transport::error::eof)
  811. {
  812. if (m_state == session::state::closed)
  813. {
  814. // we expect to get eof if the connection is closed already
  815. // just ignore it
  816. m_alog->write(log::alevel::devel, "got eof from closed con");
  817. return;
  818. }
  819. else if (m_state == session::state::closing && ! m_is_server)
  820. {
  821. // If we are a client we expect to get eof in the closing state,
  822. // this is a signal to terminate our end of the connection after
  823. // the closing handshake
  824. terminate(lib::error_code());
  825. return;
  826. }
  827. }
  828. else if (ecm == error::invalid_state)
  829. {
  830. // In general, invalid state errors in the closed state are the
  831. // result of handlers that were in the system already when the state
  832. // changed and should be ignored as they pose no problems and there
  833. // is nothing useful that we can do about them.
  834. if (m_state == session::state::closed)
  835. {
  836. m_alog->write(log::alevel::devel, "handle_read_frame: got invalid istate in closed state");
  837. return;
  838. }
  839. }
  840. else if (ecm == transport::error::action_after_shutdown)
  841. {
  842. echannel = log::elevel::info;
  843. }
  844. else
  845. {
  846. // TODO: more generally should we do something different here in the
  847. // case that m_state is cosed? Are errors after the connection is
  848. // already closed really an rerror?
  849. }
  850. log_err(echannel, "handle_read_frame", ecm);
  851. this->terminate(ecm);
  852. return;
  853. }
  854. // Boundaries checking. TODO: How much of this should be done?
  855. /*if (bytes_transferred > config::connection_read_buffer_size) {
  856. m_elog->write(log::elevel::fatal,"Fatal boundaries checking error");
  857. this->terminate(make_error_code(error::general));
  858. return;
  859. }*/
  860. size_t p = 0;
  861. if (m_alog->static_test(log::alevel::devel))
  862. {
  863. std::stringstream s;
  864. s << "p = " << p << " bytes transferred = " << bytes_transferred;
  865. m_alog->write(log::alevel::devel, s.str());
  866. }
  867. while (p < bytes_transferred)
  868. {
  869. if (m_alog->static_test(log::alevel::devel))
  870. {
  871. std::stringstream s;
  872. s << "calling consume with " << bytes_transferred - p << " bytes";
  873. m_alog->write(log::alevel::devel, s.str());
  874. }
  875. lib::error_code consume_ec;
  876. if (m_alog->static_test(log::alevel::devel))
  877. {
  878. std::stringstream s;
  879. s << "Processing Bytes: " << utility::to_hex(reinterpret_cast<uint8_t *>(m_buf) + p, bytes_transferred - p);
  880. m_alog->write(log::alevel::devel, s.str());
  881. }
  882. p += m_processor->consume(reinterpret_cast<uint8_t *>(m_buf) + p, bytes_transferred - p, consume_ec);
  883. if (m_alog->static_test(log::alevel::devel))
  884. {
  885. std::stringstream s;
  886. s << "bytes left after consume: " << bytes_transferred - p;
  887. m_alog->write(log::alevel::devel, s.str());
  888. }
  889. if (consume_ec)
  890. {
  891. log_err(log::elevel::rerror, "consume", consume_ec);
  892. if (config::drop_on_protocol_error)
  893. {
  894. this->terminate(consume_ec);
  895. return;
  896. }
  897. else
  898. {
  899. lib::error_code close_ec;
  900. this->close(processor::error::to_ws(consume_ec), consume_ec.message(), close_ec);
  901. if (close_ec)
  902. {
  903. log_err(log::elevel::fatal, "Protocol error close frame ", close_ec);
  904. this->terminate(close_ec);
  905. return;
  906. }
  907. }
  908. return;
  909. }
  910. if (m_processor->ready())
  911. {
  912. if (m_alog->static_test(log::alevel::devel))
  913. {
  914. std::stringstream s;
  915. s << "Complete message received. Dispatching";
  916. m_alog->write(log::alevel::devel, s.str());
  917. }
  918. message_ptr msg = m_processor->get_message();
  919. if (! msg)
  920. {
  921. m_alog->write(log::alevel::devel, "null message from m_processor");
  922. }
  923. else if (! is_control(msg->get_opcode()))
  924. {
  925. // data message, dispatch to user
  926. if (m_state != session::state::open)
  927. {
  928. m_elog->write(log::elevel::warn, "got non-close frame while closing");
  929. }
  930. else if (m_message_handler)
  931. {
  932. m_message_handler(m_connection_hdl, msg);
  933. }
  934. }
  935. else
  936. {
  937. process_control_frame(msg);
  938. }
  939. }
  940. }
  941. read_frame();
  942. }
  943. /// Issue a new transport read unless reading is paused.
  944. template <typename config> void connection<config>::read_frame()
  945. {
  946. if (! m_read_flag)
  947. {
  948. return;
  949. }
  950. transport_con_type::async_read_at_least(
  951. // std::min wont work with undefined static const values.
  952. // TODO: is there a more elegant way to do this?
  953. // Need to determine if requesting 1 byte or the exact number of bytes
  954. // is better here. 1 byte lets us be a bit more responsive at a
  955. // potential expense of additional runs through handle_read_frame
  956. /*(m_processor->get_bytes_needed() > config::connection_read_buffer_size ?
  957. config::connection_read_buffer_size : m_processor->get_bytes_needed())*/
  958. 1, m_buf, config::connection_read_buffer_size, m_handle_read_frame);
  959. }
  960. template <typename config> lib::error_code connection<config>::initialize_processor()
  961. {
  962. m_alog->write(log::alevel::devel, "initialize_processor");
  963. // if it isn't a websocket handshake nothing to do.
  964. if (! processor::is_websocket_handshake(m_request))
  965. {
  966. return lib::error_code();
  967. }
  968. int version = processor::get_websocket_version(m_request);
  969. if (version < 0)
  970. {
  971. m_alog->write(log::alevel::devel, "BAD REQUEST: can't determine version");
  972. m_response.set_status(http::status_code::bad_request);
  973. return error::make_error_code(error::invalid_version);
  974. }
  975. m_processor = get_processor(version);
  976. // if the processor is not null we are done
  977. if (m_processor)
  978. {
  979. return lib::error_code();
  980. }
  981. // We don't have a processor for this version. Return bad request
  982. // with Sec-WebSocket-Version header filled with values we do accept
  983. m_alog->write(log::alevel::devel, "BAD REQUEST: no processor for version");
  984. m_response.set_status(http::status_code::bad_request);
  985. std::stringstream ss;
  986. std::string sep;
  987. std::vector<int>::const_iterator it;
  988. for (it = versions_supported.begin(); it != versions_supported.end(); it++)
  989. {
  990. ss << sep << *it;
  991. sep = ",";
  992. }
  993. m_response.replace_header("Sec-WebSocket-Version", ss.str());
  994. return error::make_error_code(error::unsupported_version);
  995. }
  996. template <typename config> lib::error_code connection<config>::process_handshake_request()
  997. {
  998. m_alog->write(log::alevel::devel, "process handshake request");
  999. if (! processor::is_websocket_handshake(m_request))
  1000. {
  1001. // this is not a websocket handshake. Process as plain HTTP
  1002. m_alog->write(log::alevel::devel, "HTTP REQUEST");
  1003. // extract URI from request
  1004. m_uri = processor::get_uri_from_host(m_request, transport_con_type::is_secure() ? "https" : "http");
  1005. if (! m_uri->get_valid())
  1006. {
  1007. m_alog->write(log::alevel::devel, "Bad request: failed to parse uri");
  1008. m_response.set_status(http::status_code::bad_request);
  1009. return error::make_error_code(error::invalid_uri);
  1010. }
  1011. if (m_http_handler)
  1012. {
  1013. m_is_http = true;
  1014. m_http_handler(m_connection_hdl);
  1015. if (m_state == session::state::closed)
  1016. {
  1017. return error::make_error_code(error::http_connection_ended);
  1018. }
  1019. }
  1020. else
  1021. {
  1022. set_status(http::status_code::upgrade_required);
  1023. return error::make_error_code(error::upgrade_required);
  1024. }
  1025. return lib::error_code();
  1026. }
  1027. lib::error_code ec = m_processor->validate_handshake(m_request);
  1028. // Validate: make sure all required elements are present.
  1029. if (ec)
  1030. {
  1031. // Not a valid handshake request
  1032. m_alog->write(log::alevel::devel, "Bad request " + ec.message());
  1033. m_response.set_status(http::status_code::bad_request);
  1034. return ec;
  1035. }
  1036. // Read extension parameters and set up values necessary for the end user
  1037. // to complete extension negotiation.
  1038. std::pair<lib::error_code, std::string> neg_results;
  1039. neg_results = m_processor->negotiate_extensions(m_request);
  1040. if (neg_results.first == processor::error::make_error_code(processor::error::extension_parse_error))
  1041. {
  1042. // There was a fatal error in extension parsing that should result in
  1043. // a failed connection attempt.
  1044. m_elog->write(log::elevel::info, "Bad request: " + neg_results.first.message());
  1045. m_response.set_status(http::status_code::bad_request);
  1046. return neg_results.first;
  1047. }
  1048. else if (neg_results.first)
  1049. {
  1050. // There was a fatal error in extension processing that is probably our
  1051. // fault. Consider extension negotiation to have failed and continue as
  1052. // if extensions were not supported
  1053. m_elog->write(log::elevel::info, "Extension negotiation failed: " + neg_results.first.message());
  1054. }
  1055. else
  1056. {
  1057. // extension negotiation succeeded, set response header accordingly
  1058. // we don't send an empty extensions header because it breaks many
  1059. // clients.
  1060. if (neg_results.second.size() > 0)
  1061. {
  1062. m_response.replace_header("Sec-WebSocket-Extensions", neg_results.second);
  1063. }
  1064. }
  1065. // extract URI from request
  1066. m_uri = m_processor->get_uri(m_request);
  1067. if (! m_uri->get_valid())
  1068. {
  1069. m_alog->write(log::alevel::devel, "Bad request: failed to parse uri");
  1070. m_response.set_status(http::status_code::bad_request);
  1071. return error::make_error_code(error::invalid_uri);
  1072. }
  1073. // extract subprotocols
  1074. lib::error_code subp_ec = m_processor->extract_subprotocols(m_request, m_requested_subprotocols);
  1075. if (subp_ec)
  1076. {
  1077. // should we do anything?
  1078. }
  1079. // Ask application to validate the connection
  1080. if (! m_validate_handler || m_validate_handler(m_connection_hdl))
  1081. {
  1082. m_response.set_status(http::status_code::switching_protocols);
  1083. // Write the appropriate response headers based on request and
  1084. // processor version
  1085. ec = m_processor->process_handshake(m_request, m_subprotocol, m_response);
  1086. if (ec)
  1087. {
  1088. std::stringstream s;
  1089. s << "Processing error: " << ec << "(" << ec.message() << ")";
  1090. m_alog->write(log::alevel::devel, s.str());
  1091. m_response.set_status(http::status_code::internal_server_error);
  1092. return ec;
  1093. }
  1094. }
  1095. else
  1096. {
  1097. // User application has rejected the handshake
  1098. m_alog->write(log::alevel::devel, "USER REJECT");
  1099. // Use Bad Request if the user handler did not provide a more
  1100. // specific http response error code.
  1101. // TODO: is there a better default?
  1102. if (m_response.get_status_code() == http::status_code::uninitialized)
  1103. {
  1104. m_response.set_status(http::status_code::bad_request);
  1105. }
  1106. return error::make_error_code(error::rejected);
  1107. }
  1108. return lib::error_code();
  1109. }
  1110. template <typename config> void connection<config>::write_http_response(const lib::error_code & ec)
  1111. {
  1112. m_alog->write(log::alevel::devel, "connection write_http_response");
  1113. if (ec == error::make_error_code(error::http_connection_ended))
  1114. {
  1115. m_alog->write(log::alevel::http, "An HTTP handler took over the connection.");
  1116. return;
  1117. }
  1118. if (m_response.get_status_code() == http::status_code::uninitialized)
  1119. {
  1120. m_response.set_status(http::status_code::internal_server_error);
  1121. m_ec = error::make_error_code(error::general);
  1122. }
  1123. else
  1124. {
  1125. m_ec = ec;
  1126. }
  1127. m_response.set_version("HTTP/1.1");
  1128. // Set server header based on the user agent settings
  1129. if (m_response.get_header("Server").empty())
  1130. {
  1131. if (! m_user_agent.empty())
  1132. {
  1133. m_response.replace_header("Server", m_user_agent);
  1134. }
  1135. else
  1136. {
  1137. m_response.remove_header("Server");
  1138. }
  1139. }
  1140. // have the processor generate the raw bytes for the wire (if it exists)
  1141. if (m_processor)
  1142. {
  1143. m_handshake_buffer = m_processor->get_raw(m_response);
  1144. }
  1145. else
  1146. {
  1147. // a processor wont exist for raw HTTP responses.
  1148. m_handshake_buffer = m_response.raw();
  1149. }
  1150. if (m_alog->static_test(log::alevel::devel))
  1151. {
  1152. m_alog->write(log::alevel::devel, "Raw Handshake response:\n" + m_handshake_buffer);
  1153. if (! m_response.get_header("Sec-WebSocket-Key3").empty())
  1154. {
  1155. m_alog->write(log::alevel::devel, utility::to_hex(m_response.get_header("Sec-WebSocket-Key3")));
  1156. }
  1157. }
  1158. // write raw bytes
  1159. transport_con_type::async_write(m_handshake_buffer.data(), m_handshake_buffer.size(), lib::bind(&type::handle_write_http_response, type::get_shared(), lib::placeholders::_1));
  1160. }
  1161. template <typename config> void connection<config>::handle_write_http_response(const lib::error_code & ec)
  1162. {
  1163. m_alog->write(log::alevel::devel, "handle_write_http_response");
  1164. lib::error_code ecm = ec;
  1165. if (! ecm)
  1166. {
  1167. scoped_lock_type lock(m_connection_state_lock);
  1168. if (m_state == session::state::connecting)
  1169. {
  1170. if (m_internal_state != istate::PROCESS_HTTP_REQUEST)
  1171. {
  1172. ecm = error::make_error_code(error::invalid_state);
  1173. }
  1174. }
  1175. else if (m_state == session::state::closed)
  1176. {
  1177. // The connection was canceled while the response was being sent,
  1178. // usually by the handshake timer. This is basically expected
  1179. // (though hopefully rare) and there is nothing we can do so ignore.
  1180. m_alog->write(log::alevel::devel, "handle_write_http_response invoked after connection was closed");
  1181. return;
  1182. }
  1183. else
  1184. {
  1185. ecm = error::make_error_code(error::invalid_state);
  1186. }
  1187. }
  1188. if (ecm)
  1189. {
  1190. if (ecm == transport::error::eof && m_state == session::state::closed)
  1191. {
  1192. // we expect to get eof if the connection is closed already
  1193. m_alog->write(log::alevel::devel, "got (expected) eof/state error from closed con");
  1194. return;
  1195. }
  1196. log_err(log::elevel::rerror, "handle_write_http_response", ecm);
  1197. this->terminate(ecm);
  1198. return;
  1199. }
  1200. if (m_handshake_timer)
  1201. {
  1202. m_handshake_timer->cancel();
  1203. m_handshake_timer.reset();
  1204. }
  1205. if (m_response.get_status_code() != http::status_code::switching_protocols)
  1206. {
  1207. /*if (m_processor || m_ec == error::http_parse_error ||
  1208. m_ec == error::invalid_version || m_ec == error::unsupported_version
  1209. || m_ec == error::upgrade_required)
  1210. {*/
  1211. if (! m_is_http)
  1212. {
  1213. std::stringstream s;
  1214. s << "Handshake ended with HTTP error: " << m_response.get_status_code();
  1215. m_elog->write(log::elevel::rerror, s.str());
  1216. }
  1217. else
  1218. {
  1219. // if this was not a websocket connection, we have written
  1220. // the expected response and the connection can be closed.
  1221. this->log_http_result();
  1222. if (m_ec)
  1223. {
  1224. m_alog->write(log::alevel::devel, "got to writing HTTP results with m_ec set: " + m_ec.message());
  1225. }
  1226. m_ec = make_error_code(error::http_connection_ended);
  1227. }
  1228. this->terminate(m_ec);
  1229. return;
  1230. }
  1231. this->log_open_result();
  1232. m_internal_state = istate::PROCESS_CONNECTION;
  1233. m_state = session::state::open;
  1234. if (m_open_handler)
  1235. {
  1236. m_open_handler(m_connection_hdl);
  1237. }
  1238. this->handle_read_frame(lib::error_code(), m_buf_cursor);
  1239. }
  1240. template <typename config> void connection<config>::send_http_request()
  1241. {
  1242. m_alog->write(log::alevel::devel, "connection send_http_request");
  1243. // TODO: origin header?
  1244. // Have the protocol processor fill in the appropriate fields based on the
  1245. // selected client version
  1246. if (m_processor)
  1247. {
  1248. lib::error_code ec;
  1249. ec = m_processor->client_handshake_request(m_request, m_uri, m_requested_subprotocols);
  1250. if (ec)
  1251. {
  1252. log_err(log::elevel::fatal, "Internal library error: Processor", ec);
  1253. return;
  1254. }
  1255. }
  1256. else
  1257. {
  1258. m_elog->write(log::elevel::fatal, "Internal library error: missing processor");
  1259. return;
  1260. }
  1261. // Unless the user has overridden the user agent, send generic WS++ UA.
  1262. if (m_request.get_header("User-Agent").empty())
  1263. {
  1264. if (! m_user_agent.empty())
  1265. {
  1266. m_request.replace_header("User-Agent", m_user_agent);
  1267. }
  1268. else
  1269. {
  1270. m_request.remove_header("User-Agent");
  1271. }
  1272. }
  1273. m_handshake_buffer = m_request.raw();
  1274. if (m_alog->static_test(log::alevel::devel))
  1275. {
  1276. m_alog->write(log::alevel::devel, "Raw Handshake request:\n" + m_handshake_buffer);
  1277. }
  1278. if (m_open_handshake_timeout_dur > 0)
  1279. {
  1280. m_handshake_timer = transport_con_type::set_timer(m_open_handshake_timeout_dur, lib::bind(&type::handle_open_handshake_timeout, type::get_shared(), lib::placeholders::_1));
  1281. }
  1282. transport_con_type::async_write(m_handshake_buffer.data(), m_handshake_buffer.size(), lib::bind(&type::handle_send_http_request, type::get_shared(), lib::placeholders::_1));
  1283. }
  1284. template <typename config> void connection<config>::handle_send_http_request(const lib::error_code & ec)
  1285. {
  1286. m_alog->write(log::alevel::devel, "handle_send_http_request");
  1287. lib::error_code ecm = ec;
  1288. if (! ecm)
  1289. {
  1290. scoped_lock_type lock(m_connection_state_lock);
  1291. if (m_state == session::state::connecting)
  1292. {
  1293. if (m_internal_state != istate::WRITE_HTTP_REQUEST)
  1294. {
  1295. ecm = error::make_error_code(error::invalid_state);
  1296. }
  1297. else
  1298. {
  1299. m_internal_state = istate::READ_HTTP_RESPONSE;
  1300. }
  1301. }
  1302. else if (m_state == session::state::closed)
  1303. {
  1304. // The connection was canceled while the response was being sent,
  1305. // usually by the handshake timer. This is basically expected
  1306. // (though hopefully rare) and there is nothing we can do so ignore.
  1307. m_alog->write(log::alevel::devel, "handle_send_http_request invoked after connection was closed");
  1308. return;
  1309. }
  1310. else
  1311. {
  1312. ecm = error::make_error_code(error::invalid_state);
  1313. }
  1314. }
  1315. if (ecm)
  1316. {
  1317. if (ecm == transport::error::eof && m_state == session::state::closed)
  1318. {
  1319. // we expect to get eof if the connection is closed already
  1320. m_alog->write(log::alevel::devel, "got (expected) eof/state error from closed con");
  1321. return;
  1322. }
  1323. log_err(log::elevel::rerror, "handle_send_http_request", ecm);
  1324. this->terminate(ecm);
  1325. return;
  1326. }
  1327. transport_con_type::async_read_at_least(1, m_buf, config::connection_read_buffer_size, lib::bind(&type::handle_read_http_response, type::get_shared(), lib::placeholders::_1, lib::placeholders::_2));
  1328. }
  1329. template <typename config> void connection<config>::handle_read_http_response(const lib::error_code & ec, size_t bytes_transferred)
  1330. {
  1331. m_alog->write(log::alevel::devel, "handle_read_http_response");
  1332. lib::error_code ecm = ec;
  1333. if (! ecm)
  1334. {
  1335. scoped_lock_type lock(m_connection_state_lock);
  1336. if (m_state == session::state::connecting)
  1337. {
  1338. if (m_internal_state != istate::READ_HTTP_RESPONSE)
  1339. {
  1340. ecm = error::make_error_code(error::invalid_state);
  1341. }
  1342. }
  1343. else if (m_state == session::state::closed)
  1344. {
  1345. // The connection was canceled while the response was being sent,
  1346. // usually by the handshake timer. This is basically expected
  1347. // (though hopefully rare) and there is nothing we can do so ignore.
  1348. m_alog->write(log::alevel::devel, "handle_read_http_response invoked after connection was closed");
  1349. return;
  1350. }
  1351. else
  1352. {
  1353. ecm = error::make_error_code(error::invalid_state);
  1354. }
  1355. }
  1356. if (ecm)
  1357. {
  1358. if (ecm == transport::error::eof && m_state == session::state::closed)
  1359. {
  1360. // we expect to get eof if the connection is closed already
  1361. m_alog->write(log::alevel::devel, "got (expected) eof/state error from closed con");
  1362. return;
  1363. }
  1364. log_err(log::elevel::rerror, "handle_read_http_response", ecm);
  1365. this->terminate(ecm);
  1366. return;
  1367. }
  1368. size_t bytes_processed = 0;
  1369. // TODO: refactor this to use error codes rather than exceptions
  1370. try
  1371. {
  1372. bytes_processed = m_response.consume(m_buf, bytes_transferred);
  1373. }
  1374. catch (http::exception & e)
  1375. {
  1376. m_elog->write(log::elevel::rerror, std::string("error in handle_read_http_response: ") + e.what());
  1377. this->terminate(make_error_code(error::general));
  1378. return;
  1379. }
  1380. m_alog->write(log::alevel::devel, std::string("Raw response: ") + m_response.raw());
  1381. if (m_response.headers_ready())
  1382. {
  1383. if (m_handshake_timer)
  1384. {
  1385. m_handshake_timer->cancel();
  1386. m_handshake_timer.reset();
  1387. }
  1388. lib::error_code validate_ec = m_processor->validate_server_handshake_response(m_request, m_response);
  1389. if (validate_ec)
  1390. {
  1391. log_err(log::elevel::rerror, "Server handshake response", validate_ec);
  1392. this->terminate(validate_ec);
  1393. return;
  1394. }
  1395. // Read extension parameters and set up values necessary for the end
  1396. // user to complete extension negotiation.
  1397. std::pair<lib::error_code, std::string> neg_results;
  1398. neg_results = m_processor->negotiate_extensions(m_response);
  1399. if (neg_results.first)
  1400. {
  1401. // There was a fatal error in extension negotiation. For the moment
  1402. // kill all connections that fail extension negotiation.
  1403. // TODO: deal with cases where the response is well formed but
  1404. // doesn't match the options requested by the client. Its possible
  1405. // that the best behavior in this cases is to log and continue with
  1406. // an unextended connection.
  1407. m_alog->write(log::alevel::devel, "Extension negotiation failed: " + neg_results.first.message());
  1408. this->terminate(make_error_code(error::extension_neg_failed));
  1409. // TODO: close connection with reason 1010 (and list extensions)
  1410. }
  1411. // response is valid, connection can now be assumed to be open
  1412. m_internal_state = istate::PROCESS_CONNECTION;
  1413. m_state = session::state::open;
  1414. this->log_open_result();
  1415. if (m_open_handler)
  1416. {
  1417. m_open_handler(m_connection_hdl);
  1418. }
  1419. // The remaining bytes in m_buf are frame data. Copy them to the
  1420. // beginning of the buffer and note the length. They will be read after
  1421. // the handshake completes and before more bytes are read.
  1422. std::copy(m_buf + bytes_processed, m_buf + bytes_transferred, m_buf);
  1423. m_buf_cursor = bytes_transferred - bytes_processed;
  1424. this->handle_read_frame(lib::error_code(), m_buf_cursor);
  1425. }
  1426. else
  1427. {
  1428. transport_con_type::async_read_at_least(1, m_buf, config::connection_read_buffer_size, lib::bind(&type::handle_read_http_response, type::get_shared(), lib::placeholders::_1, lib::placeholders::_2));
  1429. }
  1430. }
  1431. template <typename config> void connection<config>::handle_open_handshake_timeout(const lib::error_code & ec)
  1432. {
  1433. if (ec == transport::error::operation_aborted)
  1434. {
  1435. m_alog->write(log::alevel::devel, "open handshake timer cancelled");
  1436. }
  1437. else if (ec)
  1438. {
  1439. m_alog->write(log::alevel::devel, "open handle_open_handshake_timeout error: " + ec.message());
  1440. // TODO: ignore or fail here?
  1441. }
  1442. else
  1443. {
  1444. m_alog->write(log::alevel::devel, "open handshake timer expired");
  1445. terminate(make_error_code(error::open_handshake_timeout));
  1446. }
  1447. }
  1448. template <typename config> void connection<config>::handle_close_handshake_timeout(const lib::error_code & ec)
  1449. {
  1450. if (ec == transport::error::operation_aborted)
  1451. {
  1452. m_alog->write(log::alevel::devel, "asio close handshake timer cancelled");
  1453. }
  1454. else if (ec)
  1455. {
  1456. m_alog->write(log::alevel::devel, "asio open handle_close_handshake_timeout error: " + ec.message());
  1457. // TODO: ignore or fail here?
  1458. }
  1459. else
  1460. {
  1461. m_alog->write(log::alevel::devel, "asio close handshake timer expired");
  1462. terminate(make_error_code(error::close_handshake_timeout));
  1463. }
  1464. }
  1465. template <typename config> void connection<config>::terminate(const lib::error_code & ec)
  1466. {
  1467. if (m_alog->static_test(log::alevel::devel))
  1468. {
  1469. m_alog->write(log::alevel::devel, "connection terminate");
  1470. }
  1471. // Cancel close handshake timer
  1472. if (m_handshake_timer)
  1473. {
  1474. m_handshake_timer->cancel();
  1475. m_handshake_timer.reset();
  1476. }
  1477. terminate_status tstat = unknown;
  1478. if (ec)
  1479. {
  1480. m_ec = ec;
  1481. m_local_close_code = close::status::abnormal_close;
  1482. m_local_close_reason = ec.message();
  1483. }
  1484. // TODO: does any of this need a mutex?
  1485. if (m_is_http)
  1486. {
  1487. m_http_state = session::http_state::closed;
  1488. }
  1489. if (m_state == session::state::connecting)
  1490. {
  1491. m_state = session::state::closed;
  1492. tstat = failed;
  1493. // Log fail result here before socket is shut down and we can't get
  1494. // the remote address, etc anymore
  1495. if (m_ec != error::http_connection_ended)
  1496. {
  1497. log_fail_result();
  1498. }
  1499. }
  1500. else if (m_state != session::state::closed)
  1501. {
  1502. m_state = session::state::closed;
  1503. tstat = closed;
  1504. }
  1505. else
  1506. {
  1507. m_alog->write(log::alevel::devel, "terminate called on connection that was already terminated");
  1508. return;
  1509. }
  1510. // TODO: choose between shutdown and close based on error code sent
  1511. transport_con_type::async_shutdown(lib::bind(&type::handle_terminate, type::get_shared(), tstat, lib::placeholders::_1));
  1512. }
  1513. template <typename config> void connection<config>::handle_terminate(terminate_status tstat, const lib::error_code & ec)
  1514. {
  1515. if (m_alog->static_test(log::alevel::devel))
  1516. {
  1517. m_alog->write(log::alevel::devel, "connection handle_terminate");
  1518. }
  1519. if (ec)
  1520. {
  1521. // there was an error actually shutting down the connection
  1522. log_err(log::elevel::devel, "handle_terminate", ec);
  1523. }
  1524. // clean shutdown
  1525. if (tstat == failed)
  1526. {
  1527. if (m_ec != error::http_connection_ended)
  1528. {
  1529. if (m_fail_handler)
  1530. {
  1531. m_fail_handler(m_connection_hdl);
  1532. }
  1533. }
  1534. }
  1535. else if (tstat == closed)
  1536. {
  1537. if (m_close_handler)
  1538. {
  1539. m_close_handler(m_connection_hdl);
  1540. }
  1541. log_close_result();
  1542. }
  1543. else
  1544. {
  1545. m_elog->write(log::elevel::rerror, "Unknown terminate_status");
  1546. }
  1547. // call the termination handler if it exists
  1548. // if it exists it might (but shouldn't) refer to a bad memory location.
  1549. // If it does, we don't care and should catch and ignore it.
  1550. if (m_termination_handler)
  1551. {
  1552. try
  1553. {
  1554. m_termination_handler(type::get_shared());
  1555. }
  1556. catch (const std::exception & e)
  1557. {
  1558. m_elog->write(log::elevel::warn, std::string("termination_handler call failed. Reason was: ") + e.what());
  1559. }
  1560. }
  1561. }
  1562. template <typename config> void connection<config>::write_frame()
  1563. {
  1564. // m_alog->write(log::alevel::devel,"connection write_frame");
  1565. {
  1566. scoped_lock_type lock(m_write_lock);
  1567. // Check the write flag. If true, there is an outstanding transport
  1568. // write already. In this case we just return. The write handler will
  1569. // start a new write if the write queue isn't empty. If false, we set
  1570. // the write flag and proceed to initiate a transport write.
  1571. if (m_write_flag)
  1572. {
  1573. return;
  1574. }
  1575. // pull off all the messages that are ready to write.
  1576. // stop if we get a message marked terminal
  1577. message_ptr next_message = write_pop();
  1578. while (next_message)
  1579. {
  1580. m_current_msgs.push_back(next_message);
  1581. if (! next_message->get_terminal())
  1582. {
  1583. next_message = write_pop();
  1584. }
  1585. else
  1586. {
  1587. next_message = message_ptr();
  1588. }
  1589. }
  1590. if (m_current_msgs.empty())
  1591. {
  1592. // there was nothing to send
  1593. return;
  1594. }
  1595. else
  1596. {
  1597. // At this point we own the next messages to be sent and are
  1598. // responsible for holding the write flag until they are
  1599. // successfully sent or there is some error
  1600. m_write_flag = true;
  1601. }
  1602. }
  1603. typename std::vector<message_ptr>::iterator it;
  1604. for (it = m_current_msgs.begin(); it != m_current_msgs.end(); ++it)
  1605. {
  1606. const std::string & header = (*it)->get_header();
  1607. const std::string & payload = (*it)->get_payload();
  1608. m_send_buffer.push_back(transport::buffer(header.c_str(), header.size()));
  1609. m_send_buffer.push_back(transport::buffer(payload.c_str(), payload.size()));
  1610. }
  1611. // Print detailed send stats if those log levels are enabled
  1612. if (m_alog->static_test(log::alevel::frame_header))
  1613. {
  1614. if (m_alog->dynamic_test(log::alevel::frame_header))
  1615. {
  1616. std::stringstream general, header, payload;
  1617. general << "Dispatching write containing " << m_current_msgs.size() << " message(s) containing ";
  1618. header << "Header Bytes: \n";
  1619. payload << "Payload Bytes: \n";
  1620. size_t hbytes = 0;
  1621. size_t pbytes = 0;
  1622. for (size_t i = 0; i < m_current_msgs.size(); i++)
  1623. {
  1624. hbytes += m_current_msgs[i]->get_header().size();
  1625. pbytes += m_current_msgs[i]->get_payload().size();
  1626. header << "[" << i << "] (" << m_current_msgs[i]->get_header().size() << ") " << utility::to_hex(m_current_msgs[i]->get_header()) << "\n";
  1627. if (m_alog->static_test(log::alevel::frame_payload))
  1628. {
  1629. if (m_alog->dynamic_test(log::alevel::frame_payload))
  1630. {
  1631. payload << "[" << i << "] (" << m_current_msgs[i]->get_payload().size() << ") [" << m_current_msgs[i]->get_opcode() << "] "
  1632. << (m_current_msgs[i]->get_opcode() == frame::opcode::text ? m_current_msgs[i]->get_payload() : utility::to_hex(m_current_msgs[i]->get_payload())) << "\n";
  1633. }
  1634. }
  1635. }
  1636. general << hbytes << " header bytes and " << pbytes << " payload bytes";
  1637. m_alog->write(log::alevel::frame_header, general.str());
  1638. m_alog->write(log::alevel::frame_header, header.str());
  1639. m_alog->write(log::alevel::frame_payload, payload.str());
  1640. }
  1641. }
  1642. transport_con_type::async_write(m_send_buffer, m_write_frame_handler);
  1643. }
  1644. template <typename config> void connection<config>::handle_write_frame(const lib::error_code & ec)
  1645. {
  1646. if (m_alog->static_test(log::alevel::devel))
  1647. {
  1648. m_alog->write(log::alevel::devel, "connection handle_write_frame");
  1649. }
  1650. bool terminal = m_current_msgs.back()->get_terminal();
  1651. m_send_buffer.clear();
  1652. m_current_msgs.clear();
  1653. // TODO: recycle instead of deleting
  1654. if (ec)
  1655. {
  1656. log_err(log::elevel::fatal, "handle_write_frame", ec);
  1657. this->terminate(ec);
  1658. return;
  1659. }
  1660. if (terminal)
  1661. {
  1662. this->terminate(lib::error_code());
  1663. return;
  1664. }
  1665. bool needs_writing = false;
  1666. {
  1667. scoped_lock_type lock(m_write_lock);
  1668. // release write flag
  1669. m_write_flag = false;
  1670. needs_writing = ! m_send_queue.empty();
  1671. }
  1672. if (needs_writing)
  1673. {
  1674. transport_con_type::dispatch(lib::bind(&type::write_frame, type::get_shared()));
  1675. }
  1676. }
  1677. template <typename config> const std::vector<int> & connection<config>::get_supported_versions() const
  1678. {
  1679. return versions_supported;
  1680. }
  1681. template <typename config> void connection<config>::process_control_frame(typename config::message_type::ptr msg)
  1682. {
  1683. m_alog->write(log::alevel::devel, "process_control_frame");
  1684. frame::opcode::value op = msg->get_opcode();
  1685. lib::error_code ec;
  1686. std::stringstream s;
  1687. s << "Control frame received with opcode " << op;
  1688. m_alog->write(log::alevel::control, s.str());
  1689. if (m_state == session::state::closed)
  1690. {
  1691. m_elog->write(log::elevel::warn, "got frame in state closed");
  1692. return;
  1693. }
  1694. if (op != frame::opcode::CLOSE && m_state != session::state::open)
  1695. {
  1696. m_elog->write(log::elevel::warn, "got non-close frame in state closing");
  1697. return;
  1698. }
  1699. if (op == frame::opcode::PING)
  1700. {
  1701. bool should_reply = true;
  1702. if (m_ping_handler)
  1703. {
  1704. should_reply = m_ping_handler(m_connection_hdl, msg->get_payload());
  1705. }
  1706. if (should_reply)
  1707. {
  1708. this->pong(msg->get_payload(), ec);
  1709. if (ec)
  1710. {
  1711. log_err(log::elevel::devel, "Failed to send response pong", ec);
  1712. }
  1713. }
  1714. }
  1715. else if (op == frame::opcode::PONG)
  1716. {
  1717. if (m_pong_handler)
  1718. {
  1719. m_pong_handler(m_connection_hdl, msg->get_payload());
  1720. }
  1721. if (m_ping_timer)
  1722. {
  1723. m_ping_timer->cancel();
  1724. }
  1725. }
  1726. else if (op == frame::opcode::CLOSE)
  1727. {
  1728. m_alog->write(log::alevel::devel, "got close frame");
  1729. // record close code and reason somewhere
  1730. m_remote_close_code = close::extract_code(msg->get_payload(), ec);
  1731. if (ec)
  1732. {
  1733. s.str("");
  1734. if (config::drop_on_protocol_error)
  1735. {
  1736. s << "Received invalid close code " << m_remote_close_code << " dropping connection per config.";
  1737. m_elog->write(log::elevel::devel, s.str());
  1738. this->terminate(ec);
  1739. }
  1740. else
  1741. {
  1742. s << "Received invalid close code " << m_remote_close_code << " sending acknowledgement and closing";
  1743. m_elog->write(log::elevel::devel, s.str());
  1744. ec = send_close_ack(close::status::protocol_error, "Invalid close code");
  1745. if (ec)
  1746. {
  1747. log_err(log::elevel::devel, "send_close_ack", ec);
  1748. }
  1749. }
  1750. return;
  1751. }
  1752. m_remote_close_reason = close::extract_reason(msg->get_payload(), ec);
  1753. if (ec)
  1754. {
  1755. if (config::drop_on_protocol_error)
  1756. {
  1757. m_elog->write(log::elevel::devel, "Received invalid close reason. Dropping connection per config");
  1758. this->terminate(ec);
  1759. }
  1760. else
  1761. {
  1762. m_elog->write(log::elevel::devel, "Received invalid close reason. Sending acknowledgement and closing");
  1763. ec = send_close_ack(close::status::protocol_error, "Invalid close reason");
  1764. if (ec)
  1765. {
  1766. log_err(log::elevel::devel, "send_close_ack", ec);
  1767. }
  1768. }
  1769. return;
  1770. }
  1771. if (m_state == session::state::open)
  1772. {
  1773. s.str("");
  1774. s << "Received close frame with code " << m_remote_close_code << " and reason " << m_remote_close_reason;
  1775. m_alog->write(log::alevel::devel, s.str());
  1776. ec = send_close_ack();
  1777. if (ec)
  1778. {
  1779. log_err(log::elevel::devel, "send_close_ack", ec);
  1780. }
  1781. }
  1782. else if (m_state == session::state::closing && ! m_was_clean)
  1783. {
  1784. // ack of our close
  1785. m_alog->write(log::alevel::devel, "Got acknowledgement of close");
  1786. m_was_clean = true;
  1787. // If we are a server terminate the connection now. Clients should
  1788. // leave the connection open to give the server an opportunity to
  1789. // initiate the TCP close. The client's timer will handle closing
  1790. // its side of the connection if the server misbehaves.
  1791. //
  1792. // TODO: different behavior if the underlying transport doesn't
  1793. // support timers?
  1794. if (m_is_server)
  1795. {
  1796. terminate(lib::error_code());
  1797. }
  1798. }
  1799. else
  1800. {
  1801. // spurious, ignore
  1802. m_elog->write(log::elevel::devel, "Got close frame in wrong state");
  1803. }
  1804. }
  1805. else
  1806. {
  1807. // got an invalid control opcode
  1808. m_elog->write(log::elevel::devel, "Got control frame with invalid opcode");
  1809. // initiate protocol error shutdown
  1810. }
  1811. }
  1812. template <typename config> lib::error_code connection<config>::send_close_ack(close::status::value code, const std::string & reason)
  1813. {
  1814. return send_close_frame(code, reason, true, m_is_server);
  1815. }
  1816. template <typename config> lib::error_code connection<config>::send_close_frame(close::status::value code, const std::string & reason, bool ack, bool terminal)
  1817. {
  1818. m_alog->write(log::alevel::devel, "send_close_frame");
  1819. // check for special codes
  1820. // If silent close is set, respect it and blank out close information
  1821. // Otherwise use whatever has been specified in the parameters. If
  1822. // parameters specifies close::status::blank then determine what to do
  1823. // based on whether or not this is an ack. If it is not an ack just
  1824. // send blank info. If it is an ack then echo the close information from
  1825. // the remote endpoint.
  1826. if (config::silent_close)
  1827. {
  1828. m_alog->write(log::alevel::devel, "closing silently");
  1829. m_local_close_code = close::status::no_status;
  1830. m_local_close_reason.clear();
  1831. }
  1832. else if (code != close::status::blank)
  1833. {
  1834. m_alog->write(log::alevel::devel, "closing with specified codes");
  1835. m_local_close_code = code;
  1836. m_local_close_reason = reason;
  1837. }
  1838. else if (! ack)
  1839. {
  1840. m_alog->write(log::alevel::devel, "closing with no status code");
  1841. m_local_close_code = close::status::no_status;
  1842. m_local_close_reason.clear();
  1843. }
  1844. else if (m_remote_close_code == close::status::no_status)
  1845. {
  1846. m_alog->write(log::alevel::devel, "acknowledging a no-status close with normal code");
  1847. m_local_close_code = close::status::normal;
  1848. m_local_close_reason.clear();
  1849. }
  1850. else
  1851. {
  1852. m_alog->write(log::alevel::devel, "acknowledging with remote codes");
  1853. m_local_close_code = m_remote_close_code;
  1854. m_local_close_reason = m_remote_close_reason;
  1855. }
  1856. std::stringstream s;
  1857. s << "Closing with code: " << m_local_close_code << ", and reason: " << m_local_close_reason;
  1858. m_alog->write(log::alevel::devel, s.str());
  1859. message_ptr msg = m_msg_manager->get_message();
  1860. if (! msg)
  1861. {
  1862. return error::make_error_code(error::no_outgoing_buffers);
  1863. }
  1864. lib::error_code ec = m_processor->prepare_close(m_local_close_code, m_local_close_reason, msg);
  1865. if (ec)
  1866. {
  1867. return ec;
  1868. }
  1869. // Messages flagged terminal will result in the TCP connection being dropped
  1870. // after the message has been written. This is typically used when servers
  1871. // send an ack and when any endpoint encounters a protocol error
  1872. if (terminal)
  1873. {
  1874. msg->set_terminal(true);
  1875. }
  1876. m_state = session::state::closing;
  1877. if (ack)
  1878. {
  1879. m_was_clean = true;
  1880. }
  1881. // Start a timer so we don't wait forever for the acknowledgement close
  1882. // frame
  1883. if (m_close_handshake_timeout_dur > 0)
  1884. {
  1885. m_handshake_timer = transport_con_type::set_timer(m_close_handshake_timeout_dur, lib::bind(&type::handle_close_handshake_timeout, type::get_shared(), lib::placeholders::_1));
  1886. }
  1887. bool needs_writing = false;
  1888. {
  1889. scoped_lock_type lock(m_write_lock);
  1890. write_push(msg);
  1891. needs_writing = ! m_write_flag && ! m_send_queue.empty();
  1892. }
  1893. if (needs_writing)
  1894. {
  1895. transport_con_type::dispatch(lib::bind(&type::write_frame, type::get_shared()));
  1896. }
  1897. return lib::error_code();
  1898. }
  1899. template <typename config> typename connection<config>::processor_ptr connection<config>::get_processor(int version) const
  1900. {
  1901. // TODO: allow disabling certain versions
  1902. processor_ptr p;
  1903. switch (version)
  1904. {
  1905. case 0 : p = lib::make_shared<processor::hybi00<config>>(transport_con_type::is_secure(), m_is_server, m_msg_manager); break;
  1906. case 7 : p = lib::make_shared<processor::hybi07<config>>(transport_con_type::is_secure(), m_is_server, m_msg_manager, lib::ref(m_rng)); break;
  1907. case 8 : p = lib::make_shared<processor::hybi08<config>>(transport_con_type::is_secure(), m_is_server, m_msg_manager, lib::ref(m_rng)); break;
  1908. case 13: p = lib::make_shared<processor::hybi13<config>>(transport_con_type::is_secure(), m_is_server, m_msg_manager, lib::ref(m_rng)); break;
  1909. default: return p;
  1910. }
  1911. // Settings not configured by the constructor
  1912. p->set_max_message_size(m_max_message_size);
  1913. return p;
  1914. }
  1915. template <typename config> void connection<config>::write_push(typename config::message_type::ptr msg)
  1916. {
  1917. if (! msg)
  1918. {
  1919. return;
  1920. }
  1921. m_send_buffer_size += msg->get_payload().size();
  1922. m_send_queue.push(msg);
  1923. if (m_alog->static_test(log::alevel::devel))
  1924. {
  1925. std::stringstream s;
  1926. s << "write_push: message count: " << m_send_queue.size() << " buffer size: " << m_send_buffer_size;
  1927. m_alog->write(log::alevel::devel, s.str());
  1928. }
  1929. }
  1930. template <typename config> typename config::message_type::ptr connection<config>::write_pop()
  1931. {
  1932. message_ptr msg;
  1933. if (m_send_queue.empty())
  1934. {
  1935. return msg;
  1936. }
  1937. msg = m_send_queue.front();
  1938. m_send_buffer_size -= msg->get_payload().size();
  1939. m_send_queue.pop();
  1940. if (m_alog->static_test(log::alevel::devel))
  1941. {
  1942. std::stringstream s;
  1943. s << "write_pop: message count: " << m_send_queue.size() << " buffer size: " << m_send_buffer_size;
  1944. m_alog->write(log::alevel::devel, s.str());
  1945. }
  1946. return msg;
  1947. }
  1948. template <typename config> void connection<config>::log_open_result()
  1949. {
  1950. std::stringstream s;
  1951. int version;
  1952. if (! processor::is_websocket_handshake(m_request))
  1953. {
  1954. version = -1;
  1955. }
  1956. else
  1957. {
  1958. version = processor::get_websocket_version(m_request);
  1959. }
  1960. // Connection Type
  1961. s << (version == -1 ? "HTTP" : "WebSocket") << " Connection ";
  1962. // Remote endpoint address
  1963. s << transport_con_type::get_remote_endpoint() << " ";
  1964. // Version string if WebSocket
  1965. if (version != -1)
  1966. {
  1967. s << "v" << version << " ";
  1968. }
  1969. // User Agent
  1970. std::string ua = m_request.get_header("User-Agent");
  1971. if (ua.empty())
  1972. {
  1973. s << "\"\" ";
  1974. }
  1975. else
  1976. {
  1977. // check if there are any quotes in the user agent
  1978. s << "\"" << utility::string_replace_all(ua, "\"", "\\\"") << "\" ";
  1979. }
  1980. // URI
  1981. s << (m_uri ? m_uri->get_resource() : "NULL") << " ";
  1982. // Status code
  1983. s << m_response.get_status_code();
  1984. m_alog->write(log::alevel::connect, s.str());
  1985. }
  1986. template <typename config> void connection<config>::log_close_result()
  1987. {
  1988. std::stringstream s;
  1989. s << "Disconnect "
  1990. << "close local:[" << m_local_close_code << (m_local_close_reason.empty() ? "" : "," + m_local_close_reason) << "] remote:[" << m_remote_close_code << (m_remote_close_reason.empty() ? "" : "," + m_remote_close_reason) << "]";
  1991. m_alog->write(log::alevel::disconnect, s.str());
  1992. }
  1993. template <typename config> void connection<config>::log_fail_result()
  1994. {
  1995. std::stringstream s;
  1996. int version = processor::get_websocket_version(m_request);
  1997. // Connection Type
  1998. s << "WebSocket Connection ";
  1999. // Remote endpoint address & WebSocket version
  2000. s << transport_con_type::get_remote_endpoint();
  2001. if (version < 0)
  2002. {
  2003. s << " -";
  2004. }
  2005. else
  2006. {
  2007. s << " v" << version;
  2008. }
  2009. // User Agent
  2010. std::string ua = m_request.get_header("User-Agent");
  2011. if (ua.empty())
  2012. {
  2013. s << " \"\" ";
  2014. }
  2015. else
  2016. {
  2017. // check if there are any quotes in the user agent
  2018. s << " \"" << utility::string_replace_all(ua, "\"", "\\\"") << "\" ";
  2019. }
  2020. // URI
  2021. s << (m_uri ? m_uri->get_resource() : "-");
  2022. // HTTP Status code
  2023. s << " " << m_response.get_status_code();
  2024. // WebSocket++ error code & reason
  2025. s << " " << m_ec << " " << m_ec.message();
  2026. m_alog->write(log::alevel::fail, s.str());
  2027. }
  2028. template <typename config> void connection<config>::log_http_result()
  2029. {
  2030. std::stringstream s;
  2031. if (processor::is_websocket_handshake(m_request))
  2032. {
  2033. m_alog->write(log::alevel::devel, "Call to log_http_result for WebSocket");
  2034. return;
  2035. }
  2036. // Connection Type
  2037. s << (m_request.get_header("host").empty() ? "-" : m_request.get_header("host")) << " " << transport_con_type::get_remote_endpoint() << " \"" << m_request.get_method() << " " << (m_uri ? m_uri->get_resource() : "-") << " "
  2038. << m_request.get_version() << "\" " << m_response.get_status_code() << " " << m_response.get_body().size();
  2039. // User Agent
  2040. std::string ua = m_request.get_header("User-Agent");
  2041. if (ua.empty())
  2042. {
  2043. s << " \"\" ";
  2044. }
  2045. else
  2046. {
  2047. // check if there are any quotes in the user agent
  2048. s << " \"" << utility::string_replace_all(ua, "\"", "\\\"") << "\" ";
  2049. }
  2050. m_alog->write(log::alevel::http, s.str());
  2051. }
  2052. } // namespace websocketpp
  2053. #endif // WEBSOCKETPP_CONNECTION_IMPL_HPP