1/* 2 * Copyright 2009 The WebRTC Project Authors. All rights reserved. 3 * 4 * Use of this source code is governed by a BSD-style license 5 * that can be found in the LICENSE file in the root of the source 6 * tree. An additional intellectual property rights grant can be found 7 * in the file PATENTS. All contributing project authors may 8 * be found in the AUTHORS file in the root of the source tree. 9 */ 10 11#include "webrtc/p2p/base/p2ptransportchannel.h" 12#include "webrtc/p2p/base/testrelayserver.h" 13#include "webrtc/p2p/base/teststunserver.h" 14#include "webrtc/p2p/base/testturnserver.h" 15#include "webrtc/p2p/client/basicportallocator.h" 16#include "webrtc/p2p/client/fakeportallocator.h" 17#include "webrtc/base/dscp.h" 18#include "webrtc/base/fakenetwork.h" 19#include "webrtc/base/firewallsocketserver.h" 20#include "webrtc/base/gunit.h" 21#include "webrtc/base/helpers.h" 22#include "webrtc/base/logging.h" 23#include "webrtc/base/natserver.h" 24#include "webrtc/base/natsocketfactory.h" 25#include "webrtc/base/physicalsocketserver.h" 26#include "webrtc/base/proxyserver.h" 27#include "webrtc/base/socketaddress.h" 28#include "webrtc/base/ssladapter.h" 29#include "webrtc/base/thread.h" 30#include "webrtc/base/virtualsocketserver.h" 31 32using cricket::kDefaultPortAllocatorFlags; 33using cricket::kMinimumStepDelay; 34using cricket::kDefaultStepDelay; 35using cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET; 36using cricket::ServerAddresses; 37using rtc::SocketAddress; 38 39static const int kDefaultTimeout = 1000; 40static const int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN | 41 cricket::PORTALLOCATOR_DISABLE_RELAY | 42 cricket::PORTALLOCATOR_DISABLE_TCP; 43// Addresses on the public internet. 44static const SocketAddress kPublicAddrs[2] = 45 { SocketAddress("11.11.11.11", 0), SocketAddress("22.22.22.22", 0) }; 46// IPv6 Addresses on the public internet. 47static const SocketAddress kIPv6PublicAddrs[2] = { 48 SocketAddress("2400:4030:1:2c00:be30:abcd:efab:cdef", 0), 49 SocketAddress("2620:0:1000:1b03:2e41:38ff:fea6:f2a4", 0) 50}; 51// For configuring multihomed clients. 52static const SocketAddress kAlternateAddrs[2] = 53 { SocketAddress("11.11.11.101", 0), SocketAddress("22.22.22.202", 0) }; 54// Addresses for HTTP proxy servers. 55static const SocketAddress kHttpsProxyAddrs[2] = 56 { SocketAddress("11.11.11.1", 443), SocketAddress("22.22.22.1", 443) }; 57// Addresses for SOCKS proxy servers. 58static const SocketAddress kSocksProxyAddrs[2] = 59 { SocketAddress("11.11.11.1", 1080), SocketAddress("22.22.22.1", 1080) }; 60// Internal addresses for NAT boxes. 61static const SocketAddress kNatAddrs[2] = 62 { SocketAddress("192.168.1.1", 0), SocketAddress("192.168.2.1", 0) }; 63// Private addresses inside the NAT private networks. 64static const SocketAddress kPrivateAddrs[2] = 65 { SocketAddress("192.168.1.11", 0), SocketAddress("192.168.2.22", 0) }; 66// For cascaded NATs, the internal addresses of the inner NAT boxes. 67static const SocketAddress kCascadedNatAddrs[2] = 68 { SocketAddress("192.168.10.1", 0), SocketAddress("192.168.20.1", 0) }; 69// For cascaded NATs, private addresses inside the inner private networks. 70static const SocketAddress kCascadedPrivateAddrs[2] = 71 { SocketAddress("192.168.10.11", 0), SocketAddress("192.168.20.22", 0) }; 72// The address of the public STUN server. 73static const SocketAddress kStunAddr("99.99.99.1", cricket::STUN_SERVER_PORT); 74// The addresses for the public relay server. 75static const SocketAddress kRelayUdpIntAddr("99.99.99.2", 5000); 76static const SocketAddress kRelayUdpExtAddr("99.99.99.3", 5001); 77static const SocketAddress kRelayTcpIntAddr("99.99.99.2", 5002); 78static const SocketAddress kRelayTcpExtAddr("99.99.99.3", 5003); 79static const SocketAddress kRelaySslTcpIntAddr("99.99.99.2", 5004); 80static const SocketAddress kRelaySslTcpExtAddr("99.99.99.3", 5005); 81// The addresses for the public turn server. 82static const SocketAddress kTurnUdpIntAddr("99.99.99.4", 83 cricket::STUN_SERVER_PORT); 84static const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0); 85static const cricket::RelayCredentials kRelayCredentials("test", "test"); 86 87// Based on ICE_UFRAG_LENGTH 88static const char* kIceUfrag[4] = {"TESTICEUFRAG0000", "TESTICEUFRAG0001", 89 "TESTICEUFRAG0002", "TESTICEUFRAG0003"}; 90// Based on ICE_PWD_LENGTH 91static const char* kIcePwd[4] = {"TESTICEPWD00000000000000", 92 "TESTICEPWD00000000000001", 93 "TESTICEPWD00000000000002", 94 "TESTICEPWD00000000000003"}; 95 96static const uint64_t kTiebreaker1 = 11111; 97static const uint64_t kTiebreaker2 = 22222; 98 99enum { 100 MSG_CANDIDATE 101}; 102 103static cricket::IceConfig CreateIceConfig(int receiving_timeout_ms, 104 bool gather_continually, 105 int backup_ping_interval = -1) { 106 cricket::IceConfig config; 107 config.receiving_timeout_ms = receiving_timeout_ms; 108 config.gather_continually = gather_continually; 109 config.backup_connection_ping_interval = backup_ping_interval; 110 return config; 111} 112 113// This test simulates 2 P2P endpoints that want to establish connectivity 114// with each other over various network topologies and conditions, which can be 115// specified in each individial test. 116// A virtual network (via VirtualSocketServer) along with virtual firewalls and 117// NATs (via Firewall/NATSocketServer) are used to simulate the various network 118// conditions. We can configure the IP addresses of the endpoints, 119// block various types of connectivity, or add arbitrary levels of NAT. 120// We also run a STUN server and a relay server on the virtual network to allow 121// our typical P2P mechanisms to do their thing. 122// For each case, we expect the P2P stack to eventually settle on a specific 123// form of connectivity to the other side. The test checks that the P2P 124// negotiation successfully establishes connectivity within a certain time, 125// and that the result is what we expect. 126// Note that this class is a base class for use by other tests, who will provide 127// specialized test behavior. 128class P2PTransportChannelTestBase : public testing::Test, 129 public rtc::MessageHandler, 130 public sigslot::has_slots<> { 131 public: 132 P2PTransportChannelTestBase() 133 : main_(rtc::Thread::Current()), 134 pss_(new rtc::PhysicalSocketServer), 135 vss_(new rtc::VirtualSocketServer(pss_.get())), 136 nss_(new rtc::NATSocketServer(vss_.get())), 137 ss_(new rtc::FirewallSocketServer(nss_.get())), 138 ss_scope_(ss_.get()), 139 stun_server_(cricket::TestStunServer::Create(main_, kStunAddr)), 140 turn_server_(main_, kTurnUdpIntAddr, kTurnUdpExtAddr), 141 relay_server_(main_, kRelayUdpIntAddr, kRelayUdpExtAddr, 142 kRelayTcpIntAddr, kRelayTcpExtAddr, 143 kRelaySslTcpIntAddr, kRelaySslTcpExtAddr), 144 socks_server1_(ss_.get(), kSocksProxyAddrs[0], 145 ss_.get(), kSocksProxyAddrs[0]), 146 socks_server2_(ss_.get(), kSocksProxyAddrs[1], 147 ss_.get(), kSocksProxyAddrs[1]), 148 clear_remote_candidates_ufrag_pwd_(false), 149 force_relay_(false) { 150 ep1_.role_ = cricket::ICEROLE_CONTROLLING; 151 ep2_.role_ = cricket::ICEROLE_CONTROLLED; 152 153 ServerAddresses stun_servers; 154 stun_servers.insert(kStunAddr); 155 ep1_.allocator_.reset(new cricket::BasicPortAllocator( 156 &ep1_.network_manager_, 157 stun_servers, kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr)); 158 ep2_.allocator_.reset(new cricket::BasicPortAllocator( 159 &ep2_.network_manager_, 160 stun_servers, kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr)); 161 } 162 163 protected: 164 enum Config { 165 OPEN, // Open to the Internet 166 NAT_FULL_CONE, // NAT, no filtering 167 NAT_ADDR_RESTRICTED, // NAT, must send to an addr to recv 168 NAT_PORT_RESTRICTED, // NAT, must send to an addr+port to recv 169 NAT_SYMMETRIC, // NAT, endpoint-dependent bindings 170 NAT_DOUBLE_CONE, // Double NAT, both cone 171 NAT_SYMMETRIC_THEN_CONE, // Double NAT, symmetric outer, cone inner 172 BLOCK_UDP, // Firewall, UDP in/out blocked 173 BLOCK_UDP_AND_INCOMING_TCP, // Firewall, UDP in/out and TCP in blocked 174 BLOCK_ALL_BUT_OUTGOING_HTTP, // Firewall, only TCP out on 80/443 175 PROXY_HTTPS, // All traffic through HTTPS proxy 176 PROXY_SOCKS, // All traffic through SOCKS proxy 177 NUM_CONFIGS 178 }; 179 180 struct Result { 181 Result(const std::string& lt, const std::string& lp, 182 const std::string& rt, const std::string& rp, 183 const std::string& lt2, const std::string& lp2, 184 const std::string& rt2, const std::string& rp2, int wait) 185 : local_type(lt), local_proto(lp), remote_type(rt), remote_proto(rp), 186 local_type2(lt2), local_proto2(lp2), remote_type2(rt2), 187 remote_proto2(rp2), connect_wait(wait) { 188 } 189 190 std::string local_type; 191 std::string local_proto; 192 std::string remote_type; 193 std::string remote_proto; 194 std::string local_type2; 195 std::string local_proto2; 196 std::string remote_type2; 197 std::string remote_proto2; 198 int connect_wait; 199 }; 200 201 struct ChannelData { 202 bool CheckData(const char* data, int len) { 203 bool ret = false; 204 if (!ch_packets_.empty()) { 205 std::string packet = ch_packets_.front(); 206 ret = (packet == std::string(data, len)); 207 ch_packets_.pop_front(); 208 } 209 return ret; 210 } 211 212 std::string name_; // TODO - Currently not used. 213 std::list<std::string> ch_packets_; 214 rtc::scoped_ptr<cricket::P2PTransportChannel> ch_; 215 }; 216 217 struct CandidateData : public rtc::MessageData { 218 CandidateData(cricket::TransportChannel* ch, const cricket::Candidate& c) 219 : channel(ch), candidate(c) { 220 } 221 cricket::TransportChannel* channel; 222 cricket::Candidate candidate; 223 }; 224 225 struct Endpoint { 226 Endpoint() 227 : role_(cricket::ICEROLE_UNKNOWN), 228 tiebreaker_(0), 229 role_conflict_(false), 230 save_candidates_(false) {} 231 bool HasChannel(cricket::TransportChannel* ch) { 232 return (ch == cd1_.ch_.get() || ch == cd2_.ch_.get()); 233 } 234 ChannelData* GetChannelData(cricket::TransportChannel* ch) { 235 if (!HasChannel(ch)) return NULL; 236 if (cd1_.ch_.get() == ch) 237 return &cd1_; 238 else 239 return &cd2_; 240 } 241 242 void SetIceRole(cricket::IceRole role) { role_ = role; } 243 cricket::IceRole ice_role() { return role_; } 244 void SetIceTiebreaker(uint64_t tiebreaker) { tiebreaker_ = tiebreaker; } 245 uint64_t GetIceTiebreaker() { return tiebreaker_; } 246 void OnRoleConflict(bool role_conflict) { role_conflict_ = role_conflict; } 247 bool role_conflict() { return role_conflict_; } 248 void SetAllocationStepDelay(uint32_t delay) { 249 allocator_->set_step_delay(delay); 250 } 251 void SetAllowTcpListen(bool allow_tcp_listen) { 252 allocator_->set_allow_tcp_listen(allow_tcp_listen); 253 } 254 255 rtc::FakeNetworkManager network_manager_; 256 rtc::scoped_ptr<cricket::BasicPortAllocator> allocator_; 257 ChannelData cd1_; 258 ChannelData cd2_; 259 cricket::IceRole role_; 260 uint64_t tiebreaker_; 261 bool role_conflict_; 262 bool save_candidates_; 263 std::vector<CandidateData*> saved_candidates_; 264 }; 265 266 ChannelData* GetChannelData(cricket::TransportChannel* channel) { 267 if (ep1_.HasChannel(channel)) 268 return ep1_.GetChannelData(channel); 269 else 270 return ep2_.GetChannelData(channel); 271 } 272 273 void CreateChannels(int num) { 274 std::string ice_ufrag_ep1_cd1_ch = kIceUfrag[0]; 275 std::string ice_pwd_ep1_cd1_ch = kIcePwd[0]; 276 std::string ice_ufrag_ep2_cd1_ch = kIceUfrag[1]; 277 std::string ice_pwd_ep2_cd1_ch = kIcePwd[1]; 278 ep1_.cd1_.ch_.reset(CreateChannel( 279 0, cricket::ICE_CANDIDATE_COMPONENT_DEFAULT, 280 ice_ufrag_ep1_cd1_ch, ice_pwd_ep1_cd1_ch, 281 ice_ufrag_ep2_cd1_ch, ice_pwd_ep2_cd1_ch)); 282 ep2_.cd1_.ch_.reset(CreateChannel( 283 1, cricket::ICE_CANDIDATE_COMPONENT_DEFAULT, 284 ice_ufrag_ep2_cd1_ch, ice_pwd_ep2_cd1_ch, 285 ice_ufrag_ep1_cd1_ch, ice_pwd_ep1_cd1_ch)); 286 if (num == 2) { 287 std::string ice_ufrag_ep1_cd2_ch = kIceUfrag[2]; 288 std::string ice_pwd_ep1_cd2_ch = kIcePwd[2]; 289 std::string ice_ufrag_ep2_cd2_ch = kIceUfrag[3]; 290 std::string ice_pwd_ep2_cd2_ch = kIcePwd[3]; 291 ep1_.cd2_.ch_.reset(CreateChannel( 292 0, cricket::ICE_CANDIDATE_COMPONENT_DEFAULT, 293 ice_ufrag_ep1_cd2_ch, ice_pwd_ep1_cd2_ch, 294 ice_ufrag_ep2_cd2_ch, ice_pwd_ep2_cd2_ch)); 295 ep2_.cd2_.ch_.reset(CreateChannel( 296 1, cricket::ICE_CANDIDATE_COMPONENT_DEFAULT, 297 ice_ufrag_ep2_cd2_ch, ice_pwd_ep2_cd2_ch, 298 ice_ufrag_ep1_cd2_ch, ice_pwd_ep1_cd2_ch)); 299 } 300 } 301 cricket::P2PTransportChannel* CreateChannel( 302 int endpoint, 303 int component, 304 const std::string& local_ice_ufrag, 305 const std::string& local_ice_pwd, 306 const std::string& remote_ice_ufrag, 307 const std::string& remote_ice_pwd) { 308 cricket::P2PTransportChannel* channel = new cricket::P2PTransportChannel( 309 "test content name", component, NULL, GetAllocator(endpoint)); 310 channel->SignalCandidateGathered.connect( 311 this, &P2PTransportChannelTestBase::OnCandidate); 312 channel->SignalReadPacket.connect( 313 this, &P2PTransportChannelTestBase::OnReadPacket); 314 channel->SignalRoleConflict.connect( 315 this, &P2PTransportChannelTestBase::OnRoleConflict); 316 channel->SetIceCredentials(local_ice_ufrag, local_ice_pwd); 317 if (clear_remote_candidates_ufrag_pwd_) { 318 // This only needs to be set if we're clearing them from the 319 // candidates. Some unit tests rely on this not being set. 320 channel->SetRemoteIceCredentials(remote_ice_ufrag, remote_ice_pwd); 321 } 322 channel->SetIceRole(GetEndpoint(endpoint)->ice_role()); 323 channel->SetIceTiebreaker(GetEndpoint(endpoint)->GetIceTiebreaker()); 324 channel->Connect(); 325 channel->MaybeStartGathering(); 326 return channel; 327 } 328 void DestroyChannels() { 329 ep1_.cd1_.ch_.reset(); 330 ep2_.cd1_.ch_.reset(); 331 ep1_.cd2_.ch_.reset(); 332 ep2_.cd2_.ch_.reset(); 333 } 334 cricket::P2PTransportChannel* ep1_ch1() { return ep1_.cd1_.ch_.get(); } 335 cricket::P2PTransportChannel* ep1_ch2() { return ep1_.cd2_.ch_.get(); } 336 cricket::P2PTransportChannel* ep2_ch1() { return ep2_.cd1_.ch_.get(); } 337 cricket::P2PTransportChannel* ep2_ch2() { return ep2_.cd2_.ch_.get(); } 338 339 // Common results. 340 static const Result kLocalUdpToLocalUdp; 341 static const Result kLocalUdpToStunUdp; 342 static const Result kLocalUdpToPrflxUdp; 343 static const Result kPrflxUdpToLocalUdp; 344 static const Result kStunUdpToLocalUdp; 345 static const Result kStunUdpToStunUdp; 346 static const Result kPrflxUdpToStunUdp; 347 static const Result kLocalUdpToRelayUdp; 348 static const Result kPrflxUdpToRelayUdp; 349 static const Result kLocalTcpToLocalTcp; 350 static const Result kLocalTcpToPrflxTcp; 351 static const Result kPrflxTcpToLocalTcp; 352 353 rtc::NATSocketServer* nat() { return nss_.get(); } 354 rtc::FirewallSocketServer* fw() { return ss_.get(); } 355 356 Endpoint* GetEndpoint(int endpoint) { 357 if (endpoint == 0) { 358 return &ep1_; 359 } else if (endpoint == 1) { 360 return &ep2_; 361 } else { 362 return NULL; 363 } 364 } 365 cricket::PortAllocator* GetAllocator(int endpoint) { 366 return GetEndpoint(endpoint)->allocator_.get(); 367 } 368 void AddAddress(int endpoint, const SocketAddress& addr) { 369 GetEndpoint(endpoint)->network_manager_.AddInterface(addr); 370 } 371 void RemoveAddress(int endpoint, const SocketAddress& addr) { 372 GetEndpoint(endpoint)->network_manager_.RemoveInterface(addr); 373 } 374 void SetProxy(int endpoint, rtc::ProxyType type) { 375 rtc::ProxyInfo info; 376 info.type = type; 377 info.address = (type == rtc::PROXY_HTTPS) ? 378 kHttpsProxyAddrs[endpoint] : kSocksProxyAddrs[endpoint]; 379 GetAllocator(endpoint)->set_proxy("unittest/1.0", info); 380 } 381 void SetAllocatorFlags(int endpoint, int flags) { 382 GetAllocator(endpoint)->set_flags(flags); 383 } 384 void SetIceRole(int endpoint, cricket::IceRole role) { 385 GetEndpoint(endpoint)->SetIceRole(role); 386 } 387 void SetIceTiebreaker(int endpoint, uint64_t tiebreaker) { 388 GetEndpoint(endpoint)->SetIceTiebreaker(tiebreaker); 389 } 390 bool GetRoleConflict(int endpoint) { 391 return GetEndpoint(endpoint)->role_conflict(); 392 } 393 void SetAllocationStepDelay(int endpoint, uint32_t delay) { 394 return GetEndpoint(endpoint)->SetAllocationStepDelay(delay); 395 } 396 void SetAllowTcpListen(int endpoint, bool allow_tcp_listen) { 397 return GetEndpoint(endpoint)->SetAllowTcpListen(allow_tcp_listen); 398 } 399 bool IsLocalToPrflxOrTheReverse(const Result& expected) { 400 return ( 401 (expected.local_type == "local" && expected.remote_type == "prflx") || 402 (expected.local_type == "prflx" && expected.remote_type == "local")); 403 } 404 405 // Return true if the approprite parts of the expected Result, based 406 // on the local and remote candidate of ep1_ch1, match. This can be 407 // used in an EXPECT_TRUE_WAIT. 408 bool CheckCandidate1(const Result& expected) { 409 const std::string& local_type = LocalCandidate(ep1_ch1())->type(); 410 const std::string& local_proto = LocalCandidate(ep1_ch1())->protocol(); 411 const std::string& remote_type = RemoteCandidate(ep1_ch1())->type(); 412 const std::string& remote_proto = RemoteCandidate(ep1_ch1())->protocol(); 413 return ((local_proto == expected.local_proto && 414 remote_proto == expected.remote_proto) && 415 ((local_type == expected.local_type && 416 remote_type == expected.remote_type) || 417 // Sometimes we expect local -> prflx or prflx -> local 418 // and instead get prflx -> local or local -> prflx, and 419 // that's OK. 420 (IsLocalToPrflxOrTheReverse(expected) && 421 local_type == expected.remote_type && 422 remote_type == expected.local_type))); 423 } 424 425 // EXPECT_EQ on the approprite parts of the expected Result, based 426 // on the local and remote candidate of ep1_ch1. This is like 427 // CheckCandidate1, except that it will provide more detail about 428 // what didn't match. 429 void ExpectCandidate1(const Result& expected) { 430 if (CheckCandidate1(expected)) { 431 return; 432 } 433 434 const std::string& local_type = LocalCandidate(ep1_ch1())->type(); 435 const std::string& local_proto = LocalCandidate(ep1_ch1())->protocol(); 436 const std::string& remote_type = RemoteCandidate(ep1_ch1())->type(); 437 const std::string& remote_proto = RemoteCandidate(ep1_ch1())->protocol(); 438 EXPECT_EQ(expected.local_type, local_type); 439 EXPECT_EQ(expected.remote_type, remote_type); 440 EXPECT_EQ(expected.local_proto, local_proto); 441 EXPECT_EQ(expected.remote_proto, remote_proto); 442 } 443 444 // Return true if the approprite parts of the expected Result, based 445 // on the local and remote candidate of ep2_ch1, match. This can be 446 // used in an EXPECT_TRUE_WAIT. 447 bool CheckCandidate2(const Result& expected) { 448 const std::string& local_type = LocalCandidate(ep2_ch1())->type(); 449 // const std::string& remote_type = RemoteCandidate(ep2_ch1())->type(); 450 const std::string& local_proto = LocalCandidate(ep2_ch1())->protocol(); 451 const std::string& remote_proto = RemoteCandidate(ep2_ch1())->protocol(); 452 // Removed remote_type comparision aginst best connection remote 453 // candidate. This is done to handle remote type discrepancy from 454 // local to stun based on the test type. 455 // For example in case of Open -> NAT, ep2 channels will have LULU 456 // and in other cases like NAT -> NAT it will be LUSU. To avoid these 457 // mismatches and we are doing comparision in different way. 458 // i.e. when don't match its remote type is either local or stun. 459 // TODO(ronghuawu): Refine the test criteria. 460 // https://code.google.com/p/webrtc/issues/detail?id=1953 461 return ((local_proto == expected.local_proto2 && 462 remote_proto == expected.remote_proto2) && 463 (local_type == expected.local_type2 || 464 // Sometimes we expect local -> prflx or prflx -> local 465 // and instead get prflx -> local or local -> prflx, and 466 // that's OK. 467 (IsLocalToPrflxOrTheReverse(expected) && 468 local_type == expected.remote_type2))); 469 } 470 471 // EXPECT_EQ on the approprite parts of the expected Result, based 472 // on the local and remote candidate of ep2_ch1. This is like 473 // CheckCandidate2, except that it will provide more detail about 474 // what didn't match. 475 void ExpectCandidate2(const Result& expected) { 476 if (CheckCandidate2(expected)) { 477 return; 478 } 479 480 const std::string& local_type = LocalCandidate(ep2_ch1())->type(); 481 const std::string& local_proto = LocalCandidate(ep2_ch1())->protocol(); 482 const std::string& remote_type = RemoteCandidate(ep2_ch1())->type(); 483 EXPECT_EQ(expected.local_proto2, local_proto); 484 EXPECT_EQ(expected.remote_proto2, remote_type); 485 EXPECT_EQ(expected.local_type2, local_type); 486 if (remote_type != expected.remote_type2) { 487 EXPECT_TRUE(expected.remote_type2 == cricket::LOCAL_PORT_TYPE || 488 expected.remote_type2 == cricket::STUN_PORT_TYPE); 489 EXPECT_TRUE(remote_type == cricket::LOCAL_PORT_TYPE || 490 remote_type == cricket::STUN_PORT_TYPE || 491 remote_type == cricket::PRFLX_PORT_TYPE); 492 } 493 } 494 495 void Test(const Result& expected) { 496 int32_t connect_start = rtc::Time(), connect_time; 497 498 // Create the channels and wait for them to connect. 499 CreateChannels(1); 500 EXPECT_TRUE_WAIT_MARGIN(ep1_ch1() != NULL && 501 ep2_ch1() != NULL && 502 ep1_ch1()->receiving() && 503 ep1_ch1()->writable() && 504 ep2_ch1()->receiving() && 505 ep2_ch1()->writable(), 506 expected.connect_wait, 507 1000); 508 connect_time = rtc::TimeSince(connect_start); 509 if (connect_time < expected.connect_wait) { 510 LOG(LS_INFO) << "Connect time: " << connect_time << " ms"; 511 } else { 512 LOG(LS_INFO) << "Connect time: " << "TIMEOUT (" 513 << expected.connect_wait << " ms)"; 514 } 515 516 // Allow a few turns of the crank for the best connections to emerge. 517 // This may take up to 2 seconds. 518 if (ep1_ch1()->best_connection() && 519 ep2_ch1()->best_connection()) { 520 int32_t converge_start = rtc::Time(), converge_time; 521 int converge_wait = 2000; 522 EXPECT_TRUE_WAIT_MARGIN(CheckCandidate1(expected), converge_wait, 523 converge_wait); 524 // Also do EXPECT_EQ on each part so that failures are more verbose. 525 ExpectCandidate1(expected); 526 527 // Verifying remote channel best connection information. This is done 528 // only for the RFC 5245 as controlled agent will use USE-CANDIDATE 529 // from controlling (ep1) agent. We can easily predict from EP1 result 530 // matrix. 531 532 // Checking for best connection candidates information at remote. 533 EXPECT_TRUE_WAIT(CheckCandidate2(expected), kDefaultTimeout); 534 // For verbose 535 ExpectCandidate2(expected); 536 537 converge_time = rtc::TimeSince(converge_start); 538 if (converge_time < converge_wait) { 539 LOG(LS_INFO) << "Converge time: " << converge_time << " ms"; 540 } else { 541 LOG(LS_INFO) << "Converge time: " << "TIMEOUT (" 542 << converge_wait << " ms)"; 543 } 544 } 545 // Try sending some data to other end. 546 TestSendRecv(1); 547 548 // Destroy the channels, and wait for them to be fully cleaned up. 549 DestroyChannels(); 550 } 551 552 void TestSendRecv(int channels) { 553 for (int i = 0; i < 10; ++i) { 554 const char* data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; 555 int len = static_cast<int>(strlen(data)); 556 // local_channel1 <==> remote_channel1 557 EXPECT_EQ_WAIT(len, SendData(ep1_ch1(), data, len), 1000); 558 EXPECT_TRUE_WAIT(CheckDataOnChannel(ep2_ch1(), data, len), 1000); 559 EXPECT_EQ_WAIT(len, SendData(ep2_ch1(), data, len), 1000); 560 EXPECT_TRUE_WAIT(CheckDataOnChannel(ep1_ch1(), data, len), 1000); 561 if (channels == 2 && ep1_ch2() && ep2_ch2()) { 562 // local_channel2 <==> remote_channel2 563 EXPECT_EQ_WAIT(len, SendData(ep1_ch2(), data, len), 1000); 564 EXPECT_TRUE_WAIT(CheckDataOnChannel(ep2_ch2(), data, len), 1000); 565 EXPECT_EQ_WAIT(len, SendData(ep2_ch2(), data, len), 1000); 566 EXPECT_TRUE_WAIT(CheckDataOnChannel(ep1_ch2(), data, len), 1000); 567 } 568 } 569 } 570 571 // This test waits for the transport to become receiving and writable on both 572 // end points. Once they are, the end points set new local ice credentials and 573 // restart the ice gathering. Finally it waits for the transport to select a 574 // new connection using the newly generated ice candidates. 575 // Before calling this function the end points must be configured. 576 void TestHandleIceUfragPasswordChanged() { 577 ep1_ch1()->SetRemoteIceCredentials(kIceUfrag[1], kIcePwd[1]); 578 ep2_ch1()->SetRemoteIceCredentials(kIceUfrag[0], kIcePwd[0]); 579 EXPECT_TRUE_WAIT_MARGIN(ep1_ch1()->receiving() && ep1_ch1()->writable() && 580 ep2_ch1()->receiving() && ep2_ch1()->writable(), 581 1000, 1000); 582 583 const cricket::Candidate* old_local_candidate1 = LocalCandidate(ep1_ch1()); 584 const cricket::Candidate* old_local_candidate2 = LocalCandidate(ep2_ch1()); 585 const cricket::Candidate* old_remote_candidate1 = 586 RemoteCandidate(ep1_ch1()); 587 const cricket::Candidate* old_remote_candidate2 = 588 RemoteCandidate(ep2_ch1()); 589 590 ep1_ch1()->SetIceCredentials(kIceUfrag[2], kIcePwd[2]); 591 ep1_ch1()->SetRemoteIceCredentials(kIceUfrag[3], kIcePwd[3]); 592 ep1_ch1()->MaybeStartGathering(); 593 ep2_ch1()->SetIceCredentials(kIceUfrag[3], kIcePwd[3]); 594 ep2_ch1()->SetRemoteIceCredentials(kIceUfrag[2], kIcePwd[2]); 595 ep2_ch1()->MaybeStartGathering(); 596 597 EXPECT_TRUE_WAIT_MARGIN(LocalCandidate(ep1_ch1())->generation() != 598 old_local_candidate1->generation(), 599 1000, 1000); 600 EXPECT_TRUE_WAIT_MARGIN(LocalCandidate(ep2_ch1())->generation() != 601 old_local_candidate2->generation(), 602 1000, 1000); 603 EXPECT_TRUE_WAIT_MARGIN(RemoteCandidate(ep1_ch1())->generation() != 604 old_remote_candidate1->generation(), 605 1000, 1000); 606 EXPECT_TRUE_WAIT_MARGIN(RemoteCandidate(ep2_ch1())->generation() != 607 old_remote_candidate2->generation(), 608 1000, 1000); 609 EXPECT_EQ(1u, RemoteCandidate(ep2_ch1())->generation()); 610 EXPECT_EQ(1u, RemoteCandidate(ep1_ch1())->generation()); 611 } 612 613 void TestSignalRoleConflict() { 614 SetIceTiebreaker(0, kTiebreaker1); // Default EP1 is in controlling state. 615 616 SetIceRole(1, cricket::ICEROLE_CONTROLLING); 617 SetIceTiebreaker(1, kTiebreaker2); 618 619 // Creating channels with both channels role set to CONTROLLING. 620 CreateChannels(1); 621 // Since both the channels initiated with controlling state and channel2 622 // has higher tiebreaker value, channel1 should receive SignalRoleConflict. 623 EXPECT_TRUE_WAIT(GetRoleConflict(0), 1000); 624 EXPECT_FALSE(GetRoleConflict(1)); 625 626 EXPECT_TRUE_WAIT(ep1_ch1()->receiving() && 627 ep1_ch1()->writable() && 628 ep2_ch1()->receiving() && 629 ep2_ch1()->writable(), 630 1000); 631 632 EXPECT_TRUE(ep1_ch1()->best_connection() && 633 ep2_ch1()->best_connection()); 634 635 TestSendRecv(1); 636 } 637 638 // We pass the candidates directly to the other side. 639 void OnCandidate(cricket::TransportChannelImpl* ch, 640 const cricket::Candidate& c) { 641 if (force_relay_ && c.type() != cricket::RELAY_PORT_TYPE) 642 return; 643 644 if (GetEndpoint(ch)->save_candidates_) { 645 GetEndpoint(ch)->saved_candidates_.push_back(new CandidateData(ch, c)); 646 } else { 647 main_->Post(this, MSG_CANDIDATE, new CandidateData(ch, c)); 648 } 649 } 650 651 void PauseCandidates(int endpoint) { 652 GetEndpoint(endpoint)->save_candidates_ = true; 653 } 654 655 // Tcp candidate verification has to be done when they are generated. 656 void VerifySavedTcpCandidates(int endpoint, const std::string& tcptype) { 657 for (auto& data : GetEndpoint(endpoint)->saved_candidates_) { 658 EXPECT_EQ(data->candidate.protocol(), cricket::TCP_PROTOCOL_NAME); 659 EXPECT_EQ(data->candidate.tcptype(), tcptype); 660 if (data->candidate.tcptype() == cricket::TCPTYPE_ACTIVE_STR) { 661 EXPECT_EQ(data->candidate.address().port(), cricket::DISCARD_PORT); 662 } else if (data->candidate.tcptype() == cricket::TCPTYPE_PASSIVE_STR) { 663 EXPECT_NE(data->candidate.address().port(), cricket::DISCARD_PORT); 664 } else { 665 FAIL() << "Unknown tcptype: " << data->candidate.tcptype(); 666 } 667 } 668 } 669 670 void ResumeCandidates(int endpoint) { 671 Endpoint* ed = GetEndpoint(endpoint); 672 std::vector<CandidateData*>::iterator it = ed->saved_candidates_.begin(); 673 for (; it != ed->saved_candidates_.end(); ++it) { 674 main_->Post(this, MSG_CANDIDATE, *it); 675 } 676 ed->saved_candidates_.clear(); 677 ed->save_candidates_ = false; 678 } 679 680 void OnMessage(rtc::Message* msg) { 681 switch (msg->message_id) { 682 case MSG_CANDIDATE: { 683 rtc::scoped_ptr<CandidateData> data( 684 static_cast<CandidateData*>(msg->pdata)); 685 cricket::P2PTransportChannel* rch = GetRemoteChannel(data->channel); 686 cricket::Candidate c = data->candidate; 687 if (clear_remote_candidates_ufrag_pwd_) { 688 c.set_username(""); 689 c.set_password(""); 690 } 691 LOG(LS_INFO) << "Candidate(" << data->channel->component() << "->" 692 << rch->component() << "): " << c.ToString(); 693 rch->AddRemoteCandidate(c); 694 break; 695 } 696 } 697 } 698 void OnReadPacket(cricket::TransportChannel* channel, const char* data, 699 size_t len, const rtc::PacketTime& packet_time, 700 int flags) { 701 std::list<std::string>& packets = GetPacketList(channel); 702 packets.push_front(std::string(data, len)); 703 } 704 void OnRoleConflict(cricket::TransportChannelImpl* channel) { 705 GetEndpoint(channel)->OnRoleConflict(true); 706 cricket::IceRole new_role = 707 GetEndpoint(channel)->ice_role() == cricket::ICEROLE_CONTROLLING ? 708 cricket::ICEROLE_CONTROLLED : cricket::ICEROLE_CONTROLLING; 709 channel->SetIceRole(new_role); 710 } 711 int SendData(cricket::TransportChannel* channel, 712 const char* data, size_t len) { 713 rtc::PacketOptions options; 714 return channel->SendPacket(data, len, options, 0); 715 } 716 bool CheckDataOnChannel(cricket::TransportChannel* channel, 717 const char* data, int len) { 718 return GetChannelData(channel)->CheckData(data, len); 719 } 720 static const cricket::Candidate* LocalCandidate( 721 cricket::P2PTransportChannel* ch) { 722 return (ch && ch->best_connection()) ? 723 &ch->best_connection()->local_candidate() : NULL; 724 } 725 static const cricket::Candidate* RemoteCandidate( 726 cricket::P2PTransportChannel* ch) { 727 return (ch && ch->best_connection()) ? 728 &ch->best_connection()->remote_candidate() : NULL; 729 } 730 Endpoint* GetEndpoint(cricket::TransportChannel* ch) { 731 if (ep1_.HasChannel(ch)) { 732 return &ep1_; 733 } else if (ep2_.HasChannel(ch)) { 734 return &ep2_; 735 } else { 736 return NULL; 737 } 738 } 739 cricket::P2PTransportChannel* GetRemoteChannel( 740 cricket::TransportChannel* ch) { 741 if (ch == ep1_ch1()) 742 return ep2_ch1(); 743 else if (ch == ep1_ch2()) 744 return ep2_ch2(); 745 else if (ch == ep2_ch1()) 746 return ep1_ch1(); 747 else if (ch == ep2_ch2()) 748 return ep1_ch2(); 749 else 750 return NULL; 751 } 752 std::list<std::string>& GetPacketList(cricket::TransportChannel* ch) { 753 return GetChannelData(ch)->ch_packets_; 754 } 755 756 void set_clear_remote_candidates_ufrag_pwd(bool clear) { 757 clear_remote_candidates_ufrag_pwd_ = clear; 758 } 759 760 void set_force_relay(bool relay) { 761 force_relay_ = relay; 762 } 763 764 private: 765 rtc::Thread* main_; 766 rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_; 767 rtc::scoped_ptr<rtc::VirtualSocketServer> vss_; 768 rtc::scoped_ptr<rtc::NATSocketServer> nss_; 769 rtc::scoped_ptr<rtc::FirewallSocketServer> ss_; 770 rtc::SocketServerScope ss_scope_; 771 rtc::scoped_ptr<cricket::TestStunServer> stun_server_; 772 cricket::TestTurnServer turn_server_; 773 cricket::TestRelayServer relay_server_; 774 rtc::SocksProxyServer socks_server1_; 775 rtc::SocksProxyServer socks_server2_; 776 Endpoint ep1_; 777 Endpoint ep2_; 778 bool clear_remote_candidates_ufrag_pwd_; 779 bool force_relay_; 780}; 781 782// The tests have only a few outcomes, which we predefine. 783const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase:: 784 kLocalUdpToLocalUdp("local", "udp", "local", "udp", 785 "local", "udp", "local", "udp", 1000); 786const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase:: 787 kLocalUdpToStunUdp("local", "udp", "stun", "udp", 788 "local", "udp", "stun", "udp", 1000); 789const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase:: 790 kLocalUdpToPrflxUdp("local", "udp", "prflx", "udp", 791 "prflx", "udp", "local", "udp", 1000); 792const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase:: 793 kPrflxUdpToLocalUdp("prflx", "udp", "local", "udp", 794 "local", "udp", "prflx", "udp", 1000); 795const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase:: 796 kStunUdpToLocalUdp("stun", "udp", "local", "udp", 797 "local", "udp", "stun", "udp", 1000); 798const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase:: 799 kStunUdpToStunUdp("stun", "udp", "stun", "udp", 800 "stun", "udp", "stun", "udp", 1000); 801const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase:: 802 kPrflxUdpToStunUdp("prflx", "udp", "stun", "udp", 803 "local", "udp", "prflx", "udp", 1000); 804const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase:: 805 kLocalUdpToRelayUdp("local", "udp", "relay", "udp", 806 "relay", "udp", "local", "udp", 2000); 807const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase:: 808 kPrflxUdpToRelayUdp("prflx", "udp", "relay", "udp", 809 "relay", "udp", "prflx", "udp", 2000); 810const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase:: 811 kLocalTcpToLocalTcp("local", "tcp", "local", "tcp", 812 "local", "tcp", "local", "tcp", 3000); 813const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase:: 814 kLocalTcpToPrflxTcp("local", "tcp", "prflx", "tcp", 815 "prflx", "tcp", "local", "tcp", 3000); 816const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase:: 817 kPrflxTcpToLocalTcp("prflx", "tcp", "local", "tcp", 818 "local", "tcp", "prflx", "tcp", 3000); 819 820// Test the matrix of all the connectivity types we expect to see in the wild. 821// Just test every combination of the configs in the Config enum. 822class P2PTransportChannelTest : public P2PTransportChannelTestBase { 823 protected: 824 static const Result* kMatrix[NUM_CONFIGS][NUM_CONFIGS]; 825 static const Result* kMatrixSharedUfrag[NUM_CONFIGS][NUM_CONFIGS]; 826 static const Result* kMatrixSharedSocketAsGice[NUM_CONFIGS][NUM_CONFIGS]; 827 static const Result* kMatrixSharedSocketAsIce[NUM_CONFIGS][NUM_CONFIGS]; 828 void ConfigureEndpoints(Config config1, 829 Config config2, 830 int allocator_flags1, 831 int allocator_flags2) { 832 ServerAddresses stun_servers; 833 stun_servers.insert(kStunAddr); 834 GetEndpoint(0)->allocator_.reset( 835 new cricket::BasicPortAllocator(&(GetEndpoint(0)->network_manager_), 836 stun_servers, 837 rtc::SocketAddress(), rtc::SocketAddress(), 838 rtc::SocketAddress())); 839 GetEndpoint(1)->allocator_.reset( 840 new cricket::BasicPortAllocator(&(GetEndpoint(1)->network_manager_), 841 stun_servers, 842 rtc::SocketAddress(), rtc::SocketAddress(), 843 rtc::SocketAddress())); 844 845 cricket::RelayServerConfig turn_server(cricket::RELAY_TURN); 846 turn_server.credentials = kRelayCredentials; 847 turn_server.ports.push_back( 848 cricket::ProtocolAddress(kTurnUdpIntAddr, cricket::PROTO_UDP, false)); 849 GetEndpoint(0)->allocator_->AddTurnServer(turn_server); 850 GetEndpoint(1)->allocator_->AddTurnServer(turn_server); 851 852 int delay = kMinimumStepDelay; 853 ConfigureEndpoint(0, config1); 854 SetAllocatorFlags(0, allocator_flags1); 855 SetAllocationStepDelay(0, delay); 856 ConfigureEndpoint(1, config2); 857 SetAllocatorFlags(1, allocator_flags2); 858 SetAllocationStepDelay(1, delay); 859 860 set_clear_remote_candidates_ufrag_pwd(true); 861 } 862 void ConfigureEndpoint(int endpoint, Config config) { 863 switch (config) { 864 case OPEN: 865 AddAddress(endpoint, kPublicAddrs[endpoint]); 866 break; 867 case NAT_FULL_CONE: 868 case NAT_ADDR_RESTRICTED: 869 case NAT_PORT_RESTRICTED: 870 case NAT_SYMMETRIC: 871 AddAddress(endpoint, kPrivateAddrs[endpoint]); 872 // Add a single NAT of the desired type 873 nat()->AddTranslator(kPublicAddrs[endpoint], kNatAddrs[endpoint], 874 static_cast<rtc::NATType>(config - NAT_FULL_CONE))-> 875 AddClient(kPrivateAddrs[endpoint]); 876 break; 877 case NAT_DOUBLE_CONE: 878 case NAT_SYMMETRIC_THEN_CONE: 879 AddAddress(endpoint, kCascadedPrivateAddrs[endpoint]); 880 // Add a two cascaded NATs of the desired types 881 nat()->AddTranslator(kPublicAddrs[endpoint], kNatAddrs[endpoint], 882 (config == NAT_DOUBLE_CONE) ? 883 rtc::NAT_OPEN_CONE : rtc::NAT_SYMMETRIC)-> 884 AddTranslator(kPrivateAddrs[endpoint], kCascadedNatAddrs[endpoint], 885 rtc::NAT_OPEN_CONE)-> 886 AddClient(kCascadedPrivateAddrs[endpoint]); 887 break; 888 case BLOCK_UDP: 889 case BLOCK_UDP_AND_INCOMING_TCP: 890 case BLOCK_ALL_BUT_OUTGOING_HTTP: 891 case PROXY_HTTPS: 892 case PROXY_SOCKS: 893 AddAddress(endpoint, kPublicAddrs[endpoint]); 894 // Block all UDP 895 fw()->AddRule(false, rtc::FP_UDP, rtc::FD_ANY, 896 kPublicAddrs[endpoint]); 897 if (config == BLOCK_UDP_AND_INCOMING_TCP) { 898 // Block TCP inbound to the endpoint 899 fw()->AddRule(false, rtc::FP_TCP, SocketAddress(), 900 kPublicAddrs[endpoint]); 901 } else if (config == BLOCK_ALL_BUT_OUTGOING_HTTP) { 902 // Block all TCP to/from the endpoint except 80/443 out 903 fw()->AddRule(true, rtc::FP_TCP, kPublicAddrs[endpoint], 904 SocketAddress(rtc::IPAddress(INADDR_ANY), 80)); 905 fw()->AddRule(true, rtc::FP_TCP, kPublicAddrs[endpoint], 906 SocketAddress(rtc::IPAddress(INADDR_ANY), 443)); 907 fw()->AddRule(false, rtc::FP_TCP, rtc::FD_ANY, 908 kPublicAddrs[endpoint]); 909 } else if (config == PROXY_HTTPS) { 910 // Block all TCP to/from the endpoint except to the proxy server 911 fw()->AddRule(true, rtc::FP_TCP, kPublicAddrs[endpoint], 912 kHttpsProxyAddrs[endpoint]); 913 fw()->AddRule(false, rtc::FP_TCP, rtc::FD_ANY, 914 kPublicAddrs[endpoint]); 915 SetProxy(endpoint, rtc::PROXY_HTTPS); 916 } else if (config == PROXY_SOCKS) { 917 // Block all TCP to/from the endpoint except to the proxy server 918 fw()->AddRule(true, rtc::FP_TCP, kPublicAddrs[endpoint], 919 kSocksProxyAddrs[endpoint]); 920 fw()->AddRule(false, rtc::FP_TCP, rtc::FD_ANY, 921 kPublicAddrs[endpoint]); 922 SetProxy(endpoint, rtc::PROXY_SOCKS5); 923 } 924 break; 925 default: 926 break; 927 } 928 } 929}; 930 931// Shorthands for use in the test matrix. 932#define LULU &kLocalUdpToLocalUdp 933#define LUSU &kLocalUdpToStunUdp 934#define LUPU &kLocalUdpToPrflxUdp 935#define PULU &kPrflxUdpToLocalUdp 936#define SULU &kStunUdpToLocalUdp 937#define SUSU &kStunUdpToStunUdp 938#define PUSU &kPrflxUdpToStunUdp 939#define LURU &kLocalUdpToRelayUdp 940#define PURU &kPrflxUdpToRelayUdp 941#define LTLT &kLocalTcpToLocalTcp 942#define LTPT &kLocalTcpToPrflxTcp 943#define PTLT &kPrflxTcpToLocalTcp 944// TODO: Enable these once TestRelayServer can accept external TCP. 945#define LTRT NULL 946#define LSRS NULL 947 948// Test matrix. Originator behavior defined by rows, receiever by columns. 949 950// Currently the p2ptransportchannel.cc (specifically the 951// P2PTransportChannel::OnUnknownAddress) operates in 2 modes depend on the 952// remote candidates - ufrag per port or shared ufrag. 953// For example, if the remote candidates have the shared ufrag, for the unknown 954// address reaches the OnUnknownAddress, we will try to find the matched 955// remote candidate based on the address and protocol, if not found, a new 956// remote candidate will be created for this address. But if the remote 957// candidates have different ufrags, we will try to find the matched remote 958// candidate by comparing the ufrag. If not found, an error will be returned. 959// Because currently the shared ufrag feature is under the experiment and will 960// be rolled out gradually. We want to test the different combinations of peers 961// with/without the shared ufrag enabled. And those different combinations have 962// different expectation of the best connection. For example in the OpenToCONE 963// case, an unknown address will be updated to a "host" remote candidate if the 964// remote peer uses different ufrag per port. But in the shared ufrag case, 965// a "stun" (should be peer-reflexive eventually) candidate will be created for 966// that. So the expected best candidate will be LUSU instead of LULU. 967// With all these, we have to keep 2 test matrixes for the tests: 968// kMatrix - for the tests that the remote peer uses different ufrag per port. 969// kMatrixSharedUfrag - for the tests that remote peer uses shared ufrag. 970// The different between the two matrixes are on: 971// OPToCONE, OPTo2CON, 972// COToCONE, COToADDR, COToPORT, COToSYMM, COTo2CON, COToSCON, 973// ADToCONE, ADToADDR, ADTo2CON, 974// POToADDR, 975// SYToADDR, 976// 2CToCONE, 2CToADDR, 2CToPORT, 2CToSYMM, 2CTo2CON, 2CToSCON, 977// SCToADDR, 978 979// TODO: Fix NULLs caused by lack of TCP support in NATSocket. 980// TODO: Fix NULLs caused by no HTTP proxy support. 981// TODO: Rearrange rows/columns from best to worst. 982// TODO(ronghuawu): Keep only one test matrix once the shared ufrag is enabled. 983const P2PTransportChannelTest::Result* 984 P2PTransportChannelTest::kMatrix[NUM_CONFIGS][NUM_CONFIGS] = { 985// OPEN CONE ADDR PORT SYMM 2CON SCON !UDP !TCP HTTP PRXH PRXS 986/*OP*/ {LULU, LULU, LULU, LULU, LULU, LULU, LULU, LTLT, LTLT, LSRS, NULL, LTLT}, 987/*CO*/ {LULU, LULU, LULU, SULU, SULU, LULU, SULU, NULL, NULL, LSRS, NULL, LTRT}, 988/*AD*/ {LULU, LULU, LULU, SUSU, SUSU, LULU, SUSU, NULL, NULL, LSRS, NULL, LTRT}, 989/*PO*/ {LULU, LUSU, LUSU, SUSU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT}, 990/*SY*/ {LULU, LUSU, LUSU, LURU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT}, 991/*2C*/ {LULU, LULU, LULU, SULU, SULU, LULU, SULU, NULL, NULL, LSRS, NULL, LTRT}, 992/*SC*/ {LULU, LUSU, LUSU, LURU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT}, 993/*!U*/ {LTLT, NULL, NULL, NULL, NULL, NULL, NULL, LTLT, LTLT, LSRS, NULL, LTRT}, 994/*!T*/ {LTRT, NULL, NULL, NULL, NULL, NULL, NULL, LTLT, LTRT, LSRS, NULL, LTRT}, 995/*HT*/ {LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, NULL, LSRS}, 996/*PR*/ {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}, 997/*PR*/ {LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LSRS, NULL, LTRT}, 998}; 999const P2PTransportChannelTest::Result* 1000 P2PTransportChannelTest::kMatrixSharedUfrag[NUM_CONFIGS][NUM_CONFIGS] = { 1001// OPEN CONE ADDR PORT SYMM 2CON SCON !UDP !TCP HTTP PRXH PRXS 1002/*OP*/ {LULU, LUSU, LULU, LULU, LULU, LUSU, LULU, LTLT, LTLT, LSRS, NULL, LTLT}, 1003/*CO*/ {LULU, LUSU, LUSU, SUSU, SUSU, LUSU, SUSU, NULL, NULL, LSRS, NULL, LTRT}, 1004/*AD*/ {LULU, LUSU, LUSU, SUSU, SUSU, LUSU, SUSU, NULL, NULL, LSRS, NULL, LTRT}, 1005/*PO*/ {LULU, LUSU, LUSU, SUSU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT}, 1006/*SY*/ {LULU, LUSU, LUSU, LURU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT}, 1007/*2C*/ {LULU, LUSU, LUSU, SUSU, SUSU, LUSU, SUSU, NULL, NULL, LSRS, NULL, LTRT}, 1008/*SC*/ {LULU, LUSU, LUSU, LURU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT}, 1009/*!U*/ {LTLT, NULL, NULL, NULL, NULL, NULL, NULL, LTLT, LTLT, LSRS, NULL, LTRT}, 1010/*!T*/ {LTRT, NULL, NULL, NULL, NULL, NULL, NULL, LTLT, LTRT, LSRS, NULL, LTRT}, 1011/*HT*/ {LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, NULL, LSRS}, 1012/*PR*/ {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}, 1013/*PR*/ {LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LSRS, NULL, LTRT}, 1014}; 1015const P2PTransportChannelTest::Result* 1016 P2PTransportChannelTest::kMatrixSharedSocketAsGice 1017 [NUM_CONFIGS][NUM_CONFIGS] = { 1018// OPEN CONE ADDR PORT SYMM 2CON SCON !UDP !TCP HTTP PRXH PRXS 1019/*OP*/ {LULU, LUSU, LUSU, LUSU, LUSU, LUSU, LUSU, LTLT, LTLT, LSRS, NULL, LTLT}, 1020/*CO*/ {LULU, LUSU, LUSU, LUSU, LUSU, LUSU, LUSU, NULL, NULL, LSRS, NULL, LTRT}, 1021/*AD*/ {LULU, LUSU, LUSU, LUSU, LUSU, LUSU, LUSU, NULL, NULL, LSRS, NULL, LTRT}, 1022/*PO*/ {LULU, LUSU, LUSU, LUSU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT}, 1023/*SY*/ {LULU, LUSU, LUSU, LURU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT}, 1024/*2C*/ {LULU, LUSU, LUSU, LUSU, LUSU, LUSU, LUSU, NULL, NULL, LSRS, NULL, LTRT}, 1025/*SC*/ {LULU, LUSU, LUSU, LURU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT}, 1026/*!U*/ {LTLT, NULL, NULL, NULL, NULL, NULL, NULL, LTLT, LTLT, LSRS, NULL, LTRT}, 1027/*!T*/ {LTRT, NULL, NULL, NULL, NULL, NULL, NULL, LTLT, LTRT, LSRS, NULL, LTRT}, 1028/*HT*/ {LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, NULL, LSRS}, 1029/*PR*/ {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}, 1030/*PR*/ {LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LSRS, NULL, LTRT}, 1031}; 1032const P2PTransportChannelTest::Result* 1033 P2PTransportChannelTest::kMatrixSharedSocketAsIce 1034 [NUM_CONFIGS][NUM_CONFIGS] = { 1035// OPEN CONE ADDR PORT SYMM 2CON SCON !UDP !TCP HTTP PRXH PRXS 1036/*OP*/ {LULU, LUSU, LUSU, LUSU, LUPU, LUSU, LUPU, PTLT, LTPT, LSRS, NULL, LTPT}, 1037/*CO*/ {LULU, LUSU, LUSU, LUSU, LUPU, LUSU, LUPU, NULL, NULL, LSRS, NULL, LTRT}, 1038/*AD*/ {LULU, LUSU, LUSU, LUSU, LUPU, LUSU, LUPU, NULL, NULL, LSRS, NULL, LTRT}, 1039/*PO*/ {LULU, LUSU, LUSU, LUSU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT}, 1040/*SY*/ {PULU, PUSU, PUSU, PURU, PURU, PUSU, PURU, NULL, NULL, LSRS, NULL, LTRT}, 1041/*2C*/ {LULU, LUSU, LUSU, LUSU, LUPU, LUSU, LUPU, NULL, NULL, LSRS, NULL, LTRT}, 1042/*SC*/ {PULU, PUSU, PUSU, PURU, PURU, PUSU, PURU, NULL, NULL, LSRS, NULL, LTRT}, 1043/*!U*/ {PTLT, NULL, NULL, NULL, NULL, NULL, NULL, PTLT, LTPT, LSRS, NULL, LTRT}, 1044/*!T*/ {LTRT, NULL, NULL, NULL, NULL, NULL, NULL, PTLT, LTRT, LSRS, NULL, LTRT}, 1045/*HT*/ {LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, NULL, LSRS}, 1046/*PR*/ {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}, 1047/*PR*/ {LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LSRS, NULL, LTRT}, 1048}; 1049 1050// The actual tests that exercise all the various configurations. 1051// Test names are of the form P2PTransportChannelTest_TestOPENToNAT_FULL_CONE 1052#define P2P_TEST_DECLARATION(x, y, z) \ 1053 TEST_F(P2PTransportChannelTest, z##Test##x##To##y) { \ 1054 ConfigureEndpoints(x, y, PORTALLOCATOR_ENABLE_SHARED_SOCKET, \ 1055 PORTALLOCATOR_ENABLE_SHARED_SOCKET); \ 1056 if (kMatrixSharedSocketAsIce[x][y] != NULL) \ 1057 Test(*kMatrixSharedSocketAsIce[x][y]); \ 1058 else \ 1059 LOG(LS_WARNING) << "Not yet implemented"; \ 1060 } 1061 1062#define P2P_TEST(x, y) \ 1063 P2P_TEST_DECLARATION(x, y,) 1064 1065#define FLAKY_P2P_TEST(x, y) \ 1066 P2P_TEST_DECLARATION(x, y, DISABLED_) 1067 1068// TODO(holmer): Disabled due to randomly failing on webrtc buildbots. 1069// Issue: webrtc/2383 1070#define P2P_TEST_SET(x) \ 1071 P2P_TEST(x, OPEN) \ 1072 FLAKY_P2P_TEST(x, NAT_FULL_CONE) \ 1073 FLAKY_P2P_TEST(x, NAT_ADDR_RESTRICTED) \ 1074 FLAKY_P2P_TEST(x, NAT_PORT_RESTRICTED) \ 1075 P2P_TEST(x, NAT_SYMMETRIC) \ 1076 FLAKY_P2P_TEST(x, NAT_DOUBLE_CONE) \ 1077 P2P_TEST(x, NAT_SYMMETRIC_THEN_CONE) \ 1078 P2P_TEST(x, BLOCK_UDP) \ 1079 P2P_TEST(x, BLOCK_UDP_AND_INCOMING_TCP) \ 1080 P2P_TEST(x, BLOCK_ALL_BUT_OUTGOING_HTTP) \ 1081 P2P_TEST(x, PROXY_HTTPS) \ 1082 P2P_TEST(x, PROXY_SOCKS) 1083 1084#define FLAKY_P2P_TEST_SET(x) \ 1085 P2P_TEST(x, OPEN) \ 1086 P2P_TEST(x, NAT_FULL_CONE) \ 1087 P2P_TEST(x, NAT_ADDR_RESTRICTED) \ 1088 P2P_TEST(x, NAT_PORT_RESTRICTED) \ 1089 P2P_TEST(x, NAT_SYMMETRIC) \ 1090 P2P_TEST(x, NAT_DOUBLE_CONE) \ 1091 P2P_TEST(x, NAT_SYMMETRIC_THEN_CONE) \ 1092 P2P_TEST(x, BLOCK_UDP) \ 1093 P2P_TEST(x, BLOCK_UDP_AND_INCOMING_TCP) \ 1094 P2P_TEST(x, BLOCK_ALL_BUT_OUTGOING_HTTP) \ 1095 P2P_TEST(x, PROXY_HTTPS) \ 1096 P2P_TEST(x, PROXY_SOCKS) 1097 1098P2P_TEST_SET(OPEN) 1099P2P_TEST_SET(NAT_FULL_CONE) 1100P2P_TEST_SET(NAT_ADDR_RESTRICTED) 1101P2P_TEST_SET(NAT_PORT_RESTRICTED) 1102P2P_TEST_SET(NAT_SYMMETRIC) 1103P2P_TEST_SET(NAT_DOUBLE_CONE) 1104P2P_TEST_SET(NAT_SYMMETRIC_THEN_CONE) 1105P2P_TEST_SET(BLOCK_UDP) 1106P2P_TEST_SET(BLOCK_UDP_AND_INCOMING_TCP) 1107P2P_TEST_SET(BLOCK_ALL_BUT_OUTGOING_HTTP) 1108P2P_TEST_SET(PROXY_HTTPS) 1109P2P_TEST_SET(PROXY_SOCKS) 1110 1111// Test that we restart candidate allocation when local ufrag&pwd changed. 1112// Standard Ice protocol is used. 1113TEST_F(P2PTransportChannelTest, HandleUfragPwdChange) { 1114 ConfigureEndpoints(OPEN, OPEN, kDefaultPortAllocatorFlags, 1115 kDefaultPortAllocatorFlags); 1116 CreateChannels(1); 1117 TestHandleIceUfragPasswordChanged(); 1118 DestroyChannels(); 1119} 1120 1121// Test the operation of GetStats. 1122TEST_F(P2PTransportChannelTest, GetStats) { 1123 ConfigureEndpoints(OPEN, OPEN, kDefaultPortAllocatorFlags, 1124 kDefaultPortAllocatorFlags); 1125 CreateChannels(1); 1126 EXPECT_TRUE_WAIT_MARGIN(ep1_ch1()->receiving() && ep1_ch1()->writable() && 1127 ep2_ch1()->receiving() && ep2_ch1()->writable(), 1128 1000, 1000); 1129 TestSendRecv(1); 1130 cricket::ConnectionInfos infos; 1131 ASSERT_TRUE(ep1_ch1()->GetStats(&infos)); 1132 ASSERT_TRUE(infos.size() >= 1); 1133 cricket::ConnectionInfo* best_conn_info = nullptr; 1134 for (cricket::ConnectionInfo& info : infos) { 1135 if (info.best_connection) { 1136 best_conn_info = &info; 1137 break; 1138 } 1139 } 1140 ASSERT_TRUE(best_conn_info != nullptr); 1141 EXPECT_TRUE(best_conn_info->new_connection); 1142 EXPECT_TRUE(best_conn_info->receiving); 1143 EXPECT_TRUE(best_conn_info->writable); 1144 EXPECT_FALSE(best_conn_info->timeout); 1145 EXPECT_EQ(10U, best_conn_info->sent_total_packets); 1146 EXPECT_EQ(0U, best_conn_info->sent_discarded_packets); 1147 EXPECT_EQ(10 * 36U, best_conn_info->sent_total_bytes); 1148 EXPECT_EQ(10 * 36U, best_conn_info->recv_total_bytes); 1149 EXPECT_GT(best_conn_info->rtt, 0U); 1150 DestroyChannels(); 1151} 1152 1153// Test that we properly create a connection on a STUN ping from unknown address 1154// when the signaling is slow. 1155TEST_F(P2PTransportChannelTest, PeerReflexiveCandidateBeforeSignaling) { 1156 ConfigureEndpoints(OPEN, OPEN, kDefaultPortAllocatorFlags, 1157 kDefaultPortAllocatorFlags); 1158 // Emulate no remote credentials coming in. 1159 set_clear_remote_candidates_ufrag_pwd(false); 1160 CreateChannels(1); 1161 // Only have remote credentials come in for ep2, not ep1. 1162 ep2_ch1()->SetRemoteIceCredentials(kIceUfrag[3], kIcePwd[3]); 1163 1164 // Pause sending ep2's candidates to ep1 until ep1 receives the peer reflexive 1165 // candidate. 1166 PauseCandidates(1); 1167 1168 // The caller should have the best connection connected to the peer reflexive 1169 // candidate. 1170 const cricket::Connection* best_connection = NULL; 1171 WAIT((best_connection = ep1_ch1()->best_connection()) != NULL, 2000); 1172 EXPECT_EQ("prflx", ep1_ch1()->best_connection()->remote_candidate().type()); 1173 1174 // Because we don't have a remote pwd, we don't ping yet. 1175 EXPECT_EQ(kIceUfrag[1], 1176 ep1_ch1()->best_connection()->remote_candidate().username()); 1177 EXPECT_EQ("", ep1_ch1()->best_connection()->remote_candidate().password()); 1178 EXPECT_TRUE(nullptr == ep1_ch1()->FindNextPingableConnection()); 1179 1180 ep1_ch1()->SetRemoteIceCredentials(kIceUfrag[1], kIcePwd[1]); 1181 ResumeCandidates(1); 1182 1183 EXPECT_EQ(kIcePwd[1], 1184 ep1_ch1()->best_connection()->remote_candidate().password()); 1185 EXPECT_TRUE(nullptr != ep1_ch1()->FindNextPingableConnection()); 1186 1187 WAIT(ep2_ch1()->best_connection() != NULL, 2000); 1188 // Verify ep1's best connection is updated to use the 'local' candidate. 1189 EXPECT_EQ_WAIT( 1190 "local", 1191 ep1_ch1()->best_connection()->remote_candidate().type(), 1192 2000); 1193 EXPECT_EQ(best_connection, ep1_ch1()->best_connection()); 1194 DestroyChannels(); 1195} 1196 1197// Test that we properly create a connection on a STUN ping from unknown address 1198// when the signaling is slow and the end points are behind NAT. 1199TEST_F(P2PTransportChannelTest, PeerReflexiveCandidateBeforeSignalingWithNAT) { 1200 ConfigureEndpoints(OPEN, NAT_SYMMETRIC, kDefaultPortAllocatorFlags, 1201 kDefaultPortAllocatorFlags); 1202 // Emulate no remote credentials coming in. 1203 set_clear_remote_candidates_ufrag_pwd(false); 1204 CreateChannels(1); 1205 // Only have remote credentials come in for ep2, not ep1. 1206 ep2_ch1()->SetRemoteIceCredentials(kIceUfrag[3], kIcePwd[3]); 1207 // Pause sending ep2's candidates to ep1 until ep1 receives the peer reflexive 1208 // candidate. 1209 PauseCandidates(1); 1210 1211 // The caller should have the best connection connected to the peer reflexive 1212 // candidate. 1213 WAIT(ep1_ch1()->best_connection() != NULL, 2000); 1214 EXPECT_EQ("prflx", ep1_ch1()->best_connection()->remote_candidate().type()); 1215 1216 // Because we don't have a remote pwd, we don't ping yet. 1217 EXPECT_EQ(kIceUfrag[1], 1218 ep1_ch1()->best_connection()->remote_candidate().username()); 1219 EXPECT_EQ("", ep1_ch1()->best_connection()->remote_candidate().password()); 1220 EXPECT_TRUE(nullptr == ep1_ch1()->FindNextPingableConnection()); 1221 1222 ep1_ch1()->SetRemoteIceCredentials(kIceUfrag[1], kIcePwd[1]); 1223 ResumeCandidates(1); 1224 1225 EXPECT_EQ(kIcePwd[1], 1226 ep1_ch1()->best_connection()->remote_candidate().password()); 1227 EXPECT_TRUE(nullptr != ep1_ch1()->FindNextPingableConnection()); 1228 1229 const cricket::Connection* best_connection = NULL; 1230 WAIT((best_connection = ep2_ch1()->best_connection()) != NULL, 2000); 1231 1232 // Wait to verify the connection is not culled. 1233 WAIT(ep1_ch1()->writable(), 2000); 1234 EXPECT_EQ(ep2_ch1()->best_connection(), best_connection); 1235 EXPECT_EQ("prflx", ep1_ch1()->best_connection()->remote_candidate().type()); 1236 DestroyChannels(); 1237} 1238 1239// Test that if remote candidates don't have ufrag and pwd, we still work. 1240TEST_F(P2PTransportChannelTest, RemoteCandidatesWithoutUfragPwd) { 1241 set_clear_remote_candidates_ufrag_pwd(true); 1242 ConfigureEndpoints(OPEN, OPEN, kDefaultPortAllocatorFlags, 1243 kDefaultPortAllocatorFlags); 1244 CreateChannels(1); 1245 const cricket::Connection* best_connection = NULL; 1246 // Wait until the callee's connections are created. 1247 WAIT((best_connection = ep2_ch1()->best_connection()) != NULL, 1000); 1248 // Wait to see if they get culled; they shouldn't. 1249 WAIT(ep2_ch1()->best_connection() != best_connection, 1000); 1250 EXPECT_TRUE(ep2_ch1()->best_connection() == best_connection); 1251 DestroyChannels(); 1252} 1253 1254// Test that a host behind NAT cannot be reached when incoming_only 1255// is set to true. 1256TEST_F(P2PTransportChannelTest, IncomingOnlyBlocked) { 1257 ConfigureEndpoints(NAT_FULL_CONE, OPEN, kDefaultPortAllocatorFlags, 1258 kDefaultPortAllocatorFlags); 1259 1260 SetAllocatorFlags(0, kOnlyLocalPorts); 1261 CreateChannels(1); 1262 ep1_ch1()->set_incoming_only(true); 1263 1264 // Pump for 1 second and verify that the channels are not connected. 1265 rtc::Thread::Current()->ProcessMessages(1000); 1266 1267 EXPECT_FALSE(ep1_ch1()->receiving()); 1268 EXPECT_FALSE(ep1_ch1()->writable()); 1269 EXPECT_FALSE(ep2_ch1()->receiving()); 1270 EXPECT_FALSE(ep2_ch1()->writable()); 1271 1272 DestroyChannels(); 1273} 1274 1275// Test that a peer behind NAT can connect to a peer that has 1276// incoming_only flag set. 1277TEST_F(P2PTransportChannelTest, IncomingOnlyOpen) { 1278 ConfigureEndpoints(OPEN, NAT_FULL_CONE, kDefaultPortAllocatorFlags, 1279 kDefaultPortAllocatorFlags); 1280 1281 SetAllocatorFlags(0, kOnlyLocalPorts); 1282 CreateChannels(1); 1283 ep1_ch1()->set_incoming_only(true); 1284 1285 EXPECT_TRUE_WAIT_MARGIN(ep1_ch1() != NULL && ep2_ch1() != NULL && 1286 ep1_ch1()->receiving() && ep1_ch1()->writable() && 1287 ep2_ch1()->receiving() && ep2_ch1()->writable(), 1288 1000, 1000); 1289 1290 DestroyChannels(); 1291} 1292 1293TEST_F(P2PTransportChannelTest, TestTcpConnectionsFromActiveToPassive) { 1294 AddAddress(0, kPublicAddrs[0]); 1295 AddAddress(1, kPublicAddrs[1]); 1296 1297 SetAllocationStepDelay(0, kMinimumStepDelay); 1298 SetAllocationStepDelay(1, kMinimumStepDelay); 1299 1300 int kOnlyLocalTcpPorts = cricket::PORTALLOCATOR_DISABLE_UDP | 1301 cricket::PORTALLOCATOR_DISABLE_STUN | 1302 cricket::PORTALLOCATOR_DISABLE_RELAY; 1303 // Disable all protocols except TCP. 1304 SetAllocatorFlags(0, kOnlyLocalTcpPorts); 1305 SetAllocatorFlags(1, kOnlyLocalTcpPorts); 1306 1307 SetAllowTcpListen(0, true); // actpass. 1308 SetAllowTcpListen(1, false); // active. 1309 1310 // Pause candidate so we could verify the candidate properties. 1311 PauseCandidates(0); 1312 PauseCandidates(1); 1313 CreateChannels(1); 1314 1315 // Verify tcp candidates. 1316 VerifySavedTcpCandidates(0, cricket::TCPTYPE_PASSIVE_STR); 1317 VerifySavedTcpCandidates(1, cricket::TCPTYPE_ACTIVE_STR); 1318 1319 // Resume candidates. 1320 ResumeCandidates(0); 1321 ResumeCandidates(1); 1322 1323 EXPECT_TRUE_WAIT(ep1_ch1()->receiving() && ep1_ch1()->writable() && 1324 ep2_ch1()->receiving() && ep2_ch1()->writable(), 1325 1000); 1326 EXPECT_TRUE( 1327 ep1_ch1()->best_connection() && ep2_ch1()->best_connection() && 1328 LocalCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[0]) && 1329 RemoteCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[1])); 1330 1331 TestSendRecv(1); 1332 DestroyChannels(); 1333} 1334 1335TEST_F(P2PTransportChannelTest, TestIceRoleConflict) { 1336 AddAddress(0, kPublicAddrs[0]); 1337 AddAddress(1, kPublicAddrs[1]); 1338 TestSignalRoleConflict(); 1339} 1340 1341// Tests that the ice configs (protocol, tiebreaker and role) can be passed 1342// down to ports. 1343TEST_F(P2PTransportChannelTest, TestIceConfigWillPassDownToPort) { 1344 AddAddress(0, kPublicAddrs[0]); 1345 AddAddress(1, kPublicAddrs[1]); 1346 1347 SetIceRole(0, cricket::ICEROLE_CONTROLLING); 1348 SetIceTiebreaker(0, kTiebreaker1); 1349 SetIceRole(1, cricket::ICEROLE_CONTROLLING); 1350 SetIceTiebreaker(1, kTiebreaker2); 1351 1352 CreateChannels(1); 1353 1354 EXPECT_EQ_WAIT(2u, ep1_ch1()->ports().size(), 1000); 1355 1356 const std::vector<cricket::PortInterface *> ports_before = ep1_ch1()->ports(); 1357 for (size_t i = 0; i < ports_before.size(); ++i) { 1358 EXPECT_EQ(cricket::ICEROLE_CONTROLLING, ports_before[i]->GetIceRole()); 1359 EXPECT_EQ(kTiebreaker1, ports_before[i]->IceTiebreaker()); 1360 } 1361 1362 ep1_ch1()->SetIceRole(cricket::ICEROLE_CONTROLLED); 1363 ep1_ch1()->SetIceTiebreaker(kTiebreaker2); 1364 1365 const std::vector<cricket::PortInterface *> ports_after = ep1_ch1()->ports(); 1366 for (size_t i = 0; i < ports_after.size(); ++i) { 1367 EXPECT_EQ(cricket::ICEROLE_CONTROLLED, ports_before[i]->GetIceRole()); 1368 // SetIceTiebreaker after Connect() has been called will fail. So expect the 1369 // original value. 1370 EXPECT_EQ(kTiebreaker1, ports_before[i]->IceTiebreaker()); 1371 } 1372 1373 EXPECT_TRUE_WAIT(ep1_ch1()->receiving() && 1374 ep1_ch1()->writable() && 1375 ep2_ch1()->receiving() && 1376 ep2_ch1()->writable(), 1377 1000); 1378 1379 EXPECT_TRUE(ep1_ch1()->best_connection() && 1380 ep2_ch1()->best_connection()); 1381 1382 TestSendRecv(1); 1383 DestroyChannels(); 1384} 1385 1386// Verify that we can set DSCP value and retrieve properly from P2PTC. 1387TEST_F(P2PTransportChannelTest, TestDefaultDscpValue) { 1388 AddAddress(0, kPublicAddrs[0]); 1389 AddAddress(1, kPublicAddrs[1]); 1390 1391 CreateChannels(1); 1392 EXPECT_EQ(rtc::DSCP_NO_CHANGE, 1393 GetEndpoint(0)->cd1_.ch_->DefaultDscpValue()); 1394 EXPECT_EQ(rtc::DSCP_NO_CHANGE, 1395 GetEndpoint(1)->cd1_.ch_->DefaultDscpValue()); 1396 GetEndpoint(0)->cd1_.ch_->SetOption( 1397 rtc::Socket::OPT_DSCP, rtc::DSCP_CS6); 1398 GetEndpoint(1)->cd1_.ch_->SetOption( 1399 rtc::Socket::OPT_DSCP, rtc::DSCP_CS6); 1400 EXPECT_EQ(rtc::DSCP_CS6, 1401 GetEndpoint(0)->cd1_.ch_->DefaultDscpValue()); 1402 EXPECT_EQ(rtc::DSCP_CS6, 1403 GetEndpoint(1)->cd1_.ch_->DefaultDscpValue()); 1404 GetEndpoint(0)->cd1_.ch_->SetOption( 1405 rtc::Socket::OPT_DSCP, rtc::DSCP_AF41); 1406 GetEndpoint(1)->cd1_.ch_->SetOption( 1407 rtc::Socket::OPT_DSCP, rtc::DSCP_AF41); 1408 EXPECT_EQ(rtc::DSCP_AF41, 1409 GetEndpoint(0)->cd1_.ch_->DefaultDscpValue()); 1410 EXPECT_EQ(rtc::DSCP_AF41, 1411 GetEndpoint(1)->cd1_.ch_->DefaultDscpValue()); 1412} 1413 1414// Verify IPv6 connection is preferred over IPv4. 1415TEST_F(P2PTransportChannelTest, TestIPv6Connections) { 1416 AddAddress(0, kIPv6PublicAddrs[0]); 1417 AddAddress(0, kPublicAddrs[0]); 1418 AddAddress(1, kIPv6PublicAddrs[1]); 1419 AddAddress(1, kPublicAddrs[1]); 1420 1421 SetAllocationStepDelay(0, kMinimumStepDelay); 1422 SetAllocationStepDelay(1, kMinimumStepDelay); 1423 1424 // Enable IPv6 1425 SetAllocatorFlags(0, cricket::PORTALLOCATOR_ENABLE_IPV6); 1426 SetAllocatorFlags(1, cricket::PORTALLOCATOR_ENABLE_IPV6); 1427 1428 CreateChannels(1); 1429 1430 EXPECT_TRUE_WAIT(ep1_ch1()->receiving() && ep1_ch1()->writable() && 1431 ep2_ch1()->receiving() && ep2_ch1()->writable(), 1432 1000); 1433 EXPECT_TRUE( 1434 ep1_ch1()->best_connection() && ep2_ch1()->best_connection() && 1435 LocalCandidate(ep1_ch1())->address().EqualIPs(kIPv6PublicAddrs[0]) && 1436 RemoteCandidate(ep1_ch1())->address().EqualIPs(kIPv6PublicAddrs[1])); 1437 1438 TestSendRecv(1); 1439 DestroyChannels(); 1440} 1441 1442// Testing forceful TURN connections. 1443TEST_F(P2PTransportChannelTest, TestForceTurn) { 1444 ConfigureEndpoints( 1445 NAT_PORT_RESTRICTED, NAT_SYMMETRIC, 1446 kDefaultPortAllocatorFlags | cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET, 1447 kDefaultPortAllocatorFlags | cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET); 1448 set_force_relay(true); 1449 1450 SetAllocationStepDelay(0, kMinimumStepDelay); 1451 SetAllocationStepDelay(1, kMinimumStepDelay); 1452 1453 CreateChannels(1); 1454 1455 EXPECT_TRUE_WAIT(ep1_ch1()->receiving() && ep1_ch1()->writable() && 1456 ep2_ch1()->receiving() && ep2_ch1()->writable(), 1457 2000); 1458 1459 EXPECT_TRUE(ep1_ch1()->best_connection() && 1460 ep2_ch1()->best_connection()); 1461 1462 EXPECT_EQ("relay", RemoteCandidate(ep1_ch1())->type()); 1463 EXPECT_EQ("relay", LocalCandidate(ep1_ch1())->type()); 1464 EXPECT_EQ("relay", RemoteCandidate(ep2_ch1())->type()); 1465 EXPECT_EQ("relay", LocalCandidate(ep2_ch1())->type()); 1466 1467 TestSendRecv(1); 1468 DestroyChannels(); 1469} 1470 1471// Test that if continual gathering is set to true, ICE gathering state will 1472// not change to "Complete", and vice versa. 1473TEST_F(P2PTransportChannelTest, TestContinualGathering) { 1474 ConfigureEndpoints(OPEN, OPEN, kDefaultPortAllocatorFlags, 1475 kDefaultPortAllocatorFlags); 1476 SetAllocationStepDelay(0, kDefaultStepDelay); 1477 SetAllocationStepDelay(1, kDefaultStepDelay); 1478 CreateChannels(1); 1479 cricket::IceConfig config = CreateIceConfig(1000, true); 1480 ep1_ch1()->SetIceConfig(config); 1481 // By default, ep2 does not gather continually. 1482 1483 EXPECT_TRUE_WAIT_MARGIN(ep1_ch1() != NULL && ep2_ch1() != NULL && 1484 ep1_ch1()->receiving() && ep1_ch1()->writable() && 1485 ep2_ch1()->receiving() && ep2_ch1()->writable(), 1486 1000, 1000); 1487 WAIT(cricket::IceGatheringState::kIceGatheringComplete == 1488 ep1_ch1()->gathering_state(), 1489 1000); 1490 EXPECT_EQ(cricket::IceGatheringState::kIceGatheringGathering, 1491 ep1_ch1()->gathering_state()); 1492 // By now, ep2 should have completed gathering. 1493 EXPECT_EQ(cricket::IceGatheringState::kIceGatheringComplete, 1494 ep2_ch1()->gathering_state()); 1495 1496 DestroyChannels(); 1497} 1498 1499// Test what happens when we have 2 users behind the same NAT. This can lead 1500// to interesting behavior because the STUN server will only give out the 1501// address of the outermost NAT. 1502class P2PTransportChannelSameNatTest : public P2PTransportChannelTestBase { 1503 protected: 1504 void ConfigureEndpoints(Config nat_type, Config config1, Config config2) { 1505 ASSERT(nat_type >= NAT_FULL_CONE && nat_type <= NAT_SYMMETRIC); 1506 rtc::NATSocketServer::Translator* outer_nat = 1507 nat()->AddTranslator(kPublicAddrs[0], kNatAddrs[0], 1508 static_cast<rtc::NATType>(nat_type - NAT_FULL_CONE)); 1509 ConfigureEndpoint(outer_nat, 0, config1); 1510 ConfigureEndpoint(outer_nat, 1, config2); 1511 } 1512 void ConfigureEndpoint(rtc::NATSocketServer::Translator* nat, 1513 int endpoint, Config config) { 1514 ASSERT(config <= NAT_SYMMETRIC); 1515 if (config == OPEN) { 1516 AddAddress(endpoint, kPrivateAddrs[endpoint]); 1517 nat->AddClient(kPrivateAddrs[endpoint]); 1518 } else { 1519 AddAddress(endpoint, kCascadedPrivateAddrs[endpoint]); 1520 nat->AddTranslator(kPrivateAddrs[endpoint], kCascadedNatAddrs[endpoint], 1521 static_cast<rtc::NATType>(config - NAT_FULL_CONE))->AddClient( 1522 kCascadedPrivateAddrs[endpoint]); 1523 } 1524 } 1525}; 1526 1527TEST_F(P2PTransportChannelSameNatTest, TestConesBehindSameCone) { 1528 ConfigureEndpoints(NAT_FULL_CONE, NAT_FULL_CONE, NAT_FULL_CONE); 1529 Test(P2PTransportChannelTestBase::Result( 1530 "prflx", "udp", "stun", "udp", "stun", "udp", "prflx", "udp", 1000)); 1531} 1532 1533// Test what happens when we have multiple available pathways. 1534// In the future we will try different RTTs and configs for the different 1535// interfaces, so that we can simulate a user with Ethernet and VPN networks. 1536class P2PTransportChannelMultihomedTest : public P2PTransportChannelTestBase { 1537}; 1538 1539// Test that we can establish connectivity when both peers are multihomed. 1540TEST_F(P2PTransportChannelMultihomedTest, DISABLED_TestBasic) { 1541 AddAddress(0, kPublicAddrs[0]); 1542 AddAddress(0, kAlternateAddrs[0]); 1543 AddAddress(1, kPublicAddrs[1]); 1544 AddAddress(1, kAlternateAddrs[1]); 1545 Test(kLocalUdpToLocalUdp); 1546} 1547 1548// Test that we can quickly switch links if an interface goes down. 1549// The controlled side has two interfaces and one will die. 1550TEST_F(P2PTransportChannelMultihomedTest, TestFailoverControlledSide) { 1551 AddAddress(0, kPublicAddrs[0]); 1552 // Adding alternate address will make sure |kPublicAddrs| has the higher 1553 // priority than others. This is due to FakeNetwork::AddInterface method. 1554 AddAddress(1, kAlternateAddrs[1]); 1555 AddAddress(1, kPublicAddrs[1]); 1556 1557 // Use only local ports for simplicity. 1558 SetAllocatorFlags(0, kOnlyLocalPorts); 1559 SetAllocatorFlags(1, kOnlyLocalPorts); 1560 1561 // Create channels and let them go writable, as usual. 1562 CreateChannels(1); 1563 1564 EXPECT_TRUE_WAIT_MARGIN(ep1_ch1()->receiving() && ep1_ch1()->writable() && 1565 ep2_ch1()->receiving() && ep2_ch1()->writable(), 1566 1000, 1000); 1567 EXPECT_TRUE( 1568 ep1_ch1()->best_connection() && ep2_ch1()->best_connection() && 1569 LocalCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[0]) && 1570 RemoteCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[1])); 1571 1572 // Make the receiving timeout shorter for testing. 1573 cricket::IceConfig config = CreateIceConfig(1000, false); 1574 ep1_ch1()->SetIceConfig(config); 1575 ep2_ch1()->SetIceConfig(config); 1576 1577 // Blackhole any traffic to or from the public addrs. 1578 LOG(LS_INFO) << "Failing over..."; 1579 fw()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, kPublicAddrs[1]); 1580 // The best connections will switch, so keep references to them. 1581 const cricket::Connection* best_connection1 = ep1_ch1()->best_connection(); 1582 const cricket::Connection* best_connection2 = ep2_ch1()->best_connection(); 1583 // We should detect loss of receiving within 1 second or so. 1584 EXPECT_TRUE_WAIT( 1585 !best_connection1->receiving() && !best_connection2->receiving(), 3000); 1586 1587 // We should switch over to use the alternate addr immediately on both sides 1588 // when we are not receiving. 1589 EXPECT_TRUE_WAIT( 1590 ep1_ch1()->best_connection()->receiving() && 1591 ep2_ch1()->best_connection()->receiving(), 1000); 1592 EXPECT_TRUE(LocalCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[0])); 1593 EXPECT_TRUE( 1594 RemoteCandidate(ep1_ch1())->address().EqualIPs(kAlternateAddrs[1])); 1595 EXPECT_TRUE( 1596 LocalCandidate(ep2_ch1())->address().EqualIPs(kAlternateAddrs[1])); 1597 1598 DestroyChannels(); 1599} 1600 1601// Test that we can quickly switch links if an interface goes down. 1602// The controlling side has two interfaces and one will die. 1603TEST_F(P2PTransportChannelMultihomedTest, TestFailoverControllingSide) { 1604 // Adding alternate address will make sure |kPublicAddrs| has the higher 1605 // priority than others. This is due to FakeNetwork::AddInterface method. 1606 AddAddress(0, kAlternateAddrs[0]); 1607 AddAddress(0, kPublicAddrs[0]); 1608 AddAddress(1, kPublicAddrs[1]); 1609 1610 // Use only local ports for simplicity. 1611 SetAllocatorFlags(0, kOnlyLocalPorts); 1612 SetAllocatorFlags(1, kOnlyLocalPorts); 1613 1614 // Create channels and let them go writable, as usual. 1615 CreateChannels(1); 1616 EXPECT_TRUE_WAIT_MARGIN(ep1_ch1()->receiving() && ep1_ch1()->writable() && 1617 ep2_ch1()->receiving() && ep2_ch1()->writable(), 1618 1000, 1000); 1619 EXPECT_TRUE( 1620 ep1_ch1()->best_connection() && ep2_ch1()->best_connection() && 1621 LocalCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[0]) && 1622 RemoteCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[1])); 1623 1624 // Make the receiving timeout shorter for testing. 1625 cricket::IceConfig config = CreateIceConfig(1000, false); 1626 ep1_ch1()->SetIceConfig(config); 1627 ep2_ch1()->SetIceConfig(config); 1628 1629 // Blackhole any traffic to or from the public addrs. 1630 LOG(LS_INFO) << "Failing over..."; 1631 fw()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, kPublicAddrs[0]); 1632 // The best connections will switch, so keep references to them. 1633 const cricket::Connection* best_connection1 = ep1_ch1()->best_connection(); 1634 const cricket::Connection* best_connection2 = ep2_ch1()->best_connection(); 1635 // We should detect loss of receiving within 1 second or so. 1636 EXPECT_TRUE_WAIT( 1637 !best_connection1->receiving() && !best_connection2->receiving(), 3000); 1638 1639 // We should switch over to use the alternate addr immediately on both sides 1640 // when we are not receiving. 1641 EXPECT_TRUE_WAIT( 1642 ep1_ch1()->best_connection()->receiving() && 1643 ep2_ch1()->best_connection()->receiving(), 1000); 1644 EXPECT_TRUE( 1645 LocalCandidate(ep1_ch1())->address().EqualIPs(kAlternateAddrs[0])); 1646 EXPECT_TRUE(RemoteCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[1])); 1647 EXPECT_TRUE( 1648 RemoteCandidate(ep2_ch1())->address().EqualIPs(kAlternateAddrs[0])); 1649 1650 DestroyChannels(); 1651} 1652 1653// Test that the backup connection is pinged at a rate no faster than 1654// what was configured. 1655TEST_F(P2PTransportChannelMultihomedTest, TestPingBackupConnectionRate) { 1656 AddAddress(0, kPublicAddrs[0]); 1657 // Adding alternate address will make sure |kPublicAddrs| has the higher 1658 // priority than others. This is due to FakeNetwork::AddInterface method. 1659 AddAddress(1, kAlternateAddrs[1]); 1660 AddAddress(1, kPublicAddrs[1]); 1661 1662 // Use only local ports for simplicity. 1663 SetAllocatorFlags(0, kOnlyLocalPorts); 1664 SetAllocatorFlags(1, kOnlyLocalPorts); 1665 1666 // Create channels and let them go writable, as usual. 1667 CreateChannels(1); 1668 EXPECT_TRUE_WAIT_MARGIN(ep1_ch1()->receiving() && ep1_ch1()->writable() && 1669 ep2_ch1()->receiving() && ep2_ch1()->writable(), 1670 1000, 1000); 1671 int backup_ping_interval = 2000; 1672 ep2_ch1()->SetIceConfig(CreateIceConfig(2000, false, backup_ping_interval)); 1673 // After the state becomes COMPLETED, the backup connection will be pinged 1674 // once every |backup_ping_interval| milliseconds. 1675 ASSERT_TRUE_WAIT(ep2_ch1()->GetState() == cricket::STATE_COMPLETED, 1000); 1676 const std::vector<cricket::Connection*>& connections = 1677 ep2_ch1()->connections(); 1678 ASSERT_EQ(2U, connections.size()); 1679 cricket::Connection* backup_conn = connections[1]; 1680 EXPECT_TRUE_WAIT(backup_conn->writable(), 3000); 1681 uint32_t last_ping_response_ms = backup_conn->last_ping_response_received(); 1682 EXPECT_TRUE_WAIT( 1683 last_ping_response_ms < backup_conn->last_ping_response_received(), 5000); 1684 int time_elapsed = 1685 backup_conn->last_ping_response_received() - last_ping_response_ms; 1686 LOG(LS_INFO) << "Time elapsed: " << time_elapsed; 1687 EXPECT_GE(time_elapsed, backup_ping_interval); 1688} 1689 1690TEST_F(P2PTransportChannelMultihomedTest, TestGetState) { 1691 AddAddress(0, kAlternateAddrs[0]); 1692 AddAddress(0, kPublicAddrs[0]); 1693 AddAddress(1, kPublicAddrs[1]); 1694 // Create channels and let them go writable, as usual. 1695 CreateChannels(1); 1696 1697 // Both transport channels will reach STATE_COMPLETED quickly. 1698 EXPECT_EQ_WAIT(cricket::TransportChannelState::STATE_COMPLETED, 1699 ep1_ch1()->GetState(), 1000); 1700 EXPECT_EQ_WAIT(cricket::TransportChannelState::STATE_COMPLETED, 1701 ep2_ch1()->GetState(), 1000); 1702} 1703 1704/* 1705 1706TODO(pthatcher): Once have a way to handle network interfaces changes 1707without signalling an ICE restart, put a test like this back. In the 1708mean time, this test only worked for GICE. With ICE, it's currently 1709not possible without an ICE restart. 1710 1711// Test that we can switch links in a coordinated fashion. 1712TEST_F(P2PTransportChannelMultihomedTest, TestDrain) { 1713 AddAddress(0, kPublicAddrs[0]); 1714 AddAddress(1, kPublicAddrs[1]); 1715 // Use only local ports for simplicity. 1716 SetAllocatorFlags(0, kOnlyLocalPorts); 1717 SetAllocatorFlags(1, kOnlyLocalPorts); 1718 1719 // Create channels and let them go writable, as usual. 1720 CreateChannels(1); 1721 EXPECT_TRUE_WAIT(ep1_ch1()->receiving() && ep1_ch1()->writable() && 1722 ep2_ch1()->receiving() && ep2_ch1()->writable(), 1723 1000); 1724 EXPECT_TRUE( 1725 ep1_ch1()->best_connection() && ep2_ch1()->best_connection() && 1726 LocalCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[0]) && 1727 RemoteCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[1])); 1728 1729 1730 // Remove the public interface, add the alternate interface, and allocate 1731 // a new generation of candidates for the new interface (via 1732 // MaybeStartGathering()). 1733 LOG(LS_INFO) << "Draining..."; 1734 AddAddress(1, kAlternateAddrs[1]); 1735 RemoveAddress(1, kPublicAddrs[1]); 1736 ep2_ch1()->MaybeStartGathering(); 1737 1738 // We should switch over to use the alternate address after 1739 // an exchange of pings. 1740 EXPECT_TRUE_WAIT( 1741 ep1_ch1()->best_connection() && ep2_ch1()->best_connection() && 1742 LocalCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[0]) && 1743 RemoteCandidate(ep1_ch1())->address().EqualIPs(kAlternateAddrs[1]), 1744 3000); 1745 1746 DestroyChannels(); 1747} 1748 1749*/ 1750 1751// A collection of tests which tests a single P2PTransportChannel by sending 1752// pings. 1753class P2PTransportChannelPingTest : public testing::Test, 1754 public sigslot::has_slots<> { 1755 public: 1756 P2PTransportChannelPingTest() 1757 : pss_(new rtc::PhysicalSocketServer), 1758 vss_(new rtc::VirtualSocketServer(pss_.get())), 1759 ss_scope_(vss_.get()) {} 1760 1761 protected: 1762 void PrepareChannel(cricket::P2PTransportChannel* ch) { 1763 ch->SetIceRole(cricket::ICEROLE_CONTROLLING); 1764 ch->SetIceCredentials(kIceUfrag[0], kIcePwd[0]); 1765 ch->SetRemoteIceCredentials(kIceUfrag[1], kIcePwd[1]); 1766 } 1767 1768 cricket::Candidate CreateCandidate(const std::string& ip, 1769 int port, 1770 int priority, 1771 const std::string& ufrag = "") { 1772 cricket::Candidate c; 1773 c.set_address(rtc::SocketAddress(ip, port)); 1774 c.set_component(1); 1775 c.set_protocol(cricket::UDP_PROTOCOL_NAME); 1776 c.set_priority(priority); 1777 c.set_username(ufrag); 1778 return c; 1779 } 1780 1781 cricket::Connection* WaitForConnectionTo(cricket::P2PTransportChannel* ch, 1782 const std::string& ip, 1783 int port_num) { 1784 EXPECT_TRUE_WAIT(GetConnectionTo(ch, ip, port_num) != nullptr, 3000); 1785 return GetConnectionTo(ch, ip, port_num); 1786 } 1787 1788 cricket::Port* GetPort(cricket::P2PTransportChannel* ch) { 1789 if (ch->ports().empty()) { 1790 return nullptr; 1791 } 1792 return static_cast<cricket::Port*>(ch->ports()[0]); 1793 } 1794 1795 cricket::Connection* GetConnectionTo(cricket::P2PTransportChannel* ch, 1796 const std::string& ip, 1797 int port_num) { 1798 cricket::Port* port = GetPort(ch); 1799 if (!port) { 1800 return nullptr; 1801 } 1802 return port->GetConnection(rtc::SocketAddress(ip, port_num)); 1803 } 1804 1805 private: 1806 rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_; 1807 rtc::scoped_ptr<rtc::VirtualSocketServer> vss_; 1808 rtc::SocketServerScope ss_scope_; 1809}; 1810 1811TEST_F(P2PTransportChannelPingTest, TestTriggeredChecks) { 1812 cricket::FakePortAllocator pa(rtc::Thread::Current(), nullptr); 1813 cricket::P2PTransportChannel ch("trigger checks", 1, nullptr, &pa); 1814 PrepareChannel(&ch); 1815 ch.Connect(); 1816 ch.MaybeStartGathering(); 1817 ch.AddRemoteCandidate(CreateCandidate("1.1.1.1", 1, 1)); 1818 ch.AddRemoteCandidate(CreateCandidate("2.2.2.2", 2, 2)); 1819 1820 cricket::Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1); 1821 cricket::Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2); 1822 ASSERT_TRUE(conn1 != nullptr); 1823 ASSERT_TRUE(conn2 != nullptr); 1824 1825 // Before a triggered check, the first connection to ping is the 1826 // highest priority one. 1827 EXPECT_EQ(conn2, ch.FindNextPingableConnection()); 1828 1829 // Receiving a ping causes a triggered check which should make conn1 1830 // be pinged first instead of conn2, even though conn2 has a higher 1831 // priority. 1832 conn1->ReceivedPing(); 1833 EXPECT_EQ(conn1, ch.FindNextPingableConnection()); 1834} 1835 1836TEST_F(P2PTransportChannelPingTest, TestNoTriggeredChecksWhenWritable) { 1837 cricket::FakePortAllocator pa(rtc::Thread::Current(), nullptr); 1838 cricket::P2PTransportChannel ch("trigger checks", 1, nullptr, &pa); 1839 PrepareChannel(&ch); 1840 ch.Connect(); 1841 ch.MaybeStartGathering(); 1842 ch.AddRemoteCandidate(CreateCandidate("1.1.1.1", 1, 1)); 1843 ch.AddRemoteCandidate(CreateCandidate("2.2.2.2", 2, 2)); 1844 1845 cricket::Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1); 1846 cricket::Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2); 1847 ASSERT_TRUE(conn1 != nullptr); 1848 ASSERT_TRUE(conn2 != nullptr); 1849 1850 EXPECT_EQ(conn2, ch.FindNextPingableConnection()); 1851 conn1->ReceivedPingResponse(); 1852 ASSERT_TRUE(conn1->writable()); 1853 conn1->ReceivedPing(); 1854 1855 // Ping received, but the connection is already writable, so no 1856 // "triggered check" and conn2 is pinged before conn1 because it has 1857 // a higher priority. 1858 EXPECT_EQ(conn2, ch.FindNextPingableConnection()); 1859} 1860 1861// Test adding remote candidates with different ufrags. If a remote candidate 1862// is added with an old ufrag, it will be discarded. If it is added with a 1863// ufrag that was not seen before, it will be used to create connections 1864// although the ICE pwd in the remote candidate will be set when the ICE 1865// credentials arrive. If a remote candidate is added with the current ICE 1866// ufrag, its pwd and generation will be set properly. 1867TEST_F(P2PTransportChannelPingTest, TestAddRemoteCandidateWithVariousUfrags) { 1868 cricket::FakePortAllocator pa(rtc::Thread::Current(), nullptr); 1869 cricket::P2PTransportChannel ch("add candidate", 1, nullptr, &pa); 1870 PrepareChannel(&ch); 1871 ch.Connect(); 1872 ch.MaybeStartGathering(); 1873 // Add a candidate with a future ufrag. 1874 ch.AddRemoteCandidate(CreateCandidate("1.1.1.1", 1, 1, kIceUfrag[2])); 1875 cricket::Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1); 1876 ASSERT_TRUE(conn1 != nullptr); 1877 const cricket::Candidate& candidate = conn1->remote_candidate(); 1878 EXPECT_EQ(kIceUfrag[2], candidate.username()); 1879 EXPECT_TRUE(candidate.password().empty()); 1880 EXPECT_TRUE(ch.FindNextPingableConnection() == nullptr); 1881 1882 // Set the remote credentials with the "future" ufrag. 1883 // This should set the ICE pwd in the remote candidate of |conn1|, making 1884 // it pingable. 1885 ch.SetRemoteIceCredentials(kIceUfrag[2], kIcePwd[2]); 1886 EXPECT_EQ(kIceUfrag[2], candidate.username()); 1887 EXPECT_EQ(kIcePwd[2], candidate.password()); 1888 EXPECT_EQ(conn1, ch.FindNextPingableConnection()); 1889 1890 // Add a candidate with an old ufrag. No connection will be created. 1891 ch.AddRemoteCandidate(CreateCandidate("2.2.2.2", 2, 2, kIceUfrag[1])); 1892 rtc::Thread::Current()->ProcessMessages(500); 1893 EXPECT_TRUE(GetConnectionTo(&ch, "2.2.2.2", 2) == nullptr); 1894 1895 // Add a candidate with the current ufrag, its pwd and generation will be 1896 // assigned, even if the generation is not set. 1897 ch.AddRemoteCandidate(CreateCandidate("3.3.3.3", 3, 0, kIceUfrag[2])); 1898 cricket::Connection* conn3 = nullptr; 1899 ASSERT_TRUE_WAIT((conn3 = GetConnectionTo(&ch, "3.3.3.3", 3)) != nullptr, 1900 3000); 1901 const cricket::Candidate& new_candidate = conn3->remote_candidate(); 1902 EXPECT_EQ(kIcePwd[2], new_candidate.password()); 1903 EXPECT_EQ(1U, new_candidate.generation()); 1904 1905 // Check that the pwd of all remote candidates are properly assigned. 1906 for (const cricket::RemoteCandidate& candidate : ch.remote_candidates()) { 1907 EXPECT_TRUE(candidate.username() == kIceUfrag[1] || 1908 candidate.username() == kIceUfrag[2]); 1909 if (candidate.username() == kIceUfrag[1]) { 1910 EXPECT_EQ(kIcePwd[1], candidate.password()); 1911 } else if (candidate.username() == kIceUfrag[2]) { 1912 EXPECT_EQ(kIcePwd[2], candidate.password()); 1913 } 1914 } 1915} 1916 1917TEST_F(P2PTransportChannelPingTest, ConnectionResurrection) { 1918 cricket::FakePortAllocator pa(rtc::Thread::Current(), nullptr); 1919 cricket::P2PTransportChannel ch("connection resurrection", 1, nullptr, &pa); 1920 PrepareChannel(&ch); 1921 ch.Connect(); 1922 ch.MaybeStartGathering(); 1923 1924 // Create conn1 and keep track of original candidate priority. 1925 ch.AddRemoteCandidate(CreateCandidate("1.1.1.1", 1, 1)); 1926 cricket::Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1); 1927 ASSERT_TRUE(conn1 != nullptr); 1928 uint32_t remote_priority = conn1->remote_candidate().priority(); 1929 1930 // Create a higher priority candidate and make the connection 1931 // receiving/writable. This will prune conn1. 1932 ch.AddRemoteCandidate(CreateCandidate("2.2.2.2", 2, 2)); 1933 cricket::Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2); 1934 ASSERT_TRUE(conn2 != nullptr); 1935 conn2->ReceivedPing(); 1936 conn2->ReceivedPingResponse(); 1937 1938 // Wait for conn1 to be pruned. 1939 EXPECT_TRUE_WAIT(conn1->pruned(), 3000); 1940 // Destroy the connection to test SignalUnknownAddress. 1941 conn1->Destroy(); 1942 EXPECT_TRUE_WAIT(GetConnectionTo(&ch, "1.1.1.1", 1) == nullptr, 1000); 1943 1944 // Create a minimal STUN message with prflx priority. 1945 cricket::IceMessage request; 1946 request.SetType(cricket::STUN_BINDING_REQUEST); 1947 request.AddAttribute(new cricket::StunByteStringAttribute( 1948 cricket::STUN_ATTR_USERNAME, kIceUfrag[1])); 1949 uint32_t prflx_priority = cricket::ICE_TYPE_PREFERENCE_PRFLX << 24; 1950 request.AddAttribute(new cricket::StunUInt32Attribute( 1951 cricket::STUN_ATTR_PRIORITY, prflx_priority)); 1952 EXPECT_NE(prflx_priority, remote_priority); 1953 1954 cricket::Port* port = GetPort(&ch); 1955 // conn1 should be resurrected with original priority. 1956 port->SignalUnknownAddress(port, rtc::SocketAddress("1.1.1.1", 1), 1957 cricket::PROTO_UDP, &request, kIceUfrag[1], false); 1958 conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1); 1959 ASSERT_TRUE(conn1 != nullptr); 1960 EXPECT_EQ(conn1->remote_candidate().priority(), remote_priority); 1961 1962 // conn3, a real prflx connection, should have prflx priority. 1963 port->SignalUnknownAddress(port, rtc::SocketAddress("3.3.3.3", 1), 1964 cricket::PROTO_UDP, &request, kIceUfrag[1], false); 1965 cricket::Connection* conn3 = WaitForConnectionTo(&ch, "3.3.3.3", 1); 1966 ASSERT_TRUE(conn3 != nullptr); 1967 EXPECT_EQ(conn3->remote_candidate().priority(), prflx_priority); 1968} 1969 1970TEST_F(P2PTransportChannelPingTest, TestReceivingStateChange) { 1971 cricket::FakePortAllocator pa(rtc::Thread::Current(), nullptr); 1972 cricket::P2PTransportChannel ch("receiving state change", 1, nullptr, &pa); 1973 PrepareChannel(&ch); 1974 // Default receiving timeout and checking receiving delay should not be too 1975 // small. 1976 EXPECT_LE(1000, ch.receiving_timeout()); 1977 EXPECT_LE(200, ch.check_receiving_delay()); 1978 ch.SetIceConfig(CreateIceConfig(500, false)); 1979 EXPECT_EQ(500, ch.receiving_timeout()); 1980 EXPECT_EQ(50, ch.check_receiving_delay()); 1981 ch.Connect(); 1982 ch.MaybeStartGathering(); 1983 ch.AddRemoteCandidate(CreateCandidate("1.1.1.1", 1, 1)); 1984 cricket::Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1); 1985 ASSERT_TRUE(conn1 != nullptr); 1986 1987 conn1->ReceivedPing(); 1988 conn1->OnReadPacket("ABC", 3, rtc::CreatePacketTime(0)); 1989 EXPECT_TRUE_WAIT(ch.best_connection() != nullptr, 1000); 1990 EXPECT_TRUE_WAIT(ch.receiving(), 1000); 1991 EXPECT_TRUE_WAIT(!ch.receiving(), 1000); 1992} 1993 1994// The controlled side will select a connection as the "best connection" based 1995// on priority until the controlling side nominates a connection, at which 1996// point the controlled side will select that connection as the 1997// "best connection". 1998TEST_F(P2PTransportChannelPingTest, TestSelectConnectionBeforeNomination) { 1999 cricket::FakePortAllocator pa(rtc::Thread::Current(), nullptr); 2000 cricket::P2PTransportChannel ch("receiving state change", 1, nullptr, &pa); 2001 PrepareChannel(&ch); 2002 ch.SetIceRole(cricket::ICEROLE_CONTROLLED); 2003 ch.Connect(); 2004 ch.MaybeStartGathering(); 2005 ch.AddRemoteCandidate(CreateCandidate("1.1.1.1", 1, 1)); 2006 cricket::Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1); 2007 ASSERT_TRUE(conn1 != nullptr); 2008 EXPECT_EQ(conn1, ch.best_connection()); 2009 2010 // When a higher priority candidate comes in, the new connection is chosen 2011 // as the best connection. 2012 ch.AddRemoteCandidate(CreateCandidate("2.2.2.2", 2, 10)); 2013 cricket::Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2); 2014 ASSERT_TRUE(conn2 != nullptr); 2015 EXPECT_EQ(conn2, ch.best_connection()); 2016 2017 // If a stun request with use-candidate attribute arrives, the receiving 2018 // connection will be set as the best connection, even though 2019 // its priority is lower. 2020 ch.AddRemoteCandidate(CreateCandidate("3.3.3.3", 3, 1)); 2021 cricket::Connection* conn3 = WaitForConnectionTo(&ch, "3.3.3.3", 3); 2022 ASSERT_TRUE(conn3 != nullptr); 2023 // Because it has a lower priority, the best connection is still conn2. 2024 EXPECT_EQ(conn2, ch.best_connection()); 2025 conn3->ReceivedPingResponse(); // Become writable. 2026 // But if it is nominated via use_candidate, it is chosen as the best 2027 // connection. 2028 conn3->set_nominated(true); 2029 conn3->SignalNominated(conn3); 2030 EXPECT_EQ(conn3, ch.best_connection()); 2031 2032 // Even if another higher priority candidate arrives, 2033 // it will not be set as the best connection because the best connection 2034 // is nominated by the controlling side. 2035 ch.AddRemoteCandidate(CreateCandidate("4.4.4.4", 4, 100)); 2036 cricket::Connection* conn4 = WaitForConnectionTo(&ch, "4.4.4.4", 4); 2037 ASSERT_TRUE(conn4 != nullptr); 2038 EXPECT_EQ(conn3, ch.best_connection()); 2039 // But if it is nominated via use_candidate and writable, it will be set as 2040 // the best connection. 2041 conn4->set_nominated(true); 2042 conn4->SignalNominated(conn4); 2043 // Not switched yet because conn4 is not writable. 2044 EXPECT_EQ(conn3, ch.best_connection()); 2045 // The best connection switches after conn4 becomes writable. 2046 conn4->ReceivedPingResponse(); 2047 EXPECT_EQ(conn4, ch.best_connection()); 2048} 2049 2050// The controlled side will select a connection as the "best connection" based 2051// on requests from an unknown address before the controlling side nominates 2052// a connection, and will nominate a connection from an unknown address if the 2053// request contains the use_candidate attribute. Plus, it will also sends back 2054// a ping response and set the ICE pwd in the remote candidate appropriately. 2055TEST_F(P2PTransportChannelPingTest, TestSelectConnectionFromUnknownAddress) { 2056 cricket::FakePortAllocator pa(rtc::Thread::Current(), nullptr); 2057 cricket::P2PTransportChannel ch("receiving state change", 1, nullptr, &pa); 2058 PrepareChannel(&ch); 2059 ch.SetIceRole(cricket::ICEROLE_CONTROLLED); 2060 ch.Connect(); 2061 ch.MaybeStartGathering(); 2062 // A minimal STUN message with prflx priority. 2063 cricket::IceMessage request; 2064 request.SetType(cricket::STUN_BINDING_REQUEST); 2065 request.AddAttribute(new cricket::StunByteStringAttribute( 2066 cricket::STUN_ATTR_USERNAME, kIceUfrag[1])); 2067 uint32_t prflx_priority = cricket::ICE_TYPE_PREFERENCE_PRFLX << 24; 2068 request.AddAttribute(new cricket::StunUInt32Attribute( 2069 cricket::STUN_ATTR_PRIORITY, prflx_priority)); 2070 cricket::TestUDPPort* port = static_cast<cricket::TestUDPPort*>(GetPort(&ch)); 2071 port->SignalUnknownAddress(port, rtc::SocketAddress("1.1.1.1", 1), 2072 cricket::PROTO_UDP, &request, kIceUfrag[1], false); 2073 cricket::Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1); 2074 ASSERT_TRUE(conn1 != nullptr); 2075 EXPECT_TRUE(port->sent_binding_response()); 2076 EXPECT_EQ(conn1, ch.best_connection()); 2077 conn1->ReceivedPingResponse(); 2078 EXPECT_EQ(conn1, ch.best_connection()); 2079 port->set_sent_binding_response(false); 2080 2081 // Another connection is nominated via use_candidate. 2082 ch.AddRemoteCandidate(CreateCandidate("2.2.2.2", 2, 1)); 2083 cricket::Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2); 2084 ASSERT_TRUE(conn2 != nullptr); 2085 // Because it has a lower priority, the best connection is still conn1. 2086 EXPECT_EQ(conn1, ch.best_connection()); 2087 // When it is nominated via use_candidate and writable, it is chosen as the 2088 // best connection. 2089 conn2->ReceivedPingResponse(); // Become writable. 2090 conn2->set_nominated(true); 2091 conn2->SignalNominated(conn2); 2092 EXPECT_EQ(conn2, ch.best_connection()); 2093 2094 // Another request with unknown address, it will not be set as the best 2095 // connection because the best connection was nominated by the controlling 2096 // side. 2097 port->SignalUnknownAddress(port, rtc::SocketAddress("3.3.3.3", 3), 2098 cricket::PROTO_UDP, &request, kIceUfrag[1], false); 2099 cricket::Connection* conn3 = WaitForConnectionTo(&ch, "3.3.3.3", 3); 2100 ASSERT_TRUE(conn3 != nullptr); 2101 EXPECT_TRUE(port->sent_binding_response()); 2102 conn3->ReceivedPingResponse(); // Become writable. 2103 EXPECT_EQ(conn2, ch.best_connection()); 2104 port->set_sent_binding_response(false); 2105 2106 // However if the request contains use_candidate attribute, it will be 2107 // selected as the best connection. 2108 request.AddAttribute( 2109 new cricket::StunByteStringAttribute(cricket::STUN_ATTR_USE_CANDIDATE)); 2110 port->SignalUnknownAddress(port, rtc::SocketAddress("4.4.4.4", 4), 2111 cricket::PROTO_UDP, &request, kIceUfrag[1], false); 2112 cricket::Connection* conn4 = WaitForConnectionTo(&ch, "4.4.4.4", 4); 2113 ASSERT_TRUE(conn4 != nullptr); 2114 EXPECT_TRUE(port->sent_binding_response()); 2115 // conn4 is not the best connection yet because it is not writable. 2116 EXPECT_EQ(conn2, ch.best_connection()); 2117 conn4->ReceivedPingResponse(); // Become writable. 2118 EXPECT_EQ(conn4, ch.best_connection()); 2119 2120 // Test that the request from an unknown address contains a ufrag from an old 2121 // generation. 2122 port->set_sent_binding_response(false); 2123 ch.SetRemoteIceCredentials(kIceUfrag[2], kIcePwd[2]); 2124 ch.SetRemoteIceCredentials(kIceUfrag[3], kIcePwd[3]); 2125 port->SignalUnknownAddress(port, rtc::SocketAddress("5.5.5.5", 5), 2126 cricket::PROTO_UDP, &request, kIceUfrag[2], false); 2127 cricket::Connection* conn5 = WaitForConnectionTo(&ch, "5.5.5.5", 5); 2128 ASSERT_TRUE(conn5 != nullptr); 2129 EXPECT_TRUE(port->sent_binding_response()); 2130 EXPECT_EQ(kIcePwd[2], conn5->remote_candidate().password()); 2131} 2132 2133// The controlled side will select a connection as the "best connection" 2134// based on media received until the controlling side nominates a connection, 2135// at which point the controlled side will select that connection as 2136// the "best connection". 2137TEST_F(P2PTransportChannelPingTest, TestSelectConnectionBasedOnMediaReceived) { 2138 cricket::FakePortAllocator pa(rtc::Thread::Current(), nullptr); 2139 cricket::P2PTransportChannel ch("receiving state change", 1, nullptr, &pa); 2140 PrepareChannel(&ch); 2141 ch.SetIceRole(cricket::ICEROLE_CONTROLLED); 2142 ch.Connect(); 2143 ch.MaybeStartGathering(); 2144 ch.AddRemoteCandidate(CreateCandidate("1.1.1.1", 1, 10)); 2145 cricket::Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1); 2146 ASSERT_TRUE(conn1 != nullptr); 2147 EXPECT_EQ(conn1, ch.best_connection()); 2148 2149 // If a data packet is received on conn2, the best connection should 2150 // switch to conn2 because the controlled side must mirror the media path 2151 // chosen by the controlling side. 2152 ch.AddRemoteCandidate(CreateCandidate("2.2.2.2", 2, 1)); 2153 cricket::Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2); 2154 ASSERT_TRUE(conn2 != nullptr); 2155 conn2->ReceivedPing(); // Start receiving. 2156 // Do not switch because it is not writable. 2157 conn2->OnReadPacket("ABC", 3, rtc::CreatePacketTime(0)); 2158 EXPECT_EQ(conn1, ch.best_connection()); 2159 2160 conn2->ReceivedPingResponse(); // Become writable. 2161 // Switch because it is writable. 2162 conn2->OnReadPacket("DEF", 3, rtc::CreatePacketTime(0)); 2163 EXPECT_EQ(conn2, ch.best_connection()); 2164 2165 // Now another STUN message with an unknown address and use_candidate will 2166 // nominate the best connection. 2167 cricket::IceMessage request; 2168 request.SetType(cricket::STUN_BINDING_REQUEST); 2169 request.AddAttribute(new cricket::StunByteStringAttribute( 2170 cricket::STUN_ATTR_USERNAME, kIceUfrag[1])); 2171 uint32_t prflx_priority = cricket::ICE_TYPE_PREFERENCE_PRFLX << 24; 2172 request.AddAttribute(new cricket::StunUInt32Attribute( 2173 cricket::STUN_ATTR_PRIORITY, prflx_priority)); 2174 request.AddAttribute( 2175 new cricket::StunByteStringAttribute(cricket::STUN_ATTR_USE_CANDIDATE)); 2176 cricket::Port* port = GetPort(&ch); 2177 port->SignalUnknownAddress(port, rtc::SocketAddress("3.3.3.3", 3), 2178 cricket::PROTO_UDP, &request, kIceUfrag[1], false); 2179 cricket::Connection* conn3 = WaitForConnectionTo(&ch, "3.3.3.3", 3); 2180 ASSERT_TRUE(conn3 != nullptr); 2181 EXPECT_EQ(conn2, ch.best_connection()); // Not writable yet. 2182 conn3->ReceivedPingResponse(); // Become writable. 2183 EXPECT_EQ(conn3, ch.best_connection()); 2184 2185 // Now another data packet will not switch the best connection because the 2186 // best connection was nominated by the controlling side. 2187 conn2->ReceivedPing(); 2188 conn2->ReceivedPingResponse(); 2189 conn2->OnReadPacket("XYZ", 3, rtc::CreatePacketTime(0)); 2190 EXPECT_EQ(conn3, ch.best_connection()); 2191} 2192 2193// When the current best connection is strong, lower-priority connections will 2194// be pruned. Otherwise, lower-priority connections are kept. 2195TEST_F(P2PTransportChannelPingTest, TestDontPruneWhenWeak) { 2196 cricket::FakePortAllocator pa(rtc::Thread::Current(), nullptr); 2197 cricket::P2PTransportChannel ch("test channel", 1, nullptr, &pa); 2198 PrepareChannel(&ch); 2199 ch.SetIceRole(cricket::ICEROLE_CONTROLLED); 2200 ch.Connect(); 2201 ch.MaybeStartGathering(); 2202 ch.AddRemoteCandidate(CreateCandidate("1.1.1.1", 1, 1)); 2203 cricket::Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1); 2204 ASSERT_TRUE(conn1 != nullptr); 2205 EXPECT_EQ(conn1, ch.best_connection()); 2206 conn1->ReceivedPingResponse(); // Becomes writable and receiving 2207 2208 // When a higher-priority, nominated candidate comes in, the connections with 2209 // lower-priority are pruned. 2210 ch.AddRemoteCandidate(CreateCandidate("2.2.2.2", 2, 10)); 2211 cricket::Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2); 2212 ASSERT_TRUE(conn2 != nullptr); 2213 conn2->ReceivedPingResponse(); // Becomes writable and receiving 2214 conn2->set_nominated(true); 2215 conn2->SignalNominated(conn2); 2216 EXPECT_TRUE_WAIT(conn1->pruned(), 3000); 2217 2218 ch.SetIceConfig(CreateIceConfig(500, false)); 2219 // Wait until conn2 becomes not receiving. 2220 EXPECT_TRUE_WAIT(!conn2->receiving(), 3000); 2221 2222 ch.AddRemoteCandidate(CreateCandidate("3.3.3.3", 3, 1)); 2223 cricket::Connection* conn3 = WaitForConnectionTo(&ch, "3.3.3.3", 3); 2224 ASSERT_TRUE(conn3 != nullptr); 2225 // The best connection should still be conn2. Even through conn3 has lower 2226 // priority and is not receiving/writable, it is not pruned because the best 2227 // connection is not receiving. 2228 WAIT(conn3->pruned(), 1000); 2229 EXPECT_FALSE(conn3->pruned()); 2230} 2231 2232// Test that GetState returns the state correctly. 2233TEST_F(P2PTransportChannelPingTest, TestGetState) { 2234 cricket::FakePortAllocator pa(rtc::Thread::Current(), nullptr); 2235 cricket::P2PTransportChannel ch("test channel", 1, nullptr, &pa); 2236 PrepareChannel(&ch); 2237 ch.Connect(); 2238 ch.MaybeStartGathering(); 2239 EXPECT_EQ(cricket::TransportChannelState::STATE_INIT, ch.GetState()); 2240 ch.AddRemoteCandidate(CreateCandidate("1.1.1.1", 1, 100)); 2241 ch.AddRemoteCandidate(CreateCandidate("2.2.2.2", 2, 1)); 2242 cricket::Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1); 2243 cricket::Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2); 2244 ASSERT_TRUE(conn1 != nullptr); 2245 ASSERT_TRUE(conn2 != nullptr); 2246 // Now there are two connections, so the transport channel is connecting. 2247 EXPECT_EQ(cricket::TransportChannelState::STATE_CONNECTING, ch.GetState()); 2248 // |conn1| becomes writable and receiving; it then should prune |conn2|. 2249 conn1->ReceivedPingResponse(); 2250 EXPECT_TRUE_WAIT(conn2->pruned(), 1000); 2251 EXPECT_EQ(cricket::TransportChannelState::STATE_COMPLETED, ch.GetState()); 2252 conn1->Prune(); // All connections are pruned. 2253 // Need to wait until the channel state is updated. 2254 EXPECT_EQ_WAIT(cricket::TransportChannelState::STATE_FAILED, ch.GetState(), 2255 1000); 2256} 2257 2258// Test that when a low-priority connection is pruned, it is not deleted 2259// right away, and it can become active and be pruned again. 2260TEST_F(P2PTransportChannelPingTest, TestConnectionPrunedAgain) { 2261 cricket::FakePortAllocator pa(rtc::Thread::Current(), nullptr); 2262 cricket::P2PTransportChannel ch("test channel", 1, nullptr, &pa); 2263 PrepareChannel(&ch); 2264 ch.SetIceConfig(CreateIceConfig(1000, false)); 2265 ch.Connect(); 2266 ch.MaybeStartGathering(); 2267 ch.AddRemoteCandidate(CreateCandidate("1.1.1.1", 1, 100)); 2268 cricket::Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1); 2269 ASSERT_TRUE(conn1 != nullptr); 2270 EXPECT_EQ(conn1, ch.best_connection()); 2271 conn1->ReceivedPingResponse(); // Becomes writable and receiving 2272 2273 // Add a low-priority connection |conn2|, which will be pruned, but it will 2274 // not be deleted right away. Once the current best connection becomes not 2275 // receiving, |conn2| will start to ping and upon receiving the ping response, 2276 // it will become the best connection. 2277 ch.AddRemoteCandidate(CreateCandidate("2.2.2.2", 2, 1)); 2278 cricket::Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2); 2279 ASSERT_TRUE(conn2 != nullptr); 2280 EXPECT_TRUE_WAIT(!conn2->active(), 1000); 2281 // |conn2| should not send a ping yet. 2282 EXPECT_EQ(cricket::Connection::STATE_WAITING, conn2->state()); 2283 EXPECT_EQ(cricket::TransportChannelState::STATE_COMPLETED, ch.GetState()); 2284 // Wait for |conn1| becoming not receiving. 2285 EXPECT_TRUE_WAIT(!conn1->receiving(), 3000); 2286 // Make sure conn2 is not deleted. 2287 conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2); 2288 ASSERT_TRUE(conn2 != nullptr); 2289 EXPECT_EQ_WAIT(cricket::Connection::STATE_INPROGRESS, conn2->state(), 1000); 2290 conn2->ReceivedPingResponse(); 2291 EXPECT_EQ_WAIT(conn2, ch.best_connection(), 1000); 2292 EXPECT_EQ(cricket::TransportChannelState::STATE_CONNECTING, ch.GetState()); 2293 2294 // When |conn1| comes back again, |conn2| will be pruned again. 2295 conn1->ReceivedPingResponse(); 2296 EXPECT_EQ_WAIT(conn1, ch.best_connection(), 1000); 2297 EXPECT_TRUE_WAIT(!conn2->active(), 1000); 2298 EXPECT_EQ(cricket::TransportChannelState::STATE_COMPLETED, ch.GetState()); 2299} 2300 2301// Test that if all connections in a channel has timed out on writing, they 2302// will all be deleted. We use Prune to simulate write_time_out. 2303TEST_F(P2PTransportChannelPingTest, TestDeleteConnectionsIfAllWriteTimedout) { 2304 cricket::FakePortAllocator pa(rtc::Thread::Current(), nullptr); 2305 cricket::P2PTransportChannel ch("test channel", 1, nullptr, &pa); 2306 PrepareChannel(&ch); 2307 ch.Connect(); 2308 ch.MaybeStartGathering(); 2309 // Have one connection only but later becomes write-time-out. 2310 ch.AddRemoteCandidate(CreateCandidate("1.1.1.1", 1, 100)); 2311 cricket::Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1); 2312 ASSERT_TRUE(conn1 != nullptr); 2313 conn1->ReceivedPing(); // Becomes receiving 2314 conn1->Prune(); 2315 EXPECT_TRUE_WAIT(ch.connections().empty(), 1000); 2316 2317 // Have two connections but both become write-time-out later. 2318 ch.AddRemoteCandidate(CreateCandidate("2.2.2.2", 2, 1)); 2319 cricket::Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2); 2320 ASSERT_TRUE(conn2 != nullptr); 2321 conn2->ReceivedPing(); // Becomes receiving 2322 ch.AddRemoteCandidate(CreateCandidate("3.3.3.3", 3, 2)); 2323 cricket::Connection* conn3 = WaitForConnectionTo(&ch, "3.3.3.3", 3); 2324 ASSERT_TRUE(conn3 != nullptr); 2325 conn3->ReceivedPing(); // Becomes receiving 2326 // Now prune both conn2 and conn3; they will be deleted soon. 2327 conn2->Prune(); 2328 conn3->Prune(); 2329 EXPECT_TRUE_WAIT(ch.connections().empty(), 1000); 2330} 2331 2332// Test that after a port allocator session is started, it will be stopped 2333// when a new connection becomes writable and receiving. Also test that this 2334// holds even if the transport channel did not lose the writability. 2335TEST_F(P2PTransportChannelPingTest, TestStopPortAllocatorSessions) { 2336 cricket::FakePortAllocator pa(rtc::Thread::Current(), nullptr); 2337 cricket::P2PTransportChannel ch("test channel", 1, nullptr, &pa); 2338 PrepareChannel(&ch); 2339 ch.SetIceConfig(CreateIceConfig(2000, false)); 2340 ch.Connect(); 2341 ch.MaybeStartGathering(); 2342 ch.AddRemoteCandidate(CreateCandidate("1.1.1.1", 1, 100)); 2343 cricket::Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1); 2344 ASSERT_TRUE(conn1 != nullptr); 2345 conn1->ReceivedPingResponse(); // Becomes writable and receiving 2346 EXPECT_TRUE(!ch.allocator_session()->IsGettingPorts()); 2347 2348 // Restart gathering even if the transport channel is still writable. 2349 // It should stop getting ports after a new connection becomes strongly 2350 // connected. 2351 ch.SetIceCredentials(kIceUfrag[1], kIcePwd[1]); 2352 ch.MaybeStartGathering(); 2353 ch.AddRemoteCandidate(CreateCandidate("2.2.2.2", 2, 100)); 2354 cricket::Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2); 2355 ASSERT_TRUE(conn2 != nullptr); 2356 conn2->ReceivedPingResponse(); // Becomes writable and receiving 2357 EXPECT_TRUE(!ch.allocator_session()->IsGettingPorts()); 2358} 2359