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();
117 static const int kInvalidSocket
= -1;
120 SOCKET_OPTION_REUSE_ADDRESS
= 1 << 0,
121 SOCKET_OPTION_BROADCAST
= 1 << 1
124 class ReadWatcher
: public MessageLoopForIO::Watcher
{
126 explicit ReadWatcher(UDPSocketLibevent
* socket
) : socket_(socket
) {}
128 // MessageLoopForIO::Watcher methods
130 virtual void OnFileCanReadWithoutBlocking(int /* fd */) OVERRIDE
;
132 virtual void OnFileCanWriteWithoutBlocking(int /* fd */) OVERRIDE
{}
135 UDPSocketLibevent
* const socket_
;
137 DISALLOW_COPY_AND_ASSIGN(ReadWatcher
);
140 class WriteWatcher
: public MessageLoopForIO::Watcher
{
142 explicit WriteWatcher(UDPSocketLibevent
* socket
) : socket_(socket
) {}
144 // MessageLoopForIO::Watcher methods
146 virtual void OnFileCanReadWithoutBlocking(int /* fd */) OVERRIDE
{}
148 virtual void OnFileCanWriteWithoutBlocking(int /* fd */) OVERRIDE
;
151 UDPSocketLibevent
* const socket_
;
153 DISALLOW_COPY_AND_ASSIGN(WriteWatcher
);
156 void DoReadCallback(int rv
);
157 void DoWriteCallback(int rv
);
158 void DidCompleteRead();
159 void DidCompleteWrite();
161 // Handles stats and logging. |result| is the number of bytes transferred, on
162 // success, or the net error code on failure. On success, LogRead takes in a
163 // sockaddr and its length, which are mandatory, while LogWrite takes in an
164 // optional IPEndPoint.
165 void LogRead(int result
, const char* bytes
, socklen_t addr_len
,
166 const sockaddr
* addr
) const;
167 void LogWrite(int result
, const char* bytes
, const IPEndPoint
* address
) const;
169 // Returns the OS error code (or 0 on success).
170 int CreateSocket(const IPEndPoint
& address
);
172 // Same as SendTo(), except that address is passed by pointer
173 // instead of by reference. It is called from Write() with |address|
175 int SendToOrWrite(IOBuffer
* buf
,
177 const IPEndPoint
* address
,
178 const CompletionCallback
& callback
);
180 int InternalConnect(const IPEndPoint
& address
);
181 int InternalRecvFrom(IOBuffer
* buf
, int buf_len
, IPEndPoint
* address
);
182 int InternalSendTo(IOBuffer
* buf
, int buf_len
, const IPEndPoint
* address
);
184 // Applies |socket_options_| to |socket_|. Should be called before
186 int SetSocketOptions();
187 int DoBind(const IPEndPoint
& address
);
188 int RandomBind(const IPEndPoint
& address
);
192 // Bitwise-or'd combination of SocketOptions. Specifies the set of
193 // options that should be applied to |socket_| before Bind().
196 // How to do source port binding, used only when UDPSocket is part of
197 // UDPClientSocket, since UDPServerSocket provides Bind.
198 DatagramSocket::BindType bind_type_
;
200 // PRNG function for generating port numbers.
201 RandIntCallback rand_int_cb_
;
203 // These are mutable since they're just cached copies to make
204 // GetPeerAddress/GetLocalAddress smarter.
205 mutable scoped_ptr
<IPEndPoint
> local_address_
;
206 mutable scoped_ptr
<IPEndPoint
> remote_address_
;
208 // The socket's libevent wrappers
209 MessageLoopForIO::FileDescriptorWatcher read_socket_watcher_
;
210 MessageLoopForIO::FileDescriptorWatcher write_socket_watcher_
;
212 // The corresponding watchers for reads and writes.
213 ReadWatcher read_watcher_
;
214 WriteWatcher write_watcher_
;
216 // The buffer used by InternalRead() to retry Read requests
217 scoped_refptr
<IOBuffer
> read_buf_
;
219 IPEndPoint
* recv_from_address_
;
221 // The buffer used by InternalWrite() to retry Write requests
222 scoped_refptr
<IOBuffer
> write_buf_
;
224 scoped_ptr
<IPEndPoint
> send_to_address_
;
226 // External callback; called when read is complete.
227 CompletionCallback read_callback_
;
229 // External callback; called when write is complete.
230 CompletionCallback write_callback_
;
232 BoundNetLog net_log_
;
234 DISALLOW_COPY_AND_ASSIGN(UDPSocketLibevent
);
239 #endif // NET_UDP_UDP_SOCKET_LIBEVENT_H_