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/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"
23 class NET_EXPORT UDPSocketLibevent
: public base::NonThreadSafe
{
25 UDPSocketLibevent(DatagramSocket::BindType bind_type
,
26 const RandIntCallback
& rand_int_cb
,
28 const net::NetLog::Source
& source
);
29 virtual ~UDPSocketLibevent();
31 // Connect the socket to connect with a certain |address|.
32 // Returns a net error code.
33 int Connect(const IPEndPoint
& address
);
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
);
43 // Copy the remote udp address into |address| and return a network error code.
44 int GetPeerAddress(IPEndPoint
* address
) const;
46 // Copy the local udp address into |address| and return a network error code.
47 // (similar to getsockname)
48 int GetLocalAddress(IPEndPoint
* address
) const;
51 // Multiple outstanding read requests are not supported.
52 // Full duplex mode (reading and writing at the same time) is supported
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
);
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
);
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| is the callback on completion of the RecvFrom.
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
,
80 const CompletionCallback
& callback
);
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
,
93 const IPEndPoint
& address
,
94 const CompletionCallback
& callback
);
96 // Set the receive buffer size (in bytes) for the socket.
97 int SetReceiveBufferSize(int32 size
);
99 // Set the send buffer size (in bytes) for the socket.
100 int SetSendBufferSize(int32 size
);
102 // Returns true if the socket is already connected or bound.
103 bool is_connected() const { return socket_
!= kInvalidSocket
; }
105 const BoundNetLog
& NetLog() const { return net_log_
; }
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();
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();
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;
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;
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
);
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
);
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.
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
);
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
);
166 // Resets the thread to be used for thread-safety checks.
167 void DetachFromThread();
171 SOCKET_OPTION_REUSE_ADDRESS
= 1 << 0,
172 SOCKET_OPTION_BROADCAST
= 1 << 1,
173 SOCKET_OPTION_MULTICAST_LOOP
= 1 << 2
176 class ReadWatcher
: public base::MessageLoopForIO::Watcher
{
178 explicit ReadWatcher(UDPSocketLibevent
* socket
) : socket_(socket
) {}
180 // MessageLoopForIO::Watcher methods
182 virtual void OnFileCanReadWithoutBlocking(int /* fd */) OVERRIDE
;
184 virtual void OnFileCanWriteWithoutBlocking(int /* fd */) OVERRIDE
{}
187 UDPSocketLibevent
* const socket_
;
189 DISALLOW_COPY_AND_ASSIGN(ReadWatcher
);
192 class WriteWatcher
: public base::MessageLoopForIO::Watcher
{
194 explicit WriteWatcher(UDPSocketLibevent
* socket
) : socket_(socket
) {}
196 // MessageLoopForIO::Watcher methods
198 virtual void OnFileCanReadWithoutBlocking(int /* fd */) OVERRIDE
{}
200 virtual void OnFileCanWriteWithoutBlocking(int /* fd */) OVERRIDE
;
203 UDPSocketLibevent
* const socket_
;
205 DISALLOW_COPY_AND_ASSIGN(WriteWatcher
);
208 void DoReadCallback(int rv
);
209 void DoWriteCallback(int rv
);
210 void DidCompleteRead();
211 void DidCompleteWrite();
213 // Handles stats and logging. |result| is the number of bytes transferred, on
214 // success, or the net error code on failure. On success, LogRead takes in a
215 // sockaddr and its length, which are mandatory, while LogWrite takes in an
216 // optional IPEndPoint.
217 void LogRead(int result
, const char* bytes
, socklen_t addr_len
,
218 const sockaddr
* addr
) const;
219 void LogWrite(int result
, const char* bytes
, const IPEndPoint
* address
) const;
221 // Returns the OS error code (or 0 on success).
222 int CreateSocket(int addr_family
);
224 // Same as SendTo(), except that address is passed by pointer
225 // instead of by reference. It is called from Write() with |address|
227 int SendToOrWrite(IOBuffer
* buf
,
229 const IPEndPoint
* address
,
230 const CompletionCallback
& callback
);
232 int InternalConnect(const IPEndPoint
& address
);
233 int InternalRecvFrom(IOBuffer
* buf
, int buf_len
, IPEndPoint
* address
);
234 int InternalSendTo(IOBuffer
* buf
, int buf_len
, const IPEndPoint
* address
);
236 // Applies |socket_options_| to |socket_|. Should be called before
238 int SetSocketOptions();
239 int DoBind(const IPEndPoint
& address
);
240 // Binds to a random port on |address|.
241 int RandomBind(const IPAddressNumber
& address
);
246 // Bitwise-or'd combination of SocketOptions. Specifies the set of
247 // options that should be applied to |socket_| before Bind().
250 // Multicast interface.
251 uint32 multicast_interface_
;
253 // Multicast socket options cached for SetSocketOption.
254 // Cannot be used after Bind().
255 int multicast_time_to_live_
;
257 // How to do source port binding, used only when UDPSocket is part of
258 // UDPClientSocket, since UDPServerSocket provides Bind.
259 DatagramSocket::BindType bind_type_
;
261 // PRNG function for generating port numbers.
262 RandIntCallback rand_int_cb_
;
264 // These are mutable since they're just cached copies to make
265 // GetPeerAddress/GetLocalAddress smarter.
266 mutable scoped_ptr
<IPEndPoint
> local_address_
;
267 mutable scoped_ptr
<IPEndPoint
> remote_address_
;
269 // The socket's libevent wrappers
270 base::MessageLoopForIO::FileDescriptorWatcher read_socket_watcher_
;
271 base::MessageLoopForIO::FileDescriptorWatcher write_socket_watcher_
;
273 // The corresponding watchers for reads and writes.
274 ReadWatcher read_watcher_
;
275 WriteWatcher write_watcher_
;
277 // The buffer used by InternalRead() to retry Read requests
278 scoped_refptr
<IOBuffer
> read_buf_
;
280 IPEndPoint
* recv_from_address_
;
282 // The buffer used by InternalWrite() to retry Write requests
283 scoped_refptr
<IOBuffer
> write_buf_
;
285 scoped_ptr
<IPEndPoint
> send_to_address_
;
287 // External callback; called when read is complete.
288 CompletionCallback read_callback_
;
290 // External callback; called when write is complete.
291 CompletionCallback write_callback_
;
293 BoundNetLog net_log_
;
295 DISALLOW_COPY_AND_ASSIGN(UDPSocketLibevent
);
300 #endif // NET_UDP_UDP_SOCKET_LIBEVENT_H_