blob: 2782ba9b80e8351c788121b6b5e6e3cefd734066 [file] [log] [blame]
[email protected]7054e78f2012-05-07 21:44:561// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]a2798d92011-03-02 22:56:182// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]3d2fd542014-08-12 03:07:085#include "net/udp/udp_socket.h"
6
[email protected]a2798d92011-03-02 22:56:187#include "net/udp/udp_client_socket.h"
8#include "net/udp/udp_server_socket.h"
9
[email protected]5370c012011-06-29 03:47:0410#include "base/bind.h"
skyostil4891b25b2015-06-11 11:43:4511#include "base/location.h"
tfarinac40df1c2015-11-30 22:31:4712#include "base/macros.h"
hclam5a5ee682015-02-05 04:18:2213#include "base/memory/weak_ptr.h"
hclam5a5ee682015-02-05 04:18:2214#include "base/run_loop.h"
skyostil4891b25b2015-06-11 11:43:4515#include "base/single_thread_task_runner.h"
[email protected]7286e3fc2011-07-19 22:13:2416#include "base/stl_util.h"
skyostil4891b25b2015-06-11 11:43:4517#include "base/thread_task_runner_handle.h"
[email protected]a2798d92011-03-02 22:56:1818#include "net/base/io_buffer.h"
[email protected]43d4a0262011-03-09 19:26:0419#include "net/base/ip_endpoint.h"
[email protected]a2798d92011-03-02 22:56:1820#include "net/base/net_errors.h"
[email protected]a2798d92011-03-02 22:56:1821#include "net/base/test_completion_callback.h"
mmenke16a7cbdd2015-04-24 23:00:5622#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4623#include "net/log/test_net_log_entry.h"
24#include "net/log/test_net_log_util.h"
[email protected]8efa4ba42013-03-18 21:14:1425#include "net/test/net_test_suite.h"
[email protected]a2798d92011-03-02 22:56:1826#include "testing/gtest/include/gtest/gtest.h"
27#include "testing/platform_test.h"
28
blundellb8163592f2015-12-16 14:22:4229#if defined(OS_IOS)
30#include <TargetConditionals.h>
31#endif
32
[email protected]a2798d92011-03-02 22:56:1833namespace net {
34
35namespace {
36
37class UDPSocketTest : public PlatformTest {
38 public:
hclam5a5ee682015-02-05 04:18:2239 UDPSocketTest() : buffer_(new IOBufferWithSize(kMaxRead)) {}
[email protected]a2798d92011-03-02 22:56:1840
41 // Blocks until data is read from the socket.
42 std::string RecvFromSocket(UDPServerSocket* socket) {
[email protected]83039bb2011-12-09 18:43:5543 TestCompletionCallback callback;
[email protected]a2798d92011-03-02 22:56:1844
[email protected]90499482013-06-01 00:39:5045 int rv = socket->RecvFrom(
46 buffer_.get(), kMaxRead, &recv_from_address_, callback.callback());
[email protected]a2798d92011-03-02 22:56:1847 if (rv == ERR_IO_PENDING)
48 rv = callback.WaitForResult();
49 if (rv < 0)
[email protected]007b3f82013-04-09 08:46:4550 return std::string(); // error!
[email protected]a2798d92011-03-02 22:56:1851 return std::string(buffer_->data(), rv);
52 }
53
54 // Loop until |msg| has been written to the socket or until an
55 // error occurs.
[email protected]43d4a0262011-03-09 19:26:0456 // If |address| is specified, then it is used for the destination
57 // to send to. Otherwise, will send to the last socket this server
58 // received from.
ki.stfu144dce12015-09-22 01:07:5759 int SendToSocket(UDPServerSocket* socket, const std::string& msg) {
[email protected]43d4a0262011-03-09 19:26:0460 return SendToSocket(socket, msg, recv_from_address_);
61 }
62
[email protected]a2798d92011-03-02 22:56:1863 int SendToSocket(UDPServerSocket* socket,
64 std::string msg,
[email protected]43d4a0262011-03-09 19:26:0465 const IPEndPoint& address) {
[email protected]83039bb2011-12-09 18:43:5566 TestCompletionCallback callback;
[email protected]a2798d92011-03-02 22:56:1867
[email protected]a2798d92011-03-02 22:56:1868 int length = msg.length();
69 scoped_refptr<StringIOBuffer> io_buffer(new StringIOBuffer(msg));
70 scoped_refptr<DrainableIOBuffer> buffer(
[email protected]90499482013-06-01 00:39:5071 new DrainableIOBuffer(io_buffer.get(), length));
[email protected]a2798d92011-03-02 22:56:1872
73 int bytes_sent = 0;
74 while (buffer->BytesRemaining()) {
[email protected]90499482013-06-01 00:39:5075 int rv = socket->SendTo(
76 buffer.get(), buffer->BytesRemaining(), address, callback.callback());
[email protected]a2798d92011-03-02 22:56:1877 if (rv == ERR_IO_PENDING)
78 rv = callback.WaitForResult();
79 if (rv <= 0)
80 return bytes_sent > 0 ? bytes_sent : rv;
81 bytes_sent += rv;
82 buffer->DidConsume(rv);
83 }
84 return bytes_sent;
85 }
86
87 std::string ReadSocket(UDPClientSocket* socket) {
[email protected]83039bb2011-12-09 18:43:5588 TestCompletionCallback callback;
[email protected]a2798d92011-03-02 22:56:1889
[email protected]90499482013-06-01 00:39:5090 int rv = socket->Read(buffer_.get(), kMaxRead, callback.callback());
[email protected]a2798d92011-03-02 22:56:1891 if (rv == ERR_IO_PENDING)
92 rv = callback.WaitForResult();
93 if (rv < 0)
[email protected]007b3f82013-04-09 08:46:4594 return std::string(); // error!
[email protected]a2798d92011-03-02 22:56:1895 return std::string(buffer_->data(), rv);
96 }
97
98 // Loop until |msg| has been written to the socket or until an
99 // error occurs.
ki.stfu144dce12015-09-22 01:07:57100 int WriteSocket(UDPClientSocket* socket, const std::string& msg) {
[email protected]83039bb2011-12-09 18:43:55101 TestCompletionCallback callback;
[email protected]a2798d92011-03-02 22:56:18102
103 int length = msg.length();
104 scoped_refptr<StringIOBuffer> io_buffer(new StringIOBuffer(msg));
105 scoped_refptr<DrainableIOBuffer> buffer(
[email protected]90499482013-06-01 00:39:50106 new DrainableIOBuffer(io_buffer.get(), length));
[email protected]a2798d92011-03-02 22:56:18107
108 int bytes_sent = 0;
109 while (buffer->BytesRemaining()) {
[email protected]90499482013-06-01 00:39:50110 int rv = socket->Write(
111 buffer.get(), buffer->BytesRemaining(), callback.callback());
[email protected]a2798d92011-03-02 22:56:18112 if (rv == ERR_IO_PENDING)
113 rv = callback.WaitForResult();
114 if (rv <= 0)
115 return bytes_sent > 0 ? bytes_sent : rv;
116 bytes_sent += rv;
117 buffer->DidConsume(rv);
118 }
119 return bytes_sent;
120 }
121
ki.stfu144dce12015-09-22 01:07:57122 void WriteSocketIgnoreResult(UDPClientSocket* socket,
123 const std::string& msg) {
hclam5a5ee682015-02-05 04:18:22124 WriteSocket(socket, msg);
125 }
126
127 // Creates an address from ip address and port and writes it to |*address|.
ki.stfu144dce12015-09-22 01:07:57128 void CreateUDPAddress(const std::string& ip_str,
tfarinac40df1c2015-11-30 22:31:47129 uint16_t port,
ki.stfu144dce12015-09-22 01:07:57130 IPEndPoint* address) {
hclam5a5ee682015-02-05 04:18:22131 IPAddressNumber ip_number;
132 bool rv = ParseIPLiteralToNumber(ip_str, &ip_number);
133 if (!rv)
134 return;
135 *address = IPEndPoint(ip_number, port);
136 }
137
138 // Run unit test for a connection test.
139 // |use_nonblocking_io| is used to switch between overlapped and non-blocking
140 // IO on Windows. It has no effect in other ports.
141 void ConnectTest(bool use_nonblocking_io);
142
[email protected]7b6afd02011-03-12 00:03:12143 protected:
[email protected]a2798d92011-03-02 22:56:18144 static const int kMaxRead = 1024;
145 scoped_refptr<IOBufferWithSize> buffer_;
[email protected]9d1e2ba02011-03-09 19:42:33146 IPEndPoint recv_from_address_;
[email protected]a2798d92011-03-02 22:56:18147};
148
hclam5a5ee682015-02-05 04:18:22149void ReadCompleteCallback(int* result_out, base::Closure callback, int result) {
150 *result_out = result;
151 callback.Run();
[email protected]a2798d92011-03-02 22:56:18152}
153
hclam5a5ee682015-02-05 04:18:22154void UDPSocketTest::ConnectTest(bool use_nonblocking_io) {
tfarinac40df1c2015-11-30 22:31:47155 const uint16_t kPort = 9999;
[email protected]a2798d92011-03-02 22:56:18156 std::string simple_message("hello world!");
157
158 // Setup the server to listen.
[email protected]43d4a0262011-03-09 19:26:04159 IPEndPoint bind_address;
[email protected]2cb83102012-09-18 19:13:01160 CreateUDPAddress("127.0.0.1", kPort, &bind_address);
vishal.b62985ca92015-04-17 08:45:51161 TestNetLog server_log;
[email protected]8866f622011-10-18 20:08:10162 scoped_ptr<UDPServerSocket> server(
163 new UDPServerSocket(&server_log, NetLog::Source()));
hclam5a5ee682015-02-05 04:18:22164#if defined(OS_WIN)
165 if (use_nonblocking_io)
166 server->UseNonBlockingIO();
167#endif
[email protected]2cb83102012-09-18 19:13:01168 server->AllowAddressReuse();
[email protected]8866f622011-10-18 20:08:10169 int rv = server->Listen(bind_address);
[email protected]d72a14f2012-09-11 16:27:11170 ASSERT_EQ(OK, rv);
[email protected]a2798d92011-03-02 22:56:18171
172 // Setup the client.
[email protected]43d4a0262011-03-09 19:26:04173 IPEndPoint server_address;
[email protected]a2798d92011-03-02 22:56:18174 CreateUDPAddress("127.0.0.1", kPort, &server_address);
vishal.b62985ca92015-04-17 08:45:51175 TestNetLog client_log;
[email protected]8866f622011-10-18 20:08:10176 scoped_ptr<UDPClientSocket> client(
hclam5a5ee682015-02-05 04:18:22177 new UDPClientSocket(DatagramSocket::DEFAULT_BIND, RandIntCallback(),
178 &client_log, NetLog::Source()));
179#if defined(OS_WIN)
180 if (use_nonblocking_io)
181 client->UseNonBlockingIO();
182#endif
183
[email protected]8866f622011-10-18 20:08:10184 rv = client->Connect(server_address);
[email protected]a2798d92011-03-02 22:56:18185 EXPECT_EQ(OK, rv);
186
187 // Client sends to the server.
[email protected]8866f622011-10-18 20:08:10188 rv = WriteSocket(client.get(), simple_message);
[email protected]a2798d92011-03-02 22:56:18189 EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
190
191 // Server waits for message.
[email protected]8866f622011-10-18 20:08:10192 std::string str = RecvFromSocket(server.get());
[email protected]a2798d92011-03-02 22:56:18193 DCHECK(simple_message == str);
194
195 // Server echoes reply.
[email protected]8866f622011-10-18 20:08:10196 rv = SendToSocket(server.get(), simple_message);
[email protected]a2798d92011-03-02 22:56:18197 EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
198
199 // Client waits for response.
[email protected]8866f622011-10-18 20:08:10200 str = ReadSocket(client.get());
[email protected]a2798d92011-03-02 22:56:18201 DCHECK(simple_message == str);
[email protected]8866f622011-10-18 20:08:10202
hclam5a5ee682015-02-05 04:18:22203 // Test asynchronous read. Server waits for message.
204 base::RunLoop run_loop;
205 int read_result = 0;
206 rv = server->RecvFrom(
207 buffer_.get(), kMaxRead, &recv_from_address_,
208 base::Bind(&ReadCompleteCallback, &read_result, run_loop.QuitClosure()));
209 EXPECT_EQ(ERR_IO_PENDING, rv);
210
211 // Client sends to the server.
skyostil4891b25b2015-06-11 11:43:45212 base::ThreadTaskRunnerHandle::Get()->PostTask(
hclam5a5ee682015-02-05 04:18:22213 FROM_HERE,
214 base::Bind(&UDPSocketTest::WriteSocketIgnoreResult,
215 base::Unretained(this), client.get(), simple_message));
216 run_loop.Run();
217 EXPECT_EQ(simple_message.length(), static_cast<size_t>(read_result));
218 EXPECT_EQ(simple_message, std::string(buffer_->data(), read_result));
219
[email protected]8866f622011-10-18 20:08:10220 // Delete sockets so they log their final events.
221 server.reset();
222 client.reset();
223
224 // Check the server's log.
mmenke43758e62015-05-04 21:09:46225 TestNetLogEntry::List server_entries;
[email protected]8866f622011-10-18 20:08:10226 server_log.GetEntries(&server_entries);
hclam5a5ee682015-02-05 04:18:22227 EXPECT_EQ(5u, server_entries.size());
228 EXPECT_TRUE(
229 LogContainsBeginEvent(server_entries, 0, NetLog::TYPE_SOCKET_ALIVE));
[email protected]8866f622011-10-18 20:08:10230 EXPECT_TRUE(LogContainsEvent(
231 server_entries, 1, NetLog::TYPE_UDP_BYTES_RECEIVED, NetLog::PHASE_NONE));
hclam5a5ee682015-02-05 04:18:22232 EXPECT_TRUE(LogContainsEvent(server_entries, 2, NetLog::TYPE_UDP_BYTES_SENT,
233 NetLog::PHASE_NONE));
[email protected]8866f622011-10-18 20:08:10234 EXPECT_TRUE(LogContainsEvent(
hclam5a5ee682015-02-05 04:18:22235 server_entries, 3, NetLog::TYPE_UDP_BYTES_RECEIVED, NetLog::PHASE_NONE));
236 EXPECT_TRUE(
237 LogContainsEndEvent(server_entries, 4, NetLog::TYPE_SOCKET_ALIVE));
[email protected]8866f622011-10-18 20:08:10238
239 // Check the client's log.
mmenke43758e62015-05-04 21:09:46240 TestNetLogEntry::List client_entries;
[email protected]8866f622011-10-18 20:08:10241 client_log.GetEntries(&client_entries);
hclam5a5ee682015-02-05 04:18:22242 EXPECT_EQ(7u, client_entries.size());
243 EXPECT_TRUE(
244 LogContainsBeginEvent(client_entries, 0, NetLog::TYPE_SOCKET_ALIVE));
245 EXPECT_TRUE(
246 LogContainsBeginEvent(client_entries, 1, NetLog::TYPE_UDP_CONNECT));
247 EXPECT_TRUE(LogContainsEndEvent(client_entries, 2, NetLog::TYPE_UDP_CONNECT));
248 EXPECT_TRUE(LogContainsEvent(client_entries, 3, NetLog::TYPE_UDP_BYTES_SENT,
249 NetLog::PHASE_NONE));
[email protected]8866f622011-10-18 20:08:10250 EXPECT_TRUE(LogContainsEvent(
251 client_entries, 4, NetLog::TYPE_UDP_BYTES_RECEIVED, NetLog::PHASE_NONE));
hclam5a5ee682015-02-05 04:18:22252 EXPECT_TRUE(LogContainsEvent(client_entries, 5, NetLog::TYPE_UDP_BYTES_SENT,
253 NetLog::PHASE_NONE));
254 EXPECT_TRUE(
255 LogContainsEndEvent(client_entries, 6, NetLog::TYPE_SOCKET_ALIVE));
[email protected]a2798d92011-03-02 22:56:18256}
257
hclam5a5ee682015-02-05 04:18:22258TEST_F(UDPSocketTest, Connect) {
259 // The variable |use_nonblocking_io| has no effect in non-Windows ports.
260 ConnectTest(false);
261}
262
263#if defined(OS_WIN)
264TEST_F(UDPSocketTest, ConnectNonBlocking) {
265 ConnectTest(true);
266}
267#endif
268
[email protected]86c8e5122012-11-15 20:34:43269#if defined(OS_MACOSX)
[email protected]2cb83102012-09-18 19:13:01270// UDPSocketPrivate_Broadcast is disabled for OSX because it requires
271// root permissions on OSX 10.7+.
[email protected]86c8e5122012-11-15 20:34:43272TEST_F(UDPSocketTest, DISABLED_Broadcast) {
273#elif defined(OS_ANDROID)
mef39df8ac2015-06-16 17:19:41274// Disabled for Android because devices attached to testbots don't have default
275// network, so broadcasting to 255.255.255.255 returns error -109 (Address not
276// reachable). crbug.com/139144.
[email protected]2cb83102012-09-18 19:13:01277TEST_F(UDPSocketTest, DISABLED_Broadcast) {
278#else
[email protected]a1781d7b2012-07-16 11:52:34279TEST_F(UDPSocketTest, Broadcast) {
[email protected]2cb83102012-09-18 19:13:01280#endif
tfarinac40df1c2015-11-30 22:31:47281 const uint16_t kPort = 9999;
[email protected]a1781d7b2012-07-16 11:52:34282 std::string first_message("first message"), second_message("second message");
283
284 IPEndPoint broadcast_address;
285 CreateUDPAddress("255.255.255.255", kPort, &broadcast_address);
286 IPEndPoint listen_address;
287 CreateUDPAddress("0.0.0.0", kPort, &listen_address);
288
vishal.b62985ca92015-04-17 08:45:51289 TestNetLog server1_log, server2_log;
[email protected]a1781d7b2012-07-16 11:52:34290 scoped_ptr<UDPServerSocket> server1(
291 new UDPServerSocket(&server1_log, NetLog::Source()));
292 scoped_ptr<UDPServerSocket> server2(
293 new UDPServerSocket(&server2_log, NetLog::Source()));
294 server1->AllowAddressReuse();
295 server1->AllowBroadcast();
296 server2->AllowAddressReuse();
297 server2->AllowBroadcast();
298
299 int rv = server1->Listen(listen_address);
300 EXPECT_EQ(OK, rv);
301 rv = server2->Listen(listen_address);
302 EXPECT_EQ(OK, rv);
303
304 rv = SendToSocket(server1.get(), first_message, broadcast_address);
[email protected]86c8e5122012-11-15 20:34:43305 ASSERT_EQ(static_cast<int>(first_message.size()), rv);
[email protected]a1781d7b2012-07-16 11:52:34306 std::string str = RecvFromSocket(server1.get());
307 ASSERT_EQ(first_message, str);
308 str = RecvFromSocket(server2.get());
309 ASSERT_EQ(first_message, str);
310
311 rv = SendToSocket(server2.get(), second_message, broadcast_address);
[email protected]86c8e5122012-11-15 20:34:43312 ASSERT_EQ(static_cast<int>(second_message.size()), rv);
[email protected]a1781d7b2012-07-16 11:52:34313 str = RecvFromSocket(server1.get());
314 ASSERT_EQ(second_message, str);
315 str = RecvFromSocket(server2.get());
316 ASSERT_EQ(second_message, str);
317}
318
[email protected]5370c012011-06-29 03:47:04319// In this test, we verify that random binding logic works, which attempts
320// to bind to a random port and returns if succeeds, otherwise retries for
321// |kBindRetries| number of times.
322
323// To generate the scenario, we first create |kBindRetries| number of
324// UDPClientSockets with default binding policy and connect to the same
325// peer and save the used port numbers. Then we get rid of the last
326// socket, making sure that the local port it was bound to is available.
327// Finally, we create a socket with random binding policy, passing it a
328// test PRNG that would serve used port numbers in the array, one after
329// another. At the end, we make sure that the test socket was bound to the
330// port that became available after deleting the last socket with default
331// binding policy.
332
333// We do not test the randomness of bound ports, but that we are using
334// passed in PRNG correctly, thus, it's the duty of PRNG to produce strong
335// random numbers.
336static const int kBindRetries = 10;
337
338class TestPrng {
339 public:
340 explicit TestPrng(const std::deque<int>& numbers) : numbers_(numbers) {}
341 int GetNext(int /* min */, int /* max */) {
342 DCHECK(!numbers_.empty());
343 int rv = numbers_.front();
344 numbers_.pop_front();
345 return rv;
346 }
347 private:
348 std::deque<int> numbers_;
349
350 DISALLOW_COPY_AND_ASSIGN(TestPrng);
351};
352
353TEST_F(UDPSocketTest, ConnectRandomBind) {
354 std::vector<UDPClientSocket*> sockets;
355 IPEndPoint peer_address;
mef39df8ac2015-06-16 17:19:41356 CreateUDPAddress("127.0.0.1", 53, &peer_address);
[email protected]5370c012011-06-29 03:47:04357
358 // Create and connect sockets and save port numbers.
359 std::deque<int> used_ports;
360 for (int i = 0; i < kBindRetries; ++i) {
361 UDPClientSocket* socket =
362 new UDPClientSocket(DatagramSocket::DEFAULT_BIND,
363 RandIntCallback(),
364 NULL,
365 NetLog::Source());
366 sockets.push_back(socket);
367 EXPECT_EQ(OK, socket->Connect(peer_address));
368
369 IPEndPoint client_address;
370 EXPECT_EQ(OK, socket->GetLocalAddress(&client_address));
371 used_ports.push_back(client_address.port());
372 }
373
374 // Free the last socket, its local port is still in |used_ports|.
375 delete sockets.back();
376 sockets.pop_back();
377
378 TestPrng test_prng(used_ports);
379 RandIntCallback rand_int_cb =
380 base::Bind(&TestPrng::GetNext, base::Unretained(&test_prng));
381
382 // Create a socket with random binding policy and connect.
383 scoped_ptr<UDPClientSocket> test_socket(
384 new UDPClientSocket(DatagramSocket::RANDOM_BIND,
385 rand_int_cb,
386 NULL,
387 NetLog::Source()));
388 EXPECT_EQ(OK, test_socket->Connect(peer_address));
389
390 // Make sure that the last port number in the |used_ports| was used.
391 IPEndPoint client_address;
392 EXPECT_EQ(OK, test_socket->GetLocalAddress(&client_address));
393 EXPECT_EQ(used_ports.back(), client_address.port());
394
395 STLDeleteElements(&sockets);
396}
397
[email protected]391de682013-02-22 22:44:44398// Return a privileged port (under 1024) so binding will fail.
399int PrivilegedRand(int min, int max) {
400 // Chosen by fair dice roll. Guaranteed to be random.
401 return 4;
402}
403
blundellb8163592f2015-12-16 14:22:42404#if defined(OS_IOS) && !TARGET_IPHONE_SIMULATOR
405// TODO(droger): On iOS this test fails on device (but passes on simulator).
406// See http://crbug.com/227760.
407#define MAYBE_ConnectFail DISABLED_ConnectFail
408#else
409#define MAYBE_ConnectFail ConnectFail
410#endif
411TEST_F(UDPSocketTest, MAYBE_ConnectFail) {
[email protected]391de682013-02-22 22:44:44412 IPEndPoint peer_address;
413 CreateUDPAddress("0.0.0.0", 53, &peer_address);
414
415 scoped_ptr<UDPSocket> socket(
416 new UDPSocket(DatagramSocket::RANDOM_BIND,
417 base::Bind(&PrivilegedRand),
418 NULL,
419 NetLog::Source()));
hidehiko17fac552014-12-08 06:02:17420 int rv = socket->Open(peer_address.GetFamily());
421 EXPECT_EQ(OK, rv);
422 rv = socket->Connect(peer_address);
[email protected]391de682013-02-22 22:44:44423 // Connect should have failed since we couldn't bind to that port,
424 EXPECT_NE(OK, rv);
425 // Make sure that UDPSocket actually closed the socket.
426 EXPECT_FALSE(socket->is_connected());
427}
428
[email protected]a2798d92011-03-02 22:56:18429// In this test, we verify that connect() on a socket will have the effect
430// of filtering reads on this socket only to data read from the destination
431// we connected to.
432//
433// The purpose of this test is that some documentation indicates that connect
434// binds the client's sends to send to a particular server endpoint, but does
435// not bind the client's reads to only be from that endpoint, and that we need
436// to always use recvfrom() to disambiguate.
437TEST_F(UDPSocketTest, VerifyConnectBindsAddr) {
tfarinac40df1c2015-11-30 22:31:47438 const uint16_t kPort1 = 9999;
439 const uint16_t kPort2 = 10000;
[email protected]a2798d92011-03-02 22:56:18440 std::string simple_message("hello world!");
441 std::string foreign_message("BAD MESSAGE TO GET!!");
442
443 // Setup the first server to listen.
[email protected]43d4a0262011-03-09 19:26:04444 IPEndPoint bind_address;
[email protected]2cb83102012-09-18 19:13:01445 CreateUDPAddress("127.0.0.1", kPort1, &bind_address);
[email protected]a2798d92011-03-02 22:56:18446 UDPServerSocket server1(NULL, NetLog::Source());
[email protected]2cb83102012-09-18 19:13:01447 server1.AllowAddressReuse();
[email protected]a2798d92011-03-02 22:56:18448 int rv = server1.Listen(bind_address);
[email protected]d72a14f2012-09-11 16:27:11449 ASSERT_EQ(OK, rv);
[email protected]a2798d92011-03-02 22:56:18450
451 // Setup the second server to listen.
[email protected]2cb83102012-09-18 19:13:01452 CreateUDPAddress("127.0.0.1", kPort2, &bind_address);
[email protected]a2798d92011-03-02 22:56:18453 UDPServerSocket server2(NULL, NetLog::Source());
[email protected]2cb83102012-09-18 19:13:01454 server2.AllowAddressReuse();
[email protected]a2798d92011-03-02 22:56:18455 rv = server2.Listen(bind_address);
[email protected]d72a14f2012-09-11 16:27:11456 ASSERT_EQ(OK, rv);
[email protected]a2798d92011-03-02 22:56:18457
458 // Setup the client, connected to server 1.
[email protected]43d4a0262011-03-09 19:26:04459 IPEndPoint server_address;
[email protected]a2798d92011-03-02 22:56:18460 CreateUDPAddress("127.0.0.1", kPort1, &server_address);
[email protected]5370c012011-06-29 03:47:04461 UDPClientSocket client(DatagramSocket::DEFAULT_BIND,
462 RandIntCallback(),
463 NULL,
464 NetLog::Source());
[email protected]a2798d92011-03-02 22:56:18465 rv = client.Connect(server_address);
466 EXPECT_EQ(OK, rv);
467
468 // Client sends to server1.
469 rv = WriteSocket(&client, simple_message);
470 EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
471
472 // Server1 waits for message.
473 std::string str = RecvFromSocket(&server1);
474 DCHECK(simple_message == str);
475
476 // Get the client's address.
[email protected]43d4a0262011-03-09 19:26:04477 IPEndPoint client_address;
[email protected]a2798d92011-03-02 22:56:18478 rv = client.GetLocalAddress(&client_address);
479 EXPECT_EQ(OK, rv);
480
481 // Server2 sends reply.
482 rv = SendToSocket(&server2, foreign_message,
[email protected]43d4a0262011-03-09 19:26:04483 client_address);
[email protected]a2798d92011-03-02 22:56:18484 EXPECT_EQ(foreign_message.length(), static_cast<size_t>(rv));
485
486 // Server1 sends reply.
487 rv = SendToSocket(&server1, simple_message,
[email protected]43d4a0262011-03-09 19:26:04488 client_address);
[email protected]a2798d92011-03-02 22:56:18489 EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
490
491 // Client waits for response.
492 str = ReadSocket(&client);
493 DCHECK(simple_message == str);
494}
495
ellyjones74165fa2015-08-27 16:28:05496TEST_F(UDPSocketTest, ClientGetLocalPeerAddresses) {
[email protected]a2798d92011-03-02 22:56:18497 struct TestData {
498 std::string remote_address;
499 std::string local_address;
[email protected]7b6afd02011-03-12 00:03:12500 bool may_fail;
[email protected]a2798d92011-03-02 22:56:18501 } tests[] = {
502 { "127.0.00.1", "127.0.0.1", false },
[email protected]75aa4952011-03-11 21:38:55503 { "::1", "::1", true },
ellyjones74165fa2015-08-27 16:28:05504#if !defined(OS_ANDROID) && !defined(OS_IOS)
[email protected]86c8e5122012-11-15 20:34:43505 // Addresses below are disabled on Android. See crbug.com/161248
ellyjones74165fa2015-08-27 16:28:05506 // They are also disabled on iOS. See https://crbug.com/523225
[email protected]86c8e5122012-11-15 20:34:43507 { "192.168.1.1", "127.0.0.1", false },
[email protected]a2798d92011-03-02 22:56:18508 { "2001:db8:0::42", "::1", true },
[email protected]86c8e5122012-11-15 20:34:43509#endif
[email protected]a2798d92011-03-02 22:56:18510 };
viettrungluue4a8b882014-10-16 06:17:38511 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]7b6afd02011-03-12 00:03:12512 SCOPED_TRACE(std::string("Connecting from ") + tests[i].local_address +
513 std::string(" to ") + tests[i].remote_address);
514
[email protected]8866f622011-10-18 20:08:10515 IPAddressNumber ip_number;
516 ParseIPLiteralToNumber(tests[i].remote_address, &ip_number);
517 IPEndPoint remote_address(ip_number, 80);
518 ParseIPLiteralToNumber(tests[i].local_address, &ip_number);
519 IPEndPoint local_address(ip_number, 80);
[email protected]a2798d92011-03-02 22:56:18520
[email protected]5370c012011-06-29 03:47:04521 UDPClientSocket client(DatagramSocket::DEFAULT_BIND,
522 RandIntCallback(),
523 NULL,
524 NetLog::Source());
[email protected]a2798d92011-03-02 22:56:18525 int rv = client.Connect(remote_address);
[email protected]7b6afd02011-03-12 00:03:12526 if (tests[i].may_fail && rv == ERR_ADDRESS_UNREACHABLE) {
527 // Connect() may return ERR_ADDRESS_UNREACHABLE for IPv6
528 // addresses if IPv6 is not configured.
529 continue;
530 }
531
[email protected]a2798d92011-03-02 22:56:18532 EXPECT_LE(ERR_IO_PENDING, rv);
533
[email protected]43d4a0262011-03-09 19:26:04534 IPEndPoint fetched_local_address;
[email protected]a2798d92011-03-02 22:56:18535 rv = client.GetLocalAddress(&fetched_local_address);
536 EXPECT_EQ(OK, rv);
537
[email protected]a2798d92011-03-02 22:56:18538 // TODO(mbelshe): figure out how to verify the IP and port.
539 // The port is dynamically generated by the udp stack.
540 // The IP is the real IP of the client, not necessarily
541 // loopback.
[email protected]43d4a0262011-03-09 19:26:04542 //EXPECT_EQ(local_address.address(), fetched_local_address.address());
[email protected]a2798d92011-03-02 22:56:18543
[email protected]43d4a0262011-03-09 19:26:04544 IPEndPoint fetched_remote_address;
[email protected]a2798d92011-03-02 22:56:18545 rv = client.GetPeerAddress(&fetched_remote_address);
546 EXPECT_EQ(OK, rv);
547
[email protected]43d4a0262011-03-09 19:26:04548 EXPECT_EQ(remote_address, fetched_remote_address);
[email protected]a2798d92011-03-02 22:56:18549 }
550}
551
552TEST_F(UDPSocketTest, ServerGetLocalAddress) {
[email protected]7b6afd02011-03-12 00:03:12553 IPEndPoint bind_address;
554 CreateUDPAddress("127.0.0.1", 0, &bind_address);
555 UDPServerSocket server(NULL, NetLog::Source());
556 int rv = server.Listen(bind_address);
557 EXPECT_EQ(OK, rv);
558
559 IPEndPoint local_address;
560 rv = server.GetLocalAddress(&local_address);
561 EXPECT_EQ(rv, 0);
562
563 // Verify that port was allocated.
[email protected]c10d57a12011-04-05 21:36:24564 EXPECT_GT(local_address.port(), 0);
[email protected]7b6afd02011-03-12 00:03:12565 EXPECT_EQ(local_address.address(), bind_address.address());
[email protected]a2798d92011-03-02 22:56:18566}
567
568TEST_F(UDPSocketTest, ServerGetPeerAddress) {
[email protected]7b6afd02011-03-12 00:03:12569 IPEndPoint bind_address;
570 CreateUDPAddress("127.0.0.1", 0, &bind_address);
571 UDPServerSocket server(NULL, NetLog::Source());
572 int rv = server.Listen(bind_address);
573 EXPECT_EQ(OK, rv);
574
575 IPEndPoint peer_address;
576 rv = server.GetPeerAddress(&peer_address);
577 EXPECT_EQ(rv, ERR_SOCKET_NOT_CONNECTED);
578}
579
580// Close the socket while read is pending.
581TEST_F(UDPSocketTest, CloseWithPendingRead) {
582 IPEndPoint bind_address;
583 CreateUDPAddress("127.0.0.1", 0, &bind_address);
584 UDPServerSocket server(NULL, NetLog::Source());
585 int rv = server.Listen(bind_address);
586 EXPECT_EQ(OK, rv);
587
[email protected]83039bb2011-12-09 18:43:55588 TestCompletionCallback callback;
[email protected]7b6afd02011-03-12 00:03:12589 IPEndPoint from;
[email protected]90499482013-06-01 00:39:50590 rv = server.RecvFrom(buffer_.get(), kMaxRead, &from, callback.callback());
[email protected]7b6afd02011-03-12 00:03:12591 EXPECT_EQ(rv, ERR_IO_PENDING);
592
593 server.Close();
594
[email protected]a647bcf2011-03-14 18:33:31595 EXPECT_FALSE(callback.have_result());
[email protected]a2798d92011-03-02 22:56:18596}
597
[email protected]5f01ce22013-04-30 00:53:18598#if defined(OS_ANDROID)
599// Some Android devices do not support multicast socket.
600// The ones supporting multicast need WifiManager.MulitcastLock to enable it.
601// http://goo.gl/jjAk9
602#define MAYBE_JoinMulticastGroup DISABLED_JoinMulticastGroup
603#else
604#define MAYBE_JoinMulticastGroup JoinMulticastGroup
605#endif // defined(OS_ANDROID)
606
607TEST_F(UDPSocketTest, MAYBE_JoinMulticastGroup) {
tfarinac40df1c2015-11-30 22:31:47608 const uint16_t kPort = 9999;
thestig9d3bb0c2015-01-24 00:49:51609 const char kGroup[] = "237.132.100.17";
[email protected]5f01ce22013-04-30 00:53:18610
611 IPEndPoint bind_address;
612 CreateUDPAddress("0.0.0.0", kPort, &bind_address);
613 IPAddressNumber group_ip;
614 EXPECT_TRUE(ParseIPLiteralToNumber(kGroup, &group_ip));
615
616 UDPSocket socket(DatagramSocket::DEFAULT_BIND,
617 RandIntCallback(),
618 NULL,
619 NetLog::Source());
hidehiko17fac552014-12-08 06:02:17620 EXPECT_EQ(OK, socket.Open(bind_address.GetFamily()));
[email protected]5f01ce22013-04-30 00:53:18621 EXPECT_EQ(OK, socket.Bind(bind_address));
622 EXPECT_EQ(OK, socket.JoinGroup(group_ip));
623 // Joining group multiple times.
624 EXPECT_NE(OK, socket.JoinGroup(group_ip));
625 EXPECT_EQ(OK, socket.LeaveGroup(group_ip));
626 // Leaving group multiple times.
627 EXPECT_NE(OK, socket.LeaveGroup(group_ip));
628
629 socket.Close();
630}
631
632TEST_F(UDPSocketTest, MulticastOptions) {
tfarinac40df1c2015-11-30 22:31:47633 const uint16_t kPort = 9999;
[email protected]5f01ce22013-04-30 00:53:18634 IPEndPoint bind_address;
635 CreateUDPAddress("0.0.0.0", kPort, &bind_address);
636
637 UDPSocket socket(DatagramSocket::DEFAULT_BIND,
638 RandIntCallback(),
639 NULL,
640 NetLog::Source());
641 // Before binding.
642 EXPECT_EQ(OK, socket.SetMulticastLoopbackMode(false));
643 EXPECT_EQ(OK, socket.SetMulticastLoopbackMode(true));
644 EXPECT_EQ(OK, socket.SetMulticastTimeToLive(0));
645 EXPECT_EQ(OK, socket.SetMulticastTimeToLive(3));
646 EXPECT_NE(OK, socket.SetMulticastTimeToLive(-1));
[email protected]7b29dac2013-12-05 11:19:42647 EXPECT_EQ(OK, socket.SetMulticastInterface(0));
[email protected]5f01ce22013-04-30 00:53:18648
hidehiko17fac552014-12-08 06:02:17649 EXPECT_EQ(OK, socket.Open(bind_address.GetFamily()));
[email protected]5f01ce22013-04-30 00:53:18650 EXPECT_EQ(OK, socket.Bind(bind_address));
651
[email protected]7b29dac2013-12-05 11:19:42652 EXPECT_NE(OK, socket.SetMulticastLoopbackMode(false));
653 EXPECT_NE(OK, socket.SetMulticastTimeToLive(0));
654 EXPECT_NE(OK, socket.SetMulticastInterface(0));
655
[email protected]5f01ce22013-04-30 00:53:18656 socket.Close();
657}
658
[email protected]3d2fd542014-08-12 03:07:08659// Checking that DSCP bits are set correctly is difficult,
660// but let's check that the code doesn't crash at least.
661TEST_F(UDPSocketTest, SetDSCP) {
662 // Setup the server to listen.
663 IPEndPoint bind_address;
664 UDPSocket client(DatagramSocket::DEFAULT_BIND,
665 RandIntCallback(),
666 NULL,
667 NetLog::Source());
668 // We need a real IP, but we won't actually send anything to it.
669 CreateUDPAddress("8.8.8.8", 9999, &bind_address);
hidehiko17fac552014-12-08 06:02:17670 int rv = client.Open(bind_address.GetFamily());
671 EXPECT_EQ(OK, rv);
672
673 rv = client.Connect(bind_address);
[email protected]3d2fd542014-08-12 03:07:08674 if (rv != OK) {
675 // Let's try localhost then..
676 CreateUDPAddress("127.0.0.1", 9999, &bind_address);
677 rv = client.Connect(bind_address);
678 }
679 EXPECT_EQ(OK, rv);
680
681 client.SetDiffServCodePoint(DSCP_NO_CHANGE);
682 client.SetDiffServCodePoint(DSCP_AF41);
683 client.SetDiffServCodePoint(DSCP_DEFAULT);
684 client.SetDiffServCodePoint(DSCP_CS2);
685 client.SetDiffServCodePoint(DSCP_NO_CHANGE);
686 client.SetDiffServCodePoint(DSCP_DEFAULT);
687 client.Close();
688}
689
[email protected]a2798d92011-03-02 22:56:18690} // namespace
691
[email protected]3d2fd542014-08-12 03:07:08692#if defined(OS_WIN)
693
694namespace {
695
696const HANDLE kFakeHandle = (HANDLE)19;
697const QOS_FLOWID kFakeFlowId = (QOS_FLOWID)27;
698
699BOOL WINAPI FakeQOSCreateHandleFAIL(PQOS_VERSION version, PHANDLE handle) {
700 EXPECT_EQ(0, version->MinorVersion);
701 EXPECT_EQ(1, version->MajorVersion);
702 SetLastError(ERROR_OPEN_FAILED);
703 return false;
704}
705
706BOOL WINAPI FakeQOSCreateHandle(PQOS_VERSION version, PHANDLE handle) {
707 EXPECT_EQ(0, version->MinorVersion);
708 EXPECT_EQ(1, version->MajorVersion);
709 *handle = kFakeHandle;
710 return true;
711}
712
713BOOL WINAPI FakeQOSCloseHandle(HANDLE handle) {
714 EXPECT_EQ(kFakeHandle, handle);
715 return true;
716}
717
718QOS_TRAFFIC_TYPE g_expected_traffic_type;
719
720BOOL WINAPI FakeQOSAddSocketToFlow(HANDLE handle,
721 SOCKET socket,
722 PSOCKADDR addr,
723 QOS_TRAFFIC_TYPE traffic_type,
724 DWORD flags,
725 PQOS_FLOWID flow_id) {
726 EXPECT_EQ(kFakeHandle, handle);
727 EXPECT_EQ(NULL, addr);
thakis6ef917b2015-12-10 19:29:57728 EXPECT_EQ(static_cast<DWORD>(QOS_NON_ADAPTIVE_FLOW), flags);
729 EXPECT_EQ(0u, *flow_id);
[email protected]3d2fd542014-08-12 03:07:08730 *flow_id = kFakeFlowId;
731 return true;
732}
733
734BOOL WINAPI FakeQOSRemoveSocketFromFlow(HANDLE handle,
735 SOCKET socket,
736 QOS_FLOWID flowid,
737 DWORD reserved) {
738 EXPECT_EQ(kFakeHandle, handle);
thakis6ef917b2015-12-10 19:29:57739 EXPECT_EQ(0u, socket);
[email protected]3d2fd542014-08-12 03:07:08740 EXPECT_EQ(kFakeFlowId, flowid);
thakis6ef917b2015-12-10 19:29:57741 EXPECT_EQ(0u, reserved);
[email protected]3d2fd542014-08-12 03:07:08742 return true;
743}
744
745DWORD g_expected_dscp;
746
747BOOL WINAPI FakeQOSSetFlow(HANDLE handle,
748 QOS_FLOWID flow_id,
749 QOS_SET_FLOW op,
750 ULONG size,
751 PVOID data,
752 DWORD reserved,
753 LPOVERLAPPED overlapped) {
754 EXPECT_EQ(kFakeHandle, handle);
755 EXPECT_EQ(QOSSetOutgoingDSCPValue, op);
756 EXPECT_EQ(sizeof(DWORD), size);
757 EXPECT_EQ(g_expected_dscp, *reinterpret_cast<DWORD*>(data));
758 EXPECT_EQ(kFakeFlowId, flow_id);
thakis6ef917b2015-12-10 19:29:57759 EXPECT_EQ(0u, reserved);
[email protected]3d2fd542014-08-12 03:07:08760 EXPECT_EQ(NULL, overlapped);
761 return true;
762}
763
764} // namespace
765
766// Mock out the Qwave functions and make sure they are
767// called correctly. Must be in net namespace for friendship
768// reasons.
769TEST_F(UDPSocketTest, SetDSCPFake) {
770 // Setup the server to listen.
771 IPEndPoint bind_address;
772 // We need a real IP, but we won't actually send anything to it.
773 CreateUDPAddress("8.8.8.8", 9999, &bind_address);
774 UDPSocket client(DatagramSocket::DEFAULT_BIND,
775 RandIntCallback(),
776 NULL,
777 NetLog::Source());
778 int rv = client.SetDiffServCodePoint(DSCP_AF41);
779 EXPECT_EQ(ERR_SOCKET_NOT_CONNECTED, rv);
hidehiko17fac552014-12-08 06:02:17780
781 rv = client.Open(bind_address.GetFamily());
782 EXPECT_EQ(OK, rv);
783
[email protected]3d2fd542014-08-12 03:07:08784 rv = client.Connect(bind_address);
785 EXPECT_EQ(OK, rv);
786
787 QwaveAPI& qos(QwaveAPI::Get());
788 qos.create_handle_func_ = FakeQOSCreateHandleFAIL;
789 qos.close_handle_func_ = FakeQOSCloseHandle;
790 qos.add_socket_to_flow_func_ = FakeQOSAddSocketToFlow;
791 qos.remove_socket_from_flow_func_ = FakeQOSRemoveSocketFromFlow;
792 qos.set_flow_func_ = FakeQOSSetFlow;
793 qos.qwave_supported_ = true;
794
795 EXPECT_EQ(OK, client.SetDiffServCodePoint(DSCP_NO_CHANGE));
796 EXPECT_EQ(ERROR_NOT_SUPPORTED, client.SetDiffServCodePoint(DSCP_AF41));
797 qos.create_handle_func_ = FakeQOSCreateHandle;
798 g_expected_dscp = DSCP_AF41;
799 g_expected_traffic_type = QOSTrafficTypeAudioVideo;
800 EXPECT_EQ(OK, client.SetDiffServCodePoint(DSCP_AF41));
801 g_expected_dscp = DSCP_DEFAULT;
802 g_expected_traffic_type = QOSTrafficTypeBestEffort;
803 EXPECT_EQ(OK, client.SetDiffServCodePoint(DSCP_DEFAULT));
804 g_expected_dscp = DSCP_CS2;
805 g_expected_traffic_type = QOSTrafficTypeExcellentEffort;
806 EXPECT_EQ(OK, client.SetDiffServCodePoint(DSCP_CS2));
807 g_expected_dscp = DSCP_CS3;
808 g_expected_traffic_type = QOSTrafficTypeExcellentEffort;
809 EXPECT_EQ(OK, client.SetDiffServCodePoint(DSCP_NO_CHANGE));
810 g_expected_dscp = DSCP_DEFAULT;
811 g_expected_traffic_type = QOSTrafficTypeBestEffort;
812 EXPECT_EQ(OK, client.SetDiffServCodePoint(DSCP_DEFAULT));
813 client.Close();
814}
815#endif
816
[email protected]a2798d92011-03-02 22:56:18817} // namespace net