3 * Copyright 2011, Google Inc.
4 * Copyright 2011, RTFM, Inc.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
9 * 1. Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
20 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
23 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
24 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
25 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
26 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include "talk/p2p/base/dtlstransportchannel.h"
31 #include "talk/base/buffer.h"
32 #include "talk/base/dscp.h"
33 #include "talk/base/messagequeue.h"
34 #include "talk/base/stream.h"
35 #include "talk/base/sslstreamadapter.h"
36 #include "talk/base/thread.h"
37 #include "talk/p2p/base/common.h"
41 // We don't pull the RTP constants from rtputils.h, to avoid a layer violation.
42 static const size_t kDtlsRecordHeaderLen = 13;
43 static const size_t kMaxDtlsPacketLen = 2048;
44 static const size_t kMinRtpPacketLen = 12;
45 static const size_t kDefaultVideoAndDataCryptos = 1;
47 static bool IsDtlsPacket(const char* data, size_t len) {
48 const uint8* u = reinterpret_cast<const uint8*>(data);
49 return (len >= kDtlsRecordHeaderLen && (u[0] > 19 && u[0] < 64));
51 static bool IsRtpPacket(const char* data, size_t len) {
52 const uint8* u = reinterpret_cast<const uint8*>(data);
53 return (len >= kMinRtpPacketLen && (u[0] & 0xC0) == 0x80);
56 talk_base::StreamResult StreamInterfaceChannel::Read(void* buffer,
60 if (state_ == talk_base::SS_CLOSED)
61 return talk_base::SR_EOS;
62 if (state_ == talk_base::SS_OPENING)
63 return talk_base::SR_BLOCK;
65 return fifo_.Read(buffer, buffer_len, read, error);
68 talk_base::StreamResult StreamInterfaceChannel::Write(const void* data,
72 // Always succeeds, since this is an unreliable transport anyway.
73 // TODO: Should this block if channel_'s temporarily unwritable?
74 talk_base::PacketOptions packet_options;
75 channel_->SendPacket(static_cast<const char*>(data), data_len,
80 return talk_base::SR_SUCCESS;
83 bool StreamInterfaceChannel::OnPacketReceived(const char* data, size_t size) {
84 // We force a read event here to ensure that we don't overflow our FIFO.
85 // Under high packet rate this can occur if we wait for the FIFO to post its
87 bool ret = (fifo_.WriteAll(data, size, NULL, NULL) == talk_base::SR_SUCCESS);
89 SignalEvent(this, talk_base::SE_READ, 0);
94 void StreamInterfaceChannel::OnEvent(talk_base::StreamInterface* stream,
96 SignalEvent(this, sig, err);
99 DtlsTransportChannelWrapper::DtlsTransportChannelWrapper(
100 Transport* transport,
101 TransportChannelImpl* channel)
102 : TransportChannelImpl(channel->content_name(), channel->component()),
103 transport_(transport),
104 worker_thread_(talk_base::Thread::Current()),
107 dtls_state_(STATE_NONE),
108 local_identity_(NULL),
109 ssl_role_(talk_base::SSL_CLIENT) {
110 channel_->SignalReadableState.connect(this,
111 &DtlsTransportChannelWrapper::OnReadableState);
112 channel_->SignalWritableState.connect(this,
113 &DtlsTransportChannelWrapper::OnWritableState);
114 channel_->SignalReadPacket.connect(this,
115 &DtlsTransportChannelWrapper::OnReadPacket);
116 channel_->SignalReadyToSend.connect(this,
117 &DtlsTransportChannelWrapper::OnReadyToSend);
118 channel_->SignalRequestSignaling.connect(this,
119 &DtlsTransportChannelWrapper::OnRequestSignaling);
120 channel_->SignalCandidateReady.connect(this,
121 &DtlsTransportChannelWrapper::OnCandidateReady);
122 channel_->SignalCandidatesAllocationDone.connect(this,
123 &DtlsTransportChannelWrapper::OnCandidatesAllocationDone);
124 channel_->SignalRoleConflict.connect(this,
125 &DtlsTransportChannelWrapper::OnRoleConflict);
126 channel_->SignalRouteChange.connect(this,
127 &DtlsTransportChannelWrapper::OnRouteChange);
128 channel_->SignalConnectionRemoved.connect(this,
129 &DtlsTransportChannelWrapper::OnConnectionRemoved);
132 DtlsTransportChannelWrapper::~DtlsTransportChannelWrapper() {
135 void DtlsTransportChannelWrapper::Connect() {
136 // We should only get a single call to Connect.
137 ASSERT(dtls_state_ == STATE_NONE ||
138 dtls_state_ == STATE_OFFERED ||
139 dtls_state_ == STATE_ACCEPTED);
143 void DtlsTransportChannelWrapper::Reset() {
148 // Re-call SetupDtls()
150 LOG_J(LS_ERROR, this) << "Error re-initializing DTLS";
151 dtls_state_ = STATE_CLOSED;
155 dtls_state_ = STATE_ACCEPTED;
158 bool DtlsTransportChannelWrapper::SetLocalIdentity(
159 talk_base::SSLIdentity* identity) {
160 if (dtls_state_ == STATE_OPEN && identity == local_identity_) {
164 // TODO(ekr@rtfm.com): Forbid this if Connect() has been called.
165 if (dtls_state_ != STATE_NONE) {
166 LOG_J(LS_ERROR, this) << "Can't set DTLS local identity in this state";
171 local_identity_ = identity;
172 dtls_state_ = STATE_OFFERED;
174 LOG_J(LS_INFO, this) << "NULL DTLS identity supplied. Not doing DTLS";
180 bool DtlsTransportChannelWrapper::GetLocalIdentity(
181 talk_base::SSLIdentity** identity) const {
182 if (!local_identity_)
185 *identity = local_identity_->GetReference();
189 bool DtlsTransportChannelWrapper::SetSslRole(talk_base::SSLRole role) {
190 if (dtls_state_ == STATE_OPEN) {
191 if (ssl_role_ != role) {
192 LOG(LS_ERROR) << "SSL Role can't be reversed after the session is setup.";
202 bool DtlsTransportChannelWrapper::GetSslRole(talk_base::SSLRole* role) const {
207 bool DtlsTransportChannelWrapper::SetRemoteFingerprint(
208 const std::string& digest_alg,
212 talk_base::Buffer remote_fingerprint_value(digest, digest_len);
214 if ((dtls_state_ == STATE_OPEN) &&
215 (remote_fingerprint_value_ == remote_fingerprint_value)) {
219 // Allow SetRemoteFingerprint with a NULL digest even if SetLocalIdentity
220 // hasn't been called.
221 if (dtls_state_ > STATE_OFFERED ||
222 (dtls_state_ == STATE_NONE && !digest_alg.empty())) {
223 LOG_J(LS_ERROR, this) << "Can't set DTLS remote settings in this state.";
227 if (digest_alg.empty()) {
228 LOG_J(LS_INFO, this) << "Other side didn't support DTLS.";
229 dtls_state_ = STATE_NONE;
233 // At this point we know we are doing DTLS
234 remote_fingerprint_value.TransferTo(&remote_fingerprint_value_);
235 remote_fingerprint_algorithm_ = digest_alg;
238 dtls_state_ = STATE_CLOSED;
242 dtls_state_ = STATE_ACCEPTED;
246 bool DtlsTransportChannelWrapper::GetRemoteCertificate(
247 talk_base::SSLCertificate** cert) const {
251 return dtls_->GetPeerCertificate(cert);
254 bool DtlsTransportChannelWrapper::SetupDtls() {
255 StreamInterfaceChannel* downward =
256 new StreamInterfaceChannel(worker_thread_, channel_);
258 dtls_.reset(talk_base::SSLStreamAdapter::Create(downward));
260 LOG_J(LS_ERROR, this) << "Failed to create DTLS adapter.";
265 downward_ = downward;
267 dtls_->SetIdentity(local_identity_->GetReference());
268 dtls_->SetMode(talk_base::SSL_MODE_DTLS);
269 dtls_->SetServerRole(ssl_role_);
270 dtls_->SignalEvent.connect(this, &DtlsTransportChannelWrapper::OnDtlsEvent);
271 if (!dtls_->SetPeerCertificateDigest(
272 remote_fingerprint_algorithm_,
273 reinterpret_cast<unsigned char *>(remote_fingerprint_value_.data()),
274 remote_fingerprint_value_.length())) {
275 LOG_J(LS_ERROR, this) << "Couldn't set DTLS certificate digest.";
279 // Set up DTLS-SRTP, if it's been enabled.
280 if (!srtp_ciphers_.empty()) {
281 if (!dtls_->SetDtlsSrtpCiphers(srtp_ciphers_)) {
282 LOG_J(LS_ERROR, this) << "Couldn't set DTLS-SRTP ciphers.";
286 LOG_J(LS_INFO, this) << "Not using DTLS.";
289 LOG_J(LS_INFO, this) << "DTLS setup complete.";
293 bool DtlsTransportChannelWrapper::SetSrtpCiphers(
294 const std::vector<std::string>& ciphers) {
295 if (srtp_ciphers_ == ciphers)
298 if (dtls_state_ == STATE_OPEN) {
299 // We don't support DTLS renegotiation currently. If new set of srtp ciphers
300 // are different than what's being used currently, we will not use it.
301 // So for now, let's be happy (or sad) with a warning message.
302 std::string current_srtp_cipher;
303 if (!dtls_->GetDtlsSrtpCipher(¤t_srtp_cipher)) {
304 LOG(LS_ERROR) << "Failed to get the current SRTP cipher for DTLS channel";
307 const std::vector<std::string>::const_iterator iter =
308 std::find(ciphers.begin(), ciphers.end(), current_srtp_cipher);
309 if (iter == ciphers.end()) {
310 std::string requested_str;
311 for (size_t i = 0; i < ciphers.size(); ++i) {
312 requested_str.append(" ");
313 requested_str.append(ciphers[i]);
314 requested_str.append(" ");
316 LOG(LS_WARNING) << "Ignoring new set of SRTP ciphers, as DTLS "
317 << "renegotiation is not supported currently "
318 << "current cipher = " << current_srtp_cipher << " and "
319 << "requested = " << "[" << requested_str << "]";
324 if (dtls_state_ != STATE_NONE &&
325 dtls_state_ != STATE_OFFERED &&
326 dtls_state_ != STATE_ACCEPTED) {
331 srtp_ciphers_ = ciphers;
335 bool DtlsTransportChannelWrapper::GetSrtpCipher(std::string* cipher) {
336 if (dtls_state_ != STATE_OPEN) {
340 return dtls_->GetDtlsSrtpCipher(cipher);
344 // Called from upper layers to send a media packet.
345 int DtlsTransportChannelWrapper::SendPacket(
346 const char* data, size_t size,
347 const talk_base::PacketOptions& options, int flags) {
350 switch (dtls_state_) {
352 // We don't know if we are doing DTLS yet, so we can't send a packet.
353 // TODO(ekr@rtfm.com): assert here?
359 // Can't send data until the connection is active
364 if (flags & PF_SRTP_BYPASS) {
365 ASSERT(!srtp_ciphers_.empty());
366 if (!IsRtpPacket(data, size)) {
371 result = channel_->SendPacket(data, size, options);
373 result = (dtls_->WriteAll(data, size, NULL, NULL) ==
374 talk_base::SR_SUCCESS) ? static_cast<int>(size) : -1;
379 result = channel_->SendPacket(data, size, options);
382 case STATE_CLOSED: // Can't send anything when we're closed.
389 // The state transition logic here is as follows:
390 // (1) If we're not doing DTLS-SRTP, then the state is just the
391 // state of the underlying impl()
392 // (2) If we're doing DTLS-SRTP:
393 // - Prior to the DTLS handshake, the state is neither readable or
395 // - When the impl goes writable for the first time we
396 // start the DTLS handshake
397 // - Once the DTLS handshake completes, the state is that of the
399 void DtlsTransportChannelWrapper::OnReadableState(TransportChannel* channel) {
400 ASSERT(talk_base::Thread::Current() == worker_thread_);
401 ASSERT(channel == channel_);
402 LOG_J(LS_VERBOSE, this)
403 << "DTLSTransportChannelWrapper: channel readable state changed.";
405 if (dtls_state_ == STATE_NONE || dtls_state_ == STATE_OPEN) {
406 set_readable(channel_->readable());
407 // Note: SignalReadableState fired by set_readable.
411 void DtlsTransportChannelWrapper::OnWritableState(TransportChannel* channel) {
412 ASSERT(talk_base::Thread::Current() == worker_thread_);
413 ASSERT(channel == channel_);
414 LOG_J(LS_VERBOSE, this)
415 << "DTLSTransportChannelWrapper: channel writable state changed.";
417 switch (dtls_state_) {
420 set_writable(channel_->writable());
421 // Note: SignalWritableState fired by set_writable.
429 if (!MaybeStartDtls()) {
430 // This should never happen:
431 // Because we are operating in a nonblocking mode and all
432 // incoming packets come in via OnReadPacket(), which rejects
433 // packets in this state, the incoming queue must be empty. We
434 // ignore write errors, thus any errors must be because of
435 // configuration and therefore are our fault.
436 // Note that in non-debug configurations, failure in
437 // MaybeStartDtls() changes the state to STATE_CLOSED.
447 // Should not happen. Do nothing
452 void DtlsTransportChannelWrapper::OnReadPacket(
453 TransportChannel* channel, const char* data, size_t size,
454 const talk_base::PacketTime& packet_time, int flags) {
455 ASSERT(talk_base::Thread::Current() == worker_thread_);
456 ASSERT(channel == channel_);
459 switch (dtls_state_) {
461 // We are not doing DTLS
462 SignalReadPacket(this, data, size, packet_time, 0);
466 // Currently drop the packet, but we might in future
467 // decide to take this as evidence that the other
468 // side is ready to do DTLS and start the handshake
470 LOG_J(LS_WARNING, this) << "Received packet before we know if we are "
471 << "doing DTLS or not; dropping.";
475 // Drop packets received before DTLS has actually started
476 LOG_J(LS_INFO, this) << "Dropping packet received before DTLS started.";
481 // We should only get DTLS or SRTP packets; STUN's already been demuxed.
482 // Is this potentially a DTLS packet?
483 if (IsDtlsPacket(data, size)) {
484 if (!HandleDtlsPacket(data, size)) {
485 LOG_J(LS_ERROR, this) << "Failed to handle DTLS packet.";
489 // Not a DTLS packet; our handshake should be complete by now.
490 if (dtls_state_ != STATE_OPEN) {
491 LOG_J(LS_ERROR, this) << "Received non-DTLS packet before DTLS "
496 // And it had better be a SRTP packet.
497 if (!IsRtpPacket(data, size)) {
498 LOG_J(LS_ERROR, this) << "Received unexpected non-DTLS packet.";
503 ASSERT(!srtp_ciphers_.empty());
505 // Signal this upwards as a bypass packet.
506 SignalReadPacket(this, data, size, packet_time, PF_SRTP_BYPASS);
510 // This shouldn't be happening. Drop the packet
515 void DtlsTransportChannelWrapper::OnReadyToSend(TransportChannel* channel) {
517 SignalReadyToSend(this);
521 void DtlsTransportChannelWrapper::OnDtlsEvent(talk_base::StreamInterface* dtls,
523 ASSERT(talk_base::Thread::Current() == worker_thread_);
524 ASSERT(dtls == dtls_.get());
525 if (sig & talk_base::SE_OPEN) {
526 // This is the first time.
527 LOG_J(LS_INFO, this) << "DTLS handshake complete.";
528 if (dtls_->GetState() == talk_base::SS_OPEN) {
529 // The check for OPEN shouldn't be necessary but let's make
530 // sure we don't accidentally frob the state if it's closed.
531 dtls_state_ = STATE_OPEN;
537 if (sig & talk_base::SE_READ) {
538 char buf[kMaxDtlsPacketLen];
540 if (dtls_->Read(buf, sizeof(buf), &read, NULL) == talk_base::SR_SUCCESS) {
541 SignalReadPacket(this, buf, read, talk_base::CreatePacketTime(0), 0);
544 if (sig & talk_base::SE_CLOSE) {
545 ASSERT(sig == talk_base::SE_CLOSE); // SE_CLOSE should be by itself.
547 LOG_J(LS_INFO, this) << "DTLS channel closed";
549 LOG_J(LS_INFO, this) << "DTLS channel error, code=" << err;
554 dtls_state_ = STATE_CLOSED;
558 bool DtlsTransportChannelWrapper::MaybeStartDtls() {
559 if (channel_->writable()) {
560 if (dtls_->StartSSLWithPeer()) {
561 LOG_J(LS_ERROR, this) << "Couldn't start DTLS handshake";
562 dtls_state_ = STATE_CLOSED;
566 << "DtlsTransportChannelWrapper: Started DTLS handshake";
568 dtls_state_ = STATE_STARTED;
573 // Called from OnReadPacket when a DTLS packet is received.
574 bool DtlsTransportChannelWrapper::HandleDtlsPacket(const char* data,
576 // Sanity check we're not passing junk that
577 // just looks like DTLS.
578 const uint8* tmp_data = reinterpret_cast<const uint8* >(data);
579 size_t tmp_size = size;
580 while (tmp_size > 0) {
581 if (tmp_size < kDtlsRecordHeaderLen)
582 return false; // Too short for the header
584 size_t record_len = (tmp_data[11] << 8) | (tmp_data[12]);
585 if ((record_len + kDtlsRecordHeaderLen) > tmp_size)
586 return false; // Body too short
588 tmp_data += record_len + kDtlsRecordHeaderLen;
589 tmp_size -= record_len + kDtlsRecordHeaderLen;
592 // Looks good. Pass to the SIC which ends up being passed to
594 return downward_->OnPacketReceived(data, size);
597 void DtlsTransportChannelWrapper::OnRequestSignaling(
598 TransportChannelImpl* channel) {
599 ASSERT(channel == channel_);
600 SignalRequestSignaling(this);
603 void DtlsTransportChannelWrapper::OnCandidateReady(
604 TransportChannelImpl* channel, const Candidate& c) {
605 ASSERT(channel == channel_);
606 SignalCandidateReady(this, c);
609 void DtlsTransportChannelWrapper::OnCandidatesAllocationDone(
610 TransportChannelImpl* channel) {
611 ASSERT(channel == channel_);
612 SignalCandidatesAllocationDone(this);
615 void DtlsTransportChannelWrapper::OnRoleConflict(
616 TransportChannelImpl* channel) {
617 ASSERT(channel == channel_);
618 SignalRoleConflict(this);
621 void DtlsTransportChannelWrapper::OnRouteChange(
622 TransportChannel* channel, const Candidate& candidate) {
623 ASSERT(channel == channel_);
624 SignalRouteChange(this, candidate);
627 void DtlsTransportChannelWrapper::OnConnectionRemoved(
628 TransportChannelImpl* channel) {
629 ASSERT(channel == channel_);
630 SignalConnectionRemoved(this);
633 } // namespace cricket