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

New single thread design begins.

上级 eb1115e9
...@@ -48,7 +48,6 @@ SYSTEM_LIBS := pthread ...@@ -48,7 +48,6 @@ SYSTEM_LIBS := pthread
# External libraries with pkg-config support. # External libraries with pkg-config support.
PKG_LIBS := PKG_LIBS :=
PKG_LIBS += libuv >= 1.6.1 PKG_LIBS += libuv >= 1.6.1
PKG_LIBS += libconfig++ >= 1.4.8
PKG_LIBS += openssl >= 1.0.1 PKG_LIBS += openssl >= 1.0.1
PKG_LIBS += libsrtp >= 1.5.2 PKG_LIBS += libsrtp >= 1.5.2
......
#ifndef MS_CONTROL_PROTOCOL_MESSAGE_H
#define MS_CONTROL_PROTOCOL_MESSAGE_H
#include "common.h"
namespace ControlProtocol
{
class Message
{
public:
enum class Kind
{
Request = 1,
Response,
Notification
};
public:
Message(Kind);
virtual ~Message();
Kind GetKind();
virtual bool IsValid(); // TODO: Must be pure virtual.
void SetTransaction(int32_t transaction);
int32_t GetTransaction();
virtual void Dump() = 0;
protected:
Kind kind;
int32_t transaction = 0;
};
/* Inlime methods. */
inline
Message::Kind Message::GetKind()
{
return this->kind;
}
inline
void Message::SetTransaction(int32_t transaction)
{
this->transaction = transaction;
}
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:
Parser();
virtual ~Parser();
/**
* Parses the given buffer.
*
* @param buffer The buffer to parse.
* @param len The lenght of the buffer.
*
* @return Returns a pointer to ControlProtocol::Message if parsing succeded,
* or nullptr if the message is not completed or parsing failed.
*/
Message* Parse(const MS_BYTE* buffer, size_t len);
/**
* Checks whether the ongoing parsing has error or not.
*
* @return true if there is parsing error, false otherwise.
*/
bool HasError();
/**
* Get the length of the complete or uncomplete message parsed or being parsed.
*
* @return The number of chars parsed in the current message.
*/
size_t GetParsedLen();
/**
* Resets the parser internals. Must be called before parsing a new message
* (regardless the previous one succeded or not).
*/
void Reset();
/**
* Prints current status of the parser.
*/
void Dump();
protected:
size_t parsedLen;
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
{
Hello = 1,
Authenticate,
CreateConference
};
public:
Request(Type);
virtual ~Request();
virtual void Dump() = 0;
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
{
public:
virtual void onControlProtocolMessage(ControlProtocol::TCPConnection* connection, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len) = 0;
};
public:
TCPConnection(Reader* reader, size_t bufferSize);
virtual ~TCPConnection();
/* Pure virtual methods inherited from ::TCPConnection. */
public:
virtual void userOnTCPConnectionRead(const MS_BYTE* data, size_t len) override;
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"
#include "ControlProtocol/TCPConnection.h"
#include "ControlProtocol/Message.h"
#include <string>
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:
TCPServer(Listener* listener, ControlProtocol::TCPConnection::Reader* reader, const std::string &ip, MS_PORT port);
/* 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:
// 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
{
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:
UnixStreamSocket(Listener* listener, int fd);
virtual ~UnixStreamSocket();
/* 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:
// 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:
RequestAuthenticate();
virtual ~RequestAuthenticate();
void SetUser(const char* str, size_t len);
void SetPasswd(const char* str, size_t len);
virtual void Dump() override;
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:
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:
RequestHello();
virtual ~RequestHello();
virtual void Dump() override;
};
} // namespace ControlProtocol
#endif
#ifndef MS_DAEMON_H
#define MS_DAEMON_H
class Daemon
{
public:
static void Daemonize();
static void SendOKStatusToAncestor();
static void SendErrorStatusToAncestor();
static bool IsDaemonized();
static void End();
private:
static bool WritePIDFile();
static void DeletePIDFile();
static bool WaitForDaemonizedStatus(char* status);
static void SendStatusToAncestor(char status);
private:
static int statusPipe[2];
static bool isDaemonized;
static bool hasWrittenPIDFile;
};
#endif
#ifndef MS_DEP_LIBUV_H #ifndef MS_DEP_LIBUV_H
#define MS_DEP_LIBUV_H #define MS_DEP_LIBUV_H
#include "common.h"
#include <uv.h> #include <uv.h>
class DepLibUV class DepLibUV
{ {
public: public:
static void ClassInit(); static void ClassInit();
static void ThreadInit(); static void ClassDestroy();
static void ThreadDestroy();
static uv_loop_t* GetLoop();
static void RunLoop(); static void RunLoop();
static uv_loop_t* GetLoop();
private: private:
static __thread uv_loop_t* loop; static uv_loop_t* loop;
}; };
/* Inline static methods. */ /* Inline static methods. */
......
#ifndef MS_DISPATCHER_H
#define MS_DISPATCHER_H
#include "common.h"
#include "handles/SignalsHandler.h"
#include "ControlProtocol/TCPServer.h"
#include "ControlProtocol/TCPConnection.h"
#include "ControlProtocol/UnixStreamSocket.h"
#include "ControlProtocol/Message.h"
#include <vector>
class Dispatcher :
public SignalsHandler::Listener,
public ControlProtocol::TCPServer::Listener,
public ControlProtocol::TCPConnection::Reader,
public ControlProtocol::UnixStreamSocket::Listener
{
public:
Dispatcher();
virtual ~Dispatcher();
void Close();
/* Methods inherited from SignalsHandler::Listener. */
public:
virtual void onSignal(SignalsHandler* signalsHandler, int signum) override;
virtual void onSignalsHandlerClosed(SignalsHandler* signalsHandler) override;
/* Methods inherited from ControlProtocol::TCPServer::Listener. */
public:
virtual void onControlProtocolNewTCPConnection(ControlProtocol::TCPServer* tcpServer, ControlProtocol::TCPConnection* connection) override;
virtual void onControlProtocolTCPConnectionClosed(ControlProtocol::TCPServer* tcpServer, ControlProtocol::TCPConnection* connection, bool is_closed_by_peer) override;
/* Methods inherited from ControlProtocol::TCPConnection::Reader. */
public:
virtual void onControlProtocolMessage(ControlProtocol::TCPConnection* connection, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len) override;
/* Methods inherited from ControlProtocol::UnixStreamSocket::Listener. */
public:
virtual void onControlProtocolMessage(ControlProtocol::UnixStreamSocket* unixSocket, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len) override;
virtual void onControlProtocolUnixStreamSocketClosed(ControlProtocol::UnixStreamSocket* unixSocket, bool is_closed_by_peer) override;
private:
// Allocated by this:
SignalsHandler* signalsHandler = nullptr;
ControlProtocol::TCPServer* controlProtocolTCPServer = nullptr;
typedef std::vector<ControlProtocol::UnixStreamSocket*> ControlProtocolUnixStreamSockets;
ControlProtocolUnixStreamSockets controlProtocolUnixStreamSockets;
// Others:
bool closed = false;
};
#endif
...@@ -50,34 +50,30 @@ extern "C" ...@@ -50,34 +50,30 @@ extern "C"
/* /*
* This macro must point to a unsigned int function, method or variable that * This macro must point to a unsigned int function, method or variable that
* returns Syslog logging level. * returns the Syslog logging level.
*/ */
#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 Init(const std::string name);
static const char* GetThreadName(); static const char* GetProcessName();
static void EnableSyslog(); static void EnableSyslog();
static bool IsSyslogEnabled(); static bool IsSyslogEnabled();
static bool HasDebugLevel(); static bool HasDebugLevel();
private: private:
// NOTE: static std::string processName;
// __thread implemented in GCC >= 4.7 and Clang.
// local_thread implemented in GCC >= 4.8.
static __thread std::string* threadName;
static __thread const char* threadNamePtr;
static bool isSyslogEnabled; static bool isSyslogEnabled;
}; };
/* Inline static methods. */ /* Inline static methods. */
inline inline
const char* Logger::GetThreadName() const char* Logger::GetProcessName()
{ {
return Logger::threadNamePtr; return Logger::processName.c_str();
} }
inline inline
...@@ -98,11 +94,11 @@ bool Logger::HasDebugLevel() ...@@ -98,11 +94,11 @@ bool Logger::HasDebugLevel()
#define _MS_LOG_STR "[%s] %s:%d | %s::%s()" #define _MS_LOG_STR "[%s] %s:%d | %s::%s()"
#define _MS_LOG_STR_DESC _MS_LOG_STR " | " #define _MS_LOG_STR_DESC _MS_LOG_STR " | "
#define _MS_FILE (std::strchr(__FILE__, '/') ? std::strchr(__FILE__, '/') + 1 : __FILE__) #define _MS_FILE (std::strchr(__FILE__, '/') ? std::strchr(__FILE__, '/') + 1 : __FILE__)
#define _MS_LOG_ARG Logger::GetThreadName(), _MS_FILE, __LINE__, MS_CLASS, __FUNCTION__ #define _MS_LOG_ARG Logger::GetProcessName(), _MS_FILE, __LINE__, MS_CLASS, __FUNCTION__
#else #else
#define _MS_LOG_STR "[%s] %s::%s()" #define _MS_LOG_STR "[%s] %s::%s()"
#define _MS_LOG_STR_DESC _MS_LOG_STR " | " #define _MS_LOG_STR_DESC _MS_LOG_STR " | "
#define _MS_LOG_ARG Logger::GetThreadName(), MS_CLASS, __FUNCTION__ #define _MS_LOG_ARG Logger::GetProcessName(), MS_CLASS, __FUNCTION__
#endif #endif
#define _MS_TO_STDOUT(prefix) \ #define _MS_TO_STDOUT(prefix) \
......
#ifndef MS_WORKER_H
#define MS_WORKER_H
#include "common.h"
#include "handles/SignalsHandler.h"
class Loop :
public SignalsHandler::Listener
{
public:
Loop();
~Loop();
// TODO: IMHO this can be private.
void Close();
/* Methods inherited from SignalsHandler::Listener. */
public:
virtual void onSignal(SignalsHandler* signalsHandler, int signum) override;
virtual void onSignalsHandlerClosed(SignalsHandler* signalsHandler) override;
private:
// Allocated by this.
SignalsHandler* signalsHandler = nullptr;
// Others.
bool closed = false;
};
#endif
#ifndef MS_MEDIASOUP_H
#define MS_MEDIASOUP_H
/*
* MediaSoup top class.
*
* Entry point of the application.
*/
class MediaSoup
{
public:
// Set the process.
static void SetProcess();
// Run MediaSoup.
static void Run();
// Stop MediaSoup.
static void End();
private:
static void IgnoreSignals();
static void SetKernelLimits();
static void SetUserGroup();
static void ThreadInit();
static void ThreadDestroy();
static void ClassInit();
static void ClassDestroy();
static void RunWorkerThread(void* data);
};
#endif
...@@ -8,7 +8,8 @@ ...@@ -8,7 +8,8 @@
namespace RTC namespace RTC
{ {
class UDPSocket : public ::UDPSocket class UDPSocket :
public ::UDPSocket
{ {
public: public:
class Listener class Listener
......
...@@ -4,8 +4,6 @@ ...@@ -4,8 +4,6 @@
#include "common.h" #include "common.h"
#include <map> #include <map>
#include <string> #include <string>
#include <vector>
#include <libconfig.h++>
extern "C" extern "C"
{ {
#include <syslog.h> #include <syslog.h>
...@@ -14,28 +12,11 @@ extern "C" ...@@ -14,28 +12,11 @@ extern "C"
class Settings class Settings
{ {
public: public:
// Struct holding command line arguments. // Struct holding the configuration.
struct Arguments
{
std::string configFile;
bool daemonize { false };
std::string pidFile;
std::string user;
std::string group;
};
// 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 };
struct
{
std::string listenIP { "127.0.0.1" };
MS_PORT listenPort { 4080 };
} ControlProtocol;
struct struct
{ {
...@@ -52,32 +33,19 @@ public: ...@@ -52,32 +33,19 @@ public:
}; };
public: public:
static void ReadArguments(int argc, char* argv[]); static void SetConfiguration(int argc, char* argv[]);
static void PrintHelp(bool error);
static void PrintVersion();
static void SetDefaultConfiguration();
static void ReadConfigurationFile();
static void ConfigurationPostCheck();
static bool ReloadConfigurationFile();
static void PrintConfiguration(); static void PrintConfiguration();
private: private:
static libconfig::Config* ParseConfigFile(); static void SetDefaultRtcListenIP(int requested_family);
static void SetLogLevel(std::string &level); static void SetLogLevel(std::string &level);
static void SetSyslogFacility(std::string &facility); static void SetSyslogFacility(std::string &facility);
static void SetNumWorkers(int numWorkers); static void SetRtcListenIPv4(const std::string &ip);
static void SetDefaultNumWorkers(); static void SetRtcListenIPv6(const std::string &ip);
static void SetControlProtocolListenIP(const std::string &ip); static void SetRtcPorts();
static void SetControlProtocolListenPort(MS_PORT port); static void SetDtlsCertificateAndPrivateKeyFiles();
static void SetRTClistenIPv4(const std::string &ip);
static void SetRTClistenIPv6(const std::string &ip);
static void SetDefaultRTClistenIP(int requested_family);
static bool IsBindableIP(const std::string &ip, int family, int* _bind_err);
static void SetRTCports(MS_PORT minPort, MS_PORT maxPort);
static void SetDtlsCertificateAndPrivateKeyFiles(std::string& dtlsCertificateFile, std::string& dtlsPrivateKeyFile);
public: public:
static struct Arguments arguments;
static struct Configuration configuration; static struct Configuration configuration;
private: private:
......
...@@ -217,17 +217,17 @@ namespace Utils ...@@ -217,17 +217,17 @@ namespace Utils
class Crypto class Crypto
{ {
public: public:
static void ThreadInit(); static void ClassInit();
static void ThreadDestroy(); static void ClassDestroy();
static unsigned int GetRandomUInt(unsigned int min, unsigned int max); static unsigned int GetRandomUInt(unsigned int min, unsigned int max);
static const char* GetRandomHexString(char* str, size_t len); static const char* GetRandomHexString(char* str, size_t len);
static MS_4BYTES CRC32(const MS_BYTE* data, size_t size); static MS_4BYTES GetCRC32(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* GetHMAC_SHA1(const std::string &key, const MS_BYTE* data, size_t len);
private: private:
static __thread unsigned int seed; static unsigned int seed;
static __thread HMAC_CTX hmacSha1Ctx; static HMAC_CTX hmacSha1Ctx;
static __thread MS_BYTE hmacSha1Buffer[]; static MS_BYTE hmacSha1Buffer[];
static const MS_4BYTES crc32Table[256]; static const MS_4BYTES crc32Table[256];
}; };
...@@ -262,7 +262,7 @@ namespace Utils ...@@ -262,7 +262,7 @@ namespace Utils
} }
inline inline
MS_4BYTES Crypto::CRC32(const MS_BYTE* data, size_t size) MS_4BYTES Crypto::GetCRC32(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,6 +272,6 @@ namespace Utils ...@@ -272,6 +272,6 @@ namespace Utils
return crc ^ ~0U; return crc ^ ~0U;
} }
} // namespace Utils }
#endif #endif
#ifndef MS_VERSION_H
#define MS_VERSION_H
#include <string>
class Version
{
public:
static const std::string GetVersion();
static const std::string GetNameAndVersion();
public:
static const int versionMajor;
static const int versionMinor;
static const int versionTiny;
static const std::string name;
static const std::string command;
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"
#include <map>
#include <atomic>
// TMP
#include "RTC/Room.h"
class Worker :
public ControlProtocol::UnixStreamSocket::Listener
{
public:
static void ThreadInit(int workerId);
static void ThreadDestroy();
static void SetWorker(int workerId, Worker* worker);
static int CountWorkers();
static bool AreAllWorkersRunning();
static int GetControlProtocolRemoteSocket(int workerId);
private:
typedef std::map <int, Worker*> Workers;
static Workers workers;
static int numWorkers;
static std::atomic<int> numWorkersRunning;
public:
Worker(int workerId);
~Worker();
void Close();
int GetControlProtocolRemoteSocket();
private:
void BlockSignals();
/* Methods inherited from ControlProtocol::UnixStreamSocket::Listener. */
public:
virtual void onControlProtocolMessage(ControlProtocol::UnixStreamSocket* unixSocket, ControlProtocol::Message* msg, const MS_BYTE* raw, size_t len) override;
virtual void onControlProtocolUnixStreamSocketClosed(ControlProtocol::UnixStreamSocket* unixSocket, bool is_closed_by_peer) override;
private:
// Allocated by this:
ControlProtocol::UnixStreamSocket* controlProtocolUnixStreamSocket = nullptr;
// Others:
int workerId = 0;
int controlProtocolRemoteSocket = 0;
// TMP
RTC::Room* room = nullptr;
};
#endif
...@@ -6,7 +6,6 @@ ...@@ -6,7 +6,6 @@
#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
#include <netinet/in.h> // sockaddr_in, sockaddr_in6 #include <netinet/in.h> // sockaddr_in, sockaddr_in6
#include <arpa/inet.h> // htonl(), htons(), ntohl(), ntohs() #include <arpa/inet.h> // htonl(), htons(), ntohl(), ntohs()
#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_CLASS "ControlProtocol::Message"
#include "ControlProtocol/Message.h"
#include "Logger.h"
namespace ControlProtocol
{
/* Instance methods. */
Message::Message(Kind kind) :
kind(kind)
{
MS_TRACE();
}
Message::~Message()
{
MS_TRACE();
}
// TMP: must be pure virtual.
bool Message::IsValid()
{
MS_TRACE();
return true;
}
} // namespace ControlProtocol
差异被折叠。
#define MS_CLASS "ControlProtocol::Parser"
#include "ControlProtocol/Parser.h"
#include "ControlProtocol/messages.h"
#include "Logger.h"
#include <cstdlib> // std::atol()
#define MARK(M, P) (M = (P) - buffer)
#define LEN(AT, P) ((P) - buffer - (AT))
#define LEN_FROM_MARK (p - buffer - this->mark)
#define PTR_TO(F) (buffer + (F))
#define PTR_TO_MARK (const char*)(buffer + this->mark)
namespace ControlProtocol
{
/**
* Ragel: machine definition
*/
%%{
machine MessageParser;
alphtype unsigned char;
action mark
{
MARK(this->mark, p);
}
action on_transaction
{
int32_t transaction = std::atol(PTR_TO_MARK);
this->msg->SetTransaction(transaction);
}
action on_message
{
fbreak;
}
include core_grammar "../core_grammar.rl";
transaction = ULONG >mark %on_transaction;
include RequestHello "grammar/RequestHello.rl";
include RequestAuthenticate "grammar/RequestAuthenticate.rl";
include RequestCreateConference "grammar/RequestCreateConference.rl";
Request = RequestHello |
RequestAuthenticate |
RequestCreateConference;
#Message = Request | Response | Notification;
Message = Request @on_message;
main := Message;
}%%
/**
* Ragel: %%write data
* This generates Ragel's static variables such as:
* static const int MessageParser_start
*/
%%write data;
Parser::Parser()
{
MS_TRACE();
Reset();
}
Parser::~Parser()
{
MS_TRACE();
}
Message* Parser::Parse(const MS_BYTE* buffer, size_t len)
{
MS_TRACE();
// Used by Ragel:
const unsigned char* p;
const unsigned char* pe;
// const unsigned char* eof;
MS_ASSERT(this->parsedLen <= len, "parsedLen pasts end of buffer");
p = (const unsigned char*)buffer + this->parsedLen;
pe = (const unsigned char*)buffer + len;
// eof = nullptr; // Ragel manual pag 36 (eof variable).
/**
* Ragel: %%write exec
* This updates cs variable needed by Ragel (so this->cs at the end) and p.
*/
%%write exec;
this->parsedLen = p - (const unsigned char*)buffer;
MS_ASSERT(p <= pe, "buffer overflow after parsing execute");
MS_ASSERT(this->parsedLen <= len, "parsedLen longer than length");
MS_ASSERT(this->mark < len, "mark is after buffer end");
// Parsing succedded.
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())
{
MS_ERROR("invalid message");
delete this->msg;
return (this->msg = nullptr);
}
return this->msg;
}
// Parsing 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)
{
delete this->msg;
this->msg = nullptr;
}
return nullptr;
}
// Parsing not finished.
else
{
MS_DEBUG("parsing not finished");
return nullptr;
}
}
bool Parser::HasError()
{
MS_TRACE();
return (this->cs == (size_t)MessageParser_error);
}
size_t Parser::GetParsedLen()
{
MS_TRACE();
return this->parsedLen;
}
void Parser::Reset()
{
MS_TRACE();
this->parsedLen = 0;
this->msg = nullptr;
this->cs = 0;
this->mark = 0;
/**
* Ragel: %%write init
* This sets cs variable needed by Ragel (so this->cs at the end).
*/
%%write init;
}
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
#define MS_CLASS "ControlProtocol::Request"
#include "ControlProtocol/Request.h"
#include "Logger.h"
namespace ControlProtocol
{
/* Instance methods. */
Request::Request(Type type) :
Message(Message::Kind::Request),
type(type)
{
MS_TRACE();
}
Request::~Request()
{
MS_TRACE();
}
} // namespace ControlProtocol
#define MS_CLASS "ControlProtocol::TCPConnection"
#include "ControlProtocol/TCPConnection.h"
#include "Logger.h"
#include <cstring> // std::memmove()
namespace ControlProtocol
{
/* Instance methods. */
TCPConnection::TCPConnection(Reader* reader, size_t bufferSize) :
::TCPConnection(bufferSize),
reader(reader)
{
MS_TRACE();
// Initiate a ControlProtocol::Parser.
this->parser = new ControlProtocol::Parser();
}
TCPConnection::~TCPConnection()
{
MS_TRACE();
if (this->parser)
delete this->parser;
}
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)
{
ControlProtocol::Message* msg;
// Tell the parser to parse the buffer starting from the beginning of the latest
// detected message until the end of the data in the buffer.
msg = this->parser->Parse(this->buffer + this->msgStart, this->bufferDataLen - this->msgStart);
size_t parsed_len = parser->GetParsedLen();
// Message parsed.
if (msg)
{
// Notify the reader.
this->reader->onControlProtocolMessage(this, msg, this->buffer + this->msgStart, parsed_len);
// Free the message.
delete msg;
// 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)
{
MS_DEBUG("no more space in the buffer, emptying the buffer data");
this->msgStart = 0;
this->bufferDataLen = 0;
}
// If there is still space in the buffer, set the beginning of the next
// parsing to the next position after the parsed message.
else
{
this->msgStart += parsed_len;
}
// Reset the parser.
this->parser->Reset();
// 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)
{
MS_DEBUG("there is more data after the parsed message, continue parsing");
continue;
}
else
{
break;
}
}
// Parsing error. Close the connection.
else if (this->parser->HasError())
{
MS_ERROR("parsing error, closing the connection");
// Close the connection.
Close();
// Exit the parsing loop.
break;
}
// Message not finished.
else
{
// Check if the buffer is full.
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)
{
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 connection.
else
{
MS_ERROR("no more space in the buffer for the unfinished message being parsed, closing the connection");
// Close the socket.
Close();
}
}
// The buffer is not full.
else
{
MS_DEBUG("message not finished yet, waiting for more data");
}
// Exit the parsing loop.
break;
}
} // while()
}
} // namespace ControlProtocol
#define MS_CLASS "ControlProtocol::TCPServer"
#include "ControlProtocol/TCPServer.h"
#include "Logger.h"
namespace ControlProtocol
{
/* Instance methods. */
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)
{
MS_TRACE();
// Allocate a new ControlProtocol::TCPConnection and pass it our reader.
*connection = new ControlProtocol::TCPConnection(this->reader, 65536);
}
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)
{
MS_TRACE();
// Notify the listener.
this->listener->onControlProtocolTCPConnectionClosed(this, static_cast<ControlProtocol::TCPConnection*>(connection), is_closed_by_peer);
}
void TCPServer::userOnTCPServerClosed()
{
MS_TRACE();
}
} // namespace ControlProtocol
#define MS_CLASS "ControlProtocol::UnixStreamSocket"
#include "ControlProtocol/UnixStreamSocket.h"
#include "Logger.h"
#include <cstring> // std::memmove()
namespace ControlProtocol
{
/* Instance methods. */
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()
{
MS_TRACE();
if (this->parser)
delete this->parser;
}
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)
{
ControlProtocol::Message* msg;
// Tell the parser to parse the buffer starting from the beginning of the latest
// detected message until the end of the data in the buffer.
msg = this->parser->Parse(this->buffer + this->msgStart, this->bufferDataLen - this->msgStart);
size_t parsed_len = parser->GetParsedLen();
// Message parsed.
if (msg)
{
// Notify the listener.
this->listener->onControlProtocolMessage(this, msg, this->buffer + this->msgStart, parsed_len);
// Free the message.
delete msg;
// 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)
{
MS_DEBUG("no more space in the buffer, emptying the buffer data");
this->msgStart = 0;
this->bufferDataLen = 0;
}
// If there is still space in the buffer, set the beginning of the next
// parsing to the next position after the parsed message.
else
{
this->msgStart += parsed_len;
}
// Reset the parser.
this->parser->Reset();
// 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)
{
MS_DEBUG("there is more data after the parsed message, continue parsing");
continue;
}
else
{
break;
}
}
// Parsing error. Close the pipe.
else if (this->parser->HasError())
{
MS_ERROR("parsing error, closing the pipe");
// Close the pipe.
Close();
// Exit the parsing loop.
break;
}
// Message not finished.
else
{
// Check if the buffer is full.
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)
{
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
{
MS_ERROR("no more space in the buffer for the unfinished message being parsed, closing the pipe");
// Close the socket.
Close();
}
}
// The buffer is not full.
else
{
MS_DEBUG("message not finished yet, waiting for more data");
}
// Exit the parsing loop.
break;
}
} // while()
}
void UnixStreamSocket::userOnUnixStreamSocketClosed(bool is_closed_by_peer)
{
MS_TRACE();
// Notify the listener.
this->listener->onControlProtocolUnixStreamSocketClosed(this, is_closed_by_peer);
}
} // namespace ControlProtocol
#!/usr/bin/env bash
ROOT_DIR="../../"
RAGEL_FILE="src/ControlProtocol/Parser.rl"
RAGEL_COMPILE_TYPE="-G2"
PRODUCTION=false
set -e
which ragel >/dev/null
if [ $? -ne 0 ] ; then
echo ">>> ERROR: ragel binary not found, cannot compile the Ragel grammar" >&2
exit 1
else
ragel -v
fi
cd $ROOT_DIR
cpp_file="${RAGEL_FILE%.rl}.cpp"
echo ">>> INFO: compiling $RAGEL_FILE:"
if [ "$PRODUCTION" == "true" ] ; then
show_ragel_lines="-L"
else
show_ragel_lines=""
fi
ragel $RAGEL_COMPILE_TYPE -C $RAGEL_FILE $show_ragel_lines -o $cpp_file
# Remove unused Ragel variables.
sed -i".delete_me" -E "s/.*static const int MessageParser_en_main.*//g" $cpp_file
echo ">>> DEBUG: Ragel's unused static variables removed from $cpp_file"
rm -f ${cpp_file}.delete_me
echo ">>> INFO: $cpp_file generated"
%%{
machine RequestAuthenticate;
action on_request_type_Authenticate
{
this->msg = new ControlProtocol::RequestAuthenticate();
}
action on_auth_user
{
static_cast<RequestAuthenticate*>(this->msg)->SetUser(PTR_TO_MARK, LEN_FROM_MARK);
}
action on_auth_passwd
{
static_cast<RequestAuthenticate*>(this->msg)->SetPasswd(PTR_TO_MARK, LEN_FROM_MARK);
}
auth_user = token >mark %on_auth_user;
auth_passwd = token >mark %on_auth_passwd;
RequestAuthenticate = "Request" SP "Authenticate" CRLF %on_request_type_Authenticate
transaction CRLF
"user:" SP auth_user CRLF
"passwd:" SP auth_passwd CRLF
CRLF;
}%%
%%{
machine RequestCreateConference;
action on_request_type_CreateConference
{
this->msg = new ControlProtocol::RequestCreateConference();
}
RequestCreateConference = "Request" SP "CreateConference" CRLF %on_request_type_CreateConference
transaction CRLF
CRLF;
}%%
%%{
machine RequestHello;
action on_request_type_Hello
{
this->msg = new ControlProtocol::RequestHello();
}
RequestHello = "Request" SP "Hello" CRLF %on_request_type_Hello
transaction CRLF
CRLF;
}%%
#define MS_CLASS "ControlProtocol::RequestAuthenticate"
#include "ControlProtocol/messages/RequestAuthenticate.h"
#include "Logger.h"
namespace ControlProtocol
{
/* Instance methods. */
RequestAuthenticate::RequestAuthenticate() :
Request(Type::Authenticate)
{
MS_DEBUG("kind: %d, type: %d", (int)this->kind, (int)this->type);
}
RequestAuthenticate::~RequestAuthenticate()
{
MS_TRACE();
}
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)
{
MS_TRACE();
this->passwd = std::string(str, len);
}
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
#define MS_CLASS "ControlProtocol::RequestCreateConference"
#include "ControlProtocol/messages/RequestCreateConference.h"
#include "Logger.h"
namespace ControlProtocol
{
/* Instance methods. */
RequestCreateConference::RequestCreateConference() : Request(Type::CreateConference)
{
MS_DEBUG("kind: %d, type: %d", (int)this->kind, (int)this->type);
}
RequestCreateConference::~RequestCreateConference()
{
MS_TRACE();
}
void RequestCreateConference::Dump()
{
MS_DEBUG("[Request CreateConference]");
MS_DEBUG("- transaction: %zu", (size_t)this->transaction);
MS_DEBUG("[/Request CreateConference]");
}
} // namespace ControlProtocol
#define MS_CLASS "ControlProtocol::RequestHello"
#include "ControlProtocol/messages/RequestHello.h"
#include "Logger.h"
namespace ControlProtocol
{
/* Instance methods. */
RequestHello::RequestHello() : Request(Type::Hello)
{
MS_DEBUG("kind: %d, type: %d", (int)this->kind, (int)this->type);
}
RequestHello::~RequestHello()
{
MS_TRACE();
}
void RequestHello::Dump()
{
MS_DEBUG("[Request Hello]");
MS_DEBUG("- transaction: %zu", (size_t)this->transaction);
MS_DEBUG("[/Request Hello]");
}
} // namespace ControlProtocol
#define MS_CLASS "Daemon"
#include "Daemon.h"
#include "Settings.h"
#include "Version.h"
#include "MediaSoupError.h"
#include "Logger.h"
#include <string>
#include <cerrno>
#include <cstdlib> // std::_Exit()
#include <cstdio> // std::setbuf(), std::freopen(), std::fopen(), std::fscanf(), std::fprintf(), std::remove()
#include <csignal> // kill()
#include <unistd.h> // pipe(), fork(), close(), setsid(), getpid()
/* Static variables. */
int Daemon::statusPipe[2] {-1, -1};
bool Daemon::isDaemonized = false;
bool Daemon::hasWrittenPIDFile = false;
/* Static methods. */
void Daemon::Daemonize()
{
MS_TRACE();
/**
* - ancestor process (running in foreground)
* \- intermediary process
* \- daemonized process (main process running in background)
*/
int ret;
int pid;
char status;
// Flush std file descriptors to avoid flushes after fork (same message
// appearing multiple times) and switch to unbuffered mode.
std::setbuf(stdout, 0);
std::setbuf(stderr, 0);
// Set the pipe for the daemonized process to send its status to the ancestor
// process (that waits for it in the foreground).
do
{
ret = pipe(Daemon::statusPipe);
}
while (ret < 0 && errno == EINTR);
if (ret < 0)
MS_THROW_ERROR("pipe() failed: %s", std::strerror(errno));
// NOTE: Don't need to update thread name after fork() calls. fork() copies
// the memory of the calling thread.
// First fork: don't be group leader.
if ((pid = fork()) < 0)
{
MS_THROW_ERROR("first fork() failed: %s", std::strerror(errno));
}
else if (pid > 0)
{
// When fork() returns a positive number, we are in the ancestor process
// and the return value is the PID of the newly created child process (the
// intermediary process).
// Ancestor process wait for the daemonized process to write into the pipe (or to die
// before) so it can exit with the proper exit status.
if (Daemon::WaitForDaemonizedStatus(&status))
{
if ((int)status == EXIT_SUCCESS)
{
MS_NOTICE("%s running as daemon", Version::name.c_str());
std::_Exit(EXIT_SUCCESS);
}
else
{
MS_EXIT_FAILURE("daemonized process failed to start (check Syslog)");
}
}
// The daemonized process died before writing its status on the pipe.
else
{
MS_EXIT_FAILURE("daemonized process died before writing its status (check Syslog)");
}
}
// This is the intermediary process.
// We are now daemonized (even if this is not the definitive forked process).
Daemon::isDaemonized = true;
// Clean unused fds.
if (Daemon::statusPipe[0] != -1)
{
close(Daemon::statusPipe[0]);
Daemon::statusPipe[0] = -1;
}
// Become session leader to drop the ctrl terminal.
if (setsid() < 0)
{
MS_THROW_ERROR("setsid() failed: %s", std::strerror(errno));
}
// Fork again to drop group leadership.
if ((pid = fork()) < 0)
{
MS_THROW_ERROR("second fork() failed: %s", std::strerror(errno));
}
else if (pid > 0) {
// Intermediary process just exits.
std::_Exit(EXIT_SUCCESS);
}
// This is the daemonized process.
// Create a PID file if requested.
if (!Settings::arguments.pidFile.empty())
{
if (!Daemon::WritePIDFile())
MS_THROW_ERROR("error writing the PID file '%s'", Settings::arguments.pidFile.c_str());
}
// Replace stdin, stdout & stderr with /dev/null.
if (std::freopen("/dev/null", "r", stdin) == nullptr)
{
MS_ERROR("error replacing stdin with /dev/null: %s", std::strerror(errno));
}
if (std::freopen("/dev/null", "w", stdout) == nullptr)
{
MS_ERROR("error replacing stdout with /dev/null: %s", std::strerror(errno));
}
if (std::freopen("/dev/null", "w", stderr) == nullptr)
{
MS_ERROR("error replacing stderr with /dev/null: %s", std::strerror(errno));
}
// Close all the possible fds inherited from the ancestor process (all but
// the write side of the pipe as the daemonized process must use it).
for (int fd = 3; fd < 32; fd++)
{
if (fd != Daemon::statusPipe[1])
close(fd);
}
// Enable Syslog logging.
Logger::EnableSyslog();
// First log in Syslog.
MS_NOTICE("%s running as daemon", Version::name.c_str());
}
void Daemon::SendOKStatusToAncestor()
{
MS_TRACE();
MS_DEBUG("sending OK status to the ancestor process");
SendStatusToAncestor(EXIT_SUCCESS);
}
void Daemon::SendErrorStatusToAncestor()
{
MS_TRACE();
MS_DEBUG("sending error status to the ancestor process");
SendStatusToAncestor(EXIT_FAILURE);
}
bool Daemon::IsDaemonized()
{
MS_TRACE();
return Daemon::isDaemonized;
}
void Daemon::End()
{
MS_TRACE();
// Delete PID file.
if (Daemon::hasWrittenPIDFile)
{
int err;
err = std::remove(Settings::arguments.pidFile.c_str());
if (err)
MS_ERROR("cannot delete the PID file '%s': %s", Settings::arguments.pidFile.c_str(), std::strerror(errno));
}
}
bool Daemon::WritePIDFile()
{
MS_TRACE();
FILE *pid_file;
const char* pidFile = Settings::arguments.pidFile.c_str();
unsigned int existing_pid = 0;
pid_t pid;
pid_file = std::fopen(pidFile, "r");
// PID file already exists. Check it.
if (pid_file)
{
MS_DEBUG("a PID file '%s' already exists", pidFile);
if (std::fscanf(pid_file, "%9u", &existing_pid) < 0)
{
MS_ERROR("could not parse existing PID file '%s'", pidFile);
std::fclose(pid_file);
return false;
}
fclose(pid_file);
if (existing_pid == 0)
{
MS_ERROR("existing PID file '%s' does not contain a valid value", pidFile);
return false;
}
if (kill((pid_t)existing_pid, 0) == 0 || errno == EPERM)
{
MS_ERROR("there is a running process with the same PID as in the existing PID file '%s'",
pidFile);
return false;
}
else
{
MS_NOTICE("existing PID file '%s' contains an old PID, replacing its value", pidFile);
}
}
// Get our PID.
pid = getpid();
MS_DEBUG("PID of the daemonized process: %u", (unsigned int)pid);
// Write into the PID file.
pid_file = std::fopen(pidFile, "w");
if (!pid_file)
{
MS_ERROR("cannot open PID file '%s' for writing: %s", pidFile, std::strerror(errno));
return false;
}
std::fprintf(pid_file, "%u\n", (unsigned int)pid);
std::fclose(pid_file);
Daemon::hasWrittenPIDFile = true;
MS_DEBUG("PID file '%s' created with our PID value", pidFile);
return true;
}
bool Daemon::WaitForDaemonizedStatus(char* status)
{
MS_TRACE();
int ret;
MS_DEBUG("waiting for the daemonized process to write its status");
// Close the output side of the pipe.
if (Daemon::statusPipe[1] != -1)
{
close(Daemon::statusPipe[1]);
Daemon::statusPipe[1] = -1;
}
// If the read side of the pipe is closed the daemonized process died even before
// sending status.
if (Daemon::statusPipe[0] == -1)
{
return false;
}
do
{
ret = read(Daemon::statusPipe[0], status, 1);
}
while (ret < 0 && errno == EINTR);
// If a byte has been read return true and the ancestor process will inspect the
// status value.
return (ret == 1) ? true : false;
}
void Daemon::SendStatusToAncestor(char status)
{
MS_TRACE();
int ret;
if (Daemon::statusPipe[1] == -1)
{
MS_ERROR("cannot send status to ancestor process, pipe is closed");
return;
}
do
{
ret = write(Daemon::statusPipe[1], &status, 1);
}
while (ret < 0 && errno == EINTR);
if (ret != 1)
MS_ERROR("cannot send status to ancestor process: %s", std::strerror(errno));
close(Daemon::statusPipe[1]);
Daemon::statusPipe[1] = -1;
}
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
/* Static variables. */ /* Static variables. */
__thread uv_loop_t* DepLibUV::loop = nullptr; uv_loop_t* DepLibUV::loop = nullptr;
/* Static methods. */ /* Static methods. */
...@@ -13,19 +13,10 @@ void DepLibUV::ClassInit() ...@@ -13,19 +13,10 @@ void DepLibUV::ClassInit()
{ {
MS_TRACE(); MS_TRACE();
// Print libuv version.
MS_DEBUG("loaded libuv version: %s", uv_version_string());
}
void DepLibUV::ThreadInit()
{
MS_TRACE();
int err; int err;
// This should never happen. // Print libuv version.
if (DepLibUV::loop) MS_DEBUG("loaded libuv version: %s", uv_version_string());
MS_ABORT("DepLibUV::loop alread allocated in this thread");
DepLibUV::loop = new uv_loop_t; DepLibUV::loop = new uv_loop_t;
err = uv_loop_init(DepLibUV::loop); err = uv_loop_init(DepLibUV::loop);
...@@ -33,13 +24,13 @@ void DepLibUV::ThreadInit() ...@@ -33,13 +24,13 @@ void DepLibUV::ThreadInit()
MS_ABORT("uv_loop_init() failed: %s", uv_strerror(err)); MS_ABORT("uv_loop_init() failed: %s", uv_strerror(err));
} }
void DepLibUV::ThreadDestroy() void DepLibUV::ClassDestroy()
{ {
MS_TRACE(); MS_TRACE();
// This should never happen. // This should never happen.
if (!DepLibUV::loop) if (!DepLibUV::loop)
MS_ABORT("DepLibUV::loop was not allocated in this thread"); MS_ABORT("DepLibUV::loop was not allocated");
uv_loop_close(DepLibUV::loop); uv_loop_close(DepLibUV::loop);
delete DepLibUV::loop; delete DepLibUV::loop;
...@@ -51,7 +42,7 @@ void DepLibUV::RunLoop() ...@@ -51,7 +42,7 @@ void DepLibUV::RunLoop()
// This should never happen. // This should never happen.
if (!DepLibUV::loop) if (!DepLibUV::loop)
MS_ABORT("DepLibUV::loop was not allocated in this thread"); MS_ABORT("DepLibUV::loop was not allocated");
uv_run(DepLibUV::loop, UV_RUN_DEFAULT); uv_run(DepLibUV::loop, UV_RUN_DEFAULT);
} }
#define MS_CLASS "Dispatcher"
#include "Dispatcher.h"
#include "Settings.h"
#include "Daemon.h"
#include "Worker.h"
#include "Utils.h"
#include "DepLibUV.h"
#include "ControlProtocol/messages.h"
#include "MediaSoupError.h"
#include "Logger.h"
#include <string>
#include <csignal> // sigaction(), pthread_sigmask()
#include <cerrno>
/* Instance methods. */
Dispatcher::Dispatcher()
{
MS_TRACE();
// Set the signals handler.
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)
{
MS_THROW_ERROR("error creating the SignalsHandler: %s", error.what());
}
MS_DEBUG("SignalsHandler ready");
// Create a ControlProtocol TCP server.
std::string ip = Settings::configuration.ControlProtocol.listenIP;
MS_PORT port = Settings::configuration.ControlProtocol.listenPort;
try
{
this->controlProtocolTCPServer = new ControlProtocol::TCPServer(this, this, ip, port);
}
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());
// Create the ControlProtocol UnixStream sockets.
int num_workers = Worker::CountWorkers();
// Insert a nullptr value in position 0 of the vector of ControlProtocol::UnixStreamSocket*
// since the first entry will be in position 1.
this->controlProtocolUnixStreamSockets.push_back(nullptr);
for (int workerId = 1; workerId <= num_workers; workerId++)
{
int fd = Worker::GetControlProtocolRemoteSocket(workerId);
ControlProtocol::UnixStreamSocket* controlProtocolUnixStreamSocket;
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)
{
MS_THROW_ERROR("error creating a ControlProtocol Unix socket for Worker %d: %s", workerId, error.what());
}
// Add to the vector. Note that workerId 1 will be placed in position 1 of the vector.
this->controlProtocolUnixStreamSockets.push_back(controlProtocolUnixStreamSocket);
MS_DEBUG("ControlProtocol Unix socket for Worker #%d ready", workerId);
}
MS_DEBUG("Dispatcher running");
// Write the success status on the pipe if daemonized to tell the ancestor
// process that the daemonized process is properly running.
if (Settings::arguments.daemonize)
Daemon::SendOKStatusToAncestor();
// Run the loop.
DepLibUV::RunLoop();
MS_DEBUG("libuv loop ends");
}
Dispatcher::~Dispatcher()
{
MS_TRACE();
}
void Dispatcher::Close()
{
MS_TRACE();
if (this->closed)
{
MS_ERROR("already closed");
return;
}
this->closed = true;
MS_DEBUG("closing all the services running in the Dispatcher");
// First block all the signals to not be interrupted while closing.
int err;
sigset_t signal_mask;
// Block all the signals.
sigfillset(&signal_mask);
err = pthread_sigmask(SIG_BLOCK, &signal_mask, nullptr);
if (err)
MS_ERROR("pthread_sigmask() failed: %s", std::strerror(errno));
// Close the SignalsHandler.
this->signalsHandler->Close();
// Close the ControlProtocol TCP server.
this->controlProtocolTCPServer->Close();
// Close the ControlProtocol UnixStream sockets.
int num_workers = Worker::CountWorkers();
for (int workerId = 1; workerId <= num_workers; workerId++)
this->controlProtocolUnixStreamSockets[workerId]->Close();
}
void Dispatcher::onSignal(SignalsHandler* signalsHandler, int signum)
{
MS_TRACE();
switch (signum)
{
// SIGUSR1 means configuration reload.
case SIGUSR1:
MS_NOTICE("signal USR1 received, reloading configuration");
if (Settings::ReloadConfigurationFile())
{
// Print new configuration.
Settings::PrintConfiguration();
}
break;
case SIGINT:
MS_NOTICE("signal INT received, exiting");
Close();
break;
case SIGTERM:
MS_NOTICE("signal TERM received, exiting");
Close();
break;
default:
MS_ERROR("received a signal (with signum %d) for which there is no handling code", signum);
}
}
void Dispatcher::onSignalsHandlerClosed(SignalsHandler* signalsHandler)
{
MS_TRACE();
}
void Dispatcher::onControlProtocolNewTCPConnection(ControlProtocol::TCPServer* tcpServer, ControlProtocol::TCPConnection* connection)
{
MS_TRACE();
MS_DEBUG("new ControlProtocol TCP connection:");
tcpServer->Dump();
connection->Dump();
}
void Dispatcher::onControlProtocolTCPConnectionClosed(ControlProtocol::TCPServer* tcpServer, ControlProtocol::TCPConnection* connection, bool is_closed_by_peer)
{
MS_TRACE();
if (is_closed_by_peer)
MS_DEBUG("ControlProtocol TCP connection closed by peer:");
else
MS_DEBUG("ControlProtocol TCP connection closed locally:");
connection->Dump();
tcpServer->Dump();
}
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());
// TODO: process the ControlProtocol::Message.
// TEST
bool relayToRandomWorker = true;
bool relayToAllWorkers = false;
bool replyOK = true;
if (relayToRandomWorker)
{
int workerId = (int)Utils::Crypto::GetRandomUInt(1, (unsigned int)Worker::CountWorkers());
MS_INFO("relaying ControlProtocol message to Worker #%d ...", workerId);
ControlProtocol::UnixStreamSocket* controlProtocolUnixStreamSocket = controlProtocolUnixStreamSockets[workerId];
controlProtocolUnixStreamSocket->Write(raw, len);
}
if (relayToAllWorkers)
{
int num_workers = Worker::CountWorkers();
for (int workerId = 1; workerId <= num_workers; workerId++)
{
ControlProtocol::UnixStreamSocket* controlProtocolUnixStreamSocket = controlProtocolUnixStreamSockets[workerId];
MS_INFO("relaying ControlProtocol message to Worker #%d ...", workerId);
controlProtocolUnixStreamSocket->Write(raw, len);
}
}
if (replyOK)
{
MS_INFO("replying 'OK, message received' via TCP ...");
// TEST: Write(std::string &data)
std::string ok_reply_begin = "OK, message received with transaction ";
connection->Write(ok_reply_begin);
// TEST: Write(std::string &data)
std::string transaction_str = std::to_string(msg->GetTransaction());
connection->Write(transaction_str);
// TEST: Write(std::string &data)
std::string ok_reply_end = ":\n---------------------\n";
connection->Write(ok_reply_end);
// TEST: Write(const MS_BYTE* data, size_t len)
connection->Write(raw, len);
// TEST: Write(std::string &data)
std::string ok_reply_real_end = "---------------------\n";
connection->Write(ok_reply_real_end);
}
}
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.
int workerId = *(int*)unixSocket->GetUserData();
// TMP
MS_INFO("ControlProtocol message received from Worker #%d", workerId);
// TMP send back to the worker (loop !!!)
unixSocket->Write((MS_BYTE*)raw, len);
// TODO: process the ControlProtocol::Message.
}
void Dispatcher::onControlProtocolUnixStreamSocketClosed(ControlProtocol::UnixStreamSocket* unixSocket, bool is_closed_by_peer)
{
MS_TRACE();
// Get the workerId associated to this socket.
int* userData = (int*)unixSocket->GetUserData();
int workerId = *userData;
// Free the socket's user data and remove the socket from the map.
delete userData;
controlProtocolUnixStreamSockets[workerId] = nullptr;
// A Worker MUST NEVER close the socket. If it does it is due to a parsing error
// that should NEVER happen, so abort.
if (is_closed_by_peer)
MS_ABORT("ControlProtocol Unix socket for Worker #%d remotely closed", workerId);
else
MS_DEBUG("ControlProtocol Unix socket for Worker #%d locally closed", workerId);
}
#define MS_CLASS "Logger" #define MS_CLASS "Logger"
#include "Logger.h" #include "Logger.h"
#include "Version.h"
/* Static variables. */ /* Static variables. */
__thread std::string* Logger::threadName = nullptr; std::string Logger::processName;
__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::Init(const std::string name)
{ {
// Store the name for this thread in thread local storage. Logger::processName = name;
if (Logger::threadName)
delete Logger::threadName;
// NOTE: this std::string pointer is never deallocated.
Logger::threadName = new std::string(name);
Logger::threadNamePtr = Logger::threadName->c_str();
MS_TRACE(); MS_TRACE();
} }
...@@ -28,7 +20,8 @@ void Logger::EnableSyslog() ...@@ -28,7 +20,8 @@ void Logger::EnableSyslog()
{ {
MS_TRACE(); MS_TRACE();
openlog(Version::command.c_str(), (LOG_PID), Settings::configuration.syslogFacility); // TODO: Set the process name/id as well.
openlog("MediaSoup", (LOG_PID), Settings::configuration.syslogFacility);
Logger::isSyslogEnabled = true; Logger::isSyslogEnabled = true;
} }
#define MS_CLASS "Loop"
#include "Loop.h"
#include "DepLibUV.h"
#include "MediaSoupError.h"
#include "Logger.h"
#include <string>
#include <csignal> // sigfillset, pthread_sigmask()
#include <cerrno>
/* Instance methods. */
Loop::Loop()
{
MS_TRACE();
// Set the signals handler.
try
{
this->signalsHandler = new SignalsHandler(this);
// Add signals to handle.
this->signalsHandler->AddSignal(SIGINT, "INT");
this->signalsHandler->AddSignal(SIGTERM, "TERM");
}
catch (const MediaSoupError &error)
{
MS_THROW_ERROR("error creating the SignalsHandler: %s", error.what());
}
MS_DEBUG("SignalsHandler ready");
MS_DEBUG("starting libuv loop");
DepLibUV::RunLoop();
MS_DEBUG("libuv loop ended");
}
Loop::~Loop()
{
MS_TRACE();
}
void Loop::Close()
{
MS_TRACE();
int err;
sigset_t signal_mask;
if (this->closed)
{
MS_ERROR("already closed");
return;
}
this->closed = true;
// First block all the signals to not be interrupted while closing.
sigfillset(&signal_mask);
err = pthread_sigmask(SIG_BLOCK, &signal_mask, nullptr);
if (err)
MS_ERROR("pthread_sigmask() failed: %s", std::strerror(errno));
// Close the SignalsHandler.
this->signalsHandler->Close();
}
void Loop::onSignal(SignalsHandler* signalsHandler, int signum)
{
MS_TRACE();
switch (signum)
{
case SIGINT:
MS_NOTICE("signal INT received, exiting");
Close();
break;
case SIGTERM:
MS_NOTICE("signal TERM received, exiting");
Close();
break;
default:
MS_ERROR("received a signal (with signum %d) for which there is no handling code", signum);
}
}
void Loop::onSignalsHandlerClosed(SignalsHandler* signalsHandler)
{
MS_TRACE();
}
差异被折叠。
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
#include "RTC/DTLSHandler.h" #include "RTC/DTLSHandler.h"
#include "Settings.h" #include "Settings.h"
#include "Version.h"
#include "Utils.h" #include "Utils.h"
#include "MediaSoupError.h" #include "MediaSoupError.h"
#include "Logger.h" #include "Logger.h"
...@@ -84,8 +83,8 @@ namespace RTC ...@@ -84,8 +83,8 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
// Generate a X509 certificate and private key (unless PEM files are privided). // Generate a X509 certificate and private key (unless PEM files are provided).
if (Settings::configuration.RTC.dtlsCertificateFile.empty()) if (Settings::configuration.RTC.dtlsCertificateFile.empty() || Settings::configuration.RTC.dtlsPrivateKeyFile.empty())
GenerateCertificateAndPrivateKey(); GenerateCertificateAndPrivateKey();
else else
ReadCertificateAndPrivateKeyFromFiles(); ReadCertificateAndPrivateKeyFromFiles();
...@@ -208,8 +207,8 @@ namespace RTC ...@@ -208,8 +207,8 @@ namespace RTC
LOG_OPENSSL_ERROR("X509_get_subject_name() failed"); LOG_OPENSSL_ERROR("X509_get_subject_name() failed");
goto error; goto error;
} }
X509_NAME_add_entry_by_txt(cert_name, "O", MBSTRING_ASC, (unsigned char *)Version::GetNameAndVersion().c_str(), -1, -1, 0); X509_NAME_add_entry_by_txt(cert_name, "O", MBSTRING_ASC, (unsigned char *)"Mediasoup", -1, -1, 0);
X509_NAME_add_entry_by_txt(cert_name, "CN", MBSTRING_ASC, (unsigned char *)Version::name.c_str(), -1, -1, 0); X509_NAME_add_entry_by_txt(cert_name, "CN", MBSTRING_ASC, (unsigned char *)"Mediasoup", -1, -1, 0);
// It is self signed so set the issuer name to be the same as the subject. // It is self signed so set the issuer name to be the same as the subject.
ret = X509_set_issuer_name(DTLSHandler::certificate, cert_name); ret = X509_set_issuer_name(DTLSHandler::certificate, cert_name);
...@@ -1176,4 +1175,4 @@ namespace RTC ...@@ -1176,4 +1175,4 @@ namespace RTC
SendPendingOutgoingDTLSData(); SendPendingOutgoingDTLSData();
SetTimeout(); SetTimeout();
} }
} // namespace RTC }
...@@ -179,7 +179,7 @@ namespace RTC ...@@ -179,7 +179,7 @@ namespace RTC
{ {
// Compute the CRC32 of the received message up to (but excluding) the // Compute the CRC32 of the received message up to (but excluding) the
// FINGERPRINT attribute and XOR it with 0x5354554e. // FINGERPRINT attribute and XOR it with 0x5354554e.
MS_4BYTES computed_fingerprint = Utils::Crypto::CRC32(data, fingerprint_attr_pos) ^ 0x5354554e; MS_4BYTES computed_fingerprint = Utils::Crypto::GetCRC32(data, fingerprint_attr_pos) ^ 0x5354554e;
// Compare with the FINGERPRINT value in the message. // Compare with the FINGERPRINT value in the message.
if (fingerprint != computed_fingerprint) if (fingerprint != computed_fingerprint)
...@@ -254,7 +254,7 @@ namespace RTC ...@@ -254,7 +254,7 @@ namespace RTC
Utils::Byte::Set2Bytes(this->raw, 2, (MS_2BYTES)(this->length - 20 - 8)); Utils::Byte::Set2Bytes(this->raw, 2, (MS_2BYTES)(this->length - 20 - 8));
// Calculate the HMAC-SHA1 of the message according to MESSAGE-INTEGRITY rules. // Calculate the HMAC-SHA1 of the message according to MESSAGE-INTEGRITY rules.
const MS_BYTE* computed_message_integrity = Utils::Crypto::HMAC_SHA1(local_password, this->raw, (this->messageIntegrity - 4) - this->raw); const MS_BYTE* computed_message_integrity = Utils::Crypto::GetHMAC_SHA1(local_password, this->raw, (this->messageIntegrity - 4) - this->raw);
Authentication result; Authentication result;
...@@ -525,7 +525,7 @@ namespace RTC ...@@ -525,7 +525,7 @@ namespace RTC
Utils::Byte::Set2Bytes(this->raw, 2, (MS_2BYTES)(this->length - 20 - 8)); Utils::Byte::Set2Bytes(this->raw, 2, (MS_2BYTES)(this->length - 20 - 8));
// Calculate the HMAC-SHA1 of the message according to MESSAGE-INTEGRITY rules. // Calculate the HMAC-SHA1 of the message according to MESSAGE-INTEGRITY rules.
const MS_BYTE* computed_message_integrity = Utils::Crypto::HMAC_SHA1(this->password, this->raw, pos); const MS_BYTE* computed_message_integrity = Utils::Crypto::GetHMAC_SHA1(this->password, this->raw, pos);
Utils::Byte::Set2Bytes(this->raw, pos, (MS_2BYTES)Attribute::MessageIntegrity); Utils::Byte::Set2Bytes(this->raw, pos, (MS_2BYTES)Attribute::MessageIntegrity);
Utils::Byte::Set2Bytes(this->raw, pos + 2, 20); Utils::Byte::Set2Bytes(this->raw, pos + 2, 20);
...@@ -550,7 +550,7 @@ namespace RTC ...@@ -550,7 +550,7 @@ namespace RTC
{ {
// Compute the CRC32 of the message up to (but excluding) the FINGERPRINT // Compute the CRC32 of the message up to (but excluding) the FINGERPRINT
// attribute and XOR it with 0x5354554e. // attribute and XOR it with 0x5354554e.
MS_4BYTES computed_fingerprint = Utils::Crypto::CRC32(this->raw, pos) ^ 0x5354554e; MS_4BYTES computed_fingerprint = Utils::Crypto::GetCRC32(this->raw, pos) ^ 0x5354554e;
Utils::Byte::Set2Bytes(this->raw, pos, (MS_2BYTES)Attribute::Fingerprint); Utils::Byte::Set2Bytes(this->raw, pos, (MS_2BYTES)Attribute::Fingerprint);
Utils::Byte::Set2Bytes(this->raw, pos + 2, 4); Utils::Byte::Set2Bytes(this->raw, pos + 2, 4);
......
...@@ -35,7 +35,6 @@ namespace RTC ...@@ -35,7 +35,6 @@ namespace RTC
/* Static methods. */ /* Static methods. */
// NOTE: Must be called from MediaSoup::Init().
void UDPSocket::ClassInit() void UDPSocket::ClassInit()
{ {
MS_TRACE(); MS_TRACE();
...@@ -95,11 +94,6 @@ namespace RTC ...@@ -95,11 +94,6 @@ namespace RTC
sockets[1] = new RTC::UDPSocket(uvHandles[1]); sockets[1] = new RTC::UDPSocket(uvHandles[1]);
} }
/*
* By calling this method, two different workers (threads) can access to the
* static map of available ports. No problem since the map keys are not modified,
* and values are a MS_PORT (uint16_t) which is atomic.
*/
void UDPSocket::RandomizePort(int address_family, uv_udp_t* uvHandles[], bool pair) void UDPSocket::RandomizePort(int address_family, uv_udp_t* uvHandles[], bool pair)
{ {
MS_TRACE(); MS_TRACE();
......
差异被折叠。
...@@ -8,9 +8,9 @@ namespace Utils ...@@ -8,9 +8,9 @@ namespace Utils
{ {
/* Static variables. */ /* Static variables. */
__thread unsigned int Crypto::seed; unsigned int Crypto::seed;
__thread HMAC_CTX Crypto::hmacSha1Ctx; HMAC_CTX Crypto::hmacSha1Ctx;
__thread MS_BYTE Crypto::hmacSha1Buffer[20]; // SHA-1 result is 20 bytes long. MS_BYTE Crypto::hmacSha1Buffer[20]; // SHA-1 result is 20 bytes long.
const MS_4BYTES Crypto::crc32Table[] = const MS_4BYTES Crypto::crc32Table[] =
{ {
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
...@@ -60,10 +60,11 @@ namespace Utils ...@@ -60,10 +60,11 @@ namespace Utils
/* Static methods. */ /* Static methods. */
void Crypto::ThreadInit() void Crypto::ClassInit()
{ {
MS_TRACE(); MS_TRACE();
// TODO: refactor comment
// Init the seed of each thread with a random number taken from the address // Init the seed of each thread with a random number taken from the address
// of the seed variable itself (which is different for each thread). // of the seed variable itself (which is different for each thread).
Crypto::seed = (unsigned int)(unsigned long)&Crypto::seed; Crypto::seed = (unsigned int)(unsigned long)&Crypto::seed;
...@@ -72,14 +73,14 @@ namespace Utils ...@@ -72,14 +73,14 @@ namespace Utils
HMAC_CTX_init(&Crypto::hmacSha1Ctx); HMAC_CTX_init(&Crypto::hmacSha1Ctx);
} }
void Crypto::ThreadDestroy() void Crypto::ClassDestroy()
{ {
MS_TRACE(); MS_TRACE();
HMAC_CTX_cleanup(&Crypto::hmacSha1Ctx); HMAC_CTX_cleanup(&Crypto::hmacSha1Ctx);
} }
const MS_BYTE* Crypto::HMAC_SHA1(const std::string &key, const MS_BYTE* data, size_t len) const MS_BYTE* Crypto::GetHMAC_SHA1(const std::string &key, const MS_BYTE* data, size_t len)
{ {
MS_TRACE(); MS_TRACE();
...@@ -98,4 +99,4 @@ namespace Utils ...@@ -98,4 +99,4 @@ namespace Utils
return Crypto::hmacSha1Buffer; return Crypto::hmacSha1Buffer;
} }
} // namespace Utils }
...@@ -7,11 +7,10 @@ ...@@ -7,11 +7,10 @@
#include <unistd.h> // access(), R_OK #include <unistd.h> // access(), R_OK
#include <sys/stat.h> // stat() #include <sys/stat.h> // stat()
namespace Utils
namespace Utils { {
void Utils::File::CheckFile(const char* file)
{
void Utils::File::CheckFile(const char* file) {
MS_TRACE(); MS_TRACE();
struct stat file_stat; struct stat file_stat;
...@@ -30,7 +29,5 @@ void Utils::File::CheckFile(const char* file) { ...@@ -30,7 +29,5 @@ void Utils::File::CheckFile(const char* file) {
err = access(file, R_OK); err = access(file, R_OK);
if (err) if (err)
MS_THROW_ERROR("cannot read file '%s': %s", file, std::strerror(errno)); MS_THROW_ERROR("cannot read file '%s': %s", file, std::strerror(errno));
}
} }
} // namespace Utils
差异被折叠。
...@@ -36,7 +36,6 @@ namespace Utils ...@@ -36,7 +36,6 @@ namespace Utils
IPv6address @on_ipv6; IPv6address @on_ipv6;
}%% }%%
/** /**
* Ragel: %%write data * Ragel: %%write data
* This generates Ragel's static variables. * This generates Ragel's static variables.
...@@ -97,4 +96,4 @@ namespace Utils ...@@ -97,4 +96,4 @@ namespace Utils
*family = addr->sa_family; *family = addr->sa_family;
ip.assign(_ip); ip.assign(_ip);
} }
} // namespace Utils }
...@@ -85,4 +85,4 @@ namespace Utils ...@@ -85,4 +85,4 @@ namespace Utils
return true; return true;
} }
} // namespace Utils }
#define MS_CLASS "Version"
#include "Version.h"
#include "Logger.h"
/* Static variables. */
const int Version::versionMajor = 0;
const int Version::versionMinor = 0;
const int Version::versionTiny = 1;
const std::string Version::name = "MediaSoup";
const std::string Version::command = "mediasoup";
const std::string Version::copyright = "Copyright (c) 2014 Iñaki Baz Castillo | https://github.com/ibc";
/* Static methods .*/
const std::string Version::GetVersion()
{
MS_TRACE();
std::string version;
version.append(std::to_string(Version::versionMajor));
version.append(".");
version.append(std::to_string(Version::versionMinor));
version.append(".");
version.append(std::to_string(Version::versionTiny));
return version;
}
const std::string Version::GetNameAndVersion()
{
MS_TRACE();
std::string name_and_version;
name_and_version.append(Version::name);
name_and_version.append(" v");
name_and_version.append(Version::GetVersion());
return name_and_version;
}
差异被折叠。
差异被折叠。
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论