udp_socket_win.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. #ifndef NET_SOCKET_UDP_SOCKET_WIN_H_
  5. #define NET_SOCKET_UDP_SOCKET_WIN_H_
  6. #include <qos2.h>
  7. #include <stdint.h>
  8. #include <winsock2.h>
  9. #include <atomic>
  10. #include <memory>
  11. #include <set>
  12. #include "base/gtest_prod_util.h"
  13. #include "base/memory/raw_ptr.h"
  14. #include "base/memory/ref_counted.h"
  15. #include "base/memory/weak_ptr.h"
  16. #include "base/threading/thread_checker.h"
  17. #include "base/win/object_watcher.h"
  18. #include "base/win/scoped_handle.h"
  19. #include "net/base/address_family.h"
  20. #include "net/base/completion_once_callback.h"
  21. #include "net/base/io_buffer.h"
  22. #include "net/base/ip_endpoint.h"
  23. #include "net/base/net_export.h"
  24. #include "net/base/network_handle.h"
  25. #include "net/log/net_log_with_source.h"
  26. #include "net/socket/datagram_socket.h"
  27. #include "net/socket/diff_serv_code_point.h"
  28. #include "net/socket/udp_socket_global_limits.h"
  29. #include "net/traffic_annotation/network_traffic_annotation.h"
  30. namespace net {
  31. class IPAddress;
  32. class NetLog;
  33. struct NetLogSource;
  34. class SocketTag;
  35. // QWAVE (Quality Windows Audio/Video Experience) is the latest windows
  36. // library for setting packet priorities (and other things). Unfortunately,
  37. // Microsoft has decided that setting the DSCP bits with setsockopt() no
  38. // longer works, so we have to use this API instead.
  39. // This class is meant to be used as a singleton. It exposes a few dynamically
  40. // loaded functions and a bool called "qwave_supported".
  41. class NET_EXPORT QwaveApi {
  42. typedef BOOL(WINAPI* CreateHandleFn)(PQOS_VERSION, PHANDLE);
  43. typedef BOOL(WINAPI* CloseHandleFn)(HANDLE);
  44. typedef BOOL(WINAPI* AddSocketToFlowFn)(HANDLE,
  45. SOCKET,
  46. PSOCKADDR,
  47. QOS_TRAFFIC_TYPE,
  48. DWORD,
  49. PQOS_FLOWID);
  50. typedef BOOL(WINAPI* RemoveSocketFromFlowFn)(HANDLE,
  51. SOCKET,
  52. QOS_FLOWID,
  53. DWORD);
  54. typedef BOOL(WINAPI* SetFlowFn)(HANDLE,
  55. QOS_FLOWID,
  56. QOS_SET_FLOW,
  57. ULONG,
  58. PVOID,
  59. DWORD,
  60. LPOVERLAPPED);
  61. public:
  62. QwaveApi();
  63. QwaveApi(const QwaveApi&) = delete;
  64. QwaveApi& operator=(const QwaveApi&) = delete;
  65. static QwaveApi* GetDefault();
  66. virtual bool qwave_supported() const;
  67. virtual void OnFatalError();
  68. virtual BOOL CreateHandle(PQOS_VERSION version, PHANDLE handle);
  69. virtual BOOL CloseHandle(HANDLE handle);
  70. virtual BOOL AddSocketToFlow(HANDLE handle,
  71. SOCKET socket,
  72. PSOCKADDR addr,
  73. QOS_TRAFFIC_TYPE traffic_type,
  74. DWORD flags,
  75. PQOS_FLOWID flow_id);
  76. virtual BOOL RemoveSocketFromFlow(HANDLE handle,
  77. SOCKET socket,
  78. QOS_FLOWID flow_id,
  79. DWORD reserved);
  80. virtual BOOL SetFlow(HANDLE handle,
  81. QOS_FLOWID flow_id,
  82. QOS_SET_FLOW op,
  83. ULONG size,
  84. PVOID data,
  85. DWORD reserved,
  86. LPOVERLAPPED overlapped);
  87. private:
  88. std::atomic<bool> qwave_supported_{false};
  89. CreateHandleFn create_handle_func_;
  90. CloseHandleFn close_handle_func_;
  91. AddSocketToFlowFn add_socket_to_flow_func_;
  92. RemoveSocketFromFlowFn remove_socket_from_flow_func_;
  93. SetFlowFn set_flow_func_;
  94. };
  95. //-----------------------------------------------------------------------------
  96. // Helper for maintaining the state that (unlike a blanket socket option), DSCP
  97. // values are set per-remote endpoint instead of just per-socket on Windows.
  98. // The implementation creates a single QWAVE 'flow' for the socket, and adds
  99. // all encountered remote addresses to that flow. Flows are the minimum
  100. // manageable unit within the QWAVE API. See
  101. // https://docs.microsoft.com/en-us/previous-versions/windows/desktop/api/qos2/
  102. // for Microsoft's documentation.
  103. class NET_EXPORT DscpManager {
  104. public:
  105. DscpManager(QwaveApi* api, SOCKET socket);
  106. DscpManager(const DscpManager&) = delete;
  107. DscpManager& operator=(const DscpManager&) = delete;
  108. ~DscpManager();
  109. // Remembers the latest |dscp| so PrepareToSend can add remote addresses to
  110. // the qos flow. Destroys the old flow if it exists and |dscp| changes.
  111. void Set(DiffServCodePoint dscp);
  112. // Constructs a qos flow for the latest set DSCP value if we don't already
  113. // have one. Adds |remote_address| to the qos flow if it hasn't been added
  114. // already. Does nothing if no DSCP value has been Set.
  115. int PrepareForSend(const IPEndPoint& remote_address);
  116. private:
  117. void RequestHandle();
  118. static HANDLE DoCreateHandle(QwaveApi* api);
  119. static void OnHandleCreated(QwaveApi* api,
  120. base::WeakPtr<DscpManager> dscp_manager,
  121. HANDLE handle);
  122. const raw_ptr<QwaveApi> api_;
  123. const SOCKET socket_;
  124. DiffServCodePoint dscp_value_ = DSCP_NO_CHANGE;
  125. // The remote addresses currently in the flow.
  126. std::set<IPEndPoint> configured_;
  127. HANDLE qos_handle_ = nullptr;
  128. bool handle_is_initializing_ = false;
  129. // 0 means no flow has been constructed.
  130. QOS_FLOWID flow_id_ = 0;
  131. base::WeakPtrFactory<DscpManager> weak_ptr_factory_{this};
  132. };
  133. //-----------------------------------------------------------------------------
  134. class NET_EXPORT UDPSocketWin : public base::win::ObjectWatcher::Delegate {
  135. public:
  136. // BindType is ignored. Windows has an option to do random binds, so
  137. // UDPSocketWin sets that whenever connecting a socket.
  138. UDPSocketWin(DatagramSocket::BindType bind_type,
  139. net::NetLog* net_log,
  140. const net::NetLogSource& source);
  141. UDPSocketWin(const UDPSocketWin&) = delete;
  142. UDPSocketWin& operator=(const UDPSocketWin&) = delete;
  143. ~UDPSocketWin() override;
  144. // Opens the socket.
  145. // Returns a net error code.
  146. int Open(AddressFamily address_family);
  147. // Not implemented. Returns ERR_NOT_IMPLEMENTED.
  148. int BindToNetwork(handles::NetworkHandle network);
  149. // Connects the socket to connect with a certain |address|.
  150. // Should be called after Open().
  151. // Returns a net error code.
  152. int Connect(const IPEndPoint& address);
  153. // Binds the address/port for this socket to |address|. This is generally
  154. // only used on a server. Should be called after Open().
  155. // Returns a net error code.
  156. int Bind(const IPEndPoint& address);
  157. // Closes the socket.
  158. // TODO(rvargas, hidehiko): Disallow re-Open() after Close().
  159. void Close();
  160. // Copies the remote udp address into |address| and returns a net error code.
  161. int GetPeerAddress(IPEndPoint* address) const;
  162. // Copies the local udp address into |address| and returns a net error code.
  163. // (similar to getsockname)
  164. int GetLocalAddress(IPEndPoint* address) const;
  165. // IO:
  166. // Multiple outstanding read requests are not supported.
  167. // Full duplex mode (reading and writing at the same time) is supported
  168. // Reads from the socket.
  169. // Only usable from the client-side of a UDP socket, after the socket
  170. // has been connected.
  171. int Read(IOBuffer* buf, int buf_len, CompletionOnceCallback callback);
  172. // Writes to the socket.
  173. // Only usable from the client-side of a UDP socket, after the socket
  174. // has been connected.
  175. int Write(IOBuffer* buf,
  176. int buf_len,
  177. CompletionOnceCallback callback,
  178. const NetworkTrafficAnnotationTag& traffic_annotation);
  179. // Reads from a socket and receive sender address information.
  180. // |buf| is the buffer to read data into.
  181. // |buf_len| is the maximum amount of data to read.
  182. // |address| is a buffer provided by the caller for receiving the sender
  183. // address information about the received data. This buffer must be kept
  184. // alive by the caller until the callback is placed.
  185. // |callback| is the callback on completion of the RecvFrom.
  186. // Returns a net error code, or ERR_IO_PENDING if the IO is in progress.
  187. // If ERR_IO_PENDING is returned, this socket takes a ref to |buf| to keep
  188. // it alive until the data is received. However, the caller must keep
  189. // |address| alive until the callback is called.
  190. int RecvFrom(IOBuffer* buf,
  191. int buf_len,
  192. IPEndPoint* address,
  193. CompletionOnceCallback callback);
  194. // Sends to a socket with a particular destination.
  195. // |buf| is the buffer to send.
  196. // |buf_len| is the number of bytes to send.
  197. // |address| is the recipient address.
  198. // |callback| is the user callback function to call on complete.
  199. // Returns a net error code, or ERR_IO_PENDING if the IO is in progress.
  200. // If ERR_IO_PENDING is returned, this socket copies |address| for
  201. // asynchronous sending, and takes a ref to |buf| to keep it alive until the
  202. // data is sent.
  203. int SendTo(IOBuffer* buf,
  204. int buf_len,
  205. const IPEndPoint& address,
  206. CompletionOnceCallback callback);
  207. // Sets the receive buffer size (in bytes) for the socket.
  208. // Returns a net error code.
  209. int SetReceiveBufferSize(int32_t size);
  210. // Sets the send buffer size (in bytes) for the socket.
  211. // Returns a net error code.
  212. int SetSendBufferSize(int32_t size);
  213. // Requests that packets sent by this socket not be fragment, either locally
  214. // by the host, or by routers (via the DF bit in the IPv4 packet header).
  215. // May not be supported by all platforms. Returns a network error code if
  216. // there was a problem, but the socket will still be usable. Can not
  217. // return ERR_IO_PENDING.
  218. int SetDoNotFragment();
  219. // This is a no-op on Windows.
  220. void SetMsgConfirm(bool confirm);
  221. // Returns true if the socket is already connected or bound.
  222. bool is_connected() const { return is_connected_; }
  223. const NetLogWithSource& NetLog() const { return net_log_; }
  224. // Sets socket options to allow the socket to share the local address to which
  225. // the socket will be bound with other processes. If multiple processes are
  226. // bound to the same local address at the same time, behavior is undefined;
  227. // e.g., it is not guaranteed that incoming messages will be sent to all
  228. // listening sockets. Returns a net error code.
  229. //
  230. // Should be called between Open() and Bind().
  231. int AllowAddressReuse();
  232. // Sets socket options to allow sending and receiving packets to and from
  233. // broadcast addresses.
  234. int SetBroadcast(bool broadcast);
  235. // Sets socket options to allow the socket to share the local address to which
  236. // the socket will be bound with other processes and attempt to allow all such
  237. // sockets to receive the same multicast messages. Returns a net error code.
  238. //
  239. // For Windows, multicast messages should always be shared between sockets
  240. // configured thusly as long as the sockets join the same multicast group and
  241. // interface.
  242. //
  243. // Should be called between Open() and Bind().
  244. int AllowAddressSharingForMulticast();
  245. // Joins the multicast group.
  246. // |group_address| is the group address to join, could be either
  247. // an IPv4 or IPv6 address.
  248. // Returns a net error code.
  249. int JoinGroup(const IPAddress& group_address) const;
  250. // Leaves the multicast group.
  251. // |group_address| is the group address to leave, could be either
  252. // an IPv4 or IPv6 address. If the socket hasn't joined the group,
  253. // it will be ignored.
  254. // It's optional to leave the multicast group before destroying
  255. // the socket. It will be done by the OS.
  256. // Return a net error code.
  257. int LeaveGroup(const IPAddress& group_address) const;
  258. // Sets interface to use for multicast. If |interface_index| set to 0,
  259. // default interface is used.
  260. // Should be called before Bind().
  261. // Returns a net error code.
  262. int SetMulticastInterface(uint32_t interface_index);
  263. // Sets the time-to-live option for UDP packets sent to the multicast
  264. // group address. The default value of this option is 1.
  265. // Cannot be negative or more than 255.
  266. // Should be called before Bind().
  267. int SetMulticastTimeToLive(int time_to_live);
  268. // Sets the loopback flag for UDP socket. If this flag is true, the host
  269. // will receive packets sent to the joined group from itself.
  270. // The default value of this option is true.
  271. // Should be called before Bind().
  272. //
  273. // Note: the behavior of |SetMulticastLoopbackMode| is slightly
  274. // different between Windows and Unix-like systems. The inconsistency only
  275. // happens when there are more than one applications on the same host
  276. // joined to the same multicast group while having different settings on
  277. // multicast loopback mode. On Windows, the applications with loopback off
  278. // will not RECEIVE the loopback packets; while on Unix-like systems, the
  279. // applications with loopback off will not SEND the loopback packets to
  280. // other applications on the same host. See MSDN: http://goo.gl/6vqbj
  281. int SetMulticastLoopbackMode(bool loopback);
  282. // Sets the differentiated services flags on outgoing packets. May not do
  283. // anything on some platforms. A return value of ERR_INVALID_HANDLE indicates
  284. // the value was not set but could succeed on a future call, because
  285. // initialization is in progress.
  286. int SetDiffServCodePoint(DiffServCodePoint dscp);
  287. // Resets the thread to be used for thread-safety checks.
  288. void DetachFromThread();
  289. // This class by default uses overlapped IO. Call this method before Open()
  290. // to switch to non-blocking IO.
  291. void UseNonBlockingIO();
  292. // Apply |tag| to this socket.
  293. void ApplySocketTag(const SocketTag& tag);
  294. private:
  295. enum SocketOptions {
  296. SOCKET_OPTION_MULTICAST_LOOP = 1 << 0
  297. };
  298. class Core;
  299. void DoReadCallback(int rv);
  300. void DoWriteCallback(int rv);
  301. void DidCompleteRead();
  302. void DidCompleteWrite();
  303. // base::ObjectWatcher::Delegate implementation.
  304. void OnObjectSignaled(HANDLE object) override;
  305. void OnReadSignaled();
  306. void OnWriteSignaled();
  307. void WatchForReadWrite();
  308. // Handles stats and logging. |result| is the number of bytes transferred, on
  309. // success, or the net error code on failure.
  310. void LogRead(int result, const char* bytes, const IPEndPoint* address) const;
  311. void LogWrite(int result, const char* bytes, const IPEndPoint* address) const;
  312. // Same as SendTo(), except that address is passed by pointer
  313. // instead of by reference. It is called from Write() with |address|
  314. // set to NULL.
  315. int SendToOrWrite(IOBuffer* buf,
  316. int buf_len,
  317. const IPEndPoint* address,
  318. CompletionOnceCallback callback);
  319. int InternalConnect(const IPEndPoint& address);
  320. // Version for using overlapped IO.
  321. int InternalRecvFromOverlapped(IOBuffer* buf,
  322. int buf_len,
  323. IPEndPoint* address);
  324. int InternalSendToOverlapped(IOBuffer* buf,
  325. int buf_len,
  326. const IPEndPoint* address);
  327. // Version for using non-blocking IO.
  328. int InternalRecvFromNonBlocking(IOBuffer* buf,
  329. int buf_len,
  330. IPEndPoint* address);
  331. int InternalSendToNonBlocking(IOBuffer* buf,
  332. int buf_len,
  333. const IPEndPoint* address);
  334. // Applies |socket_options_| to |socket_|. Should be called before
  335. // Bind().
  336. int SetMulticastOptions();
  337. int DoBind(const IPEndPoint& address);
  338. // This is provided to allow QwaveApi mocking in tests. |UDPSocketWin| method
  339. // implementations should call |GetQwaveApi()| instead of
  340. // |QwaveApi::GetDefault()| directly.
  341. virtual QwaveApi* GetQwaveApi() const;
  342. SOCKET socket_;
  343. int addr_family_ = 0;
  344. bool is_connected_ = false;
  345. // Bitwise-or'd combination of SocketOptions. Specifies the set of
  346. // options that should be applied to |socket_| before Bind().
  347. int socket_options_;
  348. // Multicast interface.
  349. uint32_t multicast_interface_ = 0;
  350. // Multicast socket options cached for SetMulticastOption.
  351. // Cannot be used after Bind().
  352. int multicast_time_to_live_ = 1;
  353. // These are mutable since they're just cached copies to make
  354. // GetPeerAddress/GetLocalAddress smarter.
  355. mutable std::unique_ptr<IPEndPoint> local_address_;
  356. mutable std::unique_ptr<IPEndPoint> remote_address_;
  357. // The core of the socket that can live longer than the socket itself. We pass
  358. // resources to the Windows async IO functions and we have to make sure that
  359. // they are not destroyed while the OS still references them.
  360. scoped_refptr<Core> core_;
  361. // True if non-blocking IO is used.
  362. bool use_non_blocking_io_ = false;
  363. // Watches |read_write_event_|.
  364. base::win::ObjectWatcher read_write_watcher_;
  365. // Events for read and write.
  366. base::win::ScopedHandle read_write_event_;
  367. // The buffers used in Read() and Write().
  368. scoped_refptr<IOBuffer> read_iobuffer_;
  369. scoped_refptr<IOBuffer> write_iobuffer_;
  370. int read_iobuffer_len_ = 0;
  371. int write_iobuffer_len_ = 0;
  372. raw_ptr<IPEndPoint> recv_from_address_ = nullptr;
  373. // Cached copy of the current address we're sending to, if any. Used for
  374. // logging.
  375. std::unique_ptr<IPEndPoint> send_to_address_;
  376. // External callback; called when read is complete.
  377. CompletionOnceCallback read_callback_;
  378. // External callback; called when write is complete.
  379. CompletionOnceCallback write_callback_;
  380. NetLogWithSource net_log_;
  381. // Maintains remote addresses for QWAVE qos management.
  382. std::unique_ptr<DscpManager> dscp_manager_;
  383. // Manages decrementing the global open UDP socket counter when this
  384. // UDPSocket is destroyed.
  385. OwnedUDPSocketCount owned_socket_count_;
  386. THREAD_CHECKER(thread_checker_);
  387. // Used to prevent null dereferences in OnObjectSignaled, when passing an
  388. // error to both read and write callbacks. Cleared in Close()
  389. base::WeakPtrFactory<UDPSocketWin> event_pending_{this};
  390. };
  391. //-----------------------------------------------------------------------------
  392. } // namespace net
  393. #endif // NET_SOCKET_UDP_SOCKET_WIN_H_