Note: We no longer publish the latest version of our code here. We primarily use a kumc-bmi github organization. The heron ETL repository, in particular, is not public. Peers in the informatics community should see MultiSiteDev for details on requesting access.

source: webrtc/talk/p2p/base/p2ptransportchannel_unittest.cc @ 0:4bda6873e34c

pub_scrub_3792 tip
Last change on this file since 0:4bda6873e34c was 0:4bda6873e34c, checked in by Michael Prittie <mprittie@…>, 6 years ago

Scrubbed password for publication.

File size: 67.4 KB
Line 
1/*
2 * libjingle
3 * Copyright 2009 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 *  1. Redistributions of source code must retain the above copyright notice,
9 *     this list of conditions and the following disclaimer.
10 *  2. Redistributions in binary form must reproduce the above copyright notice,
11 *     this list of conditions and the following disclaimer in the documentation
12 *     and/or other materials provided with the distribution.
13 *  3. The name of the author may not be used to endorse or promote products
14 *     derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/base/dscp.h"
29#include "talk/base/fakenetwork.h"
30#include "talk/base/firewallsocketserver.h"
31#include "talk/base/gunit.h"
32#include "talk/base/helpers.h"
33#include "talk/base/logging.h"
34#include "talk/base/natserver.h"
35#include "talk/base/natsocketfactory.h"
36#include "talk/base/physicalsocketserver.h"
37#include "talk/base/proxyserver.h"
38#include "talk/base/socketaddress.h"
39#include "talk/base/thread.h"
40#include "talk/base/virtualsocketserver.h"
41#include "talk/p2p/base/p2ptransportchannel.h"
42#include "talk/p2p/base/testrelayserver.h"
43#include "talk/p2p/base/teststunserver.h"
44#include "talk/p2p/client/basicportallocator.h"
45
46using cricket::kDefaultPortAllocatorFlags;
47using cricket::kMinimumStepDelay;
48using cricket::kDefaultStepDelay;
49using cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG;
50using cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET;
51using talk_base::SocketAddress;
52
53static const int kDefaultTimeout = 1000;
54static const int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
55                                   cricket::PORTALLOCATOR_DISABLE_RELAY |
56                                   cricket::PORTALLOCATOR_DISABLE_TCP;
57// Addresses on the public internet.
58static const SocketAddress kPublicAddrs[2] =
59    { SocketAddress("11.11.11.11", 0), SocketAddress("22.22.22.22", 0) };
60// IPv6 Addresses on the public internet.
61static const SocketAddress kIPv6PublicAddrs[2] = {
62    SocketAddress("2400:4030:1:2c00:be30:abcd:efab:cdef", 0),
63    SocketAddress("2620:0:1000:1b03:2e41:38ff:fea6:f2a4", 0)
64};
65// For configuring multihomed clients.
66static const SocketAddress kAlternateAddrs[2] =
67    { SocketAddress("11.11.11.101", 0), SocketAddress("22.22.22.202", 0) };
68// Addresses for HTTP proxy servers.
69static const SocketAddress kHttpsProxyAddrs[2] =
70    { SocketAddress("11.11.11.1", 443), SocketAddress("22.22.22.1", 443) };
71// Addresses for SOCKS proxy servers.
72static const SocketAddress kSocksProxyAddrs[2] =
73    { SocketAddress("11.11.11.1", 1080), SocketAddress("22.22.22.1", 1080) };
74// Internal addresses for NAT boxes.
75static const SocketAddress kNatAddrs[2] =
76    { SocketAddress("192.168.1.1", 0), SocketAddress("192.168.2.1", 0) };
77// Private addresses inside the NAT private networks.
78static const SocketAddress kPrivateAddrs[2] =
79    { SocketAddress("192.168.1.11", 0), SocketAddress("192.168.2.22", 0) };
80// For cascaded NATs, the internal addresses of the inner NAT boxes.
81static const SocketAddress kCascadedNatAddrs[2] =
82    { SocketAddress("192.168.10.1", 0), SocketAddress("192.168.20.1", 0) };
83// For cascaded NATs, private addresses inside the inner private networks.
84static const SocketAddress kCascadedPrivateAddrs[2] =
85    { SocketAddress("192.168.10.11", 0), SocketAddress("192.168.20.22", 0) };
86// The address of the public STUN server.
87static const SocketAddress kStunAddr("99.99.99.1", cricket::STUN_SERVER_PORT);
88// The addresses for the public relay server.
89static const SocketAddress kRelayUdpIntAddr("99.99.99.2", 5000);
90static const SocketAddress kRelayUdpExtAddr("99.99.99.3", 5001);
91static const SocketAddress kRelayTcpIntAddr("99.99.99.2", 5002);
92static const SocketAddress kRelayTcpExtAddr("99.99.99.3", 5003);
93static const SocketAddress kRelaySslTcpIntAddr("99.99.99.2", 5004);
94static const SocketAddress kRelaySslTcpExtAddr("99.99.99.3", 5005);
95
96// Based on ICE_UFRAG_LENGTH
97static const char* kIceUfrag[4] = {"TESTICEUFRAG0000", "TESTICEUFRAG0001",
98                                   "TESTICEUFRAG0002", "TESTICEUFRAG0003"};
99// Based on ICE_PWD_LENGTH
100static const char* kIcePwd[4] = {"TESTICEPWD00000000000000",
101                                 "TESTICEPWD00000000000001",
102                                 "TESTICEPWD00000000000002",
103                                 "TESTICEPWD00000000000003"};
104
105static const uint64 kTiebreaker1 = 11111;
106static const uint64 kTiebreaker2 = 22222;
107
108// This test simulates 2 P2P endpoints that want to establish connectivity
109// with each other over various network topologies and conditions, which can be
110// specified in each individial test.
111// A virtual network (via VirtualSocketServer) along with virtual firewalls and
112// NATs (via Firewall/NATSocketServer) are used to simulate the various network
113// conditions. We can configure the IP addresses of the endpoints,
114// block various types of connectivity, or add arbitrary levels of NAT.
115// We also run a STUN server and a relay server on the virtual network to allow
116// our typical P2P mechanisms to do their thing.
117// For each case, we expect the P2P stack to eventually settle on a specific
118// form of connectivity to the other side. The test checks that the P2P
119// negotiation successfully establishes connectivity within a certain time,
120// and that the result is what we expect.
121// Note that this class is a base class for use by other tests, who will provide
122// specialized test behavior.
123class P2PTransportChannelTestBase : public testing::Test,
124                                    public talk_base::MessageHandler,
125                                    public sigslot::has_slots<> {
126 public:
127  P2PTransportChannelTestBase()
128      : main_(talk_base::Thread::Current()),
129        pss_(new talk_base::PhysicalSocketServer),
130        vss_(new talk_base::VirtualSocketServer(pss_.get())),
131        nss_(new talk_base::NATSocketServer(vss_.get())),
132        ss_(new talk_base::FirewallSocketServer(nss_.get())),
133        ss_scope_(ss_.get()),
134        stun_server_(main_, kStunAddr),
135        relay_server_(main_, kRelayUdpIntAddr, kRelayUdpExtAddr,
136                      kRelayTcpIntAddr, kRelayTcpExtAddr,
137                      kRelaySslTcpIntAddr, kRelaySslTcpExtAddr),
138        socks_server1_(ss_.get(), kSocksProxyAddrs[0],
139                       ss_.get(), kSocksProxyAddrs[0]),
140        socks_server2_(ss_.get(), kSocksProxyAddrs[1],
141                       ss_.get(), kSocksProxyAddrs[1]),
142        clear_remote_candidates_ufrag_pwd_(false) {
143    ep1_.role_ = cricket::ICEROLE_CONTROLLING;
144    ep2_.role_ = cricket::ICEROLE_CONTROLLED;
145    ep1_.allocator_.reset(new cricket::BasicPortAllocator(
146        &ep1_.network_manager_, kStunAddr, kRelayUdpIntAddr,
147        kRelayTcpIntAddr, kRelaySslTcpIntAddr));
148    ep2_.allocator_.reset(new cricket::BasicPortAllocator(
149        &ep2_.network_manager_, kStunAddr, kRelayUdpIntAddr,
150        kRelayTcpIntAddr, kRelaySslTcpIntAddr));
151  }
152
153 protected:
154  enum Config {
155    OPEN,                           // Open to the Internet
156    NAT_FULL_CONE,                  // NAT, no filtering
157    NAT_ADDR_RESTRICTED,            // NAT, must send to an addr to recv
158    NAT_PORT_RESTRICTED,            // NAT, must send to an addr+port to recv
159    NAT_SYMMETRIC,                  // NAT, endpoint-dependent bindings
160    NAT_DOUBLE_CONE,                // Double NAT, both cone
161    NAT_SYMMETRIC_THEN_CONE,        // Double NAT, symmetric outer, cone inner
162    BLOCK_UDP,                      // Firewall, UDP in/out blocked
163    BLOCK_UDP_AND_INCOMING_TCP,     // Firewall, UDP in/out and TCP in blocked
164    BLOCK_ALL_BUT_OUTGOING_HTTP,    // Firewall, only TCP out on 80/443
165    PROXY_HTTPS,                    // All traffic through HTTPS proxy
166    PROXY_SOCKS,                    // All traffic through SOCKS proxy
167    NUM_CONFIGS
168  };
169
170  struct Result {
171    Result(const std::string& lt, const std::string& lp,
172           const std::string& rt, const std::string& rp,
173           const std::string& lt2, const std::string& lp2,
174           const std::string& rt2, const std::string& rp2, int wait)
175        : local_type(lt), local_proto(lp), remote_type(rt), remote_proto(rp),
176          local_type2(lt2), local_proto2(lp2), remote_type2(rt2),
177          remote_proto2(rp2), connect_wait(wait) {
178    }
179    std::string local_type;
180    std::string local_proto;
181    std::string remote_type;
182    std::string remote_proto;
183    std::string local_type2;
184    std::string local_proto2;
185    std::string remote_type2;
186    std::string remote_proto2;
187    int connect_wait;
188  };
189
190  struct ChannelData {
191    bool CheckData(const char* data, int len) {
192      bool ret = false;
193      if (!ch_packets_.empty()) {
194        std::string packet =  ch_packets_.front();
195        ret = (packet == std::string(data, len));
196        ch_packets_.pop_front();
197      }
198      return ret;
199    }
200
201    std::string name_;  // TODO - Currently not used.
202    std::list<std::string> ch_packets_;
203    talk_base::scoped_ptr<cricket::P2PTransportChannel> ch_;
204  };
205
206  struct Endpoint {
207    Endpoint() : signaling_delay_(0), role_(cricket::ICEROLE_UNKNOWN),
208        tiebreaker_(0), role_conflict_(false),
209        protocol_type_(cricket::ICEPROTO_GOOGLE) {}
210    bool HasChannel(cricket::TransportChannel* ch) {
211      return (ch == cd1_.ch_.get() || ch == cd2_.ch_.get());
212    }
213    ChannelData* GetChannelData(cricket::TransportChannel* ch) {
214      if (!HasChannel(ch)) return NULL;
215      if (cd1_.ch_.get() == ch)
216        return &cd1_;
217      else
218        return &cd2_;
219    }
220    void SetSignalingDelay(int delay) { signaling_delay_ = delay; }
221
222    void SetIceRole(cricket::IceRole role) { role_ = role; }
223    cricket::IceRole ice_role() { return role_; }
224    void SetIceProtocolType(cricket::IceProtocolType type) {
225      protocol_type_ = type;
226    }
227    cricket::IceProtocolType protocol_type() { return protocol_type_; }
228    void SetIceTiebreaker(uint64 tiebreaker) { tiebreaker_ = tiebreaker; }
229    uint64 GetIceTiebreaker() { return tiebreaker_; }
230    void OnRoleConflict(bool role_conflict) { role_conflict_ = role_conflict; }
231    bool role_conflict() { return role_conflict_; }
232    void SetAllocationStepDelay(uint32 delay) {
233      allocator_->set_step_delay(delay);
234    }
235    void SetAllowTcpListen(bool allow_tcp_listen) {
236      allocator_->set_allow_tcp_listen(allow_tcp_listen);
237    }
238
239    talk_base::FakeNetworkManager network_manager_;
240    talk_base::scoped_ptr<cricket::PortAllocator> allocator_;
241    ChannelData cd1_;
242    ChannelData cd2_;
243    int signaling_delay_;
244    cricket::IceRole role_;
245    uint64 tiebreaker_;
246    bool role_conflict_;
247    cricket::IceProtocolType protocol_type_;
248  };
249
250  struct CandidateData : public talk_base::MessageData {
251    CandidateData(cricket::TransportChannel* ch, const cricket::Candidate& c)
252        : channel(ch), candidate(c) {
253    }
254    cricket::TransportChannel* channel;
255    cricket::Candidate candidate;
256  };
257
258  ChannelData* GetChannelData(cricket::TransportChannel* channel) {
259    if (ep1_.HasChannel(channel))
260      return ep1_.GetChannelData(channel);
261    else
262      return ep2_.GetChannelData(channel);
263  }
264
265  void CreateChannels(int num) {
266    std::string ice_ufrag_ep1_cd1_ch = kIceUfrag[0];
267    std::string ice_pwd_ep1_cd1_ch = kIcePwd[0];
268    std::string ice_ufrag_ep2_cd1_ch = kIceUfrag[1];
269    std::string ice_pwd_ep2_cd1_ch = kIcePwd[1];
270    ep1_.cd1_.ch_.reset(CreateChannel(
271        0, cricket::ICE_CANDIDATE_COMPONENT_DEFAULT,
272        ice_ufrag_ep1_cd1_ch, ice_pwd_ep1_cd1_ch,
273        ice_ufrag_ep2_cd1_ch, ice_pwd_ep2_cd1_ch));
274    ep2_.cd1_.ch_.reset(CreateChannel(
275        1, cricket::ICE_CANDIDATE_COMPONENT_DEFAULT,
276        ice_ufrag_ep2_cd1_ch, ice_pwd_ep2_cd1_ch,
277        ice_ufrag_ep1_cd1_ch, ice_pwd_ep1_cd1_ch));
278    if (num == 2) {
279      std::string ice_ufrag_ep1_cd2_ch = kIceUfrag[2];
280      std::string ice_pwd_ep1_cd2_ch = kIcePwd[2];
281      std::string ice_ufrag_ep2_cd2_ch = kIceUfrag[3];
282      std::string ice_pwd_ep2_cd2_ch = kIcePwd[3];
283      // In BUNDLE each endpoint must share common ICE credentials.
284      if (ep1_.allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_BUNDLE) {
285        ice_ufrag_ep1_cd2_ch = ice_ufrag_ep1_cd1_ch;
286        ice_pwd_ep1_cd2_ch = ice_pwd_ep1_cd1_ch;
287      }
288      if (ep2_.allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_BUNDLE) {
289        ice_ufrag_ep2_cd2_ch = ice_ufrag_ep2_cd1_ch;
290        ice_pwd_ep2_cd2_ch = ice_pwd_ep2_cd1_ch;
291      }
292      ep1_.cd2_.ch_.reset(CreateChannel(
293          0, cricket::ICE_CANDIDATE_COMPONENT_DEFAULT,
294          ice_ufrag_ep1_cd2_ch, ice_pwd_ep1_cd2_ch,
295          ice_ufrag_ep2_cd2_ch, ice_pwd_ep2_cd2_ch));
296      ep2_.cd2_.ch_.reset(CreateChannel(
297          1, cricket::ICE_CANDIDATE_COMPONENT_DEFAULT,
298          ice_ufrag_ep2_cd2_ch, ice_pwd_ep2_cd2_ch,
299          ice_ufrag_ep1_cd2_ch, ice_pwd_ep1_cd2_ch));
300    }
301  }
302  cricket::P2PTransportChannel* CreateChannel(
303      int endpoint,
304      int component,
305      const std::string& local_ice_ufrag,
306      const std::string& local_ice_pwd,
307      const std::string& remote_ice_ufrag,
308      const std::string& remote_ice_pwd) {
309    cricket::P2PTransportChannel* channel = new cricket::P2PTransportChannel(
310        "test content name", component, NULL, GetAllocator(endpoint));
311    channel->SignalRequestSignaling.connect(
312        this, &P2PTransportChannelTestBase::OnChannelRequestSignaling);
313    channel->SignalCandidateReady.connect(this,
314        &P2PTransportChannelTestBase::OnCandidate);
315    channel->SignalReadPacket.connect(
316        this, &P2PTransportChannelTestBase::OnReadPacket);
317    channel->SignalRoleConflict.connect(
318        this, &P2PTransportChannelTestBase::OnRoleConflict);
319    channel->SetIceProtocolType(GetEndpoint(endpoint)->protocol_type());
320    channel->SetIceCredentials(local_ice_ufrag, local_ice_pwd);
321    if (clear_remote_candidates_ufrag_pwd_) {
322      // This only needs to be set if we're clearing them from the
323      // candidates.  Some unit tests rely on this not being set.
324      channel->SetRemoteIceCredentials(remote_ice_ufrag, remote_ice_pwd);
325    }
326    channel->SetIceRole(GetEndpoint(endpoint)->ice_role());
327    channel->SetIceTiebreaker(GetEndpoint(endpoint)->GetIceTiebreaker());
328    channel->Connect();
329    return channel;
330  }
331  void DestroyChannels() {
332    ep1_.cd1_.ch_.reset();
333    ep2_.cd1_.ch_.reset();
334    ep1_.cd2_.ch_.reset();
335    ep2_.cd2_.ch_.reset();
336  }
337  cricket::P2PTransportChannel* ep1_ch1() { return ep1_.cd1_.ch_.get(); }
338  cricket::P2PTransportChannel* ep1_ch2() { return ep1_.cd2_.ch_.get(); }
339  cricket::P2PTransportChannel* ep2_ch1() { return ep2_.cd1_.ch_.get(); }
340  cricket::P2PTransportChannel* ep2_ch2() { return ep2_.cd2_.ch_.get(); }
341
342  // Common results.
343  static const Result kLocalUdpToLocalUdp;
344  static const Result kLocalUdpToStunUdp;
345  static const Result kLocalUdpToPrflxUdp;
346  static const Result kPrflxUdpToLocalUdp;
347  static const Result kStunUdpToLocalUdp;
348  static const Result kStunUdpToStunUdp;
349  static const Result kPrflxUdpToStunUdp;
350  static const Result kLocalUdpToRelayUdp;
351  static const Result kPrflxUdpToRelayUdp;
352  static const Result kLocalTcpToLocalTcp;
353  static const Result kLocalTcpToPrflxTcp;
354  static const Result kPrflxTcpToLocalTcp;
355
356  static void SetUpTestCase() {
357    // Ensure the RNG is inited.
358    talk_base::InitRandom(NULL, 0);
359  }
360
361  talk_base::NATSocketServer* nat() { return nss_.get(); }
362  talk_base::FirewallSocketServer* fw() { return ss_.get(); }
363
364  Endpoint* GetEndpoint(int endpoint) {
365    if (endpoint == 0) {
366      return &ep1_;
367    } else if (endpoint == 1) {
368      return &ep2_;
369    } else {
370      return NULL;
371    }
372  }
373  cricket::PortAllocator* GetAllocator(int endpoint) {
374    return GetEndpoint(endpoint)->allocator_.get();
375  }
376  void AddAddress(int endpoint, const SocketAddress& addr) {
377    GetEndpoint(endpoint)->network_manager_.AddInterface(addr);
378  }
379  void RemoveAddress(int endpoint, const SocketAddress& addr) {
380    GetEndpoint(endpoint)->network_manager_.RemoveInterface(addr);
381  }
382  void SetProxy(int endpoint, talk_base::ProxyType type) {
383    talk_base::ProxyInfo info;
384    info.type = type;
385    info.address = (type == talk_base::PROXY_HTTPS) ?
386        kHttpsProxyAddrs[endpoint] : kSocksProxyAddrs[endpoint];
387    GetAllocator(endpoint)->set_proxy("unittest/1.0", info);
388  }
389  void SetAllocatorFlags(int endpoint, int flags) {
390    GetAllocator(endpoint)->set_flags(flags);
391  }
392  void SetSignalingDelay(int endpoint, int delay) {
393    GetEndpoint(endpoint)->SetSignalingDelay(delay);
394  }
395  void SetIceProtocol(int endpoint, cricket::IceProtocolType type) {
396    GetEndpoint(endpoint)->SetIceProtocolType(type);
397  }
398  void SetIceRole(int endpoint, cricket::IceRole role) {
399    GetEndpoint(endpoint)->SetIceRole(role);
400  }
401  void SetIceTiebreaker(int endpoint, uint64 tiebreaker) {
402    GetEndpoint(endpoint)->SetIceTiebreaker(tiebreaker);
403  }
404  bool GetRoleConflict(int endpoint) {
405    return GetEndpoint(endpoint)->role_conflict();
406  }
407  void SetAllocationStepDelay(int endpoint, uint32 delay) {
408    return GetEndpoint(endpoint)->SetAllocationStepDelay(delay);
409  }
410  void SetAllowTcpListen(int endpoint, bool allow_tcp_listen) {
411    return GetEndpoint(endpoint)->SetAllowTcpListen(allow_tcp_listen);
412  }
413
414  void Test(const Result& expected) {
415    int32 connect_start = talk_base::Time(), connect_time;
416
417    // Create the channels and wait for them to connect.
418    CreateChannels(1);
419    EXPECT_TRUE_WAIT_MARGIN(ep1_ch1() != NULL &&
420                            ep2_ch1() != NULL &&
421                            ep1_ch1()->readable() &&
422                            ep1_ch1()->writable() &&
423                            ep2_ch1()->readable() &&
424                            ep2_ch1()->writable(),
425                            expected.connect_wait,
426                            1000);
427    connect_time = talk_base::TimeSince(connect_start);
428    if (connect_time < expected.connect_wait) {
429      LOG(LS_INFO) << "Connect time: " << connect_time << " ms";
430    } else {
431      LOG(LS_INFO) << "Connect time: " << "TIMEOUT ("
432                   << expected.connect_wait << " ms)";
433    }
434
435    // Allow a few turns of the crank for the best connections to emerge.
436    // This may take up to 2 seconds.
437    if (ep1_ch1()->best_connection() &&
438        ep2_ch1()->best_connection()) {
439      int32 converge_start = talk_base::Time(), converge_time;
440      int converge_wait = 2000;
441      EXPECT_TRUE_WAIT_MARGIN(
442          LocalCandidate(ep1_ch1())->type() == expected.local_type &&
443          LocalCandidate(ep1_ch1())->protocol() == expected.local_proto &&
444          RemoteCandidate(ep1_ch1())->type() == expected.remote_type &&
445          RemoteCandidate(ep1_ch1())->protocol() == expected.remote_proto,
446          converge_wait,
447          converge_wait);
448
449      // Also do EXPECT_EQ on each part so that failures are more verbose.
450      EXPECT_EQ(expected.local_type, LocalCandidate(ep1_ch1())->type());
451      EXPECT_EQ(expected.local_proto, LocalCandidate(ep1_ch1())->protocol());
452      EXPECT_EQ(expected.remote_type, RemoteCandidate(ep1_ch1())->type());
453      EXPECT_EQ(expected.remote_proto, RemoteCandidate(ep1_ch1())->protocol());
454
455      // Verifying remote channel best connection information. This is done
456      // only for the RFC 5245 as controlled agent will use USE-CANDIDATE
457      // from controlling (ep1) agent. We can easily predict from EP1 result
458      // matrix.
459      if (ep2_.protocol_type_ == cricket::ICEPROTO_RFC5245) {
460        // Checking for best connection candidates information at remote.
461        EXPECT_TRUE_WAIT(
462            LocalCandidate(ep2_ch1())->type() == expected.local_type2 &&
463            LocalCandidate(ep2_ch1())->protocol() == expected.local_proto2 &&
464            RemoteCandidate(ep2_ch1())->protocol() == expected.remote_proto2,
465            kDefaultTimeout);
466
467        // For verbose
468        EXPECT_EQ(expected.local_type2, LocalCandidate(ep2_ch1())->type());
469        EXPECT_EQ(expected.local_proto2, LocalCandidate(ep2_ch1())->protocol());
470        EXPECT_EQ(expected.remote_proto2,
471                  RemoteCandidate(ep2_ch1())->protocol());
472        // Removed remote_type comparision aginst best connection remote
473        // candidate. This is done to handle remote type discrepancy from
474        // local to stun based on the test type.
475        // For example in case of Open -> NAT, ep2 channels will have LULU
476        // and in other cases like NAT -> NAT it will be LUSU. To avoid these
477        // mismatches and we are doing comparision in different way.
478        // i.e. when don't match its remote type is either local or stun.
479        // TODO(ronghuawu): Refine the test criteria.
480        // https://code.google.com/p/webrtc/issues/detail?id=1953
481        if (expected.remote_type2 != RemoteCandidate(ep2_ch1())->type())
482          EXPECT_TRUE(expected.remote_type2 == cricket::LOCAL_PORT_TYPE ||
483                      expected.remote_type2 == cricket::STUN_PORT_TYPE);
484          EXPECT_TRUE(
485              RemoteCandidate(ep2_ch1())->type() == cricket::LOCAL_PORT_TYPE ||
486              RemoteCandidate(ep2_ch1())->type() == cricket::STUN_PORT_TYPE ||
487              RemoteCandidate(ep2_ch1())->type() == cricket::PRFLX_PORT_TYPE);
488      }
489
490      converge_time = talk_base::TimeSince(converge_start);
491      if (converge_time < converge_wait) {
492        LOG(LS_INFO) << "Converge time: " << converge_time << " ms";
493      } else {
494        LOG(LS_INFO) << "Converge time: " << "TIMEOUT ("
495                     << converge_wait << " ms)";
496      }
497    }
498    // Try sending some data to other end.
499    TestSendRecv(1);
500
501    // Destroy the channels, and wait for them to be fully cleaned up.
502    DestroyChannels();
503  }
504
505  void TestSendRecv(int channels) {
506    for (int i = 0; i < 10; ++i) {
507    const char* data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
508      int len = static_cast<int>(strlen(data));
509      // local_channel1 <==> remote_channel1
510      EXPECT_EQ_WAIT(len, SendData(ep1_ch1(), data, len), 1000);
511      EXPECT_TRUE_WAIT(CheckDataOnChannel(ep2_ch1(), data, len), 1000);
512      EXPECT_EQ_WAIT(len, SendData(ep2_ch1(), data, len), 1000);
513      EXPECT_TRUE_WAIT(CheckDataOnChannel(ep1_ch1(), data, len), 1000);
514      if (channels == 2 && ep1_ch2() && ep2_ch2()) {
515        // local_channel2 <==> remote_channel2
516        EXPECT_EQ_WAIT(len, SendData(ep1_ch2(), data, len), 1000);
517        EXPECT_TRUE_WAIT(CheckDataOnChannel(ep2_ch2(), data, len), 1000);
518        EXPECT_EQ_WAIT(len, SendData(ep2_ch2(), data, len), 1000);
519        EXPECT_TRUE_WAIT(CheckDataOnChannel(ep1_ch2(), data, len), 1000);
520      }
521    }
522  }
523
524  // This test waits for the transport to become readable and writable on both
525  // end points. Once they are, the end points set new local ice credentials to
526  // restart the ice gathering. Finally it waits for the transport to select a
527  // new connection using the newly generated ice candidates.
528  // Before calling this function the end points must be configured.
529  void TestHandleIceUfragPasswordChanged() {
530    ep1_ch1()->SetRemoteIceCredentials(kIceUfrag[1], kIcePwd[1]);
531    ep2_ch1()->SetRemoteIceCredentials(kIceUfrag[0], kIcePwd[0]);
532    EXPECT_TRUE_WAIT_MARGIN(ep1_ch1()->readable() && ep1_ch1()->writable() &&
533                            ep2_ch1()->readable() && ep2_ch1()->writable(),
534                            1000, 1000);
535
536    const cricket::Candidate* old_local_candidate1 = LocalCandidate(ep1_ch1());
537    const cricket::Candidate* old_local_candidate2 = LocalCandidate(ep2_ch1());
538    const cricket::Candidate* old_remote_candidate1 =
539        RemoteCandidate(ep1_ch1());
540    const cricket::Candidate* old_remote_candidate2 =
541        RemoteCandidate(ep2_ch1());
542
543    ep1_ch1()->SetIceCredentials(kIceUfrag[2], kIcePwd[2]);
544    ep1_ch1()->SetRemoteIceCredentials(kIceUfrag[3], kIcePwd[3]);
545    ep2_ch1()->SetIceCredentials(kIceUfrag[3], kIcePwd[3]);
546    ep2_ch1()->SetRemoteIceCredentials(kIceUfrag[2], kIcePwd[2]);
547
548    EXPECT_TRUE_WAIT_MARGIN(LocalCandidate(ep1_ch1())->generation() !=
549                            old_local_candidate1->generation(),
550                            1000, 1000);
551    EXPECT_TRUE_WAIT_MARGIN(LocalCandidate(ep2_ch1())->generation() !=
552                            old_local_candidate2->generation(),
553                            1000, 1000);
554    EXPECT_TRUE_WAIT_MARGIN(RemoteCandidate(ep1_ch1())->generation() !=
555                            old_remote_candidate1->generation(),
556                            1000, 1000);
557    EXPECT_TRUE_WAIT_MARGIN(RemoteCandidate(ep2_ch1())->generation() !=
558                            old_remote_candidate2->generation(),
559                            1000, 1000);
560    EXPECT_EQ(1u, RemoteCandidate(ep2_ch1())->generation());
561    EXPECT_EQ(1u, RemoteCandidate(ep1_ch1())->generation());
562  }
563
564  void TestSignalRoleConflict() {
565    SetIceProtocol(0, cricket::ICEPROTO_RFC5245);
566    SetIceTiebreaker(0, kTiebreaker1);  // Default EP1 is in controlling state.
567
568    SetIceProtocol(1, cricket::ICEPROTO_RFC5245);
569    SetIceRole(1, cricket::ICEROLE_CONTROLLING);
570    SetIceTiebreaker(1, kTiebreaker2);
571
572    // Creating channels with both channels role set to CONTROLLING.
573    CreateChannels(1);
574    // Since both the channels initiated with controlling state and channel2
575    // has higher tiebreaker value, channel1 should receive SignalRoleConflict.
576    EXPECT_TRUE_WAIT(GetRoleConflict(0), 1000);
577    EXPECT_FALSE(GetRoleConflict(1));
578
579    EXPECT_TRUE_WAIT(ep1_ch1()->readable() &&
580                     ep1_ch1()->writable() &&
581                     ep2_ch1()->readable() &&
582                     ep2_ch1()->writable(),
583                     1000);
584
585    EXPECT_TRUE(ep1_ch1()->best_connection() &&
586                ep2_ch1()->best_connection());
587
588    TestSendRecv(1);
589  }
590
591  void OnChannelRequestSignaling(cricket::TransportChannelImpl* channel) {
592    channel->OnSignalingReady();
593  }
594  // We pass the candidates directly to the other side.
595  void OnCandidate(cricket::TransportChannelImpl* ch,
596                   const cricket::Candidate& c) {
597    main_->PostDelayed(GetEndpoint(ch)->signaling_delay_, this, 0,
598                       new CandidateData(ch, c));
599  }
600  void OnMessage(talk_base::Message* msg) {
601    talk_base::scoped_ptr<CandidateData> data(
602        static_cast<CandidateData*>(msg->pdata));
603    cricket::P2PTransportChannel* rch = GetRemoteChannel(data->channel);
604    cricket::Candidate c = data->candidate;
605    if (clear_remote_candidates_ufrag_pwd_) {
606      c.set_username("");
607      c.set_password("");
608    }
609    LOG(LS_INFO) << "Candidate(" << data->channel->component() << "->"
610                 << rch->component() << "): " << c.type() << ", " << c.protocol()
611                 << ", " << c.address().ToString() << ", " << c.username()
612                 << ", " << c.generation();
613    rch->OnCandidate(c);
614  }
615  void OnReadPacket(cricket::TransportChannel* channel, const char* data,
616                    size_t len, int flags) {
617    std::list<std::string>& packets = GetPacketList(channel);
618    packets.push_front(std::string(data, len));
619  }
620  void OnRoleConflict(cricket::TransportChannelImpl* channel) {
621    GetEndpoint(channel)->OnRoleConflict(true);
622    cricket::IceRole new_role =
623        GetEndpoint(channel)->ice_role() == cricket::ICEROLE_CONTROLLING ?
624            cricket::ICEROLE_CONTROLLED : cricket::ICEROLE_CONTROLLING;
625    channel->SetIceRole(new_role);
626  }
627  int SendData(cricket::TransportChannel* channel,
628               const char* data, size_t len) {
629    return channel->SendPacket(data, len, talk_base::DSCP_NO_CHANGE, 0);
630  }
631  bool CheckDataOnChannel(cricket::TransportChannel* channel,
632                          const char* data, int len) {
633    return GetChannelData(channel)->CheckData(data, len);
634  }
635  static const cricket::Candidate* LocalCandidate(
636      cricket::P2PTransportChannel* ch) {
637    return (ch && ch->best_connection()) ?
638        &ch->best_connection()->local_candidate() : NULL;
639  }
640  static const cricket::Candidate* RemoteCandidate(
641      cricket::P2PTransportChannel* ch) {
642    return (ch && ch->best_connection()) ?
643        &ch->best_connection()->remote_candidate() : NULL;
644  }
645  Endpoint* GetEndpoint(cricket::TransportChannel* ch) {
646    if (ep1_.HasChannel(ch)) {
647      return &ep1_;
648    } else if (ep2_.HasChannel(ch)) {
649      return &ep2_;
650    } else {
651      return NULL;
652    }
653  }
654  cricket::P2PTransportChannel* GetRemoteChannel(
655      cricket::TransportChannel* ch) {
656    if (ch == ep1_ch1())
657      return ep2_ch1();
658    else if (ch == ep1_ch2())
659      return ep2_ch2();
660    else if (ch == ep2_ch1())
661      return ep1_ch1();
662    else if (ch == ep2_ch2())
663      return ep1_ch2();
664    else
665      return NULL;
666  }
667  std::list<std::string>& GetPacketList(cricket::TransportChannel* ch) {
668    return GetChannelData(ch)->ch_packets_;
669  }
670
671  void set_clear_remote_candidates_ufrag_pwd(bool clear) {
672    clear_remote_candidates_ufrag_pwd_ = clear;
673  }
674
675 private:
676  talk_base::Thread* main_;
677  talk_base::scoped_ptr<talk_base::PhysicalSocketServer> pss_;
678  talk_base::scoped_ptr<talk_base::VirtualSocketServer> vss_;
679  talk_base::scoped_ptr<talk_base::NATSocketServer> nss_;
680  talk_base::scoped_ptr<talk_base::FirewallSocketServer> ss_;
681  talk_base::SocketServerScope ss_scope_;
682  cricket::TestStunServer stun_server_;
683  cricket::TestRelayServer relay_server_;
684  talk_base::SocksProxyServer socks_server1_;
685  talk_base::SocksProxyServer socks_server2_;
686  Endpoint ep1_;
687  Endpoint ep2_;
688  bool clear_remote_candidates_ufrag_pwd_;
689};
690
691// The tests have only a few outcomes, which we predefine.
692const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
693    kLocalUdpToLocalUdp("local", "udp", "local", "udp",
694                        "local", "udp", "local", "udp", 1000);
695const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
696    kLocalUdpToStunUdp("local", "udp", "stun", "udp",
697                       "local", "udp", "stun", "udp", 1000);
698const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
699    kLocalUdpToPrflxUdp("local", "udp", "prflx", "udp",
700                        "prflx", "udp", "local", "udp", 1000);
701const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
702    kPrflxUdpToLocalUdp("prflx", "udp", "local", "udp",
703                        "local", "udp", "prflx", "udp", 1000);
704const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
705    kStunUdpToLocalUdp("stun", "udp", "local", "udp",
706                       "local", "udp", "stun", "udp", 1000);
707const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
708    kStunUdpToStunUdp("stun", "udp", "stun", "udp",
709                      "stun", "udp", "stun", "udp", 1000);
710const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
711    kPrflxUdpToStunUdp("prflx", "udp", "stun", "udp",
712                       "local", "udp", "prflx", "udp", 1000);
713const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
714    kLocalUdpToRelayUdp("local", "udp", "relay", "udp",
715                        "relay", "udp", "local", "udp", 2000);
716const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
717    kPrflxUdpToRelayUdp("prflx", "udp", "relay", "udp",
718                        "relay", "udp", "prflx", "udp", 2000);
719const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
720    kLocalTcpToLocalTcp("local", "tcp", "local", "tcp",
721                        "local", "tcp", "local", "tcp", 3000);
722const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
723    kLocalTcpToPrflxTcp("local", "tcp", "prflx", "tcp",
724                        "prflx", "tcp", "local", "tcp", 3000);
725const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
726    kPrflxTcpToLocalTcp("prflx", "tcp", "local", "tcp",
727                        "local", "tcp", "prflx", "tcp", 3000);
728
729// Test the matrix of all the connectivity types we expect to see in the wild.
730// Just test every combination of the configs in the Config enum.
731class P2PTransportChannelTest : public P2PTransportChannelTestBase {
732 protected:
733  static const Result* kMatrix[NUM_CONFIGS][NUM_CONFIGS];
734  static const Result* kMatrixSharedUfrag[NUM_CONFIGS][NUM_CONFIGS];
735  static const Result* kMatrixSharedSocketAsGice[NUM_CONFIGS][NUM_CONFIGS];
736  static const Result* kMatrixSharedSocketAsIce[NUM_CONFIGS][NUM_CONFIGS];
737  void ConfigureEndpoints(Config config1, Config config2,
738      int allocator_flags1, int allocator_flags2,
739      int delay1, int delay2,
740      cricket::IceProtocolType type) {
741    ConfigureEndpoint(0, config1);
742    SetIceProtocol(0, type);
743    SetAllocatorFlags(0, allocator_flags1);
744    SetAllocationStepDelay(0, delay1);
745    ConfigureEndpoint(1, config2);
746    SetIceProtocol(1, type);
747    SetAllocatorFlags(1, allocator_flags2);
748    SetAllocationStepDelay(1, delay2);
749  }
750  void ConfigureEndpoint(int endpoint, Config config) {
751    switch (config) {
752      case OPEN:
753        AddAddress(endpoint, kPublicAddrs[endpoint]);
754        break;
755      case NAT_FULL_CONE:
756      case NAT_ADDR_RESTRICTED:
757      case NAT_PORT_RESTRICTED:
758      case NAT_SYMMETRIC:
759        AddAddress(endpoint, kPrivateAddrs[endpoint]);
760        // Add a single NAT of the desired type
761        nat()->AddTranslator(kPublicAddrs[endpoint], kNatAddrs[endpoint],
762            static_cast<talk_base::NATType>(config - NAT_FULL_CONE))->
763            AddClient(kPrivateAddrs[endpoint]);
764        break;
765      case NAT_DOUBLE_CONE:
766      case NAT_SYMMETRIC_THEN_CONE:
767        AddAddress(endpoint, kCascadedPrivateAddrs[endpoint]);
768        // Add a two cascaded NATs of the desired types
769        nat()->AddTranslator(kPublicAddrs[endpoint], kNatAddrs[endpoint],
770            (config == NAT_DOUBLE_CONE) ?
771                talk_base::NAT_OPEN_CONE : talk_base::NAT_SYMMETRIC)->
772            AddTranslator(kPrivateAddrs[endpoint], kCascadedNatAddrs[endpoint],
773                talk_base::NAT_OPEN_CONE)->
774                AddClient(kCascadedPrivateAddrs[endpoint]);
775        break;
776      case BLOCK_UDP:
777      case BLOCK_UDP_AND_INCOMING_TCP:
778      case BLOCK_ALL_BUT_OUTGOING_HTTP:
779      case PROXY_HTTPS:
780      case PROXY_SOCKS:
781        AddAddress(endpoint, kPublicAddrs[endpoint]);
782        // Block all UDP
783        fw()->AddRule(false, talk_base::FP_UDP, talk_base::FD_ANY,
784                      kPublicAddrs[endpoint]);
785        if (config == BLOCK_UDP_AND_INCOMING_TCP) {
786          // Block TCP inbound to the endpoint
787          fw()->AddRule(false, talk_base::FP_TCP, SocketAddress(),
788                        kPublicAddrs[endpoint]);
789        } else if (config == BLOCK_ALL_BUT_OUTGOING_HTTP) {
790          // Block all TCP to/from the endpoint except 80/443 out
791          fw()->AddRule(true, talk_base::FP_TCP, kPublicAddrs[endpoint],
792                        SocketAddress(talk_base::IPAddress(INADDR_ANY), 80));
793          fw()->AddRule(true, talk_base::FP_TCP, kPublicAddrs[endpoint],
794                        SocketAddress(talk_base::IPAddress(INADDR_ANY), 443));
795          fw()->AddRule(false, talk_base::FP_TCP, talk_base::FD_ANY,
796                        kPublicAddrs[endpoint]);
797        } else if (config == PROXY_HTTPS) {
798          // Block all TCP to/from the endpoint except to the proxy server
799          fw()->AddRule(true, talk_base::FP_TCP, kPublicAddrs[endpoint],
800                        kHttpsProxyAddrs[endpoint]);
801          fw()->AddRule(false, talk_base::FP_TCP, talk_base::FD_ANY,
802                        kPublicAddrs[endpoint]);
803          SetProxy(endpoint, talk_base::PROXY_HTTPS);
804        } else if (config == PROXY_SOCKS) {
805          // Block all TCP to/from the endpoint except to the proxy server
806          fw()->AddRule(true, talk_base::FP_TCP, kPublicAddrs[endpoint],
807                        kSocksProxyAddrs[endpoint]);
808          fw()->AddRule(false, talk_base::FP_TCP, talk_base::FD_ANY,
809                        kPublicAddrs[endpoint]);
810          SetProxy(endpoint, talk_base::PROXY_SOCKS5);
811        }
812        break;
813      default:
814        break;
815    }
816  }
817};
818
819// Shorthands for use in the test matrix.
820#define LULU &kLocalUdpToLocalUdp
821#define LUSU &kLocalUdpToStunUdp
822#define LUPU &kLocalUdpToPrflxUdp
823#define PULU &kPrflxUdpToLocalUdp
824#define SULU &kStunUdpToLocalUdp
825#define SUSU &kStunUdpToStunUdp
826#define PUSU &kPrflxUdpToStunUdp
827#define LURU &kLocalUdpToRelayUdp
828#define PURU &kPrflxUdpToRelayUdp
829#define LTLT &kLocalTcpToLocalTcp
830#define LTPT &kLocalTcpToPrflxTcp
831#define PTLT &kPrflxTcpToLocalTcp
832// TODO: Enable these once TestRelayServer can accept external TCP.
833#define LTRT NULL
834#define LSRS NULL
835
836// Test matrix. Originator behavior defined by rows, receiever by columns.
837
838// Currently the p2ptransportchannel.cc (specifically the
839// P2PTransportChannel::OnUnknownAddress) operates in 2 modes depend on the
840// remote candidates - ufrag per port or shared ufrag.
841// For example, if the remote candidates have the shared ufrag, for the unknown
842// address reaches the OnUnknownAddress, we will try to find the matched
843// remote candidate based on the address and protocol, if not found, a new
844// remote candidate will be created for this address. But if the remote
845// candidates have different ufrags, we will try to find the matched remote
846// candidate by comparing the ufrag. If not found, an error will be returned.
847// Because currently the shared ufrag feature is under the experiment and will
848// be rolled out gradually. We want to test the different combinations of peers
849// with/without the shared ufrag enabled. And those different combinations have
850// different expectation of the best connection. For example in the OpenToCONE
851// case, an unknown address will be updated to a "host" remote candidate if the
852// remote peer uses different ufrag per port. But in the shared ufrag case,
853// a "stun" (should be peer-reflexive eventually) candidate will be created for
854// that. So the expected best candidate will be LUSU instead of LULU.
855// With all these, we have to keep 2 test matrixes for the tests:
856// kMatrix - for the tests that the remote peer uses different ufrag per port.
857// kMatrixSharedUfrag - for the tests that remote peer uses shared ufrag.
858// The different between the two matrixes are on:
859// OPToCONE, OPTo2CON,
860// COToCONE, COToADDR, COToPORT, COToSYMM, COTo2CON, COToSCON,
861// ADToCONE, ADToADDR, ADTo2CON,
862// POToADDR,
863// SYToADDR,
864// 2CToCONE, 2CToADDR, 2CToPORT, 2CToSYMM, 2CTo2CON, 2CToSCON,
865// SCToADDR,
866
867// TODO: Fix NULLs caused by lack of TCP support in NATSocket.
868// TODO: Fix NULLs caused by no HTTP proxy support.
869// TODO: Rearrange rows/columns from best to worst.
870// TODO(ronghuawu): Keep only one test matrix once the shared ufrag is enabled.
871const P2PTransportChannelTest::Result*
872    P2PTransportChannelTest::kMatrix[NUM_CONFIGS][NUM_CONFIGS] = {
873//      OPEN  CONE  ADDR  PORT  SYMM  2CON  SCON  !UDP  !TCP  HTTP  PRXH  PRXS
874/*OP*/ {LULU, LULU, LULU, LULU, LULU, LULU, LULU, LTLT, LTLT, LSRS, NULL, LTLT},
875/*CO*/ {LULU, LULU, LULU, SULU, SULU, LULU, SULU, NULL, NULL, LSRS, NULL, LTRT},
876/*AD*/ {LULU, LULU, LULU, SUSU, SUSU, LULU, SUSU, NULL, NULL, LSRS, NULL, LTRT},
877/*PO*/ {LULU, LUSU, LUSU, SUSU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
878/*SY*/ {LULU, LUSU, LUSU, LURU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
879/*2C*/ {LULU, LULU, LULU, SULU, SULU, LULU, SULU, NULL, NULL, LSRS, NULL, LTRT},
880/*SC*/ {LULU, LUSU, LUSU, LURU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
881/*!U*/ {LTLT, NULL, NULL, NULL, NULL, NULL, NULL, LTLT, LTLT, LSRS, NULL, LTRT},
882/*!T*/ {LTRT, NULL, NULL, NULL, NULL, NULL, NULL, LTLT, LTRT, LSRS, NULL, LTRT},
883/*HT*/ {LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, NULL, LSRS},
884/*PR*/ {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
885/*PR*/ {LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LSRS, NULL, LTRT},
886};
887const P2PTransportChannelTest::Result*
888    P2PTransportChannelTest::kMatrixSharedUfrag[NUM_CONFIGS][NUM_CONFIGS] = {
889//      OPEN  CONE  ADDR  PORT  SYMM  2CON  SCON  !UDP  !TCP  HTTP  PRXH  PRXS
890/*OP*/ {LULU, LUSU, LULU, LULU, LULU, LUSU, LULU, LTLT, LTLT, LSRS, NULL, LTLT},
891/*CO*/ {LULU, LUSU, LUSU, SUSU, SUSU, LUSU, SUSU, NULL, NULL, LSRS, NULL, LTRT},
892/*AD*/ {LULU, LUSU, LUSU, SUSU, SUSU, LUSU, SUSU, NULL, NULL, LSRS, NULL, LTRT},
893/*PO*/ {LULU, LUSU, LUSU, SUSU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
894/*SY*/ {LULU, LUSU, LUSU, LURU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
895/*2C*/ {LULU, LUSU, LUSU, SUSU, SUSU, LUSU, SUSU, NULL, NULL, LSRS, NULL, LTRT},
896/*SC*/ {LULU, LUSU, LUSU, LURU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
897/*!U*/ {LTLT, NULL, NULL, NULL, NULL, NULL, NULL, LTLT, LTLT, LSRS, NULL, LTRT},
898/*!T*/ {LTRT, NULL, NULL, NULL, NULL, NULL, NULL, LTLT, LTRT, LSRS, NULL, LTRT},
899/*HT*/ {LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, NULL, LSRS},
900/*PR*/ {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
901/*PR*/ {LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LSRS, NULL, LTRT},
902};
903const P2PTransportChannelTest::Result*
904    P2PTransportChannelTest::kMatrixSharedSocketAsGice
905        [NUM_CONFIGS][NUM_CONFIGS] = {
906//      OPEN  CONE  ADDR  PORT  SYMM  2CON  SCON  !UDP  !TCP  HTTP  PRXH  PRXS
907/*OP*/ {LULU, LUSU, LUSU, LUSU, LUSU, LUSU, LUSU, LTLT, LTLT, LSRS, NULL, LTLT},
908/*CO*/ {LULU, LUSU, LUSU, LUSU, LUSU, LUSU, LUSU, NULL, NULL, LSRS, NULL, LTRT},
909/*AD*/ {LULU, LUSU, LUSU, LUSU, LUSU, LUSU, LUSU, NULL, NULL, LSRS, NULL, LTRT},
910/*PO*/ {LULU, LUSU, LUSU, LUSU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
911/*SY*/ {LULU, LUSU, LUSU, LURU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
912/*2C*/ {LULU, LUSU, LUSU, LUSU, LUSU, LUSU, LUSU, NULL, NULL, LSRS, NULL, LTRT},
913/*SC*/ {LULU, LUSU, LUSU, LURU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
914/*!U*/ {LTLT, NULL, NULL, NULL, NULL, NULL, NULL, LTLT, LTLT, LSRS, NULL, LTRT},
915/*!T*/ {LTRT, NULL, NULL, NULL, NULL, NULL, NULL, LTLT, LTRT, LSRS, NULL, LTRT},
916/*HT*/ {LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, NULL, LSRS},
917/*PR*/ {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
918/*PR*/ {LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LSRS, NULL, LTRT},
919};
920const P2PTransportChannelTest::Result*
921    P2PTransportChannelTest::kMatrixSharedSocketAsIce
922        [NUM_CONFIGS][NUM_CONFIGS] = {
923//      OPEN  CONE  ADDR  PORT  SYMM  2CON  SCON  !UDP  !TCP  HTTP  PRXH  PRXS
924/*OP*/ {LULU, LUSU, LUSU, LUSU, LUPU, LUSU, LUPU, PTLT, LTPT, LSRS, NULL, PTLT},
925/*CO*/ {LULU, LUSU, LUSU, LUSU, LUPU, LUSU, LUPU, NULL, NULL, LSRS, NULL, LTRT},
926/*AD*/ {LULU, LUSU, LUSU, LUSU, LUPU, LUSU, LUPU, NULL, NULL, LSRS, NULL, LTRT},
927/*PO*/ {LULU, LUSU, LUSU, LUSU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
928/*SY*/ {PULU, PUSU, PUSU, PURU, PURU, PUSU, PURU, NULL, NULL, LSRS, NULL, LTRT},
929/*2C*/ {LULU, LUSU, LUSU, LUSU, LUPU, LUSU, LUPU, NULL, NULL, LSRS, NULL, LTRT},
930/*SC*/ {PULU, PUSU, PUSU, PURU, PURU, PUSU, PURU, NULL, NULL, LSRS, NULL, LTRT},
931/*!U*/ {PTLT, NULL, NULL, NULL, NULL, NULL, NULL, PTLT, LTPT, LSRS, NULL, LTRT},
932/*!T*/ {LTRT, NULL, NULL, NULL, NULL, NULL, NULL, PTLT, LTRT, LSRS, NULL, LTRT},
933/*HT*/ {LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, NULL, LSRS},
934/*PR*/ {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
935/*PR*/ {LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LSRS, NULL, LTRT},
936};
937
938// The actual tests that exercise all the various configurations.
939// Test names are of the form P2PTransportChannelTest_TestOPENToNAT_FULL_CONE
940// Same test case is run in both GICE and ICE mode.
941// kDefaultStepDelay - is used for all Gice cases.
942// kMinimumStepDelay - is used when both end points have
943//                     PORTALLOCATOR_ENABLE_SHARED_UFRAG flag enabled.
944// Technically we should be able to use kMinimumStepDelay irrespective of
945// protocol type. But which might need modifications to current result matrices
946// for tests in this file.
947#define P2P_TEST_DECLARATION(x, y, z) \
948  TEST_F(P2PTransportChannelTest, z##Test##x##To##y##AsGiceNoneSharedUfrag) { \
949    ConfigureEndpoints(x, y, kDefaultPortAllocatorFlags, \
950                       kDefaultPortAllocatorFlags, \
951                       kDefaultStepDelay, kDefaultStepDelay, \
952                       cricket::ICEPROTO_GOOGLE); \
953    if (kMatrix[x][y] != NULL) \
954      Test(*kMatrix[x][y]); \
955    else \
956      LOG(LS_WARNING) << "Not yet implemented"; \
957  } \
958  TEST_F(P2PTransportChannelTest, z##Test##x##To##y##AsGiceP0SharedUfrag) { \
959    ConfigureEndpoints(x, y, PORTALLOCATOR_ENABLE_SHARED_UFRAG, \
960                       kDefaultPortAllocatorFlags, \
961                       kDefaultStepDelay, kDefaultStepDelay, \
962                       cricket::ICEPROTO_GOOGLE); \
963    if (kMatrix[x][y] != NULL) \
964      Test(*kMatrix[x][y]); \
965    else \
966      LOG(LS_WARNING) << "Not yet implemented"; \
967  } \
968  TEST_F(P2PTransportChannelTest, z##Test##x##To##y##AsGiceP1SharedUfrag) { \
969    ConfigureEndpoints(x, y, kDefaultPortAllocatorFlags, \
970                       PORTALLOCATOR_ENABLE_SHARED_UFRAG, \
971                       kDefaultStepDelay, kDefaultStepDelay, \
972                       cricket::ICEPROTO_GOOGLE); \
973    if (kMatrixSharedUfrag[x][y] != NULL) \
974      Test(*kMatrixSharedUfrag[x][y]); \
975    else \
976      LOG(LS_WARNING) << "Not yet implemented"; \
977  } \
978  TEST_F(P2PTransportChannelTest, z##Test##x##To##y##AsGiceBothSharedUfrag) { \
979    ConfigureEndpoints(x, y, PORTALLOCATOR_ENABLE_SHARED_UFRAG, \
980                       PORTALLOCATOR_ENABLE_SHARED_UFRAG, \
981                       kDefaultStepDelay, kDefaultStepDelay, \
982                       cricket::ICEPROTO_GOOGLE); \
983    if (kMatrixSharedUfrag[x][y] != NULL) \
984      Test(*kMatrixSharedUfrag[x][y]); \
985    else \
986      LOG(LS_WARNING) << "Not yet implemented"; \
987  } \
988  TEST_F(P2PTransportChannelTest, \
989         z##Test##x##To##y##AsGiceBothSharedUfragWithMinimumStepDelay) { \
990    ConfigureEndpoints(x, y, PORTALLOCATOR_ENABLE_SHARED_UFRAG, \
991                       PORTALLOCATOR_ENABLE_SHARED_UFRAG, \
992                       kMinimumStepDelay, kMinimumStepDelay, \
993                       cricket::ICEPROTO_GOOGLE); \
994    if (kMatrixSharedUfrag[x][y] != NULL) \
995      Test(*kMatrixSharedUfrag[x][y]); \
996    else \
997      LOG(LS_WARNING) << "Not yet implemented"; \
998  } \
999  TEST_F(P2PTransportChannelTest, \
1000         z##Test##x##To##y##AsGiceBothSharedUfragSocket) { \
1001    ConfigureEndpoints(x, y, PORTALLOCATOR_ENABLE_SHARED_UFRAG | \
1002                       PORTALLOCATOR_ENABLE_SHARED_SOCKET, \
1003                       PORTALLOCATOR_ENABLE_SHARED_UFRAG | \
1004                       PORTALLOCATOR_ENABLE_SHARED_SOCKET, \
1005                       kMinimumStepDelay, kMinimumStepDelay, \
1006                       cricket::ICEPROTO_GOOGLE); \
1007    if (kMatrixSharedSocketAsGice[x][y] != NULL) \
1008      Test(*kMatrixSharedSocketAsGice[x][y]); \
1009    else \
1010    LOG(LS_WARNING) << "Not yet implemented"; \
1011  } \
1012  TEST_F(P2PTransportChannelTest, z##Test##x##To##y##AsIce) { \
1013    ConfigureEndpoints(x, y, PORTALLOCATOR_ENABLE_SHARED_UFRAG | \
1014                       PORTALLOCATOR_ENABLE_SHARED_SOCKET, \
1015                       PORTALLOCATOR_ENABLE_SHARED_UFRAG | \
1016                       PORTALLOCATOR_ENABLE_SHARED_SOCKET, \
1017                       kMinimumStepDelay, kMinimumStepDelay, \
1018                       cricket::ICEPROTO_RFC5245); \
1019    if (kMatrixSharedSocketAsIce[x][y] != NULL) \
1020      Test(*kMatrixSharedSocketAsIce[x][y]); \
1021    else \
1022    LOG(LS_WARNING) << "Not yet implemented"; \
1023  }
1024
1025#define P2P_TEST(x, y) \
1026  P2P_TEST_DECLARATION(x, y,)
1027
1028#define FLAKY_P2P_TEST(x, y) \
1029  P2P_TEST_DECLARATION(x, y, DISABLED_)
1030
1031// TODO(holmer): Disabled due to randomly failing on webrtc buildbots.
1032// Issue: webrtc/2383
1033#define P2P_TEST_SET(x) \
1034  P2P_TEST(x, OPEN) \
1035  FLAKY_P2P_TEST(x, NAT_FULL_CONE) \
1036  FLAKY_P2P_TEST(x, NAT_ADDR_RESTRICTED) \
1037  P2P_TEST(x, NAT_PORT_RESTRICTED) \
1038  P2P_TEST(x, NAT_SYMMETRIC) \
1039  FLAKY_P2P_TEST(x, NAT_DOUBLE_CONE) \
1040  P2P_TEST(x, NAT_SYMMETRIC_THEN_CONE) \
1041  P2P_TEST(x, BLOCK_UDP) \
1042  P2P_TEST(x, BLOCK_UDP_AND_INCOMING_TCP) \
1043  P2P_TEST(x, BLOCK_ALL_BUT_OUTGOING_HTTP) \
1044  P2P_TEST(x, PROXY_HTTPS) \
1045  P2P_TEST(x, PROXY_SOCKS)
1046
1047#define FLAKY_P2P_TEST_SET(x) \
1048  P2P_TEST(x, OPEN) \
1049  P2P_TEST(x, NAT_FULL_CONE) \
1050  P2P_TEST(x, NAT_ADDR_RESTRICTED) \
1051  P2P_TEST(x, NAT_PORT_RESTRICTED) \
1052  P2P_TEST(x, NAT_SYMMETRIC) \
1053  P2P_TEST(x, NAT_DOUBLE_CONE) \
1054  P2P_TEST(x, NAT_SYMMETRIC_THEN_CONE) \
1055  P2P_TEST(x, BLOCK_UDP) \
1056  P2P_TEST(x, BLOCK_UDP_AND_INCOMING_TCP) \
1057  P2P_TEST(x, BLOCK_ALL_BUT_OUTGOING_HTTP) \
1058  P2P_TEST(x, PROXY_HTTPS) \
1059  P2P_TEST(x, PROXY_SOCKS)
1060
1061P2P_TEST_SET(OPEN)
1062P2P_TEST_SET(NAT_FULL_CONE)
1063P2P_TEST_SET(NAT_ADDR_RESTRICTED)
1064P2P_TEST_SET(NAT_PORT_RESTRICTED)
1065P2P_TEST_SET(NAT_SYMMETRIC)
1066P2P_TEST_SET(NAT_DOUBLE_CONE)
1067P2P_TEST_SET(NAT_SYMMETRIC_THEN_CONE)
1068P2P_TEST_SET(BLOCK_UDP)
1069P2P_TEST_SET(BLOCK_UDP_AND_INCOMING_TCP)
1070P2P_TEST_SET(BLOCK_ALL_BUT_OUTGOING_HTTP)
1071P2P_TEST_SET(PROXY_HTTPS)
1072P2P_TEST_SET(PROXY_SOCKS)
1073
1074// Test that we restart candidate allocation when local ufrag&pwd changed.
1075// Standard Ice protocol is used.
1076TEST_F(P2PTransportChannelTest, HandleUfragPwdChangeAsIce) {
1077  ConfigureEndpoints(OPEN, OPEN,
1078                     PORTALLOCATOR_ENABLE_SHARED_UFRAG,
1079                     PORTALLOCATOR_ENABLE_SHARED_UFRAG,
1080                     kMinimumStepDelay, kMinimumStepDelay,
1081                     cricket::ICEPROTO_RFC5245);
1082  CreateChannels(1);
1083  TestHandleIceUfragPasswordChanged();
1084}
1085
1086// Test that we restart candidate allocation when local ufrag&pwd changed.
1087// Standard Ice protocol is used.
1088TEST_F(P2PTransportChannelTest, HandleUfragPwdChangeBundleAsIce) {
1089  ConfigureEndpoints(OPEN, OPEN,
1090                     PORTALLOCATOR_ENABLE_SHARED_UFRAG,
1091                     PORTALLOCATOR_ENABLE_SHARED_UFRAG,
1092                     kMinimumStepDelay, kMinimumStepDelay,
1093                     cricket::ICEPROTO_RFC5245);
1094  SetAllocatorFlags(0, cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1095  SetAllocatorFlags(1, cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1096
1097  CreateChannels(2);
1098  TestHandleIceUfragPasswordChanged();
1099}
1100
1101// Test that we restart candidate allocation when local ufrag&pwd changed.
1102// Google Ice protocol is used.
1103TEST_F(P2PTransportChannelTest, HandleUfragPwdChangeAsGice) {
1104  ConfigureEndpoints(OPEN, OPEN,
1105                     PORTALLOCATOR_ENABLE_SHARED_UFRAG,
1106                     PORTALLOCATOR_ENABLE_SHARED_UFRAG,
1107                     kDefaultStepDelay, kDefaultStepDelay,
1108                     cricket::ICEPROTO_GOOGLE);
1109  CreateChannels(1);
1110  TestHandleIceUfragPasswordChanged();
1111}
1112
1113// Test that ICE restart works when bundle is enabled.
1114// Google Ice protocol is used.
1115TEST_F(P2PTransportChannelTest, HandleUfragPwdChangeBundleAsGice) {
1116  ConfigureEndpoints(OPEN, OPEN,
1117                     PORTALLOCATOR_ENABLE_SHARED_UFRAG,
1118                     PORTALLOCATOR_ENABLE_SHARED_UFRAG,
1119                     kDefaultStepDelay, kDefaultStepDelay,
1120                     cricket::ICEPROTO_GOOGLE);
1121  SetAllocatorFlags(0, cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1122  SetAllocatorFlags(1, cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1123
1124  CreateChannels(2);
1125  TestHandleIceUfragPasswordChanged();
1126}
1127
1128// Test the operation of GetStats.
1129TEST_F(P2PTransportChannelTest, GetStats) {
1130  ConfigureEndpoints(OPEN, OPEN,
1131                     kDefaultPortAllocatorFlags,
1132                     kDefaultPortAllocatorFlags,
1133                     kDefaultStepDelay, kDefaultStepDelay,
1134                     cricket::ICEPROTO_GOOGLE);
1135  CreateChannels(1);
1136  EXPECT_TRUE_WAIT_MARGIN(ep1_ch1()->readable() && ep1_ch1()->writable() &&
1137                          ep2_ch1()->readable() && ep2_ch1()->writable(),
1138                          1000, 1000);
1139  TestSendRecv(1);
1140  cricket::ConnectionInfos infos;
1141  ASSERT_TRUE(ep1_ch1()->GetStats(&infos));
1142  ASSERT_EQ(1U, infos.size());
1143  EXPECT_TRUE(infos[0].new_connection);
1144  EXPECT_TRUE(infos[0].best_connection);
1145  EXPECT_TRUE(infos[0].readable);
1146  EXPECT_TRUE(infos[0].writable);
1147  EXPECT_FALSE(infos[0].timeout);
1148  EXPECT_EQ(10 * 36U, infos[0].sent_total_bytes);
1149  EXPECT_EQ(10 * 36U, infos[0].recv_total_bytes);
1150  EXPECT_GT(infos[0].rtt, 0U);
1151  DestroyChannels();
1152}
1153
1154// Test that we properly handle getting a STUN error due to slow signaling.
1155TEST_F(P2PTransportChannelTest, DISABLED_SlowSignaling) {
1156  ConfigureEndpoints(OPEN, NAT_SYMMETRIC,
1157                     kDefaultPortAllocatorFlags,
1158                     kDefaultPortAllocatorFlags,
1159                     kDefaultStepDelay, kDefaultStepDelay,
1160                     cricket::ICEPROTO_GOOGLE);
1161  // Make signaling from the callee take 500ms, so that the initial STUN pings
1162  // from the callee beat the signaling, and so the caller responds with a
1163  // unknown username error. We should just eat that and carry on; mishandling
1164  // this will instead cause all the callee's connections to be discarded.
1165  SetSignalingDelay(1, 1000);
1166  CreateChannels(1);
1167  const cricket::Connection* best_connection = NULL;
1168  // Wait until the callee's connections are created.
1169  WAIT((best_connection = ep2_ch1()->best_connection()) != NULL, 1000);
1170  // Wait to see if they get culled; they shouldn't.
1171  WAIT(ep2_ch1()->best_connection() != best_connection, 1000);
1172  EXPECT_TRUE(ep2_ch1()->best_connection() == best_connection);
1173  DestroyChannels();
1174}
1175
1176// Test that if remote candidates don't have ufrag and pwd, we still work.
1177TEST_F(P2PTransportChannelTest, RemoteCandidatesWithoutUfragPwd) {
1178  set_clear_remote_candidates_ufrag_pwd(true);
1179  ConfigureEndpoints(OPEN, OPEN,
1180                     PORTALLOCATOR_ENABLE_SHARED_UFRAG,
1181                     PORTALLOCATOR_ENABLE_SHARED_UFRAG,
1182                     kMinimumStepDelay, kMinimumStepDelay,
1183                     cricket::ICEPROTO_GOOGLE);
1184  CreateChannels(1);
1185  const cricket::Connection* best_connection = NULL;
1186  // Wait until the callee's connections are created.
1187  WAIT((best_connection = ep2_ch1()->best_connection()) != NULL, 1000);
1188  // Wait to see if they get culled; they shouldn't.
1189  WAIT(ep2_ch1()->best_connection() != best_connection, 1000);
1190  EXPECT_TRUE(ep2_ch1()->best_connection() == best_connection);
1191  DestroyChannels();
1192}
1193
1194// Test that a host behind NAT cannot be reached when incoming_only
1195// is set to true.
1196TEST_F(P2PTransportChannelTest, IncomingOnlyBlocked) {
1197  ConfigureEndpoints(NAT_FULL_CONE, OPEN,
1198                     kDefaultPortAllocatorFlags,
1199                     kDefaultPortAllocatorFlags,
1200                     kDefaultStepDelay, kDefaultStepDelay,
1201                     cricket::ICEPROTO_GOOGLE);
1202
1203  SetAllocatorFlags(0, kOnlyLocalPorts);
1204  CreateChannels(1);
1205  ep1_ch1()->set_incoming_only(true);
1206
1207  // Pump for 1 second and verify that the channels are not connected.
1208  talk_base::Thread::Current()->ProcessMessages(1000);
1209
1210  EXPECT_FALSE(ep1_ch1()->readable());
1211  EXPECT_FALSE(ep1_ch1()->writable());
1212  EXPECT_FALSE(ep2_ch1()->readable());
1213  EXPECT_FALSE(ep2_ch1()->writable());
1214
1215  DestroyChannels();
1216}
1217
1218// Test that a peer behind NAT can connect to a peer that has
1219// incoming_only flag set.
1220TEST_F(P2PTransportChannelTest, IncomingOnlyOpen) {
1221  ConfigureEndpoints(OPEN, NAT_FULL_CONE,
1222                     kDefaultPortAllocatorFlags,
1223                     kDefaultPortAllocatorFlags,
1224                     kDefaultStepDelay, kDefaultStepDelay,
1225                     cricket::ICEPROTO_GOOGLE);
1226
1227  SetAllocatorFlags(0, kOnlyLocalPorts);
1228  CreateChannels(1);
1229  ep1_ch1()->set_incoming_only(true);
1230
1231  EXPECT_TRUE_WAIT_MARGIN(ep1_ch1() != NULL && ep2_ch1() != NULL &&
1232                          ep1_ch1()->readable() && ep1_ch1()->writable() &&
1233                          ep2_ch1()->readable() && ep2_ch1()->writable(),
1234                          1000, 1000);
1235
1236  DestroyChannels();
1237}
1238
1239TEST_F(P2PTransportChannelTest, TestTcpConnectionsFromActiveToPassive) {
1240  AddAddress(0, kPublicAddrs[0]);
1241  AddAddress(1, kPublicAddrs[1]);
1242
1243  SetAllocationStepDelay(0, kMinimumStepDelay);
1244  SetAllocationStepDelay(1, kMinimumStepDelay);
1245
1246  int kOnlyLocalTcpPorts = cricket::PORTALLOCATOR_DISABLE_UDP |
1247                           cricket::PORTALLOCATOR_DISABLE_STUN |
1248                           cricket::PORTALLOCATOR_DISABLE_RELAY |
1249                           cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG;
1250  // Disable all protocols except TCP.
1251  SetAllocatorFlags(0, kOnlyLocalTcpPorts);
1252  SetAllocatorFlags(1, kOnlyLocalTcpPorts);
1253
1254  SetAllowTcpListen(0, true);   // actpass.
1255  SetAllowTcpListen(1, false);  // active.
1256
1257  CreateChannels(1);
1258
1259  EXPECT_TRUE_WAIT(ep1_ch1()->readable() && ep1_ch1()->writable() &&
1260                   ep2_ch1()->readable() && ep2_ch1()->writable(),
1261                   1000);
1262  EXPECT_TRUE(
1263      ep1_ch1()->best_connection() && ep2_ch1()->best_connection() &&
1264      LocalCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[0]) &&
1265      RemoteCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[1]));
1266
1267  std::string kTcpProtocol = "tcp";
1268  EXPECT_EQ(kTcpProtocol, RemoteCandidate(ep1_ch1())->protocol());
1269  EXPECT_EQ(kTcpProtocol, LocalCandidate(ep1_ch1())->protocol());
1270  EXPECT_EQ(kTcpProtocol, RemoteCandidate(ep2_ch1())->protocol());
1271  EXPECT_EQ(kTcpProtocol, LocalCandidate(ep2_ch1())->protocol());
1272
1273  TestSendRecv(1);
1274  DestroyChannels();
1275}
1276
1277TEST_F(P2PTransportChannelTest, TestBundleAllocatorToBundleAllocator) {
1278  AddAddress(0, kPublicAddrs[0]);
1279  AddAddress(1, kPublicAddrs[1]);
1280  SetAllocatorFlags(0, cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1281  SetAllocatorFlags(1, cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1282
1283  CreateChannels(2);
1284
1285  EXPECT_TRUE_WAIT(ep1_ch1()->readable() &&
1286                   ep1_ch1()->writable() &&
1287                   ep2_ch1()->readable() &&
1288                   ep2_ch1()->writable(),
1289                   1000);
1290  EXPECT_TRUE(ep1_ch1()->best_connection() &&
1291              ep2_ch1()->best_connection());
1292
1293  EXPECT_FALSE(ep1_ch2()->readable());
1294  EXPECT_FALSE(ep1_ch2()->writable());
1295  EXPECT_FALSE(ep2_ch2()->readable());
1296  EXPECT_FALSE(ep2_ch2()->writable());
1297
1298  TestSendRecv(1);  // Only 1 channel is writable per Endpoint.
1299  DestroyChannels();
1300}
1301
1302TEST_F(P2PTransportChannelTest, TestBundleAllocatorToNonBundleAllocator) {
1303  AddAddress(0, kPublicAddrs[0]);
1304  AddAddress(1, kPublicAddrs[1]);
1305  // Enable BUNDLE flag at one side.
1306  SetAllocatorFlags(0, cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1307
1308  CreateChannels(2);
1309
1310  EXPECT_TRUE_WAIT(ep1_ch1()->readable() &&
1311                   ep1_ch1()->writable() &&
1312                   ep2_ch1()->readable() &&
1313                   ep2_ch1()->writable(),
1314                   1000);
1315  EXPECT_TRUE_WAIT(ep1_ch2()->readable() &&
1316                   ep1_ch2()->writable() &&
1317                   ep2_ch2()->readable() &&
1318                   ep2_ch2()->writable(),
1319                   1000);
1320
1321  EXPECT_TRUE(ep1_ch1()->best_connection() &&
1322              ep2_ch1()->best_connection());
1323  EXPECT_TRUE(ep1_ch2()->best_connection() &&
1324              ep2_ch2()->best_connection());
1325
1326  TestSendRecv(2);
1327  DestroyChannels();
1328}
1329
1330TEST_F(P2PTransportChannelTest, TestIceRoleConflictWithoutBundle) {
1331  AddAddress(0, kPublicAddrs[0]);
1332  AddAddress(1, kPublicAddrs[1]);
1333  TestSignalRoleConflict();
1334}
1335
1336TEST_F(P2PTransportChannelTest, TestIceRoleConflictWithBundle) {
1337  AddAddress(0, kPublicAddrs[0]);
1338  AddAddress(1, kPublicAddrs[1]);
1339  SetAllocatorFlags(0, cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1340  SetAllocatorFlags(1, cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1341  TestSignalRoleConflict();
1342}
1343
1344// Tests that the ice configs (protocol, tiebreaker and role) can be passed
1345// down to ports.
1346TEST_F(P2PTransportChannelTest, TestIceConfigWillPassDownToPort) {
1347  AddAddress(0, kPublicAddrs[0]);
1348  AddAddress(1, kPublicAddrs[1]);
1349
1350  SetIceRole(0, cricket::ICEROLE_CONTROLLING);
1351  SetIceProtocol(0, cricket::ICEPROTO_GOOGLE);
1352  SetIceTiebreaker(0, kTiebreaker1);
1353  SetIceRole(1, cricket::ICEROLE_CONTROLLING);
1354  SetIceProtocol(1, cricket::ICEPROTO_RFC5245);
1355  SetIceTiebreaker(1, kTiebreaker2);
1356
1357  CreateChannels(1);
1358
1359  EXPECT_EQ_WAIT(2u, ep1_ch1()->ports().size(), 1000);
1360
1361  const std::vector<cricket::PortInterface *> ports_before = ep1_ch1()->ports();
1362  for (size_t i = 0; i < ports_before.size(); ++i) {
1363    EXPECT_EQ(cricket::ICEROLE_CONTROLLING, ports_before[i]->GetIceRole());
1364    EXPECT_EQ(cricket::ICEPROTO_GOOGLE, ports_before[i]->IceProtocol());
1365    EXPECT_EQ(kTiebreaker1, ports_before[i]->IceTiebreaker());
1366  }
1367
1368  ep1_ch1()->SetIceRole(cricket::ICEROLE_CONTROLLED);
1369  ep1_ch1()->SetIceProtocolType(cricket::ICEPROTO_RFC5245);
1370  ep1_ch1()->SetIceTiebreaker(kTiebreaker2);
1371
1372  const std::vector<cricket::PortInterface *> ports_after = ep1_ch1()->ports();
1373  for (size_t i = 0; i < ports_after.size(); ++i) {
1374    EXPECT_EQ(cricket::ICEROLE_CONTROLLED, ports_before[i]->GetIceRole());
1375    EXPECT_EQ(cricket::ICEPROTO_RFC5245, ports_before[i]->IceProtocol());
1376    // SetIceTiebreaker after Connect() has been called will fail. So expect the
1377    // original value.
1378    EXPECT_EQ(kTiebreaker1, ports_before[i]->IceTiebreaker());
1379  }
1380
1381  EXPECT_TRUE_WAIT(ep1_ch1()->readable() &&
1382                   ep1_ch1()->writable() &&
1383                   ep2_ch1()->readable() &&
1384                   ep2_ch1()->writable(),
1385                   1000);
1386
1387  EXPECT_TRUE(ep1_ch1()->best_connection() &&
1388              ep2_ch1()->best_connection());
1389
1390  TestSendRecv(1);
1391}
1392
1393// Verify that we can set DSCP value and retrieve properly from P2PTC.
1394TEST_F(P2PTransportChannelTest, TestDefaultDscpValue) {
1395  AddAddress(0, kPublicAddrs[0]);
1396  AddAddress(1, kPublicAddrs[1]);
1397
1398  CreateChannels(1);
1399  EXPECT_EQ(talk_base::DSCP_NO_CHANGE,
1400            GetEndpoint(0)->cd1_.ch_->DefaultDscpValue());
1401  EXPECT_EQ(talk_base::DSCP_NO_CHANGE,
1402            GetEndpoint(1)->cd1_.ch_->DefaultDscpValue());
1403  GetEndpoint(0)->cd1_.ch_->SetOption(
1404      talk_base::Socket::OPT_DSCP, talk_base::DSCP_CS6);
1405  GetEndpoint(1)->cd1_.ch_->SetOption(
1406      talk_base::Socket::OPT_DSCP, talk_base::DSCP_CS6);
1407  EXPECT_EQ(talk_base::DSCP_CS6,
1408            GetEndpoint(0)->cd1_.ch_->DefaultDscpValue());
1409  EXPECT_EQ(talk_base::DSCP_CS6,
1410            GetEndpoint(1)->cd1_.ch_->DefaultDscpValue());
1411  GetEndpoint(0)->cd1_.ch_->SetOption(
1412      talk_base::Socket::OPT_DSCP, talk_base::DSCP_AF41);
1413  GetEndpoint(1)->cd1_.ch_->SetOption(
1414      talk_base::Socket::OPT_DSCP, talk_base::DSCP_AF41);
1415  EXPECT_EQ(talk_base::DSCP_AF41,
1416            GetEndpoint(0)->cd1_.ch_->DefaultDscpValue());
1417  EXPECT_EQ(talk_base::DSCP_AF41,
1418            GetEndpoint(1)->cd1_.ch_->DefaultDscpValue());
1419}
1420
1421// Verify IPv6 connection is preferred over IPv4.
1422TEST_F(P2PTransportChannelTest, TestIPv6Connections) {
1423  AddAddress(0, kIPv6PublicAddrs[0]);
1424  AddAddress(0, kPublicAddrs[0]);
1425  AddAddress(1, kIPv6PublicAddrs[1]);
1426  AddAddress(1, kPublicAddrs[1]);
1427
1428  SetAllocationStepDelay(0, kMinimumStepDelay);
1429  SetAllocationStepDelay(1, kMinimumStepDelay);
1430
1431  // Enable IPv6
1432  SetAllocatorFlags(0, cricket::PORTALLOCATOR_ENABLE_IPV6);
1433  SetAllocatorFlags(1, cricket::PORTALLOCATOR_ENABLE_IPV6);
1434
1435  CreateChannels(1);
1436
1437  EXPECT_TRUE_WAIT(ep1_ch1()->readable() && ep1_ch1()->writable() &&
1438                   ep2_ch1()->readable() && ep2_ch1()->writable(),
1439                   1000);
1440  EXPECT_TRUE(
1441      ep1_ch1()->best_connection() && ep2_ch1()->best_connection() &&
1442      LocalCandidate(ep1_ch1())->address().EqualIPs(kIPv6PublicAddrs[0]) &&
1443      RemoteCandidate(ep1_ch1())->address().EqualIPs(kIPv6PublicAddrs[1]));
1444
1445  TestSendRecv(1);
1446  DestroyChannels();
1447}
1448
1449// Test what happens when we have 2 users behind the same NAT. This can lead
1450// to interesting behavior because the STUN server will only give out the
1451// address of the outermost NAT.
1452class P2PTransportChannelSameNatTest : public P2PTransportChannelTestBase {
1453 protected:
1454  void ConfigureEndpoints(Config nat_type, Config config1, Config config2) {
1455    ASSERT(nat_type >= NAT_FULL_CONE && nat_type <= NAT_SYMMETRIC);
1456    talk_base::NATSocketServer::Translator* outer_nat =
1457        nat()->AddTranslator(kPublicAddrs[0], kNatAddrs[0],
1458            static_cast<talk_base::NATType>(nat_type - NAT_FULL_CONE));
1459    ConfigureEndpoint(outer_nat, 0, config1);
1460    ConfigureEndpoint(outer_nat, 1, config2);
1461  }
1462  void ConfigureEndpoint(talk_base::NATSocketServer::Translator* nat,
1463                         int endpoint, Config config) {
1464    ASSERT(config <= NAT_SYMMETRIC);
1465    if (config == OPEN) {
1466      AddAddress(endpoint, kPrivateAddrs[endpoint]);
1467      nat->AddClient(kPrivateAddrs[endpoint]);
1468    } else {
1469      AddAddress(endpoint, kCascadedPrivateAddrs[endpoint]);
1470      nat->AddTranslator(kPrivateAddrs[endpoint], kCascadedNatAddrs[endpoint],
1471          static_cast<talk_base::NATType>(config - NAT_FULL_CONE))->AddClient(
1472              kCascadedPrivateAddrs[endpoint]);
1473    }
1474  }
1475};
1476
1477TEST_F(P2PTransportChannelSameNatTest, TestConesBehindSameCone) {
1478  ConfigureEndpoints(NAT_FULL_CONE, NAT_FULL_CONE, NAT_FULL_CONE);
1479  Test(kLocalUdpToStunUdp);
1480}
1481
1482// Test what happens when we have multiple available pathways.
1483// In the future we will try different RTTs and configs for the different
1484// interfaces, so that we can simulate a user with Ethernet and VPN networks.
1485class P2PTransportChannelMultihomedTest : public P2PTransportChannelTestBase {
1486};
1487
1488// Test that we can establish connectivity when both peers are multihomed.
1489TEST_F(P2PTransportChannelMultihomedTest, DISABLED_TestBasic) {
1490  AddAddress(0, kPublicAddrs[0]);
1491  AddAddress(0, kAlternateAddrs[0]);
1492  AddAddress(1, kPublicAddrs[1]);
1493  AddAddress(1, kAlternateAddrs[1]);
1494  Test(kLocalUdpToLocalUdp);
1495}
1496
1497// Test that we can quickly switch links if an interface goes down.
1498TEST_F(P2PTransportChannelMultihomedTest, TestFailover) {
1499  AddAddress(0, kPublicAddrs[0]);
1500  AddAddress(1, kPublicAddrs[1]);
1501  AddAddress(1, kAlternateAddrs[1]);
1502  // Use only local ports for simplicity.
1503  SetAllocatorFlags(0, kOnlyLocalPorts);
1504  SetAllocatorFlags(1, kOnlyLocalPorts);
1505
1506  // Create channels and let them go writable, as usual.
1507  CreateChannels(1);
1508  EXPECT_TRUE_WAIT(ep1_ch1()->readable() && ep1_ch1()->writable() &&
1509                   ep2_ch1()->readable() && ep2_ch1()->writable(),
1510                   1000);
1511  EXPECT_TRUE(
1512      ep1_ch1()->best_connection() && ep2_ch1()->best_connection() &&
1513      LocalCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[0]) &&
1514      RemoteCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[1]));
1515
1516  // Blackhole any traffic to or from the public addrs.
1517  LOG(LS_INFO) << "Failing over...";
1518  fw()->AddRule(false, talk_base::FP_ANY, talk_base::FD_ANY,
1519                kPublicAddrs[1]);
1520
1521  // We should detect loss of connectivity within 5 seconds or so.
1522  EXPECT_TRUE_WAIT(!ep1_ch1()->writable(), 7000);
1523
1524  // We should switch over to use the alternate addr immediately
1525  // when we lose writability.
1526  EXPECT_TRUE_WAIT(
1527      ep1_ch1()->best_connection() && ep2_ch1()->best_connection() &&
1528      LocalCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[0]) &&
1529      RemoteCandidate(ep1_ch1())->address().EqualIPs(kAlternateAddrs[1]),
1530      3000);
1531
1532  DestroyChannels();
1533}
1534
1535// Test that we can switch links in a coordinated fashion.
1536TEST_F(P2PTransportChannelMultihomedTest, TestDrain) {
1537  AddAddress(0, kPublicAddrs[0]);
1538  AddAddress(1, kPublicAddrs[1]);
1539  // Use only local ports for simplicity.
1540  SetAllocatorFlags(0, kOnlyLocalPorts);
1541  SetAllocatorFlags(1, kOnlyLocalPorts);
1542
1543  // Create channels and let them go writable, as usual.
1544  CreateChannels(1);
1545  EXPECT_TRUE_WAIT(ep1_ch1()->readable() && ep1_ch1()->writable() &&
1546                   ep2_ch1()->readable() && ep2_ch1()->writable(),
1547                   1000);
1548  EXPECT_TRUE(
1549      ep1_ch1()->best_connection() && ep2_ch1()->best_connection() &&
1550      LocalCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[0]) &&
1551      RemoteCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[1]));
1552
1553  // Remove the public interface, add the alternate interface, and allocate
1554  // a new generation of candidates for the new interface (via Connect()).
1555  LOG(LS_INFO) << "Draining...";
1556  AddAddress(1, kAlternateAddrs[1]);
1557  RemoveAddress(1, kPublicAddrs[1]);
1558  ep2_ch1()->Connect();
1559
1560  // We should switch over to use the alternate address after
1561  // an exchange of pings.
1562  EXPECT_TRUE_WAIT(
1563      ep1_ch1()->best_connection() && ep2_ch1()->best_connection() &&
1564      LocalCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[0]) &&
1565      RemoteCandidate(ep1_ch1())->address().EqualIPs(kAlternateAddrs[1]),
1566      3000);
1567
1568  DestroyChannels();
1569}
Note: See TracBrowser for help on using the repository browser.