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