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