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