Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / third_party / libjingle / source / talk / p2p / base / port_unittest.cc
1 /*
2  * libjingle
3  * Copyright 2004 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/crc32.h"
29 #include "talk/base/gunit.h"
30 #include "talk/base/helpers.h"
31 #include "talk/base/logging.h"
32 #include "talk/base/natserver.h"
33 #include "talk/base/natsocketfactory.h"
34 #include "talk/base/physicalsocketserver.h"
35 #include "talk/base/scoped_ptr.h"
36 #include "talk/base/socketaddress.h"
37 #include "talk/base/stringutils.h"
38 #include "talk/base/thread.h"
39 #include "talk/base/virtualsocketserver.h"
40 #include "talk/p2p/base/basicpacketsocketfactory.h"
41 #include "talk/p2p/base/portproxy.h"
42 #include "talk/p2p/base/relayport.h"
43 #include "talk/p2p/base/stunport.h"
44 #include "talk/p2p/base/tcpport.h"
45 #include "talk/p2p/base/testrelayserver.h"
46 #include "talk/p2p/base/teststunserver.h"
47 #include "talk/p2p/base/testturnserver.h"
48 #include "talk/p2p/base/transport.h"
49 #include "talk/p2p/base/turnport.h"
50
51 using talk_base::AsyncPacketSocket;
52 using talk_base::ByteBuffer;
53 using talk_base::NATType;
54 using talk_base::NAT_OPEN_CONE;
55 using talk_base::NAT_ADDR_RESTRICTED;
56 using talk_base::NAT_PORT_RESTRICTED;
57 using talk_base::NAT_SYMMETRIC;
58 using talk_base::PacketSocketFactory;
59 using talk_base::scoped_ptr;
60 using talk_base::Socket;
61 using talk_base::SocketAddress;
62 using namespace cricket;
63
64 static const int kTimeout = 1000;
65 static const SocketAddress kLocalAddr1("192.168.1.2", 0);
66 static const SocketAddress kLocalAddr2("192.168.1.3", 0);
67 static const SocketAddress kNatAddr1("77.77.77.77", talk_base::NAT_SERVER_PORT);
68 static const SocketAddress kNatAddr2("88.88.88.88", talk_base::NAT_SERVER_PORT);
69 static const SocketAddress kStunAddr("99.99.99.1", STUN_SERVER_PORT);
70 static const SocketAddress kRelayUdpIntAddr("99.99.99.2", 5000);
71 static const SocketAddress kRelayUdpExtAddr("99.99.99.3", 5001);
72 static const SocketAddress kRelayTcpIntAddr("99.99.99.2", 5002);
73 static const SocketAddress kRelayTcpExtAddr("99.99.99.3", 5003);
74 static const SocketAddress kRelaySslTcpIntAddr("99.99.99.2", 5004);
75 static const SocketAddress kRelaySslTcpExtAddr("99.99.99.3", 5005);
76 static const SocketAddress kTurnUdpIntAddr("99.99.99.4", STUN_SERVER_PORT);
77 static const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0);
78 static const RelayCredentials kRelayCredentials("test", "test");
79
80 // TODO: Update these when RFC5245 is completely supported.
81 // Magic value of 30 is from RFC3484, for IPv4 addresses.
82 static const uint32 kDefaultPrflxPriority = ICE_TYPE_PREFERENCE_PRFLX << 24 |
83              30 << 8 | (256 - ICE_CANDIDATE_COMPONENT_DEFAULT);
84 static const int STUN_ERROR_BAD_REQUEST_AS_GICE =
85     STUN_ERROR_BAD_REQUEST / 256 * 100 + STUN_ERROR_BAD_REQUEST % 256;
86 static const int STUN_ERROR_UNAUTHORIZED_AS_GICE =
87     STUN_ERROR_UNAUTHORIZED / 256 * 100 + STUN_ERROR_UNAUTHORIZED % 256;
88 static const int STUN_ERROR_SERVER_ERROR_AS_GICE =
89     STUN_ERROR_SERVER_ERROR / 256 * 100 + STUN_ERROR_SERVER_ERROR % 256;
90
91 static const int kTiebreaker1 = 11111;
92 static const int kTiebreaker2 = 22222;
93
94 static Candidate GetCandidate(Port* port) {
95   assert(port->Candidates().size() == 1);
96   return port->Candidates()[0];
97 }
98
99 static SocketAddress GetAddress(Port* port) {
100   return GetCandidate(port).address();
101 }
102
103 static IceMessage* CopyStunMessage(const IceMessage* src) {
104   IceMessage* dst = new IceMessage();
105   ByteBuffer buf;
106   src->Write(&buf);
107   dst->Read(&buf);
108   return dst;
109 }
110
111 static bool WriteStunMessage(const StunMessage* msg, ByteBuffer* buf) {
112   buf->Resize(0);  // clear out any existing buffer contents
113   return msg->Write(buf);
114 }
115
116 // Stub port class for testing STUN generation and processing.
117 class TestPort : public Port {
118  public:
119   TestPort(talk_base::Thread* thread, const std::string& type,
120            talk_base::PacketSocketFactory* factory, talk_base::Network* network,
121            const talk_base::IPAddress& ip, int min_port, int max_port,
122            const std::string& username_fragment, const std::string& password)
123       : Port(thread, type, factory, network, ip,
124              min_port, max_port, username_fragment, password) {
125   }
126   ~TestPort() {}
127
128   // Expose GetStunMessage so that we can test it.
129   using cricket::Port::GetStunMessage;
130
131   // The last StunMessage that was sent on this Port.
132   // TODO: Make these const; requires changes to SendXXXXResponse.
133   ByteBuffer* last_stun_buf() { return last_stun_buf_.get(); }
134   IceMessage* last_stun_msg() { return last_stun_msg_.get(); }
135   int last_stun_error_code() {
136     int code = 0;
137     if (last_stun_msg_) {
138       const StunErrorCodeAttribute* error_attr = last_stun_msg_->GetErrorCode();
139       if (error_attr) {
140         code = error_attr->code();
141       }
142     }
143     return code;
144   }
145
146   virtual void PrepareAddress() {
147     talk_base::SocketAddress addr(ip(), min_port());
148     AddAddress(addr, addr, "udp", Type(), ICE_TYPE_PREFERENCE_HOST, true);
149   }
150
151   // Exposed for testing candidate building.
152   void AddCandidateAddress(const talk_base::SocketAddress& addr) {
153     AddAddress(addr, addr, "udp", Type(), type_preference_, false);
154   }
155   void AddCandidateAddress(const talk_base::SocketAddress& addr,
156                            const talk_base::SocketAddress& base_address,
157                            const std::string& type,
158                            int type_preference,
159                            bool final) {
160     AddAddress(addr, base_address, "udp", type,
161                type_preference, final);
162   }
163
164   virtual Connection* CreateConnection(const Candidate& remote_candidate,
165                                        CandidateOrigin origin) {
166     Connection* conn = new ProxyConnection(this, 0, remote_candidate);
167     AddConnection(conn);
168     // Set use-candidate attribute flag as this will add USE-CANDIDATE attribute
169     // in STUN binding requests.
170     conn->set_use_candidate_attr(true);
171     return conn;
172   }
173   virtual int SendTo(
174       const void* data, size_t size, const talk_base::SocketAddress& addr,
175       talk_base::DiffServCodePoint dscp, bool payload) {
176     if (!payload) {
177       IceMessage* msg = new IceMessage;
178       ByteBuffer* buf = new ByteBuffer(static_cast<const char*>(data), size);
179       ByteBuffer::ReadPosition pos(buf->GetReadPosition());
180       if (!msg->Read(buf)) {
181         delete msg;
182         delete buf;
183         return -1;
184       }
185       buf->SetReadPosition(pos);
186       last_stun_buf_.reset(buf);
187       last_stun_msg_.reset(msg);
188     }
189     return static_cast<int>(size);
190   }
191   virtual int SetOption(talk_base::Socket::Option opt, int value) {
192     return 0;
193   }
194   virtual int GetOption(talk_base::Socket::Option opt, int* value) {
195     return -1;
196   }
197   virtual int GetError() {
198     return 0;
199   }
200   void Reset() {
201     last_stun_buf_.reset();
202     last_stun_msg_.reset();
203   }
204   void set_type_preference(int type_preference) {
205     type_preference_ = type_preference;
206   }
207
208  private:
209   talk_base::scoped_ptr<ByteBuffer> last_stun_buf_;
210   talk_base::scoped_ptr<IceMessage> last_stun_msg_;
211   int type_preference_;
212 };
213
214 class TestChannel : public sigslot::has_slots<> {
215  public:
216   // Takes ownership of |p1| (but not |p2|).
217   TestChannel(Port* p1, Port* p2)
218       : ice_mode_(ICEMODE_FULL), src_(p1), dst_(p2), complete_count_(0),
219         conn_(NULL), remote_request_(), nominated_(false) {
220     src_->SignalPortComplete.connect(
221         this, &TestChannel::OnPortComplete);
222     src_->SignalUnknownAddress.connect(this, &TestChannel::OnUnknownAddress);
223     src_->SignalDestroyed.connect(this, &TestChannel::OnSrcPortDestroyed);
224   }
225
226   int complete_count() { return complete_count_; }
227   Connection* conn() { return conn_; }
228   const SocketAddress& remote_address() { return remote_address_; }
229   const std::string remote_fragment() { return remote_frag_; }
230
231   void Start() {
232     src_->PrepareAddress();
233   }
234   void CreateConnection() {
235     conn_ = src_->CreateConnection(GetCandidate(dst_), Port::ORIGIN_MESSAGE);
236     IceMode remote_ice_mode =
237         (ice_mode_ == ICEMODE_FULL) ? ICEMODE_LITE : ICEMODE_FULL;
238     conn_->set_remote_ice_mode(remote_ice_mode);
239     conn_->set_use_candidate_attr(remote_ice_mode == ICEMODE_FULL);
240     conn_->SignalStateChange.connect(
241         this, &TestChannel::OnConnectionStateChange);
242   }
243   void OnConnectionStateChange(Connection* conn) {
244     if (conn->write_state() == Connection::STATE_WRITABLE) {
245       conn->set_use_candidate_attr(true);
246       nominated_ = true;
247     }
248   }
249   void AcceptConnection() {
250     ASSERT_TRUE(remote_request_.get() != NULL);
251     Candidate c = GetCandidate(dst_);
252     c.set_address(remote_address_);
253     conn_ = src_->CreateConnection(c, Port::ORIGIN_MESSAGE);
254     src_->SendBindingResponse(remote_request_.get(), remote_address_);
255     remote_request_.reset();
256   }
257   void Ping() {
258     Ping(0);
259   }
260   void Ping(uint32 now) {
261     conn_->Ping(now);
262   }
263   void Stop() {
264     conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
265     conn_->Destroy();
266   }
267
268   void OnPortComplete(Port* port) {
269     complete_count_++;
270   }
271   void SetIceMode(IceMode ice_mode) {
272     ice_mode_ = ice_mode;
273   }
274
275   void OnUnknownAddress(PortInterface* port, const SocketAddress& addr,
276                         ProtocolType proto,
277                         IceMessage* msg, const std::string& rf,
278                         bool /*port_muxed*/) {
279     ASSERT_EQ(src_.get(), port);
280     if (!remote_address_.IsNil()) {
281       ASSERT_EQ(remote_address_, addr);
282     }
283     // MI and PRIORITY attribute should be present in ping requests when port
284     // is in ICEPROTO_RFC5245 mode.
285     const cricket::StunUInt32Attribute* priority_attr =
286         msg->GetUInt32(STUN_ATTR_PRIORITY);
287     const cricket::StunByteStringAttribute* mi_attr =
288         msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY);
289     const cricket::StunUInt32Attribute* fingerprint_attr =
290         msg->GetUInt32(STUN_ATTR_FINGERPRINT);
291     if (src_->IceProtocol() == cricket::ICEPROTO_RFC5245) {
292       EXPECT_TRUE(priority_attr != NULL);
293       EXPECT_TRUE(mi_attr != NULL);
294       EXPECT_TRUE(fingerprint_attr != NULL);
295     } else {
296       EXPECT_TRUE(priority_attr == NULL);
297       EXPECT_TRUE(mi_attr == NULL);
298       EXPECT_TRUE(fingerprint_attr == NULL);
299     }
300     remote_address_ = addr;
301     remote_request_.reset(CopyStunMessage(msg));
302     remote_frag_ = rf;
303   }
304
305   void OnDestroyed(Connection* conn) {
306     ASSERT_EQ(conn_, conn);
307     conn_ = NULL;
308   }
309
310   void OnSrcPortDestroyed(PortInterface* port) {
311     Port* destroyed_src = src_.release();
312     ASSERT_EQ(destroyed_src, port);
313   }
314
315   bool nominated() const { return nominated_; }
316
317  private:
318   IceMode ice_mode_;
319   talk_base::scoped_ptr<Port> src_;
320   Port* dst_;
321
322   int complete_count_;
323   Connection* conn_;
324   SocketAddress remote_address_;
325   talk_base::scoped_ptr<StunMessage> remote_request_;
326   std::string remote_frag_;
327   bool nominated_;
328 };
329
330 class PortTest : public testing::Test, public sigslot::has_slots<> {
331  public:
332   PortTest()
333       : main_(talk_base::Thread::Current()),
334         pss_(new talk_base::PhysicalSocketServer),
335         ss_(new talk_base::VirtualSocketServer(pss_.get())),
336         ss_scope_(ss_.get()),
337         network_("unittest", "unittest", talk_base::IPAddress(INADDR_ANY), 32),
338         socket_factory_(talk_base::Thread::Current()),
339         nat_factory1_(ss_.get(), kNatAddr1),
340         nat_factory2_(ss_.get(), kNatAddr2),
341         nat_socket_factory1_(&nat_factory1_),
342         nat_socket_factory2_(&nat_factory2_),
343         stun_server_(main_, kStunAddr),
344         turn_server_(main_, kTurnUdpIntAddr, kTurnUdpExtAddr),
345         relay_server_(main_, kRelayUdpIntAddr, kRelayUdpExtAddr,
346                       kRelayTcpIntAddr, kRelayTcpExtAddr,
347                       kRelaySslTcpIntAddr, kRelaySslTcpExtAddr),
348         username_(talk_base::CreateRandomString(ICE_UFRAG_LENGTH)),
349         password_(talk_base::CreateRandomString(ICE_PWD_LENGTH)),
350         ice_protocol_(cricket::ICEPROTO_GOOGLE),
351         role_conflict_(false),
352         destroyed_(false) {
353     network_.AddIP(talk_base::IPAddress(INADDR_ANY));
354   }
355
356  protected:
357   static void SetUpTestCase() {
358     // Ensure the RNG is inited.
359     talk_base::InitRandom(NULL, 0);
360   }
361
362   void TestLocalToLocal() {
363     Port* port1 = CreateUdpPort(kLocalAddr1);
364     Port* port2 = CreateUdpPort(kLocalAddr2);
365     TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
366   }
367   void TestLocalToStun(NATType ntype) {
368     Port* port1 = CreateUdpPort(kLocalAddr1);
369     nat_server2_.reset(CreateNatServer(kNatAddr2, ntype));
370     Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
371     TestConnectivity("udp", port1, StunName(ntype), port2,
372                      ntype == NAT_OPEN_CONE, true,
373                      ntype != NAT_SYMMETRIC, true);
374   }
375   void TestLocalToRelay(RelayType rtype, ProtocolType proto) {
376     Port* port1 = CreateUdpPort(kLocalAddr1);
377     Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
378     TestConnectivity("udp", port1, RelayName(rtype, proto), port2,
379                      rtype == RELAY_GTURN, true, true, true);
380   }
381   void TestStunToLocal(NATType ntype) {
382     nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
383     Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
384     Port* port2 = CreateUdpPort(kLocalAddr2);
385     TestConnectivity(StunName(ntype), port1, "udp", port2,
386                      true, ntype != NAT_SYMMETRIC, true, true);
387   }
388   void TestStunToStun(NATType ntype1, NATType ntype2) {
389     nat_server1_.reset(CreateNatServer(kNatAddr1, ntype1));
390     Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
391     nat_server2_.reset(CreateNatServer(kNatAddr2, ntype2));
392     Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
393     TestConnectivity(StunName(ntype1), port1, StunName(ntype2), port2,
394                      ntype2 == NAT_OPEN_CONE,
395                      ntype1 != NAT_SYMMETRIC, ntype2 != NAT_SYMMETRIC,
396                      ntype1 + ntype2 < (NAT_PORT_RESTRICTED + NAT_SYMMETRIC));
397   }
398   void TestStunToRelay(NATType ntype, RelayType rtype, ProtocolType proto) {
399     nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
400     Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
401     Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
402     TestConnectivity(StunName(ntype), port1, RelayName(rtype, proto), port2,
403                      rtype == RELAY_GTURN, ntype != NAT_SYMMETRIC, true, true);
404   }
405   void TestTcpToTcp() {
406     Port* port1 = CreateTcpPort(kLocalAddr1);
407     Port* port2 = CreateTcpPort(kLocalAddr2);
408     TestConnectivity("tcp", port1, "tcp", port2, true, false, true, true);
409   }
410   void TestTcpToRelay(RelayType rtype, ProtocolType proto) {
411     Port* port1 = CreateTcpPort(kLocalAddr1);
412     Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_TCP);
413     TestConnectivity("tcp", port1, RelayName(rtype, proto), port2,
414                      rtype == RELAY_GTURN, false, true, true);
415   }
416   void TestSslTcpToRelay(RelayType rtype, ProtocolType proto) {
417     Port* port1 = CreateTcpPort(kLocalAddr1);
418     Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_SSLTCP);
419     TestConnectivity("ssltcp", port1, RelayName(rtype, proto), port2,
420                      rtype == RELAY_GTURN, false, true, true);
421   }
422
423   // helpers for above functions
424   UDPPort* CreateUdpPort(const SocketAddress& addr) {
425     return CreateUdpPort(addr, &socket_factory_);
426   }
427   UDPPort* CreateUdpPort(const SocketAddress& addr,
428                          PacketSocketFactory* socket_factory) {
429     UDPPort* port = UDPPort::Create(main_, socket_factory, &network_,
430                                     addr.ipaddr(), 0, 0, username_, password_);
431     port->SetIceProtocolType(ice_protocol_);
432     return port;
433   }
434   TCPPort* CreateTcpPort(const SocketAddress& addr) {
435     TCPPort* port = CreateTcpPort(addr, &socket_factory_);
436     port->SetIceProtocolType(ice_protocol_);
437     return port;
438   }
439   TCPPort* CreateTcpPort(const SocketAddress& addr,
440                         PacketSocketFactory* socket_factory) {
441     TCPPort* port = TCPPort::Create(main_, socket_factory, &network_,
442                                     addr.ipaddr(), 0, 0, username_, password_,
443                                     true);
444     port->SetIceProtocolType(ice_protocol_);
445     return port;
446   }
447   StunPort* CreateStunPort(const SocketAddress& addr,
448                            talk_base::PacketSocketFactory* factory) {
449     StunPort* port = StunPort::Create(main_, factory, &network_,
450                                       addr.ipaddr(), 0, 0,
451                                       username_, password_, kStunAddr);
452     port->SetIceProtocolType(ice_protocol_);
453     return port;
454   }
455   Port* CreateRelayPort(const SocketAddress& addr, RelayType rtype,
456                         ProtocolType int_proto, ProtocolType ext_proto) {
457     if (rtype == RELAY_TURN) {
458       return CreateTurnPort(addr, &socket_factory_, int_proto, ext_proto);
459     } else {
460       return CreateGturnPort(addr, int_proto, ext_proto);
461     }
462   }
463   TurnPort* CreateTurnPort(const SocketAddress& addr,
464                            PacketSocketFactory* socket_factory,
465                            ProtocolType int_proto, ProtocolType ext_proto) {
466     TurnPort* port = TurnPort::Create(main_, socket_factory, &network_,
467                                       addr.ipaddr(), 0, 0,
468                                       username_, password_, ProtocolAddress(
469                                           kTurnUdpIntAddr, PROTO_UDP),
470                                       kRelayCredentials);
471     port->SetIceProtocolType(ice_protocol_);
472     return port;
473   }
474   RelayPort* CreateGturnPort(const SocketAddress& addr,
475                              ProtocolType int_proto, ProtocolType ext_proto) {
476     RelayPort* port = CreateGturnPort(addr);
477     SocketAddress addrs[] =
478         { kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr };
479     port->AddServerAddress(ProtocolAddress(addrs[int_proto], int_proto));
480     return port;
481   }
482   RelayPort* CreateGturnPort(const SocketAddress& addr) {
483     RelayPort* port = RelayPort::Create(main_, &socket_factory_, &network_,
484                                         addr.ipaddr(), 0, 0,
485                                         username_, password_);
486     // TODO: Add an external address for ext_proto, so that the
487     // other side can connect to this port using a non-UDP protocol.
488     port->SetIceProtocolType(ice_protocol_);
489     return port;
490   }
491   talk_base::NATServer* CreateNatServer(const SocketAddress& addr,
492                                         talk_base::NATType type) {
493     return new talk_base::NATServer(type, ss_.get(), addr, ss_.get(), addr);
494   }
495   static const char* StunName(NATType type) {
496     switch (type) {
497       case NAT_OPEN_CONE:       return "stun(open cone)";
498       case NAT_ADDR_RESTRICTED: return "stun(addr restricted)";
499       case NAT_PORT_RESTRICTED: return "stun(port restricted)";
500       case NAT_SYMMETRIC:       return "stun(symmetric)";
501       default:                  return "stun(?)";
502     }
503   }
504   static const char* RelayName(RelayType type, ProtocolType proto) {
505     if (type == RELAY_TURN) {
506       switch (proto) {
507         case PROTO_UDP:           return "turn(udp)";
508         case PROTO_TCP:           return "turn(tcp)";
509         case PROTO_SSLTCP:        return "turn(ssltcp)";
510         default:                  return "turn(?)";
511       }
512     } else {
513       switch (proto) {
514         case PROTO_UDP:           return "gturn(udp)";
515         case PROTO_TCP:           return "gturn(tcp)";
516         case PROTO_SSLTCP:        return "gturn(ssltcp)";
517         default:                  return "gturn(?)";
518       }
519     }
520   }
521
522   void TestCrossFamilyPorts(int type);
523
524   // This does all the work and then deletes |port1| and |port2|.
525   void TestConnectivity(const char* name1, Port* port1,
526                         const char* name2, Port* port2,
527                         bool accept, bool same_addr1,
528                         bool same_addr2, bool possible);
529
530   // This connects and disconnects the provided channels in the same sequence as
531   // TestConnectivity with all options set to |true|.  It does not delete either
532   // channel.
533   void ConnectAndDisconnectChannels(TestChannel* ch1, TestChannel* ch2);
534
535   void SetIceProtocolType(cricket::IceProtocolType protocol) {
536     ice_protocol_ = protocol;
537   }
538
539   IceMessage* CreateStunMessage(int type) {
540     IceMessage* msg = new IceMessage();
541     msg->SetType(type);
542     msg->SetTransactionID("TESTTESTTEST");
543     return msg;
544   }
545   IceMessage* CreateStunMessageWithUsername(int type,
546                                             const std::string& username) {
547     IceMessage* msg = CreateStunMessage(type);
548     msg->AddAttribute(
549         new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
550     return msg;
551   }
552   TestPort* CreateTestPort(const talk_base::SocketAddress& addr,
553                            const std::string& username,
554                            const std::string& password) {
555     TestPort* port =  new TestPort(main_, "test", &socket_factory_, &network_,
556                                    addr.ipaddr(), 0, 0, username, password);
557     port->SignalRoleConflict.connect(this, &PortTest::OnRoleConflict);
558     return port;
559   }
560   TestPort* CreateTestPort(const talk_base::SocketAddress& addr,
561                            const std::string& username,
562                            const std::string& password,
563                            cricket::IceProtocolType type,
564                            cricket::IceRole role,
565                            int tiebreaker) {
566     TestPort* port = CreateTestPort(addr, username, password);
567     port->SetIceProtocolType(type);
568     port->SetIceRole(role);
569     port->SetIceTiebreaker(tiebreaker);
570     return port;
571   }
572
573   void OnRoleConflict(PortInterface* port) {
574     role_conflict_ = true;
575   }
576   bool role_conflict() const { return role_conflict_; }
577
578   void ConnectToSignalDestroyed(PortInterface* port) {
579     port->SignalDestroyed.connect(this, &PortTest::OnDestroyed);
580   }
581
582   void OnDestroyed(PortInterface* port) {
583     destroyed_ = true;
584   }
585   bool destroyed() const { return destroyed_; }
586
587   talk_base::BasicPacketSocketFactory* nat_socket_factory1() {
588     return &nat_socket_factory1_;
589   }
590
591  private:
592   talk_base::Thread* main_;
593   talk_base::scoped_ptr<talk_base::PhysicalSocketServer> pss_;
594   talk_base::scoped_ptr<talk_base::VirtualSocketServer> ss_;
595   talk_base::SocketServerScope ss_scope_;
596   talk_base::Network network_;
597   talk_base::BasicPacketSocketFactory socket_factory_;
598   talk_base::scoped_ptr<talk_base::NATServer> nat_server1_;
599   talk_base::scoped_ptr<talk_base::NATServer> nat_server2_;
600   talk_base::NATSocketFactory nat_factory1_;
601   talk_base::NATSocketFactory nat_factory2_;
602   talk_base::BasicPacketSocketFactory nat_socket_factory1_;
603   talk_base::BasicPacketSocketFactory nat_socket_factory2_;
604   TestStunServer stun_server_;
605   TestTurnServer turn_server_;
606   TestRelayServer relay_server_;
607   std::string username_;
608   std::string password_;
609   cricket::IceProtocolType ice_protocol_;
610   bool role_conflict_;
611   bool destroyed_;
612 };
613
614 void PortTest::TestConnectivity(const char* name1, Port* port1,
615                                 const char* name2, Port* port2,
616                                 bool accept, bool same_addr1,
617                                 bool same_addr2, bool possible) {
618   LOG(LS_INFO) << "Test: " << name1 << " to " << name2 << ": ";
619   port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
620   port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
621
622   // Set up channels and ensure both ports will be deleted.
623   TestChannel ch1(port1, port2);
624   TestChannel ch2(port2, port1);
625   EXPECT_EQ(0, ch1.complete_count());
626   EXPECT_EQ(0, ch2.complete_count());
627
628   // Acquire addresses.
629   ch1.Start();
630   ch2.Start();
631   ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
632   ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
633
634   // Send a ping from src to dst. This may or may not make it.
635   ch1.CreateConnection();
636   ASSERT_TRUE(ch1.conn() != NULL);
637   EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout);  // for TCP connect
638   ch1.Ping();
639   WAIT(!ch2.remote_address().IsNil(), kTimeout);
640
641   if (accept) {
642     // We are able to send a ping from src to dst. This is the case when
643     // sending to UDP ports and cone NATs.
644     EXPECT_TRUE(ch1.remote_address().IsNil());
645     EXPECT_EQ(ch2.remote_fragment(), port1->username_fragment());
646
647     // Ensure the ping came from the same address used for src.
648     // This is the case unless the source NAT was symmetric.
649     if (same_addr1) EXPECT_EQ(ch2.remote_address(), GetAddress(port1));
650     EXPECT_TRUE(same_addr2);
651
652     // Send a ping from dst to src.
653     ch2.AcceptConnection();
654     ASSERT_TRUE(ch2.conn() != NULL);
655     ch2.Ping();
656     EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
657                    kTimeout);
658   } else {
659     // We can't send a ping from src to dst, so flip it around. This will happen
660     // when the destination NAT is addr/port restricted or symmetric.
661     EXPECT_TRUE(ch1.remote_address().IsNil());
662     EXPECT_TRUE(ch2.remote_address().IsNil());
663
664     // Send a ping from dst to src. Again, this may or may not make it.
665     ch2.CreateConnection();
666     ASSERT_TRUE(ch2.conn() != NULL);
667     ch2.Ping();
668     WAIT(ch2.conn()->write_state() == Connection::STATE_WRITABLE, kTimeout);
669
670     if (same_addr1 && same_addr2) {
671       // The new ping got back to the source.
672       EXPECT_EQ(Connection::STATE_READABLE, ch1.conn()->read_state());
673       EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
674
675       // First connection may not be writable if the first ping did not get
676       // through.  So we will have to do another.
677       if (ch1.conn()->write_state() == Connection::STATE_WRITE_INIT) {
678         ch1.Ping();
679         EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
680                        kTimeout);
681       }
682     } else if (!same_addr1 && possible) {
683       // The new ping went to the candidate address, but that address was bad.
684       // This will happen when the source NAT is symmetric.
685       EXPECT_TRUE(ch1.remote_address().IsNil());
686       EXPECT_TRUE(ch2.remote_address().IsNil());
687
688       // However, since we have now sent a ping to the source IP, we should be
689       // able to get a ping from it. This gives us the real source address.
690       ch1.Ping();
691       EXPECT_TRUE_WAIT(!ch2.remote_address().IsNil(), kTimeout);
692       EXPECT_EQ(Connection::STATE_READ_INIT, ch2.conn()->read_state());
693       EXPECT_TRUE(ch1.remote_address().IsNil());
694
695       // Pick up the actual address and establish the connection.
696       ch2.AcceptConnection();
697       ASSERT_TRUE(ch2.conn() != NULL);
698       ch2.Ping();
699       EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
700                      kTimeout);
701     } else if (!same_addr2 && possible) {
702       // The new ping came in, but from an unexpected address. This will happen
703       // when the destination NAT is symmetric.
704       EXPECT_FALSE(ch1.remote_address().IsNil());
705       EXPECT_EQ(Connection::STATE_READ_INIT, ch1.conn()->read_state());
706
707       // Update our address and complete the connection.
708       ch1.AcceptConnection();
709       ch1.Ping();
710       EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
711                      kTimeout);
712     } else {  // (!possible)
713       // There should be s no way for the pings to reach each other. Check it.
714       EXPECT_TRUE(ch1.remote_address().IsNil());
715       EXPECT_TRUE(ch2.remote_address().IsNil());
716       ch1.Ping();
717       WAIT(!ch2.remote_address().IsNil(), kTimeout);
718       EXPECT_TRUE(ch1.remote_address().IsNil());
719       EXPECT_TRUE(ch2.remote_address().IsNil());
720     }
721   }
722
723   // Everything should be good, unless we know the situation is impossible.
724   ASSERT_TRUE(ch1.conn() != NULL);
725   ASSERT_TRUE(ch2.conn() != NULL);
726   if (possible) {
727     EXPECT_EQ(Connection::STATE_READABLE, ch1.conn()->read_state());
728     EXPECT_EQ(Connection::STATE_WRITABLE, ch1.conn()->write_state());
729     EXPECT_EQ(Connection::STATE_READABLE, ch2.conn()->read_state());
730     EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
731   } else {
732     EXPECT_NE(Connection::STATE_READABLE, ch1.conn()->read_state());
733     EXPECT_NE(Connection::STATE_WRITABLE, ch1.conn()->write_state());
734     EXPECT_NE(Connection::STATE_READABLE, ch2.conn()->read_state());
735     EXPECT_NE(Connection::STATE_WRITABLE, ch2.conn()->write_state());
736   }
737
738   // Tear down and ensure that goes smoothly.
739   ch1.Stop();
740   ch2.Stop();
741   EXPECT_TRUE_WAIT(ch1.conn() == NULL, kTimeout);
742   EXPECT_TRUE_WAIT(ch2.conn() == NULL, kTimeout);
743 }
744
745 void PortTest::ConnectAndDisconnectChannels(TestChannel* ch1,
746                                             TestChannel* ch2) {
747   // Acquire addresses.
748   ch1->Start();
749   ch2->Start();
750
751   // Send a ping from src to dst.
752   ch1->CreateConnection();
753   EXPECT_TRUE_WAIT(ch1->conn()->connected(), kTimeout);  // for TCP connect
754   ch1->Ping();
755   WAIT(!ch2->remote_address().IsNil(), kTimeout);
756
757   // Send a ping from dst to src.
758   ch2->AcceptConnection();
759   ch2->Ping();
760   EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2->conn()->write_state(),
761                  kTimeout);
762
763   // Destroy the connections.
764   ch1->Stop();
765   ch2->Stop();
766 }
767
768 class FakePacketSocketFactory : public talk_base::PacketSocketFactory {
769  public:
770   FakePacketSocketFactory()
771       : next_udp_socket_(NULL),
772         next_server_tcp_socket_(NULL),
773         next_client_tcp_socket_(NULL) {
774   }
775   virtual ~FakePacketSocketFactory() { }
776
777   virtual AsyncPacketSocket* CreateUdpSocket(
778       const SocketAddress& address, int min_port, int max_port) {
779     EXPECT_TRUE(next_udp_socket_ != NULL);
780     AsyncPacketSocket* result = next_udp_socket_;
781     next_udp_socket_ = NULL;
782     return result;
783   }
784
785   virtual AsyncPacketSocket* CreateServerTcpSocket(
786       const SocketAddress& local_address, int min_port, int max_port,
787       int opts) {
788     EXPECT_TRUE(next_server_tcp_socket_ != NULL);
789     AsyncPacketSocket* result = next_server_tcp_socket_;
790     next_server_tcp_socket_ = NULL;
791     return result;
792   }
793
794   // TODO: |proxy_info| and |user_agent| should be set
795   // per-factory and not when socket is created.
796   virtual AsyncPacketSocket* CreateClientTcpSocket(
797       const SocketAddress& local_address, const SocketAddress& remote_address,
798       const talk_base::ProxyInfo& proxy_info,
799       const std::string& user_agent, int opts) {
800     EXPECT_TRUE(next_client_tcp_socket_ != NULL);
801     AsyncPacketSocket* result = next_client_tcp_socket_;
802     next_client_tcp_socket_ = NULL;
803     return result;
804   }
805
806   void set_next_udp_socket(AsyncPacketSocket* next_udp_socket) {
807     next_udp_socket_ = next_udp_socket;
808   }
809   void set_next_server_tcp_socket(AsyncPacketSocket* next_server_tcp_socket) {
810     next_server_tcp_socket_ = next_server_tcp_socket;
811   }
812   void set_next_client_tcp_socket(AsyncPacketSocket* next_client_tcp_socket) {
813     next_client_tcp_socket_ = next_client_tcp_socket;
814   }
815   talk_base::AsyncResolverInterface* CreateAsyncResolver() {
816     return NULL;
817   }
818
819  private:
820   AsyncPacketSocket* next_udp_socket_;
821   AsyncPacketSocket* next_server_tcp_socket_;
822   AsyncPacketSocket* next_client_tcp_socket_;
823 };
824
825 class FakeAsyncPacketSocket : public AsyncPacketSocket {
826  public:
827   // Returns current local address. Address may be set to NULL if the
828   // socket is not bound yet (GetState() returns STATE_BINDING).
829   virtual SocketAddress GetLocalAddress() const {
830     return SocketAddress();
831   }
832
833   // Returns remote address. Returns zeroes if this is not a client TCP socket.
834   virtual SocketAddress GetRemoteAddress() const {
835     return SocketAddress();
836   }
837
838   // Send a packet.
839   virtual int Send(const void *pv, size_t cb,
840                    talk_base::DiffServCodePoint dscp) {
841     return static_cast<int>(cb);
842   }
843   virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr,
844                      talk_base::DiffServCodePoint dscp) {
845     return static_cast<int>(cb);
846   }
847   virtual int Close() {
848     return 0;
849   }
850
851   virtual State GetState() const { return state_; }
852   virtual int GetOption(Socket::Option opt, int* value) { return 0; }
853   virtual int SetOption(Socket::Option opt, int value) { return 0; }
854   virtual int GetError() const { return 0; }
855   virtual void SetError(int error) { }
856
857   void set_state(State state) { state_ = state; }
858
859  private:
860   State state_;
861 };
862
863 // Local -> XXXX
864 TEST_F(PortTest, TestLocalToLocal) {
865   TestLocalToLocal();
866 }
867
868 TEST_F(PortTest, TestLocalToConeNat) {
869   TestLocalToStun(NAT_OPEN_CONE);
870 }
871
872 TEST_F(PortTest, TestLocalToARNat) {
873   TestLocalToStun(NAT_ADDR_RESTRICTED);
874 }
875
876 TEST_F(PortTest, TestLocalToPRNat) {
877   TestLocalToStun(NAT_PORT_RESTRICTED);
878 }
879
880 TEST_F(PortTest, TestLocalToSymNat) {
881   TestLocalToStun(NAT_SYMMETRIC);
882 }
883
884 TEST_F(PortTest, TestLocalToTurn) {
885   TestLocalToRelay(RELAY_TURN, PROTO_UDP);
886 }
887
888 TEST_F(PortTest, TestLocalToGturn) {
889   TestLocalToRelay(RELAY_GTURN, PROTO_UDP);
890 }
891
892 TEST_F(PortTest, TestLocalToTcpGturn) {
893   TestLocalToRelay(RELAY_GTURN, PROTO_TCP);
894 }
895
896 TEST_F(PortTest, TestLocalToSslTcpGturn) {
897   TestLocalToRelay(RELAY_GTURN, PROTO_SSLTCP);
898 }
899
900 // Cone NAT -> XXXX
901 TEST_F(PortTest, TestConeNatToLocal) {
902   TestStunToLocal(NAT_OPEN_CONE);
903 }
904
905 TEST_F(PortTest, TestConeNatToConeNat) {
906   TestStunToStun(NAT_OPEN_CONE, NAT_OPEN_CONE);
907 }
908
909 TEST_F(PortTest, TestConeNatToARNat) {
910   TestStunToStun(NAT_OPEN_CONE, NAT_ADDR_RESTRICTED);
911 }
912
913 TEST_F(PortTest, TestConeNatToPRNat) {
914   TestStunToStun(NAT_OPEN_CONE, NAT_PORT_RESTRICTED);
915 }
916
917 TEST_F(PortTest, TestConeNatToSymNat) {
918   TestStunToStun(NAT_OPEN_CONE, NAT_SYMMETRIC);
919 }
920
921 TEST_F(PortTest, TestConeNatToTurn) {
922   TestStunToRelay(NAT_OPEN_CONE, RELAY_TURN, PROTO_UDP);
923 }
924
925 TEST_F(PortTest, TestConeNatToGturn) {
926   TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_UDP);
927 }
928
929 TEST_F(PortTest, TestConeNatToTcpGturn) {
930   TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_TCP);
931 }
932
933 // Address-restricted NAT -> XXXX
934 TEST_F(PortTest, TestARNatToLocal) {
935   TestStunToLocal(NAT_ADDR_RESTRICTED);
936 }
937
938 TEST_F(PortTest, TestARNatToConeNat) {
939   TestStunToStun(NAT_ADDR_RESTRICTED, NAT_OPEN_CONE);
940 }
941
942 TEST_F(PortTest, TestARNatToARNat) {
943   TestStunToStun(NAT_ADDR_RESTRICTED, NAT_ADDR_RESTRICTED);
944 }
945
946 TEST_F(PortTest, TestARNatToPRNat) {
947   TestStunToStun(NAT_ADDR_RESTRICTED, NAT_PORT_RESTRICTED);
948 }
949
950 TEST_F(PortTest, TestARNatToSymNat) {
951   TestStunToStun(NAT_ADDR_RESTRICTED, NAT_SYMMETRIC);
952 }
953
954 TEST_F(PortTest, TestARNatToTurn) {
955   TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_TURN, PROTO_UDP);
956 }
957
958 TEST_F(PortTest, TestARNatToGturn) {
959   TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_UDP);
960 }
961
962 TEST_F(PortTest, TestARNATNatToTcpGturn) {
963   TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_TCP);
964 }
965
966 // Port-restricted NAT -> XXXX
967 TEST_F(PortTest, TestPRNatToLocal) {
968   TestStunToLocal(NAT_PORT_RESTRICTED);
969 }
970
971 TEST_F(PortTest, TestPRNatToConeNat) {
972   TestStunToStun(NAT_PORT_RESTRICTED, NAT_OPEN_CONE);
973 }
974
975 TEST_F(PortTest, TestPRNatToARNat) {
976   TestStunToStun(NAT_PORT_RESTRICTED, NAT_ADDR_RESTRICTED);
977 }
978
979 TEST_F(PortTest, TestPRNatToPRNat) {
980   TestStunToStun(NAT_PORT_RESTRICTED, NAT_PORT_RESTRICTED);
981 }
982
983 TEST_F(PortTest, TestPRNatToSymNat) {
984   // Will "fail"
985   TestStunToStun(NAT_PORT_RESTRICTED, NAT_SYMMETRIC);
986 }
987
988 TEST_F(PortTest, TestPRNatToTurn) {
989   TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_TURN, PROTO_UDP);
990 }
991
992 TEST_F(PortTest, TestPRNatToGturn) {
993   TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_UDP);
994 }
995
996 TEST_F(PortTest, TestPRNatToTcpGturn) {
997   TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_TCP);
998 }
999
1000 // Symmetric NAT -> XXXX
1001 TEST_F(PortTest, TestSymNatToLocal) {
1002   TestStunToLocal(NAT_SYMMETRIC);
1003 }
1004
1005 TEST_F(PortTest, TestSymNatToConeNat) {
1006   TestStunToStun(NAT_SYMMETRIC, NAT_OPEN_CONE);
1007 }
1008
1009 TEST_F(PortTest, TestSymNatToARNat) {
1010   TestStunToStun(NAT_SYMMETRIC, NAT_ADDR_RESTRICTED);
1011 }
1012
1013 TEST_F(PortTest, TestSymNatToPRNat) {
1014   // Will "fail"
1015   TestStunToStun(NAT_SYMMETRIC, NAT_PORT_RESTRICTED);
1016 }
1017
1018 TEST_F(PortTest, TestSymNatToSymNat) {
1019   // Will "fail"
1020   TestStunToStun(NAT_SYMMETRIC, NAT_SYMMETRIC);
1021 }
1022
1023 TEST_F(PortTest, TestSymNatToTurn) {
1024   TestStunToRelay(NAT_SYMMETRIC, RELAY_TURN, PROTO_UDP);
1025 }
1026
1027 TEST_F(PortTest, TestSymNatToGturn) {
1028   TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_UDP);
1029 }
1030
1031 TEST_F(PortTest, TestSymNatToTcpGturn) {
1032   TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_TCP);
1033 }
1034
1035 // Outbound TCP -> XXXX
1036 TEST_F(PortTest, TestTcpToTcp) {
1037   TestTcpToTcp();
1038 }
1039
1040 /* TODO: Enable these once testrelayserver can accept external TCP.
1041 TEST_F(PortTest, TestTcpToTcpRelay) {
1042   TestTcpToRelay(PROTO_TCP);
1043 }
1044
1045 TEST_F(PortTest, TestTcpToSslTcpRelay) {
1046   TestTcpToRelay(PROTO_SSLTCP);
1047 }
1048 */
1049
1050 // Outbound SSLTCP -> XXXX
1051 /* TODO: Enable these once testrelayserver can accept external SSL.
1052 TEST_F(PortTest, TestSslTcpToTcpRelay) {
1053   TestSslTcpToRelay(PROTO_TCP);
1054 }
1055
1056 TEST_F(PortTest, TestSslTcpToSslTcpRelay) {
1057   TestSslTcpToRelay(PROTO_SSLTCP);
1058 }
1059 */
1060
1061 // This test case verifies standard ICE features in STUN messages. Currently it
1062 // verifies Message Integrity attribute in STUN messages and username in STUN
1063 // binding request will have colon (":") between remote and local username.
1064 TEST_F(PortTest, TestLocalToLocalAsIce) {
1065   SetIceProtocolType(cricket::ICEPROTO_RFC5245);
1066   UDPPort* port1 = CreateUdpPort(kLocalAddr1);
1067   port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1068   port1->SetIceTiebreaker(kTiebreaker1);
1069   ASSERT_EQ(cricket::ICEPROTO_RFC5245, port1->IceProtocol());
1070   UDPPort* port2 = CreateUdpPort(kLocalAddr2);
1071   port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
1072   port2->SetIceTiebreaker(kTiebreaker2);
1073   ASSERT_EQ(cricket::ICEPROTO_RFC5245, port2->IceProtocol());
1074   // Same parameters as TestLocalToLocal above.
1075   TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
1076 }
1077
1078 // This test is trying to validate a successful and failure scenario in a
1079 // loopback test when protocol is RFC5245. For success IceTiebreaker, username
1080 // should remain equal to the request generated by the port and role of port
1081 // must be in controlling.
1082 TEST_F(PortTest, TestLoopbackCallAsIce) {
1083   talk_base::scoped_ptr<TestPort> lport(
1084       CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1085   lport->SetIceProtocolType(ICEPROTO_RFC5245);
1086   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1087   lport->SetIceTiebreaker(kTiebreaker1);
1088   lport->PrepareAddress();
1089   ASSERT_FALSE(lport->Candidates().empty());
1090   Connection* conn = lport->CreateConnection(lport->Candidates()[0],
1091                                              Port::ORIGIN_MESSAGE);
1092   conn->Ping(0);
1093
1094   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1095   IceMessage* msg = lport->last_stun_msg();
1096   EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1097   conn->OnReadPacket(lport->last_stun_buf()->Data(),
1098                      lport->last_stun_buf()->Length(),
1099                      talk_base::PacketTime());
1100   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1101   msg = lport->last_stun_msg();
1102   EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1103
1104   // If the tiebreaker value is different from port, we expect a error
1105   // response.
1106   lport->Reset();
1107   lport->AddCandidateAddress(kLocalAddr2);
1108   // Creating a different connection as |conn| is in STATE_READABLE.
1109   Connection* conn1 = lport->CreateConnection(lport->Candidates()[1],
1110                                               Port::ORIGIN_MESSAGE);
1111   conn1->Ping(0);
1112
1113   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1114   msg = lport->last_stun_msg();
1115   EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1116   talk_base::scoped_ptr<IceMessage> modified_req(
1117       CreateStunMessage(STUN_BINDING_REQUEST));
1118   const StunByteStringAttribute* username_attr = msg->GetByteString(
1119       STUN_ATTR_USERNAME);
1120   modified_req->AddAttribute(new StunByteStringAttribute(
1121       STUN_ATTR_USERNAME, username_attr->GetString()));
1122   // To make sure we receive error response, adding tiebreaker less than
1123   // what's present in request.
1124   modified_req->AddAttribute(new StunUInt64Attribute(
1125       STUN_ATTR_ICE_CONTROLLING, kTiebreaker1 - 1));
1126   modified_req->AddMessageIntegrity("lpass");
1127   modified_req->AddFingerprint();
1128
1129   lport->Reset();
1130   talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1131   WriteStunMessage(modified_req.get(), buf.get());
1132   conn1->OnReadPacket(buf->Data(), buf->Length(), talk_base::PacketTime());
1133   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1134   msg = lport->last_stun_msg();
1135   EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1136 }
1137
1138 // This test verifies role conflict signal is received when there is
1139 // conflict in the role. In this case both ports are in controlling and
1140 // |rport| has higher tiebreaker value than |lport|. Since |lport| has lower
1141 // value of tiebreaker, when it receives ping request from |rport| it will
1142 // send role conflict signal.
1143 TEST_F(PortTest, TestIceRoleConflict) {
1144   talk_base::scoped_ptr<TestPort> lport(
1145       CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1146   lport->SetIceProtocolType(ICEPROTO_RFC5245);
1147   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1148   lport->SetIceTiebreaker(kTiebreaker1);
1149   talk_base::scoped_ptr<TestPort> rport(
1150       CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1151   rport->SetIceProtocolType(ICEPROTO_RFC5245);
1152   rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1153   rport->SetIceTiebreaker(kTiebreaker2);
1154
1155   lport->PrepareAddress();
1156   rport->PrepareAddress();
1157   ASSERT_FALSE(lport->Candidates().empty());
1158   ASSERT_FALSE(rport->Candidates().empty());
1159   Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
1160                                               Port::ORIGIN_MESSAGE);
1161   Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
1162                                               Port::ORIGIN_MESSAGE);
1163   rconn->Ping(0);
1164
1165   ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1166   IceMessage* msg = rport->last_stun_msg();
1167   EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1168   // Send rport binding request to lport.
1169   lconn->OnReadPacket(rport->last_stun_buf()->Data(),
1170                       rport->last_stun_buf()->Length(),
1171                       talk_base::PacketTime());
1172
1173   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1174   EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
1175   EXPECT_TRUE(role_conflict());
1176 }
1177
1178 TEST_F(PortTest, TestTcpNoDelay) {
1179   TCPPort* port1 = CreateTcpPort(kLocalAddr1);
1180   int option_value = -1;
1181   int success = port1->GetOption(talk_base::Socket::OPT_NODELAY,
1182                                  &option_value);
1183   ASSERT_EQ(0, success);  // GetOption() should complete successfully w/ 0
1184   ASSERT_EQ(1, option_value);
1185   delete port1;
1186 }
1187
1188 TEST_F(PortTest, TestDelayedBindingUdp) {
1189   FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1190   FakePacketSocketFactory socket_factory;
1191
1192   socket_factory.set_next_udp_socket(socket);
1193   scoped_ptr<UDPPort> port(
1194       CreateUdpPort(kLocalAddr1, &socket_factory));
1195
1196   socket->set_state(AsyncPacketSocket::STATE_BINDING);
1197   port->PrepareAddress();
1198
1199   EXPECT_EQ(0U, port->Candidates().size());
1200   socket->SignalAddressReady(socket, kLocalAddr2);
1201
1202   EXPECT_EQ(1U, port->Candidates().size());
1203 }
1204
1205 TEST_F(PortTest, TestDelayedBindingTcp) {
1206   FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1207   FakePacketSocketFactory socket_factory;
1208
1209   socket_factory.set_next_server_tcp_socket(socket);
1210   scoped_ptr<TCPPort> port(
1211       CreateTcpPort(kLocalAddr1, &socket_factory));
1212
1213   socket->set_state(AsyncPacketSocket::STATE_BINDING);
1214   port->PrepareAddress();
1215
1216   EXPECT_EQ(0U, port->Candidates().size());
1217   socket->SignalAddressReady(socket, kLocalAddr2);
1218
1219   EXPECT_EQ(1U, port->Candidates().size());
1220 }
1221
1222 void PortTest::TestCrossFamilyPorts(int type) {
1223   FakePacketSocketFactory factory;
1224   scoped_ptr<Port> ports[4];
1225   SocketAddress addresses[4] = {SocketAddress("192.168.1.3", 0),
1226                                 SocketAddress("192.168.1.4", 0),
1227                                 SocketAddress("2001:db8::1", 0),
1228                                 SocketAddress("2001:db8::2", 0)};
1229   for (int i = 0; i < 4; i++) {
1230     FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1231     if (type == SOCK_DGRAM) {
1232       factory.set_next_udp_socket(socket);
1233       ports[i].reset(CreateUdpPort(addresses[i], &factory));
1234     } else if (type == SOCK_STREAM) {
1235       factory.set_next_server_tcp_socket(socket);
1236       ports[i].reset(CreateTcpPort(addresses[i], &factory));
1237     }
1238     socket->set_state(AsyncPacketSocket::STATE_BINDING);
1239     socket->SignalAddressReady(socket, addresses[i]);
1240     ports[i]->PrepareAddress();
1241   }
1242
1243   // IPv4 Port, connects to IPv6 candidate and then to IPv4 candidate.
1244   if (type == SOCK_STREAM) {
1245     FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1246     factory.set_next_client_tcp_socket(clientsocket);
1247   }
1248   Connection* c = ports[0]->CreateConnection(GetCandidate(ports[2].get()),
1249                                              Port::ORIGIN_MESSAGE);
1250   EXPECT_TRUE(NULL == c);
1251   EXPECT_EQ(0U, ports[0]->connections().size());
1252   c = ports[0]->CreateConnection(GetCandidate(ports[1].get()),
1253                                  Port::ORIGIN_MESSAGE);
1254   EXPECT_FALSE(NULL == c);
1255   EXPECT_EQ(1U, ports[0]->connections().size());
1256
1257   // IPv6 Port, connects to IPv4 candidate and to IPv6 candidate.
1258   if (type == SOCK_STREAM) {
1259     FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1260     factory.set_next_client_tcp_socket(clientsocket);
1261   }
1262   c = ports[2]->CreateConnection(GetCandidate(ports[0].get()),
1263                                  Port::ORIGIN_MESSAGE);
1264   EXPECT_TRUE(NULL == c);
1265   EXPECT_EQ(0U, ports[2]->connections().size());
1266   c = ports[2]->CreateConnection(GetCandidate(ports[3].get()),
1267                                  Port::ORIGIN_MESSAGE);
1268   EXPECT_FALSE(NULL == c);
1269   EXPECT_EQ(1U, ports[2]->connections().size());
1270 }
1271
1272 TEST_F(PortTest, TestSkipCrossFamilyTcp) {
1273   TestCrossFamilyPorts(SOCK_STREAM);
1274 }
1275
1276 TEST_F(PortTest, TestSkipCrossFamilyUdp) {
1277   TestCrossFamilyPorts(SOCK_DGRAM);
1278 }
1279
1280 // This test verifies DSCP value set through SetOption interface can be
1281 // get through DefaultDscpValue.
1282 TEST_F(PortTest, TestDefaultDscpValue) {
1283   talk_base::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
1284   udpport->SetOption(talk_base::Socket::OPT_DSCP, talk_base::DSCP_CS6);
1285   EXPECT_EQ(talk_base::DSCP_CS6, udpport->DefaultDscpValue());
1286   talk_base::scoped_ptr<TCPPort> tcpport(CreateTcpPort(kLocalAddr1));
1287   tcpport->SetOption(talk_base::Socket::OPT_DSCP, talk_base::DSCP_AF31);
1288   EXPECT_EQ(talk_base::DSCP_AF31, tcpport->DefaultDscpValue());
1289   talk_base::scoped_ptr<StunPort> stunport(
1290       CreateStunPort(kLocalAddr1, nat_socket_factory1()));
1291   stunport->SetOption(talk_base::Socket::OPT_DSCP, talk_base::DSCP_AF41);
1292   EXPECT_EQ(talk_base::DSCP_AF41, stunport->DefaultDscpValue());
1293   talk_base::scoped_ptr<TurnPort> turnport(CreateTurnPort(
1294       kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1295   turnport->SetOption(talk_base::Socket::OPT_DSCP, talk_base::DSCP_CS7);
1296   EXPECT_EQ(talk_base::DSCP_CS7, turnport->DefaultDscpValue());
1297   // TODO(mallinath) - Test DSCP through GetOption.
1298 }
1299
1300 // Test sending STUN messages in GICE format.
1301 TEST_F(PortTest, TestSendStunMessageAsGice) {
1302   talk_base::scoped_ptr<TestPort> lport(
1303       CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1304   talk_base::scoped_ptr<TestPort> rport(
1305       CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1306   lport->SetIceProtocolType(ICEPROTO_GOOGLE);
1307   rport->SetIceProtocolType(ICEPROTO_GOOGLE);
1308
1309   // Send a fake ping from lport to rport.
1310   lport->PrepareAddress();
1311   rport->PrepareAddress();
1312   ASSERT_FALSE(rport->Candidates().empty());
1313   Connection* conn = lport->CreateConnection(rport->Candidates()[0],
1314       Port::ORIGIN_MESSAGE);
1315   rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1316   conn->Ping(0);
1317
1318   // Check that it's a proper BINDING-REQUEST.
1319   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1320   IceMessage* msg = lport->last_stun_msg();
1321   EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1322   EXPECT_FALSE(msg->IsLegacy());
1323   const StunByteStringAttribute* username_attr = msg->GetByteString(
1324       STUN_ATTR_USERNAME);
1325   ASSERT_TRUE(username_attr != NULL);
1326   EXPECT_EQ("rfraglfrag", username_attr->GetString());
1327   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) == NULL);
1328   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1329   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_FINGERPRINT) == NULL);
1330
1331   // Save a copy of the BINDING-REQUEST for use below.
1332   talk_base::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
1333
1334   // Respond with a BINDING-RESPONSE.
1335   rport->SendBindingResponse(request.get(), lport->Candidates()[0].address());
1336   msg = rport->last_stun_msg();
1337   ASSERT_TRUE(msg != NULL);
1338   EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1339   EXPECT_FALSE(msg->IsLegacy());
1340   username_attr = msg->GetByteString(STUN_ATTR_USERNAME);
1341   ASSERT_TRUE(username_attr != NULL);  // GICE has a username in the response.
1342   EXPECT_EQ("rfraglfrag", username_attr->GetString());
1343   const StunAddressAttribute* addr_attr = msg->GetAddress(
1344       STUN_ATTR_MAPPED_ADDRESS);
1345   ASSERT_TRUE(addr_attr != NULL);
1346   EXPECT_EQ(lport->Candidates()[0].address(), addr_attr->GetAddress());
1347   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_XOR_MAPPED_ADDRESS) == NULL);
1348   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) == NULL);
1349   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1350   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_FINGERPRINT) == NULL);
1351
1352   // Respond with a BINDING-ERROR-RESPONSE. This wouldn't happen in real life,
1353   // but we can do it here.
1354   rport->SendBindingErrorResponse(request.get(),
1355                                   rport->Candidates()[0].address(),
1356                                   STUN_ERROR_SERVER_ERROR,
1357                                   STUN_ERROR_REASON_SERVER_ERROR);
1358   msg = rport->last_stun_msg();
1359   ASSERT_TRUE(msg != NULL);
1360   EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1361   EXPECT_FALSE(msg->IsLegacy());
1362   username_attr = msg->GetByteString(STUN_ATTR_USERNAME);
1363   ASSERT_TRUE(username_attr != NULL);  // GICE has a username in the response.
1364   EXPECT_EQ("rfraglfrag", username_attr->GetString());
1365   const StunErrorCodeAttribute* error_attr = msg->GetErrorCode();
1366   ASSERT_TRUE(error_attr != NULL);
1367   // The GICE wire format for error codes is incorrect.
1368   EXPECT_EQ(STUN_ERROR_SERVER_ERROR_AS_GICE, error_attr->code());
1369   EXPECT_EQ(STUN_ERROR_SERVER_ERROR / 256, error_attr->eclass());
1370   EXPECT_EQ(STUN_ERROR_SERVER_ERROR % 256, error_attr->number());
1371   EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR), error_attr->reason());
1372   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1373   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) == NULL);
1374   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_FINGERPRINT) == NULL);
1375 }
1376
1377 // Test sending STUN messages in ICE format.
1378 TEST_F(PortTest, TestSendStunMessageAsIce) {
1379   talk_base::scoped_ptr<TestPort> lport(
1380       CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1381   talk_base::scoped_ptr<TestPort> rport(
1382       CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1383   lport->SetIceProtocolType(ICEPROTO_RFC5245);
1384   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1385   lport->SetIceTiebreaker(kTiebreaker1);
1386   rport->SetIceProtocolType(ICEPROTO_RFC5245);
1387   rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1388   rport->SetIceTiebreaker(kTiebreaker2);
1389
1390   // Send a fake ping from lport to rport.
1391   lport->PrepareAddress();
1392   rport->PrepareAddress();
1393   ASSERT_FALSE(rport->Candidates().empty());
1394   Connection* lconn = lport->CreateConnection(
1395       rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1396   Connection* rconn = rport->CreateConnection(
1397       lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1398   lconn->Ping(0);
1399
1400   // Check that it's a proper BINDING-REQUEST.
1401   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1402   IceMessage* msg = lport->last_stun_msg();
1403   EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1404   EXPECT_FALSE(msg->IsLegacy());
1405   const StunByteStringAttribute* username_attr =
1406       msg->GetByteString(STUN_ATTR_USERNAME);
1407   ASSERT_TRUE(username_attr != NULL);
1408   const StunUInt32Attribute* priority_attr = msg->GetUInt32(STUN_ATTR_PRIORITY);
1409   ASSERT_TRUE(priority_attr != NULL);
1410   EXPECT_EQ(kDefaultPrflxPriority, priority_attr->value());
1411   EXPECT_EQ("rfrag:lfrag", username_attr->GetString());
1412   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1413   EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1414       lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length(),
1415       "rpass"));
1416   const StunUInt64Attribute* ice_controlling_attr =
1417       msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1418   ASSERT_TRUE(ice_controlling_attr != NULL);
1419   EXPECT_EQ(lport->IceTiebreaker(), ice_controlling_attr->value());
1420   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1421   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
1422   EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1423   EXPECT_TRUE(StunMessage::ValidateFingerprint(
1424       lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1425
1426   // Request should not include ping count.
1427   ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1428
1429   // Save a copy of the BINDING-REQUEST for use below.
1430   talk_base::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
1431
1432   // Respond with a BINDING-RESPONSE.
1433   rport->SendBindingResponse(request.get(), lport->Candidates()[0].address());
1434   msg = rport->last_stun_msg();
1435   ASSERT_TRUE(msg != NULL);
1436   EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1437
1438
1439   EXPECT_FALSE(msg->IsLegacy());
1440   const StunAddressAttribute* addr_attr = msg->GetAddress(
1441       STUN_ATTR_XOR_MAPPED_ADDRESS);
1442   ASSERT_TRUE(addr_attr != NULL);
1443   EXPECT_EQ(lport->Candidates()[0].address(), addr_attr->GetAddress());
1444   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1445   EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1446       rport->last_stun_buf()->Data(), rport->last_stun_buf()->Length(),
1447       "rpass"));
1448   EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1449   EXPECT_TRUE(StunMessage::ValidateFingerprint(
1450       lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1451   // No USERNAME or PRIORITY in ICE responses.
1452   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1453   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1454   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MAPPED_ADDRESS) == NULL);
1455   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLING) == NULL);
1456   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1457   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1458
1459   // Response should not include ping count.
1460   ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1461
1462   // Respond with a BINDING-ERROR-RESPONSE. This wouldn't happen in real life,
1463   // but we can do it here.
1464   rport->SendBindingErrorResponse(request.get(),
1465                                   lport->Candidates()[0].address(),
1466                                   STUN_ERROR_SERVER_ERROR,
1467                                   STUN_ERROR_REASON_SERVER_ERROR);
1468   msg = rport->last_stun_msg();
1469   ASSERT_TRUE(msg != NULL);
1470   EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1471   EXPECT_FALSE(msg->IsLegacy());
1472   const StunErrorCodeAttribute* error_attr = msg->GetErrorCode();
1473   ASSERT_TRUE(error_attr != NULL);
1474   EXPECT_EQ(STUN_ERROR_SERVER_ERROR, error_attr->code());
1475   EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR), error_attr->reason());
1476   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1477   EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1478       rport->last_stun_buf()->Data(), rport->last_stun_buf()->Length(),
1479       "rpass"));
1480   EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1481   EXPECT_TRUE(StunMessage::ValidateFingerprint(
1482       lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1483   // No USERNAME with ICE.
1484   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1485   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1486
1487   // Testing STUN binding requests from rport --> lport, having ICE_CONTROLLED
1488   // and (incremented) RETRANSMIT_COUNT attributes.
1489   rport->Reset();
1490   rport->set_send_retransmit_count_attribute(true);
1491   rconn->Ping(0);
1492   rconn->Ping(0);
1493   rconn->Ping(0);
1494   ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1495   msg = rport->last_stun_msg();
1496   EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1497   const StunUInt64Attribute* ice_controlled_attr =
1498       msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
1499   ASSERT_TRUE(ice_controlled_attr != NULL);
1500   EXPECT_EQ(rport->IceTiebreaker(), ice_controlled_attr->value());
1501   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1502
1503   // Request should include ping count.
1504   const StunUInt32Attribute* retransmit_attr =
1505       msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1506   ASSERT_TRUE(retransmit_attr != NULL);
1507   EXPECT_EQ(2U, retransmit_attr->value());
1508
1509   // Respond with a BINDING-RESPONSE.
1510   request.reset(CopyStunMessage(msg));
1511   lport->SendBindingResponse(request.get(), rport->Candidates()[0].address());
1512   msg = lport->last_stun_msg();
1513
1514   // Response should include same ping count.
1515   retransmit_attr = msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1516   ASSERT_TRUE(retransmit_attr != NULL);
1517   EXPECT_EQ(2U, retransmit_attr->value());
1518 }
1519
1520 TEST_F(PortTest, TestUseCandidateAttribute) {
1521   talk_base::scoped_ptr<TestPort> lport(
1522       CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1523   talk_base::scoped_ptr<TestPort> rport(
1524       CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1525   lport->SetIceProtocolType(ICEPROTO_RFC5245);
1526   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1527   lport->SetIceTiebreaker(kTiebreaker1);
1528   rport->SetIceProtocolType(ICEPROTO_RFC5245);
1529   rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1530   rport->SetIceTiebreaker(kTiebreaker2);
1531
1532   // Send a fake ping from lport to rport.
1533   lport->PrepareAddress();
1534   rport->PrepareAddress();
1535   ASSERT_FALSE(rport->Candidates().empty());
1536   Connection* lconn = lport->CreateConnection(
1537       rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1538   lconn->Ping(0);
1539   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1540   IceMessage* msg = lport->last_stun_msg();
1541   const StunUInt64Attribute* ice_controlling_attr =
1542       msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1543   ASSERT_TRUE(ice_controlling_attr != NULL);
1544   const StunByteStringAttribute* use_candidate_attr = msg->GetByteString(
1545       STUN_ATTR_USE_CANDIDATE);
1546   ASSERT_TRUE(use_candidate_attr != NULL);
1547 }
1548
1549 // Test handling STUN messages in GICE format.
1550 TEST_F(PortTest, TestHandleStunMessageAsGice) {
1551   // Our port will act as the "remote" port.
1552   talk_base::scoped_ptr<TestPort> port(
1553       CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1554   port->SetIceProtocolType(ICEPROTO_GOOGLE);
1555
1556   talk_base::scoped_ptr<IceMessage> in_msg, out_msg;
1557   talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1558   talk_base::SocketAddress addr(kLocalAddr1);
1559   std::string username;
1560
1561   // BINDING-REQUEST from local to remote with valid GICE username and no M-I.
1562   in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1563                                              "rfraglfrag"));
1564   WriteStunMessage(in_msg.get(), buf.get());
1565   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1566                                    out_msg.accept(), &username));
1567   EXPECT_TRUE(out_msg.get() != NULL);  // Succeeds, since this is GICE.
1568   EXPECT_EQ("lfrag", username);
1569
1570   // Add M-I; should be ignored and rest of message parsed normally.
1571   in_msg->AddMessageIntegrity("password");
1572   WriteStunMessage(in_msg.get(), buf.get());
1573   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1574                                    out_msg.accept(), &username));
1575   EXPECT_TRUE(out_msg.get() != NULL);
1576   EXPECT_EQ("lfrag", username);
1577
1578   // BINDING-RESPONSE with username, as done in GICE. Should succeed.
1579   in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_RESPONSE,
1580                                              "rfraglfrag"));
1581   in_msg->AddAttribute(
1582       new StunAddressAttribute(STUN_ATTR_MAPPED_ADDRESS, kLocalAddr2));
1583   WriteStunMessage(in_msg.get(), buf.get());
1584   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1585                                    out_msg.accept(), &username));
1586   EXPECT_TRUE(out_msg.get() != NULL);
1587   EXPECT_EQ("", username);
1588
1589   // BINDING-RESPONSE without username. Should be tolerated as well.
1590   in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1591   in_msg->AddAttribute(
1592       new StunAddressAttribute(STUN_ATTR_MAPPED_ADDRESS, kLocalAddr2));
1593   WriteStunMessage(in_msg.get(), buf.get());
1594   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1595                                    out_msg.accept(), &username));
1596   EXPECT_TRUE(out_msg.get() != NULL);
1597   EXPECT_EQ("", username);
1598
1599   // BINDING-ERROR-RESPONSE with username and error code.
1600   in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_ERROR_RESPONSE,
1601                                              "rfraglfrag"));
1602   in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1603       STUN_ERROR_SERVER_ERROR_AS_GICE, STUN_ERROR_REASON_SERVER_ERROR));
1604   WriteStunMessage(in_msg.get(), buf.get());
1605   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1606                                    out_msg.accept(), &username));
1607   ASSERT_TRUE(out_msg.get() != NULL);
1608   EXPECT_EQ("", username);
1609   ASSERT_TRUE(out_msg->GetErrorCode() != NULL);
1610   // GetStunMessage doesn't unmunge the GICE error code (happens downstream).
1611   EXPECT_EQ(STUN_ERROR_SERVER_ERROR_AS_GICE, out_msg->GetErrorCode()->code());
1612   EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR),
1613       out_msg->GetErrorCode()->reason());
1614 }
1615
1616 // Test handling STUN messages in ICE format.
1617 TEST_F(PortTest, TestHandleStunMessageAsIce) {
1618   // Our port will act as the "remote" port.
1619   talk_base::scoped_ptr<TestPort> port(
1620       CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1621   port->SetIceProtocolType(ICEPROTO_RFC5245);
1622
1623   talk_base::scoped_ptr<IceMessage> in_msg, out_msg;
1624   talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1625   talk_base::SocketAddress addr(kLocalAddr1);
1626   std::string username;
1627
1628   // BINDING-REQUEST from local to remote with valid ICE username,
1629   // MESSAGE-INTEGRITY, and FINGERPRINT.
1630   in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1631                                              "rfrag:lfrag"));
1632   in_msg->AddMessageIntegrity("rpass");
1633   in_msg->AddFingerprint();
1634   WriteStunMessage(in_msg.get(), buf.get());
1635   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1636                                    out_msg.accept(), &username));
1637   EXPECT_TRUE(out_msg.get() != NULL);
1638   EXPECT_EQ("lfrag", username);
1639
1640   // BINDING-RESPONSE without username, with MESSAGE-INTEGRITY and FINGERPRINT.
1641   in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1642   in_msg->AddAttribute(
1643       new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1644   in_msg->AddMessageIntegrity("rpass");
1645   in_msg->AddFingerprint();
1646   WriteStunMessage(in_msg.get(), buf.get());
1647   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1648                                    out_msg.accept(), &username));
1649   EXPECT_TRUE(out_msg.get() != NULL);
1650   EXPECT_EQ("", username);
1651
1652   // BINDING-ERROR-RESPONSE without username, with error, M-I, and FINGERPRINT.
1653   in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1654   in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1655       STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1656   in_msg->AddFingerprint();
1657   WriteStunMessage(in_msg.get(), buf.get());
1658   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1659                                    out_msg.accept(), &username));
1660   EXPECT_TRUE(out_msg.get() != NULL);
1661   EXPECT_EQ("", username);
1662   ASSERT_TRUE(out_msg->GetErrorCode() != NULL);
1663   EXPECT_EQ(STUN_ERROR_SERVER_ERROR, out_msg->GetErrorCode()->code());
1664   EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR),
1665       out_msg->GetErrorCode()->reason());
1666 }
1667
1668 // Tests handling of GICE binding requests with missing or incorrect usernames.
1669 TEST_F(PortTest, TestHandleStunMessageAsGiceBadUsername) {
1670   talk_base::scoped_ptr<TestPort> port(
1671       CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1672   port->SetIceProtocolType(ICEPROTO_GOOGLE);
1673
1674   talk_base::scoped_ptr<IceMessage> in_msg, out_msg;
1675   talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1676   talk_base::SocketAddress addr(kLocalAddr1);
1677   std::string username;
1678
1679   // BINDING-REQUEST with no username.
1680   in_msg.reset(CreateStunMessage(STUN_BINDING_REQUEST));
1681   WriteStunMessage(in_msg.get(), buf.get());
1682   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1683                                    out_msg.accept(), &username));
1684   EXPECT_TRUE(out_msg.get() == NULL);
1685   EXPECT_EQ("", username);
1686   EXPECT_EQ(STUN_ERROR_BAD_REQUEST_AS_GICE, port->last_stun_error_code());
1687
1688   // BINDING-REQUEST with empty username.
1689   in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, ""));
1690   WriteStunMessage(in_msg.get(), buf.get());
1691   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1692                                    out_msg.accept(), &username));
1693   EXPECT_TRUE(out_msg.get() == NULL);
1694   EXPECT_EQ("", username);
1695   EXPECT_EQ(STUN_ERROR_UNAUTHORIZED_AS_GICE, port->last_stun_error_code());
1696
1697   // BINDING-REQUEST with too-short username.
1698   in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "lfra"));
1699   WriteStunMessage(in_msg.get(), buf.get());
1700   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1701                                    out_msg.accept(), &username));
1702   EXPECT_TRUE(out_msg.get() == NULL);
1703   EXPECT_EQ("", username);
1704   EXPECT_EQ(STUN_ERROR_UNAUTHORIZED_AS_GICE, port->last_stun_error_code());
1705
1706   // BINDING-REQUEST with reversed username.
1707   in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1708                                              "lfragrfrag"));
1709   WriteStunMessage(in_msg.get(), buf.get());
1710   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1711                                    out_msg.accept(), &username));
1712   EXPECT_TRUE(out_msg.get() == NULL);
1713   EXPECT_EQ("", username);
1714   EXPECT_EQ(STUN_ERROR_UNAUTHORIZED_AS_GICE, port->last_stun_error_code());
1715
1716   // BINDING-REQUEST with garbage username.
1717   in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1718                                              "abcdefgh"));
1719   WriteStunMessage(in_msg.get(), buf.get());
1720   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1721                                    out_msg.accept(), &username));
1722   EXPECT_TRUE(out_msg.get() == NULL);
1723   EXPECT_EQ("", username);
1724   EXPECT_EQ(STUN_ERROR_UNAUTHORIZED_AS_GICE, port->last_stun_error_code());
1725 }
1726
1727 // Tests handling of ICE binding requests with missing or incorrect usernames.
1728 TEST_F(PortTest, TestHandleStunMessageAsIceBadUsername) {
1729   talk_base::scoped_ptr<TestPort> port(
1730       CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1731   port->SetIceProtocolType(ICEPROTO_RFC5245);
1732
1733   talk_base::scoped_ptr<IceMessage> in_msg, out_msg;
1734   talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1735   talk_base::SocketAddress addr(kLocalAddr1);
1736   std::string username;
1737
1738   // BINDING-REQUEST with no username.
1739   in_msg.reset(CreateStunMessage(STUN_BINDING_REQUEST));
1740   in_msg->AddMessageIntegrity("rpass");
1741   in_msg->AddFingerprint();
1742   WriteStunMessage(in_msg.get(), buf.get());
1743   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1744                                    out_msg.accept(), &username));
1745   EXPECT_TRUE(out_msg.get() == NULL);
1746   EXPECT_EQ("", username);
1747   EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1748
1749   // BINDING-REQUEST with empty username.
1750   in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, ""));
1751   in_msg->AddMessageIntegrity("rpass");
1752   in_msg->AddFingerprint();
1753   WriteStunMessage(in_msg.get(), buf.get());
1754   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1755                                    out_msg.accept(), &username));
1756   EXPECT_TRUE(out_msg.get() == NULL);
1757   EXPECT_EQ("", username);
1758   EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1759
1760   // BINDING-REQUEST with too-short username.
1761   in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "rfra"));
1762   in_msg->AddMessageIntegrity("rpass");
1763   in_msg->AddFingerprint();
1764   WriteStunMessage(in_msg.get(), buf.get());
1765   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1766                                    out_msg.accept(), &username));
1767   EXPECT_TRUE(out_msg.get() == NULL);
1768   EXPECT_EQ("", username);
1769   EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1770
1771   // BINDING-REQUEST with reversed username.
1772   in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1773                                             "lfrag:rfrag"));
1774   in_msg->AddMessageIntegrity("rpass");
1775   in_msg->AddFingerprint();
1776   WriteStunMessage(in_msg.get(), buf.get());
1777   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1778                                    out_msg.accept(), &username));
1779   EXPECT_TRUE(out_msg.get() == NULL);
1780   EXPECT_EQ("", username);
1781   EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1782
1783   // BINDING-REQUEST with garbage username.
1784   in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1785                                              "abcd:efgh"));
1786   in_msg->AddMessageIntegrity("rpass");
1787   in_msg->AddFingerprint();
1788   WriteStunMessage(in_msg.get(), buf.get());
1789   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1790                                    out_msg.accept(), &username));
1791   EXPECT_TRUE(out_msg.get() == NULL);
1792   EXPECT_EQ("", username);
1793   EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1794 }
1795
1796 // Test handling STUN messages (as ICE) with missing or malformed M-I.
1797 TEST_F(PortTest, TestHandleStunMessageAsIceBadMessageIntegrity) {
1798   // Our port will act as the "remote" port.
1799   talk_base::scoped_ptr<TestPort> port(
1800       CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1801   port->SetIceProtocolType(ICEPROTO_RFC5245);
1802
1803   talk_base::scoped_ptr<IceMessage> in_msg, out_msg;
1804   talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1805   talk_base::SocketAddress addr(kLocalAddr1);
1806   std::string username;
1807
1808   // BINDING-REQUEST from local to remote with valid ICE username and
1809   // FINGERPRINT, but no MESSAGE-INTEGRITY.
1810   in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1811                                              "rfrag:lfrag"));
1812   in_msg->AddFingerprint();
1813   WriteStunMessage(in_msg.get(), buf.get());
1814   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1815                                    out_msg.accept(), &username));
1816   EXPECT_TRUE(out_msg.get() == NULL);
1817   EXPECT_EQ("", username);
1818   EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1819
1820   // BINDING-REQUEST from local to remote with valid ICE username and
1821   // FINGERPRINT, but invalid MESSAGE-INTEGRITY.
1822   in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1823                                              "rfrag:lfrag"));
1824   in_msg->AddMessageIntegrity("invalid");
1825   in_msg->AddFingerprint();
1826   WriteStunMessage(in_msg.get(), buf.get());
1827   EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1828                                    out_msg.accept(), &username));
1829   EXPECT_TRUE(out_msg.get() == NULL);
1830   EXPECT_EQ("", username);
1831   EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1832
1833   // TODO: BINDING-RESPONSES and BINDING-ERROR-RESPONSES are checked
1834   // by the Connection, not the Port, since they require the remote username.
1835   // Change this test to pass in data via Connection::OnReadPacket instead.
1836 }
1837
1838 // Test handling STUN messages (as ICE) with missing or malformed FINGERPRINT.
1839 TEST_F(PortTest, TestHandleStunMessageAsIceBadFingerprint) {
1840   // Our port will act as the "remote" port.
1841   talk_base::scoped_ptr<TestPort> port(
1842       CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1843   port->SetIceProtocolType(ICEPROTO_RFC5245);
1844
1845   talk_base::scoped_ptr<IceMessage> in_msg, out_msg;
1846   talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1847   talk_base::SocketAddress addr(kLocalAddr1);
1848   std::string username;
1849
1850   // BINDING-REQUEST from local to remote with valid ICE username and
1851   // MESSAGE-INTEGRITY, but no FINGERPRINT; GetStunMessage should fail.
1852   in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1853                                              "rfrag:lfrag"));
1854   in_msg->AddMessageIntegrity("rpass");
1855   WriteStunMessage(in_msg.get(), buf.get());
1856   EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1857                                     out_msg.accept(), &username));
1858   EXPECT_EQ(0, port->last_stun_error_code());
1859
1860   // Now, add a fingerprint, but munge the message so it's not valid.
1861   in_msg->AddFingerprint();
1862   in_msg->SetTransactionID("TESTTESTBADD");
1863   WriteStunMessage(in_msg.get(), buf.get());
1864   EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1865                                     out_msg.accept(), &username));
1866   EXPECT_EQ(0, port->last_stun_error_code());
1867
1868   // Valid BINDING-RESPONSE, except no FINGERPRINT.
1869   in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1870   in_msg->AddAttribute(
1871       new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1872   in_msg->AddMessageIntegrity("rpass");
1873   WriteStunMessage(in_msg.get(), buf.get());
1874   EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1875                                     out_msg.accept(), &username));
1876   EXPECT_EQ(0, port->last_stun_error_code());
1877
1878   // Now, add a fingerprint, but munge the message so it's not valid.
1879   in_msg->AddFingerprint();
1880   in_msg->SetTransactionID("TESTTESTBADD");
1881   WriteStunMessage(in_msg.get(), buf.get());
1882   EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1883                                     out_msg.accept(), &username));
1884   EXPECT_EQ(0, port->last_stun_error_code());
1885
1886   // Valid BINDING-ERROR-RESPONSE, except no FINGERPRINT.
1887   in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1888   in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1889       STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1890   in_msg->AddMessageIntegrity("rpass");
1891   WriteStunMessage(in_msg.get(), buf.get());
1892   EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1893                                     out_msg.accept(), &username));
1894   EXPECT_EQ(0, port->last_stun_error_code());
1895
1896   // Now, add a fingerprint, but munge the message so it's not valid.
1897   in_msg->AddFingerprint();
1898   in_msg->SetTransactionID("TESTTESTBADD");
1899   WriteStunMessage(in_msg.get(), buf.get());
1900   EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1901                                     out_msg.accept(), &username));
1902   EXPECT_EQ(0, port->last_stun_error_code());
1903 }
1904
1905 // Test handling of STUN binding indication messages (as ICE). STUN binding
1906 // indications are allowed only to the connection which is in read mode.
1907 TEST_F(PortTest, TestHandleStunBindingIndication) {
1908   talk_base::scoped_ptr<TestPort> lport(
1909       CreateTestPort(kLocalAddr2, "lfrag", "lpass"));
1910   lport->SetIceProtocolType(ICEPROTO_RFC5245);
1911   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1912   lport->SetIceTiebreaker(kTiebreaker1);
1913
1914   // Verifying encoding and decoding STUN indication message.
1915   talk_base::scoped_ptr<IceMessage> in_msg, out_msg;
1916   talk_base::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1917   talk_base::SocketAddress addr(kLocalAddr1);
1918   std::string username;
1919
1920   in_msg.reset(CreateStunMessage(STUN_BINDING_INDICATION));
1921   in_msg->AddFingerprint();
1922   WriteStunMessage(in_msg.get(), buf.get());
1923   EXPECT_TRUE(lport->GetStunMessage(buf->Data(), buf->Length(), addr,
1924                                     out_msg.accept(), &username));
1925   EXPECT_TRUE(out_msg.get() != NULL);
1926   EXPECT_EQ(out_msg->type(), STUN_BINDING_INDICATION);
1927   EXPECT_EQ("", username);
1928
1929   // Verify connection can handle STUN indication and updates
1930   // last_ping_received.
1931   talk_base::scoped_ptr<TestPort> rport(
1932       CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1933   rport->SetIceProtocolType(ICEPROTO_RFC5245);
1934   rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1935   rport->SetIceTiebreaker(kTiebreaker2);
1936
1937   lport->PrepareAddress();
1938   rport->PrepareAddress();
1939   ASSERT_FALSE(lport->Candidates().empty());
1940   ASSERT_FALSE(rport->Candidates().empty());
1941
1942   Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
1943                                               Port::ORIGIN_MESSAGE);
1944   Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
1945                                               Port::ORIGIN_MESSAGE);
1946   rconn->Ping(0);
1947
1948   ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1949   IceMessage* msg = rport->last_stun_msg();
1950   EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1951   // Send rport binding request to lport.
1952   lconn->OnReadPacket(rport->last_stun_buf()->Data(),
1953                       rport->last_stun_buf()->Length(),
1954                       talk_base::PacketTime());
1955   ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1956   EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
1957   uint32 last_ping_received1 = lconn->last_ping_received();
1958
1959   // Adding a delay of 100ms.
1960   talk_base::Thread::Current()->ProcessMessages(100);
1961   // Pinging lconn using stun indication message.
1962   lconn->OnReadPacket(buf->Data(), buf->Length(), talk_base::PacketTime());
1963   uint32 last_ping_received2 = lconn->last_ping_received();
1964   EXPECT_GT(last_ping_received2, last_ping_received1);
1965 }
1966
1967 TEST_F(PortTest, TestComputeCandidatePriority) {
1968   talk_base::scoped_ptr<TestPort> port(
1969       CreateTestPort(kLocalAddr1, "name", "pass"));
1970   port->set_type_preference(90);
1971   port->set_component(177);
1972   port->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
1973   port->AddCandidateAddress(SocketAddress("2001:db8::1234", 1234));
1974   port->AddCandidateAddress(SocketAddress("fc12:3456::1234", 1234));
1975   port->AddCandidateAddress(SocketAddress("::ffff:192.168.1.4", 1234));
1976   port->AddCandidateAddress(SocketAddress("::192.168.1.4", 1234));
1977   port->AddCandidateAddress(SocketAddress("2002::1234:5678", 1234));
1978   port->AddCandidateAddress(SocketAddress("2001::1234:5678", 1234));
1979   port->AddCandidateAddress(SocketAddress("fecf::1234:5678", 1234));
1980   port->AddCandidateAddress(SocketAddress("3ffe::1234:5678", 1234));
1981   // These should all be:
1982   // (90 << 24) | ([rfc3484 pref value] << 8) | (256 - 177)
1983   uint32 expected_priority_v4 = 1509957199U;
1984   uint32 expected_priority_v6 = 1509959759U;
1985   uint32 expected_priority_ula = 1509962319U;
1986   uint32 expected_priority_v4mapped = expected_priority_v4;
1987   uint32 expected_priority_v4compat = 1509949775U;
1988   uint32 expected_priority_6to4 = 1509954639U;
1989   uint32 expected_priority_teredo = 1509952079U;
1990   uint32 expected_priority_sitelocal = 1509949775U;
1991   uint32 expected_priority_6bone = 1509949775U;
1992   ASSERT_EQ(expected_priority_v4, port->Candidates()[0].priority());
1993   ASSERT_EQ(expected_priority_v6, port->Candidates()[1].priority());
1994   ASSERT_EQ(expected_priority_ula, port->Candidates()[2].priority());
1995   ASSERT_EQ(expected_priority_v4mapped, port->Candidates()[3].priority());
1996   ASSERT_EQ(expected_priority_v4compat, port->Candidates()[4].priority());
1997   ASSERT_EQ(expected_priority_6to4, port->Candidates()[5].priority());
1998   ASSERT_EQ(expected_priority_teredo, port->Candidates()[6].priority());
1999   ASSERT_EQ(expected_priority_sitelocal, port->Candidates()[7].priority());
2000   ASSERT_EQ(expected_priority_6bone, port->Candidates()[8].priority());
2001 }
2002
2003 TEST_F(PortTest, TestPortProxyProperties) {
2004   talk_base::scoped_ptr<TestPort> port(
2005       CreateTestPort(kLocalAddr1, "name", "pass"));
2006   port->SetIceRole(cricket::ICEROLE_CONTROLLING);
2007   port->SetIceTiebreaker(kTiebreaker1);
2008
2009   // Create a proxy port.
2010   talk_base::scoped_ptr<PortProxy> proxy(new PortProxy());
2011   proxy->set_impl(port.get());
2012   EXPECT_EQ(port->Type(), proxy->Type());
2013   EXPECT_EQ(port->Network(), proxy->Network());
2014   EXPECT_EQ(port->GetIceRole(), proxy->GetIceRole());
2015   EXPECT_EQ(port->IceTiebreaker(), proxy->IceTiebreaker());
2016 }
2017
2018 // In the case of shared socket, one port may be shared by local and stun.
2019 // Test that candidates with different types will have different foundation.
2020 TEST_F(PortTest, TestFoundation) {
2021   talk_base::scoped_ptr<TestPort> testport(
2022       CreateTestPort(kLocalAddr1, "name", "pass"));
2023   testport->AddCandidateAddress(kLocalAddr1, kLocalAddr1,
2024                                 LOCAL_PORT_TYPE,
2025                                 cricket::ICE_TYPE_PREFERENCE_HOST, false);
2026   testport->AddCandidateAddress(kLocalAddr2, kLocalAddr1,
2027                                 STUN_PORT_TYPE,
2028                                 cricket::ICE_TYPE_PREFERENCE_SRFLX, true);
2029   EXPECT_NE(testport->Candidates()[0].foundation(),
2030             testport->Candidates()[1].foundation());
2031 }
2032
2033 // This test verifies the foundation of different types of ICE candidates.
2034 TEST_F(PortTest, TestCandidateFoundation) {
2035   talk_base::scoped_ptr<talk_base::NATServer> nat_server(
2036       CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2037   talk_base::scoped_ptr<UDPPort> udpport1(CreateUdpPort(kLocalAddr1));
2038   udpport1->PrepareAddress();
2039   talk_base::scoped_ptr<UDPPort> udpport2(CreateUdpPort(kLocalAddr1));
2040   udpport2->PrepareAddress();
2041   EXPECT_EQ(udpport1->Candidates()[0].foundation(),
2042             udpport2->Candidates()[0].foundation());
2043   talk_base::scoped_ptr<TCPPort> tcpport1(CreateTcpPort(kLocalAddr1));
2044   tcpport1->PrepareAddress();
2045   talk_base::scoped_ptr<TCPPort> tcpport2(CreateTcpPort(kLocalAddr1));
2046   tcpport2->PrepareAddress();
2047   EXPECT_EQ(tcpport1->Candidates()[0].foundation(),
2048             tcpport2->Candidates()[0].foundation());
2049   talk_base::scoped_ptr<Port> stunport(
2050       CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2051   stunport->PrepareAddress();
2052   ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2053   EXPECT_NE(tcpport1->Candidates()[0].foundation(),
2054             stunport->Candidates()[0].foundation());
2055   EXPECT_NE(tcpport2->Candidates()[0].foundation(),
2056             stunport->Candidates()[0].foundation());
2057   EXPECT_NE(udpport1->Candidates()[0].foundation(),
2058             stunport->Candidates()[0].foundation());
2059   EXPECT_NE(udpport2->Candidates()[0].foundation(),
2060             stunport->Candidates()[0].foundation());
2061   // Verify GTURN candidate foundation.
2062   talk_base::scoped_ptr<RelayPort> relayport(
2063       CreateGturnPort(kLocalAddr1));
2064   relayport->AddServerAddress(
2065       cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2066   relayport->PrepareAddress();
2067   ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2068   EXPECT_NE(udpport1->Candidates()[0].foundation(),
2069             relayport->Candidates()[0].foundation());
2070   EXPECT_NE(udpport2->Candidates()[0].foundation(),
2071             relayport->Candidates()[0].foundation());
2072   // Verifying TURN candidate foundation.
2073   talk_base::scoped_ptr<Port> turnport(CreateTurnPort(
2074       kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2075   turnport->PrepareAddress();
2076   ASSERT_EQ_WAIT(1U, turnport->Candidates().size(), kTimeout);
2077   EXPECT_NE(udpport1->Candidates()[0].foundation(),
2078             turnport->Candidates()[0].foundation());
2079   EXPECT_NE(udpport2->Candidates()[0].foundation(),
2080             turnport->Candidates()[0].foundation());
2081   EXPECT_NE(stunport->Candidates()[0].foundation(),
2082             turnport->Candidates()[0].foundation());
2083 }
2084
2085 // This test verifies the related addresses of different types of
2086 // ICE candiates.
2087 TEST_F(PortTest, TestCandidateRelatedAddress) {
2088   talk_base::scoped_ptr<talk_base::NATServer> nat_server(
2089       CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2090   talk_base::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
2091   udpport->PrepareAddress();
2092   // For UDPPort, related address will be empty.
2093   EXPECT_TRUE(udpport->Candidates()[0].related_address().IsNil());
2094   // Testing related address for stun candidates.
2095   // For stun candidate related address must be equal to the base
2096   // socket address.
2097   talk_base::scoped_ptr<StunPort> stunport(
2098       CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2099   stunport->PrepareAddress();
2100   ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2101   // Check STUN candidate address.
2102   EXPECT_EQ(stunport->Candidates()[0].address().ipaddr(),
2103             kNatAddr1.ipaddr());
2104   // Check STUN candidate related address.
2105   EXPECT_EQ(stunport->Candidates()[0].related_address(),
2106             stunport->GetLocalAddress());
2107   // Verifying the related address for the GTURN candidates.
2108   // NOTE: In case of GTURN related address will be equal to the mapped
2109   // address, but address(mapped) will not be XOR.
2110   talk_base::scoped_ptr<RelayPort> relayport(
2111       CreateGturnPort(kLocalAddr1));
2112   relayport->AddServerAddress(
2113       cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2114   relayport->PrepareAddress();
2115   ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2116   // For Gturn related address is set to "0.0.0.0:0"
2117   EXPECT_EQ(talk_base::SocketAddress(),
2118             relayport->Candidates()[0].related_address());
2119   // Verifying the related address for TURN candidate.
2120   // For TURN related address must be equal to the mapped address.
2121   talk_base::scoped_ptr<Port> turnport(CreateTurnPort(
2122       kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2123   turnport->PrepareAddress();
2124   ASSERT_EQ_WAIT(1U, turnport->Candidates().size(), kTimeout);
2125   EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
2126             turnport->Candidates()[0].address().ipaddr());
2127   EXPECT_EQ(kNatAddr1.ipaddr(),
2128             turnport->Candidates()[0].related_address().ipaddr());
2129 }
2130
2131 // Test priority value overflow handling when preference is set to 3.
2132 TEST_F(PortTest, TestCandidatePreference) {
2133   cricket::Candidate cand1;
2134   cand1.set_preference(3);
2135   cricket::Candidate cand2;
2136   cand2.set_preference(1);
2137   EXPECT_TRUE(cand1.preference() > cand2.preference());
2138 }
2139
2140 // Test the Connection priority is calculated correctly.
2141 TEST_F(PortTest, TestConnectionPriority) {
2142   talk_base::scoped_ptr<TestPort> lport(
2143       CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
2144   lport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_HOST);
2145   talk_base::scoped_ptr<TestPort> rport(
2146       CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
2147   rport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_RELAY);
2148   lport->set_component(123);
2149   lport->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2150   rport->set_component(23);
2151   rport->AddCandidateAddress(SocketAddress("10.1.1.100", 1234));
2152
2153   EXPECT_EQ(0x7E001E85U, lport->Candidates()[0].priority());
2154   EXPECT_EQ(0x2001EE9U, rport->Candidates()[0].priority());
2155
2156   // RFC 5245
2157   // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
2158   lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2159   rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2160   Connection* lconn = lport->CreateConnection(
2161       rport->Candidates()[0], Port::ORIGIN_MESSAGE);
2162 #if defined(WIN32)
2163   EXPECT_EQ(0x2001EE9FC003D0BU, lconn->priority());
2164 #else
2165   EXPECT_EQ(0x2001EE9FC003D0BLLU, lconn->priority());
2166 #endif
2167
2168   lport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2169   rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2170   Connection* rconn = rport->CreateConnection(
2171       lport->Candidates()[0], Port::ORIGIN_MESSAGE);
2172 #if defined(WIN32)
2173   EXPECT_EQ(0x2001EE9FC003D0AU, rconn->priority());
2174 #else
2175   EXPECT_EQ(0x2001EE9FC003D0ALLU, rconn->priority());
2176 #endif
2177 }
2178
2179 TEST_F(PortTest, TestWritableState) {
2180   UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2181   UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2182
2183   // Set up channels.
2184   TestChannel ch1(port1, port2);
2185   TestChannel ch2(port2, port1);
2186
2187   // Acquire addresses.
2188   ch1.Start();
2189   ch2.Start();
2190   ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2191   ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
2192
2193   // Send a ping from src to dst.
2194   ch1.CreateConnection();
2195   ASSERT_TRUE(ch1.conn() != NULL);
2196   EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2197   EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout);  // for TCP connect
2198   ch1.Ping();
2199   WAIT(!ch2.remote_address().IsNil(), kTimeout);
2200
2201   // Data should be unsendable until the connection is accepted.
2202   char data[] = "abcd";
2203   int data_size = ARRAY_SIZE(data);
2204   EXPECT_EQ(SOCKET_ERROR,
2205             ch1.conn()->Send(data, data_size, talk_base::DSCP_NO_CHANGE));
2206
2207   // Accept the connection to return the binding response, transition to
2208   // writable, and allow data to be sent.
2209   ch2.AcceptConnection();
2210   EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2211                  kTimeout);
2212   EXPECT_EQ(data_size,
2213             ch1.conn()->Send(data, data_size, talk_base::DSCP_NO_CHANGE));
2214
2215   // Ask the connection to update state as if enough time has passed to lose
2216   // full writability and 5 pings went unresponded to. We'll accomplish the
2217   // latter by sending pings but not pumping messages.
2218   for (uint32 i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
2219     ch1.Ping(i);
2220   }
2221   uint32 unreliable_timeout_delay = CONNECTION_WRITE_CONNECT_TIMEOUT + 500u;
2222   ch1.conn()->UpdateState(unreliable_timeout_delay);
2223   EXPECT_EQ(Connection::STATE_WRITE_UNRELIABLE, ch1.conn()->write_state());
2224
2225   // Data should be able to be sent in this state.
2226   EXPECT_EQ(data_size,
2227             ch1.conn()->Send(data, data_size, talk_base::DSCP_NO_CHANGE));
2228
2229   // And now allow the other side to process the pings and send binding
2230   // responses.
2231   EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2232                  kTimeout);
2233
2234   // Wait long enough for a full timeout (past however long we've already
2235   // waited).
2236   for (uint32 i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
2237     ch1.Ping(unreliable_timeout_delay + i);
2238   }
2239   ch1.conn()->UpdateState(unreliable_timeout_delay + CONNECTION_WRITE_TIMEOUT +
2240                           500u);
2241   EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2242
2243   // Now that the connection has completely timed out, data send should fail.
2244   EXPECT_EQ(SOCKET_ERROR,
2245             ch1.conn()->Send(data, data_size, talk_base::DSCP_NO_CHANGE));
2246
2247   ch1.Stop();
2248   ch2.Stop();
2249 }
2250
2251 TEST_F(PortTest, TestTimeoutForNeverWritable) {
2252   UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2253   UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2254
2255   // Set up channels.
2256   TestChannel ch1(port1, port2);
2257   TestChannel ch2(port2, port1);
2258
2259   // Acquire addresses.
2260   ch1.Start();
2261   ch2.Start();
2262
2263   ch1.CreateConnection();
2264   ASSERT_TRUE(ch1.conn() != NULL);
2265   EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2266
2267   // Attempt to go directly to write timeout.
2268   for (uint32 i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
2269     ch1.Ping(i);
2270   }
2271   ch1.conn()->UpdateState(CONNECTION_WRITE_TIMEOUT + 500u);
2272   EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2273 }
2274
2275 // This test verifies the connection setup between ICEMODE_FULL
2276 // and ICEMODE_LITE.
2277 // In this test |ch1| behaves like FULL mode client and we have created
2278 // port which responds to the ping message just like LITE client.
2279 TEST_F(PortTest, TestIceLiteConnectivity) {
2280   TestPort* ice_full_port = CreateTestPort(
2281       kLocalAddr1, "lfrag", "lpass", cricket::ICEPROTO_RFC5245,
2282       cricket::ICEROLE_CONTROLLING, kTiebreaker1);
2283
2284   talk_base::scoped_ptr<TestPort> ice_lite_port(CreateTestPort(
2285       kLocalAddr2, "rfrag", "rpass", cricket::ICEPROTO_RFC5245,
2286       cricket::ICEROLE_CONTROLLED, kTiebreaker2));
2287   // Setup TestChannel. This behaves like FULL mode client.
2288   TestChannel ch1(ice_full_port, ice_lite_port.get());
2289   ch1.SetIceMode(ICEMODE_FULL);
2290
2291   // Start gathering candidates.
2292   ch1.Start();
2293   ice_lite_port->PrepareAddress();
2294
2295   ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2296   ASSERT_FALSE(ice_lite_port->Candidates().empty());
2297
2298   ch1.CreateConnection();
2299   ASSERT_TRUE(ch1.conn() != NULL);
2300   EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2301
2302   // Send ping from full mode client.
2303   // This ping must not have USE_CANDIDATE_ATTR.
2304   ch1.Ping();
2305
2306   // Verify stun ping is without USE_CANDIDATE_ATTR. Getting message directly
2307   // from port.
2308   ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2309   IceMessage* msg = ice_full_port->last_stun_msg();
2310   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
2311
2312   // Respond with a BINDING-RESPONSE from litemode client.
2313   // NOTE: Ideally we should't create connection at this stage from lite
2314   // port, as it should be done only after receiving ping with USE_CANDIDATE.
2315   // But we need a connection to send a response message.
2316   ice_lite_port->CreateConnection(
2317       ice_full_port->Candidates()[0], cricket::Port::ORIGIN_MESSAGE);
2318   talk_base::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
2319   ice_lite_port->SendBindingResponse(
2320       request.get(), ice_full_port->Candidates()[0].address());
2321
2322   // Feeding the respone message from litemode to the full mode connection.
2323   ch1.conn()->OnReadPacket(ice_lite_port->last_stun_buf()->Data(),
2324                            ice_lite_port->last_stun_buf()->Length(),
2325                            talk_base::PacketTime());
2326   // Verifying full mode connection becomes writable from the response.
2327   EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2328                  kTimeout);
2329   EXPECT_TRUE_WAIT(ch1.nominated(), kTimeout);
2330
2331   // Clear existing stun messsages. Otherwise we will process old stun
2332   // message right after we send ping.
2333   ice_full_port->Reset();
2334   // Send ping. This must have USE_CANDIDATE_ATTR.
2335   ch1.Ping();
2336   ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2337   msg = ice_full_port->last_stun_msg();
2338   EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
2339   ch1.Stop();
2340 }
2341
2342 // This test case verifies that the CONTROLLING port does not time out.
2343 TEST_F(PortTest, TestControllingNoTimeout) {
2344   SetIceProtocolType(cricket::ICEPROTO_RFC5245);
2345   UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2346   ConnectToSignalDestroyed(port1);
2347   port1->set_timeout_delay(10);  // milliseconds
2348   port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2349   port1->SetIceTiebreaker(kTiebreaker1);
2350
2351   UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2352   port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2353   port2->SetIceTiebreaker(kTiebreaker2);
2354
2355   // Set up channels and ensure both ports will be deleted.
2356   TestChannel ch1(port1, port2);
2357   TestChannel ch2(port2, port1);
2358
2359   // Simulate a connection that succeeds, and then is destroyed.
2360   ConnectAndDisconnectChannels(&ch1, &ch2);
2361
2362   // After the connection is destroyed, the port should not be destroyed.
2363   talk_base::Thread::Current()->ProcessMessages(kTimeout);
2364   EXPECT_FALSE(destroyed());
2365 }
2366
2367 // This test case verifies that the CONTROLLED port does time out, but only
2368 // after connectivity is lost.
2369 TEST_F(PortTest, TestControlledTimeout) {
2370   SetIceProtocolType(cricket::ICEPROTO_RFC5245);
2371   UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2372   port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2373   port1->SetIceTiebreaker(kTiebreaker1);
2374
2375   UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2376   ConnectToSignalDestroyed(port2);
2377   port2->set_timeout_delay(10);  // milliseconds
2378   port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2379   port2->SetIceTiebreaker(kTiebreaker2);
2380
2381   // The connection must not be destroyed before a connection is attempted.
2382   EXPECT_FALSE(destroyed());
2383
2384   port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2385   port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2386
2387   // Set up channels and ensure both ports will be deleted.
2388   TestChannel ch1(port1, port2);
2389   TestChannel ch2(port2, port1);
2390
2391   // Simulate a connection that succeeds, and then is destroyed.
2392   ConnectAndDisconnectChannels(&ch1, &ch2);
2393
2394   // The controlled port should be destroyed after 10 milliseconds.
2395   EXPECT_TRUE_WAIT(destroyed(), kTimeout);
2396 }