tcp_socket_unittest.cc 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. // Copyright 2013 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/tcp_socket.h"
  5. #include <stddef.h>
  6. #include <string.h>
  7. #include <memory>
  8. #include <string>
  9. #include <vector>
  10. #include "base/bind.h"
  11. #include "base/memory/ref_counted.h"
  12. #include "base/test/bind.h"
  13. #include "base/time/time.h"
  14. #include "build/build_config.h"
  15. #include "net/base/address_list.h"
  16. #include "net/base/io_buffer.h"
  17. #include "net/base/ip_endpoint.h"
  18. #include "net/base/net_errors.h"
  19. #include "net/base/sockaddr_storage.h"
  20. #include "net/base/sys_addrinfo.h"
  21. #include "net/base/test_completion_callback.h"
  22. #include "net/log/net_log_source.h"
  23. #include "net/socket/socket_descriptor.h"
  24. #include "net/socket/socket_performance_watcher.h"
  25. #include "net/socket/socket_test_util.h"
  26. #include "net/socket/tcp_client_socket.h"
  27. #include "net/test/embedded_test_server/embedded_test_server.h"
  28. #include "net/test/gtest_util.h"
  29. #include "net/test/test_with_task_environment.h"
  30. #include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
  31. #include "testing/gmock/include/gmock/gmock.h"
  32. #include "testing/gtest/include/gtest/gtest.h"
  33. #include "testing/platform_test.h"
  34. #if BUILDFLAG(IS_ANDROID)
  35. #include "base/android/build_info.h"
  36. #include "base/android/radio_utils.h"
  37. #include "base/test/metrics/histogram_tester.h"
  38. #include "base/test/scoped_feature_list.h"
  39. #include "net/android/network_change_notifier_factory_android.h"
  40. #include "net/android/radio_activity_tracker.h"
  41. #include "net/base/features.h"
  42. #include "net/base/network_change_notifier.h"
  43. #endif // BUILDFLAG(IS_ANDROID)
  44. // For getsockopt() call.
  45. #if BUILDFLAG(IS_WIN)
  46. #include <winsock2.h>
  47. #else // !BUILDFLAG(IS_WIN)
  48. #include <sys/socket.h>
  49. #endif // !BUILDFLAG(IS_WIN)
  50. using net::test::IsError;
  51. using net::test::IsOk;
  52. namespace net {
  53. namespace {
  54. // IOBuffer with the ability to invoke a callback when destroyed. Useful for
  55. // checking for leaks.
  56. class IOBufferWithDestructionCallback : public IOBufferWithSize {
  57. public:
  58. explicit IOBufferWithDestructionCallback(base::OnceClosure on_destroy_closure)
  59. : IOBufferWithSize(1024),
  60. on_destroy_closure_(std::move(on_destroy_closure)) {
  61. DCHECK(on_destroy_closure_);
  62. }
  63. protected:
  64. ~IOBufferWithDestructionCallback() override {
  65. std::move(on_destroy_closure_).Run();
  66. }
  67. base::OnceClosure on_destroy_closure_;
  68. };
  69. class TestSocketPerformanceWatcher : public SocketPerformanceWatcher {
  70. public:
  71. explicit TestSocketPerformanceWatcher(bool should_notify_updated_rtt)
  72. : should_notify_updated_rtt_(should_notify_updated_rtt) {}
  73. TestSocketPerformanceWatcher(const TestSocketPerformanceWatcher&) = delete;
  74. TestSocketPerformanceWatcher& operator=(const TestSocketPerformanceWatcher&) =
  75. delete;
  76. ~TestSocketPerformanceWatcher() override = default;
  77. bool ShouldNotifyUpdatedRTT() const override {
  78. return should_notify_updated_rtt_;
  79. }
  80. void OnUpdatedRTTAvailable(const base::TimeDelta& rtt) override {
  81. rtt_notification_count_++;
  82. }
  83. void OnConnectionChanged() override { connection_changed_count_++; }
  84. size_t rtt_notification_count() const { return rtt_notification_count_; }
  85. size_t connection_changed_count() const { return connection_changed_count_; }
  86. private:
  87. const bool should_notify_updated_rtt_;
  88. size_t connection_changed_count_ = 0u;
  89. size_t rtt_notification_count_ = 0u;
  90. };
  91. const int kListenBacklog = 5;
  92. class TCPSocketTest : public PlatformTest, public WithTaskEnvironment {
  93. protected:
  94. TCPSocketTest() : socket_(nullptr, nullptr, NetLogSource()) {}
  95. void SetUpListenIPv4() {
  96. ASSERT_THAT(socket_.Open(ADDRESS_FAMILY_IPV4), IsOk());
  97. ASSERT_THAT(socket_.Bind(IPEndPoint(IPAddress::IPv4Localhost(), 0)),
  98. IsOk());
  99. ASSERT_THAT(socket_.Listen(kListenBacklog), IsOk());
  100. ASSERT_THAT(socket_.GetLocalAddress(&local_address_), IsOk());
  101. }
  102. void SetUpListenIPv6(bool* success) {
  103. *success = false;
  104. if (socket_.Open(ADDRESS_FAMILY_IPV6) != OK ||
  105. socket_.Bind(IPEndPoint(IPAddress::IPv6Localhost(), 0)) != OK ||
  106. socket_.Listen(kListenBacklog) != OK) {
  107. LOG(ERROR) << "Failed to listen on ::1 - probably because IPv6 is "
  108. "disabled. Skipping the test";
  109. return;
  110. }
  111. ASSERT_THAT(socket_.GetLocalAddress(&local_address_), IsOk());
  112. *success = true;
  113. }
  114. void TestAcceptAsync() {
  115. TestCompletionCallback accept_callback;
  116. std::unique_ptr<TCPSocket> accepted_socket;
  117. IPEndPoint accepted_address;
  118. ASSERT_THAT(socket_.Accept(&accepted_socket, &accepted_address,
  119. accept_callback.callback()),
  120. IsError(ERR_IO_PENDING));
  121. TestCompletionCallback connect_callback;
  122. TCPClientSocket connecting_socket(local_address_list(), nullptr, nullptr,
  123. nullptr, NetLogSource());
  124. int connect_result = connecting_socket.Connect(connect_callback.callback());
  125. EXPECT_THAT(connect_callback.GetResult(connect_result), IsOk());
  126. EXPECT_THAT(accept_callback.WaitForResult(), IsOk());
  127. EXPECT_TRUE(accepted_socket.get());
  128. // Both sockets should be on the loopback network interface.
  129. EXPECT_EQ(accepted_address.address(), local_address_.address());
  130. }
  131. #if defined(TCP_INFO) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  132. // Tests that notifications to Socket Performance Watcher (SPW) are delivered
  133. // correctly. |should_notify_updated_rtt| is true if the SPW is interested in
  134. // receiving RTT notifications. |num_messages| is the number of messages that
  135. // are written/read by the sockets. |expect_connection_changed_count| is the
  136. // expected number of connection change notifications received by the SPW.
  137. // |expect_rtt_notification_count| is the expected number of RTT
  138. // notifications received by the SPW. This test works by writing
  139. // |num_messages| to the socket. A different socket (with a SPW attached to
  140. // it) reads the messages.
  141. void TestSPWNotifications(bool should_notify_updated_rtt,
  142. size_t num_messages,
  143. size_t expect_connection_changed_count,
  144. size_t expect_rtt_notification_count) {
  145. ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4());
  146. TestCompletionCallback connect_callback;
  147. auto watcher = std::make_unique<TestSocketPerformanceWatcher>(
  148. should_notify_updated_rtt);
  149. TestSocketPerformanceWatcher* watcher_ptr = watcher.get();
  150. TCPSocket connecting_socket(std::move(watcher), nullptr, NetLogSource());
  151. int result = connecting_socket.Open(ADDRESS_FAMILY_IPV4);
  152. ASSERT_THAT(result, IsOk());
  153. int connect_result =
  154. connecting_socket.Connect(local_address_, connect_callback.callback());
  155. TestCompletionCallback accept_callback;
  156. std::unique_ptr<TCPSocket> accepted_socket;
  157. IPEndPoint accepted_address;
  158. result = socket_.Accept(&accepted_socket, &accepted_address,
  159. accept_callback.callback());
  160. ASSERT_THAT(accept_callback.GetResult(result), IsOk());
  161. ASSERT_TRUE(accepted_socket.get());
  162. // Both sockets should be on the loopback network interface.
  163. EXPECT_EQ(accepted_address.address(), local_address_.address());
  164. ASSERT_THAT(connect_callback.GetResult(connect_result), IsOk());
  165. for (size_t i = 0; i < num_messages; ++i) {
  166. // Use a 1 byte message so that the watcher is notified at most once per
  167. // message.
  168. const std::string message("t");
  169. scoped_refptr<IOBufferWithSize> write_buffer =
  170. base::MakeRefCounted<IOBufferWithSize>(message.size());
  171. memmove(write_buffer->data(), message.data(), message.size());
  172. TestCompletionCallback write_callback;
  173. int write_result = accepted_socket->Write(
  174. write_buffer.get(), write_buffer->size(), write_callback.callback(),
  175. TRAFFIC_ANNOTATION_FOR_TESTS);
  176. scoped_refptr<IOBufferWithSize> read_buffer =
  177. base::MakeRefCounted<IOBufferWithSize>(message.size());
  178. TestCompletionCallback read_callback;
  179. int read_result = connecting_socket.Read(
  180. read_buffer.get(), read_buffer->size(), read_callback.callback());
  181. ASSERT_EQ(1, write_callback.GetResult(write_result));
  182. ASSERT_EQ(1, read_callback.GetResult(read_result));
  183. }
  184. EXPECT_EQ(expect_connection_changed_count,
  185. watcher_ptr->connection_changed_count());
  186. EXPECT_EQ(expect_rtt_notification_count,
  187. watcher_ptr->rtt_notification_count());
  188. }
  189. #endif // defined(TCP_INFO) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  190. AddressList local_address_list() const {
  191. return AddressList(local_address_);
  192. }
  193. TCPSocket socket_;
  194. IPEndPoint local_address_;
  195. };
  196. // Test listening and accepting with a socket bound to an IPv4 address.
  197. TEST_F(TCPSocketTest, Accept) {
  198. ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4());
  199. TestCompletionCallback connect_callback;
  200. // TODO(yzshen): Switch to use TCPSocket when it supports client socket
  201. // operations.
  202. TCPClientSocket connecting_socket(local_address_list(), nullptr, nullptr,
  203. nullptr, NetLogSource());
  204. int connect_result = connecting_socket.Connect(connect_callback.callback());
  205. TestCompletionCallback accept_callback;
  206. std::unique_ptr<TCPSocket> accepted_socket;
  207. IPEndPoint accepted_address;
  208. int result = socket_.Accept(&accepted_socket, &accepted_address,
  209. accept_callback.callback());
  210. ASSERT_THAT(accept_callback.GetResult(result), IsOk());
  211. EXPECT_TRUE(accepted_socket.get());
  212. // Both sockets should be on the loopback network interface.
  213. EXPECT_EQ(accepted_address.address(), local_address_.address());
  214. EXPECT_THAT(connect_callback.GetResult(connect_result), IsOk());
  215. }
  216. // Test Accept() callback.
  217. TEST_F(TCPSocketTest, AcceptAsync) {
  218. ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4());
  219. TestAcceptAsync();
  220. }
  221. // Test AdoptConnectedSocket()
  222. TEST_F(TCPSocketTest, AdoptConnectedSocket) {
  223. TCPSocket accepting_socket(nullptr, nullptr, NetLogSource());
  224. ASSERT_THAT(accepting_socket.Open(ADDRESS_FAMILY_IPV4), IsOk());
  225. ASSERT_THAT(accepting_socket.Bind(IPEndPoint(IPAddress::IPv4Localhost(), 0)),
  226. IsOk());
  227. ASSERT_THAT(accepting_socket.GetLocalAddress(&local_address_), IsOk());
  228. ASSERT_THAT(accepting_socket.Listen(kListenBacklog), IsOk());
  229. TestCompletionCallback connect_callback;
  230. // TODO(yzshen): Switch to use TCPSocket when it supports client socket
  231. // operations.
  232. TCPClientSocket connecting_socket(local_address_list(), nullptr, nullptr,
  233. nullptr, NetLogSource());
  234. int connect_result = connecting_socket.Connect(connect_callback.callback());
  235. TestCompletionCallback accept_callback;
  236. std::unique_ptr<TCPSocket> accepted_socket;
  237. IPEndPoint accepted_address;
  238. int result = accepting_socket.Accept(&accepted_socket, &accepted_address,
  239. accept_callback.callback());
  240. ASSERT_THAT(accept_callback.GetResult(result), IsOk());
  241. SocketDescriptor accepted_descriptor =
  242. accepted_socket->ReleaseSocketDescriptorForTesting();
  243. ASSERT_THAT(
  244. socket_.AdoptConnectedSocket(accepted_descriptor, accepted_address),
  245. IsOk());
  246. // socket_ should now have the local address.
  247. IPEndPoint adopted_address;
  248. ASSERT_THAT(socket_.GetLocalAddress(&adopted_address), IsOk());
  249. EXPECT_EQ(local_address_.address(), adopted_address.address());
  250. EXPECT_THAT(connect_callback.GetResult(connect_result), IsOk());
  251. }
  252. // Test Accept() for AdoptUnconnectedSocket.
  253. TEST_F(TCPSocketTest, AcceptForAdoptedUnconnectedSocket) {
  254. SocketDescriptor existing_socket =
  255. CreatePlatformSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  256. ASSERT_THAT(socket_.AdoptUnconnectedSocket(existing_socket), IsOk());
  257. IPEndPoint address(IPAddress::IPv4Localhost(), 0);
  258. SockaddrStorage storage;
  259. ASSERT_TRUE(address.ToSockAddr(storage.addr, &storage.addr_len));
  260. ASSERT_EQ(0, bind(existing_socket, storage.addr, storage.addr_len));
  261. ASSERT_THAT(socket_.Listen(kListenBacklog), IsOk());
  262. ASSERT_THAT(socket_.GetLocalAddress(&local_address_), IsOk());
  263. TestAcceptAsync();
  264. }
  265. // Accept two connections simultaneously.
  266. TEST_F(TCPSocketTest, Accept2Connections) {
  267. ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4());
  268. TestCompletionCallback accept_callback;
  269. std::unique_ptr<TCPSocket> accepted_socket;
  270. IPEndPoint accepted_address;
  271. ASSERT_THAT(socket_.Accept(&accepted_socket, &accepted_address,
  272. accept_callback.callback()),
  273. IsError(ERR_IO_PENDING));
  274. TestCompletionCallback connect_callback;
  275. TCPClientSocket connecting_socket(local_address_list(), nullptr, nullptr,
  276. nullptr, NetLogSource());
  277. int connect_result = connecting_socket.Connect(connect_callback.callback());
  278. TestCompletionCallback connect_callback2;
  279. TCPClientSocket connecting_socket2(local_address_list(), nullptr, nullptr,
  280. nullptr, NetLogSource());
  281. int connect_result2 =
  282. connecting_socket2.Connect(connect_callback2.callback());
  283. EXPECT_THAT(accept_callback.WaitForResult(), IsOk());
  284. TestCompletionCallback accept_callback2;
  285. std::unique_ptr<TCPSocket> accepted_socket2;
  286. IPEndPoint accepted_address2;
  287. int result = socket_.Accept(&accepted_socket2, &accepted_address2,
  288. accept_callback2.callback());
  289. ASSERT_THAT(accept_callback2.GetResult(result), IsOk());
  290. EXPECT_THAT(connect_callback.GetResult(connect_result), IsOk());
  291. EXPECT_THAT(connect_callback2.GetResult(connect_result2), IsOk());
  292. EXPECT_TRUE(accepted_socket.get());
  293. EXPECT_TRUE(accepted_socket2.get());
  294. EXPECT_NE(accepted_socket.get(), accepted_socket2.get());
  295. EXPECT_EQ(accepted_address.address(), local_address_.address());
  296. EXPECT_EQ(accepted_address2.address(), local_address_.address());
  297. }
  298. // Test listening and accepting with a socket bound to an IPv6 address.
  299. TEST_F(TCPSocketTest, AcceptIPv6) {
  300. bool initialized = false;
  301. ASSERT_NO_FATAL_FAILURE(SetUpListenIPv6(&initialized));
  302. if (!initialized)
  303. return;
  304. TestCompletionCallback connect_callback;
  305. TCPClientSocket connecting_socket(local_address_list(), nullptr, nullptr,
  306. nullptr, NetLogSource());
  307. int connect_result = connecting_socket.Connect(connect_callback.callback());
  308. TestCompletionCallback accept_callback;
  309. std::unique_ptr<TCPSocket> accepted_socket;
  310. IPEndPoint accepted_address;
  311. int result = socket_.Accept(&accepted_socket, &accepted_address,
  312. accept_callback.callback());
  313. ASSERT_THAT(accept_callback.GetResult(result), IsOk());
  314. EXPECT_TRUE(accepted_socket.get());
  315. // Both sockets should be on the loopback network interface.
  316. EXPECT_EQ(accepted_address.address(), local_address_.address());
  317. EXPECT_THAT(connect_callback.GetResult(connect_result), IsOk());
  318. }
  319. TEST_F(TCPSocketTest, ReadWrite) {
  320. ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4());
  321. TestCompletionCallback connect_callback;
  322. TCPSocket connecting_socket(nullptr, nullptr, NetLogSource());
  323. int result = connecting_socket.Open(ADDRESS_FAMILY_IPV4);
  324. ASSERT_THAT(result, IsOk());
  325. int connect_result =
  326. connecting_socket.Connect(local_address_, connect_callback.callback());
  327. TestCompletionCallback accept_callback;
  328. std::unique_ptr<TCPSocket> accepted_socket;
  329. IPEndPoint accepted_address;
  330. result = socket_.Accept(&accepted_socket, &accepted_address,
  331. accept_callback.callback());
  332. ASSERT_THAT(accept_callback.GetResult(result), IsOk());
  333. ASSERT_TRUE(accepted_socket.get());
  334. // Both sockets should be on the loopback network interface.
  335. EXPECT_EQ(accepted_address.address(), local_address_.address());
  336. EXPECT_THAT(connect_callback.GetResult(connect_result), IsOk());
  337. const std::string message("test message");
  338. std::vector<char> buffer(message.size());
  339. size_t bytes_written = 0;
  340. while (bytes_written < message.size()) {
  341. scoped_refptr<IOBufferWithSize> write_buffer =
  342. base::MakeRefCounted<IOBufferWithSize>(message.size() - bytes_written);
  343. memmove(write_buffer->data(), message.data() + bytes_written,
  344. message.size() - bytes_written);
  345. TestCompletionCallback write_callback;
  346. int write_result = accepted_socket->Write(
  347. write_buffer.get(), write_buffer->size(), write_callback.callback(),
  348. TRAFFIC_ANNOTATION_FOR_TESTS);
  349. write_result = write_callback.GetResult(write_result);
  350. ASSERT_TRUE(write_result >= 0);
  351. bytes_written += write_result;
  352. ASSERT_TRUE(bytes_written <= message.size());
  353. }
  354. size_t bytes_read = 0;
  355. while (bytes_read < message.size()) {
  356. scoped_refptr<IOBufferWithSize> read_buffer =
  357. base::MakeRefCounted<IOBufferWithSize>(message.size() - bytes_read);
  358. TestCompletionCallback read_callback;
  359. int read_result = connecting_socket.Read(
  360. read_buffer.get(), read_buffer->size(), read_callback.callback());
  361. read_result = read_callback.GetResult(read_result);
  362. ASSERT_TRUE(read_result >= 0);
  363. ASSERT_TRUE(bytes_read + read_result <= message.size());
  364. memmove(&buffer[bytes_read], read_buffer->data(), read_result);
  365. bytes_read += read_result;
  366. }
  367. std::string received_message(buffer.begin(), buffer.end());
  368. ASSERT_EQ(message, received_message);
  369. }
  370. // Destroy a TCPSocket while there's a pending read, and make sure the read
  371. // IOBuffer that the socket was holding on to is destroyed.
  372. // See https://crbug.com/804868.
  373. TEST_F(TCPSocketTest, DestroyWithPendingRead) {
  374. ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4());
  375. // Create a connected socket.
  376. TestCompletionCallback connect_callback;
  377. std::unique_ptr<TCPSocket> connecting_socket =
  378. std::make_unique<TCPSocket>(nullptr, nullptr, NetLogSource());
  379. int result = connecting_socket->Open(ADDRESS_FAMILY_IPV4);
  380. ASSERT_THAT(result, IsOk());
  381. int connect_result =
  382. connecting_socket->Connect(local_address_, connect_callback.callback());
  383. TestCompletionCallback accept_callback;
  384. std::unique_ptr<TCPSocket> accepted_socket;
  385. IPEndPoint accepted_address;
  386. result = socket_.Accept(&accepted_socket, &accepted_address,
  387. accept_callback.callback());
  388. ASSERT_THAT(accept_callback.GetResult(result), IsOk());
  389. ASSERT_TRUE(accepted_socket.get());
  390. ASSERT_THAT(connect_callback.GetResult(connect_result), IsOk());
  391. // Try to read from the socket, but never write anything to the other end.
  392. base::RunLoop run_loop;
  393. scoped_refptr<IOBufferWithDestructionCallback> read_buffer(
  394. base::MakeRefCounted<IOBufferWithDestructionCallback>(
  395. run_loop.QuitClosure()));
  396. TestCompletionCallback read_callback;
  397. EXPECT_EQ(ERR_IO_PENDING,
  398. connecting_socket->Read(read_buffer.get(), read_buffer->size(),
  399. read_callback.callback()));
  400. // Release the handle to the read buffer and destroy the socket. Make sure the
  401. // read buffer is destroyed.
  402. read_buffer = nullptr;
  403. connecting_socket.reset();
  404. run_loop.Run();
  405. }
  406. // Destroy a TCPSocket while there's a pending write, and make sure the write
  407. // IOBuffer that the socket was holding on to is destroyed.
  408. TEST_F(TCPSocketTest, DestroyWithPendingWrite) {
  409. ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4());
  410. // Create a connected socket.
  411. TestCompletionCallback connect_callback;
  412. std::unique_ptr<TCPSocket> connecting_socket =
  413. std::make_unique<TCPSocket>(nullptr, nullptr, NetLogSource());
  414. int result = connecting_socket->Open(ADDRESS_FAMILY_IPV4);
  415. ASSERT_THAT(result, IsOk());
  416. int connect_result =
  417. connecting_socket->Connect(local_address_, connect_callback.callback());
  418. TestCompletionCallback accept_callback;
  419. std::unique_ptr<TCPSocket> accepted_socket;
  420. IPEndPoint accepted_address;
  421. result = socket_.Accept(&accepted_socket, &accepted_address,
  422. accept_callback.callback());
  423. ASSERT_THAT(accept_callback.GetResult(result), IsOk());
  424. ASSERT_TRUE(accepted_socket.get());
  425. ASSERT_THAT(connect_callback.GetResult(connect_result), IsOk());
  426. // Repeatedly write to the socket until an operation does not complete
  427. // synchronously.
  428. base::RunLoop run_loop;
  429. scoped_refptr<IOBufferWithDestructionCallback> write_buffer(
  430. base::MakeRefCounted<IOBufferWithDestructionCallback>(
  431. run_loop.QuitClosure()));
  432. memset(write_buffer->data(), '1', write_buffer->size());
  433. TestCompletionCallback write_callback;
  434. while (true) {
  435. result = connecting_socket->Write(write_buffer.get(), write_buffer->size(),
  436. write_callback.callback(),
  437. TRAFFIC_ANNOTATION_FOR_TESTS);
  438. if (result == ERR_IO_PENDING)
  439. break;
  440. ASSERT_LT(0, result);
  441. }
  442. // Release the handle to the read buffer and destroy the socket. Make sure the
  443. // write buffer is destroyed.
  444. write_buffer = nullptr;
  445. connecting_socket.reset();
  446. run_loop.Run();
  447. }
  448. // If a ReadIfReady is pending, it's legal to cancel it and start reading later.
  449. TEST_F(TCPSocketTest, CancelPendingReadIfReady) {
  450. ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4());
  451. // Create a connected socket.
  452. TestCompletionCallback connect_callback;
  453. std::unique_ptr<TCPSocket> connecting_socket =
  454. std::make_unique<TCPSocket>(nullptr, nullptr, NetLogSource());
  455. int result = connecting_socket->Open(ADDRESS_FAMILY_IPV4);
  456. ASSERT_THAT(result, IsOk());
  457. int connect_result =
  458. connecting_socket->Connect(local_address_, connect_callback.callback());
  459. TestCompletionCallback accept_callback;
  460. std::unique_ptr<TCPSocket> accepted_socket;
  461. IPEndPoint accepted_address;
  462. result = socket_.Accept(&accepted_socket, &accepted_address,
  463. accept_callback.callback());
  464. ASSERT_THAT(accept_callback.GetResult(result), IsOk());
  465. ASSERT_TRUE(accepted_socket.get());
  466. ASSERT_THAT(connect_callback.GetResult(connect_result), IsOk());
  467. // Try to read from the socket, but never write anything to the other end.
  468. base::RunLoop run_loop;
  469. scoped_refptr<IOBufferWithDestructionCallback> read_buffer(
  470. base::MakeRefCounted<IOBufferWithDestructionCallback>(
  471. run_loop.QuitClosure()));
  472. TestCompletionCallback read_callback;
  473. EXPECT_EQ(ERR_IO_PENDING, connecting_socket->ReadIfReady(
  474. read_buffer.get(), read_buffer->size(),
  475. read_callback.callback()));
  476. // Now cancel the pending ReadIfReady().
  477. connecting_socket->CancelReadIfReady();
  478. // Send data to |connecting_socket|.
  479. const char kMsg[] = "hello!";
  480. scoped_refptr<StringIOBuffer> write_buffer =
  481. base::MakeRefCounted<StringIOBuffer>(kMsg);
  482. TestCompletionCallback write_callback;
  483. int write_result = accepted_socket->Write(write_buffer.get(), strlen(kMsg),
  484. write_callback.callback(),
  485. TRAFFIC_ANNOTATION_FOR_TESTS);
  486. const int msg_size = strlen(kMsg);
  487. ASSERT_EQ(msg_size, write_result);
  488. TestCompletionCallback read_callback2;
  489. int read_result = connecting_socket->ReadIfReady(
  490. read_buffer.get(), read_buffer->size(), read_callback2.callback());
  491. if (read_result == ERR_IO_PENDING) {
  492. ASSERT_EQ(OK, read_callback2.GetResult(read_result));
  493. read_result = connecting_socket->ReadIfReady(
  494. read_buffer.get(), read_buffer->size(), read_callback2.callback());
  495. }
  496. ASSERT_EQ(msg_size, read_result);
  497. ASSERT_EQ(0, memcmp(&kMsg, read_buffer->data(), msg_size));
  498. }
  499. TEST_F(TCPSocketTest, IsConnected) {
  500. ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4());
  501. TestCompletionCallback accept_callback;
  502. std::unique_ptr<TCPSocket> accepted_socket;
  503. IPEndPoint accepted_address;
  504. EXPECT_THAT(socket_.Accept(&accepted_socket, &accepted_address,
  505. accept_callback.callback()),
  506. IsError(ERR_IO_PENDING));
  507. TestCompletionCallback connect_callback;
  508. TCPClientSocket connecting_socket(local_address_list(), nullptr, nullptr,
  509. nullptr, NetLogSource());
  510. // Immediately after creation, the socket should not be connected.
  511. EXPECT_FALSE(connecting_socket.IsConnected());
  512. EXPECT_FALSE(connecting_socket.IsConnectedAndIdle());
  513. int connect_result = connecting_socket.Connect(connect_callback.callback());
  514. EXPECT_THAT(accept_callback.WaitForResult(), IsOk());
  515. EXPECT_THAT(connect_callback.GetResult(connect_result), IsOk());
  516. // |connecting_socket| and |accepted_socket| should now both be reported as
  517. // connected, and idle
  518. EXPECT_TRUE(accepted_socket->IsConnected());
  519. EXPECT_TRUE(accepted_socket->IsConnectedAndIdle());
  520. EXPECT_TRUE(connecting_socket.IsConnected());
  521. EXPECT_TRUE(connecting_socket.IsConnectedAndIdle());
  522. // Write one byte to the |accepted_socket|, then close it.
  523. const char kSomeData[] = "!";
  524. scoped_refptr<IOBuffer> some_data_buffer =
  525. base::MakeRefCounted<StringIOBuffer>(kSomeData);
  526. TestCompletionCallback write_callback;
  527. EXPECT_THAT(write_callback.GetResult(accepted_socket->Write(
  528. some_data_buffer.get(), 1, write_callback.callback(),
  529. TRAFFIC_ANNOTATION_FOR_TESTS)),
  530. 1);
  531. accepted_socket.reset();
  532. // Wait until |connecting_socket| is signalled as having data to read.
  533. fd_set read_fds;
  534. FD_ZERO(&read_fds);
  535. SocketDescriptor connecting_fd =
  536. connecting_socket.SocketDescriptorForTesting();
  537. FD_SET(connecting_fd, &read_fds);
  538. ASSERT_EQ(select(FD_SETSIZE, &read_fds, nullptr, nullptr, nullptr), 1);
  539. ASSERT_TRUE(FD_ISSET(connecting_fd, &read_fds));
  540. // It should now be reported as connected, but not as idle.
  541. EXPECT_TRUE(connecting_socket.IsConnected());
  542. EXPECT_FALSE(connecting_socket.IsConnectedAndIdle());
  543. // Read the message from |connecting_socket_|, then read the end-of-stream.
  544. scoped_refptr<IOBufferWithSize> read_buffer =
  545. base::MakeRefCounted<IOBufferWithSize>(2);
  546. TestCompletionCallback read_callback;
  547. EXPECT_THAT(
  548. read_callback.GetResult(connecting_socket.Read(
  549. read_buffer.get(), read_buffer->size(), read_callback.callback())),
  550. 1);
  551. EXPECT_THAT(
  552. read_callback.GetResult(connecting_socket.Read(
  553. read_buffer.get(), read_buffer->size(), read_callback.callback())),
  554. 0);
  555. // |connecting_socket| has no more data to read, so should noe be reported
  556. // as disconnected.
  557. EXPECT_FALSE(connecting_socket.IsConnected());
  558. EXPECT_FALSE(connecting_socket.IsConnectedAndIdle());
  559. }
  560. // Tests that setting a socket option in the BeforeConnectCallback works. With
  561. // real sockets, socket options often have to be set before the connect() call,
  562. // and the BeforeConnectCallback is the only way to do that, with a
  563. // TCPClientSocket.
  564. TEST_F(TCPSocketTest, BeforeConnectCallback) {
  565. // A receive buffer size that is between max and minimum buffer size limits,
  566. // and weird enough to likely not be a default value.
  567. const int kReceiveBufferSize = 32 * 1024 + 1117;
  568. ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4());
  569. TestCompletionCallback accept_callback;
  570. std::unique_ptr<TCPSocket> accepted_socket;
  571. IPEndPoint accepted_address;
  572. EXPECT_THAT(socket_.Accept(&accepted_socket, &accepted_address,
  573. accept_callback.callback()),
  574. IsError(ERR_IO_PENDING));
  575. TestCompletionCallback connect_callback;
  576. TCPClientSocket connecting_socket(local_address_list(), nullptr, nullptr,
  577. nullptr, NetLogSource());
  578. connecting_socket.SetBeforeConnectCallback(base::BindLambdaForTesting([&] {
  579. EXPECT_FALSE(connecting_socket.IsConnected());
  580. int result = connecting_socket.SetReceiveBufferSize(kReceiveBufferSize);
  581. EXPECT_THAT(result, IsOk());
  582. return result;
  583. }));
  584. int connect_result = connecting_socket.Connect(connect_callback.callback());
  585. EXPECT_THAT(accept_callback.WaitForResult(), IsOk());
  586. EXPECT_THAT(connect_callback.GetResult(connect_result), IsOk());
  587. int actual_size = 0;
  588. socklen_t actual_size_len = sizeof(actual_size);
  589. int os_result = getsockopt(
  590. connecting_socket.SocketDescriptorForTesting(), SOL_SOCKET, SO_RCVBUF,
  591. reinterpret_cast<char*>(&actual_size), &actual_size_len);
  592. ASSERT_EQ(0, os_result);
  593. // Linux platforms generally allocate twice as much buffer size is requested to
  594. // account for internal kernel data structures.
  595. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
  596. EXPECT_EQ(2 * kReceiveBufferSize, actual_size);
  597. // Unfortunately, Apple platform behavior doesn't seem to be documented, and
  598. // doesn't match behavior on any other platforms.
  599. // Fuchsia doesn't currently implement SO_RCVBUF.
  600. #elif !BUILDFLAG(IS_APPLE) && !BUILDFLAG(IS_FUCHSIA)
  601. EXPECT_EQ(kReceiveBufferSize, actual_size);
  602. #endif
  603. }
  604. TEST_F(TCPSocketTest, BeforeConnectCallbackFails) {
  605. // Setting up a server isn't strictly necessary, but it does allow checking
  606. // the server was never connected to.
  607. ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4());
  608. TestCompletionCallback accept_callback;
  609. std::unique_ptr<TCPSocket> accepted_socket;
  610. IPEndPoint accepted_address;
  611. EXPECT_THAT(socket_.Accept(&accepted_socket, &accepted_address,
  612. accept_callback.callback()),
  613. IsError(ERR_IO_PENDING));
  614. TestCompletionCallback connect_callback;
  615. TCPClientSocket connecting_socket(local_address_list(), nullptr, nullptr,
  616. nullptr, NetLogSource());
  617. // Set a callback that returns a nonsensical error, and make sure it's
  618. // returned.
  619. connecting_socket.SetBeforeConnectCallback(base::BindRepeating(
  620. [] { return static_cast<int>(net::ERR_NAME_NOT_RESOLVED); }));
  621. int connect_result = connecting_socket.Connect(connect_callback.callback());
  622. EXPECT_THAT(connect_callback.GetResult(connect_result),
  623. IsError(net::ERR_NAME_NOT_RESOLVED));
  624. // Best effort check that the socket wasn't accepted - may flakily pass on
  625. // regression, unfortunately.
  626. base::RunLoop().RunUntilIdle();
  627. EXPECT_FALSE(accept_callback.have_result());
  628. }
  629. TEST_F(TCPSocketTest, SetKeepAlive) {
  630. ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4());
  631. TestCompletionCallback accept_callback;
  632. std::unique_ptr<TCPSocket> accepted_socket;
  633. IPEndPoint accepted_address;
  634. EXPECT_THAT(socket_.Accept(&accepted_socket, &accepted_address,
  635. accept_callback.callback()),
  636. IsError(ERR_IO_PENDING));
  637. TestCompletionCallback connect_callback;
  638. TCPClientSocket connecting_socket(local_address_list(), nullptr, nullptr,
  639. nullptr, NetLogSource());
  640. // Non-connected sockets should not be able to set KeepAlive.
  641. ASSERT_FALSE(connecting_socket.IsConnected());
  642. EXPECT_FALSE(
  643. connecting_socket.SetKeepAlive(true /* enable */, 14 /* delay */));
  644. // Connect.
  645. int connect_result = connecting_socket.Connect(connect_callback.callback());
  646. EXPECT_THAT(accept_callback.WaitForResult(), IsOk());
  647. EXPECT_THAT(connect_callback.GetResult(connect_result), IsOk());
  648. // Connected sockets should be able to enable and disable KeepAlive.
  649. ASSERT_TRUE(connecting_socket.IsConnected());
  650. EXPECT_TRUE(
  651. connecting_socket.SetKeepAlive(true /* enable */, 22 /* delay */));
  652. EXPECT_TRUE(
  653. connecting_socket.SetKeepAlive(false /* enable */, 3 /* delay */));
  654. }
  655. TEST_F(TCPSocketTest, SetNoDelay) {
  656. ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4());
  657. TestCompletionCallback accept_callback;
  658. std::unique_ptr<TCPSocket> accepted_socket;
  659. IPEndPoint accepted_address;
  660. EXPECT_THAT(socket_.Accept(&accepted_socket, &accepted_address,
  661. accept_callback.callback()),
  662. IsError(ERR_IO_PENDING));
  663. TestCompletionCallback connect_callback;
  664. TCPClientSocket connecting_socket(local_address_list(), nullptr, nullptr,
  665. nullptr, NetLogSource());
  666. // Non-connected sockets should not be able to set NoDelay.
  667. ASSERT_FALSE(connecting_socket.IsConnected());
  668. EXPECT_FALSE(connecting_socket.SetNoDelay(true /* no_delay */));
  669. // Connect.
  670. int connect_result = connecting_socket.Connect(connect_callback.callback());
  671. EXPECT_THAT(accept_callback.WaitForResult(), IsOk());
  672. EXPECT_THAT(connect_callback.GetResult(connect_result), IsOk());
  673. // Connected sockets should be able to enable and disable NoDelay.
  674. ASSERT_TRUE(connecting_socket.IsConnected());
  675. EXPECT_TRUE(connecting_socket.SetNoDelay(true /* no_delay */));
  676. EXPECT_TRUE(connecting_socket.SetNoDelay(false /* no_delay */));
  677. }
  678. // These tests require kernel support for tcp_info struct, and so they are
  679. // enabled only on certain platforms.
  680. #if defined(TCP_INFO) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  681. // If SocketPerformanceWatcher::ShouldNotifyUpdatedRTT always returns false,
  682. // then the wtatcher should not receive any notifications.
  683. TEST_F(TCPSocketTest, SPWNotInterested) {
  684. TestSPWNotifications(false, 2u, 0u, 0u);
  685. }
  686. // One notification should be received when the socket connects. One
  687. // additional notification should be received for each message read.
  688. TEST_F(TCPSocketTest, SPWNoAdvance) {
  689. TestSPWNotifications(true, 2u, 0u, 3u);
  690. }
  691. #endif // defined(TCP_INFO) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  692. // On Android, where socket tagging is supported, verify that TCPSocket::Tag
  693. // works as expected.
  694. #if BUILDFLAG(IS_ANDROID)
  695. TEST_F(TCPSocketTest, Tag) {
  696. if (!CanGetTaggedBytes()) {
  697. DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
  698. return;
  699. }
  700. // Start test server.
  701. EmbeddedTestServer test_server;
  702. test_server.AddDefaultHandlers(base::FilePath());
  703. ASSERT_TRUE(test_server.Start());
  704. AddressList addr_list;
  705. ASSERT_TRUE(test_server.GetAddressList(&addr_list));
  706. EXPECT_EQ(socket_.Open(addr_list[0].GetFamily()), OK);
  707. // Verify TCP connect packets are tagged and counted properly.
  708. int32_t tag_val1 = 0x12345678;
  709. uint64_t old_traffic = GetTaggedBytes(tag_val1);
  710. SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
  711. socket_.ApplySocketTag(tag1);
  712. TestCompletionCallback connect_callback;
  713. int connect_result =
  714. socket_.Connect(addr_list[0], connect_callback.callback());
  715. EXPECT_THAT(connect_callback.GetResult(connect_result), IsOk());
  716. EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
  717. // Verify socket can be retagged with a new value and the current process's
  718. // UID.
  719. int32_t tag_val2 = 0x87654321;
  720. old_traffic = GetTaggedBytes(tag_val2);
  721. SocketTag tag2(getuid(), tag_val2);
  722. socket_.ApplySocketTag(tag2);
  723. const char kRequest1[] = "GET / HTTP/1.0";
  724. scoped_refptr<IOBuffer> write_buffer1 =
  725. base::MakeRefCounted<StringIOBuffer>(kRequest1);
  726. TestCompletionCallback write_callback1;
  727. EXPECT_EQ(
  728. socket_.Write(write_buffer1.get(), strlen(kRequest1),
  729. write_callback1.callback(), TRAFFIC_ANNOTATION_FOR_TESTS),
  730. static_cast<int>(strlen(kRequest1)));
  731. EXPECT_GT(GetTaggedBytes(tag_val2), old_traffic);
  732. // Verify socket can be retagged with a new value and the current process's
  733. // UID.
  734. old_traffic = GetTaggedBytes(tag_val1);
  735. socket_.ApplySocketTag(tag1);
  736. const char kRequest2[] = "\n\n";
  737. scoped_refptr<IOBuffer> write_buffer2 =
  738. base::MakeRefCounted<StringIOBuffer>(kRequest2);
  739. TestCompletionCallback write_callback2;
  740. EXPECT_EQ(
  741. socket_.Write(write_buffer2.get(), strlen(kRequest2),
  742. write_callback2.callback(), TRAFFIC_ANNOTATION_FOR_TESTS),
  743. static_cast<int>(strlen(kRequest2)));
  744. EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
  745. socket_.Close();
  746. }
  747. TEST_F(TCPSocketTest, TagAfterConnect) {
  748. if (!CanGetTaggedBytes()) {
  749. DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
  750. return;
  751. }
  752. // Start test server.
  753. EmbeddedTestServer test_server;
  754. test_server.AddDefaultHandlers(base::FilePath());
  755. ASSERT_TRUE(test_server.Start());
  756. AddressList addr_list;
  757. ASSERT_TRUE(test_server.GetAddressList(&addr_list));
  758. EXPECT_EQ(socket_.Open(addr_list[0].GetFamily()), OK);
  759. // Connect socket.
  760. TestCompletionCallback connect_callback;
  761. int connect_result =
  762. socket_.Connect(addr_list[0], connect_callback.callback());
  763. EXPECT_THAT(connect_callback.GetResult(connect_result), IsOk());
  764. // Verify socket can be tagged with a new value and the current process's
  765. // UID.
  766. int32_t tag_val2 = 0x87654321;
  767. uint64_t old_traffic = GetTaggedBytes(tag_val2);
  768. SocketTag tag2(getuid(), tag_val2);
  769. socket_.ApplySocketTag(tag2);
  770. const char kRequest1[] = "GET / HTTP/1.0";
  771. scoped_refptr<IOBuffer> write_buffer1 =
  772. base::MakeRefCounted<StringIOBuffer>(kRequest1);
  773. TestCompletionCallback write_callback1;
  774. EXPECT_EQ(
  775. socket_.Write(write_buffer1.get(), strlen(kRequest1),
  776. write_callback1.callback(), TRAFFIC_ANNOTATION_FOR_TESTS),
  777. static_cast<int>(strlen(kRequest1)));
  778. EXPECT_GT(GetTaggedBytes(tag_val2), old_traffic);
  779. // Verify socket can be retagged with a new value and the current process's
  780. // UID.
  781. int32_t tag_val1 = 0x12345678;
  782. old_traffic = GetTaggedBytes(tag_val1);
  783. SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
  784. socket_.ApplySocketTag(tag1);
  785. const char kRequest2[] = "\n\n";
  786. scoped_refptr<IOBuffer> write_buffer2 =
  787. base::MakeRefCounted<StringIOBuffer>(kRequest2);
  788. TestCompletionCallback write_callback2;
  789. EXPECT_EQ(
  790. socket_.Write(write_buffer2.get(), strlen(kRequest2),
  791. write_callback2.callback(), TRAFFIC_ANNOTATION_FOR_TESTS),
  792. static_cast<int>(strlen(kRequest2)));
  793. EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
  794. socket_.Close();
  795. }
  796. TEST_F(TCPSocketTest, RecordRadioWakeUpTrigger) {
  797. base::test::ScopedFeatureList feature_list;
  798. feature_list.InitAndEnableFeature(features::kRecordRadioWakeupTrigger);
  799. base::HistogramTester histograms;
  800. // Simulates the radio state is dormant.
  801. android::RadioActivityTracker::GetInstance().OverrideRadioActivityForTesting(
  802. base::android::RadioDataActivity::kDormant);
  803. android::RadioActivityTracker::GetInstance().OverrideRadioTypeForTesting(
  804. base::android::RadioConnectionType::kCell);
  805. ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4());
  806. // Create a connected socket.
  807. TestCompletionCallback connect_callback;
  808. std::unique_ptr<TCPSocket> connecting_socket =
  809. std::make_unique<TCPSocket>(nullptr, nullptr, NetLogSource());
  810. int result = connecting_socket->Open(ADDRESS_FAMILY_IPV4);
  811. ASSERT_THAT(result, IsOk());
  812. int connect_result =
  813. connecting_socket->Connect(local_address_, connect_callback.callback());
  814. TestCompletionCallback accept_callback;
  815. std::unique_ptr<TCPSocket> accepted_socket;
  816. IPEndPoint accepted_address;
  817. result = socket_.Accept(&accepted_socket, &accepted_address,
  818. accept_callback.callback());
  819. ASSERT_THAT(accept_callback.GetResult(result), IsOk());
  820. ASSERT_TRUE(accepted_socket.get());
  821. ASSERT_THAT(connect_callback.GetResult(connect_result), IsOk());
  822. // Write to the socket once.
  823. base::RunLoop run_loop;
  824. scoped_refptr<IOBufferWithDestructionCallback> write_buffer(
  825. base::MakeRefCounted<IOBufferWithDestructionCallback>(
  826. run_loop.QuitClosure()));
  827. memset(write_buffer->data(), '1', write_buffer->size());
  828. TestCompletionCallback write_callback;
  829. result = connecting_socket->Write(write_buffer.get(), write_buffer->size(),
  830. write_callback.callback(),
  831. TRAFFIC_ANNOTATION_FOR_TESTS);
  832. ASSERT_LT(0, result);
  833. // Release the handle to the read buffer and destroy the socket. Make sure the
  834. // write buffer is destroyed.
  835. write_buffer = nullptr;
  836. connecting_socket.reset();
  837. run_loop.Run();
  838. // Check the write is recorded as a possible radio wake-up trigger.
  839. histograms.ExpectTotalCount(
  840. android::kUmaNamePossibleWakeupTriggerTCPWriteAnnotationId, 1);
  841. }
  842. TEST_F(TCPSocketTest, BindToNetwork) {
  843. NetworkChangeNotifierFactoryAndroid ncn_factory;
  844. NetworkChangeNotifier::DisableForTest ncn_disable_for_test;
  845. std::unique_ptr<NetworkChangeNotifier> ncn(ncn_factory.CreateInstance());
  846. if (!NetworkChangeNotifier::AreNetworkHandlesSupported())
  847. GTEST_SKIP() << "Network handles are required to test BindToNetwork.";
  848. const handles::NetworkHandle wrong_network_handle = 65536;
  849. // Try binding to this IP to trigger the underlying BindToNetwork call.
  850. const IPEndPoint ip(IPAddress::IPv4Localhost(), 0);
  851. // TestCompletionCallback connect_callback;
  852. TCPClientSocket connecting_socket(local_address_list(), nullptr, nullptr,
  853. nullptr, NetLogSource(),
  854. wrong_network_handle);
  855. // Different Android versions might report different errors. Hence, just check
  856. // what shouldn't happen.
  857. int rv = connecting_socket.Bind(ip);
  858. EXPECT_NE(OK, rv);
  859. EXPECT_NE(ERR_NOT_IMPLEMENTED, rv);
  860. // Connecting using an existing network should succeed.
  861. const handles::NetworkHandle network_handle =
  862. NetworkChangeNotifier::GetDefaultNetwork();
  863. if (network_handle != handles::kInvalidNetworkHandle) {
  864. TCPClientSocket connecting_socket(local_address_list(), nullptr, nullptr,
  865. nullptr, NetLogSource(),
  866. wrong_network_handle);
  867. EXPECT_EQ(OK, connecting_socket.Bind(ip));
  868. }
  869. }
  870. #endif // BUILDFLAG(IS_ANDROID)
  871. } // namespace
  872. } // namespace net