udp_socket_unittest.cc 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "net/socket/udp_socket.h"
  5. #include <algorithm>
  6. #include "base/bind.h"
  7. #include "base/containers/circular_deque.h"
  8. #include "base/location.h"
  9. #include "base/memory/raw_ptr.h"
  10. #include "base/memory/weak_ptr.h"
  11. #include "base/run_loop.h"
  12. #include "base/scoped_clear_last_error.h"
  13. #include "base/strings/string_number_conversions.h"
  14. #include "base/task/single_thread_task_runner.h"
  15. #include "base/test/scoped_feature_list.h"
  16. #include "base/threading/thread.h"
  17. #include "base/threading/thread_task_runner_handle.h"
  18. #include "base/time/time.h"
  19. #include "build/build_config.h"
  20. #include "build/chromeos_buildflags.h"
  21. #include "net/base/features.h"
  22. #include "net/base/io_buffer.h"
  23. #include "net/base/ip_address.h"
  24. #include "net/base/ip_endpoint.h"
  25. #include "net/base/net_errors.h"
  26. #include "net/base/network_interfaces.h"
  27. #include "net/base/test_completion_callback.h"
  28. #include "net/log/net_log_event_type.h"
  29. #include "net/log/net_log_source.h"
  30. #include "net/log/test_net_log.h"
  31. #include "net/log/test_net_log_util.h"
  32. #include "net/socket/socket_test_util.h"
  33. #include "net/socket/udp_client_socket.h"
  34. #include "net/socket/udp_server_socket.h"
  35. #include "net/socket/udp_socket_global_limits.h"
  36. #include "net/test/gtest_util.h"
  37. #include "net/test/test_with_task_environment.h"
  38. #include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
  39. #include "testing/gmock/include/gmock/gmock.h"
  40. #include "testing/gtest/include/gtest/gtest.h"
  41. #include "testing/platform_test.h"
  42. #if BUILDFLAG(IS_ANDROID)
  43. #include "base/android/build_info.h"
  44. #include "base/android/radio_utils.h"
  45. #include "base/test/metrics/histogram_tester.h"
  46. #include "net/android/network_change_notifier_factory_android.h"
  47. #include "net/android/radio_activity_tracker.h"
  48. #include "net/base/network_change_notifier.h"
  49. #endif
  50. #if BUILDFLAG(IS_IOS)
  51. #include <TargetConditionals.h>
  52. #endif
  53. #if BUILDFLAG(IS_MAC)
  54. #include "base/mac/mac_util.h"
  55. #endif // BUILDFLAG(IS_MAC)
  56. using net::test::IsError;
  57. using net::test::IsOk;
  58. using testing::DoAll;
  59. using testing::Not;
  60. namespace net {
  61. namespace {
  62. // Creates an address from ip address and port and writes it to |*address|.
  63. bool CreateUDPAddress(const std::string& ip_str,
  64. uint16_t port,
  65. IPEndPoint* address) {
  66. IPAddress ip_address;
  67. if (!ip_address.AssignFromIPLiteral(ip_str))
  68. return false;
  69. *address = IPEndPoint(ip_address, port);
  70. return true;
  71. }
  72. class UDPSocketTest : public PlatformTest, public WithTaskEnvironment {
  73. public:
  74. UDPSocketTest() : buffer_(base::MakeRefCounted<IOBufferWithSize>(kMaxRead)) {}
  75. // Blocks until data is read from the socket.
  76. std::string RecvFromSocket(UDPServerSocket* socket) {
  77. TestCompletionCallback callback;
  78. int rv = socket->RecvFrom(buffer_.get(), kMaxRead, &recv_from_address_,
  79. callback.callback());
  80. rv = callback.GetResult(rv);
  81. if (rv < 0)
  82. return std::string();
  83. return std::string(buffer_->data(), rv);
  84. }
  85. // Sends UDP packet.
  86. // If |address| is specified, then it is used for the destination
  87. // to send to. Otherwise, will send to the last socket this server
  88. // received from.
  89. int SendToSocket(UDPServerSocket* socket, const std::string& msg) {
  90. return SendToSocket(socket, msg, recv_from_address_);
  91. }
  92. int SendToSocket(UDPServerSocket* socket,
  93. std::string msg,
  94. const IPEndPoint& address) {
  95. scoped_refptr<StringIOBuffer> io_buffer =
  96. base::MakeRefCounted<StringIOBuffer>(msg);
  97. TestCompletionCallback callback;
  98. int rv = socket->SendTo(io_buffer.get(), io_buffer->size(), address,
  99. callback.callback());
  100. return callback.GetResult(rv);
  101. }
  102. std::string ReadSocket(UDPClientSocket* socket) {
  103. TestCompletionCallback callback;
  104. int rv = socket->Read(buffer_.get(), kMaxRead, callback.callback());
  105. rv = callback.GetResult(rv);
  106. if (rv < 0)
  107. return std::string();
  108. return std::string(buffer_->data(), rv);
  109. }
  110. // Writes specified message to the socket.
  111. int WriteSocket(UDPClientSocket* socket, const std::string& msg) {
  112. scoped_refptr<StringIOBuffer> io_buffer =
  113. base::MakeRefCounted<StringIOBuffer>(msg);
  114. TestCompletionCallback callback;
  115. int rv = socket->Write(io_buffer.get(), io_buffer->size(),
  116. callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS);
  117. return callback.GetResult(rv);
  118. }
  119. void WriteSocketIgnoreResult(UDPClientSocket* socket,
  120. const std::string& msg) {
  121. WriteSocket(socket, msg);
  122. }
  123. // And again for a bare socket
  124. int SendToSocket(UDPSocket* socket,
  125. std::string msg,
  126. const IPEndPoint& address) {
  127. auto io_buffer = base::MakeRefCounted<StringIOBuffer>(msg);
  128. TestCompletionCallback callback;
  129. int rv = socket->SendTo(io_buffer.get(), io_buffer->size(), address,
  130. callback.callback());
  131. return callback.GetResult(rv);
  132. }
  133. // Run unit test for a connection test.
  134. // |use_nonblocking_io| is used to switch between overlapped and non-blocking
  135. // IO on Windows. It has no effect in other ports.
  136. void ConnectTest(bool use_nonblocking_io);
  137. protected:
  138. static const int kMaxRead = 1024;
  139. scoped_refptr<IOBufferWithSize> buffer_;
  140. IPEndPoint recv_from_address_;
  141. };
  142. const int UDPSocketTest::kMaxRead;
  143. void ReadCompleteCallback(int* result_out,
  144. base::OnceClosure callback,
  145. int result) {
  146. *result_out = result;
  147. std::move(callback).Run();
  148. }
  149. void UDPSocketTest::ConnectTest(bool use_nonblocking_io) {
  150. std::string simple_message("hello world!");
  151. RecordingNetLogObserver net_log_observer;
  152. // Setup the server to listen.
  153. IPEndPoint server_address(IPAddress::IPv4Localhost(), 0 /* port */);
  154. auto server =
  155. std::make_unique<UDPServerSocket>(NetLog::Get(), NetLogSource());
  156. if (use_nonblocking_io)
  157. server->UseNonBlockingIO();
  158. server->AllowAddressReuse();
  159. ASSERT_THAT(server->Listen(server_address), IsOk());
  160. // Get bound port.
  161. ASSERT_THAT(server->GetLocalAddress(&server_address), IsOk());
  162. // Setup the client.
  163. auto client = std::make_unique<UDPClientSocket>(
  164. DatagramSocket::DEFAULT_BIND, NetLog::Get(), NetLogSource());
  165. if (use_nonblocking_io)
  166. client->UseNonBlockingIO();
  167. EXPECT_THAT(client->Connect(server_address), IsOk());
  168. // Client sends to the server.
  169. EXPECT_EQ(simple_message.length(),
  170. static_cast<size_t>(WriteSocket(client.get(), simple_message)));
  171. // Server waits for message.
  172. std::string str = RecvFromSocket(server.get());
  173. EXPECT_EQ(simple_message, str);
  174. // Server echoes reply.
  175. EXPECT_EQ(simple_message.length(),
  176. static_cast<size_t>(SendToSocket(server.get(), simple_message)));
  177. // Client waits for response.
  178. str = ReadSocket(client.get());
  179. EXPECT_EQ(simple_message, str);
  180. // Test asynchronous read. Server waits for message.
  181. base::RunLoop run_loop;
  182. int read_result = 0;
  183. int rv = server->RecvFrom(buffer_.get(), kMaxRead, &recv_from_address_,
  184. base::BindOnce(&ReadCompleteCallback, &read_result,
  185. run_loop.QuitClosure()));
  186. EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  187. // Client sends to the server.
  188. base::ThreadTaskRunnerHandle::Get()->PostTask(
  189. FROM_HERE,
  190. base::BindOnce(&UDPSocketTest::WriteSocketIgnoreResult,
  191. base::Unretained(this), client.get(), simple_message));
  192. run_loop.Run();
  193. EXPECT_EQ(simple_message.length(), static_cast<size_t>(read_result));
  194. EXPECT_EQ(simple_message, std::string(buffer_->data(), read_result));
  195. NetLogSource server_net_log_source = server->NetLog().source();
  196. NetLogSource client_net_log_source = client->NetLog().source();
  197. // Delete sockets so they log their final events.
  198. server.reset();
  199. client.reset();
  200. // Check the server's log.
  201. auto server_entries =
  202. net_log_observer.GetEntriesForSource(server_net_log_source);
  203. ASSERT_EQ(6u, server_entries.size());
  204. EXPECT_TRUE(
  205. LogContainsBeginEvent(server_entries, 0, NetLogEventType::SOCKET_ALIVE));
  206. EXPECT_TRUE(LogContainsEvent(server_entries, 1,
  207. NetLogEventType::UDP_LOCAL_ADDRESS,
  208. NetLogEventPhase::NONE));
  209. EXPECT_TRUE(LogContainsEvent(server_entries, 2,
  210. NetLogEventType::UDP_BYTES_RECEIVED,
  211. NetLogEventPhase::NONE));
  212. EXPECT_TRUE(LogContainsEvent(server_entries, 3,
  213. NetLogEventType::UDP_BYTES_SENT,
  214. NetLogEventPhase::NONE));
  215. EXPECT_TRUE(LogContainsEvent(server_entries, 4,
  216. NetLogEventType::UDP_BYTES_RECEIVED,
  217. NetLogEventPhase::NONE));
  218. EXPECT_TRUE(
  219. LogContainsEndEvent(server_entries, 5, NetLogEventType::SOCKET_ALIVE));
  220. // Check the client's log.
  221. auto client_entries =
  222. net_log_observer.GetEntriesForSource(client_net_log_source);
  223. EXPECT_EQ(7u, client_entries.size());
  224. EXPECT_TRUE(
  225. LogContainsBeginEvent(client_entries, 0, NetLogEventType::SOCKET_ALIVE));
  226. EXPECT_TRUE(
  227. LogContainsBeginEvent(client_entries, 1, NetLogEventType::UDP_CONNECT));
  228. EXPECT_TRUE(
  229. LogContainsEndEvent(client_entries, 2, NetLogEventType::UDP_CONNECT));
  230. EXPECT_TRUE(LogContainsEvent(client_entries, 3,
  231. NetLogEventType::UDP_BYTES_SENT,
  232. NetLogEventPhase::NONE));
  233. EXPECT_TRUE(LogContainsEvent(client_entries, 4,
  234. NetLogEventType::UDP_BYTES_RECEIVED,
  235. NetLogEventPhase::NONE));
  236. EXPECT_TRUE(LogContainsEvent(client_entries, 5,
  237. NetLogEventType::UDP_BYTES_SENT,
  238. NetLogEventPhase::NONE));
  239. EXPECT_TRUE(
  240. LogContainsEndEvent(client_entries, 6, NetLogEventType::SOCKET_ALIVE));
  241. }
  242. TEST_F(UDPSocketTest, Connect) {
  243. // The variable |use_nonblocking_io| has no effect in non-Windows ports.
  244. ConnectTest(false);
  245. }
  246. #if BUILDFLAG(IS_WIN)
  247. TEST_F(UDPSocketTest, ConnectNonBlocking) {
  248. ConnectTest(true);
  249. }
  250. #endif
  251. TEST_F(UDPSocketTest, PartialRecv) {
  252. UDPServerSocket server_socket(nullptr, NetLogSource());
  253. ASSERT_THAT(server_socket.Listen(IPEndPoint(IPAddress::IPv4Localhost(), 0)),
  254. IsOk());
  255. IPEndPoint server_address;
  256. ASSERT_THAT(server_socket.GetLocalAddress(&server_address), IsOk());
  257. UDPClientSocket client_socket(DatagramSocket::DEFAULT_BIND, nullptr,
  258. NetLogSource());
  259. ASSERT_THAT(client_socket.Connect(server_address), IsOk());
  260. std::string test_packet("hello world!");
  261. ASSERT_EQ(static_cast<int>(test_packet.size()),
  262. WriteSocket(&client_socket, test_packet));
  263. TestCompletionCallback recv_callback;
  264. // Read just 2 bytes. Read() is expected to return the first 2 bytes from the
  265. // packet and discard the rest.
  266. const int kPartialReadSize = 2;
  267. scoped_refptr<IOBuffer> buffer =
  268. base::MakeRefCounted<IOBuffer>(kPartialReadSize);
  269. int rv =
  270. server_socket.RecvFrom(buffer.get(), kPartialReadSize,
  271. &recv_from_address_, recv_callback.callback());
  272. rv = recv_callback.GetResult(rv);
  273. EXPECT_EQ(rv, ERR_MSG_TOO_BIG);
  274. // Send a different message again.
  275. std::string second_packet("Second packet");
  276. ASSERT_EQ(static_cast<int>(second_packet.size()),
  277. WriteSocket(&client_socket, second_packet));
  278. // Read whole packet now.
  279. std::string received = RecvFromSocket(&server_socket);
  280. EXPECT_EQ(second_packet, received);
  281. }
  282. #if BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_ANDROID)
  283. // - MacOS: requires root permissions on OSX 10.7+.
  284. // - Android: devices attached to testbots don't have default network, so
  285. // broadcasting to 255.255.255.255 returns error -109 (Address not reachable).
  286. // crbug.com/139144.
  287. #define MAYBE_LocalBroadcast DISABLED_LocalBroadcast
  288. #else
  289. #define MAYBE_LocalBroadcast LocalBroadcast
  290. #endif
  291. TEST_F(UDPSocketTest, MAYBE_LocalBroadcast) {
  292. std::string first_message("first message"), second_message("second message");
  293. IPEndPoint listen_address;
  294. ASSERT_TRUE(CreateUDPAddress("0.0.0.0", 0 /* port */, &listen_address));
  295. auto server1 =
  296. std::make_unique<UDPServerSocket>(NetLog::Get(), NetLogSource());
  297. auto server2 =
  298. std::make_unique<UDPServerSocket>(NetLog::Get(), NetLogSource());
  299. server1->AllowAddressReuse();
  300. server1->AllowBroadcast();
  301. server2->AllowAddressReuse();
  302. server2->AllowBroadcast();
  303. EXPECT_THAT(server1->Listen(listen_address), IsOk());
  304. // Get bound port.
  305. EXPECT_THAT(server1->GetLocalAddress(&listen_address), IsOk());
  306. EXPECT_THAT(server2->Listen(listen_address), IsOk());
  307. IPEndPoint broadcast_address;
  308. ASSERT_TRUE(CreateUDPAddress("127.255.255.255", listen_address.port(),
  309. &broadcast_address));
  310. ASSERT_EQ(static_cast<int>(first_message.size()),
  311. SendToSocket(server1.get(), first_message, broadcast_address));
  312. std::string str = RecvFromSocket(server1.get());
  313. ASSERT_EQ(first_message, str);
  314. str = RecvFromSocket(server2.get());
  315. ASSERT_EQ(first_message, str);
  316. ASSERT_EQ(static_cast<int>(second_message.size()),
  317. SendToSocket(server2.get(), second_message, broadcast_address));
  318. str = RecvFromSocket(server1.get());
  319. ASSERT_EQ(second_message, str);
  320. str = RecvFromSocket(server2.get());
  321. ASSERT_EQ(second_message, str);
  322. }
  323. // ConnectRandomBind verifies RANDOM_BIND is handled correctly. It connects
  324. // 1000 sockets and then verifies that the allocated port numbers satisfy the
  325. // following 2 conditions:
  326. // 1. Range from min port value to max is greater than 10000.
  327. // 2. There is at least one port in the 5 buckets in the [min, max] range.
  328. //
  329. // These conditions are not enough to verify that the port numbers are truly
  330. // random, but they are enough to protect from most common non-random port
  331. // allocation strategies (e.g. counter, pool of available ports, etc.) False
  332. // positive result is theoretically possible, but its probability is negligible.
  333. TEST_F(UDPSocketTest, ConnectRandomBind) {
  334. const int kIterations = 1000;
  335. std::vector<int> used_ports;
  336. for (int i = 0; i < kIterations; ++i) {
  337. UDPClientSocket socket(DatagramSocket::RANDOM_BIND, nullptr,
  338. NetLogSource());
  339. EXPECT_THAT(socket.Connect(IPEndPoint(IPAddress::IPv4Localhost(), 53)),
  340. IsOk());
  341. IPEndPoint client_address;
  342. EXPECT_THAT(socket.GetLocalAddress(&client_address), IsOk());
  343. used_ports.push_back(client_address.port());
  344. }
  345. int min_port = *std::min_element(used_ports.begin(), used_ports.end());
  346. int max_port = *std::max_element(used_ports.begin(), used_ports.end());
  347. int range = max_port - min_port + 1;
  348. // Verify that the range of ports used by the random port allocator is wider
  349. // than 10k. Assuming that socket implementation limits port range to 16k
  350. // ports (default on Fuchsia) probability of false negative is below
  351. // 10^-200.
  352. static int kMinRange = 10000;
  353. EXPECT_GT(range, kMinRange);
  354. static int kBuckets = 5;
  355. std::vector<int> bucket_sizes(kBuckets, 0);
  356. for (int port : used_ports) {
  357. bucket_sizes[(port - min_port) * kBuckets / range] += 1;
  358. }
  359. // Verify that there is at least one value in each bucket. Probability of
  360. // false negative is below (kBuckets * (1 - 1 / kBuckets) ^ kIterations),
  361. // which is less than 10^-96.
  362. for (int size : bucket_sizes) {
  363. EXPECT_GT(size, 0);
  364. }
  365. }
  366. TEST_F(UDPSocketTest, ConnectFail) {
  367. UDPSocket socket(DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
  368. EXPECT_THAT(socket.Open(ADDRESS_FAMILY_IPV4), IsOk());
  369. // Connect to an IPv6 address should fail since the socket was created for
  370. // IPv4.
  371. EXPECT_THAT(socket.Connect(net::IPEndPoint(IPAddress::IPv6Localhost(), 53)),
  372. Not(IsOk()));
  373. // Make sure that UDPSocket actually closed the socket.
  374. EXPECT_FALSE(socket.is_connected());
  375. }
  376. // In this test, we verify that connect() on a socket will have the effect
  377. // of filtering reads on this socket only to data read from the destination
  378. // we connected to.
  379. //
  380. // The purpose of this test is that some documentation indicates that connect
  381. // binds the client's sends to send to a particular server endpoint, but does
  382. // not bind the client's reads to only be from that endpoint, and that we need
  383. // to always use recvfrom() to disambiguate.
  384. TEST_F(UDPSocketTest, VerifyConnectBindsAddr) {
  385. std::string simple_message("hello world!");
  386. std::string foreign_message("BAD MESSAGE TO GET!!");
  387. // Setup the first server to listen.
  388. IPEndPoint server1_address(IPAddress::IPv4Localhost(), 0 /* port */);
  389. UDPServerSocket server1(nullptr, NetLogSource());
  390. ASSERT_THAT(server1.Listen(server1_address), IsOk());
  391. // Get the bound port.
  392. ASSERT_THAT(server1.GetLocalAddress(&server1_address), IsOk());
  393. // Setup the second server to listen.
  394. IPEndPoint server2_address(IPAddress::IPv4Localhost(), 0 /* port */);
  395. UDPServerSocket server2(nullptr, NetLogSource());
  396. ASSERT_THAT(server2.Listen(server2_address), IsOk());
  397. // Setup the client, connected to server 1.
  398. UDPClientSocket client(DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
  399. EXPECT_THAT(client.Connect(server1_address), IsOk());
  400. // Client sends to server1.
  401. EXPECT_EQ(simple_message.length(),
  402. static_cast<size_t>(WriteSocket(&client, simple_message)));
  403. // Server1 waits for message.
  404. std::string str = RecvFromSocket(&server1);
  405. EXPECT_EQ(simple_message, str);
  406. // Get the client's address.
  407. IPEndPoint client_address;
  408. EXPECT_THAT(client.GetLocalAddress(&client_address), IsOk());
  409. // Server2 sends reply.
  410. EXPECT_EQ(foreign_message.length(),
  411. static_cast<size_t>(
  412. SendToSocket(&server2, foreign_message, client_address)));
  413. // Server1 sends reply.
  414. EXPECT_EQ(simple_message.length(),
  415. static_cast<size_t>(
  416. SendToSocket(&server1, simple_message, client_address)));
  417. // Client waits for response.
  418. str = ReadSocket(&client);
  419. EXPECT_EQ(simple_message, str);
  420. }
  421. TEST_F(UDPSocketTest, ClientGetLocalPeerAddresses) {
  422. struct TestData {
  423. std::string remote_address;
  424. std::string local_address;
  425. bool may_fail;
  426. } tests[] = {
  427. {"127.0.00.1", "127.0.0.1", false},
  428. {"::1", "::1", true},
  429. #if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
  430. // Addresses below are disabled on Android. See crbug.com/161248
  431. // They are also disabled on iOS. See https://crbug.com/523225
  432. {"192.168.1.1", "127.0.0.1", false},
  433. {"2001:db8:0::42", "::1", true},
  434. #endif
  435. };
  436. for (const auto& test : tests) {
  437. SCOPED_TRACE(std::string("Connecting from ") + test.local_address +
  438. std::string(" to ") + test.remote_address);
  439. IPAddress ip_address;
  440. EXPECT_TRUE(ip_address.AssignFromIPLiteral(test.remote_address));
  441. IPEndPoint remote_address(ip_address, 80);
  442. EXPECT_TRUE(ip_address.AssignFromIPLiteral(test.local_address));
  443. IPEndPoint local_address(ip_address, 80);
  444. UDPClientSocket client(DatagramSocket::DEFAULT_BIND, nullptr,
  445. NetLogSource());
  446. int rv = client.Connect(remote_address);
  447. if (test.may_fail && rv == ERR_ADDRESS_UNREACHABLE) {
  448. // Connect() may return ERR_ADDRESS_UNREACHABLE for IPv6
  449. // addresses if IPv6 is not configured.
  450. continue;
  451. }
  452. EXPECT_LE(ERR_IO_PENDING, rv);
  453. IPEndPoint fetched_local_address;
  454. rv = client.GetLocalAddress(&fetched_local_address);
  455. EXPECT_THAT(rv, IsOk());
  456. // TODO(mbelshe): figure out how to verify the IP and port.
  457. // The port is dynamically generated by the udp stack.
  458. // The IP is the real IP of the client, not necessarily
  459. // loopback.
  460. // EXPECT_EQ(local_address.address(), fetched_local_address.address());
  461. IPEndPoint fetched_remote_address;
  462. rv = client.GetPeerAddress(&fetched_remote_address);
  463. EXPECT_THAT(rv, IsOk());
  464. EXPECT_EQ(remote_address, fetched_remote_address);
  465. }
  466. }
  467. TEST_F(UDPSocketTest, ServerGetLocalAddress) {
  468. IPEndPoint bind_address(IPAddress::IPv4Localhost(), 0);
  469. UDPServerSocket server(nullptr, NetLogSource());
  470. int rv = server.Listen(bind_address);
  471. EXPECT_THAT(rv, IsOk());
  472. IPEndPoint local_address;
  473. rv = server.GetLocalAddress(&local_address);
  474. EXPECT_EQ(rv, 0);
  475. // Verify that port was allocated.
  476. EXPECT_GT(local_address.port(), 0);
  477. EXPECT_EQ(local_address.address(), bind_address.address());
  478. }
  479. TEST_F(UDPSocketTest, ServerGetPeerAddress) {
  480. IPEndPoint bind_address(IPAddress::IPv4Localhost(), 0);
  481. UDPServerSocket server(nullptr, NetLogSource());
  482. int rv = server.Listen(bind_address);
  483. EXPECT_THAT(rv, IsOk());
  484. IPEndPoint peer_address;
  485. rv = server.GetPeerAddress(&peer_address);
  486. EXPECT_EQ(rv, ERR_SOCKET_NOT_CONNECTED);
  487. }
  488. TEST_F(UDPSocketTest, ClientSetDoNotFragment) {
  489. for (std::string ip : {"127.0.0.1", "::1"}) {
  490. UDPClientSocket client(DatagramSocket::DEFAULT_BIND, nullptr,
  491. NetLogSource());
  492. IPAddress ip_address;
  493. EXPECT_TRUE(ip_address.AssignFromIPLiteral(ip));
  494. IPEndPoint remote_address(ip_address, 80);
  495. int rv = client.Connect(remote_address);
  496. // May fail on IPv6 is IPv6 is not configured.
  497. if (ip_address.IsIPv6() && rv == ERR_ADDRESS_UNREACHABLE)
  498. return;
  499. EXPECT_THAT(rv, IsOk());
  500. rv = client.SetDoNotFragment();
  501. #if BUILDFLAG(IS_IOS) || BUILDFLAG(IS_FUCHSIA)
  502. // TODO(crbug.com/945590): IP_MTU_DISCOVER is not implemented on Fuchsia.
  503. EXPECT_THAT(rv, IsError(ERR_NOT_IMPLEMENTED));
  504. #elif BUILDFLAG(IS_MAC)
  505. if (base::mac::IsAtLeastOS11()) {
  506. EXPECT_THAT(rv, IsOk());
  507. } else {
  508. EXPECT_THAT(rv, IsError(ERR_NOT_IMPLEMENTED));
  509. }
  510. #else
  511. EXPECT_THAT(rv, IsOk());
  512. #endif
  513. }
  514. }
  515. TEST_F(UDPSocketTest, ServerSetDoNotFragment) {
  516. for (std::string ip : {"127.0.0.1", "::1"}) {
  517. IPEndPoint bind_address;
  518. ASSERT_TRUE(CreateUDPAddress(ip, 0, &bind_address));
  519. UDPServerSocket server(nullptr, NetLogSource());
  520. int rv = server.Listen(bind_address);
  521. // May fail on IPv6 is IPv6 is not configure
  522. if (bind_address.address().IsIPv6() &&
  523. (rv == ERR_ADDRESS_INVALID || rv == ERR_ADDRESS_UNREACHABLE))
  524. return;
  525. EXPECT_THAT(rv, IsOk());
  526. rv = server.SetDoNotFragment();
  527. #if BUILDFLAG(IS_IOS) || BUILDFLAG(IS_FUCHSIA)
  528. // TODO(crbug.com/945590): IP_MTU_DISCOVER is not implemented on Fuchsia.
  529. EXPECT_THAT(rv, IsError(ERR_NOT_IMPLEMENTED));
  530. #elif BUILDFLAG(IS_MAC)
  531. if (base::mac::IsAtLeastOS11()) {
  532. EXPECT_THAT(rv, IsOk());
  533. } else {
  534. EXPECT_THAT(rv, IsError(ERR_NOT_IMPLEMENTED));
  535. }
  536. #else
  537. EXPECT_THAT(rv, IsOk());
  538. #endif
  539. }
  540. }
  541. // Close the socket while read is pending.
  542. TEST_F(UDPSocketTest, CloseWithPendingRead) {
  543. IPEndPoint bind_address(IPAddress::IPv4Localhost(), 0);
  544. UDPServerSocket server(nullptr, NetLogSource());
  545. int rv = server.Listen(bind_address);
  546. EXPECT_THAT(rv, IsOk());
  547. TestCompletionCallback callback;
  548. IPEndPoint from;
  549. rv = server.RecvFrom(buffer_.get(), kMaxRead, &from, callback.callback());
  550. EXPECT_EQ(rv, ERR_IO_PENDING);
  551. server.Close();
  552. EXPECT_FALSE(callback.have_result());
  553. }
  554. // Some Android devices do not support multicast.
  555. // The ones supporting multicast need WifiManager.MulitcastLock to enable it.
  556. // http://goo.gl/jjAk9
  557. #if !BUILDFLAG(IS_ANDROID)
  558. TEST_F(UDPSocketTest, JoinMulticastGroup) {
  559. const char kGroup[] = "237.132.100.17";
  560. IPAddress group_ip;
  561. EXPECT_TRUE(group_ip.AssignFromIPLiteral(kGroup));
  562. // TODO(https://github.com/google/gvisor/issues/3839): don't guard on
  563. // OS_FUCHSIA.
  564. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_FUCHSIA)
  565. IPEndPoint bind_address(IPAddress::AllZeros(group_ip.size()), 0 /* port */);
  566. #else
  567. IPEndPoint bind_address(group_ip, 0 /* port */);
  568. #endif // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_FUCHSIA)
  569. UDPSocket socket(DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
  570. EXPECT_THAT(socket.Open(bind_address.GetFamily()), IsOk());
  571. EXPECT_THAT(socket.Bind(bind_address), IsOk());
  572. EXPECT_THAT(socket.JoinGroup(group_ip), IsOk());
  573. // Joining group multiple times.
  574. EXPECT_NE(OK, socket.JoinGroup(group_ip));
  575. EXPECT_THAT(socket.LeaveGroup(group_ip), IsOk());
  576. // Leaving group multiple times.
  577. EXPECT_NE(OK, socket.LeaveGroup(group_ip));
  578. socket.Close();
  579. }
  580. // TODO(https://crbug.com/947115): failing on device on iOS 12.2.
  581. // TODO(https://crbug.com/1227554): flaky on Mac 11.
  582. #if BUILDFLAG(IS_IOS) || BUILDFLAG(IS_MAC)
  583. #define MAYBE_SharedMulticastAddress DISABLED_SharedMulticastAddress
  584. #else
  585. #define MAYBE_SharedMulticastAddress SharedMulticastAddress
  586. #endif
  587. TEST_F(UDPSocketTest, MAYBE_SharedMulticastAddress) {
  588. const char kGroup[] = "224.0.0.251";
  589. IPAddress group_ip;
  590. ASSERT_TRUE(group_ip.AssignFromIPLiteral(kGroup));
  591. // TODO(https://github.com/google/gvisor/issues/3839): don't guard on
  592. // OS_FUCHSIA.
  593. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_FUCHSIA)
  594. IPEndPoint receive_address(IPAddress::AllZeros(group_ip.size()),
  595. 0 /* port */);
  596. #else
  597. IPEndPoint receive_address(group_ip, 0 /* port */);
  598. #endif // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_FUCHSIA)
  599. NetworkInterfaceList interfaces;
  600. ASSERT_TRUE(GetNetworkList(&interfaces, 0));
  601. // The test fails with the Hyper-V switch interface (on the host side).
  602. interfaces.erase(std::remove_if(interfaces.begin(), interfaces.end(),
  603. [](const auto& iface) {
  604. return iface.friendly_name.rfind(
  605. "vEthernet", 0) == 0;
  606. }),
  607. interfaces.end());
  608. ASSERT_FALSE(interfaces.empty());
  609. // Setup first receiving socket.
  610. UDPServerSocket socket1(nullptr, NetLogSource());
  611. socket1.AllowAddressSharingForMulticast();
  612. ASSERT_THAT(socket1.SetMulticastInterface(interfaces[0].interface_index),
  613. IsOk());
  614. ASSERT_THAT(socket1.Listen(receive_address), IsOk());
  615. ASSERT_THAT(socket1.JoinGroup(group_ip), IsOk());
  616. // Get the bound port.
  617. ASSERT_THAT(socket1.GetLocalAddress(&receive_address), IsOk());
  618. // Setup second receiving socket.
  619. UDPServerSocket socket2(nullptr, NetLogSource());
  620. socket2.AllowAddressSharingForMulticast(), IsOk();
  621. ASSERT_THAT(socket2.SetMulticastInterface(interfaces[0].interface_index),
  622. IsOk());
  623. ASSERT_THAT(socket2.Listen(receive_address), IsOk());
  624. ASSERT_THAT(socket2.JoinGroup(group_ip), IsOk());
  625. // Setup client socket.
  626. IPEndPoint send_address(group_ip, receive_address.port());
  627. UDPClientSocket client_socket(DatagramSocket::DEFAULT_BIND, nullptr,
  628. NetLogSource());
  629. ASSERT_THAT(client_socket.Connect(send_address), IsOk());
  630. #if !BUILDFLAG(IS_CHROMEOS_ASH)
  631. // Send a message via the multicast group. That message is expected be be
  632. // received by both receving sockets.
  633. //
  634. // Skip on ChromeOS where it's known to sometimes not work.
  635. // TODO(crbug.com/898964): If possible, fix and reenable.
  636. const char kMessage[] = "hello!";
  637. ASSERT_GE(WriteSocket(&client_socket, kMessage), 0);
  638. EXPECT_EQ(kMessage, RecvFromSocket(&socket1));
  639. EXPECT_EQ(kMessage, RecvFromSocket(&socket2));
  640. #endif // !BUILDFLAG(IS_CHROMEOS_ASH)
  641. }
  642. #endif // !BUILDFLAG(IS_ANDROID)
  643. TEST_F(UDPSocketTest, MulticastOptions) {
  644. IPEndPoint bind_address;
  645. ASSERT_TRUE(CreateUDPAddress("0.0.0.0", 0 /* port */, &bind_address));
  646. UDPSocket socket(DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
  647. // Before binding.
  648. EXPECT_THAT(socket.SetMulticastLoopbackMode(false), IsOk());
  649. EXPECT_THAT(socket.SetMulticastLoopbackMode(true), IsOk());
  650. EXPECT_THAT(socket.SetMulticastTimeToLive(0), IsOk());
  651. EXPECT_THAT(socket.SetMulticastTimeToLive(3), IsOk());
  652. EXPECT_NE(OK, socket.SetMulticastTimeToLive(-1));
  653. EXPECT_THAT(socket.SetMulticastInterface(0), IsOk());
  654. EXPECT_THAT(socket.Open(bind_address.GetFamily()), IsOk());
  655. EXPECT_THAT(socket.Bind(bind_address), IsOk());
  656. EXPECT_NE(OK, socket.SetMulticastLoopbackMode(false));
  657. EXPECT_NE(OK, socket.SetMulticastTimeToLive(0));
  658. EXPECT_NE(OK, socket.SetMulticastInterface(0));
  659. socket.Close();
  660. }
  661. // Checking that DSCP bits are set correctly is difficult,
  662. // but let's check that the code doesn't crash at least.
  663. TEST_F(UDPSocketTest, SetDSCP) {
  664. // Setup the server to listen.
  665. IPEndPoint bind_address;
  666. UDPSocket client(DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
  667. // We need a real IP, but we won't actually send anything to it.
  668. ASSERT_TRUE(CreateUDPAddress("8.8.8.8", 9999, &bind_address));
  669. int rv = client.Open(bind_address.GetFamily());
  670. EXPECT_THAT(rv, IsOk());
  671. rv = client.Connect(bind_address);
  672. if (rv != OK) {
  673. // Let's try localhost then.
  674. bind_address = IPEndPoint(IPAddress::IPv4Localhost(), 9999);
  675. rv = client.Connect(bind_address);
  676. }
  677. EXPECT_THAT(rv, IsOk());
  678. client.SetDiffServCodePoint(DSCP_NO_CHANGE);
  679. client.SetDiffServCodePoint(DSCP_AF41);
  680. client.SetDiffServCodePoint(DSCP_DEFAULT);
  681. client.SetDiffServCodePoint(DSCP_CS2);
  682. client.SetDiffServCodePoint(DSCP_NO_CHANGE);
  683. client.SetDiffServCodePoint(DSCP_DEFAULT);
  684. client.Close();
  685. }
  686. TEST_F(UDPSocketTest, ConnectUsingNetwork) {
  687. // The specific value of this address doesn't really matter, and no
  688. // server needs to be running here. The test only needs to call
  689. // ConnectUsingNetwork() and won't send any datagrams.
  690. const IPEndPoint fake_server_address(IPAddress::IPv4Localhost(), 8080);
  691. const handles::NetworkHandle wrong_network_handle = 65536;
  692. #if BUILDFLAG(IS_ANDROID)
  693. NetworkChangeNotifierFactoryAndroid ncn_factory;
  694. NetworkChangeNotifier::DisableForTest ncn_disable_for_test;
  695. std::unique_ptr<NetworkChangeNotifier> ncn(ncn_factory.CreateInstance());
  696. if (!NetworkChangeNotifier::AreNetworkHandlesSupported())
  697. GTEST_SKIP() << "Network handles are required to test BindToNetwork.";
  698. {
  699. // Connecting using a not existing network should fail but not report
  700. // ERR_NOT_IMPLEMENTED when network handles are supported.
  701. UDPClientSocket socket(DatagramSocket::RANDOM_BIND, nullptr,
  702. NetLogSource());
  703. int rv =
  704. socket.ConnectUsingNetwork(wrong_network_handle, fake_server_address);
  705. EXPECT_NE(ERR_NOT_IMPLEMENTED, rv);
  706. EXPECT_NE(OK, rv);
  707. EXPECT_NE(wrong_network_handle, socket.GetBoundNetwork());
  708. }
  709. {
  710. // Connecting using an existing network should succeed when
  711. // NetworkChangeNotifier returns a valid default network.
  712. UDPClientSocket socket(DatagramSocket::RANDOM_BIND, nullptr,
  713. NetLogSource());
  714. const handles::NetworkHandle network_handle =
  715. NetworkChangeNotifier::GetDefaultNetwork();
  716. if (network_handle != handles::kInvalidNetworkHandle) {
  717. EXPECT_EQ(
  718. OK, socket.ConnectUsingNetwork(network_handle, fake_server_address));
  719. EXPECT_EQ(network_handle, socket.GetBoundNetwork());
  720. }
  721. }
  722. #else
  723. UDPClientSocket socket(DatagramSocket::RANDOM_BIND, nullptr, NetLogSource());
  724. EXPECT_EQ(
  725. ERR_NOT_IMPLEMENTED,
  726. socket.ConnectUsingNetwork(wrong_network_handle, fake_server_address));
  727. #endif // BUILDFLAG(IS_ANDROID)
  728. }
  729. } // namespace
  730. #if BUILDFLAG(IS_WIN)
  731. namespace {
  732. const HANDLE kFakeHandle1 = (HANDLE)12;
  733. const HANDLE kFakeHandle2 = (HANDLE)13;
  734. const QOS_FLOWID kFakeFlowId1 = (QOS_FLOWID)27;
  735. const QOS_FLOWID kFakeFlowId2 = (QOS_FLOWID)38;
  736. class TestUDPSocketWin : public UDPSocketWin {
  737. public:
  738. TestUDPSocketWin(QwaveApi* qos,
  739. DatagramSocket::BindType bind_type,
  740. net::NetLog* net_log,
  741. const net::NetLogSource& source)
  742. : UDPSocketWin(bind_type, net_log, source), qos_(qos) {}
  743. TestUDPSocketWin(const TestUDPSocketWin&) = delete;
  744. TestUDPSocketWin& operator=(const TestUDPSocketWin&) = delete;
  745. // Overriding GetQwaveApi causes the test class to use the injected mock
  746. // QwaveApi instance instead of the singleton.
  747. QwaveApi* GetQwaveApi() const override { return qos_; }
  748. private:
  749. raw_ptr<QwaveApi> qos_;
  750. };
  751. class MockQwaveApi : public QwaveApi {
  752. public:
  753. MOCK_CONST_METHOD0(qwave_supported, bool());
  754. MOCK_METHOD0(OnFatalError, void());
  755. MOCK_METHOD2(CreateHandle, BOOL(PQOS_VERSION version, PHANDLE handle));
  756. MOCK_METHOD1(CloseHandle, BOOL(HANDLE handle));
  757. MOCK_METHOD6(AddSocketToFlow,
  758. BOOL(HANDLE handle,
  759. SOCKET socket,
  760. PSOCKADDR addr,
  761. QOS_TRAFFIC_TYPE traffic_type,
  762. DWORD flags,
  763. PQOS_FLOWID flow_id));
  764. MOCK_METHOD4(
  765. RemoveSocketFromFlow,
  766. BOOL(HANDLE handle, SOCKET socket, QOS_FLOWID flow_id, DWORD reserved));
  767. MOCK_METHOD7(SetFlow,
  768. BOOL(HANDLE handle,
  769. QOS_FLOWID flow_id,
  770. QOS_SET_FLOW op,
  771. ULONG size,
  772. PVOID data,
  773. DWORD reserved,
  774. LPOVERLAPPED overlapped));
  775. };
  776. std::unique_ptr<UDPSocket> OpenedDscpTestClient(QwaveApi* api,
  777. IPEndPoint bind_address) {
  778. auto client = std::make_unique<TestUDPSocketWin>(
  779. api, DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
  780. int rv = client->Open(bind_address.GetFamily());
  781. EXPECT_THAT(rv, IsOk());
  782. return client;
  783. }
  784. std::unique_ptr<UDPSocket> ConnectedDscpTestClient(QwaveApi* api) {
  785. IPEndPoint bind_address;
  786. // We need a real IP, but we won't actually send anything to it.
  787. EXPECT_TRUE(CreateUDPAddress("8.8.8.8", 9999, &bind_address));
  788. auto client = OpenedDscpTestClient(api, bind_address);
  789. EXPECT_THAT(client->Connect(bind_address), IsOk());
  790. return client;
  791. }
  792. std::unique_ptr<UDPSocket> UnconnectedDscpTestClient(QwaveApi* api) {
  793. IPEndPoint bind_address;
  794. EXPECT_TRUE(CreateUDPAddress("0.0.0.0", 9999, &bind_address));
  795. auto client = OpenedDscpTestClient(api, bind_address);
  796. EXPECT_THAT(client->Bind(bind_address), IsOk());
  797. return client;
  798. }
  799. } // namespace
  800. using ::testing::Return;
  801. using ::testing::SetArgPointee;
  802. using ::testing::_;
  803. TEST_F(UDPSocketTest, SetDSCPNoopIfPassedNoChange) {
  804. MockQwaveApi api;
  805. EXPECT_CALL(api, qwave_supported()).WillRepeatedly(Return(true));
  806. EXPECT_CALL(api, AddSocketToFlow(_, _, _, _, _, _)).Times(0);
  807. std::unique_ptr<UDPSocket> client = ConnectedDscpTestClient(&api);
  808. EXPECT_THAT(client->SetDiffServCodePoint(DSCP_NO_CHANGE), IsOk());
  809. }
  810. TEST_F(UDPSocketTest, SetDSCPFailsIfQOSDoesntLink) {
  811. MockQwaveApi api;
  812. EXPECT_CALL(api, qwave_supported()).WillRepeatedly(Return(false));
  813. EXPECT_CALL(api, CreateHandle(_, _)).Times(0);
  814. std::unique_ptr<UDPSocket> client = ConnectedDscpTestClient(&api);
  815. EXPECT_EQ(ERR_NOT_IMPLEMENTED, client->SetDiffServCodePoint(DSCP_AF41));
  816. }
  817. TEST_F(UDPSocketTest, SetDSCPFailsIfHandleCantBeCreated) {
  818. MockQwaveApi api;
  819. EXPECT_CALL(api, qwave_supported()).WillRepeatedly(Return(true));
  820. EXPECT_CALL(api, CreateHandle(_, _)).WillOnce(Return(false));
  821. EXPECT_CALL(api, OnFatalError()).Times(1);
  822. std::unique_ptr<UDPSocket> client = ConnectedDscpTestClient(&api);
  823. EXPECT_EQ(ERR_INVALID_HANDLE, client->SetDiffServCodePoint(DSCP_AF41));
  824. RunUntilIdle();
  825. EXPECT_CALL(api, qwave_supported()).WillRepeatedly(Return(false));
  826. EXPECT_EQ(ERR_NOT_IMPLEMENTED, client->SetDiffServCodePoint(DSCP_AF41));
  827. }
  828. MATCHER_P(DscpPointee, dscp, "") {
  829. return *(DWORD*)arg == (DWORD)dscp;
  830. }
  831. TEST_F(UDPSocketTest, ConnectedSocketDelayedInitAndUpdate) {
  832. MockQwaveApi api;
  833. std::unique_ptr<UDPSocket> client = ConnectedDscpTestClient(&api);
  834. EXPECT_CALL(api, qwave_supported()).WillRepeatedly(Return(true));
  835. EXPECT_CALL(api, CreateHandle(_, _))
  836. .WillOnce(DoAll(SetArgPointee<1>(kFakeHandle1), Return(true)));
  837. EXPECT_CALL(api, AddSocketToFlow(_, _, _, _, _, _))
  838. .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId1), Return(true)));
  839. EXPECT_CALL(api, SetFlow(_, _, _, _, _, _, _));
  840. // First set on connected sockets will fail since init is async and
  841. // we haven't given the runloop a chance to execute the callback.
  842. EXPECT_EQ(ERR_INVALID_HANDLE, client->SetDiffServCodePoint(DSCP_AF41));
  843. RunUntilIdle();
  844. EXPECT_THAT(client->SetDiffServCodePoint(DSCP_AF41), IsOk());
  845. // New dscp value should reset the flow.
  846. EXPECT_CALL(api, RemoveSocketFromFlow(_, _, kFakeFlowId1, _));
  847. EXPECT_CALL(api, AddSocketToFlow(_, _, _, QOSTrafficTypeBestEffort, _, _))
  848. .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId2), Return(true)));
  849. EXPECT_CALL(api, SetFlow(_, _, QOSSetOutgoingDSCPValue, _,
  850. DscpPointee(DSCP_DEFAULT), _, _));
  851. EXPECT_THAT(client->SetDiffServCodePoint(DSCP_DEFAULT), IsOk());
  852. // Called from DscpManager destructor.
  853. EXPECT_CALL(api, RemoveSocketFromFlow(_, _, kFakeFlowId2, _));
  854. EXPECT_CALL(api, CloseHandle(kFakeHandle1));
  855. }
  856. TEST_F(UDPSocketTest, UnonnectedSocketDelayedInitAndUpdate) {
  857. MockQwaveApi api;
  858. EXPECT_CALL(api, qwave_supported()).WillRepeatedly(Return(true));
  859. EXPECT_CALL(api, CreateHandle(_, _))
  860. .WillOnce(DoAll(SetArgPointee<1>(kFakeHandle1), Return(true)));
  861. // CreateHandle won't have completed yet. Set passes.
  862. std::unique_ptr<UDPSocket> client = UnconnectedDscpTestClient(&api);
  863. EXPECT_THAT(client->SetDiffServCodePoint(DSCP_AF41), IsOk());
  864. RunUntilIdle();
  865. EXPECT_THAT(client->SetDiffServCodePoint(DSCP_AF42), IsOk());
  866. // Called from DscpManager destructor.
  867. EXPECT_CALL(api, CloseHandle(kFakeHandle1));
  868. }
  869. // TODO(zstein): Mocking out DscpManager might be simpler here
  870. // (just verify that DscpManager::Set and DscpManager::PrepareForSend are
  871. // called).
  872. TEST_F(UDPSocketTest, SendToCallsQwaveApis) {
  873. MockQwaveApi api;
  874. std::unique_ptr<UDPSocket> client = UnconnectedDscpTestClient(&api);
  875. EXPECT_CALL(api, qwave_supported()).WillRepeatedly(Return(true));
  876. EXPECT_CALL(api, CreateHandle(_, _))
  877. .WillOnce(DoAll(SetArgPointee<1>(kFakeHandle1), Return(true)));
  878. EXPECT_THAT(client->SetDiffServCodePoint(DSCP_AF41), IsOk());
  879. RunUntilIdle();
  880. EXPECT_CALL(api, AddSocketToFlow(_, _, _, _, _, _))
  881. .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId1), Return(true)));
  882. EXPECT_CALL(api, SetFlow(_, _, _, _, _, _, _));
  883. std::string simple_message("hello world");
  884. IPEndPoint server_address(IPAddress::IPv4Localhost(), 9438);
  885. int rv = SendToSocket(client.get(), simple_message, server_address);
  886. EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
  887. // TODO(zstein): Move to second test case (Qwave APIs called once per address)
  888. rv = SendToSocket(client.get(), simple_message, server_address);
  889. EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
  890. // TODO(zstein): Move to third test case (Qwave APIs called for each
  891. // destination address).
  892. EXPECT_CALL(api, AddSocketToFlow(_, _, _, _, _, _)).WillOnce(Return(true));
  893. IPEndPoint server_address2(IPAddress::IPv4Localhost(), 9439);
  894. rv = SendToSocket(client.get(), simple_message, server_address2);
  895. EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
  896. // Called from DscpManager destructor.
  897. EXPECT_CALL(api, RemoveSocketFromFlow(_, _, _, _));
  898. EXPECT_CALL(api, CloseHandle(kFakeHandle1));
  899. }
  900. TEST_F(UDPSocketTest, SendToCallsApisAfterDeferredInit) {
  901. MockQwaveApi api;
  902. std::unique_ptr<UDPSocket> client = UnconnectedDscpTestClient(&api);
  903. EXPECT_CALL(api, qwave_supported()).WillRepeatedly(Return(true));
  904. EXPECT_CALL(api, CreateHandle(_, _))
  905. .WillOnce(DoAll(SetArgPointee<1>(kFakeHandle1), Return(true)));
  906. // SetDiffServCodepoint works even if qos api hasn't finished initing.
  907. EXPECT_THAT(client->SetDiffServCodePoint(DSCP_CS7), IsOk());
  908. std::string simple_message("hello world");
  909. IPEndPoint server_address(IPAddress::IPv4Localhost(), 9438);
  910. // SendTo works, but doesn't yet apply TOS
  911. EXPECT_CALL(api, AddSocketToFlow(_, _, _, _, _, _)).Times(0);
  912. int rv = SendToSocket(client.get(), simple_message, server_address);
  913. EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
  914. RunUntilIdle();
  915. // Now we're initialized, SendTo triggers qos calls with correct codepoint.
  916. EXPECT_CALL(api, AddSocketToFlow(_, _, _, QOSTrafficTypeControl, _, _))
  917. .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId1), Return(true)));
  918. EXPECT_CALL(api, SetFlow(_, _, _, _, _, _, _)).WillOnce(Return(true));
  919. rv = SendToSocket(client.get(), simple_message, server_address);
  920. EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
  921. // Called from DscpManager destructor.
  922. EXPECT_CALL(api, RemoveSocketFromFlow(_, _, kFakeFlowId1, _));
  923. EXPECT_CALL(api, CloseHandle(kFakeHandle1));
  924. }
  925. class DscpManagerTest : public TestWithTaskEnvironment {
  926. protected:
  927. DscpManagerTest() {
  928. EXPECT_CALL(api_, qwave_supported()).WillRepeatedly(Return(true));
  929. EXPECT_CALL(api_, CreateHandle(_, _))
  930. .WillOnce(DoAll(SetArgPointee<1>(kFakeHandle1), Return(true)));
  931. dscp_manager_ = std::make_unique<DscpManager>(&api_, INVALID_SOCKET);
  932. CreateUDPAddress("1.2.3.4", 9001, &address1_);
  933. CreateUDPAddress("1234:5678:90ab:cdef:1234:5678:90ab:cdef", 9002,
  934. &address2_);
  935. }
  936. MockQwaveApi api_;
  937. std::unique_ptr<DscpManager> dscp_manager_;
  938. IPEndPoint address1_;
  939. IPEndPoint address2_;
  940. };
  941. TEST_F(DscpManagerTest, PrepareForSendIsNoopIfNoSet) {
  942. RunUntilIdle();
  943. dscp_manager_->PrepareForSend(address1_);
  944. }
  945. TEST_F(DscpManagerTest, PrepareForSendCallsQwaveApisAfterSet) {
  946. RunUntilIdle();
  947. dscp_manager_->Set(DSCP_CS2);
  948. // AddSocketToFlow should be called for each address.
  949. // SetFlow should only be called when the flow is first created.
  950. EXPECT_CALL(api_, AddSocketToFlow(_, _, _, _, _, _))
  951. .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId1), Return(true)));
  952. EXPECT_CALL(api_, SetFlow(_, kFakeFlowId1, _, _, _, _, _));
  953. dscp_manager_->PrepareForSend(address1_);
  954. EXPECT_CALL(api_, AddSocketToFlow(_, _, _, _, _, _))
  955. .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId1), Return(true)));
  956. EXPECT_CALL(api_, SetFlow(_, _, _, _, _, _, _)).Times(0);
  957. dscp_manager_->PrepareForSend(address2_);
  958. // Called from DscpManager destructor.
  959. EXPECT_CALL(api_, RemoveSocketFromFlow(_, _, kFakeFlowId1, _));
  960. EXPECT_CALL(api_, CloseHandle(kFakeHandle1));
  961. }
  962. TEST_F(DscpManagerTest, PrepareForSendCallsQwaveApisOncePerAddress) {
  963. RunUntilIdle();
  964. dscp_manager_->Set(DSCP_CS2);
  965. EXPECT_CALL(api_, AddSocketToFlow(_, _, _, _, _, _))
  966. .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId1), Return(true)));
  967. EXPECT_CALL(api_, SetFlow(_, kFakeFlowId1, _, _, _, _, _));
  968. dscp_manager_->PrepareForSend(address1_);
  969. EXPECT_CALL(api_, AddSocketToFlow(_, _, _, _, _, _)).Times(0);
  970. EXPECT_CALL(api_, SetFlow(_, _, _, _, _, _, _)).Times(0);
  971. dscp_manager_->PrepareForSend(address1_);
  972. // Called from DscpManager destructor.
  973. EXPECT_CALL(api_, RemoveSocketFromFlow(_, _, kFakeFlowId1, _));
  974. EXPECT_CALL(api_, CloseHandle(kFakeHandle1));
  975. }
  976. TEST_F(DscpManagerTest, SetDestroysExistingFlow) {
  977. RunUntilIdle();
  978. dscp_manager_->Set(DSCP_CS2);
  979. EXPECT_CALL(api_, AddSocketToFlow(_, _, _, _, _, _))
  980. .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId1), Return(true)));
  981. EXPECT_CALL(api_, SetFlow(_, kFakeFlowId1, _, _, _, _, _));
  982. dscp_manager_->PrepareForSend(address1_);
  983. // Calling Set should destroy the existing flow.
  984. // TODO(zstein): Verify that RemoveSocketFromFlow with no address
  985. // destroys the flow for all destinations.
  986. EXPECT_CALL(api_, RemoveSocketFromFlow(_, NULL, kFakeFlowId1, _));
  987. dscp_manager_->Set(DSCP_CS5);
  988. EXPECT_CALL(api_, AddSocketToFlow(_, _, _, _, _, _))
  989. .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId2), Return(true)));
  990. EXPECT_CALL(api_, SetFlow(_, kFakeFlowId2, _, _, _, _, _));
  991. dscp_manager_->PrepareForSend(address1_);
  992. // Called from DscpManager destructor.
  993. EXPECT_CALL(api_, RemoveSocketFromFlow(_, _, kFakeFlowId2, _));
  994. EXPECT_CALL(api_, CloseHandle(kFakeHandle1));
  995. }
  996. TEST_F(DscpManagerTest, SocketReAddedOnRecreateHandle) {
  997. RunUntilIdle();
  998. dscp_manager_->Set(DSCP_CS2);
  999. // First Set and Send work fine.
  1000. EXPECT_CALL(api_, AddSocketToFlow(_, _, _, _, _, _))
  1001. .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId1), Return(true)));
  1002. EXPECT_CALL(api_, SetFlow(_, kFakeFlowId1, _, _, _, _, _))
  1003. .WillOnce(Return(true));
  1004. EXPECT_THAT(dscp_manager_->PrepareForSend(address1_), IsOk());
  1005. // Make Second flow operation fail (requires resetting the codepoint).
  1006. EXPECT_CALL(api_, RemoveSocketFromFlow(_, _, kFakeFlowId1, _))
  1007. .WillOnce(Return(true));
  1008. dscp_manager_->Set(DSCP_CS7);
  1009. auto error = std::make_unique<base::ScopedClearLastError>();
  1010. ::SetLastError(ERROR_DEVICE_REINITIALIZATION_NEEDED);
  1011. EXPECT_CALL(api_, AddSocketToFlow(_, _, _, _, _, _)).WillOnce(Return(false));
  1012. EXPECT_CALL(api_, SetFlow(_, _, _, _, _, _, _)).Times(0);
  1013. EXPECT_CALL(api_, CloseHandle(kFakeHandle1));
  1014. EXPECT_CALL(api_, CreateHandle(_, _))
  1015. .WillOnce(DoAll(SetArgPointee<1>(kFakeHandle2), Return(true)));
  1016. EXPECT_EQ(ERR_INVALID_HANDLE, dscp_manager_->PrepareForSend(address1_));
  1017. error = nullptr;
  1018. RunUntilIdle();
  1019. // Next Send should work fine, without requiring another Set
  1020. EXPECT_CALL(api_, AddSocketToFlow(_, _, _, QOSTrafficTypeControl, _, _))
  1021. .WillOnce(DoAll(SetArgPointee<5>(kFakeFlowId2), Return(true)));
  1022. EXPECT_CALL(api_, SetFlow(_, kFakeFlowId2, _, _, _, _, _))
  1023. .WillOnce(Return(true));
  1024. EXPECT_THAT(dscp_manager_->PrepareForSend(address1_), IsOk());
  1025. // Called from DscpManager destructor.
  1026. EXPECT_CALL(api_, RemoveSocketFromFlow(_, _, kFakeFlowId2, _));
  1027. EXPECT_CALL(api_, CloseHandle(kFakeHandle2));
  1028. }
  1029. #endif
  1030. TEST_F(UDPSocketTest, ReadWithSocketOptimization) {
  1031. std::string simple_message("hello world!");
  1032. // Setup the server to listen.
  1033. IPEndPoint server_address(IPAddress::IPv4Localhost(), 0 /* port */);
  1034. UDPServerSocket server(nullptr, NetLogSource());
  1035. server.AllowAddressReuse();
  1036. ASSERT_THAT(server.Listen(server_address), IsOk());
  1037. // Get bound port.
  1038. ASSERT_THAT(server.GetLocalAddress(&server_address), IsOk());
  1039. // Setup the client, enable experimental optimization and connected to the
  1040. // server.
  1041. UDPClientSocket client(DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
  1042. client.EnableRecvOptimization();
  1043. EXPECT_THAT(client.Connect(server_address), IsOk());
  1044. // Get the client's address.
  1045. IPEndPoint client_address;
  1046. EXPECT_THAT(client.GetLocalAddress(&client_address), IsOk());
  1047. // Server sends the message to the client.
  1048. EXPECT_EQ(simple_message.length(),
  1049. static_cast<size_t>(
  1050. SendToSocket(&server, simple_message, client_address)));
  1051. // Client receives the message.
  1052. std::string str = ReadSocket(&client);
  1053. EXPECT_EQ(simple_message, str);
  1054. server.Close();
  1055. client.Close();
  1056. }
  1057. // Tests that read from a socket correctly returns
  1058. // |ERR_MSG_TOO_BIG| when the buffer is too small and
  1059. // returns the actual message when it fits the buffer.
  1060. // For the optimized path, the buffer size should be at least
  1061. // 1 byte greater than the message.
  1062. TEST_F(UDPSocketTest, ReadWithSocketOptimizationTruncation) {
  1063. std::string too_long_message(kMaxRead + 1, 'A');
  1064. std::string right_length_message(kMaxRead - 1, 'B');
  1065. std::string exact_length_message(kMaxRead, 'C');
  1066. // Setup the server to listen.
  1067. IPEndPoint server_address(IPAddress::IPv4Localhost(), 0 /* port */);
  1068. UDPServerSocket server(nullptr, NetLogSource());
  1069. server.AllowAddressReuse();
  1070. ASSERT_THAT(server.Listen(server_address), IsOk());
  1071. // Get bound port.
  1072. ASSERT_THAT(server.GetLocalAddress(&server_address), IsOk());
  1073. // Setup the client, enable experimental optimization and connected to the
  1074. // server.
  1075. UDPClientSocket client(DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
  1076. client.EnableRecvOptimization();
  1077. EXPECT_THAT(client.Connect(server_address), IsOk());
  1078. // Get the client's address.
  1079. IPEndPoint client_address;
  1080. EXPECT_THAT(client.GetLocalAddress(&client_address), IsOk());
  1081. // Send messages to the client.
  1082. EXPECT_EQ(too_long_message.length(),
  1083. static_cast<size_t>(
  1084. SendToSocket(&server, too_long_message, client_address)));
  1085. EXPECT_EQ(right_length_message.length(),
  1086. static_cast<size_t>(
  1087. SendToSocket(&server, right_length_message, client_address)));
  1088. EXPECT_EQ(exact_length_message.length(),
  1089. static_cast<size_t>(
  1090. SendToSocket(&server, exact_length_message, client_address)));
  1091. // Client receives the messages.
  1092. // 1. The first message is |too_long_message|. Its size exceeds the buffer.
  1093. // In that case, the client is expected to get |ERR_MSG_TOO_BIG| when the
  1094. // data is read.
  1095. TestCompletionCallback callback;
  1096. int rv = client.Read(buffer_.get(), kMaxRead, callback.callback());
  1097. EXPECT_EQ(ERR_MSG_TOO_BIG, callback.GetResult(rv));
  1098. // 2. The second message is |right_length_message|. Its size is
  1099. // one byte smaller than the size of the buffer. In that case, the client
  1100. // is expected to read the whole message successfully.
  1101. rv = client.Read(buffer_.get(), kMaxRead, callback.callback());
  1102. rv = callback.GetResult(rv);
  1103. EXPECT_EQ(static_cast<int>(right_length_message.length()), rv);
  1104. EXPECT_EQ(right_length_message, std::string(buffer_->data(), rv));
  1105. // 3. The third message is |exact_length_message|. Its size is equal to
  1106. // the read buffer size. In that case, the client expects to get
  1107. // |ERR_MSG_TOO_BIG| when the socket is read. Internally, the optimized
  1108. // path uses read() system call that requires one extra byte to detect
  1109. // truncated messages; therefore, messages that fill the buffer exactly
  1110. // are considered truncated.
  1111. // The optimization is only enabled on POSIX platforms. On Windows,
  1112. // the optimization is turned off; therefore, the client
  1113. // should be able to read the whole message without encountering
  1114. // |ERR_MSG_TOO_BIG|.
  1115. rv = client.Read(buffer_.get(), kMaxRead, callback.callback());
  1116. rv = callback.GetResult(rv);
  1117. #if BUILDFLAG(IS_POSIX)
  1118. EXPECT_EQ(ERR_MSG_TOO_BIG, rv);
  1119. #else
  1120. EXPECT_EQ(static_cast<int>(exact_length_message.length()), rv);
  1121. EXPECT_EQ(exact_length_message, std::string(buffer_->data(), rv));
  1122. #endif
  1123. server.Close();
  1124. client.Close();
  1125. }
  1126. // On Android, where socket tagging is supported, verify that UDPSocket::Tag
  1127. // works as expected.
  1128. #if BUILDFLAG(IS_ANDROID)
  1129. TEST_F(UDPSocketTest, Tag) {
  1130. if (!CanGetTaggedBytes()) {
  1131. DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
  1132. return;
  1133. }
  1134. UDPServerSocket server(nullptr, NetLogSource());
  1135. ASSERT_THAT(server.Listen(IPEndPoint(IPAddress::IPv4Localhost(), 0)), IsOk());
  1136. IPEndPoint server_address;
  1137. ASSERT_THAT(server.GetLocalAddress(&server_address), IsOk());
  1138. UDPClientSocket client(DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
  1139. ASSERT_THAT(client.Connect(server_address), IsOk());
  1140. // Verify UDP packets are tagged and counted properly.
  1141. int32_t tag_val1 = 0x12345678;
  1142. uint64_t old_traffic = GetTaggedBytes(tag_val1);
  1143. SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
  1144. client.ApplySocketTag(tag1);
  1145. // Client sends to the server.
  1146. std::string simple_message("hello world!");
  1147. int rv = WriteSocket(&client, simple_message);
  1148. EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
  1149. // Server waits for message.
  1150. std::string str = RecvFromSocket(&server);
  1151. EXPECT_EQ(simple_message, str);
  1152. // Server echoes reply.
  1153. rv = SendToSocket(&server, simple_message);
  1154. EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
  1155. // Client waits for response.
  1156. str = ReadSocket(&client);
  1157. EXPECT_EQ(simple_message, str);
  1158. EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
  1159. // Verify socket can be retagged with a new value and the current process's
  1160. // UID.
  1161. int32_t tag_val2 = 0x87654321;
  1162. old_traffic = GetTaggedBytes(tag_val2);
  1163. SocketTag tag2(getuid(), tag_val2);
  1164. client.ApplySocketTag(tag2);
  1165. // Client sends to the server.
  1166. rv = WriteSocket(&client, simple_message);
  1167. EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
  1168. // Server waits for message.
  1169. str = RecvFromSocket(&server);
  1170. EXPECT_EQ(simple_message, str);
  1171. // Server echoes reply.
  1172. rv = SendToSocket(&server, simple_message);
  1173. EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
  1174. // Client waits for response.
  1175. str = ReadSocket(&client);
  1176. EXPECT_EQ(simple_message, str);
  1177. EXPECT_GT(GetTaggedBytes(tag_val2), old_traffic);
  1178. // Verify socket can be retagged with a new value and the current process's
  1179. // UID.
  1180. old_traffic = GetTaggedBytes(tag_val1);
  1181. client.ApplySocketTag(tag1);
  1182. // Client sends to the server.
  1183. rv = WriteSocket(&client, simple_message);
  1184. EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
  1185. // Server waits for message.
  1186. str = RecvFromSocket(&server);
  1187. EXPECT_EQ(simple_message, str);
  1188. // Server echoes reply.
  1189. rv = SendToSocket(&server, simple_message);
  1190. EXPECT_EQ(simple_message.length(), static_cast<size_t>(rv));
  1191. // Client waits for response.
  1192. str = ReadSocket(&client);
  1193. EXPECT_EQ(simple_message, str);
  1194. EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
  1195. }
  1196. TEST_F(UDPSocketTest, RecordRadioWakeUpTrigger) {
  1197. base::test::ScopedFeatureList feature_list;
  1198. feature_list.InitAndEnableFeature(features::kRecordRadioWakeupTrigger);
  1199. base::HistogramTester histograms;
  1200. // Simulates the radio state is dormant.
  1201. android::RadioActivityTracker::GetInstance().OverrideRadioActivityForTesting(
  1202. base::android::RadioDataActivity::kDormant);
  1203. android::RadioActivityTracker::GetInstance().OverrideRadioTypeForTesting(
  1204. base::android::RadioConnectionType::kCell);
  1205. ConnectTest(/*use_nonblocking_io=*/false);
  1206. // Check the write is recorded as a possible radio wake-up trigger.
  1207. histograms.ExpectTotalCount(
  1208. android::kUmaNamePossibleWakeupTriggerUDPWriteAnnotationId, 1);
  1209. }
  1210. TEST_F(UDPSocketTest, BindToNetwork) {
  1211. // The specific value of this address doesn't really matter, and no
  1212. // server needs to be running here. The test only needs to call
  1213. // Connect() and won't send any datagrams.
  1214. const IPEndPoint fake_server_address(IPAddress::IPv4Localhost(), 8080);
  1215. NetworkChangeNotifierFactoryAndroid ncn_factory;
  1216. NetworkChangeNotifier::DisableForTest ncn_disable_for_test;
  1217. std::unique_ptr<NetworkChangeNotifier> ncn(ncn_factory.CreateInstance());
  1218. if (!NetworkChangeNotifier::AreNetworkHandlesSupported())
  1219. GTEST_SKIP() << "Network handles are required to test BindToNetwork.";
  1220. // Binding the socket to a not existing network should fail at connect time.
  1221. const handles::NetworkHandle wrong_network_handle = 65536;
  1222. UDPClientSocket socket(DatagramSocket::RANDOM_BIND, nullptr, NetLogSource(),
  1223. wrong_network_handle);
  1224. // Different Android versions might report different errors. Hence, just check
  1225. // what shouldn't happen.
  1226. int rv = socket.Connect(fake_server_address);
  1227. EXPECT_NE(OK, rv);
  1228. EXPECT_NE(ERR_NOT_IMPLEMENTED, rv);
  1229. EXPECT_NE(wrong_network_handle, socket.GetBoundNetwork());
  1230. // Binding the socket to an existing network should succeed.
  1231. const handles::NetworkHandle network_handle =
  1232. NetworkChangeNotifier::GetDefaultNetwork();
  1233. if (network_handle != handles::kInvalidNetworkHandle) {
  1234. UDPClientSocket socket(DatagramSocket::RANDOM_BIND, nullptr, NetLogSource(),
  1235. network_handle);
  1236. EXPECT_EQ(OK, socket.Connect(fake_server_address));
  1237. EXPECT_EQ(network_handle, socket.GetBoundNetwork());
  1238. }
  1239. }
  1240. #endif // BUILDFLAG(IS_ANDROID)
  1241. // Scoped helper to override the process-wide UDP socket limit.
  1242. class OverrideUDPSocketLimit {
  1243. public:
  1244. explicit OverrideUDPSocketLimit(int new_limit) {
  1245. base::FieldTrialParams params;
  1246. params[features::kLimitOpenUDPSocketsMax.name] =
  1247. base::NumberToString(new_limit);
  1248. scoped_feature_list_.InitAndEnableFeatureWithParameters(
  1249. features::kLimitOpenUDPSockets, params);
  1250. }
  1251. private:
  1252. base::test::ScopedFeatureList scoped_feature_list_;
  1253. };
  1254. // Tests that UDPClientSocket respects the global UDP socket limits.
  1255. TEST_F(UDPSocketTest, LimitClientSocket) {
  1256. // Reduce the global UDP limit to 2.
  1257. OverrideUDPSocketLimit set_limit(2);
  1258. ASSERT_EQ(0, GetGlobalUDPSocketCountForTesting());
  1259. auto socket1 = std::make_unique<UDPClientSocket>(DatagramSocket::DEFAULT_BIND,
  1260. nullptr, NetLogSource());
  1261. auto socket2 = std::make_unique<UDPClientSocket>(DatagramSocket::DEFAULT_BIND,
  1262. nullptr, NetLogSource());
  1263. // Simply constructing a UDPClientSocket does not increase the limit (no
  1264. // Connect() or Bind() has been called yet).
  1265. ASSERT_EQ(0, GetGlobalUDPSocketCountForTesting());
  1266. // The specific value of this address doesn't really matter, and no server
  1267. // needs to be running here. The test only needs to call Connect() and won't
  1268. // send any datagrams.
  1269. IPEndPoint server_address(IPAddress::IPv4Localhost(), 8080);
  1270. // Successful Connect() on socket1 increases socket count.
  1271. EXPECT_THAT(socket1->Connect(server_address), IsOk());
  1272. EXPECT_EQ(1, GetGlobalUDPSocketCountForTesting());
  1273. // Successful Connect() on socket2 increases socket count.
  1274. EXPECT_THAT(socket2->Connect(server_address), IsOk());
  1275. EXPECT_EQ(2, GetGlobalUDPSocketCountForTesting());
  1276. // Attempting a third Connect() should fail with ERR_INSUFFICIENT_RESOURCES,
  1277. // as the limit is currently 2.
  1278. auto socket3 = std::make_unique<UDPClientSocket>(DatagramSocket::DEFAULT_BIND,
  1279. nullptr, NetLogSource());
  1280. EXPECT_THAT(socket3->Connect(server_address),
  1281. IsError(ERR_INSUFFICIENT_RESOURCES));
  1282. EXPECT_EQ(2, GetGlobalUDPSocketCountForTesting());
  1283. // Check that explicitly closing socket2 free up a count.
  1284. socket2->Close();
  1285. EXPECT_EQ(1, GetGlobalUDPSocketCountForTesting());
  1286. // Since the socket was already closed, deleting it will not affect the count.
  1287. socket2.reset();
  1288. EXPECT_EQ(1, GetGlobalUDPSocketCountForTesting());
  1289. // Now that the count is below limit, try to connect socket3 again. This time
  1290. // it will work.
  1291. EXPECT_THAT(socket3->Connect(server_address), IsOk());
  1292. EXPECT_EQ(2, GetGlobalUDPSocketCountForTesting());
  1293. // Verify that closing the two remaining sockets brings the open count back to
  1294. // 0.
  1295. socket1.reset();
  1296. EXPECT_EQ(1, GetGlobalUDPSocketCountForTesting());
  1297. socket3.reset();
  1298. EXPECT_EQ(0, GetGlobalUDPSocketCountForTesting());
  1299. }
  1300. // Tests that UDPSocketClient updates the global counter
  1301. // correctly when Connect() fails.
  1302. TEST_F(UDPSocketTest, LimitConnectFail) {
  1303. ASSERT_EQ(0, GetGlobalUDPSocketCountForTesting());
  1304. {
  1305. // Simply allocating a UDPSocket does not increase count.
  1306. UDPSocket socket(DatagramSocket::DEFAULT_BIND, nullptr, NetLogSource());
  1307. EXPECT_EQ(0, GetGlobalUDPSocketCountForTesting());
  1308. // Calling Open() allocates the socket and increases the global counter.
  1309. EXPECT_THAT(socket.Open(ADDRESS_FAMILY_IPV4), IsOk());
  1310. EXPECT_EQ(1, GetGlobalUDPSocketCountForTesting());
  1311. // Connect to an IPv6 address should fail since the socket was created for
  1312. // IPv4.
  1313. EXPECT_THAT(socket.Connect(net::IPEndPoint(IPAddress::IPv6Localhost(), 53)),
  1314. Not(IsOk()));
  1315. // That Connect() failed doesn't change the global counter.
  1316. EXPECT_EQ(1, GetGlobalUDPSocketCountForTesting());
  1317. }
  1318. // Finally, destroying UDPSocket decrements the global counter.
  1319. EXPECT_EQ(0, GetGlobalUDPSocketCountForTesting());
  1320. }
  1321. // Tests allocating UDPClientSockets and Connect()ing them in parallel.
  1322. //
  1323. // This is primarily intended for coverage under TSAN, to check for races
  1324. // enforcing the global socket counter.
  1325. TEST_F(UDPSocketTest, LimitConnectMultithreaded) {
  1326. ASSERT_EQ(0, GetGlobalUDPSocketCountForTesting());
  1327. // Start up some threads.
  1328. std::vector<std::unique_ptr<base::Thread>> threads;
  1329. for (size_t i = 0; i < 5; ++i) {
  1330. threads.push_back(std::make_unique<base::Thread>("Worker thread"));
  1331. ASSERT_TRUE(threads.back()->Start());
  1332. }
  1333. // Post tasks to each of the threads.
  1334. for (const auto& thread : threads) {
  1335. thread->task_runner()->PostTask(
  1336. FROM_HERE, base::BindOnce([] {
  1337. // The specific value of this address doesn't really matter, and no
  1338. // server needs to be running here. The test only needs to call
  1339. // Connect() and won't send any datagrams.
  1340. IPEndPoint server_address(IPAddress::IPv4Localhost(), 8080);
  1341. UDPClientSocket socket(DatagramSocket::DEFAULT_BIND, nullptr,
  1342. NetLogSource());
  1343. EXPECT_THAT(socket.Connect(server_address), IsOk());
  1344. }));
  1345. }
  1346. // Complete all the tasks.
  1347. threads.clear();
  1348. EXPECT_EQ(0, GetGlobalUDPSocketCountForTesting());
  1349. }
  1350. } // namespace net