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