transport_client_socket_unittest.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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/transport_client_socket_test_util.h"
  5. #include <string>
  6. #include "base/bind.h"
  7. #include "base/memory/raw_ptr.h"
  8. #include "base/memory/ref_counted.h"
  9. #include "base/run_loop.h"
  10. #include "net/base/address_list.h"
  11. #include "net/base/io_buffer.h"
  12. #include "net/base/ip_address.h"
  13. #include "net/base/net_errors.h"
  14. #include "net/base/test_completion_callback.h"
  15. #include "net/log/net_log_event_type.h"
  16. #include "net/log/net_log_source.h"
  17. #include "net/log/net_log_with_source.h"
  18. #include "net/log/test_net_log.h"
  19. #include "net/log/test_net_log_util.h"
  20. #include "net/socket/client_socket_factory.h"
  21. #include "net/socket/tcp_client_socket.h"
  22. #include "net/socket/tcp_server_socket.h"
  23. #include "net/test/gtest_util.h"
  24. #include "net/test/test_with_task_environment.h"
  25. #include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
  26. #include "testing/gmock/include/gmock/gmock.h"
  27. #include "testing/gtest/include/gtest/gtest.h"
  28. #include "testing/platform_test.h"
  29. using net::test::IsError;
  30. using net::test::IsOk;
  31. namespace net {
  32. namespace {
  33. const char kServerReply[] = "HTTP/1.1 404 Not Found";
  34. } // namespace
  35. class TransportClientSocketTest : public ::testing::Test,
  36. public WithTaskEnvironment {
  37. public:
  38. TransportClientSocketTest()
  39. : socket_factory_(ClientSocketFactory::GetDefaultFactory()) {}
  40. ~TransportClientSocketTest() override = default;
  41. // Testcase hooks
  42. void SetUp() override;
  43. void CloseServerSocket() {
  44. // delete the connected_sock_, which will close it.
  45. connected_sock_.reset();
  46. }
  47. void AcceptCallback(int res) {
  48. ASSERT_THAT(res, IsOk());
  49. connect_loop_.Quit();
  50. }
  51. // Establishes a connection to the server.
  52. void EstablishConnection(TestCompletionCallback* callback);
  53. protected:
  54. base::RunLoop connect_loop_;
  55. uint16_t listen_port_ = 0;
  56. RecordingNetLogObserver net_log_observer_;
  57. const raw_ptr<ClientSocketFactory> socket_factory_;
  58. std::unique_ptr<StreamSocket> sock_;
  59. std::unique_ptr<StreamSocket> connected_sock_;
  60. private:
  61. std::unique_ptr<TCPServerSocket> listen_sock_;
  62. };
  63. void TransportClientSocketTest::SetUp() {
  64. // Open a server socket on an ephemeral port.
  65. listen_sock_ = std::make_unique<TCPServerSocket>(nullptr, NetLogSource());
  66. IPEndPoint local_address(IPAddress::IPv4Localhost(), 0);
  67. ASSERT_THAT(listen_sock_->Listen(local_address, 1), IsOk());
  68. // Get the server's address (including the actual port number).
  69. ASSERT_THAT(listen_sock_->GetLocalAddress(&local_address), IsOk());
  70. listen_port_ = local_address.port();
  71. listen_sock_->Accept(
  72. &connected_sock_,
  73. base::BindOnce(&TransportClientSocketTest::AcceptCallback,
  74. base::Unretained(this)));
  75. AddressList addr = AddressList::CreateFromIPAddress(
  76. IPAddress::IPv4Localhost(), listen_port_);
  77. sock_ = socket_factory_->CreateTransportClientSocket(
  78. addr, nullptr, nullptr, NetLog::Get(), NetLogSource());
  79. }
  80. void TransportClientSocketTest::EstablishConnection(
  81. TestCompletionCallback* callback) {
  82. int rv = sock_->Connect(callback->callback());
  83. // Wait for |listen_sock_| to accept a connection.
  84. connect_loop_.Run();
  85. // Now wait for the client socket to accept the connection.
  86. EXPECT_THAT(callback->GetResult(rv), IsOk());
  87. }
  88. TEST_F(TransportClientSocketTest, Connect) {
  89. TestCompletionCallback callback;
  90. EXPECT_FALSE(sock_->IsConnected());
  91. int rv = sock_->Connect(callback.callback());
  92. // Wait for |listen_sock_| to accept a connection.
  93. connect_loop_.Run();
  94. auto net_log_entries = net_log_observer_.GetEntries();
  95. EXPECT_TRUE(
  96. LogContainsBeginEvent(net_log_entries, 0, NetLogEventType::SOCKET_ALIVE));
  97. EXPECT_TRUE(
  98. LogContainsBeginEvent(net_log_entries, 1, NetLogEventType::TCP_CONNECT));
  99. // Now wait for the client socket to accept the connection.
  100. if (rv != OK) {
  101. ASSERT_EQ(rv, ERR_IO_PENDING);
  102. rv = callback.WaitForResult();
  103. EXPECT_EQ(rv, OK);
  104. }
  105. EXPECT_TRUE(sock_->IsConnected());
  106. net_log_entries = net_log_observer_.GetEntries();
  107. EXPECT_TRUE(
  108. LogContainsEndEvent(net_log_entries, -1, NetLogEventType::TCP_CONNECT));
  109. sock_->Disconnect();
  110. EXPECT_FALSE(sock_->IsConnected());
  111. }
  112. TEST_F(TransportClientSocketTest, IsConnected) {
  113. scoped_refptr<IOBuffer> buf = base::MakeRefCounted<IOBuffer>(4096);
  114. TestCompletionCallback callback;
  115. uint32_t bytes_read;
  116. EXPECT_FALSE(sock_->IsConnected());
  117. EXPECT_FALSE(sock_->IsConnectedAndIdle());
  118. EstablishConnection(&callback);
  119. EXPECT_TRUE(sock_->IsConnected());
  120. EXPECT_TRUE(sock_->IsConnectedAndIdle());
  121. // Send the request and wait for the server to respond.
  122. SendRequestAndResponse(sock_.get(), connected_sock_.get());
  123. // Drain a single byte so we know we've received some data.
  124. bytes_read = DrainStreamSocket(sock_.get(), buf.get(), 1, 1, &callback);
  125. ASSERT_EQ(bytes_read, 1u);
  126. // Socket should be considered connected, but not idle, due to
  127. // pending data.
  128. EXPECT_TRUE(sock_->IsConnected());
  129. EXPECT_FALSE(sock_->IsConnectedAndIdle());
  130. bytes_read = DrainStreamSocket(sock_.get(), buf.get(), 4096,
  131. strlen(kServerReply) - 1, &callback);
  132. ASSERT_EQ(bytes_read, strlen(kServerReply) - 1);
  133. // After draining the data, the socket should be back to connected
  134. // and idle.
  135. EXPECT_TRUE(sock_->IsConnected());
  136. EXPECT_TRUE(sock_->IsConnectedAndIdle());
  137. // This time close the server socket immediately after the server response.
  138. SendRequestAndResponse(sock_.get(), connected_sock_.get());
  139. CloseServerSocket();
  140. bytes_read = DrainStreamSocket(sock_.get(), buf.get(), 1, 1, &callback);
  141. ASSERT_EQ(bytes_read, 1u);
  142. // As above because of data.
  143. EXPECT_TRUE(sock_->IsConnected());
  144. EXPECT_FALSE(sock_->IsConnectedAndIdle());
  145. bytes_read = DrainStreamSocket(sock_.get(), buf.get(), 4096,
  146. strlen(kServerReply) - 1, &callback);
  147. ASSERT_EQ(bytes_read, strlen(kServerReply) - 1);
  148. // Once the data is drained, the socket should now be seen as not
  149. // connected.
  150. if (sock_->IsConnected()) {
  151. // In the unlikely event that the server's connection closure is not
  152. // processed in time, wait for the connection to be closed.
  153. int rv = sock_->Read(buf.get(), 4096, callback.callback());
  154. EXPECT_EQ(0, callback.GetResult(rv));
  155. EXPECT_FALSE(sock_->IsConnected());
  156. }
  157. EXPECT_FALSE(sock_->IsConnectedAndIdle());
  158. }
  159. TEST_F(TransportClientSocketTest, Read) {
  160. TestCompletionCallback callback;
  161. EstablishConnection(&callback);
  162. SendRequestAndResponse(sock_.get(), connected_sock_.get());
  163. scoped_refptr<IOBuffer> buf = base::MakeRefCounted<IOBuffer>(4096);
  164. uint32_t bytes_read = DrainStreamSocket(sock_.get(), buf.get(), 4096,
  165. strlen(kServerReply), &callback);
  166. ASSERT_EQ(bytes_read, strlen(kServerReply));
  167. ASSERT_EQ(std::string(kServerReply), std::string(buf->data(), bytes_read));
  168. // All data has been read now. Read once more to force an ERR_IO_PENDING, and
  169. // then close the server socket, and note the close.
  170. int rv = sock_->Read(buf.get(), 4096, callback.callback());
  171. ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
  172. CloseServerSocket();
  173. EXPECT_EQ(0, callback.WaitForResult());
  174. }
  175. TEST_F(TransportClientSocketTest, Read_SmallChunks) {
  176. TestCompletionCallback callback;
  177. EstablishConnection(&callback);
  178. SendRequestAndResponse(sock_.get(), connected_sock_.get());
  179. scoped_refptr<IOBuffer> buf = base::MakeRefCounted<IOBuffer>(1);
  180. uint32_t bytes_read = 0;
  181. while (bytes_read < strlen(kServerReply)) {
  182. int rv = sock_->Read(buf.get(), 1, callback.callback());
  183. EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
  184. rv = callback.GetResult(rv);
  185. ASSERT_EQ(1, rv);
  186. bytes_read += rv;
  187. }
  188. // All data has been read now. Read once more to force an ERR_IO_PENDING, and
  189. // then close the server socket, and note the close.
  190. int rv = sock_->Read(buf.get(), 1, callback.callback());
  191. ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
  192. CloseServerSocket();
  193. EXPECT_EQ(0, callback.WaitForResult());
  194. }
  195. TEST_F(TransportClientSocketTest, Read_Interrupted) {
  196. TestCompletionCallback callback;
  197. EstablishConnection(&callback);
  198. SendRequestAndResponse(sock_.get(), connected_sock_.get());
  199. // Do a partial read and then exit. This test should not crash!
  200. scoped_refptr<IOBuffer> buf = base::MakeRefCounted<IOBuffer>(16);
  201. int rv = sock_->Read(buf.get(), 16, callback.callback());
  202. EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
  203. rv = callback.GetResult(rv);
  204. EXPECT_NE(0, rv);
  205. }
  206. TEST_F(TransportClientSocketTest, FullDuplex_ReadFirst) {
  207. TestCompletionCallback callback;
  208. EstablishConnection(&callback);
  209. // Read first. There's no data, so it should return ERR_IO_PENDING.
  210. const int kBufLen = 4096;
  211. scoped_refptr<IOBuffer> buf = base::MakeRefCounted<IOBuffer>(kBufLen);
  212. int rv = sock_->Read(buf.get(), kBufLen, callback.callback());
  213. EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  214. const int kWriteBufLen = 64 * 1024;
  215. scoped_refptr<IOBuffer> request_buffer =
  216. base::MakeRefCounted<IOBuffer>(kWriteBufLen);
  217. char* request_data = request_buffer->data();
  218. memset(request_data, 'A', kWriteBufLen);
  219. TestCompletionCallback write_callback;
  220. int bytes_written = 0;
  221. while (true) {
  222. rv = sock_->Write(request_buffer.get(), kWriteBufLen,
  223. write_callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS);
  224. ASSERT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
  225. if (rv == ERR_IO_PENDING) {
  226. ReadDataOfExpectedLength(connected_sock_.get(), bytes_written);
  227. SendServerResponse(connected_sock_.get());
  228. rv = write_callback.WaitForResult();
  229. break;
  230. }
  231. bytes_written += rv;
  232. }
  233. // At this point, both read and write have returned ERR_IO_PENDING, and the
  234. // write callback has executed. We wait for the read callback to run now to
  235. // make sure that the socket can handle full duplex communications.
  236. rv = callback.WaitForResult();
  237. EXPECT_GE(rv, 0);
  238. }
  239. TEST_F(TransportClientSocketTest, FullDuplex_WriteFirst) {
  240. TestCompletionCallback callback;
  241. EstablishConnection(&callback);
  242. const int kWriteBufLen = 64 * 1024;
  243. scoped_refptr<IOBuffer> request_buffer =
  244. base::MakeRefCounted<IOBuffer>(kWriteBufLen);
  245. char* request_data = request_buffer->data();
  246. memset(request_data, 'A', kWriteBufLen);
  247. TestCompletionCallback write_callback;
  248. int bytes_written = 0;
  249. while (true) {
  250. int rv =
  251. sock_->Write(request_buffer.get(), kWriteBufLen,
  252. write_callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS);
  253. ASSERT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
  254. if (rv == ERR_IO_PENDING)
  255. break;
  256. bytes_written += rv;
  257. }
  258. // Now we have the Write() blocked on ERR_IO_PENDING. It's time to force the
  259. // Read() to block on ERR_IO_PENDING too.
  260. const int kBufLen = 4096;
  261. scoped_refptr<IOBuffer> buf = base::MakeRefCounted<IOBuffer>(kBufLen);
  262. while (true) {
  263. int rv = sock_->Read(buf.get(), kBufLen, callback.callback());
  264. ASSERT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
  265. if (rv == ERR_IO_PENDING)
  266. break;
  267. }
  268. // At this point, both read and write have returned ERR_IO_PENDING. Now we
  269. // run the write and read callbacks to make sure they can handle full duplex
  270. // communications.
  271. ReadDataOfExpectedLength(connected_sock_.get(), bytes_written);
  272. SendServerResponse(connected_sock_.get());
  273. int rv = write_callback.WaitForResult();
  274. EXPECT_GE(rv, 0);
  275. rv = callback.WaitForResult();
  276. EXPECT_GT(rv, 0);
  277. }
  278. } // namespace net