1
0
mirror of https://github.com/VCMP-SqMod/SqMod.git synced 2025-07-03 07:27:11 +02:00

Initial preparations for CURL and Discord integration.

This commit is contained in:
Sandu Liviu Catalin
2021-01-27 07:27:48 +02:00
parent 8257eb61d6
commit 95705e87c8
1751 changed files with 440547 additions and 854 deletions

View File

@ -0,0 +1,232 @@
/*
* Copyright (c) 2015, Peter Thorson. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the WebSocket++ Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef WEBSOCKETPP_TRANSPORT_ASIO_BASE_HPP
#define WEBSOCKETPP_TRANSPORT_ASIO_BASE_HPP
#include <websocketpp/common/asio.hpp>
#include <websocketpp/common/cpp11.hpp>
#include <websocketpp/common/functional.hpp>
#include <websocketpp/common/system_error.hpp>
#include <websocketpp/common/type_traits.hpp>
#include <string>
namespace websocketpp {
namespace transport {
/// Transport policy that uses asio
/**
* This policy uses a single asio io_service to provide transport
* services to a WebSocket++ endpoint.
*/
namespace asio {
// Class to manage the memory to be used for handler-based custom allocation.
// It contains a single block of memory which may be returned for allocation
// requests. If the memory is in use when an allocation request is made, the
// allocator delegates allocation to the global heap.
class handler_allocator {
public:
static const size_t size = 1024;
handler_allocator() : m_in_use(false) {}
#ifdef _WEBSOCKETPP_DEFAULT_DELETE_FUNCTIONS_
handler_allocator(handler_allocator const & cpy) = delete;
handler_allocator & operator =(handler_allocator const &) = delete;
#endif
void * allocate(std::size_t memsize) {
if (!m_in_use && memsize < size) {
m_in_use = true;
return static_cast<void*>(&m_storage);
} else {
return ::operator new(memsize);
}
}
void deallocate(void * pointer) {
if (pointer == &m_storage) {
m_in_use = false;
} else {
::operator delete(pointer);
}
}
private:
// Storage space used for handler-based custom memory allocation.
lib::aligned_storage<size>::type m_storage;
// Whether the handler-based custom allocation storage has been used.
bool m_in_use;
};
// Wrapper class template for handler objects to allow handler memory
// allocation to be customised. Calls to operator() are forwarded to the
// encapsulated handler.
template <typename Handler>
class custom_alloc_handler {
public:
custom_alloc_handler(handler_allocator& a, Handler h)
: allocator_(a),
handler_(h)
{}
template <typename Arg1>
void operator()(Arg1 arg1) {
handler_(arg1);
}
template <typename Arg1, typename Arg2>
void operator()(Arg1 arg1, Arg2 arg2) {
handler_(arg1, arg2);
}
friend void* asio_handler_allocate(std::size_t size,
custom_alloc_handler<Handler> * this_handler)
{
return this_handler->allocator_.allocate(size);
}
friend void asio_handler_deallocate(void* pointer, std::size_t /*size*/,
custom_alloc_handler<Handler> * this_handler)
{
this_handler->allocator_.deallocate(pointer);
}
private:
handler_allocator & allocator_;
Handler handler_;
};
// Helper function to wrap a handler object to add custom allocation.
template <typename Handler>
inline custom_alloc_handler<Handler> make_custom_alloc_handler(
handler_allocator & a, Handler h)
{
return custom_alloc_handler<Handler>(a, h);
}
// Forward declaration of class endpoint so that it can be friended/referenced
// before being included.
template <typename config>
class endpoint;
typedef lib::function<void (lib::asio::error_code const & ec,
size_t bytes_transferred)> async_read_handler;
typedef lib::function<void (lib::asio::error_code const & ec,
size_t bytes_transferred)> async_write_handler;
typedef lib::function<void (lib::error_code const & ec)> pre_init_handler;
// handle_timer: dynamic parameters, multiple copies
// handle_proxy_write
// handle_proxy_read
// handle_async_write
// handle_pre_init
/// Asio transport errors
namespace error {
enum value {
/// Catch-all error for transport policy errors that don't fit in other
/// categories
general = 1,
/// async_read_at_least call requested more bytes than buffer can store
invalid_num_bytes,
/// there was an error in the underlying transport library
pass_through,
/// The connection to the requested proxy server failed
proxy_failed,
/// Invalid Proxy URI
proxy_invalid,
/// Invalid host or service
invalid_host_service
};
/// Asio transport error category
class category : public lib::error_category {
public:
char const * name() const _WEBSOCKETPP_NOEXCEPT_TOKEN_ {
return "websocketpp.transport.asio";
}
std::string message(int value) const {
switch(value) {
case error::general:
return "Generic asio transport policy error";
case error::invalid_num_bytes:
return "async_read_at_least call requested more bytes than buffer can store";
case error::pass_through:
return "Underlying Transport Error";
case error::proxy_failed:
return "Proxy connection failed";
case error::proxy_invalid:
return "Invalid proxy URI";
case error::invalid_host_service:
return "Invalid host or service";
default:
return "Unknown";
}
}
};
/// Get a reference to a static copy of the asio transport error category
inline lib::error_category const & get_category() {
static category instance;
return instance;
}
/// Create an error code with the given value and the asio transport category
inline lib::error_code make_error_code(error::value e) {
return lib::error_code(static_cast<int>(e), get_category());
}
} // namespace error
} // namespace asio
} // namespace transport
} // namespace websocketpp
_WEBSOCKETPP_ERROR_CODE_ENUM_NS_START_
template<> struct is_error_code_enum<websocketpp::transport::asio::error::value>
{
static bool const value = true;
};
_WEBSOCKETPP_ERROR_CODE_ENUM_NS_END_
#endif // WEBSOCKETPP_TRANSPORT_ASIO_HPP

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,159 @@
/*
* Copyright (c) 2015, Peter Thorson. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the WebSocket++ Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef WEBSOCKETPP_TRANSPORT_ASIO_SOCKET_BASE_HPP
#define WEBSOCKETPP_TRANSPORT_ASIO_SOCKET_BASE_HPP
#include <websocketpp/common/asio.hpp>
#include <websocketpp/common/memory.hpp>
#include <websocketpp/common/functional.hpp>
#include <websocketpp/common/system_error.hpp>
#include <websocketpp/common/cpp11.hpp>
#include <websocketpp/common/connection_hdl.hpp>
#include <string>
// Interface that sockets/security policies must implement
/*
* Endpoint Interface
*
* bool is_secure() const;
* @return Whether or not the endpoint creates secure connections
*
* lib::error_code init(socket_con_ptr scon);
* Called by the transport after a new connection is created to initialize
* the socket component of the connection.
* @param scon Pointer to the socket component of the connection
* @return Error code (empty on success)
*/
// Connection
// TODO
// set_hostname(std::string hostname)
// pre_init(init_handler);
// post_init(init_handler);
namespace websocketpp {
namespace transport {
namespace asio {
namespace socket {
typedef lib::function<void(lib::asio::error_code const &)> shutdown_handler;
/**
* The transport::asio::socket::* classes are a set of security/socket related
* policies and support code for the ASIO transport types.
*/
/// Errors related to asio transport sockets
namespace error {
enum value {
/// Catch-all error for security policy errors that don't fit in other
/// categories
security = 1,
/// Catch-all error for socket component errors that don't fit in other
/// categories
socket,
/// A function was called in a state that it was illegal to do so.
invalid_state,
/// The application was prompted to provide a TLS context and it was
/// empty or otherwise invalid
invalid_tls_context,
/// TLS Handshake Timeout
tls_handshake_timeout,
/// pass_through from underlying library
pass_through,
/// Required tls_init handler not present
missing_tls_init_handler,
/// TLS Handshake Failed
tls_handshake_failed,
/// Failed to set TLS SNI hostname
tls_failed_sni_hostname
};
} // namespace error
/// Error category related to asio transport socket policies
class socket_category : public lib::error_category {
public:
char const * name() const _WEBSOCKETPP_NOEXCEPT_TOKEN_ {
return "websocketpp.transport.asio.socket";
}
std::string message(int value) const {
switch(value) {
case error::security:
return "Security policy error";
case error::socket:
return "Socket component error";
case error::invalid_state:
return "Invalid state";
case error::invalid_tls_context:
return "Invalid or empty TLS context supplied";
case error::tls_handshake_timeout:
return "TLS handshake timed out";
case error::pass_through:
return "Pass through from socket policy";
case error::missing_tls_init_handler:
return "Required tls_init handler not present.";
case error::tls_handshake_failed:
return "TLS handshake failed";
case error::tls_failed_sni_hostname:
return "Failed to set TLS SNI hostname";
default:
return "Unknown";
}
}
};
inline lib::error_category const & get_socket_category() {
static socket_category instance;
return instance;
}
inline lib::error_code make_error_code(error::value e) {
return lib::error_code(static_cast<int>(e), get_socket_category());
}
/// Type of asio transport socket policy initialization handlers
typedef lib::function<void(const lib::error_code&)> init_handler;
} // namespace socket
} // namespace asio
} // namespace transport
} // namespace websocketpp
#endif // WEBSOCKETPP_TRANSPORT_ASIO_SOCKET_BASE_HPP

View File

@ -0,0 +1,372 @@
/*
* Copyright (c) 2015, Peter Thorson. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the WebSocket++ Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef WEBSOCKETPP_TRANSPORT_SECURITY_NONE_HPP
#define WEBSOCKETPP_TRANSPORT_SECURITY_NONE_HPP
#include <websocketpp/uri.hpp>
#include <websocketpp/transport/base/connection.hpp>
#include <websocketpp/transport/asio/security/base.hpp>
#include <websocketpp/common/asio.hpp>
#include <websocketpp/common/memory.hpp>
#include <sstream>
#include <string>
namespace websocketpp {
namespace transport {
namespace asio {
/// A socket policy for the asio transport that implements a plain, unencrypted
/// socket
namespace basic_socket {
/// The signature of the socket init handler for this socket policy
typedef lib::function<void(connection_hdl,lib::asio::ip::tcp::socket&)>
socket_init_handler;
/// Basic Asio connection socket component
/**
* transport::asio::basic_socket::connection implements a connection socket
* component using Asio ip::tcp::socket.
*/
class connection : public lib::enable_shared_from_this<connection> {
public:
/// Type of this connection socket component
typedef connection type;
/// Type of a shared pointer to this connection socket component
typedef lib::shared_ptr<type> ptr;
/// Type of a pointer to the Asio io_service being used
typedef lib::asio::io_service* io_service_ptr;
/// Type of a pointer to the Asio io_service strand being used
typedef lib::shared_ptr<lib::asio::io_service::strand> strand_ptr;
/// Type of the ASIO socket being used
typedef lib::asio::ip::tcp::socket socket_type;
/// Type of a shared pointer to the socket being used.
typedef lib::shared_ptr<socket_type> socket_ptr;
explicit connection() : m_state(UNINITIALIZED) {
//std::cout << "transport::asio::basic_socket::connection constructor"
// << std::endl;
}
/// Get a shared pointer to this component
ptr get_shared() {
return shared_from_this();
}
/// Check whether or not this connection is secure
/**
* @return Whether or not this connection is secure
*/
bool is_secure() const {
return false;
}
/// Set the socket initialization handler
/**
* The socket initialization handler is called after the socket object is
* created but before it is used. This gives the application a chance to
* set any Asio socket options it needs.
*
* @param h The new socket_init_handler
*/
void set_socket_init_handler(socket_init_handler h) {
m_socket_init_handler = h;
}
/// Retrieve a pointer to the underlying socket
/**
* This is used internally. It can also be used to set socket options, etc
*/
lib::asio::ip::tcp::socket & get_socket() {
return *m_socket;
}
/// Retrieve a pointer to the underlying socket
/**
* This is used internally.
*/
lib::asio::ip::tcp::socket & get_next_layer() {
return *m_socket;
}
/// Retrieve a pointer to the underlying socket
/**
* This is used internally. It can also be used to set socket options, etc
*/
lib::asio::ip::tcp::socket & get_raw_socket() {
return *m_socket;
}
/// Get the remote endpoint address
/**
* The iostream transport has no information about the ultimate remote
* endpoint. It will return the string "iostream transport". To indicate
* this.
*
* TODO: allow user settable remote endpoint addresses if this seems useful
*
* @return A string identifying the address of the remote endpoint
*/
std::string get_remote_endpoint(lib::error_code & ec) const {
std::stringstream s;
lib::asio::error_code aec;
lib::asio::ip::tcp::endpoint ep = m_socket->remote_endpoint(aec);
if (aec) {
ec = error::make_error_code(error::pass_through);
s << "Error getting remote endpoint: " << aec
<< " (" << aec.message() << ")";
return s.str();
} else {
ec = lib::error_code();
s << ep;
return s.str();
}
}
protected:
/// Perform one time initializations
/**
* init_asio is called once immediately after construction to initialize
* Asio components to the io_service
*
* @param service A pointer to the endpoint's io_service
* @param strand A shared pointer to the connection's asio strand
* @param is_server Whether or not the endpoint is a server or not.
*/
lib::error_code init_asio (io_service_ptr service, strand_ptr, bool)
{
if (m_state != UNINITIALIZED) {
return socket::make_error_code(socket::error::invalid_state);
}
m_socket.reset(new lib::asio::ip::tcp::socket(*service));
if (m_socket_init_handler) {
m_socket_init_handler(m_hdl, *m_socket);
}
m_state = READY;
return lib::error_code();
}
/// Set uri hook
/**
* Called by the transport as a connection is being established to provide
* the uri being connected to to the security/socket layer.
*
* This socket policy doesn't use the uri so it is ignored.
*
* @since 0.6.0
*
* @param u The uri to set
*/
void set_uri(uri_ptr) {}
/// Pre-initialize security policy
/**
* Called by the transport after a new connection is created to initialize
* the socket component of the connection. This method is not allowed to
* write any bytes to the wire. This initialization happens before any
* proxies or other intermediate wrappers are negotiated.
*
* @param callback Handler to call back with completion information
*/
void pre_init(init_handler callback) {
if (m_state != READY) {
callback(socket::make_error_code(socket::error::invalid_state));
return;
}
m_state = READING;
callback(lib::error_code());
}
/// Post-initialize security policy
/**
* Called by the transport after all intermediate proxies have been
* negotiated. This gives the security policy the chance to talk with the
* real remote endpoint for a bit before the websocket handshake.
*
* @param callback Handler to call back with completion information
*/
void post_init(init_handler callback) {
callback(lib::error_code());
}
/// Sets the connection handle
/**
* The connection handle is passed to any handlers to identify the
* connection
*
* @param hdl The new handle
*/
void set_handle(connection_hdl hdl) {
m_hdl = hdl;
}
/// Cancel all async operations on this socket
/**
* Attempts to cancel all async operations on this socket and reports any
* failures.
*
* NOTE: Windows XP and earlier do not support socket cancellation.
*
* @return The error that occurred, if any.
*/
lib::asio::error_code cancel_socket() {
lib::asio::error_code ec;
m_socket->cancel(ec);
return ec;
}
void async_shutdown(socket::shutdown_handler h) {
lib::asio::error_code ec;
m_socket->shutdown(lib::asio::ip::tcp::socket::shutdown_both, ec);
h(ec);
}
lib::error_code get_ec() const {
return lib::error_code();
}
public:
/// Translate any security policy specific information about an error code
/**
* Translate_ec takes an Asio error code and attempts to convert its value
* to an appropriate websocketpp error code. In the case that the Asio and
* Websocketpp error types are the same (such as using boost::asio and
* boost::system_error or using standalone asio and std::system_error the
* code will be passed through natively.
*
* In the case of a mismatch (boost::asio with std::system_error) a
* translated code will be returned. The plain socket policy does not have
* any additional information so all such errors will be reported as the
* generic transport pass_through error.
*
* @since 0.3.0
*
* @param ec The error code to translate_ec
* @return The translated error code
*/
template <typename ErrorCodeType>
static
lib::error_code translate_ec(ErrorCodeType) {
// We don't know any more information about this error so pass through
return make_error_code(transport::error::pass_through);
}
static
/// Overload of translate_ec to catch cases where lib::error_code is the
/// same type as lib::asio::error_code
lib::error_code translate_ec(lib::error_code ec) {
// We don't know any more information about this error, but the error is
// the same type as the one we are translating to, so pass through
// untranslated.
return ec;
}
private:
enum state {
UNINITIALIZED = 0,
READY = 1,
READING = 2
};
socket_ptr m_socket;
state m_state;
connection_hdl m_hdl;
socket_init_handler m_socket_init_handler;
};
/// Basic ASIO endpoint socket component
/**
* transport::asio::basic_socket::endpoint implements an endpoint socket
* component that uses Boost ASIO's ip::tcp::socket.
*/
class endpoint {
public:
/// The type of this endpoint socket component
typedef endpoint type;
/// The type of the corresponding connection socket component
typedef connection socket_con_type;
/// The type of a shared pointer to the corresponding connection socket
/// component.
typedef socket_con_type::ptr socket_con_ptr;
explicit endpoint() {}
/// Checks whether the endpoint creates secure connections
/**
* @return Whether or not the endpoint creates secure connections
*/
bool is_secure() const {
return false;
}
/// Set socket init handler
/**
* The socket init handler is called after a connection's socket is created
* but before it is used. This gives the end application an opportunity to
* set asio socket specific parameters.
*
* @param h The new socket_init_handler
*/
void set_socket_init_handler(socket_init_handler h) {
m_socket_init_handler = h;
}
protected:
/// Initialize a connection
/**
* Called by the transport after a new connection is created to initialize
* the socket component of the connection.
*
* @param scon Pointer to the socket component of the connection
*
* @return Error code (empty on success)
*/
lib::error_code init(socket_con_ptr scon) {
scon->set_socket_init_handler(m_socket_init_handler);
return lib::error_code();
}
private:
socket_init_handler m_socket_init_handler;
};
} // namespace basic_socket
} // namespace asio
} // namespace transport
} // namespace websocketpp
#endif // WEBSOCKETPP_TRANSPORT_SECURITY_NONE_HPP

View File

@ -0,0 +1,474 @@
/*
* Copyright (c) 2015, Peter Thorson. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the WebSocket++ Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef WEBSOCKETPP_TRANSPORT_SECURITY_TLS_HPP
#define WEBSOCKETPP_TRANSPORT_SECURITY_TLS_HPP
#include <websocketpp/transport/asio/security/base.hpp>
#include <websocketpp/uri.hpp>
#include <websocketpp/common/asio_ssl.hpp>
#include <websocketpp/common/asio.hpp>
#include <websocketpp/common/connection_hdl.hpp>
#include <websocketpp/common/functional.hpp>
#include <websocketpp/common/memory.hpp>
#include <sstream>
#include <string>
namespace websocketpp {
namespace transport {
namespace asio {
/// A socket policy for the asio transport that implements a TLS encrypted
/// socket by wrapping with an asio::ssl::stream
namespace tls_socket {
/// The signature of the socket_init_handler for this socket policy
typedef lib::function<void(connection_hdl,lib::asio::ssl::stream<
lib::asio::ip::tcp::socket>&)> socket_init_handler;
/// The signature of the tls_init_handler for this socket policy
typedef lib::function<lib::shared_ptr<lib::asio::ssl::context>(connection_hdl)>
tls_init_handler;
/// TLS enabled Asio connection socket component
/**
* transport::asio::tls_socket::connection implements a secure connection socket
* component that uses Asio's ssl::stream to wrap an ip::tcp::socket.
*/
class connection : public lib::enable_shared_from_this<connection> {
public:
/// Type of this connection socket component
typedef connection type;
/// Type of a shared pointer to this connection socket component
typedef lib::shared_ptr<type> ptr;
/// Type of the ASIO socket being used
typedef lib::asio::ssl::stream<lib::asio::ip::tcp::socket> socket_type;
/// Type of a shared pointer to the ASIO socket being used
typedef lib::shared_ptr<socket_type> socket_ptr;
/// Type of a pointer to the ASIO io_service being used
typedef lib::asio::io_service * io_service_ptr;
/// Type of a pointer to the ASIO io_service strand being used
typedef lib::shared_ptr<lib::asio::io_service::strand> strand_ptr;
/// Type of a shared pointer to the ASIO TLS context being used
typedef lib::shared_ptr<lib::asio::ssl::context> context_ptr;
explicit connection() {
//std::cout << "transport::asio::tls_socket::connection constructor"
// << std::endl;
}
/// Get a shared pointer to this component
ptr get_shared() {
return shared_from_this();
}
/// Check whether or not this connection is secure
/**
* @return Whether or not this connection is secure
*/
bool is_secure() const {
return true;
}
/// Retrieve a pointer to the underlying socket
/**
* This is used internally. It can also be used to set socket options, etc
*/
socket_type::lowest_layer_type & get_raw_socket() {
return m_socket->lowest_layer();
}
/// Retrieve a pointer to the layer below the ssl stream
/**
* This is used internally.
*/
socket_type::next_layer_type & get_next_layer() {
return m_socket->next_layer();
}
/// Retrieve a pointer to the wrapped socket
/**
* This is used internally.
*/
socket_type & get_socket() {
return *m_socket;
}
/// Set the socket initialization handler
/**
* The socket initialization handler is called after the socket object is
* created but before it is used. This gives the application a chance to
* set any ASIO socket options it needs.
*
* @param h The new socket_init_handler
*/
void set_socket_init_handler(socket_init_handler h) {
m_socket_init_handler = h;
}
/// Set TLS init handler
/**
* The tls init handler is called when needed to request a TLS context for
* the library to use. A TLS init handler must be set and it must return a
* valid TLS context in order for this endpoint to be able to initialize
* TLS connections
*
* @param h The new tls_init_handler
*/
void set_tls_init_handler(tls_init_handler h) {
m_tls_init_handler = h;
}
/// Get the remote endpoint address
/**
* The iostream transport has no information about the ultimate remote
* endpoint. It will return the string "iostream transport". To indicate
* this.
*
* TODO: allow user settable remote endpoint addresses if this seems useful
*
* @return A string identifying the address of the remote endpoint
*/
std::string get_remote_endpoint(lib::error_code & ec) const {
std::stringstream s;
lib::asio::error_code aec;
lib::asio::ip::tcp::endpoint ep = m_socket->lowest_layer().remote_endpoint(aec);
if (aec) {
ec = error::make_error_code(error::pass_through);
s << "Error getting remote endpoint: " << aec
<< " (" << aec.message() << ")";
return s.str();
} else {
ec = lib::error_code();
s << ep;
return s.str();
}
}
protected:
/// Perform one time initializations
/**
* init_asio is called once immediately after construction to initialize
* Asio components to the io_service
*
* @param service A pointer to the endpoint's io_service
* @param strand A pointer to the connection's strand
* @param is_server Whether or not the endpoint is a server or not.
*/
lib::error_code init_asio (io_service_ptr service, strand_ptr strand,
bool is_server)
{
if (!m_tls_init_handler) {
return socket::make_error_code(socket::error::missing_tls_init_handler);
}
m_context = m_tls_init_handler(m_hdl);
if (!m_context) {
return socket::make_error_code(socket::error::invalid_tls_context);
}
m_socket.reset(new socket_type(*service, *m_context));
if (m_socket_init_handler) {
m_socket_init_handler(m_hdl, get_socket());
}
m_io_service = service;
m_strand = strand;
m_is_server = is_server;
return lib::error_code();
}
/// Set hostname hook
/**
* Called by the transport as a connection is being established to provide
* the hostname being connected to to the security/socket layer.
*
* This socket policy uses the hostname to set the appropriate TLS SNI
* header.
*
* @since 0.6.0
*
* @param u The uri to set
*/
void set_uri(uri_ptr u) {
m_uri = u;
}
/// Pre-initialize security policy
/**
* Called by the transport after a new connection is created to initialize
* the socket component of the connection. This method is not allowed to
* write any bytes to the wire. This initialization happens before any
* proxies or other intermediate wrappers are negotiated.
*
* @param callback Handler to call back with completion information
*/
void pre_init(init_handler callback) {
// TODO: is this the best way to check whether this function is
// available in the version of OpenSSL being used?
// TODO: consider case where host is an IP address
#if OPENSSL_VERSION_NUMBER >= 0x90812f
if (!m_is_server) {
// For clients on systems with a suitable OpenSSL version, set the
// TLS SNI hostname header so connecting to TLS servers using SNI
// will work.
long res = SSL_set_tlsext_host_name(
get_socket().native_handle(), m_uri->get_host().c_str());
if (!(1 == res)) {
callback(socket::make_error_code(socket::error::tls_failed_sni_hostname));
}
}
#endif
callback(lib::error_code());
}
/// Post-initialize security policy
/**
* Called by the transport after all intermediate proxies have been
* negotiated. This gives the security policy the chance to talk with the
* real remote endpoint for a bit before the websocket handshake.
*
* @param callback Handler to call back with completion information
*/
void post_init(init_handler callback) {
m_ec = socket::make_error_code(socket::error::tls_handshake_timeout);
// TLS handshake
if (m_strand) {
m_socket->async_handshake(
get_handshake_type(),
m_strand->wrap(lib::bind(
&type::handle_init, get_shared(),
callback,
lib::placeholders::_1
))
);
} else {
m_socket->async_handshake(
get_handshake_type(),
lib::bind(
&type::handle_init, get_shared(),
callback,
lib::placeholders::_1
)
);
}
}
/// Sets the connection handle
/**
* The connection handle is passed to any handlers to identify the
* connection
*
* @param hdl The new handle
*/
void set_handle(connection_hdl hdl) {
m_hdl = hdl;
}
void handle_init(init_handler callback,lib::asio::error_code const & ec) {
if (ec) {
m_ec = socket::make_error_code(socket::error::tls_handshake_failed);
} else {
m_ec = lib::error_code();
}
callback(m_ec);
}
lib::error_code get_ec() const {
return m_ec;
}
/// Cancel all async operations on this socket
/**
* Attempts to cancel all async operations on this socket and reports any
* failures.
*
* NOTE: Windows XP and earlier do not support socket cancellation.
*
* @return The error that occurred, if any.
*/
lib::asio::error_code cancel_socket() {
lib::asio::error_code ec;
get_raw_socket().cancel(ec);
return ec;
}
void async_shutdown(socket::shutdown_handler callback) {
if (m_strand) {
m_socket->async_shutdown(m_strand->wrap(callback));
} else {
m_socket->async_shutdown(callback);
}
}
public:
/// Translate any security policy specific information about an error code
/**
* Translate_ec takes an Asio error code and attempts to convert its value
* to an appropriate websocketpp error code. In the case that the Asio and
* Websocketpp error types are the same (such as using boost::asio and
* boost::system_error or using standalone asio and std::system_error the
* code will be passed through natively.
*
* In the case of a mismatch (boost::asio with std::system_error) a
* translated code will be returned. Any error that is determined to be
* related to TLS but does not have a more specific websocketpp error code
* is returned under the catch all error `tls_error`. Non-TLS related errors
* are returned as the transport generic error `pass_through`
*
* @since 0.3.0
*
* @param ec The error code to translate_ec
* @return The translated error code
*/
template <typename ErrorCodeType>
static
lib::error_code translate_ec(ErrorCodeType ec) {
if (ec.category() == lib::asio::error::get_ssl_category()) {
// We know it is a TLS related error, but otherwise don't know more.
// Pass through as TLS generic.
return make_error_code(transport::error::tls_error);
} else {
// We don't know any more information about this error so pass
// through
return make_error_code(transport::error::pass_through);
}
}
static
/// Overload of translate_ec to catch cases where lib::error_code is the
/// same type as lib::asio::error_code
lib::error_code translate_ec(lib::error_code ec) {
return ec;
}
private:
socket_type::handshake_type get_handshake_type() {
if (m_is_server) {
return lib::asio::ssl::stream_base::server;
} else {
return lib::asio::ssl::stream_base::client;
}
}
io_service_ptr m_io_service;
strand_ptr m_strand;
context_ptr m_context;
socket_ptr m_socket;
uri_ptr m_uri;
bool m_is_server;
lib::error_code m_ec;
connection_hdl m_hdl;
socket_init_handler m_socket_init_handler;
tls_init_handler m_tls_init_handler;
};
/// TLS enabled Asio endpoint socket component
/**
* transport::asio::tls_socket::endpoint implements a secure endpoint socket
* component that uses Asio's ssl::stream to wrap an ip::tcp::socket.
*/
class endpoint {
public:
/// The type of this endpoint socket component
typedef endpoint type;
/// The type of the corresponding connection socket component
typedef connection socket_con_type;
/// The type of a shared pointer to the corresponding connection socket
/// component.
typedef socket_con_type::ptr socket_con_ptr;
explicit endpoint() {}
/// Checks whether the endpoint creates secure connections
/**
* @return Whether or not the endpoint creates secure connections
*/
bool is_secure() const {
return true;
}
/// Set socket init handler
/**
* The socket init handler is called after a connection's socket is created
* but before it is used. This gives the end application an opportunity to
* set asio socket specific parameters.
*
* @param h The new socket_init_handler
*/
void set_socket_init_handler(socket_init_handler h) {
m_socket_init_handler = h;
}
/// Set TLS init handler
/**
* The tls init handler is called when needed to request a TLS context for
* the library to use. A TLS init handler must be set and it must return a
* valid TLS context in order for this endpoint to be able to initialize
* TLS connections
*
* @param h The new tls_init_handler
*/
void set_tls_init_handler(tls_init_handler h) {
m_tls_init_handler = h;
}
protected:
/// Initialize a connection
/**
* Called by the transport after a new connection is created to initialize
* the socket component of the connection.
*
* @param scon Pointer to the socket component of the connection
*
* @return Error code (empty on success)
*/
lib::error_code init(socket_con_ptr scon) {
scon->set_socket_init_handler(m_socket_init_handler);
scon->set_tls_init_handler(m_tls_init_handler);
return lib::error_code();
}
private:
socket_init_handler m_socket_init_handler;
tls_init_handler m_tls_init_handler;
};
} // namespace tls_socket
} // namespace asio
} // namespace transport
} // namespace websocketpp
#endif // WEBSOCKETPP_TRANSPORT_SECURITY_TLS_HPP