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