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

New C++ style.

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