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