Unverified 提交 6c8d051d authored 作者: Iñaki Baz Castillo's avatar Iñaki Baz Castillo 提交者: GitHub

C++: Remove Destroy() methods (#256)

上级 c4be3bef
...@@ -20,8 +20,6 @@ namespace Channel ...@@ -20,8 +20,6 @@ namespace Channel
public: public:
explicit UnixStreamSocket(int fd); explicit UnixStreamSocket(int fd);
private:
~UnixStreamSocket() override; ~UnixStreamSocket() override;
public: public:
...@@ -42,7 +40,6 @@ namespace Channel ...@@ -42,7 +40,6 @@ namespace Channel
Json::CharReader* jsonReader{ nullptr }; Json::CharReader* jsonReader{ nullptr };
Json::StreamWriter* jsonWriter{ nullptr }; Json::StreamWriter* jsonWriter{ nullptr };
size_t msgStart{ 0 }; // Where the latest message starts. size_t msgStart{ 0 }; // Where the latest message starts.
bool closed{ false };
}; };
} // namespace Channel } // namespace Channel
......
...@@ -34,12 +34,9 @@ namespace RTC ...@@ -34,12 +34,9 @@ namespace RTC
uint32_t consumerId, uint32_t consumerId,
RTC::Media::Kind kind, RTC::Media::Kind kind,
uint32_t sourceProducerId); uint32_t sourceProducerId);
private:
virtual ~Consumer(); virtual ~Consumer();
public: public:
void Destroy();
Json::Value ToJson() const; Json::Value ToJson() const;
Json::Value GetStats() const; Json::Value GetStats() const;
void AddListener(RTC::ConsumerListener* listener); void AddListener(RTC::ConsumerListener* listener);
......
...@@ -81,17 +81,13 @@ namespace RTC ...@@ -81,17 +81,13 @@ namespace RTC
std::string& remoteCert) = 0; std::string& remoteCert) = 0;
// The DTLS connection has been closed as the result of an error (such as a // The DTLS connection has been closed as the result of an error (such as a
// DTLS alert or a failure to validate the remote fingerprint). // DTLS alert or a failure to validate the remote fingerprint).
// NOTE: The caller MUST NOT call Destroy() during this callback.
virtual void OnDtlsFailed(const RTC::DtlsTransport* dtlsTransport) = 0; virtual void OnDtlsFailed(const RTC::DtlsTransport* dtlsTransport) = 0;
// The DTLS connection has been closed due to receipt of a close_notify alert. // The DTLS connection has been closed due to receipt of a close_notify alert.
// NOTE: The caller MUST NOT call Destroy() during this callback.
virtual void OnDtlsClosed(const RTC::DtlsTransport* dtlsTransport) = 0; virtual void OnDtlsClosed(const RTC::DtlsTransport* dtlsTransport) = 0;
// Need to send DTLS data to the peer. // Need to send DTLS data to the peer.
// NOTE: The caller MUST NOT call Destroy() during this callback.
virtual void OnOutgoingDtlsData( virtual void OnOutgoingDtlsData(
const RTC::DtlsTransport* dtlsTransport, const uint8_t* data, size_t len) = 0; const RTC::DtlsTransport* dtlsTransport, const uint8_t* data, size_t len) = 0;
// DTLS application data received. // DTLS application data received.
// NOTE: The caller MUST NOT call Destroy() during this callback.
virtual void OnDtlsApplicationData( virtual void OnDtlsApplicationData(
const RTC::DtlsTransport* dtlsTransport, const uint8_t* data, size_t len) = 0; const RTC::DtlsTransport* dtlsTransport, const uint8_t* data, size_t len) = 0;
}; };
...@@ -122,12 +118,9 @@ namespace RTC ...@@ -122,12 +118,9 @@ namespace RTC
public: public:
explicit DtlsTransport(Listener* listener); explicit DtlsTransport(Listener* listener);
private:
~DtlsTransport() override; ~DtlsTransport() override;
public: public:
void Destroy();
void Dump() const; void Dump() const;
void Run(Role localRole); void Run(Role localRole);
bool SetRemoteFingerprint(Fingerprint fingerprint); bool SetRemoteFingerprint(Fingerprint fingerprint);
......
...@@ -42,7 +42,6 @@ namespace RTC ...@@ -42,7 +42,6 @@ namespace RTC
public: public:
IceServer(Listener* listener, const std::string& usernameFragment, const std::string& password); IceServer(Listener* listener, const std::string& usernameFragment, const std::string& password);
void Destroy();
void ProcessStunMessage(RTC::StunMessage* msg, RTC::TransportTuple* tuple); void ProcessStunMessage(RTC::StunMessage* msg, RTC::TransportTuple* tuple);
const std::string& GetUsernameFragment() const; const std::string& GetUsernameFragment() const;
const std::string& GetPassword() const; const std::string& GetPassword() const;
......
...@@ -57,13 +57,9 @@ namespace RTC ...@@ -57,13 +57,9 @@ namespace RTC
RTC::RtpParameters& rtpParameters, RTC::RtpParameters& rtpParameters,
struct RtpMapping& rtpMapping, struct RtpMapping& rtpMapping,
bool paused); bool paused);
~Producer();
public: public:
// Must be public because Router needs to call it.
virtual ~Producer();
public:
void Destroy();
Json::Value ToJson() const; Json::Value ToJson() const;
Json::Value GetStats() const; Json::Value GetStats() const;
void AddListener(RTC::ProducerListener* listener); void AddListener(RTC::ProducerListener* listener);
......
...@@ -38,12 +38,9 @@ namespace RTC ...@@ -38,12 +38,9 @@ namespace RTC
public: public:
Router(Listener* listener, Channel::Notifier* notifier, uint32_t routerId); Router(Listener* listener, Channel::Notifier* notifier, uint32_t routerId);
private:
virtual ~Router(); virtual ~Router();
public: public:
void Destroy();
Json::Value ToJson() const; Json::Value ToJson() const;
void HandleRequest(Channel::Request* request); void HandleRequest(Channel::Request* request);
......
...@@ -31,12 +31,9 @@ namespace RTC ...@@ -31,12 +31,9 @@ namespace RTC
public: public:
SrtpSession(Type type, Profile profile, uint8_t* key, size_t keyLen); SrtpSession(Type type, Profile profile, uint8_t* key, size_t keyLen);
private:
~SrtpSession(); ~SrtpSession();
public: public:
void Destroy();
bool EncryptRtp(const uint8_t** data, size_t* len); bool EncryptRtp(const uint8_t** data, size_t* len);
bool DecryptSrtp(const uint8_t* data, size_t* len); bool DecryptSrtp(const uint8_t* data, size_t* len);
bool EncryptRtcp(const uint8_t** data, size_t* len); bool EncryptRtcp(const uint8_t** data, size_t* len);
......
...@@ -18,9 +18,6 @@ namespace RTC ...@@ -18,9 +18,6 @@ namespace RTC
public: public:
TcpConnection(Listener* listener, size_t bufferSize); TcpConnection(Listener* listener, size_t bufferSize);
private:
~TcpConnection() override = default;
public: public:
void Send(const uint8_t* data, size_t len); void Send(const uint8_t* data, size_t len);
size_t GetRecvBytes() const; size_t GetRecvBytes() const;
......
...@@ -39,16 +39,13 @@ namespace RTC ...@@ -39,16 +39,13 @@ namespace RTC
public: public:
TcpServer(Listener* listener, RTC::TcpConnection::Listener* connListener, int addressFamily); TcpServer(Listener* listener, RTC::TcpConnection::Listener* connListener, int addressFamily);
~TcpServer() override;
private:
~TcpServer() override = default;
/* Pure virtual methods inherited from ::TcpServer. */ /* Pure virtual methods inherited from ::TcpServer. */
public: public:
void UserOnTcpConnectionAlloc(::TcpConnection** connection) override; void UserOnTcpConnectionAlloc(::TcpConnection** connection) override;
void UserOnNewTcpConnection(::TcpConnection* connection) override; void UserOnNewTcpConnection(::TcpConnection* connection) override;
void UserOnTcpConnectionClosed(::TcpConnection* connection, bool isClosedByPeer) override; void UserOnTcpConnectionClosed(::TcpConnection* connection, bool isClosedByPeer) override;
void UserOnTcpServerClosed() override;
private: private:
// Passed by argument. // Passed by argument.
......
...@@ -67,12 +67,10 @@ namespace RTC ...@@ -67,12 +67,10 @@ namespace RTC
public: public:
Transport(Listener* listener, Channel::Notifier* notifier, uint32_t transportId); Transport(Listener* listener, Channel::Notifier* notifier, uint32_t transportId);
protected:
virtual ~Transport(); virtual ~Transport();
public: public:
void Destroy(); void Close();
virtual Json::Value ToJson() const = 0; virtual Json::Value ToJson() const = 0;
virtual Json::Value GetStats() const = 0; virtual Json::Value GetStats() const = 0;
void HandleProducer(RTC::Producer* producer); void HandleProducer(RTC::Producer* producer);
...@@ -132,9 +130,10 @@ namespace RTC ...@@ -132,9 +130,10 @@ namespace RTC
Channel::Notifier* notifier{ nullptr }; Channel::Notifier* notifier{ nullptr };
// Allocated by this. // Allocated by this.
Timer* rtcpTimer{ nullptr }; Timer* rtcpTimer{ nullptr };
// Allocated (Mirroring).
RTC::UdpSocket* mirrorSocket{ nullptr }; RTC::UdpSocket* mirrorSocket{ nullptr };
RTC::TransportTuple* mirrorTuple{ nullptr }; RTC::TransportTuple* mirrorTuple{ nullptr };
// Others.
bool closed{ false };
// Others (Producers and Consumers). // Others (Producers and Consumers).
std::unordered_set<RTC::Producer*> producers; std::unordered_set<RTC::Producer*> producers;
std::unordered_set<RTC::Consumer*> consumers; std::unordered_set<RTC::Consumer*> consumers;
......
...@@ -39,14 +39,11 @@ namespace RTC ...@@ -39,14 +39,11 @@ namespace RTC
public: public:
UdpSocket(Listener* listener, int addressFamily); UdpSocket(Listener* listener, int addressFamily);
UdpSocket(Listener* listener, const std::string& ip); UdpSocket(Listener* listener, const std::string& ip);
~UdpSocket() override;
private:
~UdpSocket() override = default;
/* Pure virtual methods inherited from ::UdpSocket. */ /* Pure virtual methods inherited from ::UdpSocket. */
public: public:
void UserOnUdpDatagramRecv(const uint8_t* data, size_t len, const struct sockaddr* addr) override; void UserOnUdpDatagramRecv(const uint8_t* data, size_t len, const struct sockaddr* addr) override;
void UserOnUdpSocketClosed() override;
private: private:
// Passed by argument. // Passed by argument.
......
...@@ -42,9 +42,7 @@ namespace RTC ...@@ -42,9 +42,7 @@ namespace RTC
Channel::Notifier* notifier, Channel::Notifier* notifier,
uint32_t transportId, uint32_t transportId,
Options& options); Options& options);
~WebRtcTransport() override;
private:
~WebRtcTransport();
public: public:
Json::Value ToJson() const override; Json::Value ToJson() const override;
......
...@@ -19,12 +19,10 @@ public: ...@@ -19,12 +19,10 @@ public:
public: public:
explicit SignalsHandler(Listener* listener); explicit SignalsHandler(Listener* listener);
~SignalsHandler();
private:
~SignalsHandler() = default;
public: public:
void Destroy(); void Close();
void AddSignal(int signum, const std::string& name); void AddSignal(int signum, const std::string& name);
/* Callbacks fired by UV events. */ /* Callbacks fired by UV events. */
...@@ -36,6 +34,8 @@ private: ...@@ -36,6 +34,8 @@ private:
Listener* listener{ nullptr }; Listener* listener{ nullptr };
// Allocated by this. // Allocated by this.
std::vector<uv_signal_t*> uvHandles; std::vector<uv_signal_t*> uvHandles;
// Others.
bool closed{ false };
}; };
#endif #endif
...@@ -37,19 +37,17 @@ public: ...@@ -37,19 +37,17 @@ public:
explicit TcpConnection(size_t bufferSize); explicit TcpConnection(size_t bufferSize);
TcpConnection& operator=(const TcpConnection&) = delete; TcpConnection& operator=(const TcpConnection&) = delete;
TcpConnection(const TcpConnection&) = delete; TcpConnection(const TcpConnection&) = delete;
protected:
virtual ~TcpConnection(); virtual ~TcpConnection();
public: public:
void Destroy(); void Close();
virtual void Dump() const; virtual void Dump() const;
void Setup( void Setup(
Listener* listener, Listener* listener,
struct sockaddr_storage* localAddr, struct sockaddr_storage* localAddr,
const std::string& localIP, const std::string& localIP,
uint16_t localPort); uint16_t localPort);
bool IsClosing() const; bool IsClosed() const;
uv_tcp_t* GetUvHandle() const; uv_tcp_t* GetUvHandle() const;
void Start(); void Start();
void Write(const uint8_t* data, size_t len); void Write(const uint8_t* data, size_t len);
...@@ -71,8 +69,6 @@ public: ...@@ -71,8 +69,6 @@ public:
void OnUvReadAlloc(size_t suggestedSize, uv_buf_t* buf); void OnUvReadAlloc(size_t suggestedSize, uv_buf_t* buf);
void OnUvRead(ssize_t nread, const uv_buf_t* buf); void OnUvRead(ssize_t nread, const uv_buf_t* buf);
void OnUvWriteError(int error); void OnUvWriteError(int error);
void OnUvShutdown(uv_shutdown_t* req, int status);
void OnUvClosed();
/* Pure virtual methods that must be implemented by the subclass. */ /* Pure virtual methods that must be implemented by the subclass. */
protected: protected:
...@@ -85,7 +81,7 @@ private: ...@@ -85,7 +81,7 @@ private:
uv_tcp_t* uvHandle{ nullptr }; uv_tcp_t* uvHandle{ nullptr };
// Others. // Others.
struct sockaddr_storage* localAddr{ nullptr }; struct sockaddr_storage* localAddr{ nullptr };
bool isClosing{ false }; bool closed{ false };
bool isClosedByPeer{ false }; bool isClosedByPeer{ false };
bool hasError{ false }; bool hasError{ false };
...@@ -105,9 +101,9 @@ protected: ...@@ -105,9 +101,9 @@ protected:
/* Inline methods. */ /* Inline methods. */
inline bool TcpConnection::IsClosing() const inline bool TcpConnection::IsClosed() const
{ {
return this->isClosing; return this->closed;
} }
inline uv_tcp_t* TcpConnection::GetUvHandle() const inline uv_tcp_t* TcpConnection::GetUvHandle() const
......
...@@ -15,14 +15,11 @@ public: ...@@ -15,14 +15,11 @@ public:
* uvHandle must be an already initialized and binded uv_tcp_t pointer. * uvHandle must be an already initialized and binded uv_tcp_t pointer.
*/ */
TcpServer(uv_tcp_t* uvHandle, int backlog); TcpServer(uv_tcp_t* uvHandle, int backlog);
virtual ~TcpServer() override;
protected:
~TcpServer() override;
public: public:
void Destroy(); void Close();
virtual void Dump() const; virtual void Dump() const;
bool IsClosing() const;
const struct sockaddr* GetLocalAddress() const; const struct sockaddr* GetLocalAddress() const;
int GetLocalFamily() const; int GetLocalFamily() const;
const std::string& GetLocalIP() const; const std::string& GetLocalIP() const;
...@@ -37,12 +34,10 @@ protected: ...@@ -37,12 +34,10 @@ protected:
virtual void UserOnTcpConnectionAlloc(TcpConnection** connection) = 0; virtual void UserOnTcpConnectionAlloc(TcpConnection** connection) = 0;
virtual void UserOnNewTcpConnection(TcpConnection* connection) = 0; virtual void UserOnNewTcpConnection(TcpConnection* connection) = 0;
virtual void UserOnTcpConnectionClosed(TcpConnection* connection, bool isClosedByPeer) = 0; virtual void UserOnTcpConnectionClosed(TcpConnection* connection, bool isClosedByPeer) = 0;
virtual void UserOnTcpServerClosed() = 0;
/* Callbacks fired by UV events. */ /* Callbacks fired by UV events. */
public: public:
void OnUvConnection(int status); void OnUvConnection(int status);
void OnUvClosed();
/* Methods inherited from TcpConnection::Listener. */ /* Methods inherited from TcpConnection::Listener. */
public: public:
...@@ -53,7 +48,7 @@ private: ...@@ -53,7 +48,7 @@ private:
uv_tcp_t* uvHandle{ nullptr }; uv_tcp_t* uvHandle{ nullptr };
// Others. // Others.
std::unordered_set<TcpConnection*> connections; std::unordered_set<TcpConnection*> connections;
bool isClosing{ false }; bool closed{ false };
protected: protected:
struct sockaddr_storage localAddr; struct sockaddr_storage localAddr;
...@@ -63,11 +58,6 @@ protected: ...@@ -63,11 +58,6 @@ protected:
/* Inline methods. */ /* Inline methods. */
inline bool TcpServer::IsClosing() const
{
return this->isClosing;
}
inline size_t TcpServer::GetNumConnections() const inline size_t TcpServer::GetNumConnections() const
{ {
return this->connections.size(); return this->connections.size();
......
...@@ -20,12 +20,10 @@ public: ...@@ -20,12 +20,10 @@ public:
explicit Timer(Listener* listener); explicit Timer(Listener* listener);
Timer& operator=(const Timer&) = delete; Timer& operator=(const Timer&) = delete;
Timer(const Timer&) = delete; Timer(const Timer&) = delete;
~Timer();
private:
~Timer() = default;
public: public:
void Destroy(); void Close();
void Start(uint64_t timeout, uint64_t repeat = 0); void Start(uint64_t timeout, uint64_t repeat = 0);
void Stop(); void Stop();
void Reset(); void Reset();
...@@ -42,6 +40,7 @@ private: ...@@ -42,6 +40,7 @@ private:
// Allocated by this. // Allocated by this.
uv_timer_t* uvHandle{ nullptr }; uv_timer_t* uvHandle{ nullptr };
// Others. // Others.
bool closed{ false };
uint64_t timeout{ 0 }; uint64_t timeout{ 0 };
uint64_t repeat{ 0 }; uint64_t repeat{ 0 };
}; };
......
...@@ -24,12 +24,10 @@ public: ...@@ -24,12 +24,10 @@ public:
explicit UdpSocket(uv_udp_t* uvHandle); explicit UdpSocket(uv_udp_t* uvHandle);
UdpSocket& operator=(const UdpSocket&) = delete; UdpSocket& operator=(const UdpSocket&) = delete;
UdpSocket(const UdpSocket&) = delete; UdpSocket(const UdpSocket&) = delete;
protected:
virtual ~UdpSocket(); virtual ~UdpSocket();
public: public:
void Destroy(); void Close();
virtual void Dump() const; virtual void Dump() const;
void Send(const uint8_t* data, size_t len, const struct sockaddr* addr); void Send(const uint8_t* 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);
...@@ -50,18 +48,16 @@ public: ...@@ -50,18 +48,16 @@ public:
void OnUvRecvAlloc(size_t suggestedSize, uv_buf_t* buf); void OnUvRecvAlloc(size_t suggestedSize, uv_buf_t* buf);
void OnUvRecv(ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned int flags); void OnUvRecv(ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned int flags);
void OnUvSendError(int error); void OnUvSendError(int error);
void OnUvClosed();
/* Pure virtual methods that must be implemented by the subclass. */ /* Pure virtual methods that must be implemented by the subclass. */
protected: protected:
virtual void UserOnUdpDatagramRecv(const uint8_t* data, size_t len, const struct sockaddr* addr) = 0; virtual void UserOnUdpDatagramRecv(const uint8_t* data, size_t len, const struct sockaddr* addr) = 0;
virtual void UserOnUdpSocketClosed() = 0;
private: private:
// Allocated by this (may be passed by argument). // Allocated by this (may be passed by argument).
uv_udp_t* uvHandle{ nullptr }; uv_udp_t* uvHandle{ nullptr };
// Others. // Others.
bool isClosing{ false }; bool closed{ false };
size_t recvBytes{ 0 }; size_t recvBytes{ 0 };
size_t sentBytes{ 0 }; size_t sentBytes{ 0 };
......
...@@ -20,13 +20,11 @@ public: ...@@ -20,13 +20,11 @@ public:
UnixStreamSocket(int fd, size_t bufferSize); UnixStreamSocket(int fd, size_t bufferSize);
UnixStreamSocket& operator=(const UnixStreamSocket&) = delete; UnixStreamSocket& operator=(const UnixStreamSocket&) = delete;
UnixStreamSocket(const UnixStreamSocket&) = delete; UnixStreamSocket(const UnixStreamSocket&) = delete;
protected:
virtual ~UnixStreamSocket(); virtual ~UnixStreamSocket();
public: public:
void Destroy(); void Close();
bool IsClosing() const; bool IsClosed() const;
void Write(const uint8_t* data, size_t len); void Write(const uint8_t* data, size_t len);
void Write(const std::string& data); void Write(const std::string& data);
...@@ -35,8 +33,6 @@ public: ...@@ -35,8 +33,6 @@ public:
void OnUvReadAlloc(size_t suggestedSize, uv_buf_t* buf); void OnUvReadAlloc(size_t suggestedSize, uv_buf_t* buf);
void OnUvRead(ssize_t nread, const uv_buf_t* buf); void OnUvRead(ssize_t nread, const uv_buf_t* buf);
void OnUvWriteError(int error); void OnUvWriteError(int error);
void OnUvShutdown(uv_shutdown_t* req, int status);
void OnUvClosed();
/* Pure virtual methods that must be implemented by the subclass. */ /* Pure virtual methods that must be implemented by the subclass. */
protected: protected:
...@@ -47,7 +43,7 @@ private: ...@@ -47,7 +43,7 @@ private:
// Allocated by this. // Allocated by this.
uv_pipe_t* uvHandle{ nullptr }; uv_pipe_t* uvHandle{ nullptr };
// Others. // Others.
bool isClosing{ false }; bool closed{ false };
bool isClosedByPeer{ false }; bool isClosedByPeer{ false };
bool hasError{ false }; bool hasError{ false };
...@@ -62,9 +58,9 @@ protected: ...@@ -62,9 +58,9 @@ protected:
/* Inline methods. */ /* Inline methods. */
inline bool UnixStreamSocket::IsClosing() const inline bool UnixStreamSocket::IsClosed() const
{ {
return this->isClosing; return this->closed;
} }
inline void UnixStreamSocket::Write(const std::string& data) inline void UnixStreamSocket::Write(const std::string& data)
......
...@@ -73,7 +73,7 @@ namespace Channel ...@@ -73,7 +73,7 @@ namespace Channel
void UnixStreamSocket::Send(Json::Value& msg) void UnixStreamSocket::Send(Json::Value& msg)
{ {
if (this->closed) if (IsClosed())
return; return;
// MS_TRACE_STD(); // MS_TRACE_STD();
...@@ -117,7 +117,7 @@ namespace Channel ...@@ -117,7 +117,7 @@ namespace Channel
void UnixStreamSocket::SendLog(char* nsPayload, size_t nsPayloadLen) void UnixStreamSocket::SendLog(char* nsPayload, size_t nsPayloadLen)
{ {
if (this->closed) if (IsClosed())
return; return;
// MS_TRACE_STD(); // MS_TRACE_STD();
...@@ -154,7 +154,7 @@ namespace Channel ...@@ -154,7 +154,7 @@ namespace Channel
void UnixStreamSocket::SendBinary(const uint8_t* nsPayload, size_t nsPayloadLen) void UnixStreamSocket::SendBinary(const uint8_t* nsPayload, size_t nsPayloadLen)
{ {
if (this->closed) if (IsClosed())
return; return;
size_t nsNumLen; size_t nsNumLen;
...@@ -194,7 +194,7 @@ namespace Channel ...@@ -194,7 +194,7 @@ namespace Channel
// Be ready to parse more than a single message in a single TCP chunk. // Be ready to parse more than a single message in a single TCP chunk.
while (true) while (true)
{ {
if (IsClosing()) if (IsClosed())
return; return;
size_t readLen = this->bufferDataLen - this->msgStart; size_t readLen = this->bufferDataLen - this->msgStart;
...@@ -329,12 +329,8 @@ namespace Channel ...@@ -329,12 +329,8 @@ namespace Channel
{ {
MS_TRACE_STD(); MS_TRACE_STD();
this->closed = true; // Notify the listener.
if (isClosedByPeer) if (isClosedByPeer)
{
// Notify the listener.
this->listener->OnChannelUnixStreamSocketRemotelyClosed(this); this->listener->OnChannelUnixStreamSocketRemotelyClosed(this);
}
} }
} // namespace Channel } // namespace Channel
...@@ -39,11 +39,6 @@ namespace RTC ...@@ -39,11 +39,6 @@ namespace RTC
delete this->rtpStream; delete this->rtpStream;
delete this->rtpMonitor; delete this->rtpMonitor;
}
void Consumer::Destroy()
{
MS_TRACE();
for (auto& listener : this->listeners) for (auto& listener : this->listeners)
{ {
...@@ -51,8 +46,6 @@ namespace RTC ...@@ -51,8 +46,6 @@ namespace RTC
} }
this->notifier->Emit(this->consumerId, "close"); this->notifier->Emit(this->consumerId, "close");
delete this;
} }
Json::Value Consumer::ToJson() const Json::Value Consumer::ToJson() const
......
...@@ -579,19 +579,6 @@ namespace RTC ...@@ -579,19 +579,6 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (this->ssl != nullptr)
{
SSL_free(this->ssl);
this->ssl = nullptr;
this->sslBioFromNetwork = nullptr;
this->sslBioToNetwork = nullptr;
}
}
void DtlsTransport::Destroy()
{
MS_TRACE();
if (IsRunning()) if (IsRunning())
{ {
// Send close alert to the peer. // Send close alert to the peer.
...@@ -599,10 +586,16 @@ namespace RTC ...@@ -599,10 +586,16 @@ namespace RTC
SendPendingOutgoingDtlsData(); SendPendingOutgoingDtlsData();
} }
// Destroy the DTLS timer. if (this->ssl != nullptr)
this->timer->Destroy(); {
SSL_free(this->ssl);
this->ssl = nullptr;
this->sslBioFromNetwork = nullptr;
this->sslBioToNetwork = nullptr;
}
delete this; // Close the DTLS timer.
delete this->timer;
} }
void DtlsTransport::Dump() const void DtlsTransport::Dump() const
......
...@@ -27,13 +27,6 @@ namespace RTC ...@@ -27,13 +27,6 @@ namespace RTC
this->password.c_str()); this->password.c_str());
} }
void IceServer::Destroy()
{
MS_TRACE();
delete this;
}
void IceServer::ProcessStunMessage(RTC::StunMessage* msg, RTC::TransportTuple* tuple) void IceServer::ProcessStunMessage(RTC::StunMessage* msg, RTC::TransportTuple* tuple)
{ {
MS_TRACE(); MS_TRACE();
......
...@@ -31,7 +31,7 @@ namespace RTC ...@@ -31,7 +31,7 @@ namespace RTC
MS_TRACE(); MS_TRACE();
// Close the timer. // Close the timer.
this->timer->Destroy(); delete this->timer;
} }
// Returns true if this is a found nacked packet. False otherwise. // Returns true if this is a found nacked packet. False otherwise.
......
...@@ -42,8 +42,8 @@ namespace RTC ...@@ -42,8 +42,8 @@ namespace RTC
} }
catch (const MediaSoupError& error) catch (const MediaSoupError& error)
{ {
// Destroy UdpSocket since ~PlainRtpTransport() will not be called. // Close UdpSocket since ~PlainRtpTransport() will not be called.
this->udpSocket->Destroy(); delete this->udpSocket;
throw; throw;
} }
...@@ -84,9 +84,7 @@ namespace RTC ...@@ -84,9 +84,7 @@ namespace RTC
MS_TRACE(); MS_TRACE();
delete this->tuple; delete this->tuple;
delete this->udpSocket;
if (this->udpSocket != nullptr)
this->udpSocket->Destroy();
} }
Json::Value PlainRtpTransport::ToJson() const Json::Value PlainRtpTransport::ToJson() const
......
...@@ -57,21 +57,14 @@ namespace RTC ...@@ -57,21 +57,14 @@ namespace RTC
delete rtpStream; delete rtpStream;
} }
}
void Producer::Destroy() // Close the RTP key frame request block timer.
{ delete this->keyFrameRequestBlockTimer;
MS_TRACE();
for (auto& listener : this->listeners) for (auto& listener : this->listeners)
{ {
listener->OnProducerClosed(this); listener->OnProducerClosed(this);
} }
// Close the RTP key frame request block timer.
this->keyFrameRequestBlockTimer->Destroy();
delete this;
} }
Json::Value Producer::ToJson() const Json::Value Producer::ToJson() const
......
...@@ -31,11 +31,6 @@ namespace RTC ...@@ -31,11 +31,6 @@ namespace RTC
} }
Router::~Router() Router::~Router()
{
MS_TRACE();
}
void Router::Destroy()
{ {
MS_TRACE(); MS_TRACE();
...@@ -45,7 +40,7 @@ namespace RTC ...@@ -45,7 +40,7 @@ namespace RTC
auto* producer = it->second; auto* producer = it->second;
it = this->producers.erase(it); it = this->producers.erase(it);
producer->Destroy(); delete producer;
} }
// Close all the Consumers. // Close all the Consumers.
...@@ -54,27 +49,25 @@ namespace RTC ...@@ -54,27 +49,25 @@ namespace RTC
auto* consumer = it->second; auto* consumer = it->second;
it = this->consumers.erase(it); it = this->consumers.erase(it);
consumer->Destroy(); delete consumer;
} }
// Close all the Transports. // Close all the Transports.
// NOTE: It is critical to close Transports after Producers/Consumers // NOTE: It is critical to close Transports after Producers/Consumers
// because their Destroy() method fires an event in the Transport. // because their destructor fires an event in the Transport.
for (auto it = this->transports.begin(); it != this->transports.end();) for (auto it = this->transports.begin(); it != this->transports.end();)
{ {
auto* transport = it->second; auto* transport = it->second;
it = this->transports.erase(it); it = this->transports.erase(it);
transport->Destroy(); delete transport;
} }
// Close the audio level timer. // Close the audio level timer.
this->audioLevelsTimer->Destroy(); delete this->audioLevelsTimer;
// Notify the listener. // Notify the listener.
this->listener->OnRouterClosed(this); this->listener->OnRouterClosed(this);
delete this;
} }
Json::Value Router::ToJson() const Json::Value Router::ToJson() const
...@@ -601,7 +594,7 @@ namespace RTC ...@@ -601,7 +594,7 @@ namespace RTC
return; return;
} }
transport->Destroy(); delete transport;
MS_DEBUG_DEV("Transport closed [transportId:%" PRIu32 "]", transport->transportId); MS_DEBUG_DEV("Transport closed [transportId:%" PRIu32 "]", transport->transportId);
...@@ -999,7 +992,7 @@ namespace RTC ...@@ -999,7 +992,7 @@ namespace RTC
return; return;
} }
producer->Destroy(); delete producer;
MS_DEBUG_DEV("Producer closed [producerId:%" PRIu32 "]", producer->producerId); MS_DEBUG_DEV("Producer closed [producerId:%" PRIu32 "]", producer->producerId);
...@@ -1171,7 +1164,7 @@ namespace RTC ...@@ -1171,7 +1164,7 @@ namespace RTC
return; return;
} }
consumer->Destroy(); delete consumer;
request->Accept(); request->Accept();
...@@ -1611,6 +1604,7 @@ namespace RTC ...@@ -1611,6 +1604,7 @@ namespace RTC
this->producers.erase(producer->producerId); this->producers.erase(producer->producerId);
// Remove the Producer from the map. // Remove the Producer from the map.
// NOTE: It may not exist if it failed before being inserted into the maps.
if (this->mapProducerConsumers.find(producer) != this->mapProducerConsumers.end()) if (this->mapProducerConsumers.find(producer) != this->mapProducerConsumers.end())
{ {
// Iterate the map and close all the Consumers associated to it. // Iterate the map and close all the Consumers associated to it.
...@@ -1621,7 +1615,7 @@ namespace RTC ...@@ -1621,7 +1615,7 @@ namespace RTC
auto* consumer = *it; auto* consumer = *it;
it = consumers.erase(it); it = consumers.erase(it);
consumer->Destroy(); delete consumer;
} }
// Finally delete the Producer entry in the map. // Finally delete the Producer entry in the map.
......
...@@ -32,7 +32,7 @@ namespace RTC ...@@ -32,7 +32,7 @@ namespace RTC
MS_TRACE(); MS_TRACE();
// Close the status check timer. // Close the status check timer.
this->statusCheckTimer->Destroy(); delete this->statusCheckTimer;
} }
Json::Value RtpStream::ToJson() Json::Value RtpStream::ToJson()
...@@ -260,8 +260,6 @@ namespace RTC ...@@ -260,8 +260,6 @@ namespace RTC
MS_TRACE(); MS_TRACE();
if (timer == this->statusCheckTimer) if (timer == this->statusCheckTimer)
{
CheckStatus(); CheckStatus();
}
} }
} // namespace RTC } // namespace RTC
...@@ -115,13 +115,6 @@ namespace RTC ...@@ -115,13 +115,6 @@ namespace RTC
} }
} }
void SrtpSession::Destroy()
{
MS_TRACE();
delete this;
}
bool SrtpSession::EncryptRtp(const uint8_t** data, size_t* len) bool SrtpSession::EncryptRtp(const uint8_t** data, size_t* len)
{ {
MS_TRACE(); MS_TRACE();
......
...@@ -47,9 +47,9 @@ namespace RTC ...@@ -47,9 +47,9 @@ namespace RTC
while (true) while (true)
{ {
// We may receive multiple packets in the same TCP chunk. If one of them is // We may receive multiple packets in the same TCP chunk. If one of them is
// a DTLS Close Alert this would be closed (Destroy() called) so we cannot call // a DTLS Close Alert this would be closed (Close() called) so we cannot call
// our listeners anymore. // our listeners anymore.
if (IsClosing()) if (IsClosed())
return; return;
size_t dataLen = this->bufferDataLen - this->frameStart; size_t dataLen = this->bufferDataLen - this->frameStart;
...@@ -125,7 +125,7 @@ namespace RTC ...@@ -125,7 +125,7 @@ namespace RTC
"connection"); "connection");
// Close the socket. // Close the socket.
Destroy(); Close();
} }
} }
// The buffer is not full. // The buffer is not full.
...@@ -151,7 +151,6 @@ namespace RTC ...@@ -151,7 +151,6 @@ namespace RTC
uint8_t frameLen[2]; uint8_t frameLen[2];
Utils::Byte::Set2Bytes(frameLen, 0, len); Utils::Byte::Set2Bytes(frameLen, 0, len);
Write(frameLen, 2, data, len); Write(frameLen, 2, data, len);
} }
} // namespace RTC } // namespace RTC
...@@ -229,6 +229,17 @@ namespace RTC ...@@ -229,6 +229,17 @@ namespace RTC
MS_TRACE(); MS_TRACE();
} }
TcpServer::~TcpServer()
{
MS_TRACE();
// Mark the port as available again.
if (this->localAddr.ss_family == AF_INET)
RTC::TcpServer::availableIPv4Ports[this->localPort] = true;
else if (this->localAddr.ss_family == AF_INET6)
RTC::TcpServer::availableIPv6Ports[this->localPort] = true;
}
void TcpServer::UserOnTcpConnectionAlloc(::TcpConnection** connection) void TcpServer::UserOnTcpConnectionAlloc(::TcpConnection** connection)
{ {
MS_TRACE(); MS_TRACE();
...@@ -243,31 +254,14 @@ namespace RTC ...@@ -243,31 +254,14 @@ namespace RTC
// Allow just MaxTcpConnectionsPerServer. // Allow just MaxTcpConnectionsPerServer.
if (GetNumConnections() > MaxTcpConnectionsPerServer) if (GetNumConnections() > MaxTcpConnectionsPerServer)
connection->Destroy(); connection->Close();
} }
void TcpServer::UserOnTcpConnectionClosed(::TcpConnection* connection, bool isClosedByPeer) void TcpServer::UserOnTcpConnectionClosed(::TcpConnection* connection, bool isClosedByPeer)
{ {
MS_TRACE(); MS_TRACE();
// Notify the listener. this->listener->OnRtcTcpConnectionClosed(
// NOTE: Don't do it if closing (since at this point the listener is already freed). this, dynamic_cast<RTC::TcpConnection*>(connection), isClosedByPeer);
// At the end, this is just called if the connection was remotely closed.
if (!IsClosing())
{
this->listener->OnRtcTcpConnectionClosed(
this, dynamic_cast<RTC::TcpConnection*>(connection), isClosedByPeer);
}
}
void TcpServer::UserOnTcpServerClosed()
{
MS_TRACE();
// Mark the port as available again.
if (this->localAddr.ss_family == AF_INET)
RTC::TcpServer::availableIPv4Ports[this->localPort] = true;
else if (this->localAddr.ss_family == AF_INET6)
RTC::TcpServer::availableIPv6Ports[this->localPort] = true;
} }
} // namespace RTC } // namespace RTC
...@@ -30,13 +30,26 @@ namespace RTC ...@@ -30,13 +30,26 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (!this->closed)
Close();
}
void Transport::Close()
{
MS_TRACE();
if (this->closed)
return;
this->closed = true;
// Close all the handled Producers. // Close all the handled Producers.
for (auto it = this->producers.begin(); it != this->producers.end();) for (auto it = this->producers.begin(); it != this->producers.end();)
{ {
auto* producer = *it; auto* producer = *it;
it = this->producers.erase(it); it = this->producers.erase(it);
producer->Destroy(); delete producer;
} }
// Disable all the handled Consumers. // Disable all the handled Consumers.
...@@ -48,22 +61,22 @@ namespace RTC ...@@ -48,22 +61,22 @@ namespace RTC
consumer->RemoveListener(this); consumer->RemoveListener(this);
} }
// Destroy the RTCP timer. // Close the RTCP timer.
if (this->rtcpTimer != nullptr) delete this->rtcpTimer;
this->rtcpTimer->Destroy();
}
void Transport::Destroy() // Delete mirror tuple.
{ if (this->mirrorTuple != nullptr)
MS_TRACE(); delete this->mirrorTuple;
// Notify. // Delete mirror socket.
this->notifier->Emit(this->transportId, "close"); if (this->mirrorSocket != nullptr)
delete this->mirrorSocket;
// Notify the listener. // Notify the listener.
this->listener->OnTransportClosed(this); this->listener->OnTransportClosed(this);
delete this; // Notify.
this->notifier->Emit(this->transportId, "close");
} }
void Transport::StartMirroring(MirroringOptions& options) void Transport::StartMirroring(MirroringOptions& options)
...@@ -132,9 +145,7 @@ namespace RTC ...@@ -132,9 +145,7 @@ namespace RTC
void Transport::StopMirroring() void Transport::StopMirroring()
{ {
delete this->mirrorTuple; delete this->mirrorTuple;
delete this->mirrorSocket;
if (this->mirrorSocket != nullptr)
this->mirrorSocket->Destroy();
this->mirrorTuple = nullptr; this->mirrorTuple = nullptr;
this->mirrorSocket = nullptr; this->mirrorSocket = nullptr;
......
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
/* Static methods for UV callbacks. */ /* Static methods for UV callbacks. */
static inline void onErrorClose(uv_handle_t* handle) static inline void onClose(uv_handle_t* handle)
{ {
delete handle; delete handle;
} }
...@@ -188,7 +188,7 @@ namespace RTC ...@@ -188,7 +188,7 @@ namespace RTC
iteratingPort, iteratingPort,
uv_strerror(err)); uv_strerror(err));
uv_close(reinterpret_cast<uv_handle_t*>(uvHandle), static_cast<uv_close_cb>(onErrorClose)); uv_close(reinterpret_cast<uv_handle_t*>(uvHandle), static_cast<uv_close_cb>(onClose));
// 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)
...@@ -235,6 +235,17 @@ namespace RTC ...@@ -235,6 +235,17 @@ namespace RTC
MS_TRACE(); MS_TRACE();
} }
UdpSocket::~UdpSocket()
{
MS_TRACE();
// Mark the port as available again.
if (this->localAddr.ss_family == AF_INET)
RTC::UdpSocket::availableIPv4Ports[this->localPort] = true;
else if (this->localAddr.ss_family == AF_INET6)
RTC::UdpSocket::availableIPv6Ports[this->localPort] = true;
}
void UdpSocket::UserOnUdpDatagramRecv(const uint8_t* data, size_t len, const struct sockaddr* addr) void UdpSocket::UserOnUdpDatagramRecv(const uint8_t* data, size_t len, const struct sockaddr* addr)
{ {
MS_TRACE(); MS_TRACE();
...@@ -249,15 +260,4 @@ namespace RTC ...@@ -249,15 +260,4 @@ namespace RTC
// Notify the reader. // Notify the reader.
this->listener->OnPacketRecv(this, data, len, addr); this->listener->OnPacketRecv(this, data, len, addr);
} }
void UdpSocket::UserOnUdpSocketClosed()
{
MS_TRACE();
// Mark the port as available again.
if (this->localAddr.ss_family == AF_INET)
RTC::UdpSocket::availableIPv4Ports[this->localPort] = true;
else if (this->localAddr.ss_family == AF_INET6)
RTC::UdpSocket::availableIPv6Ports[this->localPort] = true;
}
} // namespace RTC } // namespace RTC
...@@ -163,22 +163,16 @@ namespace RTC ...@@ -163,22 +163,16 @@ namespace RTC
// Ensure there is at least one IP:port binding. // Ensure there is at least one IP:port binding.
if (this->udpSockets.empty() && this->tcpServers.empty()) if (this->udpSockets.empty() && this->tcpServers.empty())
{ {
// NOTE: We must manually delete above allocated objects. We cannot call `delete this` delete this->iceServer;
// here since it would call the parent ~Transport destructor, and it would be called
// again after throwing the exception here.
//
// See: https://github.com/versatica/mediasoup/issues/222
this->iceServer->Destroy();
for (auto* socket : this->udpSockets) for (auto* socket : this->udpSockets)
{ {
socket->Destroy(); delete socket;
} }
for (auto* server : this->tcpServers) for (auto* server : this->tcpServers)
{ {
server->Destroy(); delete server;
} }
MS_THROW_ERROR("could not open any IP:port"); MS_THROW_ERROR("could not open any IP:port");
...@@ -198,31 +192,29 @@ namespace RTC ...@@ -198,31 +192,29 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (this->srtpRecvSession != nullptr) // It's important deleting DTLS transport first since it will generate a
this->srtpRecvSession->Destroy(); // DTLS alert to be sent.
delete this->dtlsTransport;
if (this->srtpSendSession != nullptr)
this->srtpSendSession->Destroy();
if (this->dtlsTransport != nullptr)
this->dtlsTransport->Destroy();
if (this->iceServer != nullptr) delete this->iceServer;
this->iceServer->Destroy();
for (auto* socket : this->udpSockets) for (auto* socket : this->udpSockets)
{ {
socket->Destroy(); delete socket;
} }
this->udpSockets.clear(); this->udpSockets.clear();
for (auto* server : this->tcpServers) for (auto* server : this->tcpServers)
{ {
server->Destroy(); delete server;
} }
this->tcpServers.clear(); this->tcpServers.clear();
this->selectedTuple = nullptr; if (this->srtpRecvSession != nullptr)
delete this->srtpRecvSession;
if (this->srtpSendSession != nullptr)
delete this->srtpSendSession;
} }
Json::Value WebRtcTransport::ToJson() const Json::Value WebRtcTransport::ToJson() const
...@@ -1128,12 +1120,12 @@ namespace RTC ...@@ -1128,12 +1120,12 @@ namespace RTC
// Close it if it was already set and update it. // Close it if it was already set and update it.
if (this->srtpSendSession != nullptr) if (this->srtpSendSession != nullptr)
{ {
this->srtpSendSession->Destroy(); delete this->srtpSendSession;
this->srtpSendSession = nullptr; this->srtpSendSession = nullptr;
} }
if (this->srtpRecvSession != nullptr) if (this->srtpRecvSession != nullptr)
{ {
this->srtpRecvSession->Destroy(); delete this->srtpRecvSession;
this->srtpRecvSession = nullptr; this->srtpRecvSession = nullptr;
} }
...@@ -1156,7 +1148,7 @@ namespace RTC ...@@ -1156,7 +1148,7 @@ namespace RTC
{ {
MS_ERROR("error creating SRTP receiving session: %s", error.what()); MS_ERROR("error creating SRTP receiving session: %s", error.what());
this->srtpSendSession->Destroy(); delete this->srtpSendSession;
this->srtpSendSession = nullptr; this->srtpSendSession = nullptr;
} }
...@@ -1191,7 +1183,7 @@ namespace RTC ...@@ -1191,7 +1183,7 @@ namespace RTC
this->notifier->Emit(this->transportId, "dtlsstatechange", eventData); this->notifier->Emit(this->transportId, "dtlsstatechange", eventData);
// This is a fatal error so close the transport. // This is a fatal error so close the transport.
Destroy(); Close();
} }
void WebRtcTransport::OnDtlsClosed(const RTC::DtlsTransport* /*dtlsTransport*/) void WebRtcTransport::OnDtlsClosed(const RTC::DtlsTransport* /*dtlsTransport*/)
...@@ -1210,7 +1202,7 @@ namespace RTC ...@@ -1210,7 +1202,7 @@ namespace RTC
this->notifier->Emit(this->transportId, "dtlsstatechange", eventData); this->notifier->Emit(this->transportId, "dtlsstatechange", eventData);
// This is a fatal error so close the transport. // This is a fatal error so close the transport.
Destroy(); Close();
} }
void WebRtcTransport::OnOutgoingDtlsData( void WebRtcTransport::OnOutgoingDtlsData(
......
...@@ -39,6 +39,9 @@ Worker::Worker(Channel::UnixStreamSocket* channel) : channel(channel) ...@@ -39,6 +39,9 @@ Worker::Worker(Channel::UnixStreamSocket* channel) : channel(channel)
Worker::~Worker() Worker::~Worker()
{ {
MS_TRACE(); MS_TRACE();
if (!this->closed)
Close();
} }
void Worker::Close() void Worker::Close()
...@@ -46,17 +49,12 @@ void Worker::Close() ...@@ -46,17 +49,12 @@ void Worker::Close()
MS_TRACE(); MS_TRACE();
if (this->closed) if (this->closed)
{
MS_ERROR("already closed");
return; return;
}
this->closed = true; this->closed = true;
// Close the SignalsHandler. // Close the SignalsHandler.
if (this->signalsHandler != nullptr) delete this->signalsHandler;
this->signalsHandler->Destroy();
// Close all the Routers. // Close all the Routers.
// NOTE: Upon Router closure the onRouterClosed() method is called, which // NOTE: Upon Router closure the onRouterClosed() method is called, which
...@@ -67,15 +65,14 @@ void Worker::Close() ...@@ -67,15 +65,14 @@ void Worker::Close()
RTC::Router* router = it->second; RTC::Router* router = it->second;
it = this->routers.erase(it); it = this->routers.erase(it);
router->Destroy(); delete router;
} }
// Delete the Notifier. // Delete the Notifier.
delete this->notifier; delete this->notifier;
// Close the Channel socket. // Close the Channel socket.
if (this->channel != nullptr) delete this->channel;
this->channel->Destroy();
} }
RTC::Router* Worker::GetRouterFromRequest(Channel::Request* request, uint32_t* routerId) RTC::Router* Worker::GetRouterFromRequest(Channel::Request* request, uint32_t* routerId)
...@@ -241,7 +238,8 @@ void Worker::OnChannelRequest(Channel::UnixStreamSocket* /*channel*/, Channel::R ...@@ -241,7 +238,8 @@ void Worker::OnChannelRequest(Channel::UnixStreamSocket* /*channel*/, Channel::R
return; return;
} }
router->Destroy(); delete router;
request->Accept(); request->Accept();
break; break;
...@@ -322,8 +320,6 @@ void Worker::OnChannelUnixStreamSocketRemotelyClosed(Channel::UnixStreamSocket* ...@@ -322,8 +320,6 @@ void Worker::OnChannelUnixStreamSocketRemotelyClosed(Channel::UnixStreamSocket*
// abruptly died (SIGKILL?) so we must die. // abruptly died (SIGKILL?) so we must die.
MS_ERROR_STD("Channel remotely closed, killing myself"); MS_ERROR_STD("Channel remotely closed, killing myself");
this->channel = nullptr;
Close(); Close();
} }
......
...@@ -25,10 +25,36 @@ SignalsHandler::SignalsHandler(Listener* listener) : listener(listener) ...@@ -25,10 +25,36 @@ SignalsHandler::SignalsHandler(Listener* listener) : listener(listener)
MS_TRACE(); MS_TRACE();
} }
SignalsHandler::~SignalsHandler()
{
MS_TRACE();
if (!this->closed)
Close();
}
void SignalsHandler::Close()
{
MS_TRACE();
if (this->closed)
return;
this->closed = true;
for (auto uvHandle : uvHandles)
{
uv_close(reinterpret_cast<uv_handle_t*>(uvHandle), static_cast<uv_close_cb>(onClose));
}
}
void SignalsHandler::AddSignal(int signum, const std::string& name) void SignalsHandler::AddSignal(int signum, const std::string& name)
{ {
MS_TRACE(); MS_TRACE();
if (this->closed)
MS_THROW_ERROR("closed");
int err; int err;
auto uvHandle = new uv_signal_t; auto uvHandle = new uv_signal_t;
...@@ -50,19 +76,6 @@ void SignalsHandler::AddSignal(int signum, const std::string& name) ...@@ -50,19 +76,6 @@ void SignalsHandler::AddSignal(int signum, const std::string& name)
this->uvHandles.push_back(uvHandle); this->uvHandles.push_back(uvHandle);
} }
void SignalsHandler::Destroy()
{
MS_TRACE();
for (auto uvHandle : uvHandles)
{
uv_close(reinterpret_cast<uv_handle_t*>(uvHandle), static_cast<uv_close_cb>(onClose));
}
// And delete this.
delete this;
}
inline void SignalsHandler::OnUvSignal(int signum) inline void SignalsHandler::OnUvSignal(int signum)
{ {
MS_TRACE(); MS_TRACE();
......
...@@ -34,14 +34,19 @@ inline static void onWrite(uv_write_t* req, int status) ...@@ -34,14 +34,19 @@ inline static void onWrite(uv_write_t* req, int status)
connection->OnUvWriteError(status); connection->OnUvWriteError(status);
} }
inline static void onShutdown(uv_shutdown_t* req, int status) inline static void onClose(uv_handle_t* handle)
{ {
static_cast<TcpConnection*>(req->data)->OnUvShutdown(req, status); delete handle;
} }
inline static void onClose(uv_handle_t* handle) inline static void onShutdown(uv_shutdown_t* req, int status)
{ {
static_cast<TcpConnection*>(handle->data)->OnUvClosed(); auto* handle = req->handle;
delete req;
// Now do close the handle.
uv_close(reinterpret_cast<uv_handle_t*>(handle), static_cast<uv_close_cb>(onClose));
} }
/* Instance methods. */ /* Instance methods. */
...@@ -60,46 +65,22 @@ TcpConnection::~TcpConnection() ...@@ -60,46 +65,22 @@ TcpConnection::~TcpConnection()
{ {
MS_TRACE(); MS_TRACE();
delete this->uvHandle; if (!this->closed)
delete[] this->buffer; Close();
}
void TcpConnection::Setup(
Listener* listener, struct sockaddr_storage* localAddr, const std::string& localIP, uint16_t localPort)
{
MS_TRACE();
int err;
// Set the UV handle.
err = uv_tcp_init(DepLibUV::GetLoop(), this->uvHandle);
if (err != 0)
{
delete this->uvHandle;
this->uvHandle = nullptr;
MS_THROW_ERROR("uv_tcp_init() failed: %s", uv_strerror(err));
}
// Set the listener. delete[] this->buffer;
this->listener = listener;
// Set the local address.
this->localAddr = localAddr;
this->localIP = localIP;
this->localPort = localPort;
} }
void TcpConnection::Destroy() void TcpConnection::Close()
{ {
MS_TRACE(); MS_TRACE();
if (this->isClosing) if (this->closed)
return; return;
int err; int err;
this->isClosing = true; this->closed = true;
// Don't read more. // Don't read more.
err = uv_read_stop(reinterpret_cast<uv_stream_t*>(this->uvHandle)); err = uv_read_stop(reinterpret_cast<uv_stream_t*>(this->uvHandle));
...@@ -123,6 +104,9 @@ void TcpConnection::Destroy() ...@@ -123,6 +104,9 @@ void TcpConnection::Destroy()
{ {
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose)); uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
} }
// Notify the listener.
this->listener->OnTcpConnectionClosed(this, this->isClosedByPeer);
} }
void TcpConnection::Dump() const void TcpConnection::Dump() const
...@@ -134,15 +118,41 @@ void TcpConnection::Dump() const ...@@ -134,15 +118,41 @@ void TcpConnection::Dump() const
static_cast<uint16_t>(this->localPort), static_cast<uint16_t>(this->localPort),
this->peerIP.c_str(), this->peerIP.c_str(),
static_cast<uint16_t>(this->peerPort), static_cast<uint16_t>(this->peerPort),
(!this->isClosing) ? "open" : "closed"); (!this->closed) ? "open" : "closed");
MS_DEBUG_DEV("</TcpConnection>"); MS_DEBUG_DEV("</TcpConnection>");
} }
void TcpConnection::Setup(
Listener* listener, struct sockaddr_storage* localAddr, const std::string& localIP, uint16_t localPort)
{
MS_TRACE();
// Set the listener.
this->listener = listener;
// Set the local address.
this->localAddr = localAddr;
this->localIP = localIP;
this->localPort = localPort;
int err;
// Set the UV handle.
err = uv_tcp_init(DepLibUV::GetLoop(), this->uvHandle);
if (err != 0)
{
delete this->uvHandle;
this->uvHandle = nullptr;
MS_THROW_ERROR("uv_tcp_init() failed: %s", uv_strerror(err));
}
}
void TcpConnection::Start() void TcpConnection::Start()
{ {
MS_TRACE(); MS_TRACE();
if (this->isClosing) if (this->closed)
return; return;
int err; int err;
...@@ -163,7 +173,7 @@ void TcpConnection::Write(const uint8_t* data, size_t len) ...@@ -163,7 +173,7 @@ void TcpConnection::Write(const uint8_t* data, size_t len)
{ {
MS_TRACE(); MS_TRACE();
if (this->isClosing) if (this->closed)
return; return;
if (len == 0) if (len == 0)
...@@ -195,7 +205,7 @@ void TcpConnection::Write(const uint8_t* data, size_t len) ...@@ -195,7 +205,7 @@ void TcpConnection::Write(const uint8_t* data, size_t len)
{ {
MS_WARN_DEV("uv_try_write() failed, closing the connection: %s", uv_strerror(written)); MS_WARN_DEV("uv_try_write() failed, closing the connection: %s", uv_strerror(written));
Destroy(); Close();
return; return;
} }
...@@ -228,7 +238,7 @@ void TcpConnection::Write(const uint8_t* data1, size_t len1, const uint8_t* data ...@@ -228,7 +238,7 @@ void TcpConnection::Write(const uint8_t* data1, size_t len1, const uint8_t* data
{ {
MS_TRACE(); MS_TRACE();
if (this->isClosing) if (this->closed)
return; return;
if (len1 == 0 && len2 == 0) if (len1 == 0 && len2 == 0)
...@@ -262,7 +272,8 @@ void TcpConnection::Write(const uint8_t* data1, size_t len1, const uint8_t* data ...@@ -262,7 +272,8 @@ void TcpConnection::Write(const uint8_t* data1, size_t len1, const uint8_t* data
{ {
MS_WARN_DEV("uv_try_write() failed, closing the connection: %s", uv_strerror(written)); MS_WARN_DEV("uv_try_write() failed, closing the connection: %s", uv_strerror(written));
Destroy(); Close();
return; return;
} }
...@@ -331,6 +342,9 @@ inline void TcpConnection::OnUvReadAlloc(size_t /*suggestedSize*/, uv_buf_t* buf ...@@ -331,6 +342,9 @@ inline void TcpConnection::OnUvReadAlloc(size_t /*suggestedSize*/, uv_buf_t* buf
{ {
MS_TRACE(); MS_TRACE();
if (this->closed)
return;
// If this is the first call to onUvReadAlloc() then allocate the receiving buffer now. // If this is the first call to onUvReadAlloc() then allocate the receiving buffer now.
if (this->buffer == nullptr) if (this->buffer == nullptr)
this->buffer = new uint8_t[this->bufferSize]; this->buffer = new uint8_t[this->bufferSize];
...@@ -354,7 +368,7 @@ inline void TcpConnection::OnUvRead(ssize_t nread, const uv_buf_t* /*buf*/) ...@@ -354,7 +368,7 @@ inline void TcpConnection::OnUvRead(ssize_t nread, const uv_buf_t* /*buf*/)
{ {
MS_TRACE(); MS_TRACE();
if (this->isClosing) if (this->closed)
return; return;
if (nread == 0) if (nread == 0)
...@@ -377,7 +391,7 @@ inline void TcpConnection::OnUvRead(ssize_t nread, const uv_buf_t* /*buf*/) ...@@ -377,7 +391,7 @@ inline void TcpConnection::OnUvRead(ssize_t nread, const uv_buf_t* /*buf*/)
this->isClosedByPeer = true; this->isClosedByPeer = true;
// Close server side of the connection. // Close server side of the connection.
Destroy(); Close();
} }
// Some error. // Some error.
else else
...@@ -387,7 +401,7 @@ inline void TcpConnection::OnUvRead(ssize_t nread, const uv_buf_t* /*buf*/) ...@@ -387,7 +401,7 @@ inline void TcpConnection::OnUvRead(ssize_t nread, const uv_buf_t* /*buf*/)
this->hasError = true; this->hasError = true;
// Close server side of the connection. // Close server side of the connection.
Destroy(); Close();
} }
} }
...@@ -395,7 +409,7 @@ inline void TcpConnection::OnUvWriteError(int error) ...@@ -395,7 +409,7 @@ inline void TcpConnection::OnUvWriteError(int error)
{ {
MS_TRACE(); MS_TRACE();
if (this->isClosing) if (this->closed)
return; return;
if (error != UV_EPIPE && error != UV_ENOTCONN) if (error != UV_EPIPE && error != UV_ENOTCONN)
...@@ -403,31 +417,5 @@ inline void TcpConnection::OnUvWriteError(int error) ...@@ -403,31 +417,5 @@ inline void TcpConnection::OnUvWriteError(int error)
MS_WARN_DEV("write error, closing the connection: %s", uv_strerror(error)); MS_WARN_DEV("write error, closing the connection: %s", uv_strerror(error));
Destroy(); Close();
}
inline void TcpConnection::OnUvShutdown(uv_shutdown_t* req, int status)
{
MS_TRACE();
delete req;
if (status != 0)
{
MS_WARN_DEV("shutdown error: %s", uv_strerror(status));
}
// Now do close the handle.
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
}
inline void TcpConnection::OnUvClosed()
{
MS_TRACE();
// Notify the listener.
this->listener->OnTcpConnectionClosed(this, this->isClosedByPeer);
// And delete this.
delete this;
} }
...@@ -15,11 +15,6 @@ inline static void onConnection(uv_stream_t* handle, int status) ...@@ -15,11 +15,6 @@ inline static void onConnection(uv_stream_t* handle, int status)
} }
inline static void onClose(uv_handle_t* handle) inline static void onClose(uv_handle_t* handle)
{
static_cast<TcpServer*>(handle->data)->OnUvClosed();
}
inline static void onErrorClose(uv_handle_t* handle)
{ {
delete handle; delete handle;
} }
...@@ -76,7 +71,7 @@ TcpServer::TcpServer(const std::string& ip, uint16_t port, int backlog) ...@@ -76,7 +71,7 @@ TcpServer::TcpServer(const std::string& ip, uint16_t port, int backlog)
default: default:
{ {
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onErrorClose)); uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR("invalid binding IP '%s'", ip.c_str()); MS_THROW_ERROR("invalid binding IP '%s'", ip.c_str());
...@@ -87,7 +82,7 @@ TcpServer::TcpServer(const std::string& ip, uint16_t port, int backlog) ...@@ -87,7 +82,7 @@ TcpServer::TcpServer(const std::string& ip, uint16_t port, int backlog)
err = uv_tcp_bind(this->uvHandle, reinterpret_cast<const struct sockaddr*>(&bindAddr), flags); err = uv_tcp_bind(this->uvHandle, reinterpret_cast<const struct sockaddr*>(&bindAddr), flags);
if (err != 0) if (err != 0)
{ {
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onErrorClose)); uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR("uv_tcp_bind() failed: %s", uv_strerror(err)); MS_THROW_ERROR("uv_tcp_bind() failed: %s", uv_strerror(err));
} }
...@@ -97,14 +92,14 @@ TcpServer::TcpServer(const std::string& ip, uint16_t port, int backlog) ...@@ -97,14 +92,14 @@ TcpServer::TcpServer(const std::string& ip, uint16_t port, int backlog)
static_cast<uv_connection_cb>(onConnection)); static_cast<uv_connection_cb>(onConnection));
if (err != 0) if (err != 0)
{ {
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onErrorClose)); uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR("uv_listen() failed: %s", uv_strerror(err)); MS_THROW_ERROR("uv_listen() failed: %s", uv_strerror(err));
} }
// Set local address. // Set local address.
if (!SetLocalAddress()) if (!SetLocalAddress())
{ {
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onErrorClose)); uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR("error setting local IP and port"); MS_THROW_ERROR("error setting local IP and port");
} }
} }
...@@ -123,14 +118,14 @@ TcpServer::TcpServer(uv_tcp_t* uvHandle, int backlog) : uvHandle(uvHandle) ...@@ -123,14 +118,14 @@ TcpServer::TcpServer(uv_tcp_t* uvHandle, int backlog) : uvHandle(uvHandle)
static_cast<uv_connection_cb>(onConnection)); static_cast<uv_connection_cb>(onConnection));
if (err != 0) if (err != 0)
{ {
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onErrorClose)); uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR("uv_listen() failed: %s", uv_strerror(err)); MS_THROW_ERROR("uv_listen() failed: %s", uv_strerror(err));
} }
// Set local address. // Set local address.
if (!SetLocalAddress()) if (!SetLocalAddress())
{ {
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onErrorClose)); uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR("error setting local IP and port"); MS_THROW_ERROR("error setting local IP and port");
} }
} }
...@@ -139,33 +134,30 @@ TcpServer::~TcpServer() ...@@ -139,33 +134,30 @@ TcpServer::~TcpServer()
{ {
MS_TRACE(); MS_TRACE();
delete this->uvHandle; if (!this->closed)
Close();
} }
void TcpServer::Destroy() void TcpServer::Close()
{ {
MS_TRACE(); MS_TRACE();
if (this->isClosing) if (this->closed)
return; return;
this->isClosing = true; this->closed = true;
// If there are no connections then close now. MS_DEBUG_DEV("closing %zu active connections", this->connections.size());
if (this->connections.empty())
{ for (auto it = this->connections.begin(); it != this->connections.end();)
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
}
// Otherwise close all the connections (but not the TCP server).
else
{ {
MS_DEBUG_DEV("closing %zu active connections", this->connections.size()); auto* connection = *it;
for (auto connection : this->connections) it = this->connections.erase(it);
{ delete connection;
connection->Destroy();
}
} }
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
} }
void TcpServer::Dump() const void TcpServer::Dump() const
...@@ -175,7 +167,7 @@ void TcpServer::Dump() const ...@@ -175,7 +167,7 @@ void TcpServer::Dump() const
" [TCP, local:%s :%" PRIu16 ", status:%s, connections:%zu]", " [TCP, local:%s :%" PRIu16 ", status:%s, connections:%zu]",
this->localIP.c_str(), this->localIP.c_str(),
static_cast<uint16_t>(this->localPort), static_cast<uint16_t>(this->localPort),
(!this->isClosing) ? "open" : "closed", (!this->closed) ? "open" : "closed",
this->connections.size()); this->connections.size());
MS_DEBUG_DEV("</TcpServer>"); MS_DEBUG_DEV("</TcpServer>");
} }
...@@ -210,7 +202,7 @@ inline void TcpServer::OnUvConnection(int status) ...@@ -210,7 +202,7 @@ inline void TcpServer::OnUvConnection(int status)
{ {
MS_TRACE(); MS_TRACE();
if (this->isClosing) if (this->closed)
return; return;
int err; int err;
...@@ -253,59 +245,31 @@ inline void TcpServer::OnUvConnection(int status) ...@@ -253,59 +245,31 @@ inline void TcpServer::OnUvConnection(int status)
try try
{ {
connection->Start(); connection->Start();
// Notify the subclass.
UserOnNewTcpConnection(connection);
} }
catch (const MediaSoupError& error) catch (const MediaSoupError& error)
{ {
MS_ERROR("cannot run the TCP connection, closing the connection: %s", error.what()); MS_ERROR("cannot run the TCP connection, closing the connection: %s", error.what());
connection->Destroy(); delete connection;
// NOTE: Don't return here so the user won't be notified about a TCP connection
// closure for which there was not a previous creation event.
} }
// Notify the subclass.
UserOnNewTcpConnection(connection);
} }
inline void TcpServer::OnUvClosed() void TcpServer::OnTcpConnectionClosed(TcpConnection* connection, bool isClosedByPeer)
{ {
MS_TRACE(); MS_TRACE();
// Notify the subclass.
UserOnTcpServerClosed();
// And delete this.
delete this;
}
inline void TcpServer::OnTcpConnectionClosed(TcpConnection* connection, bool isClosedByPeer)
{
MS_TRACE();
// NOTE:
// Worst scenario is that in which this is the latest connection,
// which is remotely closed (no TcpServer.Destroy() was called) and the user
// call TcpServer.Destroy() on UserOnTcpConnectionClosed() callback, so Destroy()
// is called with zero connections and calls uv_close(), but then
// onTcpConnectionClosed() continues and finds that isClosing is true and
// there are zero connections, so calls uv_close() again and get a crash.
//
// SOLUTION:
// Check isClosing value *before* onTcpConnectionClosed() callback.
bool wasClosing = this->isClosing;
MS_DEBUG_DEV("TCP connection closed"); MS_DEBUG_DEV("TCP connection closed");
// Remove the TcpConnection from the set. // Remove the TcpConnection from the set.
this->connections.erase(connection); size_t numErased = this->connections.erase(connection);
// If the closed connection was not present in the set, do nothing else.
if (numErased == 0)
return;
// Notify the subclass. // Notify the subclass.
UserOnTcpConnectionClosed(connection, isClosedByPeer); UserOnTcpConnectionClosed(connection, isClosedByPeer);
// Check if the server was closing connections, and if this is the last
// connection then close the server now.
if (wasClosing && this->connections.empty())
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
} }
...@@ -39,20 +39,33 @@ Timer::Timer(Listener* listener) : listener(listener) ...@@ -39,20 +39,33 @@ Timer::Timer(Listener* listener) : listener(listener)
} }
} }
void Timer::Destroy() Timer::~Timer()
{ {
MS_TRACE(); MS_TRACE();
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose)); if (!this->closed)
Close();
}
void Timer::Close()
{
MS_TRACE();
if (this->closed)
return;
// Delete this. this->closed = true;
delete this;
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
} }
void Timer::Start(uint64_t timeout, uint64_t repeat) void Timer::Start(uint64_t timeout, uint64_t repeat)
{ {
MS_TRACE(); MS_TRACE();
if (this->closed)
MS_THROW_ERROR("closed");
this->timeout = timeout; this->timeout = timeout;
this->repeat = repeat; this->repeat = repeat;
...@@ -70,6 +83,9 @@ void Timer::Stop() ...@@ -70,6 +83,9 @@ void Timer::Stop()
{ {
MS_TRACE(); MS_TRACE();
if (this->closed)
MS_THROW_ERROR("closed");
int err; int err;
err = uv_timer_stop(this->uvHandle); err = uv_timer_stop(this->uvHandle);
...@@ -81,6 +97,9 @@ void Timer::Reset() ...@@ -81,6 +97,9 @@ void Timer::Reset()
{ {
MS_TRACE(); MS_TRACE();
if (this->closed)
MS_THROW_ERROR("closed");
int err; int err;
if (uv_is_active(reinterpret_cast<uv_handle_t*>(this->uvHandle)) == 0) if (uv_is_active(reinterpret_cast<uv_handle_t*>(this->uvHandle)) == 0)
...@@ -98,6 +117,9 @@ void Timer::Restart() ...@@ -98,6 +117,9 @@ void Timer::Restart()
{ {
MS_TRACE(); MS_TRACE();
if (this->closed)
MS_THROW_ERROR("closed");
int err; int err;
if (uv_is_active(reinterpret_cast<uv_handle_t*>(this->uvHandle)) != 0) if (uv_is_active(reinterpret_cast<uv_handle_t*>(this->uvHandle)) != 0)
......
...@@ -39,11 +39,6 @@ inline static void onSend(uv_udp_send_t* req, int status) ...@@ -39,11 +39,6 @@ inline static void onSend(uv_udp_send_t* req, int status)
} }
inline static void onClose(uv_handle_t* handle) inline static void onClose(uv_handle_t* handle)
{
static_cast<UdpSocket*>(handle->data)->OnUvClosed();
}
inline static void onErrorClose(uv_handle_t* handle)
{ {
delete handle; delete handle;
} }
...@@ -100,7 +95,7 @@ UdpSocket::UdpSocket(const std::string& ip, uint16_t port) ...@@ -100,7 +95,7 @@ UdpSocket::UdpSocket(const std::string& ip, uint16_t port)
default: default:
{ {
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onErrorClose)); uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR("invalid binding IP '%s'", ip.c_str()); MS_THROW_ERROR("invalid binding IP '%s'", ip.c_str());
...@@ -111,7 +106,7 @@ UdpSocket::UdpSocket(const std::string& ip, uint16_t port) ...@@ -111,7 +106,7 @@ UdpSocket::UdpSocket(const std::string& ip, uint16_t port)
err = uv_udp_bind(this->uvHandle, reinterpret_cast<const struct sockaddr*>(&bindAddr), flags); err = uv_udp_bind(this->uvHandle, reinterpret_cast<const struct sockaddr*>(&bindAddr), flags);
if (err != 0) if (err != 0)
{ {
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onErrorClose)); uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR("uv_udp_bind() failed: %s", uv_strerror(err)); MS_THROW_ERROR("uv_udp_bind() failed: %s", uv_strerror(err));
} }
...@@ -119,14 +114,14 @@ UdpSocket::UdpSocket(const std::string& ip, uint16_t port) ...@@ -119,14 +114,14 @@ UdpSocket::UdpSocket(const std::string& ip, uint16_t port)
this->uvHandle, static_cast<uv_alloc_cb>(onAlloc), static_cast<uv_udp_recv_cb>(onRecv)); this->uvHandle, static_cast<uv_alloc_cb>(onAlloc), static_cast<uv_udp_recv_cb>(onRecv));
if (err != 0) if (err != 0)
{ {
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onErrorClose)); uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR("uv_udp_recv_start() failed: %s", uv_strerror(err)); MS_THROW_ERROR("uv_udp_recv_start() failed: %s", uv_strerror(err));
} }
// Set local address. // Set local address.
if (!SetLocalAddress()) if (!SetLocalAddress())
{ {
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onErrorClose)); uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR("error setting local IP and port"); MS_THROW_ERROR("error setting local IP and port");
} }
} }
...@@ -143,14 +138,14 @@ UdpSocket::UdpSocket(uv_udp_t* uvHandle) : uvHandle(uvHandle) ...@@ -143,14 +138,14 @@ UdpSocket::UdpSocket(uv_udp_t* uvHandle) : uvHandle(uvHandle)
this->uvHandle, static_cast<uv_alloc_cb>(onAlloc), static_cast<uv_udp_recv_cb>(onRecv)); this->uvHandle, static_cast<uv_alloc_cb>(onAlloc), static_cast<uv_udp_recv_cb>(onRecv));
if (err != 0) if (err != 0)
{ {
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onErrorClose)); uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR("uv_udp_recv_start() failed: %s", uv_strerror(err)); MS_THROW_ERROR("uv_udp_recv_start() failed: %s", uv_strerror(err));
} }
// Set local address. // Set local address.
if (!SetLocalAddress()) if (!SetLocalAddress())
{ {
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onErrorClose)); uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR("error setting local IP and port"); MS_THROW_ERROR("error setting local IP and port");
} }
} }
...@@ -159,19 +154,20 @@ UdpSocket::~UdpSocket() ...@@ -159,19 +154,20 @@ UdpSocket::~UdpSocket()
{ {
MS_TRACE(); MS_TRACE();
delete this->uvHandle; if (!this->closed)
Close();
} }
void UdpSocket::Destroy() void UdpSocket::Close()
{ {
MS_TRACE(); MS_TRACE();
if (this->isClosing) if (this->closed)
return; return;
int err; int err;
this->isClosing = true; this->closed = true;
// Don't read more. // Don't read more.
err = uv_udp_recv_stop(this->uvHandle); err = uv_udp_recv_stop(this->uvHandle);
...@@ -188,7 +184,7 @@ void UdpSocket::Dump() const ...@@ -188,7 +184,7 @@ void UdpSocket::Dump() const
" [UDP, local:%s :%" PRIu16 ", status:%s]", " [UDP, local:%s :%" PRIu16 ", status:%s]",
this->localIP.c_str(), this->localIP.c_str(),
static_cast<uint16_t>(this->localPort), static_cast<uint16_t>(this->localPort),
(!this->isClosing) ? "open" : "closed"); (!this->closed) ? "open" : "closed");
MS_DEBUG_DEV("</UdpSocket>"); MS_DEBUG_DEV("</UdpSocket>");
} }
...@@ -196,7 +192,7 @@ void UdpSocket::Send(const uint8_t* data, size_t len, const struct sockaddr* add ...@@ -196,7 +192,7 @@ void UdpSocket::Send(const uint8_t* data, size_t len, const struct sockaddr* add
{ {
MS_TRACE(); MS_TRACE();
if (this->isClosing) if (this->closed)
return; return;
if (len == 0) if (len == 0)
...@@ -271,7 +267,7 @@ void UdpSocket::Send(const uint8_t* data, size_t len, const std::string& ip, uin ...@@ -271,7 +267,7 @@ void UdpSocket::Send(const uint8_t* data, size_t len, const std::string& ip, uin
{ {
MS_TRACE(); MS_TRACE();
if (this->isClosing) if (this->closed)
return; return;
int err; int err;
...@@ -357,7 +353,7 @@ inline void UdpSocket::OnUvRecv( ...@@ -357,7 +353,7 @@ inline void UdpSocket::OnUvRecv(
{ {
MS_TRACE(); MS_TRACE();
if (this->isClosing) if (this->closed)
return; 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
...@@ -393,19 +389,8 @@ inline void UdpSocket::OnUvSendError(int /*error*/) ...@@ -393,19 +389,8 @@ inline void UdpSocket::OnUvSendError(int /*error*/)
{ {
MS_TRACE(); MS_TRACE();
if (this->isClosing) if (this->closed)
return; return;
MS_DEBUG_DEV("send error: %s", uv_strerror(error)); MS_DEBUG_DEV("send error: %s", uv_strerror(error));
} }
inline void UdpSocket::OnUvClosed()
{
MS_TRACE();
// Notify the subclass.
UserOnUdpSocketClosed();
// And delete this.
delete this;
}
...@@ -38,19 +38,19 @@ inline static void onWrite(uv_write_t* req, int status) ...@@ -38,19 +38,19 @@ inline static void onWrite(uv_write_t* req, int status)
socket->OnUvWriteError(status); socket->OnUvWriteError(status);
} }
inline static void onShutdown(uv_shutdown_t* req, int status)
{
static_cast<UnixStreamSocket*>(req->data)->OnUvShutdown(req, status);
}
inline static void onClose(uv_handle_t* handle) inline static void onClose(uv_handle_t* handle)
{ {
static_cast<UnixStreamSocket*>(handle->data)->OnUvClosed(); delete handle;
} }
inline static void onErrorClose(uv_handle_t* handle) inline static void onShutdown(uv_shutdown_t* req, int status)
{ {
delete handle; auto* handle = req->handle;
delete req;
// Now do close the handle.
uv_close(reinterpret_cast<uv_handle_t*>(handle), static_cast<uv_close_cb>(onClose));
} }
/* Instance methods. */ /* Instance methods. */
...@@ -76,7 +76,7 @@ UnixStreamSocket::UnixStreamSocket(int fd, size_t bufferSize) : bufferSize(buffe ...@@ -76,7 +76,7 @@ UnixStreamSocket::UnixStreamSocket(int fd, size_t bufferSize) : bufferSize(buffe
err = uv_pipe_open(this->uvHandle, fd); err = uv_pipe_open(this->uvHandle, fd);
if (err != 0) if (err != 0)
{ {
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onErrorClose)); uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR_STD("uv_pipe_open() failed: %s", uv_strerror(err)); MS_THROW_ERROR_STD("uv_pipe_open() failed: %s", uv_strerror(err));
} }
...@@ -88,7 +88,7 @@ UnixStreamSocket::UnixStreamSocket(int fd, size_t bufferSize) : bufferSize(buffe ...@@ -88,7 +88,7 @@ UnixStreamSocket::UnixStreamSocket(int fd, size_t bufferSize) : bufferSize(buffe
static_cast<uv_read_cb>(onRead)); static_cast<uv_read_cb>(onRead));
if (err != 0) if (err != 0)
{ {
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onErrorClose)); uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR_STD("uv_read_start() failed: %s", uv_strerror(err)); MS_THROW_ERROR_STD("uv_read_start() failed: %s", uv_strerror(err));
} }
...@@ -100,20 +100,22 @@ UnixStreamSocket::~UnixStreamSocket() ...@@ -100,20 +100,22 @@ UnixStreamSocket::~UnixStreamSocket()
{ {
MS_TRACE_STD(); MS_TRACE_STD();
delete this->uvHandle; if (!this->closed)
Close();
delete[] this->buffer; delete[] this->buffer;
} }
void UnixStreamSocket::Destroy() void UnixStreamSocket::Close()
{ {
MS_TRACE_STD(); MS_TRACE_STD();
if (this->isClosing) if (this->closed)
return; return;
int err; int err;
this->isClosing = true; this->closed = true;
// Don't read more. // Don't read more.
err = uv_read_stop(reinterpret_cast<uv_stream_t*>(this->uvHandle)); err = uv_read_stop(reinterpret_cast<uv_stream_t*>(this->uvHandle));
...@@ -140,7 +142,7 @@ void UnixStreamSocket::Destroy() ...@@ -140,7 +142,7 @@ void UnixStreamSocket::Destroy()
void UnixStreamSocket::Write(const uint8_t* data, size_t len) void UnixStreamSocket::Write(const uint8_t* data, size_t len)
{ {
if (this->isClosing) if (this->closed)
return; return;
if (len == 0) if (len == 0)
...@@ -172,7 +174,10 @@ void UnixStreamSocket::Write(const uint8_t* data, size_t len) ...@@ -172,7 +174,10 @@ void UnixStreamSocket::Write(const uint8_t* data, size_t len)
{ {
MS_ERROR_STD("uv_try_write() failed, closing the socket: %s", uv_strerror(written)); MS_ERROR_STD("uv_try_write() failed, closing the socket: %s", uv_strerror(written));
Destroy(); Close();
// Notify the subclass.
UserOnUnixStreamSocketClosed(this->isClosedByPeer);
return; return;
} }
...@@ -202,6 +207,9 @@ inline void UnixStreamSocket::OnUvReadAlloc(size_t /*suggestedSize*/, uv_buf_t* ...@@ -202,6 +207,9 @@ inline void UnixStreamSocket::OnUvReadAlloc(size_t /*suggestedSize*/, uv_buf_t*
{ {
MS_TRACE_STD(); MS_TRACE_STD();
if (this->closed)
return;
// If this is the first call to onUvReadAlloc() then allocate the receiving buffer now. // If this is the first call to onUvReadAlloc() then allocate the receiving buffer now.
if (this->buffer == nullptr) if (this->buffer == nullptr)
this->buffer = new uint8_t[this->bufferSize]; this->buffer = new uint8_t[this->bufferSize];
...@@ -225,6 +233,9 @@ inline void UnixStreamSocket::OnUvRead(ssize_t nread, const uv_buf_t* /*buf*/) ...@@ -225,6 +233,9 @@ inline void UnixStreamSocket::OnUvRead(ssize_t nread, const uv_buf_t* /*buf*/)
{ {
MS_TRACE_STD(); MS_TRACE_STD();
if (this->closed)
return;
if (nread == 0) if (nread == 0)
return; return;
...@@ -243,7 +254,10 @@ inline void UnixStreamSocket::OnUvRead(ssize_t nread, const uv_buf_t* /*buf*/) ...@@ -243,7 +254,10 @@ inline void UnixStreamSocket::OnUvRead(ssize_t nread, const uv_buf_t* /*buf*/)
this->isClosedByPeer = true; this->isClosedByPeer = true;
// Close local side of the pipe. // Close local side of the pipe.
Destroy(); Close();
// Notify the subclass.
UserOnUnixStreamSocketClosed(this->isClosedByPeer);
} }
// Some error. // Some error.
else else
...@@ -253,7 +267,10 @@ inline void UnixStreamSocket::OnUvRead(ssize_t nread, const uv_buf_t* /*buf*/) ...@@ -253,7 +267,10 @@ inline void UnixStreamSocket::OnUvRead(ssize_t nread, const uv_buf_t* /*buf*/)
this->hasError = true; this->hasError = true;
// Close the socket. // Close the socket.
Destroy(); Close();
// Notify the subclass.
UserOnUnixStreamSocketClosed(this->isClosedByPeer);
} }
} }
...@@ -261,7 +278,7 @@ inline void UnixStreamSocket::OnUvWriteError(int error) ...@@ -261,7 +278,7 @@ inline void UnixStreamSocket::OnUvWriteError(int error)
{ {
MS_TRACE_STD(); MS_TRACE_STD();
if (this->isClosing) if (this->closed)
return; return;
if (error != UV_EPIPE && error != UV_ENOTCONN) if (error != UV_EPIPE && error != UV_ENOTCONN)
...@@ -269,31 +286,8 @@ inline void UnixStreamSocket::OnUvWriteError(int error) ...@@ -269,31 +286,8 @@ inline void UnixStreamSocket::OnUvWriteError(int error)
MS_ERROR_STD("write error, closing the pipe: %s", uv_strerror(error)); MS_ERROR_STD("write error, closing the pipe: %s", uv_strerror(error));
Destroy(); Close();
}
inline void UnixStreamSocket::OnUvShutdown(uv_shutdown_t* req, int status)
{
MS_TRACE_STD();
delete req;
if (status != 0)
{
MS_ERROR_STD("shutdown error: %s", uv_strerror(status));
}
// Now do close the handle.
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
}
inline void UnixStreamSocket::OnUvClosed()
{
MS_TRACE_STD();
// Notify the subclass. // Notify the subclass.
UserOnUnixStreamSocketClosed(this->isClosedByPeer); UserOnUnixStreamSocketClosed(this->isClosedByPeer);
// And delete this.
delete this;
} }
...@@ -92,6 +92,7 @@ int main(int argc, char* argv[]) ...@@ -92,6 +92,7 @@ int main(int argc, char* argv[])
// Worker ended. // Worker ended.
destroy(); destroy();
exitSuccess(); exitSuccess();
} }
catch (const MediaSoupError& error) catch (const MediaSoupError& error)
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论