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