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