tcp_socket_win.h 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. #ifndef NET_SOCKET_TCP_SOCKET_WIN_H_
  5. #define NET_SOCKET_TCP_SOCKET_WIN_H_
  6. #include <stdint.h>
  7. #include <winsock2.h>
  8. #include <memory>
  9. #include "base/memory/raw_ptr.h"
  10. #include "base/memory/ref_counted.h"
  11. #include "base/threading/thread_checker.h"
  12. #include "base/win/object_watcher.h"
  13. #include "net/base/address_family.h"
  14. #include "net/base/completion_once_callback.h"
  15. #include "net/base/net_export.h"
  16. #include "net/base/network_handle.h"
  17. #include "net/log/net_log_with_source.h"
  18. #include "net/socket/socket_descriptor.h"
  19. #include "net/socket/socket_performance_watcher.h"
  20. #include "net/traffic_annotation/network_traffic_annotation.h"
  21. namespace net {
  22. class AddressList;
  23. class IOBuffer;
  24. class IPEndPoint;
  25. class NetLog;
  26. struct NetLogSource;
  27. class SocketTag;
  28. class NET_EXPORT TCPSocketWin : public base::win::ObjectWatcher::Delegate {
  29. public:
  30. TCPSocketWin(
  31. std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
  32. NetLog* net_log,
  33. const NetLogSource& source);
  34. TCPSocketWin(const TCPSocketWin&) = delete;
  35. TCPSocketWin& operator=(const TCPSocketWin&) = delete;
  36. ~TCPSocketWin() override;
  37. int Open(AddressFamily family);
  38. // Takes ownership of |socket|, which is known to already be connected to the
  39. // given peer address. However, peer address may be the empty address, for
  40. // compatibility. The given peer address will be returned by GetPeerAddress.
  41. int AdoptConnectedSocket(SocketDescriptor socket,
  42. const IPEndPoint& peer_address);
  43. // Takes ownership of |socket|, which may or may not be open, bound, or
  44. // listening. The caller must determine the state of the socket based on its
  45. // provenance and act accordingly. The socket may have connections waiting
  46. // to be accepted, but must not be actually connected.
  47. int AdoptUnconnectedSocket(SocketDescriptor socket);
  48. int Bind(const IPEndPoint& address);
  49. int Listen(int backlog);
  50. int Accept(std::unique_ptr<TCPSocketWin>* socket,
  51. IPEndPoint* address,
  52. CompletionOnceCallback callback);
  53. int Connect(const IPEndPoint& address, CompletionOnceCallback callback);
  54. bool IsConnected() const;
  55. bool IsConnectedAndIdle() const;
  56. // Multiple outstanding requests are not supported.
  57. // Full duplex mode (reading and writing at the same time) is supported.
  58. int Read(IOBuffer* buf, int buf_len, CompletionOnceCallback callback);
  59. int ReadIfReady(IOBuffer* buf, int buf_len, CompletionOnceCallback callback);
  60. int CancelReadIfReady();
  61. int Write(IOBuffer* buf,
  62. int buf_len,
  63. CompletionOnceCallback callback,
  64. const NetworkTrafficAnnotationTag& traffic_annotation);
  65. int GetLocalAddress(IPEndPoint* address) const;
  66. int GetPeerAddress(IPEndPoint* address) const;
  67. // Sets various socket options.
  68. // The commonly used options for server listening sockets:
  69. // - SetExclusiveAddrUse().
  70. int SetDefaultOptionsForServer();
  71. // The commonly used options for client sockets and accepted sockets:
  72. // - SetNoDelay(true);
  73. // - SetKeepAlive(true, 45).
  74. void SetDefaultOptionsForClient();
  75. int SetExclusiveAddrUse();
  76. int SetReceiveBufferSize(int32_t size);
  77. int SetSendBufferSize(int32_t size);
  78. bool SetKeepAlive(bool enable, int delay);
  79. bool SetNoDelay(bool no_delay);
  80. // Gets the estimated RTT. Returns false if the RTT is
  81. // unavailable. May also return false when estimated RTT is 0.
  82. [[nodiscard]] bool GetEstimatedRoundTripTime(base::TimeDelta* out_rtt) const;
  83. void Close();
  84. bool IsValid() const { return socket_ != INVALID_SOCKET; }
  85. // Detachs from the current thread, to allow the socket to be transferred to
  86. // a new thread. Should only be called when the object is no longer used by
  87. // the old thread.
  88. void DetachFromThread();
  89. // Marks the start/end of a series of connect attempts for logging purpose.
  90. //
  91. // TCPClientSocket may attempt to connect to multiple addresses until it
  92. // succeeds in establishing a connection. The corresponding log will have
  93. // multiple NetLogEventType::TCP_CONNECT_ATTEMPT entries nested within a
  94. // NetLogEventType::TCP_CONNECT. These methods set the start/end of
  95. // NetLogEventType::TCP_CONNECT.
  96. //
  97. // TODO(yzshen): Change logging format and let TCPClientSocket log the
  98. // start/end of a series of connect attempts itself.
  99. void StartLoggingMultipleConnectAttempts(const AddressList& addresses);
  100. void EndLoggingMultipleConnectAttempts(int net_error);
  101. const NetLogWithSource& net_log() const { return net_log_; }
  102. // Return the underlying SocketDescriptor and clean up this object, which may
  103. // no longer be used. This method should be used only for testing. No read,
  104. // write, or accept operations should be pending.
  105. SocketDescriptor ReleaseSocketDescriptorForTesting();
  106. // Exposes the underlying socket descriptor for testing its state. Does not
  107. // release ownership of the descriptor.
  108. SocketDescriptor SocketDescriptorForTesting() const;
  109. // Apply |tag| to this socket.
  110. void ApplySocketTag(const SocketTag& tag);
  111. // Not implemented. Returns ERR_NOT_IMPLEMENTED.
  112. int BindToNetwork(handles::NetworkHandle network);
  113. // May return nullptr.
  114. SocketPerformanceWatcher* socket_performance_watcher() const {
  115. return socket_performance_watcher_.get();
  116. }
  117. private:
  118. class Core;
  119. // base::ObjectWatcher::Delegate implementation.
  120. void OnObjectSignaled(HANDLE object) override;
  121. int AcceptInternal(std::unique_ptr<TCPSocketWin>* socket,
  122. IPEndPoint* address);
  123. int DoConnect();
  124. void DoConnectComplete(int result);
  125. void LogConnectBegin(const AddressList& addresses);
  126. void LogConnectEnd(int net_error);
  127. void RetryRead(int rv);
  128. void DidCompleteConnect();
  129. void DidCompleteWrite();
  130. void DidSignalRead();
  131. SOCKET socket_;
  132. // |socket_performance_watcher_| may be nullptr.
  133. std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher_;
  134. HANDLE accept_event_;
  135. base::win::ObjectWatcher accept_watcher_;
  136. raw_ptr<std::unique_ptr<TCPSocketWin>> accept_socket_ = nullptr;
  137. raw_ptr<IPEndPoint> accept_address_ = nullptr;
  138. CompletionOnceCallback accept_callback_;
  139. // The various states that the socket could be in.
  140. bool waiting_connect_ = false;
  141. bool waiting_read_ = false;
  142. bool waiting_write_ = false;
  143. // The core of the socket that can live longer than the socket itself. We pass
  144. // resources to the Windows async IO functions and we have to make sure that
  145. // they are not destroyed while the OS still references them.
  146. scoped_refptr<Core> core_;
  147. // External callback; called when connect or read is complete.
  148. CompletionOnceCallback read_callback_;
  149. // Non-null if a ReadIfReady() is to be completed asynchronously. This is an
  150. // external callback if user used ReadIfReady() instead of Read(), but a
  151. // wrapped callback on top of RetryRead() if Read() is used.
  152. CompletionOnceCallback read_if_ready_callback_;
  153. // External callback; called when write is complete.
  154. CompletionOnceCallback write_callback_;
  155. std::unique_ptr<IPEndPoint> peer_address_;
  156. // The OS error that a connect attempt last completed with.
  157. int connect_os_error_ = 0;
  158. bool logging_multiple_connect_attempts_ = false;
  159. NetLogWithSource net_log_;
  160. THREAD_CHECKER(thread_checker_);
  161. };
  162. } // namespace net
  163. #endif // NET_SOCKET_TCP_SOCKET_WIN_H_