Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / libjingle / source / talk / p2p / base / dtlstransportchannel.cc
1 /*
2  * libjingle
3  * Copyright 2011, Google Inc.
4  * Copyright 2011, RTFM, Inc.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
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.
16  *
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.
27  */
28
29 #include "talk/p2p/base/dtlstransportchannel.h"
30
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"
38
39 namespace cricket {
40
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;
46
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));
50 }
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);
54 }
55
56 talk_base::StreamResult StreamInterfaceChannel::Read(void* buffer,
57                                                      size_t buffer_len,
58                                                      size_t* read,
59                                                      int* error) {
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;
64
65   return fifo_.Read(buffer, buffer_len, read, error);
66 }
67
68 talk_base::StreamResult StreamInterfaceChannel::Write(const void* data,
69                                                       size_t data_len,
70                                                       size_t* written,
71                                                       int* error) {
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,
76                        packet_options);
77   if (written) {
78     *written = data_len;
79   }
80   return talk_base::SR_SUCCESS;
81 }
82
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
86   // own SE_READ.
87   bool ret = (fifo_.WriteAll(data, size, NULL, NULL) == talk_base::SR_SUCCESS);
88   if (ret) {
89     SignalEvent(this, talk_base::SE_READ, 0);
90   }
91   return ret;
92 }
93
94 void StreamInterfaceChannel::OnEvent(talk_base::StreamInterface* stream,
95                                      int sig, int err) {
96   SignalEvent(this, sig, err);
97 }
98
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()),
105       channel_(channel),
106       downward_(NULL),
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);
130 }
131
132 DtlsTransportChannelWrapper::~DtlsTransportChannelWrapper() {
133 }
134
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);
140   channel_->Connect();
141 }
142
143 void DtlsTransportChannelWrapper::Reset() {
144   channel_->Reset();
145   set_writable(false);
146   set_readable(false);
147
148   // Re-call SetupDtls()
149   if (!SetupDtls()) {
150     LOG_J(LS_ERROR, this) << "Error re-initializing DTLS";
151     dtls_state_ = STATE_CLOSED;
152     return;
153   }
154
155   dtls_state_ = STATE_ACCEPTED;
156 }
157
158 bool DtlsTransportChannelWrapper::SetLocalIdentity(
159     talk_base::SSLIdentity* identity) {
160   if (dtls_state_ == STATE_OPEN && identity == local_identity_) {
161     return true;
162   }
163
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";
167     return false;
168   }
169
170   if (identity) {
171     local_identity_ = identity;
172     dtls_state_ = STATE_OFFERED;
173   } else {
174     LOG_J(LS_INFO, this) << "NULL DTLS identity supplied. Not doing DTLS";
175   }
176
177   return true;
178 }
179
180 bool DtlsTransportChannelWrapper::GetLocalIdentity(
181     talk_base::SSLIdentity** identity) const {
182   if (!local_identity_)
183     return false;
184
185   *identity = local_identity_->GetReference();
186   return true;
187 }
188
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.";
193       return false;
194     }
195     return true;
196   }
197
198   ssl_role_ = role;
199   return true;
200 }
201
202 bool DtlsTransportChannelWrapper::GetSslRole(talk_base::SSLRole* role) const {
203   *role = ssl_role_;
204   return true;
205 }
206
207 bool DtlsTransportChannelWrapper::SetRemoteFingerprint(
208     const std::string& digest_alg,
209     const uint8* digest,
210     size_t digest_len) {
211
212   talk_base::Buffer remote_fingerprint_value(digest, digest_len);
213
214   if ((dtls_state_ == STATE_OPEN) &&
215       (remote_fingerprint_value_ == remote_fingerprint_value)) {
216     return true;
217   }
218
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.";
224     return false;
225   }
226
227   if (digest_alg.empty()) {
228     LOG_J(LS_INFO, this) << "Other side didn't support DTLS.";
229     dtls_state_ = STATE_NONE;
230     return true;
231   }
232
233   // At this point we know we are doing DTLS
234   remote_fingerprint_value.TransferTo(&remote_fingerprint_value_);
235   remote_fingerprint_algorithm_ = digest_alg;
236
237   if (!SetupDtls()) {
238     dtls_state_ = STATE_CLOSED;
239     return false;
240   }
241
242   dtls_state_ = STATE_ACCEPTED;
243   return true;
244 }
245
246 bool DtlsTransportChannelWrapper::GetRemoteCertificate(
247     talk_base::SSLCertificate** cert) const {
248   if (!dtls_)
249     return false;
250
251   return dtls_->GetPeerCertificate(cert);
252 }
253
254 bool DtlsTransportChannelWrapper::SetupDtls() {
255   StreamInterfaceChannel* downward =
256       new StreamInterfaceChannel(worker_thread_, channel_);
257
258   dtls_.reset(talk_base::SSLStreamAdapter::Create(downward));
259   if (!dtls_) {
260     LOG_J(LS_ERROR, this) << "Failed to create DTLS adapter.";
261     delete downward;
262     return false;
263   }
264
265   downward_ = downward;
266
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.";
276     return false;
277   }
278
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.";
283       return false;
284     }
285   } else {
286     LOG_J(LS_INFO, this) << "Not using DTLS.";
287   }
288
289   LOG_J(LS_INFO, this) << "DTLS setup complete.";
290   return true;
291 }
292
293 bool DtlsTransportChannelWrapper::SetSrtpCiphers(
294     const std::vector<std::string>& ciphers) {
295   if (srtp_ciphers_ == ciphers)
296     return true;
297
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(&current_srtp_cipher)) {
304       LOG(LS_ERROR) << "Failed to get the current SRTP cipher for DTLS channel";
305       return false;
306     }
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(" ");
315       }
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 << "]";
320     }
321     return true;
322   }
323
324   if (dtls_state_ != STATE_NONE &&
325       dtls_state_ != STATE_OFFERED &&
326       dtls_state_ != STATE_ACCEPTED) {
327     ASSERT(false);
328     return false;
329   }
330
331   srtp_ciphers_ = ciphers;
332   return true;
333 }
334
335 bool DtlsTransportChannelWrapper::GetSrtpCipher(std::string* cipher) {
336   if (dtls_state_ != STATE_OPEN) {
337     return false;
338   }
339
340   return dtls_->GetDtlsSrtpCipher(cipher);
341 }
342
343
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) {
348   int result = -1;
349
350   switch (dtls_state_) {
351     case STATE_OFFERED:
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?
354       result = -1;
355       break;
356
357     case STATE_STARTED:
358     case STATE_ACCEPTED:
359       // Can't send data until the connection is active
360       result = -1;
361       break;
362
363     case STATE_OPEN:
364       if (flags & PF_SRTP_BYPASS) {
365         ASSERT(!srtp_ciphers_.empty());
366         if (!IsRtpPacket(data, size)) {
367           result = false;
368           break;
369         }
370
371         result = channel_->SendPacket(data, size, options);
372       } else {
373         result = (dtls_->WriteAll(data, size, NULL, NULL) ==
374           talk_base::SR_SUCCESS) ? static_cast<int>(size) : -1;
375       }
376       break;
377       // Not doing DTLS.
378     case STATE_NONE:
379       result = channel_->SendPacket(data, size, options);
380       break;
381
382     case STATE_CLOSED:  // Can't send anything when we're closed.
383       return -1;
384   }
385
386   return result;
387 }
388
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
394 //       writable
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
398 //       impl again
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.";
404
405   if (dtls_state_ == STATE_NONE || dtls_state_ == STATE_OPEN) {
406     set_readable(channel_->readable());
407     // Note: SignalReadableState fired by set_readable.
408   }
409 }
410
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.";
416
417   switch (dtls_state_) {
418     case STATE_NONE:
419     case STATE_OPEN:
420       set_writable(channel_->writable());
421       // Note: SignalWritableState fired by set_writable.
422       break;
423
424     case STATE_OFFERED:
425       // Do nothing
426       break;
427
428     case STATE_ACCEPTED:
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.
438         ASSERT(false);
439       }
440       break;
441
442     case STATE_STARTED:
443       // Do nothing
444       break;
445
446     case STATE_CLOSED:
447       // Should not happen. Do nothing
448       break;
449   }
450 }
451
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_);
457   ASSERT(flags == 0);
458
459   switch (dtls_state_) {
460     case STATE_NONE:
461       // We are not doing DTLS
462       SignalReadPacket(this, data, size, packet_time, 0);
463       break;
464
465     case STATE_OFFERED:
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
469       // on our end
470       LOG_J(LS_WARNING, this) << "Received packet before we know if we are "
471                               << "doing DTLS or not; dropping.";
472       break;
473
474     case STATE_ACCEPTED:
475       // Drop packets received before DTLS has actually started
476       LOG_J(LS_INFO, this) << "Dropping packet received before DTLS started.";
477       break;
478
479     case STATE_STARTED:
480     case STATE_OPEN:
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.";
486           return;
487         }
488       } else {
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 "
492                                 << "complete.";
493           return;
494         }
495
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.";
499           return;
500         }
501
502         // Sanity check.
503         ASSERT(!srtp_ciphers_.empty());
504
505         // Signal this upwards as a bypass packet.
506         SignalReadPacket(this, data, size, packet_time, PF_SRTP_BYPASS);
507       }
508       break;
509     case STATE_CLOSED:
510       // This shouldn't be happening. Drop the packet
511       break;
512   }
513 }
514
515 void DtlsTransportChannelWrapper::OnReadyToSend(TransportChannel* channel) {
516   if (writable()) {
517     SignalReadyToSend(this);
518   }
519 }
520
521 void DtlsTransportChannelWrapper::OnDtlsEvent(talk_base::StreamInterface* dtls,
522                                               int sig, int err) {
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;
532
533       set_readable(true);
534       set_writable(true);
535     }
536   }
537   if (sig & talk_base::SE_READ) {
538     char buf[kMaxDtlsPacketLen];
539     size_t read;
540     if (dtls_->Read(buf, sizeof(buf), &read, NULL) == talk_base::SR_SUCCESS) {
541       SignalReadPacket(this, buf, read, talk_base::CreatePacketTime(0), 0);
542     }
543   }
544   if (sig & talk_base::SE_CLOSE) {
545     ASSERT(sig == talk_base::SE_CLOSE);  // SE_CLOSE should be by itself.
546     if (!err) {
547       LOG_J(LS_INFO, this) << "DTLS channel closed";
548     } else {
549       LOG_J(LS_INFO, this) << "DTLS channel error, code=" << err;
550     }
551
552     set_readable(false);
553     set_writable(false);
554     dtls_state_ = STATE_CLOSED;
555   }
556 }
557
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;
563       return false;
564     }
565     LOG_J(LS_INFO, this)
566       << "DtlsTransportChannelWrapper: Started DTLS handshake";
567
568     dtls_state_ = STATE_STARTED;
569   }
570   return true;
571 }
572
573 // Called from OnReadPacket when a DTLS packet is received.
574 bool DtlsTransportChannelWrapper::HandleDtlsPacket(const char* data,
575                                                    size_t size) {
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
583
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
587
588     tmp_data += record_len + kDtlsRecordHeaderLen;
589     tmp_size -= record_len + kDtlsRecordHeaderLen;
590   }
591
592   // Looks good. Pass to the SIC which ends up being passed to
593   // the DTLS stack.
594   return downward_->OnPacketReceived(data, size);
595 }
596
597 void DtlsTransportChannelWrapper::OnRequestSignaling(
598     TransportChannelImpl* channel) {
599   ASSERT(channel == channel_);
600   SignalRequestSignaling(this);
601 }
602
603 void DtlsTransportChannelWrapper::OnCandidateReady(
604     TransportChannelImpl* channel, const Candidate& c) {
605   ASSERT(channel == channel_);
606   SignalCandidateReady(this, c);
607 }
608
609 void DtlsTransportChannelWrapper::OnCandidatesAllocationDone(
610     TransportChannelImpl* channel) {
611   ASSERT(channel == channel_);
612   SignalCandidatesAllocationDone(this);
613 }
614
615 void DtlsTransportChannelWrapper::OnRoleConflict(
616     TransportChannelImpl* channel) {
617   ASSERT(channel == channel_);
618   SignalRoleConflict(this);
619 }
620
621 void DtlsTransportChannelWrapper::OnRouteChange(
622     TransportChannel* channel, const Candidate& candidate) {
623   ASSERT(channel == channel_);
624   SignalRouteChange(this, candidate);
625 }
626
627 void DtlsTransportChannelWrapper::OnConnectionRemoved(
628     TransportChannelImpl* channel) {
629   ASSERT(channel == channel_);
630   SignalConnectionRemoved(this);
631 }
632
633 }  // namespace cricket