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

Lot of work in Transport and DTLS.

上级 130d546c
...@@ -54,6 +54,11 @@ class Transport extends EventEmitter ...@@ -54,6 +54,11 @@ class Transport extends EventEmitter
return this._data.dtlsLocalParameters; return this._data.dtlsLocalParameters;
} }
get dtlsState()
{
return this._data.dtlsState;
}
/** /**
* Close the Transport * Close the Transport
*/ */
......
...@@ -18,6 +18,7 @@ tap.test('transport.createAssociatedTransport() must succeed', { timeout: 1000 } ...@@ -18,6 +18,7 @@ tap.test('transport.createAssociatedTransport() must succeed', { timeout: 1000 }
{ {
t.pass('peer.createTransport() succeeded'); t.pass('peer.createTransport() succeeded');
t.equal(transport.iceComponent, 'RTP', 'transport must have "RTP" `iceComponent`'); t.equal(transport.iceComponent, 'RTP', 'transport must have "RTP" `iceComponent`');
t.equal(transport.dtlsState, 'new', 'transport must have "new" `dtlsState`');
transport.iceLocalCandidates.forEach((candidate) => transport.iceLocalCandidates.forEach((candidate) =>
{ {
...@@ -31,6 +32,7 @@ tap.test('transport.createAssociatedTransport() must succeed', { timeout: 1000 } ...@@ -31,6 +32,7 @@ tap.test('transport.createAssociatedTransport() must succeed', { timeout: 1000 }
{ {
t.pass('transport.createAssociatedTransport() succeeded'); t.pass('transport.createAssociatedTransport() succeeded');
t.equal(associatedTransport.iceComponent, 'RTCP', 'associated transport must have "RTCP" `iceComponent`'); t.equal(associatedTransport.iceComponent, 'RTCP', 'associated transport must have "RTCP" `iceComponent`');
t.equal(associatedTransport.dtlsState, 'new', 'associated transport must have "new" `dtlsState`');
associatedTransport.iceLocalCandidates.forEach((candidate) => associatedTransport.iceLocalCandidates.forEach((candidate) =>
{ {
...@@ -39,6 +41,15 @@ tap.test('transport.createAssociatedTransport() must succeed', { timeout: 1000 } ...@@ -39,6 +41,15 @@ tap.test('transport.createAssociatedTransport() must succeed', { timeout: 1000 }
}); });
t.pass('associated transport just contains "udp" candidates'); t.pass('associated transport just contains "udp" candidates');
associatedTransport.createAssociatedTransport()
.then(() =>
{
t.fail('associatedTransport.createAssociatedTransport() succeeded');
})
.catch((error) =>
{
t.pass(`associatedTransport.createAssociatedTransport() failed: ${error}`);
peer.dump() peer.dump()
.then((data) => .then((data) =>
{ {
...@@ -47,6 +58,7 @@ tap.test('transport.createAssociatedTransport() must succeed', { timeout: 1000 } ...@@ -47,6 +58,7 @@ tap.test('transport.createAssociatedTransport() must succeed', { timeout: 1000 }
t.end(); t.end();
}) })
.catch((error) => t.fail(`peer.dump() failed: ${error}`)); .catch((error) => t.fail(`peer.dump() failed: ${error}`));
});
}) })
.catch((error) => t.fail(`transport.createAssociatedTransport() failed: ${error}`)); .catch((error) => t.fail(`transport.createAssociatedTransport() failed: ${error}`));
}) })
...@@ -99,7 +111,7 @@ tap.test('transport.setRemoteDtlsParameters() with "server" `role` must succeed' ...@@ -99,7 +111,7 @@ tap.test('transport.setRemoteDtlsParameters() with "server" `role` must succeed'
.then((transport) => .then((transport) =>
{ {
t.pass('peer.createTransport() succeeded'); t.pass('peer.createTransport() succeeded');
t.equal(transport.dtlsLocalParameters.role, 'server', 'default local DTLS `role` must be "server"'); t.equal(transport.dtlsLocalParameters.role, 'auto', 'default local DTLS `role` must be "auto"');
transport.setRemoteDtlsParameters( transport.setRemoteDtlsParameters(
{ {
...@@ -239,7 +251,7 @@ tap.test('transport.setRemoteDtlsParameters() with invalid `role` must fail', { ...@@ -239,7 +251,7 @@ tap.test('transport.setRemoteDtlsParameters() with invalid `role` must fail', {
.catch((error) => .catch((error) =>
{ {
t.pass(`transport.createAssociatedTransport() failed: ${error}`); t.pass(`transport.createAssociatedTransport() failed: ${error}`);
t.equal(transport.dtlsLocalParameters.role, 'server', 'local DTLS `role` must be "server"'); t.equal(transport.dtlsLocalParameters.role, 'auto', 'local DTLS `role` must be "auto"');
t.end(); t.end();
}); });
}) })
...@@ -268,7 +280,7 @@ tap.test('transport.setRemoteDtlsParameters() without `fingerprint` must fail', ...@@ -268,7 +280,7 @@ tap.test('transport.setRemoteDtlsParameters() without `fingerprint` must fail',
.catch((error) => .catch((error) =>
{ {
t.pass(`transport.createAssociatedTransport() failed: ${error}`); t.pass(`transport.createAssociatedTransport() failed: ${error}`);
t.equal(transport.dtlsLocalParameters.role, 'server', 'local DTLS `role` must be "server"'); t.equal(transport.dtlsLocalParameters.role, 'auto', 'local DTLS `role` must be "auto"');
t.end(); t.end();
}); });
}) })
......
...@@ -8,6 +8,14 @@ ...@@ -8,6 +8,14 @@
window.localStorage.setItem('debug', '* -engine* -socket*'); window.localStorage.setItem('debug', '* -engine* -socket*');
</script> </script>
<script type="text/javascript" src="mediasoup-tester.js"></script> <script type="text/javascript" src="mediasoup-tester.js"></script>
<style>
body
{
background-color: magenta;
height: 100%;
}
</style>
</head> </head>
<body> <body>
......
...@@ -31,7 +31,14 @@ class Peer extends EventEmitter ...@@ -31,7 +31,14 @@ class Peer extends EventEmitter
this._pc = new rtcninja.RTCPeerConnection({ iceServers: [] }); this._pc = new rtcninja.RTCPeerConnection({ iceServers: [] });
// TODO: TMP // TODO: TMP
global.PROTOO = this._protoo;
global.PC = this._pc; global.PC = this._pc;
global.close = () =>
{
this._protoo.close();
this._pc.close();
};
document.addEventListener('click', () => global.close());
} }
testTransport() testTransport()
......
...@@ -135,7 +135,15 @@ app.put('/test-transport', function(req) ...@@ -135,7 +135,15 @@ app.put('/test-transport', function(req)
let transportPromises = []; let transportPromises = [];
answer.version = 0; answer.version = 0;
answer.origin = offer.origin; answer.origin =
{
address : '0.0.0.0',
ipVer : offer.origin.ipVer,
netType : offer.origin.netType,
sessionId : offer.origin.sessionId,
sessionVersion : offer.origin.sessionVersion,
username : 'mediasoup'
};
answer.name = 'mediasoup'; answer.name = 'mediasoup';
answer.timing = { start: 0, stop: 0 }; answer.timing = { start: 0, stop: 0 };
answer.groups = offer.groups; answer.groups = offer.groups;
...@@ -158,7 +166,7 @@ app.put('/test-transport', function(req) ...@@ -158,7 +166,7 @@ app.put('/test-transport', function(req)
debug('/test-transport [numTransports:%d]', numTransports); debug('/test-transport [numTransports:%d]', numTransports);
// Create transports promises // Create transports promises
for (let i = 0; i < numTransports ; i++) for (let i = 0; i < numTransports; i++)
{ {
let promise = mediaPeer.createTransport({ udp: true, tcp: false }); let promise = mediaPeer.createTransport({ udp: true, tcp: false });
...@@ -212,6 +220,7 @@ app.put('/test-transport', function(req) ...@@ -212,6 +220,7 @@ app.put('/test-transport', function(req)
ac.type = candidate.type; ac.type = candidate.type;
if (candidate.tcpType) if (candidate.tcpType)
ac.tcpType = candidate.tcpType; ac.tcpType = candidate.tcpType;
am.candidates.push(ac); am.candidates.push(ac);
}); });
...@@ -243,7 +252,7 @@ app.put('/test-transport', function(req) ...@@ -243,7 +252,7 @@ app.put('/test-transport', function(req)
// Create a promise // Create a promise
let promise = transport.setRemoteDtlsParameters( let promise = transport.setRemoteDtlsParameters(
{ {
role : 'auto', // SDP offer MUST always have a=setup:actpass so we can choose whatever we want role : 'client', // SDP offer MUST always have a=setup:actpass so we can choose whatever we want
fingerprint : fingerprint :
{ {
algorithm : remoteFingerprint.type, algorithm : remoteFingerprint.type,
...@@ -283,9 +292,9 @@ app.put('/test-transport', function(req) ...@@ -283,9 +292,9 @@ app.put('/test-transport', function(req)
}); });
}); });
setTimeout(() => setInterval(() =>
{ {
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')))
.catch((error) => debugerror('SERVER DUMP ERROR: [status:%s, error:"%s"]', error.status, error)); .catch((error) => debugerror('SERVER DUMP ERROR: [status:%s, error:"%s"]', error.status, error));
}, 10000); }, 20000);
...@@ -55,15 +55,26 @@ namespace RTC ...@@ -55,15 +55,26 @@ namespace RTC
class Listener class Listener
{ {
public: public:
// NOTE: The caller MUST NOT call Reset() or Close() during the // DTLS is in the process of negotiating a secure connection. Incoming
// onOutgoingDTLSData() callback. // media can flow through.
virtual void onOutgoingDTLSData(DTLSTransport* dtlsTransport, const MS_BYTE* data, size_t len) = 0; // NOTE: The caller MUST NOT call any method during this callback.
// NOTE: The caller MUST NOT call any method during the onDTLSConnected, virtual void onDTLSConnecting(DTLSTransport* dtlsTransport) = 0;
// onDTLSDisconnected or onDTLSFailed callbacks. // DTLS has completed negotiation of a secure connection (including DTLS-SRTP
virtual void onDTLSConnected(DTLSTransport* dtlsTransport) = 0; // and remote fingerprint verification). Outgoing media can now flow through.
virtual void onDTLSDisconnected(DTLSTransport* dtlsTransport) = 0; // NOTE: TODO
virtual void onDTLSConnected(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;
// The DTLS connection has been closed intentionally via Close().
// NOTE: The caller MUST NOT call any method during this callback.
virtual void onDTLSClosed(DTLSTransport* dtlsTransport) = 0;
// 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).
// NOTE: The caller MUST NOT call Close() during this callback.
virtual void onDTLSFailed(DTLSTransport* dtlsTransport) = 0; virtual void onDTLSFailed(DTLSTransport* dtlsTransport) = 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; // Need to send DTLS data to the peer.
// NOTE: The caller MUST NOT call Close() during this callback.
virtual void onOutgoingDTLSData(DTLSTransport* dtlsTransport, const MS_BYTE* data, size_t len) = 0;
// DTLS application data received.
// NOTE: The caller MUST NOT call Close() during this callback.
virtual void onDTLSApplicationData(DTLSTransport* dtlsTransport, const MS_BYTE* data, size_t len) = 0; virtual void onDTLSApplicationData(DTLSTransport* dtlsTransport, const MS_BYTE* data, size_t len) = 0;
}; };
...@@ -71,7 +82,7 @@ namespace RTC ...@@ -71,7 +82,7 @@ namespace RTC
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 Role StringToRole(std::string role);
static FingerprintAlgorithm GetFingerprintAlgorithm(std::string fingerprint); 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);
...@@ -96,23 +107,22 @@ namespace RTC ...@@ -96,23 +107,22 @@ namespace RTC
virtual ~DTLSTransport(); virtual ~DTLSTransport();
void Close(); void Close();
void Reset();
void Dump(); void Dump();
void Run(Role localRole); void Run(Role localRole);
void SetRemoteFingerprint(Fingerprint fingerprint); void SetRemoteFingerprint(Fingerprint fingerprint);
void ProcessDTLSData(const MS_BYTE* data, size_t len); void ProcessDTLSData(const MS_BYTE* data, size_t len);
bool IsRunning(); Role GetLocalRole();
bool IsConnected();
void SendApplicationData(const MS_BYTE* data, size_t len); void SendApplicationData(const MS_BYTE* data, size_t len);
private: private:
void Reset();
bool CheckStatus(int return_code); bool CheckStatus(int return_code);
void SendPendingOutgoingDTLSData(); void SendPendingOutgoingDTLSData();
void SetTimeout(); bool SetTimeout();
void ProcessHandshake(); void ProcessHandshake();
bool CheckRemoteFingerprint(); bool CheckRemoteFingerprint();
RTC::SRTPSession::SRTPProfile GetNegotiatedSRTPProfile();
void ExtractSRTPKeys(RTC::SRTPSession::SRTPProfile srtp_profile); void ExtractSRTPKeys(RTC::SRTPSession::SRTPProfile srtp_profile);
RTC::SRTPSession::SRTPProfile GetNegotiatedSRTPProfile();
/* Callbacks fired by OpenSSL events. */ /* Callbacks fired by OpenSSL events. */
public: public:
...@@ -137,9 +147,6 @@ namespace RTC ...@@ -137,9 +147,6 @@ namespace RTC
bool handshakeDone = false; bool handshakeDone = false;
bool handshakeDoneNow = false; bool handshakeDoneNow = false;
bool connected = false; bool connected = false;
bool checkingStatus = false;
bool doReset = false;
bool doClose = false;
}; };
/* Inline static methods. */ /* Inline static methods. */
...@@ -151,7 +158,7 @@ namespace RTC ...@@ -151,7 +158,7 @@ namespace RTC
} }
inline inline
DTLSTransport::Role DTLSTransport::GetRole(std::string role) DTLSTransport::Role DTLSTransport::StringToRole(std::string role)
{ {
auto it = DTLSTransport::string2Role.find(role); auto it = DTLSTransport::string2Role.find(role);
...@@ -186,15 +193,9 @@ namespace RTC ...@@ -186,15 +193,9 @@ namespace RTC
/* Inline instance methods. */ /* Inline instance methods. */
inline inline
bool DTLSTransport::IsRunning() DTLSTransport::Role DTLSTransport::GetLocalRole()
{
return this->running;
}
inline
bool DTLSTransport::IsConnected()
{ {
return this->connected; return this->localRole;
} }
} }
......
...@@ -38,6 +38,16 @@ namespace RTC ...@@ -38,6 +38,16 @@ namespace RTC
RTCP = 2 RTCP = 2
}; };
private:
enum class DtlsTransportState
{
NEW = 1,
CONNECTING,
CONNECTED,
CLOSED,
FAILED
};
private: private:
static size_t maxSources; static size_t maxSources;
...@@ -53,10 +63,12 @@ namespace RTC ...@@ -53,10 +63,12 @@ namespace RTC
Transport* CreateAssociatedTransport(unsigned int transportId); Transport* CreateAssociatedTransport(unsigned int transportId);
private: private:
void Terminate();
bool IsAlive();
int SetSendingSource(RTC::TransportSource* source); int SetSendingSource(RTC::TransportSource* source);
int IsValidSource(RTC::TransportSource* source); int IsValidSource(RTC::TransportSource* source);
bool RemoveSource(RTC::TransportSource* source); bool RemoveSource(RTC::TransportSource* source);
void RunDTLSTransportIfReady(); void MayRunDTLSTransport();
/* Private methods to unify UDP and TCP behavior. */ /* Private methods to unify UDP and TCP behavior. */
private: private:
...@@ -90,16 +102,18 @@ namespace RTC ...@@ -90,16 +102,18 @@ namespace RTC
/* Pure virtual methods inherited from RTC::DTLSTransport::Listener. */ /* Pure virtual methods inherited from RTC::DTLSTransport::Listener. */
public: public:
virtual void onDTLSConnecting(DTLSTransport* dtlsTransport) override;
virtual void onDTLSConnected(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 onDTLSClosed(DTLSTransport* dtlsTransport) override;
virtual void onDTLSFailed(DTLSTransport* dtlsTransport) override;
virtual void onOutgoingDTLSData(RTC::DTLSTransport* dtlsTransport, const MS_BYTE* data, size_t len) override; 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; 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;
protected:
// Others. // Others.
bool hasIPv4udp = false; bool hasIPv4udp = false;
bool hasIPv6udp = false; bool hasIPv6udp = false;
...@@ -124,12 +138,25 @@ namespace RTC ...@@ -124,12 +138,25 @@ namespace RTC
bool icePaired = false; bool icePaired = false;
bool icePairedWithUseCandidate = false; bool icePairedWithUseCandidate = false;
// Others (DTLS). // Others (DTLS).
DtlsTransportState dtlsState = DtlsTransportState::NEW;
bool remoteDtlsParametersGiven = false; bool remoteDtlsParametersGiven = false;
RTC::DTLSTransport::Role dtlsLocalRole = RTC::DTLSTransport::Role::SERVER; RTC::DTLSTransport::Role dtlsLocalRole = RTC::DTLSTransport::Role::AUTO;
}; };
/* Inline methods. */ /* Inline methods. */
inline
bool Transport::IsAlive()
{
if (this->dtlsState == DtlsTransportState::CLOSED ||
this->dtlsState == DtlsTransportState::FAILED)
{
return false;
}
return true;
}
inline inline
std::string& Transport::GetIceUsernameFragment() std::string& Transport::GetIceUsernameFragment()
{ {
......
...@@ -25,13 +25,13 @@ ...@@ -25,13 +25,13 @@
do \ do \
{ \ { \
if (ERR_peek_error() == 0) \ if (ERR_peek_error() == 0) \
MS_ERROR("OpenSSL error | " desc); \ MS_ERROR("OpenSSL error [desc:'%s']", desc); \
else \ else \
{ \ { \
unsigned long err; \ unsigned long err; \
while ((err = ERR_get_error()) != 0) \ while ((err = ERR_get_error()) != 0) \
{ \ { \
MS_ERROR("OpenSSL error | " desc ": %s", ERR_error_string(err, nullptr)); \ MS_ERROR("OpenSSL error [desc:'%s', error:'%s']", desc, ERR_error_string(err, nullptr)); \
} \ } \
ERR_clear_error(); \ ERR_clear_error(); \
} \ } \
...@@ -45,7 +45,7 @@ int on_ssl_certificate_verify(int preverify_ok, X509_STORE_CTX* ctx) ...@@ -45,7 +45,7 @@ int on_ssl_certificate_verify(int preverify_ok, X509_STORE_CTX* ctx)
{ {
MS_TRACE(); MS_TRACE();
// Always valid. // Always valid since DTLS certificates are self-signed.
return 1; return 1;
} }
...@@ -209,7 +209,7 @@ namespace RTC ...@@ -209,7 +209,7 @@ namespace RTC
X509_NAME_add_entry_by_txt(cert_name, "O", MBSTRING_ASC, (unsigned char *)MS_APP_NAME, -1, -1, 0); X509_NAME_add_entry_by_txt(cert_name, "O", 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); 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(DTLSTransport::certificate, cert_name); ret = X509_set_issuer_name(DTLSTransport::certificate, cert_name);
if (ret == 0) if (ret == 0)
{ {
...@@ -542,12 +542,6 @@ namespace RTC ...@@ -542,12 +542,6 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (this->checkingStatus)
{
this->doClose = true;
return;
}
if (this->running) if (this->running)
{ {
// Send close alert to the peer. // Send close alert to the peer.
...@@ -555,58 +549,20 @@ namespace RTC ...@@ -555,58 +549,20 @@ namespace RTC
SendPendingOutgoingDTLSData(); SendPendingOutgoingDTLSData();
} }
// Close the DTLS timer.
this->timer->Close(); this->timer->Close();
delete this; // Notify the listener.
} this->listener->onDTLSClosed(this);
void DTLSTransport::Reset()
{
MS_TRACE();
int ret;
this->doReset = false;
if (!this->running)
return;
if (this->checkingStatus)
{
this->doReset = true;
return;
}
MS_DEBUG("resetting DTLS status");
// Stop the DTLS timer.
this->timer->Stop();
// Send close alert to the peer.
SSL_shutdown(this->ssl);
SendPendingOutgoingDTLSData();
this->localRole = Role::NONE;
this->running = false;
this->handshakeDone = false;
this->handshakeDoneNow = false;
this->connected = false;
this->doClose = false;
this->checkingStatus = false;
// Reset SSL status. delete this;
// NOTE: For this to properly work, SSL_shutdown() must be called before.
// NOTE: This may fail if not enough DTLS handshake data has been received.
ret = SSL_clear(this->ssl);
if (ret == 0)
LOG_OPENSSL_ERROR("SSL_clear() failed");
} }
void DTLSTransport::Dump() void DTLSTransport::Dump()
{ {
MS_TRACE(); MS_TRACE();
MS_DEBUG("[role: %s | running: %s | handshake done: %s | connected: %s]", MS_DEBUG("[role:%s, running:%s, handshake done:%s, connected:%s]",
(this->localRole == Role::SERVER ? "server" : (this->localRole == Role::CLIENT ? "client" : "none")), (this->localRole == Role::SERVER ? "server" : (this->localRole == Role::CLIENT ? "client" : "none")),
this->running ? "yes" : "no", this->running ? "yes" : "no",
this->handshakeDone ? "yes" : "no", this->handshakeDone ? "yes" : "no",
...@@ -623,7 +579,7 @@ namespace RTC ...@@ -623,7 +579,7 @@ namespace RTC
if (localRole == previousLocalRole) if (localRole == previousLocalRole)
{ {
MS_DEBUG("same local DTLS role provided, doing nothing"); MS_ERROR("same local DTLS role provided, doing nothing");
return; return;
} }
...@@ -631,7 +587,7 @@ namespace RTC ...@@ -631,7 +587,7 @@ namespace RTC
// If the previous local DTLS role was 'client' or 'server' do reset. // If the previous local DTLS role was 'client' or 'server' do reset.
if (previousLocalRole == Role::CLIENT || previousLocalRole == Role::SERVER) if (previousLocalRole == Role::CLIENT || previousLocalRole == Role::SERVER)
{ {
MS_DEBUG("resetting due to local DTLS role change"); MS_DEBUG("resetting DTLS due to local role change");
Reset(); Reset();
} }
...@@ -641,15 +597,22 @@ namespace RTC ...@@ -641,15 +597,22 @@ namespace RTC
// Set running flag. // Set running flag.
this->running = true; this->running = true;
// Notify the listener.
this->listener->onDTLSConnecting(this);
switch (this->localRole) switch (this->localRole)
{ {
case Role::CLIENT: case Role::CLIENT:
MS_DEBUG("running [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 Role::SERVER: case Role::SERVER:
MS_DEBUG("running [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;
...@@ -707,17 +670,21 @@ namespace RTC ...@@ -707,17 +670,21 @@ namespace RTC
return; return;
// Set/update the DTLS timeout. // Set/update the DTLS timeout.
SetTimeout(); if (!SetTimeout())
return;
// Application data received. Notify to the listener. // Application data received. Notify to the listener.
if (read > 0) if (read > 0)
{ {
if (!this->connected) // It is allowed to receive DTLS data even before validating remote fingerprint.
if (!this->handshakeDone)
{ {
MS_DEBUG("ignoring application data received while DTLS not fully connected"); MS_DEBUG("ignoring application data received while DTLS handshake not done");
return; return;
} }
// Notify the listener.
this->listener->onDTLSApplicationData(this, (MS_BYTE*)DTLSTransport::sslReadBuffer, (size_t)read); this->listener->onDTLSApplicationData(this, (MS_BYTE*)DTLSTransport::sslReadBuffer, (size_t)read);
} }
} }
...@@ -726,15 +693,18 @@ namespace RTC ...@@ -726,15 +693,18 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
// We cannot send data to the peer if its remote fingerprint is not validated.
if (!this->connected) if (!this->connected)
{ {
MS_ERROR("cannot send application data while DTLS is not fully connected"); MS_ERROR("cannot send application data while DTLS is not fully connected");
return; return;
} }
if (len == 0) if (len == 0)
{ {
MS_DEBUG("ignoring 0 length data"); MS_DEBUG("ignoring 0 length data");
return; return;
} }
...@@ -744,17 +714,52 @@ namespace RTC ...@@ -744,17 +714,52 @@ namespace RTC
if (written < 0) if (written < 0)
{ {
LOG_OPENSSL_ERROR("SSL_write() failed"); LOG_OPENSSL_ERROR("SSL_write() failed");
CheckStatus(written); CheckStatus(written);
} }
else if (written != (int)len) else if (written != (int)len)
{ {
MS_ERROR("OpenSSL SSL_write() wrote less (%d bytes) than given data (%zu bytes)", written, len); MS_WARN("OpenSSL SSL_write() wrote less (%d bytes) than given data (%zu bytes)", written, len);
} }
// Send data. // Send data.
SendPendingOutgoingDTLSData(); SendPendingOutgoingDTLSData();
} }
void DTLSTransport::Reset()
{
MS_TRACE();
int ret;
if (!this->running)
return;
MS_DEBUG("resetting DTLS transport");
// Stop the DTLS timer.
this->timer->Stop();
// We need to reset the SSL instance so we need to "shutdown" it, but we don't
// want to send a Close Alert to the peer, so just don't call to
// SendPendingOutgoingDTLSData().
SSL_shutdown(this->ssl);
this->localRole = Role::NONE;
this->running = false;
this->handshakeDone = false;
this->handshakeDoneNow = false;
this->connected = false;
// Reset SSL status.
// NOTE: For this to properly work, SSL_shutdown() must be called before.
// NOTE: This may fail if not enough DTLS handshake data has been received,
// but we don't care so just clear the error queue.
ret = SSL_clear(this->ssl);
if (ret == 0)
ERR_clear_error();
}
inline inline
bool DTLSTransport::CheckStatus(int return_code) bool DTLSTransport::CheckStatus(int return_code)
{ {
...@@ -762,9 +767,6 @@ namespace RTC ...@@ -762,9 +767,6 @@ namespace RTC
int err; int err;
// Set a flag to avoid certain methods to be called while in this method.
this->checkingStatus = true;
err = SSL_get_error(this->ssl, return_code); err = SSL_get_error(this->ssl, return_code);
switch (err) switch (err)
{ {
...@@ -819,35 +821,23 @@ namespace RTC ...@@ -819,35 +821,23 @@ namespace RTC
if (was_connected) if (was_connected)
{ {
MS_DEBUG("DTLS connection disconnected"); MS_DEBUG("DTLS disconnected");
Reset();
// Notify to the listener. // Notify to the listener.
this->listener->onDTLSDisconnected(this); this->listener->onDTLSFailed(this);
} }
else else
{ {
MS_DEBUG("DTLS connection failed"); MS_DEBUG("DTLS connection failed");
Reset();
// Notify to the listener. // Notify to the listener.
this->listener->onDTLSFailed(this); this->listener->onDTLSFailed(this);
} }
// Set Reset flag.
this->doReset = true;
}
// Unset the safe flag.
this->checkingStatus = false;
// Check reset/close flags (note that they may have been set in user callbacks).
if (this->doClose)
{
Close();
return false;
}
else if (this->doReset)
{
Reset();
return false; return false;
} }
...@@ -869,7 +859,7 @@ namespace RTC ...@@ -869,7 +859,7 @@ namespace RTC
MS_DEBUG("%ld bytes of DTLS data ready to sent to the peer", read); MS_DEBUG("%ld bytes of DTLS data ready to sent to the peer", read);
// NOTE: The caller MUST NOT call Reset() or Close() in this callback. // Notify the listener.
this->listener->onOutgoingDTLSData(this, (MS_BYTE*)data, (size_t)read); this->listener->onOutgoingDTLSData(this, (MS_BYTE*)data, (size_t)read);
// Clear the BIO buffer. // Clear the BIO buffer.
...@@ -878,7 +868,7 @@ namespace RTC ...@@ -878,7 +868,7 @@ namespace RTC
} }
inline inline
void DTLSTransport::SetTimeout() bool DTLSTransport::SetTimeout()
{ {
MS_TRACE(); MS_TRACE();
...@@ -890,23 +880,32 @@ namespace RTC ...@@ -890,23 +880,32 @@ namespace RTC
// NOTE: No DTLSv_1_2_get_timeout() or DTLS_get_timeout() in OpenSSL 1.1.0-dev. // NOTE: No DTLSv_1_2_get_timeout() or DTLS_get_timeout() in OpenSSL 1.1.0-dev.
ret = DTLSv1_get_timeout(this->ssl, (void*)&dtls_timeout); ret = DTLSv1_get_timeout(this->ssl, (void*)&dtls_timeout);
if (ret == 0) if (ret == 0)
return; return true;
timeout_ms = (dtls_timeout.tv_sec * (MS_8BYTES)1000) + (dtls_timeout.tv_usec / 1000); timeout_ms = (dtls_timeout.tv_sec * (MS_8BYTES)1000) + (dtls_timeout.tv_usec / 1000);
if (timeout_ms == 0) if (timeout_ms == 0)
{ {
return; return true;
} }
else if (timeout_ms < 30000) else if (timeout_ms < 30000)
{ {
MS_DEBUG("DTLS timer set in %llu ms", (unsigned long long)timeout_ms); MS_DEBUG("DTLS timer set in %llu ms", (unsigned long long)timeout_ms);
this->timer->Start(timeout_ms); this->timer->Start(timeout_ms);
return true;
} }
// NOTE: Don't start the timer again if the timeout is greater than 30 seconds. // NOTE: Don't start the timer again if the timeout is greater than 30 seconds.
else else
{ {
MS_DEBUG("DTLS timeout too high (%llu ms), resetting DTLS status", (unsigned long long)timeout_ms); MS_DEBUG("DTLS timeout too high (%llu ms), resetting DLTS", (unsigned long long)timeout_ms);
Reset(); Reset();
// Notify to the listener.
this->listener->onDTLSFailed(this);
return false;
} }
} }
...@@ -929,20 +928,16 @@ namespace RTC ...@@ -929,20 +928,16 @@ namespace RTC
// Validate the remote fingerprint. // Validate the remote fingerprint.
if (!CheckRemoteFingerprint()) if (!CheckRemoteFingerprint())
{ {
Reset();
// Notify to the listener. // Notify to the listener.
this->listener->onDTLSFailed(this); this->listener->onDTLSFailed(this);
// Reset DTLS.
Reset();
return; return;
} }
this->connected = true; this->connected = true;
// Notify the listener.
this->listener->onDTLSConnected(this);
// Get the negotiated SRTP profile. // Get the negotiated SRTP profile.
RTC::SRTPSession::SRTPProfile srtp_profile; RTC::SRTPSession::SRTPProfile srtp_profile;
srtp_profile = GetNegotiatedSRTPProfile(); srtp_profile = GetNegotiatedSRTPProfile();
...@@ -954,9 +949,14 @@ namespace RTC ...@@ -954,9 +949,14 @@ namespace RTC
} }
else else
{ {
// TODO: this is not an error? // NOTE: We assume that "use_srtp" DTLS extension is required even if
// there is no audio/video.
MS_WARN("SRTP profile not negotiated");
Reset();
MS_DEBUG("SRTP profile not negotiated"); // Notify to the listener.
this->listener->onDTLSFailed(this);
} }
} }
...@@ -977,7 +977,8 @@ namespace RTC ...@@ -977,7 +977,8 @@ namespace RTC
certificate = SSL_get_peer_certificate(this->ssl); certificate = SSL_get_peer_certificate(this->ssl);
if (!certificate) if (!certificate)
{ {
MS_ERROR("no certificate was provided by the peer"); MS_WARN("no certificate was provided by the peer");
return false; return false;
} }
...@@ -1020,47 +1021,16 @@ namespace RTC ...@@ -1020,47 +1021,16 @@ namespace RTC
if (this->remoteFingerprint.value.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.value.c_str()); MS_WARN("fingerprint in the remote certificate (%s) does not match the announced one (%s)", hex_fingerprint, this->remoteFingerprint.value.c_str());
return false; return false;
} }
// TODO: remove
MS_DEBUG("valid remote fingerprint"); MS_DEBUG("valid remote fingerprint");
return true; return true;
} }
inline
RTC::SRTPSession::SRTPProfile DTLSTransport::GetNegotiatedSRTPProfile()
{
MS_TRACE();
RTC::SRTPSession::SRTPProfile negotiated_srtp_profile = RTC::SRTPSession::SRTPProfile::NONE;
// Ensure that the SRTP profile has been negotiated.
SRTP_PROTECTION_PROFILE* ssl_srtp_profile = SSL_get_selected_srtp_profile(this->ssl);
if (!ssl_srtp_profile)
{
return negotiated_srtp_profile;
}
// Get the negotiated SRTP profile.
for (auto it = DTLSTransport::srtpProfiles.begin(); it != DTLSTransport::srtpProfiles.end(); ++it)
{
SrtpProfileMapEntry* profile_entry = &(*it);
if (std::strcmp(ssl_srtp_profile->name, profile_entry->name) == 0)
{
MS_DEBUG("chosen SRTP profile: %s", profile_entry->name);
negotiated_srtp_profile = profile_entry->profile;
}
}
MS_ASSERT(negotiated_srtp_profile != RTC::SRTPSession::SRTPProfile::NONE, "chosen SRTP profile is not an available one");
return negotiated_srtp_profile;
}
inline inline
void DTLSTransport::ExtractSRTPKeys(RTC::SRTPSession::SRTPProfile srtp_profile) void DTLSTransport::ExtractSRTPKeys(RTC::SRTPSession::SRTPProfile srtp_profile)
{ {
...@@ -1105,7 +1075,39 @@ namespace RTC ...@@ -1105,7 +1075,39 @@ namespace RTC
std::memcpy(srtp_remote_master_key + MS_SRTP_MASTER_KEY_LENGTH, srtp_remote_salt, MS_SRTP_MASTER_SALT_LENGTH); std::memcpy(srtp_remote_master_key + MS_SRTP_MASTER_KEY_LENGTH, srtp_remote_salt, MS_SRTP_MASTER_SALT_LENGTH);
// Notify the listener with the SRTP key material. // Notify the listener with the SRTP key material.
this->listener->onSRTPKeyMaterial(this, srtp_profile, srtp_local_master_key, MS_SRTP_MASTER_LENGTH, srtp_remote_master_key, MS_SRTP_MASTER_LENGTH); this->listener->onDTLSConnected(this, srtp_profile, srtp_local_master_key, MS_SRTP_MASTER_LENGTH, srtp_remote_master_key, MS_SRTP_MASTER_LENGTH);
}
inline
RTC::SRTPSession::SRTPProfile DTLSTransport::GetNegotiatedSRTPProfile()
{
MS_TRACE();
RTC::SRTPSession::SRTPProfile negotiated_srtp_profile = RTC::SRTPSession::SRTPProfile::NONE;
// Ensure that the SRTP profile has been negotiated.
SRTP_PROTECTION_PROFILE* ssl_srtp_profile = SSL_get_selected_srtp_profile(this->ssl);
if (!ssl_srtp_profile)
{
return negotiated_srtp_profile;
}
// Get the negotiated SRTP profile.
for (auto it = DTLSTransport::srtpProfiles.begin(); it != DTLSTransport::srtpProfiles.end(); ++it)
{
SrtpProfileMapEntry* profile_entry = &(*it);
if (std::strcmp(ssl_srtp_profile->name, profile_entry->name) == 0)
{
MS_DEBUG("chosen SRTP profile: %s", profile_entry->name);
negotiated_srtp_profile = profile_entry->profile;
}
}
MS_ASSERT(negotiated_srtp_profile != RTC::SRTPSession::SRTPProfile::NONE, "chosen SRTP profile is not an available one");
return negotiated_srtp_profile;
} }
inline inline
...@@ -1122,7 +1124,7 @@ namespace RTC ...@@ -1122,7 +1124,7 @@ namespace RTC
if (where & SSL_CB_LOOP) if (where & SSL_CB_LOOP)
{ {
MS_DEBUG("role: %s | action: %s", role, SSL_state_string_long(this->ssl)); MS_DEBUG("[role:%s, action:'%s']", role, SSL_state_string_long(this->ssl));
} }
else if (where & SSL_CB_ALERT) else if (where & SSL_CB_ALERT)
{ {
...@@ -1145,15 +1147,14 @@ namespace RTC ...@@ -1145,15 +1147,14 @@ namespace RTC
else if (where & SSL_CB_EXIT) else if (where & SSL_CB_EXIT)
{ {
if (ret == 0) if (ret == 0)
MS_DEBUG("role: %s | failed in: %s", role, SSL_state_string_long(this->ssl)); MS_DEBUG("[role:%s, failed:'%s']", role, SSL_state_string_long(this->ssl));
else if (ret < 0) else if (ret < 0)
MS_DEBUG("role: %s | waiting for: %s", role, SSL_state_string_long(this->ssl)); MS_DEBUG("role: %s, waiting:'%s']", role, SSL_state_string_long(this->ssl));
} }
else if (where & SSL_CB_HANDSHAKE_START) else if (where & SSL_CB_HANDSHAKE_START)
{ {
MS_DEBUG("DTLS handshake start"); MS_DEBUG("DTLS handshake start");
} }
else if (where & SSL_CB_HANDSHAKE_DONE) else if (where & SSL_CB_HANDSHAKE_DONE)
{ {
MS_DEBUG("DTLS handshake done"); MS_DEBUG("DTLS handshake done");
...@@ -1172,7 +1173,10 @@ namespace RTC ...@@ -1172,7 +1173,10 @@ namespace RTC
DTLSv1_handle_timeout(this->ssl); DTLSv1_handle_timeout(this->ssl);
// If required, send DTLS data.
SendPendingOutgoingDTLSData(); SendPendingOutgoingDTLSData();
// Set the DTLS timer again.
SetTimeout(); SetTimeout();
} }
} }
...@@ -202,24 +202,18 @@ namespace RTC ...@@ -202,24 +202,18 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (this->iceServer) // Close all the servers.
this->iceServer->Close(); Terminate();
// And also close the DTLSTransport.
if (this->dtlsTransport) if (this->dtlsTransport)
{
this->dtlsTransport->Close(); this->dtlsTransport->Close();
this->dtlsTransport = nullptr;
}
// if (this->srtpRecvSession) // If this was allocated (it did not throw in the constructor) notify the
// this->srtpRecvSession->Close(); // listener and delete it.
// if (this->srtpSendSession)
// this->srtpSendSession->Close();
for (auto socket : this->udpSockets)
socket->Close();
for (auto server : this->tcpServers)
server->Close();
if (this->allocated) if (this->allocated)
{ {
// Notify the listener. // Notify the listener.
...@@ -243,8 +237,15 @@ namespace RTC ...@@ -243,8 +237,15 @@ namespace RTC
static const Json::StaticString k_dtlsLocalParameters("dtlsLocalParameters"); static const Json::StaticString k_dtlsLocalParameters("dtlsLocalParameters");
static const Json::StaticString k_fingerprints("fingerprints"); static const Json::StaticString k_fingerprints("fingerprints");
static const Json::StaticString k_role("role"); 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_client("client");
static const Json::StaticString v_server("server"); static const Json::StaticString v_server("server");
static const Json::StaticString k_dtlsState("dtlsState");
static const Json::StaticString v_new("new");
static const Json::StaticString v_connecting("connecting");
static const Json::StaticString v_connected("connected");
static const Json::StaticString v_closed("closed");
static const Json::StaticString v_failed("failed");
Json::Value data; Json::Value data;
...@@ -271,6 +272,9 @@ namespace RTC ...@@ -271,6 +272,9 @@ namespace RTC
// Add `dtlsLocalParameters.role`. // Add `dtlsLocalParameters.role`.
switch (this->dtlsLocalRole) switch (this->dtlsLocalRole)
{ {
case RTC::DTLSTransport::Role::AUTO:
data[k_dtlsLocalParameters][k_role] = v_auto;
break;
case RTC::DTLSTransport::Role::CLIENT: case RTC::DTLSTransport::Role::CLIENT:
data[k_dtlsLocalParameters][k_role] = v_client; data[k_dtlsLocalParameters][k_role] = v_client;
break; break;
...@@ -281,6 +285,26 @@ namespace RTC ...@@ -281,6 +285,26 @@ namespace RTC
MS_ABORT("invalid local DTLS role"); MS_ABORT("invalid local DTLS role");
} }
// Add `dtlsState`.
switch (this->dtlsState)
{
case DtlsTransportState::NEW:
data[k_dtlsState] = v_new;
break;
case DtlsTransportState::CONNECTING:
data[k_dtlsState] = v_connecting;
break;
case DtlsTransportState::CONNECTED:
data[k_dtlsState] = v_connected;
break;
case DtlsTransportState::CLOSED:
data[k_dtlsState] = v_closed;
break;
case DtlsTransportState::FAILED:
data[k_dtlsState] = v_failed;
break;
}
return data; return data;
} }
...@@ -324,6 +348,14 @@ namespace RTC ...@@ -324,6 +348,14 @@ namespace RTC
RTC::DTLSTransport::Fingerprint remoteFingerprint; RTC::DTLSTransport::Fingerprint remoteFingerprint;
RTC::DTLSTransport::Role remoteRole = RTC::DTLSTransport::Role::AUTO; // Default value if missing. RTC::DTLSTransport::Role remoteRole = RTC::DTLSTransport::Role::AUTO; // Default value if missing.
if (!IsAlive())
{
MS_ERROR("Transport not alive");
request->Reject(500, "Transport not alive");
return;
}
// Ensure this method is not called twice. // Ensure this method is not called twice.
if (this->remoteDtlsParametersGiven) if (this->remoteDtlsParametersGiven)
{ {
...@@ -366,7 +398,7 @@ namespace RTC ...@@ -366,7 +398,7 @@ namespace RTC
remoteFingerprint.value = request->data[k_fingerprint][k_value].asString(); remoteFingerprint.value = request->data[k_fingerprint][k_value].asString();
if (request->data[k_role].isString()) if (request->data[k_role].isString())
remoteRole = RTC::DTLSTransport::GetRole(request->data[k_role].asString()); remoteRole = RTC::DTLSTransport::StringToRole(request->data[k_role].asString());
// Set local DTLS role. // Set local DTLS role.
switch (remoteRole) switch (remoteRole)
...@@ -377,8 +409,7 @@ namespace RTC ...@@ -377,8 +409,7 @@ namespace RTC
case RTC::DTLSTransport::Role::SERVER: case RTC::DTLSTransport::Role::SERVER:
this->dtlsLocalRole = RTC::DTLSTransport::Role::CLIENT; this->dtlsLocalRole = RTC::DTLSTransport::Role::CLIENT;
break; break;
// If the peer has "auto" role let us become "client" so DTLS // If the peer has "auto" we become "client" since we are ICE controlled.
// happens faster.
case RTC::DTLSTransport::Role::AUTO: case RTC::DTLSTransport::Role::AUTO:
this->dtlsLocalRole = RTC::DTLSTransport::Role::CLIENT; this->dtlsLocalRole = RTC::DTLSTransport::Role::CLIENT;
break; break;
...@@ -405,11 +436,11 @@ namespace RTC ...@@ -405,11 +436,11 @@ namespace RTC
request->Accept(data); request->Accept(data);
// Pass the remote fingerprint to the DTLS transport. // Pass the remote fingerprint to the DTLS transport-
this->dtlsTransport->SetRemoteFingerprint(remoteFingerprint); this->dtlsTransport->SetRemoteFingerprint(remoteFingerprint);
// Run the DTLS transport if ready. // Run the DTLS transport if ready.
RunDTLSTransportIfReady(); MayRunDTLSTransport();
break; break;
} }
...@@ -421,12 +452,47 @@ namespace RTC ...@@ -421,12 +452,47 @@ namespace RTC
} }
} }
// This closes all the server but not the DTLSTransport.
void Transport::Terminate()
{
MS_TRACE();
if (this->iceServer)
{
this->iceServer->Close();
this->iceServer = nullptr;
}
// if (this->srtpRecvSession)
// {
// this->srtpRecvSession->Close();
// this->srtpRecvSession = nullptr;
// }
// if (this->srtpSendSession)
// {
// this->srtpSendSession->Close();
// this->srtpSendSession = nullptr;
// }
for (auto socket : this->udpSockets)
socket->Close();
this->udpSockets.clear();
for (auto server : this->tcpServers)
server->Close();
this->tcpServers.clear();
}
Transport* Transport::CreateAssociatedTransport(unsigned int transportId) Transport* Transport::CreateAssociatedTransport(unsigned int transportId)
{ {
MS_TRACE(); MS_TRACE();
static Json::Value nullData(Json::nullValue); static Json::Value nullData(Json::nullValue);
if (!IsAlive())
MS_THROW_ERROR("cannot call CreateAssociatedTransport() on a non alive Transport");
if (this->iceComponent != IceComponent::RTP) if (this->iceComponent != IceComponent::RTP)
MS_THROW_ERROR("cannot call CreateAssociatedTransport() on a RTCP Transport"); MS_THROW_ERROR("cannot call CreateAssociatedTransport() on a RTCP Transport");
...@@ -434,12 +500,32 @@ namespace RTC ...@@ -434,12 +500,32 @@ namespace RTC
} }
inline inline
void Transport::RunDTLSTransportIfReady() void Transport::MayRunDTLSTransport()
{ {
MS_TRACE(); MS_TRACE();
// Do nothing if we have the same local DTLS role as the DTLS transport.
// NOTE: local role in DTLS transport can be NONE, but not ours.
if (this->dtlsTransport->GetLocalRole() == this->dtlsLocalRole)
return;
// Check our local DTLS role.
switch (this->dtlsLocalRole) switch (this->dtlsLocalRole)
{ {
// If still 'auto' then transition to 'server' if ICE is complete (with or
// without UseCandidate).
case RTC::DTLSTransport::Role::AUTO:
if (this->icePaired)
{
MS_DEBUG("transition from local 'auto' role to 'server' and running DTLS transport");
this->dtlsLocalRole = RTC::DTLSTransport::Role::SERVER;
this->dtlsTransport->Run(RTC::DTLSTransport::Role::SERVER);
}
break;
// 'client' is only set if a 'setRemoteDtlsParameters' request was previously
// received with remote DTLS role 'server'.
// If 'client' then wait for the first Binding with USE-CANDIDATE. // If 'client' then wait for the first Binding with USE-CANDIDATE.
case RTC::DTLSTransport::Role::CLIENT: case RTC::DTLSTransport::Role::CLIENT:
if (this->icePairedWithUseCandidate) if (this->icePairedWithUseCandidate)
...@@ -460,9 +546,6 @@ namespace RTC ...@@ -460,9 +546,6 @@ namespace RTC
} }
break; break;
case RTC::DTLSTransport::Role::AUTO:
MS_ABORT("local DTLS role cannot be 'auto'");
case RTC::DTLSTransport::Role::NONE: case RTC::DTLSTransport::Role::NONE:
MS_ABORT("local DTLS role not set"); MS_ABORT("local DTLS role not set");
} }
...@@ -498,7 +581,9 @@ namespace RTC ...@@ -498,7 +581,9 @@ namespace RTC
return; return;
} }
if (this->dtlsTransport->IsRunning()) // Check that DTLS status is 'connecting' or 'connected'.
if (this->dtlsState == DtlsTransportState::CONNECTING ||
this->dtlsState == DtlsTransportState::CONNECTED)
{ {
MS_DEBUG("DTLS data received, passing it to the DTLS transport"); MS_DEBUG("DTLS data received, passing it to the DTLS transport");
...@@ -506,7 +591,7 @@ namespace RTC ...@@ -506,7 +591,7 @@ namespace RTC
} }
else else
{ {
MS_DEBUG("DTLSTransport is not running, ignoring received DTLS data"); MS_DEBUG("DTLSTransport is not connecting or conneted, ignoring received DTLS data");
return; return;
} }
...@@ -532,6 +617,9 @@ namespace RTC ...@@ -532,6 +617,9 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (!IsAlive())
return;
RTC::TransportSource source(socket, remote_addr); RTC::TransportSource source(socket, remote_addr);
onSTUNDataRecv(&source, data, len); onSTUNDataRecv(&source, data, len);
} }
...@@ -540,6 +628,9 @@ namespace RTC ...@@ -540,6 +628,9 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (!IsAlive())
return;
RTC::TransportSource source(socket, remote_addr); RTC::TransportSource source(socket, remote_addr);
onDTLSDataRecv(&source, data, len); onDTLSDataRecv(&source, data, len);
} }
...@@ -548,6 +639,9 @@ namespace RTC ...@@ -548,6 +639,9 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (!IsAlive())
return;
RTC::TransportSource source(socket, remote_addr); RTC::TransportSource source(socket, remote_addr);
onRTPDataRecv(&source, data, len); onRTPDataRecv(&source, data, len);
} }
...@@ -556,6 +650,9 @@ namespace RTC ...@@ -556,6 +650,9 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (!IsAlive())
return;
RTC::TransportSource source(socket, remote_addr); RTC::TransportSource source(socket, remote_addr);
onRTCPDataRecv(&source, data, len); onRTCPDataRecv(&source, data, len);
} }
...@@ -564,6 +661,9 @@ namespace RTC ...@@ -564,6 +661,9 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (!IsAlive())
return;
RTC::TransportSource source(connection); RTC::TransportSource source(connection);
if (RemoveSource(&source)) if (RemoveSource(&source))
...@@ -576,6 +676,9 @@ namespace RTC ...@@ -576,6 +676,9 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (!IsAlive())
return;
RTC::TransportSource source(connection); RTC::TransportSource source(connection);
onSTUNDataRecv(&source, data, len); onSTUNDataRecv(&source, data, len);
} }
...@@ -584,6 +687,9 @@ namespace RTC ...@@ -584,6 +687,9 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (!IsAlive())
return;
RTC::TransportSource source(connection); RTC::TransportSource source(connection);
onDTLSDataRecv(&source, data, len); onDTLSDataRecv(&source, data, len);
} }
...@@ -600,6 +706,9 @@ namespace RTC ...@@ -600,6 +706,9 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (!IsAlive())
return;
RTC::TransportSource source(connection); RTC::TransportSource source(connection);
onRTCPDataRecv(&source, data, len); onRTCPDataRecv(&source, data, len);
} }
...@@ -608,6 +717,9 @@ namespace RTC ...@@ -608,6 +717,9 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (!IsAlive())
return;
// Send the STUN response over the same transport source. // Send the STUN response over the same transport source.
source->Send(msg->GetRaw(), msg->GetLength()); source->Send(msg->GetRaw(), msg->GetLength());
} }
...@@ -616,6 +728,9 @@ namespace RTC ...@@ -616,6 +728,9 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (!IsAlive())
return;
/* /*
* RFC 5245 section 11.2 "Receiving Media": * RFC 5245 section 11.2 "Receiving Media":
* *
...@@ -645,41 +760,41 @@ namespace RTC ...@@ -645,41 +760,41 @@ namespace RTC
} }
// If ready, run the DTLS handler. // If ready, run the DTLS handler.
RunDTLSTransportIfReady(); MayRunDTLSTransport();
} }
void Transport::onOutgoingDTLSData(RTC::DTLSTransport* dtlsTransport, const MS_BYTE* data, size_t len) void Transport::onDTLSConnecting(RTC::DTLSTransport* dtlsTransport)
{ {
MS_TRACE(); MS_TRACE();
if (!this->sendingSource) MS_DEBUG("DTLS connecting");
{
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); this->dtlsState = DtlsTransportState::CONNECTING;
} }
void Transport::onDTLSConnected(RTC::DTLSTransport* dtlsTransport) void Transport::onDTLSConnected(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_TRACE();
MS_DEBUG("DTLS connected"); MS_DEBUG("DTLS connected");
this->dtlsState = DtlsTransportState::CONNECTED;
// TODO
// SetLocalSRTPKey(srtp_profile, srtp_local_key, srtp_local_key_len);
// SetRemoteSRTPKey(srtp_profile, srtp_remote_key, srtp_remote_key_len);
} }
void Transport::onDTLSDisconnected(RTC::DTLSTransport* dtlsTransport) void Transport::onDTLSClosed(RTC::DTLSTransport* dtlsTransport)
{ {
MS_TRACE(); MS_TRACE();
MS_DEBUG("DTLS disconnected"); MS_DEBUG("DTLS closed");
// TODO this->dtlsState = DtlsTransportState::CLOSED;
// Reset();
// NOTE: This is just called when calling Close() so don't call
// Terminate() here (not needed).
} }
void Transport::onDTLSFailed(RTC::DTLSTransport* dtlsTransport) void Transport::onDTLSFailed(RTC::DTLSTransport* dtlsTransport)
...@@ -688,19 +803,27 @@ namespace RTC ...@@ -688,19 +803,27 @@ namespace RTC
MS_DEBUG("DTLS failed"); MS_DEBUG("DTLS failed");
// TODO this->dtlsState = DtlsTransportState::FAILED;
// Reset();
// Call Terminate() so all the servers are closed.
Terminate();
} }
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) void Transport::onOutgoingDTLSData(RTC::DTLSTransport* dtlsTransport, const MS_BYTE* data, size_t len)
{ {
MS_TRACE(); MS_TRACE();
MS_DEBUG("got SRTP key material"); if (!this->sendingSource)
{
MS_DEBUG("no sending address set, cannot send DTLS packet");
return;
}
// TODO // TODO: remove
// SetLocalSRTPKey(srtp_profile, srtp_local_key, srtp_local_key_len); MS_DEBUG("sending DTLS data to to:");
// SetRemoteSRTPKey(srtp_profile, srtp_remote_key, srtp_remote_key_len); this->sendingSource->Dump();
this->sendingSource->Send(data, len);
} }
void Transport::onDTLSApplicationData(RTC::DTLSTransport* dtlsTransport, const MS_BYTE* data, size_t len) void Transport::onDTLSApplicationData(RTC::DTLSTransport* dtlsTransport, const MS_BYTE* data, size_t len)
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论