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