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