1 // Copyright 2013 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef NET_SOCKET_TCP_SOCKET_POSIX_H_ 6 #define NET_SOCKET_TCP_SOCKET_POSIX_H_ 7 8 #include <stdint.h> 9 10 #include <memory> 11 12 #include "base/functional/callback.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/socket/socket_tag.h" 21 #include "net/traffic_annotation/network_traffic_annotation.h" 22 23 namespace base { 24 class TimeDelta; 25 } 26 27 namespace net { 28 29 class AddressList; 30 class IOBuffer; 31 class IPEndPoint; 32 class SocketPosix; 33 class NetLog; 34 struct NetLogSource; 35 class SocketTag; 36 37 class NET_EXPORT TCPSocketPosix { 38 public: 39 // |socket_performance_watcher| is notified of the performance metrics related 40 // to this socket. |socket_performance_watcher| may be null. 41 static std::unique_ptr<TCPSocketPosix> Create( 42 std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher, 43 NetLog* net_log, 44 const NetLogSource& source); 45 static std::unique_ptr<TCPSocketPosix> Create( 46 std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher, 47 NetLogWithSource net_log_source); 48 49 TCPSocketPosix(const TCPSocketPosix&) = delete; 50 TCPSocketPosix& operator=(const TCPSocketPosix&) = delete; 51 52 virtual ~TCPSocketPosix(); 53 54 // Opens the socket. 55 // Returns a net error code. 56 int Open(AddressFamily family); 57 58 // Takes ownership of |socket|, which is known to already be connected to the 59 // given peer address. However, peer address may be the empty address, for 60 // compatibility. The given peer address will be returned by GetPeerAddress. 61 int AdoptConnectedSocket(SocketDescriptor socket, 62 const IPEndPoint& peer_address); 63 // Takes ownership of |socket|, which may or may not be open, bound, or 64 // listening. The caller must determine the state of the socket based on its 65 // provenance and act accordingly. The socket may have connections waiting 66 // to be accepted, but must not be actually connected. 67 int AdoptUnconnectedSocket(SocketDescriptor socket); 68 69 // Binds this socket to |address|. This is generally only used on a server. 70 // Should be called after Open(). Returns a net error code. 71 int Bind(const IPEndPoint& address); 72 73 // Put this socket on listen state with the given |backlog|. 74 // Returns a net error code. 75 int Listen(int backlog); 76 77 // Accepts incoming connection. 78 // Returns a net error code. 79 int Accept(std::unique_ptr<TCPSocketPosix>* socket, 80 IPEndPoint* address, 81 CompletionOnceCallback callback); 82 83 // Connects this socket to the given |address|. 84 // Should be called after Open(). 85 // Returns a net error code. 86 int Connect(const IPEndPoint& address, CompletionOnceCallback callback); 87 bool IsConnected() const; 88 bool IsConnectedAndIdle() const; 89 90 // IO: 91 // Multiple outstanding requests are not supported. 92 // Full duplex mode (reading and writing at the same time) is supported. 93 94 // Reads from the socket. 95 // Returns a net error code. 96 int Read(IOBuffer* buf, int buf_len, CompletionOnceCallback callback); 97 int ReadIfReady(IOBuffer* buf, int buf_len, CompletionOnceCallback callback); 98 int CancelReadIfReady(); 99 100 // Writes to the socket. 101 // Returns a net error code. 102 int Write(IOBuffer* buf, 103 int buf_len, 104 CompletionOnceCallback callback, 105 const NetworkTrafficAnnotationTag& traffic_annotation); 106 107 // Copies the local tcp address into |address| and returns a net error code. 108 int GetLocalAddress(IPEndPoint* address) const; 109 110 // Copies the remote tcp code into |address| and returns a net error code. 111 int GetPeerAddress(IPEndPoint* address) const; 112 113 // Sets various socket options. 114 // The commonly used options for server listening sockets: 115 // - AllowAddressReuse(). 116 int SetDefaultOptionsForServer(); 117 // The commonly used options for client sockets and accepted sockets: 118 // - SetNoDelay(true); 119 // - SetKeepAlive(true, 45). 120 void SetDefaultOptionsForClient(); 121 int AllowAddressReuse(); 122 int SetReceiveBufferSize(int32_t size); 123 int SetSendBufferSize(int32_t size); 124 bool SetKeepAlive(bool enable, int delay); 125 bool SetNoDelay(bool no_delay); 126 int SetIPv6Only(bool ipv6_only); 127 128 // Gets the estimated RTT. Returns false if the RTT is 129 // unavailable. May also return false when estimated RTT is 0. 130 [[nodiscard]] bool GetEstimatedRoundTripTime(base::TimeDelta* out_rtt) const; 131 132 // Closes the socket. 133 void Close(); 134 135 bool IsValid() const; 136 137 // Detachs from the current thread, to allow the socket to be transferred to 138 // a new thread. Should only be called when the object is no longer used by 139 // the old thread. 140 void DetachFromThread(); 141 142 // Marks the start/end of a series of connect attempts for logging purpose. 143 // 144 // TCPClientSocket may attempt to connect to multiple addresses until it 145 // succeeds in establishing a connection. The corresponding log will have 146 // multiple NetLogEventType::TCP_CONNECT_ATTEMPT entries nested within a 147 // NetLogEventType::TCP_CONNECT. These methods set the start/end of 148 // NetLogEventType::TCP_CONNECT. 149 // 150 // TODO(yzshen): Change logging format and let TCPClientSocket log the 151 // start/end of a series of connect attempts itself. 152 void StartLoggingMultipleConnectAttempts(const AddressList& addresses); 153 void EndLoggingMultipleConnectAttempts(int net_error); 154 net_log()155 const NetLogWithSource& net_log() const { return net_log_; } 156 157 // Return the underlying SocketDescriptor and clean up this object, which may 158 // no longer be used. This method should be used only for testing. No read, 159 // write, or accept operations should be pending. 160 SocketDescriptor ReleaseSocketDescriptorForTesting(); 161 162 // Exposes the underlying socket descriptor for testing its state. Does not 163 // release ownership of the descriptor. 164 SocketDescriptor SocketDescriptorForTesting() const; 165 166 // Apply |tag| to this socket. 167 void ApplySocketTag(const SocketTag& tag); 168 169 // May return nullptr. socket_performance_watcher()170 SocketPerformanceWatcher* socket_performance_watcher() const { 171 return socket_performance_watcher_.get(); 172 } 173 174 // Binds this socket to `network`. All data traffic on the socket will be sent 175 // and received via `network`. Must be called after Open() but before 176 // Connect() and/or Bind(). This call will fail if `network` has disconnected. 177 // Communication using this socket will fail if `network` disconnects. 178 // Returns a net error code. 179 int BindToNetwork(handles::NetworkHandle network); 180 181 private: 182 TCPSocketPosix( 183 std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher, 184 NetLog* net_log, 185 const NetLogSource& source); 186 TCPSocketPosix( 187 std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher, 188 NetLogWithSource net_log_source); 189 190 void AcceptCompleted(std::unique_ptr<TCPSocketPosix>* tcp_socket, 191 IPEndPoint* address, 192 CompletionOnceCallback callback, 193 int rv); 194 int HandleAcceptCompleted(std::unique_ptr<TCPSocketPosix>* tcp_socket, 195 IPEndPoint* address, 196 int rv); 197 int BuildTcpSocketPosix(std::unique_ptr<TCPSocketPosix>* tcp_socket, 198 IPEndPoint* address); 199 200 void ConnectCompleted(CompletionOnceCallback callback, int rv); 201 int HandleConnectCompleted(int rv); 202 void LogConnectBegin(const AddressList& addresses) const; 203 void LogConnectEnd(int net_error) const; 204 205 void ReadCompleted(const scoped_refptr<IOBuffer>& buf, 206 CompletionOnceCallback callback, 207 int rv); 208 void ReadIfReadyCompleted(CompletionOnceCallback callback, int rv); 209 int HandleReadCompleted(IOBuffer* buf, int rv); 210 void HandleReadCompletedHelper(int rv); 211 212 void WriteCompleted(const scoped_refptr<IOBuffer>& buf, 213 CompletionOnceCallback callback, 214 int rv); 215 int HandleWriteCompleted(IOBuffer* buf, int rv); 216 217 // Notifies |socket_performance_watcher_| of the latest RTT estimate available 218 // from the tcp_info struct for this TCP socket. 219 void NotifySocketPerformanceWatcher(); 220 221 std::unique_ptr<SocketPosix> socket_; 222 std::unique_ptr<SocketPosix> accept_socket_; 223 224 // Socket performance statistics (such as RTT) are reported to the 225 // |socket_performance_watcher_|. May be nullptr. 226 std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher_; 227 228 bool logging_multiple_connect_attempts_ = false; 229 230 NetLogWithSource net_log_; 231 232 // Current socket tag if |socket_| is valid, otherwise the tag to apply when 233 // |socket_| is opened. 234 SocketTag tag_; 235 }; 236 237 } // namespace net 238 239 #endif // NET_SOCKET_TCP_SOCKET_POSIX_H_ 240