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