Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(150)

Side by Side Diff: webrtc/p2p/quic/quictransportchannel.cc

Issue 1721673004: Create QuicTransportChannel (Closed) Base URL: https://chromium.googlesource.com/external/webrtc.git@master
Patch Set: Inline and rename unit test methods Created 4 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 /*
2 * Copyright 2016 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #include "webrtc/p2p/quic/quictransportchannel.h"
12
13 #include <utility>
14
15 #include "net/quic/crypto/proof_source.h"
16 #include "net/quic/crypto/proof_verifier.h"
17 #include "net/quic/crypto/quic_crypto_client_config.h"
18 #include "net/quic/crypto/quic_crypto_server_config.h"
19 #include "net/quic/quic_connection.h"
20 #include "net/quic/quic_crypto_client_stream.h"
21 #include "net/quic/quic_crypto_server_stream.h"
22 #include "net/quic/quic_protocol.h"
23 #include "webrtc/base/checks.h"
24 #include "webrtc/base/helpers.h"
25 #include "webrtc/base/logging.h"
26 #include "webrtc/base/socket.h"
27 #include "webrtc/base/thread.h"
28 #include "webrtc/p2p/base/common.h"
29
30 namespace {
31
32 // QUIC public header constants for net::QuicConnection. These are arbitrary
33 // given that |channel_| only receives packets specific to this channel,
34 // in which case we already know the QUIC packets have the correct destination.
35 const net::QuicConnectionId kConnectionId = 0;
36 const net::IPAddressNumber kConnectionIpAddress(net::kIPv4AddressSize, 0);
37 const net::IPEndPoint kConnectionIpEndpoint(kConnectionIpAddress, 0);
38
39 // Arbitrary server port number for net::QuicCryptoClientConfig.
40 const int kQuicServerPort = 0;
41
42 // QUIC connection timeout. This is large so that |channel_| can
43 // be responsible for connection timeout.
44 const int kIdleConnectionStateLifetime = 1000; // seconds
45
46 // Length of HKDF input keying material, equal to its number of bytes.
47 // https://tools.ietf.org/html/rfc5869#section-2.2.
48 // TODO(mikescarlett): Verify that input keying material length is correct.
49 const size_t kInputKeyingMaterialLength = 32;
50
51 // We don't pull the RTP constants from rtputils.h, to avoid a layer violation.
52 const size_t kMinRtpPacketLen = 12;
53
54 bool IsRtpPacket(const char* data, size_t len) {
55 const uint8_t* u = reinterpret_cast<const uint8_t*>(data);
56 return (len >= kMinRtpPacketLen && (u[0] & 0xC0) == 0x80);
57 }
58
59 // Function for detecting QUIC packets based off
60 // https://tools.ietf.org/html/draft-tsvwg-quic-protocol-02#section-6.
61 const size_t kMinQuicPacketLen = 2;
62
63 bool IsQuicPacket(const char* data, size_t len) {
64 const uint8_t* u = reinterpret_cast<const uint8_t*>(data);
65 return (len >= kMinQuicPacketLen && (u[0] & 0x80) == 0);
66 }
67
68 // Used by QuicCryptoServerConfig to provide dummy proof credentials.
69 // TODO(mikescarlett): Remove when secure P2P QUIC handshake is possible.
70 class DummyProofSource : public net::ProofSource {
71 public:
72 DummyProofSource() {}
73 ~DummyProofSource() override {}
74
75 // ProofSource override.
76 bool GetProof(const net::IPAddressNumber& server_ip,
77 const std::string& hostname,
78 const std::string& server_config,
79 bool ecdsa_ok,
80 const std::vector<std::string>** out_certs,
81 std::string* out_signature,
82 std::string* out_leaf_cert_sct) override {
83 LOG(INFO) << "GetProof() providing dummy credentials for insecure QUIC";
84 std::vector<std::string>* certs = new std::vector<std::string>();
85 certs->push_back("Dummy cert");
86 std::string signature("Dummy signature");
87
88 *out_certs = certs;
89 *out_signature = signature;
90
91 return true;
92 }
93 };
94
95 // Used by QuicCryptoClientConfig to ignore the peer's credentials
96 // and establish an insecure QUIC connection.
97 // TODO(mikescarlett): Remove when secure P2P QUIC handshake is possible.
98 class InsecureProofVerifier : public net::ProofVerifier {
99 public:
100 InsecureProofVerifier() {}
101 ~InsecureProofVerifier() override {}
102
103 // ProofVerifier override.
104 net::QuicAsyncStatus VerifyProof(
105 const std::string& hostname,
106 const std::string& server_config,
107 const std::vector<std::string>& certs,
108 const std::string& cert_sct,
109 const std::string& signature,
110 const net::ProofVerifyContext* verify_context,
111 std::string* error_details,
112 scoped_ptr<net::ProofVerifyDetails>* verify_details,
113 net::ProofVerifierCallback* callback) override {
114 LOG(INFO) << "VerifyProof() ignoring credentials and returning success";
115 return net::QUIC_SUCCESS;
116 }
117 };
118
119 } // namespace
120
121 namespace cricket {
122
123 QuicTransportChannel::QuicTransportChannel(TransportChannelImpl* channel)
124 : TransportChannelImpl(channel->transport_name(), channel->component()),
125 worker_thread_(rtc::Thread::Current()),
126 channel_(channel),
127 helper_(worker_thread_) {
128 channel_->SignalWritableState.connect(this,
129 &QuicTransportChannel::OnWritableState);
130 channel_->SignalReadPacket.connect(this, &QuicTransportChannel::OnReadPacket);
131 channel_->SignalSentPacket.connect(this, &QuicTransportChannel::OnSentPacket);
132 channel_->SignalReadyToSend.connect(this,
133 &QuicTransportChannel::OnReadyToSend);
134 channel_->SignalGatheringState.connect(
135 this, &QuicTransportChannel::OnGatheringState);
136 channel_->SignalCandidateGathered.connect(
137 this, &QuicTransportChannel::OnCandidateGathered);
138 channel_->SignalRoleConflict.connect(this,
139 &QuicTransportChannel::OnRoleConflict);
140 channel_->SignalRouteChange.connect(this,
141 &QuicTransportChannel::OnRouteChange);
142 channel_->SignalConnectionRemoved.connect(
143 this, &QuicTransportChannel::OnConnectionRemoved);
144 channel_->SignalReceivingState.connect(
145 this, &QuicTransportChannel::OnReceivingState);
146
147 config_.SetIdleConnectionStateLifetime(
148 net::QuicTime::Delta::FromSeconds(kIdleConnectionStateLifetime),
149 net::QuicTime::Delta::FromSeconds(kIdleConnectionStateLifetime));
150 // Sets the bytes reserved for the QUIC connection ID to zero.
151 config_.SetBytesForConnectionIdToSend(0);
152 }
153
154 QuicTransportChannel::~QuicTransportChannel() {}
155
156 void QuicTransportChannel::Connect() {
157 // We should only get a single call to Connect.
158 ASSERT(quic_state_ == QUIC_TRANSPORT_NEW);
159 channel_->Connect();
160 }
161
162 bool QuicTransportChannel::SetLocalCertificate(
163 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
164 if (!certificate) {
165 LOG_J(ERROR, this) << "No local certificate was supplied. Not doing QUIC.";
166 return false;
167 }
168 if (!local_certificate_) {
169 local_certificate_ = certificate;
170 return true;
171 }
172 if (certificate == local_certificate_) {
173 // This may happen during renegotiation.
174 LOG_J(INFO, this) << "Ignoring identical certificate";
175 return true;
176 }
177 LOG_J(ERROR, this) << "Local certificate of the QUIC connection already set. "
178 "Can't change the local certificate once it's active.";
179 return false;
180 }
181
182 rtc::scoped_refptr<rtc::RTCCertificate>
183 QuicTransportChannel::GetLocalCertificate() const {
184 return local_certificate_;
185 }
186
187 bool QuicTransportChannel::SetSslRole(rtc::SSLRole role) {
188 if (ssl_role_ && *ssl_role_ == role) {
189 LOG_J(WARNING, this) << "Ignoring SSL Role identical to current role.";
190 return true;
191 }
192 if (quic_state_ != QUIC_TRANSPORT_CONNECTED) {
193 ssl_role_ = rtc::Optional<rtc::SSLRole>(role);
194 return true;
195 }
196 LOG_J(ERROR, this)
197 << "SSL Role can't be reversed after the session is setup.";
198 return false;
199 }
200
201 bool QuicTransportChannel::GetSslRole(rtc::SSLRole* role) const {
202 if (!ssl_role_) {
203 return false;
204 }
205 *role = *ssl_role_;
206 return true;
207 }
208
209 bool QuicTransportChannel::SetRemoteFingerprint(const std::string& digest_alg,
210 const uint8_t* digest,
211 size_t digest_len) {
212 if (digest_alg.empty()) {
213 RTC_DCHECK(!digest_len);
214 LOG_J(ERROR, this) << "Remote peer doesn't support digest algorithm.";
215 return false;
216 }
217 std::string remote_fingerprint_value(reinterpret_cast<const char*>(digest),
218 digest_len);
219 // Once we have the local certificate, the same remote fingerprint can be set
220 // multiple times. This may happen during renegotiation.
221 if (remote_fingerprint_ &&
222 remote_fingerprint_->value == remote_fingerprint_value &&
223 remote_fingerprint_->algorithm == digest_alg) {
224 LOG_J(INFO, this) << "Ignoring identical remote fingerprint and algorithm";
225 return true;
226 }
227 // At this point we know we are doing QUIC.
228 remote_fingerprint_ = rtc::Optional<RemoteFingerprint>(RemoteFingerprint());
229 remote_fingerprint_->value = remote_fingerprint_value;
230 remote_fingerprint_->algorithm = digest_alg;
231 return true;
232 }
233
234 bool QuicTransportChannel::ExportKeyingMaterial(const std::string& label,
235 const uint8_t* context,
236 size_t context_len,
237 bool use_context,
238 uint8_t* result,
239 size_t result_len) {
240 std::string quic_context(reinterpret_cast<const char*>(context), context_len);
241 std::string quic_result;
242 if (!quic_->ExportKeyingMaterial(label, quic_context, result_len,
243 &quic_result)) {
244 return false;
245 }
246 quic_result.copy(reinterpret_cast<char*>(result), result_len);
247 return true;
248 }
249
250 bool QuicTransportChannel::GetSrtpCryptoSuite(int* cipher) {
251 *cipher = rtc::SRTP_AES128_CM_SHA1_80;
252 return true;
253 }
254
255 // Called from upper layers to send a media packet.
256 int QuicTransportChannel::SendPacket(const char* data,
257 size_t size,
258 const rtc::PacketOptions& options,
259 int flags) {
260 if ((flags & PF_SRTP_BYPASS) && IsRtpPacket(data, size)) {
261 return channel_->SendPacket(data, size, options);
262 }
263 LOG(ERROR) << "Failed to send an invalid SRTP bypass packet using QUIC.";
264 return -1;
265 }
266
267 // The state transition logic here is as follows:
268 // - Before the QUIC handshake is complete, the QUIC channel is unwritable.
269 // - When |channel_| goes writable for the first time we
270 // start the QUIC handshake.
271 // - Once the QUIC handshake completes, the state is that of the
272 // |channel_| again.
273 void QuicTransportChannel::OnWritableState(TransportChannel* channel) {
274 ASSERT(rtc::Thread::Current() == worker_thread_);
275 ASSERT(channel == channel_);
276 LOG_J(VERBOSE, this)
277 << "QuicTransportChannel: channel writable state changed to "
278 << channel_->writable();
279 switch (quic_state_) {
280 case QUIC_TRANSPORT_NEW:
281 // Starts the QUIC handshake when |channel_| is writable.
282 // This will fail if the SSL role or remote fingerprint are not set.
283 // Otherwise failure could result from network or QUIC errors.
284 MaybeStartQuic();
285 break;
286 case QUIC_TRANSPORT_CONNECTED:
287 // Note: SignalWritableState fired by set_writable.
288 set_writable(channel_->writable());
289 if (HasDataToWrite()) {
290 OnCanWrite();
291 }
292 break;
293 case QUIC_TRANSPORT_CONNECTING:
294 // This channel is not writable until the QUIC handshake finishes. It
295 // might
296 // have been write blocked.
297 if (HasDataToWrite()) {
298 OnCanWrite();
299 }
300 break;
301 case QUIC_TRANSPORT_FAILED:
302 // Should not happen. Do nothing.
303 break;
304 }
305 }
306
307 void QuicTransportChannel::OnReceivingState(TransportChannel* channel) {
308 ASSERT(rtc::Thread::Current() == worker_thread_);
309 ASSERT(channel == channel_);
310 LOG_J(VERBOSE, this)
311 << "QuicTransportChannel: channel receiving state changed to "
312 << channel_->receiving();
313 if (quic_state_ == QUIC_TRANSPORT_CONNECTED) {
314 // Note: SignalReceivingState fired by set_receiving.
315 set_receiving(channel_->receiving());
316 }
317 }
318
319 void QuicTransportChannel::OnReadPacket(TransportChannel* channel,
320 const char* data,
321 size_t size,
322 const rtc::PacketTime& packet_time,
323 int flags) {
324 ASSERT(rtc::Thread::Current() == worker_thread_);
325 ASSERT(channel == channel_);
326 ASSERT(flags == 0);
327
328 switch (quic_state_) {
329 case QUIC_TRANSPORT_NEW:
330 // This would occur if other peer is ready to start QUIC but this peer
331 // hasn't started QUIC.
332 LOG_J(INFO, this) << "Dropping packet received before QUIC started.";
333 break;
334 case QUIC_TRANSPORT_CONNECTING:
335 case QUIC_TRANSPORT_CONNECTED:
336 // We should only get QUIC or SRTP packets; STUN's already been demuxed.
337 // Is this potentially a QUIC packet?
338 if (IsQuicPacket(data, size)) {
339 if (!HandleQuicPacket(data, size)) {
340 LOG_J(ERROR, this) << "Failed to handle QUIC packet.";
341 return;
342 }
343 } else {
344 // If this is an RTP packet, signal upwards as a bypass packet.
345 if (!IsRtpPacket(data, size)) {
346 LOG_J(ERROR, this) << "Received unexpected non-QUIC, non-RTP packet.";
347 return;
348 }
349 SignalReadPacket(this, data, size, packet_time, PF_SRTP_BYPASS);
350 }
351 break;
352 case QUIC_TRANSPORT_FAILED:
353 // This shouldn't be happening. Drop the packet.
354 break;
355 }
356 }
357
358 void QuicTransportChannel::OnSentPacket(TransportChannel* channel,
359 const rtc::SentPacket& sent_packet) {
360 ASSERT(rtc::Thread::Current() == worker_thread_);
361 SignalSentPacket(this, sent_packet);
362 }
363
364 void QuicTransportChannel::OnReadyToSend(TransportChannel* channel) {
365 if (writable()) {
366 SignalReadyToSend(this);
367 }
368 }
369
370 void QuicTransportChannel::OnGatheringState(TransportChannelImpl* channel) {
371 ASSERT(channel == channel_);
372 SignalGatheringState(this);
373 }
374
375 void QuicTransportChannel::OnCandidateGathered(TransportChannelImpl* channel,
376 const Candidate& c) {
377 ASSERT(channel == channel_);
378 SignalCandidateGathered(this, c);
379 }
380
381 void QuicTransportChannel::OnRoleConflict(TransportChannelImpl* channel) {
382 ASSERT(channel == channel_);
383 SignalRoleConflict(this);
384 }
385
386 void QuicTransportChannel::OnRouteChange(TransportChannel* channel,
387 const Candidate& candidate) {
388 ASSERT(channel == channel_);
389 SignalRouteChange(this, candidate);
390 }
391
392 void QuicTransportChannel::OnConnectionRemoved(TransportChannelImpl* channel) {
393 ASSERT(channel == channel_);
394 SignalConnectionRemoved(this);
395 }
396
397 bool QuicTransportChannel::MaybeStartQuic() {
398 if (!channel_->writable()) {
399 LOG_J(ERROR, this) << "Couldn't start QUIC handshake.";
400 return false;
401 }
402 if (!CreateQuicSession() || !StartQuicHandshake()) {
403 LOG_J(WARNING, this) << "Underlying channel is writable but cannot start "
404 "the QUIC handshake.";
405 return false;
406 }
407 // Verify connection is not closed due to QUIC bug or network failure.
408 // A closed connection should not happen since |channel_| is writable.
409 if (!quic_->connection()->connected()) {
410 LOG_J(ERROR, this) << "QUIC connection should not be closed if underlying "
411 "channel is writable.";
412 return false;
413 }
414 // Indicate that |quic_| is ready to receive QUIC packets.
415 set_quic_state(QUIC_TRANSPORT_CONNECTING);
416 return true;
417 }
418
419 bool QuicTransportChannel::CreateQuicSession() {
420 if (!ssl_role_ || !remote_fingerprint_) {
421 return false;
422 }
423 net::Perspective perspective = (*ssl_role_ == rtc::SSL_CLIENT)
424 ? net::Perspective::IS_CLIENT
425 : net::Perspective::IS_SERVER;
426 bool owns_writer = false;
427 scoped_ptr<net::QuicConnection> connection(new net::QuicConnection(
428 kConnectionId, kConnectionIpEndpoint, &helper_, this, owns_writer,
429 perspective, net::QuicSupportedVersions()));
430 quic_.reset(new QuicSession(std::move(connection), config_));
431 quic_->SignalHandshakeComplete.connect(
432 this, &QuicTransportChannel::OnHandshakeComplete);
433 quic_->SignalConnectionClosed.connect(
434 this, &QuicTransportChannel::OnConnectionClosed);
435 return true;
436 }
437
438 bool QuicTransportChannel::StartQuicHandshake() {
439 if (*ssl_role_ == rtc::SSL_CLIENT) {
440 // Unique identifier for remote peer.
441 net::QuicServerId server_id(remote_fingerprint_->value, kQuicServerPort);
442 // Performs authentication of remote peer; owned by QuicCryptoClientConfig.
honghaiz3 2016/03/03 01:35:58 Performs=>Perform. Only add "s" when this is a com
mikescarlett 2016/03/03 02:19:20 Ok seems better.
443 // TODO(mikescarlett): Actually verify proof.
444 net::ProofVerifier* proof_verifier = new InsecureProofVerifier();
445 quic_crypto_client_config_.reset(
446 new net::QuicCryptoClientConfig(proof_verifier));
447 net::QuicCryptoClientStream* crypto_stream =
448 new net::QuicCryptoClientStream(server_id, quic_.get(),
449 new net::ProofVerifyContext(),
450 quic_crypto_client_config_.get(), this);
451 quic_->StartClientHandshake(crypto_stream);
452 LOG_J(INFO, this) << "QuicTransportChannel: Started client handshake.";
453 } else {
454 RTC_DCHECK_EQ(*ssl_role_, rtc::SSL_SERVER);
455 // Provides credentials to remote peer; owned by QuicCryptoServerConfig.
456 // TODO(mikescarlett): Actually provide credentials.
457 net::ProofSource* proof_source = new DummyProofSource();
458 // Input keying material to HKDF, per http://tools.ietf.org/html/rfc5869.
459 // This is pseudorandom so that HKDF-Extract outputs a pseudorandom key,
460 // since QuicCryptoServerConfig does not use a salt value.
461 std::string source_address_token_secret;
462 if (!rtc::CreateRandomString(kInputKeyingMaterialLength,
463 &source_address_token_secret)) {
464 LOG_J(ERROR, this) << "Error generating input keying material for HKDF.";
465 return false;
466 }
467 quic_crypto_server_config_.reset(new net::QuicCryptoServerConfig(
468 source_address_token_secret, helper_.GetRandomGenerator(),
469 proof_source));
470 // Provides server with serialized config string to prove ownership.
471 net::QuicCryptoServerConfig::ConfigOptions options;
472 quic_crypto_server_config_->AddDefaultConfig(helper_.GetRandomGenerator(),
473 helper_.GetClock(), options);
474 net::QuicCryptoServerStream* crypto_stream =
475 new net::QuicCryptoServerStream(quic_crypto_server_config_.get(),
476 quic_.get());
477 quic_->StartServerHandshake(crypto_stream);
478 LOG_J(INFO, this) << "QuicTransportChannel: Started server handshake.";
479 }
480 return true;
481 }
482
483 bool QuicTransportChannel::HandleQuicPacket(const char* data, size_t size) {
484 ASSERT(rtc::Thread::Current() == worker_thread_);
485 return quic_->OnReadPacket(data, size);
486 }
487
488 net::WriteResult QuicTransportChannel::WritePacket(
489 const char* buffer,
490 size_t buf_len,
491 const net::IPAddressNumber& self_address,
492 const net::IPEndPoint& peer_address) {
493 // QUIC should never call this if IsWriteBlocked, but just in case...
494 if (IsWriteBlocked()) {
495 return net::WriteResult(net::WRITE_STATUS_BLOCKED, EWOULDBLOCK);
496 }
497 // TODO(mikescarlett): Figure out how to tell QUIC "I dropped your packet, but
498 // don't block" without the QUIC connection tearing itself down.
499 int sent = channel_->SendPacket(buffer, buf_len, rtc::PacketOptions());
500 int bytes_written = sent > 0 ? sent : 0;
501 return net::WriteResult(net::WRITE_STATUS_OK, bytes_written);
502 }
503
504 // TODO(mikescarlett): Implement check for whether |channel_| is currently
505 // write blocked so that |quic_| does not try to write packet. This is
506 // necessary because |channel_| can be writable yet write blocked and
507 // channel_->GetError() is not updated when there is no error.
508 bool QuicTransportChannel::IsWriteBlocked() const {
509 return !channel_->writable();
510 }
511
512 void QuicTransportChannel::OnHandshakeComplete() {
513 set_quic_state(QUIC_TRANSPORT_CONNECTED);
514 set_writable(true);
515 }
516
517 // TODO(mikescarlett): Implement a new QUIC state that allows connection to
518 // be reset.
519 void QuicTransportChannel::OnConnectionClosed(net::QuicErrorCode error,
520 bool from_peer) {
521 LOG_J(INFO, this) << "Connection closed by " << (from_peer ? "other" : "this")
522 << " peer "
523 << "with QUIC error " << error;
524 set_quic_state(QUIC_TRANSPORT_FAILED);
honghaiz3 2016/03/02 22:47:45 Is this always a failed state? Could it be just th
mikescarlett 2016/03/03 02:19:20 I renamed this to QUIC_TRANSPORT_CLOSED. It isn't
525 set_writable(false);
526 }
527
528 void QuicTransportChannel::OnProofValid(
529 const net::QuicCryptoClientConfig::CachedState& cached) {
530 LOG_J(INFO, this) << "Cached proof marked valid";
531 }
532
533 void QuicTransportChannel::OnProofVerifyDetailsAvailable(
534 const net::ProofVerifyDetails& verify_details) {
535 LOG_J(INFO, this) << "Proof verify details available from"
536 << " QuicCryptoClientStream";
537 }
538
539 bool QuicTransportChannel::HasDataToWrite() const {
540 return quic_ && quic_->HasDataToWrite();
541 }
542
543 void QuicTransportChannel::OnCanWrite() {
544 RTC_DCHECK(quic_ != nullptr);
545 quic_->connection()->OnCanWrite();
546 }
547
548 void QuicTransportChannel::set_quic_state(QuicTransportState state) {
549 LOG_J(VERBOSE, this) << "set_quic_state from:" << quic_state_ << " to "
550 << state;
551 quic_state_ = state;
552 }
553
554 } // namespace cricket
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698