1 /*
2  *  Copyright 2009 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 #ifndef WEBRTC_P2P_BASE_FAKETRANSPORTCONTROLLER_H_
12 #define WEBRTC_P2P_BASE_FAKETRANSPORTCONTROLLER_H_
13 
14 #include <map>
15 #include <memory>
16 #include <string>
17 #include <vector>
18 
19 #include "webrtc/base/bind.h"
20 #include "webrtc/base/buffer.h"
21 #include "webrtc/base/fakesslidentity.h"
22 #include "webrtc/base/messagequeue.h"
23 #include "webrtc/base/sigslot.h"
24 #include "webrtc/base/sslfingerprint.h"
25 #include "webrtc/base/thread.h"
26 #include "webrtc/p2p/base/candidatepairinterface.h"
27 #include "webrtc/p2p/base/icetransportinternal.h"
28 #include "webrtc/p2p/base/transportchannel.h"
29 #include "webrtc/p2p/base/transportchannelimpl.h"
30 #include "webrtc/p2p/base/transportcontroller.h"
31 
32 #ifdef HAVE_QUIC
33 #include "webrtc/p2p/quic/quictransport.h"
34 #endif
35 
36 namespace cricket {
37 
38 namespace {
39 struct PacketMessageData : public rtc::MessageData {
PacketMessageDataPacketMessageData40   PacketMessageData(const char* data, size_t len) : packet(data, len) {}
41   rtc::Buffer packet;
42 };
43 }  // namespace
44 
45 class FakeIceTransport : public IceTransportInternal,
46                          public rtc::MessageHandler {
47  public:
FakeIceTransport(const std::string & name,int component)48   explicit FakeIceTransport(const std::string& name, int component)
49       : name_(name), component_(component) {}
~FakeIceTransport()50   ~FakeIceTransport() { Reset(); }
51 
transport_name()52   const std::string& transport_name() const override { return name_; }
component()53   int component() const override { return component_; }
IceTiebreaker()54   uint64_t IceTiebreaker() const { return tiebreaker_; }
remote_ice_mode()55   IceMode remote_ice_mode() const { return remote_ice_mode_; }
ice_ufrag()56   const std::string& ice_ufrag() const { return ice_ufrag_; }
ice_pwd()57   const std::string& ice_pwd() const { return ice_pwd_; }
remote_ice_ufrag()58   const std::string& remote_ice_ufrag() const { return remote_ice_ufrag_; }
remote_ice_pwd()59   const std::string& remote_ice_pwd() const { return remote_ice_pwd_; }
60 
61   // If async, will send packets by "Post"-ing to message queue instead of
62   // synchronously "Send"-ing.
SetAsync(bool async)63   void SetAsync(bool async) { async_ = async; }
SetAsyncDelay(int delay_ms)64   void SetAsyncDelay(int delay_ms) { async_delay_ms_ = delay_ms; }
65 
GetState()66   IceTransportState GetState() const override {
67     if (connection_count_ == 0) {
68       return had_connection_ ? IceTransportState::STATE_FAILED
69                              : IceTransportState::STATE_INIT;
70     }
71 
72     if (connection_count_ == 1) {
73       return IceTransportState::STATE_COMPLETED;
74     }
75 
76     return IceTransportState::STATE_CONNECTING;
77   }
78 
SetIceRole(IceRole role)79   void SetIceRole(IceRole role) override { role_ = role; }
GetIceRole()80   IceRole GetIceRole() const override { return role_; }
SetIceTiebreaker(uint64_t tiebreaker)81   void SetIceTiebreaker(uint64_t tiebreaker) override {
82     tiebreaker_ = tiebreaker;
83   }
SetIceParameters(const IceParameters & ice_params)84   void SetIceParameters(const IceParameters& ice_params) override {
85     ice_ufrag_ = ice_params.ufrag;
86     ice_pwd_ = ice_params.pwd;
87   }
SetRemoteIceParameters(const IceParameters & params)88   void SetRemoteIceParameters(const IceParameters& params) override {
89     remote_ice_ufrag_ = params.ufrag;
90     remote_ice_pwd_ = params.pwd;
91   }
92 
SetRemoteIceMode(IceMode mode)93   void SetRemoteIceMode(IceMode mode) override { remote_ice_mode_ = mode; }
94 
MaybeStartGathering()95   void MaybeStartGathering() override {
96     if (gathering_state_ == kIceGatheringNew) {
97       gathering_state_ = kIceGatheringGathering;
98       SignalGatheringState(this);
99     }
100   }
101 
gathering_state()102   IceGatheringState gathering_state() const override {
103     return gathering_state_;
104   }
105 
Reset()106   void Reset() {
107     if (state_ != STATE_INIT) {
108       state_ = STATE_INIT;
109       if (dest_) {
110         dest_->state_ = STATE_INIT;
111         dest_->dest_ = nullptr;
112         dest_ = nullptr;
113       }
114     }
115   }
116 
SetWritable(bool writable)117   void SetWritable(bool writable) { set_writable(writable); }
118 
set_writable(bool writable)119   void set_writable(bool writable) {
120     if (writable_ == writable) {
121       return;
122     }
123     LOG(INFO) << "set_writable from:" << writable_ << " to " << writable;
124     writable_ = writable;
125     if (writable_) {
126       SignalReadyToSend(this);
127     }
128     SignalWritableState(this);
129   }
writable()130   bool writable() const override { return writable_; }
131 
132   // Simulates the two transports connecting to each other.
133   // If |asymmetric| is true this method only affects this FakeIceTransport.
134   // If false, it affects |dest| as well.
135   void SetDestination(FakeIceTransport* dest, bool asymmetric = false) {
136     if (state_ == STATE_INIT && dest) {
137       // This simulates the delivery of candidates.
138       dest_ = dest;
139       state_ = STATE_CONNECTED;
140       set_writable(true);
141       if (!asymmetric) {
142         dest->SetDestination(this, true);
143       }
144     } else if (state_ == STATE_CONNECTED && !dest) {
145       // Simulates loss of connectivity, by asymmetrically forgetting dest_.
146       dest_ = nullptr;
147       state_ = STATE_INIT;
148       set_writable(false);
149     }
150   }
151 
SetConnectionCount(size_t connection_count)152   void SetConnectionCount(size_t connection_count) {
153     size_t old_connection_count = connection_count_;
154     connection_count_ = connection_count;
155     if (connection_count)
156       had_connection_ = true;
157     // In this fake transport channel, |connection_count_| determines the
158     // transport channel state.
159     if (connection_count_ < old_connection_count)
160       SignalStateChanged(this);
161   }
162 
SetCandidatesGatheringComplete()163   void SetCandidatesGatheringComplete() {
164     if (gathering_state_ != kIceGatheringComplete) {
165       gathering_state_ = kIceGatheringComplete;
166       SignalGatheringState(this);
167     }
168   }
169 
SetReceiving(bool receiving)170   void SetReceiving(bool receiving) { set_receiving(receiving); }
171 
set_receiving(bool receiving)172   void set_receiving(bool receiving) {
173     if (receiving_ == receiving) {
174       return;
175     }
176     receiving_ = receiving;
177     SignalReceivingState(this);
178   }
receiving()179   bool receiving() const override { return receiving_; }
180 
SetIceConfig(const IceConfig & config)181   void SetIceConfig(const IceConfig& config) override { ice_config_ = config; }
182 
receiving_timeout()183   int receiving_timeout() const { return ice_config_.receiving_timeout; }
gather_continually()184   bool gather_continually() const { return ice_config_.gather_continually(); }
185 
SendPacket(const char * data,size_t len,const rtc::PacketOptions & options,int flags)186   int SendPacket(const char* data,
187                  size_t len,
188                  const rtc::PacketOptions& options,
189                  int flags) override {
190     if (state_ != STATE_CONNECTED) {
191       return -1;
192     }
193 
194     if (flags != PF_SRTP_BYPASS && flags != 0) {
195       return -1;
196     }
197 
198     PacketMessageData* packet = new PacketMessageData(data, len);
199     if (async_) {
200       if (async_delay_ms_) {
201         rtc::Thread::Current()->PostDelayed(RTC_FROM_HERE, async_delay_ms_,
202                                             this, 0, packet);
203       } else {
204         rtc::Thread::Current()->Post(RTC_FROM_HERE, this, 0, packet);
205       }
206     } else {
207       rtc::Thread::Current()->Send(RTC_FROM_HERE, this, 0, packet);
208     }
209     rtc::SentPacket sent_packet(options.packet_id, rtc::TimeMillis());
210     SignalSentPacket(this, sent_packet);
211     return static_cast<int>(len);
212   }
SetOption(rtc::Socket::Option opt,int value)213   int SetOption(rtc::Socket::Option opt, int value) override { return true; }
GetOption(rtc::Socket::Option opt,int * value)214   bool GetOption(rtc::Socket::Option opt, int* value) override { return true; }
GetError()215   int GetError() override { return 0; }
216 
AddRemoteCandidate(const Candidate & candidate)217   void AddRemoteCandidate(const Candidate& candidate) override {
218     remote_candidates_.push_back(candidate);
219   }
220 
RemoveRemoteCandidate(const Candidate & candidate)221   void RemoveRemoteCandidate(const Candidate& candidate) override {}
222 
remote_candidates()223   const Candidates& remote_candidates() const { return remote_candidates_; }
224 
OnMessage(rtc::Message * msg)225   void OnMessage(rtc::Message* msg) override {
226     PacketMessageData* data = static_cast<PacketMessageData*>(msg->pdata);
227     dest_->SignalReadPacket(dest_, data->packet.data<char>(),
228                             data->packet.size(), rtc::CreatePacketTime(0), 0);
229     delete data;
230   }
231 
GetStats(ConnectionInfos * infos)232   bool GetStats(ConnectionInfos* infos) override {
233     ConnectionInfo info;
234     infos->clear();
235     infos->push_back(info);
236     return true;
237   }
238 
SetMetricsObserver(webrtc::MetricsObserverInterface * observer)239   void SetMetricsObserver(webrtc::MetricsObserverInterface* observer) override {
240   }
241 
242  private:
243   std::string name_;
244   int component_;
245   enum State { STATE_INIT, STATE_CONNECTED };
246   FakeIceTransport* dest_ = nullptr;
247   State state_ = STATE_INIT;
248   bool async_ = false;
249   int async_delay_ms_ = 0;
250   Candidates remote_candidates_;
251   IceConfig ice_config_;
252   IceRole role_ = ICEROLE_UNKNOWN;
253   uint64_t tiebreaker_ = 0;
254   std::string ice_ufrag_;
255   std::string ice_pwd_;
256   std::string remote_ice_ufrag_;
257   std::string remote_ice_pwd_;
258   IceMode remote_ice_mode_ = ICEMODE_FULL;
259   size_t connection_count_ = 0;
260   IceGatheringState gathering_state_ = kIceGatheringNew;
261   bool had_connection_ = false;
262   bool writable_ = false;
263   bool receiving_ = false;
264 };
265 
266 // Fake transport channel class, which can be passed to anything that needs a
267 // transport channel. Can be informed of another FakeTransportChannel via
268 // SetDestination.
269 // TODO(hbos): Move implementation to .cc file, this and other classes in file.
270 class FakeTransportChannel : public TransportChannelImpl,
271                              public rtc::MessageHandler {
272  public:
FakeTransportChannel(const std::string & name,int component)273   explicit FakeTransportChannel(const std::string& name, int component)
274       : TransportChannelImpl(name, component),
275         dtls_fingerprint_("", nullptr, 0) {}
~FakeTransportChannel()276   ~FakeTransportChannel() { Reset(); }
277 
IceTiebreaker()278   uint64_t IceTiebreaker() const { return tiebreaker_; }
remote_ice_mode()279   IceMode remote_ice_mode() const { return remote_ice_mode_; }
ice_ufrag()280   const std::string& ice_ufrag() const { return ice_ufrag_; }
ice_pwd()281   const std::string& ice_pwd() const { return ice_pwd_; }
remote_ice_ufrag()282   const std::string& remote_ice_ufrag() const { return remote_ice_ufrag_; }
remote_ice_pwd()283   const std::string& remote_ice_pwd() const { return remote_ice_pwd_; }
dtls_fingerprint()284   const rtc::SSLFingerprint& dtls_fingerprint() const {
285     return dtls_fingerprint_;
286   }
287 
288   // If async, will send packets by "Post"-ing to message queue instead of
289   // synchronously "Send"-ing.
SetAsync(bool async)290   void SetAsync(bool async) { async_ = async; }
SetAsyncDelay(int delay_ms)291   void SetAsyncDelay(int delay_ms) { async_delay_ms_ = delay_ms; }
292 
GetState()293   IceTransportState GetState() const override {
294     if (connection_count_ == 0) {
295       return had_connection_ ? IceTransportState::STATE_FAILED
296                              : IceTransportState::STATE_INIT;
297     }
298 
299     if (connection_count_ == 1) {
300       return IceTransportState::STATE_COMPLETED;
301     }
302 
303     return IceTransportState::STATE_CONNECTING;
304   }
305 
SetIceRole(IceRole role)306   void SetIceRole(IceRole role) override { role_ = role; }
GetIceRole()307   IceRole GetIceRole() const override { return role_; }
SetIceTiebreaker(uint64_t tiebreaker)308   void SetIceTiebreaker(uint64_t tiebreaker) override {
309     tiebreaker_ = tiebreaker;
310   }
SetIceParameters(const IceParameters & ice_params)311   void SetIceParameters(const IceParameters& ice_params) override {
312     ice_ufrag_ = ice_params.ufrag;
313     ice_pwd_ = ice_params.pwd;
314   }
SetRemoteIceParameters(const IceParameters & params)315   void SetRemoteIceParameters(const IceParameters& params) override {
316     remote_ice_ufrag_ = params.ufrag;
317     remote_ice_pwd_ = params.pwd;
318   }
319 
SetRemoteIceMode(IceMode mode)320   void SetRemoteIceMode(IceMode mode) override { remote_ice_mode_ = mode; }
SetRemoteFingerprint(const std::string & alg,const uint8_t * digest,size_t digest_len)321   bool SetRemoteFingerprint(const std::string& alg,
322                             const uint8_t* digest,
323                             size_t digest_len) override {
324     dtls_fingerprint_ = rtc::SSLFingerprint(alg, digest, digest_len);
325     return true;
326   }
SetSslRole(rtc::SSLRole role)327   bool SetSslRole(rtc::SSLRole role) override {
328     ssl_role_ = role;
329     return true;
330   }
GetSslRole(rtc::SSLRole * role)331   bool GetSslRole(rtc::SSLRole* role) const override {
332     *role = ssl_role_;
333     return true;
334   }
335 
MaybeStartGathering()336   void MaybeStartGathering() override {
337     if (gathering_state_ == kIceGatheringNew) {
338       gathering_state_ = kIceGatheringGathering;
339       SignalGatheringState(this);
340     }
341   }
342 
gathering_state()343   IceGatheringState gathering_state() const override {
344     return gathering_state_;
345   }
346 
Reset()347   void Reset() {
348     if (state_ != STATE_INIT) {
349       state_ = STATE_INIT;
350       if (dest_) {
351         dest_->state_ = STATE_INIT;
352         dest_->dest_ = nullptr;
353         dest_ = nullptr;
354       }
355     }
356   }
357 
SetWritable(bool writable)358   void SetWritable(bool writable) { set_writable(writable); }
359 
360   // Simulates the two transport channels connecting to each other.
361   // If |asymmetric| is true this method only affects this FakeTransportChannel.
362   // If false, it affects |dest| as well.
363   void SetDestination(FakeTransportChannel* dest, bool asymmetric = false) {
364     if (state_ == STATE_INIT && dest) {
365       // This simulates the delivery of candidates.
366       dest_ = dest;
367       if (local_cert_ && dest_->local_cert_) {
368         do_dtls_ = true;
369         NegotiateSrtpCiphers();
370       }
371       state_ = STATE_CONNECTED;
372       set_writable(true);
373       if (!asymmetric) {
374         dest->SetDestination(this, true);
375       }
376     } else if (state_ == STATE_CONNECTED && !dest) {
377       // Simulates loss of connectivity, by asymmetrically forgetting dest_.
378       dest_ = nullptr;
379       state_ = STATE_INIT;
380       set_writable(false);
381     }
382   }
383 
SetConnectionCount(size_t connection_count)384   void SetConnectionCount(size_t connection_count) {
385     size_t old_connection_count = connection_count_;
386     connection_count_ = connection_count;
387     if (connection_count)
388       had_connection_ = true;
389     // In this fake transport channel, |connection_count_| determines the
390     // transport channel state.
391     if (connection_count_ < old_connection_count)
392       SignalStateChanged(this);
393   }
394 
SetCandidatesGatheringComplete()395   void SetCandidatesGatheringComplete() {
396     if (gathering_state_ != kIceGatheringComplete) {
397       gathering_state_ = kIceGatheringComplete;
398       SignalGatheringState(this);
399     }
400   }
401 
SetReceiving(bool receiving)402   void SetReceiving(bool receiving) { set_receiving(receiving); }
403 
SetIceConfig(const IceConfig & config)404   void SetIceConfig(const IceConfig& config) override { ice_config_ = config; }
405 
receiving_timeout()406   int receiving_timeout() const { return ice_config_.receiving_timeout; }
gather_continually()407   bool gather_continually() const { return ice_config_.gather_continually(); }
408 
SendPacket(const char * data,size_t len,const rtc::PacketOptions & options,int flags)409   int SendPacket(const char* data,
410                  size_t len,
411                  const rtc::PacketOptions& options,
412                  int flags) override {
413     if (state_ != STATE_CONNECTED) {
414       return -1;
415     }
416 
417     if (flags != PF_SRTP_BYPASS && flags != 0) {
418       return -1;
419     }
420 
421     PacketMessageData* packet = new PacketMessageData(data, len);
422     if (async_) {
423       if (async_delay_ms_) {
424         rtc::Thread::Current()->PostDelayed(RTC_FROM_HERE, async_delay_ms_,
425                                             this, 0, packet);
426       } else {
427         rtc::Thread::Current()->Post(RTC_FROM_HERE, this, 0, packet);
428       }
429     } else {
430       rtc::Thread::Current()->Send(RTC_FROM_HERE, this, 0, packet);
431     }
432     rtc::SentPacket sent_packet(options.packet_id, rtc::TimeMillis());
433     SignalSentPacket(this, sent_packet);
434     return static_cast<int>(len);
435   }
SetOption(rtc::Socket::Option opt,int value)436   int SetOption(rtc::Socket::Option opt, int value) override { return true; }
GetOption(rtc::Socket::Option opt,int * value)437   bool GetOption(rtc::Socket::Option opt, int* value) override { return true; }
GetError()438   int GetError() override { return 0; }
439 
AddRemoteCandidate(const Candidate & candidate)440   void AddRemoteCandidate(const Candidate& candidate) override {
441     remote_candidates_.push_back(candidate);
442   }
443 
RemoveRemoteCandidate(const Candidate & candidate)444   void RemoveRemoteCandidate(const Candidate& candidate) override {}
445 
remote_candidates()446   const Candidates& remote_candidates() const { return remote_candidates_; }
447 
OnMessage(rtc::Message * msg)448   void OnMessage(rtc::Message* msg) override {
449     PacketMessageData* data = static_cast<PacketMessageData*>(msg->pdata);
450     dest_->SignalReadPacket(dest_, data->packet.data<char>(),
451                             data->packet.size(), rtc::CreatePacketTime(0), 0);
452     delete data;
453   }
454 
SetLocalCertificate(const rtc::scoped_refptr<rtc::RTCCertificate> & certificate)455   bool SetLocalCertificate(
456       const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) override {
457     local_cert_ = certificate;
458     return true;
459   }
460 
SetRemoteSSLCertificate(rtc::FakeSSLCertificate * cert)461   void SetRemoteSSLCertificate(rtc::FakeSSLCertificate* cert) {
462     remote_cert_ = cert;
463   }
464 
IsDtlsActive()465   bool IsDtlsActive() const override { return do_dtls_; }
466 
SetSrtpCryptoSuites(const std::vector<int> & ciphers)467   bool SetSrtpCryptoSuites(const std::vector<int>& ciphers) override {
468     srtp_ciphers_ = ciphers;
469     return true;
470   }
471 
GetSrtpCryptoSuite(int * crypto_suite)472   bool GetSrtpCryptoSuite(int* crypto_suite) override {
473     if (chosen_crypto_suite_ != rtc::SRTP_INVALID_CRYPTO_SUITE) {
474       *crypto_suite = chosen_crypto_suite_;
475       return true;
476     }
477     return false;
478   }
479 
GetSslCipherSuite(int * cipher_suite)480   bool GetSslCipherSuite(int* cipher_suite) override { return false; }
481 
GetLocalCertificate()482   rtc::scoped_refptr<rtc::RTCCertificate> GetLocalCertificate() const override {
483     return local_cert_;
484   }
485 
GetRemoteSSLCertificate()486   std::unique_ptr<rtc::SSLCertificate> GetRemoteSSLCertificate()
487       const override {
488     return remote_cert_ ? std::unique_ptr<rtc::SSLCertificate>(
489                               remote_cert_->GetReference())
490                         : nullptr;
491   }
492 
ExportKeyingMaterial(const std::string & label,const uint8_t * context,size_t context_len,bool use_context,uint8_t * result,size_t result_len)493   bool ExportKeyingMaterial(const std::string& label,
494                             const uint8_t* context,
495                             size_t context_len,
496                             bool use_context,
497                             uint8_t* result,
498                             size_t result_len) override {
499     if (chosen_crypto_suite_ != rtc::SRTP_INVALID_CRYPTO_SUITE) {
500       memset(result, 0xff, result_len);
501       return true;
502     }
503 
504     return false;
505   }
506 
GetStats(ConnectionInfos * infos)507   bool GetStats(ConnectionInfos* infos) override {
508     ConnectionInfo info;
509     infos->clear();
510     infos->push_back(info);
511     return true;
512   }
513 
set_ssl_max_protocol_version(rtc::SSLProtocolVersion version)514   void set_ssl_max_protocol_version(rtc::SSLProtocolVersion version) {
515     ssl_max_version_ = version;
516   }
ssl_max_protocol_version()517   rtc::SSLProtocolVersion ssl_max_protocol_version() const {
518     return ssl_max_version_;
519   }
520 
SetMetricsObserver(webrtc::MetricsObserverInterface * observer)521   void SetMetricsObserver(webrtc::MetricsObserverInterface* observer) override {
522   }
523 
524  private:
NegotiateSrtpCiphers()525   void NegotiateSrtpCiphers() {
526     for (std::vector<int>::const_iterator it1 = srtp_ciphers_.begin();
527          it1 != srtp_ciphers_.end(); ++it1) {
528       for (std::vector<int>::const_iterator it2 = dest_->srtp_ciphers_.begin();
529            it2 != dest_->srtp_ciphers_.end(); ++it2) {
530         if (*it1 == *it2) {
531           chosen_crypto_suite_ = *it1;
532           return;
533         }
534       }
535     }
536   }
537 
538   enum State { STATE_INIT, STATE_CONNECTED };
539   FakeTransportChannel* dest_ = nullptr;
540   State state_ = STATE_INIT;
541   bool async_ = false;
542   int async_delay_ms_ = 0;
543   Candidates remote_candidates_;
544   rtc::scoped_refptr<rtc::RTCCertificate> local_cert_;
545   rtc::FakeSSLCertificate* remote_cert_ = nullptr;
546   bool do_dtls_ = false;
547   std::vector<int> srtp_ciphers_;
548   int chosen_crypto_suite_ = rtc::SRTP_INVALID_CRYPTO_SUITE;
549   IceConfig ice_config_;
550   IceRole role_ = ICEROLE_UNKNOWN;
551   uint64_t tiebreaker_ = 0;
552   std::string ice_ufrag_;
553   std::string ice_pwd_;
554   std::string remote_ice_ufrag_;
555   std::string remote_ice_pwd_;
556   IceMode remote_ice_mode_ = ICEMODE_FULL;
557   rtc::SSLProtocolVersion ssl_max_version_ = rtc::SSL_PROTOCOL_DTLS_12;
558   rtc::SSLFingerprint dtls_fingerprint_;
559   rtc::SSLRole ssl_role_ = rtc::SSL_CLIENT;
560   size_t connection_count_ = 0;
561   IceGatheringState gathering_state_ = kIceGatheringNew;
562   bool had_connection_ = false;
563 };
564 
565 // Fake candidate pair class, which can be passed to BaseChannel for testing
566 // purposes.
567 class FakeCandidatePair : public CandidatePairInterface {
568  public:
FakeCandidatePair(const Candidate & local_candidate,const Candidate & remote_candidate)569   FakeCandidatePair(const Candidate& local_candidate,
570                     const Candidate& remote_candidate)
571       : local_candidate_(local_candidate),
572         remote_candidate_(remote_candidate) {}
local_candidate()573   const Candidate& local_candidate() const override { return local_candidate_; }
remote_candidate()574   const Candidate& remote_candidate() const override {
575     return remote_candidate_;
576   }
577 
578  private:
579   Candidate local_candidate_;
580   Candidate remote_candidate_;
581 };
582 
583 // Fake TransportController class, which can be passed into a BaseChannel object
584 // for test purposes. Can be connected to other FakeTransportControllers via
585 // Connect().
586 //
587 // This fake is unusual in that for the most part, it's implemented with the
588 // real TransportController code, but with fake TransportChannels underneath.
589 class FakeTransportController : public TransportController {
590  public:
FakeTransportController()591   FakeTransportController()
592       : TransportController(rtc::Thread::Current(),
593                             rtc::Thread::Current(),
594                             nullptr) {}
595 
FakeTransportController(bool redetermine_role_on_ice_restart)596   explicit FakeTransportController(bool redetermine_role_on_ice_restart)
597       : TransportController(rtc::Thread::Current(),
598                             rtc::Thread::Current(),
599                             nullptr,
600                             redetermine_role_on_ice_restart) {}
601 
FakeTransportController(IceRole role)602   explicit FakeTransportController(IceRole role)
603       : TransportController(rtc::Thread::Current(),
604                             rtc::Thread::Current(),
605                             nullptr) {
606     SetIceRole(role);
607   }
608 
FakeTransportController(rtc::Thread * network_thread)609   explicit FakeTransportController(rtc::Thread* network_thread)
610       : TransportController(rtc::Thread::Current(), network_thread, nullptr) {}
611 
FakeTransportController(rtc::Thread * network_thread,IceRole role)612   FakeTransportController(rtc::Thread* network_thread, IceRole role)
613       : TransportController(rtc::Thread::Current(), network_thread, nullptr) {
614     SetIceRole(role);
615   }
616 
GetFakeTransportChannel_n(const std::string & transport_name,int component)617   FakeTransportChannel* GetFakeTransportChannel_n(
618       const std::string& transport_name,
619       int component) {
620     return static_cast<FakeTransportChannel*>(
621         get_channel_for_testing(transport_name, component));
622   }
623 
624   // Simulate the exchange of transport descriptions, and the gathering and
625   // exchange of ICE candidates.
Connect(FakeTransportController * dest)626   void Connect(FakeTransportController* dest) {
627     for (const std::string& transport_name : transport_names_for_testing()) {
628       std::unique_ptr<rtc::SSLFingerprint> local_fingerprint;
629       std::unique_ptr<rtc::SSLFingerprint> remote_fingerprint;
630       if (certificate_for_testing()) {
631         local_fingerprint.reset(rtc::SSLFingerprint::CreateFromCertificate(
632             certificate_for_testing()));
633       }
634       if (dest->certificate_for_testing()) {
635         remote_fingerprint.reset(rtc::SSLFingerprint::CreateFromCertificate(
636             dest->certificate_for_testing()));
637       }
638       TransportDescription local_desc(
639           std::vector<std::string>(),
640           rtc::CreateRandomString(cricket::ICE_UFRAG_LENGTH),
641           rtc::CreateRandomString(cricket::ICE_PWD_LENGTH),
642           cricket::ICEMODE_FULL, cricket::CONNECTIONROLE_NONE,
643           local_fingerprint.get());
644       TransportDescription remote_desc(
645           std::vector<std::string>(),
646           rtc::CreateRandomString(cricket::ICE_UFRAG_LENGTH),
647           rtc::CreateRandomString(cricket::ICE_PWD_LENGTH),
648           cricket::ICEMODE_FULL, cricket::CONNECTIONROLE_NONE,
649           remote_fingerprint.get());
650       std::string err;
651       SetLocalTransportDescription(transport_name, local_desc,
652                                    cricket::CA_OFFER, &err);
653       dest->SetRemoteTransportDescription(transport_name, local_desc,
654                                           cricket::CA_OFFER, &err);
655       dest->SetLocalTransportDescription(transport_name, remote_desc,
656                                          cricket::CA_ANSWER, &err);
657       SetRemoteTransportDescription(transport_name, remote_desc,
658                                     cricket::CA_ANSWER, &err);
659     }
660     MaybeStartGathering();
661     dest->MaybeStartGathering();
662     network_thread()->Invoke<void>(
663         RTC_FROM_HERE,
664         rtc::Bind(&FakeTransportController::SetChannelDestinations_n, this,
665                   dest));
666   }
667 
CreateFakeCandidatePair(const rtc::SocketAddress & local_address,int16_t local_network_id,const rtc::SocketAddress & remote_address,int16_t remote_network_id)668   FakeCandidatePair* CreateFakeCandidatePair(
669       const rtc::SocketAddress& local_address,
670       int16_t local_network_id,
671       const rtc::SocketAddress& remote_address,
672       int16_t remote_network_id) {
673     Candidate local_candidate(0, "udp", local_address, 0u, "", "", "local", 0,
674                               "foundation", local_network_id, 0);
675     Candidate remote_candidate(0, "udp", remote_address, 0u, "", "", "local", 0,
676                                "foundation", remote_network_id, 0);
677     return new FakeCandidatePair(local_candidate, remote_candidate);
678   }
679 
DestroyRtcpTransport(const std::string & transport_name)680   void DestroyRtcpTransport(const std::string& transport_name) {
681     DestroyTransportChannel_n(transport_name,
682                               cricket::ICE_CANDIDATE_COMPONENT_RTCP);
683   }
684 
685  protected:
686   // The ICE channel is never actually used by TransportController directly,
687   // since (currently) the DTLS channel pretends to be both ICE + DTLS. This
688   // will change when we get rid of TransportChannelImpl.
CreateIceTransportChannel_n(const std::string & transport_name,int component)689   IceTransportInternal* CreateIceTransportChannel_n(
690       const std::string& transport_name,
691       int component) override {
692     return nullptr;
693   }
694 
CreateDtlsTransportChannel_n(const std::string & transport_name,int component,IceTransportInternal *)695   TransportChannelImpl* CreateDtlsTransportChannel_n(
696       const std::string& transport_name,
697       int component,
698       IceTransportInternal*) override {
699     return new FakeTransportChannel(transport_name, component);
700   }
701 
702  private:
SetChannelDestinations_n(FakeTransportController * dest)703   void SetChannelDestinations_n(FakeTransportController* dest) {
704     for (TransportChannelImpl* tc : channels_for_testing()) {
705       FakeTransportChannel* local = static_cast<FakeTransportChannel*>(tc);
706       FakeTransportChannel* remote = dest->GetFakeTransportChannel_n(
707           local->transport_name(), local->component());
708       if (remote) {
709         bool asymmetric = false;
710         local->SetDestination(remote, asymmetric);
711       }
712     }
713   }
714 };
715 
716 }  // namespace cricket
717 
718 #endif  // WEBRTC_P2P_BASE_FAKETRANSPORTCONTROLLER_H_
719