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
5 #ifndef NET_UDP_UDP_SOCKET_WIN_H_
6 #define NET_UDP_UDP_SOCKET_WIN_H_
7
8 #include <qos2.h>
9 #include <winsock2.h>
10
11 #include "base/memory/ref_counted.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/threading/non_thread_safe.h"
14 #include "base/win/object_watcher.h"
15 #include "net/base/completion_callback.h"
16 #include "net/base/net_export.h"
17 #include "net/base/rand_callback.h"
18 #include "net/base/ip_endpoint.h"
19 #include "net/base/io_buffer.h"
20 #include "net/base/net_log.h"
21 #include "net/udp/datagram_socket.h"
22
23 namespace net {
24
NON_EXPORTED_BASE(public base::NonThreadSafe)25 class NET_EXPORT UDPSocketWin : NON_EXPORTED_BASE(public base::NonThreadSafe) {
26 public:
27 UDPSocketWin(DatagramSocket::BindType bind_type,
28 const RandIntCallback& rand_int_cb,
29 net::NetLog* net_log,
30 const net::NetLog::Source& source);
31 virtual ~UDPSocketWin();
32
33 // Connect the socket to connect with a certain |address|.
34 // Returns a net error code.
35 int Connect(const IPEndPoint& address);
36
37 // Bind the address/port for this socket to |address|. This is generally
38 // only used on a server.
39 // Returns a net error code.
40 int Bind(const IPEndPoint& address);
41
42 // Close the socket.
43 void Close();
44
45 // Copy the remote udp address into |address| and return a network error code.
46 int GetPeerAddress(IPEndPoint* address) const;
47
48 // Copy the local udp address into |address| and return a network error code.
49 // (similar to getsockname)
50 int GetLocalAddress(IPEndPoint* address) const;
51
52 // IO:
53 // Multiple outstanding read requests are not supported.
54 // Full duplex mode (reading and writing at the same time) is supported
55
56 // Read from the socket.
57 // Only usable from the client-side of a UDP socket, after the socket
58 // has been connected.
59 int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
60
61 // Write to the socket.
62 // Only usable from the client-side of a UDP socket, after the socket
63 // has been connected.
64 int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
65
66 // Read from a socket and receive sender address information.
67 // |buf| is the buffer to read data into.
68 // |buf_len| is the maximum amount of data to read.
69 // |address| is a buffer provided by the caller for receiving the sender
70 // address information about the received data. This buffer must be kept
71 // alive by the caller until the callback is placed.
72 // |address_length| is a ptr to the length of the |address| buffer. This
73 // is an input parameter containing the maximum size |address| can hold
74 // and also an output parameter for the size of |address| upon completion.
75 // |callback| is the callback on completion of the RecvFrom.
76 // Returns a net error code, or ERR_IO_PENDING if the IO is in progress.
77 // If ERR_IO_PENDING is returned, the caller must keep |buf|, |address|,
78 // and |address_length| alive until the callback is called.
79 int RecvFrom(IOBuffer* buf,
80 int buf_len,
81 IPEndPoint* address,
82 const CompletionCallback& callback);
83
84 // Send to a socket with a particular destination.
85 // |buf| is the buffer to send
86 // |buf_len| is the number of bytes to send
87 // |address| is the recipient address.
88 // |address_length| is the size of the recipient address
89 // |callback| is the user callback function to call on complete.
90 // Returns a net error code, or ERR_IO_PENDING if the IO is in progress.
91 // If ERR_IO_PENDING is returned, the caller must keep |buf| and |address|
92 // alive until the callback is called.
93 int SendTo(IOBuffer* buf,
94 int buf_len,
95 const IPEndPoint& address,
96 const CompletionCallback& callback);
97
98 // Set the receive buffer size (in bytes) for the socket.
99 // Returns a net error code.
100 int SetReceiveBufferSize(int32 size);
101
102 // Set the send buffer size (in bytes) for the socket.
103 // Returns a net error code.
104 int SetSendBufferSize(int32 size);
105
106 // Returns true if the socket is already connected or bound.
107 bool is_connected() const { return socket_ != INVALID_SOCKET; }
108
109 const BoundNetLog& NetLog() const { return net_log_; }
110
111 // Sets corresponding flags in |socket_options_| to allow the socket
112 // to share the local address to which the socket will be bound with
113 // other processes. Should be called before Bind().
114 void AllowAddressReuse();
115
116 // Sets corresponding flags in |socket_options_| to allow sending
117 // and receiving packets to and from broadcast addresses. Should be
118 // called before Bind().
119 void AllowBroadcast();
120
121 // Join the multicast group.
122 // |group_address| is the group address to join, could be either
123 // an IPv4 or IPv6 address.
124 // Return a network error code.
125 int JoinGroup(const IPAddressNumber& group_address) const;
126
127 // Leave the multicast group.
128 // |group_address| is the group address to leave, could be either
129 // an IPv4 or IPv6 address. If the socket hasn't joined the group,
130 // it will be ignored.
131 // It's optional to leave the multicast group before destroying
132 // the socket. It will be done by the OS.
133 // Return a network error code.
134 int LeaveGroup(const IPAddressNumber& group_address) const;
135
136 // Set interface to use for multicast. If |interface_index| set to 0, default
137 // interface is used.
138 // Should be called before Bind().
139 // Returns a network error code.
140 int SetMulticastInterface(uint32 interface_index);
141
142 // Set the time-to-live option for UDP packets sent to the multicast
143 // group address. The default value of this option is 1.
144 // Cannot be negative or more than 255.
145 // Should be called before Bind().
146 int SetMulticastTimeToLive(int time_to_live);
147
148 // Set the loopback flag for UDP socket. If this flag is true, the host
149 // will receive packets sent to the joined group from itself.
150 // The default value of this option is true.
151 // Should be called before Bind().
152 //
153 // Note: the behavior of |SetMulticastLoopbackMode| is slightly
154 // different between Windows and Unix-like systems. The inconsistency only
155 // happens when there are more than one applications on the same host
156 // joined to the same multicast group while having different settings on
157 // multicast loopback mode. On Windows, the applications with loopback off
158 // will not RECEIVE the loopback packets; while on Unix-like systems, the
159 // applications with loopback off will not SEND the loopback packets to
160 // other applications on the same host. See MSDN: http://goo.gl/6vqbj
161 int SetMulticastLoopbackMode(bool loopback);
162
163 // Set the differentiated services flags on outgoing packets. May not
164 // do anything on some platforms.
165 int SetDiffServCodePoint(DiffServCodePoint dscp);
166
167 // Resets the thread to be used for thread-safety checks.
168 void DetachFromThread();
169
170 private:
171 enum SocketOptions {
172 SOCKET_OPTION_REUSE_ADDRESS = 1 << 0,
173 SOCKET_OPTION_BROADCAST = 1 << 1,
174 SOCKET_OPTION_MULTICAST_LOOP = 1 << 2
175 };
176
177 class Core;
178
179 void DoReadCallback(int rv);
180 void DoWriteCallback(int rv);
181 void DidCompleteRead();
182 void DidCompleteWrite();
183
184 // Handles stats and logging. |result| is the number of bytes transferred, on
185 // success, or the net error code on failure. LogRead retrieves the address
186 // from |recv_addr_storage_|, while LogWrite takes it as an optional argument.
187 void LogRead(int result, const char* bytes) const;
188 void LogWrite(int result, const char* bytes, const IPEndPoint* address) const;
189
190 // Returns the OS error code (or 0 on success).
191 int CreateSocket(int addr_family);
192
193 // Same as SendTo(), except that address is passed by pointer
194 // instead of by reference. It is called from Write() with |address|
195 // set to NULL.
196 int SendToOrWrite(IOBuffer* buf,
197 int buf_len,
198 const IPEndPoint* address,
199 const CompletionCallback& callback);
200
201 int InternalConnect(const IPEndPoint& address);
202 int InternalRecvFrom(IOBuffer* buf, int buf_len, IPEndPoint* address);
203 int InternalSendTo(IOBuffer* buf, int buf_len, const IPEndPoint* address);
204
205 // Applies |socket_options_| to |socket_|. Should be called before
206 // Bind().
207 int SetSocketOptions();
208 int DoBind(const IPEndPoint& address);
209 // Binds to a random port on |address|.
210 int RandomBind(const IPAddressNumber& address);
211
212 // Attempts to convert the data in |recv_addr_storage_| and |recv_addr_len_|
213 // to an IPEndPoint and writes it to |address|. Returns true on success.
214 bool ReceiveAddressToIPEndpoint(IPEndPoint* address) const;
215
216 SOCKET socket_;
217 int addr_family_;
218
219 // Bitwise-or'd combination of SocketOptions. Specifies the set of
220 // options that should be applied to |socket_| before Bind().
221 int socket_options_;
222
223 // Multicast interface.
224 uint32 multicast_interface_;
225
226 // Multicast socket options cached for SetSocketOption.
227 // Cannot be used after Bind().
228 int multicast_time_to_live_;
229
230 // How to do source port binding, used only when UDPSocket is part of
231 // UDPClientSocket, since UDPServerSocket provides Bind.
232 DatagramSocket::BindType bind_type_;
233
234 // PRNG function for generating port numbers.
235 RandIntCallback rand_int_cb_;
236
237 // These are mutable since they're just cached copies to make
238 // GetPeerAddress/GetLocalAddress smarter.
239 mutable scoped_ptr<IPEndPoint> local_address_;
240 mutable scoped_ptr<IPEndPoint> remote_address_;
241
242 // The core of the socket that can live longer than the socket itself. We pass
243 // resources to the Windows async IO functions and we have to make sure that
244 // they are not destroyed while the OS still references them.
245 scoped_refptr<Core> core_;
246
247 IPEndPoint* recv_from_address_;
248
249 // Cached copy of the current address we're sending to, if any. Used for
250 // logging.
251 scoped_ptr<IPEndPoint> send_to_address_;
252
253 // External callback; called when read is complete.
254 CompletionCallback read_callback_;
255
256 // External callback; called when write is complete.
257 CompletionCallback write_callback_;
258
259 BoundNetLog net_log_;
260
261 // QWAVE data. Used to set DSCP bits on outgoing packets.
262 HANDLE qos_handle_;
263 QOS_FLOWID qos_flow_id_;
264
265 DISALLOW_COPY_AND_ASSIGN(UDPSocketWin);
266 };
267
268 //-----------------------------------------------------------------------------
269
270 // QWAVE (Quality Windows Audio/Video Experience) is the latest windows
271 // library for setting packet priorities (and other things). Unfortunately,
272 // Microsoft has decided that setting the DSCP bits with setsockopt() no
273 // longer works, so we have to use this API instead.
274 // This class is meant to be used as a singleton. It exposes a few dynamically
275 // loaded functions and a bool called "qwave_supported".
276 class NET_EXPORT QwaveAPI {
277 typedef BOOL (WINAPI *CreateHandleFn)(PQOS_VERSION, PHANDLE);
278 typedef BOOL (WINAPI *CloseHandleFn)(HANDLE);
279 typedef BOOL (WINAPI *AddSocketToFlowFn)(
280 HANDLE, SOCKET, PSOCKADDR, QOS_TRAFFIC_TYPE, DWORD, PQOS_FLOWID);
281 typedef BOOL (WINAPI *RemoveSocketFromFlowFn)(
282 HANDLE, SOCKET, QOS_FLOWID, DWORD);
283 typedef BOOL (WINAPI *SetFlowFn)(
284 HANDLE, QOS_FLOWID, QOS_SET_FLOW, ULONG, PVOID, DWORD, LPOVERLAPPED);
285
286 public:
287 QwaveAPI();
288
289 static QwaveAPI& Get();
290
291 bool qwave_supported() const;
292 BOOL CreateHandle(PQOS_VERSION version, PHANDLE handle);
293 BOOL CloseHandle(HANDLE handle);
294 BOOL AddSocketToFlow(HANDLE handle,
295 SOCKET socket,
296 PSOCKADDR addr,
297 QOS_TRAFFIC_TYPE traffic_type,
298 DWORD flags,
299 PQOS_FLOWID flow_id);
300 BOOL RemoveSocketFromFlow(HANDLE handle,
301 SOCKET socket,
302 QOS_FLOWID flow_id,
303 DWORD reserved);
304 BOOL SetFlow(HANDLE handle,
305 QOS_FLOWID flow_id,
306 QOS_SET_FLOW op,
307 ULONG size,
308 PVOID data,
309 DWORD reserved,
310 LPOVERLAPPED overlapped);
311
312 private:
313 bool qwave_supported_;
314 CreateHandleFn create_handle_func_;
315 CloseHandleFn close_handle_func_;
316 AddSocketToFlowFn add_socket_to_flow_func_;
317 RemoveSocketFromFlowFn remove_socket_from_flow_func_;
318 SetFlowFn set_flow_func_;
319
320 FRIEND_TEST_ALL_PREFIXES(UDPSocketTest, SetDSCPFake);
321 DISALLOW_COPY_AND_ASSIGN(QwaveAPI);
322 };
323
324
325 } // namespace net
326
327 #endif // NET_UDP_UDP_SOCKET_WIN_H_
328