ozone: drm: Crash immediately if no usable GPU is found
[chromium-blink-merge.git] / net / udp / udp_socket_win.h
blob52f4517f316a5e923ae741636b34d667c5f273ed
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.
5 #ifndef NET_UDP_UDP_SOCKET_WIN_H_
6 #define NET_UDP_UDP_SOCKET_WIN_H_
8 #include <qos2.h>
9 #include <winsock2.h>
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 "base/win/scoped_handle.h"
16 #include "net/base/address_family.h"
17 #include "net/base/completion_callback.h"
18 #include "net/base/io_buffer.h"
19 #include "net/base/ip_endpoint.h"
20 #include "net/base/net_export.h"
21 #include "net/base/net_util.h"
22 #include "net/base/rand_callback.h"
23 #include "net/log/net_log.h"
24 #include "net/udp/datagram_socket.h"
26 namespace net {
28 class NET_EXPORT UDPSocketWin
29 : NON_EXPORTED_BASE(public base::NonThreadSafe),
30 NON_EXPORTED_BASE(public base::win::ObjectWatcher::Delegate) {
31 public:
32 UDPSocketWin(DatagramSocket::BindType bind_type,
33 const RandIntCallback& rand_int_cb,
34 net::NetLog* net_log,
35 const net::NetLog::Source& source);
36 ~UDPSocketWin() override;
38 // Opens the socket.
39 // Returns a net error code.
40 int Open(AddressFamily address_family);
42 // Connects the socket to connect with a certain |address|.
43 // Should be called after Open().
44 // Returns a net error code.
45 int Connect(const IPEndPoint& address);
47 // Binds the address/port for this socket to |address|. This is generally
48 // only used on a server. Should be called after Open().
49 // Returns a net error code.
50 int Bind(const IPEndPoint& address);
52 // Closes the socket.
53 // TODO(rvargas, hidehiko): Disallow re-Open() after Close().
54 void Close();
56 // Copies the remote udp address into |address| and returns a net error code.
57 int GetPeerAddress(IPEndPoint* address) const;
59 // Copies the local udp address into |address| and returns a net error code.
60 // (similar to getsockname)
61 int GetLocalAddress(IPEndPoint* address) const;
63 // IO:
64 // Multiple outstanding read requests are not supported.
65 // Full duplex mode (reading and writing at the same time) is supported
67 // Reads from the socket.
68 // Only usable from the client-side of a UDP socket, after the socket
69 // has been connected.
70 int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
72 // Writes to the socket.
73 // Only usable from the client-side of a UDP socket, after the socket
74 // has been connected.
75 int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
77 // Reads from a socket and receive sender address information.
78 // |buf| is the buffer to read data into.
79 // |buf_len| is the maximum amount of data to read.
80 // |address| is a buffer provided by the caller for receiving the sender
81 // address information about the received data. This buffer must be kept
82 // alive by the caller until the callback is placed.
83 // |address_length| is a ptr to the length of the |address| buffer. This
84 // is an input parameter containing the maximum size |address| can hold
85 // and also an output parameter for the size of |address| upon completion.
86 // |callback| is the callback on completion of the RecvFrom.
87 // Returns a net error code, or ERR_IO_PENDING if the IO is in progress.
88 // If ERR_IO_PENDING is returned, the caller must keep |buf|, |address|,
89 // and |address_length| alive until the callback is called.
90 int RecvFrom(IOBuffer* buf,
91 int buf_len,
92 IPEndPoint* address,
93 const CompletionCallback& callback);
95 // Sends to a socket with a particular destination.
96 // |buf| is the buffer to send
97 // |buf_len| is the number of bytes to send
98 // |address| is the recipient address.
99 // |address_length| is the size of the recipient address
100 // |callback| is the user callback function to call on complete.
101 // Returns a net error code, or ERR_IO_PENDING if the IO is in progress.
102 // If ERR_IO_PENDING is returned, the caller must keep |buf| and |address|
103 // alive until the callback is called.
104 int SendTo(IOBuffer* buf,
105 int buf_len,
106 const IPEndPoint& address,
107 const CompletionCallback& callback);
109 // Sets the receive buffer size (in bytes) for the socket.
110 // Returns a net error code.
111 int SetReceiveBufferSize(int32 size);
113 // Sets the send buffer size (in bytes) for the socket.
114 // Returns a net error code.
115 int SetSendBufferSize(int32 size);
117 // Returns true if the socket is already connected or bound.
118 bool is_connected() const { return is_connected_; }
120 const BoundNetLog& NetLog() const { return net_log_; }
122 // Sets corresponding flags in |socket_options_| to allow the socket
123 // to share the local address to which the socket will be bound with
124 // other processes. Should be called between Open() and Bind().
125 // Returns a net error code.
126 int AllowAddressReuse();
128 // Sets corresponding flags in |socket_options_| to allow sending
129 // and receiving packets to and from broadcast addresses.
130 int SetBroadcast(bool broadcast);
132 // Joins the multicast group.
133 // |group_address| is the group address to join, could be either
134 // an IPv4 or IPv6 address.
135 // Returns a net error code.
136 int JoinGroup(const IPAddressNumber& group_address) const;
138 // Leaves the multicast group.
139 // |group_address| is the group address to leave, could be either
140 // an IPv4 or IPv6 address. If the socket hasn't joined the group,
141 // it will be ignored.
142 // It's optional to leave the multicast group before destroying
143 // the socket. It will be done by the OS.
144 // Return a net error code.
145 int LeaveGroup(const IPAddressNumber& group_address) const;
147 // Sets interface to use for multicast. If |interface_index| set to 0,
148 // default interface is used.
149 // Should be called before Bind().
150 // Returns a net error code.
151 int SetMulticastInterface(uint32 interface_index);
153 // Sets the time-to-live option for UDP packets sent to the multicast
154 // group address. The default value of this option is 1.
155 // Cannot be negative or more than 255.
156 // Should be called before Bind().
157 int SetMulticastTimeToLive(int time_to_live);
159 // Sets the loopback flag for UDP socket. If this flag is true, the host
160 // will receive packets sent to the joined group from itself.
161 // The default value of this option is true.
162 // Should be called before Bind().
164 // Note: the behavior of |SetMulticastLoopbackMode| is slightly
165 // different between Windows and Unix-like systems. The inconsistency only
166 // happens when there are more than one applications on the same host
167 // joined to the same multicast group while having different settings on
168 // multicast loopback mode. On Windows, the applications with loopback off
169 // will not RECEIVE the loopback packets; while on Unix-like systems, the
170 // applications with loopback off will not SEND the loopback packets to
171 // other applications on the same host. See MSDN: http://goo.gl/6vqbj
172 int SetMulticastLoopbackMode(bool loopback);
174 // Sets the differentiated services flags on outgoing packets. May not
175 // do anything on some platforms.
176 int SetDiffServCodePoint(DiffServCodePoint dscp);
178 // Resets the thread to be used for thread-safety checks.
179 void DetachFromThread();
181 // This class by default uses overlapped IO. Call this method before Open()
182 // to switch to non-blocking IO.
183 void UseNonBlockingIO();
185 private:
186 enum SocketOptions {
187 SOCKET_OPTION_MULTICAST_LOOP = 1 << 0
190 class Core;
192 void DoReadCallback(int rv);
193 void DoWriteCallback(int rv);
195 void DidCompleteRead();
196 void DidCompleteWrite();
198 // base::ObjectWatcher::Delegate implementation.
199 void OnObjectSignaled(HANDLE object) override;
200 void OnReadSignaled();
201 void OnWriteSignaled();
203 void WatchForReadWrite();
205 // Handles stats and logging. |result| is the number of bytes transferred, on
206 // success, or the net error code on failure.
207 void LogRead(int result, const char* bytes, const IPEndPoint* address) const;
208 void LogWrite(int result, const char* bytes, const IPEndPoint* address) const;
210 // Same as SendTo(), except that address is passed by pointer
211 // instead of by reference. It is called from Write() with |address|
212 // set to NULL.
213 int SendToOrWrite(IOBuffer* buf,
214 int buf_len,
215 const IPEndPoint* address,
216 const CompletionCallback& callback);
218 int InternalConnect(const IPEndPoint& address);
220 // Version for using overlapped IO.
221 int InternalRecvFromOverlapped(IOBuffer* buf,
222 int buf_len,
223 IPEndPoint* address);
224 int InternalSendToOverlapped(IOBuffer* buf,
225 int buf_len,
226 const IPEndPoint* address);
228 // Version for using non-blocking IO.
229 int InternalRecvFromNonBlocking(IOBuffer* buf,
230 int buf_len,
231 IPEndPoint* address);
232 int InternalSendToNonBlocking(IOBuffer* buf,
233 int buf_len,
234 const IPEndPoint* address);
236 // Applies |socket_options_| to |socket_|. Should be called before
237 // Bind().
238 int SetMulticastOptions();
239 int DoBind(const IPEndPoint& address);
240 // Binds to a random port on |address|.
241 int RandomBind(const IPAddressNumber& address);
243 SOCKET socket_;
244 int addr_family_;
245 bool is_connected_;
247 // Bitwise-or'd combination of SocketOptions. Specifies the set of
248 // options that should be applied to |socket_| before Bind().
249 int socket_options_;
251 // Multicast interface.
252 uint32 multicast_interface_;
254 // Multicast socket options cached for SetMulticastOption.
255 // Cannot be used after Bind().
256 int multicast_time_to_live_;
258 // How to do source port binding, used only when UDPSocket is part of
259 // UDPClientSocket, since UDPServerSocket provides Bind.
260 DatagramSocket::BindType bind_type_;
262 // PRNG function for generating port numbers.
263 RandIntCallback rand_int_cb_;
265 // These are mutable since they're just cached copies to make
266 // GetPeerAddress/GetLocalAddress smarter.
267 mutable scoped_ptr<IPEndPoint> local_address_;
268 mutable scoped_ptr<IPEndPoint> remote_address_;
270 // The core of the socket that can live longer than the socket itself. We pass
271 // resources to the Windows async IO functions and we have to make sure that
272 // they are not destroyed while the OS still references them.
273 scoped_refptr<Core> core_;
275 // True if non-blocking IO is used.
276 bool use_non_blocking_io_;
278 // Watches |read_write_event_|.
279 base::win::ObjectWatcher read_write_watcher_;
281 // Events for read and write.
282 base::win::ScopedHandle read_write_event_;
284 // The buffers used in Read() and Write().
285 scoped_refptr<IOBuffer> read_iobuffer_;
286 scoped_refptr<IOBuffer> write_iobuffer_;
288 int read_iobuffer_len_;
289 int write_iobuffer_len_;
291 IPEndPoint* recv_from_address_;
293 // Cached copy of the current address we're sending to, if any. Used for
294 // logging.
295 scoped_ptr<IPEndPoint> send_to_address_;
297 // External callback; called when read is complete.
298 CompletionCallback read_callback_;
300 // External callback; called when write is complete.
301 CompletionCallback write_callback_;
303 BoundNetLog net_log_;
305 // QWAVE data. Used to set DSCP bits on outgoing packets.
306 HANDLE qos_handle_;
307 QOS_FLOWID qos_flow_id_;
309 DISALLOW_COPY_AND_ASSIGN(UDPSocketWin);
312 //-----------------------------------------------------------------------------
314 // QWAVE (Quality Windows Audio/Video Experience) is the latest windows
315 // library for setting packet priorities (and other things). Unfortunately,
316 // Microsoft has decided that setting the DSCP bits with setsockopt() no
317 // longer works, so we have to use this API instead.
318 // This class is meant to be used as a singleton. It exposes a few dynamically
319 // loaded functions and a bool called "qwave_supported".
320 class NET_EXPORT QwaveAPI {
321 typedef BOOL (WINAPI *CreateHandleFn)(PQOS_VERSION, PHANDLE);
322 typedef BOOL (WINAPI *CloseHandleFn)(HANDLE);
323 typedef BOOL (WINAPI *AddSocketToFlowFn)(
324 HANDLE, SOCKET, PSOCKADDR, QOS_TRAFFIC_TYPE, DWORD, PQOS_FLOWID);
325 typedef BOOL (WINAPI *RemoveSocketFromFlowFn)(
326 HANDLE, SOCKET, QOS_FLOWID, DWORD);
327 typedef BOOL (WINAPI *SetFlowFn)(
328 HANDLE, QOS_FLOWID, QOS_SET_FLOW, ULONG, PVOID, DWORD, LPOVERLAPPED);
330 public:
331 QwaveAPI();
333 static QwaveAPI& Get();
335 bool qwave_supported() const;
336 BOOL CreateHandle(PQOS_VERSION version, PHANDLE handle);
337 BOOL CloseHandle(HANDLE handle);
338 BOOL AddSocketToFlow(HANDLE handle,
339 SOCKET socket,
340 PSOCKADDR addr,
341 QOS_TRAFFIC_TYPE traffic_type,
342 DWORD flags,
343 PQOS_FLOWID flow_id);
344 BOOL RemoveSocketFromFlow(HANDLE handle,
345 SOCKET socket,
346 QOS_FLOWID flow_id,
347 DWORD reserved);
348 BOOL SetFlow(HANDLE handle,
349 QOS_FLOWID flow_id,
350 QOS_SET_FLOW op,
351 ULONG size,
352 PVOID data,
353 DWORD reserved,
354 LPOVERLAPPED overlapped);
356 private:
357 bool qwave_supported_;
358 CreateHandleFn create_handle_func_;
359 CloseHandleFn close_handle_func_;
360 AddSocketToFlowFn add_socket_to_flow_func_;
361 RemoveSocketFromFlowFn remove_socket_from_flow_func_;
362 SetFlowFn set_flow_func_;
364 FRIEND_TEST_ALL_PREFIXES(UDPSocketTest, SetDSCPFake);
365 DISALLOW_COPY_AND_ASSIGN(QwaveAPI);
369 } // namespace net
371 #endif // NET_UDP_UDP_SOCKET_WIN_H_