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