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

Work in DTLS stuff

上级 b13a9214
...@@ -128,6 +128,11 @@ class Transport extends EventEmitter ...@@ -128,6 +128,11 @@ class Transport extends EventEmitter
}); });
} }
/**
* Start the DTLS stack
* @param {Object} remoteDtlsParameters Remote DTLS parameters
* @return {Promise}
*/
start(remoteDtlsParameters) start(remoteDtlsParameters)
{ {
logger.debug('start() [remoteDtlsParameters:%o]', remoteDtlsParameters); logger.debug('start() [remoteDtlsParameters:%o]', remoteDtlsParameters);
...@@ -140,7 +145,8 @@ class Transport extends EventEmitter ...@@ -140,7 +145,8 @@ class Transport extends EventEmitter
roomId : this._roomId, roomId : this._roomId,
peerId : this._peerId, peerId : this._peerId,
transportId : this._transportId, transportId : this._transportId,
remoteDtlsParameters :remoteDtlsParameters role : remoteDtlsParameters.role,
fingerprint : remoteDtlsParameters.fingerprint
}; };
// Send Channel request // Send Channel request
...@@ -155,6 +161,10 @@ class Transport extends EventEmitter ...@@ -155,6 +161,10 @@ class Transport extends EventEmitter
}); });
} }
/**
* Create an asociated Transport for RTCP
* @return {Promise}
*/
createAssociatedTransport() createAssociatedTransport()
{ {
logger.debug('createAssociatedTransport()'); logger.debug('createAssociatedTransport()');
......
...@@ -177,7 +177,7 @@ app.put('/test-transport', function(req) ...@@ -177,7 +177,7 @@ app.put('/test-transport', function(req)
}); });
}); });
setInterval(() => setTimeout(() =>
{ {
room.dump() room.dump()
.then((data) => debug('ROOM DUMP:\n%s', JSON.stringify(data, null, '\t'))) .then((data) => debug('ROOM DUMP:\n%s', JSON.stringify(data, null, '\t')))
......
#ifndef MS_RTC_DTLS_AGENT_H #ifndef MS_RTC_DTLS_TRANSPORT_H
#define MS_RTC_DTLS_AGENT_H #define MS_RTC_DTLS_TRANSPORT_H
#include "common.h" #include "common.h"
#include "RTC/SRTPSession.h" #include "RTC/SRTPSession.h"
#include "handles/Timer.h" #include "handles/Timer.h"
#include <string> #include <string>
#include <map>
#include <vector> #include <vector>
#include <openssl/ssl.h> #include <openssl/ssl.h>
#include <openssl/bio.h> #include <openssl/bio.h>
...@@ -13,28 +14,36 @@ ...@@ -13,28 +14,36 @@
namespace RTC namespace RTC
{ {
class DTLSAgent : class DTLSTransport :
public Timer::Listener public Timer::Listener
{ {
public: public:
enum class DTLSRole enum class Role
{ {
NONE = 0, NONE = 0,
SERVER = 1, AUTO = 1,
CLIENT CLIENT,
SERVER
}; };
public: public:
enum class FingerprintHash enum class FingerprintAlgorithm
{ {
NONE = 0, NONE = 0,
SHA1 = 1, SHA1 = 1,
SHA224, SHA224,
SHA256, SHA256,
SHA384, SHA384,
SHA512 SHA512
}; };
public:
struct Fingerprint
{
FingerprintAlgorithm algorithm;
std::string value;
};
private: private:
struct SrtpProfileMapEntry struct SrtpProfileMapEntry
{ {
...@@ -48,20 +57,22 @@ namespace RTC ...@@ -48,20 +57,22 @@ namespace RTC
public: public:
// NOTE: The caller MUST NOT call Reset() or Close() during the // NOTE: The caller MUST NOT call Reset() or Close() during the
// onOutgoingDTLSData() callback. // onOutgoingDTLSData() callback.
virtual void onOutgoingDTLSData(DTLSAgent* dtlsAgent, const MS_BYTE* data, size_t len) = 0; virtual void onOutgoingDTLSData(DTLSTransport* dtlsTransport, const MS_BYTE* data, size_t len) = 0;
// NOTE: The caller MUST NOT call any method during the onDTLSConnected, // NOTE: The caller MUST NOT call any method during the onDTLSConnected,
// onDTLSDisconnected or onDTLSFailed callbacks. // onDTLSDisconnected or onDTLSFailed callbacks.
virtual void onDTLSConnected(DTLSAgent* dtlsAgent) = 0; virtual void onDTLSConnected(DTLSTransport* dtlsTransport) = 0;
virtual void onDTLSDisconnected(DTLSAgent* dtlsAgent) = 0; virtual void onDTLSDisconnected(DTLSTransport* dtlsTransport) = 0;
virtual void onDTLSFailed(DTLSAgent* dtlsAgent) = 0; virtual void onDTLSFailed(DTLSTransport* dtlsTransport) = 0;
virtual void onSRTPKeyMaterial(DTLSAgent* dtlsAgent, RTC::SRTPSession::SRTPProfile srtp_profile, MS_BYTE* srtp_local_key, size_t srtp_local_key_len, MS_BYTE* srtp_remote_key, size_t srtp_remote_key_len) = 0; virtual void onSRTPKeyMaterial(DTLSTransport* dtlsTransport, RTC::SRTPSession::SRTPProfile srtp_profile, MS_BYTE* srtp_local_key, size_t srtp_local_key_len, MS_BYTE* srtp_remote_key, size_t srtp_remote_key_len) = 0;
virtual void onDTLSApplicationData(DTLSAgent* dtlsAgent, const MS_BYTE* data, size_t len) = 0; virtual void onDTLSApplicationData(DTLSTransport* dtlsTransport, const MS_BYTE* data, size_t len) = 0;
}; };
public: public:
static void ClassInit(); static void ClassInit();
static void ClassDestroy(); static void ClassDestroy();
static Json::Value& GetLocalFingerprints(); static Json::Value& GetLocalFingerprints();
static Role GetRole(std::string role);
static FingerprintAlgorithm GetFingerprintAlgorithm(std::string fingerprint);
static bool IsDTLS(const MS_BYTE* data, size_t len); static bool IsDTLS(const MS_BYTE* data, size_t len);
private: private:
...@@ -74,21 +85,22 @@ namespace RTC ...@@ -74,21 +85,22 @@ namespace RTC
static X509* certificate; static X509* certificate;
static EVP_PKEY* privateKey; static EVP_PKEY* privateKey;
static SSL_CTX* sslCtx; static SSL_CTX* sslCtx;
static Json::Value localFingerprints;
typedef std::vector<SrtpProfileMapEntry> SRTPProfiles;
static SRTPProfiles srtpProfiles;
static MS_BYTE sslReadBuffer[]; static MS_BYTE sslReadBuffer[];
static std::map<std::string, Role> string2Role;
static std::map<std::string, FingerprintAlgorithm> string2FingerprintAlgorithm;
static Json::Value localFingerprints;
static std::vector<SrtpProfileMapEntry> srtpProfiles;
public: public:
DTLSAgent(Listener* listener); DTLSTransport(Listener* listener);
virtual ~DTLSAgent(); virtual ~DTLSTransport();
void Run(DTLSRole role); void Start(Role role);
void SetRemoteFingerprint(FingerprintHash hash, std::string& fingerprint); void SetRemoteFingerprint(Fingerprint fingerprint);
void Reset(); void Reset();
void Close(); void Close();
void ProcessDTLSData(const MS_BYTE* data, size_t len); void ProcessDTLSData(const MS_BYTE* data, size_t len);
bool IsRunning(); bool IsStarted();
bool IsConnected(); bool IsConnected();
void SendApplicationData(const MS_BYTE* data, size_t len); void SendApplicationData(const MS_BYTE* data, size_t len);
void Dump(); void Dump();
...@@ -119,15 +131,13 @@ namespace RTC ...@@ -119,15 +131,13 @@ namespace RTC
BIO* sslBioToNetwork = nullptr; // The BIO in which ssl writes. BIO* sslBioToNetwork = nullptr; // The BIO in which ssl writes.
Timer* timer = nullptr; Timer* timer = nullptr;
// Others. // Others.
// TODO: rename to localRole Role localRole = Role::NONE;
DTLSRole role = DTLSRole::NONE; Fingerprint remoteFingerprint = { FingerprintAlgorithm::NONE, "" };
FingerprintHash remoteFingerprintHash = FingerprintHash::NONE; bool started = false;
std::string remoteFingerprint; bool handshakeDone = false;
bool isRunning = false; bool handshakeDoneNow = false;
bool isHandshakeDone = false; bool connected = false;
bool isHandshakeDoneNow = false; bool checkingStatus = false;
bool isConnected = false;
bool isCheckingStatus = false;
bool doReset = false; bool doReset = false;
bool doClose = false; bool doClose = false;
}; };
...@@ -135,7 +145,35 @@ namespace RTC ...@@ -135,7 +145,35 @@ namespace RTC
/* Inline static methods. */ /* Inline static methods. */
inline inline
bool DTLSAgent::IsDTLS(const MS_BYTE* data, size_t len) Json::Value& DTLSTransport::GetLocalFingerprints()
{
return DTLSTransport::localFingerprints;
}
inline
DTLSTransport::Role DTLSTransport::GetRole(std::string role)
{
auto it = DTLSTransport::string2Role.find(role);
if (it != DTLSTransport::string2Role.end())
return it->second;
else
return DTLSTransport::Role::NONE;
}
inline
DTLSTransport::FingerprintAlgorithm DTLSTransport::GetFingerprintAlgorithm(std::string fingerprint)
{
auto it = DTLSTransport::string2FingerprintAlgorithm.find(fingerprint);
if (it != DTLSTransport::string2FingerprintAlgorithm.end())
return it->second;
else
return DTLSTransport::FingerprintAlgorithm::NONE;
}
inline
bool DTLSTransport::IsDTLS(const MS_BYTE* data, size_t len)
{ {
return ( return (
// Minimum DTLS record length is 13 bytes. // Minimum DTLS record length is 13 bytes.
...@@ -148,15 +186,15 @@ namespace RTC ...@@ -148,15 +186,15 @@ namespace RTC
/* Inline instance methods. */ /* Inline instance methods. */
inline inline
bool DTLSAgent::IsConnected() bool DTLSTransport::IsConnected()
{ {
return this->isConnected; return this->connected;
} }
inline inline
bool DTLSAgent::IsRunning() bool DTLSTransport::IsStarted()
{ {
return this->isRunning; return this->started;
} }
} }
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
#include "common.h" #include "common.h"
#include "RTC/IceCandidate.h" #include "RTC/IceCandidate.h"
#include "RTC/IceServer.h" #include "RTC/IceServer.h"
#include "RTC/DTLSAgent.h" #include "RTC/DTLSTransport.h"
#include "RTC/STUNMessage.h" #include "RTC/STUNMessage.h"
#include "RTC/TransportSource.h" #include "RTC/TransportSource.h"
#include "RTC/UDPSocket.h" #include "RTC/UDPSocket.h"
...@@ -18,10 +18,11 @@ ...@@ -18,10 +18,11 @@
namespace RTC namespace RTC
{ {
class Transport : class Transport :
public RTC::IceServer::Listener,
public RTC::UDPSocket::Listener, public RTC::UDPSocket::Listener,
public RTC::TCPServer::Listener, public RTC::TCPServer::Listener,
public RTC::TCPConnection::Reader public RTC::TCPConnection::Reader,
public RTC::IceServer::Listener,
public RTC::DTLSTransport::Listener
{ {
public: public:
class Listener class Listener
...@@ -52,14 +53,10 @@ namespace RTC ...@@ -52,14 +53,10 @@ namespace RTC
Transport* CreateAssociatedTransport(unsigned int transportId); Transport* CreateAssociatedTransport(unsigned int transportId);
private: private:
bool SetSendingSource(RTC::TransportSource* source); int SetSendingSource(RTC::TransportSource* source);
bool IsValidSource(RTC::TransportSource* source); int IsValidSource(RTC::TransportSource* source);
bool RemoveSource(RTC::TransportSource* source); bool RemoveSource(RTC::TransportSource* source);
void RunDTLSTransportIfReady();
/* Pure virtual methods inherited from RTC::IceServer::Listener. */
public:
virtual void onOutgoingSTUNMessage(RTC::IceServer* iceServer, RTC::STUNMessage* msg, RTC::TransportSource* source) override;
virtual void onICEValidPair(RTC::IceServer* iceServer, RTC::TransportSource* source, bool has_use_candidate) override;
/* Private methods to unify UDP and TCP behavior. */ /* Private methods to unify UDP and TCP behavior. */
private: private:
...@@ -86,6 +83,20 @@ namespace RTC ...@@ -86,6 +83,20 @@ namespace RTC
virtual void onRTPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) override; virtual void onRTPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) override;
virtual void onRTCPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) override; virtual void onRTCPDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) override;
/* Pure virtual methods inherited from RTC::IceServer::Listener. */
public:
virtual void onOutgoingSTUNMessage(RTC::IceServer* iceServer, RTC::STUNMessage* msg, RTC::TransportSource* source) override;
virtual void onICEValidPair(RTC::IceServer* iceServer, RTC::TransportSource* source, bool has_use_candidate) override;
/* Pure virtual methods inherited from RTC::DTLSTransport::Listener. */
public:
virtual void onOutgoingDTLSData(RTC::DTLSTransport* dtlsTransport, const MS_BYTE* data, size_t len) override;
virtual void onDTLSConnected(RTC::DTLSTransport* dtlsTransport) override;
virtual void onDTLSDisconnected(RTC::DTLSTransport* dtlsTransport) override;
virtual void onDTLSFailed(RTC::DTLSTransport* dtlsTransport) override;
virtual void onSRTPKeyMaterial(RTC::DTLSTransport* dtlsTransport, RTC::SRTPSession::SRTPProfile srtp_profile, MS_BYTE* srtp_local_key, size_t srtp_local_key_len, MS_BYTE* srtp_remote_key, size_t srtp_remote_key_len) override;
virtual void onDTLSApplicationData(RTC::DTLSTransport* dtlsTransport, const MS_BYTE* data, size_t len) override;
public: public:
// Passed by argument. // Passed by argument.
unsigned int transportId; unsigned int transportId;
...@@ -103,13 +114,18 @@ namespace RTC ...@@ -103,13 +114,18 @@ namespace RTC
RTC::IceServer* iceServer = nullptr; RTC::IceServer* iceServer = nullptr;
std::vector<RTC::UDPSocket*> udpSockets; std::vector<RTC::UDPSocket*> udpSockets;
std::vector<RTC::TCPServer*> tcpServers; std::vector<RTC::TCPServer*> tcpServers;
RTC::DTLSTransport* dtlsTransport = nullptr;
// Others. // Others.
bool allocated = false; bool allocated = false;
// Others (ICE).
std::vector<IceCandidate> iceLocalCandidates; std::vector<IceCandidate> iceLocalCandidates;
std::list<RTC::TransportSource> sources; std::list<RTC::TransportSource> sources;
RTC::TransportSource* sendingSource = nullptr; RTC::TransportSource* sendingSource = nullptr;
bool icePaired = false; bool icePaired = false;
bool icePairedWithUseCandidate = false; bool icePairedWithUseCandidate = false;
// Others (DTLS).
bool started = false;
RTC::DTLSTransport::Role dtlsLocalRole = RTC::DTLSTransport::Role::CLIENT;
}; };
/* Inline methods. */ /* Inline methods. */
...@@ -133,14 +149,23 @@ namespace RTC ...@@ -133,14 +149,23 @@ namespace RTC
* @param source: A RTC::TransportSource (which is a UDP tuple or TCP connection). * @param source: A RTC::TransportSource (which is a UDP tuple or TCP connection).
* @return: true if the given source was not an already valid source, * @return: true if the given source was not an already valid source,
* false otherwise. * false otherwise.
* @return: 1 if it's the current sending source, 2 if it's another
* valid source, 0 if it's not a valid source.
*/ */
inline inline
bool Transport::SetSendingSource(RTC::TransportSource* source) int Transport::SetSendingSource(RTC::TransportSource* source)
{ {
// If the give source is already a valid one return. // Check whether this is already a valid source.
// NOTE: The IsValidSource() method will also mark it as sending source. // NOTE: The IsValidSource() method will also mark it as sending source.
if (IsValidSource(source)) switch (IsValidSource(source))
return false; {
// This is already the sending source.
case 1:
return 1;
// This is another valid source.
case 2:
return 2;
}
// If there are Transport::maxSources sources then close and remove the last one. // If there are Transport::maxSources sources then close and remove the last one.
if (this->sources.size() == Transport::maxSources) if (this->sources.size() == Transport::maxSources)
...@@ -162,7 +187,7 @@ namespace RTC ...@@ -162,7 +187,7 @@ namespace RTC
if (this->sendingSource->IsUDP()) if (this->sendingSource->IsUDP())
this->sendingSource->StoreUdpRemoteAddress(); this->sendingSource->StoreUdpRemoteAddress();
return true; return 0;
} }
/** /**
...@@ -171,34 +196,36 @@ namespace RTC ...@@ -171,34 +196,36 @@ namespace RTC
* source for the outgoing data. * source for the outgoing data.
* *
* @param source: The RTC::TransportSource to check. * @param source: The RTC::TransportSource to check.
* @return: true if it is a valid source, false otherwise. * @return: 1 if it's the current sending source, 2 if it's another
* valid source, 0 if it's not a valid source.
*/ */
inline inline
bool Transport::IsValidSource(RTC::TransportSource* source) int Transport::IsValidSource(RTC::TransportSource* source)
{ {
// If there is no sending source yet then we know that the sources list // If there is no sending source yet then we know that the sources list
// is empty, so return false. // is empty, so return 0.
if (!this->sendingSource) if (!this->sendingSource)
return false; return 0;
// First check the current sending source. If it matches then return true. // First check the current sending source. If it matches then return 1.
if (this->sendingSource->Compare(source)) if (this->sendingSource->Compare(source))
return true; return 1;
// Otherwise check other valid source in the sources list. // Otherwise check other valid source in the sources list.
for (auto it = this->sources.begin(); it != this->sources.end(); ++it) for (auto it = this->sources.begin(); it != this->sources.end(); ++it)
{ {
RTC::TransportSource* valid_source = &(*it); RTC::TransportSource* valid_source = &(*it);
// If found set it as sending source. // If found set it as sending source and return 2.
if (valid_source->Compare(source)) if (valid_source->Compare(source))
{ {
this->sendingSource = valid_source; this->sendingSource = valid_source;
return true; return 2;
} }
} }
return false; // Otherwise it is not a valid source so return 0.
return 0;
} }
/** /**
...@@ -236,6 +263,8 @@ namespace RTC ...@@ -236,6 +263,8 @@ namespace RTC
// This is just useful is there are just TCP sources. // This is just useful is there are just TCP sources.
this->icePaired = false; this->icePaired = false;
this->icePairedWithUseCandidate = false; this->icePairedWithUseCandidate = false;
// TODO: This should fire a 'icefailed' event.
} }
} }
......
...@@ -16,12 +16,12 @@ public: ...@@ -16,12 +16,12 @@ public:
public: public:
/* Struct for the data field of uv_req_t when writing into the connection. */ /* Struct for the data field of uv_req_t when writing into the connection. */
typedef struct UvWriteData struct UvWriteData
{ {
TCPConnection* connection; TCPConnection* connection;
uv_write_t req; uv_write_t req;
MS_BYTE store[1]; MS_BYTE store[1];
} UvWriteData; };
public: public:
TCPConnection(size_t bufferSize); TCPConnection(size_t bufferSize);
......
...@@ -9,12 +9,12 @@ class UDPSocket ...@@ -9,12 +9,12 @@ class UDPSocket
{ {
public: public:
/* Struct for the data field of uv_req_t when sending a datagram. */ /* Struct for the data field of uv_req_t when sending a datagram. */
typedef struct UvSendData struct UvSendData
{ {
UDPSocket* socket; UDPSocket* socket;
uv_udp_send_t req; uv_udp_send_t req;
MS_BYTE store[1]; MS_BYTE store[1];
} UvSendData; };
private: private:
static MS_BYTE readBuffer[]; static MS_BYTE readBuffer[];
......
...@@ -9,12 +9,12 @@ class UnixStreamSocket ...@@ -9,12 +9,12 @@ class UnixStreamSocket
{ {
public: public:
/* Struct for the data field of uv_req_t when writing data. */ /* Struct for the data field of uv_req_t when writing data. */
typedef struct UvWriteData struct UvWriteData
{ {
UnixStreamSocket* socket; UnixStreamSocket* socket;
uv_write_t req; uv_write_t req;
MS_BYTE store[1]; MS_BYTE store[1];
} UvWriteData; };
public: public:
UnixStreamSocket(int fd, size_t bufferSize); UnixStreamSocket(int fd, size_t bufferSize);
......
#define MS_CLASS "RTC::DTLSAgent" #define MS_CLASS "RTC::DTLSTransport"
#include "RTC/DTLSAgent.h" #include "RTC/DTLSTransport.h"
#include "Settings.h" #include "Settings.h"
#include "Utils.h" #include "Utils.h"
#include "MediaSoupError.h" #include "MediaSoupError.h"
...@@ -9,7 +9,6 @@ ...@@ -9,7 +9,6 @@
#include <cstdio> // std::sprintf(), std::fopen() #include <cstdio> // std::sprintf(), std::fopen()
#include <cstring> // std::memcpy(), std::strcmp() #include <cstring> // std::memcpy(), std::strcmp()
#include <ctime> // struct timeval #include <ctime> // struct timeval
#include <algorithm> // std::transform()
#include <openssl/err.h> #include <openssl/err.h>
#include <openssl/bn.h> #include <openssl/bn.h>
#include <openssl/evp.h> #include <openssl/evp.h>
...@@ -53,27 +52,41 @@ int on_ssl_certificate_verify(int preverify_ok, X509_STORE_CTX* ctx) ...@@ -53,27 +52,41 @@ int on_ssl_certificate_verify(int preverify_ok, X509_STORE_CTX* ctx)
static inline static inline
void on_ssl_info(const SSL* ssl, int where, int ret) void on_ssl_info(const SSL* ssl, int where, int ret)
{ {
static_cast<RTC::DTLSAgent*>(SSL_get_ex_data(ssl, 0))->onSSLInfo(where, ret); static_cast<RTC::DTLSTransport*>(SSL_get_ex_data(ssl, 0))->onSSLInfo(where, ret);
} }
namespace RTC namespace RTC
{ {
/* Class variables. */ /* Class variables. */
X509* DTLSAgent::certificate = nullptr; X509* DTLSTransport::certificate = nullptr;
EVP_PKEY* DTLSAgent::privateKey = nullptr; EVP_PKEY* DTLSTransport::privateKey = nullptr;
SSL_CTX* DTLSAgent::sslCtx = nullptr; SSL_CTX* DTLSTransport::sslCtx = nullptr;
Json::Value DTLSAgent::localFingerprints = Json::Value(Json::objectValue); MS_BYTE DTLSTransport::sslReadBuffer[MS_SSL_READ_BUFFER_SIZE];
DTLSAgent::SRTPProfiles DTLSAgent::srtpProfiles = std::map<std::string, DTLSTransport::FingerprintAlgorithm> DTLSTransport::string2FingerprintAlgorithm =
{
{ "sha-1", DTLSTransport::FingerprintAlgorithm::SHA1 },
{ "sha-224", DTLSTransport::FingerprintAlgorithm::SHA224 },
{ "sha-256", DTLSTransport::FingerprintAlgorithm::SHA256 },
{ "sha-384", DTLSTransport::FingerprintAlgorithm::SHA384 },
{ "sha-512", DTLSTransport::FingerprintAlgorithm::SHA512 }
};
std::map<std::string, DTLSTransport::Role> DTLSTransport::string2Role =
{
{ "auto", DTLSTransport::Role::AUTO },
{ "client", DTLSTransport::Role::CLIENT },
{ "server", DTLSTransport::Role::SERVER }
};
Json::Value DTLSTransport::localFingerprints = Json::Value(Json::objectValue);
std::vector<DTLSTransport::SrtpProfileMapEntry> DTLSTransport::srtpProfiles =
{ {
{ RTC::SRTPSession::SRTPProfile::AES_CM_128_HMAC_SHA1_80, "SRTP_AES128_CM_SHA1_80" }, { RTC::SRTPSession::SRTPProfile::AES_CM_128_HMAC_SHA1_80, "SRTP_AES128_CM_SHA1_80" },
{ RTC::SRTPSession::SRTPProfile::AES_CM_128_HMAC_SHA1_32, "SRTP_AES128_CM_SHA1_32" } { RTC::SRTPSession::SRTPProfile::AES_CM_128_HMAC_SHA1_32, "SRTP_AES128_CM_SHA1_32" }
}; };
MS_BYTE DTLSAgent::sslReadBuffer[MS_SSL_READ_BUFFER_SIZE];
/* Class methods. */ /* Class methods. */
void DTLSAgent::ClassInit() void DTLSTransport::ClassInit()
{ {
MS_TRACE(); MS_TRACE();
...@@ -90,26 +103,19 @@ namespace RTC ...@@ -90,26 +103,19 @@ namespace RTC
GenerateFingerprints(); GenerateFingerprints();
} }
void DTLSAgent::ClassDestroy() void DTLSTransport::ClassDestroy()
{
MS_TRACE();
if (DTLSAgent::privateKey)
EVP_PKEY_free(DTLSAgent::privateKey);
if (DTLSAgent::certificate)
X509_free(DTLSAgent::certificate);
if (DTLSAgent::sslCtx)
SSL_CTX_free(DTLSAgent::sslCtx);
}
Json::Value& DTLSAgent::GetLocalFingerprints()
{ {
MS_TRACE(); MS_TRACE();
return DTLSAgent::localFingerprints; if (DTLSTransport::privateKey)
EVP_PKEY_free(DTLSTransport::privateKey);
if (DTLSTransport::certificate)
X509_free(DTLSTransport::certificate);
if (DTLSTransport::sslCtx)
SSL_CTX_free(DTLSTransport::sslCtx);
} }
void DTLSAgent::GenerateCertificateAndPrivateKey() void DTLSTransport::GenerateCertificateAndPrivateKey()
{ {
MS_TRACE(); MS_TRACE();
...@@ -151,14 +157,14 @@ namespace RTC ...@@ -151,14 +157,14 @@ namespace RTC
} }
// Create a private key object (needed to hold the RSA key). // Create a private key object (needed to hold the RSA key).
DTLSAgent::privateKey = EVP_PKEY_new(); DTLSTransport::privateKey = EVP_PKEY_new();
if (!DTLSAgent::privateKey) if (!DTLSTransport::privateKey)
{ {
LOG_OPENSSL_ERROR("EVP_PKEY_new() failed"); LOG_OPENSSL_ERROR("EVP_PKEY_new() failed");
goto error; goto error;
} }
ret = EVP_PKEY_assign_RSA(DTLSAgent::privateKey, rsa_key); ret = EVP_PKEY_assign_RSA(DTLSTransport::privateKey, rsa_key);
if (ret == 0) if (ret == 0)
{ {
LOG_OPENSSL_ERROR("EVP_PKEY_assign_RSA() failed"); LOG_OPENSSL_ERROR("EVP_PKEY_assign_RSA() failed");
...@@ -168,25 +174,25 @@ namespace RTC ...@@ -168,25 +174,25 @@ namespace RTC
rsa_key = nullptr; rsa_key = nullptr;
// Create the X509 certificate. // Create the X509 certificate.
DTLSAgent::certificate = X509_new(); DTLSTransport::certificate = X509_new();
if (!DTLSAgent::certificate) if (!DTLSTransport::certificate)
{ {
LOG_OPENSSL_ERROR("X509_new() failed"); LOG_OPENSSL_ERROR("X509_new() failed");
goto error; goto error;
} }
// Set version 3 (note that 0 means version 1). // Set version 3 (note that 0 means version 1).
X509_set_version(DTLSAgent::certificate, 2); X509_set_version(DTLSTransport::certificate, 2);
// Set serial number (avoid default 0). // Set serial number (avoid default 0).
ASN1_INTEGER_set(X509_get_serialNumber(DTLSAgent::certificate), (long)Utils::Crypto::GetRandomUInt(1000000, 9999999)); ASN1_INTEGER_set(X509_get_serialNumber(DTLSTransport::certificate), (long)Utils::Crypto::GetRandomUInt(1000000, 9999999));
// Set valid period. // Set valid period.
X509_gmtime_adj(X509_get_notBefore(DTLSAgent::certificate), -1*60*60*24*365*10); // - 10 years. X509_gmtime_adj(X509_get_notBefore(DTLSTransport::certificate), -1*60*60*24*365*10); // - 10 years.
X509_gmtime_adj(X509_get_notAfter(DTLSAgent::certificate), 60*60*24*365*10); // 10 years. X509_gmtime_adj(X509_get_notAfter(DTLSTransport::certificate), 60*60*24*365*10); // 10 years.
// Set the public key for the certificate using the key. // Set the public key for the certificate using the key.
ret = X509_set_pubkey(DTLSAgent::certificate, DTLSAgent::privateKey); ret = X509_set_pubkey(DTLSTransport::certificate, DTLSTransport::privateKey);
if (ret == 0) if (ret == 0)
{ {
LOG_OPENSSL_ERROR("X509_set_pubkey() failed"); LOG_OPENSSL_ERROR("X509_set_pubkey() failed");
...@@ -194,7 +200,7 @@ namespace RTC ...@@ -194,7 +200,7 @@ namespace RTC
} }
// Set certificate fields. // Set certificate fields.
cert_name = X509_get_subject_name(DTLSAgent::certificate); cert_name = X509_get_subject_name(DTLSTransport::certificate);
if (!cert_name) if (!cert_name)
{ {
LOG_OPENSSL_ERROR("X509_get_subject_name() failed"); LOG_OPENSSL_ERROR("X509_get_subject_name() failed");
...@@ -204,7 +210,7 @@ namespace RTC ...@@ -204,7 +210,7 @@ namespace RTC
X509_NAME_add_entry_by_txt(cert_name, "CN", MBSTRING_ASC, (unsigned char *)MS_APP_NAME, -1, -1, 0); X509_NAME_add_entry_by_txt(cert_name, "CN", MBSTRING_ASC, (unsigned char *)MS_APP_NAME, -1, -1, 0);
// It is self signed so set the issuer name to be the same as the subject. // It is self signed so set the issuer name to be the same as the subject.
ret = X509_set_issuer_name(DTLSAgent::certificate, cert_name); ret = X509_set_issuer_name(DTLSTransport::certificate, cert_name);
if (ret == 0) if (ret == 0)
{ {
LOG_OPENSSL_ERROR("X509_set_issuer_name() failed"); LOG_OPENSSL_ERROR("X509_set_issuer_name() failed");
...@@ -212,7 +218,7 @@ namespace RTC ...@@ -212,7 +218,7 @@ namespace RTC
} }
// Sign the certificate with its own private key. // Sign the certificate with its own private key.
ret = X509_sign(DTLSAgent::certificate, DTLSAgent::privateKey, EVP_sha1()); ret = X509_sign(DTLSTransport::certificate, DTLSTransport::privateKey, EVP_sha1());
if (ret == 0) if (ret == 0)
{ {
LOG_OPENSSL_ERROR("X509_sign() failed"); LOG_OPENSSL_ERROR("X509_sign() failed");
...@@ -226,17 +232,17 @@ namespace RTC ...@@ -226,17 +232,17 @@ namespace RTC
error: error:
if (bne) if (bne)
BN_free(bne); BN_free(bne);
if (rsa_key && !DTLSAgent::privateKey) if (rsa_key && !DTLSTransport::privateKey)
RSA_free(rsa_key); RSA_free(rsa_key);
if (DTLSAgent::privateKey) if (DTLSTransport::privateKey)
EVP_PKEY_free(DTLSAgent::privateKey); // NOTE: This also frees the RSA key. EVP_PKEY_free(DTLSTransport::privateKey); // NOTE: This also frees the RSA key.
if (DTLSAgent::certificate) if (DTLSTransport::certificate)
X509_free(DTLSAgent::certificate); X509_free(DTLSTransport::certificate);
MS_THROW_ERROR("DTLS certificate and private key generation failed"); MS_THROW_ERROR("DTLS certificate and private key generation failed");
} }
void DTLSAgent::ReadCertificateAndPrivateKeyFromFiles() void DTLSTransport::ReadCertificateAndPrivateKeyFromFiles()
{ {
MS_TRACE(); MS_TRACE();
...@@ -248,8 +254,8 @@ namespace RTC ...@@ -248,8 +254,8 @@ namespace RTC
MS_ERROR("error reading DTLS certificate file: %s", std::strerror(errno)); MS_ERROR("error reading DTLS certificate file: %s", std::strerror(errno));
goto error; goto error;
} }
DTLSAgent::certificate = PEM_read_X509(file, nullptr, nullptr, nullptr); DTLSTransport::certificate = PEM_read_X509(file, nullptr, nullptr, nullptr);
if (!DTLSAgent::certificate) if (!DTLSTransport::certificate)
{ {
LOG_OPENSSL_ERROR("PEM_read_X509() failed"); LOG_OPENSSL_ERROR("PEM_read_X509() failed");
goto error; goto error;
...@@ -262,8 +268,8 @@ namespace RTC ...@@ -262,8 +268,8 @@ namespace RTC
MS_ERROR("error reading DTLS private key file: %s", std::strerror(errno)); MS_ERROR("error reading DTLS private key file: %s", std::strerror(errno));
goto error; goto error;
} }
DTLSAgent::privateKey = PEM_read_PrivateKey(file, nullptr, nullptr, nullptr); DTLSTransport::privateKey = PEM_read_PrivateKey(file, nullptr, nullptr, nullptr);
if (!DTLSAgent::privateKey) if (!DTLSTransport::privateKey)
{ {
LOG_OPENSSL_ERROR("PEM_read_PrivateKey() failed"); LOG_OPENSSL_ERROR("PEM_read_PrivateKey() failed");
goto error; goto error;
...@@ -276,7 +282,7 @@ namespace RTC ...@@ -276,7 +282,7 @@ namespace RTC
MS_THROW_ERROR("error reading DTLS certificate and private key PEM files"); MS_THROW_ERROR("error reading DTLS certificate and private key PEM files");
} }
void DTLSAgent::CreateSSL_CTX() void DTLSTransport::CreateSSL_CTX()
{ {
MS_TRACE(); MS_TRACE();
...@@ -288,35 +294,35 @@ namespace RTC ...@@ -288,35 +294,35 @@ namespace RTC
// - Both DTLS 1.0 and 1.2 (requires OpenSSL >= 1.1.0). // - Both DTLS 1.0 and 1.2 (requires OpenSSL >= 1.1.0).
#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
DTLSAgent::sslCtx = SSL_CTX_new(DTLS_method()); DTLSTransport::sslCtx = SSL_CTX_new(DTLS_method());
// - Just DTLS 1.0 (requires OpenSSL >= 1.0.1). // - Just DTLS 1.0 (requires OpenSSL >= 1.0.1).
#elif (OPENSSL_VERSION_NUMBER >= 0x10001000L) #elif (OPENSSL_VERSION_NUMBER >= 0x10001000L)
DTLSAgent::sslCtx = SSL_CTX_new(DTLSv1_method()); DTLSTransport::sslCtx = SSL_CTX_new(DTLSv1_method());
#else #else
#error "too old OpenSSL version" #error "too old OpenSSL version"
#endif #endif
if (!DTLSAgent::sslCtx) if (!DTLSTransport::sslCtx)
{ {
LOG_OPENSSL_ERROR("SSL_CTX_new() failed"); LOG_OPENSSL_ERROR("SSL_CTX_new() failed");
goto error; goto error;
} }
ret = SSL_CTX_use_certificate(DTLSAgent::sslCtx, DTLSAgent::certificate); ret = SSL_CTX_use_certificate(DTLSTransport::sslCtx, DTLSTransport::certificate);
if (ret == 0) if (ret == 0)
{ {
LOG_OPENSSL_ERROR("SSL_CTX_use_certificate() failed"); LOG_OPENSSL_ERROR("SSL_CTX_use_certificate() failed");
goto error; goto error;
} }
ret = SSL_CTX_use_PrivateKey(DTLSAgent::sslCtx, DTLSAgent::privateKey); ret = SSL_CTX_use_PrivateKey(DTLSTransport::sslCtx, DTLSTransport::privateKey);
if (ret == 0) if (ret == 0)
{ {
LOG_OPENSSL_ERROR("SSL_CTX_use_PrivateKey() failed"); LOG_OPENSSL_ERROR("SSL_CTX_use_PrivateKey() failed");
goto error; goto error;
} }
ret = SSL_CTX_check_private_key(DTLSAgent::sslCtx); ret = SSL_CTX_check_private_key(DTLSTransport::sslCtx);
if (ret == 0) if (ret == 0)
{ {
LOG_OPENSSL_ERROR("SSL_CTX_check_private_key() failed"); LOG_OPENSSL_ERROR("SSL_CTX_check_private_key() failed");
...@@ -324,24 +330,24 @@ namespace RTC ...@@ -324,24 +330,24 @@ namespace RTC
} }
// Set options. // Set options.
SSL_CTX_set_options(DTLSAgent::sslCtx, SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_NO_TICKET | SSL_OP_SINGLE_ECDH_USE); SSL_CTX_set_options(DTLSTransport::sslCtx, SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_NO_TICKET | SSL_OP_SINGLE_ECDH_USE);
// Don't use sessions cache. // Don't use sessions cache.
SSL_CTX_set_session_cache_mode(DTLSAgent::sslCtx, SSL_SESS_CACHE_OFF); SSL_CTX_set_session_cache_mode(DTLSTransport::sslCtx, SSL_SESS_CACHE_OFF);
// Read always as much into the buffer as possible. // Read always as much into the buffer as possible.
SSL_CTX_set_read_ahead(DTLSAgent::sslCtx, 1); SSL_CTX_set_read_ahead(DTLSTransport::sslCtx, 1);
SSL_CTX_set_verify_depth(DTLSAgent::sslCtx, 4); SSL_CTX_set_verify_depth(DTLSTransport::sslCtx, 4);
// Require certificate from peer. // Require certificate from peer.
SSL_CTX_set_verify(DTLSAgent::sslCtx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, on_ssl_certificate_verify); SSL_CTX_set_verify(DTLSTransport::sslCtx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, on_ssl_certificate_verify);
// Set SSL info callback. // Set SSL info callback.
SSL_CTX_set_info_callback(DTLSAgent::sslCtx, on_ssl_info); SSL_CTX_set_info_callback(DTLSTransport::sslCtx, on_ssl_info);
// Set ciphers. // Set ciphers.
ret = SSL_CTX_set_cipher_list(DTLSAgent::sslCtx, "ALL:!ADH:!LOW:!EXP:!MD5:!aNULL:!eNULL:@STRENGTH"); ret = SSL_CTX_set_cipher_list(DTLSTransport::sslCtx, "ALL:!ADH:!LOW:!EXP:!MD5:!aNULL:!eNULL:@STRENGTH");
if (ret == 0) if (ret == 0)
{ {
LOG_OPENSSL_ERROR("SSL_CTX_set_cipher_list() failed"); LOG_OPENSSL_ERROR("SSL_CTX_set_cipher_list() failed");
...@@ -353,7 +359,7 @@ namespace RTC ...@@ -353,7 +359,7 @@ namespace RTC
// NOTE: https://code.google.com/p/chromium/issues/detail?id=406458 // NOTE: https://code.google.com/p/chromium/issues/detail?id=406458
// For OpenSSL >= 1.0.2: // For OpenSSL >= 1.0.2:
#if (OPENSSL_VERSION_NUMBER >= 0x10002000L) #if (OPENSSL_VERSION_NUMBER >= 0x10002000L)
SSL_CTX_set_ecdh_auto(DTLSAgent::sslCtx, 1); SSL_CTX_set_ecdh_auto(DTLSTransport::sslCtx, 1);
#else #else
ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
if (!ecdh) if (!ecdh)
...@@ -361,7 +367,7 @@ namespace RTC ...@@ -361,7 +367,7 @@ namespace RTC
LOG_OPENSSL_ERROR("EC_KEY_new_by_curve_name() failed"); LOG_OPENSSL_ERROR("EC_KEY_new_by_curve_name() failed");
goto error; goto error;
} }
if (SSL_CTX_set_tmp_ecdh(DTLSAgent::sslCtx, ecdh) != 1) if (SSL_CTX_set_tmp_ecdh(DTLSTransport::sslCtx, ecdh) != 1)
{ {
LOG_OPENSSL_ERROR("SSL_CTX_set_tmp_ecdh() failed"); LOG_OPENSSL_ERROR("SSL_CTX_set_tmp_ecdh() failed");
goto error; goto error;
...@@ -371,9 +377,9 @@ namespace RTC ...@@ -371,9 +377,9 @@ namespace RTC
#endif #endif
// Set the "use_srtp" DTLS extension. // Set the "use_srtp" DTLS extension.
for (auto it = DTLSAgent::srtpProfiles.begin(); it != DTLSAgent::srtpProfiles.end(); ++it) for (auto it = DTLSTransport::srtpProfiles.begin(); it != DTLSTransport::srtpProfiles.end(); ++it)
{ {
if (it != DTLSAgent::srtpProfiles.begin()) if (it != DTLSTransport::srtpProfiles.begin())
ssl_srtp_profiles += ":"; ssl_srtp_profiles += ":";
SrtpProfileMapEntry* profile_entry = &(*it); SrtpProfileMapEntry* profile_entry = &(*it);
...@@ -381,7 +387,7 @@ namespace RTC ...@@ -381,7 +387,7 @@ namespace RTC
} }
MS_DEBUG("setting SRTP profiles for DTLS: %s", ssl_srtp_profiles.c_str()); MS_DEBUG("setting SRTP profiles for DTLS: %s", ssl_srtp_profiles.c_str());
// NOTE: This function returns 0 on success. // NOTE: This function returns 0 on success.
ret = SSL_CTX_set_tlsext_use_srtp(DTLSAgent::sslCtx, ssl_srtp_profiles.c_str()); ret = SSL_CTX_set_tlsext_use_srtp(DTLSTransport::sslCtx, ssl_srtp_profiles.c_str());
if (ret != 0) if (ret != 0)
{ {
MS_ERROR("SSL_CTX_set_tlsext_use_srtp() failed when entering '%s'", ssl_srtp_profiles.c_str()); MS_ERROR("SSL_CTX_set_tlsext_use_srtp() failed when entering '%s'", ssl_srtp_profiles.c_str());
...@@ -392,10 +398,10 @@ namespace RTC ...@@ -392,10 +398,10 @@ namespace RTC
return; return;
error: error:
if (DTLSAgent::sslCtx) if (DTLSTransport::sslCtx)
{ {
SSL_CTX_free(DTLSAgent::sslCtx); SSL_CTX_free(DTLSTransport::sslCtx);
DTLSAgent::sslCtx = nullptr; DTLSTransport::sslCtx = nullptr;
} }
if (ecdh) if (ecdh)
...@@ -404,55 +410,42 @@ namespace RTC ...@@ -404,55 +410,42 @@ namespace RTC
MS_THROW_ERROR("SSL context creation failed"); MS_THROW_ERROR("SSL context creation failed");
} }
void DTLSAgent::GenerateFingerprints() void DTLSTransport::GenerateFingerprints()
{ {
MS_TRACE(); MS_TRACE();
static const std::vector<FingerprintHash> hashes = for (auto it = DTLSTransport::string2FingerprintAlgorithm.begin(); it != DTLSTransport::string2FingerprintAlgorithm.end(); ++it)
{
FingerprintHash::SHA1,
FingerprintHash::SHA224,
FingerprintHash::SHA256,
FingerprintHash::SHA384,
FingerprintHash::SHA512
};
for (auto hash : hashes)
{ {
std::string hash_str; std::string algorithm_str = it->first;
FingerprintAlgorithm algorithm = it->second;
unsigned char binary_fingerprint[EVP_MAX_MD_SIZE]; unsigned char binary_fingerprint[EVP_MAX_MD_SIZE];
unsigned int size = 0; unsigned int size = 0;
char hex_fingerprint[(EVP_MAX_MD_SIZE * 2) + 1]; char hex_fingerprint[(EVP_MAX_MD_SIZE * 2) + 1];
const EVP_MD* hash_function; const EVP_MD* hash_function;
int ret; int ret;
switch (hash) switch (algorithm)
{ {
case FingerprintHash::SHA1: case FingerprintAlgorithm::SHA1:
hash_function = EVP_sha1(); hash_function = EVP_sha1();
hash_str = "sha-1";
break; break;
case FingerprintHash::SHA224: case FingerprintAlgorithm::SHA224:
hash_function = EVP_sha224(); hash_function = EVP_sha224();
hash_str = "sha-224";
break; break;
case FingerprintHash::SHA256: case FingerprintAlgorithm::SHA256:
hash_function = EVP_sha256(); hash_function = EVP_sha256();
hash_str = "sha-256";
break; break;
case FingerprintHash::SHA384: case FingerprintAlgorithm::SHA384:
hash_function = EVP_sha384(); hash_function = EVP_sha384();
hash_str = "sha-384";
break; break;
case FingerprintHash::SHA512: case FingerprintAlgorithm::SHA512:
hash_function = EVP_sha512(); hash_function = EVP_sha512();
hash_str = "sha-512";
break; break;
default: default:
MS_ABORT("unknown hash"); MS_ABORT("unknown algorithm");
} }
ret = X509_digest(DTLSAgent::certificate, hash_function, binary_fingerprint, &size); ret = X509_digest(DTLSTransport::certificate, hash_function, binary_fingerprint, &size);
if (ret == 0) if (ret == 0)
{ {
MS_ERROR("X509_digest() failed"); MS_ERROR("X509_digest() failed");
...@@ -466,23 +459,23 @@ namespace RTC ...@@ -466,23 +459,23 @@ namespace RTC
} }
hex_fingerprint[size * 2] = '\0'; hex_fingerprint[size * 2] = '\0';
MS_DEBUG("%-7s fingerprint: %s", hash_str.c_str(), hex_fingerprint); MS_DEBUG("%-7s fingerprint: %s", algorithm_str.c_str(), hex_fingerprint);
// Store in the JSON. // Store in the JSON.
DTLSAgent::localFingerprints[hash_str] = hex_fingerprint; DTLSTransport::localFingerprints[algorithm_str] = hex_fingerprint;
} }
} }
/* Instance methods. */ /* Instance methods. */
DTLSAgent::DTLSAgent(Listener* listener) : DTLSTransport::DTLSTransport(Listener* listener) :
listener(listener) listener(listener)
{ {
MS_TRACE(); MS_TRACE();
/* Set SSL. */ /* Set SSL. */
this->ssl = SSL_new(DTLSAgent::sslCtx); this->ssl = SSL_new(DTLSTransport::sslCtx);
if (!this->ssl) if (!this->ssl)
{ {
LOG_OPENSSL_ERROR("SSL_new() failed"); LOG_OPENSSL_ERROR("SSL_new() failed");
...@@ -529,10 +522,10 @@ namespace RTC ...@@ -529,10 +522,10 @@ namespace RTC
// NOTE: If this is not catched by the caller the program will abort, but // NOTE: If this is not catched by the caller the program will abort, but
// this should never happen. // this should never happen.
MS_THROW_ERROR("DTLSAgent instance creation failed"); MS_THROW_ERROR("DTLSTransport instance creation failed");
} }
DTLSAgent::~DTLSAgent() DTLSTransport::~DTLSTransport()
{ {
MS_TRACE(); MS_TRACE();
...@@ -545,62 +538,54 @@ namespace RTC ...@@ -545,62 +538,54 @@ namespace RTC
} }
} }
void DTLSAgent::Run(DTLSRole role) // TODO: en realidad esto debería juntarse con el SetRemoteFingerprint.
void DTLSTransport::Start(Role role)
{ {
MS_TRACE(); MS_TRACE();
if (this->isRunning) if (this->started)
return; return;
this->isRunning = true; this->started = true;
this->role = role; this->localRole = role;
switch (this->role) switch (this->localRole)
{ {
case DTLSRole::SERVER: case Role::SERVER:
SSL_set_accept_state(this->ssl); SSL_set_accept_state(this->ssl);
SSL_do_handshake(this->ssl); SSL_do_handshake(this->ssl);
break; break;
case DTLSRole::CLIENT: case Role::CLIENT:
SSL_set_connect_state(this->ssl); SSL_set_connect_state(this->ssl);
SSL_do_handshake(this->ssl); SSL_do_handshake(this->ssl);
SendPendingOutgoingDTLSData(); SendPendingOutgoingDTLSData();
SetTimeout(); SetTimeout();
break; break;
case DTLSRole::NONE: case Role::NONE:
MS_ABORT("no valid DTLS role given"); MS_ABORT("no valid DTLS role given");
break; break;
} }
} }
void DTLSAgent::SetRemoteFingerprint(FingerprintHash hash, std::string& fingerprint) // TODO: replace with start()
void DTLSTransport::SetRemoteFingerprint(Fingerprint fingerprint)
{ {
MS_TRACE(); MS_TRACE();
MS_ASSERT(hash != FingerprintHash::NONE, "no fingerprint hash provided"); MS_ASSERT(fingerprint.algorithm != FingerprintAlgorithm::NONE, "no fingerprint algorithm provided");
// Lowcase fingerprint and remove colons.
fingerprint.erase(std::remove(fingerprint.begin(), fingerprint.end(), ':'), fingerprint.end());
std::transform(fingerprint.begin(), fingerprint.end(), fingerprint.begin(), ::tolower);
// Ensure
this->remoteFingerprintHash = hash;
this->remoteFingerprint = fingerprint; this->remoteFingerprint = fingerprint;
// Upcase given fingerprint.
std::transform(this->remoteFingerprint.begin(), this->remoteFingerprint.end(), this->remoteFingerprint.begin(), ::toupper);
// The remote fingerpring may have been set after DTLS handshake was done, // The remote fingerpring may have been set after DTLS handshake was done,
// so we may need to process it now. // so we may need to process it now.
if (this->isHandshakeDone && !this->isConnected) if (this->handshakeDone && !this->connected)
{ {
MS_DEBUG("handshake already done, processing it right now"); MS_DEBUG("handshake already done, processing it right now");
ProcessHandshake(); ProcessHandshake();
} }
} }
void DTLSAgent::Reset() void DTLSTransport::Reset()
{ {
MS_TRACE(); MS_TRACE();
...@@ -608,10 +593,10 @@ namespace RTC ...@@ -608,10 +593,10 @@ namespace RTC
this->doReset = false; this->doReset = false;
if (!this->isRunning) if (!this->started)
return; return;
if (this->isCheckingStatus) if (this->checkingStatus)
{ {
this->doReset = true; this->doReset = true;
return; return;
...@@ -626,13 +611,13 @@ namespace RTC ...@@ -626,13 +611,13 @@ namespace RTC
SSL_shutdown(this->ssl); SSL_shutdown(this->ssl);
SendPendingOutgoingDTLSData(); SendPendingOutgoingDTLSData();
this->role = DTLSRole::NONE; this->localRole = Role::NONE;
this->isRunning = false; this->started = false;
this->isHandshakeDone = false; this->handshakeDone = false;
this->isHandshakeDoneNow = false; this->handshakeDoneNow = false;
this->isConnected = false; this->connected = false;
this->doClose = false; this->doClose = false;
this->isCheckingStatus = false; this->checkingStatus = false;
// Reset SSL status. // Reset SSL status.
// NOTE: For this to properly work, SSL_shutdown() must be called before. // NOTE: For this to properly work, SSL_shutdown() must be called before.
...@@ -642,17 +627,17 @@ namespace RTC ...@@ -642,17 +627,17 @@ namespace RTC
LOG_OPENSSL_ERROR("SSL_clear() failed"); LOG_OPENSSL_ERROR("SSL_clear() failed");
} }
void DTLSAgent::Close() void DTLSTransport::Close()
{ {
MS_TRACE(); MS_TRACE();
if (this->isCheckingStatus) if (this->checkingStatus)
{ {
this->doClose = true; this->doClose = true;
return; return;
} }
if (this->isRunning) if (this->started)
{ {
// Send close alert to the peer. // Send close alert to the peer.
SSL_shutdown(this->ssl); SSL_shutdown(this->ssl);
...@@ -664,16 +649,16 @@ namespace RTC ...@@ -664,16 +649,16 @@ namespace RTC
delete this; delete this;
} }
void DTLSAgent::ProcessDTLSData(const MS_BYTE* data, size_t len) void DTLSTransport::ProcessDTLSData(const MS_BYTE* data, size_t len)
{ {
MS_TRACE(); MS_TRACE();
int written; int written;
int read; int read;
if (!this->isRunning) if (!this->started)
{ {
MS_ERROR("cannot process data while not running"); MS_ERROR("cannot process data while not started");
return; return;
} }
...@@ -683,7 +668,7 @@ namespace RTC ...@@ -683,7 +668,7 @@ namespace RTC
MS_WARN("OpenSSL BIO_write() wrote less (%zu bytes) than given data (%zu bytes)", (size_t)written, len); MS_WARN("OpenSSL BIO_write() wrote less (%zu bytes) than given data (%zu bytes)", (size_t)written, len);
// Must call SSL_read() to process received DTLS data. // Must call SSL_read() to process received DTLS data.
read = SSL_read(this->ssl, (void*)DTLSAgent::sslReadBuffer, MS_SSL_READ_BUFFER_SIZE); read = SSL_read(this->ssl, (void*)DTLSTransport::sslReadBuffer, MS_SSL_READ_BUFFER_SIZE);
// Send data if it's ready. // Send data if it's ready.
SendPendingOutgoingDTLSData(); SendPendingOutgoingDTLSData();
...@@ -698,21 +683,21 @@ namespace RTC ...@@ -698,21 +683,21 @@ namespace RTC
// Application data received. Notify to the listener. // Application data received. Notify to the listener.
if (read > 0) if (read > 0)
{ {
if (!this->isConnected) if (!this->connected)
{ {
MS_DEBUG("ignoring application data received while DTLS not fully connected"); MS_DEBUG("ignoring application data received while DTLS not fully connected");
return; return;
} }
this->listener->onDTLSApplicationData(this, (MS_BYTE*)DTLSAgent::sslReadBuffer, (size_t)read); this->listener->onDTLSApplicationData(this, (MS_BYTE*)DTLSTransport::sslReadBuffer, (size_t)read);
} }
} }
void DTLSAgent::SendApplicationData(const MS_BYTE* data, size_t len) void DTLSTransport::SendApplicationData(const MS_BYTE* data, size_t len)
{ {
MS_TRACE(); MS_TRACE();
if (!this->isConnected) if (!this->connected)
{ {
MS_ERROR("cannot send application data while DTLS is not connected"); MS_ERROR("cannot send application data while DTLS is not connected");
return; return;
...@@ -741,26 +726,26 @@ namespace RTC ...@@ -741,26 +726,26 @@ namespace RTC
SendPendingOutgoingDTLSData(); SendPendingOutgoingDTLSData();
} }
void DTLSAgent::Dump() void DTLSTransport::Dump()
{ {
MS_TRACE(); MS_TRACE();
MS_DEBUG("[role: %s | running: %s | handshake done: %s | connected: %s]", MS_DEBUG("[role: %s | started: %s | handshake done: %s | connected: %s]",
(this->role == DTLSRole::SERVER ? "server" : (this->role == DTLSRole::CLIENT ? "client" : "none")), (this->localRole == Role::SERVER ? "server" : (this->localRole == Role::CLIENT ? "client" : "none")),
this->isRunning ? "yes" : "no", this->started ? "yes" : "no",
this->isHandshakeDone ? "yes" : "no", this->handshakeDone ? "yes" : "no",
this->isConnected ? "yes" : "no"); this->connected ? "yes" : "no");
} }
inline inline
bool DTLSAgent::CheckStatus(int return_code) bool DTLSTransport::CheckStatus(int return_code)
{ {
MS_TRACE(); MS_TRACE();
int err; int err;
// Set a flag to avoid certain methods to be called while in this method. // Set a flag to avoid certain methods to be called while in this method.
this->isCheckingStatus = true; this->checkingStatus = true;
err = SSL_get_error(this->ssl, return_code); err = SSL_get_error(this->ssl, return_code);
switch (err) switch (err)
...@@ -792,10 +777,10 @@ namespace RTC ...@@ -792,10 +777,10 @@ namespace RTC
} }
// Check if the handshake (or re-handshake) has been done right now. // Check if the handshake (or re-handshake) has been done right now.
if (this->isHandshakeDoneNow) if (this->handshakeDoneNow)
{ {
this->isHandshakeDoneNow = false; this->handshakeDoneNow = false;
this->isHandshakeDone = true; this->handshakeDone = true;
// Stop the timer. // Stop the timer.
this->timer->Stop(); this->timer->Stop();
...@@ -806,13 +791,13 @@ namespace RTC ...@@ -806,13 +791,13 @@ namespace RTC
// Check if the peer sent close alert or a fatal error happened. // Check if the peer sent close alert or a fatal error happened.
else if ((SSL_get_shutdown(this->ssl) & SSL_RECEIVED_SHUTDOWN) || err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) else if ((SSL_get_shutdown(this->ssl) & SSL_RECEIVED_SHUTDOWN) || err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL)
{ {
bool was_connected = this->isConnected; bool was_connected = this->connected;
this->role = DTLSRole::NONE; this->localRole = Role::NONE;
this->isRunning = false; this->started = false;
this->isHandshakeDone = false; this->handshakeDone = false;
this->isHandshakeDoneNow = false; this->handshakeDoneNow = false;
this->isConnected = false; this->connected = false;
if (was_connected) if (was_connected)
{ {
...@@ -834,7 +819,7 @@ namespace RTC ...@@ -834,7 +819,7 @@ namespace RTC
} }
// Unset the safe flag. // Unset the safe flag.
this->isCheckingStatus = false; this->checkingStatus = false;
// Check reset/close flags (note that they may have been set in user callbacks). // Check reset/close flags (note that they may have been set in user callbacks).
if (this->doClose) if (this->doClose)
...@@ -852,7 +837,7 @@ namespace RTC ...@@ -852,7 +837,7 @@ namespace RTC
} }
inline inline
void DTLSAgent::SendPendingOutgoingDTLSData() void DTLSTransport::SendPendingOutgoingDTLSData()
{ {
MS_TRACE(); MS_TRACE();
...@@ -875,7 +860,7 @@ namespace RTC ...@@ -875,7 +860,7 @@ namespace RTC
} }
inline inline
void DTLSAgent::SetTimeout() void DTLSTransport::SetTimeout()
{ {
MS_TRACE(); MS_TRACE();
...@@ -908,15 +893,15 @@ namespace RTC ...@@ -908,15 +893,15 @@ namespace RTC
} }
inline inline
void DTLSAgent::ProcessHandshake() void DTLSTransport::ProcessHandshake()
{ {
MS_TRACE(); MS_TRACE();
MS_ASSERT(this->isHandshakeDone, "handshake not done yet"); MS_ASSERT(this->handshakeDone, "handshake not done yet");
// If the remote fingerprint is not yet set then do nothing (this method // If the remote fingerprint is not yet set then do nothing (this method
// will be called when the fingerprint is set). // will be called when the fingerprint is set).
if (this->remoteFingerprintHash == FingerprintHash::NONE) if (this->remoteFingerprint.algorithm == FingerprintAlgorithm::NONE)
{ {
MS_DEBUG("remote fingerprint not yet set, waiting for it"); MS_DEBUG("remote fingerprint not yet set, waiting for it");
return; return;
...@@ -933,7 +918,7 @@ namespace RTC ...@@ -933,7 +918,7 @@ namespace RTC
return; return;
} }
this->isConnected = true; this->connected = true;
// Notify the listener. // Notify the listener.
this->listener->onDTLSConnected(this); this->listener->onDTLSConnected(this);
...@@ -954,11 +939,11 @@ namespace RTC ...@@ -954,11 +939,11 @@ namespace RTC
} }
inline inline
bool DTLSAgent::CheckRemoteFingerprint() bool DTLSTransport::CheckRemoteFingerprint()
{ {
MS_TRACE(); MS_TRACE();
MS_ASSERT(this->remoteFingerprintHash != FingerprintHash::NONE, "remote fingerprint not set"); MS_ASSERT(this->remoteFingerprint.algorithm != FingerprintAlgorithm::NONE, "remote fingerprint not set");
X509* certificate; X509* certificate;
unsigned char binary_fingerprint[EVP_MAX_MD_SIZE]; unsigned char binary_fingerprint[EVP_MAX_MD_SIZE];
...@@ -974,25 +959,25 @@ namespace RTC ...@@ -974,25 +959,25 @@ namespace RTC
return false; return false;
} }
switch (this->remoteFingerprintHash) switch (this->remoteFingerprint.algorithm)
{ {
case FingerprintHash::SHA1: case FingerprintAlgorithm::SHA1:
hash_function = EVP_sha1(); hash_function = EVP_sha1();
break; break;
case FingerprintHash::SHA224: case FingerprintAlgorithm::SHA224:
hash_function = EVP_sha224(); hash_function = EVP_sha224();
break; break;
case FingerprintHash::SHA256: case FingerprintAlgorithm::SHA256:
hash_function = EVP_sha256(); hash_function = EVP_sha256();
break; break;
case FingerprintHash::SHA384: case FingerprintAlgorithm::SHA384:
hash_function = EVP_sha384(); hash_function = EVP_sha384();
break; break;
case FingerprintHash::SHA512: case FingerprintAlgorithm::SHA512:
hash_function = EVP_sha512(); hash_function = EVP_sha512();
break; break;
default: default:
MS_ABORT("unknown hash"); MS_ABORT("unknown algorithm");
} }
ret = X509_digest(certificate, hash_function, binary_fingerprint, &size); ret = X509_digest(certificate, hash_function, binary_fingerprint, &size);
...@@ -1011,9 +996,9 @@ namespace RTC ...@@ -1011,9 +996,9 @@ namespace RTC
} }
hex_fingerprint[size * 2] = '\0'; hex_fingerprint[size * 2] = '\0';
if (this->remoteFingerprint.compare(hex_fingerprint) != 0) if (this->remoteFingerprint.value.compare(hex_fingerprint) != 0)
{ {
MS_DEBUG("fingerprint in the remote certificate (%s) does not match the announced one (%s)", hex_fingerprint, this->remoteFingerprint.c_str()); MS_DEBUG("fingerprint in the remote certificate (%s) does not match the announced one (%s)", hex_fingerprint, this->remoteFingerprint.value.c_str());
return false; return false;
} }
...@@ -1025,7 +1010,7 @@ namespace RTC ...@@ -1025,7 +1010,7 @@ namespace RTC
} }
inline inline
RTC::SRTPSession::SRTPProfile DTLSAgent::GetNegotiatedSRTPProfile() RTC::SRTPSession::SRTPProfile DTLSTransport::GetNegotiatedSRTPProfile()
{ {
MS_TRACE(); MS_TRACE();
...@@ -1039,7 +1024,7 @@ namespace RTC ...@@ -1039,7 +1024,7 @@ namespace RTC
} }
// Get the negotiated SRTP profile. // Get the negotiated SRTP profile.
for (auto it = DTLSAgent::srtpProfiles.begin(); it != DTLSAgent::srtpProfiles.end(); ++it) for (auto it = DTLSTransport::srtpProfiles.begin(); it != DTLSTransport::srtpProfiles.end(); ++it)
{ {
SrtpProfileMapEntry* profile_entry = &(*it); SrtpProfileMapEntry* profile_entry = &(*it);
...@@ -1055,7 +1040,7 @@ namespace RTC ...@@ -1055,7 +1040,7 @@ namespace RTC
} }
inline inline
void DTLSAgent::ExtractSRTPKeys(RTC::SRTPSession::SRTPProfile srtp_profile) void DTLSTransport::ExtractSRTPKeys(RTC::SRTPSession::SRTPProfile srtp_profile)
{ {
MS_TRACE(); MS_TRACE();
...@@ -1071,21 +1056,21 @@ namespace RTC ...@@ -1071,21 +1056,21 @@ namespace RTC
ret = SSL_export_keying_material(this->ssl, srtp_material, MS_SRTP_MASTER_LENGTH * 2, "EXTRACTOR-dtls_srtp", 19, nullptr, 0, 0); ret = SSL_export_keying_material(this->ssl, srtp_material, MS_SRTP_MASTER_LENGTH * 2, "EXTRACTOR-dtls_srtp", 19, nullptr, 0, 0);
MS_ASSERT(ret != 0, "SSL_export_keying_material() failed"); MS_ASSERT(ret != 0, "SSL_export_keying_material() failed");
switch (this->role) switch (this->localRole)
{ {
case DTLSRole::SERVER: case Role::SERVER:
srtp_remote_key = srtp_material; srtp_remote_key = srtp_material;
srtp_local_key = srtp_remote_key + MS_SRTP_MASTER_KEY_LENGTH; srtp_local_key = srtp_remote_key + MS_SRTP_MASTER_KEY_LENGTH;
srtp_remote_salt = srtp_local_key + MS_SRTP_MASTER_KEY_LENGTH; srtp_remote_salt = srtp_local_key + MS_SRTP_MASTER_KEY_LENGTH;
srtp_local_salt = srtp_remote_salt + MS_SRTP_MASTER_SALT_LENGTH; srtp_local_salt = srtp_remote_salt + MS_SRTP_MASTER_SALT_LENGTH;
break; break;
case DTLSRole::CLIENT: case Role::CLIENT:
srtp_local_key = srtp_material; srtp_local_key = srtp_material;
srtp_remote_key = srtp_local_key + MS_SRTP_MASTER_KEY_LENGTH; srtp_remote_key = srtp_local_key + MS_SRTP_MASTER_KEY_LENGTH;
srtp_local_salt = srtp_remote_key + MS_SRTP_MASTER_KEY_LENGTH; srtp_local_salt = srtp_remote_key + MS_SRTP_MASTER_KEY_LENGTH;
srtp_remote_salt = srtp_local_salt + MS_SRTP_MASTER_SALT_LENGTH; srtp_remote_salt = srtp_local_salt + MS_SRTP_MASTER_SALT_LENGTH;
break; break;
case DTLSRole::NONE: case Role::NONE:
MS_ABORT("no DTLS role set"); MS_ABORT("no DTLS role set");
break; break;
} }
...@@ -1102,7 +1087,7 @@ namespace RTC ...@@ -1102,7 +1087,7 @@ namespace RTC
} }
inline inline
void DTLSAgent::onSSLInfo(int where, int ret) void DTLSTransport::onSSLInfo(int where, int ret)
{ {
MS_TRACE(); MS_TRACE();
...@@ -1153,7 +1138,7 @@ namespace RTC ...@@ -1153,7 +1138,7 @@ namespace RTC
else if (where & SSL_CB_HANDSHAKE_DONE) else if (where & SSL_CB_HANDSHAKE_DONE)
{ {
MS_DEBUG("DTLS handshake done"); MS_DEBUG("DTLS handshake done");
this->isHandshakeDoneNow = true; this->handshakeDoneNow = true;
} }
// NOTE: checking SSL_get_shutdown(this->ssl) & SSL_RECEIVED_SHUTDOWN here upon // NOTE: checking SSL_get_shutdown(this->ssl) & SSL_RECEIVED_SHUTDOWN here upon
...@@ -1161,7 +1146,7 @@ namespace RTC ...@@ -1161,7 +1146,7 @@ namespace RTC
} }
inline inline
void DTLSAgent::onTimer(Timer* timer) void DTLSTransport::onTimer(Timer* timer)
{ {
MS_TRACE(); MS_TRACE();
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
#include "RTC/TCPConnection.h" #include "RTC/TCPConnection.h"
#include "RTC/STUNMessage.h" #include "RTC/STUNMessage.h"
#include "RTC/DTLSAgent.h" #include "RTC/DTLSTransport.h"
#include "RTC/RTPPacket.h" #include "RTC/RTPPacket.h"
#include "RTC/RTCPPacket.h" #include "RTC/RTCPPacket.h"
#include "Utils.h" #include "Utils.h"
...@@ -84,7 +84,7 @@ namespace RTC ...@@ -84,7 +84,7 @@ namespace RTC
this->reader->onRTPDataRecv(this, packet, packet_len); this->reader->onRTPDataRecv(this, packet, packet_len);
} }
// Check if it's DTLS. // Check if it's DTLS.
else if (DTLSAgent::IsDTLS(packet, packet_len)) else if (DTLSTransport::IsDTLS(packet, packet_len))
{ {
this->reader->onDTLSDataRecv(this, packet, packet_len); this->reader->onDTLSDataRecv(this, packet, packet_len);
} }
......
...@@ -51,6 +51,7 @@ namespace RTC ...@@ -51,6 +51,7 @@ namespace RTC
{ {
this->iceComponent = IceComponent::RTP; this->iceComponent = IceComponent::RTP;
// Create a ICE server.
this->iceServer = new RTC::IceServer(this, this->iceServer = new RTC::IceServer(this,
Utils::Crypto::GetRandomString(16), Utils::Crypto::GetRandomString(16),
Utils::Crypto::GetRandomString(32)); Utils::Crypto::GetRandomString(32));
...@@ -66,6 +67,7 @@ namespace RTC ...@@ -66,6 +67,7 @@ namespace RTC
{ {
this->iceComponent = IceComponent::RTCP; this->iceComponent = IceComponent::RTCP;
// Create a ICE server.
this->iceServer = new RTC::IceServer(this, this->iceServer = new RTC::IceServer(this,
rtpTransport->GetIceUsernameFragment(), rtpTransport->GetIceUsernameFragment(),
rtpTransport->GetIcePassword()); rtpTransport->GetIcePassword());
...@@ -184,6 +186,9 @@ namespace RTC ...@@ -184,6 +186,9 @@ namespace RTC
MS_THROW_ERROR("could not open any IP:port"); MS_THROW_ERROR("could not open any IP:port");
} }
// Create a DTLS agent.
this->dtlsTransport = new RTC::DTLSTransport(this);
// Hack to avoid that Close() above attempts to delete this. // Hack to avoid that Close() above attempts to delete this.
this->allocated = true; this->allocated = true;
} }
...@@ -200,8 +205,8 @@ namespace RTC ...@@ -200,8 +205,8 @@ namespace RTC
if (this->iceServer) if (this->iceServer)
this->iceServer->Close(); this->iceServer->Close();
// if (this->dtlsAgent) if (this->dtlsTransport)
// this->dtlsAgent->Close(); this->dtlsTransport->Close();
// if (this->srtpRecvSession) // if (this->srtpRecvSession)
// this->srtpRecvSession->Close(); // this->srtpRecvSession->Close();
...@@ -257,7 +262,7 @@ namespace RTC ...@@ -257,7 +262,7 @@ namespace RTC
} }
// Add `dtlsLocalFingerprints`. // Add `dtlsLocalFingerprints`.
data[k_dtlsLocalFingerprints] = RTC::DTLSAgent::GetLocalFingerprints(); data[k_dtlsLocalFingerprints] = RTC::DTLSTransport::GetLocalFingerprints();
return data; return data;
} }
...@@ -291,7 +296,72 @@ namespace RTC ...@@ -291,7 +296,72 @@ namespace RTC
case Channel::Request::MethodId::transport_start: case Channel::Request::MethodId::transport_start:
{ {
// TODO static const Json::StaticString k_role("role");
static const Json::StaticString v_auto("auto");
static const Json::StaticString v_client("client");
static const Json::StaticString v_server("server");
static const Json::StaticString k_fingerprint("fingerprint");
static const Json::StaticString k_algorithm("algorithm");
static const Json::StaticString k_value("value");
RTC::DTLSTransport::FingerprintAlgorithm fingerprint_algorithm;
std::string fingerprint_value;
RTC::DTLSTransport::Role role = RTC::DTLSTransport::Role::AUTO; // Default value.
// Ensure this method is not called twice.
if (this->started)
{
MS_ERROR("method already called");
request->Reject(500, "method already called");
return;
}
this->started = true;
// Validate request data.
if (!request->data[k_fingerprint].isObject())
{
MS_ERROR("missing .fingerprint");
request->Reject(500, "missing .fingerprint");
return;
}
if (!request->data[k_fingerprint][k_algorithm].isString() ||
!request->data[k_fingerprint][k_value].isString())
{
MS_ERROR("missing .fingerprint.algorithm and/or .fingerprint.value");
request->Reject(500, "missing .fingerprint.algorithm and/or .fingerprint.value");
return;
}
fingerprint_algorithm = RTC::DTLSTransport::GetFingerprintAlgorithm(request->data[k_fingerprint][k_algorithm].asString());
if (fingerprint_algorithm == RTC::DTLSTransport::FingerprintAlgorithm::NONE)
{
MS_ERROR("unsupported .fingerprint.algorithm");
request->Reject(500, "unsupported .fingerprint.algorithm");
return;
}
fingerprint_value = request->data[k_fingerprint][k_value].asString();
if (request->data[k_role].isString())
{
role = RTC::DTLSTransport::GetRole(request->data[k_role].asString());
if (role == RTC::DTLSTransport::Role::NONE)
{
MS_ERROR("invalid .role");
request->Reject(500, "invalid .role");
return;
}
}
break; break;
} }
...@@ -315,32 +385,12 @@ namespace RTC ...@@ -315,32 +385,12 @@ namespace RTC
return new RTC::Transport(this->listener, transportId, nullData, this); return new RTC::Transport(this->listener, transportId, nullData, this);
} }
void Transport::onOutgoingSTUNMessage(RTC::IceServer* iceServer, RTC::STUNMessage* msg, RTC::TransportSource* source) inline
{ void Transport::RunDTLSTransportIfReady()
MS_TRACE();
// Send the STUN response over the same transport source.
source->Send(msg->GetRaw(), msg->GetLength());
}
void Transport::onICEValidPair(RTC::IceServer* iceServer, RTC::TransportSource* source, bool has_use_candidate)
{ {
MS_TRACE(); MS_TRACE();
this->icePaired = true; // TODO
if (has_use_candidate)
this->icePairedWithUseCandidate = true;
/*
* RFC 5245 section 11.2 "Receiving Media":
*
* ICE implementations MUST be prepared to receive media on each component
* on any candidates provided for that component.
*/
if (SetSendingSource(source))
MS_DEBUG("got an ICE valid pair [UseCandidate:%s]", has_use_candidate ? "true" : "false");
// TODO: more
} }
inline inline
...@@ -431,13 +481,12 @@ namespace RTC ...@@ -431,13 +481,12 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
// RTC::TransportSource source(connection); RTC::TransportSource source(connection);
// if (RemoveSource(&source)) if (RemoveSource(&source))
// { {
// MS_DEBUG("valid source %s:", is_closed_by_peer ? "closed by peer" : "locally closed"); MS_DEBUG("valid source %s:", is_closed_by_peer ? "closed by peer" : "locally closed");
// source.Dump(); }
// }
} }
void Transport::onSTUNDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len) void Transport::onSTUNDataRecv(RTC::TCPConnection *connection, const MS_BYTE* data, size_t len)
...@@ -471,4 +520,113 @@ namespace RTC ...@@ -471,4 +520,113 @@ namespace RTC
RTC::TransportSource source(connection); RTC::TransportSource source(connection);
onRTCPDataRecv(&source, data, len); onRTCPDataRecv(&source, data, len);
} }
void Transport::onOutgoingSTUNMessage(RTC::IceServer* iceServer, RTC::STUNMessage* msg, RTC::TransportSource* source)
{
MS_TRACE();
// Send the STUN response over the same transport source.
source->Send(msg->GetRaw(), msg->GetLength());
}
void Transport::onICEValidPair(RTC::IceServer* iceServer, RTC::TransportSource* source, bool has_use_candidate)
{
MS_TRACE();
/*
* RFC 5245 section 11.2 "Receiving Media":
*
* ICE implementations MUST be prepared to receive media on each component
* on any candidates provided for that component.
*/
this->icePaired = true;
if (has_use_candidate)
this->icePairedWithUseCandidate = true;
switch (SetSendingSource(source))
{
// This is a new source.
case 0:
MS_DEBUG("got a new ICE valid pair [UseCandidate:%s]", has_use_candidate ? "true" : "false");
break;
// This is already the sending source.
case 1:
break;
// This is another valid source.
case 2:
MS_DEBUG("got a previous ICE valid pair [UseCandidate:%s]", has_use_candidate ? "true" : "false");
break;
}
// If ready, run the DTLS handler.
RunDTLSTransportIfReady();
}
void Transport::onOutgoingDTLSData(RTC::DTLSTransport* dtlsTransport, const MS_BYTE* data, size_t len)
{
MS_TRACE();
if (!this->sendingSource)
{
MS_DEBUG("no sending address set, cannot send DTLS packet");
return;
}
// TODO: remove
MS_DEBUG("sending DTLS data to to:");
this->sendingSource->Dump();
this->sendingSource->Send(data, len);
}
void Transport::onDTLSConnected(RTC::DTLSTransport* dtlsTransport)
{
MS_TRACE();
MS_DEBUG("DTLS connected");
}
void Transport::onDTLSDisconnected(RTC::DTLSTransport* dtlsTransport)
{
MS_TRACE();
MS_DEBUG("DTLS disconnected");
// TODO
// Reset();
}
void Transport::onDTLSFailed(RTC::DTLSTransport* dtlsTransport)
{
MS_TRACE();
MS_DEBUG("DTLS failed");
// TODO
// Reset();
}
void Transport::onSRTPKeyMaterial(RTC::DTLSTransport* dtlsTransport, RTC::SRTPSession::SRTPProfile srtp_profile, MS_BYTE* srtp_local_key, size_t srtp_local_key_len, MS_BYTE* srtp_remote_key, size_t srtp_remote_key_len)
{
MS_TRACE();
MS_DEBUG("got SRTP key material");
// TODO
// SetLocalSRTPKey(srtp_profile, srtp_local_key, srtp_local_key_len);
// SetRemoteSRTPKey(srtp_profile, srtp_remote_key, srtp_remote_key_len);
}
void Transport::onDTLSApplicationData(RTC::DTLSTransport* dtlsTransport, const MS_BYTE* data, size_t len)
{
MS_TRACE();
MS_DEBUG("DTLS application data received [size:%zu]", len);
// TMP
MS_DEBUG("data: %s", std::string((char*)data, len).c_str());
}
} }
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
#include "RTC/UDPSocket.h" #include "RTC/UDPSocket.h"
#include "RTC/STUNMessage.h" #include "RTC/STUNMessage.h"
#include "RTC/DTLSAgent.h" #include "RTC/DTLSTransport.h"
#include "RTC/RTPPacket.h" #include "RTC/RTPPacket.h"
#include "RTC/RTCPPacket.h" #include "RTC/RTCPPacket.h"
#include "Settings.h" #include "Settings.h"
...@@ -368,7 +368,7 @@ namespace RTC ...@@ -368,7 +368,7 @@ namespace RTC
} }
// Check if it's DTLS. // Check if it's DTLS.
if (DTLSAgent::IsDTLS(data, len)) if (DTLSTransport::IsDTLS(data, len))
{ {
this->listener->onDTLSDataRecv(this, data, len, addr); this->listener->onDTLSDataRecv(this, data, len, addr);
return; return;
......
...@@ -326,7 +326,7 @@ void TCPConnection::onUvReadAlloc(size_t suggested_size, uv_buf_t* buf) ...@@ -326,7 +326,7 @@ 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); // MS_DEBUG("available space in the buffer: %zu", buf->len);
} }
else else
{ {
......
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
#include "Channel/UnixStreamSocket.h" #include "Channel/UnixStreamSocket.h"
#include "RTC/UDPSocket.h" #include "RTC/UDPSocket.h"
#include "RTC/TCPServer.h" #include "RTC/TCPServer.h"
#include "RTC/DTLSAgent.h" #include "RTC/DTLSTransport.h"
#include "RTC/SRTPSession.h" #include "RTC/SRTPSession.h"
#include "Loop.h" #include "Loop.h"
#include "MediaSoupError.h" #include "MediaSoupError.h"
...@@ -113,7 +113,7 @@ void init() ...@@ -113,7 +113,7 @@ void init()
DepUsrSCTP::ClassInit(); DepUsrSCTP::ClassInit();
RTC::UDPSocket::ClassInit(); RTC::UDPSocket::ClassInit();
RTC::TCPServer::ClassInit(); RTC::TCPServer::ClassInit();
RTC::DTLSAgent::ClassInit(); RTC::DTLSTransport::ClassInit();
RTC::SRTPSession::ClassInit(); RTC::SRTPSession::ClassInit();
Utils::Crypto::ClassInit(); Utils::Crypto::ClassInit();
} }
...@@ -159,7 +159,7 @@ void destroy() ...@@ -159,7 +159,7 @@ void destroy()
DepOpenSSL::ClassDestroy(); DepOpenSSL::ClassDestroy();
DepLibSRTP::ClassDestroy(); DepLibSRTP::ClassDestroy();
DepUsrSCTP::ClassDestroy(); DepUsrSCTP::ClassDestroy();
RTC::DTLSAgent::ClassDestroy(); RTC::DTLSTransport::ClassDestroy();
Utils::Crypto::ClassDestroy(); Utils::Crypto::ClassDestroy();
} }
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论