提交 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
return this._data.dtlsLocalParameters;
}
get dtlsState()
{
return this._data.dtlsState;
}
/**
* Close the Transport
*/
......
......@@ -18,6 +18,7 @@ tap.test('transport.createAssociatedTransport() must succeed', { timeout: 1000 }
{
t.pass('peer.createTransport() succeeded');
t.equal(transport.iceComponent, 'RTP', 'transport must have "RTP" `iceComponent`');
t.equal(transport.dtlsState, 'new', 'transport must have "new" `dtlsState`');
transport.iceLocalCandidates.forEach((candidate) =>
{
......@@ -31,6 +32,7 @@ tap.test('transport.createAssociatedTransport() must succeed', { timeout: 1000 }
{
t.pass('transport.createAssociatedTransport() succeeded');
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) =>
{
......@@ -39,14 +41,24 @@ tap.test('transport.createAssociatedTransport() must succeed', { timeout: 1000 }
});
t.pass('associated transport just contains "udp" candidates');
peer.dump()
.then((data) =>
associatedTransport.createAssociatedTransport()
.then(() =>
{
t.pass('peer.dump() succeeded');
t.equal(Object.keys(data.transports).length, 2, 'peer.dump() should retrieve two transports');
t.end();
t.fail('associatedTransport.createAssociatedTransport() succeeded');
})
.catch((error) => t.fail(`peer.dump() failed: ${error}`));
.catch((error) =>
{
t.pass(`associatedTransport.createAssociatedTransport() failed: ${error}`);
peer.dump()
.then((data) =>
{
t.pass('peer.dump() succeeded');
t.equal(Object.keys(data.transports).length, 2, 'peer.dump() should retrieve two transports');
t.end();
})
.catch((error) => t.fail(`peer.dump() failed: ${error}`));
});
})
.catch((error) => t.fail(`transport.createAssociatedTransport() failed: ${error}`));
})
......@@ -99,7 +111,7 @@ tap.test('transport.setRemoteDtlsParameters() with "server" `role` must succeed'
.then((transport) =>
{
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(
{
......@@ -239,7 +251,7 @@ tap.test('transport.setRemoteDtlsParameters() with invalid `role` must fail', {
.catch((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();
});
})
......@@ -262,13 +274,13 @@ tap.test('transport.setRemoteDtlsParameters() without `fingerprint` must fail',
transport.setRemoteDtlsParameters(
{
role : 'server'
role : 'server'
})
.then(() => t.fail('transport.setRemoteDtlsParameters() succeeded'))
.catch((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();
});
})
......
......@@ -8,6 +8,14 @@
window.localStorage.setItem('debug', '* -engine* -socket*');
</script>
<script type="text/javascript" src="mediasoup-tester.js"></script>
<style>
body
{
background-color: magenta;
height: 100%;
}
</style>
</head>
<body>
......
......@@ -31,7 +31,14 @@ class Peer extends EventEmitter
this._pc = new rtcninja.RTCPeerConnection({ iceServers: [] });
// TODO: TMP
global.PROTOO = this._protoo;
global.PC = this._pc;
global.close = () =>
{
this._protoo.close();
this._pc.close();
};
document.addEventListener('click', () => global.close());
}
testTransport()
......
......@@ -135,7 +135,15 @@ app.put('/test-transport', function(req)
let transportPromises = [];
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.timing = { start: 0, stop: 0 };
answer.groups = offer.groups;
......@@ -158,7 +166,7 @@ app.put('/test-transport', function(req)
debug('/test-transport [numTransports:%d]', numTransports);
// 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 });
......@@ -212,6 +220,7 @@ app.put('/test-transport', function(req)
ac.type = candidate.type;
if (candidate.tcpType)
ac.tcpType = candidate.tcpType;
am.candidates.push(ac);
});
......@@ -243,7 +252,7 @@ app.put('/test-transport', function(req)
// Create a promise
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 :
{
algorithm : remoteFingerprint.type,
......@@ -283,9 +292,9 @@ app.put('/test-transport', function(req)
});
});
setTimeout(() =>
setInterval(() =>
{
room.dump()
.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));
}, 10000);
}, 20000);
......@@ -55,15 +55,26 @@ namespace RTC
class Listener
{
public:
// NOTE: The caller MUST NOT call Reset() or Close() during the
// onOutgoingDTLSData() callback.
virtual void onOutgoingDTLSData(DTLSTransport* dtlsTransport, const MS_BYTE* data, size_t len) = 0;
// NOTE: The caller MUST NOT call any method during the onDTLSConnected,
// onDTLSDisconnected or onDTLSFailed callbacks.
virtual void onDTLSConnected(DTLSTransport* dtlsTransport) = 0;
virtual void onDTLSDisconnected(DTLSTransport* dtlsTransport) = 0;
// DTLS is in the process of negotiating a secure connection. Incoming
// media can flow through.
// NOTE: The caller MUST NOT call any method during this callback.
virtual void onDTLSConnecting(DTLSTransport* dtlsTransport) = 0;
// DTLS has completed negotiation of a secure connection (including DTLS-SRTP
// and remote fingerprint verification). Outgoing media can now flow through.
// 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 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;
};
......@@ -71,7 +82,7 @@ namespace RTC
static void ClassInit();
static void ClassDestroy();
static Json::Value& GetLocalFingerprints();
static Role GetRole(std::string role);
static Role StringToRole(std::string role);
static FingerprintAlgorithm GetFingerprintAlgorithm(std::string fingerprint);
static bool IsDTLS(const MS_BYTE* data, size_t len);
......@@ -96,23 +107,22 @@ namespace RTC
virtual ~DTLSTransport();
void Close();
void Reset();
void Dump();
void Run(Role localRole);
void SetRemoteFingerprint(Fingerprint fingerprint);
void ProcessDTLSData(const MS_BYTE* data, size_t len);
bool IsRunning();
bool IsConnected();
Role GetLocalRole();
void SendApplicationData(const MS_BYTE* data, size_t len);
private:
void Reset();
bool CheckStatus(int return_code);
void SendPendingOutgoingDTLSData();
void SetTimeout();
bool SetTimeout();
void ProcessHandshake();
bool CheckRemoteFingerprint();
RTC::SRTPSession::SRTPProfile GetNegotiatedSRTPProfile();
void ExtractSRTPKeys(RTC::SRTPSession::SRTPProfile srtp_profile);
RTC::SRTPSession::SRTPProfile GetNegotiatedSRTPProfile();
/* Callbacks fired by OpenSSL events. */
public:
......@@ -137,9 +147,6 @@ namespace RTC
bool handshakeDone = false;
bool handshakeDoneNow = false;
bool connected = false;
bool checkingStatus = false;
bool doReset = false;
bool doClose = false;
};
/* Inline static methods. */
......@@ -151,7 +158,7 @@ namespace RTC
}
inline
DTLSTransport::Role DTLSTransport::GetRole(std::string role)
DTLSTransport::Role DTLSTransport::StringToRole(std::string role)
{
auto it = DTLSTransport::string2Role.find(role);
......@@ -186,15 +193,9 @@ namespace RTC
/* Inline instance methods. */
inline
bool DTLSTransport::IsRunning()
{
return this->running;
}
inline
bool DTLSTransport::IsConnected()
DTLSTransport::Role DTLSTransport::GetLocalRole()
{
return this->connected;
return this->localRole;
}
}
......
......@@ -38,6 +38,16 @@ namespace RTC
RTCP = 2
};
private:
enum class DtlsTransportState
{
NEW = 1,
CONNECTING,
CONNECTED,
CLOSED,
FAILED
};
private:
static size_t maxSources;
......@@ -53,10 +63,12 @@ namespace RTC
Transport* CreateAssociatedTransport(unsigned int transportId);
private:
void Terminate();
bool IsAlive();
int SetSendingSource(RTC::TransportSource* source);
int IsValidSource(RTC::TransportSource* source);
bool RemoveSource(RTC::TransportSource* source);
void RunDTLSTransportIfReady();
void MayRunDTLSTransport();
/* Private methods to unify UDP and TCP behavior. */
private:
......@@ -90,16 +102,18 @@ namespace RTC
/* Pure virtual methods inherited from RTC::DTLSTransport::Listener. */
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 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:
// Passed by argument.
unsigned int transportId;
protected:
// Others.
bool hasIPv4udp = false;
bool hasIPv6udp = false;
......@@ -124,12 +138,25 @@ namespace RTC
bool icePaired = false;
bool icePairedWithUseCandidate = false;
// Others (DTLS).
DtlsTransportState dtlsState = DtlsTransportState::NEW;
bool remoteDtlsParametersGiven = false;
RTC::DTLSTransport::Role dtlsLocalRole = RTC::DTLSTransport::Role::SERVER;
RTC::DTLSTransport::Role dtlsLocalRole = RTC::DTLSTransport::Role::AUTO;
};
/* Inline methods. */
inline
bool Transport::IsAlive()
{
if (this->dtlsState == DtlsTransportState::CLOSED ||
this->dtlsState == DtlsTransportState::FAILED)
{
return false;
}
return true;
}
inline
std::string& Transport::GetIceUsernameFragment()
{
......
......@@ -25,13 +25,13 @@
do \
{ \
if (ERR_peek_error() == 0) \
MS_ERROR("OpenSSL error | " desc); \
MS_ERROR("OpenSSL error [desc:'%s']", desc); \
else \
{ \
unsigned long err; \
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(); \
} \
......@@ -45,7 +45,7 @@ int on_ssl_certificate_verify(int preverify_ok, X509_STORE_CTX* ctx)
{
MS_TRACE();
// Always valid.
// Always valid since DTLS certificates are self-signed.
return 1;
}
......@@ -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, "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);
if (ret == 0)
{
......@@ -542,12 +542,6 @@ namespace RTC
{
MS_TRACE();
if (this->checkingStatus)
{
this->doClose = true;
return;
}
if (this->running)
{
// Send close alert to the peer.
......@@ -555,58 +549,20 @@ namespace RTC
SendPendingOutgoingDTLSData();
}
// Close the DTLS timer.
this->timer->Close();
delete 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;
// Notify the listener.
this->listener->onDTLSClosed(this);
// 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.
ret = SSL_clear(this->ssl);
if (ret == 0)
LOG_OPENSSL_ERROR("SSL_clear() failed");
delete this;
}
void DTLSTransport::Dump()
{
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->running ? "yes" : "no",
this->handshakeDone ? "yes" : "no",
......@@ -623,7 +579,7 @@ namespace RTC
if (localRole == previousLocalRole)
{
MS_DEBUG("same local DTLS role provided, doing nothing");
MS_ERROR("same local DTLS role provided, doing nothing");
return;
}
......@@ -631,7 +587,7 @@ namespace RTC
// If the previous local DTLS role was 'client' or 'server' do reset.
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();
}
......@@ -641,15 +597,22 @@ namespace RTC
// Set running flag.
this->running = true;
// Notify the listener.
this->listener->onDTLSConnecting(this);
switch (this->localRole)
{
case Role::CLIENT:
MS_DEBUG("running [role:client]");
SSL_set_connect_state(this->ssl);
SSL_do_handshake(this->ssl);
SendPendingOutgoingDTLSData();
SetTimeout();
break;
case Role::SERVER:
MS_DEBUG("running [role:server]");
SSL_set_accept_state(this->ssl);
SSL_do_handshake(this->ssl);
break;
......@@ -707,17 +670,21 @@ namespace RTC
return;
// Set/update the DTLS timeout.
SetTimeout();
if (!SetTimeout())
return;
// Application data received. Notify to the listener.
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;
}
// Notify the listener.
this->listener->onDTLSApplicationData(this, (MS_BYTE*)DTLSTransport::sslReadBuffer, (size_t)read);
}
}
......@@ -726,15 +693,18 @@ namespace RTC
{
MS_TRACE();
// We cannot send data to the peer if its remote fingerprint is not validated.
if (!this->connected)
{
MS_ERROR("cannot send application data while DTLS is not fully connected");
return;
}
if (len == 0)
{
MS_DEBUG("ignoring 0 length data");
return;
}
......@@ -744,17 +714,52 @@ namespace RTC
if (written < 0)
{
LOG_OPENSSL_ERROR("SSL_write() failed");
CheckStatus(written);
}
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.
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
bool DTLSTransport::CheckStatus(int return_code)
{
......@@ -762,9 +767,6 @@ namespace RTC
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);
switch (err)
{
......@@ -819,35 +821,23 @@ namespace RTC
if (was_connected)
{
MS_DEBUG("DTLS connection disconnected");
MS_DEBUG("DTLS disconnected");
Reset();
// Notify to the listener.
this->listener->onDTLSDisconnected(this);
this->listener->onDTLSFailed(this);
}
else
{
MS_DEBUG("DTLS connection failed");
Reset();
// Notify to the listener.
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;
}
......@@ -869,7 +859,7 @@ namespace RTC
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);
// Clear the BIO buffer.
......@@ -878,7 +868,7 @@ namespace RTC
}
inline
void DTLSTransport::SetTimeout()
bool DTLSTransport::SetTimeout()
{
MS_TRACE();
......@@ -890,23 +880,32 @@ namespace RTC
// 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);
if (ret == 0)
return;
return true;
timeout_ms = (dtls_timeout.tv_sec * (MS_8BYTES)1000) + (dtls_timeout.tv_usec / 1000);
if (timeout_ms == 0)
{
return;
return true;
}
else if (timeout_ms < 30000)
{
MS_DEBUG("DTLS timer set in %llu ms", (unsigned long long)timeout_ms);
this->timer->Start(timeout_ms);
return true;
}
// NOTE: Don't start the timer again if the timeout is greater than 30 seconds.
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();
// Notify to the listener.
this->listener->onDTLSFailed(this);
return false;
}
}
......@@ -929,20 +928,16 @@ namespace RTC
// Validate the remote fingerprint.
if (!CheckRemoteFingerprint())
{
Reset();
// Notify to the listener.
this->listener->onDTLSFailed(this);
// Reset DTLS.
Reset();
return;
}
this->connected = true;
// Notify the listener.
this->listener->onDTLSConnected(this);
// Get the negotiated SRTP profile.
RTC::SRTPSession::SRTPProfile srtp_profile;
srtp_profile = GetNegotiatedSRTPProfile();
......@@ -954,9 +949,14 @@ namespace RTC
}
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
certificate = SSL_get_peer_certificate(this->ssl);
if (!certificate)
{
MS_ERROR("no certificate was provided by the peer");
MS_WARN("no certificate was provided by the peer");
return false;
}
......@@ -1020,47 +1021,16 @@ namespace RTC
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;
}
// TODO: remove
MS_DEBUG("valid remote fingerprint");
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
void DTLSTransport::ExtractSRTPKeys(RTC::SRTPSession::SRTPProfile srtp_profile)
{
......@@ -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);
// 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
......@@ -1116,13 +1118,13 @@ namespace RTC
int w = where & -SSL_ST_MASK;
const char* role;
if (w & SSL_ST_CONNECT) role = "client";
else if (w & SSL_ST_ACCEPT) role = "server";
else role = "undefined";
if (w & SSL_ST_CONNECT) role = "client";
else if (w & SSL_ST_ACCEPT) role = "server";
else role = "undefined";
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)
{
......@@ -1145,15 +1147,14 @@ namespace RTC
else if (where & SSL_CB_EXIT)
{
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)
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)
{
MS_DEBUG("DTLS handshake start");
}
else if (where & SSL_CB_HANDSHAKE_DONE)
{
MS_DEBUG("DTLS handshake done");
......@@ -1172,7 +1173,10 @@ namespace RTC
DTLSv1_handle_timeout(this->ssl);
// If required, send DTLS data.
SendPendingOutgoingDTLSData();
// Set the DTLS timer again.
SetTimeout();
}
}
......@@ -202,24 +202,18 @@ namespace RTC
{
MS_TRACE();
if (this->iceServer)
this->iceServer->Close();
// Close all the servers.
Terminate();
// And also close the DTLSTransport.
if (this->dtlsTransport)
{
this->dtlsTransport->Close();
this->dtlsTransport = nullptr;
}
// if (this->srtpRecvSession)
// this->srtpRecvSession->Close();
// if (this->srtpSendSession)
// this->srtpSendSession->Close();
for (auto socket : this->udpSockets)
socket->Close();
for (auto server : this->tcpServers)
server->Close();
// If this was allocated (it did not throw in the constructor) notify the
// listener and delete it.
if (this->allocated)
{
// Notify the listener.
......@@ -243,8 +237,15 @@ namespace RTC
static const Json::StaticString k_dtlsLocalParameters("dtlsLocalParameters");
static const Json::StaticString k_fingerprints("fingerprints");
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_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;
......@@ -271,6 +272,9 @@ namespace RTC
// Add `dtlsLocalParameters.role`.
switch (this->dtlsLocalRole)
{
case RTC::DTLSTransport::Role::AUTO:
data[k_dtlsLocalParameters][k_role] = v_auto;
break;
case RTC::DTLSTransport::Role::CLIENT:
data[k_dtlsLocalParameters][k_role] = v_client;
break;
......@@ -281,6 +285,26 @@ namespace RTC
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;
}
......@@ -324,6 +348,14 @@ namespace RTC
RTC::DTLSTransport::Fingerprint remoteFingerprint;
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.
if (this->remoteDtlsParametersGiven)
{
......@@ -366,7 +398,7 @@ namespace RTC
remoteFingerprint.value = request->data[k_fingerprint][k_value].asString();
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.
switch (remoteRole)
......@@ -377,8 +409,7 @@ namespace RTC
case RTC::DTLSTransport::Role::SERVER:
this->dtlsLocalRole = RTC::DTLSTransport::Role::CLIENT;
break;
// If the peer has "auto" role let us become "client" so DTLS
// happens faster.
// If the peer has "auto" we become "client" since we are ICE controlled.
case RTC::DTLSTransport::Role::AUTO:
this->dtlsLocalRole = RTC::DTLSTransport::Role::CLIENT;
break;
......@@ -405,11 +436,11 @@ namespace RTC
request->Accept(data);
// Pass the remote fingerprint to the DTLS transport.
// Pass the remote fingerprint to the DTLS transport-
this->dtlsTransport->SetRemoteFingerprint(remoteFingerprint);
// Run the DTLS transport if ready.
RunDTLSTransportIfReady();
MayRunDTLSTransport();
break;
}
......@@ -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)
{
MS_TRACE();
static Json::Value nullData(Json::nullValue);
if (!IsAlive())
MS_THROW_ERROR("cannot call CreateAssociatedTransport() on a non alive Transport");
if (this->iceComponent != IceComponent::RTP)
MS_THROW_ERROR("cannot call CreateAssociatedTransport() on a RTCP Transport");
......@@ -434,12 +500,32 @@ namespace RTC
}
inline
void Transport::RunDTLSTransportIfReady()
void Transport::MayRunDTLSTransport()
{
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)
{
// 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.
case RTC::DTLSTransport::Role::CLIENT:
if (this->icePairedWithUseCandidate)
......@@ -460,9 +546,6 @@ namespace RTC
}
break;
case RTC::DTLSTransport::Role::AUTO:
MS_ABORT("local DTLS role cannot be 'auto'");
case RTC::DTLSTransport::Role::NONE:
MS_ABORT("local DTLS role not set");
}
......@@ -498,7 +581,9 @@ namespace RTC
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");
......@@ -506,7 +591,7 @@ namespace RTC
}
else
{
MS_DEBUG("DTLSTransport is not running, ignoring received DTLS data");
MS_DEBUG("DTLSTransport is not connecting or conneted, ignoring received DTLS data");
return;
}
......@@ -532,6 +617,9 @@ namespace RTC
{
MS_TRACE();
if (!IsAlive())
return;
RTC::TransportSource source(socket, remote_addr);
onSTUNDataRecv(&source, data, len);
}
......@@ -540,6 +628,9 @@ namespace RTC
{
MS_TRACE();
if (!IsAlive())
return;
RTC::TransportSource source(socket, remote_addr);
onDTLSDataRecv(&source, data, len);
}
......@@ -548,6 +639,9 @@ namespace RTC
{
MS_TRACE();
if (!IsAlive())
return;
RTC::TransportSource source(socket, remote_addr);
onRTPDataRecv(&source, data, len);
}
......@@ -556,6 +650,9 @@ namespace RTC
{
MS_TRACE();
if (!IsAlive())
return;
RTC::TransportSource source(socket, remote_addr);
onRTCPDataRecv(&source, data, len);
}
......@@ -564,6 +661,9 @@ namespace RTC
{
MS_TRACE();
if (!IsAlive())
return;
RTC::TransportSource source(connection);
if (RemoveSource(&source))
......@@ -576,6 +676,9 @@ namespace RTC
{
MS_TRACE();
if (!IsAlive())
return;
RTC::TransportSource source(connection);
onSTUNDataRecv(&source, data, len);
}
......@@ -584,6 +687,9 @@ namespace RTC
{
MS_TRACE();
if (!IsAlive())
return;
RTC::TransportSource source(connection);
onDTLSDataRecv(&source, data, len);
}
......@@ -600,6 +706,9 @@ namespace RTC
{
MS_TRACE();
if (!IsAlive())
return;
RTC::TransportSource source(connection);
onRTCPDataRecv(&source, data, len);
}
......@@ -608,6 +717,9 @@ namespace RTC
{
MS_TRACE();
if (!IsAlive())
return;
// Send the STUN response over the same transport source.
source->Send(msg->GetRaw(), msg->GetLength());
}
......@@ -616,6 +728,9 @@ namespace RTC
{
MS_TRACE();
if (!IsAlive())
return;
/*
* RFC 5245 section 11.2 "Receiving Media":
*
......@@ -645,41 +760,41 @@ namespace RTC
}
// 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();
if (!this->sendingSource)
{
MS_DEBUG("no sending address set, cannot send DTLS packet");
return;
}
MS_DEBUG("DTLS connecting");
// 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_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_DEBUG("DTLS disconnected");
MS_DEBUG("DTLS closed");
// TODO
// Reset();
this->dtlsState = DtlsTransportState::CLOSED;
// NOTE: This is just called when calling Close() so don't call
// Terminate() here (not needed).
}
void Transport::onDTLSFailed(RTC::DTLSTransport* dtlsTransport)
......@@ -688,19 +803,27 @@ namespace RTC
MS_DEBUG("DTLS failed");
// TODO
// Reset();
this->dtlsState = DtlsTransportState::FAILED;
// 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_DEBUG("got SRTP key material");
if (!this->sendingSource)
{
MS_DEBUG("no sending address set, cannot send DTLS packet");
return;
}
// TODO
// SetLocalSRTPKey(srtp_profile, srtp_local_key, srtp_local_key_len);
// SetRemoteSRTPKey(srtp_profile, srtp_remote_key, srtp_remote_key_len);
// TODO: remove
MS_DEBUG("sending DTLS data to to:");
this->sendingSource->Dump();
this->sendingSource->Send(data, len);
}
void Transport::onDTLSApplicationData(RTC::DTLSTransport* dtlsTransport, const MS_BYTE* data, size_t len)
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论