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

Improve C (related to #16)

上级 69ced621
#ifndef MS_CHANNEL_NOTIFIER_H #ifndef MS_CHANNEL_NOTIFIER_H
#define MS_CHANNEL_NOTIFIER_H #define MS_CHANNEL_NOTIFIER_H
#include "common.h"
#include "Channel/UnixStreamSocket.h" #include "Channel/UnixStreamSocket.h"
#include <string> #include <string>
#include <json/json.h> #include <json/json.h>
...@@ -15,8 +16,8 @@ namespace Channel ...@@ -15,8 +16,8 @@ namespace Channel
void Close(); void Close();
void Emit(unsigned int targetId, std::string eventName); void Emit(uint32_t targetId, std::string eventName);
void Emit(unsigned int targetId, std::string eventName, Json::Value& eventData); void Emit(uint32_t targetId, std::string eventName, Json::Value& eventData);
public: public:
// Passed by argument. // Passed by argument.
......
#ifndef MS_CHANNEL_REQUEST_H #ifndef MS_CHANNEL_REQUEST_H
#define MS_CHANNEL_REQUEST_H #define MS_CHANNEL_REQUEST_H
#include "common.h"
#include "Channel/UnixStreamSocket.h" #include "Channel/UnixStreamSocket.h"
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
...@@ -40,13 +41,13 @@ namespace Channel ...@@ -40,13 +41,13 @@ namespace Channel
void Accept(); void Accept();
void Accept(Json::Value &data); void Accept(Json::Value &data);
void Reject(unsigned int status, std::string& reason); void Reject(uint16_t status, std::string& reason);
void Reject(unsigned int status, const char* reason = nullptr); void Reject(uint16_t status, const char* reason = nullptr);
public: public:
// Passed by argument. // Passed by argument.
Channel::UnixStreamSocket* channel = nullptr; Channel::UnixStreamSocket* channel = nullptr;
unsigned int id; uint32_t id;
std::string method; std::string method;
MethodId methodId; MethodId methodId;
Json::Value internal; Json::Value internal;
......
...@@ -31,7 +31,7 @@ namespace Channel ...@@ -31,7 +31,7 @@ namespace Channel
void SetListener(Listener* listener); void SetListener(Listener* listener);
void Send(Json::Value &json); void Send(Json::Value &json);
void SendLog(char* ns_payload, int ns_payload_len); void SendLog(char* ns_payload, size_t ns_payload_len);
/* Pure virtual methods inherited from ::UnixStreamSocket. */ /* Pure virtual methods inherited from ::UnixStreamSocket. */
public: public:
......
...@@ -26,7 +26,7 @@ private: ...@@ -26,7 +26,7 @@ private:
private: private:
static pthread_mutex_t* mutexes; static pthread_mutex_t* mutexes;
static int numMutexes; static uint32_t numMutexes;
}; };
#endif #endif
...@@ -47,6 +47,7 @@ namespace RTC ...@@ -47,6 +47,7 @@ namespace RTC
RTPPacket(Header* header, ExtensionHeader* extensionHeader, const MS_BYTE* payload, size_t payloadLen, MS_BYTE payloadPadding, const MS_BYTE* raw, size_t length); RTPPacket(Header* header, ExtensionHeader* extensionHeader, const MS_BYTE* payload, size_t payloadLen, MS_BYTE payloadPadding, const MS_BYTE* raw, size_t length);
~RTPPacket(); ~RTPPacket();
void Dump();
const MS_BYTE* GetRaw(); const MS_BYTE* GetRaw();
size_t GetLength(); size_t GetLength();
MS_BYTE GetPayloadType(); MS_BYTE GetPayloadType();
...@@ -63,7 +64,6 @@ namespace RTC ...@@ -63,7 +64,6 @@ namespace RTC
MS_BYTE* GetPayload(); MS_BYTE* GetPayload();
size_t GetPayloadLength(); size_t GetPayloadLength();
void Serialize(); void Serialize();
void Dump();
private: private:
// Passed by argument. // Passed by argument.
......
#ifndef MS_RTC_ROOM_H #ifndef MS_RTC_ROOM_H
#define MS_RTC_ROOM_H #define MS_RTC_ROOM_H
#include "common.h"
#include "RTC/Peer.h" #include "RTC/Peer.h"
#include "Channel/Request.h" #include "Channel/Request.h"
#include "Channel/Notifier.h" #include "Channel/Notifier.h"
...@@ -20,7 +21,7 @@ namespace RTC ...@@ -20,7 +21,7 @@ namespace RTC
}; };
public: public:
Room(Listener* listener, Channel::Notifier* notifier, unsigned int roomId); Room(Listener* listener, Channel::Notifier* notifier, uint32_t roomId);
virtual ~Room(); virtual ~Room();
void Close(); void Close();
...@@ -28,7 +29,7 @@ namespace RTC ...@@ -28,7 +29,7 @@ namespace RTC
void HandleRequest(Channel::Request* request); void HandleRequest(Channel::Request* request);
private: private:
RTC::Peer* GetPeerFromRequest(Channel::Request* request, unsigned int* peerId = nullptr); RTC::Peer* GetPeerFromRequest(Channel::Request* request, uint32_t* peerId = nullptr);
/* Pure virtual methods inherited from RTC::Peer::Listener. */ /* Pure virtual methods inherited from RTC::Peer::Listener. */
public: public:
...@@ -36,14 +37,14 @@ namespace RTC ...@@ -36,14 +37,14 @@ namespace RTC
public: public:
// Passed by argument. // Passed by argument.
unsigned int roomId; uint32_t roomId;
private: private:
// Passed by argument. // Passed by argument.
Listener* listener = nullptr; Listener* listener = nullptr;
Channel::Notifier* notifier = nullptr; Channel::Notifier* notifier = nullptr;
// Others. // Others.
std::unordered_map<unsigned int, RTC::Peer*> peers; std::unordered_map<uint32_t, RTC::Peer*> peers;
}; };
} }
......
...@@ -63,6 +63,7 @@ namespace RTC ...@@ -63,6 +63,7 @@ namespace RTC
STUNMessage(Class klass, Method method, const MS_BYTE* transactionId, const MS_BYTE* raw, size_t length); STUNMessage(Class klass, Method method, const MS_BYTE* transactionId, const MS_BYTE* raw, size_t length);
~STUNMessage(); ~STUNMessage();
void Dump();
Class GetClass(); Class GetClass();
Method GetMethod(); Method GetMethod();
const MS_BYTE* GetRaw(); const MS_BYTE* GetRaw();
...@@ -90,7 +91,6 @@ namespace RTC ...@@ -90,7 +91,6 @@ namespace RTC
STUNMessage* CreateErrorResponse(MS_2BYTES errorCode); STUNMessage* CreateErrorResponse(MS_2BYTES errorCode);
void Authenticate(const std::string &password); void Authenticate(const std::string &password);
void Serialize(); void Serialize();
void Dump();
private: private:
// Passed by argument. // Passed by argument.
......
...@@ -13,7 +13,7 @@ public: ...@@ -13,7 +13,7 @@ public:
// Struct holding the configuration. // Struct holding the configuration.
struct Configuration struct Configuration
{ {
unsigned int logLevel { MS_LOG_LEVEL_DEBUG }; uint8_t logLevel { MS_LOG_LEVEL_DEBUG };
std::string rtcListenIPv4; std::string rtcListenIPv4;
std::string rtcListenIPv6; std::string rtcListenIPv6;
MS_PORT rtcMinPort { 10000 }; MS_PORT rtcMinPort { 10000 };
...@@ -42,8 +42,8 @@ public: ...@@ -42,8 +42,8 @@ public:
static struct Configuration configuration; static struct Configuration configuration;
private: private:
static std::map<std::string, unsigned int> string2LogLevel; static std::map<std::string, uint8_t> string2LogLevel;
static std::map<unsigned int, std::string> logLevel2String; static std::map<uint8_t, std::string> logLevel2String;
}; };
#endif #endif
...@@ -17,19 +17,18 @@ public: ...@@ -17,19 +17,18 @@ public:
public: public:
SignalsHandler(Listener* listener); SignalsHandler(Listener* listener);
void AddSignal(int signum, std::string name);
void Close(); void Close();
void AddSignal(int signum, std::string name);
/* Callbacks fired by UV events. */ /* Callbacks fired by UV events. */
public: public:
void onUvSignal(int signum); void onUvSignal(int signum);
private: private:
// Allocated by this.
typedef std::vector<uv_signal_t*> UvHandles;
UvHandles uvHandles;
// Passed by argument. // Passed by argument.
Listener* listener = nullptr; Listener* listener = nullptr;
// Allocated by this.
std::vector<uv_signal_t*> uvHandles;
}; };
#endif #endif
...@@ -27,7 +27,10 @@ public: ...@@ -27,7 +27,10 @@ public:
TCPConnection(size_t bufferSize); TCPConnection(size_t bufferSize);
virtual ~TCPConnection(); virtual ~TCPConnection();
void Close();
virtual void Dump();
void Setup(Listener* listener, struct sockaddr_storage* localAddr, const std::string &localIP, MS_PORT localPort); void Setup(Listener* listener, struct sockaddr_storage* localAddr, const std::string &localIP, MS_PORT localPort);
bool IsClosing();
uv_tcp_t* GetUvHandle(); uv_tcp_t* GetUvHandle();
void Start(); void Start();
void Write(const MS_BYTE* data, size_t len); void Write(const MS_BYTE* data, size_t len);
...@@ -39,9 +42,6 @@ public: ...@@ -39,9 +42,6 @@ public:
const struct sockaddr* GetPeerAddress(); const struct sockaddr* GetPeerAddress();
const std::string& GetPeerIP(); const std::string& GetPeerIP();
MS_PORT GetPeerPort(); MS_PORT GetPeerPort();
void Close();
bool IsClosing();
virtual void Dump();
private: private:
bool SetPeerAddress(); bool SetPeerAddress();
...@@ -59,10 +59,10 @@ protected: ...@@ -59,10 +59,10 @@ protected:
virtual void userOnTCPConnectionRead() = 0; virtual void userOnTCPConnectionRead() = 0;
private: private:
// Allocated by this.
uv_tcp_t* uvHandle = nullptr;
// Passed by argument. // Passed by argument.
Listener* listener = nullptr; Listener* listener = nullptr;
// Allocated by this.
uv_tcp_t* uvHandle = nullptr;
// Others. // Others.
struct sockaddr_storage* localAddr = nullptr; struct sockaddr_storage* localAddr = nullptr;
bool isClosing = false; bool isClosing = false;
...@@ -70,10 +70,10 @@ private: ...@@ -70,10 +70,10 @@ private:
bool hasError = false; bool hasError = false;
protected: protected:
// Allocated by this.
MS_BYTE* buffer = nullptr;
// Passed by argument. // Passed by argument.
size_t bufferSize = 0; size_t bufferSize = 0;
// Allocated by this.
MS_BYTE* buffer = nullptr;
// Others. // Others.
size_t bufferDataLen = 0; size_t bufferDataLen = 0;
std::string localIP; std::string localIP;
...@@ -85,6 +85,12 @@ protected: ...@@ -85,6 +85,12 @@ protected:
/* Inline methods. */ /* Inline methods. */
inline
bool TCPConnection::IsClosing()
{
return this->isClosing;
}
inline inline
uv_tcp_t* TCPConnection::GetUvHandle() uv_tcp_t* TCPConnection::GetUvHandle()
{ {
...@@ -133,10 +139,4 @@ MS_PORT TCPConnection::GetPeerPort() ...@@ -133,10 +139,4 @@ MS_PORT TCPConnection::GetPeerPort()
return this->peerPort; return this->peerPort;
} }
inline
bool TCPConnection::IsClosing()
{
return this->isClosing;
}
#endif #endif
...@@ -17,13 +17,13 @@ public: ...@@ -17,13 +17,13 @@ public:
TCPServer(uv_tcp_t* uvHandle, int backlog); TCPServer(uv_tcp_t* uvHandle, int backlog);
virtual ~TCPServer(); virtual ~TCPServer();
void Close();
virtual void Dump();
bool IsClosing();
const struct sockaddr* GetLocalAddress(); const struct sockaddr* GetLocalAddress();
const std::string& GetLocalIP(); const std::string& GetLocalIP();
MS_PORT GetLocalPort(); MS_PORT GetLocalPort();
size_t GetNumConnections(); size_t GetNumConnections();
void Close();
bool IsClosing();
virtual void Dump();
private: private:
bool SetLocalAddress(); bool SetLocalAddress();
...@@ -61,15 +61,15 @@ protected: ...@@ -61,15 +61,15 @@ protected:
/* Inline methods. */ /* Inline methods. */
inline inline
size_t TCPServer::GetNumConnections() bool TCPServer::IsClosing()
{ {
return this->connections.size(); return this->isClosing;
} }
inline inline
bool TCPServer::IsClosing() size_t TCPServer::GetNumConnections()
{ {
return this->isClosing; return this->connections.size();
} }
#endif #endif
...@@ -16,19 +16,19 @@ public: ...@@ -16,19 +16,19 @@ public:
public: public:
Timer(Listener* listener); Timer(Listener* listener);
void Close();
void Start(MS_8BYTES timeout); void Start(MS_8BYTES timeout);
void Stop(); void Stop();
void Close();
/* Callbacks fired by UV events. */ /* Callbacks fired by UV events. */
public: public:
void onUvTimer(); void onUvTimer();
private: private:
// Allocated by this.
uv_timer_t* uvHandle = nullptr;
// Passed by argument. // Passed by argument.
Listener* listener = nullptr; Listener* listener = nullptr;
// Allocated by this.
uv_timer_t* uvHandle = nullptr;
}; };
#endif #endif
...@@ -27,6 +27,8 @@ public: ...@@ -27,6 +27,8 @@ public:
UDPSocket(uv_udp_t* uvHandle); UDPSocket(uv_udp_t* uvHandle);
virtual ~UDPSocket(); virtual ~UDPSocket();
void Close();
virtual void Dump();
void Send(const MS_BYTE* data, size_t len, const struct sockaddr* addr); void Send(const MS_BYTE* data, size_t len, const struct sockaddr* addr);
void Send(const std::string &data, const struct sockaddr* addr); void Send(const std::string &data, const struct sockaddr* addr);
void Send(const MS_BYTE* data, size_t len, const std::string &ip, MS_PORT port); void Send(const MS_BYTE* data, size_t len, const std::string &ip, MS_PORT port);
...@@ -34,8 +36,6 @@ public: ...@@ -34,8 +36,6 @@ public:
const struct sockaddr* GetLocalAddress(); const struct sockaddr* GetLocalAddress();
const std::string& GetLocalIP(); const std::string& GetLocalIP();
MS_PORT GetLocalPort(); MS_PORT GetLocalPort();
void Close();
virtual void Dump();
private: private:
bool SetLocalAddress(); bool SetLocalAddress();
......
...@@ -20,11 +20,10 @@ public: ...@@ -20,11 +20,10 @@ public:
UnixStreamSocket(int fd, size_t bufferSize); UnixStreamSocket(int fd, size_t bufferSize);
virtual ~UnixStreamSocket(); virtual ~UnixStreamSocket();
void Write(const MS_BYTE* data, size_t len);
void Write(const std::string &data);
void Close(); void Close();
bool IsClosing(); bool IsClosing();
virtual void Dump(); void Write(const MS_BYTE* data, size_t len);
void Write(const std::string &data);
/* Callbacks fired by UV events. */ /* Callbacks fired by UV events. */
public: public:
...@@ -48,10 +47,10 @@ private: ...@@ -48,10 +47,10 @@ private:
bool hasError = false; bool hasError = false;
protected: protected:
// Allocated by this.
MS_BYTE* buffer = nullptr;
// Passed by argument. // Passed by argument.
size_t bufferSize = 0; size_t bufferSize = 0;
// Allocated by this.
MS_BYTE* buffer = nullptr;
// Others. // Others.
size_t bufferDataLen = 0; size_t bufferDataLen = 0;
}; };
...@@ -59,16 +58,15 @@ protected: ...@@ -59,16 +58,15 @@ protected:
/* Inline methods. */ /* Inline methods. */
inline inline
void UnixStreamSocket::Write(const std::string &data) bool UnixStreamSocket::IsClosing()
{ {
Write((const MS_BYTE*)data.c_str(), data.size()); return this->isClosing;
} }
inline inline
bool UnixStreamSocket::IsClosing() void UnixStreamSocket::Write(const std::string &data)
{ {
return this->isClosing; Write((const MS_BYTE*)data.c_str(), data.size());
} }
#endif #endif
...@@ -29,14 +29,14 @@ namespace Channel ...@@ -29,14 +29,14 @@ namespace Channel
delete this; delete this;
} }
void Notifier::Emit(unsigned int targetId, std::string eventName) void Notifier::Emit(uint32_t targetId, std::string eventName)
{ {
MS_TRACE(); MS_TRACE();
Emit(targetId, eventName, empty_data); Emit(targetId, eventName, empty_data);
} }
void Notifier::Emit(unsigned int targetId, std::string eventName, Json::Value &eventData) void Notifier::Emit(uint32_t targetId, std::string eventName, Json::Value &eventData)
{ {
MS_TRACE(); MS_TRACE();
......
...@@ -111,7 +111,7 @@ namespace Channel ...@@ -111,7 +111,7 @@ namespace Channel
this->channel->Send(json); this->channel->Send(json);
} }
void Request::Reject(unsigned int status, std::string& reason) void Request::Reject(uint16_t status, std::string& reason)
{ {
MS_TRACE(); MS_TRACE();
...@@ -123,7 +123,7 @@ namespace Channel ...@@ -123,7 +123,7 @@ namespace Channel
* @param status 4XX means normal rejection, 5XX means error. * @param status 4XX means normal rejection, 5XX means error.
* @param reason Description string. * @param reason Description string.
*/ */
void Request::Reject(unsigned int status, const char* reason) void Request::Reject(uint16_t status, const char* reason)
{ {
MS_TRACE(); MS_TRACE();
......
...@@ -104,7 +104,7 @@ namespace Channel ...@@ -104,7 +104,7 @@ namespace Channel
else else
{ {
ns_num_len = (size_t)std::ceil(std::log10((double)ns_payload_len + 1)); ns_num_len = (size_t)std::ceil(std::log10((double)ns_payload_len + 1));
std::sprintf((char*)UnixStreamSocket::writeBuffer, "%lu:", (unsigned long)ns_payload_len); std::sprintf((char*)UnixStreamSocket::writeBuffer, "%zu:", ns_payload_len);
std::memcpy(UnixStreamSocket::writeBuffer + ns_num_len + 1, ns_payload.c_str(), ns_payload_len); std::memcpy(UnixStreamSocket::writeBuffer + ns_num_len + 1, ns_payload.c_str(), ns_payload_len);
UnixStreamSocket::writeBuffer[ns_num_len + ns_payload_len + 1] = ','; UnixStreamSocket::writeBuffer[ns_num_len + ns_payload_len + 1] = ',';
} }
...@@ -114,7 +114,7 @@ namespace Channel ...@@ -114,7 +114,7 @@ namespace Channel
Write(UnixStreamSocket::writeBuffer, ns_len); Write(UnixStreamSocket::writeBuffer, ns_len);
} }
void UnixStreamSocket::SendLog(char* ns_payload, int ns_payload_len) void UnixStreamSocket::SendLog(char* ns_payload, size_t ns_payload_len)
{ {
if (this->closed) if (this->closed)
return; return;
...@@ -141,7 +141,7 @@ namespace Channel ...@@ -141,7 +141,7 @@ namespace Channel
else else
{ {
ns_num_len = (size_t)std::ceil(std::log10((double)ns_payload_len + 1)); ns_num_len = (size_t)std::ceil(std::log10((double)ns_payload_len + 1));
std::sprintf((char*)UnixStreamSocket::writeBuffer, "%lu:", (unsigned long)ns_payload_len); std::sprintf((char*)UnixStreamSocket::writeBuffer, "%zu:", ns_payload_len);
std::memcpy(UnixStreamSocket::writeBuffer + ns_num_len + 1, ns_payload, ns_payload_len); std::memcpy(UnixStreamSocket::writeBuffer + ns_num_len + 1, ns_payload, ns_payload_len);
UnixStreamSocket::writeBuffer[ns_num_len + ns_payload_len + 1] = ','; UnixStreamSocket::writeBuffer[ns_num_len + ns_payload_len + 1] = ',';
} }
......
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
// This array will store all of the mutex available for OpenSSL. // This array will store all of the mutex available for OpenSSL.
pthread_mutex_t* DepOpenSSL::mutexes = nullptr; pthread_mutex_t* DepOpenSSL::mutexes = nullptr;
int DepOpenSSL::numMutexes = 0; uint32_t DepOpenSSL::numMutexes = 0;
/* Static methods. */ /* Static methods. */
...@@ -32,7 +32,7 @@ void DepOpenSSL::ClassInit() ...@@ -32,7 +32,7 @@ void DepOpenSSL::ClassInit()
DepOpenSSL::numMutexes = CRYPTO_num_locks(); DepOpenSSL::numMutexes = CRYPTO_num_locks();
for (int i = 0; i < DepOpenSSL::numMutexes; i++) for (uint32_t i = 0; i < DepOpenSSL::numMutexes; i++)
{ {
int err = pthread_mutex_init(&DepOpenSSL::mutexes[i], nullptr); int err = pthread_mutex_init(&DepOpenSSL::mutexes[i], nullptr);
if (err) if (err)
...@@ -68,7 +68,7 @@ void DepOpenSSL::ClassDestroy() ...@@ -68,7 +68,7 @@ void DepOpenSSL::ClassDestroy()
sk_SSL_COMP_free(SSL_COMP_get_compression_methods()); sk_SSL_COMP_free(SSL_COMP_get_compression_methods());
// Free mutexes. // Free mutexes.
for (int i = 0; i < DepOpenSSL::numMutexes; i++) for (uint32_t i = 0; i < DepOpenSSL::numMutexes; i++)
{ {
int err = pthread_mutex_destroy(&DepOpenSSL::mutexes[i]); int err = pthread_mutex_destroy(&DepOpenSSL::mutexes[i]);
if (err) if (err)
...@@ -123,6 +123,7 @@ CRYPTO_dynlock_value* DepOpenSSL::DynCreateFunction(const char* file, int line) ...@@ -123,6 +123,7 @@ CRYPTO_dynlock_value* DepOpenSSL::DynCreateFunction(const char* file, int line)
if (!value) if (!value)
{ {
MS_ABORT("new CRYPTO_dynlock_value failed"); MS_ABORT("new CRYPTO_dynlock_value failed");
return nullptr; return nullptr;
} }
......
...@@ -880,7 +880,7 @@ namespace RTC ...@@ -880,7 +880,7 @@ namespace RTC
} }
else if (timeout_ms < 30000) else if (timeout_ms < 30000)
{ {
MS_DEBUG("DTLS timer set in %llu ms", (unsigned long long)timeout_ms); MS_DEBUG("DTLS timer set in %" PRIu64 "ms", timeout_ms);
this->timer->Start(timeout_ms); this->timer->Start(timeout_ms);
...@@ -889,7 +889,7 @@ namespace RTC ...@@ -889,7 +889,7 @@ namespace RTC
// NOTE: Don't start the timer again if the timeout is greater than 30 seconds. // NOTE: Don't start the timer again if the timeout is greater than 30 seconds.
else else
{ {
MS_DEBUG("DTLS timeout too high (%llu ms), resetting DLTS", (unsigned long long)timeout_ms); MS_WARN("DTLS timeout too high (%" PRIu64 "ms), resetting DLTS", timeout_ms);
Reset(); Reset();
......
...@@ -24,6 +24,7 @@ namespace RTC ...@@ -24,6 +24,7 @@ namespace RTC
// Check CSRC list. // Check CSRC list.
size_t csrc_list_size = 0; size_t csrc_list_size = 0;
if (header->csrc_count) if (header->csrc_count)
{ {
csrc_list_size = header->csrc_count * sizeof(header->ssrc); csrc_list_size = header->csrc_count * sizeof(header->ssrc);
...@@ -31,7 +32,8 @@ namespace RTC ...@@ -31,7 +32,8 @@ namespace RTC
// Packet size must be >= header size + CSRC list. // Packet size must be >= header size + CSRC list.
if (len < pos + csrc_list_size) if (len < pos + csrc_list_size)
{ {
MS_DEBUG("not enough space for the announced CSRC list | packet discarded"); MS_DEBUG("not enough space for the announced CSRC list, packet discarded");
return nullptr; return nullptr;
} }
pos += csrc_list_size; pos += csrc_list_size;
...@@ -40,12 +42,13 @@ namespace RTC ...@@ -40,12 +42,13 @@ namespace RTC
// Check header extension. // Check header extension.
ExtensionHeader* extensionHeader = nullptr; ExtensionHeader* extensionHeader = nullptr;
size_t extension_value_size = 0; size_t extension_value_size = 0;
if (header->extension) if (header->extension)
{ {
// The extension header is at least 4 bytes. // The extension header is at least 4 bytes.
if (len < pos + 4) if (len < pos + 4)
{ {
MS_DEBUG("not enough space for the announced extension header | packet discarded"); MS_DEBUG("not enough space for the announced extension header, packet discarded");
return nullptr; return nullptr;
} }
...@@ -59,7 +62,8 @@ namespace RTC ...@@ -59,7 +62,8 @@ namespace RTC
// Packet size must be >= header size + CSRC list + header extension size. // Packet size must be >= header size + CSRC list + header extension size.
if (len < pos + 4 + extension_value_size) if (len < pos + 4 + extension_value_size)
{ {
MS_DEBUG("not enough space for the announced header extension value | packet discarded"); MS_DEBUG("not enough space for the announced header extension value, packet discarded");
return nullptr; return nullptr;
} }
pos += 4 + extension_value_size; pos += 4 + extension_value_size;
...@@ -78,7 +82,8 @@ namespace RTC ...@@ -78,7 +82,8 @@ namespace RTC
// Must be at least a single payload byte. // Must be at least a single payload byte.
if (payloadLength == 0) if (payloadLength == 0)
{ {
MS_DEBUG("padding bit is set but no space for a padding byte | packet discarded"); MS_DEBUG("padding bit is set but no space for a padding byte, packet discarded");
return nullptr; return nullptr;
} }
...@@ -86,12 +91,14 @@ namespace RTC ...@@ -86,12 +91,14 @@ namespace RTC
if (payloadPadding == 0) if (payloadPadding == 0)
{ {
MS_DEBUG("padding byte cannot be 0 packet discarded"); MS_DEBUG("padding byte cannot be 0 packet discarded");
return nullptr; return nullptr;
} }
if (payloadLength < (size_t)payloadPadding) if (payloadLength < (size_t)payloadPadding)
{ {
MS_DEBUG("number of padding octets is greater than available space for payload | packet discarded"); MS_DEBUG("number of padding octets is greater than available space for payload, packet discarded");
return nullptr; return nullptr;
} }
payloadLength -= (size_t)payloadPadding; payloadLength -= (size_t)payloadPadding;
...@@ -130,6 +137,31 @@ namespace RTC ...@@ -130,6 +137,31 @@ namespace RTC
delete this->raw; delete this->raw;
} }
void RTPPacket::Dump()
{
MS_TRACE();
if (!Logger::HasDebugLevel())
return;
MS_DEBUG("<RTPPacket>");
MS_DEBUG("padding: %s", this->header->padding ? "true" : "false");
MS_DEBUG("extension: %s", HasExtensionHeader() ? "true" : "false");
if (HasExtensionHeader())
{
MS_DEBUG("extension ID: %" PRIu16, GetExtensionHeaderId());
MS_DEBUG("extension length: %zu bytes", GetExtensionHeaderLength());
}
MS_DEBUG("CSRC count: %" PRIu8, this->header->csrc_count); // TODO: method?
MS_DEBUG("marker: %s", HasMarker() ? "true" : "false");
MS_DEBUG("payload type: %" PRIu8, GetPayloadType());
MS_DEBUG("sequence number: %" PRIu16, GetSequenceNumber());
MS_DEBUG("timestamp: %" PRIu32, GetTimestamp());
MS_DEBUG("SSRC: %" PRIu32, GetSSRC());
MS_DEBUG("payload size: %zu bytes", GetPayloadLength());
MS_DEBUG("</RTPPacket>");
}
void RTPPacket::Serialize() void RTPPacket::Serialize()
{ {
MS_TRACE(); MS_TRACE();
...@@ -208,29 +240,4 @@ namespace RTC ...@@ -208,29 +240,4 @@ namespace RTC
MS_ASSERT(pos == this->length, "pos != this->length"); MS_ASSERT(pos == this->length, "pos != this->length");
} }
void RTPPacket::Dump()
{
MS_TRACE();
if (!Logger::HasDebugLevel())
return;
MS_DEBUG("[RTPPacket]");
MS_DEBUG("- Padding: %s", this->header->padding ? "true" : "false");
MS_DEBUG("- Extension: %s", HasExtensionHeader() ? "true" : "false");
if (HasExtensionHeader())
{
MS_DEBUG("- Extension ID: %u", (unsigned int)GetExtensionHeaderId());
MS_DEBUG("- Extension length: %zu bytes", GetExtensionHeaderLength());
}
MS_DEBUG("- CSRC count: %u", (unsigned int)this->header->csrc_count); // TODO: method?
MS_DEBUG("- Marker: %s", HasMarker() ? "true" : "false");
MS_DEBUG("- Payload type: %u", (unsigned int)GetPayloadType());
MS_DEBUG("- Sequence number: %u", (unsigned int)GetSequenceNumber());
MS_DEBUG("- Timestamp: %lu", (unsigned long)GetTimestamp());
MS_DEBUG("- SSRC: %lu", (unsigned long)GetSSRC());
MS_DEBUG("- Payload size: %zu bytes", GetPayloadLength());
MS_DEBUG("[/RTPPacket]");
}
} }
...@@ -9,7 +9,7 @@ namespace RTC ...@@ -9,7 +9,7 @@ namespace RTC
{ {
/* Instance methods. */ /* Instance methods. */
Room::Room(Listener* listener, Channel::Notifier* notifier, unsigned int roomId) : Room::Room(Listener* listener, Channel::Notifier* notifier, uint32_t roomId) :
roomId(roomId), roomId(roomId),
listener(listener), listener(listener),
notifier(notifier) notifier(notifier)
...@@ -72,11 +72,11 @@ namespace RTC ...@@ -72,11 +72,11 @@ namespace RTC
{ {
case Channel::Request::MethodId::room_close: case Channel::Request::MethodId::room_close:
{ {
unsigned int roomId = this->roomId; uint32_t roomId = this->roomId;
Close(); Close();
MS_DEBUG("Room closed [roomId:%u]", roomId); MS_DEBUG("Room closed [roomId:%" PRIu32 "]", roomId);
request->Accept(); request->Accept();
break; break;
...@@ -96,7 +96,7 @@ namespace RTC ...@@ -96,7 +96,7 @@ namespace RTC
static const Json::StaticString k_peerName("peerName"); static const Json::StaticString k_peerName("peerName");
RTC::Peer* peer; RTC::Peer* peer;
unsigned int peerId; uint32_t peerId;
std::string peerName; std::string peerName;
try try
...@@ -185,7 +185,7 @@ namespace RTC ...@@ -185,7 +185,7 @@ namespace RTC
} }
} }
RTC::Peer* Room::GetPeerFromRequest(Channel::Request* request, unsigned int* peerId) RTC::Peer* Room::GetPeerFromRequest(Channel::Request* request, uint32_t* peerId)
{ {
MS_TRACE(); MS_TRACE();
......
...@@ -51,7 +51,8 @@ namespace RTC ...@@ -51,7 +51,8 @@ namespace RTC
break; break;
} }
MS_WARN("SSRC %llu: %s", (unsigned long long)data->stream->ssrc, event_desc); // TODO: u64?
MS_WARN("SSRC %" PRIu64 ": %s", (uint64_t)data->stream->ssrc, event_desc);
} }
/* Instance methods. */ /* Instance methods. */
......
...@@ -49,7 +49,8 @@ namespace RTC ...@@ -49,7 +49,8 @@ namespace RTC
// length field must be total size minus header's 20 bytes, and must be multiple of 4 Bytes. // length field must be total size minus header's 20 bytes, and must be multiple of 4 Bytes.
if (((size_t)msg_length != len - 20) || (msg_length & 0x03)) if (((size_t)msg_length != len - 20) || (msg_length & 0x03))
{ {
MS_DEBUG("length field + 20 does not match total size (or it is not multiple of 4 bytes) | message discarded"); MS_DEBUG("length field + 20 does not match total size (or it is not multiple of 4 bytes), message discarded");
return nullptr; return nullptr;
} }
...@@ -101,7 +102,8 @@ namespace RTC ...@@ -101,7 +102,8 @@ namespace RTC
// Ensure the attribute length is not greater than the remaining size. // Ensure the attribute length is not greater than the remaining size.
if ((pos + 4 + attr_length) > len) if ((pos + 4 + attr_length) > len)
{ {
MS_DEBUG("the attribute length exceeds the remaining size | message discarded"); MS_DEBUG("the attribute length exceeds the remaining size, message discarded");
delete msg; delete msg;
return nullptr; return nullptr;
} }
...@@ -109,7 +111,8 @@ namespace RTC ...@@ -109,7 +111,8 @@ namespace RTC
// FINGERPRINT must be the last attribute. // FINGERPRINT must be the last attribute.
if (has_fingerprint) if (has_fingerprint)
{ {
MS_DEBUG("attribute after FINGERPRINT is not allowed | message discarded"); MS_DEBUG("attribute after FINGERPRINT is not allowed, message discarded");
delete msg; delete msg;
return nullptr; return nullptr;
} }
...@@ -117,7 +120,8 @@ namespace RTC ...@@ -117,7 +120,8 @@ namespace RTC
// After a MESSAGE-INTEGRITY attribute just FINGERPRINT is allowed. // After a MESSAGE-INTEGRITY attribute just FINGERPRINT is allowed.
if (has_message_integrity && attr_type != Attribute::Fingerprint) if (has_message_integrity && attr_type != Attribute::Fingerprint)
{ {
MS_DEBUG("attribute after MESSAGE_INTEGRITY other than FINGERPRINT is not allowed | message discarded"); MS_DEBUG("attribute after MESSAGE_INTEGRITY other than FINGERPRINT is not allowed, message discarded");
delete msg; delete msg;
return nullptr; return nullptr;
} }
...@@ -169,7 +173,8 @@ namespace RTC ...@@ -169,7 +173,8 @@ namespace RTC
// Ensure current position matches the total length. // Ensure current position matches the total length.
if (pos != len) if (pos != len)
{ {
MS_DEBUG("computed message size does not match total size | message discarded"); MS_DEBUG("computed message size does not match total size, message discarded");
delete msg; delete msg;
return nullptr; return nullptr;
} }
...@@ -184,7 +189,8 @@ namespace RTC ...@@ -184,7 +189,8 @@ namespace RTC
// Compare with the FINGERPRINT value in the message. // Compare with the FINGERPRINT value in the message.
if (fingerprint != computed_fingerprint) if (fingerprint != computed_fingerprint)
{ {
MS_DEBUG("computed FINGERPRINT value does not match the value in the message | message discarded"); MS_DEBUG("computed FINGERPRINT value does not match the value in the message,| message discarded");
delete msg; delete msg;
return nullptr; return nullptr;
} }
...@@ -213,6 +219,69 @@ namespace RTC ...@@ -213,6 +219,69 @@ namespace RTC
delete this->raw; delete this->raw;
} }
void STUNMessage::Dump()
{
MS_TRACE();
if (!Logger::HasDebugLevel())
return;
MS_DEBUG("<STUNMessage>");
std::string klass;
switch (this->klass)
{
case Class::Request: klass = "Request"; break;
case Class::Indication: klass = "Indication"; break;
case Class::SuccessResponse: klass = "SuccessResponse"; break;
case Class::ErrorResponse: klass = "ErrorResponse"; break;
}
if (this->method == Method::Binding)
MS_DEBUG("Binding %s", klass.c_str());
else
// This prints the unknown method number. Example: TURN Allocate => 0x003.
MS_DEBUG("%s with unknown method %#.3x", klass.c_str(), (uint16_t)this->method);
MS_DEBUG("length (with header): %zu bytes", this->length);
char transaction_id[25];
for (int i=0; i<12; i++)
{
// NOTE: n must be 3 because snprintf adds a \0 after printed chars.
std::snprintf(transaction_id+(i*2), 3, "%.2x", this->transactionId[i]);
}
MS_DEBUG("transactionId: %s", transaction_id);
if (this->errorCode)
MS_DEBUG("errorCode: %" PRIu16, this->errorCode);
if (!this->username.empty())
MS_DEBUG("username: %s", this->username.c_str());
if (this->priority)
MS_DEBUG("priority: %" PRIu32, this->priority);
if (this->iceControlling)
MS_DEBUG("iceControlling: %" PRIu64, this->iceControlling);
if (this->iceControlled)
MS_DEBUG("iceControlled: %" PRIu64, this->iceControlled);
if (this->hasUseCandidate)
MS_DEBUG("useCandidate");
if (this->xorMappedAddress)
{
int family;
MS_PORT port;
std::string ip;
Utils::IP::GetAddressInfo(this->xorMappedAddress, &family, ip, &port);
MS_DEBUG("xorMappedAddress: %s : %" PRIu16, ip.c_str(), port);
}
if (this->messageIntegrity)
{
char message_integrity[41];
for (int i=0; i<20; i++)
{
std::snprintf(message_integrity+(i*2), 3, "%.2x", this->messageIntegrity[i]);
}
MS_DEBUG("messageIntegrity: %s", message_integrity);
}
if (this->hasFingerprint)
MS_DEBUG("fingerprint");
MS_DEBUG("</STUNMessage>");
}
STUNMessage::Authentication STUNMessage::CheckAuthentication(const std::string &local_username, const std::string &local_password) STUNMessage::Authentication STUNMessage::CheckAuthentication(const std::string &local_username, const std::string &local_password)
{ {
MS_TRACE(); MS_TRACE();
...@@ -243,6 +312,7 @@ namespace RTC ...@@ -243,6 +312,7 @@ namespace RTC
case Class::ErrorResponse: case Class::ErrorResponse:
{ {
MS_ERROR("cannot check authentication for a STUN response"); MS_ERROR("cannot check authentication for a STUN response");
return Authentication::BadRequest; return Authentication::BadRequest;
} }
} }
...@@ -299,6 +369,7 @@ namespace RTC ...@@ -299,6 +369,7 @@ namespace RTC
if (this->klass == Class::ErrorResponse) if (this->klass == Class::ErrorResponse)
{ {
MS_ERROR("cannot set password for ErrorResponse messages"); MS_ERROR("cannot set password for ErrorResponse messages");
return; return;
} }
...@@ -356,6 +427,7 @@ namespace RTC ...@@ -356,6 +427,7 @@ namespace RTC
break; break;
default: default:
MS_ERROR("invalid inet family in XOR-MAPPED-ADDRESS attribute"); MS_ERROR("invalid inet family in XOR-MAPPED-ADDRESS attribute");
add_xor_mapped_address = false; add_xor_mapped_address = false;
break; break;
} }
...@@ -566,67 +638,4 @@ namespace RTC ...@@ -566,67 +638,4 @@ namespace RTC
MS_ASSERT(pos == this->length, "pos != this->length"); MS_ASSERT(pos == this->length, "pos != this->length");
} }
void STUNMessage::Dump()
{
MS_TRACE();
if (!Logger::HasDebugLevel())
return;
MS_DEBUG("[STUNMessage]");
std::string klass;
switch (this->klass)
{
case Class::Request: klass = "Request"; break;
case Class::Indication: klass = "Indication"; break;
case Class::SuccessResponse: klass = "SuccessResponse"; break;
case Class::ErrorResponse: klass = "ErrorResponse"; break;
}
if (this->method == Method::Binding)
MS_DEBUG("- Binding %s", klass.c_str());
else
// This prints the unknown method number. Example: TURN Allocate => 0x003.
MS_DEBUG("- %s with unknown method %#.3x", klass.c_str(), (unsigned int)this->method);
MS_DEBUG("- Length (with header): %zu bytes", this->length);
char transaction_id[25];
for (int i=0; i<12; i++)
{
// NOTE: n must be 3 because snprintf adds a \0 after printed chars.
std::snprintf(transaction_id+(i*2), 3, "%.2x", this->transactionId[i]);
}
MS_DEBUG("- TransactionId: %s", transaction_id);
if (this->errorCode)
MS_DEBUG("- ErrorCode: %u", (unsigned int)this->errorCode);
if (!this->username.empty())
MS_DEBUG("- Username: %s", this->username.c_str());
if (this->priority)
MS_DEBUG("- Priority: %llu", (unsigned long long)this->priority);
if (this->iceControlling)
MS_DEBUG("- IceControlling: %llu", (unsigned long long)this->iceControlling);
if (this->iceControlled)
MS_DEBUG("- IceControlled: %llu", (unsigned long long)this->iceControlled);
if (this->hasUseCandidate)
MS_DEBUG("- has UseCandidate");
if (this->xorMappedAddress)
{
int family;
MS_PORT port;
std::string ip;
Utils::IP::GetAddressInfo(this->xorMappedAddress, &family, ip, &port);
MS_DEBUG("- XorMappedAddress: %s : %u", ip.c_str(), (unsigned int)port);
}
if (this->messageIntegrity)
{
char message_integrity[41];
for (int i=0; i<20; i++)
{
std::snprintf(message_integrity+(i*2), 3, "%.2x", this->messageIntegrity[i]);
}
MS_DEBUG("- MessageIntegrity: %s", message_integrity);
}
if (this->hasFingerprint)
MS_DEBUG("- has Fingerprint");
MS_DEBUG("[/STUNMessage]");
}
} }
...@@ -29,9 +29,9 @@ namespace RTC ...@@ -29,9 +29,9 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
MS_DEBUG("data received [local: %s : %u, remote: %s : %u]", MS_DEBUG("data received [local:%s :%" PRIu16 ", remote:%s :%" PRIu16 "]",
GetLocalIP().c_str(), (unsigned int)GetLocalPort(), GetLocalIP().c_str(), GetLocalPort(),
GetPeerIP().c_str(), (unsigned int)GetPeerPort()); GetPeerIP().c_str(), GetPeerPort());
/* /*
* Framing RFC 4571 * Framing RFC 4571
...@@ -96,13 +96,7 @@ namespace RTC ...@@ -96,13 +96,7 @@ namespace RTC
} }
else else
{ {
MS_DEBUG("packet of unknown type received, closing the connection"); MS_DEBUG("ignoring received packet of unknown type");
// Close the connection.
Close();
// Exit the parsing loop.
break;
} }
// If there is no more space available in the buffer and that is because // If there is no more space available in the buffer and that is because
...@@ -125,7 +119,8 @@ namespace RTC ...@@ -125,7 +119,8 @@ namespace RTC
// parse again. Otherwise break here and wait for more data. // parse again. Otherwise break here and wait for more data.
if (this->bufferDataLen > this->frameStart) if (this->bufferDataLen > this->frameStart)
{ {
MS_DEBUG("there is more data after the parsed frame, continue parsing"); // MS_DEBUG("there is more data after the parsed frame, continue parsing");
continue; continue;
} }
else else
...@@ -144,7 +139,7 @@ namespace RTC ...@@ -144,7 +139,7 @@ namespace RTC
// the buffer, so move the frame to the position 0. // the buffer, so move the frame to the position 0.
if (this->frameStart != 0) if (this->frameStart != 0)
{ {
MS_DEBUG("no more space in the buffer, moving parsed bytes to the beginning of the buffer and wait for more data"); // MS_DEBUG("no more space in the buffer, moving parsed bytes to the beginning of the buffer and wait for more data");
std::memmove(this->buffer, this->buffer + this->frameStart, this->bufferSize - this->frameStart); std::memmove(this->buffer, this->buffer + this->frameStart, this->bufferSize - this->frameStart);
this->bufferDataLen = this->bufferSize - this->frameStart; this->bufferDataLen = this->bufferSize - this->frameStart;
...@@ -154,7 +149,7 @@ namespace RTC ...@@ -154,7 +149,7 @@ namespace RTC
// The frame is too big, so close the connection. // The frame is too big, so close the connection.
else else
{ {
MS_ERROR("no more space in the buffer for the unfinished frame being parsed, closing the connection"); MS_WARN("no more space in the buffer for the unfinished frame being parsed, closing the connection");
// Close the socket. // Close the socket.
Close(); Close();
......
...@@ -138,7 +138,7 @@ namespace RTC ...@@ -138,7 +138,7 @@ namespace RTC
} }
// Choose a random first port to start from. // Choose a random first port to start from.
random_first_port = (MS_PORT)Utils::Crypto::GetRandomUInt((unsigned int)RTC::TCPServer::minPort, (unsigned int)RTC::TCPServer::maxPort); random_first_port = (MS_PORT)Utils::Crypto::GetRandomUInt((uint32_t)RTC::TCPServer::minPort, (uint32_t)RTC::TCPServer::maxPort);
// Make it even if pair is requested. // Make it even if pair is requested.
if (pair) if (pair)
random_first_port &= ~1; random_first_port &= ~1;
...@@ -169,15 +169,10 @@ namespace RTC ...@@ -169,15 +169,10 @@ namespace RTC
iterate_second_port = iterate_first_port + 1; iterate_second_port = iterate_first_port + 1;
} }
if (!pair)
MS_DEBUG("attempt: %u | trying port %u" , (unsigned int)attempt, (unsigned int)iterate_first_port);
else
MS_DEBUG("attempt: %u | trying ports %u and %u" , (unsigned int)attempt, (unsigned int)iterate_first_port, (unsigned int)iterate_second_port);
// Check whether the chosen port is available. // Check whether the chosen port is available.
if (!(*available_ports)[iterate_first_port]) if (!(*available_ports)[iterate_first_port])
{ {
MS_DEBUG("attempt: %u | port %u is in use, try again", (unsigned int)attempt, (unsigned int)iterate_first_port); MS_DEBUG("port in use, trying again [port:%" PRIu16 ", attempt:%" PRIu16 "]", iterate_first_port, attempt);
// If we have tried all the ports in the range raise an error. // If we have tried all the ports in the range raise an error.
if (iterate_first_port == random_first_port) if (iterate_first_port == random_first_port)
...@@ -191,7 +186,7 @@ namespace RTC ...@@ -191,7 +186,7 @@ namespace RTC
// Check also the odd port (if requested). // Check also the odd port (if requested).
if (pair && !(*available_ports)[iterate_second_port]) if (pair && !(*available_ports)[iterate_second_port])
{ {
MS_DEBUG("attempt: %u | odd port %u is in use, try again", (unsigned int)attempt, (unsigned int)iterate_second_port); MS_DEBUG("odd port in use, trying again [port:%" PRIu16 ", attempt:%" PRIu16 "]", iterate_second_port, attempt);
// If we have tried all the ports in the range raise an error. // If we have tried all the ports in the range raise an error.
if (iterate_first_port == random_first_port) if (iterate_first_port == random_first_port)
...@@ -229,26 +224,26 @@ namespace RTC ...@@ -229,26 +224,26 @@ namespace RTC
if (err) if (err)
{ {
delete uvHandles[0]; delete uvHandles[0];
MS_THROW_ERROR("attempt: %u | uv_tcp_init() failed: %s", (unsigned int)attempt, uv_strerror(err)); MS_THROW_ERROR("uv_tcp_init() failed: %s", uv_strerror(err));
} }
err = uv_tcp_bind(uvHandles[0], (const struct sockaddr*)&first_bind_addr, flags); err = uv_tcp_bind(uvHandles[0], (const struct sockaddr*)&first_bind_addr, flags);
if (err) if (err)
{ {
MS_WARN("attempt: %u | uv_tcp_bind() failed for port %u: %s", (unsigned int)attempt, (unsigned int)iterate_first_port, uv_strerror(err)); MS_WARN("uv_tcp_bind() failed [port:%" PRIu16 ", attempt:%" PRIu16 "]: %s", attempt, iterate_first_port, uv_strerror(err));
uv_close((uv_handle_t*)uvHandles[0], (uv_close_cb)on_error_close); uv_close((uv_handle_t*)uvHandles[0], (uv_close_cb)on_error_close);
// If bind() fails due to "too many open files" stop here. // If bind() fails due to "too many open files" stop here.
if (err == UV_EMFILE) if (err == UV_EMFILE)
{ {
MS_THROW_ERROR("bind() fails due to many open files"); MS_THROW_ERROR("uv_tcp_bind() fails due to many open files");
} }
// If bind() fails for more that MAX_BIND_ATTEMPTS then raise an error. // If bind() fails for more that MAX_BIND_ATTEMPTS then raise an error.
if (bindAttempt > MAX_BIND_ATTEMPTS) if (bindAttempt > MAX_BIND_ATTEMPTS)
{ {
MS_THROW_ERROR("bind() fails more than %u times for IP '%s'", MAX_BIND_ATTEMPTS, listenIP); MS_THROW_ERROR("uv_tcp_bind() fails more than %u times for IP '%s'", MAX_BIND_ATTEMPTS, listenIP);
} }
// If we have tried all the ports in the range raise an error. // If we have tried all the ports in the range raise an error.
...@@ -270,13 +265,13 @@ namespace RTC ...@@ -270,13 +265,13 @@ namespace RTC
{ {
uv_close((uv_handle_t*)uvHandles[0], (uv_close_cb)on_error_close); uv_close((uv_handle_t*)uvHandles[0], (uv_close_cb)on_error_close);
delete uvHandles[1]; delete uvHandles[1];
MS_THROW_ERROR("attempt: %u | uv_tcp_init() failed: %s", (unsigned int)attempt, uv_strerror(err)); MS_THROW_ERROR("uv_tcp_init() failed: %s", uv_strerror(err));
} }
err = uv_tcp_bind(uvHandles[1], (const struct sockaddr*)&second_bind_addr, flags); err = uv_tcp_bind(uvHandles[1], (const struct sockaddr*)&second_bind_addr, flags);
if (err) if (err)
{ {
MS_WARN("attempt: %u | uv_tcp_bind() failed for odd port %u: %s", (unsigned int)attempt, (unsigned int)iterate_second_port, uv_strerror(err)); MS_WARN("uv_tcp_bind() failed [port:%" PRIu16 ", attempt:%" PRIu16 "]: %s", attempt, iterate_second_port, uv_strerror(err));
uv_close((uv_handle_t*)uvHandles[0], (uv_close_cb)on_error_close); uv_close((uv_handle_t*)uvHandles[0], (uv_close_cb)on_error_close);
uv_close((uv_handle_t*)uvHandles[1], (uv_close_cb)on_error_close); uv_close((uv_handle_t*)uvHandles[1], (uv_close_cb)on_error_close);
...@@ -284,13 +279,13 @@ namespace RTC ...@@ -284,13 +279,13 @@ namespace RTC
// If bind() fails due to "too many open files" stop here. // If bind() fails due to "too many open files" stop here.
if (err == UV_EMFILE) if (err == UV_EMFILE)
{ {
MS_THROW_ERROR("bind() fails due to many open files"); MS_THROW_ERROR("uv_tcp_bind() fails due to many open files");
} }
// If bind() fails for more that MAX_BIND_ATTEMPTS then raise an error. // If bind() fails for more that MAX_BIND_ATTEMPTS then raise an error.
if (bindAttempt > MAX_BIND_ATTEMPTS) if (bindAttempt > MAX_BIND_ATTEMPTS)
{ {
MS_THROW_ERROR("bind() fails more than %u times for IP '%s'", MAX_BIND_ATTEMPTS, listenIP); MS_THROW_ERROR("uv_tcp_bind() fails more than %u times for IP '%s'", MAX_BIND_ATTEMPTS, listenIP);
} }
// If we have tried all the ports in the range raise an error. // If we have tried all the ports in the range raise an error.
...@@ -311,9 +306,11 @@ namespace RTC ...@@ -311,9 +306,11 @@ namespace RTC
(*available_ports)[iterate_second_port] = false; (*available_ports)[iterate_second_port] = false;
if (!pair) if (!pair)
MS_DEBUG("attempt: %u | available port for IP '%s': %u" , (unsigned int)attempt, listenIP, (unsigned int)iterate_first_port); MS_DEBUG("bind success [ip:%s, port:%" PRIu16 ", attempt:%" PRIu16 "]",
listenIP, iterate_first_port, attempt);
else else
MS_DEBUG("attempt: %u | available ports for IP '%s': %u and %u" , (unsigned int)attempt, listenIP, (unsigned int)iterate_first_port, (unsigned int)iterate_second_port); MS_DEBUG("bind success [ip:%s, ports:%" PRIu16 "|%" PRIu16 ", attempt:%" PRIu16 "]",
listenIP, iterate_first_port, iterate_second_port, attempt);
return; return;
}; };
......
...@@ -67,17 +67,17 @@ namespace RTC ...@@ -67,17 +67,17 @@ namespace RTC
Utils::IP::GetAddressInfo(GetRemoteAddress(), &remote_family, remote_ip, &remote_port); Utils::IP::GetAddressInfo(GetRemoteAddress(), &remote_family, remote_ip, &remote_port);
MS_DEBUG("[UDP | local: %s : %u | remote: %s : %u]", MS_DEBUG("[UDP, local:%s :%" PRIu16 ", remote:%s :%" PRIu16 "]",
this->udpSocket->GetLocalIP().c_str(), (unsigned int)this->udpSocket->GetLocalPort(), this->udpSocket->GetLocalIP().c_str(), this->udpSocket->GetLocalPort(),
remote_ip.c_str(), remote_port); remote_ip.c_str(), remote_port);
break; break;
} }
case Protocol::TCP: case Protocol::TCP:
{ {
MS_DEBUG("[TCP | local: %s : %u | remote: %s : %u]", MS_DEBUG("[TCP, local:%s :%" PRIu16 ", remote:%s :%" PRIu16 "]",
this->tcpConnection->GetLocalIP().c_str(), (unsigned int)this->tcpConnection->GetLocalPort(), this->tcpConnection->GetLocalIP().c_str(), this->tcpConnection->GetLocalPort(),
this->tcpConnection->GetPeerIP().c_str(), (unsigned int)this->tcpConnection->GetPeerPort()); this->tcpConnection->GetPeerIP().c_str(), this->tcpConnection->GetPeerPort());
break; break;
} }
} }
......
...@@ -139,7 +139,7 @@ namespace RTC ...@@ -139,7 +139,7 @@ namespace RTC
} }
// Choose a random first port to start from. // Choose a random first port to start from.
random_first_port = (MS_PORT)Utils::Crypto::GetRandomUInt((unsigned int)RTC::UDPSocket::minPort, (unsigned int)RTC::UDPSocket::maxPort); random_first_port = (MS_PORT)Utils::Crypto::GetRandomUInt((uint32_t)RTC::UDPSocket::minPort, (uint32_t)RTC::UDPSocket::maxPort);
// Make it even if pair is requested. // Make it even if pair is requested.
if (pair) if (pair)
random_first_port &= ~1; random_first_port &= ~1;
...@@ -170,15 +170,10 @@ namespace RTC ...@@ -170,15 +170,10 @@ namespace RTC
iterate_second_port = iterate_first_port + 1; iterate_second_port = iterate_first_port + 1;
} }
if (!pair)
MS_DEBUG("attempt: %u | trying port %u" , (unsigned int)attempt, (unsigned int)iterate_first_port);
else
MS_DEBUG("attempt: %u | trying ports %u and %u" , (unsigned int)attempt, (unsigned int)iterate_first_port, (unsigned int)iterate_second_port);
// Check whether the chosen port is available. // Check whether the chosen port is available.
if (!(*available_ports)[iterate_first_port]) if (!(*available_ports)[iterate_first_port])
{ {
MS_DEBUG("attempt: %u | port %u is in use, try again", (unsigned int)attempt, (unsigned int)iterate_first_port); MS_DEBUG("port in use, trying again [port:%" PRIu16 ", attempt:%" PRIu16 "]", iterate_first_port, attempt);
// If we have tried all the ports in the range raise an error. // If we have tried all the ports in the range raise an error.
if (iterate_first_port == random_first_port) { if (iterate_first_port == random_first_port) {
...@@ -191,7 +186,7 @@ namespace RTC ...@@ -191,7 +186,7 @@ namespace RTC
// Check also the odd port (if requested). // Check also the odd port (if requested).
if (pair && !(*available_ports)[iterate_second_port]) if (pair && !(*available_ports)[iterate_second_port])
{ {
MS_DEBUG("attempt: %u | odd port %u is in use, try again", (unsigned int)attempt, (unsigned int)iterate_second_port); MS_DEBUG("odd port in use, trying again [port:%" PRIu16 ", attempt:%" PRIu16 "]", iterate_second_port, attempt);
// If we have tried all the ports in the range raise an error. // If we have tried all the ports in the range raise an error.
if (iterate_first_port == random_first_port) { if (iterate_first_port == random_first_port) {
...@@ -228,26 +223,26 @@ namespace RTC ...@@ -228,26 +223,26 @@ namespace RTC
if (err) if (err)
{ {
delete uvHandles[0]; delete uvHandles[0];
MS_THROW_ERROR("attempt: %u | uv_udp_init() failed: %s", (unsigned int)attempt, uv_strerror(err)); MS_THROW_ERROR("uv_udp_init() failed: %s", uv_strerror(err));
} }
err = uv_udp_bind(uvHandles[0], (const struct sockaddr*)&first_bind_addr, flags); err = uv_udp_bind(uvHandles[0], (const struct sockaddr*)&first_bind_addr, flags);
if (err) if (err)
{ {
MS_WARN("attempt: %u | uv_udp_bind() failed for port %u: %s", (unsigned int)attempt, (unsigned int)iterate_first_port, uv_strerror(err)); MS_WARN("uv_udp_bind() failed [port:%" PRIu16 ", attempt:%" PRIu16 "]: %s", attempt, iterate_first_port, uv_strerror(err));
uv_close((uv_handle_t*)uvHandles[0], (uv_close_cb)on_error_close); uv_close((uv_handle_t*)uvHandles[0], (uv_close_cb)on_error_close);
// If bind() fails due to "too many open files" stop here. // If bind() fails due to "too many open files" stop here.
if (err == UV_EMFILE) if (err == UV_EMFILE)
{ {
MS_THROW_ERROR("bind() fails due to many open files"); MS_THROW_ERROR("uv_udp_bind() fails due to many open files");
} }
// If bind() fails for more that MAX_BIND_ATTEMPTS then raise an error. // If bind() fails for more that MAX_BIND_ATTEMPTS then raise an error.
if (bindAttempt > MAX_BIND_ATTEMPTS) if (bindAttempt > MAX_BIND_ATTEMPTS)
{ {
MS_THROW_ERROR("bind() fails more than %u times for IP '%s'", MAX_BIND_ATTEMPTS, listenIP); MS_THROW_ERROR("uv_udp_bind() fails more than %u times for IP '%s'", MAX_BIND_ATTEMPTS, listenIP);
} }
// If we have tried all the ports in the range raise an error. // If we have tried all the ports in the range raise an error.
...@@ -269,13 +264,13 @@ namespace RTC ...@@ -269,13 +264,13 @@ namespace RTC
{ {
uv_close((uv_handle_t*)uvHandles[0], (uv_close_cb)on_error_close); uv_close((uv_handle_t*)uvHandles[0], (uv_close_cb)on_error_close);
delete uvHandles[1]; delete uvHandles[1];
MS_THROW_ERROR("attempt: %u | uv_udp_init() failed: %s", (unsigned int)attempt, uv_strerror(err)); MS_THROW_ERROR("uv_udp_init() failed: %s", uv_strerror(err));
} }
err = uv_udp_bind(uvHandles[1], (const struct sockaddr*)&second_bind_addr, flags); err = uv_udp_bind(uvHandles[1], (const struct sockaddr*)&second_bind_addr, flags);
if (err) if (err)
{ {
MS_WARN("attempt: %u | uv_udp_bind() failed for odd port %u: %s", (unsigned int)attempt, (unsigned int)iterate_second_port, uv_strerror(err)); MS_WARN("uv_udp_bind() failed [port:%" PRIu16 ", attempt:%" PRIu16 "]: %s", attempt, iterate_second_port, uv_strerror(err));
uv_close((uv_handle_t*)uvHandles[0], (uv_close_cb)on_error_close); uv_close((uv_handle_t*)uvHandles[0], (uv_close_cb)on_error_close);
uv_close((uv_handle_t*)uvHandles[1], (uv_close_cb)on_error_close); uv_close((uv_handle_t*)uvHandles[1], (uv_close_cb)on_error_close);
...@@ -283,13 +278,13 @@ namespace RTC ...@@ -283,13 +278,13 @@ namespace RTC
// If bind() fails due to "too many open files" stop here. // If bind() fails due to "too many open files" stop here.
if (err == UV_EMFILE) if (err == UV_EMFILE)
{ {
MS_THROW_ERROR("bind() fails due to many open files"); MS_THROW_ERROR("uvp_udp_bind() fails due to many open files");
} }
// If bind() fails for more that MAX_BIND_ATTEMPTS then raise an error. // If bind() fails for more that MAX_BIND_ATTEMPTS then raise an error.
if (bindAttempt > MAX_BIND_ATTEMPTS) if (bindAttempt > MAX_BIND_ATTEMPTS)
{ {
MS_THROW_ERROR("bind() fails more than %u times for IP '%s'", MAX_BIND_ATTEMPTS, listenIP); MS_THROW_ERROR("uvp_udp_bind() fails more than %u times for IP '%s'", MAX_BIND_ATTEMPTS, listenIP);
} }
// If we have tried all the ports in the range raise an error. // If we have tried all the ports in the range raise an error.
...@@ -310,9 +305,11 @@ namespace RTC ...@@ -310,9 +305,11 @@ namespace RTC
(*available_ports)[iterate_second_port] = false; (*available_ports)[iterate_second_port] = false;
if (!pair) if (!pair)
MS_DEBUG("attempt: %u | available port for IP '%s': %u" , (unsigned int)attempt, listenIP, (unsigned int)iterate_first_port); MS_DEBUG("bind success [ip:%s, port:%" PRIu16 ", attempt:%" PRIu16 "]",
listenIP, iterate_first_port, attempt);
else else
MS_DEBUG("attempt: %u | available ports for IP '%s': %u and %u" , (unsigned int)attempt, listenIP, (unsigned int)iterate_first_port, (unsigned int)iterate_second_port); MS_DEBUG("bind success [ip:%s, ports:%" PRIu16 "|%" PRIu16 ", attempt:%" PRIu16 "]",
listenIP, iterate_first_port, iterate_second_port, attempt);
return; return;
}; };
...@@ -334,6 +331,7 @@ namespace RTC ...@@ -334,6 +331,7 @@ namespace RTC
if (!this->listener) if (!this->listener)
{ {
MS_ERROR("no listener set"); MS_ERROR("no listener set");
return; return;
} }
...@@ -343,13 +341,16 @@ namespace RTC ...@@ -343,13 +341,16 @@ namespace RTC
MS_PORT port; MS_PORT port;
std::string ip; std::string ip;
Utils::IP::GetAddressInfo(addr, &family, ip, &port); Utils::IP::GetAddressInfo(addr, &family, ip, &port);
MS_DEBUG("%zu bytes datagram received [local: %s : %u, remote: %s : %u]", len, GetLocalIP().c_str(), (unsigned int)GetLocalPort(), ip.c_str(), (unsigned int)port);
MS_DEBUG("datagram received [local:%s :%" PRIu16 ", remote:%s :%" PRIu16 ", len:%zu]",
GetLocalIP().c_str(), GetLocalPort(), ip.c_str(), port, len);
} }
// Check if it's STUN. // Check if it's STUN.
if (STUNMessage::IsSTUN(data, len)) if (STUNMessage::IsSTUN(data, len))
{ {
this->listener->onSTUNDataRecv(this, data, len, addr); this->listener->onSTUNDataRecv(this, data, len, addr);
return; return;
} }
...@@ -357,6 +358,7 @@ namespace RTC ...@@ -357,6 +358,7 @@ namespace RTC
if (RTCPPacket::IsRTCP(data, len)) if (RTCPPacket::IsRTCP(data, len))
{ {
this->listener->onRTCPDataRecv(this, data, len, addr); this->listener->onRTCPDataRecv(this, data, len, addr);
return; return;
} }
...@@ -364,6 +366,7 @@ namespace RTC ...@@ -364,6 +366,7 @@ namespace RTC
if (RTPPacket::IsRTP(data, len)) if (RTPPacket::IsRTP(data, len))
{ {
this->listener->onRTPDataRecv(this, data, len, addr); this->listener->onRTPDataRecv(this, data, len, addr);
return; return;
} }
...@@ -371,6 +374,7 @@ namespace RTC ...@@ -371,6 +374,7 @@ namespace RTC
if (DTLSTransport::IsDTLS(data, len)) if (DTLSTransport::IsDTLS(data, len))
{ {
this->listener->onDTLSDataRecv(this, data, len, addr); this->listener->onDTLSDataRecv(this, data, len, addr);
return; return;
} }
......
...@@ -24,13 +24,13 @@ bool IsBindableIP(const std::string &ip, int family, int* _bind_err); ...@@ -24,13 +24,13 @@ bool IsBindableIP(const std::string &ip, int family, int* _bind_err);
/* Class variables. */ /* Class variables. */
struct Settings::Configuration Settings::configuration; struct Settings::Configuration Settings::configuration;
std::map<std::string, unsigned int> Settings::string2LogLevel = std::map<std::string, uint8_t> Settings::string2LogLevel =
{ {
{ "debug", MS_LOG_LEVEL_DEBUG }, { "debug", MS_LOG_LEVEL_DEBUG },
{ "warn", MS_LOG_LEVEL_WARN }, { "warn", MS_LOG_LEVEL_WARN },
{ "error", MS_LOG_LEVEL_ERROR } { "error", MS_LOG_LEVEL_ERROR }
}; };
std::map<unsigned int, std::string> Settings::logLevel2String = std::map<uint8_t, std::string> Settings::logLevel2String =
{ {
{ MS_LOG_LEVEL_DEBUG, "debug" }, { MS_LOG_LEVEL_DEBUG, "debug" },
{ MS_LOG_LEVEL_WARN, "warn" }, { MS_LOG_LEVEL_WARN, "warn" },
...@@ -156,8 +156,8 @@ void Settings::PrintConfiguration() ...@@ -156,8 +156,8 @@ void Settings::PrintConfiguration()
MS_DEBUG("rtcListenIPv6: \"%s\"", Settings::configuration.rtcListenIPv6.c_str()); MS_DEBUG("rtcListenIPv6: \"%s\"", Settings::configuration.rtcListenIPv6.c_str());
else else
MS_DEBUG("rtcListenIPv6: (unavailable)"); MS_DEBUG("rtcListenIPv6: (unavailable)");
MS_DEBUG("rtcMinPort: %d", Settings::configuration.rtcMinPort); MS_DEBUG("rtcMinPort: %" PRIu16, Settings::configuration.rtcMinPort);
MS_DEBUG("rtcMaxPort: %d", Settings::configuration.rtcMaxPort); MS_DEBUG("rtcMaxPort: %" PRIu16, Settings::configuration.rtcMaxPort);
if (!Settings::configuration.dtlsCertificateFile.empty()) if (!Settings::configuration.dtlsCertificateFile.empty())
{ {
MS_DEBUG("dtlsCertificateFile: \"%s\"", Settings::configuration.dtlsCertificateFile.c_str()); MS_DEBUG("dtlsCertificateFile: \"%s\"", Settings::configuration.dtlsCertificateFile.c_str());
......
...@@ -66,7 +66,7 @@ namespace Utils ...@@ -66,7 +66,7 @@ namespace Utils
// Init the vrypto seed with a random number taken from the address // Init the vrypto seed with a random number taken from the address
// of the seed variable itself (which is random). // of the seed variable itself (which is random).
Crypto::seed = (uint32_t)(unsigned long)&Crypto::seed; Crypto::seed = (uint32_t)(uintptr_t)&Crypto::seed;
// Create an OpenSSL HMAC_CTX context for HMAC SHA1 calculation. // Create an OpenSSL HMAC_CTX context for HMAC SHA1 calculation.
HMAC_CTX_init(&Crypto::hmacSha1Ctx); HMAC_CTX_init(&Crypto::hmacSha1Ctx);
......
...@@ -30,7 +30,7 @@ namespace Utils ...@@ -30,7 +30,7 @@ namespace Utils
ip_family = AF_INET6; ip_family = AF_INET6;
} }
include core_grammar "../core_grammar.rl"; include grammar "grammar.rl";
main := IPv4address @on_ipv4 | main := IPv4address @on_ipv4 |
IPv6address @on_ipv6; IPv6address @on_ipv6;
......
%%{ %%{
machine core_grammar; machine grammar;
CRLF = "\r\n"; CRLF = "\r\n";
SP = 0x20; # Space. SP = 0x20; # Space.
......
...@@ -8,13 +8,6 @@ ...@@ -8,13 +8,6 @@
#include <cstring> // std::memcpy() #include <cstring> // std::memcpy()
#include <cstdlib> // std::malloc(), std::free() #include <cstdlib> // std::malloc(), std::free()
#define RETURN_IF_CLOSING() \
if (this->isClosing) \
{ \
MS_DEBUG("in closing state, doing nothing"); \
return; \
}
/* Static methods for UV callbacks. */ /* Static methods for UV callbacks. */
static inline static inline
...@@ -102,11 +95,54 @@ void TCPConnection::Setup(Listener* listener, struct sockaddr_storage* localAddr ...@@ -102,11 +95,54 @@ void TCPConnection::Setup(Listener* listener, struct sockaddr_storage* localAddr
this->localPort = localPort; this->localPort = localPort;
} }
void TCPConnection::Close()
{
MS_TRACE();
if (this->isClosing)
return;
int err;
this->isClosing = true;
// Don't read more.
err = uv_read_stop((uv_stream_t*)this->uvHandle);
if (err)
MS_ABORT("uv_read_stop() failed: %s", uv_strerror(err));
// If there is no error and the peer didn't close its connection side then close gracefully.
if (!this->hasError && !this->isClosedByPeer)
{
// Use uv_shutdown() so pending data to be written will be sent to the peer
// before closing.
uv_shutdown_t* req = new uv_shutdown_t;
req->data = (void*)this;
err = uv_shutdown(req, (uv_stream_t*)this->uvHandle, (uv_shutdown_cb)on_shutdown);
if (err)
MS_ABORT("uv_shutdown() failed: %s", uv_strerror(err));
}
// Otherwise directly close the socket.
else
{
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close);
}
}
void TCPConnection::Dump()
{
MS_DEBUG("[TCP, local:%s :%" PRIu16 ", remote:%s :%" PRIu16 ", status:%s]",
this->localIP.c_str(), (uint16_t)this->localPort,
this->peerIP.c_str(), (uint16_t)this->peerPort,
(!this->isClosing) ? "open" : "closed");
}
void TCPConnection::Start() void TCPConnection::Start()
{ {
MS_TRACE(); MS_TRACE();
RETURN_IF_CLOSING(); if (this->isClosing)
return;
int err; int err;
...@@ -123,13 +159,11 @@ void TCPConnection::Write(const MS_BYTE* data, size_t len) ...@@ -123,13 +159,11 @@ void TCPConnection::Write(const MS_BYTE* data, size_t len)
{ {
MS_TRACE(); MS_TRACE();
RETURN_IF_CLOSING(); if (this->isClosing)
return;
if (len == 0) if (len == 0)
{
MS_DEBUG("ignoring 0 length data");
return; return;
}
uv_buf_t buffer; uv_buf_t buffer;
int written; int written;
...@@ -155,13 +189,13 @@ void TCPConnection::Write(const MS_BYTE* data, size_t len) ...@@ -155,13 +189,13 @@ void TCPConnection::Write(const MS_BYTE* data, size_t len)
// Error. Should not happen. // Error. Should not happen.
else if (written < 0) else if (written < 0)
{ {
MS_WARN("uv_try_write() failed: %s | closing the connection", uv_strerror(written)); MS_WARN("uv_try_write() failed, closing the connection: %s", uv_strerror(written));
Close(); Close();
return; return;
} }
// TMP: remove this. // MS_DEBUG("could just write %zu bytes (%zu given) at first time, using uv_write() now", (size_t)written, len);
MS_DEBUG("could just write %zu bytes (%zu given) at first time, using uv_write() now", (size_t)written, len);
size_t pending_len = len - written; size_t pending_len = len - written;
...@@ -183,13 +217,11 @@ void TCPConnection::Write(const MS_BYTE* data1, size_t len1, const MS_BYTE* data ...@@ -183,13 +217,11 @@ void TCPConnection::Write(const MS_BYTE* data1, size_t len1, const MS_BYTE* data
{ {
MS_TRACE(); MS_TRACE();
RETURN_IF_CLOSING(); if (this->isClosing)
return;
if (len1 == 0 && len2 == 0) if (len1 == 0 && len2 == 0)
{
MS_DEBUG("ignoring 0 length data1 and data2");
return; return;
}
size_t total_len = len1 + len2; size_t total_len = len1 + len2;
uv_buf_t buffers[2]; uv_buf_t buffers[2];
...@@ -217,13 +249,13 @@ void TCPConnection::Write(const MS_BYTE* data1, size_t len1, const MS_BYTE* data ...@@ -217,13 +249,13 @@ void TCPConnection::Write(const MS_BYTE* data1, size_t len1, const MS_BYTE* data
// Error. Should not happen. // Error. Should not happen.
else if (written < 0) else if (written < 0)
{ {
MS_WARN("uv_try_write() failed: %s | closing the connection", uv_strerror(written)); MS_WARN("uv_try_write() failed, closing the connection: %s", uv_strerror(written));
Close(); Close();
return; return;
} }
// TMP: remove this. // MS_DEBUG("could just write %zu bytes (%zu given) at first time, using uv_write() now", (size_t)written, total_len);
MS_DEBUG("could just write %zu bytes (%zu given) at first time, using uv_write() now", (size_t)written, total_len);
size_t pending_len = total_len - written; size_t pending_len = total_len - written;
...@@ -251,47 +283,6 @@ void TCPConnection::Write(const MS_BYTE* data1, size_t len1, const MS_BYTE* data ...@@ -251,47 +283,6 @@ void TCPConnection::Write(const MS_BYTE* data1, size_t len1, const MS_BYTE* data
MS_ABORT("uv_write() failed: %s", uv_strerror(err)); MS_ABORT("uv_write() failed: %s", uv_strerror(err));
} }
void TCPConnection::Close()
{
MS_TRACE();
RETURN_IF_CLOSING();
int err;
this->isClosing = true;
// Don't read more.
err = uv_read_stop((uv_stream_t*)this->uvHandle);
if (err)
MS_ABORT("uv_read_stop() failed: %s", uv_strerror(err));
// If there is no error and the peer didn't close its connection side then close gracefully.
if (!this->hasError && !this->isClosedByPeer)
{
// Use uv_shutdown() so pending data to be written will be sent to the peer
// before closing.
uv_shutdown_t* req = new uv_shutdown_t;
req->data = (void*)this;
err = uv_shutdown(req, (uv_stream_t*)this->uvHandle, (uv_shutdown_cb)on_shutdown);
if (err)
MS_ABORT("uv_shutdown() failed: %s", uv_strerror(err));
}
// Otherwise directly close the socket.
else
{
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close);
}
}
void TCPConnection::Dump()
{
MS_DEBUG("[TCP | local address: %s : %u | peer address: %s : %u | status: %s]",
this->localIP.c_str(), (unsigned int)this->localPort,
this->peerIP.c_str(), (unsigned int)this->peerPort,
(!this->isClosing) ? "open" : "closed");
}
bool TCPConnection::SetPeerAddress() bool TCPConnection::SetPeerAddress()
{ {
MS_TRACE(); MS_TRACE();
...@@ -303,6 +294,7 @@ bool TCPConnection::SetPeerAddress() ...@@ -303,6 +294,7 @@ bool TCPConnection::SetPeerAddress()
if (err) if (err)
{ {
MS_ERROR("uv_tcp_getpeername() failed: %s", uv_strerror(err)); MS_ERROR("uv_tcp_getpeername() failed: %s", uv_strerror(err));
return false; return false;
} }
...@@ -327,11 +319,11 @@ void TCPConnection::onUvReadAlloc(size_t suggested_size, uv_buf_t* buf) ...@@ -327,11 +319,11 @@ void TCPConnection::onUvReadAlloc(size_t suggested_size, uv_buf_t* buf)
if (this->bufferSize > this->bufferDataLen) if (this->bufferSize > this->bufferDataLen)
{ {
buf->len = this->bufferSize - this->bufferDataLen; buf->len = this->bufferSize - this->bufferDataLen;
// MS_DEBUG("available space in the buffer: %zu", buf->len);
} }
else else
{ {
buf->len = 0; buf->len = 0;
MS_WARN("no available space in the buffer"); MS_WARN("no available space in the buffer");
} }
} }
...@@ -341,7 +333,8 @@ void TCPConnection::onUvRead(ssize_t nread, const uv_buf_t* buf) ...@@ -341,7 +333,8 @@ void TCPConnection::onUvRead(ssize_t nread, const uv_buf_t* buf)
{ {
MS_TRACE(); MS_TRACE();
RETURN_IF_CLOSING(); if (this->isClosing)
return;
if (nread == 0) if (nread == 0)
return; return;
...@@ -358,7 +351,8 @@ void TCPConnection::onUvRead(ssize_t nread, const uv_buf_t* buf) ...@@ -358,7 +351,8 @@ void TCPConnection::onUvRead(ssize_t nread, const uv_buf_t* buf)
// Client disconneted. // Client disconneted.
else if (nread == UV_EOF || nread == UV_ECONNRESET) else if (nread == UV_EOF || nread == UV_ECONNRESET)
{ {
MS_DEBUG("connection closed by client | closing server side"); MS_DEBUG("connection closed by peer, closing server side");
this->isClosedByPeer = true; this->isClosedByPeer = true;
// Close server side of the connection. // Close server side of the connection.
...@@ -367,11 +361,11 @@ void TCPConnection::onUvRead(ssize_t nread, const uv_buf_t* buf) ...@@ -367,11 +361,11 @@ void TCPConnection::onUvRead(ssize_t nread, const uv_buf_t* buf)
// Some error. // Some error.
else else
{ {
MS_DEBUG("read error: %s | closing the connection", uv_strerror(nread)); MS_DEBUG("read error, closing the connection: %s", uv_strerror(nread));
this->hasError = true; this->hasError = true;
// Close server side of the connection. // Close server side of the connection.
// NOTE: calling uv_read_stop() upon EOF is a MUST.
Close(); Close();
} }
} }
...@@ -386,11 +380,12 @@ void TCPConnection::onUvWriteError(int error) ...@@ -386,11 +380,12 @@ void TCPConnection::onUvWriteError(int error)
if (error == UV_EPIPE || error == UV_ENOTCONN) if (error == UV_EPIPE || error == UV_ENOTCONN)
{ {
MS_DEBUG("write error: %s | closing the connection", uv_strerror(error)); MS_DEBUG("write error, closing the connection: %s", uv_strerror(error));
} }
else else
{ {
MS_DEBUG("write error: %s | closing the connection", uv_strerror(error)); MS_DEBUG("write error, closing the connection: %s", uv_strerror(error));
this->hasError = true; this->hasError = true;
} }
......
...@@ -6,13 +6,6 @@ ...@@ -6,13 +6,6 @@
#include "MediaSoupError.h" #include "MediaSoupError.h"
#include "Logger.h" #include "Logger.h"
#define RETURN_IF_CLOSING() \
if (this->isClosing) \
{ \
MS_DEBUG("in closing state, doing nothing"); \
return; \
}
/* Static methods for UV callbacks. */ /* Static methods for UV callbacks. */
static inline static inline
...@@ -131,32 +124,12 @@ TCPServer::~TCPServer() ...@@ -131,32 +124,12 @@ TCPServer::~TCPServer()
delete this->uvHandle; delete this->uvHandle;
} }
const struct sockaddr* TCPServer::GetLocalAddress()
{
MS_TRACE();
return (const struct sockaddr*)&this->localAddr;
}
const std::string& TCPServer::GetLocalIP()
{
MS_TRACE();
return this->localIP;
}
MS_PORT TCPServer::GetLocalPort()
{
MS_TRACE();
return this->localPort;
}
void TCPServer::Close() void TCPServer::Close()
{ {
MS_TRACE(); MS_TRACE();
RETURN_IF_CLOSING(); if (this->isClosing)
return;
this->isClosing = true; this->isClosing = true;
...@@ -180,12 +153,33 @@ void TCPServer::Close() ...@@ -180,12 +153,33 @@ void TCPServer::Close()
void TCPServer::Dump() void TCPServer::Dump()
{ {
MS_DEBUG("[TCP | local address: %s : %u | status: %s | num connections: %zu]", MS_DEBUG("[TCP, local:%s :%" PRIu16 ", status:%s, connections:%zu]",
this->localIP.c_str(), (unsigned int)this->localPort, this->localIP.c_str(), (uint16_t)this->localPort,
(!this->isClosing) ? "open" : "closed", (!this->isClosing) ? "open" : "closed",
this->connections.size()); this->connections.size());
} }
const struct sockaddr* TCPServer::GetLocalAddress()
{
MS_TRACE();
return (const struct sockaddr*)&this->localAddr;
}
const std::string& TCPServer::GetLocalIP()
{
MS_TRACE();
return this->localIP;
}
MS_PORT TCPServer::GetLocalPort()
{
MS_TRACE();
return this->localPort;
}
bool TCPServer::SetLocalAddress() bool TCPServer::SetLocalAddress()
{ {
MS_TRACE(); MS_TRACE();
...@@ -197,6 +191,7 @@ bool TCPServer::SetLocalAddress() ...@@ -197,6 +191,7 @@ bool TCPServer::SetLocalAddress()
if (err) if (err)
{ {
MS_ERROR("uv_tcp_getsockname() failed: %s", uv_strerror(err)); MS_ERROR("uv_tcp_getsockname() failed: %s", uv_strerror(err));
return false; return false;
} }
...@@ -211,13 +206,15 @@ void TCPServer::onUvConnection(int status) ...@@ -211,13 +206,15 @@ void TCPServer::onUvConnection(int status)
{ {
MS_TRACE(); MS_TRACE();
RETURN_IF_CLOSING(); if (this->isClosing)
return;
int err; int err;
if (status) if (status)
{ {
MS_ERROR("error while receiving a new TCP connection: %s", uv_strerror(status)); MS_ERROR("error while receiving a new TCP connection: %s", uv_strerror(status));
return; return;
} }
...@@ -251,7 +248,7 @@ void TCPServer::onUvConnection(int status) ...@@ -251,7 +248,7 @@ void TCPServer::onUvConnection(int status)
} }
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
MS_ERROR("cannot run the TCP connection: %s | closing the connection", error.what()); MS_ERROR("cannot run the TCP connection, closing the connection: %s", error.what());
connection->Close(); connection->Close();
// NOTE: Don't return here so the user won't be notified about a "onclose" for a TCP connection // NOTE: Don't return here so the user won't be notified about a "onclose" for a TCP connection
// for which there was not a previous "onnew" event. // for which there was not a previous "onnew" event.
...@@ -293,9 +290,5 @@ void TCPServer::onTCPConnectionClosed(TCPConnection* connection, bool is_closed_ ...@@ -293,9 +290,5 @@ void TCPServer::onTCPConnectionClosed(TCPConnection* connection, bool is_closed_
// Check if the server is closing connections and if this is the last // Check if the server is closing connections and if this is the last
// connection then close the server now. // connection then close the server now.
if (this->isClosing && this->connections.empty()) if (this->isClosing && this->connections.empty())
{
MS_DEBUG("last active connection closed");
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close); uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close);
}
} }
...@@ -40,6 +40,16 @@ Timer::Timer(Listener* listener) : ...@@ -40,6 +40,16 @@ Timer::Timer(Listener* listener) :
} }
} }
void Timer::Close()
{
MS_TRACE();
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close);
// Delete this.
delete this;
}
void Timer::Start(MS_8BYTES timeout) void Timer::Start(MS_8BYTES timeout)
{ {
MS_TRACE(); MS_TRACE();
...@@ -62,16 +72,6 @@ void Timer::Stop() ...@@ -62,16 +72,6 @@ void Timer::Stop()
MS_THROW_ERROR("uv_timer_stop() failed: %s", uv_strerror(err)); MS_THROW_ERROR("uv_timer_stop() failed: %s", uv_strerror(err));
} }
void Timer::Close()
{
MS_TRACE();
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close);
// Delete this.
delete this;
}
inline inline
void Timer::onUvTimer() void Timer::onUvTimer()
{ {
......
...@@ -7,12 +7,6 @@ ...@@ -7,12 +7,6 @@
#include "Logger.h" #include "Logger.h"
#define MS_READ_BUFFER_SIZE 65536 #define MS_READ_BUFFER_SIZE 65536
#define RETURN_IF_CLOSING() \
if (this->isClosing) \
{ \
MS_DEBUG("in closing state, doing nothing"); \
return; \
}
/* Static methods for UV callbacks. */ /* Static methods for UV callbacks. */
...@@ -156,17 +150,41 @@ UDPSocket::~UDPSocket() ...@@ -156,17 +150,41 @@ UDPSocket::~UDPSocket()
delete this->uvHandle; delete this->uvHandle;
} }
void UDPSocket::Close()
{
MS_TRACE();
if (this->isClosing)
return;
int err;
this->isClosing = true;
// Don't read more.
err = uv_udp_recv_stop(this->uvHandle);
if (err)
MS_ABORT("uv_udp_recv_stop() failed: %s", uv_strerror(err));
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close);
}
void UDPSocket::Dump()
{
MS_DEBUG("[UDP, local:%s :%" PRIu16 ", status:%s]",
this->localIP.c_str(), (uint16_t)this->localPort,
(!this->isClosing) ? "open" : "closed");
}
void UDPSocket::Send(const MS_BYTE* data, size_t len, const struct sockaddr* addr) void UDPSocket::Send(const MS_BYTE* data, size_t len, const struct sockaddr* addr)
{ {
MS_TRACE(); MS_TRACE();
RETURN_IF_CLOSING(); if (this->isClosing)
return;
if (len == 0) if (len == 0)
{
MS_DEBUG("ignoring 0 length data");
return; return;
}
uv_buf_t buffer; uv_buf_t buffer;
int sent; int sent;
...@@ -186,18 +204,19 @@ void UDPSocket::Send(const MS_BYTE* data, size_t len, const struct sockaddr* add ...@@ -186,18 +204,19 @@ void UDPSocket::Send(const MS_BYTE* data, size_t len, const struct sockaddr* add
else if (sent >= 0) else if (sent >= 0)
{ {
MS_WARN("datagram truncated (just %d of %zu bytes were sent)", sent, len); MS_WARN("datagram truncated (just %d of %zu bytes were sent)", sent, len);
return; return;
} }
// Error, // Error,
else if (sent != UV_EAGAIN) else if (sent != UV_EAGAIN)
{ {
MS_WARN("uv_udp_try_send() failed: %s", uv_strerror(sent)); MS_WARN("uv_udp_try_send() failed: %s", uv_strerror(sent));
return; return;
} }
// Otherwise UV_EAGAIN was returned so cannot send data at first time. Use uv_udp_send(). // Otherwise UV_EAGAIN was returned so cannot send data at first time. Use uv_udp_send().
// TMP: remove this. // MS_DEBUG("could not send the datagram at first time, using uv_udp_send() now");
MS_DEBUG("could not send the datagram at first time, using uv_udp_send() now");
// Allocate a special UvSendData struct pointer. // Allocate a special UvSendData struct pointer.
UvSendData* send_data = (UvSendData*)std::malloc(sizeof(UvSendData) + len); UvSendData* send_data = (UvSendData*)std::malloc(sizeof(UvSendData) + len);
...@@ -224,15 +243,13 @@ void UDPSocket::Send(const MS_BYTE* data, size_t len, const std::string &ip, MS_ ...@@ -224,15 +243,13 @@ void UDPSocket::Send(const MS_BYTE* data, size_t len, const std::string &ip, MS_
{ {
MS_TRACE(); MS_TRACE();
RETURN_IF_CLOSING(); if (this->isClosing)
return;
int err; int err;
if (len == 0) if (len == 0)
{
MS_DEBUG("ignoring 0 length data");
return; return;
}
struct sockaddr_storage addr; struct sockaddr_storage addr;
...@@ -252,37 +269,13 @@ void UDPSocket::Send(const MS_BYTE* data, size_t len, const std::string &ip, MS_ ...@@ -252,37 +269,13 @@ void UDPSocket::Send(const MS_BYTE* data, size_t len, const std::string &ip, MS_
default: default:
MS_ERROR("invalid destination IP '%s'", ip.c_str()); MS_ERROR("invalid destination IP '%s'", ip.c_str());
return; return;
} }
Send(data, len, (struct sockaddr*)&addr); Send(data, len, (struct sockaddr*)&addr);
} }
void UDPSocket::Close()
{
MS_TRACE();
RETURN_IF_CLOSING();
int err;
this->isClosing = true;
// Don't read more.
err = uv_udp_recv_stop(this->uvHandle);
if (err)
MS_ABORT("uv_udp_recv_stop() failed: %s", uv_strerror(err));
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close);
}
void UDPSocket::Dump()
{
MS_DEBUG("[UDP | local address: %s : %u | status: %s]",
this->localIP.c_str(), (unsigned int)this->localPort,
(!this->isClosing) ? "open" : "closed");
}
bool UDPSocket::SetLocalAddress() bool UDPSocket::SetLocalAddress()
{ {
MS_TRACE(); MS_TRACE();
...@@ -294,6 +287,7 @@ bool UDPSocket::SetLocalAddress() ...@@ -294,6 +287,7 @@ bool UDPSocket::SetLocalAddress()
if (err) if (err)
{ {
MS_ERROR("uv_udp_getsockname() failed: %s", uv_strerror(err)); MS_ERROR("uv_udp_getsockname() failed: %s", uv_strerror(err));
return false; return false;
} }
...@@ -319,7 +313,8 @@ void UDPSocket::onUvRecv(ssize_t nread, const uv_buf_t* buf, const struct sockad ...@@ -319,7 +313,8 @@ void UDPSocket::onUvRecv(ssize_t nread, const uv_buf_t* buf, const struct sockad
{ {
MS_TRACE(); MS_TRACE();
RETURN_IF_CLOSING(); if (this->isClosing)
return;
// NOTE: libuv calls twice to alloc & recv when a datagram is received, the // NOTE: libuv calls twice to alloc & recv when a datagram is received, the
// second one with nread = 0 and addr = NULL. Ignore it. // second one with nread = 0 and addr = NULL. Ignore it.
...@@ -330,6 +325,7 @@ void UDPSocket::onUvRecv(ssize_t nread, const uv_buf_t* buf, const struct sockad ...@@ -330,6 +325,7 @@ void UDPSocket::onUvRecv(ssize_t nread, const uv_buf_t* buf, const struct sockad
if (flags & UV_UDP_PARTIAL) if (flags & UV_UDP_PARTIAL)
{ {
MS_ERROR("received datagram was truncated due to insufficient buffer, ignoring it"); MS_ERROR("received datagram was truncated due to insufficient buffer, ignoring it");
return; return;
} }
......
/**
* NOTE: This code cannot use MS_DEBUG, MS_WARN, MS_ERROR since this is the base
* code of the intercommunication Channel.
*/
#define MS_CLASS "UnixStreamSocket" #define MS_CLASS "UnixStreamSocket"
#include "handles/UnixStreamSocket.h" #include "handles/UnixStreamSocket.h"
...@@ -7,13 +12,6 @@ ...@@ -7,13 +12,6 @@
#include <cstring> // std::memcpy() #include <cstring> // std::memcpy()
#include <cstdlib> // std::malloc(), std::free() #include <cstdlib> // std::malloc(), std::free()
#define RETURN_IF_CLOSING() \
if (this->isClosing) \
{ \
MS_DEBUG_STD("in closing state, doing nothing"); \
return; \
}
/* Static methods for UV callbacks. */ /* Static methods for UV callbacks. */
static inline static inline
...@@ -108,17 +106,45 @@ UnixStreamSocket::~UnixStreamSocket() ...@@ -108,17 +106,45 @@ UnixStreamSocket::~UnixStreamSocket()
delete[] this->buffer; delete[] this->buffer;
} }
void UnixStreamSocket::Write(const MS_BYTE* data, size_t len) void UnixStreamSocket::Close()
{ {
// MS_TRACE_STD(); MS_TRACE_STD();
RETURN_IF_CLOSING(); if (this->isClosing)
return;
if (len == 0) int err;
this->isClosing = true;
// Don't read more.
err = uv_read_stop((uv_stream_t*)this->uvHandle);
if (err)
MS_ABORT("uv_read_stop() failed: %s", uv_strerror(err));
// If there is no error and the peer didn't close its pipe side then close gracefully.
if (!this->hasError && !this->isClosedByPeer)
{ {
MS_DEBUG_STD("ignoring 0 length data"); // Use uv_shutdown() so pending data to be written will be sent to the peer before closing.
return; uv_shutdown_t* req = new uv_shutdown_t;
req->data = (void*)this;
err = uv_shutdown(req, (uv_stream_t*)this->uvHandle, (uv_shutdown_cb)on_shutdown);
if (err)
MS_ABORT("uv_shutdown() failed: %s", uv_strerror(err));
} }
// Otherwise directly close the socket.
else {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close);
}
}
void UnixStreamSocket::Write(const MS_BYTE* data, size_t len)
{
if (this->isClosing)
return;
if (len == 0)
return;
uv_buf_t buffer; uv_buf_t buffer;
int written; int written;
...@@ -144,7 +170,7 @@ void UnixStreamSocket::Write(const MS_BYTE* data, size_t len) ...@@ -144,7 +170,7 @@ void UnixStreamSocket::Write(const MS_BYTE* data, size_t len)
// Error. Should not happen. // Error. Should not happen.
else if (written < 0) else if (written < 0)
{ {
MS_ERROR_STD("uv_try_write() failed: %s | closing the socket", uv_strerror(written)); MS_ERROR_STD("uv_try_write() failed, closing the socket: %s", uv_strerror(written));
Close(); Close();
return; return;
} }
...@@ -165,42 +191,6 @@ void UnixStreamSocket::Write(const MS_BYTE* data, size_t len) ...@@ -165,42 +191,6 @@ void UnixStreamSocket::Write(const MS_BYTE* data, size_t len)
MS_ABORT("uv_write() failed: %s", uv_strerror(err)); MS_ABORT("uv_write() failed: %s", uv_strerror(err));
} }
void UnixStreamSocket::Close()
{
MS_TRACE_STD();
RETURN_IF_CLOSING();
int err;
this->isClosing = true;
// Don't read more.
err = uv_read_stop((uv_stream_t*)this->uvHandle);
if (err)
MS_ABORT("uv_read_stop() failed: %s", uv_strerror(err));
// If there is no error and the peer didn't close its pipe side then close gracefully.
if (!this->hasError && !this->isClosedByPeer)
{
// Use uv_shutdown() so pending data to be written will be sent to the peer before closing.
uv_shutdown_t* req = new uv_shutdown_t;
req->data = (void*)this;
err = uv_shutdown(req, (uv_stream_t*)this->uvHandle, (uv_shutdown_cb)on_shutdown);
if (err)
MS_ABORT("uv_shutdown() failed: %s", uv_strerror(err));
}
// Otherwise directly close the socket.
else {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close);
}
}
void UnixStreamSocket::Dump()
{
MS_DEBUG_STD("[status: %s]", (!this->isClosing) ? "open" : "closed");
}
inline inline
void UnixStreamSocket::onUvReadAlloc(size_t suggested_size, uv_buf_t* buf) void UnixStreamSocket::onUvReadAlloc(size_t suggested_size, uv_buf_t* buf)
{ {
...@@ -221,6 +211,7 @@ void UnixStreamSocket::onUvReadAlloc(size_t suggested_size, uv_buf_t* buf) ...@@ -221,6 +211,7 @@ void UnixStreamSocket::onUvReadAlloc(size_t suggested_size, uv_buf_t* buf)
else else
{ {
buf->len = 0; buf->len = 0;
MS_ERROR_STD("no available space in the buffer"); MS_ERROR_STD("no available space in the buffer");
} }
} }
...@@ -245,6 +236,8 @@ void UnixStreamSocket::onUvRead(ssize_t nread, const uv_buf_t* buf) ...@@ -245,6 +236,8 @@ void UnixStreamSocket::onUvRead(ssize_t nread, const uv_buf_t* buf)
// Peer disconneted. // Peer disconneted.
else if (nread == UV_EOF || nread == UV_ECONNRESET) else if (nread == UV_EOF || nread == UV_ECONNRESET)
{ {
MS_DEBUG("connection closed by peer, closing server side");
this->isClosedByPeer = true; this->isClosedByPeer = true;
// Close local side of the pipe. // Close local side of the pipe.
...@@ -253,11 +246,11 @@ void UnixStreamSocket::onUvRead(ssize_t nread, const uv_buf_t* buf) ...@@ -253,11 +246,11 @@ void UnixStreamSocket::onUvRead(ssize_t nread, const uv_buf_t* buf)
// Some error. // Some error.
else else
{ {
MS_ERROR_STD("read error: %s | closing the pipe", uv_strerror(nread)); MS_ERROR_STD("read error, closing the pipe: %s", uv_strerror(nread));
this->hasError = true; this->hasError = true;
// Close the socket. // Close the socket.
// NOTE: calling uv_read_stop() upon EOF is a MUST.
Close(); Close();
} }
} }
...@@ -272,11 +265,12 @@ void UnixStreamSocket::onUvWriteError(int error) ...@@ -272,11 +265,12 @@ void UnixStreamSocket::onUvWriteError(int error)
if (error == UV_EPIPE || error == UV_ENOTCONN) if (error == UV_EPIPE || error == UV_ENOTCONN)
{ {
MS_DEBUG_STD("write error: %s | closing the pipe", uv_strerror(error)); MS_DEBUG_STD("write error, closing the pipe: %s", uv_strerror(error));
} }
else else
{ {
MS_DEBUG_STD("write error: %s | closing the pipe", uv_strerror(error)); MS_DEBUG_STD("write error, closing the pipe: %s", uv_strerror(error));
this->hasError = true; this->hasError = true;
} }
......
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
#include "Logger.h" #include "Logger.h"
#include <map> #include <map>
#include <string> #include <string>
#include <iostream> // std::cerr, std::endl
#include <cstdlib> // std::_Exit(), std::genenv() #include <cstdlib> // std::_Exit(), std::genenv()
#include <csignal> // sigaction() #include <csignal> // sigaction()
#include <cerrno> #include <cerrno>
...@@ -34,7 +35,7 @@ int main(int argc, char* argv[]) ...@@ -34,7 +35,7 @@ int main(int argc, char* argv[])
// Ensure we are called by our Node library. // Ensure we are called by our Node library.
if (argc == 1 || !std::getenv("MEDIASOUP_CHANNEL_FD")) if (argc == 1 || !std::getenv("MEDIASOUP_CHANNEL_FD"))
{ {
fprintf(stderr, "YOU ARE NOT MY REAL FATHER\n"); std::cerr << "ERROR: you don't seem to be my real father" << std::endl;
std::_Exit(EXIT_FAILURE); std::_Exit(EXIT_FAILURE);
} }
...@@ -58,6 +59,7 @@ int main(int argc, char* argv[]) ...@@ -58,6 +59,7 @@ int main(int argc, char* argv[])
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
MS_ERROR("configuration error: %s", error.what()); MS_ERROR("configuration error: %s", error.what());
exitWithError(); exitWithError();
} }
...@@ -88,12 +90,14 @@ int main(int argc, char* argv[]) ...@@ -88,12 +90,14 @@ int main(int argc, char* argv[])
Loop loop(channel); Loop loop(channel);
destroy(); destroy();
MS_DEBUG_STD("success exit"); MS_DEBUG_STD("success exit");
exitSuccess(); exitSuccess();
} }
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
destroy(); destroy();
MS_ERROR_STD("failure exit: %s", error.what()); MS_ERROR_STD("failure exit: %s", error.what());
exitWithError(); exitWithError();
} }
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论