Home | History | Annotate | Download | only in base
      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 
     46 using cricket::kDefaultPortAllocatorFlags;
     47 using cricket::kMinimumStepDelay;
     48 using cricket::kDefaultStepDelay;
     49 using cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG;
     50 using cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET;
     51 using talk_base::SocketAddress;
     52 
     53 static const int kDefaultTimeout = 1000;
     54 static const int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
     55                                    cricket::PORTALLOCATOR_DISABLE_RELAY |
     56                                    cricket::PORTALLOCATOR_DISABLE_TCP;
     57 // Addresses on the public internet.
     58 static const SocketAddress kPublicAddrs[2] =
     59     { SocketAddress("11.11.11.11", 0), SocketAddress("22.22.22.22", 0) };
     60 // IPv6 Addresses on the public internet.
     61 static 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.
     66 static const SocketAddress kAlternateAddrs[2] =
     67     { SocketAddress("11.11.11.101", 0), SocketAddress("22.22.22.202", 0) };
     68 // Addresses for HTTP proxy servers.
     69 static const SocketAddress kHttpsProxyAddrs[2] =
     70     { SocketAddress("11.11.11.1", 443), SocketAddress("22.22.22.1", 443) };
     71 // Addresses for SOCKS proxy servers.
     72 static const SocketAddress kSocksProxyAddrs[2] =
     73     { SocketAddress("11.11.11.1", 1080), SocketAddress("22.22.22.1", 1080) };
     74 // Internal addresses for NAT boxes.
     75 static 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.
     78 static 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.
     81 static 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.
     84 static 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.
     87 static const SocketAddress kStunAddr("99.99.99.1", cricket::STUN_SERVER_PORT);
     88 // The addresses for the public relay server.
     89 static const SocketAddress kRelayUdpIntAddr("99.99.99.2", 5000);
     90 static const SocketAddress kRelayUdpExtAddr("99.99.99.3", 5001);
     91 static const SocketAddress kRelayTcpIntAddr("99.99.99.2", 5002);
     92 static const SocketAddress kRelayTcpExtAddr("99.99.99.3", 5003);
     93 static const SocketAddress kRelaySslTcpIntAddr("99.99.99.2", 5004);
     94 static const SocketAddress kRelaySslTcpExtAddr("99.99.99.3", 5005);
     95 
     96 // Based on ICE_UFRAG_LENGTH
     97 static const char* kIceUfrag[4] = {"TESTICEUFRAG0000", "TESTICEUFRAG0001",
     98                                    "TESTICEUFRAG0002", "TESTICEUFRAG0003"};
     99 // Based on ICE_PWD_LENGTH
    100 static const char* kIcePwd[4] = {"TESTICEPWD00000000000000",
    101                                  "TESTICEPWD00000000000001",
    102                                  "TESTICEPWD00000000000002",
    103                                  "TESTICEPWD00000000000003"};
    104 
    105 static const uint64 kTiebreaker1 = 11111;
    106 static 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.
    123 class 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, const talk_base::PacketTime& packet_time,
    617                     int flags) {
    618     std::list<std::string>& packets = GetPacketList(channel);
    619     packets.push_front(std::string(data, len));
    620   }
    621   void OnRoleConflict(cricket::TransportChannelImpl* channel) {
    622     GetEndpoint(channel)->OnRoleConflict(true);
    623     cricket::IceRole new_role =
    624         GetEndpoint(channel)->ice_role() == cricket::ICEROLE_CONTROLLING ?
    625             cricket::ICEROLE_CONTROLLED : cricket::ICEROLE_CONTROLLING;
    626     channel->SetIceRole(new_role);
    627   }
    628   int SendData(cricket::TransportChannel* channel,
    629                const char* data, size_t len) {
    630     return channel->SendPacket(data, len, talk_base::DSCP_NO_CHANGE, 0);
    631   }
    632   bool CheckDataOnChannel(cricket::TransportChannel* channel,
    633                           const char* data, int len) {
    634     return GetChannelData(channel)->CheckData(data, len);
    635   }
    636   static const cricket::Candidate* LocalCandidate(
    637       cricket::P2PTransportChannel* ch) {
    638     return (ch && ch->best_connection()) ?
    639         &ch->best_connection()->local_candidate() : NULL;
    640   }
    641   static const cricket::Candidate* RemoteCandidate(
    642       cricket::P2PTransportChannel* ch) {
    643     return (ch && ch->best_connection()) ?
    644         &ch->best_connection()->remote_candidate() : NULL;
    645   }
    646   Endpoint* GetEndpoint(cricket::TransportChannel* ch) {
    647     if (ep1_.HasChannel(ch)) {
    648       return &ep1_;
    649     } else if (ep2_.HasChannel(ch)) {
    650       return &ep2_;
    651     } else {
    652       return NULL;
    653     }
    654   }
    655   cricket::P2PTransportChannel* GetRemoteChannel(
    656       cricket::TransportChannel* ch) {
    657     if (ch == ep1_ch1())
    658       return ep2_ch1();
    659     else if (ch == ep1_ch2())
    660       return ep2_ch2();
    661     else if (ch == ep2_ch1())
    662       return ep1_ch1();
    663     else if (ch == ep2_ch2())
    664       return ep1_ch2();
    665     else
    666       return NULL;
    667   }
    668   std::list<std::string>& GetPacketList(cricket::TransportChannel* ch) {
    669     return GetChannelData(ch)->ch_packets_;
    670   }
    671 
    672   void set_clear_remote_candidates_ufrag_pwd(bool clear) {
    673     clear_remote_candidates_ufrag_pwd_ = clear;
    674   }
    675 
    676  private:
    677   talk_base::Thread* main_;
    678   talk_base::scoped_ptr<talk_base::PhysicalSocketServer> pss_;
    679   talk_base::scoped_ptr<talk_base::VirtualSocketServer> vss_;
    680   talk_base::scoped_ptr<talk_base::NATSocketServer> nss_;
    681   talk_base::scoped_ptr<talk_base::FirewallSocketServer> ss_;
    682   talk_base::SocketServerScope ss_scope_;
    683   cricket::TestStunServer stun_server_;
    684   cricket::TestRelayServer relay_server_;
    685   talk_base::SocksProxyServer socks_server1_;
    686   talk_base::SocksProxyServer socks_server2_;
    687   Endpoint ep1_;
    688   Endpoint ep2_;
    689   bool clear_remote_candidates_ufrag_pwd_;
    690 };
    691 
    692 // The tests have only a few outcomes, which we predefine.
    693 const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
    694     kLocalUdpToLocalUdp("local", "udp", "local", "udp",
    695                         "local", "udp", "local", "udp", 1000);
    696 const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
    697     kLocalUdpToStunUdp("local", "udp", "stun", "udp",
    698                        "local", "udp", "stun", "udp", 1000);
    699 const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
    700     kLocalUdpToPrflxUdp("local", "udp", "prflx", "udp",
    701                         "prflx", "udp", "local", "udp", 1000);
    702 const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
    703     kPrflxUdpToLocalUdp("prflx", "udp", "local", "udp",
    704                         "local", "udp", "prflx", "udp", 1000);
    705 const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
    706     kStunUdpToLocalUdp("stun", "udp", "local", "udp",
    707                        "local", "udp", "stun", "udp", 1000);
    708 const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
    709     kStunUdpToStunUdp("stun", "udp", "stun", "udp",
    710                       "stun", "udp", "stun", "udp", 1000);
    711 const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
    712     kPrflxUdpToStunUdp("prflx", "udp", "stun", "udp",
    713                        "local", "udp", "prflx", "udp", 1000);
    714 const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
    715     kLocalUdpToRelayUdp("local", "udp", "relay", "udp",
    716                         "relay", "udp", "local", "udp", 2000);
    717 const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
    718     kPrflxUdpToRelayUdp("prflx", "udp", "relay", "udp",
    719                         "relay", "udp", "prflx", "udp", 2000);
    720 const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
    721     kLocalTcpToLocalTcp("local", "tcp", "local", "tcp",
    722                         "local", "tcp", "local", "tcp", 3000);
    723 const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
    724     kLocalTcpToPrflxTcp("local", "tcp", "prflx", "tcp",
    725                         "prflx", "tcp", "local", "tcp", 3000);
    726 const P2PTransportChannelTestBase::Result P2PTransportChannelTestBase::
    727     kPrflxTcpToLocalTcp("prflx", "tcp", "local", "tcp",
    728                         "local", "tcp", "prflx", "tcp", 3000);
    729 
    730 // Test the matrix of all the connectivity types we expect to see in the wild.
    731 // Just test every combination of the configs in the Config enum.
    732 class P2PTransportChannelTest : public P2PTransportChannelTestBase {
    733  protected:
    734   static const Result* kMatrix[NUM_CONFIGS][NUM_CONFIGS];
    735   static const Result* kMatrixSharedUfrag[NUM_CONFIGS][NUM_CONFIGS];
    736   static const Result* kMatrixSharedSocketAsGice[NUM_CONFIGS][NUM_CONFIGS];
    737   static const Result* kMatrixSharedSocketAsIce[NUM_CONFIGS][NUM_CONFIGS];
    738   void ConfigureEndpoints(Config config1, Config config2,
    739       int allocator_flags1, int allocator_flags2,
    740       int delay1, int delay2,
    741       cricket::IceProtocolType type) {
    742     ConfigureEndpoint(0, config1);
    743     SetIceProtocol(0, type);
    744     SetAllocatorFlags(0, allocator_flags1);
    745     SetAllocationStepDelay(0, delay1);
    746     ConfigureEndpoint(1, config2);
    747     SetIceProtocol(1, type);
    748     SetAllocatorFlags(1, allocator_flags2);
    749     SetAllocationStepDelay(1, delay2);
    750   }
    751   void ConfigureEndpoint(int endpoint, Config config) {
    752     switch (config) {
    753       case OPEN:
    754         AddAddress(endpoint, kPublicAddrs[endpoint]);
    755         break;
    756       case NAT_FULL_CONE:
    757       case NAT_ADDR_RESTRICTED:
    758       case NAT_PORT_RESTRICTED:
    759       case NAT_SYMMETRIC:
    760         AddAddress(endpoint, kPrivateAddrs[endpoint]);
    761         // Add a single NAT of the desired type
    762         nat()->AddTranslator(kPublicAddrs[endpoint], kNatAddrs[endpoint],
    763             static_cast<talk_base::NATType>(config - NAT_FULL_CONE))->
    764             AddClient(kPrivateAddrs[endpoint]);
    765         break;
    766       case NAT_DOUBLE_CONE:
    767       case NAT_SYMMETRIC_THEN_CONE:
    768         AddAddress(endpoint, kCascadedPrivateAddrs[endpoint]);
    769         // Add a two cascaded NATs of the desired types
    770         nat()->AddTranslator(kPublicAddrs[endpoint], kNatAddrs[endpoint],
    771             (config == NAT_DOUBLE_CONE) ?
    772                 talk_base::NAT_OPEN_CONE : talk_base::NAT_SYMMETRIC)->
    773             AddTranslator(kPrivateAddrs[endpoint], kCascadedNatAddrs[endpoint],
    774                 talk_base::NAT_OPEN_CONE)->
    775                 AddClient(kCascadedPrivateAddrs[endpoint]);
    776         break;
    777       case BLOCK_UDP:
    778       case BLOCK_UDP_AND_INCOMING_TCP:
    779       case BLOCK_ALL_BUT_OUTGOING_HTTP:
    780       case PROXY_HTTPS:
    781       case PROXY_SOCKS:
    782         AddAddress(endpoint, kPublicAddrs[endpoint]);
    783         // Block all UDP
    784         fw()->AddRule(false, talk_base::FP_UDP, talk_base::FD_ANY,
    785                       kPublicAddrs[endpoint]);
    786         if (config == BLOCK_UDP_AND_INCOMING_TCP) {
    787           // Block TCP inbound to the endpoint
    788           fw()->AddRule(false, talk_base::FP_TCP, SocketAddress(),
    789                         kPublicAddrs[endpoint]);
    790         } else if (config == BLOCK_ALL_BUT_OUTGOING_HTTP) {
    791           // Block all TCP to/from the endpoint except 80/443 out
    792           fw()->AddRule(true, talk_base::FP_TCP, kPublicAddrs[endpoint],
    793                         SocketAddress(talk_base::IPAddress(INADDR_ANY), 80));
    794           fw()->AddRule(true, talk_base::FP_TCP, kPublicAddrs[endpoint],
    795                         SocketAddress(talk_base::IPAddress(INADDR_ANY), 443));
    796           fw()->AddRule(false, talk_base::FP_TCP, talk_base::FD_ANY,
    797                         kPublicAddrs[endpoint]);
    798         } else if (config == PROXY_HTTPS) {
    799           // Block all TCP to/from the endpoint except to the proxy server
    800           fw()->AddRule(true, talk_base::FP_TCP, kPublicAddrs[endpoint],
    801                         kHttpsProxyAddrs[endpoint]);
    802           fw()->AddRule(false, talk_base::FP_TCP, talk_base::FD_ANY,
    803                         kPublicAddrs[endpoint]);
    804           SetProxy(endpoint, talk_base::PROXY_HTTPS);
    805         } else if (config == PROXY_SOCKS) {
    806           // Block all TCP to/from the endpoint except to the proxy server
    807           fw()->AddRule(true, talk_base::FP_TCP, kPublicAddrs[endpoint],
    808                         kSocksProxyAddrs[endpoint]);
    809           fw()->AddRule(false, talk_base::FP_TCP, talk_base::FD_ANY,
    810                         kPublicAddrs[endpoint]);
    811           SetProxy(endpoint, talk_base::PROXY_SOCKS5);
    812         }
    813         break;
    814       default:
    815         break;
    816     }
    817   }
    818 };
    819 
    820 // Shorthands for use in the test matrix.
    821 #define LULU &kLocalUdpToLocalUdp
    822 #define LUSU &kLocalUdpToStunUdp
    823 #define LUPU &kLocalUdpToPrflxUdp
    824 #define PULU &kPrflxUdpToLocalUdp
    825 #define SULU &kStunUdpToLocalUdp
    826 #define SUSU &kStunUdpToStunUdp
    827 #define PUSU &kPrflxUdpToStunUdp
    828 #define LURU &kLocalUdpToRelayUdp
    829 #define PURU &kPrflxUdpToRelayUdp
    830 #define LTLT &kLocalTcpToLocalTcp
    831 #define LTPT &kLocalTcpToPrflxTcp
    832 #define PTLT &kPrflxTcpToLocalTcp
    833 // TODO: Enable these once TestRelayServer can accept external TCP.
    834 #define LTRT NULL
    835 #define LSRS NULL
    836 
    837 // Test matrix. Originator behavior defined by rows, receiever by columns.
    838 
    839 // Currently the p2ptransportchannel.cc (specifically the
    840 // P2PTransportChannel::OnUnknownAddress) operates in 2 modes depend on the
    841 // remote candidates - ufrag per port or shared ufrag.
    842 // For example, if the remote candidates have the shared ufrag, for the unknown
    843 // address reaches the OnUnknownAddress, we will try to find the matched
    844 // remote candidate based on the address and protocol, if not found, a new
    845 // remote candidate will be created for this address. But if the remote
    846 // candidates have different ufrags, we will try to find the matched remote
    847 // candidate by comparing the ufrag. If not found, an error will be returned.
    848 // Because currently the shared ufrag feature is under the experiment and will
    849 // be rolled out gradually. We want to test the different combinations of peers
    850 // with/without the shared ufrag enabled. And those different combinations have
    851 // different expectation of the best connection. For example in the OpenToCONE
    852 // case, an unknown address will be updated to a "host" remote candidate if the
    853 // remote peer uses different ufrag per port. But in the shared ufrag case,
    854 // a "stun" (should be peer-reflexive eventually) candidate will be created for
    855 // that. So the expected best candidate will be LUSU instead of LULU.
    856 // With all these, we have to keep 2 test matrixes for the tests:
    857 // kMatrix - for the tests that the remote peer uses different ufrag per port.
    858 // kMatrixSharedUfrag - for the tests that remote peer uses shared ufrag.
    859 // The different between the two matrixes are on:
    860 // OPToCONE, OPTo2CON,
    861 // COToCONE, COToADDR, COToPORT, COToSYMM, COTo2CON, COToSCON,
    862 // ADToCONE, ADToADDR, ADTo2CON,
    863 // POToADDR,
    864 // SYToADDR,
    865 // 2CToCONE, 2CToADDR, 2CToPORT, 2CToSYMM, 2CTo2CON, 2CToSCON,
    866 // SCToADDR,
    867 
    868 // TODO: Fix NULLs caused by lack of TCP support in NATSocket.
    869 // TODO: Fix NULLs caused by no HTTP proxy support.
    870 // TODO: Rearrange rows/columns from best to worst.
    871 // TODO(ronghuawu): Keep only one test matrix once the shared ufrag is enabled.
    872 const P2PTransportChannelTest::Result*
    873     P2PTransportChannelTest::kMatrix[NUM_CONFIGS][NUM_CONFIGS] = {
    874 //      OPEN  CONE  ADDR  PORT  SYMM  2CON  SCON  !UDP  !TCP  HTTP  PRXH  PRXS
    875 /*OP*/ {LULU, LULU, LULU, LULU, LULU, LULU, LULU, LTLT, LTLT, LSRS, NULL, LTLT},
    876 /*CO*/ {LULU, LULU, LULU, SULU, SULU, LULU, SULU, NULL, NULL, LSRS, NULL, LTRT},
    877 /*AD*/ {LULU, LULU, LULU, SUSU, SUSU, LULU, SUSU, NULL, NULL, LSRS, NULL, LTRT},
    878 /*PO*/ {LULU, LUSU, LUSU, SUSU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
    879 /*SY*/ {LULU, LUSU, LUSU, LURU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
    880 /*2C*/ {LULU, LULU, LULU, SULU, SULU, LULU, SULU, NULL, NULL, LSRS, NULL, LTRT},
    881 /*SC*/ {LULU, LUSU, LUSU, LURU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
    882 /*!U*/ {LTLT, NULL, NULL, NULL, NULL, NULL, NULL, LTLT, LTLT, LSRS, NULL, LTRT},
    883 /*!T*/ {LTRT, NULL, NULL, NULL, NULL, NULL, NULL, LTLT, LTRT, LSRS, NULL, LTRT},
    884 /*HT*/ {LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, NULL, LSRS},
    885 /*PR*/ {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
    886 /*PR*/ {LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LSRS, NULL, LTRT},
    887 };
    888 const P2PTransportChannelTest::Result*
    889     P2PTransportChannelTest::kMatrixSharedUfrag[NUM_CONFIGS][NUM_CONFIGS] = {
    890 //      OPEN  CONE  ADDR  PORT  SYMM  2CON  SCON  !UDP  !TCP  HTTP  PRXH  PRXS
    891 /*OP*/ {LULU, LUSU, LULU, LULU, LULU, LUSU, LULU, LTLT, LTLT, LSRS, NULL, LTLT},
    892 /*CO*/ {LULU, LUSU, LUSU, SUSU, SUSU, LUSU, SUSU, NULL, NULL, LSRS, NULL, LTRT},
    893 /*AD*/ {LULU, LUSU, LUSU, SUSU, SUSU, LUSU, SUSU, NULL, NULL, LSRS, NULL, LTRT},
    894 /*PO*/ {LULU, LUSU, LUSU, SUSU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
    895 /*SY*/ {LULU, LUSU, LUSU, LURU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
    896 /*2C*/ {LULU, LUSU, LUSU, SUSU, SUSU, LUSU, SUSU, NULL, NULL, LSRS, NULL, LTRT},
    897 /*SC*/ {LULU, LUSU, LUSU, LURU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
    898 /*!U*/ {LTLT, NULL, NULL, NULL, NULL, NULL, NULL, LTLT, LTLT, LSRS, NULL, LTRT},
    899 /*!T*/ {LTRT, NULL, NULL, NULL, NULL, NULL, NULL, LTLT, LTRT, LSRS, NULL, LTRT},
    900 /*HT*/ {LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, NULL, LSRS},
    901 /*PR*/ {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
    902 /*PR*/ {LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LSRS, NULL, LTRT},
    903 };
    904 const P2PTransportChannelTest::Result*
    905     P2PTransportChannelTest::kMatrixSharedSocketAsGice
    906         [NUM_CONFIGS][NUM_CONFIGS] = {
    907 //      OPEN  CONE  ADDR  PORT  SYMM  2CON  SCON  !UDP  !TCP  HTTP  PRXH  PRXS
    908 /*OP*/ {LULU, LUSU, LUSU, LUSU, LUSU, LUSU, LUSU, LTLT, LTLT, LSRS, NULL, LTLT},
    909 /*CO*/ {LULU, LUSU, LUSU, LUSU, LUSU, LUSU, LUSU, NULL, NULL, LSRS, NULL, LTRT},
    910 /*AD*/ {LULU, LUSU, LUSU, LUSU, LUSU, LUSU, LUSU, NULL, NULL, LSRS, NULL, LTRT},
    911 /*PO*/ {LULU, LUSU, LUSU, LUSU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
    912 /*SY*/ {LULU, LUSU, LUSU, LURU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
    913 /*2C*/ {LULU, LUSU, LUSU, LUSU, LUSU, LUSU, LUSU, NULL, NULL, LSRS, NULL, LTRT},
    914 /*SC*/ {LULU, LUSU, LUSU, LURU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
    915 /*!U*/ {LTLT, NULL, NULL, NULL, NULL, NULL, NULL, LTLT, LTLT, LSRS, NULL, LTRT},
    916 /*!T*/ {LTRT, NULL, NULL, NULL, NULL, NULL, NULL, LTLT, LTRT, LSRS, NULL, LTRT},
    917 /*HT*/ {LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, NULL, LSRS},
    918 /*PR*/ {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
    919 /*PR*/ {LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LSRS, NULL, LTRT},
    920 };
    921 const P2PTransportChannelTest::Result*
    922     P2PTransportChannelTest::kMatrixSharedSocketAsIce
    923         [NUM_CONFIGS][NUM_CONFIGS] = {
    924 //      OPEN  CONE  ADDR  PORT  SYMM  2CON  SCON  !UDP  !TCP  HTTP  PRXH  PRXS
    925 /*OP*/ {LULU, LUSU, LUSU, LUSU, LUPU, LUSU, LUPU, PTLT, LTPT, LSRS, NULL, PTLT},
    926 /*CO*/ {LULU, LUSU, LUSU, LUSU, LUPU, LUSU, LUPU, NULL, NULL, LSRS, NULL, LTRT},
    927 /*AD*/ {LULU, LUSU, LUSU, LUSU, LUPU, LUSU, LUPU, NULL, NULL, LSRS, NULL, LTRT},
    928 /*PO*/ {LULU, LUSU, LUSU, LUSU, LURU, LUSU, LURU, NULL, NULL, LSRS, NULL, LTRT},
    929 /*SY*/ {PULU, PUSU, PUSU, PURU, PURU, PUSU, PURU, NULL, NULL, LSRS, NULL, LTRT},
    930 /*2C*/ {LULU, LUSU, LUSU, LUSU, LUPU, LUSU, LUPU, NULL, NULL, LSRS, NULL, LTRT},
    931 /*SC*/ {PULU, PUSU, PUSU, PURU, PURU, PUSU, PURU, NULL, NULL, LSRS, NULL, LTRT},
    932 /*!U*/ {PTLT, NULL, NULL, NULL, NULL, NULL, NULL, PTLT, LTPT, LSRS, NULL, LTRT},
    933 /*!T*/ {LTRT, NULL, NULL, NULL, NULL, NULL, NULL, PTLT, LTRT, LSRS, NULL, LTRT},
    934 /*HT*/ {LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, NULL, LSRS},
    935 /*PR*/ {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
    936 /*PR*/ {LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LSRS, NULL, LTRT},
    937 };
    938 
    939 // The actual tests that exercise all the various configurations.
    940 // Test names are of the form P2PTransportChannelTest_TestOPENToNAT_FULL_CONE
    941 // Same test case is run in both GICE and ICE mode.
    942 // kDefaultStepDelay - is used for all Gice cases.
    943 // kMinimumStepDelay - is used when both end points have
    944 //                     PORTALLOCATOR_ENABLE_SHARED_UFRAG flag enabled.
    945 // Technically we should be able to use kMinimumStepDelay irrespective of
    946 // protocol type. But which might need modifications to current result matrices
    947 // for tests in this file.
    948 #define P2P_TEST_DECLARATION(x, y, z) \
    949   TEST_F(P2PTransportChannelTest, z##Test##x##To##y##AsGiceNoneSharedUfrag) { \
    950     ConfigureEndpoints(x, y, kDefaultPortAllocatorFlags, \
    951                        kDefaultPortAllocatorFlags, \
    952                        kDefaultStepDelay, kDefaultStepDelay, \
    953                        cricket::ICEPROTO_GOOGLE); \
    954     if (kMatrix[x][y] != NULL) \
    955       Test(*kMatrix[x][y]); \
    956     else \
    957       LOG(LS_WARNING) << "Not yet implemented"; \
    958   } \
    959   TEST_F(P2PTransportChannelTest, z##Test##x##To##y##AsGiceP0SharedUfrag) { \
    960     ConfigureEndpoints(x, y, PORTALLOCATOR_ENABLE_SHARED_UFRAG, \
    961                        kDefaultPortAllocatorFlags, \
    962                        kDefaultStepDelay, kDefaultStepDelay, \
    963                        cricket::ICEPROTO_GOOGLE); \
    964     if (kMatrix[x][y] != NULL) \
    965       Test(*kMatrix[x][y]); \
    966     else \
    967       LOG(LS_WARNING) << "Not yet implemented"; \
    968   } \
    969   TEST_F(P2PTransportChannelTest, z##Test##x##To##y##AsGiceP1SharedUfrag) { \
    970     ConfigureEndpoints(x, y, kDefaultPortAllocatorFlags, \
    971                        PORTALLOCATOR_ENABLE_SHARED_UFRAG, \
    972                        kDefaultStepDelay, kDefaultStepDelay, \
    973                        cricket::ICEPROTO_GOOGLE); \
    974     if (kMatrixSharedUfrag[x][y] != NULL) \
    975       Test(*kMatrixSharedUfrag[x][y]); \
    976     else \
    977       LOG(LS_WARNING) << "Not yet implemented"; \
    978   } \
    979   TEST_F(P2PTransportChannelTest, z##Test##x##To##y##AsGiceBothSharedUfrag) { \
    980     ConfigureEndpoints(x, y, PORTALLOCATOR_ENABLE_SHARED_UFRAG, \
    981                        PORTALLOCATOR_ENABLE_SHARED_UFRAG, \
    982                        kDefaultStepDelay, kDefaultStepDelay, \
    983                        cricket::ICEPROTO_GOOGLE); \
    984     if (kMatrixSharedUfrag[x][y] != NULL) \
    985       Test(*kMatrixSharedUfrag[x][y]); \
    986     else \
    987       LOG(LS_WARNING) << "Not yet implemented"; \
    988   } \
    989   TEST_F(P2PTransportChannelTest, \
    990          z##Test##x##To##y##AsGiceBothSharedUfragWithMinimumStepDelay) { \
    991     ConfigureEndpoints(x, y, PORTALLOCATOR_ENABLE_SHARED_UFRAG, \
    992                        PORTALLOCATOR_ENABLE_SHARED_UFRAG, \
    993                        kMinimumStepDelay, kMinimumStepDelay, \
    994                        cricket::ICEPROTO_GOOGLE); \
    995     if (kMatrixSharedUfrag[x][y] != NULL) \
    996       Test(*kMatrixSharedUfrag[x][y]); \
    997     else \
    998       LOG(LS_WARNING) << "Not yet implemented"; \
    999   } \
   1000   TEST_F(P2PTransportChannelTest, \
   1001          z##Test##x##To##y##AsGiceBothSharedUfragSocket) { \
   1002     ConfigureEndpoints(x, y, PORTALLOCATOR_ENABLE_SHARED_UFRAG | \
   1003                        PORTALLOCATOR_ENABLE_SHARED_SOCKET, \
   1004                        PORTALLOCATOR_ENABLE_SHARED_UFRAG | \
   1005                        PORTALLOCATOR_ENABLE_SHARED_SOCKET, \
   1006                        kMinimumStepDelay, kMinimumStepDelay, \
   1007                        cricket::ICEPROTO_GOOGLE); \
   1008     if (kMatrixSharedSocketAsGice[x][y] != NULL) \
   1009       Test(*kMatrixSharedSocketAsGice[x][y]); \
   1010     else \
   1011     LOG(LS_WARNING) << "Not yet implemented"; \
   1012   } \
   1013   TEST_F(P2PTransportChannelTest, z##Test##x##To##y##AsIce) { \
   1014     ConfigureEndpoints(x, y, PORTALLOCATOR_ENABLE_SHARED_UFRAG | \
   1015                        PORTALLOCATOR_ENABLE_SHARED_SOCKET, \
   1016                        PORTALLOCATOR_ENABLE_SHARED_UFRAG | \
   1017                        PORTALLOCATOR_ENABLE_SHARED_SOCKET, \
   1018                        kMinimumStepDelay, kMinimumStepDelay, \
   1019                        cricket::ICEPROTO_RFC5245); \
   1020     if (kMatrixSharedSocketAsIce[x][y] != NULL) \
   1021       Test(*kMatrixSharedSocketAsIce[x][y]); \
   1022     else \
   1023     LOG(LS_WARNING) << "Not yet implemented"; \
   1024   }
   1025 
   1026 #define P2P_TEST(x, y) \
   1027   P2P_TEST_DECLARATION(x, y,)
   1028 
   1029 #define FLAKY_P2P_TEST(x, y) \
   1030   P2P_TEST_DECLARATION(x, y, DISABLED_)
   1031 
   1032 // TODO(holmer): Disabled due to randomly failing on webrtc buildbots.
   1033 // Issue: webrtc/2383
   1034 #define P2P_TEST_SET(x) \
   1035   P2P_TEST(x, OPEN) \
   1036   FLAKY_P2P_TEST(x, NAT_FULL_CONE) \
   1037   FLAKY_P2P_TEST(x, NAT_ADDR_RESTRICTED) \
   1038   P2P_TEST(x, NAT_PORT_RESTRICTED) \
   1039   P2P_TEST(x, NAT_SYMMETRIC) \
   1040   FLAKY_P2P_TEST(x, NAT_DOUBLE_CONE) \
   1041   P2P_TEST(x, NAT_SYMMETRIC_THEN_CONE) \
   1042   P2P_TEST(x, BLOCK_UDP) \
   1043   P2P_TEST(x, BLOCK_UDP_AND_INCOMING_TCP) \
   1044   P2P_TEST(x, BLOCK_ALL_BUT_OUTGOING_HTTP) \
   1045   P2P_TEST(x, PROXY_HTTPS) \
   1046   P2P_TEST(x, PROXY_SOCKS)
   1047 
   1048 #define FLAKY_P2P_TEST_SET(x) \
   1049   P2P_TEST(x, OPEN) \
   1050   P2P_TEST(x, NAT_FULL_CONE) \
   1051   P2P_TEST(x, NAT_ADDR_RESTRICTED) \
   1052   P2P_TEST(x, NAT_PORT_RESTRICTED) \
   1053   P2P_TEST(x, NAT_SYMMETRIC) \
   1054   P2P_TEST(x, NAT_DOUBLE_CONE) \
   1055   P2P_TEST(x, NAT_SYMMETRIC_THEN_CONE) \
   1056   P2P_TEST(x, BLOCK_UDP) \
   1057   P2P_TEST(x, BLOCK_UDP_AND_INCOMING_TCP) \
   1058   P2P_TEST(x, BLOCK_ALL_BUT_OUTGOING_HTTP) \
   1059   P2P_TEST(x, PROXY_HTTPS) \
   1060   P2P_TEST(x, PROXY_SOCKS)
   1061 
   1062 P2P_TEST_SET(OPEN)
   1063 P2P_TEST_SET(NAT_FULL_CONE)
   1064 P2P_TEST_SET(NAT_ADDR_RESTRICTED)
   1065 P2P_TEST_SET(NAT_PORT_RESTRICTED)
   1066 P2P_TEST_SET(NAT_SYMMETRIC)
   1067 P2P_TEST_SET(NAT_DOUBLE_CONE)
   1068 P2P_TEST_SET(NAT_SYMMETRIC_THEN_CONE)
   1069 P2P_TEST_SET(BLOCK_UDP)
   1070 P2P_TEST_SET(BLOCK_UDP_AND_INCOMING_TCP)
   1071 P2P_TEST_SET(BLOCK_ALL_BUT_OUTGOING_HTTP)
   1072 P2P_TEST_SET(PROXY_HTTPS)
   1073 P2P_TEST_SET(PROXY_SOCKS)
   1074 
   1075 // Test that we restart candidate allocation when local ufrag&pwd changed.
   1076 // Standard Ice protocol is used.
   1077 TEST_F(P2PTransportChannelTest, HandleUfragPwdChangeAsIce) {
   1078   ConfigureEndpoints(OPEN, OPEN,
   1079                      PORTALLOCATOR_ENABLE_SHARED_UFRAG,
   1080                      PORTALLOCATOR_ENABLE_SHARED_UFRAG,
   1081                      kMinimumStepDelay, kMinimumStepDelay,
   1082                      cricket::ICEPROTO_RFC5245);
   1083   CreateChannels(1);
   1084   TestHandleIceUfragPasswordChanged();
   1085 }
   1086 
   1087 // Test that we restart candidate allocation when local ufrag&pwd changed.
   1088 // Standard Ice protocol is used.
   1089 TEST_F(P2PTransportChannelTest, HandleUfragPwdChangeBundleAsIce) {
   1090   ConfigureEndpoints(OPEN, OPEN,
   1091                      PORTALLOCATOR_ENABLE_SHARED_UFRAG,
   1092                      PORTALLOCATOR_ENABLE_SHARED_UFRAG,
   1093                      kMinimumStepDelay, kMinimumStepDelay,
   1094                      cricket::ICEPROTO_RFC5245);
   1095   SetAllocatorFlags(0, cricket::PORTALLOCATOR_ENABLE_BUNDLE);
   1096   SetAllocatorFlags(1, cricket::PORTALLOCATOR_ENABLE_BUNDLE);
   1097 
   1098   CreateChannels(2);
   1099   TestHandleIceUfragPasswordChanged();
   1100 }
   1101 
   1102 // Test that we restart candidate allocation when local ufrag&pwd changed.
   1103 // Google Ice protocol is used.
   1104 TEST_F(P2PTransportChannelTest, HandleUfragPwdChangeAsGice) {
   1105   ConfigureEndpoints(OPEN, OPEN,
   1106                      PORTALLOCATOR_ENABLE_SHARED_UFRAG,
   1107                      PORTALLOCATOR_ENABLE_SHARED_UFRAG,
   1108                      kDefaultStepDelay, kDefaultStepDelay,
   1109                      cricket::ICEPROTO_GOOGLE);
   1110   CreateChannels(1);
   1111   TestHandleIceUfragPasswordChanged();
   1112 }
   1113 
   1114 // Test that ICE restart works when bundle is enabled.
   1115 // Google Ice protocol is used.
   1116 TEST_F(P2PTransportChannelTest, HandleUfragPwdChangeBundleAsGice) {
   1117   ConfigureEndpoints(OPEN, OPEN,
   1118                      PORTALLOCATOR_ENABLE_SHARED_UFRAG,
   1119                      PORTALLOCATOR_ENABLE_SHARED_UFRAG,
   1120                      kDefaultStepDelay, kDefaultStepDelay,
   1121                      cricket::ICEPROTO_GOOGLE);
   1122   SetAllocatorFlags(0, cricket::PORTALLOCATOR_ENABLE_BUNDLE);
   1123   SetAllocatorFlags(1, cricket::PORTALLOCATOR_ENABLE_BUNDLE);
   1124 
   1125   CreateChannels(2);
   1126   TestHandleIceUfragPasswordChanged();
   1127 }
   1128 
   1129 // Test the operation of GetStats.
   1130 TEST_F(P2PTransportChannelTest, GetStats) {
   1131   ConfigureEndpoints(OPEN, OPEN,
   1132                      kDefaultPortAllocatorFlags,
   1133                      kDefaultPortAllocatorFlags,
   1134                      kDefaultStepDelay, kDefaultStepDelay,
   1135                      cricket::ICEPROTO_GOOGLE);
   1136   CreateChannels(1);
   1137   EXPECT_TRUE_WAIT_MARGIN(ep1_ch1()->readable() && ep1_ch1()->writable() &&
   1138                           ep2_ch1()->readable() && ep2_ch1()->writable(),
   1139                           1000, 1000);
   1140   TestSendRecv(1);
   1141   cricket::ConnectionInfos infos;
   1142   ASSERT_TRUE(ep1_ch1()->GetStats(&infos));
   1143   ASSERT_EQ(1U, infos.size());
   1144   EXPECT_TRUE(infos[0].new_connection);
   1145   EXPECT_TRUE(infos[0].best_connection);
   1146   EXPECT_TRUE(infos[0].readable);
   1147   EXPECT_TRUE(infos[0].writable);
   1148   EXPECT_FALSE(infos[0].timeout);
   1149   EXPECT_EQ(10 * 36U, infos[0].sent_total_bytes);
   1150   EXPECT_EQ(10 * 36U, infos[0].recv_total_bytes);
   1151   EXPECT_GT(infos[0].rtt, 0U);
   1152   DestroyChannels();
   1153 }
   1154 
   1155 // Test that we properly handle getting a STUN error due to slow signaling.
   1156 TEST_F(P2PTransportChannelTest, DISABLED_SlowSignaling) {
   1157   ConfigureEndpoints(OPEN, NAT_SYMMETRIC,
   1158                      kDefaultPortAllocatorFlags,
   1159                      kDefaultPortAllocatorFlags,
   1160                      kDefaultStepDelay, kDefaultStepDelay,
   1161                      cricket::ICEPROTO_GOOGLE);
   1162   // Make signaling from the callee take 500ms, so that the initial STUN pings
   1163   // from the callee beat the signaling, and so the caller responds with a
   1164   // unknown username error. We should just eat that and carry on; mishandling
   1165   // this will instead cause all the callee's connections to be discarded.
   1166   SetSignalingDelay(1, 1000);
   1167   CreateChannels(1);
   1168   const cricket::Connection* best_connection = NULL;
   1169   // Wait until the callee's connections are created.
   1170   WAIT((best_connection = ep2_ch1()->best_connection()) != NULL, 1000);
   1171   // Wait to see if they get culled; they shouldn't.
   1172   WAIT(ep2_ch1()->best_connection() != best_connection, 1000);
   1173   EXPECT_TRUE(ep2_ch1()->best_connection() == best_connection);
   1174   DestroyChannels();
   1175 }
   1176 
   1177 // Test that if remote candidates don't have ufrag and pwd, we still work.
   1178 TEST_F(P2PTransportChannelTest, RemoteCandidatesWithoutUfragPwd) {
   1179   set_clear_remote_candidates_ufrag_pwd(true);
   1180   ConfigureEndpoints(OPEN, OPEN,
   1181                      PORTALLOCATOR_ENABLE_SHARED_UFRAG,
   1182                      PORTALLOCATOR_ENABLE_SHARED_UFRAG,
   1183                      kMinimumStepDelay, kMinimumStepDelay,
   1184                      cricket::ICEPROTO_GOOGLE);
   1185   CreateChannels(1);
   1186   const cricket::Connection* best_connection = NULL;
   1187   // Wait until the callee's connections are created.
   1188   WAIT((best_connection = ep2_ch1()->best_connection()) != NULL, 1000);
   1189   // Wait to see if they get culled; they shouldn't.
   1190   WAIT(ep2_ch1()->best_connection() != best_connection, 1000);
   1191   EXPECT_TRUE(ep2_ch1()->best_connection() == best_connection);
   1192   DestroyChannels();
   1193 }
   1194 
   1195 // Test that a host behind NAT cannot be reached when incoming_only
   1196 // is set to true.
   1197 TEST_F(P2PTransportChannelTest, IncomingOnlyBlocked) {
   1198   ConfigureEndpoints(NAT_FULL_CONE, OPEN,
   1199                      kDefaultPortAllocatorFlags,
   1200                      kDefaultPortAllocatorFlags,
   1201                      kDefaultStepDelay, kDefaultStepDelay,
   1202                      cricket::ICEPROTO_GOOGLE);
   1203 
   1204   SetAllocatorFlags(0, kOnlyLocalPorts);
   1205   CreateChannels(1);
   1206   ep1_ch1()->set_incoming_only(true);
   1207 
   1208   // Pump for 1 second and verify that the channels are not connected.
   1209   talk_base::Thread::Current()->ProcessMessages(1000);
   1210 
   1211   EXPECT_FALSE(ep1_ch1()->readable());
   1212   EXPECT_FALSE(ep1_ch1()->writable());
   1213   EXPECT_FALSE(ep2_ch1()->readable());
   1214   EXPECT_FALSE(ep2_ch1()->writable());
   1215 
   1216   DestroyChannels();
   1217 }
   1218 
   1219 // Test that a peer behind NAT can connect to a peer that has
   1220 // incoming_only flag set.
   1221 TEST_F(P2PTransportChannelTest, IncomingOnlyOpen) {
   1222   ConfigureEndpoints(OPEN, NAT_FULL_CONE,
   1223                      kDefaultPortAllocatorFlags,
   1224                      kDefaultPortAllocatorFlags,
   1225                      kDefaultStepDelay, kDefaultStepDelay,
   1226                      cricket::ICEPROTO_GOOGLE);
   1227 
   1228   SetAllocatorFlags(0, kOnlyLocalPorts);
   1229   CreateChannels(1);
   1230   ep1_ch1()->set_incoming_only(true);
   1231 
   1232   EXPECT_TRUE_WAIT_MARGIN(ep1_ch1() != NULL && ep2_ch1() != NULL &&
   1233                           ep1_ch1()->readable() && ep1_ch1()->writable() &&
   1234                           ep2_ch1()->readable() && ep2_ch1()->writable(),
   1235                           1000, 1000);
   1236 
   1237   DestroyChannels();
   1238 }
   1239 
   1240 TEST_F(P2PTransportChannelTest, TestTcpConnectionsFromActiveToPassive) {
   1241   AddAddress(0, kPublicAddrs[0]);
   1242   AddAddress(1, kPublicAddrs[1]);
   1243 
   1244   SetAllocationStepDelay(0, kMinimumStepDelay);
   1245   SetAllocationStepDelay(1, kMinimumStepDelay);
   1246 
   1247   int kOnlyLocalTcpPorts = cricket::PORTALLOCATOR_DISABLE_UDP |
   1248                            cricket::PORTALLOCATOR_DISABLE_STUN |
   1249                            cricket::PORTALLOCATOR_DISABLE_RELAY |
   1250                            cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG;
   1251   // Disable all protocols except TCP.
   1252   SetAllocatorFlags(0, kOnlyLocalTcpPorts);
   1253   SetAllocatorFlags(1, kOnlyLocalTcpPorts);
   1254 
   1255   SetAllowTcpListen(0, true);   // actpass.
   1256   SetAllowTcpListen(1, false);  // active.
   1257 
   1258   CreateChannels(1);
   1259 
   1260   EXPECT_TRUE_WAIT(ep1_ch1()->readable() && ep1_ch1()->writable() &&
   1261                    ep2_ch1()->readable() && ep2_ch1()->writable(),
   1262                    1000);
   1263   EXPECT_TRUE(
   1264       ep1_ch1()->best_connection() && ep2_ch1()->best_connection() &&
   1265       LocalCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[0]) &&
   1266       RemoteCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[1]));
   1267 
   1268   std::string kTcpProtocol = "tcp";
   1269   EXPECT_EQ(kTcpProtocol, RemoteCandidate(ep1_ch1())->protocol());
   1270   EXPECT_EQ(kTcpProtocol, LocalCandidate(ep1_ch1())->protocol());
   1271   EXPECT_EQ(kTcpProtocol, RemoteCandidate(ep2_ch1())->protocol());
   1272   EXPECT_EQ(kTcpProtocol, LocalCandidate(ep2_ch1())->protocol());
   1273 
   1274   TestSendRecv(1);
   1275   DestroyChannels();
   1276 }
   1277 
   1278 TEST_F(P2PTransportChannelTest, TestBundleAllocatorToBundleAllocator) {
   1279   AddAddress(0, kPublicAddrs[0]);
   1280   AddAddress(1, kPublicAddrs[1]);
   1281   SetAllocatorFlags(0, cricket::PORTALLOCATOR_ENABLE_BUNDLE);
   1282   SetAllocatorFlags(1, cricket::PORTALLOCATOR_ENABLE_BUNDLE);
   1283 
   1284   CreateChannels(2);
   1285 
   1286   EXPECT_TRUE_WAIT(ep1_ch1()->readable() &&
   1287                    ep1_ch1()->writable() &&
   1288                    ep2_ch1()->readable() &&
   1289                    ep2_ch1()->writable(),
   1290                    1000);
   1291   EXPECT_TRUE(ep1_ch1()->best_connection() &&
   1292               ep2_ch1()->best_connection());
   1293 
   1294   EXPECT_FALSE(ep1_ch2()->readable());
   1295   EXPECT_FALSE(ep1_ch2()->writable());
   1296   EXPECT_FALSE(ep2_ch2()->readable());
   1297   EXPECT_FALSE(ep2_ch2()->writable());
   1298 
   1299   TestSendRecv(1);  // Only 1 channel is writable per Endpoint.
   1300   DestroyChannels();
   1301 }
   1302 
   1303 TEST_F(P2PTransportChannelTest, TestBundleAllocatorToNonBundleAllocator) {
   1304   AddAddress(0, kPublicAddrs[0]);
   1305   AddAddress(1, kPublicAddrs[1]);
   1306   // Enable BUNDLE flag at one side.
   1307   SetAllocatorFlags(0, cricket::PORTALLOCATOR_ENABLE_BUNDLE);
   1308 
   1309   CreateChannels(2);
   1310 
   1311   EXPECT_TRUE_WAIT(ep1_ch1()->readable() &&
   1312                    ep1_ch1()->writable() &&
   1313                    ep2_ch1()->readable() &&
   1314                    ep2_ch1()->writable(),
   1315                    1000);
   1316   EXPECT_TRUE_WAIT(ep1_ch2()->readable() &&
   1317                    ep1_ch2()->writable() &&
   1318                    ep2_ch2()->readable() &&
   1319                    ep2_ch2()->writable(),
   1320                    1000);
   1321 
   1322   EXPECT_TRUE(ep1_ch1()->best_connection() &&
   1323               ep2_ch1()->best_connection());
   1324   EXPECT_TRUE(ep1_ch2()->best_connection() &&
   1325               ep2_ch2()->best_connection());
   1326 
   1327   TestSendRecv(2);
   1328   DestroyChannels();
   1329 }
   1330 
   1331 TEST_F(P2PTransportChannelTest, TestIceRoleConflictWithoutBundle) {
   1332   AddAddress(0, kPublicAddrs[0]);
   1333   AddAddress(1, kPublicAddrs[1]);
   1334   TestSignalRoleConflict();
   1335 }
   1336 
   1337 TEST_F(P2PTransportChannelTest, TestIceRoleConflictWithBundle) {
   1338   AddAddress(0, kPublicAddrs[0]);
   1339   AddAddress(1, kPublicAddrs[1]);
   1340   SetAllocatorFlags(0, cricket::PORTALLOCATOR_ENABLE_BUNDLE);
   1341   SetAllocatorFlags(1, cricket::PORTALLOCATOR_ENABLE_BUNDLE);
   1342   TestSignalRoleConflict();
   1343 }
   1344 
   1345 // Tests that the ice configs (protocol, tiebreaker and role) can be passed
   1346 // down to ports.
   1347 TEST_F(P2PTransportChannelTest, TestIceConfigWillPassDownToPort) {
   1348   AddAddress(0, kPublicAddrs[0]);
   1349   AddAddress(1, kPublicAddrs[1]);
   1350 
   1351   SetIceRole(0, cricket::ICEROLE_CONTROLLING);
   1352   SetIceProtocol(0, cricket::ICEPROTO_GOOGLE);
   1353   SetIceTiebreaker(0, kTiebreaker1);
   1354   SetIceRole(1, cricket::ICEROLE_CONTROLLING);
   1355   SetIceProtocol(1, cricket::ICEPROTO_RFC5245);
   1356   SetIceTiebreaker(1, kTiebreaker2);
   1357 
   1358   CreateChannels(1);
   1359 
   1360   EXPECT_EQ_WAIT(2u, ep1_ch1()->ports().size(), 1000);
   1361 
   1362   const std::vector<cricket::PortInterface *> ports_before = ep1_ch1()->ports();
   1363   for (size_t i = 0; i < ports_before.size(); ++i) {
   1364     EXPECT_EQ(cricket::ICEROLE_CONTROLLING, ports_before[i]->GetIceRole());
   1365     EXPECT_EQ(cricket::ICEPROTO_GOOGLE, ports_before[i]->IceProtocol());
   1366     EXPECT_EQ(kTiebreaker1, ports_before[i]->IceTiebreaker());
   1367   }
   1368 
   1369   ep1_ch1()->SetIceRole(cricket::ICEROLE_CONTROLLED);
   1370   ep1_ch1()->SetIceProtocolType(cricket::ICEPROTO_RFC5245);
   1371   ep1_ch1()->SetIceTiebreaker(kTiebreaker2);
   1372 
   1373   const std::vector<cricket::PortInterface *> ports_after = ep1_ch1()->ports();
   1374   for (size_t i = 0; i < ports_after.size(); ++i) {
   1375     EXPECT_EQ(cricket::ICEROLE_CONTROLLED, ports_before[i]->GetIceRole());
   1376     EXPECT_EQ(cricket::ICEPROTO_RFC5245, ports_before[i]->IceProtocol());
   1377     // SetIceTiebreaker after Connect() has been called will fail. So expect the
   1378     // original value.
   1379     EXPECT_EQ(kTiebreaker1, ports_before[i]->IceTiebreaker());
   1380   }
   1381 
   1382   EXPECT_TRUE_WAIT(ep1_ch1()->readable() &&
   1383                    ep1_ch1()->writable() &&
   1384                    ep2_ch1()->readable() &&
   1385                    ep2_ch1()->writable(),
   1386                    1000);
   1387 
   1388   EXPECT_TRUE(ep1_ch1()->best_connection() &&
   1389               ep2_ch1()->best_connection());
   1390 
   1391   TestSendRecv(1);
   1392 }
   1393 
   1394 // Verify that we can set DSCP value and retrieve properly from P2PTC.
   1395 TEST_F(P2PTransportChannelTest, TestDefaultDscpValue) {
   1396   AddAddress(0, kPublicAddrs[0]);
   1397   AddAddress(1, kPublicAddrs[1]);
   1398 
   1399   CreateChannels(1);
   1400   EXPECT_EQ(talk_base::DSCP_NO_CHANGE,
   1401             GetEndpoint(0)->cd1_.ch_->DefaultDscpValue());
   1402   EXPECT_EQ(talk_base::DSCP_NO_CHANGE,
   1403             GetEndpoint(1)->cd1_.ch_->DefaultDscpValue());
   1404   GetEndpoint(0)->cd1_.ch_->SetOption(
   1405       talk_base::Socket::OPT_DSCP, talk_base::DSCP_CS6);
   1406   GetEndpoint(1)->cd1_.ch_->SetOption(
   1407       talk_base::Socket::OPT_DSCP, talk_base::DSCP_CS6);
   1408   EXPECT_EQ(talk_base::DSCP_CS6,
   1409             GetEndpoint(0)->cd1_.ch_->DefaultDscpValue());
   1410   EXPECT_EQ(talk_base::DSCP_CS6,
   1411             GetEndpoint(1)->cd1_.ch_->DefaultDscpValue());
   1412   GetEndpoint(0)->cd1_.ch_->SetOption(
   1413       talk_base::Socket::OPT_DSCP, talk_base::DSCP_AF41);
   1414   GetEndpoint(1)->cd1_.ch_->SetOption(
   1415       talk_base::Socket::OPT_DSCP, talk_base::DSCP_AF41);
   1416   EXPECT_EQ(talk_base::DSCP_AF41,
   1417             GetEndpoint(0)->cd1_.ch_->DefaultDscpValue());
   1418   EXPECT_EQ(talk_base::DSCP_AF41,
   1419             GetEndpoint(1)->cd1_.ch_->DefaultDscpValue());
   1420 }
   1421 
   1422 // Verify IPv6 connection is preferred over IPv4.
   1423 TEST_F(P2PTransportChannelTest, TestIPv6Connections) {
   1424   AddAddress(0, kIPv6PublicAddrs[0]);
   1425   AddAddress(0, kPublicAddrs[0]);
   1426   AddAddress(1, kIPv6PublicAddrs[1]);
   1427   AddAddress(1, kPublicAddrs[1]);
   1428 
   1429   SetAllocationStepDelay(0, kMinimumStepDelay);
   1430   SetAllocationStepDelay(1, kMinimumStepDelay);
   1431 
   1432   // Enable IPv6
   1433   SetAllocatorFlags(0, cricket::PORTALLOCATOR_ENABLE_IPV6);
   1434   SetAllocatorFlags(1, cricket::PORTALLOCATOR_ENABLE_IPV6);
   1435 
   1436   CreateChannels(1);
   1437 
   1438   EXPECT_TRUE_WAIT(ep1_ch1()->readable() && ep1_ch1()->writable() &&
   1439                    ep2_ch1()->readable() && ep2_ch1()->writable(),
   1440                    1000);
   1441   EXPECT_TRUE(
   1442       ep1_ch1()->best_connection() && ep2_ch1()->best_connection() &&
   1443       LocalCandidate(ep1_ch1())->address().EqualIPs(kIPv6PublicAddrs[0]) &&
   1444       RemoteCandidate(ep1_ch1())->address().EqualIPs(kIPv6PublicAddrs[1]));
   1445 
   1446   TestSendRecv(1);
   1447   DestroyChannels();
   1448 }
   1449 
   1450 // Test what happens when we have 2 users behind the same NAT. This can lead
   1451 // to interesting behavior because the STUN server will only give out the
   1452 // address of the outermost NAT.
   1453 class P2PTransportChannelSameNatTest : public P2PTransportChannelTestBase {
   1454  protected:
   1455   void ConfigureEndpoints(Config nat_type, Config config1, Config config2) {
   1456     ASSERT(nat_type >= NAT_FULL_CONE && nat_type <= NAT_SYMMETRIC);
   1457     talk_base::NATSocketServer::Translator* outer_nat =
   1458         nat()->AddTranslator(kPublicAddrs[0], kNatAddrs[0],
   1459             static_cast<talk_base::NATType>(nat_type - NAT_FULL_CONE));
   1460     ConfigureEndpoint(outer_nat, 0, config1);
   1461     ConfigureEndpoint(outer_nat, 1, config2);
   1462   }
   1463   void ConfigureEndpoint(talk_base::NATSocketServer::Translator* nat,
   1464                          int endpoint, Config config) {
   1465     ASSERT(config <= NAT_SYMMETRIC);
   1466     if (config == OPEN) {
   1467       AddAddress(endpoint, kPrivateAddrs[endpoint]);
   1468       nat->AddClient(kPrivateAddrs[endpoint]);
   1469     } else {
   1470       AddAddress(endpoint, kCascadedPrivateAddrs[endpoint]);
   1471       nat->AddTranslator(kPrivateAddrs[endpoint], kCascadedNatAddrs[endpoint],
   1472           static_cast<talk_base::NATType>(config - NAT_FULL_CONE))->AddClient(
   1473               kCascadedPrivateAddrs[endpoint]);
   1474     }
   1475   }
   1476 };
   1477 
   1478 TEST_F(P2PTransportChannelSameNatTest, TestConesBehindSameCone) {
   1479   ConfigureEndpoints(NAT_FULL_CONE, NAT_FULL_CONE, NAT_FULL_CONE);
   1480   Test(kLocalUdpToStunUdp);
   1481 }
   1482 
   1483 // Test what happens when we have multiple available pathways.
   1484 // In the future we will try different RTTs and configs for the different
   1485 // interfaces, so that we can simulate a user with Ethernet and VPN networks.
   1486 class P2PTransportChannelMultihomedTest : public P2PTransportChannelTestBase {
   1487 };
   1488 
   1489 // Test that we can establish connectivity when both peers are multihomed.
   1490 TEST_F(P2PTransportChannelMultihomedTest, DISABLED_TestBasic) {
   1491   AddAddress(0, kPublicAddrs[0]);
   1492   AddAddress(0, kAlternateAddrs[0]);
   1493   AddAddress(1, kPublicAddrs[1]);
   1494   AddAddress(1, kAlternateAddrs[1]);
   1495   Test(kLocalUdpToLocalUdp);
   1496 }
   1497 
   1498 // Test that we can quickly switch links if an interface goes down.
   1499 TEST_F(P2PTransportChannelMultihomedTest, TestFailover) {
   1500   AddAddress(0, kPublicAddrs[0]);
   1501   AddAddress(1, kPublicAddrs[1]);
   1502   AddAddress(1, kAlternateAddrs[1]);
   1503   // Use only local ports for simplicity.
   1504   SetAllocatorFlags(0, kOnlyLocalPorts);
   1505   SetAllocatorFlags(1, kOnlyLocalPorts);
   1506 
   1507   // Create channels and let them go writable, as usual.
   1508   CreateChannels(1);
   1509   EXPECT_TRUE_WAIT(ep1_ch1()->readable() && ep1_ch1()->writable() &&
   1510                    ep2_ch1()->readable() && ep2_ch1()->writable(),
   1511                    1000);
   1512   EXPECT_TRUE(
   1513       ep1_ch1()->best_connection() && ep2_ch1()->best_connection() &&
   1514       LocalCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[0]) &&
   1515       RemoteCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[1]));
   1516 
   1517   // Blackhole any traffic to or from the public addrs.
   1518   LOG(LS_INFO) << "Failing over...";
   1519   fw()->AddRule(false, talk_base::FP_ANY, talk_base::FD_ANY,
   1520                 kPublicAddrs[1]);
   1521 
   1522   // We should detect loss of connectivity within 5 seconds or so.
   1523   EXPECT_TRUE_WAIT(!ep1_ch1()->writable(), 7000);
   1524 
   1525   // We should switch over to use the alternate addr immediately
   1526   // when we lose writability.
   1527   EXPECT_TRUE_WAIT(
   1528       ep1_ch1()->best_connection() && ep2_ch1()->best_connection() &&
   1529       LocalCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[0]) &&
   1530       RemoteCandidate(ep1_ch1())->address().EqualIPs(kAlternateAddrs[1]),
   1531       3000);
   1532 
   1533   DestroyChannels();
   1534 }
   1535 
   1536 // Test that we can switch links in a coordinated fashion.
   1537 TEST_F(P2PTransportChannelMultihomedTest, TestDrain) {
   1538   AddAddress(0, kPublicAddrs[0]);
   1539   AddAddress(1, kPublicAddrs[1]);
   1540   // Use only local ports for simplicity.
   1541   SetAllocatorFlags(0, kOnlyLocalPorts);
   1542   SetAllocatorFlags(1, kOnlyLocalPorts);
   1543 
   1544   // Create channels and let them go writable, as usual.
   1545   CreateChannels(1);
   1546   EXPECT_TRUE_WAIT(ep1_ch1()->readable() && ep1_ch1()->writable() &&
   1547                    ep2_ch1()->readable() && ep2_ch1()->writable(),
   1548                    1000);
   1549   EXPECT_TRUE(
   1550       ep1_ch1()->best_connection() && ep2_ch1()->best_connection() &&
   1551       LocalCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[0]) &&
   1552       RemoteCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[1]));
   1553 
   1554   // Remove the public interface, add the alternate interface, and allocate
   1555   // a new generation of candidates for the new interface (via Connect()).
   1556   LOG(LS_INFO) << "Draining...";
   1557   AddAddress(1, kAlternateAddrs[1]);
   1558   RemoveAddress(1, kPublicAddrs[1]);
   1559   ep2_ch1()->Connect();
   1560 
   1561   // We should switch over to use the alternate address after
   1562   // an exchange of pings.
   1563   EXPECT_TRUE_WAIT(
   1564       ep1_ch1()->best_connection() && ep2_ch1()->best_connection() &&
   1565       LocalCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[0]) &&
   1566       RemoteCandidate(ep1_ch1())->address().EqualIPs(kAlternateAddrs[1]),
   1567       3000);
   1568 
   1569   DestroyChannels();
   1570 }
   1571