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