• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright 2004 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 "p2p/base/port.h"
12 
13 #include <string.h>
14 
15 #include <cstdint>
16 #include <limits>
17 #include <list>
18 #include <memory>
19 #include <string>
20 #include <utility>
21 #include <vector>
22 
23 #include "absl/types/optional.h"
24 #include "api/candidate.h"
25 #include "api/packet_socket_factory.h"
26 #include "api/transport/stun.h"
27 #include "api/units/time_delta.h"
28 #include "p2p/base/basic_packet_socket_factory.h"
29 #include "p2p/base/p2p_constants.h"
30 #include "p2p/base/port_allocator.h"
31 #include "p2p/base/port_interface.h"
32 #include "p2p/base/stun_port.h"
33 #include "p2p/base/stun_server.h"
34 #include "p2p/base/tcp_port.h"
35 #include "p2p/base/test_stun_server.h"
36 #include "p2p/base/test_turn_server.h"
37 #include "p2p/base/transport_description.h"
38 #include "p2p/base/turn_port.h"
39 #include "p2p/base/turn_server.h"
40 #include "p2p/client/relay_port_factory_interface.h"
41 #include "rtc_base/arraysize.h"
42 #include "rtc_base/async_packet_socket.h"
43 #include "rtc_base/async_socket.h"
44 #include "rtc_base/buffer.h"
45 #include "rtc_base/byte_buffer.h"
46 #include "rtc_base/checks.h"
47 #include "rtc_base/dscp.h"
48 #include "rtc_base/fake_clock.h"
49 #include "rtc_base/gunit.h"
50 #include "rtc_base/helpers.h"
51 #include "rtc_base/logging.h"
52 #include "rtc_base/nat_server.h"
53 #include "rtc_base/nat_socket_factory.h"
54 #include "rtc_base/nat_types.h"
55 #include "rtc_base/net_helper.h"
56 #include "rtc_base/network.h"
57 #include "rtc_base/network/sent_packet.h"
58 #include "rtc_base/network_constants.h"
59 #include "rtc_base/proxy_info.h"
60 #include "rtc_base/socket.h"
61 #include "rtc_base/socket_adapters.h"
62 #include "rtc_base/socket_address.h"
63 #include "rtc_base/third_party/sigslot/sigslot.h"
64 #include "rtc_base/thread.h"
65 #include "rtc_base/time_utils.h"
66 #include "rtc_base/virtual_socket_server.h"
67 #include "test/field_trial.h"
68 #include "test/gtest.h"
69 
70 using rtc::AsyncPacketSocket;
71 using rtc::ByteBufferReader;
72 using rtc::ByteBufferWriter;
73 using rtc::NAT_ADDR_RESTRICTED;
74 using rtc::NAT_OPEN_CONE;
75 using rtc::NAT_PORT_RESTRICTED;
76 using rtc::NAT_SYMMETRIC;
77 using rtc::NATType;
78 using rtc::PacketSocketFactory;
79 using rtc::Socket;
80 using rtc::SocketAddress;
81 
82 namespace cricket {
83 namespace {
84 
85 constexpr int kDefaultTimeout = 3000;
86 constexpr int kShortTimeout = 1000;
87 constexpr int kMaxExpectedSimulatedRtt = 200;
88 const SocketAddress kLocalAddr1("192.168.1.2", 0);
89 const SocketAddress kLocalAddr2("192.168.1.3", 0);
90 const SocketAddress kNatAddr1("77.77.77.77", rtc::NAT_SERVER_UDP_PORT);
91 const SocketAddress kNatAddr2("88.88.88.88", rtc::NAT_SERVER_UDP_PORT);
92 const SocketAddress kStunAddr("99.99.99.1", STUN_SERVER_PORT);
93 const SocketAddress kTurnUdpIntAddr("99.99.99.4", STUN_SERVER_PORT);
94 const SocketAddress kTurnTcpIntAddr("99.99.99.4", 5010);
95 const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0);
96 const RelayCredentials kRelayCredentials("test", "test");
97 
98 // TODO(?): Update these when RFC5245 is completely supported.
99 // Magic value of 30 is from RFC3484, for IPv4 addresses.
100 const uint32_t kDefaultPrflxPriority = ICE_TYPE_PREFERENCE_PRFLX << 24 |
101                                        30 << 8 |
102                                        (256 - ICE_CANDIDATE_COMPONENT_DEFAULT);
103 
104 constexpr int kTiebreaker1 = 11111;
105 constexpr int kTiebreaker2 = 22222;
106 
107 const char* data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
108 
GetCandidate(Port * port)109 Candidate GetCandidate(Port* port) {
110   RTC_DCHECK_GE(port->Candidates().size(), 1);
111   return port->Candidates()[0];
112 }
113 
GetAddress(Port * port)114 SocketAddress GetAddress(Port* port) {
115   return GetCandidate(port).address();
116 }
117 
CopyStunMessage(const IceMessage & src)118 std::unique_ptr<IceMessage> CopyStunMessage(const IceMessage& src) {
119   auto dst = std::make_unique<IceMessage>();
120   ByteBufferWriter buf;
121   src.Write(&buf);
122   ByteBufferReader read_buf(buf);
123   dst->Read(&read_buf);
124   return dst;
125 }
126 
WriteStunMessage(const StunMessage & msg,ByteBufferWriter * buf)127 bool WriteStunMessage(const StunMessage& msg, ByteBufferWriter* buf) {
128   buf->Resize(0);  // clear out any existing buffer contents
129   return msg.Write(buf);
130 }
131 
132 }  // namespace
133 
134 // Stub port class for testing STUN generation and processing.
135 class TestPort : public Port {
136  public:
TestPort(rtc::Thread * thread,const std::string & type,rtc::PacketSocketFactory * factory,rtc::Network * network,uint16_t min_port,uint16_t max_port,const std::string & username_fragment,const std::string & password)137   TestPort(rtc::Thread* thread,
138            const std::string& type,
139            rtc::PacketSocketFactory* factory,
140            rtc::Network* network,
141            uint16_t min_port,
142            uint16_t max_port,
143            const std::string& username_fragment,
144            const std::string& password)
145       : Port(thread,
146              type,
147              factory,
148              network,
149              min_port,
150              max_port,
151              username_fragment,
152              password) {}
~TestPort()153   ~TestPort() {}
154 
155   // Expose GetStunMessage so that we can test it.
156   using cricket::Port::GetStunMessage;
157 
158   // The last StunMessage that was sent on this Port.
159   // TODO(?): Make these const; requires changes to SendXXXXResponse.
last_stun_buf()160   rtc::BufferT<uint8_t>* last_stun_buf() { return last_stun_buf_.get(); }
last_stun_msg()161   IceMessage* last_stun_msg() { return last_stun_msg_.get(); }
last_stun_error_code()162   int last_stun_error_code() {
163     int code = 0;
164     if (last_stun_msg_) {
165       const StunErrorCodeAttribute* error_attr = last_stun_msg_->GetErrorCode();
166       if (error_attr) {
167         code = error_attr->code();
168       }
169     }
170     return code;
171   }
172 
PrepareAddress()173   virtual void PrepareAddress() {
174     // Act as if the socket was bound to the best IP on the network, to the
175     // first port in the allowed range.
176     rtc::SocketAddress addr(Network()->GetBestIP(), min_port());
177     AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", "", Type(),
178                ICE_TYPE_PREFERENCE_HOST, 0, "", true);
179   }
180 
SupportsProtocol(const std::string & protocol) const181   virtual bool SupportsProtocol(const std::string& protocol) const {
182     return true;
183   }
184 
GetProtocol() const185   virtual ProtocolType GetProtocol() const { return PROTO_UDP; }
186 
187   // Exposed for testing candidate building.
AddCandidateAddress(const rtc::SocketAddress & addr)188   void AddCandidateAddress(const rtc::SocketAddress& addr) {
189     AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", "", Type(),
190                type_preference_, 0, "", false);
191   }
AddCandidateAddress(const rtc::SocketAddress & addr,const rtc::SocketAddress & base_address,const std::string & type,int type_preference,bool final)192   void AddCandidateAddress(const rtc::SocketAddress& addr,
193                            const rtc::SocketAddress& base_address,
194                            const std::string& type,
195                            int type_preference,
196                            bool final) {
197     AddAddress(addr, base_address, rtc::SocketAddress(), "udp", "", "", type,
198                type_preference, 0, "", final);
199   }
200 
CreateConnection(const Candidate & remote_candidate,CandidateOrigin origin)201   virtual Connection* CreateConnection(const Candidate& remote_candidate,
202                                        CandidateOrigin origin) {
203     Connection* conn = new ProxyConnection(this, 0, remote_candidate);
204     AddOrReplaceConnection(conn);
205     // Set use-candidate attribute flag as this will add USE-CANDIDATE attribute
206     // in STUN binding requests.
207     conn->set_use_candidate_attr(true);
208     return conn;
209   }
SendTo(const void * data,size_t size,const rtc::SocketAddress & addr,const rtc::PacketOptions & options,bool payload)210   virtual int SendTo(const void* data,
211                      size_t size,
212                      const rtc::SocketAddress& addr,
213                      const rtc::PacketOptions& options,
214                      bool payload) {
215     if (!payload) {
216       auto msg = std::make_unique<IceMessage>();
217       auto buf = std::make_unique<rtc::BufferT<uint8_t>>(
218           static_cast<const char*>(data), size);
219       ByteBufferReader read_buf(*buf);
220       if (!msg->Read(&read_buf)) {
221         return -1;
222       }
223       last_stun_buf_ = std::move(buf);
224       last_stun_msg_ = std::move(msg);
225     }
226     return static_cast<int>(size);
227   }
SetOption(rtc::Socket::Option opt,int value)228   virtual int SetOption(rtc::Socket::Option opt, int value) { return 0; }
GetOption(rtc::Socket::Option opt,int * value)229   virtual int GetOption(rtc::Socket::Option opt, int* value) { return -1; }
GetError()230   virtual int GetError() { return 0; }
Reset()231   void Reset() {
232     last_stun_buf_.reset();
233     last_stun_msg_.reset();
234   }
set_type_preference(int type_preference)235   void set_type_preference(int type_preference) {
236     type_preference_ = type_preference;
237   }
238 
239  private:
OnSentPacket(rtc::AsyncPacketSocket * socket,const rtc::SentPacket & sent_packet)240   void OnSentPacket(rtc::AsyncPacketSocket* socket,
241                     const rtc::SentPacket& sent_packet) {
242     PortInterface::SignalSentPacket(sent_packet);
243   }
244   std::unique_ptr<rtc::BufferT<uint8_t>> last_stun_buf_;
245   std::unique_ptr<IceMessage> last_stun_msg_;
246   int type_preference_ = 0;
247 };
248 
SendPingAndReceiveResponse(Connection * lconn,TestPort * lport,Connection * rconn,TestPort * rport,rtc::ScopedFakeClock * clock,int64_t ms)249 static void SendPingAndReceiveResponse(Connection* lconn,
250                                        TestPort* lport,
251                                        Connection* rconn,
252                                        TestPort* rport,
253                                        rtc::ScopedFakeClock* clock,
254                                        int64_t ms) {
255   lconn->Ping(rtc::TimeMillis());
256   ASSERT_TRUE_WAIT(lport->last_stun_msg(), kDefaultTimeout);
257   ASSERT_TRUE(lport->last_stun_buf());
258   rconn->OnReadPacket(lport->last_stun_buf()->data<char>(),
259                       lport->last_stun_buf()->size(), /* packet_time_us */ -1);
260   clock->AdvanceTime(webrtc::TimeDelta::Millis(ms));
261   ASSERT_TRUE_WAIT(rport->last_stun_msg(), kDefaultTimeout);
262   ASSERT_TRUE(rport->last_stun_buf());
263   lconn->OnReadPacket(rport->last_stun_buf()->data<char>(),
264                       rport->last_stun_buf()->size(), /* packet_time_us */ -1);
265 }
266 
267 class TestChannel : public sigslot::has_slots<> {
268  public:
269   // Takes ownership of |p1| (but not |p2|).
TestChannel(std::unique_ptr<Port> p1)270   explicit TestChannel(std::unique_ptr<Port> p1) : port_(std::move(p1)) {
271     port_->SignalPortComplete.connect(this, &TestChannel::OnPortComplete);
272     port_->SignalUnknownAddress.connect(this, &TestChannel::OnUnknownAddress);
273     port_->SignalDestroyed.connect(this, &TestChannel::OnSrcPortDestroyed);
274   }
275 
complete_count()276   int complete_count() { return complete_count_; }
conn()277   Connection* conn() { return conn_; }
remote_address()278   const SocketAddress& remote_address() { return remote_address_; }
remote_fragment()279   const std::string remote_fragment() { return remote_frag_; }
280 
Start()281   void Start() { port_->PrepareAddress(); }
CreateConnection(const Candidate & remote_candidate)282   void CreateConnection(const Candidate& remote_candidate) {
283     conn_ = port_->CreateConnection(remote_candidate, Port::ORIGIN_MESSAGE);
284     IceMode remote_ice_mode =
285         (ice_mode_ == ICEMODE_FULL) ? ICEMODE_LITE : ICEMODE_FULL;
286     conn_->set_remote_ice_mode(remote_ice_mode);
287     conn_->set_use_candidate_attr(remote_ice_mode == ICEMODE_FULL);
288     conn_->SignalStateChange.connect(this,
289                                      &TestChannel::OnConnectionStateChange);
290     conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
291     conn_->SignalReadyToSend.connect(this,
292                                      &TestChannel::OnConnectionReadyToSend);
293     connection_ready_to_send_ = false;
294   }
OnConnectionStateChange(Connection * conn)295   void OnConnectionStateChange(Connection* conn) {
296     if (conn->write_state() == Connection::STATE_WRITABLE) {
297       conn->set_use_candidate_attr(true);
298       nominated_ = true;
299     }
300   }
AcceptConnection(const Candidate & remote_candidate)301   void AcceptConnection(const Candidate& remote_candidate) {
302     ASSERT_TRUE(remote_request_.get() != NULL);
303     Candidate c = remote_candidate;
304     c.set_address(remote_address_);
305     conn_ = port_->CreateConnection(c, Port::ORIGIN_MESSAGE);
306     conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
307     conn_->SendStunBindingResponse(remote_request_.get());
308     remote_request_.reset();
309   }
Ping()310   void Ping() { Ping(0); }
Ping(int64_t now)311   void Ping(int64_t now) { conn_->Ping(now); }
Stop()312   void Stop() {
313     if (conn_) {
314       conn_->Destroy();
315     }
316   }
317 
OnPortComplete(Port * port)318   void OnPortComplete(Port* port) { complete_count_++; }
SetIceMode(IceMode ice_mode)319   void SetIceMode(IceMode ice_mode) { ice_mode_ = ice_mode; }
320 
SendData(const char * data,size_t len)321   int SendData(const char* data, size_t len) {
322     rtc::PacketOptions options;
323     return conn_->Send(data, len, options);
324   }
325 
OnUnknownAddress(PortInterface * port,const SocketAddress & addr,ProtocolType proto,IceMessage * msg,const std::string & rf,bool)326   void OnUnknownAddress(PortInterface* port,
327                         const SocketAddress& addr,
328                         ProtocolType proto,
329                         IceMessage* msg,
330                         const std::string& rf,
331                         bool /*port_muxed*/) {
332     ASSERT_EQ(port_.get(), port);
333     if (!remote_address_.IsNil()) {
334       ASSERT_EQ(remote_address_, addr);
335     }
336     const cricket::StunUInt32Attribute* priority_attr =
337         msg->GetUInt32(STUN_ATTR_PRIORITY);
338     const cricket::StunByteStringAttribute* mi_attr =
339         msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY);
340     const cricket::StunUInt32Attribute* fingerprint_attr =
341         msg->GetUInt32(STUN_ATTR_FINGERPRINT);
342     EXPECT_TRUE(priority_attr != NULL);
343     EXPECT_TRUE(mi_attr != NULL);
344     EXPECT_TRUE(fingerprint_attr != NULL);
345     remote_address_ = addr;
346     remote_request_ = CopyStunMessage(*msg);
347     remote_frag_ = rf;
348   }
349 
OnDestroyed(Connection * conn)350   void OnDestroyed(Connection* conn) {
351     ASSERT_EQ(conn_, conn);
352     RTC_LOG(INFO) << "OnDestroy connection " << conn << " deleted";
353     conn_ = NULL;
354     // When the connection is destroyed, also clear these fields so future
355     // connections are possible.
356     remote_request_.reset();
357     remote_address_.Clear();
358   }
359 
OnSrcPortDestroyed(PortInterface * port)360   void OnSrcPortDestroyed(PortInterface* port) {
361     Port* destroyed_src = port_.release();
362     ASSERT_EQ(destroyed_src, port);
363   }
364 
port()365   Port* port() { return port_.get(); }
366 
nominated() const367   bool nominated() const { return nominated_; }
368 
set_connection_ready_to_send(bool ready)369   void set_connection_ready_to_send(bool ready) {
370     connection_ready_to_send_ = ready;
371   }
connection_ready_to_send() const372   bool connection_ready_to_send() const { return connection_ready_to_send_; }
373 
374  private:
375   // ReadyToSend will only issue after a Connection recovers from ENOTCONN
OnConnectionReadyToSend(Connection * conn)376   void OnConnectionReadyToSend(Connection* conn) {
377     ASSERT_EQ(conn, conn_);
378     connection_ready_to_send_ = true;
379   }
380 
381   IceMode ice_mode_ = ICEMODE_FULL;
382   std::unique_ptr<Port> port_;
383 
384   int complete_count_ = 0;
385   Connection* conn_ = nullptr;
386   SocketAddress remote_address_;
387   std::unique_ptr<StunMessage> remote_request_;
388   std::string remote_frag_;
389   bool nominated_ = false;
390   bool connection_ready_to_send_ = false;
391 };
392 
393 class PortTest : public ::testing::Test, public sigslot::has_slots<> {
394  public:
PortTest()395   PortTest()
396       : ss_(new rtc::VirtualSocketServer()),
397         main_(ss_.get()),
398         socket_factory_(rtc::Thread::Current()),
399         nat_factory1_(ss_.get(), kNatAddr1, SocketAddress()),
400         nat_factory2_(ss_.get(), kNatAddr2, SocketAddress()),
401         nat_socket_factory1_(&nat_factory1_),
402         nat_socket_factory2_(&nat_factory2_),
403         stun_server_(TestStunServer::Create(&main_, kStunAddr)),
404         turn_server_(&main_, kTurnUdpIntAddr, kTurnUdpExtAddr),
405         username_(rtc::CreateRandomString(ICE_UFRAG_LENGTH)),
406         password_(rtc::CreateRandomString(ICE_PWD_LENGTH)),
407         role_conflict_(false),
408         ports_destroyed_(0) {}
409 
410  protected:
password()411   std::string password() { return password_; }
412 
TestLocalToLocal()413   void TestLocalToLocal() {
414     auto port1 = CreateUdpPort(kLocalAddr1);
415     port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
416     auto port2 = CreateUdpPort(kLocalAddr2);
417     port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
418     TestConnectivity("udp", std::move(port1), "udp", std::move(port2), true,
419                      true, true, true);
420   }
TestLocalToStun(NATType ntype)421   void TestLocalToStun(NATType ntype) {
422     auto port1 = CreateUdpPort(kLocalAddr1);
423     port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
424     nat_server2_ = CreateNatServer(kNatAddr2, ntype);
425     auto port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
426     port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
427     TestConnectivity("udp", std::move(port1), StunName(ntype), std::move(port2),
428                      ntype == NAT_OPEN_CONE, true, ntype != NAT_SYMMETRIC,
429                      true);
430   }
TestLocalToRelay(ProtocolType proto)431   void TestLocalToRelay(ProtocolType proto) {
432     auto port1 = CreateUdpPort(kLocalAddr1);
433     port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
434     auto port2 = CreateRelayPort(kLocalAddr2, proto, PROTO_UDP);
435     port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
436     TestConnectivity("udp", std::move(port1), RelayName(proto),
437                      std::move(port2), false, true, true, true);
438   }
TestStunToLocal(NATType ntype)439   void TestStunToLocal(NATType ntype) {
440     nat_server1_ = CreateNatServer(kNatAddr1, ntype);
441     auto port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
442     port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
443     auto port2 = CreateUdpPort(kLocalAddr2);
444     port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
445     TestConnectivity(StunName(ntype), std::move(port1), "udp", std::move(port2),
446                      true, ntype != NAT_SYMMETRIC, true, true);
447   }
TestStunToStun(NATType ntype1,NATType ntype2)448   void TestStunToStun(NATType ntype1, NATType ntype2) {
449     nat_server1_ = CreateNatServer(kNatAddr1, ntype1);
450     auto port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
451     port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
452     nat_server2_ = CreateNatServer(kNatAddr2, ntype2);
453     auto port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
454     port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
455     TestConnectivity(StunName(ntype1), std::move(port1), StunName(ntype2),
456                      std::move(port2), ntype2 == NAT_OPEN_CONE,
457                      ntype1 != NAT_SYMMETRIC, ntype2 != NAT_SYMMETRIC,
458                      ntype1 + ntype2 < (NAT_PORT_RESTRICTED + NAT_SYMMETRIC));
459   }
TestStunToRelay(NATType ntype,ProtocolType proto)460   void TestStunToRelay(NATType ntype, ProtocolType proto) {
461     nat_server1_ = CreateNatServer(kNatAddr1, ntype);
462     auto port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
463     port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
464     auto port2 = CreateRelayPort(kLocalAddr2, proto, PROTO_UDP);
465     port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
466     TestConnectivity(StunName(ntype), std::move(port1), RelayName(proto),
467                      std::move(port2), false, ntype != NAT_SYMMETRIC, true,
468                      true);
469   }
TestTcpToTcp()470   void TestTcpToTcp() {
471     auto port1 = CreateTcpPort(kLocalAddr1);
472     port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
473     auto port2 = CreateTcpPort(kLocalAddr2);
474     port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
475     TestConnectivity("tcp", std::move(port1), "tcp", std::move(port2), true,
476                      false, true, true);
477   }
TestTcpToRelay(ProtocolType proto)478   void TestTcpToRelay(ProtocolType proto) {
479     auto port1 = CreateTcpPort(kLocalAddr1);
480     port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
481     auto port2 = CreateRelayPort(kLocalAddr2, proto, PROTO_TCP);
482     port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
483     TestConnectivity("tcp", std::move(port1), RelayName(proto),
484                      std::move(port2), false, false, true, true);
485   }
TestSslTcpToRelay(ProtocolType proto)486   void TestSslTcpToRelay(ProtocolType proto) {
487     auto port1 = CreateTcpPort(kLocalAddr1);
488     port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
489     auto port2 = CreateRelayPort(kLocalAddr2, proto, PROTO_SSLTCP);
490     port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
491     TestConnectivity("ssltcp", std::move(port1), RelayName(proto),
492                      std::move(port2), false, false, true, true);
493   }
494 
MakeNetwork(const SocketAddress & addr)495   rtc::Network* MakeNetwork(const SocketAddress& addr) {
496     networks_.emplace_back("unittest", "unittest", addr.ipaddr(), 32);
497     networks_.back().AddIP(addr.ipaddr());
498     return &networks_.back();
499   }
500 
501   // helpers for above functions
CreateUdpPort(const SocketAddress & addr)502   std::unique_ptr<UDPPort> CreateUdpPort(const SocketAddress& addr) {
503     return CreateUdpPort(addr, &socket_factory_);
504   }
CreateUdpPort(const SocketAddress & addr,PacketSocketFactory * socket_factory)505   std::unique_ptr<UDPPort> CreateUdpPort(const SocketAddress& addr,
506                                          PacketSocketFactory* socket_factory) {
507     return UDPPort::Create(&main_, socket_factory, MakeNetwork(addr), 0, 0,
508                            username_, password_, std::string(), true,
509                            absl::nullopt);
510   }
CreateTcpPort(const SocketAddress & addr)511   std::unique_ptr<TCPPort> CreateTcpPort(const SocketAddress& addr) {
512     return CreateTcpPort(addr, &socket_factory_);
513   }
CreateTcpPort(const SocketAddress & addr,PacketSocketFactory * socket_factory)514   std::unique_ptr<TCPPort> CreateTcpPort(const SocketAddress& addr,
515                                          PacketSocketFactory* socket_factory) {
516     return TCPPort::Create(&main_, socket_factory, MakeNetwork(addr), 0, 0,
517                            username_, password_, true);
518   }
CreateStunPort(const SocketAddress & addr,rtc::PacketSocketFactory * factory)519   std::unique_ptr<StunPort> CreateStunPort(const SocketAddress& addr,
520                                            rtc::PacketSocketFactory* factory) {
521     ServerAddresses stun_servers;
522     stun_servers.insert(kStunAddr);
523     return StunPort::Create(&main_, factory, MakeNetwork(addr), 0, 0, username_,
524                             password_, stun_servers, std::string(),
525                             absl::nullopt);
526   }
CreateRelayPort(const SocketAddress & addr,ProtocolType int_proto,ProtocolType ext_proto)527   std::unique_ptr<Port> CreateRelayPort(const SocketAddress& addr,
528                                         ProtocolType int_proto,
529                                         ProtocolType ext_proto) {
530     return CreateTurnPort(addr, &socket_factory_, int_proto, ext_proto);
531   }
CreateTurnPort(const SocketAddress & addr,PacketSocketFactory * socket_factory,ProtocolType int_proto,ProtocolType ext_proto)532   std::unique_ptr<TurnPort> CreateTurnPort(const SocketAddress& addr,
533                                            PacketSocketFactory* socket_factory,
534                                            ProtocolType int_proto,
535                                            ProtocolType ext_proto) {
536     SocketAddress server_addr =
537         int_proto == PROTO_TCP ? kTurnTcpIntAddr : kTurnUdpIntAddr;
538     return CreateTurnPort(addr, socket_factory, int_proto, ext_proto,
539                           server_addr);
540   }
CreateTurnPort(const SocketAddress & addr,PacketSocketFactory * socket_factory,ProtocolType int_proto,ProtocolType ext_proto,const rtc::SocketAddress & server_addr)541   std::unique_ptr<TurnPort> CreateTurnPort(
542       const SocketAddress& addr,
543       PacketSocketFactory* socket_factory,
544       ProtocolType int_proto,
545       ProtocolType ext_proto,
546       const rtc::SocketAddress& server_addr) {
547     return TurnPort::Create(&main_, socket_factory, MakeNetwork(addr), 0, 0,
548                             username_, password_,
549                             ProtocolAddress(server_addr, int_proto),
550                             kRelayCredentials, 0, "", {}, {}, nullptr, nullptr);
551   }
CreateNatServer(const SocketAddress & addr,rtc::NATType type)552   std::unique_ptr<rtc::NATServer> CreateNatServer(const SocketAddress& addr,
553                                                   rtc::NATType type) {
554     return std::make_unique<rtc::NATServer>(type, ss_.get(), addr, addr,
555                                             ss_.get(), addr);
556   }
StunName(NATType type)557   static const char* StunName(NATType type) {
558     switch (type) {
559       case NAT_OPEN_CONE:
560         return "stun(open cone)";
561       case NAT_ADDR_RESTRICTED:
562         return "stun(addr restricted)";
563       case NAT_PORT_RESTRICTED:
564         return "stun(port restricted)";
565       case NAT_SYMMETRIC:
566         return "stun(symmetric)";
567       default:
568         return "stun(?)";
569     }
570   }
RelayName(ProtocolType proto)571   static const char* RelayName(ProtocolType proto) {
572     switch (proto) {
573       case PROTO_UDP:
574         return "turn(udp)";
575       case PROTO_TCP:
576         return "turn(tcp)";
577       case PROTO_SSLTCP:
578         return "turn(ssltcp)";
579       case PROTO_TLS:
580         return "turn(tls)";
581       default:
582         return "turn(?)";
583     }
584   }
585 
586   void TestCrossFamilyPorts(int type);
587 
588   void ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2);
589 
590   // This does all the work and then deletes |port1| and |port2|.
591   void TestConnectivity(const char* name1,
592                         std::unique_ptr<Port> port1,
593                         const char* name2,
594                         std::unique_ptr<Port> port2,
595                         bool accept,
596                         bool same_addr1,
597                         bool same_addr2,
598                         bool possible);
599 
600   // This connects the provided channels which have already started.  |ch1|
601   // should have its Connection created (either through CreateConnection() or
602   // TCP reconnecting mechanism before entering this function.
ConnectStartedChannels(TestChannel * ch1,TestChannel * ch2)603   void ConnectStartedChannels(TestChannel* ch1, TestChannel* ch2) {
604     ASSERT_TRUE(ch1->conn());
605     EXPECT_TRUE_WAIT(ch1->conn()->connected(),
606                      kDefaultTimeout);  // for TCP connect
607     ch1->Ping();
608     WAIT(!ch2->remote_address().IsNil(), kShortTimeout);
609 
610     // Send a ping from dst to src.
611     ch2->AcceptConnection(GetCandidate(ch1->port()));
612     ch2->Ping();
613     EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2->conn()->write_state(),
614                    kDefaultTimeout);
615   }
616 
617   // This connects and disconnects the provided channels in the same sequence as
618   // TestConnectivity with all options set to |true|.  It does not delete either
619   // channel.
StartConnectAndStopChannels(TestChannel * ch1,TestChannel * ch2)620   void StartConnectAndStopChannels(TestChannel* ch1, TestChannel* ch2) {
621     // Acquire addresses.
622     ch1->Start();
623     ch2->Start();
624 
625     ch1->CreateConnection(GetCandidate(ch2->port()));
626     ConnectStartedChannels(ch1, ch2);
627 
628     // Destroy the connections.
629     ch1->Stop();
630     ch2->Stop();
631   }
632 
633   // This disconnects both end's Connection and make sure ch2 ready for new
634   // connection.
DisconnectTcpTestChannels(TestChannel * ch1,TestChannel * ch2)635   void DisconnectTcpTestChannels(TestChannel* ch1, TestChannel* ch2) {
636     TCPConnection* tcp_conn1 = static_cast<TCPConnection*>(ch1->conn());
637     TCPConnection* tcp_conn2 = static_cast<TCPConnection*>(ch2->conn());
638     ASSERT_TRUE(
639         ss_->CloseTcpConnections(tcp_conn1->socket()->GetLocalAddress(),
640                                  tcp_conn2->socket()->GetLocalAddress()));
641 
642     // Wait for both OnClose are delivered.
643     EXPECT_TRUE_WAIT(!ch1->conn()->connected(), kDefaultTimeout);
644     EXPECT_TRUE_WAIT(!ch2->conn()->connected(), kDefaultTimeout);
645 
646     // Ensure redundant SignalClose events on TcpConnection won't break tcp
647     // reconnection. Chromium will fire SignalClose for all outstanding IPC
648     // packets during reconnection.
649     tcp_conn1->socket()->SignalClose(tcp_conn1->socket(), 0);
650     tcp_conn2->socket()->SignalClose(tcp_conn2->socket(), 0);
651 
652     // Speed up destroying ch2's connection such that the test is ready to
653     // accept a new connection from ch1 before ch1's connection destroys itself.
654     ch2->conn()->Destroy();
655     EXPECT_TRUE_WAIT(ch2->conn() == NULL, kDefaultTimeout);
656   }
657 
TestTcpReconnect(bool ping_after_disconnected,bool send_after_disconnected)658   void TestTcpReconnect(bool ping_after_disconnected,
659                         bool send_after_disconnected) {
660     auto port1 = CreateTcpPort(kLocalAddr1);
661     port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
662     auto port2 = CreateTcpPort(kLocalAddr2);
663     port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
664 
665     port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
666     port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
667 
668     // Set up channels and ensure both ports will be deleted.
669     TestChannel ch1(std::move(port1));
670     TestChannel ch2(std::move(port2));
671     EXPECT_EQ(0, ch1.complete_count());
672     EXPECT_EQ(0, ch2.complete_count());
673 
674     ch1.Start();
675     ch2.Start();
676     ASSERT_EQ_WAIT(1, ch1.complete_count(), kDefaultTimeout);
677     ASSERT_EQ_WAIT(1, ch2.complete_count(), kDefaultTimeout);
678 
679     // Initial connecting the channel, create connection on channel1.
680     ch1.CreateConnection(GetCandidate(ch2.port()));
681     ConnectStartedChannels(&ch1, &ch2);
682 
683     // Shorten the timeout period.
684     const int kTcpReconnectTimeout = kDefaultTimeout;
685     static_cast<TCPConnection*>(ch1.conn())
686         ->set_reconnection_timeout(kTcpReconnectTimeout);
687     static_cast<TCPConnection*>(ch2.conn())
688         ->set_reconnection_timeout(kTcpReconnectTimeout);
689 
690     EXPECT_FALSE(ch1.connection_ready_to_send());
691     EXPECT_FALSE(ch2.connection_ready_to_send());
692 
693     // Once connected, disconnect them.
694     DisconnectTcpTestChannels(&ch1, &ch2);
695 
696     if (send_after_disconnected || ping_after_disconnected) {
697       if (send_after_disconnected) {
698         // First SendData after disconnect should fail but will trigger
699         // reconnect.
700         EXPECT_EQ(-1, ch1.SendData(data, static_cast<int>(strlen(data))));
701       }
702 
703       if (ping_after_disconnected) {
704         // Ping should trigger reconnect.
705         ch1.Ping();
706       }
707 
708       // Wait for channel's outgoing TCPConnection connected.
709       EXPECT_TRUE_WAIT(ch1.conn()->connected(), kDefaultTimeout);
710 
711       // Verify that we could still connect channels.
712       ConnectStartedChannels(&ch1, &ch2);
713       EXPECT_TRUE_WAIT(ch1.connection_ready_to_send(), kTcpReconnectTimeout);
714       // Channel2 is the passive one so a new connection is created during
715       // reconnect. This new connection should never have issued ENOTCONN
716       // hence the connection_ready_to_send() should be false.
717       EXPECT_FALSE(ch2.connection_ready_to_send());
718     } else {
719       EXPECT_EQ(ch1.conn()->write_state(), Connection::STATE_WRITABLE);
720       // Since the reconnection never happens, the connections should have been
721       // destroyed after the timeout.
722       EXPECT_TRUE_WAIT(!ch1.conn(), kTcpReconnectTimeout + kDefaultTimeout);
723       EXPECT_TRUE(!ch2.conn());
724     }
725 
726     // Tear down and ensure that goes smoothly.
727     ch1.Stop();
728     ch2.Stop();
729     EXPECT_TRUE_WAIT(ch1.conn() == NULL, kDefaultTimeout);
730     EXPECT_TRUE_WAIT(ch2.conn() == NULL, kDefaultTimeout);
731   }
732 
CreateStunMessage(int type)733   std::unique_ptr<IceMessage> CreateStunMessage(int type) {
734     auto msg = std::make_unique<IceMessage>();
735     msg->SetType(type);
736     msg->SetTransactionID("TESTTESTTEST");
737     return msg;
738   }
CreateStunMessageWithUsername(int type,const std::string & username)739   std::unique_ptr<IceMessage> CreateStunMessageWithUsername(
740       int type,
741       const std::string& username) {
742     std::unique_ptr<IceMessage> msg = CreateStunMessage(type);
743     msg->AddAttribute(std::make_unique<StunByteStringAttribute>(
744         STUN_ATTR_USERNAME, username));
745     return msg;
746   }
CreateTestPort(const rtc::SocketAddress & addr,const std::string & username,const std::string & password)747   std::unique_ptr<TestPort> CreateTestPort(const rtc::SocketAddress& addr,
748                                            const std::string& username,
749                                            const std::string& password) {
750     auto port =
751         std::make_unique<TestPort>(&main_, "test", &socket_factory_,
752                                    MakeNetwork(addr), 0, 0, username, password);
753     port->SignalRoleConflict.connect(this, &PortTest::OnRoleConflict);
754     return port;
755   }
CreateTestPort(const rtc::SocketAddress & addr,const std::string & username,const std::string & password,cricket::IceRole role,int tiebreaker)756   std::unique_ptr<TestPort> CreateTestPort(const rtc::SocketAddress& addr,
757                                            const std::string& username,
758                                            const std::string& password,
759                                            cricket::IceRole role,
760                                            int tiebreaker) {
761     auto port = CreateTestPort(addr, username, password);
762     port->SetIceRole(role);
763     port->SetIceTiebreaker(tiebreaker);
764     return port;
765   }
766   // Overload to create a test port given an rtc::Network directly.
CreateTestPort(rtc::Network * network,const std::string & username,const std::string & password)767   std::unique_ptr<TestPort> CreateTestPort(rtc::Network* network,
768                                            const std::string& username,
769                                            const std::string& password) {
770     auto port = std::make_unique<TestPort>(&main_, "test", &socket_factory_,
771                                            network, 0, 0, username, password);
772     port->SignalRoleConflict.connect(this, &PortTest::OnRoleConflict);
773     return port;
774   }
775 
OnRoleConflict(PortInterface * port)776   void OnRoleConflict(PortInterface* port) { role_conflict_ = true; }
role_conflict() const777   bool role_conflict() const { return role_conflict_; }
778 
ConnectToSignalDestroyed(PortInterface * port)779   void ConnectToSignalDestroyed(PortInterface* port) {
780     port->SignalDestroyed.connect(this, &PortTest::OnDestroyed);
781   }
782 
OnDestroyed(PortInterface * port)783   void OnDestroyed(PortInterface* port) { ++ports_destroyed_; }
ports_destroyed() const784   int ports_destroyed() const { return ports_destroyed_; }
785 
nat_socket_factory1()786   rtc::BasicPacketSocketFactory* nat_socket_factory1() {
787     return &nat_socket_factory1_;
788   }
789 
vss()790   rtc::VirtualSocketServer* vss() { return ss_.get(); }
791 
792  private:
793   // When a "create port" helper method is called with an IP, we create a
794   // Network with that IP and add it to this list. Using a list instead of a
795   // vector so that when it grows, pointers aren't invalidated.
796   std::list<rtc::Network> networks_;
797   std::unique_ptr<rtc::VirtualSocketServer> ss_;
798   rtc::AutoSocketServerThread main_;
799   rtc::BasicPacketSocketFactory socket_factory_;
800   std::unique_ptr<rtc::NATServer> nat_server1_;
801   std::unique_ptr<rtc::NATServer> nat_server2_;
802   rtc::NATSocketFactory nat_factory1_;
803   rtc::NATSocketFactory nat_factory2_;
804   rtc::BasicPacketSocketFactory nat_socket_factory1_;
805   rtc::BasicPacketSocketFactory nat_socket_factory2_;
806   std::unique_ptr<TestStunServer> stun_server_;
807   TestTurnServer turn_server_;
808   std::string username_;
809   std::string password_;
810   bool role_conflict_;
811   int ports_destroyed_;
812 };
813 
TestConnectivity(const char * name1,std::unique_ptr<Port> port1,const char * name2,std::unique_ptr<Port> port2,bool accept,bool same_addr1,bool same_addr2,bool possible)814 void PortTest::TestConnectivity(const char* name1,
815                                 std::unique_ptr<Port> port1,
816                                 const char* name2,
817                                 std::unique_ptr<Port> port2,
818                                 bool accept,
819                                 bool same_addr1,
820                                 bool same_addr2,
821                                 bool possible) {
822   rtc::ScopedFakeClock clock;
823   RTC_LOG(LS_INFO) << "Test: " << name1 << " to " << name2 << ": ";
824   port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
825   port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
826 
827   // Set up channels and ensure both ports will be deleted.
828   TestChannel ch1(std::move(port1));
829   TestChannel ch2(std::move(port2));
830   EXPECT_EQ(0, ch1.complete_count());
831   EXPECT_EQ(0, ch2.complete_count());
832 
833   // Acquire addresses.
834   ch1.Start();
835   ch2.Start();
836   ASSERT_EQ_SIMULATED_WAIT(1, ch1.complete_count(), kDefaultTimeout, clock);
837   ASSERT_EQ_SIMULATED_WAIT(1, ch2.complete_count(), kDefaultTimeout, clock);
838 
839   // Send a ping from src to dst. This may or may not make it.
840   ch1.CreateConnection(GetCandidate(ch2.port()));
841   ASSERT_TRUE(ch1.conn() != NULL);
842   EXPECT_TRUE_SIMULATED_WAIT(ch1.conn()->connected(), kDefaultTimeout,
843                              clock);  // for TCP connect
844   ch1.Ping();
845   SIMULATED_WAIT(!ch2.remote_address().IsNil(), kShortTimeout, clock);
846 
847   if (accept) {
848     // We are able to send a ping from src to dst. This is the case when
849     // sending to UDP ports and cone NATs.
850     EXPECT_TRUE(ch1.remote_address().IsNil());
851     EXPECT_EQ(ch2.remote_fragment(), ch1.port()->username_fragment());
852 
853     // Ensure the ping came from the same address used for src.
854     // This is the case unless the source NAT was symmetric.
855     if (same_addr1)
856       EXPECT_EQ(ch2.remote_address(), GetAddress(ch1.port()));
857     EXPECT_TRUE(same_addr2);
858 
859     // Send a ping from dst to src.
860     ch2.AcceptConnection(GetCandidate(ch1.port()));
861     ASSERT_TRUE(ch2.conn() != NULL);
862     ch2.Ping();
863     EXPECT_EQ_SIMULATED_WAIT(Connection::STATE_WRITABLE,
864                              ch2.conn()->write_state(), kDefaultTimeout, clock);
865   } else {
866     // We can't send a ping from src to dst, so flip it around. This will happen
867     // when the destination NAT is addr/port restricted or symmetric.
868     EXPECT_TRUE(ch1.remote_address().IsNil());
869     EXPECT_TRUE(ch2.remote_address().IsNil());
870 
871     // Send a ping from dst to src. Again, this may or may not make it.
872     ch2.CreateConnection(GetCandidate(ch1.port()));
873     ASSERT_TRUE(ch2.conn() != NULL);
874     ch2.Ping();
875     SIMULATED_WAIT(ch2.conn()->write_state() == Connection::STATE_WRITABLE,
876                    kShortTimeout, clock);
877 
878     if (same_addr1 && same_addr2) {
879       // The new ping got back to the source.
880       EXPECT_TRUE(ch1.conn()->receiving());
881       EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
882 
883       // First connection may not be writable if the first ping did not get
884       // through.  So we will have to do another.
885       if (ch1.conn()->write_state() == Connection::STATE_WRITE_INIT) {
886         ch1.Ping();
887         EXPECT_EQ_SIMULATED_WAIT(Connection::STATE_WRITABLE,
888                                  ch1.conn()->write_state(), kDefaultTimeout,
889                                  clock);
890       }
891     } else if (!same_addr1 && possible) {
892       // The new ping went to the candidate address, but that address was bad.
893       // This will happen when the source NAT is symmetric.
894       EXPECT_TRUE(ch1.remote_address().IsNil());
895       EXPECT_TRUE(ch2.remote_address().IsNil());
896 
897       // However, since we have now sent a ping to the source IP, we should be
898       // able to get a ping from it. This gives us the real source address.
899       ch1.Ping();
900       EXPECT_TRUE_SIMULATED_WAIT(!ch2.remote_address().IsNil(), kDefaultTimeout,
901                                  clock);
902       EXPECT_FALSE(ch2.conn()->receiving());
903       EXPECT_TRUE(ch1.remote_address().IsNil());
904 
905       // Pick up the actual address and establish the connection.
906       ch2.AcceptConnection(GetCandidate(ch1.port()));
907       ASSERT_TRUE(ch2.conn() != NULL);
908       ch2.Ping();
909       EXPECT_EQ_SIMULATED_WAIT(Connection::STATE_WRITABLE,
910                                ch2.conn()->write_state(), kDefaultTimeout,
911                                clock);
912     } else if (!same_addr2 && possible) {
913       // The new ping came in, but from an unexpected address. This will happen
914       // when the destination NAT is symmetric.
915       EXPECT_FALSE(ch1.remote_address().IsNil());
916       EXPECT_FALSE(ch1.conn()->receiving());
917 
918       // Update our address and complete the connection.
919       ch1.AcceptConnection(GetCandidate(ch2.port()));
920       ch1.Ping();
921       EXPECT_EQ_SIMULATED_WAIT(Connection::STATE_WRITABLE,
922                                ch1.conn()->write_state(), kDefaultTimeout,
923                                clock);
924     } else {  // (!possible)
925       // There should be s no way for the pings to reach each other. Check it.
926       EXPECT_TRUE(ch1.remote_address().IsNil());
927       EXPECT_TRUE(ch2.remote_address().IsNil());
928       ch1.Ping();
929       SIMULATED_WAIT(!ch2.remote_address().IsNil(), kShortTimeout, clock);
930       EXPECT_TRUE(ch1.remote_address().IsNil());
931       EXPECT_TRUE(ch2.remote_address().IsNil());
932     }
933   }
934 
935   // Everything should be good, unless we know the situation is impossible.
936   ASSERT_TRUE(ch1.conn() != NULL);
937   ASSERT_TRUE(ch2.conn() != NULL);
938   if (possible) {
939     EXPECT_TRUE(ch1.conn()->receiving());
940     EXPECT_EQ(Connection::STATE_WRITABLE, ch1.conn()->write_state());
941     EXPECT_TRUE(ch2.conn()->receiving());
942     EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
943   } else {
944     EXPECT_FALSE(ch1.conn()->receiving());
945     EXPECT_NE(Connection::STATE_WRITABLE, ch1.conn()->write_state());
946     EXPECT_FALSE(ch2.conn()->receiving());
947     EXPECT_NE(Connection::STATE_WRITABLE, ch2.conn()->write_state());
948   }
949 
950   // Tear down and ensure that goes smoothly.
951   ch1.Stop();
952   ch2.Stop();
953   EXPECT_TRUE_SIMULATED_WAIT(ch1.conn() == NULL, kDefaultTimeout, clock);
954   EXPECT_TRUE_SIMULATED_WAIT(ch2.conn() == NULL, kDefaultTimeout, clock);
955 }
956 
957 class FakePacketSocketFactory : public rtc::PacketSocketFactory {
958  public:
FakePacketSocketFactory()959   FakePacketSocketFactory()
960       : next_udp_socket_(NULL), next_server_tcp_socket_(NULL) {}
~FakePacketSocketFactory()961   ~FakePacketSocketFactory() override {}
962 
CreateUdpSocket(const SocketAddress & address,uint16_t min_port,uint16_t max_port)963   AsyncPacketSocket* CreateUdpSocket(const SocketAddress& address,
964                                      uint16_t min_port,
965                                      uint16_t max_port) override {
966     EXPECT_TRUE(next_udp_socket_ != NULL);
967     AsyncPacketSocket* result = next_udp_socket_;
968     next_udp_socket_ = NULL;
969     return result;
970   }
971 
CreateServerTcpSocket(const SocketAddress & local_address,uint16_t min_port,uint16_t max_port,int opts)972   AsyncPacketSocket* CreateServerTcpSocket(const SocketAddress& local_address,
973                                            uint16_t min_port,
974                                            uint16_t max_port,
975                                            int opts) override {
976     EXPECT_TRUE(next_server_tcp_socket_ != NULL);
977     AsyncPacketSocket* result = next_server_tcp_socket_;
978     next_server_tcp_socket_ = NULL;
979     return result;
980   }
981 
CreateClientTcpSocket(const SocketAddress & local_address,const SocketAddress & remote_address,const rtc::ProxyInfo & proxy_info,const std::string & user_agent,const rtc::PacketSocketTcpOptions & opts)982   AsyncPacketSocket* CreateClientTcpSocket(
983       const SocketAddress& local_address,
984       const SocketAddress& remote_address,
985       const rtc::ProxyInfo& proxy_info,
986       const std::string& user_agent,
987       const rtc::PacketSocketTcpOptions& opts) override {
988     EXPECT_TRUE(next_client_tcp_socket_.has_value());
989     AsyncPacketSocket* result = *next_client_tcp_socket_;
990     next_client_tcp_socket_ = nullptr;
991     return result;
992   }
993 
set_next_udp_socket(AsyncPacketSocket * next_udp_socket)994   void set_next_udp_socket(AsyncPacketSocket* next_udp_socket) {
995     next_udp_socket_ = next_udp_socket;
996   }
set_next_server_tcp_socket(AsyncPacketSocket * next_server_tcp_socket)997   void set_next_server_tcp_socket(AsyncPacketSocket* next_server_tcp_socket) {
998     next_server_tcp_socket_ = next_server_tcp_socket;
999   }
set_next_client_tcp_socket(AsyncPacketSocket * next_client_tcp_socket)1000   void set_next_client_tcp_socket(AsyncPacketSocket* next_client_tcp_socket) {
1001     next_client_tcp_socket_ = next_client_tcp_socket;
1002   }
CreateAsyncResolver()1003   rtc::AsyncResolverInterface* CreateAsyncResolver() override { return NULL; }
1004 
1005  private:
1006   AsyncPacketSocket* next_udp_socket_;
1007   AsyncPacketSocket* next_server_tcp_socket_;
1008   absl::optional<AsyncPacketSocket*> next_client_tcp_socket_;
1009 };
1010 
1011 class FakeAsyncPacketSocket : public AsyncPacketSocket {
1012  public:
1013   // Returns current local address. Address may be set to NULL if the
1014   // socket is not bound yet (GetState() returns STATE_BINDING).
GetLocalAddress() const1015   virtual SocketAddress GetLocalAddress() const { return local_address_; }
1016 
1017   // Returns remote address. Returns zeroes if this is not a client TCP socket.
GetRemoteAddress() const1018   virtual SocketAddress GetRemoteAddress() const { return remote_address_; }
1019 
1020   // Send a packet.
Send(const void * pv,size_t cb,const rtc::PacketOptions & options)1021   virtual int Send(const void* pv,
1022                    size_t cb,
1023                    const rtc::PacketOptions& options) {
1024     if (error_ == 0) {
1025       return static_cast<int>(cb);
1026     } else {
1027       return -1;
1028     }
1029   }
SendTo(const void * pv,size_t cb,const SocketAddress & addr,const rtc::PacketOptions & options)1030   virtual int SendTo(const void* pv,
1031                      size_t cb,
1032                      const SocketAddress& addr,
1033                      const rtc::PacketOptions& options) {
1034     if (error_ == 0) {
1035       return static_cast<int>(cb);
1036     } else {
1037       return -1;
1038     }
1039   }
Close()1040   virtual int Close() { return 0; }
1041 
GetState() const1042   virtual State GetState() const { return state_; }
GetOption(Socket::Option opt,int * value)1043   virtual int GetOption(Socket::Option opt, int* value) { return 0; }
SetOption(Socket::Option opt,int value)1044   virtual int SetOption(Socket::Option opt, int value) { return 0; }
GetError() const1045   virtual int GetError() const { return 0; }
SetError(int error)1046   virtual void SetError(int error) { error_ = error; }
1047 
set_state(State state)1048   void set_state(State state) { state_ = state; }
1049 
1050   SocketAddress local_address_;
1051   SocketAddress remote_address_;
1052 
1053  private:
1054   int error_ = 0;
1055   State state_;
1056 };
1057 
1058 // Local -> XXXX
TEST_F(PortTest,TestLocalToLocal)1059 TEST_F(PortTest, TestLocalToLocal) {
1060   TestLocalToLocal();
1061 }
1062 
TEST_F(PortTest,TestLocalToConeNat)1063 TEST_F(PortTest, TestLocalToConeNat) {
1064   TestLocalToStun(NAT_OPEN_CONE);
1065 }
1066 
TEST_F(PortTest,TestLocalToARNat)1067 TEST_F(PortTest, TestLocalToARNat) {
1068   TestLocalToStun(NAT_ADDR_RESTRICTED);
1069 }
1070 
TEST_F(PortTest,TestLocalToPRNat)1071 TEST_F(PortTest, TestLocalToPRNat) {
1072   TestLocalToStun(NAT_PORT_RESTRICTED);
1073 }
1074 
TEST_F(PortTest,TestLocalToSymNat)1075 TEST_F(PortTest, TestLocalToSymNat) {
1076   TestLocalToStun(NAT_SYMMETRIC);
1077 }
1078 
1079 // Flaky: https://code.google.com/p/webrtc/issues/detail?id=3316.
TEST_F(PortTest,DISABLED_TestLocalToTurn)1080 TEST_F(PortTest, DISABLED_TestLocalToTurn) {
1081   TestLocalToRelay(PROTO_UDP);
1082 }
1083 
1084 // Cone NAT -> XXXX
TEST_F(PortTest,TestConeNatToLocal)1085 TEST_F(PortTest, TestConeNatToLocal) {
1086   TestStunToLocal(NAT_OPEN_CONE);
1087 }
1088 
TEST_F(PortTest,TestConeNatToConeNat)1089 TEST_F(PortTest, TestConeNatToConeNat) {
1090   TestStunToStun(NAT_OPEN_CONE, NAT_OPEN_CONE);
1091 }
1092 
TEST_F(PortTest,TestConeNatToARNat)1093 TEST_F(PortTest, TestConeNatToARNat) {
1094   TestStunToStun(NAT_OPEN_CONE, NAT_ADDR_RESTRICTED);
1095 }
1096 
TEST_F(PortTest,TestConeNatToPRNat)1097 TEST_F(PortTest, TestConeNatToPRNat) {
1098   TestStunToStun(NAT_OPEN_CONE, NAT_PORT_RESTRICTED);
1099 }
1100 
TEST_F(PortTest,TestConeNatToSymNat)1101 TEST_F(PortTest, TestConeNatToSymNat) {
1102   TestStunToStun(NAT_OPEN_CONE, NAT_SYMMETRIC);
1103 }
1104 
TEST_F(PortTest,TestConeNatToTurn)1105 TEST_F(PortTest, TestConeNatToTurn) {
1106   TestStunToRelay(NAT_OPEN_CONE, PROTO_UDP);
1107 }
1108 
1109 // Address-restricted NAT -> XXXX
TEST_F(PortTest,TestARNatToLocal)1110 TEST_F(PortTest, TestARNatToLocal) {
1111   TestStunToLocal(NAT_ADDR_RESTRICTED);
1112 }
1113 
TEST_F(PortTest,TestARNatToConeNat)1114 TEST_F(PortTest, TestARNatToConeNat) {
1115   TestStunToStun(NAT_ADDR_RESTRICTED, NAT_OPEN_CONE);
1116 }
1117 
TEST_F(PortTest,TestARNatToARNat)1118 TEST_F(PortTest, TestARNatToARNat) {
1119   TestStunToStun(NAT_ADDR_RESTRICTED, NAT_ADDR_RESTRICTED);
1120 }
1121 
TEST_F(PortTest,TestARNatToPRNat)1122 TEST_F(PortTest, TestARNatToPRNat) {
1123   TestStunToStun(NAT_ADDR_RESTRICTED, NAT_PORT_RESTRICTED);
1124 }
1125 
TEST_F(PortTest,TestARNatToSymNat)1126 TEST_F(PortTest, TestARNatToSymNat) {
1127   TestStunToStun(NAT_ADDR_RESTRICTED, NAT_SYMMETRIC);
1128 }
1129 
TEST_F(PortTest,TestARNatToTurn)1130 TEST_F(PortTest, TestARNatToTurn) {
1131   TestStunToRelay(NAT_ADDR_RESTRICTED, PROTO_UDP);
1132 }
1133 
1134 // Port-restricted NAT -> XXXX
TEST_F(PortTest,TestPRNatToLocal)1135 TEST_F(PortTest, TestPRNatToLocal) {
1136   TestStunToLocal(NAT_PORT_RESTRICTED);
1137 }
1138 
TEST_F(PortTest,TestPRNatToConeNat)1139 TEST_F(PortTest, TestPRNatToConeNat) {
1140   TestStunToStun(NAT_PORT_RESTRICTED, NAT_OPEN_CONE);
1141 }
1142 
TEST_F(PortTest,TestPRNatToARNat)1143 TEST_F(PortTest, TestPRNatToARNat) {
1144   TestStunToStun(NAT_PORT_RESTRICTED, NAT_ADDR_RESTRICTED);
1145 }
1146 
TEST_F(PortTest,TestPRNatToPRNat)1147 TEST_F(PortTest, TestPRNatToPRNat) {
1148   TestStunToStun(NAT_PORT_RESTRICTED, NAT_PORT_RESTRICTED);
1149 }
1150 
TEST_F(PortTest,TestPRNatToSymNat)1151 TEST_F(PortTest, TestPRNatToSymNat) {
1152   // Will "fail"
1153   TestStunToStun(NAT_PORT_RESTRICTED, NAT_SYMMETRIC);
1154 }
1155 
TEST_F(PortTest,TestPRNatToTurn)1156 TEST_F(PortTest, TestPRNatToTurn) {
1157   TestStunToRelay(NAT_PORT_RESTRICTED, PROTO_UDP);
1158 }
1159 
1160 // Symmetric NAT -> XXXX
TEST_F(PortTest,TestSymNatToLocal)1161 TEST_F(PortTest, TestSymNatToLocal) {
1162   TestStunToLocal(NAT_SYMMETRIC);
1163 }
1164 
TEST_F(PortTest,TestSymNatToConeNat)1165 TEST_F(PortTest, TestSymNatToConeNat) {
1166   TestStunToStun(NAT_SYMMETRIC, NAT_OPEN_CONE);
1167 }
1168 
TEST_F(PortTest,TestSymNatToARNat)1169 TEST_F(PortTest, TestSymNatToARNat) {
1170   TestStunToStun(NAT_SYMMETRIC, NAT_ADDR_RESTRICTED);
1171 }
1172 
TEST_F(PortTest,TestSymNatToPRNat)1173 TEST_F(PortTest, TestSymNatToPRNat) {
1174   // Will "fail"
1175   TestStunToStun(NAT_SYMMETRIC, NAT_PORT_RESTRICTED);
1176 }
1177 
TEST_F(PortTest,TestSymNatToSymNat)1178 TEST_F(PortTest, TestSymNatToSymNat) {
1179   // Will "fail"
1180   TestStunToStun(NAT_SYMMETRIC, NAT_SYMMETRIC);
1181 }
1182 
TEST_F(PortTest,TestSymNatToTurn)1183 TEST_F(PortTest, TestSymNatToTurn) {
1184   TestStunToRelay(NAT_SYMMETRIC, PROTO_UDP);
1185 }
1186 
1187 // Outbound TCP -> XXXX
TEST_F(PortTest,TestTcpToTcp)1188 TEST_F(PortTest, TestTcpToTcp) {
1189   TestTcpToTcp();
1190 }
1191 
TEST_F(PortTest,TestTcpReconnectOnSendPacket)1192 TEST_F(PortTest, TestTcpReconnectOnSendPacket) {
1193   TestTcpReconnect(false /* ping */, true /* send */);
1194 }
1195 
TEST_F(PortTest,TestTcpReconnectOnPing)1196 TEST_F(PortTest, TestTcpReconnectOnPing) {
1197   TestTcpReconnect(true /* ping */, false /* send */);
1198 }
1199 
TEST_F(PortTest,TestTcpReconnectTimeout)1200 TEST_F(PortTest, TestTcpReconnectTimeout) {
1201   TestTcpReconnect(false /* ping */, false /* send */);
1202 }
1203 
1204 // Test when TcpConnection never connects, the OnClose() will be called to
1205 // destroy the connection.
TEST_F(PortTest,TestTcpNeverConnect)1206 TEST_F(PortTest, TestTcpNeverConnect) {
1207   auto port1 = CreateTcpPort(kLocalAddr1);
1208   port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1209   port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
1210 
1211   // Set up a channel and ensure the port will be deleted.
1212   TestChannel ch1(std::move(port1));
1213   EXPECT_EQ(0, ch1.complete_count());
1214 
1215   ch1.Start();
1216   ASSERT_EQ_WAIT(1, ch1.complete_count(), kDefaultTimeout);
1217 
1218   std::unique_ptr<rtc::AsyncSocket> server(
1219       vss()->CreateAsyncSocket(kLocalAddr2.family(), SOCK_STREAM));
1220   // Bind but not listen.
1221   EXPECT_EQ(0, server->Bind(kLocalAddr2));
1222 
1223   Candidate c = GetCandidate(ch1.port());
1224   c.set_address(server->GetLocalAddress());
1225 
1226   ch1.CreateConnection(c);
1227   EXPECT_TRUE(ch1.conn());
1228   EXPECT_TRUE_WAIT(!ch1.conn(), kDefaultTimeout);  // for TCP connect
1229 }
1230 
1231 /* TODO(?): Enable these once testrelayserver can accept external TCP.
1232 TEST_F(PortTest, TestTcpToTcpRelay) {
1233   TestTcpToRelay(PROTO_TCP);
1234 }
1235 
1236 TEST_F(PortTest, TestTcpToSslTcpRelay) {
1237   TestTcpToRelay(PROTO_SSLTCP);
1238 }
1239 */
1240 
1241 // Outbound SSLTCP -> XXXX
1242 /* TODO(?): Enable these once testrelayserver can accept external SSL.
1243 TEST_F(PortTest, TestSslTcpToTcpRelay) {
1244   TestSslTcpToRelay(PROTO_TCP);
1245 }
1246 
1247 TEST_F(PortTest, TestSslTcpToSslTcpRelay) {
1248   TestSslTcpToRelay(PROTO_SSLTCP);
1249 }
1250 */
1251 
1252 // Test that a connection will be dead and deleted if
1253 // i) it has never received anything for MIN_CONNECTION_LIFETIME milliseconds
1254 //    since it was created, or
1255 // ii) it has not received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT
1256 //     milliseconds since last receiving.
TEST_F(PortTest,TestConnectionDead)1257 TEST_F(PortTest, TestConnectionDead) {
1258   TestChannel ch1(CreateUdpPort(kLocalAddr1));
1259   TestChannel ch2(CreateUdpPort(kLocalAddr2));
1260   // Acquire address.
1261   ch1.Start();
1262   ch2.Start();
1263   ASSERT_EQ_WAIT(1, ch1.complete_count(), kDefaultTimeout);
1264   ASSERT_EQ_WAIT(1, ch2.complete_count(), kDefaultTimeout);
1265 
1266   // Test case that the connection has never received anything.
1267   int64_t before_created = rtc::TimeMillis();
1268   ch1.CreateConnection(GetCandidate(ch2.port()));
1269   int64_t after_created = rtc::TimeMillis();
1270   Connection* conn = ch1.conn();
1271   ASSERT_NE(conn, nullptr);
1272   // It is not dead if it is after MIN_CONNECTION_LIFETIME but not pruned.
1273   conn->UpdateState(after_created + MIN_CONNECTION_LIFETIME + 1);
1274   rtc::Thread::Current()->ProcessMessages(0);
1275   EXPECT_TRUE(ch1.conn() != nullptr);
1276   // It is not dead if it is before MIN_CONNECTION_LIFETIME and pruned.
1277   conn->UpdateState(before_created + MIN_CONNECTION_LIFETIME - 1);
1278   conn->Prune();
1279   rtc::Thread::Current()->ProcessMessages(0);
1280   EXPECT_TRUE(ch1.conn() != nullptr);
1281   // It will be dead after MIN_CONNECTION_LIFETIME and pruned.
1282   conn->UpdateState(after_created + MIN_CONNECTION_LIFETIME + 1);
1283   EXPECT_TRUE_WAIT(ch1.conn() == nullptr, kDefaultTimeout);
1284 
1285   // Test case that the connection has received something.
1286   // Create a connection again and receive a ping.
1287   ch1.CreateConnection(GetCandidate(ch2.port()));
1288   conn = ch1.conn();
1289   ASSERT_NE(conn, nullptr);
1290   int64_t before_last_receiving = rtc::TimeMillis();
1291   conn->ReceivedPing();
1292   int64_t after_last_receiving = rtc::TimeMillis();
1293   // The connection will be dead after DEAD_CONNECTION_RECEIVE_TIMEOUT
1294   conn->UpdateState(before_last_receiving + DEAD_CONNECTION_RECEIVE_TIMEOUT -
1295                     1);
1296   rtc::Thread::Current()->ProcessMessages(100);
1297   EXPECT_TRUE(ch1.conn() != nullptr);
1298   conn->UpdateState(after_last_receiving + DEAD_CONNECTION_RECEIVE_TIMEOUT + 1);
1299   EXPECT_TRUE_WAIT(ch1.conn() == nullptr, kDefaultTimeout);
1300 }
1301 
TEST_F(PortTest,TestConnectionDeadWithDeadConnectionTimeout)1302 TEST_F(PortTest, TestConnectionDeadWithDeadConnectionTimeout) {
1303   TestChannel ch1(CreateUdpPort(kLocalAddr1));
1304   TestChannel ch2(CreateUdpPort(kLocalAddr2));
1305   // Acquire address.
1306   ch1.Start();
1307   ch2.Start();
1308   ASSERT_EQ_WAIT(1, ch1.complete_count(), kDefaultTimeout);
1309   ASSERT_EQ_WAIT(1, ch2.complete_count(), kDefaultTimeout);
1310 
1311   // Note: set field trials manually since they are parsed by
1312   // P2PTransportChannel but P2PTransportChannel is not used in this test.
1313   IceFieldTrials field_trials;
1314   field_trials.dead_connection_timeout_ms = 90000;
1315 
1316   // Create a connection again and receive a ping.
1317   ch1.CreateConnection(GetCandidate(ch2.port()));
1318   auto conn = ch1.conn();
1319   conn->SetIceFieldTrials(&field_trials);
1320 
1321   ASSERT_NE(conn, nullptr);
1322   int64_t before_last_receiving = rtc::TimeMillis();
1323   conn->ReceivedPing();
1324   int64_t after_last_receiving = rtc::TimeMillis();
1325   // The connection will be dead after 90s
1326   conn->UpdateState(before_last_receiving + 90000 - 1);
1327   rtc::Thread::Current()->ProcessMessages(100);
1328   EXPECT_TRUE(ch1.conn() != nullptr);
1329   conn->UpdateState(after_last_receiving + 90000 + 1);
1330   EXPECT_TRUE_WAIT(ch1.conn() == nullptr, kDefaultTimeout);
1331 }
1332 
TEST_F(PortTest,TestConnectionDeadOutstandingPing)1333 TEST_F(PortTest, TestConnectionDeadOutstandingPing) {
1334   auto port1 = CreateUdpPort(kLocalAddr1);
1335   port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1336   port1->SetIceTiebreaker(kTiebreaker1);
1337   auto port2 = CreateUdpPort(kLocalAddr2);
1338   port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
1339   port2->SetIceTiebreaker(kTiebreaker2);
1340 
1341   TestChannel ch1(std::move(port1));
1342   TestChannel ch2(std::move(port2));
1343   // Acquire address.
1344   ch1.Start();
1345   ch2.Start();
1346   ASSERT_EQ_WAIT(1, ch1.complete_count(), kDefaultTimeout);
1347   ASSERT_EQ_WAIT(1, ch2.complete_count(), kDefaultTimeout);
1348 
1349   // Note: set field trials manually since they are parsed by
1350   // P2PTransportChannel but P2PTransportChannel is not used in this test.
1351   IceFieldTrials field_trials;
1352   field_trials.dead_connection_timeout_ms = 360000;
1353 
1354   // Create a connection again and receive a ping and then send
1355   // a ping and keep it outstanding.
1356   ch1.CreateConnection(GetCandidate(ch2.port()));
1357   auto conn = ch1.conn();
1358   conn->SetIceFieldTrials(&field_trials);
1359 
1360   ASSERT_NE(conn, nullptr);
1361   conn->ReceivedPing();
1362   int64_t send_ping_timestamp = rtc::TimeMillis();
1363   conn->Ping(send_ping_timestamp);
1364 
1365   // The connection will be dead 30s after the ping was sent.
1366   conn->UpdateState(send_ping_timestamp + DEAD_CONNECTION_RECEIVE_TIMEOUT - 1);
1367   rtc::Thread::Current()->ProcessMessages(100);
1368   EXPECT_TRUE(ch1.conn() != nullptr);
1369   conn->UpdateState(send_ping_timestamp + DEAD_CONNECTION_RECEIVE_TIMEOUT + 1);
1370   EXPECT_TRUE_WAIT(ch1.conn() == nullptr, kDefaultTimeout);
1371 }
1372 
1373 // This test case verifies standard ICE features in STUN messages. Currently it
1374 // verifies Message Integrity attribute in STUN messages and username in STUN
1375 // binding request will have colon (":") between remote and local username.
TEST_F(PortTest,TestLocalToLocalStandard)1376 TEST_F(PortTest, TestLocalToLocalStandard) {
1377   auto port1 = CreateUdpPort(kLocalAddr1);
1378   port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1379   port1->SetIceTiebreaker(kTiebreaker1);
1380   auto port2 = CreateUdpPort(kLocalAddr2);
1381   port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
1382   port2->SetIceTiebreaker(kTiebreaker2);
1383   // Same parameters as TestLocalToLocal above.
1384   TestConnectivity("udp", std::move(port1), "udp", std::move(port2), true, true,
1385                    true, true);
1386 }
1387 
1388 // This test is trying to validate a successful and failure scenario in a
1389 // loopback test when protocol is RFC5245. For success IceTiebreaker, username
1390 // should remain equal to the request generated by the port and role of port
1391 // must be in controlling.
TEST_F(PortTest,TestLoopbackCall)1392 TEST_F(PortTest, TestLoopbackCall) {
1393   auto lport = CreateTestPort(kLocalAddr1, "lfrag", "lpass");
1394   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1395   lport->SetIceTiebreaker(kTiebreaker1);
1396   lport->PrepareAddress();
1397   ASSERT_FALSE(lport->Candidates().empty());
1398   Connection* conn =
1399       lport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1400   conn->Ping(0);
1401 
1402   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, kDefaultTimeout);
1403   IceMessage* msg = lport->last_stun_msg();
1404   EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1405   conn->OnReadPacket(lport->last_stun_buf()->data<char>(),
1406                      lport->last_stun_buf()->size(), /* packet_time_us */ -1);
1407   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, kDefaultTimeout);
1408   msg = lport->last_stun_msg();
1409   EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1410 
1411   // If the tiebreaker value is different from port, we expect a error
1412   // response.
1413   lport->Reset();
1414   lport->AddCandidateAddress(kLocalAddr2);
1415   // Creating a different connection as |conn| is receiving.
1416   Connection* conn1 =
1417       lport->CreateConnection(lport->Candidates()[1], Port::ORIGIN_MESSAGE);
1418   conn1->Ping(0);
1419 
1420   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, kDefaultTimeout);
1421   msg = lport->last_stun_msg();
1422   EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1423   std::unique_ptr<IceMessage> modified_req(
1424       CreateStunMessage(STUN_BINDING_REQUEST));
1425   const StunByteStringAttribute* username_attr =
1426       msg->GetByteString(STUN_ATTR_USERNAME);
1427   modified_req->AddAttribute(std::make_unique<StunByteStringAttribute>(
1428       STUN_ATTR_USERNAME, username_attr->GetString()));
1429   // To make sure we receive error response, adding tiebreaker less than
1430   // what's present in request.
1431   modified_req->AddAttribute(std::make_unique<StunUInt64Attribute>(
1432       STUN_ATTR_ICE_CONTROLLING, kTiebreaker1 - 1));
1433   modified_req->AddMessageIntegrity("lpass");
1434   modified_req->AddFingerprint();
1435 
1436   lport->Reset();
1437   auto buf = std::make_unique<ByteBufferWriter>();
1438   WriteStunMessage(*modified_req, buf.get());
1439   conn1->OnReadPacket(buf->Data(), buf->Length(), /* packet_time_us */ -1);
1440   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, kDefaultTimeout);
1441   msg = lport->last_stun_msg();
1442   EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1443 }
1444 
1445 // This test verifies role conflict signal is received when there is
1446 // conflict in the role. In this case both ports are in controlling and
1447 // |rport| has higher tiebreaker value than |lport|. Since |lport| has lower
1448 // value of tiebreaker, when it receives ping request from |rport| it will
1449 // send role conflict signal.
TEST_F(PortTest,TestIceRoleConflict)1450 TEST_F(PortTest, TestIceRoleConflict) {
1451   auto lport = CreateTestPort(kLocalAddr1, "lfrag", "lpass");
1452   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1453   lport->SetIceTiebreaker(kTiebreaker1);
1454   auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass");
1455   rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1456   rport->SetIceTiebreaker(kTiebreaker2);
1457 
1458   lport->PrepareAddress();
1459   rport->PrepareAddress();
1460   ASSERT_FALSE(lport->Candidates().empty());
1461   ASSERT_FALSE(rport->Candidates().empty());
1462   Connection* lconn =
1463       lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1464   Connection* rconn =
1465       rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1466   rconn->Ping(0);
1467 
1468   ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, kDefaultTimeout);
1469   IceMessage* msg = rport->last_stun_msg();
1470   EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1471   // Send rport binding request to lport.
1472   lconn->OnReadPacket(rport->last_stun_buf()->data<char>(),
1473                       rport->last_stun_buf()->size(), /* packet_time_us */ -1);
1474 
1475   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, kDefaultTimeout);
1476   EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
1477   EXPECT_TRUE(role_conflict());
1478 }
1479 
TEST_F(PortTest,TestTcpNoDelay)1480 TEST_F(PortTest, TestTcpNoDelay) {
1481   auto port1 = CreateTcpPort(kLocalAddr1);
1482   port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1483   int option_value = -1;
1484   int success = port1->GetOption(rtc::Socket::OPT_NODELAY, &option_value);
1485   ASSERT_EQ(0, success);  // GetOption() should complete successfully w/ 0
1486   ASSERT_EQ(1, option_value);
1487 }
1488 
TEST_F(PortTest,TestDelayedBindingUdp)1489 TEST_F(PortTest, TestDelayedBindingUdp) {
1490   FakeAsyncPacketSocket* socket = new FakeAsyncPacketSocket();
1491   FakePacketSocketFactory socket_factory;
1492 
1493   socket_factory.set_next_udp_socket(socket);
1494   auto port = CreateUdpPort(kLocalAddr1, &socket_factory);
1495 
1496   socket->set_state(AsyncPacketSocket::STATE_BINDING);
1497   port->PrepareAddress();
1498 
1499   EXPECT_EQ(0U, port->Candidates().size());
1500   socket->SignalAddressReady(socket, kLocalAddr2);
1501 
1502   EXPECT_EQ(1U, port->Candidates().size());
1503 }
1504 
TEST_F(PortTest,TestDelayedBindingTcp)1505 TEST_F(PortTest, TestDelayedBindingTcp) {
1506   FakeAsyncPacketSocket* socket = new FakeAsyncPacketSocket();
1507   FakePacketSocketFactory socket_factory;
1508 
1509   socket_factory.set_next_server_tcp_socket(socket);
1510   auto port = CreateTcpPort(kLocalAddr1, &socket_factory);
1511 
1512   socket->set_state(AsyncPacketSocket::STATE_BINDING);
1513   port->PrepareAddress();
1514 
1515   EXPECT_EQ(0U, port->Candidates().size());
1516   socket->SignalAddressReady(socket, kLocalAddr2);
1517 
1518   EXPECT_EQ(1U, port->Candidates().size());
1519 }
1520 
TEST_F(PortTest,TestDisableInterfaceOfTcpPort)1521 TEST_F(PortTest, TestDisableInterfaceOfTcpPort) {
1522   FakeAsyncPacketSocket* lsocket = new FakeAsyncPacketSocket();
1523   FakeAsyncPacketSocket* rsocket = new FakeAsyncPacketSocket();
1524   FakePacketSocketFactory socket_factory;
1525 
1526   socket_factory.set_next_server_tcp_socket(lsocket);
1527   auto lport = CreateTcpPort(kLocalAddr1, &socket_factory);
1528 
1529   socket_factory.set_next_server_tcp_socket(rsocket);
1530   auto rport = CreateTcpPort(kLocalAddr2, &socket_factory);
1531 
1532   lsocket->set_state(AsyncPacketSocket::STATE_BINDING);
1533   lsocket->SignalAddressReady(lsocket, kLocalAddr1);
1534   rsocket->set_state(AsyncPacketSocket::STATE_BINDING);
1535   rsocket->SignalAddressReady(rsocket, kLocalAddr2);
1536 
1537   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1538   lport->SetIceTiebreaker(kTiebreaker1);
1539   rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1540   rport->SetIceTiebreaker(kTiebreaker2);
1541 
1542   lport->PrepareAddress();
1543   rport->PrepareAddress();
1544   ASSERT_FALSE(rport->Candidates().empty());
1545 
1546   // A client socket.
1547   FakeAsyncPacketSocket* socket = new FakeAsyncPacketSocket();
1548   socket->local_address_ = kLocalAddr1;
1549   socket->remote_address_ = kLocalAddr2;
1550   socket_factory.set_next_client_tcp_socket(socket);
1551   Connection* lconn =
1552       lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1553   ASSERT_NE(lconn, nullptr);
1554   socket->SignalConnect(socket);
1555   lconn->Ping(0);
1556 
1557   // Now disconnect the client socket...
1558   socket->SignalClose(socket, 1);
1559 
1560   // And prevent new sockets from being created.
1561   socket_factory.set_next_client_tcp_socket(nullptr);
1562 
1563   // Test that Ping() does not cause SEGV.
1564   lconn->Ping(0);
1565 }
1566 
TestCrossFamilyPorts(int type)1567 void PortTest::TestCrossFamilyPorts(int type) {
1568   FakePacketSocketFactory factory;
1569   std::unique_ptr<Port> ports[4];
1570   SocketAddress addresses[4] = {
1571       SocketAddress("192.168.1.3", 0), SocketAddress("192.168.1.4", 0),
1572       SocketAddress("2001:db8::1", 0), SocketAddress("2001:db8::2", 0)};
1573   for (int i = 0; i < 4; i++) {
1574     FakeAsyncPacketSocket* socket = new FakeAsyncPacketSocket();
1575     if (type == SOCK_DGRAM) {
1576       factory.set_next_udp_socket(socket);
1577       ports[i] = CreateUdpPort(addresses[i], &factory);
1578     } else if (type == SOCK_STREAM) {
1579       factory.set_next_server_tcp_socket(socket);
1580       ports[i] = CreateTcpPort(addresses[i], &factory);
1581     }
1582     socket->set_state(AsyncPacketSocket::STATE_BINDING);
1583     socket->SignalAddressReady(socket, addresses[i]);
1584     ports[i]->PrepareAddress();
1585   }
1586 
1587   // IPv4 Port, connects to IPv6 candidate and then to IPv4 candidate.
1588   if (type == SOCK_STREAM) {
1589     FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1590     factory.set_next_client_tcp_socket(clientsocket);
1591   }
1592   Connection* c = ports[0]->CreateConnection(GetCandidate(ports[2].get()),
1593                                              Port::ORIGIN_MESSAGE);
1594   EXPECT_TRUE(NULL == c);
1595   EXPECT_EQ(0U, ports[0]->connections().size());
1596   c = ports[0]->CreateConnection(GetCandidate(ports[1].get()),
1597                                  Port::ORIGIN_MESSAGE);
1598   EXPECT_FALSE(NULL == c);
1599   EXPECT_EQ(1U, ports[0]->connections().size());
1600 
1601   // IPv6 Port, connects to IPv4 candidate and to IPv6 candidate.
1602   if (type == SOCK_STREAM) {
1603     FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1604     factory.set_next_client_tcp_socket(clientsocket);
1605   }
1606   c = ports[2]->CreateConnection(GetCandidate(ports[0].get()),
1607                                  Port::ORIGIN_MESSAGE);
1608   EXPECT_TRUE(NULL == c);
1609   EXPECT_EQ(0U, ports[2]->connections().size());
1610   c = ports[2]->CreateConnection(GetCandidate(ports[3].get()),
1611                                  Port::ORIGIN_MESSAGE);
1612   EXPECT_FALSE(NULL == c);
1613   EXPECT_EQ(1U, ports[2]->connections().size());
1614 }
1615 
TEST_F(PortTest,TestSkipCrossFamilyTcp)1616 TEST_F(PortTest, TestSkipCrossFamilyTcp) {
1617   TestCrossFamilyPorts(SOCK_STREAM);
1618 }
1619 
TEST_F(PortTest,TestSkipCrossFamilyUdp)1620 TEST_F(PortTest, TestSkipCrossFamilyUdp) {
1621   TestCrossFamilyPorts(SOCK_DGRAM);
1622 }
1623 
ExpectPortsCanConnect(bool can_connect,Port * p1,Port * p2)1624 void PortTest::ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2) {
1625   Connection* c = p1->CreateConnection(GetCandidate(p2), Port::ORIGIN_MESSAGE);
1626   if (can_connect) {
1627     EXPECT_FALSE(NULL == c);
1628     EXPECT_EQ(1U, p1->connections().size());
1629   } else {
1630     EXPECT_TRUE(NULL == c);
1631     EXPECT_EQ(0U, p1->connections().size());
1632   }
1633 }
1634 
TEST_F(PortTest,TestUdpV6CrossTypePorts)1635 TEST_F(PortTest, TestUdpV6CrossTypePorts) {
1636   FakePacketSocketFactory factory;
1637   std::unique_ptr<Port> ports[4];
1638   SocketAddress addresses[4] = {
1639       SocketAddress("2001:db8::1", 0), SocketAddress("fe80::1", 0),
1640       SocketAddress("fe80::2", 0), SocketAddress("::1", 0)};
1641   for (int i = 0; i < 4; i++) {
1642     FakeAsyncPacketSocket* socket = new FakeAsyncPacketSocket();
1643     factory.set_next_udp_socket(socket);
1644     ports[i] = CreateUdpPort(addresses[i], &factory);
1645     socket->set_state(AsyncPacketSocket::STATE_BINDING);
1646     socket->SignalAddressReady(socket, addresses[i]);
1647     ports[i]->PrepareAddress();
1648   }
1649 
1650   Port* standard = ports[0].get();
1651   Port* link_local1 = ports[1].get();
1652   Port* link_local2 = ports[2].get();
1653   Port* localhost = ports[3].get();
1654 
1655   ExpectPortsCanConnect(false, link_local1, standard);
1656   ExpectPortsCanConnect(false, standard, link_local1);
1657   ExpectPortsCanConnect(false, link_local1, localhost);
1658   ExpectPortsCanConnect(false, localhost, link_local1);
1659 
1660   ExpectPortsCanConnect(true, link_local1, link_local2);
1661   ExpectPortsCanConnect(true, localhost, standard);
1662   ExpectPortsCanConnect(true, standard, localhost);
1663 }
1664 
1665 // This test verifies DSCP value set through SetOption interface can be
1666 // get through DefaultDscpValue.
TEST_F(PortTest,TestDefaultDscpValue)1667 TEST_F(PortTest, TestDefaultDscpValue) {
1668   int dscp;
1669   auto udpport = CreateUdpPort(kLocalAddr1);
1670   EXPECT_EQ(0, udpport->SetOption(rtc::Socket::OPT_DSCP, rtc::DSCP_CS6));
1671   EXPECT_EQ(0, udpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1672   auto tcpport = CreateTcpPort(kLocalAddr1);
1673   EXPECT_EQ(0, tcpport->SetOption(rtc::Socket::OPT_DSCP, rtc::DSCP_AF31));
1674   EXPECT_EQ(0, tcpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1675   EXPECT_EQ(rtc::DSCP_AF31, dscp);
1676   auto stunport = CreateStunPort(kLocalAddr1, nat_socket_factory1());
1677   EXPECT_EQ(0, stunport->SetOption(rtc::Socket::OPT_DSCP, rtc::DSCP_AF41));
1678   EXPECT_EQ(0, stunport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1679   EXPECT_EQ(rtc::DSCP_AF41, dscp);
1680   auto turnport1 =
1681       CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP);
1682   // Socket is created in PrepareAddress.
1683   turnport1->PrepareAddress();
1684   EXPECT_EQ(0, turnport1->SetOption(rtc::Socket::OPT_DSCP, rtc::DSCP_CS7));
1685   EXPECT_EQ(0, turnport1->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1686   EXPECT_EQ(rtc::DSCP_CS7, dscp);
1687   // This will verify correct value returned without the socket.
1688   auto turnport2 =
1689       CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP);
1690   EXPECT_EQ(0, turnport2->SetOption(rtc::Socket::OPT_DSCP, rtc::DSCP_CS6));
1691   EXPECT_EQ(0, turnport2->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1692   EXPECT_EQ(rtc::DSCP_CS6, dscp);
1693 }
1694 
1695 // Test sending STUN messages.
TEST_F(PortTest,TestSendStunMessage)1696 TEST_F(PortTest, TestSendStunMessage) {
1697   auto lport = CreateTestPort(kLocalAddr1, "lfrag", "lpass");
1698   auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass");
1699   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1700   lport->SetIceTiebreaker(kTiebreaker1);
1701   rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1702   rport->SetIceTiebreaker(kTiebreaker2);
1703 
1704   // Send a fake ping from lport to rport.
1705   lport->PrepareAddress();
1706   rport->PrepareAddress();
1707   ASSERT_FALSE(rport->Candidates().empty());
1708   Connection* lconn =
1709       lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1710   Connection* rconn =
1711       rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1712   lconn->Ping(0);
1713 
1714   // Check that it's a proper BINDING-REQUEST.
1715   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, kDefaultTimeout);
1716   IceMessage* msg = lport->last_stun_msg();
1717   EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1718   EXPECT_FALSE(msg->IsLegacy());
1719   const StunByteStringAttribute* username_attr =
1720       msg->GetByteString(STUN_ATTR_USERNAME);
1721   ASSERT_TRUE(username_attr != NULL);
1722   const StunUInt32Attribute* priority_attr = msg->GetUInt32(STUN_ATTR_PRIORITY);
1723   ASSERT_TRUE(priority_attr != NULL);
1724   EXPECT_EQ(kDefaultPrflxPriority, priority_attr->value());
1725   EXPECT_EQ("rfrag:lfrag", username_attr->GetString());
1726   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1727   EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1728       lport->last_stun_buf()->data<char>(), lport->last_stun_buf()->size(),
1729       "rpass"));
1730   const StunUInt64Attribute* ice_controlling_attr =
1731       msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1732   ASSERT_TRUE(ice_controlling_attr != NULL);
1733   EXPECT_EQ(lport->IceTiebreaker(), ice_controlling_attr->value());
1734   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1735   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
1736   EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1737   EXPECT_TRUE(StunMessage::ValidateFingerprint(
1738       lport->last_stun_buf()->data<char>(), lport->last_stun_buf()->size()));
1739 
1740   // Request should not include ping count.
1741   ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1742 
1743   // Save a copy of the BINDING-REQUEST for use below.
1744   std::unique_ptr<IceMessage> request = CopyStunMessage(*msg);
1745 
1746   // Receive the BINDING-REQUEST and respond with BINDING-RESPONSE.
1747   rconn->OnReadPacket(lport->last_stun_buf()->data<char>(),
1748                       lport->last_stun_buf()->size(), /* packet_time_us */ -1);
1749   msg = rport->last_stun_msg();
1750   ASSERT_TRUE(msg != NULL);
1751   EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1752   // Received a BINDING-RESPONSE.
1753   lconn->OnReadPacket(rport->last_stun_buf()->data<char>(),
1754                       rport->last_stun_buf()->size(), /* packet_time_us */ -1);
1755   // Verify the STUN Stats.
1756   EXPECT_EQ(1U, lconn->stats().sent_ping_requests_total);
1757   EXPECT_EQ(1U, lconn->stats().sent_ping_requests_before_first_response);
1758   EXPECT_EQ(1U, lconn->stats().recv_ping_responses);
1759   EXPECT_EQ(1U, rconn->stats().recv_ping_requests);
1760   EXPECT_EQ(1U, rconn->stats().sent_ping_responses);
1761 
1762   EXPECT_FALSE(msg->IsLegacy());
1763   const StunAddressAttribute* addr_attr =
1764       msg->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
1765   ASSERT_TRUE(addr_attr != NULL);
1766   EXPECT_EQ(lport->Candidates()[0].address(), addr_attr->GetAddress());
1767   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1768   EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1769       rport->last_stun_buf()->data<char>(), rport->last_stun_buf()->size(),
1770       "rpass"));
1771   EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1772   EXPECT_TRUE(StunMessage::ValidateFingerprint(
1773       lport->last_stun_buf()->data<char>(), lport->last_stun_buf()->size()));
1774   // No USERNAME or PRIORITY in ICE responses.
1775   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1776   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1777   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MAPPED_ADDRESS) == NULL);
1778   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLING) == NULL);
1779   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1780   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1781 
1782   // Response should not include ping count.
1783   ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1784 
1785   // Respond with a BINDING-ERROR-RESPONSE. This wouldn't happen in real life,
1786   // but we can do it here.
1787   rport->SendBindingErrorResponse(
1788       request.get(), lport->Candidates()[0].address(), STUN_ERROR_SERVER_ERROR,
1789       STUN_ERROR_REASON_SERVER_ERROR);
1790   msg = rport->last_stun_msg();
1791   ASSERT_TRUE(msg != NULL);
1792   EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1793   EXPECT_FALSE(msg->IsLegacy());
1794   const StunErrorCodeAttribute* error_attr = msg->GetErrorCode();
1795   ASSERT_TRUE(error_attr != NULL);
1796   EXPECT_EQ(STUN_ERROR_SERVER_ERROR, error_attr->code());
1797   EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR), error_attr->reason());
1798   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1799   EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1800       rport->last_stun_buf()->data<char>(), rport->last_stun_buf()->size(),
1801       "rpass"));
1802   EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1803   EXPECT_TRUE(StunMessage::ValidateFingerprint(
1804       lport->last_stun_buf()->data<char>(), lport->last_stun_buf()->size()));
1805   // No USERNAME with ICE.
1806   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1807   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1808 
1809   // Testing STUN binding requests from rport --> lport, having ICE_CONTROLLED
1810   // and (incremented) RETRANSMIT_COUNT attributes.
1811   rport->Reset();
1812   rport->set_send_retransmit_count_attribute(true);
1813   rconn->Ping(0);
1814   rconn->Ping(0);
1815   rconn->Ping(0);
1816   ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, kDefaultTimeout);
1817   msg = rport->last_stun_msg();
1818   EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1819   const StunUInt64Attribute* ice_controlled_attr =
1820       msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
1821   ASSERT_TRUE(ice_controlled_attr != NULL);
1822   EXPECT_EQ(rport->IceTiebreaker(), ice_controlled_attr->value());
1823   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1824 
1825   // Request should include ping count.
1826   const StunUInt32Attribute* retransmit_attr =
1827       msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1828   ASSERT_TRUE(retransmit_attr != NULL);
1829   EXPECT_EQ(2U, retransmit_attr->value());
1830 
1831   // Respond with a BINDING-RESPONSE.
1832   request = CopyStunMessage(*msg);
1833   lconn->OnReadPacket(rport->last_stun_buf()->data<char>(),
1834                       rport->last_stun_buf()->size(), /* packet_time_us */ -1);
1835   msg = lport->last_stun_msg();
1836   // Receive the BINDING-RESPONSE.
1837   rconn->OnReadPacket(lport->last_stun_buf()->data<char>(),
1838                       lport->last_stun_buf()->size(), /* packet_time_us */ -1);
1839 
1840   // Verify the Stun ping stats.
1841   EXPECT_EQ(3U, rconn->stats().sent_ping_requests_total);
1842   EXPECT_EQ(3U, rconn->stats().sent_ping_requests_before_first_response);
1843   EXPECT_EQ(1U, rconn->stats().recv_ping_responses);
1844   EXPECT_EQ(1U, lconn->stats().sent_ping_responses);
1845   EXPECT_EQ(1U, lconn->stats().recv_ping_requests);
1846   // Ping after receiver the first response
1847   rconn->Ping(0);
1848   rconn->Ping(0);
1849   EXPECT_EQ(5U, rconn->stats().sent_ping_requests_total);
1850   EXPECT_EQ(3U, rconn->stats().sent_ping_requests_before_first_response);
1851 
1852   // Response should include same ping count.
1853   retransmit_attr = msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1854   ASSERT_TRUE(retransmit_attr != NULL);
1855   EXPECT_EQ(2U, retransmit_attr->value());
1856 }
1857 
TEST_F(PortTest,TestNomination)1858 TEST_F(PortTest, TestNomination) {
1859   auto lport = CreateTestPort(kLocalAddr1, "lfrag", "lpass");
1860   auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass");
1861   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1862   lport->SetIceTiebreaker(kTiebreaker1);
1863   rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1864   rport->SetIceTiebreaker(kTiebreaker2);
1865 
1866   lport->PrepareAddress();
1867   rport->PrepareAddress();
1868   ASSERT_FALSE(lport->Candidates().empty());
1869   ASSERT_FALSE(rport->Candidates().empty());
1870   Connection* lconn =
1871       lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1872   Connection* rconn =
1873       rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1874 
1875   // |lconn| is controlling, |rconn| is controlled.
1876   uint32_t nomination = 1234;
1877   lconn->set_nomination(nomination);
1878 
1879   EXPECT_FALSE(lconn->nominated());
1880   EXPECT_FALSE(rconn->nominated());
1881   EXPECT_EQ(lconn->nominated(), lconn->stats().nominated);
1882   EXPECT_EQ(rconn->nominated(), rconn->stats().nominated);
1883 
1884   // Send ping (including the nomination value) from |lconn| to |rconn|. This
1885   // should set the remote nomination of |rconn|.
1886   lconn->Ping(0);
1887   ASSERT_TRUE_WAIT(lport->last_stun_msg(), kDefaultTimeout);
1888   ASSERT_TRUE(lport->last_stun_buf());
1889   rconn->OnReadPacket(lport->last_stun_buf()->data<char>(),
1890                       lport->last_stun_buf()->size(), /* packet_time_us */ -1);
1891   EXPECT_EQ(nomination, rconn->remote_nomination());
1892   EXPECT_FALSE(lconn->nominated());
1893   EXPECT_TRUE(rconn->nominated());
1894   EXPECT_EQ(lconn->nominated(), lconn->stats().nominated);
1895   EXPECT_EQ(rconn->nominated(), rconn->stats().nominated);
1896 
1897   // This should result in an acknowledgment sent back from |rconn| to |lconn|,
1898   // updating the acknowledged nomination of |lconn|.
1899   ASSERT_TRUE_WAIT(rport->last_stun_msg(), kDefaultTimeout);
1900   ASSERT_TRUE(rport->last_stun_buf());
1901   lconn->OnReadPacket(rport->last_stun_buf()->data<char>(),
1902                       rport->last_stun_buf()->size(), /* packet_time_us */ -1);
1903   EXPECT_EQ(nomination, lconn->acked_nomination());
1904   EXPECT_TRUE(lconn->nominated());
1905   EXPECT_TRUE(rconn->nominated());
1906   EXPECT_EQ(lconn->nominated(), lconn->stats().nominated);
1907   EXPECT_EQ(rconn->nominated(), rconn->stats().nominated);
1908 }
1909 
TEST_F(PortTest,TestRoundTripTime)1910 TEST_F(PortTest, TestRoundTripTime) {
1911   rtc::ScopedFakeClock clock;
1912 
1913   auto lport = CreateTestPort(kLocalAddr1, "lfrag", "lpass");
1914   auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass");
1915   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1916   lport->SetIceTiebreaker(kTiebreaker1);
1917   rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1918   rport->SetIceTiebreaker(kTiebreaker2);
1919 
1920   lport->PrepareAddress();
1921   rport->PrepareAddress();
1922   ASSERT_FALSE(lport->Candidates().empty());
1923   ASSERT_FALSE(rport->Candidates().empty());
1924   Connection* lconn =
1925       lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1926   Connection* rconn =
1927       rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1928 
1929   EXPECT_EQ(0u, lconn->stats().total_round_trip_time_ms);
1930   EXPECT_FALSE(lconn->stats().current_round_trip_time_ms);
1931 
1932   SendPingAndReceiveResponse(lconn, lport.get(), rconn, rport.get(), &clock,
1933                              10);
1934   EXPECT_EQ(10u, lconn->stats().total_round_trip_time_ms);
1935   ASSERT_TRUE(lconn->stats().current_round_trip_time_ms);
1936   EXPECT_EQ(10u, *lconn->stats().current_round_trip_time_ms);
1937 
1938   SendPingAndReceiveResponse(lconn, lport.get(), rconn, rport.get(), &clock,
1939                              20);
1940   EXPECT_EQ(30u, lconn->stats().total_round_trip_time_ms);
1941   ASSERT_TRUE(lconn->stats().current_round_trip_time_ms);
1942   EXPECT_EQ(20u, *lconn->stats().current_round_trip_time_ms);
1943 
1944   SendPingAndReceiveResponse(lconn, lport.get(), rconn, rport.get(), &clock,
1945                              30);
1946   EXPECT_EQ(60u, lconn->stats().total_round_trip_time_ms);
1947   ASSERT_TRUE(lconn->stats().current_round_trip_time_ms);
1948   EXPECT_EQ(30u, *lconn->stats().current_round_trip_time_ms);
1949 }
1950 
TEST_F(PortTest,TestUseCandidateAttribute)1951 TEST_F(PortTest, TestUseCandidateAttribute) {
1952   auto lport = CreateTestPort(kLocalAddr1, "lfrag", "lpass");
1953   auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass");
1954   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1955   lport->SetIceTiebreaker(kTiebreaker1);
1956   rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1957   rport->SetIceTiebreaker(kTiebreaker2);
1958 
1959   // Send a fake ping from lport to rport.
1960   lport->PrepareAddress();
1961   rport->PrepareAddress();
1962   ASSERT_FALSE(rport->Candidates().empty());
1963   Connection* lconn =
1964       lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1965   lconn->Ping(0);
1966   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, kDefaultTimeout);
1967   IceMessage* msg = lport->last_stun_msg();
1968   const StunUInt64Attribute* ice_controlling_attr =
1969       msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1970   ASSERT_TRUE(ice_controlling_attr != NULL);
1971   const StunByteStringAttribute* use_candidate_attr =
1972       msg->GetByteString(STUN_ATTR_USE_CANDIDATE);
1973   ASSERT_TRUE(use_candidate_attr != NULL);
1974 }
1975 
1976 // Tests that when the network type changes, the network cost of the port will
1977 // change, the network cost of the local candidates will change. Also tests that
1978 // the remote network costs are updated with the stun binding requests.
TEST_F(PortTest,TestNetworkCostChange)1979 TEST_F(PortTest, TestNetworkCostChange) {
1980   rtc::Network* test_network = MakeNetwork(kLocalAddr1);
1981   auto lport = CreateTestPort(test_network, "lfrag", "lpass");
1982   auto rport = CreateTestPort(test_network, "rfrag", "rpass");
1983   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1984   lport->SetIceTiebreaker(kTiebreaker1);
1985   rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1986   rport->SetIceTiebreaker(kTiebreaker2);
1987   lport->PrepareAddress();
1988   rport->PrepareAddress();
1989 
1990   // Default local port cost is rtc::kNetworkCostUnknown.
1991   EXPECT_EQ(rtc::kNetworkCostUnknown, lport->network_cost());
1992   ASSERT_TRUE(!lport->Candidates().empty());
1993   for (const cricket::Candidate& candidate : lport->Candidates()) {
1994     EXPECT_EQ(rtc::kNetworkCostUnknown, candidate.network_cost());
1995   }
1996 
1997   // Change the network type to wifi.
1998   test_network->set_type(rtc::ADAPTER_TYPE_WIFI);
1999   EXPECT_EQ(rtc::kNetworkCostLow, lport->network_cost());
2000   for (const cricket::Candidate& candidate : lport->Candidates()) {
2001     EXPECT_EQ(rtc::kNetworkCostLow, candidate.network_cost());
2002   }
2003 
2004   // Add a connection and then change the network type.
2005   Connection* lconn =
2006       lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE);
2007   // Change the network type to cellular.
2008   test_network->set_type(rtc::ADAPTER_TYPE_CELLULAR);
2009   EXPECT_EQ(rtc::kNetworkCostHigh, lport->network_cost());
2010   for (const cricket::Candidate& candidate : lport->Candidates()) {
2011     EXPECT_EQ(rtc::kNetworkCostHigh, candidate.network_cost());
2012   }
2013 
2014   test_network->set_type(rtc::ADAPTER_TYPE_WIFI);
2015   Connection* rconn =
2016       rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE);
2017   test_network->set_type(rtc::ADAPTER_TYPE_CELLULAR);
2018   lconn->Ping(0);
2019   // The rconn's remote candidate cost is rtc::kNetworkCostLow, but the ping
2020   // contains an attribute of network cost of rtc::kNetworkCostHigh. Once the
2021   // message is handled in rconn, The rconn's remote candidate will have cost
2022   // rtc::kNetworkCostHigh;
2023   EXPECT_EQ(rtc::kNetworkCostLow, rconn->remote_candidate().network_cost());
2024   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, kDefaultTimeout);
2025   IceMessage* msg = lport->last_stun_msg();
2026   EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
2027   // Pass the binding request to rport.
2028   rconn->OnReadPacket(lport->last_stun_buf()->data<char>(),
2029                       lport->last_stun_buf()->size(), /* packet_time_us */ -1);
2030   // Wait until rport sends the response and then check the remote network cost.
2031   ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, kDefaultTimeout);
2032   EXPECT_EQ(rtc::kNetworkCostHigh, rconn->remote_candidate().network_cost());
2033 }
2034 
TEST_F(PortTest,TestNetworkInfoAttribute)2035 TEST_F(PortTest, TestNetworkInfoAttribute) {
2036   rtc::Network* test_network = MakeNetwork(kLocalAddr1);
2037   auto lport = CreateTestPort(test_network, "lfrag", "lpass");
2038   auto rport = CreateTestPort(test_network, "rfrag", "rpass");
2039   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2040   lport->SetIceTiebreaker(kTiebreaker1);
2041   rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2042   rport->SetIceTiebreaker(kTiebreaker2);
2043 
2044   uint16_t lnetwork_id = 9;
2045   lport->Network()->set_id(lnetwork_id);
2046   // Send a fake ping from lport to rport.
2047   lport->PrepareAddress();
2048   rport->PrepareAddress();
2049   Connection* lconn =
2050       lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE);
2051   lconn->Ping(0);
2052   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, kDefaultTimeout);
2053   IceMessage* msg = lport->last_stun_msg();
2054   const StunUInt32Attribute* network_info_attr =
2055       msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
2056   ASSERT_TRUE(network_info_attr != NULL);
2057   uint32_t network_info = network_info_attr->value();
2058   EXPECT_EQ(lnetwork_id, network_info >> 16);
2059   // Default network has unknown type and cost kNetworkCostUnknown.
2060   EXPECT_EQ(rtc::kNetworkCostUnknown, network_info & 0xFFFF);
2061 
2062   // Set the network type to be cellular so its cost will be kNetworkCostHigh.
2063   // Send a fake ping from rport to lport.
2064   test_network->set_type(rtc::ADAPTER_TYPE_CELLULAR);
2065   uint16_t rnetwork_id = 8;
2066   rport->Network()->set_id(rnetwork_id);
2067   Connection* rconn =
2068       rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE);
2069   rconn->Ping(0);
2070   ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, kDefaultTimeout);
2071   msg = rport->last_stun_msg();
2072   network_info_attr = msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
2073   ASSERT_TRUE(network_info_attr != NULL);
2074   network_info = network_info_attr->value();
2075   EXPECT_EQ(rnetwork_id, network_info >> 16);
2076   EXPECT_EQ(rtc::kNetworkCostHigh, network_info & 0xFFFF);
2077 }
2078 
2079 // Test handling STUN messages.
TEST_F(PortTest,TestHandleStunMessage)2080 TEST_F(PortTest, TestHandleStunMessage) {
2081   // Our port will act as the "remote" port.
2082   auto port = CreateTestPort(kLocalAddr2, "rfrag", "rpass");
2083 
2084   std::unique_ptr<IceMessage> in_msg, out_msg;
2085   auto buf = std::make_unique<ByteBufferWriter>();
2086   rtc::SocketAddress addr(kLocalAddr1);
2087   std::string username;
2088 
2089   // BINDING-REQUEST from local to remote with valid ICE username,
2090   // MESSAGE-INTEGRITY, and FINGERPRINT.
2091   in_msg = CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "rfrag:lfrag");
2092   in_msg->AddMessageIntegrity("rpass");
2093   in_msg->AddFingerprint();
2094   WriteStunMessage(*in_msg, buf.get());
2095   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2096                                    &username));
2097   EXPECT_TRUE(out_msg.get() != NULL);
2098   EXPECT_EQ("lfrag", username);
2099 
2100   // BINDING-RESPONSE without username, with MESSAGE-INTEGRITY and FINGERPRINT.
2101   in_msg = CreateStunMessage(STUN_BINDING_RESPONSE);
2102   in_msg->AddAttribute(std::make_unique<StunXorAddressAttribute>(
2103       STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
2104   in_msg->AddMessageIntegrity("rpass");
2105   in_msg->AddFingerprint();
2106   WriteStunMessage(*in_msg, buf.get());
2107   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2108                                    &username));
2109   EXPECT_TRUE(out_msg.get() != NULL);
2110   EXPECT_EQ("", username);
2111 
2112   // BINDING-ERROR-RESPONSE without username, with error, M-I, and FINGERPRINT.
2113   in_msg = CreateStunMessage(STUN_BINDING_ERROR_RESPONSE);
2114   in_msg->AddAttribute(std::make_unique<StunErrorCodeAttribute>(
2115       STUN_ATTR_ERROR_CODE, STUN_ERROR_SERVER_ERROR,
2116       STUN_ERROR_REASON_SERVER_ERROR));
2117   in_msg->AddFingerprint();
2118   WriteStunMessage(*in_msg, buf.get());
2119   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2120                                    &username));
2121   EXPECT_TRUE(out_msg.get() != NULL);
2122   EXPECT_EQ("", username);
2123   ASSERT_TRUE(out_msg->GetErrorCode() != NULL);
2124   EXPECT_EQ(STUN_ERROR_SERVER_ERROR, out_msg->GetErrorCode()->code());
2125   EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR),
2126             out_msg->GetErrorCode()->reason());
2127 }
2128 
2129 // Tests handling of ICE binding requests with missing or incorrect usernames.
TEST_F(PortTest,TestHandleStunMessageBadUsername)2130 TEST_F(PortTest, TestHandleStunMessageBadUsername) {
2131   auto port = CreateTestPort(kLocalAddr2, "rfrag", "rpass");
2132 
2133   std::unique_ptr<IceMessage> in_msg, out_msg;
2134   auto buf = std::make_unique<ByteBufferWriter>();
2135   rtc::SocketAddress addr(kLocalAddr1);
2136   std::string username;
2137 
2138   // BINDING-REQUEST with no username.
2139   in_msg = CreateStunMessage(STUN_BINDING_REQUEST);
2140   in_msg->AddMessageIntegrity("rpass");
2141   in_msg->AddFingerprint();
2142   WriteStunMessage(*in_msg, buf.get());
2143   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2144                                    &username));
2145   EXPECT_TRUE(out_msg.get() == NULL);
2146   EXPECT_EQ("", username);
2147   EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
2148 
2149   // BINDING-REQUEST with empty username.
2150   in_msg = CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "");
2151   in_msg->AddMessageIntegrity("rpass");
2152   in_msg->AddFingerprint();
2153   WriteStunMessage(*in_msg, buf.get());
2154   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2155                                    &username));
2156   EXPECT_TRUE(out_msg.get() == NULL);
2157   EXPECT_EQ("", username);
2158   EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
2159 
2160   // BINDING-REQUEST with too-short username.
2161   in_msg = CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "rfra");
2162   in_msg->AddMessageIntegrity("rpass");
2163   in_msg->AddFingerprint();
2164   WriteStunMessage(*in_msg, buf.get());
2165   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2166                                    &username));
2167   EXPECT_TRUE(out_msg.get() == NULL);
2168   EXPECT_EQ("", username);
2169   EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
2170 
2171   // BINDING-REQUEST with reversed username.
2172   in_msg = CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "lfrag:rfrag");
2173   in_msg->AddMessageIntegrity("rpass");
2174   in_msg->AddFingerprint();
2175   WriteStunMessage(*in_msg, buf.get());
2176   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2177                                    &username));
2178   EXPECT_TRUE(out_msg.get() == NULL);
2179   EXPECT_EQ("", username);
2180   EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
2181 
2182   // BINDING-REQUEST with garbage username.
2183   in_msg = CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "abcd:efgh");
2184   in_msg->AddMessageIntegrity("rpass");
2185   in_msg->AddFingerprint();
2186   WriteStunMessage(*in_msg, buf.get());
2187   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2188                                    &username));
2189   EXPECT_TRUE(out_msg.get() == NULL);
2190   EXPECT_EQ("", username);
2191   EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
2192 }
2193 
2194 // Test handling STUN messages with missing or malformed M-I.
TEST_F(PortTest,TestHandleStunMessageBadMessageIntegrity)2195 TEST_F(PortTest, TestHandleStunMessageBadMessageIntegrity) {
2196   // Our port will act as the "remote" port.
2197   auto port = CreateTestPort(kLocalAddr2, "rfrag", "rpass");
2198 
2199   std::unique_ptr<IceMessage> in_msg, out_msg;
2200   auto buf = std::make_unique<ByteBufferWriter>();
2201   rtc::SocketAddress addr(kLocalAddr1);
2202   std::string username;
2203 
2204   // BINDING-REQUEST from local to remote with valid ICE username and
2205   // FINGERPRINT, but no MESSAGE-INTEGRITY.
2206   in_msg = CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "rfrag:lfrag");
2207   in_msg->AddFingerprint();
2208   WriteStunMessage(*in_msg, buf.get());
2209   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2210                                    &username));
2211   EXPECT_TRUE(out_msg.get() == NULL);
2212   EXPECT_EQ("", username);
2213   EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
2214 
2215   // BINDING-REQUEST from local to remote with valid ICE username and
2216   // FINGERPRINT, but invalid MESSAGE-INTEGRITY.
2217   in_msg = CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "rfrag:lfrag");
2218   in_msg->AddMessageIntegrity("invalid");
2219   in_msg->AddFingerprint();
2220   WriteStunMessage(*in_msg, buf.get());
2221   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2222                                    &username));
2223   EXPECT_TRUE(out_msg.get() == NULL);
2224   EXPECT_EQ("", username);
2225   EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
2226 
2227   // TODO(?): BINDING-RESPONSES and BINDING-ERROR-RESPONSES are checked
2228   // by the Connection, not the Port, since they require the remote username.
2229   // Change this test to pass in data via Connection::OnReadPacket instead.
2230 }
2231 
2232 // Test handling STUN messages with missing or malformed FINGERPRINT.
TEST_F(PortTest,TestHandleStunMessageBadFingerprint)2233 TEST_F(PortTest, TestHandleStunMessageBadFingerprint) {
2234   // Our port will act as the "remote" port.
2235   auto port = CreateTestPort(kLocalAddr2, "rfrag", "rpass");
2236 
2237   std::unique_ptr<IceMessage> in_msg, out_msg;
2238   auto buf = std::make_unique<ByteBufferWriter>();
2239   rtc::SocketAddress addr(kLocalAddr1);
2240   std::string username;
2241 
2242   // BINDING-REQUEST from local to remote with valid ICE username and
2243   // MESSAGE-INTEGRITY, but no FINGERPRINT; GetStunMessage should fail.
2244   in_msg = CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "rfrag:lfrag");
2245   in_msg->AddMessageIntegrity("rpass");
2246   WriteStunMessage(*in_msg, buf.get());
2247   EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2248                                     &username));
2249   EXPECT_EQ(0, port->last_stun_error_code());
2250 
2251   // Now, add a fingerprint, but munge the message so it's not valid.
2252   in_msg->AddFingerprint();
2253   in_msg->SetTransactionID("TESTTESTBADD");
2254   WriteStunMessage(*in_msg, buf.get());
2255   EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2256                                     &username));
2257   EXPECT_EQ(0, port->last_stun_error_code());
2258 
2259   // Valid BINDING-RESPONSE, except no FINGERPRINT.
2260   in_msg = CreateStunMessage(STUN_BINDING_RESPONSE);
2261   in_msg->AddAttribute(std::make_unique<StunXorAddressAttribute>(
2262       STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
2263   in_msg->AddMessageIntegrity("rpass");
2264   WriteStunMessage(*in_msg, buf.get());
2265   EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2266                                     &username));
2267   EXPECT_EQ(0, port->last_stun_error_code());
2268 
2269   // Now, add a fingerprint, but munge the message so it's not valid.
2270   in_msg->AddFingerprint();
2271   in_msg->SetTransactionID("TESTTESTBADD");
2272   WriteStunMessage(*in_msg, buf.get());
2273   EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2274                                     &username));
2275   EXPECT_EQ(0, port->last_stun_error_code());
2276 
2277   // Valid BINDING-ERROR-RESPONSE, except no FINGERPRINT.
2278   in_msg = CreateStunMessage(STUN_BINDING_ERROR_RESPONSE);
2279   in_msg->AddAttribute(std::make_unique<StunErrorCodeAttribute>(
2280       STUN_ATTR_ERROR_CODE, STUN_ERROR_SERVER_ERROR,
2281       STUN_ERROR_REASON_SERVER_ERROR));
2282   in_msg->AddMessageIntegrity("rpass");
2283   WriteStunMessage(*in_msg, buf.get());
2284   EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2285                                     &username));
2286   EXPECT_EQ(0, port->last_stun_error_code());
2287 
2288   // Now, add a fingerprint, but munge the message so it's not valid.
2289   in_msg->AddFingerprint();
2290   in_msg->SetTransactionID("TESTTESTBADD");
2291   WriteStunMessage(*in_msg, buf.get());
2292   EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2293                                     &username));
2294   EXPECT_EQ(0, port->last_stun_error_code());
2295 }
2296 
2297 // Test handling a STUN message with unknown attributes in the
2298 // "comprehension-required" range. Should respond with an error with the
2299 // unknown attributes' IDs.
TEST_F(PortTest,TestHandleStunRequestWithUnknownComprehensionRequiredAttribute)2300 TEST_F(PortTest,
2301        TestHandleStunRequestWithUnknownComprehensionRequiredAttribute) {
2302   // Our port will act as the "remote" port.
2303   std::unique_ptr<TestPort> port(CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
2304 
2305   std::unique_ptr<IceMessage> in_msg, out_msg;
2306   auto buf = std::make_unique<ByteBufferWriter>();
2307   rtc::SocketAddress addr(kLocalAddr1);
2308   std::string username;
2309 
2310   // Build ordinary message with valid ufrag/pass.
2311   in_msg = CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "rfrag:lfrag");
2312   in_msg->AddMessageIntegrity("rpass");
2313   // Add a couple attributes with ID in comprehension-required range.
2314   in_msg->AddAttribute(StunAttribute::CreateUInt32(0x7777));
2315   in_msg->AddAttribute(StunAttribute::CreateUInt32(0x4567));
2316   // ... And one outside the range.
2317   in_msg->AddAttribute(StunAttribute::CreateUInt32(0xdead));
2318   in_msg->AddFingerprint();
2319   WriteStunMessage(*in_msg, buf.get());
2320   ASSERT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2321                                    &username));
2322   IceMessage* error_response = port->last_stun_msg();
2323   ASSERT_NE(nullptr, error_response);
2324 
2325   // Verify that the "unknown attribute" error response has the right error
2326   // code, and includes an attribute that lists out the unrecognized attribute
2327   // types.
2328   EXPECT_EQ(STUN_ERROR_UNKNOWN_ATTRIBUTE, error_response->GetErrorCodeValue());
2329   const StunUInt16ListAttribute* unknown_attributes =
2330       error_response->GetUnknownAttributes();
2331   ASSERT_NE(nullptr, unknown_attributes);
2332   ASSERT_EQ(2u, unknown_attributes->Size());
2333   EXPECT_EQ(0x7777, unknown_attributes->GetType(0));
2334   EXPECT_EQ(0x4567, unknown_attributes->GetType(1));
2335 }
2336 
2337 // Similar to the above, but with a response instead of a request. In this
2338 // case the response should just be ignored and transaction treated is failed.
TEST_F(PortTest,TestHandleStunResponseWithUnknownComprehensionRequiredAttribute)2339 TEST_F(PortTest,
2340        TestHandleStunResponseWithUnknownComprehensionRequiredAttribute) {
2341   // Generic setup.
2342   auto lport = CreateTestPort(kLocalAddr1, "lfrag", "lpass");
2343   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2344   auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass");
2345   rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2346   lport->PrepareAddress();
2347   rport->PrepareAddress();
2348   ASSERT_FALSE(lport->Candidates().empty());
2349   ASSERT_FALSE(rport->Candidates().empty());
2350   Connection* lconn =
2351       lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE);
2352   Connection* rconn =
2353       rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE);
2354 
2355   // Send request.
2356   lconn->Ping(0);
2357   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, kDefaultTimeout);
2358   rconn->OnReadPacket(lport->last_stun_buf()->data<char>(),
2359                       lport->last_stun_buf()->size(), /* packet_time_us */ -1);
2360 
2361   // Intercept request and add comprehension required attribute.
2362   ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, kDefaultTimeout);
2363   auto modified_response = rport->last_stun_msg()->Clone();
2364   modified_response->AddAttribute(StunAttribute::CreateUInt32(0x7777));
2365   modified_response->RemoveAttribute(STUN_ATTR_FINGERPRINT);
2366   modified_response->AddFingerprint();
2367   ByteBufferWriter buf;
2368   WriteStunMessage(*modified_response, &buf);
2369   lconn->OnReadPacket(buf.Data(), buf.Length(), /* packet_time_us */ -1);
2370   // Response should have been ignored, leaving us unwritable still.
2371   EXPECT_FALSE(lconn->writable());
2372 }
2373 
2374 // Similar to the above, but with an indication. As with a response, it should
2375 // just be ignored.
TEST_F(PortTest,TestHandleStunIndicationWithUnknownComprehensionRequiredAttribute)2376 TEST_F(PortTest,
2377        TestHandleStunIndicationWithUnknownComprehensionRequiredAttribute) {
2378   // Generic set up.
2379   auto lport = CreateTestPort(kLocalAddr2, "lfrag", "lpass");
2380   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2381   auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass");
2382   rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2383   lport->PrepareAddress();
2384   rport->PrepareAddress();
2385   ASSERT_FALSE(lport->Candidates().empty());
2386   ASSERT_FALSE(rport->Candidates().empty());
2387   Connection* lconn =
2388       lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE);
2389 
2390   // Generate indication with comprehension required attribute and verify it
2391   // doesn't update last_ping_received.
2392   auto in_msg = CreateStunMessage(STUN_BINDING_INDICATION);
2393   in_msg->AddAttribute(StunAttribute::CreateUInt32(0x7777));
2394   in_msg->AddFingerprint();
2395   ByteBufferWriter buf;
2396   WriteStunMessage(*in_msg, &buf);
2397   lconn->OnReadPacket(buf.Data(), buf.Length(), /* packet_time_us */ -1);
2398   EXPECT_EQ(0u, lconn->last_ping_received());
2399 }
2400 
2401 // Test handling of STUN binding indication messages . STUN binding
2402 // indications are allowed only to the connection which is in read mode.
TEST_F(PortTest,TestHandleStunBindingIndication)2403 TEST_F(PortTest, TestHandleStunBindingIndication) {
2404   auto lport = CreateTestPort(kLocalAddr2, "lfrag", "lpass");
2405   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2406   lport->SetIceTiebreaker(kTiebreaker1);
2407 
2408   // Verifying encoding and decoding STUN indication message.
2409   std::unique_ptr<IceMessage> in_msg, out_msg;
2410   std::unique_ptr<ByteBufferWriter> buf(new ByteBufferWriter());
2411   rtc::SocketAddress addr(kLocalAddr1);
2412   std::string username;
2413 
2414   in_msg = CreateStunMessage(STUN_BINDING_INDICATION);
2415   in_msg->AddFingerprint();
2416   WriteStunMessage(*in_msg, buf.get());
2417   EXPECT_TRUE(lport->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2418                                     &username));
2419   EXPECT_TRUE(out_msg.get() != NULL);
2420   EXPECT_EQ(out_msg->type(), STUN_BINDING_INDICATION);
2421   EXPECT_EQ("", username);
2422 
2423   // Verify connection can handle STUN indication and updates
2424   // last_ping_received.
2425   auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass");
2426   rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2427   rport->SetIceTiebreaker(kTiebreaker2);
2428 
2429   lport->PrepareAddress();
2430   rport->PrepareAddress();
2431   ASSERT_FALSE(lport->Candidates().empty());
2432   ASSERT_FALSE(rport->Candidates().empty());
2433 
2434   Connection* lconn =
2435       lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE);
2436   Connection* rconn =
2437       rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE);
2438   rconn->Ping(0);
2439 
2440   ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, kDefaultTimeout);
2441   IceMessage* msg = rport->last_stun_msg();
2442   EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
2443   // Send rport binding request to lport.
2444   lconn->OnReadPacket(rport->last_stun_buf()->data<char>(),
2445                       rport->last_stun_buf()->size(), /* packet_time_us */ -1);
2446   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, kDefaultTimeout);
2447   EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
2448   int64_t last_ping_received1 = lconn->last_ping_received();
2449 
2450   // Adding a delay of 100ms.
2451   rtc::Thread::Current()->ProcessMessages(100);
2452   // Pinging lconn using stun indication message.
2453   lconn->OnReadPacket(buf->Data(), buf->Length(), /* packet_time_us */ -1);
2454   int64_t last_ping_received2 = lconn->last_ping_received();
2455   EXPECT_GT(last_ping_received2, last_ping_received1);
2456 }
2457 
TEST_F(PortTest,TestComputeCandidatePriority)2458 TEST_F(PortTest, TestComputeCandidatePriority) {
2459   auto port = CreateTestPort(kLocalAddr1, "name", "pass");
2460   port->set_type_preference(90);
2461   port->set_component(177);
2462   port->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2463   port->AddCandidateAddress(SocketAddress("2001:db8::1234", 1234));
2464   port->AddCandidateAddress(SocketAddress("fc12:3456::1234", 1234));
2465   port->AddCandidateAddress(SocketAddress("::ffff:192.168.1.4", 1234));
2466   port->AddCandidateAddress(SocketAddress("::192.168.1.4", 1234));
2467   port->AddCandidateAddress(SocketAddress("2002::1234:5678", 1234));
2468   port->AddCandidateAddress(SocketAddress("2001::1234:5678", 1234));
2469   port->AddCandidateAddress(SocketAddress("fecf::1234:5678", 1234));
2470   port->AddCandidateAddress(SocketAddress("3ffe::1234:5678", 1234));
2471   // These should all be:
2472   // (90 << 24) | ([rfc3484 pref value] << 8) | (256 - 177)
2473   uint32_t expected_priority_v4 = 1509957199U;
2474   uint32_t expected_priority_v6 = 1509959759U;
2475   uint32_t expected_priority_ula = 1509962319U;
2476   uint32_t expected_priority_v4mapped = expected_priority_v4;
2477   uint32_t expected_priority_v4compat = 1509949775U;
2478   uint32_t expected_priority_6to4 = 1509954639U;
2479   uint32_t expected_priority_teredo = 1509952079U;
2480   uint32_t expected_priority_sitelocal = 1509949775U;
2481   uint32_t expected_priority_6bone = 1509949775U;
2482   ASSERT_EQ(expected_priority_v4, port->Candidates()[0].priority());
2483   ASSERT_EQ(expected_priority_v6, port->Candidates()[1].priority());
2484   ASSERT_EQ(expected_priority_ula, port->Candidates()[2].priority());
2485   ASSERT_EQ(expected_priority_v4mapped, port->Candidates()[3].priority());
2486   ASSERT_EQ(expected_priority_v4compat, port->Candidates()[4].priority());
2487   ASSERT_EQ(expected_priority_6to4, port->Candidates()[5].priority());
2488   ASSERT_EQ(expected_priority_teredo, port->Candidates()[6].priority());
2489   ASSERT_EQ(expected_priority_sitelocal, port->Candidates()[7].priority());
2490   ASSERT_EQ(expected_priority_6bone, port->Candidates()[8].priority());
2491 }
2492 
2493 // In the case of shared socket, one port may be shared by local and stun.
2494 // Test that candidates with different types will have different foundation.
TEST_F(PortTest,TestFoundation)2495 TEST_F(PortTest, TestFoundation) {
2496   auto testport = CreateTestPort(kLocalAddr1, "name", "pass");
2497   testport->AddCandidateAddress(kLocalAddr1, kLocalAddr1, LOCAL_PORT_TYPE,
2498                                 cricket::ICE_TYPE_PREFERENCE_HOST, false);
2499   testport->AddCandidateAddress(kLocalAddr2, kLocalAddr1, STUN_PORT_TYPE,
2500                                 cricket::ICE_TYPE_PREFERENCE_SRFLX, true);
2501   EXPECT_NE(testport->Candidates()[0].foundation(),
2502             testport->Candidates()[1].foundation());
2503 }
2504 
2505 // This test verifies the foundation of different types of ICE candidates.
TEST_F(PortTest,TestCandidateFoundation)2506 TEST_F(PortTest, TestCandidateFoundation) {
2507   std::unique_ptr<rtc::NATServer> nat_server(
2508       CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2509   auto udpport1 = CreateUdpPort(kLocalAddr1);
2510   udpport1->PrepareAddress();
2511   auto udpport2 = CreateUdpPort(kLocalAddr1);
2512   udpport2->PrepareAddress();
2513   EXPECT_EQ(udpport1->Candidates()[0].foundation(),
2514             udpport2->Candidates()[0].foundation());
2515   auto tcpport1 = CreateTcpPort(kLocalAddr1);
2516   tcpport1->PrepareAddress();
2517   auto tcpport2 = CreateTcpPort(kLocalAddr1);
2518   tcpport2->PrepareAddress();
2519   EXPECT_EQ(tcpport1->Candidates()[0].foundation(),
2520             tcpport2->Candidates()[0].foundation());
2521   auto stunport = CreateStunPort(kLocalAddr1, nat_socket_factory1());
2522   stunport->PrepareAddress();
2523   ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kDefaultTimeout);
2524   EXPECT_NE(tcpport1->Candidates()[0].foundation(),
2525             stunport->Candidates()[0].foundation());
2526   EXPECT_NE(tcpport2->Candidates()[0].foundation(),
2527             stunport->Candidates()[0].foundation());
2528   EXPECT_NE(udpport1->Candidates()[0].foundation(),
2529             stunport->Candidates()[0].foundation());
2530   EXPECT_NE(udpport2->Candidates()[0].foundation(),
2531             stunport->Candidates()[0].foundation());
2532   // Verifying TURN candidate foundation.
2533   auto turnport1 =
2534       CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP);
2535   turnport1->PrepareAddress();
2536   ASSERT_EQ_WAIT(1U, turnport1->Candidates().size(), kDefaultTimeout);
2537   EXPECT_NE(udpport1->Candidates()[0].foundation(),
2538             turnport1->Candidates()[0].foundation());
2539   EXPECT_NE(udpport2->Candidates()[0].foundation(),
2540             turnport1->Candidates()[0].foundation());
2541   EXPECT_NE(stunport->Candidates()[0].foundation(),
2542             turnport1->Candidates()[0].foundation());
2543   auto turnport2 =
2544       CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP);
2545   turnport2->PrepareAddress();
2546   ASSERT_EQ_WAIT(1U, turnport2->Candidates().size(), kDefaultTimeout);
2547   EXPECT_EQ(turnport1->Candidates()[0].foundation(),
2548             turnport2->Candidates()[0].foundation());
2549 
2550   // Running a second turn server, to get different base IP address.
2551   SocketAddress kTurnUdpIntAddr2("99.99.98.4", STUN_SERVER_PORT);
2552   SocketAddress kTurnUdpExtAddr2("99.99.98.5", 0);
2553   TestTurnServer turn_server2(rtc::Thread::Current(), kTurnUdpIntAddr2,
2554                               kTurnUdpExtAddr2);
2555   auto turnport3 = CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP,
2556                                   PROTO_UDP, kTurnUdpIntAddr2);
2557   turnport3->PrepareAddress();
2558   ASSERT_EQ_WAIT(1U, turnport3->Candidates().size(), kDefaultTimeout);
2559   EXPECT_NE(turnport3->Candidates()[0].foundation(),
2560             turnport2->Candidates()[0].foundation());
2561 
2562   // Start a TCP turn server, and check that two turn candidates have
2563   // different foundations if their relay protocols are different.
2564   TestTurnServer turn_server3(rtc::Thread::Current(), kTurnTcpIntAddr,
2565                               kTurnUdpExtAddr, PROTO_TCP);
2566   auto turnport4 =
2567       CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_TCP, PROTO_UDP);
2568   turnport4->PrepareAddress();
2569   ASSERT_EQ_WAIT(1U, turnport4->Candidates().size(), kDefaultTimeout);
2570   EXPECT_NE(turnport2->Candidates()[0].foundation(),
2571             turnport4->Candidates()[0].foundation());
2572 }
2573 
2574 // This test verifies the related addresses of different types of
2575 // ICE candiates.
TEST_F(PortTest,TestCandidateRelatedAddress)2576 TEST_F(PortTest, TestCandidateRelatedAddress) {
2577   auto nat_server = CreateNatServer(kNatAddr1, NAT_OPEN_CONE);
2578   auto udpport = CreateUdpPort(kLocalAddr1);
2579   udpport->PrepareAddress();
2580   // For UDPPort, related address will be empty.
2581   EXPECT_TRUE(udpport->Candidates()[0].related_address().IsNil());
2582   // Testing related address for stun candidates.
2583   // For stun candidate related address must be equal to the base
2584   // socket address.
2585   auto stunport = CreateStunPort(kLocalAddr1, nat_socket_factory1());
2586   stunport->PrepareAddress();
2587   ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kDefaultTimeout);
2588   // Check STUN candidate address.
2589   EXPECT_EQ(stunport->Candidates()[0].address().ipaddr(), kNatAddr1.ipaddr());
2590   // Check STUN candidate related address.
2591   EXPECT_EQ(stunport->Candidates()[0].related_address(),
2592             stunport->GetLocalAddress());
2593   // Verifying the related address for TURN candidate.
2594   // For TURN related address must be equal to the mapped address.
2595   auto turnport =
2596       CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP);
2597   turnport->PrepareAddress();
2598   ASSERT_EQ_WAIT(1U, turnport->Candidates().size(), kDefaultTimeout);
2599   EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
2600             turnport->Candidates()[0].address().ipaddr());
2601   EXPECT_EQ(kNatAddr1.ipaddr(),
2602             turnport->Candidates()[0].related_address().ipaddr());
2603 }
2604 
2605 // Test priority value overflow handling when preference is set to 3.
TEST_F(PortTest,TestCandidatePriority)2606 TEST_F(PortTest, TestCandidatePriority) {
2607   cricket::Candidate cand1;
2608   cand1.set_priority(3);
2609   cricket::Candidate cand2;
2610   cand2.set_priority(1);
2611   EXPECT_TRUE(cand1.priority() > cand2.priority());
2612 }
2613 
2614 // Test the Connection priority is calculated correctly.
TEST_F(PortTest,TestConnectionPriority)2615 TEST_F(PortTest, TestConnectionPriority) {
2616   auto lport = CreateTestPort(kLocalAddr1, "lfrag", "lpass");
2617   lport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_HOST);
2618   auto rport = CreateTestPort(kLocalAddr2, "rfrag", "rpass");
2619   rport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_RELAY_UDP);
2620   lport->set_component(123);
2621   lport->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2622   rport->set_component(23);
2623   rport->AddCandidateAddress(SocketAddress("10.1.1.100", 1234));
2624 
2625   EXPECT_EQ(0x7E001E85U, lport->Candidates()[0].priority());
2626   EXPECT_EQ(0x2001EE9U, rport->Candidates()[0].priority());
2627 
2628   // RFC 5245
2629   // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
2630   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2631   rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2632   Connection* lconn =
2633       lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE);
2634 #if defined(WEBRTC_WIN)
2635   EXPECT_EQ(0x2001EE9FC003D0BU, lconn->priority());
2636 #else
2637   EXPECT_EQ(0x2001EE9FC003D0BLLU, lconn->priority());
2638 #endif
2639 
2640   lport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2641   rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2642   Connection* rconn =
2643       rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE);
2644 #if defined(WEBRTC_WIN)
2645   EXPECT_EQ(0x2001EE9FC003D0AU, rconn->priority());
2646 #else
2647   EXPECT_EQ(0x2001EE9FC003D0ALLU, rconn->priority());
2648 #endif
2649 }
2650 
2651 // Note that UpdateState takes into account the estimated RTT, and the
2652 // correctness of using |kMaxExpectedSimulatedRtt| as an upper bound of RTT in
2653 // the following tests depends on the link rate and the delay distriubtion
2654 // configured in VirtualSocketServer::AddPacketToNetwork. The tests below use
2655 // the default setup where the RTT is deterministically one, which generates an
2656 // estimate given by |MINIMUM_RTT| = 100.
TEST_F(PortTest,TestWritableState)2657 TEST_F(PortTest, TestWritableState) {
2658   rtc::ScopedFakeClock clock;
2659   auto port1 = CreateUdpPort(kLocalAddr1);
2660   port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2661   auto port2 = CreateUdpPort(kLocalAddr2);
2662   port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2663 
2664   // Set up channels.
2665   TestChannel ch1(std::move(port1));
2666   TestChannel ch2(std::move(port2));
2667 
2668   // Acquire addresses.
2669   ch1.Start();
2670   ch2.Start();
2671   ASSERT_EQ_SIMULATED_WAIT(1, ch1.complete_count(), kDefaultTimeout, clock);
2672   ASSERT_EQ_SIMULATED_WAIT(1, ch2.complete_count(), kDefaultTimeout, clock);
2673 
2674   // Send a ping from src to dst.
2675   ch1.CreateConnection(GetCandidate(ch2.port()));
2676   ASSERT_TRUE(ch1.conn() != NULL);
2677   EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2678   // for TCP connect
2679   EXPECT_TRUE_SIMULATED_WAIT(ch1.conn()->connected(), kDefaultTimeout, clock);
2680   ch1.Ping();
2681   SIMULATED_WAIT(!ch2.remote_address().IsNil(), kShortTimeout, clock);
2682 
2683   // Data should be sendable before the connection is accepted.
2684   char data[] = "abcd";
2685   int data_size = arraysize(data);
2686   rtc::PacketOptions options;
2687   EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2688 
2689   // Accept the connection to return the binding response, transition to
2690   // writable, and allow data to be sent.
2691   ch2.AcceptConnection(GetCandidate(ch1.port()));
2692   EXPECT_EQ_SIMULATED_WAIT(Connection::STATE_WRITABLE,
2693                            ch1.conn()->write_state(), kDefaultTimeout, clock);
2694   EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2695 
2696   // Ask the connection to update state as if enough time has passed to lose
2697   // full writability and 5 pings went unresponded to. We'll accomplish the
2698   // latter by sending pings but not pumping messages.
2699   for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
2700     ch1.Ping(i);
2701   }
2702   int unreliable_timeout_delay =
2703       CONNECTION_WRITE_CONNECT_TIMEOUT + kMaxExpectedSimulatedRtt;
2704   ch1.conn()->UpdateState(unreliable_timeout_delay);
2705   EXPECT_EQ(Connection::STATE_WRITE_UNRELIABLE, ch1.conn()->write_state());
2706 
2707   // Data should be able to be sent in this state.
2708   EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2709 
2710   // And now allow the other side to process the pings and send binding
2711   // responses.
2712   EXPECT_EQ_SIMULATED_WAIT(Connection::STATE_WRITABLE,
2713                            ch1.conn()->write_state(), kDefaultTimeout, clock);
2714   // Wait long enough for a full timeout (past however long we've already
2715   // waited).
2716   for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
2717     ch1.Ping(unreliable_timeout_delay + i);
2718   }
2719   ch1.conn()->UpdateState(unreliable_timeout_delay + CONNECTION_WRITE_TIMEOUT +
2720                           kMaxExpectedSimulatedRtt);
2721   EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2722 
2723   // Even if the connection has timed out, the Connection shouldn't block
2724   // the sending of data.
2725   EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2726 
2727   ch1.Stop();
2728   ch2.Stop();
2729 }
2730 
2731 // Test writability states using the configured threshold value to replace
2732 // the default value given by |CONNECTION_WRITE_CONNECT_TIMEOUT| and
2733 // |CONNECTION_WRITE_CONNECT_FAILURES|.
TEST_F(PortTest,TestWritableStateWithConfiguredThreshold)2734 TEST_F(PortTest, TestWritableStateWithConfiguredThreshold) {
2735   rtc::ScopedFakeClock clock;
2736   auto port1 = CreateUdpPort(kLocalAddr1);
2737   port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2738   auto port2 = CreateUdpPort(kLocalAddr2);
2739   port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2740 
2741   // Set up channels.
2742   TestChannel ch1(std::move(port1));
2743   TestChannel ch2(std::move(port2));
2744 
2745   // Acquire addresses.
2746   ch1.Start();
2747   ch2.Start();
2748   ASSERT_EQ_SIMULATED_WAIT(1, ch1.complete_count(), kDefaultTimeout, clock);
2749   ASSERT_EQ_SIMULATED_WAIT(1, ch2.complete_count(), kDefaultTimeout, clock);
2750 
2751   // Send a ping from src to dst.
2752   ch1.CreateConnection(GetCandidate(ch2.port()));
2753   ASSERT_TRUE(ch1.conn() != NULL);
2754   ch1.Ping();
2755   SIMULATED_WAIT(!ch2.remote_address().IsNil(), kShortTimeout, clock);
2756 
2757   // Accept the connection to return the binding response, transition to
2758   // writable, and allow data to be sent.
2759   ch2.AcceptConnection(GetCandidate(ch1.port()));
2760   EXPECT_EQ_SIMULATED_WAIT(Connection::STATE_WRITABLE,
2761                            ch1.conn()->write_state(), kDefaultTimeout, clock);
2762 
2763   ch1.conn()->set_unwritable_timeout(1000);
2764   ch1.conn()->set_unwritable_min_checks(3);
2765   // Send two checks.
2766   ch1.Ping(1);
2767   ch1.Ping(2);
2768   // We have not reached the timeout nor have we sent the minimum number of
2769   // checks to change the state to Unreliable.
2770   ch1.conn()->UpdateState(999);
2771   EXPECT_EQ(Connection::STATE_WRITABLE, ch1.conn()->write_state());
2772   // We have not sent the minimum number of checks without responses.
2773   ch1.conn()->UpdateState(1000 + kMaxExpectedSimulatedRtt);
2774   EXPECT_EQ(Connection::STATE_WRITABLE, ch1.conn()->write_state());
2775   // Last ping after which the candidate pair should become Unreliable after
2776   // timeout.
2777   ch1.Ping(3);
2778   // We have not reached the timeout.
2779   ch1.conn()->UpdateState(999);
2780   EXPECT_EQ(Connection::STATE_WRITABLE, ch1.conn()->write_state());
2781   // We should be in the state Unreliable now.
2782   ch1.conn()->UpdateState(1000 + kMaxExpectedSimulatedRtt);
2783   EXPECT_EQ(Connection::STATE_WRITE_UNRELIABLE, ch1.conn()->write_state());
2784 
2785   ch1.Stop();
2786   ch2.Stop();
2787 }
2788 
TEST_F(PortTest,TestTimeoutForNeverWritable)2789 TEST_F(PortTest, TestTimeoutForNeverWritable) {
2790   auto port1 = CreateUdpPort(kLocalAddr1);
2791   port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2792   auto port2 = CreateUdpPort(kLocalAddr2);
2793   port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2794 
2795   // Set up channels.
2796   TestChannel ch1(std::move(port1));
2797   TestChannel ch2(std::move(port2));
2798 
2799   // Acquire addresses.
2800   ch1.Start();
2801   ch2.Start();
2802 
2803   ch1.CreateConnection(GetCandidate(ch2.port()));
2804   ASSERT_TRUE(ch1.conn() != NULL);
2805   EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2806 
2807   // Attempt to go directly to write timeout.
2808   for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
2809     ch1.Ping(i);
2810   }
2811   ch1.conn()->UpdateState(CONNECTION_WRITE_TIMEOUT + kMaxExpectedSimulatedRtt);
2812   EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2813 }
2814 
2815 // This test verifies the connection setup between ICEMODE_FULL
2816 // and ICEMODE_LITE.
2817 // In this test |ch1| behaves like FULL mode client and we have created
2818 // port which responds to the ping message just like LITE client.
TEST_F(PortTest,TestIceLiteConnectivity)2819 TEST_F(PortTest, TestIceLiteConnectivity) {
2820   auto ice_full_port =
2821       CreateTestPort(kLocalAddr1, "lfrag", "lpass",
2822                      cricket::ICEROLE_CONTROLLING, kTiebreaker1);
2823   auto* ice_full_port_ptr = ice_full_port.get();
2824 
2825   auto ice_lite_port = CreateTestPort(
2826       kLocalAddr2, "rfrag", "rpass", cricket::ICEROLE_CONTROLLED, kTiebreaker2);
2827   // Setup TestChannel. This behaves like FULL mode client.
2828   TestChannel ch1(std::move(ice_full_port));
2829   ch1.SetIceMode(ICEMODE_FULL);
2830 
2831   // Start gathering candidates.
2832   ch1.Start();
2833   ice_lite_port->PrepareAddress();
2834 
2835   ASSERT_EQ_WAIT(1, ch1.complete_count(), kDefaultTimeout);
2836   ASSERT_FALSE(ice_lite_port->Candidates().empty());
2837 
2838   ch1.CreateConnection(GetCandidate(ice_lite_port.get()));
2839   ASSERT_TRUE(ch1.conn() != NULL);
2840   EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2841 
2842   // Send ping from full mode client.
2843   // This ping must not have USE_CANDIDATE_ATTR.
2844   ch1.Ping();
2845 
2846   // Verify stun ping is without USE_CANDIDATE_ATTR. Getting message directly
2847   // from port.
2848   ASSERT_TRUE_WAIT(ice_full_port_ptr->last_stun_msg() != NULL, kDefaultTimeout);
2849   IceMessage* msg = ice_full_port_ptr->last_stun_msg();
2850   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
2851 
2852   // Respond with a BINDING-RESPONSE from litemode client.
2853   // NOTE: Ideally we should't create connection at this stage from lite
2854   // port, as it should be done only after receiving ping with USE_CANDIDATE.
2855   // But we need a connection to send a response message.
2856   auto* con = ice_lite_port->CreateConnection(
2857       ice_full_port_ptr->Candidates()[0], cricket::Port::ORIGIN_MESSAGE);
2858   std::unique_ptr<IceMessage> request = CopyStunMessage(*msg);
2859   con->SendStunBindingResponse(request.get());
2860 
2861   // Feeding the respone message from litemode to the full mode connection.
2862   ch1.conn()->OnReadPacket(ice_lite_port->last_stun_buf()->data<char>(),
2863                            ice_lite_port->last_stun_buf()->size(),
2864                            /* packet_time_us */ -1);
2865   // Verifying full mode connection becomes writable from the response.
2866   EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2867                  kDefaultTimeout);
2868   EXPECT_TRUE_WAIT(ch1.nominated(), kDefaultTimeout);
2869 
2870   // Clear existing stun messsages. Otherwise we will process old stun
2871   // message right after we send ping.
2872   ice_full_port_ptr->Reset();
2873   // Send ping. This must have USE_CANDIDATE_ATTR.
2874   ch1.Ping();
2875   ASSERT_TRUE_WAIT(ice_full_port_ptr->last_stun_msg() != NULL, kDefaultTimeout);
2876   msg = ice_full_port_ptr->last_stun_msg();
2877   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
2878   ch1.Stop();
2879 }
2880 
2881 namespace {
2882 
2883 // Utility function for testing goog ping.
GetSupportedGoogPingVersion(const StunMessage * msg)2884 absl::optional<int> GetSupportedGoogPingVersion(const StunMessage* msg) {
2885   auto goog_misc = msg->GetUInt16List(STUN_ATTR_GOOG_MISC_INFO);
2886   if (goog_misc == nullptr) {
2887     return absl::nullopt;
2888   }
2889 
2890   if (msg->type() == STUN_BINDING_REQUEST) {
2891     if (goog_misc->Size() <
2892         static_cast<int>(cricket::IceGoogMiscInfoBindingRequestAttributeIndex::
2893                              SUPPORT_GOOG_PING_VERSION)) {
2894       return absl::nullopt;
2895     }
2896 
2897     return goog_misc->GetType(
2898         static_cast<int>(cricket::IceGoogMiscInfoBindingRequestAttributeIndex::
2899                              SUPPORT_GOOG_PING_VERSION));
2900   }
2901 
2902   if (msg->type() == STUN_BINDING_RESPONSE) {
2903     if (goog_misc->Size() <
2904         static_cast<int>(cricket::IceGoogMiscInfoBindingResponseAttributeIndex::
2905                              SUPPORT_GOOG_PING_VERSION)) {
2906       return absl::nullopt;
2907     }
2908 
2909     return goog_misc->GetType(
2910         static_cast<int>(cricket::IceGoogMiscInfoBindingResponseAttributeIndex::
2911                              SUPPORT_GOOG_PING_VERSION));
2912   }
2913   return absl::nullopt;
2914 }
2915 
2916 }  // namespace
2917 
2918 class GoogPingTest
2919     : public PortTest,
2920       public ::testing::WithParamInterface<std::pair<bool, bool>> {};
2921 
2922 // This test verifies the announce/enable on/off behavior
TEST_P(GoogPingTest,TestGoogPingAnnounceEnable)2923 TEST_P(GoogPingTest, TestGoogPingAnnounceEnable) {
2924   IceFieldTrials trials;
2925   trials.announce_goog_ping = GetParam().first;
2926   trials.enable_goog_ping = GetParam().second;
2927   RTC_LOG(LS_INFO) << "Testing combination: "
2928                       " announce: "
2929                    << trials.announce_goog_ping
2930                    << " enable:" << trials.enable_goog_ping;
2931 
2932   auto port1_unique =
2933       CreateTestPort(kLocalAddr1, "lfrag", "lpass",
2934                      cricket::ICEROLE_CONTROLLING, kTiebreaker1);
2935   auto* port1 = port1_unique.get();
2936   auto port2 = CreateTestPort(kLocalAddr2, "rfrag", "rpass",
2937                               cricket::ICEROLE_CONTROLLED, kTiebreaker2);
2938 
2939   TestChannel ch1(std::move(port1_unique));
2940   // Block usage of STUN_ATTR_USE_CANDIDATE so that
2941   // ch1.conn() will sent GOOG_PING_REQUEST directly.
2942   // This only makes test a bit shorter...
2943   ch1.SetIceMode(ICEMODE_LITE);
2944   // Start gathering candidates.
2945   ch1.Start();
2946   port2->PrepareAddress();
2947 
2948   ASSERT_EQ_WAIT(1, ch1.complete_count(), kDefaultTimeout);
2949   ASSERT_FALSE(port2->Candidates().empty());
2950 
2951   ch1.CreateConnection(GetCandidate(port2.get()));
2952   ASSERT_TRUE(ch1.conn() != NULL);
2953   EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2954   ch1.conn()->SetIceFieldTrials(&trials);
2955 
2956   // Send ping.
2957   ch1.Ping();
2958 
2959   ASSERT_TRUE_WAIT(port1->last_stun_msg() != NULL, kDefaultTimeout);
2960   const IceMessage* request1 = port1->last_stun_msg();
2961 
2962   ASSERT_EQ(trials.enable_goog_ping,
2963             GetSupportedGoogPingVersion(request1) &&
2964                 GetSupportedGoogPingVersion(request1) >= kGoogPingVersion);
2965 
2966   auto* con = port2->CreateConnection(port1->Candidates()[0],
2967                                       cricket::Port::ORIGIN_MESSAGE);
2968   con->SetIceFieldTrials(&trials);
2969 
2970   con->SendStunBindingResponse(request1);
2971 
2972   // Then check the response matches the settings.
2973   const auto* response = port2->last_stun_msg();
2974   EXPECT_EQ(response->type(), STUN_BINDING_RESPONSE);
2975   EXPECT_EQ(trials.enable_goog_ping && trials.announce_goog_ping,
2976             GetSupportedGoogPingVersion(response) &&
2977                 GetSupportedGoogPingVersion(response) >= kGoogPingVersion);
2978 
2979   // Feeding the respone message back.
2980   ch1.conn()->OnReadPacket(port2->last_stun_buf()->data<char>(),
2981                            port2->last_stun_buf()->size(),
2982                            /* packet_time_us */ -1);
2983 
2984   port1->Reset();
2985   port2->Reset();
2986 
2987   ch1.Ping();
2988   ASSERT_TRUE_WAIT(port1->last_stun_msg() != NULL, kDefaultTimeout);
2989   const IceMessage* request2 = port1->last_stun_msg();
2990 
2991   // It should be a GOOG_PING if both of these are TRUE
2992   if (trials.announce_goog_ping && trials.enable_goog_ping) {
2993     ASSERT_EQ(request2->type(), GOOG_PING_REQUEST);
2994     con->SendGoogPingResponse(request2);
2995   } else {
2996     ASSERT_EQ(request2->type(), STUN_BINDING_REQUEST);
2997     // If we sent a BINDING with enable, and we got a reply that
2998     // didn't contain announce, the next ping should not contain
2999     // the enable again.
3000     ASSERT_FALSE(GetSupportedGoogPingVersion(request2).has_value());
3001     con->SendStunBindingResponse(request2);
3002   }
3003 
3004   const auto* response2 = port2->last_stun_msg();
3005   ASSERT_TRUE(response2 != nullptr);
3006 
3007   // It should be a GOOG_PING_RESPONSE if both of these are TRUE
3008   if (trials.announce_goog_ping && trials.enable_goog_ping) {
3009     ASSERT_EQ(response2->type(), GOOG_PING_RESPONSE);
3010   } else {
3011     ASSERT_EQ(response2->type(), STUN_BINDING_RESPONSE);
3012   }
3013 
3014   ch1.Stop();
3015 }
3016 
3017 // This test if a someone send a STUN_BINDING with unsupported version
3018 // (kGoogPingVersion == 0)
TEST_F(PortTest,TestGoogPingUnsupportedVersionInStunBinding)3019 TEST_F(PortTest, TestGoogPingUnsupportedVersionInStunBinding) {
3020   IceFieldTrials trials;
3021   trials.announce_goog_ping = true;
3022   trials.enable_goog_ping = true;
3023 
3024   auto port1_unique =
3025       CreateTestPort(kLocalAddr1, "lfrag", "lpass",
3026                      cricket::ICEROLE_CONTROLLING, kTiebreaker1);
3027   auto* port1 = port1_unique.get();
3028   auto port2 = CreateTestPort(kLocalAddr2, "rfrag", "rpass",
3029                               cricket::ICEROLE_CONTROLLED, kTiebreaker2);
3030 
3031   TestChannel ch1(std::move(port1_unique));
3032   // Block usage of STUN_ATTR_USE_CANDIDATE so that
3033   // ch1.conn() will sent GOOG_PING_REQUEST directly.
3034   // This only makes test a bit shorter...
3035   ch1.SetIceMode(ICEMODE_LITE);
3036   // Start gathering candidates.
3037   ch1.Start();
3038   port2->PrepareAddress();
3039 
3040   ASSERT_EQ_WAIT(1, ch1.complete_count(), kDefaultTimeout);
3041   ASSERT_FALSE(port2->Candidates().empty());
3042 
3043   ch1.CreateConnection(GetCandidate(port2.get()));
3044   ASSERT_TRUE(ch1.conn() != NULL);
3045   EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
3046   ch1.conn()->SetIceFieldTrials(&trials);
3047 
3048   // Send ping.
3049   ch1.Ping();
3050 
3051   ASSERT_TRUE_WAIT(port1->last_stun_msg() != NULL, kDefaultTimeout);
3052   const IceMessage* request1 = port1->last_stun_msg();
3053 
3054   ASSERT_TRUE(GetSupportedGoogPingVersion(request1) &&
3055               GetSupportedGoogPingVersion(request1) >= kGoogPingVersion);
3056 
3057   // Modify the STUN message request1 to send GetSupportedGoogPingVersion == 0
3058   auto modified_request1 = request1->Clone();
3059   ASSERT_TRUE(modified_request1->RemoveAttribute(STUN_ATTR_GOOG_MISC_INFO) !=
3060               nullptr);
3061   ASSERT_TRUE(modified_request1->RemoveAttribute(STUN_ATTR_MESSAGE_INTEGRITY) !=
3062               nullptr);
3063   {
3064     auto list =
3065         StunAttribute::CreateUInt16ListAttribute(STUN_ATTR_GOOG_MISC_INFO);
3066     list->AddTypeAtIndex(
3067         static_cast<uint16_t>(
3068             cricket::IceGoogMiscInfoBindingRequestAttributeIndex::
3069                 SUPPORT_GOOG_PING_VERSION),
3070         /* version */ 0);
3071     modified_request1->AddAttribute(std::move(list));
3072     modified_request1->AddMessageIntegrity("rpass");
3073   }
3074   auto* con = port2->CreateConnection(port1->Candidates()[0],
3075                                       cricket::Port::ORIGIN_MESSAGE);
3076   con->SetIceFieldTrials(&trials);
3077 
3078   con->SendStunBindingResponse(modified_request1.get());
3079 
3080   // Then check the response matches the settings.
3081   const auto* response = port2->last_stun_msg();
3082   EXPECT_EQ(response->type(), STUN_BINDING_RESPONSE);
3083   EXPECT_FALSE(GetSupportedGoogPingVersion(response));
3084 
3085   ch1.Stop();
3086 }
3087 
3088 // This test if a someone send a STUN_BINDING_RESPONSE with unsupported version
3089 // (kGoogPingVersion == 0)
TEST_F(PortTest,TestGoogPingUnsupportedVersionInStunBindingResponse)3090 TEST_F(PortTest, TestGoogPingUnsupportedVersionInStunBindingResponse) {
3091   IceFieldTrials trials;
3092   trials.announce_goog_ping = true;
3093   trials.enable_goog_ping = true;
3094 
3095   auto port1_unique =
3096       CreateTestPort(kLocalAddr1, "lfrag", "lpass",
3097                      cricket::ICEROLE_CONTROLLING, kTiebreaker1);
3098   auto* port1 = port1_unique.get();
3099   auto port2 = CreateTestPort(kLocalAddr2, "rfrag", "rpass",
3100                               cricket::ICEROLE_CONTROLLED, kTiebreaker2);
3101 
3102   TestChannel ch1(std::move(port1_unique));
3103   // Block usage of STUN_ATTR_USE_CANDIDATE so that
3104   // ch1.conn() will sent GOOG_PING_REQUEST directly.
3105   // This only makes test a bit shorter...
3106   ch1.SetIceMode(ICEMODE_LITE);
3107   // Start gathering candidates.
3108   ch1.Start();
3109   port2->PrepareAddress();
3110 
3111   ASSERT_EQ_WAIT(1, ch1.complete_count(), kDefaultTimeout);
3112   ASSERT_FALSE(port2->Candidates().empty());
3113 
3114   ch1.CreateConnection(GetCandidate(port2.get()));
3115   ASSERT_TRUE(ch1.conn() != NULL);
3116   EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
3117   ch1.conn()->SetIceFieldTrials(&trials);
3118 
3119   // Send ping.
3120   ch1.Ping();
3121 
3122   ASSERT_TRUE_WAIT(port1->last_stun_msg() != NULL, kDefaultTimeout);
3123   const IceMessage* request1 = port1->last_stun_msg();
3124 
3125   ASSERT_TRUE(GetSupportedGoogPingVersion(request1) &&
3126               GetSupportedGoogPingVersion(request1) >= kGoogPingVersion);
3127 
3128   auto* con = port2->CreateConnection(port1->Candidates()[0],
3129                                       cricket::Port::ORIGIN_MESSAGE);
3130   con->SetIceFieldTrials(&trials);
3131 
3132   con->SendStunBindingResponse(request1);
3133 
3134   // Then check the response matches the settings.
3135   const auto* response = port2->last_stun_msg();
3136   EXPECT_EQ(response->type(), STUN_BINDING_RESPONSE);
3137   EXPECT_TRUE(GetSupportedGoogPingVersion(response));
3138 
3139   // Modify the STUN message response to contain GetSupportedGoogPingVersion ==
3140   // 0
3141   auto modified_response = response->Clone();
3142   ASSERT_TRUE(modified_response->RemoveAttribute(STUN_ATTR_GOOG_MISC_INFO) !=
3143               nullptr);
3144   ASSERT_TRUE(modified_response->RemoveAttribute(STUN_ATTR_MESSAGE_INTEGRITY) !=
3145               nullptr);
3146   ASSERT_TRUE(modified_response->RemoveAttribute(STUN_ATTR_FINGERPRINT) !=
3147               nullptr);
3148   {
3149     auto list =
3150         StunAttribute::CreateUInt16ListAttribute(STUN_ATTR_GOOG_MISC_INFO);
3151     list->AddTypeAtIndex(
3152         static_cast<uint16_t>(
3153             cricket::IceGoogMiscInfoBindingResponseAttributeIndex::
3154                 SUPPORT_GOOG_PING_VERSION),
3155         /* version */ 0);
3156     modified_response->AddAttribute(std::move(list));
3157     modified_response->AddMessageIntegrity("rpass");
3158     modified_response->AddFingerprint();
3159   }
3160 
3161   rtc::ByteBufferWriter buf;
3162   modified_response->Write(&buf);
3163 
3164   // Feeding the modified respone message back.
3165   ch1.conn()->OnReadPacket(buf.Data(), buf.Length(), /* packet_time_us */ -1);
3166 
3167   port1->Reset();
3168   port2->Reset();
3169 
3170   ch1.Ping();
3171   ASSERT_TRUE_WAIT(port1->last_stun_msg() != NULL, kDefaultTimeout);
3172 
3173   // This should now be a STUN_BINDING...without a kGoogPingVersion
3174   const IceMessage* request2 = port1->last_stun_msg();
3175   EXPECT_EQ(request2->type(), STUN_BINDING_REQUEST);
3176   EXPECT_FALSE(GetSupportedGoogPingVersion(request2));
3177 
3178   ch1.Stop();
3179 }
3180 
3181 INSTANTIATE_TEST_SUITE_P(GoogPingTest,
3182                          GoogPingTest,
3183                          // test all combinations of <announce, enable> pairs.
3184                          ::testing::Values(std::make_pair(false, false),
3185                                            std::make_pair(true, false),
3186                                            std::make_pair(false, true),
3187                                            std::make_pair(true, true)));
3188 
3189 // This test checks that a change in attributes falls back to STUN_BINDING
TEST_F(PortTest,TestChangeInAttributeMakesGoogPingFallsbackToStunBinding)3190 TEST_F(PortTest, TestChangeInAttributeMakesGoogPingFallsbackToStunBinding) {
3191   IceFieldTrials trials;
3192   trials.announce_goog_ping = true;
3193   trials.enable_goog_ping = true;
3194 
3195   auto port1_unique =
3196       CreateTestPort(kLocalAddr1, "lfrag", "lpass",
3197                      cricket::ICEROLE_CONTROLLING, kTiebreaker1);
3198   auto* port1 = port1_unique.get();
3199   auto port2 = CreateTestPort(kLocalAddr2, "rfrag", "rpass",
3200                               cricket::ICEROLE_CONTROLLED, kTiebreaker2);
3201 
3202   TestChannel ch1(std::move(port1_unique));
3203   // Block usage of STUN_ATTR_USE_CANDIDATE so that
3204   // ch1.conn() will sent GOOG_PING_REQUEST directly.
3205   // This only makes test a bit shorter...
3206   ch1.SetIceMode(ICEMODE_LITE);
3207   // Start gathering candidates.
3208   ch1.Start();
3209   port2->PrepareAddress();
3210 
3211   ASSERT_EQ_WAIT(1, ch1.complete_count(), kDefaultTimeout);
3212   ASSERT_FALSE(port2->Candidates().empty());
3213 
3214   ch1.CreateConnection(GetCandidate(port2.get()));
3215   ASSERT_TRUE(ch1.conn() != nullptr);
3216   EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
3217   ch1.conn()->SetIceFieldTrials(&trials);
3218 
3219   // Send ping.
3220   ch1.Ping();
3221 
3222   ASSERT_TRUE_WAIT(port1->last_stun_msg() != NULL, kDefaultTimeout);
3223   const IceMessage* msg = port1->last_stun_msg();
3224   auto* con = port2->CreateConnection(port1->Candidates()[0],
3225                                       cricket::Port::ORIGIN_MESSAGE);
3226   con->SetIceFieldTrials(&trials);
3227 
3228   // Feed the message into the connection.
3229   con->SendStunBindingResponse(msg);
3230 
3231   // The check reply wrt to settings.
3232   const auto* response = port2->last_stun_msg();
3233   ASSERT_EQ(response->type(), STUN_BINDING_RESPONSE);
3234   ASSERT_TRUE(GetSupportedGoogPingVersion(response) >= kGoogPingVersion);
3235 
3236   // Feeding the respone message back.
3237   ch1.conn()->OnReadPacket(port2->last_stun_buf()->data<char>(),
3238                            port2->last_stun_buf()->size(),
3239                            /* packet_time_us */ -1);
3240 
3241   port1->Reset();
3242   port2->Reset();
3243 
3244   ch1.Ping();
3245   ASSERT_TRUE_WAIT(port1->last_stun_msg() != NULL, kDefaultTimeout);
3246   const IceMessage* msg2 = port1->last_stun_msg();
3247 
3248   // It should be a GOOG_PING if both of these are TRUE
3249   ASSERT_EQ(msg2->type(), GOOG_PING_REQUEST);
3250   con->SendGoogPingResponse(msg2);
3251 
3252   const auto* response2 = port2->last_stun_msg();
3253   ASSERT_TRUE(response2 != nullptr);
3254 
3255   // It should be a GOOG_PING_RESPONSE.
3256   ASSERT_EQ(response2->type(), GOOG_PING_RESPONSE);
3257 
3258   // And now the third ping.
3259   port1->Reset();
3260   port2->Reset();
3261 
3262   // Modify the message to be sent.
3263   ch1.conn()->set_use_candidate_attr(!ch1.conn()->use_candidate_attr());
3264 
3265   ch1.Ping();
3266   ASSERT_TRUE_WAIT(port1->last_stun_msg() != NULL, kDefaultTimeout);
3267   const IceMessage* msg3 = port1->last_stun_msg();
3268 
3269   // It should be a STUN_BINDING_REQUEST
3270   ASSERT_EQ(msg3->type(), STUN_BINDING_REQUEST);
3271 
3272   ch1.Stop();
3273 }
3274 
3275 // This test that an error response fall back to STUN_BINDING.
TEST_F(PortTest,TestErrorResponseMakesGoogPingFallBackToStunBinding)3276 TEST_F(PortTest, TestErrorResponseMakesGoogPingFallBackToStunBinding) {
3277   IceFieldTrials trials;
3278   trials.announce_goog_ping = true;
3279   trials.enable_goog_ping = true;
3280 
3281   auto port1_unique =
3282       CreateTestPort(kLocalAddr1, "lfrag", "lpass",
3283                      cricket::ICEROLE_CONTROLLING, kTiebreaker1);
3284   auto* port1 = port1_unique.get();
3285   auto port2 = CreateTestPort(kLocalAddr2, "rfrag", "rpass",
3286                               cricket::ICEROLE_CONTROLLED, kTiebreaker2);
3287 
3288   TestChannel ch1(std::move(port1_unique));
3289   // Block usage of STUN_ATTR_USE_CANDIDATE so that
3290   // ch1.conn() will sent GOOG_PING_REQUEST directly.
3291   // This only makes test a bit shorter...
3292   ch1.SetIceMode(ICEMODE_LITE);
3293   // Start gathering candidates.
3294   ch1.Start();
3295   port2->PrepareAddress();
3296 
3297   ASSERT_EQ_WAIT(1, ch1.complete_count(), kDefaultTimeout);
3298   ASSERT_FALSE(port2->Candidates().empty());
3299 
3300   ch1.CreateConnection(GetCandidate(port2.get()));
3301   ASSERT_TRUE(ch1.conn() != NULL);
3302   EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
3303   ch1.conn()->SetIceFieldTrials(&trials);
3304 
3305   // Send ping.
3306   ch1.Ping();
3307 
3308   ASSERT_TRUE_WAIT(port1->last_stun_msg() != NULL, kDefaultTimeout);
3309   const IceMessage* msg = port1->last_stun_msg();
3310   auto* con = port2->CreateConnection(port1->Candidates()[0],
3311                                       cricket::Port::ORIGIN_MESSAGE);
3312   con->SetIceFieldTrials(&trials);
3313 
3314   // Feed the message into the connection.
3315   con->SendStunBindingResponse(msg);
3316 
3317   // The check reply wrt to settings.
3318   const auto* response = port2->last_stun_msg();
3319   ASSERT_EQ(response->type(), STUN_BINDING_RESPONSE);
3320   ASSERT_TRUE(GetSupportedGoogPingVersion(response) >= kGoogPingVersion);
3321 
3322   // Feeding the respone message back.
3323   ch1.conn()->OnReadPacket(port2->last_stun_buf()->data<char>(),
3324                            port2->last_stun_buf()->size(),
3325                            /* packet_time_us */ -1);
3326 
3327   port1->Reset();
3328   port2->Reset();
3329 
3330   ch1.Ping();
3331   ASSERT_TRUE_WAIT(port1->last_stun_msg() != NULL, kDefaultTimeout);
3332   const IceMessage* msg2 = port1->last_stun_msg();
3333 
3334   // It should be a GOOG_PING.
3335   ASSERT_EQ(msg2->type(), GOOG_PING_REQUEST);
3336   con->SendGoogPingResponse(msg2);
3337 
3338   const auto* response2 = port2->last_stun_msg();
3339   ASSERT_TRUE(response2 != nullptr);
3340 
3341   // It should be a GOOG_PING_RESPONSE.
3342   ASSERT_EQ(response2->type(), GOOG_PING_RESPONSE);
3343 
3344   // But rather than the RESPONSE...feedback an error.
3345   StunMessage error_response;
3346   error_response.SetType(GOOG_PING_ERROR_RESPONSE);
3347   error_response.SetTransactionID(response2->transaction_id());
3348   error_response.AddMessageIntegrity32("rpass");
3349   rtc::ByteBufferWriter buf;
3350   error_response.Write(&buf);
3351 
3352   ch1.conn()->OnReadPacket(buf.Data(), buf.Length(),
3353                            /* packet_time_us */ -1);
3354 
3355   // And now the third ping...this should be a binding.
3356   port1->Reset();
3357   port2->Reset();
3358 
3359   ch1.Ping();
3360   ASSERT_TRUE_WAIT(port1->last_stun_msg() != NULL, kDefaultTimeout);
3361   const IceMessage* msg3 = port1->last_stun_msg();
3362 
3363   // It should be a STUN_BINDING_REQUEST
3364   ASSERT_EQ(msg3->type(), STUN_BINDING_REQUEST);
3365 
3366   ch1.Stop();
3367 }
3368 
3369 // This test case verifies that both the controlling port and the controlled
3370 // port will time out after connectivity is lost, if they are not marked as
3371 // "keep alive until pruned."
TEST_F(PortTest,TestPortTimeoutIfNotKeptAlive)3372 TEST_F(PortTest, TestPortTimeoutIfNotKeptAlive) {
3373   rtc::ScopedFakeClock clock;
3374   int timeout_delay = 100;
3375   auto port1 = CreateUdpPort(kLocalAddr1);
3376   ConnectToSignalDestroyed(port1.get());
3377   port1->set_timeout_delay(timeout_delay);  // milliseconds
3378   port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
3379   port1->SetIceTiebreaker(kTiebreaker1);
3380 
3381   auto port2 = CreateUdpPort(kLocalAddr2);
3382   ConnectToSignalDestroyed(port2.get());
3383   port2->set_timeout_delay(timeout_delay);  // milliseconds
3384   port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
3385   port2->SetIceTiebreaker(kTiebreaker2);
3386 
3387   // Set up channels and ensure both ports will be deleted.
3388   TestChannel ch1(std::move(port1));
3389   TestChannel ch2(std::move(port2));
3390 
3391   // Simulate a connection that succeeds, and then is destroyed.
3392   StartConnectAndStopChannels(&ch1, &ch2);
3393   // After the connection is destroyed, the port will be destroyed because
3394   // none of them is marked as "keep alive until pruned.
3395   EXPECT_EQ_SIMULATED_WAIT(2, ports_destroyed(), 110, clock);
3396 }
3397 
3398 // Test that if after all connection are destroyed, new connections are created
3399 // and destroyed again, ports won't be destroyed until a timeout period passes
3400 // after the last set of connections are all destroyed.
TEST_F(PortTest,TestPortTimeoutAfterNewConnectionCreatedAndDestroyed)3401 TEST_F(PortTest, TestPortTimeoutAfterNewConnectionCreatedAndDestroyed) {
3402   rtc::ScopedFakeClock clock;
3403   int timeout_delay = 100;
3404   auto port1 = CreateUdpPort(kLocalAddr1);
3405   ConnectToSignalDestroyed(port1.get());
3406   port1->set_timeout_delay(timeout_delay);  // milliseconds
3407   port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
3408   port1->SetIceTiebreaker(kTiebreaker1);
3409 
3410   auto port2 = CreateUdpPort(kLocalAddr2);
3411   ConnectToSignalDestroyed(port2.get());
3412   port2->set_timeout_delay(timeout_delay);  // milliseconds
3413 
3414   port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
3415   port2->SetIceTiebreaker(kTiebreaker2);
3416 
3417   // Set up channels and ensure both ports will be deleted.
3418   TestChannel ch1(std::move(port1));
3419   TestChannel ch2(std::move(port2));
3420 
3421   // Simulate a connection that succeeds, and then is destroyed.
3422   StartConnectAndStopChannels(&ch1, &ch2);
3423   SIMULATED_WAIT(ports_destroyed() > 0, 80, clock);
3424   EXPECT_EQ(0, ports_destroyed());
3425 
3426   // Start the second set of connection and destroy them.
3427   ch1.CreateConnection(GetCandidate(ch2.port()));
3428   ch2.CreateConnection(GetCandidate(ch1.port()));
3429   ch1.Stop();
3430   ch2.Stop();
3431 
3432   SIMULATED_WAIT(ports_destroyed() > 0, 80, clock);
3433   EXPECT_EQ(0, ports_destroyed());
3434 
3435   // The ports on both sides should be destroyed after timeout.
3436   EXPECT_TRUE_SIMULATED_WAIT(ports_destroyed() == 2, 30, clock);
3437 }
3438 
3439 // This test case verifies that neither the controlling port nor the controlled
3440 // port will time out after connectivity is lost if they are marked as "keep
3441 // alive until pruned". They will time out after they are pruned.
TEST_F(PortTest,TestPortNotTimeoutUntilPruned)3442 TEST_F(PortTest, TestPortNotTimeoutUntilPruned) {
3443   rtc::ScopedFakeClock clock;
3444   int timeout_delay = 100;
3445   auto port1 = CreateUdpPort(kLocalAddr1);
3446   ConnectToSignalDestroyed(port1.get());
3447   port1->set_timeout_delay(timeout_delay);  // milliseconds
3448   port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
3449   port1->SetIceTiebreaker(kTiebreaker1);
3450 
3451   auto port2 = CreateUdpPort(kLocalAddr2);
3452   ConnectToSignalDestroyed(port2.get());
3453   port2->set_timeout_delay(timeout_delay);  // milliseconds
3454   port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
3455   port2->SetIceTiebreaker(kTiebreaker2);
3456   // The connection must not be destroyed before a connection is attempted.
3457   EXPECT_EQ(0, ports_destroyed());
3458 
3459   port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
3460   port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
3461 
3462   // Set up channels and keep the port alive.
3463   TestChannel ch1(std::move(port1));
3464   TestChannel ch2(std::move(port2));
3465   // Simulate a connection that succeeds, and then is destroyed. But ports
3466   // are kept alive. Ports won't be destroyed.
3467   StartConnectAndStopChannels(&ch1, &ch2);
3468   ch1.port()->KeepAliveUntilPruned();
3469   ch2.port()->KeepAliveUntilPruned();
3470   SIMULATED_WAIT(ports_destroyed() > 0, 150, clock);
3471   EXPECT_EQ(0, ports_destroyed());
3472 
3473   // If they are pruned now, they will be destroyed right away.
3474   ch1.port()->Prune();
3475   ch2.port()->Prune();
3476   // The ports on both sides should be destroyed after timeout.
3477   EXPECT_TRUE_SIMULATED_WAIT(ports_destroyed() == 2, 1, clock);
3478 }
3479 
TEST_F(PortTest,TestSupportsProtocol)3480 TEST_F(PortTest, TestSupportsProtocol) {
3481   auto udp_port = CreateUdpPort(kLocalAddr1);
3482   EXPECT_TRUE(udp_port->SupportsProtocol(UDP_PROTOCOL_NAME));
3483   EXPECT_FALSE(udp_port->SupportsProtocol(TCP_PROTOCOL_NAME));
3484 
3485   auto stun_port = CreateStunPort(kLocalAddr1, nat_socket_factory1());
3486   EXPECT_TRUE(stun_port->SupportsProtocol(UDP_PROTOCOL_NAME));
3487   EXPECT_FALSE(stun_port->SupportsProtocol(TCP_PROTOCOL_NAME));
3488 
3489   auto tcp_port = CreateTcpPort(kLocalAddr1);
3490   EXPECT_TRUE(tcp_port->SupportsProtocol(TCP_PROTOCOL_NAME));
3491   EXPECT_TRUE(tcp_port->SupportsProtocol(SSLTCP_PROTOCOL_NAME));
3492   EXPECT_FALSE(tcp_port->SupportsProtocol(UDP_PROTOCOL_NAME));
3493 
3494   auto turn_port =
3495       CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP);
3496   EXPECT_TRUE(turn_port->SupportsProtocol(UDP_PROTOCOL_NAME));
3497   EXPECT_FALSE(turn_port->SupportsProtocol(TCP_PROTOCOL_NAME));
3498 }
3499 
3500 // Test that SetIceParameters updates the component, ufrag and password
3501 // on both the port itself and its candidates.
TEST_F(PortTest,TestSetIceParameters)3502 TEST_F(PortTest, TestSetIceParameters) {
3503   auto port = CreateTestPort(kLocalAddr1, "ufrag1", "password1");
3504   port->PrepareAddress();
3505   EXPECT_EQ(1UL, port->Candidates().size());
3506   port->SetIceParameters(1, "ufrag2", "password2");
3507   EXPECT_EQ(1, port->component());
3508   EXPECT_EQ("ufrag2", port->username_fragment());
3509   EXPECT_EQ("password2", port->password());
3510   const Candidate& candidate = port->Candidates()[0];
3511   EXPECT_EQ(1, candidate.component());
3512   EXPECT_EQ("ufrag2", candidate.username());
3513   EXPECT_EQ("password2", candidate.password());
3514 }
3515 
TEST_F(PortTest,TestAddConnectionWithSameAddress)3516 TEST_F(PortTest, TestAddConnectionWithSameAddress) {
3517   auto port = CreateTestPort(kLocalAddr1, "ufrag1", "password1");
3518   port->PrepareAddress();
3519   EXPECT_EQ(1u, port->Candidates().size());
3520   rtc::SocketAddress address("1.1.1.1", 5000);
3521   cricket::Candidate candidate(1, "udp", address, 0, "", "", "relay", 0, "");
3522   cricket::Connection* conn1 =
3523       port->CreateConnection(candidate, Port::ORIGIN_MESSAGE);
3524   cricket::Connection* conn_in_use = port->GetConnection(address);
3525   EXPECT_EQ(conn1, conn_in_use);
3526   EXPECT_EQ(0u, conn_in_use->remote_candidate().generation());
3527 
3528   // Creating with a candidate with the same address again will get us a
3529   // different connection with the new candidate.
3530   candidate.set_generation(2);
3531   cricket::Connection* conn2 =
3532       port->CreateConnection(candidate, Port::ORIGIN_MESSAGE);
3533   EXPECT_NE(conn1, conn2);
3534   conn_in_use = port->GetConnection(address);
3535   EXPECT_EQ(conn2, conn_in_use);
3536   EXPECT_EQ(2u, conn_in_use->remote_candidate().generation());
3537 
3538   // Make sure the new connection was not deleted.
3539   rtc::Thread::Current()->ProcessMessages(300);
3540   EXPECT_TRUE(port->GetConnection(address) != nullptr);
3541 }
3542 
3543 // TODO(webrtc:11463) : Move Connection tests into separate unit test
3544 // splitting out shared test code as needed.
3545 
3546 class ConnectionTest : public PortTest {
3547  public:
ConnectionTest()3548   ConnectionTest() {
3549     lport_ = CreateTestPort(kLocalAddr1, "lfrag", "lpass");
3550     rport_ = CreateTestPort(kLocalAddr2, "rfrag", "rpass");
3551     lport_->SetIceRole(cricket::ICEROLE_CONTROLLING);
3552     lport_->SetIceTiebreaker(kTiebreaker1);
3553     rport_->SetIceRole(cricket::ICEROLE_CONTROLLED);
3554     rport_->SetIceTiebreaker(kTiebreaker2);
3555 
3556     lport_->PrepareAddress();
3557     rport_->PrepareAddress();
3558   }
3559 
3560   rtc::ScopedFakeClock clock_;
3561   int num_state_changes_ = 0;
3562 
CreateConnection(IceRole role)3563   Connection* CreateConnection(IceRole role) {
3564     Connection* conn;
3565     if (role == cricket::ICEROLE_CONTROLLING) {
3566       conn = lport_->CreateConnection(rport_->Candidates()[0],
3567                                       Port::ORIGIN_MESSAGE);
3568     } else {
3569       conn = rport_->CreateConnection(lport_->Candidates()[0],
3570                                       Port::ORIGIN_MESSAGE);
3571     }
3572     conn->SignalStateChange.connect(this,
3573                                     &ConnectionTest::OnConnectionStateChange);
3574     return conn;
3575   }
3576 
SendPingAndCaptureReply(Connection * lconn,Connection * rconn,int64_t ms,rtc::BufferT<uint8_t> * reply)3577   void SendPingAndCaptureReply(Connection* lconn,
3578                                Connection* rconn,
3579                                int64_t ms,
3580                                rtc::BufferT<uint8_t>* reply) {
3581     TestPort* lport =
3582         lconn->PortForTest() == lport_.get() ? lport_.get() : rport_.get();
3583     TestPort* rport =
3584         rconn->PortForTest() == rport_.get() ? rport_.get() : lport_.get();
3585     lconn->Ping(rtc::TimeMillis());
3586     ASSERT_TRUE_WAIT(lport->last_stun_msg(), kDefaultTimeout);
3587     ASSERT_TRUE(lport->last_stun_buf());
3588     rconn->OnReadPacket(lport->last_stun_buf()->data<char>(),
3589                         lport->last_stun_buf()->size(),
3590                         /* packet_time_us */ -1);
3591     clock_.AdvanceTime(webrtc::TimeDelta::Millis(ms));
3592     ASSERT_TRUE_WAIT(rport->last_stun_msg(), kDefaultTimeout);
3593     ASSERT_TRUE(rport->last_stun_buf());
3594     *reply = std::move(*rport->last_stun_buf());
3595   }
3596 
SendPingAndReceiveResponse(Connection * lconn,Connection * rconn,int64_t ms)3597   void SendPingAndReceiveResponse(Connection* lconn,
3598                                   Connection* rconn,
3599                                   int64_t ms) {
3600     rtc::BufferT<uint8_t> reply;
3601     SendPingAndCaptureReply(lconn, rconn, ms, &reply);
3602     lconn->OnReadPacket(reply.data<char>(), reply.size(),
3603                         /* packet_time_us */ -1);
3604   }
3605 
OnConnectionStateChange(Connection * connection)3606   void OnConnectionStateChange(Connection* connection) { num_state_changes_++; }
3607 
3608  private:
3609   std::unique_ptr<TestPort> lport_;
3610   std::unique_ptr<TestPort> rport_;
3611 };
3612 
TEST_F(ConnectionTest,ConnectionForgetLearnedState)3613 TEST_F(ConnectionTest, ConnectionForgetLearnedState) {
3614   Connection* lconn = CreateConnection(ICEROLE_CONTROLLING);
3615   Connection* rconn = CreateConnection(ICEROLE_CONTROLLED);
3616 
3617   EXPECT_FALSE(lconn->writable());
3618   EXPECT_FALSE(lconn->receiving());
3619   EXPECT_TRUE(std::isnan(lconn->GetRttEstimate().GetAverage()));
3620   EXPECT_EQ(lconn->GetRttEstimate().GetVariance(),
3621             std::numeric_limits<double>::infinity());
3622 
3623   SendPingAndReceiveResponse(lconn, rconn, 10);
3624 
3625   EXPECT_TRUE(lconn->writable());
3626   EXPECT_TRUE(lconn->receiving());
3627   EXPECT_EQ(lconn->GetRttEstimate().GetAverage(), 10);
3628   EXPECT_EQ(lconn->GetRttEstimate().GetVariance(),
3629             std::numeric_limits<double>::infinity());
3630 
3631   SendPingAndReceiveResponse(lconn, rconn, 11);
3632 
3633   EXPECT_TRUE(lconn->writable());
3634   EXPECT_TRUE(lconn->receiving());
3635   EXPECT_NEAR(lconn->GetRttEstimate().GetAverage(), 10, 0.5);
3636   EXPECT_LT(lconn->GetRttEstimate().GetVariance(),
3637             std::numeric_limits<double>::infinity());
3638 
3639   lconn->ForgetLearnedState();
3640 
3641   EXPECT_FALSE(lconn->writable());
3642   EXPECT_FALSE(lconn->receiving());
3643   EXPECT_TRUE(std::isnan(lconn->GetRttEstimate().GetAverage()));
3644   EXPECT_EQ(lconn->GetRttEstimate().GetVariance(),
3645             std::numeric_limits<double>::infinity());
3646 }
3647 
TEST_F(ConnectionTest,ConnectionForgetLearnedStateDiscardsPendingPings)3648 TEST_F(ConnectionTest, ConnectionForgetLearnedStateDiscardsPendingPings) {
3649   Connection* lconn = CreateConnection(ICEROLE_CONTROLLING);
3650   Connection* rconn = CreateConnection(ICEROLE_CONTROLLED);
3651 
3652   SendPingAndReceiveResponse(lconn, rconn, 10);
3653 
3654   EXPECT_TRUE(lconn->writable());
3655   EXPECT_TRUE(lconn->receiving());
3656 
3657   rtc::BufferT<uint8_t> reply;
3658   SendPingAndCaptureReply(lconn, rconn, 10, &reply);
3659 
3660   lconn->ForgetLearnedState();
3661 
3662   EXPECT_FALSE(lconn->writable());
3663   EXPECT_FALSE(lconn->receiving());
3664 
3665   lconn->OnReadPacket(reply.data<char>(), reply.size(),
3666                       /* packet_time_us */ -1);
3667 
3668   // That reply was discarded due to the ForgetLearnedState() while it was
3669   // outstanding.
3670   EXPECT_FALSE(lconn->writable());
3671   EXPECT_FALSE(lconn->receiving());
3672 
3673   // But sending a new ping and getting a reply works.
3674   SendPingAndReceiveResponse(lconn, rconn, 11);
3675   EXPECT_TRUE(lconn->writable());
3676   EXPECT_TRUE(lconn->receiving());
3677 }
3678 
TEST_F(ConnectionTest,ConnectionForgetLearnedStateDoesNotTriggerStateChange)3679 TEST_F(ConnectionTest, ConnectionForgetLearnedStateDoesNotTriggerStateChange) {
3680   Connection* lconn = CreateConnection(ICEROLE_CONTROLLING);
3681   Connection* rconn = CreateConnection(ICEROLE_CONTROLLED);
3682 
3683   EXPECT_EQ(num_state_changes_, 0);
3684   SendPingAndReceiveResponse(lconn, rconn, 10);
3685 
3686   EXPECT_TRUE(lconn->writable());
3687   EXPECT_TRUE(lconn->receiving());
3688   EXPECT_EQ(num_state_changes_, 2);
3689 
3690   lconn->ForgetLearnedState();
3691 
3692   EXPECT_FALSE(lconn->writable());
3693   EXPECT_FALSE(lconn->receiving());
3694   EXPECT_EQ(num_state_changes_, 2);
3695 }
3696 
3697 }  // namespace cricket
3698