blob: 4bf0e62cdb69eb1ea11b9e9a7636ac144422164f [file] [log] [blame]
Avi Drissman64595482022-09-14 20:52:291// Copyright 2012 The Chromium Authors
[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
tfarina5dd13c22016-11-16 12:08:265#include "net/socket/udp_socket.h"
[email protected]a2798d92011-03-02 22:56:186
Sergey Ulanovcbdfc8852018-03-16 20:13:287#include <algorithm>
8
Brett Wilsonc6a0c822017-09-12 00:04:299#include "base/containers/circular_deque.h"
Avi Drissman41c4a412023-01-11 22:45:3710#include "base/functional/bind.h"
skyostil4891b25b2015-06-11 11:43:4511#include "base/location.h"
Keishi Hattori0e45c022021-11-27 09:25:5212#include "base/memory/raw_ptr.h"
hclam5a5ee682015-02-05 04:18:2213#include "base/memory/weak_ptr.h"
hclam5a5ee682015-02-05 04:18:2214#include "base/run_loop.h"
Tim Haloun66923ce2018-10-27 01:01:0615#include "base/scoped_clear_last_error.h"
Eric Roman5a841922020-08-13 01:28:2516#include "base/strings/string_number_conversions.h"
Patrick Monette643cdf62021-10-15 19:13:4217#include "base/task/single_thread_task_runner.h"
Eric Roman5a841922020-08-13 01:28:2518#include "base/test/scoped_feature_list.h"
19#include "base/threading/thread.h"
Gabriel Charetted87f10f2022-03-31 00:44:2220#include "base/time/time.h"
Sergey Ulanov38e18bd2017-07-28 18:59:3621#include "build/build_config.h"
Yuta Hijikata101ed2a2020-11-18 07:50:3922#include "build/chromeos_buildflags.h"
Eric Roman5a841922020-08-13 01:28:2523#include "net/base/features.h"
[email protected]a2798d92011-03-02 22:56:1824#include "net/base/io_buffer.h"
martijnd8dafab2016-03-14 18:28:4925#include "net/base/ip_address.h"
[email protected]43d4a0262011-03-09 19:26:0426#include "net/base/ip_endpoint.h"
[email protected]a2798d92011-03-02 22:56:1827#include "net/base/net_errors.h"
Wez95384392018-07-13 22:57:3828#include "net/base/network_interfaces.h"
[email protected]a2798d92011-03-02 22:56:1829#include "net/base/test_completion_callback.h"
mikecirone8b85c432016-09-08 19:11:0030#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1931#include "net/log/net_log_source.h"
mmenke16a7cbdd2015-04-24 23:00:5632#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4633#include "net/log/test_net_log_util.h"
Paul Jensen0f49dec2017-12-12 23:39:5834#include "net/socket/socket_test_util.h"
tfarina5dd13c22016-11-16 12:08:2635#include "net/socket/udp_client_socket.h"
36#include "net/socket/udp_server_socket.h"
Eric Roman5a841922020-08-13 01:28:2537#include "net/socket/udp_socket_global_limits.h"
robpercival214763f2016-07-01 23:27:0138#include "net/test/gtest_util.h"
Gabriel Charettec7108742019-08-23 03:31:4039#include "net/test/test_with_task_environment.h"
[email protected]578968d42017-12-13 15:39:3240#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
robpercival214763f2016-07-01 23:27:0141#include "testing/gmock/include/gmock/gmock.h"
[email protected]a2798d92011-03-02 22:56:1842#include "testing/gtest/include/gtest/gtest.h"
43#include "testing/platform_test.h"
44
Xiaohan Wang2a6845b2022-01-08 04:40:5745#if BUILDFLAG(IS_ANDROID)
pauljensen479143c2016-07-22 12:35:0946#include "base/android/build_info.h"
Kenichi Ishibashi08c3ea12021-12-09 08:23:4647#include "base/android/radio_utils.h"
48#include "base/test/metrics/histogram_tester.h"
Paul Jensen546dde712017-12-05 20:39:3149#include "net/android/network_change_notifier_factory_android.h"
Kenichi Ishibashi08c3ea12021-12-09 08:23:4650#include "net/android/radio_activity_tracker.h"
Paul Jensen546dde712017-12-05 20:39:3151#include "net/base/network_change_notifier.h"
pauljensen479143c2016-07-22 12:35:0952#endif
53
Xiaohan Wang2a6845b2022-01-08 04:40:5754#if BUILDFLAG(IS_IOS)
blundellb8163592f2015-12-16 14:22:4255#include <TargetConditionals.h>
56#endif
57
Momoka Yamamotof16c5d2282022-03-16 00:20:4658#if BUILDFLAG(IS_MAC)
59#include "base/mac/mac_util.h"
60#endif // BUILDFLAG(IS_MAC)
61
robpercival214763f2016-07-01 23:27:0162using net::test::IsError;
63using net::test::IsOk;
Staphany Park648b34a2019-05-10 18:51:4964using testing::DoAll;
Sergey Ulanovcbdfc8852018-03-16 20:13:2865using testing::Not;
robpercival214763f2016-07-01 23:27:0166
[email protected]a2798d92011-03-02 22:56:1867namespace net {
68
69namespace {
70
Tim Halounce5b54932018-10-08 22:34:4671// Creates an address from ip address and port and writes it to |*address|.
72bool CreateUDPAddress(const std::string& ip_str,
73 uint16_t port,
74 IPEndPoint* address) {
75 IPAddress ip_address;
76 if (!ip_address.AssignFromIPLiteral(ip_str))
77 return false;
78
79 *address = IPEndPoint(ip_address, port);
80 return true;
81}
82
Gabriel Charette694c3c332019-08-19 14:53:0583class UDPSocketTest : public PlatformTest, public WithTaskEnvironment {
[email protected]a2798d92011-03-02 22:56:1884 public:
Victor Costan9c7302b2018-08-27 16:39:4485 UDPSocketTest() : buffer_(base::MakeRefCounted<IOBufferWithSize>(kMaxRead)) {}
[email protected]a2798d92011-03-02 22:56:1886
87 // Blocks until data is read from the socket.
88 std::string RecvFromSocket(UDPServerSocket* socket) {
[email protected]83039bb2011-12-09 18:43:5589 TestCompletionCallback callback;
[email protected]a2798d92011-03-02 22:56:1890
Eric Orth7141dbc2018-10-26 20:10:2491 int rv = socket->RecvFrom(buffer_.get(), kMaxRead, &recv_from_address_,
92 callback.callback());
Sergey Ulanov38e18bd2017-07-28 18:59:3693 rv = callback.GetResult(rv);
[email protected]a2798d92011-03-02 22:56:1894 if (rv < 0)
Sergey Ulanov38e18bd2017-07-28 18:59:3695 return std::string();
[email protected]a2798d92011-03-02 22:56:1896 return std::string(buffer_->data(), rv);
97 }
98
Sergey Ulanov2d1a4272017-09-08 21:39:4899 // Sends UDP packet.
[email protected]43d4a0262011-03-09 19:26:04100 // If |address| is specified, then it is used for the destination
101 // to send to. Otherwise, will send to the last socket this server
102 // received from.
ki.stfu144dce12015-09-22 01:07:57103 int SendToSocket(UDPServerSocket* socket, const std::string& msg) {
[email protected]43d4a0262011-03-09 19:26:04104 return SendToSocket(socket, msg, recv_from_address_);
105 }
106
[email protected]a2798d92011-03-02 22:56:18107 int SendToSocket(UDPServerSocket* socket,
108 std::string msg,
[email protected]43d4a0262011-03-09 19:26:04109 const IPEndPoint& address) {
Victor Costan9c7302b2018-08-27 16:39:44110 scoped_refptr<StringIOBuffer> io_buffer =
111 base::MakeRefCounted<StringIOBuffer>(msg);
[email protected]83039bb2011-12-09 18:43:55112 TestCompletionCallback callback;
Sergey Ulanov2d1a4272017-09-08 21:39:48113 int rv = socket->SendTo(io_buffer.get(), io_buffer->size(), address,
114 callback.callback());
115 return callback.GetResult(rv);
[email protected]a2798d92011-03-02 22:56:18116 }
117
118 std::string ReadSocket(UDPClientSocket* socket) {
[email protected]83039bb2011-12-09 18:43:55119 TestCompletionCallback callback;
[email protected]a2798d92011-03-02 22:56:18120
[email protected]90499482013-06-01 00:39:50121 int rv = socket->Read(buffer_.get(), kMaxRead, callback.callback());
Sergey Ulanov38e18bd2017-07-28 18:59:36122 rv = callback.GetResult(rv);
[email protected]a2798d92011-03-02 22:56:18123 if (rv < 0)
Sergey Ulanov38e18bd2017-07-28 18:59:36124 return std::string();
[email protected]a2798d92011-03-02 22:56:18125 return std::string(buffer_->data(), rv);
126 }
127
Sergey Ulanov2d1a4272017-09-08 21:39:48128 // Writes specified message to the socket.
ki.stfu144dce12015-09-22 01:07:57129 int WriteSocket(UDPClientSocket* socket, const std::string& msg) {
Victor Costan9c7302b2018-08-27 16:39:44130 scoped_refptr<StringIOBuffer> io_buffer =
131 base::MakeRefCounted<StringIOBuffer>(msg);
Sergey Ulanov2d1a4272017-09-08 21:39:48132 TestCompletionCallback callback;
[email protected]578968d42017-12-13 15:39:32133 int rv = socket->Write(io_buffer.get(), io_buffer->size(),
134 callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS);
Sergey Ulanov2d1a4272017-09-08 21:39:48135 return callback.GetResult(rv);
[email protected]a2798d92011-03-02 22:56:18136 }
137
ki.stfu144dce12015-09-22 01:07:57138 void WriteSocketIgnoreResult(UDPClientSocket* socket,
139 const std::string& msg) {
hclam5a5ee682015-02-05 04:18:22140 WriteSocket(socket, msg);
141 }
142
Tim Halounce5b54932018-10-08 22:34:46143 // And again for a bare socket
144 int SendToSocket(UDPSocket* socket,
145 std::string msg,
146 const IPEndPoint& address) {
Tsuyoshi Horo2c0a5042022-07-06 05:53:07147 auto io_buffer = base::MakeRefCounted<StringIOBuffer>(msg);
Tim Halounce5b54932018-10-08 22:34:46148 TestCompletionCallback callback;
149 int rv = socket->SendTo(io_buffer.get(), io_buffer->size(), address,
150 callback.callback());
151 return callback.GetResult(rv);
hclam5a5ee682015-02-05 04:18:22152 }
153
154 // Run unit test for a connection test.
155 // |use_nonblocking_io| is used to switch between overlapped and non-blocking
156 // IO on Windows. It has no effect in other ports.
Liza Burakova892ce1c2022-09-19 16:44:46157 void ConnectTest(bool use_nonblocking_io, bool use_async);
hclam5a5ee682015-02-05 04:18:22158
[email protected]7b6afd02011-03-12 00:03:12159 protected:
[email protected]a2798d92011-03-02 22:56:18160 static const int kMaxRead = 1024;
161 scoped_refptr<IOBufferWithSize> buffer_;
[email protected]9d1e2ba02011-03-09 19:42:33162 IPEndPoint recv_from_address_;
[email protected]a2798d92011-03-02 22:56:18163};
164
Victor Costan9c7302b2018-08-27 16:39:44165const int UDPSocketTest::kMaxRead;
166
Steve Kobes124cd992020-07-08 20:18:28167void ReadCompleteCallback(int* result_out,
168 base::OnceClosure callback,
169 int result) {
hclam5a5ee682015-02-05 04:18:22170 *result_out = result;
Steve Kobes124cd992020-07-08 20:18:28171 std::move(callback).Run();
[email protected]a2798d92011-03-02 22:56:18172}
173
Liza Burakova892ce1c2022-09-19 16:44:46174void UDPSocketTest::ConnectTest(bool use_nonblocking_io, bool use_async) {
[email protected]a2798d92011-03-02 22:56:18175 std::string simple_message("hello world!");
Matt Reichhoff36a1fd62021-10-12 22:52:20176 RecordingNetLogObserver net_log_observer;
[email protected]a2798d92011-03-02 22:56:18177 // Setup the server to listen.
Matt Menkebdcddfd2018-12-20 18:51:29178 IPEndPoint server_address(IPAddress::IPv4Localhost(), 0 /* port */);
Tsuyoshi Horof8861cb2022-07-05 23:50:20179 auto server =
180 std::make_unique<UDPServerSocket>(NetLog::Get(), NetLogSource());
hclam5a5ee682015-02-05 04:18:22181 if (use_nonblocking_io)
182 server->UseNonBlockingIO();
[email protected]2cb83102012-09-18 19:13:01183 server->AllowAddressReuse();
Matt Menkebdcddfd2018-12-20 18:51:29184 ASSERT_THAT(server->Listen(server_address), IsOk());
185 // Get bound port.
186 ASSERT_THAT(server->GetLocalAddress(&server_address), IsOk());
[email protected]a2798d92011-03-02 22:56:18187
188 // Setup the client.
Matt Reichhoff36a1fd62021-10-12 22:52:20189 auto client = std::make_unique<UDPClientSocket>(
190 DatagramSocket::DEFAULT_BIND, NetLog::Get(), NetLogSource());
hclam5a5ee682015-02-05 04:18:22191 if (use_nonblocking_io)
192 client->UseNonBlockingIO();
hclam5a5ee682015-02-05 04:18:22193
Liza Burakova892ce1c2022-09-19 16:44:46194 if (!use_async) {
195 EXPECT_THAT(client->Connect(server_address), IsOk());
196 } else {
197 TestCompletionCallback callback;
198 int rv = client->ConnectAsync(server_address, callback.callback());
199 if (rv != OK) {
200 ASSERT_EQ(rv, ERR_IO_PENDING);
201 rv = callback.WaitForResult();
202 EXPECT_EQ(rv, OK);
203 } else {
204 EXPECT_EQ(rv, OK);
205 }
206 }
[email protected]a2798d92011-03-02 22:56:18207 // Client sends to the server.
Matt Menkebdcddfd2018-12-20 18:51:29208 EXPECT_EQ(simple_message.length(),
209 static_cast<size_t>(WriteSocket(client.get(), simple_message)));
[email protected]a2798d92011-03-02 22:56:18210
211 // Server waits for message.
[email protected]8866f622011-10-18 20:08:10212 std::string str = RecvFromSocket(server.get());
Sergey Ulanov38e18bd2017-07-28 18:59:36213 EXPECT_EQ(simple_message, str);
[email protected]a2798d92011-03-02 22:56:18214
215 // Server echoes reply.
Matt Menkebdcddfd2018-12-20 18:51:29216 EXPECT_EQ(simple_message.length(),
217 static_cast<size_t>(SendToSocket(server.get(), simple_message)));
[email protected]a2798d92011-03-02 22:56:18218
219 // Client waits for response.
[email protected]8866f622011-10-18 20:08:10220 str = ReadSocket(client.get());
Sergey Ulanov38e18bd2017-07-28 18:59:36221 EXPECT_EQ(simple_message, str);
[email protected]8866f622011-10-18 20:08:10222
hclam5a5ee682015-02-05 04:18:22223 // Test asynchronous read. Server waits for message.
224 base::RunLoop run_loop;
225 int read_result = 0;
Yannic Bonenbergercc716d42019-09-04 17:05:36226 int rv = server->RecvFrom(buffer_.get(), kMaxRead, &recv_from_address_,
227 base::BindOnce(&ReadCompleteCallback, &read_result,
228 run_loop.QuitClosure()));
robpercival214763f2016-07-01 23:27:01229 EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
hclam5a5ee682015-02-05 04:18:22230
231 // Client sends to the server.
Sean Maher5b9af51f2022-11-21 15:32:47232 base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
hclam5a5ee682015-02-05 04:18:22233 FROM_HERE,
kylecharf4fe5172019-02-15 18:53:49234 base::BindOnce(&UDPSocketTest::WriteSocketIgnoreResult,
235 base::Unretained(this), client.get(), simple_message));
hclam5a5ee682015-02-05 04:18:22236 run_loop.Run();
237 EXPECT_EQ(simple_message.length(), static_cast<size_t>(read_result));
238 EXPECT_EQ(simple_message, std::string(buffer_->data(), read_result));
239
Matt Reichhoff36a1fd62021-10-12 22:52:20240 NetLogSource server_net_log_source = server->NetLog().source();
241 NetLogSource client_net_log_source = client->NetLog().source();
242
[email protected]8866f622011-10-18 20:08:10243 // Delete sockets so they log their final events.
244 server.reset();
245 client.reset();
246
247 // Check the server's log.
Matt Reichhoff36a1fd62021-10-12 22:52:20248 auto server_entries =
249 net_log_observer.GetEntriesForSource(server_net_log_source);
Matt Menkebdcddfd2018-12-20 18:51:29250 ASSERT_EQ(6u, server_entries.size());
hclam5a5ee682015-02-05 04:18:22251 EXPECT_TRUE(
mikecirone8b85c432016-09-08 19:11:00252 LogContainsBeginEvent(server_entries, 0, NetLogEventType::SOCKET_ALIVE));
253 EXPECT_TRUE(LogContainsEvent(server_entries, 1,
Matt Menkebdcddfd2018-12-20 18:51:29254 NetLogEventType::UDP_LOCAL_ADDRESS,
mikecirone8b85c432016-09-08 19:11:00255 NetLogEventPhase::NONE));
256 EXPECT_TRUE(LogContainsEvent(server_entries, 2,
Matt Menkebdcddfd2018-12-20 18:51:29257 NetLogEventType::UDP_BYTES_RECEIVED,
mikecirone8b85c432016-09-08 19:11:00258 NetLogEventPhase::NONE));
259 EXPECT_TRUE(LogContainsEvent(server_entries, 3,
Matt Menkebdcddfd2018-12-20 18:51:29260 NetLogEventType::UDP_BYTES_SENT,
261 NetLogEventPhase::NONE));
262 EXPECT_TRUE(LogContainsEvent(server_entries, 4,
mikecirone8b85c432016-09-08 19:11:00263 NetLogEventType::UDP_BYTES_RECEIVED,
264 NetLogEventPhase::NONE));
hclam5a5ee682015-02-05 04:18:22265 EXPECT_TRUE(
Matt Menkebdcddfd2018-12-20 18:51:29266 LogContainsEndEvent(server_entries, 5, NetLogEventType::SOCKET_ALIVE));
[email protected]8866f622011-10-18 20:08:10267
268 // Check the client's log.
Matt Reichhoff36a1fd62021-10-12 22:52:20269 auto client_entries =
270 net_log_observer.GetEntriesForSource(client_net_log_source);
hclam5a5ee682015-02-05 04:18:22271 EXPECT_EQ(7u, client_entries.size());
272 EXPECT_TRUE(
mikecirone8b85c432016-09-08 19:11:00273 LogContainsBeginEvent(client_entries, 0, NetLogEventType::SOCKET_ALIVE));
hclam5a5ee682015-02-05 04:18:22274 EXPECT_TRUE(
mikecirone8b85c432016-09-08 19:11:00275 LogContainsBeginEvent(client_entries, 1, NetLogEventType::UDP_CONNECT));
hclam5a5ee682015-02-05 04:18:22276 EXPECT_TRUE(
mikecirone8b85c432016-09-08 19:11:00277 LogContainsEndEvent(client_entries, 2, NetLogEventType::UDP_CONNECT));
278 EXPECT_TRUE(LogContainsEvent(client_entries, 3,
279 NetLogEventType::UDP_BYTES_SENT,
280 NetLogEventPhase::NONE));
281 EXPECT_TRUE(LogContainsEvent(client_entries, 4,
282 NetLogEventType::UDP_BYTES_RECEIVED,
283 NetLogEventPhase::NONE));
284 EXPECT_TRUE(LogContainsEvent(client_entries, 5,
285 NetLogEventType::UDP_BYTES_SENT,
286 NetLogEventPhase::NONE));
287 EXPECT_TRUE(
288 LogContainsEndEvent(client_entries, 6, NetLogEventType::SOCKET_ALIVE));
[email protected]a2798d92011-03-02 22:56:18289}
290
hclam5a5ee682015-02-05 04:18:22291TEST_F(UDPSocketTest, Connect) {
292 // The variable |use_nonblocking_io| has no effect in non-Windows ports.
Liza Burakova892ce1c2022-09-19 16:44:46293 // Run ConnectTest once with sync connect and once with async connect
294 ConnectTest(false, false);
295 ConnectTest(false, true);
hclam5a5ee682015-02-05 04:18:22296}
297
Xiaohan Wang2a6845b2022-01-08 04:40:57298#if BUILDFLAG(IS_WIN)
hclam5a5ee682015-02-05 04:18:22299TEST_F(UDPSocketTest, ConnectNonBlocking) {
Liza Burakova892ce1c2022-09-19 16:44:46300 ConnectTest(true, false);
301 ConnectTest(true, true);
hclam5a5ee682015-02-05 04:18:22302}
303#endif
304
Sergey Ulanov2d1a4272017-09-08 21:39:48305TEST_F(UDPSocketTest, PartialRecv) {
306 UDPServerSocket server_socket(nullptr, NetLogSource());
307 ASSERT_THAT(server_socket.Listen(IPEndPoint(IPAddress::IPv4Localhost(), 0)),
308 IsOk());
309 IPEndPoint server_address;
310 ASSERT_THAT(server_socket.GetLocalAddress(&server_address), IsOk());
311
Sergey Ulanovcbdfc8852018-03-16 20:13:28312 UDPClientSocket client_socket(DatagramSocket::DEFAULT_BIND, nullptr,
313 NetLogSource());
Sergey Ulanov2d1a4272017-09-08 21:39:48314 ASSERT_THAT(client_socket.Connect(server_address), IsOk());
315
316 std::string test_packet("hello world!");
317 ASSERT_EQ(static_cast<int>(test_packet.size()),
318 WriteSocket(&client_socket, test_packet));
319
320 TestCompletionCallback recv_callback;
321
322 // Read just 2 bytes. Read() is expected to return the first 2 bytes from the
323 // packet and discard the rest.
324 const int kPartialReadSize = 2;
Victor Costan9c7302b2018-08-27 16:39:44325 scoped_refptr<IOBuffer> buffer =
326 base::MakeRefCounted<IOBuffer>(kPartialReadSize);
Sergey Ulanov2d1a4272017-09-08 21:39:48327 int rv =
328 server_socket.RecvFrom(buffer.get(), kPartialReadSize,
329 &recv_from_address_, recv_callback.callback());
330 rv = recv_callback.GetResult(rv);
331
Sergey Ulanov2d1a4272017-09-08 21:39:48332 EXPECT_EQ(rv, ERR_MSG_TOO_BIG);
Sergey Ulanov2d1a4272017-09-08 21:39:48333
334 // Send a different message again.
335 std::string second_packet("Second packet");
336 ASSERT_EQ(static_cast<int>(second_packet.size()),
337 WriteSocket(&client_socket, second_packet));
338
339 // Read whole packet now.
340 std::string received = RecvFromSocket(&server_socket);
341 EXPECT_EQ(second_packet, received);
342}
343
Xiaohan Wang2a6845b2022-01-08 04:40:57344#if BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_ANDROID)
Sergey Ulanov38e18bd2017-07-28 18:59:36345// - MacOS: requires root permissions on OSX 10.7+.
346// - Android: devices attached to testbots don't have default network, so
347// broadcasting to 255.255.255.255 returns error -109 (Address not reachable).
348// crbug.com/139144.
Sergey Ulanov38e18bd2017-07-28 18:59:36349#define MAYBE_LocalBroadcast DISABLED_LocalBroadcast
[email protected]2cb83102012-09-18 19:13:01350#else
Sergey Ulanov38e18bd2017-07-28 18:59:36351#define MAYBE_LocalBroadcast LocalBroadcast
[email protected]2cb83102012-09-18 19:13:01352#endif
Sergey Ulanov38e18bd2017-07-28 18:59:36353TEST_F(UDPSocketTest, MAYBE_LocalBroadcast) {
[email protected]a1781d7b2012-07-16 11:52:34354 std::string first_message("first message"), second_message("second message");
355
[email protected]a1781d7b2012-07-16 11:52:34356 IPEndPoint listen_address;
Matt Menkebdcddfd2018-12-20 18:51:29357 ASSERT_TRUE(CreateUDPAddress("0.0.0.0", 0 /* port */, &listen_address));
[email protected]a1781d7b2012-07-16 11:52:34358
Tsuyoshi Horof8861cb2022-07-05 23:50:20359 auto server1 =
360 std::make_unique<UDPServerSocket>(NetLog::Get(), NetLogSource());
361 auto server2 =
362 std::make_unique<UDPServerSocket>(NetLog::Get(), NetLogSource());
[email protected]a1781d7b2012-07-16 11:52:34363 server1->AllowAddressReuse();
364 server1->AllowBroadcast();
365 server2->AllowAddressReuse();
366 server2->AllowBroadcast();
367
Matt Menkebdcddfd2018-12-20 18:51:29368 EXPECT_THAT(server1->Listen(listen_address), IsOk());
369 // Get bound port.
370 EXPECT_THAT(server1->GetLocalAddress(&listen_address), IsOk());
371 EXPECT_THAT(server2->Listen(listen_address), IsOk());
[email protected]a1781d7b2012-07-16 11:52:34372
Matt Menkebdcddfd2018-12-20 18:51:29373 IPEndPoint broadcast_address;
374 ASSERT_TRUE(CreateUDPAddress("127.255.255.255", listen_address.port(),
375 &broadcast_address));
376 ASSERT_EQ(static_cast<int>(first_message.size()),
377 SendToSocket(server1.get(), first_message, broadcast_address));
[email protected]a1781d7b2012-07-16 11:52:34378 std::string str = RecvFromSocket(server1.get());
379 ASSERT_EQ(first_message, str);
380 str = RecvFromSocket(server2.get());
381 ASSERT_EQ(first_message, str);
382
Matt Menkebdcddfd2018-12-20 18:51:29383 ASSERT_EQ(static_cast<int>(second_message.size()),
384 SendToSocket(server2.get(), second_message, broadcast_address));
[email protected]a1781d7b2012-07-16 11:52:34385 str = RecvFromSocket(server1.get());
386 ASSERT_EQ(second_message, str);
387 str = RecvFromSocket(server2.get());
388 ASSERT_EQ(second_message, str);
389}
390
Sergey Ulanovcbdfc8852018-03-16 20:13:28391// ConnectRandomBind verifies RANDOM_BIND is handled correctly. It connects
392// 1000 sockets and then verifies that the allocated port numbers satisfy the
393// following 2 conditions:
394// 1. Range from min port value to max is greater than 10000.
395// 2. There is at least one port in the 5 buckets in the [min, max] range.
396//
397// These conditions are not enough to verify that the port numbers are truly
398// random, but they are enough to protect from most common non-random port
399// allocation strategies (e.g. counter, pool of available ports, etc.) False
400// positive result is theoretically possible, but its probability is negligible.
Sergey Ulanovb94f28992018-05-07 18:17:12401TEST_F(UDPSocketTest, ConnectRandomBind) {
Sergey Ulanovcbdfc8852018-03-16 20:13:28402 const int kIterations = 1000;
[email protected]5370c012011-06-29 03:47:04403
Sergey Ulanovcbdfc8852018-03-16 20:13:28404 std::vector<int> used_ports;
405 for (int i = 0; i < kIterations; ++i) {
406 UDPClientSocket socket(DatagramSocket::RANDOM_BIND, nullptr,
407 NetLogSource());
408 EXPECT_THAT(socket.Connect(IPEndPoint(IPAddress::IPv4Localhost(), 53)),
409 IsOk());
[email protected]5370c012011-06-29 03:47:04410
411 IPEndPoint client_address;
Sergey Ulanovcbdfc8852018-03-16 20:13:28412 EXPECT_THAT(socket.GetLocalAddress(&client_address), IsOk());
[email protected]5370c012011-06-29 03:47:04413 used_ports.push_back(client_address.port());
414 }
415
Sergey Ulanovcbdfc8852018-03-16 20:13:28416 int min_port = *std::min_element(used_ports.begin(), used_ports.end());
417 int max_port = *std::max_element(used_ports.begin(), used_ports.end());
418 int range = max_port - min_port + 1;
[email protected]5370c012011-06-29 03:47:04419
Sergey Ulanovcbdfc8852018-03-16 20:13:28420 // Verify that the range of ports used by the random port allocator is wider
421 // than 10k. Assuming that socket implementation limits port range to 16k
422 // ports (default on Fuchsia) probability of false negative is below
423 // 10^-200.
424 static int kMinRange = 10000;
425 EXPECT_GT(range, kMinRange);
[email protected]5370c012011-06-29 03:47:04426
Sergey Ulanovcbdfc8852018-03-16 20:13:28427 static int kBuckets = 5;
428 std::vector<int> bucket_sizes(kBuckets, 0);
429 for (int port : used_ports) {
430 bucket_sizes[(port - min_port) * kBuckets / range] += 1;
431 }
[email protected]5370c012011-06-29 03:47:04432
Sergey Ulanovcbdfc8852018-03-16 20:13:28433 // Verify that there is at least one value in each bucket. Probability of
434 // false negative is below (kBuckets * (1 - 1 / kBuckets) ^ kIterations),
435 // which is less than 10^-96.
436 for (int size : bucket_sizes) {
437 EXPECT_GT(size, 0);
438 }
[email protected]5370c012011-06-29 03:47:04439}
440
Fabrice de Gans-Riberic9664662019-05-03 20:41:45441TEST_F(UDPSocketTest, ConnectFail) {
Sergey Ulanovcbdfc8852018-03-16 20:13:28442 UDPSocket socket(DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
[email protected]391de682013-02-22 22:44:44443
Sergey Ulanovcbdfc8852018-03-16 20:13:28444 EXPECT_THAT(socket.Open(ADDRESS_FAMILY_IPV4), IsOk());
445
446 // Connect to an IPv6 address should fail since the socket was created for
447 // IPv4.
448 EXPECT_THAT(socket.Connect(net::IPEndPoint(IPAddress::IPv6Localhost(), 53)),
449 Not(IsOk()));
450
[email protected]391de682013-02-22 22:44:44451 // Make sure that UDPSocket actually closed the socket.
Sergey Ulanovcbdfc8852018-03-16 20:13:28452 EXPECT_FALSE(socket.is_connected());
[email protected]391de682013-02-22 22:44:44453}
454
[email protected]a2798d92011-03-02 22:56:18455// In this test, we verify that connect() on a socket will have the effect
456// of filtering reads on this socket only to data read from the destination
457// we connected to.
458//
459// The purpose of this test is that some documentation indicates that connect
460// binds the client's sends to send to a particular server endpoint, but does
461// not bind the client's reads to only be from that endpoint, and that we need
462// to always use recvfrom() to disambiguate.
463TEST_F(UDPSocketTest, VerifyConnectBindsAddr) {
[email protected]a2798d92011-03-02 22:56:18464 std::string simple_message("hello world!");
465 std::string foreign_message("BAD MESSAGE TO GET!!");
466
467 // Setup the first server to listen.
Matt Menkebdcddfd2018-12-20 18:51:29468 IPEndPoint server1_address(IPAddress::IPv4Localhost(), 0 /* port */);
Sergey Ulanovcbdfc8852018-03-16 20:13:28469 UDPServerSocket server1(nullptr, NetLogSource());
Matt Menkebdcddfd2018-12-20 18:51:29470 ASSERT_THAT(server1.Listen(server1_address), IsOk());
471 // Get the bound port.
472 ASSERT_THAT(server1.GetLocalAddress(&server1_address), IsOk());
[email protected]a2798d92011-03-02 22:56:18473
474 // Setup the second server to listen.
Matt Menkebdcddfd2018-12-20 18:51:29475 IPEndPoint server2_address(IPAddress::IPv4Localhost(), 0 /* port */);
Sergey Ulanovcbdfc8852018-03-16 20:13:28476 UDPServerSocket server2(nullptr, NetLogSource());
Matt Menkebdcddfd2018-12-20 18:51:29477 ASSERT_THAT(server2.Listen(server2_address), IsOk());
[email protected]a2798d92011-03-02 22:56:18478
479 // Setup the client, connected to server 1.
Sergey Ulanovcbdfc8852018-03-16 20:13:28480 UDPClientSocket client(DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
Matt Menkebdcddfd2018-12-20 18:51:29481 EXPECT_THAT(client.Connect(server1_address), IsOk());
[email protected]a2798d92011-03-02 22:56:18482
483 // Client sends to server1.
Matt Menkebdcddfd2018-12-20 18:51:29484 EXPECT_EQ(simple_message.length(),
485 static_cast<size_t>(WriteSocket(&client, simple_message)));
[email protected]a2798d92011-03-02 22:56:18486
487 // Server1 waits for message.
488 std::string str = RecvFromSocket(&server1);
Sergey Ulanov38e18bd2017-07-28 18:59:36489 EXPECT_EQ(simple_message, str);
[email protected]a2798d92011-03-02 22:56:18490
491 // Get the client's address.
[email protected]43d4a0262011-03-09 19:26:04492 IPEndPoint client_address;
Matt Menkebdcddfd2018-12-20 18:51:29493 EXPECT_THAT(client.GetLocalAddress(&client_address), IsOk());
[email protected]a2798d92011-03-02 22:56:18494
495 // Server2 sends reply.
Matt Menkebdcddfd2018-12-20 18:51:29496 EXPECT_EQ(foreign_message.length(),
497 static_cast<size_t>(
498 SendToSocket(&server2, foreign_message, client_address)));
[email protected]a2798d92011-03-02 22:56:18499
500 // Server1 sends reply.
Matt Menkebdcddfd2018-12-20 18:51:29501 EXPECT_EQ(simple_message.length(),
502 static_cast<size_t>(
503 SendToSocket(&server1, simple_message, client_address)));
[email protected]a2798d92011-03-02 22:56:18504
505 // Client waits for response.
506 str = ReadSocket(&client);
Sergey Ulanov38e18bd2017-07-28 18:59:36507 EXPECT_EQ(simple_message, str);
[email protected]a2798d92011-03-02 22:56:18508}
509
ellyjones74165fa2015-08-27 16:28:05510TEST_F(UDPSocketTest, ClientGetLocalPeerAddresses) {
[email protected]a2798d92011-03-02 22:56:18511 struct TestData {
512 std::string remote_address;
513 std::string local_address;
[email protected]7b6afd02011-03-12 00:03:12514 bool may_fail;
[email protected]a2798d92011-03-02 22:56:18515 } tests[] = {
Eric Orth7141dbc2018-10-26 20:10:24516 {"127.0.00.1", "127.0.0.1", false},
517 {"::1", "::1", true},
Xiaohan Wang2a6845b2022-01-08 04:40:57518#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
[email protected]86c8e5122012-11-15 20:34:43519 // Addresses below are disabled on Android. See crbug.com/161248
ellyjones74165fa2015-08-27 16:28:05520 // They are also disabled on iOS. See https://crbug.com/523225
Eric Orth7141dbc2018-10-26 20:10:24521 {"192.168.1.1", "127.0.0.1", false},
522 {"2001:db8:0::42", "::1", true},
[email protected]86c8e5122012-11-15 20:34:43523#endif
[email protected]a2798d92011-03-02 22:56:18524 };
Tsuyoshi Horo17ef47d02022-06-30 10:58:27525 for (const auto& test : tests) {
526 SCOPED_TRACE(std::string("Connecting from ") + test.local_address +
527 std::string(" to ") + test.remote_address);
[email protected]7b6afd02011-03-12 00:03:12528
martijnd8dafab2016-03-14 18:28:49529 IPAddress ip_address;
Tsuyoshi Horo17ef47d02022-06-30 10:58:27530 EXPECT_TRUE(ip_address.AssignFromIPLiteral(test.remote_address));
martijnd8dafab2016-03-14 18:28:49531 IPEndPoint remote_address(ip_address, 80);
Tsuyoshi Horo17ef47d02022-06-30 10:58:27532 EXPECT_TRUE(ip_address.AssignFromIPLiteral(test.local_address));
martijnd8dafab2016-03-14 18:28:49533 IPEndPoint local_address(ip_address, 80);
[email protected]a2798d92011-03-02 22:56:18534
Sergey Ulanovcbdfc8852018-03-16 20:13:28535 UDPClientSocket client(DatagramSocket::DEFAULT_BIND, nullptr,
536 NetLogSource());
[email protected]a2798d92011-03-02 22:56:18537 int rv = client.Connect(remote_address);
Tsuyoshi Horo17ef47d02022-06-30 10:58:27538 if (test.may_fail && rv == ERR_ADDRESS_UNREACHABLE) {
[email protected]7b6afd02011-03-12 00:03:12539 // Connect() may return ERR_ADDRESS_UNREACHABLE for IPv6
540 // addresses if IPv6 is not configured.
541 continue;
542 }
543
[email protected]a2798d92011-03-02 22:56:18544 EXPECT_LE(ERR_IO_PENDING, rv);
545
[email protected]43d4a0262011-03-09 19:26:04546 IPEndPoint fetched_local_address;
[email protected]a2798d92011-03-02 22:56:18547 rv = client.GetLocalAddress(&fetched_local_address);
robpercival214763f2016-07-01 23:27:01548 EXPECT_THAT(rv, IsOk());
[email protected]a2798d92011-03-02 22:56:18549
[email protected]a2798d92011-03-02 22:56:18550 // TODO(mbelshe): figure out how to verify the IP and port.
551 // The port is dynamically generated by the udp stack.
552 // The IP is the real IP of the client, not necessarily
553 // loopback.
Eric Orth7141dbc2018-10-26 20:10:24554 // EXPECT_EQ(local_address.address(), fetched_local_address.address());
[email protected]a2798d92011-03-02 22:56:18555
[email protected]43d4a0262011-03-09 19:26:04556 IPEndPoint fetched_remote_address;
[email protected]a2798d92011-03-02 22:56:18557 rv = client.GetPeerAddress(&fetched_remote_address);
robpercival214763f2016-07-01 23:27:01558 EXPECT_THAT(rv, IsOk());
[email protected]a2798d92011-03-02 22:56:18559
[email protected]43d4a0262011-03-09 19:26:04560 EXPECT_EQ(remote_address, fetched_remote_address);
[email protected]a2798d92011-03-02 22:56:18561 }
562}
563
564TEST_F(UDPSocketTest, ServerGetLocalAddress) {
Sergey Ulanov2d1a4272017-09-08 21:39:48565 IPEndPoint bind_address(IPAddress::IPv4Localhost(), 0);
Raul Tambre94493c652019-03-11 17:18:35566 UDPServerSocket server(nullptr, NetLogSource());
[email protected]7b6afd02011-03-12 00:03:12567 int rv = server.Listen(bind_address);
robpercival214763f2016-07-01 23:27:01568 EXPECT_THAT(rv, IsOk());
[email protected]7b6afd02011-03-12 00:03:12569
570 IPEndPoint local_address;
571 rv = server.GetLocalAddress(&local_address);
572 EXPECT_EQ(rv, 0);
573
574 // Verify that port was allocated.
[email protected]c10d57a12011-04-05 21:36:24575 EXPECT_GT(local_address.port(), 0);
[email protected]7b6afd02011-03-12 00:03:12576 EXPECT_EQ(local_address.address(), bind_address.address());
[email protected]a2798d92011-03-02 22:56:18577}
578
579TEST_F(UDPSocketTest, ServerGetPeerAddress) {
Sergey Ulanov2d1a4272017-09-08 21:39:48580 IPEndPoint bind_address(IPAddress::IPv4Localhost(), 0);
Raul Tambre94493c652019-03-11 17:18:35581 UDPServerSocket server(nullptr, NetLogSource());
[email protected]7b6afd02011-03-12 00:03:12582 int rv = server.Listen(bind_address);
robpercival214763f2016-07-01 23:27:01583 EXPECT_THAT(rv, IsOk());
[email protected]7b6afd02011-03-12 00:03:12584
585 IPEndPoint peer_address;
586 rv = server.GetPeerAddress(&peer_address);
587 EXPECT_EQ(rv, ERR_SOCKET_NOT_CONNECTED);
588}
589
Fabrice de Gans-Riberic9664662019-05-03 20:41:45590TEST_F(UDPSocketTest, ClientSetDoNotFragment) {
rchff006a12016-08-24 23:56:31591 for (std::string ip : {"127.0.0.1", "::1"}) {
Sergey Ulanovcbdfc8852018-03-16 20:13:28592 UDPClientSocket client(DatagramSocket::DEFAULT_BIND, nullptr,
593 NetLogSource());
rchff006a12016-08-24 23:56:31594 IPAddress ip_address;
595 EXPECT_TRUE(ip_address.AssignFromIPLiteral(ip));
596 IPEndPoint remote_address(ip_address, 80);
597 int rv = client.Connect(remote_address);
598 // May fail on IPv6 is IPv6 is not configured.
599 if (ip_address.IsIPv6() && rv == ERR_ADDRESS_UNREACHABLE)
600 return;
601 EXPECT_THAT(rv, IsOk());
602
rchff006a12016-08-24 23:56:31603 rv = client.SetDoNotFragment();
Momoka Yamamotof16c5d2282022-03-16 00:20:46604#if BUILDFLAG(IS_IOS) || BUILDFLAG(IS_FUCHSIA)
Fabrice de Gans-Riberi2e8349542019-03-27 22:27:11605 // TODO(crbug.com/945590): IP_MTU_DISCOVER is not implemented on Fuchsia.
606 EXPECT_THAT(rv, IsError(ERR_NOT_IMPLEMENTED));
Momoka Yamamotof16c5d2282022-03-16 00:20:46607#elif BUILDFLAG(IS_MAC)
608 if (base::mac::IsAtLeastOS11()) {
609 EXPECT_THAT(rv, IsOk());
610 } else {
611 EXPECT_THAT(rv, IsError(ERR_NOT_IMPLEMENTED));
612 }
Fabrice de Gans-Riberi2e8349542019-03-27 22:27:11613#else
rchff006a12016-08-24 23:56:31614 EXPECT_THAT(rv, IsOk());
615#endif
616 }
617}
618
Fabrice de Gans-Riberic9664662019-05-03 20:41:45619TEST_F(UDPSocketTest, ServerSetDoNotFragment) {
rchff006a12016-08-24 23:56:31620 for (std::string ip : {"127.0.0.1", "::1"}) {
rchff006a12016-08-24 23:56:31621 IPEndPoint bind_address;
Tim Halounce5b54932018-10-08 22:34:46622 ASSERT_TRUE(CreateUDPAddress(ip, 0, &bind_address));
mikecironef22f9812016-10-04 03:40:19623 UDPServerSocket server(nullptr, NetLogSource());
rchff006a12016-08-24 23:56:31624 int rv = server.Listen(bind_address);
625 // May fail on IPv6 is IPv6 is not configure
mbjorge58d40e42017-04-12 20:43:03626 if (bind_address.address().IsIPv6() &&
627 (rv == ERR_ADDRESS_INVALID || rv == ERR_ADDRESS_UNREACHABLE))
rchff006a12016-08-24 23:56:31628 return;
629 EXPECT_THAT(rv, IsOk());
630
rchff006a12016-08-24 23:56:31631 rv = server.SetDoNotFragment();
Momoka Yamamotof16c5d2282022-03-16 00:20:46632#if BUILDFLAG(IS_IOS) || BUILDFLAG(IS_FUCHSIA)
Fabrice de Gans-Riberi2e8349542019-03-27 22:27:11633 // TODO(crbug.com/945590): IP_MTU_DISCOVER is not implemented on Fuchsia.
634 EXPECT_THAT(rv, IsError(ERR_NOT_IMPLEMENTED));
Momoka Yamamotof16c5d2282022-03-16 00:20:46635#elif BUILDFLAG(IS_MAC)
636 if (base::mac::IsAtLeastOS11()) {
637 EXPECT_THAT(rv, IsOk());
638 } else {
639 EXPECT_THAT(rv, IsError(ERR_NOT_IMPLEMENTED));
640 }
Fabrice de Gans-Riberi2e8349542019-03-27 22:27:11641#else
rchff006a12016-08-24 23:56:31642 EXPECT_THAT(rv, IsOk());
643#endif
644 }
645}
646
[email protected]7b6afd02011-03-12 00:03:12647// Close the socket while read is pending.
648TEST_F(UDPSocketTest, CloseWithPendingRead) {
Sergey Ulanov2d1a4272017-09-08 21:39:48649 IPEndPoint bind_address(IPAddress::IPv4Localhost(), 0);
Raul Tambre94493c652019-03-11 17:18:35650 UDPServerSocket server(nullptr, NetLogSource());
[email protected]7b6afd02011-03-12 00:03:12651 int rv = server.Listen(bind_address);
robpercival214763f2016-07-01 23:27:01652 EXPECT_THAT(rv, IsOk());
[email protected]7b6afd02011-03-12 00:03:12653
[email protected]83039bb2011-12-09 18:43:55654 TestCompletionCallback callback;
[email protected]7b6afd02011-03-12 00:03:12655 IPEndPoint from;
[email protected]90499482013-06-01 00:39:50656 rv = server.RecvFrom(buffer_.get(), kMaxRead, &from, callback.callback());
[email protected]7b6afd02011-03-12 00:03:12657 EXPECT_EQ(rv, ERR_IO_PENDING);
658
659 server.Close();
660
[email protected]a647bcf2011-03-14 18:33:31661 EXPECT_FALSE(callback.have_result());
[email protected]a2798d92011-03-02 22:56:18662}
663
Matt Menkebdcddfd2018-12-20 18:51:29664// Some Android devices do not support multicast.
[email protected]5f01ce22013-04-30 00:53:18665// The ones supporting multicast need WifiManager.MulitcastLock to enable it.
666// http://goo.gl/jjAk9
Xiaohan Wang2a6845b2022-01-08 04:40:57667#if !BUILDFLAG(IS_ANDROID)
Eric Orth7141dbc2018-10-26 20:10:24668TEST_F(UDPSocketTest, JoinMulticastGroup) {
thestig9d3bb0c2015-01-24 00:49:51669 const char kGroup[] = "237.132.100.17";
[email protected]5f01ce22013-04-30 00:53:18670
martijnd8dafab2016-03-14 18:28:49671 IPAddress group_ip;
672 EXPECT_TRUE(group_ip.AssignFromIPLiteral(kGroup));
Tamir Duberstein8d80e242020-09-10 19:46:06673// TODO(https://github.com/google/gvisor/issues/3839): don't guard on
674// OS_FUCHSIA.
Xiaohan Wang2a6845b2022-01-08 04:40:57675#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_FUCHSIA)
Matt Menkebdcddfd2018-12-20 18:51:29676 IPEndPoint bind_address(IPAddress::AllZeros(group_ip.size()), 0 /* port */);
Eric Orth7141dbc2018-10-26 20:10:24677#else
Matt Menkebdcddfd2018-12-20 18:51:29678 IPEndPoint bind_address(group_ip, 0 /* port */);
Xiaohan Wang2a6845b2022-01-08 04:40:57679#endif // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_FUCHSIA)
[email protected]5f01ce22013-04-30 00:53:18680
Sergey Ulanovcbdfc8852018-03-16 20:13:28681 UDPSocket socket(DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
robpercival214763f2016-07-01 23:27:01682 EXPECT_THAT(socket.Open(bind_address.GetFamily()), IsOk());
Sergey Ulanov20007f62017-10-23 20:33:54683
robpercival214763f2016-07-01 23:27:01684 EXPECT_THAT(socket.Bind(bind_address), IsOk());
685 EXPECT_THAT(socket.JoinGroup(group_ip), IsOk());
[email protected]5f01ce22013-04-30 00:53:18686 // Joining group multiple times.
687 EXPECT_NE(OK, socket.JoinGroup(group_ip));
robpercival214763f2016-07-01 23:27:01688 EXPECT_THAT(socket.LeaveGroup(group_ip), IsOk());
[email protected]5f01ce22013-04-30 00:53:18689 // Leaving group multiple times.
690 EXPECT_NE(OK, socket.LeaveGroup(group_ip));
691
692 socket.Close();
693}
694
Xiaohan Wang2a6845b2022-01-08 04:40:57695// TODO(https://crbug.com/947115): failing on device on iOS 12.2.
Lingqi Chi82b3ca82021-07-09 02:22:15696// TODO(https://crbug.com/1227554): flaky on Mac 11.
Xiaohan Wang83bdf142022-01-21 19:23:11697#if BUILDFLAG(IS_IOS) || BUILDFLAG(IS_MAC)
Misha Efimov0a611f32019-04-05 20:59:31698#define MAYBE_SharedMulticastAddress DISABLED_SharedMulticastAddress
699#else
700#define MAYBE_SharedMulticastAddress SharedMulticastAddress
701#endif
702TEST_F(UDPSocketTest, MAYBE_SharedMulticastAddress) {
Eric Orth7141dbc2018-10-26 20:10:24703 const char kGroup[] = "224.0.0.251";
704
705 IPAddress group_ip;
706 ASSERT_TRUE(group_ip.AssignFromIPLiteral(kGroup));
Tamir Duberstein8d80e242020-09-10 19:46:06707// TODO(https://github.com/google/gvisor/issues/3839): don't guard on
708// OS_FUCHSIA.
Xiaohan Wang2a6845b2022-01-08 04:40:57709#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_FUCHSIA)
Matt Menkebdcddfd2018-12-20 18:51:29710 IPEndPoint receive_address(IPAddress::AllZeros(group_ip.size()),
711 0 /* port */);
Eric Orth7141dbc2018-10-26 20:10:24712#else
Matt Menkebdcddfd2018-12-20 18:51:29713 IPEndPoint receive_address(group_ip, 0 /* port */);
Xiaohan Wang2a6845b2022-01-08 04:40:57714#endif // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_FUCHSIA)
Eric Orth7141dbc2018-10-26 20:10:24715
716 NetworkInterfaceList interfaces;
717 ASSERT_TRUE(GetNetworkList(&interfaces, 0));
Michal Zajaczkowskicca836c2021-05-11 15:01:31718 // The test fails with the Hyper-V switch interface (on the host side).
719 interfaces.erase(std::remove_if(interfaces.begin(), interfaces.end(),
720 [](const auto& iface) {
721 return iface.friendly_name.rfind(
722 "vEthernet", 0) == 0;
723 }),
724 interfaces.end());
Eric Orth7141dbc2018-10-26 20:10:24725 ASSERT_FALSE(interfaces.empty());
726
727 // Setup first receiving socket.
728 UDPServerSocket socket1(nullptr, NetLogSource());
729 socket1.AllowAddressSharingForMulticast();
730 ASSERT_THAT(socket1.SetMulticastInterface(interfaces[0].interface_index),
731 IsOk());
732 ASSERT_THAT(socket1.Listen(receive_address), IsOk());
733 ASSERT_THAT(socket1.JoinGroup(group_ip), IsOk());
Matt Menkebdcddfd2018-12-20 18:51:29734 // Get the bound port.
735 ASSERT_THAT(socket1.GetLocalAddress(&receive_address), IsOk());
Eric Orth7141dbc2018-10-26 20:10:24736
737 // Setup second receiving socket.
738 UDPServerSocket socket2(nullptr, NetLogSource());
739 socket2.AllowAddressSharingForMulticast(), IsOk();
740 ASSERT_THAT(socket2.SetMulticastInterface(interfaces[0].interface_index),
741 IsOk());
742 ASSERT_THAT(socket2.Listen(receive_address), IsOk());
743 ASSERT_THAT(socket2.JoinGroup(group_ip), IsOk());
744
745 // Setup client socket.
Matt Menkebdcddfd2018-12-20 18:51:29746 IPEndPoint send_address(group_ip, receive_address.port());
Eric Orth7141dbc2018-10-26 20:10:24747 UDPClientSocket client_socket(DatagramSocket::DEFAULT_BIND, nullptr,
748 NetLogSource());
749 ASSERT_THAT(client_socket.Connect(send_address), IsOk());
750
Yuta Hijikata101ed2a2020-11-18 07:50:39751#if !BUILDFLAG(IS_CHROMEOS_ASH)
Eric Orth7141dbc2018-10-26 20:10:24752 // Send a message via the multicast group. That message is expected be be
753 // received by both receving sockets.
754 //
755 // Skip on ChromeOS where it's known to sometimes not work.
756 // TODO(crbug.com/898964): If possible, fix and reenable.
757 const char kMessage[] = "hello!";
758 ASSERT_GE(WriteSocket(&client_socket, kMessage), 0);
759 EXPECT_EQ(kMessage, RecvFromSocket(&socket1));
760 EXPECT_EQ(kMessage, RecvFromSocket(&socket2));
Yuta Hijikata101ed2a2020-11-18 07:50:39761#endif // !BUILDFLAG(IS_CHROMEOS_ASH)
Eric Orth7141dbc2018-10-26 20:10:24762}
Xiaohan Wang2a6845b2022-01-08 04:40:57763#endif // !BUILDFLAG(IS_ANDROID)
Eric Orth7141dbc2018-10-26 20:10:24764
[email protected]5f01ce22013-04-30 00:53:18765TEST_F(UDPSocketTest, MulticastOptions) {
[email protected]5f01ce22013-04-30 00:53:18766 IPEndPoint bind_address;
Matt Menkebdcddfd2018-12-20 18:51:29767 ASSERT_TRUE(CreateUDPAddress("0.0.0.0", 0 /* port */, &bind_address));
[email protected]5f01ce22013-04-30 00:53:18768
Sergey Ulanovcbdfc8852018-03-16 20:13:28769 UDPSocket socket(DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
[email protected]5f01ce22013-04-30 00:53:18770 // Before binding.
robpercival214763f2016-07-01 23:27:01771 EXPECT_THAT(socket.SetMulticastLoopbackMode(false), IsOk());
772 EXPECT_THAT(socket.SetMulticastLoopbackMode(true), IsOk());
773 EXPECT_THAT(socket.SetMulticastTimeToLive(0), IsOk());
774 EXPECT_THAT(socket.SetMulticastTimeToLive(3), IsOk());
[email protected]5f01ce22013-04-30 00:53:18775 EXPECT_NE(OK, socket.SetMulticastTimeToLive(-1));
robpercival214763f2016-07-01 23:27:01776 EXPECT_THAT(socket.SetMulticastInterface(0), IsOk());
[email protected]5f01ce22013-04-30 00:53:18777
robpercival214763f2016-07-01 23:27:01778 EXPECT_THAT(socket.Open(bind_address.GetFamily()), IsOk());
779 EXPECT_THAT(socket.Bind(bind_address), IsOk());
[email protected]5f01ce22013-04-30 00:53:18780
[email protected]7b29dac2013-12-05 11:19:42781 EXPECT_NE(OK, socket.SetMulticastLoopbackMode(false));
782 EXPECT_NE(OK, socket.SetMulticastTimeToLive(0));
783 EXPECT_NE(OK, socket.SetMulticastInterface(0));
784
[email protected]5f01ce22013-04-30 00:53:18785 socket.Close();
786}
787
[email protected]3d2fd542014-08-12 03:07:08788// Checking that DSCP bits are set correctly is difficult,
789// but let's check that the code doesn't crash at least.
790TEST_F(UDPSocketTest, SetDSCP) {
791 // Setup the server to listen.
792 IPEndPoint bind_address;
Sergey Ulanovcbdfc8852018-03-16 20:13:28793 UDPSocket client(DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
[email protected]3d2fd542014-08-12 03:07:08794 // We need a real IP, but we won't actually send anything to it.
Tim Halounce5b54932018-10-08 22:34:46795 ASSERT_TRUE(CreateUDPAddress("8.8.8.8", 9999, &bind_address));
hidehiko17fac552014-12-08 06:02:17796 int rv = client.Open(bind_address.GetFamily());
robpercival214763f2016-07-01 23:27:01797 EXPECT_THAT(rv, IsOk());
hidehiko17fac552014-12-08 06:02:17798
799 rv = client.Connect(bind_address);
[email protected]3d2fd542014-08-12 03:07:08800 if (rv != OK) {
Sergey Ulanov2d1a4272017-09-08 21:39:48801 // Let's try localhost then.
802 bind_address = IPEndPoint(IPAddress::IPv4Localhost(), 9999);
[email protected]3d2fd542014-08-12 03:07:08803 rv = client.Connect(bind_address);
804 }
robpercival214763f2016-07-01 23:27:01805 EXPECT_THAT(rv, IsOk());
[email protected]3d2fd542014-08-12 03:07:08806
807 client.SetDiffServCodePoint(DSCP_NO_CHANGE);
808 client.SetDiffServCodePoint(DSCP_AF41);
809 client.SetDiffServCodePoint(DSCP_DEFAULT);
810 client.SetDiffServCodePoint(DSCP_CS2);
811 client.SetDiffServCodePoint(DSCP_NO_CHANGE);
812 client.SetDiffServCodePoint(DSCP_DEFAULT);
813 client.Close();
814}
815
Stefano Duoa44b1192022-01-25 15:24:59816TEST_F(UDPSocketTest, ConnectUsingNetwork) {
817 // The specific value of this address doesn't really matter, and no
818 // server needs to be running here. The test only needs to call
819 // ConnectUsingNetwork() and won't send any datagrams.
820 const IPEndPoint fake_server_address(IPAddress::IPv4Localhost(), 8080);
Stefano Duo6527ed42022-07-29 09:25:44821 const handles::NetworkHandle wrong_network_handle = 65536;
Stefano Duoa44b1192022-01-25 15:24:59822#if BUILDFLAG(IS_ANDROID)
823 NetworkChangeNotifierFactoryAndroid ncn_factory;
824 NetworkChangeNotifier::DisableForTest ncn_disable_for_test;
825 std::unique_ptr<NetworkChangeNotifier> ncn(ncn_factory.CreateInstance());
826 if (!NetworkChangeNotifier::AreNetworkHandlesSupported())
827 GTEST_SKIP() << "Network handles are required to test BindToNetwork.";
828
829 {
830 // Connecting using a not existing network should fail but not report
831 // ERR_NOT_IMPLEMENTED when network handles are supported.
832 UDPClientSocket socket(DatagramSocket::RANDOM_BIND, nullptr,
833 NetLogSource());
834 int rv =
835 socket.ConnectUsingNetwork(wrong_network_handle, fake_server_address);
836 EXPECT_NE(ERR_NOT_IMPLEMENTED, rv);
837 EXPECT_NE(OK, rv);
838 EXPECT_NE(wrong_network_handle, socket.GetBoundNetwork());
839 }
840
841 {
842 // Connecting using an existing network should succeed when
843 // NetworkChangeNotifier returns a valid default network.
844 UDPClientSocket socket(DatagramSocket::RANDOM_BIND, nullptr,
845 NetLogSource());
Stefano Duo6527ed42022-07-29 09:25:44846 const handles::NetworkHandle network_handle =
Stefano Duoa44b1192022-01-25 15:24:59847 NetworkChangeNotifier::GetDefaultNetwork();
Stefano Duo6527ed42022-07-29 09:25:44848 if (network_handle != handles::kInvalidNetworkHandle) {
Stefano Duoa44b1192022-01-25 15:24:59849 EXPECT_EQ(
850 OK, socket.ConnectUsingNetwork(network_handle, fake_server_address));
851 EXPECT_EQ(network_handle, socket.GetBoundNetwork());
852 }
853 }
854#else
855 UDPClientSocket socket(DatagramSocket::RANDOM_BIND, nullptr, NetLogSource());
856 EXPECT_EQ(
857 ERR_NOT_IMPLEMENTED,
858 socket.ConnectUsingNetwork(wrong_network_handle, fake_server_address));
859#endif // BUILDFLAG(IS_ANDROID)
860}
861
Liza Burakova892ce1c2022-09-19 16:44:46862TEST_F(UDPSocketTest, ConnectUsingNetworkAsync) {
863 // The specific value of this address doesn't really matter, and no
864 // server needs to be running here. The test only needs to call
865 // ConnectUsingNetwork() and won't send any datagrams.
866 const IPEndPoint fake_server_address(IPAddress::IPv4Localhost(), 8080);
867 const handles::NetworkHandle wrong_network_handle = 65536;
Liza Burakova892ce1c2022-09-19 16:44:46868#if BUILDFLAG(IS_ANDROID)
869 NetworkChangeNotifierFactoryAndroid ncn_factory;
870 NetworkChangeNotifier::DisableForTest ncn_disable_for_test;
871 std::unique_ptr<NetworkChangeNotifier> ncn(ncn_factory.CreateInstance());
872 if (!NetworkChangeNotifier::AreNetworkHandlesSupported())
873 GTEST_SKIP() << "Network handles are required to test BindToNetwork.";
874
875 {
876 // Connecting using a not existing network should fail but not report
877 // ERR_NOT_IMPLEMENTED when network handles are supported.
878 UDPClientSocket socket(DatagramSocket::RANDOM_BIND, nullptr,
879 NetLogSource());
Peter Kastingd07ce8b52022-09-21 23:46:47880 TestCompletionCallback callback;
Liza Burakova892ce1c2022-09-19 16:44:46881 int rv = socket.ConnectUsingNetworkAsync(
882 wrong_network_handle, fake_server_address, callback.callback());
883
884 if (rv == ERR_IO_PENDING) {
885 rv = callback.WaitForResult();
886 }
887 EXPECT_NE(ERR_NOT_IMPLEMENTED, rv);
888 EXPECT_NE(OK, rv);
Liza Burakova892ce1c2022-09-19 16:44:46889 }
890
891 {
892 // Connecting using an existing network should succeed when
893 // NetworkChangeNotifier returns a valid default network.
894 UDPClientSocket socket(DatagramSocket::RANDOM_BIND, nullptr,
895 NetLogSource());
896 TestCompletionCallback callback;
897 const handles::NetworkHandle network_handle =
898 NetworkChangeNotifier::GetDefaultNetwork();
899 if (network_handle != handles::kInvalidNetworkHandle) {
900 int rv = socket.ConnectUsingNetworkAsync(
901 network_handle, fake_server_address, callback.callback());
902 if (rv == ERR_IO_PENDING) {
903 rv = callback.WaitForResult();
904 }
905 EXPECT_EQ(OK, rv);
906 EXPECT_EQ(network_handle, socket.GetBoundNetwork());
907 }
908 }
909#else
910 UDPClientSocket socket(DatagramSocket::RANDOM_BIND, nullptr, NetLogSource());
Peter Kastingd07ce8b52022-09-21 23:46:47911 TestCompletionCallback callback;
Liza Burakova892ce1c2022-09-19 16:44:46912 EXPECT_EQ(ERR_NOT_IMPLEMENTED, socket.ConnectUsingNetworkAsync(
913 wrong_network_handle, fake_server_address,
914 callback.callback()));
915#endif // BUILDFLAG(IS_ANDROID)
916}
917
[email protected]a2798d92011-03-02 22:56:18918} // namespace
919
Xiaohan Wang2a6845b2022-01-08 04:40:57920#if BUILDFLAG(IS_WIN)
[email protected]3d2fd542014-08-12 03:07:08921
922namespace {
923
Tim Haloun66923ce2018-10-27 01:01:06924const HANDLE kFakeHandle1 = (HANDLE)12;
925const HANDLE kFakeHandle2 = (HANDLE)13;
926
Tim Halounce5b54932018-10-08 22:34:46927const QOS_FLOWID kFakeFlowId1 = (QOS_FLOWID)27;
928const QOS_FLOWID kFakeFlowId2 = (QOS_FLOWID)38;
[email protected]3d2fd542014-08-12 03:07:08929
Tim Halounce5b54932018-10-08 22:34:46930class TestUDPSocketWin : public UDPSocketWin {
931 public:
Tim Haloun66923ce2018-10-27 01:01:06932 TestUDPSocketWin(QwaveApi* qos,
Tim Halounce5b54932018-10-08 22:34:46933 DatagramSocket::BindType bind_type,
934 net::NetLog* net_log,
935 const net::NetLogSource& source)
936 : UDPSocketWin(bind_type, net_log, source), qos_(qos) {}
937
Peter Boström407869b2021-10-07 04:42:48938 TestUDPSocketWin(const TestUDPSocketWin&) = delete;
939 TestUDPSocketWin& operator=(const TestUDPSocketWin&) = delete;
940
Tim Haloun66923ce2018-10-27 01:01:06941 // Overriding GetQwaveApi causes the test class to use the injected mock
942 // QwaveApi instance instead of the singleton.
943 QwaveApi* GetQwaveApi() const override { return qos_; }
Tim Halounce5b54932018-10-08 22:34:46944
945 private:
Keishi Hattori0e45c022021-11-27 09:25:52946 raw_ptr<QwaveApi> qos_;
Tim Halounce5b54932018-10-08 22:34:46947};
948
Tim Haloun66923ce2018-10-27 01:01:06949class MockQwaveApi : public QwaveApi {
Tim Halounce5b54932018-10-08 22:34:46950 public:
Tim Haloun66923ce2018-10-27 01:01:06951 MOCK_CONST_METHOD0(qwave_supported, bool());
952 MOCK_METHOD0(OnFatalError, void());
Tim Halounce5b54932018-10-08 22:34:46953 MOCK_METHOD2(CreateHandle, BOOL(PQOS_VERSION version, PHANDLE handle));
954 MOCK_METHOD1(CloseHandle, BOOL(HANDLE handle));
Tim Halounce5b54932018-10-08 22:34:46955 MOCK_METHOD6(AddSocketToFlow,
956 BOOL(HANDLE handle,
957 SOCKET socket,
958 PSOCKADDR addr,
959 QOS_TRAFFIC_TYPE traffic_type,
960 DWORD flags,
961 PQOS_FLOWID flow_id));
962
963 MOCK_METHOD4(
964 RemoveSocketFromFlow,
965 BOOL(HANDLE handle, SOCKET socket, QOS_FLOWID flow_id, DWORD reserved));
966 MOCK_METHOD7(SetFlow,
967 BOOL(HANDLE handle,
968 QOS_FLOWID flow_id,
969 QOS_SET_FLOW op,
970 ULONG size,
971 PVOID data,
972 DWORD reserved,
973 LPOVERLAPPED overlapped));
974};
975
Tim Haloun66923ce2018-10-27 01:01:06976std::unique_ptr<UDPSocket> OpenedDscpTestClient(QwaveApi* api,
Tim Halounce5b54932018-10-08 22:34:46977 IPEndPoint bind_address) {
978 auto client = std::make_unique<TestUDPSocketWin>(
Tim Haloun66923ce2018-10-27 01:01:06979 api, DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
Tim Halounce5b54932018-10-08 22:34:46980 int rv = client->Open(bind_address.GetFamily());
981 EXPECT_THAT(rv, IsOk());
982
983 return client;
[email protected]3d2fd542014-08-12 03:07:08984}
985
Tim Haloun66923ce2018-10-27 01:01:06986std::unique_ptr<UDPSocket> ConnectedDscpTestClient(QwaveApi* api) {
Tim Halounce5b54932018-10-08 22:34:46987 IPEndPoint bind_address;
988 // We need a real IP, but we won't actually send anything to it.
989 EXPECT_TRUE(CreateUDPAddress("8.8.8.8", 9999, &bind_address));
Tim Haloun66923ce2018-10-27 01:01:06990 auto client = OpenedDscpTestClient(api, bind_address);
Tim Halounce5b54932018-10-08 22:34:46991 EXPECT_THAT(client->Connect(bind_address), IsOk());
992 return client;
[email protected]3d2fd542014-08-12 03:07:08993}
994
Tim Haloun66923ce2018-10-27 01:01:06995std::unique_ptr<UDPSocket> UnconnectedDscpTestClient(QwaveApi* api) {
Tim Halounce5b54932018-10-08 22:34:46996 IPEndPoint bind_address;
997 EXPECT_TRUE(CreateUDPAddress("0.0.0.0", 9999, &bind_address));
Tim Haloun66923ce2018-10-27 01:01:06998 auto client = OpenedDscpTestClient(api, bind_address);
Tim Halounce5b54932018-10-08 22:34:46999 EXPECT_THAT(client->Bind(bind_address), IsOk());
1000 return client;
[email protected]3d2fd542014-08-12 03:07:081001}
1002
1003} // namespace
1004
Tim Halounce5b54932018-10-08 22:34:461005using ::testing::Return;
1006using ::testing::SetArgPointee;
Eric Orth7141dbc2018-10-26 20:10:241007using ::testing::_;
hidehiko17fac552014-12-08 06:02:171008
Tim Halounce5b54932018-10-08 22:34:461009TEST_F(UDPSocketTest, SetDSCPNoopIfPassedNoChange) {
Tim Haloun66923ce2018-10-27 01:01:061010 MockQwaveApi api;
1011 EXPECT_CALL(api, qwave_supported()).WillRepeatedly(Return(true));
1012
1013 EXPECT_CALL(api, AddSocketToFlow(_, _, _, _, _, _)).Times(0);
1014 std::unique_ptr<UDPSocket> client = ConnectedDscpTestClient(&api);
Tim Halounce5b54932018-10-08 22:34:461015 EXPECT_THAT(client->SetDiffServCodePoint(DSCP_NO_CHANGE), IsOk());
1016}
hidehiko17fac552014-12-08 06:02:171017
Tim Haloun66923ce2018-10-27 01:01:061018TEST_F(UDPSocketTest, SetDSCPFailsIfQOSDoesntLink) {
1019 MockQwaveApi api;
1020 EXPECT_CALL(api, qwave_supported()).WillRepeatedly(Return(false));
1021 EXPECT_CALL(api, CreateHandle(_, _)).Times(0);
[email protected]3d2fd542014-08-12 03:07:081022
Tim Haloun66923ce2018-10-27 01:01:061023 std::unique_ptr<UDPSocket> client = ConnectedDscpTestClient(&api);
1024 EXPECT_EQ(ERR_NOT_IMPLEMENTED, client->SetDiffServCodePoint(DSCP_AF41));
1025}
1026
1027TEST_F(UDPSocketTest, SetDSCPFailsIfHandleCantBeCreated) {
1028 MockQwaveApi api;
1029 EXPECT_CALL(api, qwave_supported()).WillRepeatedly(Return(true));
1030 EXPECT_CALL(api, CreateHandle(_, _)).WillOnce(Return(false));
1031 EXPECT_CALL(api, OnFatalError()).Times(1);
1032
1033 std::unique_ptr<UDPSocket> client = ConnectedDscpTestClient(&api);
1034 EXPECT_EQ(ERR_INVALID_HANDLE, client->SetDiffServCodePoint(DSCP_AF41));
1035
1036 RunUntilIdle();
1037
1038 EXPECT_CALL(api, qwave_supported()).WillRepeatedly(Return(false));
Tim Halounce5b54932018-10-08 22:34:461039 EXPECT_EQ(ERR_NOT_IMPLEMENTED, client->SetDiffServCodePoint(DSCP_AF41));
1040}
[email protected]3d2fd542014-08-12 03:07:081041
Tim Halounce5b54932018-10-08 22:34:461042MATCHER_P(DscpPointee, dscp, "") {
1043 return *(DWORD*)arg == (DWORD)dscp;
1044}
1045
Tim Haloun66923ce2018-10-27 01:01:061046TEST_F(UDPSocketTest, ConnectedSocketDelayedInitAndUpdate) {
1047 MockQwaveApi api;
1048 std::unique_ptr<UDPSocket> client = ConnectedDscpTestClient(&api);
1049 EXPECT_CALL(api, qwave_supported()).WillRepeatedly(Return(true));
1050 EXPECT_CALL(api, CreateHandle(_, _))
1051 .WillOnce(DoAll(SetArgPointee<1>(kFakeHandle1), Return(true)));
Tim Halounce5b54932018-10-08 22:34:461052
Tim Haloun66923ce2018-10-27 01:01:061053 EXPECT_CALL(api, AddSocketToFlow(_, _, _, _, _, _))
Tim Halounce5b54932018-10-08 22:34:461054 .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId1), Return(true)));
Tim Haloun66923ce2018-10-27 01:01:061055 EXPECT_CALL(api, SetFlow(_, _, _, _, _, _, _));
1056
1057 // First set on connected sockets will fail since init is async and
1058 // we haven't given the runloop a chance to execute the callback.
1059 EXPECT_EQ(ERR_INVALID_HANDLE, client->SetDiffServCodePoint(DSCP_AF41));
1060 RunUntilIdle();
Tim Halounce5b54932018-10-08 22:34:461061 EXPECT_THAT(client->SetDiffServCodePoint(DSCP_AF41), IsOk());
1062
1063 // New dscp value should reset the flow.
Tim Haloun66923ce2018-10-27 01:01:061064 EXPECT_CALL(api, RemoveSocketFromFlow(_, _, kFakeFlowId1, _));
1065 EXPECT_CALL(api, AddSocketToFlow(_, _, _, QOSTrafficTypeBestEffort, _, _))
Tim Halounce5b54932018-10-08 22:34:461066 .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId2), Return(true)));
Tim Haloun66923ce2018-10-27 01:01:061067 EXPECT_CALL(api, SetFlow(_, _, QOSSetOutgoingDSCPValue, _,
Tim Halounce5b54932018-10-08 22:34:461068 DscpPointee(DSCP_DEFAULT), _, _));
1069 EXPECT_THAT(client->SetDiffServCodePoint(DSCP_DEFAULT), IsOk());
1070
1071 // Called from DscpManager destructor.
Tim Haloun66923ce2018-10-27 01:01:061072 EXPECT_CALL(api, RemoveSocketFromFlow(_, _, kFakeFlowId2, _));
1073 EXPECT_CALL(api, CloseHandle(kFakeHandle1));
1074}
1075
1076TEST_F(UDPSocketTest, UnonnectedSocketDelayedInitAndUpdate) {
1077 MockQwaveApi api;
1078 EXPECT_CALL(api, qwave_supported()).WillRepeatedly(Return(true));
1079 EXPECT_CALL(api, CreateHandle(_, _))
1080 .WillOnce(DoAll(SetArgPointee<1>(kFakeHandle1), Return(true)));
1081
1082 // CreateHandle won't have completed yet. Set passes.
1083 std::unique_ptr<UDPSocket> client = UnconnectedDscpTestClient(&api);
1084 EXPECT_THAT(client->SetDiffServCodePoint(DSCP_AF41), IsOk());
1085
1086 RunUntilIdle();
1087 EXPECT_THAT(client->SetDiffServCodePoint(DSCP_AF42), IsOk());
1088
1089 // Called from DscpManager destructor.
1090 EXPECT_CALL(api, CloseHandle(kFakeHandle1));
Tim Halounce5b54932018-10-08 22:34:461091}
1092
1093// TODO(zstein): Mocking out DscpManager might be simpler here
1094// (just verify that DscpManager::Set and DscpManager::PrepareForSend are
1095// called).
1096TEST_F(UDPSocketTest, SendToCallsQwaveApis) {
Tim Haloun66923ce2018-10-27 01:01:061097 MockQwaveApi api;
1098 std::unique_ptr<UDPSocket> client = UnconnectedDscpTestClient(&api);
1099 EXPECT_CALL(api, qwave_supported()).WillRepeatedly(Return(true));
1100 EXPECT_CALL(api, CreateHandle(_, _))
1101 .WillOnce(DoAll(SetArgPointee<1>(kFakeHandle1), Return(true)));
Tim Halounce5b54932018-10-08 22:34:461102 EXPECT_THAT(client->SetDiffServCodePoint(DSCP_AF41), IsOk());
Tim Haloun66923ce2018-10-27 01:01:061103 RunUntilIdle();
Tim Halounce5b54932018-10-08 22:34:461104
Tim Haloun66923ce2018-10-27 01:01:061105 EXPECT_CALL(api, AddSocketToFlow(_, _, _, _, _, _))
Tim Halounce5b54932018-10-08 22:34:461106 .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId1), Return(true)));
Tim Haloun66923ce2018-10-27 01:01:061107 EXPECT_CALL(api, SetFlow(_, _, _, _, _, _, _));
Tim Halounce5b54932018-10-08 22:34:461108 std::string simple_message("hello world");
1109 IPEndPoint server_address(IPAddress::IPv4Localhost(), 9438);
1110 int rv = SendToSocket(client.get(), simple_message, server_address);
1111 EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
1112
1113 // TODO(zstein): Move to second test case (Qwave APIs called once per address)
1114 rv = SendToSocket(client.get(), simple_message, server_address);
1115 EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
1116
1117 // TODO(zstein): Move to third test case (Qwave APIs called for each
1118 // destination address).
Tim Haloun66923ce2018-10-27 01:01:061119 EXPECT_CALL(api, AddSocketToFlow(_, _, _, _, _, _)).WillOnce(Return(true));
Tim Halounce5b54932018-10-08 22:34:461120 IPEndPoint server_address2(IPAddress::IPv4Localhost(), 9439);
1121
1122 rv = SendToSocket(client.get(), simple_message, server_address2);
1123 EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
1124
1125 // Called from DscpManager destructor.
Tim Haloun66923ce2018-10-27 01:01:061126 EXPECT_CALL(api, RemoveSocketFromFlow(_, _, _, _));
1127 EXPECT_CALL(api, CloseHandle(kFakeHandle1));
Tim Halounce5b54932018-10-08 22:34:461128}
1129
Tim Haloun66923ce2018-10-27 01:01:061130TEST_F(UDPSocketTest, SendToCallsApisAfterDeferredInit) {
1131 MockQwaveApi api;
1132 std::unique_ptr<UDPSocket> client = UnconnectedDscpTestClient(&api);
1133 EXPECT_CALL(api, qwave_supported()).WillRepeatedly(Return(true));
1134 EXPECT_CALL(api, CreateHandle(_, _))
1135 .WillOnce(DoAll(SetArgPointee<1>(kFakeHandle1), Return(true)));
1136
1137 // SetDiffServCodepoint works even if qos api hasn't finished initing.
1138 EXPECT_THAT(client->SetDiffServCodePoint(DSCP_CS7), IsOk());
1139
1140 std::string simple_message("hello world");
1141 IPEndPoint server_address(IPAddress::IPv4Localhost(), 9438);
1142
1143 // SendTo works, but doesn't yet apply TOS
1144 EXPECT_CALL(api, AddSocketToFlow(_, _, _, _, _, _)).Times(0);
1145 int rv = SendToSocket(client.get(), simple_message, server_address);
1146 EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
1147
1148 RunUntilIdle();
1149 // Now we're initialized, SendTo triggers qos calls with correct codepoint.
1150 EXPECT_CALL(api, AddSocketToFlow(_, _, _, QOSTrafficTypeControl, _, _))
1151 .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId1), Return(true)));
1152 EXPECT_CALL(api, SetFlow(_, _, _, _, _, _, _)).WillOnce(Return(true));
1153 rv = SendToSocket(client.get(), simple_message, server_address);
1154 EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
1155
1156 // Called from DscpManager destructor.
1157 EXPECT_CALL(api, RemoveSocketFromFlow(_, _, kFakeFlowId1, _));
1158 EXPECT_CALL(api, CloseHandle(kFakeHandle1));
1159}
1160
Gabriel Charette694c3c332019-08-19 14:53:051161class DscpManagerTest : public TestWithTaskEnvironment {
Tim Halounce5b54932018-10-08 22:34:461162 protected:
Tim Haloun66923ce2018-10-27 01:01:061163 DscpManagerTest() {
1164 EXPECT_CALL(api_, qwave_supported()).WillRepeatedly(Return(true));
1165 EXPECT_CALL(api_, CreateHandle(_, _))
1166 .WillOnce(DoAll(SetArgPointee<1>(kFakeHandle1), Return(true)));
1167 dscp_manager_ = std::make_unique<DscpManager>(&api_, INVALID_SOCKET);
1168
Tim Halounce5b54932018-10-08 22:34:461169 CreateUDPAddress("1.2.3.4", 9001, &address1_);
1170 CreateUDPAddress("1234:5678:90ab:cdef:1234:5678:90ab:cdef", 9002,
1171 &address2_);
1172 }
1173
Tim Haloun66923ce2018-10-27 01:01:061174 MockQwaveApi api_;
1175 std::unique_ptr<DscpManager> dscp_manager_;
Tim Halounce5b54932018-10-08 22:34:461176
1177 IPEndPoint address1_;
1178 IPEndPoint address2_;
1179};
1180
1181TEST_F(DscpManagerTest, PrepareForSendIsNoopIfNoSet) {
Tim Haloun66923ce2018-10-27 01:01:061182 RunUntilIdle();
1183 dscp_manager_->PrepareForSend(address1_);
Tim Halounce5b54932018-10-08 22:34:461184}
1185
1186TEST_F(DscpManagerTest, PrepareForSendCallsQwaveApisAfterSet) {
Tim Haloun66923ce2018-10-27 01:01:061187 RunUntilIdle();
1188 dscp_manager_->Set(DSCP_CS2);
Tim Halounce5b54932018-10-08 22:34:461189
1190 // AddSocketToFlow should be called for each address.
Tim Halounce5b54932018-10-08 22:34:461191 // SetFlow should only be called when the flow is first created.
Tim Haloun66923ce2018-10-27 01:01:061192 EXPECT_CALL(api_, AddSocketToFlow(_, _, _, _, _, _))
1193 .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId1), Return(true)));
1194 EXPECT_CALL(api_, SetFlow(_, kFakeFlowId1, _, _, _, _, _));
1195 dscp_manager_->PrepareForSend(address1_);
1196
1197 EXPECT_CALL(api_, AddSocketToFlow(_, _, _, _, _, _))
1198 .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId1), Return(true)));
1199 EXPECT_CALL(api_, SetFlow(_, _, _, _, _, _, _)).Times(0);
1200 dscp_manager_->PrepareForSend(address2_);
Tim Halounce5b54932018-10-08 22:34:461201
1202 // Called from DscpManager destructor.
Tim Haloun66923ce2018-10-27 01:01:061203 EXPECT_CALL(api_, RemoveSocketFromFlow(_, _, kFakeFlowId1, _));
1204 EXPECT_CALL(api_, CloseHandle(kFakeHandle1));
Tim Halounce5b54932018-10-08 22:34:461205}
1206
1207TEST_F(DscpManagerTest, PrepareForSendCallsQwaveApisOncePerAddress) {
Tim Haloun66923ce2018-10-27 01:01:061208 RunUntilIdle();
1209 dscp_manager_->Set(DSCP_CS2);
Tim Halounce5b54932018-10-08 22:34:461210
Tim Haloun66923ce2018-10-27 01:01:061211 EXPECT_CALL(api_, AddSocketToFlow(_, _, _, _, _, _))
Tim Halounce5b54932018-10-08 22:34:461212 .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId1), Return(true)));
Tim Haloun66923ce2018-10-27 01:01:061213 EXPECT_CALL(api_, SetFlow(_, kFakeFlowId1, _, _, _, _, _));
1214 dscp_manager_->PrepareForSend(address1_);
1215 EXPECT_CALL(api_, AddSocketToFlow(_, _, _, _, _, _)).Times(0);
1216 EXPECT_CALL(api_, SetFlow(_, _, _, _, _, _, _)).Times(0);
1217 dscp_manager_->PrepareForSend(address1_);
Tim Halounce5b54932018-10-08 22:34:461218
1219 // Called from DscpManager destructor.
Tim Haloun66923ce2018-10-27 01:01:061220 EXPECT_CALL(api_, RemoveSocketFromFlow(_, _, kFakeFlowId1, _));
1221 EXPECT_CALL(api_, CloseHandle(kFakeHandle1));
Tim Halounce5b54932018-10-08 22:34:461222}
1223
Tim Haloun66923ce2018-10-27 01:01:061224TEST_F(DscpManagerTest, SetDestroysExistingFlow) {
1225 RunUntilIdle();
1226 dscp_manager_->Set(DSCP_CS2);
1227
1228 EXPECT_CALL(api_, AddSocketToFlow(_, _, _, _, _, _))
Tim Halounce5b54932018-10-08 22:34:461229 .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId1), Return(true)));
Tim Haloun66923ce2018-10-27 01:01:061230 EXPECT_CALL(api_, SetFlow(_, kFakeFlowId1, _, _, _, _, _));
1231 dscp_manager_->PrepareForSend(address1_);
Tim Halounce5b54932018-10-08 22:34:461232
1233 // Calling Set should destroy the existing flow.
1234 // TODO(zstein): Verify that RemoveSocketFromFlow with no address
1235 // destroys the flow for all destinations.
Tim Haloun66923ce2018-10-27 01:01:061236 EXPECT_CALL(api_, RemoveSocketFromFlow(_, NULL, kFakeFlowId1, _));
1237 dscp_manager_->Set(DSCP_CS5);
Tim Halounce5b54932018-10-08 22:34:461238
Tim Haloun66923ce2018-10-27 01:01:061239 EXPECT_CALL(api_, AddSocketToFlow(_, _, _, _, _, _))
Tim Halounce5b54932018-10-08 22:34:461240 .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId2), Return(true)));
Tim Haloun66923ce2018-10-27 01:01:061241 EXPECT_CALL(api_, SetFlow(_, kFakeFlowId2, _, _, _, _, _));
1242 dscp_manager_->PrepareForSend(address1_);
Tim Halounce5b54932018-10-08 22:34:461243
1244 // Called from DscpManager destructor.
Tim Haloun66923ce2018-10-27 01:01:061245 EXPECT_CALL(api_, RemoveSocketFromFlow(_, _, kFakeFlowId2, _));
1246 EXPECT_CALL(api_, CloseHandle(kFakeHandle1));
[email protected]3d2fd542014-08-12 03:07:081247}
Tim Haloun66923ce2018-10-27 01:01:061248
1249TEST_F(DscpManagerTest, SocketReAddedOnRecreateHandle) {
1250 RunUntilIdle();
1251 dscp_manager_->Set(DSCP_CS2);
1252
1253 // First Set and Send work fine.
1254 EXPECT_CALL(api_, AddSocketToFlow(_, _, _, _, _, _))
1255 .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId1), Return(true)));
1256 EXPECT_CALL(api_, SetFlow(_, kFakeFlowId1, _, _, _, _, _))
1257 .WillOnce(Return(true));
1258 EXPECT_THAT(dscp_manager_->PrepareForSend(address1_), IsOk());
1259
1260 // Make Second flow operation fail (requires resetting the codepoint).
1261 EXPECT_CALL(api_, RemoveSocketFromFlow(_, _, kFakeFlowId1, _))
1262 .WillOnce(Return(true));
1263 dscp_manager_->Set(DSCP_CS7);
1264
Joshua Perazab427af262020-04-13 21:54:421265 auto error = std::make_unique<base::ScopedClearLastError>();
Tim Haloun66923ce2018-10-27 01:01:061266 ::SetLastError(ERROR_DEVICE_REINITIALIZATION_NEEDED);
1267 EXPECT_CALL(api_, AddSocketToFlow(_, _, _, _, _, _)).WillOnce(Return(false));
1268 EXPECT_CALL(api_, SetFlow(_, _, _, _, _, _, _)).Times(0);
1269 EXPECT_CALL(api_, CloseHandle(kFakeHandle1));
1270 EXPECT_CALL(api_, CreateHandle(_, _))
1271 .WillOnce(DoAll(SetArgPointee<1>(kFakeHandle2), Return(true)));
1272 EXPECT_EQ(ERR_INVALID_HANDLE, dscp_manager_->PrepareForSend(address1_));
1273 error = nullptr;
1274 RunUntilIdle();
1275
1276 // Next Send should work fine, without requiring another Set
1277 EXPECT_CALL(api_, AddSocketToFlow(_, _, _, QOSTrafficTypeControl, _, _))
1278 .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId2), Return(true)));
1279 EXPECT_CALL(api_, SetFlow(_, kFakeFlowId2, _, _, _, _, _))
1280 .WillOnce(Return(true));
1281 EXPECT_THAT(dscp_manager_->PrepareForSend(address1_), IsOk());
1282
1283 // Called from DscpManager destructor.
1284 EXPECT_CALL(api_, RemoveSocketFromFlow(_, _, kFakeFlowId2, _));
1285 EXPECT_CALL(api_, CloseHandle(kFakeHandle2));
1286}
1287
[email protected]3d2fd542014-08-12 03:07:081288#endif
1289
kapishnikov7f8dd1e2018-01-24 06:10:491290TEST_F(UDPSocketTest, ReadWithSocketOptimization) {
kapishnikov7f8dd1e2018-01-24 06:10:491291 std::string simple_message("hello world!");
1292
1293 // Setup the server to listen.
Matt Menkebdcddfd2018-12-20 18:51:291294 IPEndPoint server_address(IPAddress::IPv4Localhost(), 0 /* port */);
Raul Tambre94493c652019-03-11 17:18:351295 UDPServerSocket server(nullptr, NetLogSource());
kapishnikov7f8dd1e2018-01-24 06:10:491296 server.AllowAddressReuse();
Matt Menkebdcddfd2018-12-20 18:51:291297 ASSERT_THAT(server.Listen(server_address), IsOk());
1298 // Get bound port.
1299 ASSERT_THAT(server.GetLocalAddress(&server_address), IsOk());
kapishnikov7f8dd1e2018-01-24 06:10:491300
1301 // Setup the client, enable experimental optimization and connected to the
1302 // server.
Sergey Ulanovcbdfc8852018-03-16 20:13:281303 UDPClientSocket client(DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
kapishnikov7f8dd1e2018-01-24 06:10:491304 client.EnableRecvOptimization();
Matt Menkebdcddfd2018-12-20 18:51:291305 EXPECT_THAT(client.Connect(server_address), IsOk());
kapishnikov7f8dd1e2018-01-24 06:10:491306
1307 // Get the client's address.
1308 IPEndPoint client_address;
Matt Menkebdcddfd2018-12-20 18:51:291309 EXPECT_THAT(client.GetLocalAddress(&client_address), IsOk());
kapishnikov7f8dd1e2018-01-24 06:10:491310
1311 // Server sends the message to the client.
Matt Menkebdcddfd2018-12-20 18:51:291312 EXPECT_EQ(simple_message.length(),
1313 static_cast<size_t>(
1314 SendToSocket(&server, simple_message, client_address)));
kapishnikov7f8dd1e2018-01-24 06:10:491315
1316 // Client receives the message.
1317 std::string str = ReadSocket(&client);
1318 EXPECT_EQ(simple_message, str);
1319
1320 server.Close();
1321 client.Close();
1322}
1323
1324// Tests that read from a socket correctly returns
1325// |ERR_MSG_TOO_BIG| when the buffer is too small and
1326// returns the actual message when it fits the buffer.
1327// For the optimized path, the buffer size should be at least
1328// 1 byte greater than the message.
1329TEST_F(UDPSocketTest, ReadWithSocketOptimizationTruncation) {
kapishnikov7f8dd1e2018-01-24 06:10:491330 std::string too_long_message(kMaxRead + 1, 'A');
1331 std::string right_length_message(kMaxRead - 1, 'B');
1332 std::string exact_length_message(kMaxRead, 'C');
1333
1334 // Setup the server to listen.
Matt Menkebdcddfd2018-12-20 18:51:291335 IPEndPoint server_address(IPAddress::IPv4Localhost(), 0 /* port */);
Raul Tambre94493c652019-03-11 17:18:351336 UDPServerSocket server(nullptr, NetLogSource());
kapishnikov7f8dd1e2018-01-24 06:10:491337 server.AllowAddressReuse();
Matt Menkebdcddfd2018-12-20 18:51:291338 ASSERT_THAT(server.Listen(server_address), IsOk());
1339 // Get bound port.
1340 ASSERT_THAT(server.GetLocalAddress(&server_address), IsOk());
kapishnikov7f8dd1e2018-01-24 06:10:491341
1342 // Setup the client, enable experimental optimization and connected to the
1343 // server.
Sergey Ulanovcbdfc8852018-03-16 20:13:281344 UDPClientSocket client(DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
kapishnikov7f8dd1e2018-01-24 06:10:491345 client.EnableRecvOptimization();
Matt Menkebdcddfd2018-12-20 18:51:291346 EXPECT_THAT(client.Connect(server_address), IsOk());
kapishnikov7f8dd1e2018-01-24 06:10:491347
1348 // Get the client's address.
1349 IPEndPoint client_address;
Matt Menkebdcddfd2018-12-20 18:51:291350 EXPECT_THAT(client.GetLocalAddress(&client_address), IsOk());
kapishnikov7f8dd1e2018-01-24 06:10:491351
1352 // Send messages to the client.
Matt Menkebdcddfd2018-12-20 18:51:291353 EXPECT_EQ(too_long_message.length(),
1354 static_cast<size_t>(
1355 SendToSocket(&server, too_long_message, client_address)));
1356 EXPECT_EQ(right_length_message.length(),
1357 static_cast<size_t>(
1358 SendToSocket(&server, right_length_message, client_address)));
1359 EXPECT_EQ(exact_length_message.length(),
1360 static_cast<size_t>(
1361 SendToSocket(&server, exact_length_message, client_address)));
kapishnikov7f8dd1e2018-01-24 06:10:491362
1363 // Client receives the messages.
1364
1365 // 1. The first message is |too_long_message|. Its size exceeds the buffer.
1366 // In that case, the client is expected to get |ERR_MSG_TOO_BIG| when the
1367 // data is read.
1368 TestCompletionCallback callback;
Matt Menkebdcddfd2018-12-20 18:51:291369 int rv = client.Read(buffer_.get(), kMaxRead, callback.callback());
1370 EXPECT_EQ(ERR_MSG_TOO_BIG, callback.GetResult(rv));
kapishnikov7f8dd1e2018-01-24 06:10:491371
1372 // 2. The second message is |right_length_message|. Its size is
1373 // one byte smaller than the size of the buffer. In that case, the client
1374 // is expected to read the whole message successfully.
1375 rv = client.Read(buffer_.get(), kMaxRead, callback.callback());
1376 rv = callback.GetResult(rv);
1377 EXPECT_EQ(static_cast<int>(right_length_message.length()), rv);
1378 EXPECT_EQ(right_length_message, std::string(buffer_->data(), rv));
1379
1380 // 3. The third message is |exact_length_message|. Its size is equal to
1381 // the read buffer size. In that case, the client expects to get
1382 // |ERR_MSG_TOO_BIG| when the socket is read. Internally, the optimized
1383 // path uses read() system call that requires one extra byte to detect
1384 // truncated messages; therefore, messages that fill the buffer exactly
1385 // are considered truncated.
1386 // The optimization is only enabled on POSIX platforms. On Windows,
1387 // the optimization is turned off; therefore, the client
1388 // should be able to read the whole message without encountering
1389 // |ERR_MSG_TOO_BIG|.
1390 rv = client.Read(buffer_.get(), kMaxRead, callback.callback());
1391 rv = callback.GetResult(rv);
Xiaohan Wang2a6845b2022-01-08 04:40:571392#if BUILDFLAG(IS_POSIX)
kapishnikov7f8dd1e2018-01-24 06:10:491393 EXPECT_EQ(ERR_MSG_TOO_BIG, rv);
1394#else
1395 EXPECT_EQ(static_cast<int>(exact_length_message.length()), rv);
1396 EXPECT_EQ(exact_length_message, std::string(buffer_->data(), rv));
1397#endif
1398 server.Close();
1399 client.Close();
1400}
1401
Paul Jensen0f49dec2017-12-12 23:39:581402// On Android, where socket tagging is supported, verify that UDPSocket::Tag
1403// works as expected.
Xiaohan Wang2a6845b2022-01-08 04:40:571404#if BUILDFLAG(IS_ANDROID)
Paul Jensen0f49dec2017-12-12 23:39:581405TEST_F(UDPSocketTest, Tag) {
Peter Collingbourne8ccab722019-02-12 18:10:481406 if (!CanGetTaggedBytes()) {
1407 DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
1408 return;
1409 }
1410
Paul Jensen0f49dec2017-12-12 23:39:581411 UDPServerSocket server(nullptr, NetLogSource());
1412 ASSERT_THAT(server.Listen(IPEndPoint(IPAddress::IPv4Localhost(), 0)), IsOk());
1413 IPEndPoint server_address;
1414 ASSERT_THAT(server.GetLocalAddress(&server_address), IsOk());
1415
Sergey Ulanovcbdfc8852018-03-16 20:13:281416 UDPClientSocket client(DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
Paul Jensen0f49dec2017-12-12 23:39:581417 ASSERT_THAT(client.Connect(server_address), IsOk());
1418
1419 // Verify UDP packets are tagged and counted properly.
1420 int32_t tag_val1 = 0x12345678;
1421 uint64_t old_traffic = GetTaggedBytes(tag_val1);
1422 SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
1423 client.ApplySocketTag(tag1);
1424 // Client sends to the server.
1425 std::string simple_message("hello world!");
1426 int rv = WriteSocket(&client, simple_message);
1427 EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
1428 // Server waits for message.
1429 std::string str = RecvFromSocket(&server);
1430 EXPECT_EQ(simple_message, str);
1431 // Server echoes reply.
1432 rv = SendToSocket(&server, simple_message);
1433 EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
1434 // Client waits for response.
1435 str = ReadSocket(&client);
1436 EXPECT_EQ(simple_message, str);
1437 EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
1438
1439 // Verify socket can be retagged with a new value and the current process's
1440 // UID.
1441 int32_t tag_val2 = 0x87654321;
1442 old_traffic = GetTaggedBytes(tag_val2);
1443 SocketTag tag2(getuid(), tag_val2);
1444 client.ApplySocketTag(tag2);
1445 // Client sends to the server.
1446 rv = WriteSocket(&client, simple_message);
1447 EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
1448 // Server waits for message.
1449 str = RecvFromSocket(&server);
1450 EXPECT_EQ(simple_message, str);
1451 // Server echoes reply.
1452 rv = SendToSocket(&server, simple_message);
1453 EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
1454 // Client waits for response.
1455 str = ReadSocket(&client);
1456 EXPECT_EQ(simple_message, str);
1457 EXPECT_GT(GetTaggedBytes(tag_val2), old_traffic);
1458
1459 // Verify socket can be retagged with a new value and the current process's
1460 // UID.
1461 old_traffic = GetTaggedBytes(tag_val1);
1462 client.ApplySocketTag(tag1);
1463 // Client sends to the server.
1464 rv = WriteSocket(&client, simple_message);
1465 EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
1466 // Server waits for message.
1467 str = RecvFromSocket(&server);
1468 EXPECT_EQ(simple_message, str);
1469 // Server echoes reply.
1470 rv = SendToSocket(&server, simple_message);
1471 EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
1472 // Client waits for response.
1473 str = ReadSocket(&client);
1474 EXPECT_EQ(simple_message, str);
1475 EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
1476}
Kenichi Ishibashi08c3ea12021-12-09 08:23:461477
1478TEST_F(UDPSocketTest, RecordRadioWakeUpTrigger) {
1479 base::test::ScopedFeatureList feature_list;
1480 feature_list.InitAndEnableFeature(features::kRecordRadioWakeupTrigger);
1481
1482 base::HistogramTester histograms;
1483
1484 // Simulates the radio state is dormant.
1485 android::RadioActivityTracker::GetInstance().OverrideRadioActivityForTesting(
1486 base::android::RadioDataActivity::kDormant);
1487 android::RadioActivityTracker::GetInstance().OverrideRadioTypeForTesting(
1488 base::android::RadioConnectionType::kCell);
1489
Liza Burakova892ce1c2022-09-19 16:44:461490 ConnectTest(/*use_nonblocking_io=*/false, false);
Kenichi Ishibashi08c3ea12021-12-09 08:23:461491
1492 // Check the write is recorded as a possible radio wake-up trigger.
1493 histograms.ExpectTotalCount(
1494 android::kUmaNamePossibleWakeupTriggerUDPWriteAnnotationId, 1);
1495}
1496
Stefano Duoa44b1192022-01-25 15:24:591497TEST_F(UDPSocketTest, BindToNetwork) {
1498 // The specific value of this address doesn't really matter, and no
1499 // server needs to be running here. The test only needs to call
1500 // Connect() and won't send any datagrams.
1501 const IPEndPoint fake_server_address(IPAddress::IPv4Localhost(), 8080);
1502 NetworkChangeNotifierFactoryAndroid ncn_factory;
1503 NetworkChangeNotifier::DisableForTest ncn_disable_for_test;
1504 std::unique_ptr<NetworkChangeNotifier> ncn(ncn_factory.CreateInstance());
1505 if (!NetworkChangeNotifier::AreNetworkHandlesSupported())
1506 GTEST_SKIP() << "Network handles are required to test BindToNetwork.";
1507
1508 // Binding the socket to a not existing network should fail at connect time.
Stefano Duo6527ed42022-07-29 09:25:441509 const handles::NetworkHandle wrong_network_handle = 65536;
Peter Kastingd534d732022-09-01 18:14:371510 UDPClientSocket wrong_socket(DatagramSocket::RANDOM_BIND, nullptr,
1511 NetLogSource(), wrong_network_handle);
Stefano Duoa44b1192022-01-25 15:24:591512 // Different Android versions might report different errors. Hence, just check
1513 // what shouldn't happen.
Peter Kastingd534d732022-09-01 18:14:371514 int rv = wrong_socket.Connect(fake_server_address);
Stefano Duoa44b1192022-01-25 15:24:591515 EXPECT_NE(OK, rv);
1516 EXPECT_NE(ERR_NOT_IMPLEMENTED, rv);
Peter Kastingd534d732022-09-01 18:14:371517 EXPECT_NE(wrong_network_handle, wrong_socket.GetBoundNetwork());
Stefano Duoa44b1192022-01-25 15:24:591518
1519 // Binding the socket to an existing network should succeed.
Stefano Duo6527ed42022-07-29 09:25:441520 const handles::NetworkHandle network_handle =
Stefano Duoa44b1192022-01-25 15:24:591521 NetworkChangeNotifier::GetDefaultNetwork();
Stefano Duo6527ed42022-07-29 09:25:441522 if (network_handle != handles::kInvalidNetworkHandle) {
Peter Kastingd534d732022-09-01 18:14:371523 UDPClientSocket correct_socket(DatagramSocket::RANDOM_BIND, nullptr,
1524 NetLogSource(), network_handle);
1525 EXPECT_EQ(OK, correct_socket.Connect(fake_server_address));
1526 EXPECT_EQ(network_handle, correct_socket.GetBoundNetwork());
Stefano Duoa44b1192022-01-25 15:24:591527 }
1528}
1529
Xiaohan Wang2a6845b2022-01-08 04:40:571530#endif // BUILDFLAG(IS_ANDROID)
Paul Jensen0f49dec2017-12-12 23:39:581531
Eric Roman5a841922020-08-13 01:28:251532// Scoped helper to override the process-wide UDP socket limit.
1533class OverrideUDPSocketLimit {
1534 public:
1535 explicit OverrideUDPSocketLimit(int new_limit) {
1536 base::FieldTrialParams params;
1537 params[features::kLimitOpenUDPSocketsMax.name] =
1538 base::NumberToString(new_limit);
1539
1540 scoped_feature_list_.InitAndEnableFeatureWithParameters(
1541 features::kLimitOpenUDPSockets, params);
1542 }
1543
1544 private:
1545 base::test::ScopedFeatureList scoped_feature_list_;
1546};
1547
1548// Tests that UDPClientSocket respects the global UDP socket limits.
1549TEST_F(UDPSocketTest, LimitClientSocket) {
1550 // Reduce the global UDP limit to 2.
1551 OverrideUDPSocketLimit set_limit(2);
1552
1553 ASSERT_EQ(0, GetGlobalUDPSocketCountForTesting());
1554
1555 auto socket1 = std::make_unique<UDPClientSocket>(DatagramSocket::DEFAULT_BIND,
1556 nullptr, NetLogSource());
1557 auto socket2 = std::make_unique<UDPClientSocket>(DatagramSocket::DEFAULT_BIND,
1558 nullptr, NetLogSource());
1559
1560 // Simply constructing a UDPClientSocket does not increase the limit (no
1561 // Connect() or Bind() has been called yet).
1562 ASSERT_EQ(0, GetGlobalUDPSocketCountForTesting());
1563
1564 // The specific value of this address doesn't really matter, and no server
1565 // needs to be running here. The test only needs to call Connect() and won't
1566 // send any datagrams.
1567 IPEndPoint server_address(IPAddress::IPv4Localhost(), 8080);
1568
1569 // Successful Connect() on socket1 increases socket count.
1570 EXPECT_THAT(socket1->Connect(server_address), IsOk());
1571 EXPECT_EQ(1, GetGlobalUDPSocketCountForTesting());
1572
1573 // Successful Connect() on socket2 increases socket count.
1574 EXPECT_THAT(socket2->Connect(server_address), IsOk());
1575 EXPECT_EQ(2, GetGlobalUDPSocketCountForTesting());
1576
1577 // Attempting a third Connect() should fail with ERR_INSUFFICIENT_RESOURCES,
1578 // as the limit is currently 2.
1579 auto socket3 = std::make_unique<UDPClientSocket>(DatagramSocket::DEFAULT_BIND,
1580 nullptr, NetLogSource());
1581 EXPECT_THAT(socket3->Connect(server_address),
1582 IsError(ERR_INSUFFICIENT_RESOURCES));
1583 EXPECT_EQ(2, GetGlobalUDPSocketCountForTesting());
1584
1585 // Check that explicitly closing socket2 free up a count.
1586 socket2->Close();
1587 EXPECT_EQ(1, GetGlobalUDPSocketCountForTesting());
1588
1589 // Since the socket was already closed, deleting it will not affect the count.
1590 socket2.reset();
1591 EXPECT_EQ(1, GetGlobalUDPSocketCountForTesting());
1592
1593 // Now that the count is below limit, try to connect socket3 again. This time
1594 // it will work.
1595 EXPECT_THAT(socket3->Connect(server_address), IsOk());
1596 EXPECT_EQ(2, GetGlobalUDPSocketCountForTesting());
1597
1598 // Verify that closing the two remaining sockets brings the open count back to
1599 // 0.
1600 socket1.reset();
1601 EXPECT_EQ(1, GetGlobalUDPSocketCountForTesting());
1602 socket3.reset();
1603 EXPECT_EQ(0, GetGlobalUDPSocketCountForTesting());
1604}
1605
1606// Tests that UDPSocketClient updates the global counter
1607// correctly when Connect() fails.
1608TEST_F(UDPSocketTest, LimitConnectFail) {
1609 ASSERT_EQ(0, GetGlobalUDPSocketCountForTesting());
1610
1611 {
1612 // Simply allocating a UDPSocket does not increase count.
1613 UDPSocket socket(DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
1614 EXPECT_EQ(0, GetGlobalUDPSocketCountForTesting());
1615
1616 // Calling Open() allocates the socket and increases the global counter.
1617 EXPECT_THAT(socket.Open(ADDRESS_FAMILY_IPV4), IsOk());
1618 EXPECT_EQ(1, GetGlobalUDPSocketCountForTesting());
1619
1620 // Connect to an IPv6 address should fail since the socket was created for
1621 // IPv4.
1622 EXPECT_THAT(socket.Connect(net::IPEndPoint(IPAddress::IPv6Localhost(), 53)),
1623 Not(IsOk()));
1624
1625 // That Connect() failed doesn't change the global counter.
1626 EXPECT_EQ(1, GetGlobalUDPSocketCountForTesting());
1627 }
1628
1629 // Finally, destroying UDPSocket decrements the global counter.
1630 EXPECT_EQ(0, GetGlobalUDPSocketCountForTesting());
1631}
1632
1633// Tests allocating UDPClientSockets and Connect()ing them in parallel.
1634//
1635// This is primarily intended for coverage under TSAN, to check for races
1636// enforcing the global socket counter.
1637TEST_F(UDPSocketTest, LimitConnectMultithreaded) {
1638 ASSERT_EQ(0, GetGlobalUDPSocketCountForTesting());
1639
1640 // Start up some threads.
1641 std::vector<std::unique_ptr<base::Thread>> threads;
1642 for (size_t i = 0; i < 5; ++i) {
1643 threads.push_back(std::make_unique<base::Thread>("Worker thread"));
1644 ASSERT_TRUE(threads.back()->Start());
1645 }
1646
1647 // Post tasks to each of the threads.
1648 for (const auto& thread : threads) {
1649 thread->task_runner()->PostTask(
1650 FROM_HERE, base::BindOnce([] {
1651 // The specific value of this address doesn't really matter, and no
1652 // server needs to be running here. The test only needs to call
1653 // Connect() and won't send any datagrams.
1654 IPEndPoint server_address(IPAddress::IPv4Localhost(), 8080);
1655
1656 UDPClientSocket socket(DatagramSocket::DEFAULT_BIND, nullptr,
1657 NetLogSource());
1658 EXPECT_THAT(socket.Connect(server_address), IsOk());
1659 }));
1660 }
1661
1662 // Complete all the tasks.
1663 threads.clear();
1664
1665 EXPECT_EQ(0, GetGlobalUDPSocketCountForTesting());
1666}
1667
[email protected]a2798d92011-03-02 22:56:181668} // namespace net