提交 6262224c authored 作者: Iñaki Baz Castillo's avatar Iñaki Baz Castillo

New C++ style.

上级 9fbdf500
#ifndef MS_CONTROL_PROTOCOL_MESSAGE_H #ifndef MS_CONTROL_PROTOCOL_MESSAGE_H
#define MS_CONTROL_PROTOCOL_MESSAGE_H #define MS_CONTROL_PROTOCOL_MESSAGE_H
#include "common.h" #include "common.h"
namespace ControlProtocol
namespace ControlProtocol { {
class Message
{
class Message { public:
public: enum class Kind
enum class Kind { {
Request = 1, Request = 1,
Response, Response,
Notification Notification
}; };
public: public:
Message(Kind); Message(Kind);
virtual ~Message(); virtual ~Message();
...@@ -26,33 +25,30 @@ public: ...@@ -26,33 +25,30 @@ public:
int32_t GetTransaction(); int32_t GetTransaction();
virtual void Dump() = 0; virtual void Dump() = 0;
protected: protected:
Kind kind; Kind kind;
int32_t transaction = 0; int32_t transaction = 0;
}; };
/* Inlime methods. */ /* Inlime methods. */
inline inline
Message::Kind Message::GetKind() { Message::Kind Message::GetKind()
{
return this->kind; return this->kind;
} }
inline
inline void Message::SetTransaction(int32_t transaction)
void Message::SetTransaction(int32_t transaction) { {
this->transaction = transaction; this->transaction = transaction;
} }
inline inline
int32_t Message::GetTransaction() { int32_t Message::GetTransaction()
{
return this->transaction; return this->transaction;
} }
} // namespace ControlProtocol } // namespace ControlProtocol
#endif #endif
#ifndef MS_CONTROL_PROTOCOL_PARSER_H #ifndef MS_CONTROL_PROTOCOL_PARSER_H
#define MS_CONTROL_PROTOCOL_PARSER_H #define MS_CONTROL_PROTOCOL_PARSER_H
#include "common.h" #include "common.h"
#include "ControlProtocol/Message.h" #include "ControlProtocol/Message.h"
namespace ControlProtocol
namespace ControlProtocol { {
class Parser
{
class Parser { public:
public:
Parser(); Parser();
virtual ~Parser(); virtual ~Parser();
...@@ -50,19 +48,16 @@ public: ...@@ -50,19 +48,16 @@ public:
*/ */
void Dump(); void Dump();
protected: protected:
size_t parsedLen; size_t parsedLen;
private: private:
// Allocated by this: // Allocated by this:
ControlProtocol::Message* msg = nullptr; ControlProtocol::Message* msg = nullptr;
// Others: // Others:
size_t cs = 0; // Needed for Ragel. size_t cs = 0; // Needed for Ragel.
size_t mark = 0; size_t mark = 0;
}; };
} // namespace ControlProtocol } // namespace ControlProtocol
#endif #endif
#ifndef MS_CONTROL_PROTOCOL_REQUEST_H #ifndef MS_CONTROL_PROTOCOL_REQUEST_H
#define MS_CONTROL_PROTOCOL_REQUEST_H #define MS_CONTROL_PROTOCOL_REQUEST_H
#include "ControlProtocol/Message.h" #include "ControlProtocol/Message.h"
namespace ControlProtocol
namespace ControlProtocol { {
class Request : public ControlProtocol::Message
{
class Request : public ControlProtocol::Message { public:
public: enum class Type
enum class Type { {
Hello = 1, Hello = 1,
Authenticate, Authenticate,
CreateConference CreateConference
}; };
public: public:
Request(Type); Request(Type);
virtual ~Request(); virtual ~Request();
virtual void Dump() = 0; virtual void Dump() = 0;
public: public:
// Allow fast access to type. // Allow fast access to type.
Type type; Type type;
}; };
} // namespace ControlProtocol } // namespace ControlProtocol
#endif #endif
#ifndef MS_CONTROL_PROTOCOL_TCP_CONNECTION_H #ifndef MS_CONTROL_PROTOCOL_TCP_CONNECTION_H
#define MS_CONTROL_PROTOCOL_TCP_CONNECTION_H #define MS_CONTROL_PROTOCOL_TCP_CONNECTION_H
#include "common.h" #include "common.h"
#include "handles/TCPConnection.h" #include "handles/TCPConnection.h"
#include "ControlProtocol/Parser.h" #include "ControlProtocol/Parser.h"
#include "ControlProtocol/Message.h" #include "ControlProtocol/Message.h"
namespace ControlProtocol
namespace ControlProtocol { {
class TCPConnection : public ::TCPConnection
{
class TCPConnection : public ::TCPConnection { public:
public: class Reader
class Reader { {
public: public:
virtual void onControlProtocolMessage(ControlProtocol::TCPConnection* connection, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len) = 0; virtual void onControlProtocolMessage(ControlProtocol::TCPConnection* connection, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len) = 0;
}; };
public: public:
TCPConnection(Reader* reader, size_t bufferSize); TCPConnection(Reader* reader, size_t bufferSize);
virtual ~TCPConnection(); virtual ~TCPConnection();
/* Pure virtual methods inherited from ::TCPConnection. */ /* Pure virtual methods inherited from ::TCPConnection. */
public: public:
virtual void userOnTCPConnectionRead(const MS_BYTE* data, size_t len) override; virtual void userOnTCPConnectionRead(const MS_BYTE* data, size_t len) override;
private: private:
// Allocated by this: // Allocated by this:
ControlProtocol::Parser* parser = nullptr; ControlProtocol::Parser* parser = nullptr;
// Passed by argument: // Passed by argument:
Reader* reader = nullptr; Reader* reader = nullptr;
// Others: // Others:
size_t msgStart = 0; // Where the latest message starts. size_t msgStart = 0; // Where the latest message starts.
}; };
} // namespace ControlProtocol } // namespace ControlProtocol
#endif #endif
#ifndef MS_CONTROL_PROTOCOL_TCP_SERVER_H #ifndef MS_CONTROL_PROTOCOL_TCP_SERVER_H
#define MS_CONTROL_PROTOCOL_TCP_SERVER_H #define MS_CONTROL_PROTOCOL_TCP_SERVER_H
#include "common.h" #include "common.h"
#include "handles/TCPServer.h" #include "handles/TCPServer.h"
#include "handles/TCPConnection.h" #include "handles/TCPConnection.h"
...@@ -9,36 +8,33 @@ ...@@ -9,36 +8,33 @@
#include "ControlProtocol/Message.h" #include "ControlProtocol/Message.h"
#include <string> #include <string>
namespace ControlProtocol
namespace ControlProtocol { {
class TCPServer : public ::TCPServer
{
class TCPServer : public ::TCPServer { public:
public: class Listener
class Listener { {
public: public:
virtual void onControlProtocolNewTCPConnection(ControlProtocol::TCPServer* tcpServer, ControlProtocol::TCPConnection* connection) = 0; virtual void onControlProtocolNewTCPConnection(ControlProtocol::TCPServer* tcpServer, ControlProtocol::TCPConnection* connection) = 0;
virtual void onControlProtocolTCPConnectionClosed(ControlProtocol::TCPServer* tcpServer, ControlProtocol::TCPConnection* connection, bool is_closed_by_peer) = 0; virtual void onControlProtocolTCPConnectionClosed(ControlProtocol::TCPServer* tcpServer, ControlProtocol::TCPConnection* connection, bool is_closed_by_peer) = 0;
}; };
public: public:
TCPServer(Listener* listener, ControlProtocol::TCPConnection::Reader* reader, const std::string &ip, MS_PORT port); TCPServer(Listener* listener, ControlProtocol::TCPConnection::Reader* reader, const std::string &ip, MS_PORT port);
/* Pure virtual methods inherited from ::TCPServer. */ /* Pure virtual methods inherited from ::TCPServer. */
public: public:
virtual void userOnTCPConnectionAlloc(::TCPConnection** connection) override; virtual void userOnTCPConnectionAlloc(::TCPConnection** connection) override;
virtual void userOnNewTCPConnection(::TCPConnection* connection) override; virtual void userOnNewTCPConnection(::TCPConnection* connection) override;
virtual void userOnTCPConnectionClosed(::TCPConnection* connection, bool is_closed_by_peer) override; virtual void userOnTCPConnectionClosed(::TCPConnection* connection, bool is_closed_by_peer) override;
virtual void userOnTCPServerClosed() override; virtual void userOnTCPServerClosed() override;
private: private:
// Passed by argument: // Passed by argument:
Listener* listener = nullptr; Listener* listener = nullptr;
ControlProtocol::TCPConnection::Reader* reader = nullptr; ControlProtocol::TCPConnection::Reader* reader = nullptr;
}; };
} // namespace ControlProtocol } // namespace ControlProtocol
#endif #endif
#ifndef MS_CONTROL_PROTOCOL_UNIX_STREAM_SOCKET_H #ifndef MS_CONTROL_PROTOCOL_UNIX_STREAM_SOCKET_H
#define MS_CONTROL_PROTOCOL_UNIX_STREAM_SOCKET_H #define MS_CONTROL_PROTOCOL_UNIX_STREAM_SOCKET_H
#include "common.h" #include "common.h"
#include "handles/UnixStreamSocket.h" #include "handles/UnixStreamSocket.h"
#include "ControlProtocol/Parser.h" #include "ControlProtocol/Parser.h"
#include "ControlProtocol/Message.h" #include "ControlProtocol/Message.h"
namespace ControlProtocol
namespace ControlProtocol { {
class UnixStreamSocket : public ::UnixStreamSocket
{
class UnixStreamSocket : public ::UnixStreamSocket { public:
public: class Listener
class Listener { {
public: public:
virtual void onControlProtocolMessage(ControlProtocol::UnixStreamSocket* unixSocket, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len) = 0; virtual void onControlProtocolMessage(ControlProtocol::UnixStreamSocket* unixSocket, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len) = 0;
virtual void onControlProtocolUnixStreamSocketClosed(ControlProtocol::UnixStreamSocket* unixSocket, bool is_closed_by_peer) = 0; virtual void onControlProtocolUnixStreamSocketClosed(ControlProtocol::UnixStreamSocket* unixSocket, bool is_closed_by_peer) = 0;
}; };
public: public:
UnixStreamSocket(Listener* listener, int fd); UnixStreamSocket(Listener* listener, int fd);
virtual ~UnixStreamSocket(); virtual ~UnixStreamSocket();
/* Pure virtual methods inherited from ::UnixStreamSocket. */ /* Pure virtual methods inherited from ::UnixStreamSocket. */
public: public:
virtual void userOnUnixStreamRead(const MS_BYTE* data, size_t len) override; virtual void userOnUnixStreamRead(const MS_BYTE* data, size_t len) override;
virtual void userOnUnixStreamSocketClosed(bool is_closed_by_peer) override; virtual void userOnUnixStreamSocketClosed(bool is_closed_by_peer) override;
private: private:
// Allocated by this: // Allocated by this:
ControlProtocol::Parser* parser = nullptr; ControlProtocol::Parser* parser = nullptr;
// Passed by argument: // Passed by argument:
Listener* listener = nullptr; Listener* listener = nullptr;
// Others: // Others:
size_t msgStart = 0; // Where the latest message starts. size_t msgStart = 0; // Where the latest message starts.
}; };
} // namespace ControlProtocol } // namespace ControlProtocol
#endif #endif
#ifndef MS_CONTROL_PROTOCOL_MESSAGES_H #ifndef MS_CONTROL_PROTOCOL_MESSAGES_H
#define MS_CONTROL_PROTOCOL_MESSAGES_H #define MS_CONTROL_PROTOCOL_MESSAGES_H
#include "messages/RequestHello.h" #include "messages/RequestHello.h"
#include "messages/RequestAuthenticate.h" #include "messages/RequestAuthenticate.h"
#include "messages/RequestCreateConference.h" #include "messages/RequestCreateConference.h"
#endif #endif
#ifndef MS_CONTROL_PROTOCOL_REQUEST_AUTHENTICATE_H #ifndef MS_CONTROL_PROTOCOL_REQUEST_AUTHENTICATE_H
#define MS_CONTROL_PROTOCOL_REQUEST_AUTHENTICATE_H #define MS_CONTROL_PROTOCOL_REQUEST_AUTHENTICATE_H
#include "ControlProtocol/Request.h" #include "ControlProtocol/Request.h"
#include <string> #include <string>
namespace ControlProtocol
namespace ControlProtocol { {
class RequestAuthenticate : public ControlProtocol::Request
{
class RequestAuthenticate : public ControlProtocol::Request { public:
public:
RequestAuthenticate(); RequestAuthenticate();
virtual ~RequestAuthenticate(); virtual ~RequestAuthenticate();
...@@ -19,13 +17,10 @@ public: ...@@ -19,13 +17,10 @@ public:
virtual void Dump() override; virtual void Dump() override;
private: private:
std::string user; std::string user;
std::string passwd; std::string passwd;
}; };
} // namespace ControlProtocol } // namespace ControlProtocol
#endif #endif
#ifndef MS_CONTROL_PROTOCOL_REQUEST_CREATE_CONFERENCE_H #ifndef MS_CONTROL_PROTOCOL_REQUEST_CREATE_CONFERENCE_H
#define MS_CONTROL_PROTOCOL_REQUEST_CREATE_CONFERENCE_H #define MS_CONTROL_PROTOCOL_REQUEST_CREATE_CONFERENCE_H
#include "ControlProtocol/Request.h" #include "ControlProtocol/Request.h"
namespace ControlProtocol
namespace ControlProtocol { {
class RequestCreateConference : public ControlProtocol::Request
{
class RequestCreateConference : public ControlProtocol::Request { public:
public:
RequestCreateConference(); RequestCreateConference();
virtual ~RequestCreateConference(); virtual ~RequestCreateConference();
virtual void Dump() override; virtual void Dump() override;
}; };
} // namespace ControlProtocol } // namespace ControlProtocol
#endif #endif
#ifndef MS_CONTROL_PROTOCOL_REQUEST_HELLO_H #ifndef MS_CONTROL_PROTOCOL_REQUEST_HELLO_H
#define MS_CONTROL_PROTOCOL_REQUEST_HELLO_H #define MS_CONTROL_PROTOCOL_REQUEST_HELLO_H
#include "ControlProtocol/Request.h" #include "ControlProtocol/Request.h"
namespace ControlProtocol
namespace ControlProtocol { {
class RequestHello : public ControlProtocol::Request
{
class RequestHello : public ControlProtocol::Request { public:
public:
RequestHello(); RequestHello();
virtual ~RequestHello(); virtual ~RequestHello();
virtual void Dump() override; virtual void Dump() override;
}; };
} // namespace ControlProtocol } // namespace ControlProtocol
#endif #endif
#ifndef MS_DAEMON_H #ifndef MS_DAEMON_H
#define MS_DAEMON_H #define MS_DAEMON_H
class Daemon
class Daemon { {
public: public:
static void Daemonize(); static void Daemonize();
static void SendOKStatusToAncestor(); static void SendOKStatusToAncestor();
...@@ -22,5 +22,4 @@ private: ...@@ -22,5 +22,4 @@ private:
static bool hasWrittenPIDFile; static bool hasWrittenPIDFile;
}; };
#endif #endif
#ifndef MS_DISPATCHER_H #ifndef MS_DISPATCHER_H
#define MS_DISPATCHER_H #define MS_DISPATCHER_H
#include "common.h" #include "common.h"
#include "handles/SignalsHandler.h" #include "handles/SignalsHandler.h"
#include "ControlProtocol/TCPServer.h" #include "ControlProtocol/TCPServer.h"
...@@ -10,7 +9,6 @@ ...@@ -10,7 +9,6 @@
#include "ControlProtocol/Message.h" #include "ControlProtocol/Message.h"
#include <vector> #include <vector>
class Dispatcher : class Dispatcher :
public SignalsHandler::Listener, public SignalsHandler::Listener,
public ControlProtocol::TCPServer::Listener, public ControlProtocol::TCPServer::Listener,
...@@ -52,5 +50,4 @@ private: ...@@ -52,5 +50,4 @@ private:
bool closed = false; bool closed = false;
}; };
#endif #endif
#ifndef MS_LIBSRTP_H #ifndef MS_LIBSRTP_H
#define MS_LIBSRTP_H #define MS_LIBSRTP_H
#include <vector> #include <vector>
#include <srtp/srtp.h> #include <srtp/srtp.h>
class LibSRTP
class LibSRTP { {
public: public:
static void ClassInit(); static void ClassInit();
static void ClassDestroy(); static void ClassDestroy();
...@@ -17,20 +16,19 @@ private: ...@@ -17,20 +16,19 @@ private:
static std::vector<const char*> errors; static std::vector<const char*> errors;
}; };
/* Inline static methods. */ /* Inline static methods. */
inline inline
bool LibSRTP::IsError(err_status_t code) { bool LibSRTP::IsError(err_status_t code)
{
return (code != err_status_ok); return (code != err_status_ok);
} }
inline inline
const char* LibSRTP::GetErrorString(err_status_t code) { const char* LibSRTP::GetErrorString(err_status_t code)
{
// This throws out_of_range if the given index is not in the vector. // This throws out_of_range if the given index is not in the vector.
return LibSRTP::errors.at(code); return LibSRTP::errors.at(code);
} }
#endif #endif
#ifndef MS_LIBUV_H #ifndef MS_LIBUV_H
#define MS_LIBUV_H #define MS_LIBUV_H
#include "common.h" #include "common.h"
#include <uv.h> #include <uv.h>
class LibUV
class LibUV { {
public: public:
static void ClassInit(); static void ClassInit();
static void ThreadInit(); static void ThreadInit();
...@@ -18,13 +17,12 @@ private: ...@@ -18,13 +17,12 @@ private:
static __thread uv_loop_t* loop; static __thread uv_loop_t* loop;
}; };
/* Inline static methods. */ /* Inline static methods. */
inline inline
uv_loop_t* LibUV::GetLoop() { uv_loop_t* LibUV::GetLoop()
{
return LibUV::loop; return LibUV::loop;
} }
#endif #endif
#ifndef MS_LOGGER_H #ifndef MS_LOGGER_H
#define MS_LOGGER_H #define MS_LOGGER_H
#include "common.h" #include "common.h"
#include "Settings.h" #include "Settings.h"
#include <string> #include <string>
...@@ -9,11 +8,11 @@ ...@@ -9,11 +8,11 @@
#include <cstring> #include <cstring>
#include <cstdlib> // std::_Exit(), std::abort() #include <cstdlib> // std::_Exit(), std::abort()
#include <uv.h> #include <uv.h>
extern "C" { extern "C"
{
#include <syslog.h> #include <syslog.h>
} }
/* /*
* Logger facility for MediaSoup. * Logger facility for MediaSoup.
* *
...@@ -55,8 +54,8 @@ extern "C" { ...@@ -55,8 +54,8 @@ extern "C" {
*/ */
#define MS_GET_LOG_LEVEL Settings::configuration.logLevel #define MS_GET_LOG_LEVEL Settings::configuration.logLevel
class Logger
class Logger { {
public: public:
static void ThreadInit(const std::string name); static void ThreadInit(const std::string name);
static const char* GetThreadName(); static const char* GetThreadName();
...@@ -73,27 +72,26 @@ private: ...@@ -73,27 +72,26 @@ private:
static bool isSyslogEnabled; static bool isSyslogEnabled;
}; };
/* Inline static methods. */ /* Inline static methods. */
inline inline
const char* Logger::GetThreadName() { const char* Logger::GetThreadName()
{
return Logger::threadNamePtr; return Logger::threadNamePtr;
} }
inline inline
bool Logger::IsSyslogEnabled() { bool Logger::IsSyslogEnabled()
{
return Logger::isSyslogEnabled; return Logger::isSyslogEnabled;
} }
inline inline
bool Logger::HasDebugLevel() { bool Logger::HasDebugLevel()
{
return (LOG_DEBUG == MS_GET_LOG_LEVEL); return (LOG_DEBUG == MS_GET_LOG_LEVEL);
} }
// NOTE: Each file including Logger.h MUST define its own MS_CLASS macro. // NOTE: Each file including Logger.h MUST define its own MS_CLASS macro.
#ifdef MS_DEVEL #ifdef MS_DEVEL
...@@ -108,19 +106,22 @@ bool Logger::HasDebugLevel() { ...@@ -108,19 +106,22 @@ bool Logger::HasDebugLevel() {
#endif #endif
#define _MS_TO_STDOUT(prefix) \ #define _MS_TO_STDOUT(prefix) \
if (! Logger::IsSyslogEnabled()) { \ if (!Logger::IsSyslogEnabled()) \
{ \
std::fprintf(stdout, prefix _MS_LOG_STR "\n", _MS_LOG_ARG); \ std::fprintf(stdout, prefix _MS_LOG_STR "\n", _MS_LOG_ARG); \
fflush(stdout); \ fflush(stdout); \
} }
#define _MS_TO_STDOUT_DESC(prefix, desc, ...) \ #define _MS_TO_STDOUT_DESC(prefix, desc, ...) \
if (! Logger::IsSyslogEnabled()) { \ if (!Logger::IsSyslogEnabled()) \
{ \
std::fprintf(stdout, prefix _MS_LOG_STR_DESC desc "\n", _MS_LOG_ARG, ##__VA_ARGS__); \ std::fprintf(stdout, prefix _MS_LOG_STR_DESC desc "\n", _MS_LOG_ARG, ##__VA_ARGS__); \
fflush(stdout); \ fflush(stdout); \
} }
#define _MS_TO_STDERR_DESC(prefix, desc, ...) \ #define _MS_TO_STDERR_DESC(prefix, desc, ...) \
if (! Logger::IsSyslogEnabled()) { \ if (!Logger::IsSyslogEnabled()) \
{ \
std::fprintf(stderr, prefix _MS_LOG_STR_DESC desc "\n", _MS_LOG_ARG, ##__VA_ARGS__); \ std::fprintf(stderr, prefix _MS_LOG_STR_DESC desc "\n", _MS_LOG_ARG, ##__VA_ARGS__); \
fflush(stderr); \ fflush(stderr); \
} }
...@@ -133,7 +134,6 @@ bool Logger::HasDebugLevel() { ...@@ -133,7 +134,6 @@ bool Logger::HasDebugLevel() {
if (Logger::IsSyslogEnabled()) \ if (Logger::IsSyslogEnabled()) \
syslog(severity, prefix _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); syslog(severity, prefix _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__);
/* /*
* Log levels in syslog.h: * Log levels in syslog.h:
* *
...@@ -150,80 +150,104 @@ bool Logger::HasDebugLevel() { ...@@ -150,80 +150,104 @@ bool Logger::HasDebugLevel() {
#ifdef MS_DEVEL #ifdef MS_DEVEL
#define MS_TRACE() \ #define MS_TRACE() \
do { \ do \
{ \
_MS_TO_STDOUT("TRACE: "); \ _MS_TO_STDOUT("TRACE: "); \
_MS_TO_SYSLOG(LOG_DEBUG, "TRACE: "); \ _MS_TO_SYSLOG(LOG_DEBUG, "TRACE: "); \
} while(0) } \
while (0)
#else #else
#define MS_TRACE() #define MS_TRACE()
#endif #endif
#define MS_DEBUG(desc, ...) \ #define MS_DEBUG(desc, ...) \
do { \ do \
if (LOG_DEBUG == MS_GET_LOG_LEVEL) { \ { \
if (LOG_DEBUG == MS_GET_LOG_LEVEL) \
{ \
_MS_TO_STDOUT_DESC("DEBUG: ", desc, ##__VA_ARGS__); \ _MS_TO_STDOUT_DESC("DEBUG: ", desc, ##__VA_ARGS__); \
_MS_TO_SYSLOG_DESC(LOG_DEBUG, "DEBUG: ", desc, ##__VA_ARGS__); \ _MS_TO_SYSLOG_DESC(LOG_DEBUG, "DEBUG: ", desc, ##__VA_ARGS__); \
} \ } \
} while(0) } \
while (0)
#define MS_INFO(desc, ...) \ #define MS_INFO(desc, ...) \
do { \ do \
if (LOG_INFO <= MS_GET_LOG_LEVEL) { \ { \
if (LOG_INFO <= MS_GET_LOG_LEVEL) \
{ \
_MS_TO_STDOUT_DESC("INFO: ", desc, ##__VA_ARGS__); \ _MS_TO_STDOUT_DESC("INFO: ", desc, ##__VA_ARGS__); \
_MS_TO_SYSLOG_DESC(LOG_INFO, "INFO: ", desc, ##__VA_ARGS__); \ _MS_TO_SYSLOG_DESC(LOG_INFO, "INFO: ", desc, ##__VA_ARGS__); \
} \ } \
} while(0) } \
while (0)
#define MS_NOTICE(desc, ...) \ #define MS_NOTICE(desc, ...) \
do { \ do \
if (LOG_NOTICE <= MS_GET_LOG_LEVEL) { \ { \
if (LOG_NOTICE <= MS_GET_LOG_LEVEL) \
{ \
_MS_TO_STDOUT_DESC("NOTICE: ", desc, ##__VA_ARGS__); \ _MS_TO_STDOUT_DESC("NOTICE: ", desc, ##__VA_ARGS__); \
_MS_TO_SYSLOG_DESC(LOG_NOTICE, "NOTICE: ", desc, ##__VA_ARGS__); \ _MS_TO_SYSLOG_DESC(LOG_NOTICE, "NOTICE: ", desc, ##__VA_ARGS__); \
} \ } \
} while(0) } \
while (0)
#define MS_WARN(desc, ...) \ #define MS_WARN(desc, ...) \
do { \ do \
if (LOG_WARNING <= MS_GET_LOG_LEVEL) { \ { \
if (LOG_WARNING <= MS_GET_LOG_LEVEL) \
{ \
_MS_TO_STDERR_DESC("WARN: ", desc, ##__VA_ARGS__); \ _MS_TO_STDERR_DESC("WARN: ", desc, ##__VA_ARGS__); \
_MS_TO_SYSLOG_DESC(LOG_WARNING, "WARN: ", desc, ##__VA_ARGS__); \ _MS_TO_SYSLOG_DESC(LOG_WARNING, "WARN: ", desc, ##__VA_ARGS__); \
} \ } \
} while(0) } \
while (0)
#define MS_ERROR(desc, ...) \ #define MS_ERROR(desc, ...) \
do { \ do \
{ \
_MS_TO_STDERR_DESC("ERROR: ", desc, ##__VA_ARGS__); \ _MS_TO_STDERR_DESC("ERROR: ", desc, ##__VA_ARGS__); \
_MS_TO_SYSLOG_DESC(LOG_ERR, "ERROR: ", desc, ##__VA_ARGS__); \ _MS_TO_SYSLOG_DESC(LOG_ERR, "ERROR: ", desc, ##__VA_ARGS__); \
} while(0) } \
while (0)
#define MS_CRIT(desc, ...) \ #define MS_CRIT(desc, ...) \
do { \ do \
{ \
_MS_TO_STDERR_DESC("CRIT: ", desc, ##__VA_ARGS__); \ _MS_TO_STDERR_DESC("CRIT: ", desc, ##__VA_ARGS__); \
_MS_TO_SYSLOG_DESC(LOG_ERR, "CRIT: ", desc, ##__VA_ARGS__); \ _MS_TO_SYSLOG_DESC(LOG_ERR, "CRIT: ", desc, ##__VA_ARGS__); \
} while(0) } \
while (0)
#define MS_EXIT_SUCCESS(desc, ...) \ #define MS_EXIT_SUCCESS(desc, ...) \
do { \ do \
{ \
MS_NOTICE("SUCCESS EXIT | " desc, ##__VA_ARGS__); \ MS_NOTICE("SUCCESS EXIT | " desc, ##__VA_ARGS__); \
std::_Exit(EXIT_SUCCESS); \ std::_Exit(EXIT_SUCCESS); \
} while(0) } \
while (0)
#define MS_EXIT_FAILURE(desc, ...) \ #define MS_EXIT_FAILURE(desc, ...) \
do { \ do \
{ \
MS_CRIT("FAILURE EXIT | " desc, ##__VA_ARGS__); \ MS_CRIT("FAILURE EXIT | " desc, ##__VA_ARGS__); \
std::_Exit(EXIT_FAILURE); \ std::_Exit(EXIT_FAILURE); \
} while(0) } \
while (0)
#define MS_ABORT(desc, ...) \ #define MS_ABORT(desc, ...) \
do { \ do \
{ \
MS_CRIT("ABORT | " desc, ##__VA_ARGS__); \ MS_CRIT("ABORT | " desc, ##__VA_ARGS__); \
std::abort(); \ std::abort(); \
} while(0) } \
while (0)
#define MS_ASSERT(condition, desc, ...) \ #define MS_ASSERT(condition, desc, ...) \
if (! (condition)) { \ if (!(condition)) \
{ \
MS_ABORT("failed assertion `%s': " desc, #condition, ##__VA_ARGS__); \ MS_ABORT("failed assertion `%s': " desc, #condition, ##__VA_ARGS__); \
} }
#endif #endif
#ifndef MS_MEDIASOUP_H #ifndef MS_MEDIASOUP_H
#define MS_MEDIASOUP_H #define MS_MEDIASOUP_H
/* /*
* MediaSoup top class. * MediaSoup top class.
* *
* Entry point of the application. * Entry point of the application.
*/ */
class MediaSoup { class MediaSoup
{
public: public:
// Set the process. // Set the process.
static void SetProcess(); static void SetProcess();
...@@ -27,5 +27,4 @@ private: ...@@ -27,5 +27,4 @@ private:
static void RunWorkerThread(void* data); static void RunWorkerThread(void* data);
}; };
#endif #endif
#ifndef MS_MEDIASOUP_ERROR_H #ifndef MS_MEDIASOUP_ERROR_H
#define MS_MEDIASOUP_ERROR_H #define MS_MEDIASOUP_ERROR_H
#include "Logger.h" #include "Logger.h"
#include <stdexcept> #include <stdexcept>
#include <string> #include <string>
#include <cstdio> // std::snprintf #include <cstdio> // std::snprintf
class MediaSoupError : public std::runtime_error
class MediaSoupError : public std::runtime_error { {
public: public:
MediaSoupError(const char* description); MediaSoupError(const char* description);
}; };
/* Inline methods. */ /* Inline methods. */
inline inline
MediaSoupError::MediaSoupError(const char* description) : MediaSoupError::MediaSoupError(const char* description) : std::runtime_error(description)
std::runtime_error(description)
{} {}
#define MS_THROW_ERROR(desc, ...) \ #define MS_THROW_ERROR(desc, ...) \
do { \ do \
{ \
MS_ERROR("throwing MediaSoupError | " desc, ##__VA_ARGS__); \ MS_ERROR("throwing MediaSoupError | " desc, ##__VA_ARGS__); \
char buffer[1000]; \ char buffer[1000]; \
std::snprintf(buffer, 1000, desc, ##__VA_ARGS__); \ std::snprintf(buffer, 1000, desc, ##__VA_ARGS__); \
throw MediaSoupError(buffer); \ throw MediaSoupError(buffer); \
} while(0) } \
while (0)
#endif #endif
#ifndef MS_OPENSSL_H #ifndef MS_OPENSSL_H
#define MS_OPENSSL_H #define MS_OPENSSL_H
#include "common.h" #include "common.h"
#include <openssl/ssl.h> #include <openssl/ssl.h>
#include <openssl/crypto.h> #include <openssl/crypto.h>
/* OpenSSL doc: struct CRYPTO_dynlock_value has to be defined by the application. */ /* OpenSSL doc: struct CRYPTO_dynlock_value has to be defined by the application. */
struct CRYPTO_dynlock_value { struct CRYPTO_dynlock_value
{
pthread_mutex_t mutex; pthread_mutex_t mutex;
}; };
class OpenSSL
class OpenSSL { {
public: public:
static void ClassInit(); static void ClassInit();
static void ClassDestroy(); static void ClassDestroy();
...@@ -30,5 +29,4 @@ private: ...@@ -30,5 +29,4 @@ private:
static int numMutexes; static int numMutexes;
}; };
#endif #endif
#ifndef MS_RTC_DTLS_HANDLER_H #ifndef MS_RTC_DTLS_HANDLER_H
#define MS_RTC_DTLS_HANDLER_H #define MS_RTC_DTLS_HANDLER_H
#include "common.h" #include "common.h"
#include "handles/Timer.h" #include "handles/Timer.h"
#include "RTC/DTLSRole.h" #include "RTC/DTLSRole.h"
...@@ -14,21 +13,20 @@ ...@@ -14,21 +13,20 @@
#include <openssl/bio.h> #include <openssl/bio.h>
#include <openssl/x509.h> #include <openssl/x509.h>
namespace RTC
namespace RTC {
class DTLSHandler :
public Timer::Listener
{ {
private: class DTLSHandler : public Timer::Listener
struct SrtpProfileMapEntry { {
private:
struct SrtpProfileMapEntry
{
SRTPProfile profile; SRTPProfile profile;
const char* name; const char* name;
}; };
public: public:
class Listener { class Listener
{
public: public:
// NOTE: The caller MUST NOT call Reset() or Close() during the // NOTE: The caller MUST NOT call Reset() or Close() during the
// onOutgoingDTLSData() callback. // onOutgoingDTLSData() callback.
...@@ -42,19 +40,19 @@ public: ...@@ -42,19 +40,19 @@ public:
virtual void onDTLSApplicationData(DTLSHandler* dtlsHandler, const MS_BYTE* data, size_t len) = 0; virtual void onDTLSApplicationData(DTLSHandler* dtlsHandler, const MS_BYTE* data, size_t len) = 0;
}; };
public: public:
static void ClassInit(); static void ClassInit();
static void ClassDestroy(); static void ClassDestroy();
static bool IsDTLS(const MS_BYTE* data, size_t len); static bool IsDTLS(const MS_BYTE* data, size_t len);
static const std::string& GetFingerprint(RTC::FingerprintHash hash); static const std::string& GetFingerprint(RTC::FingerprintHash hash);
private: private:
static void GenerateCertificateAndPrivateKey(); static void GenerateCertificateAndPrivateKey();
static void ReadCertificateAndPrivateKeyFromFiles(); static void ReadCertificateAndPrivateKeyFromFiles();
static void CreateSSL_CTX(); static void CreateSSL_CTX();
static void GenerateFingerprints(); static void GenerateFingerprints();
private: private:
static X509* certificate; static X509* certificate;
static EVP_PKEY* privateKey; static EVP_PKEY* privateKey;
static SSL_CTX* sslCtx; static SSL_CTX* sslCtx;
...@@ -64,7 +62,7 @@ private: ...@@ -64,7 +62,7 @@ private:
static SRTPProfiles srtpProfiles; static SRTPProfiles srtpProfiles;
static __thread MS_BYTE sslReadBuffer[]; static __thread MS_BYTE sslReadBuffer[];
public: public:
DTLSHandler(Listener* listener); DTLSHandler(Listener* listener);
virtual ~DTLSHandler(); virtual ~DTLSHandler();
...@@ -78,7 +76,7 @@ public: ...@@ -78,7 +76,7 @@ public:
void SendApplicationData(const MS_BYTE* data, size_t len); void SendApplicationData(const MS_BYTE* data, size_t len);
void Dump(); void Dump();
private: private:
bool CheckStatus(int return_code); bool CheckStatus(int return_code);
void SendPendingOutgoingDTLSData(); void SendPendingOutgoingDTLSData();
void SetTimeout(); void SetTimeout();
...@@ -87,15 +85,15 @@ private: ...@@ -87,15 +85,15 @@ private:
RTC::SRTPProfile GetNegotiatedSRTPProfile(); RTC::SRTPProfile GetNegotiatedSRTPProfile();
void ExtractSRTPKeys(RTC::SRTPProfile srtp_profile); void ExtractSRTPKeys(RTC::SRTPProfile srtp_profile);
/* Callbacks fired by OpenSSL events. */ /* Callbacks fired by OpenSSL events. */
public: public:
void onSSLInfo(int where, int ret); void onSSLInfo(int where, int ret);
/* Pure virtual methods inherited from Timer::Listener. */ /* Pure virtual methods inherited from Timer::Listener. */
public: public:
virtual void onTimer(Timer* timer) override; virtual void onTimer(Timer* timer) override;
private: private:
// Passed by argument: // Passed by argument:
Listener* listener = nullptr; Listener* listener = nullptr;
// Allocated by this: // Allocated by this:
...@@ -114,37 +112,34 @@ private: ...@@ -114,37 +112,34 @@ private:
bool isCheckingStatus = false; bool isCheckingStatus = false;
bool doReset = false; bool doReset = false;
bool doClose = false; bool doClose = false;
}; };
/* Inline static methods. */ /* Inline static methods. */
inline inline
bool DTLSHandler::IsDTLS(const MS_BYTE* data, size_t len) { bool DTLSHandler::IsDTLS(const MS_BYTE* data, size_t len)
{
return ( return (
// Minimum DTLS record length is 13 bytes. // Minimum DTLS record length is 13 bytes.
(len >= 13) && (len >= 13) &&
// DOC: https://tools.ietf.org/html/draft-petithuguenin-avtcore-rfc5764-mux-fixes-00 // DOC: https://tools.ietf.org/html/draft-petithuguenin-avtcore-rfc5764-mux-fixes-00
(data[0] > 19 && data[0] < 64) (data[0] > 19 && data[0] < 64)
); );
} }
/* Inline instance methods. */ /* Inline instance methods. */
inline inline
bool DTLSHandler::IsConnected() { bool DTLSHandler::IsConnected()
{
return this->isConnected; return this->isConnected;
} }
inline
inline bool DTLSHandler::IsRunning()
bool DTLSHandler::IsRunning() { {
return this->isRunning; return this->isRunning;
} }
} // namespace RTC } // namespace RTC
#endif #endif
#ifndef MS_RTC_DTLS_ROLE_H #ifndef MS_RTC_DTLS_ROLE_H
#define MS_RTC_DTLS_ROLE_H #define MS_RTC_DTLS_ROLE_H
namespace RTC { namespace RTC {
enum class DTLSRole
{
enum class DTLSRole {
NONE = 0, NONE = 0,
SERVER = 1, SERVER = 1,
CLIENT CLIENT
}; };
} // namespace RTC } // namespace RTC
#endif #endif
#ifndef MS_RTC_FINGERPRINT_HASH_H #ifndef MS_RTC_FINGERPRINT_HASH_H
#define MS_RTC_FINGERPRINT_HASH_H #define MS_RTC_FINGERPRINT_HASH_H
namespace RTC
namespace RTC { {
enum class FingerprintHash
{
enum class FingerprintHash {
NONE = 0, NONE = 0,
SHA1 = 1, SHA1 = 1,
SHA224, SHA224,
SHA256, SHA256,
SHA384, SHA384,
SHA512 SHA512
}; };
} // namespace RTC } // namespace RTC
#endif #endif
#ifndef MS_RTC_ICE_SERVER_H #ifndef MS_RTC_ICE_SERVER_H
#define MS_RTC_ICE_SERVER_H #define MS_RTC_ICE_SERVER_H
#include "common.h" #include "common.h"
#include "RTC/TransportSource.h" #include "RTC/TransportSource.h"
#include "RTC/STUNMessage.h" #include "RTC/STUNMessage.h"
...@@ -9,13 +8,13 @@ ...@@ -9,13 +8,13 @@
#include "RTC/TCPConnection.h" #include "RTC/TCPConnection.h"
#include <string> #include <string>
namespace RTC
namespace RTC { {
class ICEServer
{
class ICEServer { public:
public: class Listener
class Listener { {
public: public:
/** /**
* These callbacks are guaranteed to be called before ProcessSTUNMessage() * These callbacks are guaranteed to be called before ProcessSTUNMessage()
...@@ -25,7 +24,7 @@ public: ...@@ -25,7 +24,7 @@ public:
virtual void onICEValidPair(ICEServer* iceServer, RTC::TransportSource* source, bool has_use_candidate) = 0; virtual void onICEValidPair(ICEServer* iceServer, RTC::TransportSource* source, bool has_use_candidate) = 0;
}; };
public: public:
ICEServer(Listener* listener); ICEServer(Listener* listener);
void ProcessSTUNMessage(RTC::STUNMessage* msg, RTC::TransportSource* source); void ProcessSTUNMessage(RTC::STUNMessage* msg, RTC::TransportSource* source);
...@@ -35,43 +34,40 @@ public: ...@@ -35,43 +34,40 @@ public:
void* GetUserData(); void* GetUserData();
void Close(); void Close();
private: private:
// Passed by argument: // Passed by argument:
Listener* listener = nullptr; Listener* listener = nullptr;
void* userData = nullptr; void* userData = nullptr;
// Others: // Others:
std::string localUsername; std::string localUsername;
std::string localPassword; std::string localPassword;
}; };
/* Inline methods. */ /* Inline methods. */
inline inline
std::string& ICEServer::GetLocalUsername() { std::string& ICEServer::GetLocalUsername()
{
return this->localUsername; return this->localUsername;
} }
inline inline
std::string& ICEServer::GetLocalPassword() { std::string& ICEServer::GetLocalPassword()
{
return this->localPassword; return this->localPassword;
} }
inline
inline void ICEServer::SetUserData(void* userData)
void ICEServer::SetUserData(void* userData) { {
this->userData = userData; this->userData = userData;
} }
inline inline
void* ICEServer::GetUserData() { void* ICEServer::GetUserData()
{
return this->userData; return this->userData;
} }
} // namespace RTC } // namespace RTC
#endif #endif
#ifndef MS_RTC_PEER_H #ifndef MS_RTC_PEER_H
#define MS_RTC_PEER_H #define MS_RTC_PEER_H
#include "RTC/Transport.h" #include "RTC/Transport.h"
#include "RTC/RTPPacket.h" #include "RTC/RTPPacket.h"
#include "RTC/RTCPPacket.h" #include "RTC/RTCPPacket.h"
#include <vector> #include <vector>
namespace RTC
namespace RTC {
class Peer :
RTC::Transport::Listener
{ {
public: class Peer : RTC::Transport::Listener
class Listener { {
public:
class Listener
{
public: public:
virtual void onRTPPacket(RTC::Peer* peer, RTC::RTPPacket* packet) = 0; virtual void onRTPPacket(RTC::Peer* peer, RTC::RTPPacket* packet) = 0;
virtual void onRTCPPacket(RTC::Peer* peer, RTC::RTCPPacket* packet) = 0; virtual void onRTCPPacket(RTC::Peer* peer, RTC::RTCPPacket* packet) = 0;
}; };
public: public:
Peer(Listener* listener); Peer(Listener* listener);
virtual ~Peer(); virtual ~Peer();
...@@ -31,37 +28,32 @@ public: ...@@ -31,37 +28,32 @@ public:
void* GetUserData(); void* GetUserData();
void Close(); void Close();
/* Pure virtual methods inherited from RTC::Transport::Listener. */ /* Pure virtual methods inherited from RTC::Transport::Listener. */
public: public:
virtual void onRTPPacket(RTC::Transport* transport, RTC::RTPPacket* packet) override; virtual void onRTPPacket(RTC::Transport* transport, RTC::RTPPacket* packet) override;
virtual void onRTCPPacket(RTC::Transport* transport, RTC::RTCPPacket* packet) override; virtual void onRTCPPacket(RTC::Transport* transport, RTC::RTCPPacket* packet) override;
private: private:
// Passed by argument: // Passed by argument:
Listener* listener = nullptr; Listener* listener = nullptr;
void* userData = nullptr; void* userData = nullptr;
// Others: // Others:
RTC::Transport* transport = nullptr; RTC::Transport* transport = nullptr;
}; };
/* Inline methods. */ /* Inline methods. */
inline inline
void Peer::SetUserData(void* userData) { void Peer::SetUserData(void* userData)
{
this->userData = userData; this->userData = userData;
} }
inline inline
void* Peer::GetUserData() { void* Peer::GetUserData()
{
return this->userData; return this->userData;
} }
} // namespace RTC } // namespace RTC
#endif #endif
#ifndef MS_RTC_RTCP_PACKET_H #ifndef MS_RTC_RTCP_PACKET_H
#define MS_RTC_RTCP_PACKET_H #define MS_RTC_RTCP_PACKET_H
#include "common.h" #include "common.h"
namespace RTC
namespace RTC { {
class RTCPPacket
{
class RTCPPacket { public:
public:
/* Struct for RTCP common header. */ /* Struct for RTCP common header. */
typedef struct CommonHeader { typedef struct CommonHeader
{
#if defined(MS_LITTLE_ENDIAN) #if defined(MS_LITTLE_ENDIAN)
MS_BYTE count:5; MS_BYTE count:5;
MS_BYTE padding:1; MS_BYTE padding:1;
...@@ -25,29 +24,29 @@ public: ...@@ -25,29 +24,29 @@ public:
MS_2BYTES length:16; MS_2BYTES length:16;
} CommonHeader; } CommonHeader;
public: public:
static bool IsRTCP(const MS_BYTE* data, size_t len); static bool IsRTCP(const MS_BYTE* data, size_t len);
static RTCPPacket* Parse(const MS_BYTE* data, size_t len); static RTCPPacket* Parse(const MS_BYTE* data, size_t len);
public: public:
RTCPPacket(CommonHeader* header, const MS_BYTE* raw, size_t length); RTCPPacket(CommonHeader* header, const MS_BYTE* raw, size_t length);
~RTCPPacket(); ~RTCPPacket();
const MS_BYTE* GetRaw(); const MS_BYTE* GetRaw();
size_t GetLength(); size_t GetLength();
private: private:
// Passed by argument: // Passed by argument:
CommonHeader* header = nullptr; CommonHeader* header = nullptr;
MS_BYTE* raw = nullptr; MS_BYTE* raw = nullptr;
size_t length = 0; size_t length = 0;
}; };
/* Inline static methods. */ /* Inline static methods. */
inline inline
bool RTCPPacket::IsRTCP(const MS_BYTE* data, size_t len) { bool RTCPPacket::IsRTCP(const MS_BYTE* data, size_t len)
{
CommonHeader* header = (CommonHeader*)data; CommonHeader* header = (CommonHeader*)data;
return ( return (
...@@ -61,24 +60,21 @@ bool RTCPPacket::IsRTCP(const MS_BYTE* data, size_t len) { ...@@ -61,24 +60,21 @@ bool RTCPPacket::IsRTCP(const MS_BYTE* data, size_t len) {
// RFC 5761 (RTCP-mux) states this range for secure RTCP/RTP detection. // RFC 5761 (RTCP-mux) states this range for secure RTCP/RTP detection.
(header->packet_type >= 192 && header->packet_type <= 223) (header->packet_type >= 192 && header->packet_type <= 223)
); );
} }
/* Inline instance methods. */
/* Inline instance methods. */ inline
const MS_BYTE* RTCPPacket::GetRaw()
inline {
const MS_BYTE* RTCPPacket::GetRaw() {
return this->raw; return this->raw;
} }
inline inline
size_t RTCPPacket::GetLength() { size_t RTCPPacket::GetLength()
{
return this->length; return this->length;
} }
} // namespace RTC } // namespace RTC
#endif #endif
#ifndef MS_RTC_RTP_PACKET_H #ifndef MS_RTC_RTP_PACKET_H
#define MS_RTC_RTP_PACKET_H #define MS_RTC_RTP_PACKET_H
#include "common.h" #include "common.h"
namespace RTC
namespace RTC { {
class RTPPacket
{
class RTPPacket { public:
public:
/* Struct for RTP header. */ /* Struct for RTP header. */
typedef struct Header { typedef struct Header
{
#if defined(MS_LITTLE_ENDIAN) #if defined(MS_LITTLE_ENDIAN)
MS_BYTE csrc_count:4; MS_BYTE csrc_count:4;
MS_BYTE extension:1; MS_BYTE extension:1;
...@@ -33,17 +32,18 @@ public: ...@@ -33,17 +32,18 @@ public:
} Header; } Header;
/* Struct for RTP header extension. */ /* Struct for RTP header extension. */
typedef struct ExtensionHeader { typedef struct ExtensionHeader
{
MS_2BYTES id; MS_2BYTES id;
MS_2BYTES length; // Size of value in multiples of 4 bytes. MS_2BYTES length; // Size of value in multiples of 4 bytes.
MS_BYTE* value; MS_BYTE* value;
} ExtensionHeader; } ExtensionHeader;
public: public:
static bool IsRTP(const MS_BYTE* data, size_t len); static bool IsRTP(const MS_BYTE* data, size_t len);
static RTPPacket* Parse(const MS_BYTE* data, size_t len); static RTPPacket* Parse(const MS_BYTE* data, size_t len);
public: public:
RTPPacket(Header* header, ExtensionHeader* extensionHeader, const MS_BYTE* payload, size_t payloadLen, MS_BYTE payloadPadding, const MS_BYTE* raw, size_t length); RTPPacket(Header* header, ExtensionHeader* extensionHeader, const MS_BYTE* payload, size_t payloadLen, MS_BYTE payloadPadding, const MS_BYTE* raw, size_t length);
~RTPPacket(); ~RTPPacket();
...@@ -65,7 +65,7 @@ public: ...@@ -65,7 +65,7 @@ public:
void Serialize(); void Serialize();
void Dump(); void Dump();
private: private:
// Passed by argument: // Passed by argument:
Header* header = nullptr; Header* header = nullptr;
MS_BYTE* csrcList = nullptr; MS_BYTE* csrcList = nullptr;
...@@ -77,13 +77,13 @@ private: ...@@ -77,13 +77,13 @@ private:
size_t length = 0; size_t length = 0;
// Others: // Others:
bool isSerialized = false; bool isSerialized = false;
}; };
/* Inline static methods. */ /* Inline static methods. */
inline inline
bool RTPPacket::IsRTP(const MS_BYTE* data, size_t len) { bool RTPPacket::IsRTP(const MS_BYTE* data, size_t len)
{
// NOTE: RTCPPacket::IsRTCP() must always be called before this method. // NOTE: RTCPPacket::IsRTCP() must always be called before this method.
Header* header = (Header*)data; Header* header = (Header*)data;
...@@ -95,109 +95,106 @@ bool RTPPacket::IsRTP(const MS_BYTE* data, size_t len) { ...@@ -95,109 +95,106 @@ bool RTPPacket::IsRTP(const MS_BYTE* data, size_t len) {
// RTP Version must be 2. // RTP Version must be 2.
(header->version == 2) (header->version == 2)
); );
} }
/* Inline instance methods. */ /* Inline instance methods. */
inline inline
const MS_BYTE* RTPPacket::GetRaw() { const MS_BYTE* RTPPacket::GetRaw()
{
return this->raw; return this->raw;
} }
inline
inline size_t RTPPacket::GetLength()
size_t RTPPacket::GetLength() { {
return this->length; return this->length;
} }
inline inline
MS_BYTE RTPPacket::GetPayloadType() { MS_BYTE RTPPacket::GetPayloadType()
{
return this->header->payload_type; return this->header->payload_type;
} }
inline inline
void RTPPacket::SetPayloadType(MS_BYTE payload_type) { void RTPPacket::SetPayloadType(MS_BYTE payload_type)
{
this->header->payload_type = payload_type; this->header->payload_type = payload_type;
} }
inline
inline bool RTPPacket::HasMarker()
bool RTPPacket::HasMarker() { {
return this->header->marker; return this->header->marker;
} }
inline inline
void RTPPacket::SetMarker(bool marker) { void RTPPacket::SetMarker(bool marker)
{
this->header->marker = marker; this->header->marker = marker;
} }
inline inline
MS_2BYTES RTPPacket::GetSequenceNumber() { MS_2BYTES RTPPacket::GetSequenceNumber()
{
return ntohs(this->header->sequence_number); return ntohs(this->header->sequence_number);
} }
inline
inline MS_4BYTES RTPPacket::GetTimestamp()
MS_4BYTES RTPPacket::GetTimestamp() { {
return ntohl(this->header->timestamp); return ntohl(this->header->timestamp);
} }
inline inline
MS_4BYTES RTPPacket::GetSSRC() { MS_4BYTES RTPPacket::GetSSRC()
{
return ntohl(this->header->ssrc); return ntohl(this->header->ssrc);
} }
// TODO temp // TODO temp
inline inline
void RTPPacket::SetSSRC(MS_4BYTES ssrc) { void RTPPacket::SetSSRC(MS_4BYTES ssrc)
{
this->header->ssrc = htonl(ssrc); this->header->ssrc = htonl(ssrc);
} }
inline
inline bool RTPPacket::HasExtensionHeader()
bool RTPPacket::HasExtensionHeader() { {
return (this->extensionHeader ? true : false); return (this->extensionHeader ? true : false);
} }
inline inline
MS_2BYTES RTPPacket::GetExtensionHeaderId() { MS_2BYTES RTPPacket::GetExtensionHeaderId()
{
if (this->extensionHeader) if (this->extensionHeader)
return MS_2BYTES(ntohs(this->extensionHeader->id)); return MS_2BYTES(ntohs(this->extensionHeader->id));
else else
return 0; return 0;
} }
inline inline
size_t RTPPacket::GetExtensionHeaderLength() { size_t RTPPacket::GetExtensionHeaderLength()
{
if (this->extensionHeader) if (this->extensionHeader)
return size_t(ntohs(this->extensionHeader->length) * 4); return size_t(ntohs(this->extensionHeader->length) * 4);
else else
return 0; return 0;
} }
inline
inline MS_BYTE* RTPPacket::GetPayload()
MS_BYTE* RTPPacket::GetPayload() { {
return this->payload; return this->payload;
} }
inline inline
size_t RTPPacket::GetPayloadLength() { size_t RTPPacket::GetPayloadLength()
{
return this->payloadLength; return this->payloadLength;
} }
} // namespace RTC } // namespace RTC
#endif #endif
#ifndef MS_RTC_ROOM_H #ifndef MS_RTC_ROOM_H
#define MS_RTC_ROOM_H #define MS_RTC_ROOM_H
#include "RTC/Peer.h" #include "RTC/Peer.h"
#include "RTC/RTPPacket.h" #include "RTC/RTPPacket.h"
#include "RTC/RTCPPacket.h" #include "RTC/RTCPPacket.h"
#include <vector> #include <vector>
namespace RTC
namespace RTC {
class Room :
RTC::Peer::Listener
{ {
public: class Room : RTC::Peer::Listener
{
public:
Room(); Room();
virtual ~Room(); virtual ~Room();
void Close(); void Close();
/* Pure virtual methods inherited from RTC::Peer::Listener. */ /* Pure virtual methods inherited from RTC::Peer::Listener. */
public: public:
virtual void onRTPPacket(RTC::Peer* peer, RTC::RTPPacket* packet) override; virtual void onRTPPacket(RTC::Peer* peer, RTC::RTPPacket* packet) override;
virtual void onRTCPPacket(RTC::Peer* peer, RTC::RTCPPacket* packet) override; virtual void onRTCPPacket(RTC::Peer* peer, RTC::RTCPPacket* packet) override;
private: private:
// Others: // Others:
typedef std::vector<RTC::Peer*> Peers; typedef std::vector<RTC::Peer*> Peers;
Peers peers; Peers peers;
}; };
} // namespace RTC } // namespace RTC
#endif #endif
#ifndef MS_RTC_SRTP_PROFILE_H #ifndef MS_RTC_SRTP_PROFILE_H
#define MS_RTC_SRTP_PROFILE_H #define MS_RTC_SRTP_PROFILE_H
namespace RTC
namespace RTC { {
enum class SRTPProfile
{
enum class SRTPProfile {
NONE = 0, NONE = 0,
AES_CM_128_HMAC_SHA1_80 = 1, AES_CM_128_HMAC_SHA1_80 = 1,
AES_CM_128_HMAC_SHA1_32 AES_CM_128_HMAC_SHA1_32
}; };
} // namespace RTC } // namespace RTC
#endif #endif
#ifndef MS_RTC_SRTP_SESSION_H #ifndef MS_RTC_SRTP_SESSION_H
#define MS_RTC_SRTP_SESSION_H #define MS_RTC_SRTP_SESSION_H
#include "common.h" #include "common.h"
#include "LibSRTP.h" #include "LibSRTP.h"
#include "RTC/SRTPProfile.h" #include "RTC/SRTPProfile.h"
#include <srtp/srtp.h> #include <srtp/srtp.h>
namespace RTC
namespace RTC { {
class SRTPSession
{
class SRTPSession { public:
public: enum class Type
enum class Type { {
INBOUND = 1, INBOUND = 1,
OUTBOUND OUTBOUND
}; };
public: public:
static void ClassInit(); static void ClassInit();
private: private:
static void onSRTPEvent(srtp_event_data_t* data); static void onSRTPEvent(srtp_event_data_t* data);
private: private:
static __thread MS_BYTE encryptBuffer[]; static __thread MS_BYTE encryptBuffer[];
public: public:
SRTPSession(Type type, RTC::SRTPProfile profile, MS_BYTE* key, size_t key_len); SRTPSession(Type type, RTC::SRTPProfile profile, MS_BYTE* key, size_t key_len);
~SRTPSession(); ~SRTPSession();
...@@ -38,28 +37,25 @@ public: ...@@ -38,28 +37,25 @@ public:
const char* GetLastErrorDesc(); const char* GetLastErrorDesc();
void Close(); void Close();
private: private:
// Allocated by this: // Allocated by this:
srtp_t session = nullptr; srtp_t session = nullptr;
// Others: // Others:
err_status_t lastError = (err_status_t)0; err_status_t lastError = (err_status_t)0;
}; };
/* Inline instance methods. */ /* Inline instance methods. */
inline inline
const char* SRTPSession::GetLastErrorDesc() { const char* SRTPSession::GetLastErrorDesc()
{
const char* error_string; const char* error_string;
error_string = LibSRTP::GetErrorString(this->lastError); error_string = LibSRTP::GetErrorString(this->lastError);
this->lastError = (err_status_t)0; // Reset it. this->lastError = (err_status_t)0; // Reset it.
return error_string; return error_string;
} }
} // namespace RTC } // namespace RTC
#endif #endif
#ifndef MS_RTC_STUN_MESSAGE_H #ifndef MS_RTC_STUN_MESSAGE_H
#define MS_RTC_STUN_MESSAGE_H #define MS_RTC_STUN_MESSAGE_H
#include "common.h" #include "common.h"
#include <string> #include <string>
namespace RTC
namespace RTC { {
class STUNMessage
{
class STUNMessage { public:
public:
// STUN message class. // STUN message class.
enum class Class : MS_2BYTES { enum class Class : MS_2BYTES
{
Request = 0, Request = 0,
Indication = 1, Indication = 1,
SuccessResponse = 2, SuccessResponse = 2,
...@@ -20,12 +19,14 @@ public: ...@@ -20,12 +19,14 @@ public:
}; };
// STUN message method. // STUN message method.
enum class Method : MS_2BYTES { enum class Method : MS_2BYTES
{
Binding = 1 Binding = 1
}; };
// Attribute type. // Attribute type.
enum class Attribute : MS_2BYTES { enum class Attribute : MS_2BYTES
{
MappedAddress = 0x0001, MappedAddress = 0x0001,
Username = 0x0006, Username = 0x0006,
MessageIntegrity = 0x0008, MessageIntegrity = 0x0008,
...@@ -44,20 +45,21 @@ public: ...@@ -44,20 +45,21 @@ public:
}; };
// Authentication result. // Authentication result.
enum class Authentication { enum class Authentication
{
OK = 0, OK = 0,
Unauthorized = 1, Unauthorized = 1,
BadRequest = 2 BadRequest = 2
}; };
public: public:
static bool IsSTUN(const MS_BYTE* data, size_t len); static bool IsSTUN(const MS_BYTE* data, size_t len);
static STUNMessage* Parse(const MS_BYTE* data, size_t len); static STUNMessage* Parse(const MS_BYTE* data, size_t len);
private: private:
static const MS_BYTE magicCookie[]; static const MS_BYTE magicCookie[];
public: public:
STUNMessage(Class klass, Method method, const MS_BYTE* transactionId, const MS_BYTE* raw, size_t length); STUNMessage(Class klass, Method method, const MS_BYTE* transactionId, const MS_BYTE* raw, size_t length);
~STUNMessage(); ~STUNMessage();
...@@ -90,7 +92,7 @@ public: ...@@ -90,7 +92,7 @@ public:
void Serialize(); void Serialize();
void Dump(); void Dump();
private: private:
// Passed by argument: // Passed by argument:
Class klass; // 2 bytes. Class klass; // 2 bytes.
Method method; // 2 bytes. Method method; // 2 bytes.
...@@ -110,13 +112,13 @@ private: ...@@ -110,13 +112,13 @@ private:
const struct sockaddr* xorMappedAddress = nullptr; // 8 or 20 bytes. const struct sockaddr* xorMappedAddress = nullptr; // 8 or 20 bytes.
MS_2BYTES errorCode = 0; // 4 bytes (no reason phrase). MS_2BYTES errorCode = 0; // 4 bytes (no reason phrase).
std::string password; std::string password;
}; };
/* Inline methods. */ /* Inline methods. */
inline inline
bool STUNMessage::IsSTUN(const MS_BYTE* data, size_t len) { bool STUNMessage::IsSTUN(const MS_BYTE* data, size_t len)
{
return ( return (
// STUN headers are 20 bytes. // STUN headers are 20 bytes.
(len >= 20) && (len >= 20) &&
...@@ -128,148 +130,145 @@ bool STUNMessage::IsSTUN(const MS_BYTE* data, size_t len) { ...@@ -128,148 +130,145 @@ bool STUNMessage::IsSTUN(const MS_BYTE* data, size_t len) {
(data[6] == STUNMessage::magicCookie[2]) && (data[6] == STUNMessage::magicCookie[2]) &&
(data[7] == STUNMessage::magicCookie[3]) (data[7] == STUNMessage::magicCookie[3])
); );
} }
inline
inline STUNMessage::Class STUNMessage::GetClass()
STUNMessage::Class STUNMessage::GetClass() { {
return this->klass; return this->klass;
} }
inline inline
STUNMessage::Method STUNMessage::GetMethod() { STUNMessage::Method STUNMessage::GetMethod()
{
return this->method; return this->method;
} }
inline
inline const MS_BYTE* STUNMessage::GetRaw()
const MS_BYTE* STUNMessage::GetRaw() { {
return this->raw; return this->raw;
} }
inline inline
void STUNMessage::SetLength(size_t length) { void STUNMessage::SetLength(size_t length)
{
this->length = length; this->length = length;
} }
inline
inline size_t STUNMessage::GetLength()
size_t STUNMessage::GetLength() { {
return this->length; return this->length;
} }
inline inline
void STUNMessage::SetUsername(const char* username, size_t len) { void STUNMessage::SetUsername(const char* username, size_t len)
{
if (this->username.empty()) if (this->username.empty())
this->username = std::string(username, len); this->username = std::string(username, len);
} }
inline
inline void STUNMessage::SetPriority(const MS_4BYTES priority)
void STUNMessage::SetPriority(const MS_4BYTES priority) { {
if (! this->priority) if (!this->priority)
this->priority = priority; this->priority = priority;
} }
inline inline
void STUNMessage::SetIceControlling(const MS_8BYTES iceControlling) { void STUNMessage::SetIceControlling(const MS_8BYTES iceControlling)
if (! this->iceControlling) {
if (!this->iceControlling)
this->iceControlling = iceControlling; this->iceControlling = iceControlling;
} }
inline
inline void STUNMessage::SetIceControlled(const MS_8BYTES iceControlled)
void STUNMessage::SetIceControlled(const MS_8BYTES iceControlled) { {
if (! this->iceControlled) if (!this->iceControlled)
this->iceControlled = iceControlled; this->iceControlled = iceControlled;
} }
inline inline
void STUNMessage::SetUseCandidate() { void STUNMessage::SetUseCandidate()
{
this->hasUseCandidate = true; this->hasUseCandidate = true;
} }
inline
inline void STUNMessage::SetXorMappedAddress(const struct sockaddr* xorMappedAddress)
void STUNMessage::SetXorMappedAddress(const struct sockaddr* xorMappedAddress) { {
if (! this->xorMappedAddress) if (!this->xorMappedAddress)
this->xorMappedAddress = xorMappedAddress; this->xorMappedAddress = xorMappedAddress;
} }
inline inline
void STUNMessage::SetErrorCode(MS_2BYTES errorCode) { void STUNMessage::SetErrorCode(MS_2BYTES errorCode)
{
this->errorCode = errorCode; this->errorCode = errorCode;
} }
inline
inline void STUNMessage::SetMessageIntegrity(const MS_BYTE* messageIntegrity)
void STUNMessage::SetMessageIntegrity(const MS_BYTE* messageIntegrity) { {
if (! this->messageIntegrity) if (!this->messageIntegrity)
this->messageIntegrity = messageIntegrity; this->messageIntegrity = messageIntegrity;
} }
inline inline
void STUNMessage::SetFingerprint() { void STUNMessage::SetFingerprint()
{
this->hasFingerprint = true; this->hasFingerprint = true;
} }
inline
inline const std::string& STUNMessage::GetUsername()
const std::string& STUNMessage::GetUsername() { {
return this->username; return this->username;
} }
inline inline
const MS_4BYTES STUNMessage::GetPriority() { const MS_4BYTES STUNMessage::GetPriority()
{
return this->priority; return this->priority;
} }
inline
inline const MS_8BYTES STUNMessage::GetIceControlling()
const MS_8BYTES STUNMessage::GetIceControlling() { {
return this->iceControlling; return this->iceControlling;
} }
inline inline
const MS_8BYTES STUNMessage::GetIceControlled() { const MS_8BYTES STUNMessage::GetIceControlled()
{
return this->iceControlled; return this->iceControlled;
} }
inline
inline bool STUNMessage::HasUseCandidate()
bool STUNMessage::HasUseCandidate() { {
return this->hasUseCandidate; return this->hasUseCandidate;
} }
inline inline
MS_2BYTES STUNMessage::GetErrorCode() { MS_2BYTES STUNMessage::GetErrorCode()
{
return this->errorCode; return this->errorCode;
} }
inline
inline bool STUNMessage::HasMessageIntegrity()
bool STUNMessage::HasMessageIntegrity() { {
return (this->messageIntegrity ? true : false); return (this->messageIntegrity ? true : false);
} }
inline inline
bool STUNMessage::HasFingerprint() { bool STUNMessage::HasFingerprint()
{
return this->hasFingerprint; return this->hasFingerprint;
} }
} // namespace RTC } // namespace RTC
#endif #endif
#ifndef MS_RTC_STREAM_H #ifndef MS_RTC_STREAM_H
#define MS_RTC_STREAM_H #define MS_RTC_STREAM_H
#include "common.h" #include "common.h"
#include "RTC/RTPPacket.h" #include "RTC/RTPPacket.h"
#include "RTC/RTCPPacket.h" #include "RTC/RTCPPacket.h"
#include <unordered_set> #include <unordered_set>
namespace RTC
namespace RTC { {
class Stream
{
class Stream { public:
public:
Stream(); Stream();
~Stream(); ~Stream();
void Close(); void Close();
private: private:
MS_4BYTES ssrc = 0; MS_4BYTES ssrc = 0;
std::unordered_set<MS_BYTE> payloads; std::unordered_set<MS_BYTE> payloads;
}; };
} // namespace RTC } // namespace RTC
#endif #endif
#ifndef MS_RTC_TCP_CONNECTION_H #ifndef MS_RTC_TCP_CONNECTION_H
#define MS_RTC_TCP_CONNECTION_H #define MS_RTC_TCP_CONNECTION_H
#include "common.h" #include "common.h"
#include "handles/TCPConnection.h" #include "handles/TCPConnection.h"
namespace RTC
namespace RTC { {
class TCPConnection : public ::TCPConnection
{
class TCPConnection : public ::TCPConnection { public:
public: class Reader
class Reader { {
public: public:
virtual void onSTUNDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) = 0; virtual void onSTUNDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) = 0;
virtual void onDTLSDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) = 0; virtual void onDTLSDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) = 0;
...@@ -19,25 +18,22 @@ public: ...@@ -19,25 +18,22 @@ public:
virtual void onRTCPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) = 0; virtual void onRTCPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) = 0;
}; };
public: public:
TCPConnection(Reader* reader, size_t bufferSize); TCPConnection(Reader* reader, size_t bufferSize);
virtual ~TCPConnection(); virtual ~TCPConnection();
void Send(const MS_BYTE* data, size_t len); void Send(const MS_BYTE* data, size_t len);
/* Pure virtual methods inherited from ::TCPConnection. */ /* Pure virtual methods inherited from ::TCPConnection. */
public: public:
virtual void userOnTCPConnectionRead(const MS_BYTE* data, size_t len) override; virtual void userOnTCPConnectionRead(const MS_BYTE* data, size_t len) override;
private: private:
// Passed by argument: // Passed by argument:
Reader* reader = nullptr; Reader* reader = nullptr;
// Others: // Others:
size_t frameStart = 0; // Where the latest frame starts. size_t frameStart = 0; // Where the latest frame starts.
}; };
} // namespace RTC } // namespace RTC
#endif #endif
#ifndef MS_RTC_TCP_SERVER_H #ifndef MS_RTC_TCP_SERVER_H
#define MS_RTC_TCP_SERVER_H #define MS_RTC_TCP_SERVER_H
#include "common.h" #include "common.h"
#include "handles/TCPServer.h" #include "handles/TCPServer.h"
#include "handles/TCPConnection.h" #include "handles/TCPConnection.h"
...@@ -9,26 +8,26 @@ ...@@ -9,26 +8,26 @@
#include <unordered_map> #include <unordered_map>
#include <uv.h> #include <uv.h>
namespace RTC
namespace RTC { {
class TCPServer : public ::TCPServer
{
class TCPServer : public ::TCPServer { public:
public: class Listener
class Listener { {
public: public:
virtual void onRTCTCPConnectionClosed(RTC::TCPServer* tcpServer, RTC::TCPConnection* connection, bool is_closed_by_peer) = 0; virtual void onRTCTCPConnectionClosed(RTC::TCPServer* tcpServer, RTC::TCPConnection* connection, bool is_closed_by_peer) = 0;
}; };
public: public:
static void ClassInit(); static void ClassInit();
static RTC::TCPServer* New(int address_family); static RTC::TCPServer* New(int address_family);
static void NewPair(int address_family, RTC::TCPServer* servers[]); static void NewPair(int address_family, RTC::TCPServer* servers[]);
private: private:
static void RandomizePort(int address_family, uv_tcp_t* uvHandles[], bool pair); static void RandomizePort(int address_family, uv_tcp_t* uvHandles[], bool pair);
private: private:
static struct sockaddr_storage sockaddrStorageIPv4; static struct sockaddr_storage sockaddrStorageIPv4;
static struct sockaddr_storage sockaddrStorageIPv6; static struct sockaddr_storage sockaddrStorageIPv6;
static MS_PORT minPort; static MS_PORT minPort;
...@@ -37,35 +36,32 @@ private: ...@@ -37,35 +36,32 @@ private:
static AvailablePorts availableIPv4Ports; static AvailablePorts availableIPv4Ports;
static AvailablePorts availableIPv6Ports; static AvailablePorts availableIPv6Ports;
public: public:
TCPServer(uv_tcp_t* uvHandle); TCPServer(uv_tcp_t* uvHandle);
void SetListeners(Listener* listener, RTC::TCPConnection::Reader* reader); void SetListeners(Listener* listener, RTC::TCPConnection::Reader* reader);
/* Pure virtual methods inherited from ::TCPServer. */ /* Pure virtual methods inherited from ::TCPServer. */
public: public:
virtual void userOnTCPConnectionAlloc(::TCPConnection** connection) override; virtual void userOnTCPConnectionAlloc(::TCPConnection** connection) override;
virtual void userOnNewTCPConnection(::TCPConnection* connection) override; virtual void userOnNewTCPConnection(::TCPConnection* connection) override;
virtual void userOnTCPConnectionClosed(::TCPConnection* connection, bool is_closed_by_peer) override; virtual void userOnTCPConnectionClosed(::TCPConnection* connection, bool is_closed_by_peer) override;
virtual void userOnTCPServerClosed() override; virtual void userOnTCPServerClosed() override;
private: private:
// Passed by argument: // Passed by argument:
Listener* listener = nullptr; Listener* listener = nullptr;
RTC::TCPConnection::Reader* reader = nullptr; RTC::TCPConnection::Reader* reader = nullptr;
}; };
/* Inline methods. */ /* Inline methods. */
inline inline
void TCPServer::SetListeners(Listener* listener, RTC::TCPConnection::Reader* reader) { void TCPServer::SetListeners(Listener* listener, RTC::TCPConnection::Reader* reader)
{
this->listener = listener; this->listener = listener;
this->reader = reader; this->reader = reader;
} }
} // namespace RTC } // namespace RTC
#endif #endif
差异被折叠。
#ifndef MS_RTC_TRANSPORT_SOURCE_H #ifndef MS_RTC_TRANSPORT_SOURCE_H
#define MS_RTC_TRANSPORT_SOURCE_H #define MS_RTC_TRANSPORT_SOURCE_H
#include "common.h" #include "common.h"
#include "RTC/UDPSocket.h" #include "RTC/UDPSocket.h"
#include "RTC/TCPConnection.h" #include "RTC/TCPConnection.h"
#include "Utils.h" #include "Utils.h"
#include <string> #include <string>
namespace RTC
namespace RTC { {
class TransportSource
{
class TransportSource { public:
public: enum class Type
enum class Type { {
UDP = 1, UDP = 1,
TCP TCP
}; };
public: public:
TransportSource(RTC::UDPSocket* udpSocket, const struct sockaddr* udpRemoteAddr); TransportSource(RTC::UDPSocket* udpSocket, const struct sockaddr* udpRemoteAddr);
TransportSource(RTC::TCPConnection* tcpConnection); TransportSource(RTC::TCPConnection* tcpConnection);
...@@ -32,7 +31,7 @@ public: ...@@ -32,7 +31,7 @@ public:
void Close(); void Close();
void Dump(); void Dump();
private: private:
// Passed by argument: // Passed by argument:
RTC::UDPSocket* udpSocket = nullptr; RTC::UDPSocket* udpSocket = nullptr;
struct sockaddr* udpRemoteAddr = nullptr; struct sockaddr* udpRemoteAddr = nullptr;
...@@ -40,87 +39,85 @@ private: ...@@ -40,87 +39,85 @@ private:
RTC::TCPConnection* tcpConnection = nullptr; RTC::TCPConnection* tcpConnection = nullptr;
// Others: // Others:
Type type; Type type;
}; };
/* Inline methods. */ /* Inline methods. */
inline inline
TransportSource::TransportSource(RTC::UDPSocket* udpSocket, const struct sockaddr* udpRemoteAddr) : TransportSource::TransportSource(RTC::UDPSocket* udpSocket, const struct sockaddr* udpRemoteAddr) :
udpSocket(udpSocket), udpSocket(udpSocket),
udpRemoteAddr((struct sockaddr*)udpRemoteAddr), udpRemoteAddr((struct sockaddr*)udpRemoteAddr),
type(Type::UDP) type(Type::UDP)
{} {}
inline inline
TransportSource::TransportSource(RTC::TCPConnection* tcpConnection) : TransportSource::TransportSource(RTC::TCPConnection* tcpConnection) :
tcpConnection(tcpConnection), tcpConnection(tcpConnection),
type(Type::TCP) type(Type::TCP)
{} {}
inline
inline void TransportSource::StoreUdpRemoteAddress()
void TransportSource::StoreUdpRemoteAddress() { {
// Clone the given address into our address storage and make the sockaddr // Clone the given address into our address storage and make the sockaddr
// pointer point to it. // pointer point to it.
this->udpRemoteAddrStorage = Utils::IP::CopyAddress(udpRemoteAddr); this->udpRemoteAddrStorage = Utils::IP::CopyAddress(udpRemoteAddr);
this->udpRemoteAddr = (struct sockaddr*)&this->udpRemoteAddrStorage; this->udpRemoteAddr = (struct sockaddr*)&this->udpRemoteAddrStorage;
} }
inline inline
bool TransportSource::IsUDP() { bool TransportSource::IsUDP()
{
return (this->type == Type::UDP); return (this->type == Type::UDP);
} }
inline inline
bool TransportSource::IsTCP() { bool TransportSource::IsTCP()
{
return (this->type == Type::TCP); return (this->type == Type::TCP);
} }
inline inline
bool TransportSource::Compare(TransportSource* source) { bool TransportSource::Compare(TransportSource* source)
if (this->type == Type::UDP && source->IsUDP()) { {
if (this->type == Type::UDP && source->IsUDP())
{
return (this->udpSocket == source->udpSocket && Utils::IP::CompareAddresses(this->udpRemoteAddr, source->GetRemoteAddress())); return (this->udpSocket == source->udpSocket && Utils::IP::CompareAddresses(this->udpRemoteAddr, source->GetRemoteAddress()));
} }
else if (this->type == Type::TCP && source->IsTCP()) { else if (this->type == Type::TCP && source->IsTCP())
{
return (this->tcpConnection == source->tcpConnection); return (this->tcpConnection == source->tcpConnection);
} }
else { else
{
return false; return false;
} }
} }
inline inline
void TransportSource::Send(const MS_BYTE* data, size_t len) { void TransportSource::Send(const MS_BYTE* data, size_t len)
{
if (this->type == Type::UDP) if (this->type == Type::UDP)
this->udpSocket->Send(data, len, this->udpRemoteAddr); this->udpSocket->Send(data, len, this->udpRemoteAddr);
else else
this->tcpConnection->Send(data, len); this->tcpConnection->Send(data, len);
} }
inline inline
const struct sockaddr* TransportSource::GetRemoteAddress() { const struct sockaddr* TransportSource::GetRemoteAddress()
{
if (this->type == Type::UDP) if (this->type == Type::UDP)
return (const struct sockaddr*)this->udpRemoteAddr; return (const struct sockaddr*)this->udpRemoteAddr;
else else
return this->tcpConnection->GetPeerAddress(); return this->tcpConnection->GetPeerAddress();
} }
inline inline
void TransportSource::Close() { void TransportSource::Close()
{
if (this->type == Type::TCP) if (this->type == Type::TCP)
this->tcpConnection->Close(); this->tcpConnection->Close();
} }
} // namespace RTC } // namespace RTC
#endif #endif
#ifndef MS_RTC_UDP_SOCKET_H #ifndef MS_RTC_UDP_SOCKET_H
#define MS_RTC_UDP_SOCKET_H #define MS_RTC_UDP_SOCKET_H
#include "common.h" #include "common.h"
#include "handles/UDPSocket.h" #include "handles/UDPSocket.h"
#include <unordered_map> #include <unordered_map>
#include <uv.h> #include <uv.h>
namespace RTC
namespace RTC { {
class UDPSocket : public ::UDPSocket
{
class UDPSocket : public ::UDPSocket { public:
public: class Listener
class Listener { {
public: public:
virtual void onSTUNDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) = 0; virtual void onSTUNDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) = 0;
virtual void onDTLSDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) = 0; virtual void onDTLSDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) = 0;
...@@ -21,15 +20,15 @@ public: ...@@ -21,15 +20,15 @@ public:
virtual void onRTCPDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) = 0; virtual void onRTCPDataRecv(RTC::UDPSocket *socket, const MS_BYTE* data, size_t len, const struct sockaddr* remote_addr) = 0;
}; };
public: public:
static void ClassInit(); static void ClassInit();
static RTC::UDPSocket* New(int address_family); static RTC::UDPSocket* New(int address_family);
static void NewPair(int address_family, RTC::UDPSocket* sockets[]); static void NewPair(int address_family, RTC::UDPSocket* sockets[]);
private: private:
static void RandomizePort(int address_family, uv_udp_t* uvHandles[], bool pair); static void RandomizePort(int address_family, uv_udp_t* uvHandles[], bool pair);
private: private:
static struct sockaddr_storage sockaddrStorageIPv4; static struct sockaddr_storage sockaddrStorageIPv4;
static struct sockaddr_storage sockaddrStorageIPv6; static struct sockaddr_storage sockaddrStorageIPv6;
static MS_PORT minPort; static MS_PORT minPort;
...@@ -38,31 +37,28 @@ private: ...@@ -38,31 +37,28 @@ private:
static AvailablePorts availableIPv4Ports; static AvailablePorts availableIPv4Ports;
static AvailablePorts availableIPv6Ports; static AvailablePorts availableIPv6Ports;
public: public:
UDPSocket(uv_udp_t* uvHandle); UDPSocket(uv_udp_t* uvHandle);
void SetListener(Listener* listener); void SetListener(Listener* listener);
/* Pure virtual methods inherited from ::UDPSocket. */ /* Pure virtual methods inherited from ::UDPSocket. */
public: public:
virtual void userOnUDPDatagramRecv(const MS_BYTE* data, size_t len, const struct sockaddr* addr) override; virtual void userOnUDPDatagramRecv(const MS_BYTE* data, size_t len, const struct sockaddr* addr) override;
virtual void userOnUDPSocketClosed() override; virtual void userOnUDPSocketClosed() override;
private: private:
// Passed by argument: // Passed by argument:
Listener* listener = nullptr; Listener* listener = nullptr;
}; };
/* Inline methods. */ /* Inline methods. */
inline inline
void UDPSocket::SetListener(Listener* listener) { void UDPSocket::SetListener(Listener* listener)
{
this->listener = listener; this->listener = listener;
} }
} // namespace RTC } // namespace RTC
#endif #endif
#ifndef MS_SETTINGS_H #ifndef MS_SETTINGS_H
#define MS_SETTINGS_H #define MS_SETTINGS_H
#include "common.h" #include "common.h"
#include <map> #include <map>
#include <string> #include <string>
#include <vector> #include <vector>
#include <libconfig.h++> #include <libconfig.h++>
extern "C" { extern "C"
{
#include <syslog.h> #include <syslog.h>
} }
class Settings
class Settings { {
public: public:
// Struct holding command line arguments. // Struct holding command line arguments.
struct Arguments { struct Arguments
{
std::string configFile; std::string configFile;
bool daemonize { false }; bool daemonize { false };
std::string pidFile; std::string pidFile;
...@@ -24,17 +25,20 @@ public: ...@@ -24,17 +25,20 @@ public:
}; };
// Struct holding the configuration (can be overriden by a config file). // Struct holding the configuration (can be overriden by a config file).
struct Configuration { struct Configuration
{
unsigned int logLevel { LOG_DEBUG }; unsigned int logLevel { LOG_DEBUG };
unsigned int syslogFacility { LOG_USER }; unsigned int syslogFacility { LOG_USER };
int numWorkers { 0 }; int numWorkers { 0 };
struct { struct
{
std::string listenIP { "127.0.0.1" }; std::string listenIP { "127.0.0.1" };
MS_PORT listenPort { 4080 }; MS_PORT listenPort { 4080 };
} ControlProtocol; } ControlProtocol;
struct { struct
{
std::string listenIPv4; std::string listenIPv4;
std::string listenIPv6; std::string listenIPv6;
MS_PORT minPort { 10000 }; MS_PORT minPort { 10000 };
...@@ -83,5 +87,4 @@ private: ...@@ -83,5 +87,4 @@ private:
static std::map<unsigned int, std::string> syslogFacility2String; static std::map<unsigned int, std::string> syslogFacility2String;
}; };
#endif #endif
#ifndef MS_UTILS_H #ifndef MS_UTILS_H
#define MS_UTILS_H #define MS_UTILS_H
#include "common.h" #include "common.h"
#include <string> #include <string>
#include <cstring> // std::memcmp(), std::memcpy() #include <cstring> // std::memcmp(), std::memcpy()
#include <openssl/hmac.h> #include <openssl/hmac.h>
namespace Utils
namespace Utils { {
class IP
{
class IP { public:
public:
static int GetFamily(const char *ip, size_t ip_len); static int GetFamily(const char *ip, size_t ip_len);
static int GetFamily(const std::string &ip); static int GetFamily(const std::string &ip);
static void GetAddressInfo(const struct sockaddr* addr, int* family, std::string &ip, MS_PORT* port); static void GetAddressInfo(const struct sockaddr* addr, int* family, std::string &ip, MS_PORT* port);
static bool CompareAddresses(const struct sockaddr* addr1, const struct sockaddr* addr2); static bool CompareAddresses(const struct sockaddr* addr1, const struct sockaddr* addr2);
static struct sockaddr_storage CopyAddress(const struct sockaddr* addr); static struct sockaddr_storage CopyAddress(const struct sockaddr* addr);
}; };
/* Inline static methods. */ /* Inline static methods. */
inline inline
int IP::GetFamily(const std::string &ip) { int IP::GetFamily(const std::string &ip)
{
return GetFamily(ip.c_str(), ip.size()); return GetFamily(ip.c_str(), ip.size());
} }
inline inline
bool IP::CompareAddresses(const struct sockaddr* addr1, const struct sockaddr* addr2) { bool IP::CompareAddresses(const struct sockaddr* addr1, const struct sockaddr* addr2)
{
// Compare family. // Compare family.
if (addr1->sa_family != addr2->sa_family || (addr1->sa_family != AF_INET && addr1->sa_family != AF_INET6)) if (addr1->sa_family != addr2->sa_family || (addr1->sa_family != AF_INET && addr1->sa_family != AF_INET6))
return false; return false;
...@@ -40,7 +38,8 @@ bool IP::CompareAddresses(const struct sockaddr* addr1, const struct sockaddr* a ...@@ -40,7 +38,8 @@ bool IP::CompareAddresses(const struct sockaddr* addr1, const struct sockaddr* a
return false; return false;
// Compare IP. // Compare IP.
switch(addr1->sa_family) { switch (addr1->sa_family)
{
case AF_INET: case AF_INET:
if (std::memcmp(&((struct sockaddr_in*)addr1)->sin_addr, &((struct sockaddr_in*)addr2)->sin_addr, 4) == 0) if (std::memcmp(&((struct sockaddr_in*)addr1)->sin_addr, &((struct sockaddr_in*)addr2)->sin_addr, 4) == 0)
return true; return true;
...@@ -54,14 +53,15 @@ bool IP::CompareAddresses(const struct sockaddr* addr1, const struct sockaddr* a ...@@ -54,14 +53,15 @@ bool IP::CompareAddresses(const struct sockaddr* addr1, const struct sockaddr* a
} }
return false; return false;
} }
inline inline
struct sockaddr_storage IP::CopyAddress(const struct sockaddr* addr) { struct sockaddr_storage IP::CopyAddress(const struct sockaddr* addr)
{
struct sockaddr_storage copied_addr; struct sockaddr_storage copied_addr;
switch(addr->sa_family) { switch (addr->sa_family)
{
case AF_INET: case AF_INET:
std::memcpy(&copied_addr, addr, sizeof(struct sockaddr_in)); std::memcpy(&copied_addr, addr, sizeof(struct sockaddr_in));
break; break;
...@@ -71,11 +71,11 @@ struct sockaddr_storage IP::CopyAddress(const struct sockaddr* addr) { ...@@ -71,11 +71,11 @@ struct sockaddr_storage IP::CopyAddress(const struct sockaddr* addr) {
} }
return copied_addr; return copied_addr;
} }
class Socket { class Socket
public: {
public:
/** /**
* Builds a pair of connected sockets. The sockets are created in non-blocking * Builds a pair of connected sockets. The sockets are created in non-blocking
* mode and with close-exec (so they are closed after fork()). * mode and with close-exec (so they are closed after fork()).
...@@ -88,20 +88,20 @@ public: ...@@ -88,20 +88,20 @@ public:
*/ */
static void BuildSocketPair(int family, int type, int* fds); static void BuildSocketPair(int family, int type, int* fds);
private: private:
static bool SetNonBlock(int fd); static bool SetNonBlock(int fd);
static bool SetCloExec(int fd); static bool SetCloExec(int fd);
}; };
class File { class File
public: {
public:
static void CheckFile(const char* file); static void CheckFile(const char* file);
}; };
class Byte { class Byte
public: {
public:
/** /**
* All these functions get and set bytes in Network Byte Order (Big Endian). * All these functions get and set bytes in Network Byte Order (Big Endian).
*/ */
...@@ -117,73 +117,73 @@ public: ...@@ -117,73 +117,73 @@ public:
static void Set8Bytes(MS_BYTE* data, size_t i, MS_8BYTES value); static void Set8Bytes(MS_BYTE* data, size_t i, MS_8BYTES value);
static MS_2BYTES PadTo4Bytes(MS_2BYTES size); static MS_2BYTES PadTo4Bytes(MS_2BYTES size);
static MS_4BYTES PadTo4Bytes(MS_4BYTES size); static MS_4BYTES PadTo4Bytes(MS_4BYTES size);
}; };
/* Inline static methods. */ /* Inline static methods. */
inline inline
MS_BYTE Byte::Get1Byte(const MS_BYTE* data, size_t i) { MS_BYTE Byte::Get1Byte(const MS_BYTE* data, size_t i)
{
return data[i]; return data[i];
} }
inline inline
MS_2BYTES Byte::Get2Bytes(const MS_BYTE* data, size_t i) { MS_2BYTES Byte::Get2Bytes(const MS_BYTE* data, size_t i)
{
return (MS_2BYTES)(data[i+1]) | ((MS_2BYTES)(data[i]))<<8; return (MS_2BYTES)(data[i+1]) | ((MS_2BYTES)(data[i]))<<8;
} }
inline inline
MS_4BYTES Byte::Get3Bytes(const MS_BYTE* data, size_t i) { MS_4BYTES Byte::Get3Bytes(const MS_BYTE* data, size_t i)
{
return (MS_4BYTES)(data[i+2]) | ((MS_4BYTES)(data[i+1]))<<8 | ((MS_4BYTES)(data[i]))<<16; return (MS_4BYTES)(data[i+2]) | ((MS_4BYTES)(data[i+1]))<<8 | ((MS_4BYTES)(data[i]))<<16;
} }
inline inline
MS_4BYTES Byte::Get4Bytes(const MS_BYTE* data, size_t i) { MS_4BYTES Byte::Get4Bytes(const MS_BYTE* data, size_t i)
{
return (MS_4BYTES)(data[i+3]) | ((MS_4BYTES)(data[i+2]))<<8 | ((MS_4BYTES)(data[i+1]))<<16 | ((MS_4BYTES)(data[i]))<<24; return (MS_4BYTES)(data[i+3]) | ((MS_4BYTES)(data[i+2]))<<8 | ((MS_4BYTES)(data[i+1]))<<16 | ((MS_4BYTES)(data[i]))<<24;
} }
inline inline
MS_8BYTES Byte::Get8Bytes(const MS_BYTE* data, size_t i) { MS_8BYTES Byte::Get8Bytes(const MS_BYTE* data, size_t i)
{
return ((MS_8BYTES)Byte::Get4Bytes(data,i))<<32 | Byte::Get4Bytes(data,i+4); return ((MS_8BYTES)Byte::Get4Bytes(data,i))<<32 | Byte::Get4Bytes(data,i+4);
} }
inline inline
void Byte::Set1Byte(MS_BYTE* data, size_t i, MS_BYTE value) { void Byte::Set1Byte(MS_BYTE* data, size_t i, MS_BYTE value)
{
data[i] = value; data[i] = value;
} }
inline inline
void Byte::Set2Bytes(MS_BYTE* data, size_t i, MS_2BYTES value) { void Byte::Set2Bytes(MS_BYTE* data, size_t i, MS_2BYTES value)
{
data[i+1] = (MS_BYTE)(value); data[i+1] = (MS_BYTE)(value);
data[i] = (MS_BYTE)(value>>8); data[i] = (MS_BYTE)(value>>8);
} }
inline inline
void Byte::Set3Bytes(MS_BYTE* data, size_t i, MS_4BYTES value) { void Byte::Set3Bytes(MS_BYTE* data, size_t i, MS_4BYTES value)
{
data[i+2] = (MS_BYTE)(value); data[i+2] = (MS_BYTE)(value);
data[i+1] = (MS_BYTE)(value>>8); data[i+1] = (MS_BYTE)(value>>8);
data[i] = (MS_BYTE)(value>>16); data[i] = (MS_BYTE)(value>>16);
} }
inline inline
void Byte::Set4Bytes(MS_BYTE* data, size_t i, MS_4BYTES value) { void Byte::Set4Bytes(MS_BYTE* data, size_t i, MS_4BYTES value)
{
data[i+3] = (MS_BYTE)(value); data[i+3] = (MS_BYTE)(value);
data[i+2] = (MS_BYTE)(value>>8); data[i+2] = (MS_BYTE)(value>>8);
data[i+1] = (MS_BYTE)(value>>16); data[i+1] = (MS_BYTE)(value>>16);
data[i] = (MS_BYTE)(value>>24); data[i] = (MS_BYTE)(value>>24);
} }
inline inline
void Byte::Set8Bytes(MS_BYTE* data, size_t i, MS_8BYTES value) { void Byte::Set8Bytes(MS_BYTE* data, size_t i, MS_8BYTES value)
{
data[i+7] = (MS_BYTE)(value); data[i+7] = (MS_BYTE)(value);
data[i+6] = (MS_BYTE)(value>>8); data[i+6] = (MS_BYTE)(value>>8);
data[i+5] = (MS_BYTE)(value>>16); data[i+5] = (MS_BYTE)(value>>16);
...@@ -192,31 +192,31 @@ void Byte::Set8Bytes(MS_BYTE* data, size_t i, MS_8BYTES value) { ...@@ -192,31 +192,31 @@ void Byte::Set8Bytes(MS_BYTE* data, size_t i, MS_8BYTES value) {
data[i+2] = (MS_BYTE)(value>>40); data[i+2] = (MS_BYTE)(value>>40);
data[i+1] = (MS_BYTE)(value>>48); data[i+1] = (MS_BYTE)(value>>48);
data[i] = (MS_BYTE)(value>>56); data[i] = (MS_BYTE)(value>>56);
} }
inline inline
MS_2BYTES Byte::PadTo4Bytes(MS_2BYTES size) { MS_2BYTES Byte::PadTo4Bytes(MS_2BYTES size)
{
// If size is not multiple of 32 bits then pad it. // If size is not multiple of 32 bits then pad it.
if (size & 0x03) if (size & 0x03)
return (size & 0xFFFC) + 4; return (size & 0xFFFC) + 4;
else else
return size; return size;
} }
inline inline
MS_4BYTES Byte::PadTo4Bytes(MS_4BYTES size) { MS_4BYTES Byte::PadTo4Bytes(MS_4BYTES size)
{
// If size is not multiple of 32 bits then pad it. // If size is not multiple of 32 bits then pad it.
if (size & 0x03) if (size & 0x03)
return (size & 0xFFFFFFFC) + 4; return (size & 0xFFFFFFFC) + 4;
else else
return size; return size;
} }
class Crypto { class Crypto
public: {
public:
static void ThreadInit(); static void ThreadInit();
static void ThreadDestroy(); static void ThreadDestroy();
static unsigned int GetRandomUInt(unsigned int min, unsigned int max); static unsigned int GetRandomUInt(unsigned int min, unsigned int max);
...@@ -224,18 +224,18 @@ public: ...@@ -224,18 +224,18 @@ public:
static MS_4BYTES CRC32(const MS_BYTE* data, size_t size); static MS_4BYTES CRC32(const MS_BYTE* data, size_t size);
static const MS_BYTE* HMAC_SHA1(const std::string &key, const MS_BYTE* data, size_t len); static const MS_BYTE* HMAC_SHA1(const std::string &key, const MS_BYTE* data, size_t len);
private: private:
static __thread unsigned int seed; static __thread unsigned int seed;
static __thread HMAC_CTX hmacSha1Ctx; static __thread HMAC_CTX hmacSha1Ctx;
static __thread MS_BYTE hmacSha1Buffer[]; static __thread MS_BYTE hmacSha1Buffer[];
static const MS_4BYTES crc32Table[256]; static const MS_4BYTES crc32Table[256];
}; };
/* Inline static methods. */ /* Inline static methods. */
inline inline
unsigned int Crypto::GetRandomUInt(unsigned int min, unsigned int max) { unsigned int Crypto::GetRandomUInt(unsigned int min, unsigned int max)
{
// NOTE: This is the original, but produces very small values. // NOTE: This is the original, but produces very small values.
// Crypto::seed = (214013 * Crypto::seed) + 2531011; // Crypto::seed = (214013 * Crypto::seed) + 2531011;
// return (((Crypto::seed>>16)&0x7FFF) % (max - min + 1)) + min; // return (((Crypto::seed>>16)&0x7FFF) % (max - min + 1)) + min;
...@@ -243,11 +243,11 @@ unsigned int Crypto::GetRandomUInt(unsigned int min, unsigned int max) { ...@@ -243,11 +243,11 @@ unsigned int Crypto::GetRandomUInt(unsigned int min, unsigned int max) {
// This seems to produce better results. // This seems to produce better results.
Crypto::seed = (unsigned int)((214013 * Crypto::seed) + 2531011); Crypto::seed = (unsigned int)((214013 * Crypto::seed) + 2531011);
return (((Crypto::seed>>4)&0x7FFF7FFF) % (max - min + 1)) + min; return (((Crypto::seed>>4)&0x7FFF7FFF) % (max - min + 1)) + min;
} }
inline inline
const char* Crypto::GetRandomHexString(char* buffer, size_t len) { const char* Crypto::GetRandomHexString(char* buffer, size_t len)
{
static const char hex_chars[] = { static const char hex_chars[] = {
'0','1','2','3','4','5','6','7','8','9', '0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','I','J', 'A','B','C','D','E','F','G','H','I','J',
...@@ -255,16 +255,15 @@ const char* Crypto::GetRandomHexString(char* buffer, size_t len) { ...@@ -255,16 +255,15 @@ const char* Crypto::GetRandomHexString(char* buffer, size_t len) {
'U','V','W','X','Y','Z' 'U','V','W','X','Y','Z'
}; };
for (size_t i = 0; i < len; ++i) { for (size_t i = 0; i < len; ++i)
buffer[i] = hex_chars[GetRandomUInt(0, sizeof(hex_chars) - 1)]; buffer[i] = hex_chars[GetRandomUInt(0, sizeof(hex_chars) - 1)];
}
return buffer; return buffer;
} }
inline inline
MS_4BYTES Crypto::CRC32(const MS_BYTE* data, size_t size) { MS_4BYTES Crypto::CRC32(const MS_BYTE* data, size_t size)
{
MS_4BYTES crc = 0xFFFFFFFF; MS_4BYTES crc = 0xFFFFFFFF;
const MS_BYTE* p = data; const MS_BYTE* p = data;
...@@ -272,10 +271,7 @@ MS_4BYTES Crypto::CRC32(const MS_BYTE* data, size_t size) { ...@@ -272,10 +271,7 @@ MS_4BYTES Crypto::CRC32(const MS_BYTE* data, size_t size) {
crc = Crypto::crc32Table[(crc ^ *p++) & 0xFF] ^ (crc >> 8); crc = Crypto::crc32Table[(crc ^ *p++) & 0xFF] ^ (crc >> 8);
return crc ^ ~0U; return crc ^ ~0U;
} }
} // namespace Utils } // namespace Utils
#endif
#endif /* MS_UTILS_H */
#ifndef MS_VERSION_H #ifndef MS_VERSION_H
#define MS_VERSION_H #define MS_VERSION_H
#include <string> #include <string>
class Version
class Version { {
public: public:
static const std::string GetVersion(); static const std::string GetVersion();
static const std::string GetNameAndVersion(); static const std::string GetNameAndVersion();
...@@ -19,5 +18,4 @@ public: ...@@ -19,5 +18,4 @@ public:
static const std::string copyright; static const std::string copyright;
}; };
#endif #endif
#ifndef MS_WORKER_H #ifndef MS_WORKER_H
#define MS_WORKER_H #define MS_WORKER_H
#include "common.h" #include "common.h"
#include "ControlProtocol/UnixStreamSocket.h" #include "ControlProtocol/UnixStreamSocket.h"
#include "ControlProtocol/Message.h" #include "ControlProtocol/Message.h"
...@@ -10,7 +9,6 @@ ...@@ -10,7 +9,6 @@
// TMP // TMP
#include "RTC/Room.h" #include "RTC/Room.h"
class Worker : class Worker :
public ControlProtocol::UnixStreamSocket::Listener public ControlProtocol::UnixStreamSocket::Listener
{ {
...@@ -53,5 +51,4 @@ private: ...@@ -53,5 +51,4 @@ private:
RTC::Room* room = nullptr; RTC::Room* room = nullptr;
}; };
#endif #endif
#ifndef MS_COMMON_H #ifndef MS_COMMON_H
#define MS_COMMON_H #define MS_COMMON_H
#include <cstddef> // size_t #include <cstddef> // size_t
#include <cstdint> // uint8_t, etc #include <cstdint> // uint8_t, etc
#include <sys/socket.h> // struct sockaddr, struct sockaddr_storage, AF_INET, AF_INET6 #include <sys/socket.h> // struct sockaddr, struct sockaddr_storage, AF_INET, AF_INET6
...@@ -9,14 +8,12 @@ ...@@ -9,14 +8,12 @@
#include <arpa/inet.h> // htonl(), htons(), ntohl(), ntohs() #include <arpa/inet.h> // htonl(), htons(), ntohl(), ntohs()
#include <pthread.h> // __thread #include <pthread.h> // __thread
#define MS_BYTE uint8_t #define MS_BYTE uint8_t
#define MS_2BYTES uint16_t #define MS_2BYTES uint16_t
#define MS_4BYTES uint32_t #define MS_4BYTES uint32_t
#define MS_8BYTES uint64_t #define MS_8BYTES uint64_t
#define MS_PORT uint16_t #define MS_PORT uint16_t
// Detect Little-Endian or Big-Endian CPU. // Detect Little-Endian or Big-Endian CPU.
// NOTE: If the macro MS_LITTLE_ENDIAN or MS_BIG_ENDIAN is already defined // NOTE: If the macro MS_LITTLE_ENDIAN or MS_BIG_ENDIAN is already defined
// then don't autodetect it. // then don't autodetect it.
......
#ifndef MS_SIGNALS_HANDLER_H #ifndef MS_SIGNALS_HANDLER_H
#define MS_SIGNALS_HANDLER_H #define MS_SIGNALS_HANDLER_H
#include <vector> #include <vector>
#include <string> #include <string>
#include <uv.h> #include <uv.h>
class SignalsHandler
class SignalsHandler { {
public: public:
class Listener { class Listener
{
public: public:
virtual void onSignal(SignalsHandler* signalsHandler, int signum) = 0; virtual void onSignal(SignalsHandler* signalsHandler, int signum) = 0;
virtual void onSignalsHandlerClosed(SignalsHandler* signalsHandler) = 0; virtual void onSignalsHandlerClosed(SignalsHandler* signalsHandler) = 0;
...@@ -33,5 +33,4 @@ private: ...@@ -33,5 +33,4 @@ private:
Listener* listener = nullptr; Listener* listener = nullptr;
}; };
#endif #endif
#ifndef MS_TCP_CONNECTION_H #ifndef MS_TCP_CONNECTION_H
#define MS_TCP_CONNECTION_H #define MS_TCP_CONNECTION_H
#include "common.h" #include "common.h"
#include <string> #include <string>
#include <uv.h> #include <uv.h>
class TCPConnection
class TCPConnection { {
public: public:
class Listener { class Listener
{
public: public:
virtual void onTCPConnectionClosed(TCPConnection* connection, bool is_closed_by_peer) = 0; virtual void onTCPConnectionClosed(TCPConnection* connection, bool is_closed_by_peer) = 0;
}; };
public: public:
/* Struct for the data field of uv_req_t when writing into the connection. */ /* Struct for the data field of uv_req_t when writing into the connection. */
typedef struct UvWriteData { typedef struct UvWriteData
{
TCPConnection* connection; TCPConnection* connection;
uv_write_t req; uv_write_t req;
MS_BYTE store[1]; MS_BYTE store[1];
...@@ -82,61 +83,60 @@ protected: ...@@ -82,61 +83,60 @@ protected:
MS_PORT peerPort = 0; MS_PORT peerPort = 0;
}; };
/* Inline methods. */ /* Inline methods. */
inline inline
uv_tcp_t* TCPConnection::GetUvHandle() { uv_tcp_t* TCPConnection::GetUvHandle()
{
return this->uvHandle; return this->uvHandle;
} }
inline inline
void TCPConnection::Write(const std::string &data) { void TCPConnection::Write(const std::string &data)
{
Write((const MS_BYTE*)data.c_str(), data.size()); Write((const MS_BYTE*)data.c_str(), data.size());
} }
inline inline
const std::string& TCPConnection::GetLocalIP() { const std::string& TCPConnection::GetLocalIP()
{
return this->localIP; return this->localIP;
} }
inline inline
MS_PORT TCPConnection::GetLocalPort() { MS_PORT TCPConnection::GetLocalPort()
{
return this->localPort; return this->localPort;
} }
inline inline
const struct sockaddr* TCPConnection::GetPeerAddress() { const struct sockaddr* TCPConnection::GetPeerAddress()
{
return (const struct sockaddr*)&this->peerAddr; return (const struct sockaddr*)&this->peerAddr;
} }
inline inline
const std::string& TCPConnection::GetPeerIP() { const std::string& TCPConnection::GetPeerIP()
{
return this->peerIP; return this->peerIP;
} }
inline inline
MS_PORT TCPConnection::GetPeerPort() { MS_PORT TCPConnection::GetPeerPort()
{
return this->peerPort; return this->peerPort;
} }
inline inline
void TCPConnection::SetUserData(void* userData) { void TCPConnection::SetUserData(void* userData)
{
this->userData = userData; this->userData = userData;
} }
inline inline
void* TCPConnection::GetUserData() { void* TCPConnection::GetUserData()
{
return this->userData; return this->userData;
} }
#endif #endif
#ifndef MS_TCP_SERVER_H #ifndef MS_TCP_SERVER_H
#define MS_TCP_SERVER_H #define MS_TCP_SERVER_H
#include "common.h" #include "common.h"
#include "handles/TCPConnection.h" #include "handles/TCPConnection.h"
#include <string> #include <string>
#include <unordered_set> #include <unordered_set>
#include <uv.h> #include <uv.h>
class TCPServer : public TCPConnection::Listener
class TCPServer : public TCPConnection::Listener { {
public: public:
TCPServer(const std::string &ip, MS_PORT port, int backlog); TCPServer(const std::string &ip, MS_PORT port, int backlog);
/** /**
...@@ -63,31 +62,30 @@ protected: ...@@ -63,31 +62,30 @@ protected:
MS_PORT localPort = 0; MS_PORT localPort = 0;
}; };
/* Inline methods. */ /* Inline methods. */
inline inline
void TCPServer::SetUserData(void* userData) { void TCPServer::SetUserData(void* userData)
{
this->userData = userData; this->userData = userData;
} }
inline inline
void* TCPServer::GetUserData() { void* TCPServer::GetUserData()
{
return this->userData; return this->userData;
} }
inline inline
size_t TCPServer::GetNumConnections() { size_t TCPServer::GetNumConnections()
{
return this->connections.size(); return this->connections.size();
} }
inline inline
bool TCPServer::IsClosing() { bool TCPServer::IsClosing()
{
return this->isClosing; return this->isClosing;
} }
#endif #endif
#ifndef MS_TIMER_H #ifndef MS_TIMER_H
#define MS_TIMER_H #define MS_TIMER_H
#include "common.h" #include "common.h"
#include <uv.h> #include <uv.h>
class Timer
class Timer { {
public: public:
class Listener { class Listener
{
public: public:
virtual void onTimer(Timer* timer) = 0; virtual void onTimer(Timer* timer) = 0;
}; };
...@@ -31,5 +31,4 @@ private: ...@@ -31,5 +31,4 @@ private:
Listener* listener = nullptr; Listener* listener = nullptr;
}; };
#endif #endif
#ifndef MS_UDP_SOCKET_H #ifndef MS_UDP_SOCKET_H
#define MS_UDP_SOCKET_H #define MS_UDP_SOCKET_H
#include "common.h" #include "common.h"
#include <string> #include <string>
#include <uv.h> #include <uv.h>
class UDPSocket
class UDPSocket { {
public: public:
/* Struct for the data field of uv_req_t when sending a datagram. */ /* Struct for the data field of uv_req_t when sending a datagram. */
typedef struct UvSendData { typedef struct UvSendData
{
UDPSocket* socket; UDPSocket* socket;
uv_udp_send_t req; uv_udp_send_t req;
MS_BYTE store[1]; MS_BYTE store[1];
...@@ -68,49 +68,48 @@ protected: ...@@ -68,49 +68,48 @@ protected:
MS_PORT localPort = 0; MS_PORT localPort = 0;
}; };
/* Inline methods. */ /* Inline methods. */
inline inline
void UDPSocket::Send(const std::string &data, const struct sockaddr* addr) { void UDPSocket::Send(const std::string &data, const struct sockaddr* addr)
{
Send((const MS_BYTE*)data.c_str(), data.size(), addr); Send((const MS_BYTE*)data.c_str(), data.size(), addr);
} }
inline inline
void UDPSocket::Send(const std::string &data, const std::string &ip, MS_PORT port) { void UDPSocket::Send(const std::string &data, const std::string &ip, MS_PORT port)
{
Send((const MS_BYTE*)data.c_str(), data.size(), ip, port); Send((const MS_BYTE*)data.c_str(), data.size(), ip, port);
} }
inline inline
const struct sockaddr* UDPSocket::GetLocalAddress() { const struct sockaddr* UDPSocket::GetLocalAddress()
{
return (const struct sockaddr*)&this->localAddr; return (const struct sockaddr*)&this->localAddr;
} }
inline inline
const std::string& UDPSocket::GetLocalIP() { const std::string& UDPSocket::GetLocalIP()
{
return this->localIP; return this->localIP;
} }
inline inline
MS_PORT UDPSocket::GetLocalPort() { MS_PORT UDPSocket::GetLocalPort()
{
return this->localPort; return this->localPort;
} }
inline inline
void UDPSocket::SetUserData(void* userData) { void UDPSocket::SetUserData(void* userData)
{
this->userData = userData; this->userData = userData;
} }
inline inline
void* UDPSocket::GetUserData() { void* UDPSocket::GetUserData()
{
return this->userData; return this->userData;
} }
#endif #endif
#ifndef MS_UNIX_STREAM_SOCKET_H #ifndef MS_UNIX_STREAM_SOCKET_H
#define MS_UNIX_STREAM_SOCKET_H #define MS_UNIX_STREAM_SOCKET_H
#include "common.h" #include "common.h"
#include <string> #include <string>
#include <uv.h> #include <uv.h>
class UnixStreamSocket
class UnixStreamSocket { {
public: public:
/* Struct for the data field of uv_req_t when writing data. */ /* Struct for the data field of uv_req_t when writing data. */
typedef struct UvWriteData { typedef struct UvWriteData
{
UnixStreamSocket* socket; UnixStreamSocket* socket;
uv_write_t req; uv_write_t req;
MS_BYTE store[1]; MS_BYTE store[1];
...@@ -59,25 +59,24 @@ protected: ...@@ -59,25 +59,24 @@ protected:
size_t bufferDataLen = 0; size_t bufferDataLen = 0;
}; };
/* Inline methods. */ /* Inline methods. */
inline inline
void UnixStreamSocket::Write(const std::string &data) { void UnixStreamSocket::Write(const std::string &data)
{
Write((const MS_BYTE*)data.c_str(), data.size()); Write((const MS_BYTE*)data.c_str(), data.size());
} }
inline inline
void UnixStreamSocket::SetUserData(void* userData) { void UnixStreamSocket::SetUserData(void* userData)
{
this->userData = userData; this->userData = userData;
} }
inline inline
void* UnixStreamSocket::GetUserData() { void* UnixStreamSocket::GetUserData()
{
return this->userData; return this->userData;
} }
#endif #endif
...@@ -3,30 +3,26 @@ ...@@ -3,30 +3,26 @@
#include "ControlProtocol/Message.h" #include "ControlProtocol/Message.h"
#include "Logger.h" #include "Logger.h"
namespace ControlProtocol
{
/* Instance methods. */
namespace ControlProtocol { Message::Message(Kind kind) :
/* Instance methods. */
Message::Message(Kind kind) :
kind(kind) kind(kind)
{ {
MS_TRACE(); MS_TRACE();
} }
Message::~Message()
Message::~Message() { {
MS_TRACE(); MS_TRACE();
} }
// TMP: must be pure virtual. // TMP: must be pure virtual.
bool Message::IsValid() { bool Message::IsValid()
{
MS_TRACE(); MS_TRACE();
return true; return true;
} }
} // namespace ControlProtocol } // namespace ControlProtocol
...@@ -14,25 +14,22 @@ ...@@ -14,25 +14,22 @@
#define PTR_TO(F) (buffer + (F)) #define PTR_TO(F) (buffer + (F))
#define PTR_TO_MARK (const char*)(buffer + this->mark) #define PTR_TO_MARK (const char*)(buffer + this->mark)
namespace ControlProtocol
namespace ControlProtocol { {
/**
/**
* Ragel: machine definition * Ragel: machine definition
*/ */
#line 56 "src/ControlProtocol/Parser.rl" #line 57 "src/ControlProtocol/Parser.rl"
/** /**
* Ragel: %%write data * Ragel: %%write data
* This generates Ragel's static variables such as: * This generates Ragel's static variables such as:
* static const int MessageParser_start * static const int MessageParser_start
*/ */
#line 36 "src/ControlProtocol/Parser.cpp" #line 33 "src/ControlProtocol/Parser.cpp"
static const int MessageParser_start = 1; static const int MessageParser_start = 1;
static const int MessageParser_first_final = 90; static const int MessageParser_first_final = 90;
static const int MessageParser_error = 0; static const int MessageParser_error = 0;
...@@ -42,20 +39,20 @@ static const int MessageParser_error = 0; ...@@ -42,20 +39,20 @@ static const int MessageParser_error = 0;
#line 65 "src/ControlProtocol/Parser.rl" #line 65 "src/ControlProtocol/Parser.rl"
Parser::Parser()
Parser::Parser() { {
MS_TRACE(); MS_TRACE();
Reset(); Reset();
} }
Parser::~Parser() { Parser::~Parser()
{
MS_TRACE(); MS_TRACE();
} }
Message* Parser::Parse(const MS_BYTE* buffer, size_t len) { Message* Parser::Parse(const MS_BYTE* buffer, size_t len)
{
MS_TRACE(); MS_TRACE();
// Used by Ragel: // Used by Ragel:
...@@ -74,7 +71,7 @@ Message* Parser::Parse(const MS_BYTE* buffer, size_t len) { ...@@ -74,7 +71,7 @@ Message* Parser::Parse(const MS_BYTE* buffer, size_t len) {
* This updates cs variable needed by Ragel (so this->cs at the end) and p. * This updates cs variable needed by Ragel (so this->cs at the end) and p.
*/ */
#line 78 "src/ControlProtocol/Parser.cpp" #line 75 "src/ControlProtocol/Parser.cpp"
{ {
if ( p == pe ) if ( p == pe )
goto _test_eof; goto _test_eof;
...@@ -245,11 +242,11 @@ case 23: ...@@ -245,11 +242,11 @@ case 23:
goto tr25; goto tr25;
goto st0; goto st0;
tr25: tr25:
#line 4 "src/ControlProtocol/grammar/RequestAuthenticate.rl" #line 5 "src/ControlProtocol/grammar/RequestAuthenticate.rl"
{ {
this->msg = new ControlProtocol::RequestAuthenticate(); this->msg = new ControlProtocol::RequestAuthenticate();
} }
#line 27 "src/ControlProtocol/Parser.rl" #line 26 "src/ControlProtocol/Parser.rl"
{ {
MARK(this->mark, p); MARK(this->mark, p);
} }
...@@ -258,7 +255,7 @@ st24: ...@@ -258,7 +255,7 @@ st24:
if ( ++p == pe ) if ( ++p == pe )
goto _test_eof24; goto _test_eof24;
case 24: case 24:
#line 262 "src/ControlProtocol/Parser.cpp" #line 259 "src/ControlProtocol/Parser.cpp"
if ( (*p) == 13u ) if ( (*p) == 13u )
goto tr26; goto tr26;
if ( 48u <= (*p) && (*p) <= 57u ) if ( 48u <= (*p) && (*p) <= 57u )
...@@ -275,7 +272,7 @@ st25: ...@@ -275,7 +272,7 @@ st25:
if ( ++p == pe ) if ( ++p == pe )
goto _test_eof25; goto _test_eof25;
case 25: case 25:
#line 279 "src/ControlProtocol/Parser.cpp" #line 276 "src/ControlProtocol/Parser.cpp"
if ( (*p) == 10u ) if ( (*p) == 10u )
goto st26; goto st26;
goto st0; goto st0;
...@@ -346,7 +343,7 @@ case 32: ...@@ -346,7 +343,7 @@ case 32:
goto tr35; goto tr35;
goto st0; goto st0;
tr35: tr35:
#line 27 "src/ControlProtocol/Parser.rl" #line 26 "src/ControlProtocol/Parser.rl"
{ {
MARK(this->mark, p); MARK(this->mark, p);
} }
...@@ -355,7 +352,7 @@ st33: ...@@ -355,7 +352,7 @@ st33:
if ( ++p == pe ) if ( ++p == pe )
goto _test_eof33; goto _test_eof33;
case 33: case 33:
#line 359 "src/ControlProtocol/Parser.cpp" #line 356 "src/ControlProtocol/Parser.cpp"
switch( (*p) ) { switch( (*p) ) {
case 13u: goto tr36; case 13u: goto tr36;
case 33u: goto st33; case 33u: goto st33;
...@@ -379,7 +376,7 @@ case 33: ...@@ -379,7 +376,7 @@ case 33:
goto st33; goto st33;
goto st0; goto st0;
tr36: tr36:
#line 8 "src/ControlProtocol/grammar/RequestAuthenticate.rl" #line 10 "src/ControlProtocol/grammar/RequestAuthenticate.rl"
{ {
static_cast<RequestAuthenticate*>(this->msg)->SetUser(PTR_TO_MARK, LEN_FROM_MARK); static_cast<RequestAuthenticate*>(this->msg)->SetUser(PTR_TO_MARK, LEN_FROM_MARK);
} }
...@@ -388,7 +385,7 @@ st34: ...@@ -388,7 +385,7 @@ st34:
if ( ++p == pe ) if ( ++p == pe )
goto _test_eof34; goto _test_eof34;
case 34: case 34:
#line 392 "src/ControlProtocol/Parser.cpp" #line 389 "src/ControlProtocol/Parser.cpp"
if ( (*p) == 10u ) if ( (*p) == 10u )
goto st35; goto st35;
goto st0; goto st0;
...@@ -473,7 +470,7 @@ case 43: ...@@ -473,7 +470,7 @@ case 43:
goto tr47; goto tr47;
goto st0; goto st0;
tr47: tr47:
#line 27 "src/ControlProtocol/Parser.rl" #line 26 "src/ControlProtocol/Parser.rl"
{ {
MARK(this->mark, p); MARK(this->mark, p);
} }
...@@ -482,7 +479,7 @@ st44: ...@@ -482,7 +479,7 @@ st44:
if ( ++p == pe ) if ( ++p == pe )
goto _test_eof44; goto _test_eof44;
case 44: case 44:
#line 486 "src/ControlProtocol/Parser.cpp" #line 483 "src/ControlProtocol/Parser.cpp"
switch( (*p) ) { switch( (*p) ) {
case 13u: goto tr48; case 13u: goto tr48;
case 33u: goto st44; case 33u: goto st44;
...@@ -513,7 +510,7 @@ tr78: ...@@ -513,7 +510,7 @@ tr78:
} }
goto st45; goto st45;
tr48: tr48:
#line 12 "src/ControlProtocol/grammar/RequestAuthenticate.rl" #line 15 "src/ControlProtocol/grammar/RequestAuthenticate.rl"
{ {
static_cast<RequestAuthenticate*>(this->msg)->SetPasswd(PTR_TO_MARK, LEN_FROM_MARK); static_cast<RequestAuthenticate*>(this->msg)->SetPasswd(PTR_TO_MARK, LEN_FROM_MARK);
} }
...@@ -522,7 +519,7 @@ st45: ...@@ -522,7 +519,7 @@ st45:
if ( ++p == pe ) if ( ++p == pe )
goto _test_eof45; goto _test_eof45;
case 45: case 45:
#line 526 "src/ControlProtocol/Parser.cpp" #line 523 "src/ControlProtocol/Parser.cpp"
if ( (*p) == 10u ) if ( (*p) == 10u )
goto st46; goto st46;
goto st0; goto st0;
...@@ -541,7 +538,7 @@ case 47: ...@@ -541,7 +538,7 @@ case 47:
goto tr52; goto tr52;
goto st0; goto st0;
tr52: tr52:
#line 36 "src/ControlProtocol/Parser.rl" #line 37 "src/ControlProtocol/Parser.rl"
{ {
{p++; cs = 90; goto _out;} {p++; cs = 90; goto _out;}
} }
...@@ -550,7 +547,7 @@ st90: ...@@ -550,7 +547,7 @@ st90:
if ( ++p == pe ) if ( ++p == pe )
goto _test_eof90; goto _test_eof90;
case 90: case 90:
#line 554 "src/ControlProtocol/Parser.cpp" #line 551 "src/ControlProtocol/Parser.cpp"
goto st0; goto st0;
st48: st48:
if ( ++p == pe ) if ( ++p == pe )
...@@ -749,21 +746,21 @@ case 73: ...@@ -749,21 +746,21 @@ case 73:
goto tr77; goto tr77;
goto st0; goto st0;
tr77: tr77:
#line 4 "src/ControlProtocol/grammar/RequestCreateConference.rl" #line 5 "src/ControlProtocol/grammar/RequestCreateConference.rl"
{ {
this->msg = new ControlProtocol::RequestCreateConference(); this->msg = new ControlProtocol::RequestCreateConference();
} }
#line 27 "src/ControlProtocol/Parser.rl" #line 26 "src/ControlProtocol/Parser.rl"
{ {
MARK(this->mark, p); MARK(this->mark, p);
} }
goto st74; goto st74;
tr93: tr93:
#line 4 "src/ControlProtocol/grammar/RequestHello.rl" #line 5 "src/ControlProtocol/grammar/RequestHello.rl"
{ {
this->msg = new ControlProtocol::RequestHello(); this->msg = new ControlProtocol::RequestHello();
} }
#line 27 "src/ControlProtocol/Parser.rl" #line 26 "src/ControlProtocol/Parser.rl"
{ {
MARK(this->mark, p); MARK(this->mark, p);
} }
...@@ -772,7 +769,7 @@ st74: ...@@ -772,7 +769,7 @@ st74:
if ( ++p == pe ) if ( ++p == pe )
goto _test_eof74; goto _test_eof74;
case 74: case 74:
#line 776 "src/ControlProtocol/Parser.cpp" #line 773 "src/ControlProtocol/Parser.cpp"
if ( (*p) == 13u ) if ( (*p) == 13u )
goto tr78; goto tr78;
if ( 48u <= (*p) && (*p) <= 57u ) if ( 48u <= (*p) && (*p) <= 57u )
...@@ -1001,13 +998,15 @@ case 89: ...@@ -1001,13 +998,15 @@ case 89:
MS_ASSERT(this->mark < len, "mark is after buffer end"); MS_ASSERT(this->mark < len, "mark is after buffer end");
// Parsing succedded. // Parsing succedded.
if (this->cs == (size_t)MessageParser_first_final) { if (this->cs == (size_t)MessageParser_first_final)
{
MS_DEBUG("parsing finished OK"); MS_DEBUG("parsing finished OK");
MS_ASSERT(this->msg != nullptr, "parsing OK but msg is NULL"); MS_ASSERT(this->msg != nullptr, "parsing OK but msg is NULL");
// Check the message semantics. // Check the message semantics.
if(! this->msg->IsValid()) { if (!this->msg->IsValid())
{
MS_ERROR("invalid message"); MS_ERROR("invalid message");
delete this->msg; delete this->msg;
return (this->msg = nullptr); return (this->msg = nullptr);
...@@ -1017,11 +1016,13 @@ case 89: ...@@ -1017,11 +1016,13 @@ case 89:
} }
// Parsing error. // Parsing error.
else if (this->cs == (size_t)MessageParser_error) { else if (this->cs == (size_t)MessageParser_error)
{
MS_ERROR("parsing error at position %zd", this->parsedLen); MS_ERROR("parsing error at position %zd", this->parsedLen);
// Delete this->msg if it exists. // Delete this->msg if it exists.
if (this->msg) { if (this->msg)
{
delete this->msg; delete this->msg;
this->msg = nullptr; this->msg = nullptr;
} }
...@@ -1030,29 +1031,30 @@ case 89: ...@@ -1030,29 +1031,30 @@ case 89:
} }
// Parsing not finished. // Parsing not finished.
else { else
{
MS_DEBUG("parsing not finished"); MS_DEBUG("parsing not finished");
return nullptr; return nullptr;
} }
} }
bool Parser::HasError() { bool Parser::HasError()
{
MS_TRACE(); MS_TRACE();
return (this->cs == (size_t)MessageParser_error); return (this->cs == (size_t)MessageParser_error);
} }
size_t Parser::GetParsedLen() { size_t Parser::GetParsedLen()
{
MS_TRACE(); MS_TRACE();
return this->parsedLen; return this->parsedLen;
} }
void Parser::Reset() { void Parser::Reset()
{
MS_TRACE(); MS_TRACE();
this->parsedLen = 0; this->parsedLen = 0;
...@@ -1065,21 +1067,19 @@ void Parser::Reset() { ...@@ -1065,21 +1067,19 @@ void Parser::Reset() {
* This sets cs variable needed by Ragel (so this->cs at the end). * This sets cs variable needed by Ragel (so this->cs at the end).
*/ */
#line 1069 "src/ControlProtocol/Parser.cpp" #line 1071 "src/ControlProtocol/Parser.cpp"
{ {
cs = MessageParser_start; cs = MessageParser_start;
} }
#line 170 "src/ControlProtocol/Parser.rl" #line 175 "src/ControlProtocol/Parser.rl"
} }
void Parser::Dump() { void Parser::Dump()
{
MS_DEBUG("[cs: %zu | parsedLen: %zu | mark: %zu | error?: %s | finished?: %s]", MS_DEBUG("[cs: %zu | parsedLen: %zu | mark: %zu | error?: %s | finished?: %s]",
this->cs, this->parsedLen, this->mark, this->cs, this->parsedLen, this->mark,
HasError() ? "true" : "false", HasError() ? "true" : "false",
(this->cs >= (size_t)MessageParser_first_final) ? "true" : "false"); (this->cs >= (size_t)MessageParser_first_final) ? "true" : "false");
} }
} // namespace ControlProtocol } // namespace ControlProtocol
...@@ -12,28 +12,29 @@ ...@@ -12,28 +12,29 @@
#define PTR_TO(F) (buffer + (F)) #define PTR_TO(F) (buffer + (F))
#define PTR_TO_MARK (const char*)(buffer + this->mark) #define PTR_TO_MARK (const char*)(buffer + this->mark)
namespace ControlProtocol
namespace ControlProtocol { {
/**
/**
* Ragel: machine definition * Ragel: machine definition
*/ */
%%{ %%{
machine MessageParser; machine MessageParser;
alphtype unsigned char; alphtype unsigned char;
action mark { action mark
{
MARK(this->mark, p); MARK(this->mark, p);
} }
action on_transaction { action on_transaction
{
int32_t transaction = std::atol(PTR_TO_MARK); int32_t transaction = std::atol(PTR_TO_MARK);
this->msg->SetTransaction(transaction); this->msg->SetTransaction(transaction);
} }
action on_message { action on_message
{
fbreak; fbreak;
} }
...@@ -53,30 +54,29 @@ namespace ControlProtocol { ...@@ -53,30 +54,29 @@ namespace ControlProtocol {
Message = Request @on_message; Message = Request @on_message;
main := Message; main := Message;
}%% }%%
/** /**
* Ragel: %%write data * Ragel: %%write data
* This generates Ragel's static variables such as: * This generates Ragel's static variables such as:
* static const int MessageParser_start * static const int MessageParser_start
*/ */
%%write data; %%write data;
Parser::Parser()
Parser::Parser() { {
MS_TRACE(); MS_TRACE();
Reset(); Reset();
} }
Parser::~Parser() { Parser::~Parser()
{
MS_TRACE(); MS_TRACE();
} }
Message* Parser::Parse(const MS_BYTE* buffer, size_t len) { Message* Parser::Parse(const MS_BYTE* buffer, size_t len)
{
MS_TRACE(); MS_TRACE();
// Used by Ragel: // Used by Ragel:
...@@ -103,13 +103,15 @@ Message* Parser::Parse(const MS_BYTE* buffer, size_t len) { ...@@ -103,13 +103,15 @@ Message* Parser::Parse(const MS_BYTE* buffer, size_t len) {
MS_ASSERT(this->mark < len, "mark is after buffer end"); MS_ASSERT(this->mark < len, "mark is after buffer end");
// Parsing succedded. // Parsing succedded.
if (this->cs == (size_t)MessageParser_first_final) { if (this->cs == (size_t)MessageParser_first_final)
{
MS_DEBUG("parsing finished OK"); MS_DEBUG("parsing finished OK");
MS_ASSERT(this->msg != nullptr, "parsing OK but msg is NULL"); MS_ASSERT(this->msg != nullptr, "parsing OK but msg is NULL");
// Check the message semantics. // Check the message semantics.
if(! this->msg->IsValid()) { if (!this->msg->IsValid())
{
MS_ERROR("invalid message"); MS_ERROR("invalid message");
delete this->msg; delete this->msg;
return (this->msg = nullptr); return (this->msg = nullptr);
...@@ -119,11 +121,13 @@ Message* Parser::Parse(const MS_BYTE* buffer, size_t len) { ...@@ -119,11 +121,13 @@ Message* Parser::Parse(const MS_BYTE* buffer, size_t len) {
} }
// Parsing error. // Parsing error.
else if (this->cs == (size_t)MessageParser_error) { else if (this->cs == (size_t)MessageParser_error)
{
MS_ERROR("parsing error at position %zd", this->parsedLen); MS_ERROR("parsing error at position %zd", this->parsedLen);
// Delete this->msg if it exists. // Delete this->msg if it exists.
if (this->msg) { if (this->msg)
{
delete this->msg; delete this->msg;
this->msg = nullptr; this->msg = nullptr;
} }
...@@ -132,29 +136,30 @@ Message* Parser::Parse(const MS_BYTE* buffer, size_t len) { ...@@ -132,29 +136,30 @@ Message* Parser::Parse(const MS_BYTE* buffer, size_t len) {
} }
// Parsing not finished. // Parsing not finished.
else { else
{
MS_DEBUG("parsing not finished"); MS_DEBUG("parsing not finished");
return nullptr; return nullptr;
} }
} }
bool Parser::HasError() { bool Parser::HasError()
{
MS_TRACE(); MS_TRACE();
return (this->cs == (size_t)MessageParser_error); return (this->cs == (size_t)MessageParser_error);
} }
size_t Parser::GetParsedLen() { size_t Parser::GetParsedLen()
{
MS_TRACE(); MS_TRACE();
return this->parsedLen; return this->parsedLen;
} }
void Parser::Reset() { void Parser::Reset()
{
MS_TRACE(); MS_TRACE();
this->parsedLen = 0; this->parsedLen = 0;
...@@ -167,15 +172,13 @@ void Parser::Reset() { ...@@ -167,15 +172,13 @@ void Parser::Reset() {
* This sets cs variable needed by Ragel (so this->cs at the end). * This sets cs variable needed by Ragel (so this->cs at the end).
*/ */
%%write init; %%write init;
} }
void Parser::Dump() { void Parser::Dump()
{
MS_DEBUG("[cs: %zu | parsedLen: %zu | mark: %zu | error?: %s | finished?: %s]", MS_DEBUG("[cs: %zu | parsedLen: %zu | mark: %zu | error?: %s | finished?: %s]",
this->cs, this->parsedLen, this->mark, this->cs, this->parsedLen, this->mark,
HasError() ? "true" : "false", HasError() ? "true" : "false",
(this->cs >= (size_t)MessageParser_first_final) ? "true" : "false"); (this->cs >= (size_t)MessageParser_first_final) ? "true" : "false");
} }
} // namespace ControlProtocol } // namespace ControlProtocol
...@@ -3,23 +3,19 @@ ...@@ -3,23 +3,19 @@
#include "ControlProtocol/Request.h" #include "ControlProtocol/Request.h"
#include "Logger.h" #include "Logger.h"
namespace ControlProtocol
{
/* Instance methods. */
namespace ControlProtocol { Request::Request(Type type) :
/* Instance methods. */
Request::Request(Type type) :
Message(Message::Kind::Request), Message(Message::Kind::Request),
type(type) type(type)
{ {
MS_TRACE(); MS_TRACE();
} }
Request::~Request() { Request::~Request()
{
MS_TRACE(); MS_TRACE();
} }
} // namespace ControlProtocol } // namespace ControlProtocol
...@@ -5,35 +5,35 @@ ...@@ -5,35 +5,35 @@
#include <cstring> // std::memmove() #include <cstring> // std::memmove()
namespace ControlProtocol { namespace ControlProtocol
{
/* Instance methods. */
/* Instance methods. */
TCPConnection::TCPConnection(Reader* reader, size_t bufferSize) : TCPConnection::TCPConnection(Reader* reader, size_t bufferSize) :
::TCPConnection(bufferSize), ::TCPConnection(bufferSize),
reader(reader) reader(reader)
{ {
MS_TRACE(); MS_TRACE();
// Initiate a ControlProtocol::Parser. // Initiate a ControlProtocol::Parser.
this->parser = new ControlProtocol::Parser(); this->parser = new ControlProtocol::Parser();
} }
TCPConnection::~TCPConnection() { TCPConnection::~TCPConnection()
{
MS_TRACE(); MS_TRACE();
if (this->parser) if (this->parser)
delete this->parser; delete this->parser;
} }
void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) { void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len)
{
MS_TRACE(); MS_TRACE();
// Be ready to parse more than a single message in a single TCP chunk. // Be ready to parse more than a single message in a single TCP chunk.
while(true) { while (true)
{
ControlProtocol::Message* msg; ControlProtocol::Message* msg;
// Tell the parser to parse the buffer starting from the beginning of the latest // Tell the parser to parse the buffer starting from the beginning of the latest
...@@ -42,7 +42,8 @@ void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) { ...@@ -42,7 +42,8 @@ void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) {
size_t parsed_len = parser->GetParsedLen(); size_t parsed_len = parser->GetParsedLen();
// Message parsed. // Message parsed.
if (msg) { if (msg)
{
// Notify the reader. // Notify the reader.
this->reader->onControlProtocolMessage(this, msg, this->buffer + this->msgStart, parsed_len); this->reader->onControlProtocolMessage(this, msg, this->buffer + this->msgStart, parsed_len);
...@@ -51,7 +52,8 @@ void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) { ...@@ -51,7 +52,8 @@ void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) {
// If there is no more space available in the buffer and that is because // If there is no more space available in the buffer and that is because
// the latest parsed message filled it, then empty the full buffer. // the latest parsed message filled it, then empty the full buffer.
if ((this->msgStart + parsed_len) == this->bufferSize) { if ((this->msgStart + parsed_len) == this->bufferSize)
{
MS_DEBUG("no more space in the buffer, emptying the buffer data"); MS_DEBUG("no more space in the buffer, emptying the buffer data");
this->msgStart = 0; this->msgStart = 0;
...@@ -59,7 +61,8 @@ void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) { ...@@ -59,7 +61,8 @@ void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) {
} }
// If there is still space in the buffer, set the beginning of the next // If there is still space in the buffer, set the beginning of the next
// parsing to the next position after the parsed message. // parsing to the next position after the parsed message.
else { else
{
this->msgStart += parsed_len; this->msgStart += parsed_len;
} }
...@@ -68,17 +71,20 @@ void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) { ...@@ -68,17 +71,20 @@ void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) {
// If there is more data in the buffer after the parsed message // If there is more data in the buffer after the parsed message
// then parse again. Otherwise break here and wait for more data. // then parse again. Otherwise break here and wait for more data.
if (this->bufferDataLen > this->msgStart) { if (this->bufferDataLen > this->msgStart)
{
MS_DEBUG("there is more data after the parsed message, continue parsing"); MS_DEBUG("there is more data after the parsed message, continue parsing");
continue; continue;
} }
else { else
{
break; break;
} }
} }
// Parsing error. Close the connection. // Parsing error. Close the connection.
else if (this->parser->HasError()) { else if (this->parser->HasError())
{
MS_ERROR("parsing error, closing the connection"); MS_ERROR("parsing error, closing the connection");
// Close the connection. // Close the connection.
...@@ -89,12 +95,15 @@ void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) { ...@@ -89,12 +95,15 @@ void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) {
} }
// Message not finished. // Message not finished.
else { else
{
// Check if the buffer is full. // Check if the buffer is full.
if (this->bufferDataLen == this->bufferSize) { if (this->bufferDataLen == this->bufferSize)
{
// First case: the uncomplete message does not begin at position 0 of // First case: the uncomplete message does not begin at position 0 of
// the buffer, so move the message to the position 0. // the buffer, so move the message to the position 0.
if (this->msgStart != 0) { if (this->msgStart != 0)
{
MS_DEBUG("no more space in the buffer, moving parsed bytes to the beginning of the buffer and wait for more data"); MS_DEBUG("no more space in the buffer, moving parsed bytes to the beginning of the buffer and wait for more data");
std::memmove(this->buffer, this->buffer + this->msgStart, parsed_len); std::memmove(this->buffer, this->buffer + this->msgStart, parsed_len);
...@@ -104,7 +113,8 @@ void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) { ...@@ -104,7 +113,8 @@ void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) {
// Second case: the uncomplete message begins at position 0 of the buffer. // Second case: the uncomplete message begins at position 0 of the buffer.
// The message is too big, so close the connection. // The message is too big, so close the connection.
else { else
{
MS_ERROR("no more space in the buffer for the unfinished message being parsed, closing the connection"); MS_ERROR("no more space in the buffer for the unfinished message being parsed, closing the connection");
// Close the socket. // Close the socket.
...@@ -112,7 +122,8 @@ void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) { ...@@ -112,7 +122,8 @@ void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) {
} }
} }
// The buffer is not full. // The buffer is not full.
else { else
{
MS_DEBUG("message not finished yet, waiting for more data"); MS_DEBUG("message not finished yet, waiting for more data");
} }
...@@ -120,7 +131,5 @@ void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) { ...@@ -120,7 +131,5 @@ void TCPConnection::userOnTCPConnectionRead(const MS_BYTE* data, size_t len) {
break; break;
} }
} // while() } // while()
} }
} // namespace ControlProtocol } // namespace ControlProtocol
...@@ -4,47 +4,44 @@ ...@@ -4,47 +4,44 @@
#include "Logger.h" #include "Logger.h"
namespace ControlProtocol { namespace ControlProtocol
{
/* Instance methods. */
/* Instance methods. */
TCPServer::TCPServer(Listener* listener, ControlProtocol::TCPConnection::Reader* reader, const std::string &ip, MS_PORT port) : TCPServer::TCPServer(Listener* listener, ControlProtocol::TCPConnection::Reader* reader, const std::string &ip, MS_PORT port) :
::TCPServer::TCPServer(ip, port, 2048), ::TCPServer::TCPServer(ip, port, 2048),
listener(listener), listener(listener),
reader(reader) reader(reader)
{ {
MS_TRACE(); MS_TRACE();
} }
void TCPServer::userOnTCPConnectionAlloc(::TCPConnection** connection) { void TCPServer::userOnTCPConnectionAlloc(::TCPConnection** connection)
{
MS_TRACE(); MS_TRACE();
// Allocate a new ControlProtocol::TCPConnection and pass it our reader. // Allocate a new ControlProtocol::TCPConnection and pass it our reader.
*connection = new ControlProtocol::TCPConnection(this->reader, 65536); *connection = new ControlProtocol::TCPConnection(this->reader, 65536);
} }
void TCPServer::userOnNewTCPConnection(::TCPConnection* connection)
void TCPServer::userOnNewTCPConnection(::TCPConnection* connection) { {
MS_TRACE(); MS_TRACE();
// Notify the listener. // Notify the listener.
this->listener->onControlProtocolNewTCPConnection(this, static_cast<ControlProtocol::TCPConnection*>(connection)); this->listener->onControlProtocolNewTCPConnection(this, static_cast<ControlProtocol::TCPConnection*>(connection));
} }
void TCPServer::userOnTCPConnectionClosed(::TCPConnection* connection, bool is_closed_by_peer) { void TCPServer::userOnTCPConnectionClosed(::TCPConnection* connection, bool is_closed_by_peer)
{
MS_TRACE(); MS_TRACE();
// Notify the listener. // Notify the listener.
this->listener->onControlProtocolTCPConnectionClosed(this, static_cast<ControlProtocol::TCPConnection*>(connection), is_closed_by_peer); this->listener->onControlProtocolTCPConnectionClosed(this, static_cast<ControlProtocol::TCPConnection*>(connection), is_closed_by_peer);
} }
void TCPServer::userOnTCPServerClosed() { void TCPServer::userOnTCPServerClosed()
{
MS_TRACE(); MS_TRACE();
} }
} // namespace ControlProtocol } // namespace ControlProtocol
...@@ -4,36 +4,35 @@ ...@@ -4,36 +4,35 @@
#include "Logger.h" #include "Logger.h"
#include <cstring> // std::memmove() #include <cstring> // std::memmove()
namespace ControlProtocol
{
/* Instance methods. */
namespace ControlProtocol { UnixStreamSocket::UnixStreamSocket(Listener* listener, int fd) :
/* Instance methods. */
UnixStreamSocket::UnixStreamSocket(Listener* listener, int fd) :
::UnixStreamSocket::UnixStreamSocket(fd, 65536), ::UnixStreamSocket::UnixStreamSocket(fd, 65536),
listener(listener) listener(listener)
{ {
MS_TRACE(); MS_TRACE();
// Initiate a ControlProtocol::Parser. // Initiate a ControlProtocol::Parser.
this->parser = new ControlProtocol::Parser(); this->parser = new ControlProtocol::Parser();
} }
UnixStreamSocket::~UnixStreamSocket() { UnixStreamSocket::~UnixStreamSocket()
{
MS_TRACE(); MS_TRACE();
if (this->parser) if (this->parser)
delete this->parser; delete this->parser;
} }
void UnixStreamSocket::userOnUnixStreamRead(const MS_BYTE* data, size_t len) { void UnixStreamSocket::userOnUnixStreamRead(const MS_BYTE* data, size_t len)
{
MS_TRACE(); MS_TRACE();
// Be ready to parse more than a single message in a single TCP chunk. // Be ready to parse more than a single message in a single TCP chunk.
while(true) { while (true)
{
ControlProtocol::Message* msg; ControlProtocol::Message* msg;
// Tell the parser to parse the buffer starting from the beginning of the latest // Tell the parser to parse the buffer starting from the beginning of the latest
...@@ -42,7 +41,8 @@ void UnixStreamSocket::userOnUnixStreamRead(const MS_BYTE* data, size_t len) { ...@@ -42,7 +41,8 @@ void UnixStreamSocket::userOnUnixStreamRead(const MS_BYTE* data, size_t len) {
size_t parsed_len = parser->GetParsedLen(); size_t parsed_len = parser->GetParsedLen();
// Message parsed. // Message parsed.
if (msg) { if (msg)
{
// Notify the listener. // Notify the listener.
this->listener->onControlProtocolMessage(this, msg, this->buffer + this->msgStart, parsed_len); this->listener->onControlProtocolMessage(this, msg, this->buffer + this->msgStart, parsed_len);
...@@ -51,7 +51,8 @@ void UnixStreamSocket::userOnUnixStreamRead(const MS_BYTE* data, size_t len) { ...@@ -51,7 +51,8 @@ void UnixStreamSocket::userOnUnixStreamRead(const MS_BYTE* data, size_t len) {
// If there is no more space available in the buffer and that is because // If there is no more space available in the buffer and that is because
// the latest parsed message filled it, then empty the full buffer. // the latest parsed message filled it, then empty the full buffer.
if ((this->msgStart + parsed_len) == this->bufferSize) { if ((this->msgStart + parsed_len) == this->bufferSize)
{
MS_DEBUG("no more space in the buffer, emptying the buffer data"); MS_DEBUG("no more space in the buffer, emptying the buffer data");
this->msgStart = 0; this->msgStart = 0;
...@@ -59,7 +60,8 @@ void UnixStreamSocket::userOnUnixStreamRead(const MS_BYTE* data, size_t len) { ...@@ -59,7 +60,8 @@ void UnixStreamSocket::userOnUnixStreamRead(const MS_BYTE* data, size_t len) {
} }
// If there is still space in the buffer, set the beginning of the next // If there is still space in the buffer, set the beginning of the next
// parsing to the next position after the parsed message. // parsing to the next position after the parsed message.
else { else
{
this->msgStart += parsed_len; this->msgStart += parsed_len;
} }
...@@ -68,17 +70,20 @@ void UnixStreamSocket::userOnUnixStreamRead(const MS_BYTE* data, size_t len) { ...@@ -68,17 +70,20 @@ void UnixStreamSocket::userOnUnixStreamRead(const MS_BYTE* data, size_t len) {
// If there is more data in the buffer after the parsed message // If there is more data in the buffer after the parsed message
// then parse again. Otherwise break here and wait for more data. // then parse again. Otherwise break here and wait for more data.
if (this->bufferDataLen > this->msgStart) { if (this->bufferDataLen > this->msgStart)
{
MS_DEBUG("there is more data after the parsed message, continue parsing"); MS_DEBUG("there is more data after the parsed message, continue parsing");
continue; continue;
} }
else { else
{
break; break;
} }
} }
// Parsing error. Close the pipe. // Parsing error. Close the pipe.
else if (this->parser->HasError()) { else if (this->parser->HasError())
{
MS_ERROR("parsing error, closing the pipe"); MS_ERROR("parsing error, closing the pipe");
// Close the pipe. // Close the pipe.
...@@ -89,22 +94,25 @@ void UnixStreamSocket::userOnUnixStreamRead(const MS_BYTE* data, size_t len) { ...@@ -89,22 +94,25 @@ void UnixStreamSocket::userOnUnixStreamRead(const MS_BYTE* data, size_t len) {
} }
// Message not finished. // Message not finished.
else { else
{
// Check if the buffer is full. // Check if the buffer is full.
if (this->bufferDataLen == this->bufferSize) { if (this->bufferDataLen == this->bufferSize)
{
// First case: the uncomplete message does not begin at position 0 of // First case: the uncomplete message does not begin at position 0 of
// the buffer, so move the message to the position 0. // the buffer, so move the message to the position 0.
if (this->msgStart != 0) { if (this->msgStart != 0)
{
MS_DEBUG("no more space in the buffer, moving parsed bytes to the beginning of the buffer and wait for more data"); MS_DEBUG("no more space in the buffer, moving parsed bytes to the beginning of the buffer and wait for more data");
std::memmove(this->buffer, this->buffer + this->msgStart, parsed_len); std::memmove(this->buffer, this->buffer + this->msgStart, parsed_len);
this->msgStart = 0; this->msgStart = 0;
this->bufferDataLen = parsed_len; this->bufferDataLen = parsed_len;
} }
// Second case: the uncomplete message begins at position 0 of the buffer. // Second case: the uncomplete message begins at position 0 of the buffer.
// The message is too big, so close the pipe. // The message is too big, so close the pipe.
else { else
{
MS_ERROR("no more space in the buffer for the unfinished message being parsed, closing the pipe"); MS_ERROR("no more space in the buffer for the unfinished message being parsed, closing the pipe");
// Close the socket. // Close the socket.
...@@ -112,7 +120,8 @@ void UnixStreamSocket::userOnUnixStreamRead(const MS_BYTE* data, size_t len) { ...@@ -112,7 +120,8 @@ void UnixStreamSocket::userOnUnixStreamRead(const MS_BYTE* data, size_t len) {
} }
} }
// The buffer is not full. // The buffer is not full.
else { else
{
MS_DEBUG("message not finished yet, waiting for more data"); MS_DEBUG("message not finished yet, waiting for more data");
} }
...@@ -120,15 +129,13 @@ void UnixStreamSocket::userOnUnixStreamRead(const MS_BYTE* data, size_t len) { ...@@ -120,15 +129,13 @@ void UnixStreamSocket::userOnUnixStreamRead(const MS_BYTE* data, size_t len) {
break; break;
} }
} // while() } // while()
} }
void UnixStreamSocket::userOnUnixStreamSocketClosed(bool is_closed_by_peer) { void UnixStreamSocket::userOnUnixStreamSocketClosed(bool is_closed_by_peer)
{
MS_TRACE(); MS_TRACE();
// Notify the listener. // Notify the listener.
this->listener->onControlProtocolUnixStreamSocketClosed(this, is_closed_by_peer); this->listener->onControlProtocolUnixStreamSocketClosed(this, is_closed_by_peer);
} }
} // namespace ControlProtocol } // namespace ControlProtocol
%%{ %%{
machine RequestAuthenticate; machine RequestAuthenticate;
action on_request_type_Authenticate { action on_request_type_Authenticate
{
this->msg = new ControlProtocol::RequestAuthenticate(); this->msg = new ControlProtocol::RequestAuthenticate();
} }
action on_auth_user { action on_auth_user
{
static_cast<RequestAuthenticate*>(this->msg)->SetUser(PTR_TO_MARK, LEN_FROM_MARK); static_cast<RequestAuthenticate*>(this->msg)->SetUser(PTR_TO_MARK, LEN_FROM_MARK);
} }
action on_auth_passwd { action on_auth_passwd
{
static_cast<RequestAuthenticate*>(this->msg)->SetPasswd(PTR_TO_MARK, LEN_FROM_MARK); static_cast<RequestAuthenticate*>(this->msg)->SetPasswd(PTR_TO_MARK, LEN_FROM_MARK);
} }
......
%%{ %%{
machine RequestCreateConference; machine RequestCreateConference;
action on_request_type_CreateConference { action on_request_type_CreateConference
{
this->msg = new ControlProtocol::RequestCreateConference(); this->msg = new ControlProtocol::RequestCreateConference();
} }
......
%%{ %%{
machine RequestHello; machine RequestHello;
action on_request_type_Hello { action on_request_type_Hello
{
this->msg = new ControlProtocol::RequestHello(); this->msg = new ControlProtocol::RequestHello();
} }
......
...@@ -3,45 +3,41 @@ ...@@ -3,45 +3,41 @@
#include "ControlProtocol/messages/RequestAuthenticate.h" #include "ControlProtocol/messages/RequestAuthenticate.h"
#include "Logger.h" #include "Logger.h"
namespace ControlProtocol
{
/* Instance methods. */
namespace ControlProtocol { RequestAuthenticate::RequestAuthenticate() :
/* Instance methods. */
RequestAuthenticate::RequestAuthenticate() :
Request(Type::Authenticate) Request(Type::Authenticate)
{ {
MS_DEBUG("kind: %d, type: %d", (int)this->kind, (int)this->type); MS_DEBUG("kind: %d, type: %d", (int)this->kind, (int)this->type);
} }
RequestAuthenticate::~RequestAuthenticate() { RequestAuthenticate::~RequestAuthenticate()
{
MS_TRACE(); MS_TRACE();
} }
void RequestAuthenticate::SetUser(const char* str, size_t len)
void RequestAuthenticate::SetUser(const char* str, size_t len) { {
MS_TRACE(); MS_TRACE();
this->user = std::string(str, len); this->user = std::string(str, len);
} }
void RequestAuthenticate::SetPasswd(const char* str, size_t len) { void RequestAuthenticate::SetPasswd(const char* str, size_t len)
{
MS_TRACE(); MS_TRACE();
this->passwd = std::string(str, len); this->passwd = std::string(str, len);
} }
void RequestAuthenticate::Dump() { void RequestAuthenticate::Dump()
{
MS_DEBUG("[Request Authenticate]"); MS_DEBUG("[Request Authenticate]");
MS_DEBUG("- transaction: %zu", (size_t)this->transaction); MS_DEBUG("- transaction: %zu", (size_t)this->transaction);
MS_DEBUG("- user: %s", this->user.c_str()); MS_DEBUG("- user: %s", this->user.c_str());
MS_DEBUG("- passwd: %s", this->passwd.c_str()); MS_DEBUG("- passwd: %s", this->passwd.c_str());
MS_DEBUG("[/Request Authenticate]"); MS_DEBUG("[/Request Authenticate]");
} }
} // namespace ControlProtocol } // namespace ControlProtocol
...@@ -3,27 +3,24 @@ ...@@ -3,27 +3,24 @@
#include "ControlProtocol/messages/RequestCreateConference.h" #include "ControlProtocol/messages/RequestCreateConference.h"
#include "Logger.h" #include "Logger.h"
namespace ControlProtocol
{
/* Instance methods. */
namespace ControlProtocol { RequestCreateConference::RequestCreateConference() : Request(Type::CreateConference)
{
/* Instance methods. */
RequestCreateConference::RequestCreateConference() : Request(Type::CreateConference) {
MS_DEBUG("kind: %d, type: %d", (int)this->kind, (int)this->type); MS_DEBUG("kind: %d, type: %d", (int)this->kind, (int)this->type);
} }
RequestCreateConference::~RequestCreateConference() { RequestCreateConference::~RequestCreateConference()
{
MS_TRACE(); MS_TRACE();
} }
void RequestCreateConference::Dump()
void RequestCreateConference::Dump() { {
MS_DEBUG("[Request CreateConference]"); MS_DEBUG("[Request CreateConference]");
MS_DEBUG("- transaction: %zu", (size_t)this->transaction); MS_DEBUG("- transaction: %zu", (size_t)this->transaction);
MS_DEBUG("[/Request CreateConference]"); MS_DEBUG("[/Request CreateConference]");
} }
} // namespace ControlProtocol } // namespace ControlProtocol
...@@ -3,27 +3,24 @@ ...@@ -3,27 +3,24 @@
#include "ControlProtocol/messages/RequestHello.h" #include "ControlProtocol/messages/RequestHello.h"
#include "Logger.h" #include "Logger.h"
namespace ControlProtocol
{
/* Instance methods. */
namespace ControlProtocol { RequestHello::RequestHello() : Request(Type::Hello)
{
/* Instance methods. */
RequestHello::RequestHello() : Request(Type::Hello) {
MS_DEBUG("kind: %d, type: %d", (int)this->kind, (int)this->type); MS_DEBUG("kind: %d, type: %d", (int)this->kind, (int)this->type);
} }
RequestHello::~RequestHello() { RequestHello::~RequestHello()
{
MS_TRACE(); MS_TRACE();
} }
void RequestHello::Dump()
void RequestHello::Dump() { {
MS_DEBUG("[Request Hello]"); MS_DEBUG("[Request Hello]");
MS_DEBUG("- transaction: %zu", (size_t)this->transaction); MS_DEBUG("- transaction: %zu", (size_t)this->transaction);
MS_DEBUG("[/Request Hello]"); MS_DEBUG("[/Request Hello]");
} }
} // namespace ControlProtocol } // namespace ControlProtocol
差异被折叠。
...@@ -13,21 +13,23 @@ ...@@ -13,21 +13,23 @@
#include <csignal> // sigaction(), pthread_sigmask() #include <csignal> // sigaction(), pthread_sigmask()
#include <cerrno> #include <cerrno>
/* Instance methods. */ /* Instance methods. */
Dispatcher::Dispatcher() { Dispatcher::Dispatcher()
{
MS_TRACE(); MS_TRACE();
// Set the signals handler. // Set the signals handler.
try { try
{
this->signalsHandler = new SignalsHandler(this); this->signalsHandler = new SignalsHandler(this);
// Add signals to handle. // Add signals to handle.
this->signalsHandler->AddSignal(SIGUSR1, "USR1"); this->signalsHandler->AddSignal(SIGUSR1, "USR1");
this->signalsHandler->AddSignal(SIGINT, "INT"); this->signalsHandler->AddSignal(SIGINT, "INT");
this->signalsHandler->AddSignal(SIGTERM, "TERM"); this->signalsHandler->AddSignal(SIGTERM, "TERM");
} }
catch (const MediaSoupError &error) { catch (const MediaSoupError &error)
{
MS_THROW_ERROR("error creating the SignalsHandler: %s", error.what()); MS_THROW_ERROR("error creating the SignalsHandler: %s", error.what());
} }
MS_DEBUG("SignalsHandler ready"); MS_DEBUG("SignalsHandler ready");
...@@ -35,10 +37,12 @@ Dispatcher::Dispatcher() { ...@@ -35,10 +37,12 @@ Dispatcher::Dispatcher() {
// Create a ControlProtocol TCP server. // Create a ControlProtocol TCP server.
std::string ip = Settings::configuration.ControlProtocol.listenIP; std::string ip = Settings::configuration.ControlProtocol.listenIP;
MS_PORT port = Settings::configuration.ControlProtocol.listenPort; MS_PORT port = Settings::configuration.ControlProtocol.listenPort;
try { try
{
this->controlProtocolTCPServer = new ControlProtocol::TCPServer(this, this, ip, port); this->controlProtocolTCPServer = new ControlProtocol::TCPServer(this, this, ip, port);
} }
catch (const MediaSoupError &error) { catch (const MediaSoupError &error)
{
MS_THROW_ERROR("error creating a ControlProtocol TCP server in %s : %d: %s", ip.c_str(), port, error.what()); MS_THROW_ERROR("error creating a ControlProtocol TCP server in %s : %d: %s", ip.c_str(), port, error.what());
} }
MS_DEBUG("ControlProtocol TCP server listening into %s : %d", this->controlProtocolTCPServer->GetLocalIP().c_str(), this->controlProtocolTCPServer->GetLocalPort()); MS_DEBUG("ControlProtocol TCP server listening into %s : %d", this->controlProtocolTCPServer->GetLocalIP().c_str(), this->controlProtocolTCPServer->GetLocalPort());
...@@ -50,18 +54,21 @@ Dispatcher::Dispatcher() { ...@@ -50,18 +54,21 @@ Dispatcher::Dispatcher() {
// since the first entry will be in position 1. // since the first entry will be in position 1.
this->controlProtocolUnixStreamSockets.push_back(nullptr); this->controlProtocolUnixStreamSockets.push_back(nullptr);
for (int workerId=1; workerId <= num_workers; workerId++) { for (int workerId=1; workerId <= num_workers; workerId++)
{
int fd = Worker::GetControlProtocolRemoteSocket(workerId); int fd = Worker::GetControlProtocolRemoteSocket(workerId);
ControlProtocol::UnixStreamSocket* controlProtocolUnixStreamSocket; ControlProtocol::UnixStreamSocket* controlProtocolUnixStreamSocket;
try { try
{
controlProtocolUnixStreamSocket = new ControlProtocol::UnixStreamSocket(this, fd); controlProtocolUnixStreamSocket = new ControlProtocol::UnixStreamSocket(this, fd);
// Attach the workerId as user data. // Attach the workerId as user data.
int* data = new int(workerId); int* data = new int(workerId);
controlProtocolUnixStreamSocket->SetUserData((void*)data); controlProtocolUnixStreamSocket->SetUserData((void*)data);
} }
catch (const MediaSoupError &error) { catch (const MediaSoupError &error)
{
MS_THROW_ERROR("error creating a ControlProtocol Unix socket for Worker %d: %s", workerId, error.what()); MS_THROW_ERROR("error creating a ControlProtocol Unix socket for Worker %d: %s", workerId, error.what());
} }
...@@ -84,16 +91,17 @@ Dispatcher::Dispatcher() { ...@@ -84,16 +91,17 @@ Dispatcher::Dispatcher() {
MS_DEBUG("libuv loop ends"); MS_DEBUG("libuv loop ends");
} }
Dispatcher::~Dispatcher()
Dispatcher::~Dispatcher() { {
MS_TRACE(); MS_TRACE();
} }
void Dispatcher::Close()
void Dispatcher::Close() { {
MS_TRACE(); MS_TRACE();
if (this->closed) { if (this->closed)
{
MS_ERROR("already closed"); MS_ERROR("already closed");
return; return;
} }
...@@ -120,20 +128,21 @@ void Dispatcher::Close() { ...@@ -120,20 +128,21 @@ void Dispatcher::Close() {
// Close the ControlProtocol UnixStream sockets. // Close the ControlProtocol UnixStream sockets.
int num_workers = Worker::CountWorkers(); int num_workers = Worker::CountWorkers();
for (int workerId=1; workerId <= num_workers; workerId++) { for (int workerId=1; workerId <= num_workers; workerId++)
this->controlProtocolUnixStreamSockets[workerId]->Close(); this->controlProtocolUnixStreamSockets[workerId]->Close();
}
} }
void Dispatcher::onSignal(SignalsHandler* signalsHandler, int signum)
void Dispatcher::onSignal(SignalsHandler* signalsHandler, int signum) { {
MS_TRACE(); MS_TRACE();
switch(signum) { switch (signum)
{
// SIGUSR1 means configuration reload. // SIGUSR1 means configuration reload.
case SIGUSR1: case SIGUSR1:
MS_NOTICE("signal USR1 received, reloading configuration"); MS_NOTICE("signal USR1 received, reloading configuration");
if (Settings::ReloadConfigurationFile()) { if (Settings::ReloadConfigurationFile())
{
// Print new configuration. // Print new configuration.
Settings::PrintConfiguration(); Settings::PrintConfiguration();
} }
...@@ -154,13 +163,13 @@ void Dispatcher::onSignal(SignalsHandler* signalsHandler, int signum) { ...@@ -154,13 +163,13 @@ void Dispatcher::onSignal(SignalsHandler* signalsHandler, int signum) {
} }
} }
void Dispatcher::onSignalsHandlerClosed(SignalsHandler* signalsHandler)
void Dispatcher::onSignalsHandlerClosed(SignalsHandler* signalsHandler) { {
MS_TRACE(); MS_TRACE();
} }
void Dispatcher::onControlProtocolNewTCPConnection(ControlProtocol::TCPServer* tcpServer, ControlProtocol::TCPConnection* connection)
void Dispatcher::onControlProtocolNewTCPConnection(ControlProtocol::TCPServer* tcpServer, ControlProtocol::TCPConnection* connection) { {
MS_TRACE(); MS_TRACE();
MS_DEBUG("new ControlProtocol TCP connection:"); MS_DEBUG("new ControlProtocol TCP connection:");
...@@ -168,8 +177,8 @@ void Dispatcher::onControlProtocolNewTCPConnection(ControlProtocol::TCPServer* t ...@@ -168,8 +177,8 @@ void Dispatcher::onControlProtocolNewTCPConnection(ControlProtocol::TCPServer* t
connection->Dump(); connection->Dump();
} }
void Dispatcher::onControlProtocolTCPConnectionClosed(ControlProtocol::TCPServer* tcpServer, ControlProtocol::TCPConnection* connection, bool is_closed_by_peer)
void Dispatcher::onControlProtocolTCPConnectionClosed(ControlProtocol::TCPServer* tcpServer, ControlProtocol::TCPConnection* connection, bool is_closed_by_peer) { {
MS_TRACE(); MS_TRACE();
if (is_closed_by_peer) if (is_closed_by_peer)
...@@ -180,8 +189,8 @@ void Dispatcher::onControlProtocolTCPConnectionClosed(ControlProtocol::TCPServer ...@@ -180,8 +189,8 @@ void Dispatcher::onControlProtocolTCPConnectionClosed(ControlProtocol::TCPServer
tcpServer->Dump(); tcpServer->Dump();
} }
void Dispatcher::onControlProtocolMessage(ControlProtocol::TCPConnection* connection, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len)
void Dispatcher::onControlProtocolMessage(ControlProtocol::TCPConnection* connection, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len) { {
MS_TRACE(); MS_TRACE();
MS_DEBUG("ControlProtocol message received from TCP %s : %u", connection->GetPeerIP().c_str(), (unsigned int)connection->GetPeerPort()); MS_DEBUG("ControlProtocol message received from TCP %s : %u", connection->GetPeerIP().c_str(), (unsigned int)connection->GetPeerPort());
...@@ -193,8 +202,8 @@ void Dispatcher::onControlProtocolMessage(ControlProtocol::TCPConnection* connec ...@@ -193,8 +202,8 @@ void Dispatcher::onControlProtocolMessage(ControlProtocol::TCPConnection* connec
bool relayToAllWorkers = false; bool relayToAllWorkers = false;
bool replyOK = true; bool replyOK = true;
if (relayToRandomWorker)
if (relayToRandomWorker) { {
int workerId = (int)Utils::Crypto::GetRandomUInt(1, (unsigned int)Worker::CountWorkers()); int workerId = (int)Utils::Crypto::GetRandomUInt(1, (unsigned int)Worker::CountWorkers());
MS_INFO("relaying ControlProtocol message to Worker #%d ...", workerId); MS_INFO("relaying ControlProtocol message to Worker #%d ...", workerId);
...@@ -204,10 +213,11 @@ void Dispatcher::onControlProtocolMessage(ControlProtocol::TCPConnection* connec ...@@ -204,10 +213,11 @@ void Dispatcher::onControlProtocolMessage(ControlProtocol::TCPConnection* connec
controlProtocolUnixStreamSocket->Write(raw, len); controlProtocolUnixStreamSocket->Write(raw, len);
} }
if (relayToAllWorkers)
if (relayToAllWorkers) { {
int num_workers = Worker::CountWorkers(); int num_workers = Worker::CountWorkers();
for (int workerId=1; workerId <= num_workers; workerId++) { for (int workerId=1; workerId <= num_workers; workerId++)
{
ControlProtocol::UnixStreamSocket* controlProtocolUnixStreamSocket = controlProtocolUnixStreamSockets[workerId]; ControlProtocol::UnixStreamSocket* controlProtocolUnixStreamSocket = controlProtocolUnixStreamSockets[workerId];
MS_INFO("relaying ControlProtocol message to Worker #%d ...", workerId); MS_INFO("relaying ControlProtocol message to Worker #%d ...", workerId);
...@@ -215,8 +225,8 @@ void Dispatcher::onControlProtocolMessage(ControlProtocol::TCPConnection* connec ...@@ -215,8 +225,8 @@ void Dispatcher::onControlProtocolMessage(ControlProtocol::TCPConnection* connec
} }
} }
if (replyOK)
if (replyOK) { {
MS_INFO("replying 'OK, message received' via TCP ..."); MS_INFO("replying 'OK, message received' via TCP ...");
// TEST: Write(std::string &data) // TEST: Write(std::string &data)
...@@ -240,8 +250,8 @@ void Dispatcher::onControlProtocolMessage(ControlProtocol::TCPConnection* connec ...@@ -240,8 +250,8 @@ void Dispatcher::onControlProtocolMessage(ControlProtocol::TCPConnection* connec
} }
} }
void Dispatcher::onControlProtocolMessage(ControlProtocol::UnixStreamSocket* unixSocket, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len)
void Dispatcher::onControlProtocolMessage(ControlProtocol::UnixStreamSocket* unixSocket, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len) { {
MS_TRACE(); MS_TRACE();
// Get the workerId associated to this socket. // Get the workerId associated to this socket.
...@@ -256,8 +266,8 @@ void Dispatcher::onControlProtocolMessage(ControlProtocol::UnixStreamSocket* uni ...@@ -256,8 +266,8 @@ void Dispatcher::onControlProtocolMessage(ControlProtocol::UnixStreamSocket* uni
// TODO: process the ControlProtocol::Message. // TODO: process the ControlProtocol::Message.
} }
void Dispatcher::onControlProtocolUnixStreamSocketClosed(ControlProtocol::UnixStreamSocket* unixSocket, bool is_closed_by_peer)
void Dispatcher::onControlProtocolUnixStreamSocketClosed(ControlProtocol::UnixStreamSocket* unixSocket, bool is_closed_by_peer) { {
MS_TRACE(); MS_TRACE();
// Get the workerId associated to this socket. // Get the workerId associated to this socket.
......
...@@ -4,10 +4,10 @@ ...@@ -4,10 +4,10 @@
#include "MediaSoupError.h" #include "MediaSoupError.h"
#include "Logger.h" #include "Logger.h"
/* Static variables. */ /* Static variables. */
std::vector<const char*> LibSRTP::errors = { std::vector<const char*> LibSRTP::errors =
{
// From 0 (err_status_ok) to 24 (err_status_pfkey_err). // From 0 (err_status_ok) to 24 (err_status_pfkey_err).
"nothing to report (err_status_ok)", "nothing to report (err_status_ok)",
"unspecified failure (err_status_fail)", "unspecified failure (err_status_fail)",
...@@ -36,10 +36,10 @@ std::vector<const char*> LibSRTP::errors = { ...@@ -36,10 +36,10 @@ std::vector<const char*> LibSRTP::errors = {
"error while using pfkey (err_status_pfkey_err)" "error while using pfkey (err_status_pfkey_err)"
}; };
/* Static methods. */ /* Static methods. */
void LibSRTP::ClassInit() { void LibSRTP::ClassInit()
{
MS_TRACE(); MS_TRACE();
err_status_t err; err_status_t err;
...@@ -51,8 +51,8 @@ void LibSRTP::ClassInit() { ...@@ -51,8 +51,8 @@ void LibSRTP::ClassInit() {
MS_THROW_ERROR("srtp_init() failed: %s", LibSRTP::GetErrorString(err)); MS_THROW_ERROR("srtp_init() failed: %s", LibSRTP::GetErrorString(err));
} }
void LibSRTP::ClassDestroy()
void LibSRTP::ClassDestroy() { {
MS_TRACE(); MS_TRACE();
err_status_t err; err_status_t err;
......
差异被折叠。
...@@ -3,17 +3,16 @@ ...@@ -3,17 +3,16 @@
#include "Logger.h" #include "Logger.h"
#include "Version.h" #include "Version.h"
/* Static variables. */ /* Static variables. */
__thread std::string* Logger::threadName = nullptr; __thread std::string* Logger::threadName = nullptr;
__thread const char* Logger::threadNamePtr = nullptr; __thread const char* Logger::threadNamePtr = nullptr;
bool Logger::isSyslogEnabled = false; bool Logger::isSyslogEnabled = false;
/* Static methods. */ /* Static methods. */
void Logger::ThreadInit(const std::string name) { void Logger::ThreadInit(const std::string name)
{
// Store the name for this thread in thread local storage. // Store the name for this thread in thread local storage.
if (Logger::threadName) if (Logger::threadName)
delete Logger::threadName; delete Logger::threadName;
...@@ -25,8 +24,8 @@ void Logger::ThreadInit(const std::string name) { ...@@ -25,8 +24,8 @@ void Logger::ThreadInit(const std::string name) {
MS_TRACE(); MS_TRACE();
} }
void Logger::EnableSyslog()
void Logger::EnableSyslog() { {
MS_TRACE(); MS_TRACE();
openlog(Version::command.c_str(), (LOG_PID), Settings::configuration.syslogFacility); openlog(Version::command.c_str(), (LOG_PID), Settings::configuration.syslogFacility);
......
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论