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