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