302 lines
9.6 KiB
C++
302 lines
9.6 KiB
C++
#include "WebsocketSSLClientInternal.h"
|
|
#include "WebsocketError.h"
|
|
#include "WebsocketMessage.h"
|
|
#include "lib/logging/logging.h"
|
|
#include "lib/utils/bts_assert.h"
|
|
#include <atomic>
|
|
#ifndef _WIN32
|
|
#include <bits/stdint-intn.h>
|
|
#include <bits/stdint-uintn.h>
|
|
#endif
|
|
#include <boost/asio.hpp>
|
|
#include <boost/asio/buffer.hpp>
|
|
#include <boost/asio/io_context.hpp>
|
|
#include <boost/asio/ip/address.hpp>
|
|
#include <boost/asio/ip/tcp.hpp>
|
|
#include <boost/asio/strand.hpp>
|
|
#include <boost/asio/ts/netfwd.hpp>
|
|
#include <boost/beast/core.hpp>
|
|
#include <boost/beast/core/buffers_to_string.hpp>
|
|
#include <boost/beast/core/error.hpp>
|
|
#include <boost/beast/ssl.hpp>
|
|
#include <boost/beast/websocket.hpp>
|
|
#include <boost/beast/websocket/ssl.hpp>
|
|
#include <boost/bind/bind.hpp>
|
|
#include <boost/bind/placeholders.hpp>
|
|
#include <boost/core/addressof.hpp>
|
|
#include <boost/date_time/posix_time/posix_time.hpp>
|
|
#include <boost/date_time/posix_time/posix_time_duration.hpp>
|
|
#include <chrono>
|
|
#include <cstdint>
|
|
#include <cstdlib>
|
|
#include <iostream>
|
|
#include <memory>
|
|
#include <ostream>
|
|
#include <queue>
|
|
#include <sstream>
|
|
#include <string>
|
|
#include <sys/types.h>
|
|
#include <system_error>
|
|
#include <thread>
|
|
#include <tuple>
|
|
#include <utility>
|
|
#include <vector>
|
|
#include <websocketpp/client.hpp>
|
|
#include <websocketpp/server.hpp>
|
|
|
|
namespace bts::io::websocket {
|
|
|
|
// Resolver and socket require an io_context
|
|
WebsocketSSLClientInternal::WebsocketSSLClientInternal(
|
|
const WebsocketClientConfiguration &conf,
|
|
boost::asio::io_context &ioc,
|
|
boost::asio::ssl::context &ctx,
|
|
IWebsocketListener *listener)
|
|
: _conf(conf), _resolver(boost::asio::make_strand(ioc)),
|
|
_ws(boost::asio::make_strand(ioc), ctx),
|
|
_timer(ioc, boost::posix_time::milliseconds(conf.timer_ms)),
|
|
_listener(listener) {}
|
|
|
|
// user facing function
|
|
void WebsocketSSLClientInternal::start() { _resolve(); }
|
|
|
|
void WebsocketSSLClientInternal::send_message(const WebsocketMessage &msg) {
|
|
_send_queue.push(msg);
|
|
_write_data();
|
|
}
|
|
|
|
void WebsocketSSLClientInternal::close_connection() {
|
|
if (!_close_attempted) {
|
|
_close_attempted = true;
|
|
_ws.async_close(
|
|
boost::beast::websocket::close_code::normal,
|
|
boost::beast::bind_front_handler(
|
|
&WSCI::_on_close, shared_from_this()));
|
|
}
|
|
}
|
|
|
|
void WebsocketSSLClientInternal::_fail(
|
|
boost::beast::error_code ec, char const *what) {
|
|
std::cerr << what << ": " << ec.message() << std::endl;
|
|
}
|
|
|
|
void WebsocketSSLClientInternal::_handle_error(
|
|
boost::beast::error_code error_code,
|
|
std::string &&err_msg,
|
|
WebsocketError::ErrorType err_type) {
|
|
_encountered_error = true;
|
|
std::stringstream str;
|
|
str << "Error_code:" << error_code << " Text:" << err_msg;
|
|
LOG(OrderMan, Info,
|
|
"WebsocketSSLClientInternal::_handle_error error_code:{} err_msg:{}",
|
|
error_code.message(), err_msg);
|
|
_listener->on_error({err_type, str.str()});
|
|
close_connection();
|
|
}
|
|
|
|
// Start the asynchronous operation
|
|
void WebsocketSSLClientInternal::_resolve() {
|
|
_resolver.async_resolve(
|
|
_conf.ip, _conf.port,
|
|
boost::beast::bind_front_handler(
|
|
&WSCI::_on_resolve, shared_from_this()));
|
|
}
|
|
|
|
void WebsocketSSLClientInternal::_on_resolve(
|
|
boost::beast::error_code ec,
|
|
const boost::asio::ip::tcp::resolver::results_type &results) {
|
|
if (ec) {
|
|
_fail(ec, "resolve");
|
|
_handle_error(
|
|
ec, "Address resoloution failed", WebsocketError::ErrorType::SETUP);
|
|
return;
|
|
}
|
|
LOG(OrderMan, Info,
|
|
"WebsocketSSLClientInternal::_on_resolve successfull results:{}",
|
|
results.size());
|
|
// Set the timeout for the operation
|
|
boost::beast::get_lowest_layer(_ws).expires_after(std::chrono::seconds(30));
|
|
// Make the connection on the IP address we get from a lookup
|
|
boost::beast::get_lowest_layer(_ws).async_connect(
|
|
results, boost::beast::bind_front_handler(
|
|
&WSCI::_on_connect, shared_from_this()));
|
|
}
|
|
|
|
void WebsocketSSLClientInternal::_on_connect(
|
|
boost::beast::error_code ec,
|
|
const boost::asio::ip::tcp::resolver::results_type::endpoint_type &ep) {
|
|
if (ec) {
|
|
_fail(ec, "connect");
|
|
_handle_error(ec, "Connection failed", WebsocketError::ErrorType::SETUP);
|
|
return;
|
|
}
|
|
LOG(OrderMan, Info,
|
|
"WebsocketSSLClientInternal::_on_connect successfull ep: {}:{}",
|
|
ep.address().to_string(), ep.port());
|
|
ip_port = _conf.ip + ':' + std::to_string(ep.port());
|
|
// Set a timeout on the operation
|
|
boost::beast::get_lowest_layer(_ws).expires_after(std::chrono::seconds(30));
|
|
|
|
// Set SNI Hostname (many hosts need this to handshake successfully)
|
|
if (!SSL_set_tlsext_host_name(
|
|
_ws.next_layer().native_handle(), ip_port.c_str())) {
|
|
ec = boost::beast::error_code(
|
|
static_cast<int>(::ERR_get_error()),
|
|
boost::asio::error::get_ssl_category());
|
|
_fail(ec, "connect");
|
|
_handle_error(ec, "Connection failed", WebsocketError::ErrorType::SETUP);
|
|
return;
|
|
}
|
|
|
|
// Perform the SSL handshake
|
|
_ws.next_layer().async_handshake(
|
|
boost::asio::ssl::stream_base::client,
|
|
boost::beast::bind_front_handler(
|
|
&WSCI::_on_ssl_handshake, shared_from_this()));
|
|
}
|
|
|
|
void WebsocketSSLClientInternal::_on_ssl_handshake(
|
|
boost::beast::error_code ec) {
|
|
if (ec) {
|
|
_fail(ec, "ssl_handshake");
|
|
_handle_error(
|
|
ec, "SSL Handshake failed", WebsocketError::ErrorType::SETUP);
|
|
return;
|
|
}
|
|
LOG(OrderMan, Info,
|
|
"WebsocketSSLClientInternal::_on_ssl_handshake successful");
|
|
// Turn off the timeout on the tcp_stream, because
|
|
// the websocket stream has its own timeout system.
|
|
boost::beast::get_lowest_layer(_ws).expires_never();
|
|
|
|
// Set suggested timeout settings for the websocket
|
|
_ws.set_option(boost::beast::websocket::stream_base::timeout::suggested(
|
|
boost::beast::role_type::client));
|
|
|
|
// Set a decorator to change the User-Agent of the handshake
|
|
_ws.set_option(boost::beast::websocket::stream_base::decorator(
|
|
[](boost::beast::websocket::request_type &req) {
|
|
req.set(
|
|
boost::beast::http::field::user_agent,
|
|
std::string(BOOST_BEAST_VERSION_STRING) +
|
|
" websocket-client-async-ssl");
|
|
}));
|
|
|
|
// Perform the websocket handshake
|
|
_ws.async_handshake(
|
|
ip_port, _conf.host_name,
|
|
boost::beast::bind_front_handler(
|
|
&WSCI::_on_handshake, shared_from_this()));
|
|
}
|
|
|
|
void WebsocketSSLClientInternal::_on_handshake(boost::beast::error_code ec) {
|
|
if (ec) {
|
|
_fail(ec, "handshake");
|
|
_handle_error(ec, "Handshake failed", WebsocketError::ErrorType::SETUP);
|
|
return;
|
|
}
|
|
LOG(OrderMan, Info, "WebsocketSSLClientInternal::_on_handshake successfull");
|
|
// this is when the connection is really established
|
|
_listener->on_connection_established();
|
|
_read_data();
|
|
_write_data();
|
|
_reinit_timer();
|
|
}
|
|
|
|
void WebsocketSSLClientInternal::_on_timer(boost::beast::error_code ec) {
|
|
if (ec) {
|
|
_fail(ec, "timer");
|
|
_handle_error(ec, "Timer failed", WebsocketError::ErrorType::MISC);
|
|
return;
|
|
}
|
|
_listener->on_timer();
|
|
if (_is_active()) {
|
|
_reinit_timer();
|
|
}
|
|
}
|
|
|
|
void WebsocketSSLClientInternal::_reinit_timer() {
|
|
_timer.expires_at(
|
|
_timer.expires_at() + boost::posix_time::milliseconds(_conf.timer_ms));
|
|
_timer.async_wait(
|
|
boost::beast::bind_front_handler(&WSCI::_on_timer, shared_from_this()));
|
|
}
|
|
|
|
void WebsocketSSLClientInternal::_write_data() {
|
|
if (!_pending_write) {
|
|
if (!_send_queue.empty()) {
|
|
WebsocketMessage msg = _send_queue.front();
|
|
_pending_write_msg_id = msg.message_id;
|
|
_send_queue.pop();
|
|
_pending_write = true;
|
|
_ws.async_write(
|
|
boost::asio::buffer(msg.data, msg.data_size),
|
|
boost::beast::bind_front_handler(
|
|
&WSCI::_on_write, shared_from_this()));
|
|
}
|
|
}
|
|
}
|
|
|
|
void WebsocketSSLClientInternal::_read_data() {
|
|
if (!_pending_read) {
|
|
_pending_read = true;
|
|
_ws.async_read(
|
|
_read_buffer, boost::beast::bind_front_handler(
|
|
&WSCI::_on_read, shared_from_this()));
|
|
}
|
|
}
|
|
|
|
void WebsocketSSLClientInternal::_on_write(
|
|
boost::beast::error_code ec, std::size_t bytes_transferred) {
|
|
boost::ignore_unused(bytes_transferred);
|
|
if (ec) {
|
|
_fail(ec, "write");
|
|
_handle_error(
|
|
ec, "Write failed", WebsocketError::ErrorType::WRITE_FAILED);
|
|
return;
|
|
}
|
|
_pending_write = false;
|
|
// Read a message into our buffer
|
|
_listener->on_write_complete(_pending_write_msg_id);
|
|
_read_data();
|
|
_write_data();
|
|
}
|
|
|
|
void WebsocketSSLClientInternal::_on_read(
|
|
boost::beast::error_code ec, std::size_t bytes_transferred) {
|
|
boost::ignore_unused(bytes_transferred);
|
|
if (ec) {
|
|
_fail(ec, "read");
|
|
_handle_error(ec, "Read failed", WebsocketError::ErrorType::READ_FAILED);
|
|
return;
|
|
}
|
|
_pending_read = false;
|
|
WebsocketMessage msg = {
|
|
_read_msg_id++, static_cast<char const *>(_read_buffer.cdata().data()),
|
|
_read_buffer.data().size()};
|
|
_listener->on_data(msg);
|
|
_read_buffer.clear();
|
|
_read_data();
|
|
_write_data();
|
|
}
|
|
|
|
void WebsocketSSLClientInternal::_on_close(boost::beast::error_code ec) {
|
|
if (ec) {
|
|
_fail(ec, "close");
|
|
_listener->on_connection_closed(false);
|
|
return;
|
|
}
|
|
_listener->on_connection_closed(true);
|
|
// If we get here then the connection is closed gracefully
|
|
// The make_printable() function helps print a ConstBufferSequence
|
|
std::cout << "on_close"
|
|
<< " last data:"
|
|
<< boost::beast::make_printable(_read_buffer.data()) << std::endl;
|
|
}
|
|
|
|
bool WebsocketSSLClientInternal::_is_active() const {
|
|
return !_encountered_error && !_close_attempted;
|
|
}
|
|
|
|
} // namespace bts::io::websocket
|