Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b482420d3a |
@@ -14,9 +14,7 @@ using UpgradeTowerFields = std::tuple<
|
||||
sp::BitField<std::uint16_t,
|
||||
sp::Field<std::uint16_t, 12>, //<- m_Tower
|
||||
sp::Field<std::uint8_t, 4> //<- m_Upgrade
|
||||
>,
|
||||
sp::VarInt, //<- just for testing
|
||||
std::map<std::string, std::vector<int>>
|
||||
>
|
||||
>;
|
||||
|
||||
DeclarePacket(UpgradeTower){
|
||||
|
||||
@@ -35,7 +35,6 @@ class DataBuffer {
|
||||
typedef Data::difference_type difference_type;
|
||||
|
||||
DataBuffer();
|
||||
DataBuffer(std::size_t a_InitialSize);
|
||||
DataBuffer(const DataBuffer& other);
|
||||
DataBuffer(const DataBuffer& other, difference_type offset);
|
||||
DataBuffer(DataBuffer&& other);
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
/**
|
||||
* \file NonCopyable.h
|
||||
* \brief File containing the sp::NonCopyable class
|
||||
*/
|
||||
|
||||
namespace sp {
|
||||
|
||||
/**
|
||||
* \class NonCopyable
|
||||
* \brief Class used to make a class non copyable
|
||||
* \note Inherit from this class privately to make a class non copyable
|
||||
*/
|
||||
class NonCopyable {
|
||||
public:
|
||||
NonCopyable(const NonCopyable&) = delete;
|
||||
NonCopyable& operator=(const NonCopyable&) = delete;
|
||||
|
||||
protected:
|
||||
NonCopyable() {}
|
||||
~NonCopyable() {}
|
||||
};
|
||||
|
||||
} // namespace sp
|
||||
@@ -1,60 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cxxabi.h>
|
||||
#include <string>
|
||||
|
||||
namespace sp {
|
||||
|
||||
template <typename T>
|
||||
std::string GetBasicClassName(const T& a_Value) {
|
||||
int status;
|
||||
char* demangled = abi::__cxa_demangle(typeid(a_Value).name(), 0, 0, &status);
|
||||
if (status != 0)
|
||||
return "";
|
||||
return std::string(demangled);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
std::string GetBasicClassName() {
|
||||
int status;
|
||||
char* demangled = abi::__cxa_demangle(typeid(T).name(), 0, 0, &status);
|
||||
if (status != 0)
|
||||
return "";
|
||||
return std::string(demangled);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
struct Reflector {
|
||||
static std::string GetClassName() {
|
||||
return GetBasicClassName<T>();
|
||||
}
|
||||
};
|
||||
|
||||
template <>
|
||||
struct Reflector<std::string> {
|
||||
static std::string GetClassName() {
|
||||
return "std::string";
|
||||
}
|
||||
};
|
||||
|
||||
template <typename K, typename V>
|
||||
struct Reflector<std::map<K, V>> {
|
||||
static std::string GetClassName();
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct Reflector<std::vector<T>> {
|
||||
static std::string GetClassName();
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
std::string Reflector<std::vector<T>>::GetClassName() {
|
||||
return "std::vector<" + Reflector<T>::GetClassName() + ">";
|
||||
}
|
||||
|
||||
template <typename K, typename V>
|
||||
std::string Reflector<std::map<K, V>>::GetClassName() {
|
||||
return "std::map<" + Reflector<K>::GetClassName() + ", " + Reflector<V>::GetClassName() + ">";
|
||||
}
|
||||
|
||||
} // namespace sp
|
||||
@@ -1,8 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
|
||||
namespace sp {
|
||||
|
||||
@@ -52,48 +50,4 @@ void TupleForEach(TFunc&& func, TTuple&& tuple) {
|
||||
details::TupleForEachHelper<TupleSize>::Exec(std::forward<TTuple>(tuple), std::forward<TFunc>(func));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
namespace details {
|
||||
|
||||
template <typename T, typename U = void>
|
||||
struct is_mappish_impl : std::false_type {};
|
||||
|
||||
template <typename T>
|
||||
struct is_mappish_impl<T, std::void_t<typename T::key_type, typename T::mapped_type,
|
||||
decltype(std::declval<T&>()[std::declval<const typename T::key_type&>()])>> : std::true_type {};
|
||||
|
||||
template <typename T, typename U = void>
|
||||
struct is_vectish_impl : std::false_type {};
|
||||
|
||||
template <typename T>
|
||||
struct is_vectish_impl<T,
|
||||
std::void_t<typename T::value_type, decltype(std::declval<T&>()[std::declval<const typename T::value_type&>()])>>
|
||||
: std::true_type {};
|
||||
|
||||
template <typename T, typename U = void>
|
||||
struct is_pairish_impl : std::false_type {};
|
||||
|
||||
template <typename T>
|
||||
struct is_pairish_impl<T,
|
||||
std::void_t<typename T::first_type, decltype(std::declval<T&>()[std::declval<const typename T::first_type&>()])>>
|
||||
: std::true_type {};
|
||||
|
||||
template <typename T>
|
||||
using is_general_t = std::integral_constant<bool,
|
||||
(std::is_same_v<T, std::string> || (!std::is_same_v<T, char> && !std::is_same_v<T, unsigned char> && !std::is_arithmetic_v<T> &&
|
||||
!is_pairish_impl<T>::value && !is_mappish_impl<T>::value && !is_vectish_impl<T>::value))>;
|
||||
|
||||
template <typename T>
|
||||
using is_primitive =
|
||||
std::integral_constant<bool, std::is_same_v<T, char> || std::is_same_v<T, unsigned char> || std::is_arithmetic_v<T>>;
|
||||
|
||||
} // namespace details
|
||||
|
||||
} // namespace sp
|
||||
|
||||
@@ -7,8 +7,6 @@
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <ostream>
|
||||
#include <sp/protocol/Field.h>
|
||||
|
||||
namespace sp {
|
||||
|
||||
@@ -57,8 +55,6 @@ class VarInt {
|
||||
* \param var The variable integer to deserialize
|
||||
*/
|
||||
friend DataBuffer& operator>>(DataBuffer& in, VarInt& var);
|
||||
|
||||
friend std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<VarInt>& a_VarInt);
|
||||
};
|
||||
|
||||
} // namespace sp
|
||||
|
||||
@@ -11,8 +11,7 @@ using PacketMessage = Message<
|
||||
option::ReadOperations, // add read() operation
|
||||
option::WriteOperations, // add write() operation
|
||||
option::WriteId, // write id before data
|
||||
option::Handler<PacketHandler>, // add dispatch() operation
|
||||
option::DebugPrint // add ToString() operator
|
||||
option::Handler<PacketHandler> // add dispatch() operation
|
||||
>;
|
||||
|
||||
#define PacketConstructor(packetName) \
|
||||
@@ -24,8 +23,7 @@ using PacketMessage = Message<
|
||||
|
||||
#define DeclarePacket(packetName) \
|
||||
class packetName##Packet : public sp::MessageBase<sp::PacketMessage, sp::option::StaticNumIdImpl<packetName>, \
|
||||
sp::option::DispatchImpl<packetName##Packet>, sp::option::FieldsImpl<packetName##Fields>>, \
|
||||
sp::option::ToStringImpl<packetName##Packet>
|
||||
sp::option::DispatchImpl<packetName##Packet>, sp::option::FieldsImpl<packetName##Fields>>
|
||||
|
||||
|
||||
|
||||
|
||||
41
include/sp/extensions/Encrypt.h
Normal file
41
include/sp/extensions/Encrypt.h
Normal file
@@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
/**
|
||||
* \file Encrypt.h
|
||||
* \brief File containing encrypt utilities
|
||||
*/
|
||||
|
||||
#include <sp/common/DataBuffer.h>
|
||||
|
||||
namespace sp {
|
||||
namespace option {
|
||||
|
||||
struct TlsEncrypt {
|
||||
bool m_Enabled = true;
|
||||
};
|
||||
|
||||
} // namespace option
|
||||
} // namespace sp
|
||||
|
||||
#include <sp/io/IOInterface.h>
|
||||
|
||||
namespace sp {
|
||||
namespace ssl {
|
||||
|
||||
// encrypt
|
||||
|
||||
// decrypt
|
||||
|
||||
} // namespace ssl
|
||||
|
||||
namespace io {
|
||||
|
||||
template <>
|
||||
class MessageEncapsulator<option::TlsEncrypt> {
|
||||
public:
|
||||
static DataBuffer Encapsulate(const DataBuffer& a_Data, const option::TlsEncrypt& a_Option);
|
||||
static DataBuffer Decapsulate(DataBuffer& a_Data, const option::TlsEncrypt& a_Option);
|
||||
};
|
||||
|
||||
} // namespace io
|
||||
} // namespace sp
|
||||
@@ -3,7 +3,3 @@
|
||||
#if __has_include(<sp/extensions/Compress.h>)
|
||||
#include <sp/extensions/Compress.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<sp/extensions/Tcp.h>)
|
||||
#include <sp/extensions/Tcp.h>
|
||||
#endif
|
||||
@@ -1,4 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <sp/extensions/tcp/TcpListener.h>
|
||||
#include <sp/extensions/tcp/TcpSocket.h>
|
||||
@@ -1,67 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <sp/extensions/tcp/TcpSocket.h>
|
||||
|
||||
namespace sp {
|
||||
namespace io {
|
||||
|
||||
/**
|
||||
* \class TcpListener
|
||||
*/
|
||||
class TcpListener : private NonCopyable {
|
||||
public:
|
||||
using SocketHandle = TcpTag::SocketHandle;
|
||||
|
||||
/**
|
||||
* \brief Starts listening for guests to connect
|
||||
* \param port The port to listen to
|
||||
* \param maxConnexions The maximum amount of connexion that can happen at the same time. \n
|
||||
* Every other guests will be kicked if this amount is reached.
|
||||
* \return Whether this action was succesfull
|
||||
*/
|
||||
TcpListener(std::uint16_t a_Port, int a_MaxConnexions);
|
||||
|
||||
/**
|
||||
* \brief Default destructor
|
||||
*/
|
||||
~TcpListener();
|
||||
|
||||
/**
|
||||
* \brief Tries to accept an incoming request to connect
|
||||
* \return the new socket if a new connexion was accepted or nullptr
|
||||
*/
|
||||
std::unique_ptr<TcpSocket> Accept();
|
||||
|
||||
/**
|
||||
* \brief Closes the socket
|
||||
*/
|
||||
void Close();
|
||||
|
||||
/**
|
||||
* \brief Allows to set the socket in non blocking/blocking mode
|
||||
* \param a_Blocking If set to true, every call to Read will wait until the socket receives something
|
||||
* \return true if the operation was successful
|
||||
*/
|
||||
bool SetBlocking(bool a_Blocking);
|
||||
|
||||
/**
|
||||
* \brief Getter of the m_Port member
|
||||
* \return The port which the socket listen to
|
||||
*/
|
||||
std::uint16_t GetListeningPort() const;
|
||||
|
||||
/**
|
||||
* \brief Getter of the m_MaxConnections member
|
||||
* \return The maximum amount of connexions that can happen at the same time.
|
||||
*/
|
||||
int GetMaximumConnections() const;
|
||||
|
||||
private:
|
||||
SocketHandle m_Handle;
|
||||
std::uint16_t m_Port;
|
||||
int m_MaxConnections;
|
||||
};
|
||||
|
||||
|
||||
} // namespace io
|
||||
} // namespace sp
|
||||
@@ -1,88 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <sp/common/NonCopyable.h>
|
||||
#include <sp/io/IOInterface.h>
|
||||
|
||||
namespace sp {
|
||||
namespace io {
|
||||
|
||||
struct TcpTag {
|
||||
using SocketHandle = int;
|
||||
};
|
||||
|
||||
class SocketError : public std::exception {
|
||||
private:
|
||||
std::string m_Error;
|
||||
|
||||
public:
|
||||
SocketError(std::string&& a_Msg) : m_Error(std::move(a_Msg)) {}
|
||||
|
||||
virtual const char* what() const noexcept override {
|
||||
return m_Error.c_str();
|
||||
}
|
||||
};
|
||||
|
||||
template <>
|
||||
class IOInterface<TcpTag> : private NonCopyable {
|
||||
public:
|
||||
using SocketHandle = TcpTag::SocketHandle;
|
||||
|
||||
/**
|
||||
* \enum Status
|
||||
* \brief Describes the state of a socket
|
||||
*/
|
||||
enum class Status {
|
||||
/** The socket is connected */
|
||||
Connected,
|
||||
/** The socket is not connected */
|
||||
Disconnected,
|
||||
/** Something bad happened */
|
||||
Error,
|
||||
};
|
||||
|
||||
IOInterface();
|
||||
IOInterface(const std::string& a_Host, std::uint16_t a_Port);
|
||||
IOInterface(IOInterface&& a_Other);
|
||||
IOInterface& operator=(IOInterface&& a_Other);
|
||||
virtual ~IOInterface();
|
||||
|
||||
DataBuffer Read(std::size_t a_Amount);
|
||||
void Write(const sp::DataBuffer& a_Data);
|
||||
|
||||
/**
|
||||
* \brief Allows to set the socket in non blocking/blocking mode
|
||||
* \param a_Block If set to true, every call to Read will wait until the socket receives something
|
||||
* \return true if the operation was successful
|
||||
*/
|
||||
bool SetBlocking(bool a_Block);
|
||||
|
||||
/**
|
||||
* \brief Getter of the m_Status member
|
||||
* \return The TcpSocket::Status of this socket
|
||||
*/
|
||||
Status GetStatus() const;
|
||||
|
||||
/**
|
||||
* \brief Disconnects the socket from the remote
|
||||
* \note Does nothing if the socket is not connected. \n
|
||||
* This function is also called by the destructor.
|
||||
*/
|
||||
void Disconnect();
|
||||
|
||||
|
||||
private:
|
||||
SocketHandle m_Handle;
|
||||
Status m_Status;
|
||||
|
||||
void Connect(const std::string& a_Host, std::uint16_t a_Port);
|
||||
|
||||
friend class TcpListener;
|
||||
};
|
||||
|
||||
/**
|
||||
* \typedef TcpSocket
|
||||
*/
|
||||
using TcpSocket = IOInterface<TcpTag>;
|
||||
|
||||
} // namespace io
|
||||
} // namespace sp
|
||||
@@ -48,12 +48,11 @@ Stream<IOTag, MessageDispatcher, MessageFactory, TOptions...>::Stream(
|
||||
template <typename IOTag, typename MessageDispatcher, typename MessageFactory, typename... TOptions>
|
||||
void Stream<IOTag, MessageDispatcher, MessageFactory, TOptions...>::SendMessage(const MessageBase& a_Message) {
|
||||
DataBuffer data = a_Message.Write();
|
||||
TupleForEach([&data](const auto&... a_Options) {
|
||||
data = Encapsulate(data, a_Options...);
|
||||
DataBuffer encapsulated = std::apply([&data](const auto&... a_Options) {
|
||||
return Encapsulate(data, a_Options...);
|
||||
}, m_Options);
|
||||
DataBuffer finalData;
|
||||
finalData.Reserve(data.GetSize() + sizeof(VarInt::MAX_VALUE));
|
||||
finalData << VarInt{data.GetSize()} << data;
|
||||
finalData << VarInt{encapsulated.GetSize()} << encapsulated;
|
||||
m_Interface.Write(finalData);
|
||||
}
|
||||
|
||||
@@ -94,8 +93,8 @@ void Stream<IOTag, MessageDispatcher, MessageFactory, TOptions...>::RecieveMessa
|
||||
DataBuffer buffer;
|
||||
buffer = m_Interface.Read(lenghtValue);
|
||||
|
||||
TupleForEach([&buffer, lenghtValue](const auto&... a_Options) {
|
||||
buffer = Decapsulate(buffer, a_Options...);
|
||||
buffer = std::apply([&buffer, lenghtValue](const auto&... a_Options) {
|
||||
return Decapsulate(buffer, a_Options...);
|
||||
}, m_Options);
|
||||
|
||||
VarInt packetType;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <sp/common/DataBuffer.h>
|
||||
#include <sp/common/Templates.h>
|
||||
|
||||
namespace sp {
|
||||
@@ -69,45 +70,29 @@ class BitField {
|
||||
* \tparam ValueType the type of the value to store
|
||||
* \tparam IAlignment 0 means no alignment
|
||||
*/
|
||||
template <typename ValueType, std::size_t IAlignment>
|
||||
template <typename ValueType, int IAlignment>
|
||||
class Field {
|
||||
public:
|
||||
using StorageType = ValueType;
|
||||
static constexpr std::size_t AlignmentValue = IAlignment;
|
||||
|
||||
// Provide an access to the stored value
|
||||
StorageType& GetValue() {
|
||||
ValueType& GetValue() {
|
||||
return m_Value;
|
||||
}
|
||||
|
||||
const StorageType& GetValue() const {
|
||||
const ValueType& GetValue() const {
|
||||
return m_Value;
|
||||
}
|
||||
|
||||
Field& operator=(const StorageType& value) {
|
||||
Field& operator=(const ValueType& value) {
|
||||
m_Value = value;
|
||||
return *this;
|
||||
}
|
||||
|
||||
constexpr std::size_t GetAlignment() const {
|
||||
constexpr int GetAlignment() const {
|
||||
return IAlignment;
|
||||
}
|
||||
|
||||
private:
|
||||
StorageType m_Value;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class PrintableField {
|
||||
public:
|
||||
PrintableField(const T& a_Value) : m_Value(a_Value) {}
|
||||
|
||||
const T& GetValue() const {
|
||||
return m_Value;
|
||||
}
|
||||
|
||||
private:
|
||||
const T& m_Value;
|
||||
ValueType m_Value;
|
||||
};
|
||||
|
||||
namespace details {
|
||||
|
||||
@@ -14,5 +14,3 @@ template <typename TBase, typename... TOptions>
|
||||
class MessageBase : public details::MessageImplBuilder<TBase, TOptions...>::Type {};
|
||||
|
||||
} // namespace sp
|
||||
|
||||
#include <sp/protocol/message/MessagePrinterImpl.h>
|
||||
@@ -17,7 +17,7 @@ namespace sp {
|
||||
template <typename MessageIdType, typename MessageBase, typename MessageHandler>
|
||||
class MessageDispatcher {
|
||||
private:
|
||||
std::map<MessageIdType, std::vector<MessageHandler*>> m_Handlers;
|
||||
std::map<MessageIdType, std::vector<std::shared_ptr<MessageHandler>>> m_Handlers;
|
||||
|
||||
public:
|
||||
using MessageBaseType = MessageBase;
|
||||
@@ -38,20 +38,18 @@ class MessageDispatcher {
|
||||
* \param type The packet type
|
||||
* \param handler The packet handler
|
||||
*/
|
||||
void RegisterHandler(MessageIdType a_MessageType, MessageHandler* a_Handler);
|
||||
|
||||
void RegisterHandler(MessageIdType a_MessageType, const std::shared_ptr<MessageHandler>& a_Handler);
|
||||
/**
|
||||
* \brief Unregister a packet handler
|
||||
* \param type The packet type
|
||||
* \param handler The packet handler
|
||||
*/
|
||||
void UnregisterHandler(MessageIdType a_MessageType, MessageHandler* a_Handler);
|
||||
|
||||
void UnregisterHandler(MessageIdType a_MessageType, const std::shared_ptr<MessageHandler>& a_Handler);
|
||||
/**
|
||||
* \brief Unregister a packet handler
|
||||
* \param handler The packet handler
|
||||
*/
|
||||
void UnregisterHandler(MessageHandler* a_Handler);
|
||||
void UnregisterHandler(const std::shared_ptr<MessageHandler>& a_Handler);
|
||||
};
|
||||
|
||||
#include <sp/protocol/message/MessageDispatcherImpl.inl>
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <map>
|
||||
#include <ostream>
|
||||
#include <sp/protocol/Field.h>
|
||||
#include <sp/protocol/message/OstreamFieldIterator.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace sp {
|
||||
|
||||
template <typename T, std::enable_if_t<details::is_primitive<T>::value, bool> = true>
|
||||
std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<T>& a_Field) {
|
||||
return a_Stream << std::to_string(a_Field.GetValue());
|
||||
}
|
||||
|
||||
inline std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<long unsigned int>& a_Field) {
|
||||
return a_Stream << a_Field.GetValue();
|
||||
}
|
||||
|
||||
inline std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<std::string>& a_Field) {
|
||||
return a_Stream << "\"" << a_Field.GetValue() << "\"";
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
template <typename K, typename V>
|
||||
std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<std::pair<K, V>>& a_Data);
|
||||
|
||||
template <typename K, typename V>
|
||||
std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<std::map<K, V>>& a_Data);
|
||||
|
||||
template <typename T>
|
||||
std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<std::vector<T>>& a_Data);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
template <typename K, typename V>
|
||||
std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<std::pair<K, V>>& a_Data) {
|
||||
return a_Stream << PrintableField<K>(a_Data.GetValue().first) << " => " << PrintableField<V>(a_Data.GetValue().second);
|
||||
}
|
||||
|
||||
template <typename K, typename V>
|
||||
std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<std::map<K, V>>& a_Data) {
|
||||
a_Stream << "{";
|
||||
std::copy(a_Data.GetValue().begin(), a_Data.GetValue().end(), OstreamFieldIterator<std::pair<K, V>>(std::cout, ", "));
|
||||
return a_Stream << "}";
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<std::vector<T>>& a_Data) {
|
||||
a_Stream << "{";
|
||||
std::copy(a_Data.GetValue().begin(), a_Data.GetValue().end(), OstreamFieldIterator<T>(std::cout, ", "));
|
||||
return a_Stream << "}";
|
||||
}
|
||||
|
||||
} // namespace sp
|
||||
@@ -31,7 +31,7 @@ struct ArrayFiller<TBase, TMessage, TMessages...> {
|
||||
template <typename TBase, typename TMessage>
|
||||
struct ArrayFiller<TBase, TMessage> {
|
||||
static void ArrayAppend(details::ArrayType<TBase>& array) {
|
||||
array.emplace_back([]() -> std::unique_ptr<TBase> { return std::make_unique<TMessage>(); });
|
||||
array.push_back([]() -> std::unique_ptr<TBase> { return std::make_unique<TMessage>(); });
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,36 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
template <typename MessageIdType, typename MessageBase, typename MessageHandler>
|
||||
void MessageDispatcher<MessageIdType, MessageBase, MessageHandler>::RegisterHandler(MessageIdType a_MessageType, MessageHandler* a_Handler) {
|
||||
assert(a_Handler);
|
||||
void MessageDispatcher<MessageIdType, MessageBase, MessageHandler>::RegisterHandler(MessageIdType a_MessageType, const std::shared_ptr<MessageHandler>& a_Handler) {
|
||||
auto found = std::find(m_Handlers[a_MessageType].begin(), m_Handlers[a_MessageType].end(), a_Handler);
|
||||
if (found == m_Handlers[a_MessageType].end())
|
||||
m_Handlers[a_MessageType].push_back(a_Handler);
|
||||
}
|
||||
|
||||
template <typename MessageIdType, typename MessageBase, typename MessageHandler>
|
||||
void MessageDispatcher<MessageIdType, MessageBase, MessageHandler>::UnregisterHandler(MessageIdType a_MessageType, MessageHandler* a_Handler) {
|
||||
void MessageDispatcher<MessageIdType, MessageBase, MessageHandler>::UnregisterHandler(MessageIdType a_MessageType, const std::shared_ptr<MessageHandler>& a_Handler) {
|
||||
auto found = std::find(m_Handlers[a_MessageType].begin(), m_Handlers[a_MessageType].end(), a_Handler);
|
||||
if (found != m_Handlers[a_MessageType].end())
|
||||
m_Handlers[a_MessageType].erase(found);
|
||||
}
|
||||
|
||||
template <typename MessageIdType, typename MessageBase, typename MessageHandler>
|
||||
void MessageDispatcher<MessageIdType, MessageBase, MessageHandler>::UnregisterHandler(MessageHandler* a_Handler) {
|
||||
void MessageDispatcher<MessageIdType, MessageBase, MessageHandler>::UnregisterHandler(const std::shared_ptr<MessageHandler>& a_Handler) {
|
||||
for (auto& pair : m_Handlers) {
|
||||
if (pair.second.empty())
|
||||
continue;
|
||||
|
||||
MessageIdType type = pair.first;
|
||||
|
||||
pair.second.erase(std::remove(pair.second.begin(), pair.second.end(), a_Handler), pair.second.end());
|
||||
m_Handlers[type].erase(std::remove(m_Handlers[type].begin(), m_Handlers[type].end(), a_Handler), m_Handlers[type].end());
|
||||
}
|
||||
}
|
||||
|
||||
template <typename MessageIdType, typename MessageBase, typename MessageHandler>
|
||||
void MessageDispatcher<MessageIdType, MessageBase, MessageHandler>::Dispatch(const MessageBase& a_Message) {
|
||||
MessageIdType type = a_Message.GetId();
|
||||
for (auto& handler : m_Handlers[type]) {
|
||||
for (auto& handler : m_Handlers[type])
|
||||
a_Message.Dispatch(*handler);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,12 +37,8 @@ struct MessageImplBuilder {
|
||||
static const bool HasValidImpl = InterfaceOptions::HasValid && ImplOptions::HasFieldsImpl;
|
||||
using Base6 = typename MessageImplProcessValidFields<Base5, HasValidImpl>::Type;
|
||||
|
||||
// Provide ToStringImpl() if possible
|
||||
static const bool HasToStringImpl = InterfaceOptions::HasToString;
|
||||
using Base7 = typename MessageImplProcessToString<Base6, ImplOptions, HasToStringImpl>::Type;
|
||||
|
||||
// The last BaseN must be taken as final type.
|
||||
using Type = Base7;
|
||||
using Type = Base6;
|
||||
};
|
||||
|
||||
} // namespace details
|
||||
|
||||
@@ -4,7 +4,7 @@ namespace sp {
|
||||
namespace option {
|
||||
|
||||
// Provide static numeric ID, to facilitate implementation of GetIdImpl()
|
||||
template <std::uintmax_t TId>
|
||||
template <std::intmax_t TId>
|
||||
struct StaticNumIdImpl {};
|
||||
|
||||
// Facilitate implementation of DispatchImpl()
|
||||
@@ -16,11 +16,6 @@ struct DispatchImpl {};
|
||||
template <typename TFields>
|
||||
struct FieldsImpl {};
|
||||
|
||||
// Print fields of the message, facilitate implementation of
|
||||
// ToStringImpl()
|
||||
template <typename TActual>
|
||||
struct ToStringImpl {};
|
||||
|
||||
} // namespace option
|
||||
|
||||
|
||||
@@ -44,10 +39,10 @@ struct MessageImplParsedOptions<> {
|
||||
|
||||
|
||||
|
||||
template <std::uintmax_t TId, typename... TOptions>
|
||||
template <std::intmax_t TId, typename... TOptions>
|
||||
struct MessageImplParsedOptions<option::StaticNumIdImpl<TId>, TOptions...> : public MessageImplParsedOptions<TOptions...> {
|
||||
static const bool HasStaticNumIdImpl = true;
|
||||
static const std::uintmax_t MsgId = TId;
|
||||
static const std::intmax_t MsgId = TId;
|
||||
};
|
||||
|
||||
template <typename TActual, typename... TOptions>
|
||||
|
||||
@@ -4,20 +4,6 @@ namespace sp {
|
||||
namespace details {
|
||||
|
||||
|
||||
// ToString impl
|
||||
template <typename TBase, typename ParsedImplOptions, bool TImplement>
|
||||
struct MessageImplProcessToString;
|
||||
|
||||
template <typename TBase, typename ParsedImplOptions>
|
||||
struct MessageImplProcessToString<TBase, ParsedImplOptions, true> {
|
||||
using Type = MessageImplToStringBase<TBase, typename ParsedImplOptions::ActualMessage>;
|
||||
};
|
||||
|
||||
template <typename TBase, typename ParsedImplOptions>
|
||||
struct MessageImplProcessToString<TBase, ParsedImplOptions, false> {
|
||||
using Type = TBase;
|
||||
};
|
||||
|
||||
|
||||
// id impl
|
||||
template <typename TBase, typename ParsedImplOptions, bool TImplement>
|
||||
|
||||
@@ -33,11 +33,8 @@ struct MessageInterfaceBuilder {
|
||||
// add write id functionality if write id and write was provided
|
||||
using Base7 = typename MessageInterfaceProcessWriteId<Base6, ParsedOptions::HasWriteId && ParsedOptions::HasWriteOperations>::Type;
|
||||
|
||||
// add ToString() if HasToString was provided
|
||||
using Base8 = typename MessageInterfaceProcessToString<Base7, ParsedOptions::HasToString>::Type;
|
||||
|
||||
// The last Base8 must be taken as final type.
|
||||
using Type = Base8;
|
||||
// The last Base7 must be taken as final type.
|
||||
using Type = Base7;
|
||||
};
|
||||
|
||||
} // namespace details
|
||||
|
||||
@@ -101,19 +101,5 @@ struct MessageInterfaceProcessWriteId<TBase, false> {
|
||||
using Type = TBase;
|
||||
};
|
||||
|
||||
// Build to string
|
||||
template <typename TBase, bool THasToString>
|
||||
struct MessageInterfaceProcessToString;
|
||||
|
||||
template <typename TBase>
|
||||
struct MessageInterfaceProcessToString<TBase, true> {
|
||||
using Type = MessageInterfaceToStringBase<TBase>;
|
||||
};
|
||||
|
||||
template <typename TBase>
|
||||
struct MessageInterfaceProcessToString<TBase, false> {
|
||||
using Type = TBase;
|
||||
};
|
||||
|
||||
} // namespace details
|
||||
} // namespace sp
|
||||
@@ -129,17 +129,5 @@ class MessageInterfaceWriteIdBase : public TBase {
|
||||
}
|
||||
};
|
||||
|
||||
// Debug print functionality chunk
|
||||
template <typename TBase>
|
||||
class MessageInterfaceToStringBase : public TBase {
|
||||
public:
|
||||
friend std::ostream& operator<<(std::ostream& a_Stream, const MessageInterfaceToStringBase& a_Message) {
|
||||
return a_Message.OpOutImpl(a_Stream);
|
||||
}
|
||||
|
||||
protected:
|
||||
virtual std::ostream& OpOutImpl(std::ostream& a_Stream) const = 0;
|
||||
};
|
||||
|
||||
} // namespace details
|
||||
} // namespace sp
|
||||
|
||||
@@ -16,7 +16,6 @@ struct MessageInterfaceParsedOptions<> {
|
||||
static const bool HasWriteId = false;
|
||||
static const bool HasHandler = false;
|
||||
static const bool HasValid = false;
|
||||
static const bool HasToString = false;
|
||||
};
|
||||
|
||||
|
||||
@@ -60,10 +59,5 @@ struct MessageInterfaceParsedOptions<option::ValidCheckInterface, TOptions...> :
|
||||
static const bool HasValid = true;
|
||||
};
|
||||
|
||||
template <typename... TOptions>
|
||||
struct MessageInterfaceParsedOptions<option::DebugPrint, TOptions...> : public MessageInterfaceParsedOptions<TOptions...> {
|
||||
static const bool HasToString = true;
|
||||
};
|
||||
|
||||
} // namespace details
|
||||
} // namespace sp
|
||||
|
||||
@@ -24,9 +24,6 @@ struct LittleEndian {};
|
||||
// Include validity check in public interface
|
||||
struct ValidCheckInterface {};
|
||||
|
||||
// Add a ToString() method containing fields
|
||||
struct DebugPrint {};
|
||||
|
||||
// Define handler class
|
||||
template <typename T>
|
||||
struct Handler {
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <sp/common/Reflection.h>
|
||||
#include <sp/common/Templates.h>
|
||||
#include <sp/protocol/MessagePrinter.h>
|
||||
|
||||
namespace sp {
|
||||
namespace details {
|
||||
|
||||
template <typename... TOptions>
|
||||
struct IdPrinter {};
|
||||
|
||||
template <>
|
||||
struct IdPrinter<> {
|
||||
static std::string PrintMessageId() {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
template <typename TOption, typename... TOptions>
|
||||
struct IdPrinter<TOption, TOptions...> {
|
||||
static std::string PrintMessageId() {
|
||||
return IdPrinter<TOptions...>::PrintMessageId();
|
||||
}
|
||||
};
|
||||
|
||||
template <typename... TOptions, std::uintmax_t TId>
|
||||
struct IdPrinter<option::StaticNumIdImpl<TId>, TOptions...> {
|
||||
static std::string PrintMessageId() {
|
||||
return "(Id: " + std::to_string(TId) + ")";
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace details
|
||||
|
||||
template <typename... TFields>
|
||||
std::ostream& operator<<(std::ostream& a_Stream, const std::tuple<TFields...>& a_Fields);
|
||||
|
||||
template <typename TField, unsigned int IAlignment>
|
||||
struct FieldPrinter {
|
||||
static std::ostream& PrintField(std::ostream& a_Stream, const sp::Field<TField, IAlignment>& a_Field) {
|
||||
return a_Stream << sp::Reflector<TField>::GetClassName() << "=" << PrintableField<TField>(a_Field.GetValue());
|
||||
}
|
||||
};
|
||||
|
||||
template <unsigned int IAlignment, typename TContainer, typename... TFields>
|
||||
struct FieldPrinter<sp::BitField<TContainer, TFields...>, IAlignment> {
|
||||
static std::ostream& PrintField(
|
||||
std::ostream& a_Stream, const sp::Field<sp::BitField<TContainer, TFields...>, IAlignment>& a_Field) {
|
||||
a_Stream << "BitField<" << sp::Reflector<TContainer>::GetClassName() << ">[";
|
||||
a_Stream << a_Field.GetValue().GetFields() << "]";
|
||||
return a_Stream;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename... TFields>
|
||||
std::ostream& operator<<(std::ostream& a_Stream, const std::tuple<TFields...>& a_Fields) {
|
||||
bool first = true;
|
||||
TupleForEach(
|
||||
[&a_Stream, &first](const auto& a_Field) {
|
||||
if (!first)
|
||||
a_Stream << ", ";
|
||||
using TField = typename std::decay<decltype(a_Field)>::type;
|
||||
constexpr std::size_t alignment = TField::AlignmentValue;
|
||||
FieldPrinter<typename TField::StorageType, alignment>::PrintField(a_Stream, a_Field);
|
||||
first = false;
|
||||
},
|
||||
a_Fields);
|
||||
return a_Stream;
|
||||
}
|
||||
|
||||
template <typename TBase, typename... TOptions>
|
||||
std::ostream& operator<<(std::ostream& a_Stream, const sp::MessageBase<TBase, TOptions...>& a_Message) {
|
||||
a_Stream << sp::GetBasicClassName(a_Message) << sp::details::IdPrinter<TOptions...>::PrintMessageId() << "["
|
||||
<< a_Message.GetFields() << "]";
|
||||
return a_Stream;
|
||||
}
|
||||
|
||||
} // namespace sp
|
||||
@@ -1,24 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
namespace sp {
|
||||
|
||||
template <typename TBase, typename... TOptions>
|
||||
class MessageBase;
|
||||
|
||||
namespace details {
|
||||
|
||||
template <typename TBase, typename... TOptions>
|
||||
std::string PrintMessage(const MessageBase<TBase, TOptions...>& a_Message);
|
||||
|
||||
// ID information chunk
|
||||
template <typename TBase, typename TActual>
|
||||
class MessageImplToStringBase : public TBase {
|
||||
protected:
|
||||
virtual std::ostream& OpOutImpl(std::ostream& a_Stream) const override{
|
||||
return a_Stream << static_cast<const TActual&>(*this);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
// ID information chunk
|
||||
@@ -34,8 +18,6 @@ class MessageImplStaticNumIdBase : public TBase {
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
// Dispatch implementation chunk
|
||||
template <typename TBase, typename TActual>
|
||||
class MessageImplDispatchBase : public TBase {
|
||||
@@ -99,7 +81,7 @@ class MessageImplFieldsReadBase : public TBase {
|
||||
}
|
||||
|
||||
// reading field in bitfield
|
||||
template <typename TFieldType, typename TField, std::size_t IAlignment>
|
||||
template <typename TFieldType, typename TField, int IAlignment>
|
||||
void ReadField(Field<TField, IAlignment>& field, TFieldType data, std::size_t offset) {
|
||||
static constexpr std::size_t TotalBitCount = sizeof(TFieldType) * 8;
|
||||
// we suppose that the first element is at the highest bits
|
||||
@@ -136,7 +118,7 @@ class MessageImplFieldsWriteBase : public TBase {
|
||||
}
|
||||
|
||||
// writing field in bitfield
|
||||
template <typename TFieldType, typename TField, std::size_t IAlignment>
|
||||
template <typename TFieldType, typename TField, int IAlignment>
|
||||
void WriteField(const Field<TField, IAlignment>& field, TFieldType& data, std::size_t offset) const {
|
||||
static constexpr std::size_t TotalBitCount = sizeof(TFieldType) * 8;
|
||||
// we suppose that the first element is at the highest bits
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
// infix_iterator.h
|
||||
//
|
||||
// Lifted from Jerry Coffin's 's prefix_ostream_iterator
|
||||
#pragma once
|
||||
|
||||
#include <ostream>
|
||||
#include <sp/protocol/Field.h>
|
||||
|
||||
namespace sp {
|
||||
|
||||
template <class T, class charT = char, class traits = std::char_traits<charT>>
|
||||
class OstreamFieldIterator {
|
||||
private:
|
||||
std::basic_ostream<charT, traits>* m_Os;
|
||||
std::string m_Delimiter;
|
||||
bool m_FirstElem;
|
||||
|
||||
public:
|
||||
using iterator_category = std::output_iterator_tag;
|
||||
using value_type = void;
|
||||
using difference_type = void;
|
||||
using pointer = void;
|
||||
using reference = void;
|
||||
|
||||
using char_type = charT;
|
||||
using traits_type = traits;
|
||||
using ostream_type = std::basic_ostream<charT, traits>;
|
||||
|
||||
OstreamFieldIterator(ostream_type& a_Stream) : m_Os(&a_Stream), m_Delimiter(0), m_FirstElem(true) {}
|
||||
OstreamFieldIterator(ostream_type& a_Stream, std::string&& a_Delimiter) :
|
||||
m_Os(&a_Stream), m_Delimiter(std::move(a_Delimiter)), m_FirstElem(true) {}
|
||||
|
||||
auto& operator=(const T& item) {
|
||||
// Here's the only real change from ostream_iterator:
|
||||
// Normally, the '*m_Os << item;' would come before the 'if'.
|
||||
if (!m_FirstElem && !m_Delimiter.empty())
|
||||
*m_Os << m_Delimiter;
|
||||
*m_Os << sp::PrintableField<T>(item);
|
||||
m_FirstElem = false;
|
||||
return *this;
|
||||
}
|
||||
|
||||
auto& operator*() {
|
||||
return *this;
|
||||
}
|
||||
|
||||
auto& operator++() {
|
||||
return *this;
|
||||
}
|
||||
|
||||
auto& operator++(int) {
|
||||
return *this;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace sp
|
||||
@@ -8,8 +8,6 @@ namespace sp {
|
||||
|
||||
DataBuffer::DataBuffer() : m_ReadOffset(0) {}
|
||||
|
||||
DataBuffer::DataBuffer(std::size_t a_InitialSize) : m_Buffer(a_InitialSize), m_ReadOffset(0) {}
|
||||
|
||||
DataBuffer::DataBuffer(const DataBuffer& other) : m_Buffer(other.m_Buffer), m_ReadOffset(other.m_ReadOffset) {}
|
||||
|
||||
DataBuffer::DataBuffer(DataBuffer&& other) : m_Buffer(std::move(other.m_Buffer)), m_ReadOffset(std::move(other.m_ReadOffset)) {}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#include <sp/common/VarInt.h>
|
||||
|
||||
#include <sp/common/DataBuffer.h>
|
||||
#include <stdexcept>
|
||||
#include <sp/common/DataBuffer.h>
|
||||
|
||||
namespace sp {
|
||||
|
||||
@@ -49,8 +49,4 @@ DataBuffer& operator>>(DataBuffer& in, VarInt& var) {
|
||||
return in;
|
||||
}
|
||||
|
||||
std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<VarInt>& a_VarInt) {
|
||||
return a_Stream << a_VarInt.GetValue().GetValue();
|
||||
}
|
||||
|
||||
} // namespace sp
|
||||
|
||||
@@ -11,7 +11,7 @@ static DataBuffer Inflate(const std::uint8_t* source, std::size_t size, std::siz
|
||||
DataBuffer result;
|
||||
result.Resize(uncompressedSize);
|
||||
|
||||
uncompress(static_cast<Bytef*>(result.data()), reinterpret_cast<uLongf*>(&uncompressedSize), static_cast<const Bytef*>(source),
|
||||
uncompress(static_cast<Bytef*>(result.data()), static_cast<uLongf*>(&uncompressedSize), static_cast<const Bytef*>(source),
|
||||
static_cast<uLong>(size));
|
||||
|
||||
assert(result.GetSize() == uncompressedSize);
|
||||
|
||||
3
src/sp/extensions/Encrypt.cpp
Normal file
3
src/sp/extensions/Encrypt.cpp
Normal file
@@ -0,0 +1,3 @@
|
||||
#include <sp/extensions/Encrypt.h>
|
||||
|
||||
#include <openssl/ssl.h>
|
||||
@@ -1,52 +0,0 @@
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <mbedtls/ctr_drbg.h>
|
||||
#include <mbedtls/entropy.h>
|
||||
#include <mbedtls/x509_crt.h>
|
||||
#include <sp/common/DataBuffer.h>
|
||||
#include <sp/common/NonCopyable.h>
|
||||
|
||||
namespace sp {
|
||||
|
||||
class SslContext : private NonCopyable {
|
||||
public:
|
||||
SslContext(unsigned int a_KeySizeBits) {
|
||||
mbedtls_rsa_context rsaContext;
|
||||
mbedtls_rsa_init(&rsaContext);
|
||||
mbedtls_rsa_gen_key(&rsaContext, mbedtls_ctr_drbg_random, &m_CtrCrbg, a_KeySizeBits, 65537);
|
||||
mbedtls_rsa_free(&rsaContext);
|
||||
}
|
||||
|
||||
SslContext(const DataBuffer& a_Data) {
|
||||
mbedtls_x509_crt_parse(&m_CaCert, (const unsigned char*)a_Data.data(), a_Data.GetSize()) == 0;
|
||||
}
|
||||
|
||||
SslContext(const std::string& a_CertFilePath) {
|
||||
mbedtls_x509_crt_parse_file(&m_CaCert, a_CertFilePath.c_str());
|
||||
}
|
||||
|
||||
~SslContext() {
|
||||
mbedtls_ctr_drbg_free(&m_CtrCrbg);
|
||||
mbedtls_entropy_free(&m_Entropy);
|
||||
mbedtls_x509_crt_free(&m_CaCert);
|
||||
}
|
||||
|
||||
private:
|
||||
void InitContext() {
|
||||
int error = 0;
|
||||
|
||||
mbedtls_x509_crt_init(&m_CaCert);
|
||||
mbedtls_ctr_drbg_init(&m_CtrCrbg);
|
||||
|
||||
mbedtls_entropy_init(&m_Entropy);
|
||||
if ((error = mbedtls_ctr_drbg_seed(&m_CtrCrbg, mbedtls_entropy_func, &m_Entropy, nullptr, 0)) != 0) {
|
||||
throw std::runtime_error("Failed to initialise random number generator. Returned error: " + std::to_string(error));
|
||||
}
|
||||
}
|
||||
|
||||
mbedtls_entropy_context m_Entropy;
|
||||
mbedtls_ctr_drbg_context m_CtrCrbg;
|
||||
mbedtls_x509_crt m_CaCert;
|
||||
};
|
||||
|
||||
} // namespace sp
|
||||
@@ -1,114 +0,0 @@
|
||||
#include <sp/extensions/tcp/TcpListener.h>
|
||||
|
||||
|
||||
#ifdef _WIN32
|
||||
|
||||
// Windows
|
||||
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
|
||||
#define ioctl ioctlsocket
|
||||
#define WOULDBLOCK WSAEWOULDBLOCK
|
||||
#define MSG_DONTWAIT 0
|
||||
|
||||
#else
|
||||
|
||||
// Linux/Unix
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <netdb.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define closesocket close
|
||||
#define WOULDBLOCK EWOULDBLOCK
|
||||
#define SD_BOTH SHUT_RDWR
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
#ifndef INVALID_SOCKET
|
||||
#define INVALID_SOCKET -1
|
||||
#endif
|
||||
|
||||
|
||||
namespace sp {
|
||||
namespace io {
|
||||
|
||||
TcpListener::TcpListener(std::uint16_t a_Port, int a_MaxConnexions) {
|
||||
if ((m_Handle = static_cast<SocketHandle>(socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))) < 0) {
|
||||
throw SocketError("Failed to create server socket");
|
||||
}
|
||||
|
||||
struct sockaddr_in address;
|
||||
address.sin_family = AF_INET;
|
||||
address.sin_addr.s_addr = INADDR_ANY;
|
||||
address.sin_port = htons(a_Port);
|
||||
|
||||
if (bind(m_Handle, reinterpret_cast<sockaddr*>(&address), sizeof(address)) < 0)
|
||||
throw SocketError("Failed to create server socket");
|
||||
|
||||
if (listen(m_Handle, a_MaxConnexions) < 0)
|
||||
throw SocketError("Failed to create server socket");
|
||||
|
||||
socklen_t len = sizeof(address);
|
||||
if (getsockname(m_Handle, reinterpret_cast<sockaddr*>(&address), &len) < 0)
|
||||
throw SocketError("Failed to create server socket");
|
||||
|
||||
m_Port = ntohs(address.sin_port);
|
||||
m_MaxConnections = a_MaxConnexions;
|
||||
}
|
||||
|
||||
|
||||
TcpListener::~TcpListener() {
|
||||
Close();
|
||||
}
|
||||
|
||||
std::unique_ptr<TcpSocket> TcpListener::Accept() {
|
||||
sockaddr remoteAddress;
|
||||
int addrlen = sizeof(remoteAddress);
|
||||
|
||||
auto newSocket = std::make_unique<TcpSocket>();
|
||||
|
||||
newSocket->m_Handle = static_cast<SocketHandle>(
|
||||
accept(m_Handle, reinterpret_cast<sockaddr*>(&remoteAddress), reinterpret_cast<socklen_t*>(&addrlen)));
|
||||
|
||||
if (newSocket->m_Handle < 0)
|
||||
return nullptr;
|
||||
|
||||
newSocket->m_Status = TcpSocket::Status::Connected;
|
||||
return newSocket;
|
||||
}
|
||||
|
||||
void TcpListener::Close() {
|
||||
if (m_Handle > 0) {
|
||||
closesocket(m_Handle);
|
||||
shutdown(m_Handle, SD_BOTH);
|
||||
}
|
||||
}
|
||||
|
||||
bool TcpListener::SetBlocking(bool a_Blocking) {
|
||||
unsigned long mode = !a_Blocking;
|
||||
|
||||
if (ioctl(m_Handle, FIONBIO, &mode) < 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
std::uint16_t TcpListener::GetListeningPort() const {
|
||||
return m_Port;
|
||||
}
|
||||
|
||||
int TcpListener::GetMaximumConnections() const {
|
||||
return m_MaxConnections;
|
||||
}
|
||||
|
||||
} // namespace io
|
||||
} // namespace sp
|
||||
@@ -1,164 +0,0 @@
|
||||
#include <sp/extensions/tcp/TcpSocket.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
|
||||
// Windows
|
||||
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
|
||||
#define ioctl ioctlsocket
|
||||
#define WOULDBLOCK WSAEWOULDBLOCK
|
||||
#define MSG_DONTWAIT 0
|
||||
|
||||
#else
|
||||
|
||||
// Linux/Unix
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <netdb.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define closesocket close
|
||||
#define WOULDBLOCK EWOULDBLOCK
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
#ifndef INVALID_SOCKET
|
||||
#define INVALID_SOCKET -1
|
||||
#endif
|
||||
|
||||
|
||||
namespace sp {
|
||||
namespace io {
|
||||
|
||||
TcpSocket::IOInterface() : m_Handle(static_cast<SocketHandle>(INVALID_SOCKET)), m_Status(Status::Disconnected) {}
|
||||
|
||||
TcpSocket::IOInterface(const std::string& a_Host, std::uint16_t a_Port) : IOInterface() {
|
||||
Connect(a_Host, a_Port);
|
||||
}
|
||||
|
||||
TcpSocket::IOInterface(IOInterface&& a_Other) {
|
||||
std::swap(m_Handle, a_Other.m_Handle);
|
||||
std::swap(m_Status, a_Other.m_Status);
|
||||
}
|
||||
|
||||
TcpSocket::~IOInterface() {}
|
||||
|
||||
void TcpSocket::Connect(const std::string& a_Host, std::uint16_t a_Port) {
|
||||
struct addrinfo hints {};
|
||||
|
||||
struct addrinfo* result = nullptr;
|
||||
|
||||
hints.ai_family = AF_INET;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
hints.ai_protocol = IPPROTO_TCP;
|
||||
|
||||
m_Status = Status::Error;
|
||||
|
||||
if (getaddrinfo(a_Host.c_str(), std::to_string(static_cast<int>(a_Port)).c_str(), &hints, &result) != 0) {
|
||||
throw SocketError("Failed to get address info");
|
||||
}
|
||||
|
||||
m_Handle = static_cast<SocketHandle>(socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
|
||||
if (m_Handle < 0) {
|
||||
throw SocketError("Failed to create socket");
|
||||
}
|
||||
|
||||
struct addrinfo* ptr = nullptr;
|
||||
for (ptr = result; ptr != nullptr; ptr = ptr->ai_next) {
|
||||
struct sockaddr* sockaddr = ptr->ai_addr;
|
||||
if (connect(m_Handle, sockaddr, sizeof(sockaddr_in)) == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
freeaddrinfo(result);
|
||||
|
||||
if (!ptr) {
|
||||
throw SocketError("Could not find a suitable interface for connecting");
|
||||
}
|
||||
|
||||
m_Status = Status::Connected;
|
||||
}
|
||||
|
||||
DataBuffer TcpSocket::Read(std::size_t a_Amount) {
|
||||
DataBuffer buffer(a_Amount);
|
||||
|
||||
std::size_t totalRecieved = 0;
|
||||
|
||||
while (totalRecieved < a_Amount) {
|
||||
int recvAmount =
|
||||
recv(m_Handle, reinterpret_cast<char*>(buffer.data() + totalRecieved), static_cast<int>(a_Amount - totalRecieved), 0);
|
||||
if (recvAmount <= 0) {
|
||||
#if defined(_WIN32) || defined(WIN32)
|
||||
int err = WSAGetLastError();
|
||||
#else
|
||||
int err = errno;
|
||||
#endif
|
||||
if (err == WOULDBLOCK) {
|
||||
// we are in non blocking mode and nothing is available
|
||||
return {};
|
||||
}
|
||||
|
||||
Disconnect();
|
||||
m_Status = Status::Error;
|
||||
throw SocketError("Error while reading");
|
||||
}
|
||||
totalRecieved += recvAmount;
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
void TcpSocket::Write(const sp::DataBuffer& a_Data) {
|
||||
if (GetStatus() != Status::Connected)
|
||||
return;
|
||||
|
||||
std::size_t sent = 0;
|
||||
|
||||
while (sent < a_Data.GetSize()) {
|
||||
int cur = send(m_Handle, reinterpret_cast<const char*>(a_Data.data() + sent), static_cast<int>(a_Data.GetSize() - sent), 0);
|
||||
|
||||
if (cur <= 0) {
|
||||
Disconnect();
|
||||
m_Status = Status::Error;
|
||||
return;
|
||||
}
|
||||
sent += static_cast<std::size_t>(cur);
|
||||
}
|
||||
}
|
||||
|
||||
bool TcpSocket::SetBlocking(bool a_Block) {
|
||||
unsigned long mode = !a_Block;
|
||||
|
||||
if (ioctl(m_Handle, FIONBIO, &mode) < 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
TcpSocket::Status TcpSocket::GetStatus() const {
|
||||
return m_Status;
|
||||
}
|
||||
|
||||
void TcpSocket::Disconnect() {
|
||||
if (m_Handle > 0)
|
||||
closesocket(m_Handle);
|
||||
m_Status = Status::Disconnected;
|
||||
}
|
||||
|
||||
TcpSocket& TcpSocket::operator=(IOInterface&& a_Other) {
|
||||
std::swap(m_Handle, a_Other.m_Handle);
|
||||
std::swap(m_Status, a_Other.m_Status);
|
||||
return *this;
|
||||
}
|
||||
|
||||
} // namespace io
|
||||
} // namespace sp
|
||||
@@ -23,8 +23,8 @@ int main() {
|
||||
auto handler = std::make_shared<CustomPacketHandler>();
|
||||
|
||||
FileStream stream(sp::io::File{"test.txt", sp::io::FileTag::In | sp::io::FileTag::Out}, {});
|
||||
stream.GetDispatcher().RegisterHandler(PacketId::Disconnect, handler.get());
|
||||
stream.GetDispatcher().RegisterHandler(PacketId::KeepAlive, handler.get());
|
||||
stream.GetDispatcher().RegisterHandler(PacketId::Disconnect, handler);
|
||||
stream.GetDispatcher().RegisterHandler(PacketId::KeepAlive, handler);
|
||||
|
||||
stream.SendMessage(KeepAlivePacket{96});
|
||||
stream.SendMessage(KeepAlivePacket{69});
|
||||
|
||||
@@ -23,13 +23,13 @@ int main() {
|
||||
auto handler = std::make_shared<CustomPacketHandler>();
|
||||
|
||||
DataBufferStream stream;
|
||||
stream.GetDispatcher().RegisterHandler(PacketId::Disconnect, handler.get());
|
||||
stream.GetDispatcher().RegisterHandler(PacketId::Disconnect, handler);
|
||||
|
||||
// this should not be dispatched
|
||||
stream.SendMessage(KeepAlivePacket{96});
|
||||
stream.RecieveMessages();
|
||||
|
||||
stream.GetDispatcher().RegisterHandler(PacketId::KeepAlive, handler.get());
|
||||
stream.GetDispatcher().RegisterHandler(PacketId::KeepAlive, handler);
|
||||
|
||||
stream.SendMessage(KeepAlivePacket{69});
|
||||
stream.RecieveMessages();
|
||||
|
||||
@@ -8,8 +8,7 @@
|
||||
|
||||
class KeepAliveHandler : public sp::PacketHandler {
|
||||
void Handle(const KeepAlivePacket& packet) {
|
||||
std::cout << "KeepAlive handled !!\n";
|
||||
std::cout << packet << std::endl;
|
||||
std::cout << "KeepAlive handled !\n";
|
||||
}
|
||||
|
||||
void Handle(const DisconnectPacket& packet) {
|
||||
@@ -22,15 +21,12 @@ class KeepAliveHandler : public sp::PacketHandler {
|
||||
};
|
||||
|
||||
int main() {
|
||||
std::map<std::string, std::vector<int>> yes = {{"woa", {5, 8}}, {"insane", {6, 9}}};
|
||||
auto upgradeTower = std::make_unique<UpgradeTowerPacket>(std::make_tuple(666, 9), 789, yes);
|
||||
auto keepAlive = std::make_unique<KeepAlivePacket>(6969);
|
||||
auto upgradeTower = std::make_unique<UpgradeTowerPacket>(std::make_tuple(666, 9));
|
||||
|
||||
sp::PacketMessage* msg = upgradeTower.get();
|
||||
|
||||
auto handler = std::make_shared<KeepAliveHandler>();
|
||||
msg->Dispatch(*handler);
|
||||
keepAlive->Dispatch(*handler);
|
||||
|
||||
sp::DataBuffer buffer = msg->Write();
|
||||
|
||||
@@ -40,7 +36,7 @@ int main() {
|
||||
auto upgradeTower2 = std::make_unique<UpgradeTowerPacket>();
|
||||
upgradeTower2->Read(buffer);
|
||||
|
||||
std::cout << "Test : " << *msg << "\n";
|
||||
std::cout << "Test : " << (unsigned)upgradeTower2->GetTowerId() << "\n";
|
||||
|
||||
sp::PacketFactory factory;
|
||||
auto packet = factory.CreateMessage(msgId);
|
||||
@@ -52,10 +48,10 @@ int main() {
|
||||
packet->Dispatch(*handler);
|
||||
|
||||
sp::PacketDispatcher dispatcher;
|
||||
dispatcher.RegisterHandler(PacketId::KeepAlive, handler.get());
|
||||
dispatcher.RegisterHandler(PacketId::KeepAlive, handler);
|
||||
dispatcher.Dispatch(*packet);
|
||||
dispatcher.UnregisterHandler(PacketId::KeepAlive, handler.get());
|
||||
dispatcher.UnregisterHandler(handler.get());
|
||||
dispatcher.UnregisterHandler(PacketId::KeepAlive, handler);
|
||||
dispatcher.UnregisterHandler(handler);
|
||||
|
||||
return 0;
|
||||
}
|
||||
49
xmake.lua
49
xmake.lua
@@ -9,24 +9,14 @@ local modules = {
|
||||
Includes = {"include/(sp/extensions/Compress.h)"},
|
||||
Sources = {"src/sp/extensions/Compress.cpp"}
|
||||
},
|
||||
TcpSocket = {
|
||||
Option = "tcp",
|
||||
Deps = {},
|
||||
Includes = {"include/(sp/extensions/Tcp.h)", "include/(sp/extensions/tcp/*.h)"},
|
||||
Sources = {"src/sp/extensions/Tcp*.cpp"}
|
||||
},
|
||||
MbedTls = {
|
||||
Option = "tls",
|
||||
Deps = {"mbedtls"},
|
||||
Includes = {"include/(sp/extensions/Ssl.h)", "include/(sp/extensions/Ssl/*.h)"},
|
||||
Sources = {"src/sp/extensions/Ssl*.cpp"}
|
||||
Encryption = {
|
||||
Option = "ssl",
|
||||
Deps = {"openssl"},
|
||||
Includes = {"include/(sp/extensions/Encrypt.h)"},
|
||||
Sources = {"src/sp/extensions/Encrypt.cpp"}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
-- Map modules to options
|
||||
for name, module in table.orderpairs(modules) do
|
||||
if module.Option then
|
||||
@@ -34,10 +24,6 @@ for name, module in table.orderpairs(modules) do
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
-- Add modules requirements
|
||||
for name, module in table.orderpairs(modules) do
|
||||
if module.Deps then
|
||||
@@ -45,10 +31,6 @@ for name, module in table.orderpairs(modules) do
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
-- Add modules targets
|
||||
for name, module in table.orderpairs(modules) do
|
||||
if module.Deps and has_config(module.Option) then
|
||||
@@ -68,17 +50,14 @@ for name, module in table.orderpairs(modules) do
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
target("SimpleProtocol")
|
||||
add_includedirs("include")
|
||||
add_files("src/sp/**.cpp")
|
||||
set_group("Library")
|
||||
set_kind("$(kind)")
|
||||
|
||||
add_headerfiles("include/(sp/**.h)", "include/(sp/**.inl)")
|
||||
local includeFolders = {"common", "default", "io", "protocol"}
|
||||
for _, folder in ipairs(includeFolders) do
|
||||
add_headerfiles("include/(sp/" .. folder .. "/**.h)")
|
||||
end
|
||||
|
||||
-- adding extensions
|
||||
for name, module in table.orderpairs(modules) do
|
||||
@@ -89,14 +68,8 @@ target("SimpleProtocol")
|
||||
|
||||
-- we don't want extensions
|
||||
remove_files("src/sp/extensions/**.cpp")
|
||||
remove_headerfiles("include/(sp/extension/**.h)")
|
||||
|
||||
-- we need this for endian functions
|
||||
if is_os("windows") then
|
||||
add_links("ws2_32")
|
||||
end
|
||||
|
||||
|
||||
set_group("Library")
|
||||
set_kind("$(kind)")
|
||||
|
||||
-- Tests
|
||||
for _, file in ipairs(os.files("test/**.cpp")) do
|
||||
|
||||
Reference in New Issue
Block a user