blob: df3bf9735ba2d5074f4a9fe4b0952328a4167548 [file] [log] [blame]
[email protected]398dca82012-04-25 17:54:531// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]a2798d92011-03-02 22:56:182// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
tfarina5dd13c22016-11-16 12:08:265#ifndef NET_SOCKET_UDP_SOCKET_POSIX_H_
6#define NET_SOCKET_UDP_SOCKET_POSIX_H_
[email protected]a2798d92011-03-02 22:56:187
tfarinac40df1c2015-11-30 22:31:478#include <stdint.h>
Charles 'Buck' Krasic762317f2018-03-30 20:08:099#include <sys/socket.h>
10#include <sys/types.h>
tfarinac40df1c2015-11-30 22:31:4711
danakja9850e12016-04-18 22:28:0812#include <memory>
13
Hans Wennborg725d0432020-06-18 13:54:1614#include "base/logging.h"
Avi Drissman13fc8932015-12-20 04:40:4615#include "base/macros.h"
[email protected]3b63f8f42011-03-28 01:54:1516#include "base/memory/ref_counted.h"
Gabriel Charette19d2ae62018-04-10 14:10:5817#include "base/message_loop/message_pump_for_io.h"
gabd43afa12017-05-30 18:26:2418#include "base/threading/thread_checker.h"
Charles 'Buck' Krasice70ff452017-08-14 22:11:4419#include "base/timer/timer.h"
Charles 'Buck' Krasic762317f2018-03-30 20:08:0920#include "build/build_config.h"
hidehiko17fac552014-12-08 06:02:1721#include "net/base/address_family.h"
Brad Lassey3a814172018-04-26 03:30:2122#include "net/base/completion_once_callback.h"
Charles 'Buck' Krasic762317f2018-03-30 20:08:0923#include "net/base/datagram_buffer.h"
[email protected]5370c012011-06-29 03:47:0424#include "net/base/io_buffer.h"
[email protected]43d4a0262011-03-09 19:26:0425#include "net/base/ip_endpoint.h"
[email protected]7f86564d2013-07-18 00:41:2226#include "net/base/net_export.h"
tfarina42f7ce832015-10-08 20:45:5327#include "net/base/network_change_notifier.h"
mikecironef22f9812016-10-04 03:40:1928#include "net/log/net_log_with_source.h"
tfarina5dd13c22016-11-16 12:08:2629#include "net/socket/datagram_socket.h"
30#include "net/socket/diff_serv_code_point.h"
[email protected]bbfef1f2013-08-28 03:00:5131#include "net/socket/socket_descriptor.h"
Paul Jensen0f49dec2017-12-12 23:39:5832#include "net/socket/socket_tag.h"
[email protected]a2b2cfc2017-12-06 09:06:0833#include "net/traffic_annotation/network_traffic_annotation.h"
[email protected]a2798d92011-03-02 22:56:1834
Charles 'Buck' Krasic762317f2018-03-30 20:08:0935#if defined(__ANDROID__) && defined(__aarch64__)
36#define HAVE_SENDMMSG 1
37#elif defined(OS_LINUX)
38#define HAVE_SENDMMSG 1
39#else
40#define HAVE_SENDMMSG 0
41#endif
42
[email protected]a2798d92011-03-02 22:56:1843namespace net {
44
martijnd8dafab2016-03-14 18:28:4945class IPAddress;
mikecironef22f9812016-10-04 03:40:1946class NetLog;
47struct NetLogSource;
Paul Jensen0f49dec2017-12-12 23:39:5848class SocketTag;
martijnd8dafab2016-03-14 18:28:4949
Charles 'Buck' Krasic762317f2018-03-30 20:08:0950// Sendresult is inspired by sendmmsg, but unlike sendmmsg it is not
51// convenient to require that a positive |write_count| and a negative
52// error code are mutually exclusive.
53struct NET_EXPORT SendResult {
54 explicit SendResult();
55 ~SendResult();
56 SendResult(int rv, int write_count, DatagramBuffers buffers);
57 SendResult(SendResult& other) = delete;
58 SendResult& operator=(SendResult& other) = delete;
59 SendResult(SendResult&& other);
60 SendResult& operator=(SendResult&& other) = default;
61 int rv;
62 // number of successful writes.
63 int write_count;
64 DatagramBuffers buffers;
65};
66
67// Don't delay writes more than this.
68const base::TimeDelta kWriteAsyncMsThreshold =
69 base::TimeDelta::FromMilliseconds(1);
70// Prefer local if number of writes is not more than this.
71const int kWriteAsyncMinBuffersThreshold = 2;
72// Don't allow more than this many outstanding async writes.
73const int kWriteAsyncMaxBuffersThreshold = 16;
74// PostTask immediately when unwritten buffers reaches this.
75const int kWriteAsyncPostBuffersThreshold = kWriteAsyncMaxBuffersThreshold / 2;
76// Don't unblock writer unless pending async writes are less than this.
77const int kWriteAsyncCallbackBuffersThreshold = kWriteAsyncMaxBuffersThreshold;
78
79// To allow mock |Send|/|Sendmsg| in testing. This has to be
80// reference counted thread safe because |SendBuffers| and
81// |SendmmsgBuffers| may be invoked in another thread via PostTask*.
82class NET_EXPORT UDPSocketPosixSender
83 : public base::RefCountedThreadSafe<UDPSocketPosixSender> {
84 public:
Eric Orth7141dbc2018-10-26 20:10:2485 UDPSocketPosixSender();
Charles 'Buck' Krasic762317f2018-03-30 20:08:0986
87 SendResult SendBuffers(int fd, DatagramBuffers buffers);
88
89 void SetSendmmsgEnabled(bool enabled) {
90#if HAVE_SENDMMSG
91 sendmmsg_enabled_ = enabled;
92#endif
93 }
94
95 protected:
96 friend class base::RefCountedThreadSafe<UDPSocketPosixSender>;
97
98 virtual ~UDPSocketPosixSender();
99 virtual ssize_t Send(int sockfd,
100 const void* buf,
101 size_t len,
102 int flags) const;
103#if HAVE_SENDMMSG
104 virtual int Sendmmsg(int sockfd,
105 struct mmsghdr* msgvec,
106 unsigned int vlen,
107 unsigned int flags) const;
108#endif
109
110 SendResult InternalSendBuffers(int fd, DatagramBuffers buffers) const;
111#if HAVE_SENDMMSG
112 SendResult InternalSendmmsgBuffers(int fd, DatagramBuffers buffers) const;
113#endif
114
115 private:
116 UDPSocketPosixSender(const UDPSocketPosixSender&) = delete;
117 UDPSocketPosixSender& operator=(const UDPSocketPosixSender&) = delete;
118 bool sendmmsg_enabled_;
119};
120
gabd43afa12017-05-30 18:26:24121class NET_EXPORT UDPSocketPosix {
[email protected]a2798d92011-03-02 22:56:18122 public:
Charles 'Buck' Krasice70ff452017-08-14 22:11:44123 // Performance helper for NetworkActivityMonitor, it batches
124 // throughput samples, subject to a byte limit threshold (64 KB) or
125 // timer (100 ms), whichever comes first. The batching is subject
126 // to a minimum number of samples (2) required by NQE to update its
127 // throughput estimate.
128 class ActivityMonitor {
129 public:
130 ActivityMonitor() : bytes_(0), increments_(0) {}
131 virtual ~ActivityMonitor() {}
132 // Provided by sent/received subclass.
133 // Update throughput, but batch to limit overhead of NetworkActivityMonitor.
134 void Increment(uint32_t bytes);
135 // For flushing cached values.
136 void OnClose();
137
138 private:
139 virtual void NetworkActivityMonitorIncrement(uint32_t bytes) = 0;
140 void Update();
141 void OnTimerFired();
142
143 uint32_t bytes_;
144 uint32_t increments_;
145 base::RepeatingTimer timer_;
146 DISALLOW_COPY_AND_ASSIGN(ActivityMonitor);
147 };
148
149 class SentActivityMonitor : public ActivityMonitor {
150 public:
151 ~SentActivityMonitor() override {}
152
153 private:
154 void NetworkActivityMonitorIncrement(uint32_t bytes) override;
155 };
156
157 class ReceivedActivityMonitor : public ActivityMonitor {
158 public:
159 ~ReceivedActivityMonitor() override {}
160
161 private:
162 void NetworkActivityMonitorIncrement(uint32_t bytes) override;
163 };
164
tfarina4eb7aad82015-09-14 17:10:34165 UDPSocketPosix(DatagramSocket::BindType bind_type,
tfarina4eb7aad82015-09-14 17:10:34166 net::NetLog* net_log,
mikecironef22f9812016-10-04 03:40:19167 const net::NetLogSource& source);
tfarina4eb7aad82015-09-14 17:10:34168 virtual ~UDPSocketPosix();
[email protected]a2798d92011-03-02 22:56:18169
hidehiko17fac552014-12-08 06:02:17170 // Opens the socket.
171 // Returns a net error code.
172 int Open(AddressFamily address_family);
173
pauljensenbe5bc3232015-10-05 20:39:27174 // Binds this socket to |network|. All data traffic on the socket will be sent
175 // and received via |network|. Must be called before Connect(). This call will
176 // fail if |network| has disconnected. Communication using this socket will
177 // fail if |network| disconnects.
178 // Returns a net error code.
179 int BindToNetwork(NetworkChangeNotifier::NetworkHandle network);
180
hidehiko17fac552014-12-08 06:02:17181 // Connects the socket to connect with a certain |address|.
182 // Should be called after Open().
[email protected]a2798d92011-03-02 22:56:18183 // Returns a net error code.
[email protected]43d4a0262011-03-09 19:26:04184 int Connect(const IPEndPoint& address);
[email protected]a2798d92011-03-02 22:56:18185
hidehiko17fac552014-12-08 06:02:17186 // Binds the address/port for this socket to |address|. This is generally
187 // only used on a server. Should be called after Open().
[email protected]a2798d92011-03-02 22:56:18188 // Returns a net error code.
[email protected]43d4a0262011-03-09 19:26:04189 int Bind(const IPEndPoint& address);
[email protected]a2798d92011-03-02 22:56:18190
hidehiko17fac552014-12-08 06:02:17191 // Closes the socket.
192 // TODO(rvargas, hidehiko): Disallow re-Open() after Close().
[email protected]a2798d92011-03-02 22:56:18193 void Close();
194
hidehiko17fac552014-12-08 06:02:17195 // Copies the remote udp address into |address| and returns a net error code.
[email protected]43d4a0262011-03-09 19:26:04196 int GetPeerAddress(IPEndPoint* address) const;
[email protected]a2798d92011-03-02 22:56:18197
hidehiko17fac552014-12-08 06:02:17198 // Copies the local udp address into |address| and returns a net error code.
[email protected]a2798d92011-03-02 22:56:18199 // (similar to getsockname)
[email protected]43d4a0262011-03-09 19:26:04200 int GetLocalAddress(IPEndPoint* address) const;
[email protected]a2798d92011-03-02 22:56:18201
202 // IO:
203 // Multiple outstanding read requests are not supported.
204 // Full duplex mode (reading and writing at the same time) is supported
205
hidehiko17fac552014-12-08 06:02:17206 // Reads from the socket.
[email protected]a2798d92011-03-02 22:56:18207 // Only usable from the client-side of a UDP socket, after the socket
208 // has been connected.
Brad Lassey3a814172018-04-26 03:30:21209 int Read(IOBuffer* buf, int buf_len, CompletionOnceCallback callback);
[email protected]a2798d92011-03-02 22:56:18210
hidehiko17fac552014-12-08 06:02:17211 // Writes to the socket.
[email protected]a2798d92011-03-02 22:56:18212 // Only usable from the client-side of a UDP socket, after the socket
213 // has been connected.
[email protected]a2b2cfc2017-12-06 09:06:08214 int Write(IOBuffer* buf,
215 int buf_len,
Brad Lassey3a814172018-04-26 03:30:21216 CompletionOnceCallback callback,
[email protected]cda4b7b2017-12-20 06:04:43217 const NetworkTrafficAnnotationTag& traffic_annotation);
[email protected]a2798d92011-03-02 22:56:18218
Charles 'Buck' Krasic762317f2018-03-30 20:08:09219 // Refer to datagram_client_socket.h
220 int WriteAsync(DatagramBuffers buffers,
Brad Lassey3a814172018-04-26 03:30:21221 CompletionOnceCallback callback,
Charles 'Buck' Krasic762317f2018-03-30 20:08:09222 const NetworkTrafficAnnotationTag& traffic_annotation);
223 int WriteAsync(const char* buffer,
224 size_t buf_len,
Brad Lassey3a814172018-04-26 03:30:21225 CompletionOnceCallback callback,
Charles 'Buck' Krasic762317f2018-03-30 20:08:09226 const NetworkTrafficAnnotationTag& traffic_annotation);
227
228 DatagramBuffers GetUnwrittenBuffers();
229
hidehiko17fac552014-12-08 06:02:17230 // Reads from a socket and receive sender address information.
[email protected]a2798d92011-03-02 22:56:18231 // |buf| is the buffer to read data into.
232 // |buf_len| is the maximum amount of data to read.
233 // |address| is a buffer provided by the caller for receiving the sender
234 // address information about the received data. This buffer must be kept
235 // alive by the caller until the callback is placed.
[email protected]73c5b692014-07-01 12:43:41236 // |callback| is the callback on completion of the RecvFrom.
[email protected]a2798d92011-03-02 22:56:18237 // Returns a net error code, or ERR_IO_PENDING if the IO is in progress.
Matthew Denton111df5ad2018-10-19 20:39:25238 // If ERR_IO_PENDING is returned, this socket takes a ref to |buf| to keep
239 // it alive until the data is received. However, the caller must keep
240 // |address| alive until the callback is called.
[email protected]a2798d92011-03-02 22:56:18241 int RecvFrom(IOBuffer* buf,
242 int buf_len,
[email protected]43d4a0262011-03-09 19:26:04243 IPEndPoint* address,
Brad Lassey3a814172018-04-26 03:30:21244 CompletionOnceCallback callback);
[email protected]a2798d92011-03-02 22:56:18245
hidehiko17fac552014-12-08 06:02:17246 // Sends to a socket with a particular destination.
tfarina39524dd2016-02-19 10:52:10247 // |buf| is the buffer to send.
248 // |buf_len| is the number of bytes to send.
[email protected]a2798d92011-03-02 22:56:18249 // |address| is the recipient address.
[email protected]a2798d92011-03-02 22:56:18250 // |callback| is the user callback function to call on complete.
251 // Returns a net error code, or ERR_IO_PENDING if the IO is in progress.
Matthew Denton111df5ad2018-10-19 20:39:25252 // If ERR_IO_PENDING is returned, this socket copies |address| for
253 // asynchronous sending, and takes a ref to |buf| to keep it alive until the
254 // data is sent.
[email protected]a2798d92011-03-02 22:56:18255 int SendTo(IOBuffer* buf,
256 int buf_len,
[email protected]43d4a0262011-03-09 19:26:04257 const IPEndPoint& address,
Brad Lassey3a814172018-04-26 03:30:21258 CompletionOnceCallback callback);
[email protected]a2798d92011-03-02 22:56:18259
hidehiko17fac552014-12-08 06:02:17260 // Sets the receive buffer size (in bytes) for the socket.
261 // Returns a net error code.
tfarinac40df1c2015-11-30 22:31:47262 int SetReceiveBufferSize(int32_t size);
[email protected]df31da42011-10-18 01:44:40263
hidehiko17fac552014-12-08 06:02:17264 // Sets the send buffer size (in bytes) for the socket.
265 // Returns a net error code.
tfarinac40df1c2015-11-30 22:31:47266 int SetSendBufferSize(int32_t size);
[email protected]df31da42011-10-18 01:44:40267
rchff006a12016-08-24 23:56:31268 // Requests that packets sent by this socket not be fragment, either locally
269 // by the host, or by routers (via the DF bit in the IPv4 packet header).
270 // May not be supported by all platforms. Returns a return a network error
271 // code if there was a problem, but the socket will still be usable. Can not
272 // return ERR_IO_PENDING.
273 int SetDoNotFragment();
274
Yixin Wang3ae76ca2018-03-15 17:18:52275 // If |confirm| is true, then the MSG_CONFIRM flag will be passed to
276 // subsequent writes if it's supported by the platform.
277 void SetMsgConfirm(bool confirm);
278
[email protected]a2798d92011-03-02 22:56:18279 // Returns true if the socket is already connected or bound.
hidehiko17fac552014-12-08 06:02:17280 bool is_connected() const { return is_connected_; }
[email protected]a2798d92011-03-02 22:56:18281
tfarina42834112016-09-22 13:38:20282 const NetLogWithSource& NetLog() const { return net_log_; }
[email protected]eaf10dc2011-07-18 21:47:35283
tfarina6f2f3beb2017-04-19 11:53:14284 // Call this to enable SO_REUSEADDR on the underlying socket.
285 // Should be called between Open() and Bind().
hidehiko17fac552014-12-08 06:02:17286 // Returns a net error code.
287 int AllowAddressReuse();
[email protected]a1781d7b2012-07-16 11:52:34288
tfarina6f2f3beb2017-04-19 11:53:14289 // Call this to allow or disallow sending and receiving packets to and from
290 // broadcast addresses.
hidehiko17fac552014-12-08 06:02:17291 // Returns a net error code.
292 int SetBroadcast(bool broadcast);
[email protected]a1781d7b2012-07-16 11:52:34293
Eric Orth7141dbc2018-10-26 20:10:24294 // Sets socket options to allow the socket to share the local address to which
295 // the socket will be bound with other processes and attempt to allow all such
296 // sockets to receive the same multicast messages. Returns a net error code.
297 //
298 // Ability and requirements for different sockets to receive the same messages
299 // varies between POSIX platforms. For best results in allowing the messages
300 // to be shared, all sockets sharing the same address should join the same
301 // multicast group and interface. Also, the socket should listen to the
302 // specific multicast address rather than a wildcard address (e.g. 0.0.0.0).
303 //
304 // Should be called between Open() and Bind().
305 int AllowAddressSharingForMulticast();
306
hidehiko17fac552014-12-08 06:02:17307 // Joins the multicast group.
[email protected]5f01ce22013-04-30 00:53:18308 // |group_address| is the group address to join, could be either
309 // an IPv4 or IPv6 address.
hidehiko17fac552014-12-08 06:02:17310 // Returns a net error code.
martijnd8dafab2016-03-14 18:28:49311 int JoinGroup(const IPAddress& group_address) const;
[email protected]5f01ce22013-04-30 00:53:18312
hidehiko17fac552014-12-08 06:02:17313 // Leaves the multicast group.
[email protected]5f01ce22013-04-30 00:53:18314 // |group_address| is the group address to leave, could be either
315 // an IPv4 or IPv6 address. If the socket hasn't joined the group,
316 // it will be ignored.
317 // It's optional to leave the multicast group before destroying
318 // the socket. It will be done by the OS.
hidehiko17fac552014-12-08 06:02:17319 // Returns a net error code.
martijnd8dafab2016-03-14 18:28:49320 int LeaveGroup(const IPAddress& group_address) const;
[email protected]5f01ce22013-04-30 00:53:18321
hidehiko17fac552014-12-08 06:02:17322 // Sets interface to use for multicast. If |interface_index| set to 0,
323 // default interface is used.
[email protected]7b29dac2013-12-05 11:19:42324 // Should be called before Bind().
hidehiko17fac552014-12-08 06:02:17325 // Returns a net error code.
tfarinac40df1c2015-11-30 22:31:47326 int SetMulticastInterface(uint32_t interface_index);
[email protected]7b29dac2013-12-05 11:19:42327
hidehiko17fac552014-12-08 06:02:17328 // Sets the time-to-live option for UDP packets sent to the multicast
[email protected]5f01ce22013-04-30 00:53:18329 // group address. The default value of this option is 1.
330 // Cannot be negative or more than 255.
331 // Should be called before Bind().
hidehiko17fac552014-12-08 06:02:17332 // Returns a net error code.
[email protected]5f01ce22013-04-30 00:53:18333 int SetMulticastTimeToLive(int time_to_live);
334
hidehiko17fac552014-12-08 06:02:17335 // Sets the loopback flag for UDP socket. If this flag is true, the host
[email protected]5f01ce22013-04-30 00:53:18336 // will receive packets sent to the joined group from itself.
337 // The default value of this option is true.
338 // Should be called before Bind().
hidehiko17fac552014-12-08 06:02:17339 // Returns a net error code.
[email protected]5f01ce22013-04-30 00:53:18340 //
341 // Note: the behavior of |SetMulticastLoopbackMode| is slightly
342 // different between Windows and Unix-like systems. The inconsistency only
343 // happens when there are more than one applications on the same host
344 // joined to the same multicast group while having different settings on
345 // multicast loopback mode. On Windows, the applications with loopback off
346 // will not RECEIVE the loopback packets; while on Unix-like systems, the
347 // applications with loopback off will not SEND the loopback packets to
348 // other applications on the same host. See MSDN: http://goo.gl/6vqbj
349 int SetMulticastLoopbackMode(bool loopback);
350
hidehiko17fac552014-12-08 06:02:17351 // Sets the differentiated services flags on outgoing packets. May not
[email protected]a8a442b32013-10-22 00:34:41352 // do anything on some platforms.
hidehiko17fac552014-12-08 06:02:17353 // Returns a net error code.
[email protected]a8a442b32013-10-22 00:34:41354 int SetDiffServCodePoint(DiffServCodePoint dscp);
355
[email protected]1901dbcb2014-03-10 07:18:37356 // Resets the thread to be used for thread-safety checks.
357 void DetachFromThread();
358
Paul Jensen0f49dec2017-12-12 23:39:58359 // Apply |tag| to this socket.
360 void ApplySocketTag(const SocketTag& tag);
361
Charles 'Buck' Krasic762317f2018-03-30 20:08:09362 void SetWriteAsyncEnabled(bool enabled) { write_async_enabled_ = enabled; }
363 bool WriteAsyncEnabled() { return write_async_enabled_; }
364
365 void SetMaxPacketSize(size_t max_packet_size);
366
367 void SetWriteMultiCoreEnabled(bool enabled) {
368 write_multi_core_enabled_ = enabled;
369 }
370
371 void SetSendmmsgEnabled(bool enabled) {
372 DCHECK(sender_ != nullptr);
373 sender_->SetSendmmsgEnabled(enabled);
374 }
375
376 void SetWriteBatchingActive(bool active) { write_batching_active_ = active; }
377
378 void SetWriteAsyncMaxBuffers(int value) {
379 LOG(INFO) << "SetWriteAsyncMaxBuffers: " << value;
380 write_async_max_buffers_ = value;
381 }
382
kapishnikov7f8dd1e2018-01-24 06:10:49383 // Enables experimental optimization. This method should be called
384 // before the socket is used to read data for the first time.
385 void enable_experimental_recv_optimization() {
386 DCHECK_EQ(kInvalidSocket, socket_);
387 experimental_recv_optimization_enabled_ = true;
Eric Orth7141dbc2018-10-26 20:10:24388 }
kapishnikov7f8dd1e2018-01-24 06:10:49389
Charles 'Buck' Krasic762317f2018-03-30 20:08:09390 protected:
391 // WriteAsync batching etc. are to improve throughput of large high
392 // bandwidth uploads.
393
394 // Watcher for WriteAsync paths.
Gabriel Charette19d2ae62018-04-10 14:10:58395 class WriteAsyncWatcher : public base::MessagePumpForIO::FdWatcher {
Charles 'Buck' Krasic762317f2018-03-30 20:08:09396 public:
397 explicit WriteAsyncWatcher(UDPSocketPosix* socket)
398 : socket_(socket), watching_(false) {}
399
Gabriel Charette19d2ae62018-04-10 14:10:58400 // MessagePumpForIO::FdWatcher methods
Charles 'Buck' Krasic762317f2018-03-30 20:08:09401
402 void OnFileCanReadWithoutBlocking(int /* fd */) override {}
403
404 void OnFileCanWriteWithoutBlocking(int /* fd */) override;
405
406 void set_watching(bool watching) { watching_ = watching; }
407
408 bool watching() { return watching_; }
409
410 private:
411 UDPSocketPosix* const socket_;
412 bool watching_;
413
414 DISALLOW_COPY_AND_ASSIGN(WriteAsyncWatcher);
415 };
416
417 void IncreaseWriteAsyncOutstanding(int increment) {
418 write_async_outstanding_ += increment;
419 }
420
421 virtual bool InternalWatchFileDescriptor();
422 virtual void InternalStopWatchingFileDescriptor();
423
Brad Lassey3a814172018-04-26 03:30:21424 void SetWriteCallback(CompletionOnceCallback callback) {
Charles 'Buck' Krasic762317f2018-03-30 20:08:09425 write_callback_ = std::move(callback);
426 }
427
428 void DidSendBuffers(SendResult buffers);
429 void FlushPending();
430
431 std::unique_ptr<WriteAsyncWatcher> write_async_watcher_;
432 scoped_refptr<UDPSocketPosixSender> sender_;
433 std::unique_ptr<DatagramBufferPool> datagram_buffer_pool_;
434 // |WriteAsync| pending writes, does not include buffers that have
435 // been |PostTask*|'d.
436 DatagramBuffers pending_writes_;
437
[email protected]a2798d92011-03-02 22:56:18438 private:
[email protected]a1781d7b2012-07-16 11:52:34439 enum SocketOptions {
hidehiko17fac552014-12-08 06:02:17440 SOCKET_OPTION_MULTICAST_LOOP = 1 << 0
[email protected]a1781d7b2012-07-16 11:52:34441 };
442
Gabriel Charette19d2ae62018-04-10 14:10:58443 class ReadWatcher : public base::MessagePumpForIO::FdWatcher {
[email protected]a2798d92011-03-02 22:56:18444 public:
tfarina4eb7aad82015-09-14 17:10:34445 explicit ReadWatcher(UDPSocketPosix* socket) : socket_(socket) {}
[email protected]a2798d92011-03-02 22:56:18446
Gabriel Charette19d2ae62018-04-10 14:10:58447 // MessagePumpForIO::FdWatcher methods
[email protected]a2798d92011-03-02 22:56:18448
dchengb03027d2014-10-21 12:00:20449 void OnFileCanReadWithoutBlocking(int /* fd */) override;
[email protected]a2798d92011-03-02 22:56:18450
dchengb03027d2014-10-21 12:00:20451 void OnFileCanWriteWithoutBlocking(int /* fd */) override {}
[email protected]a2798d92011-03-02 22:56:18452
453 private:
tfarina4eb7aad82015-09-14 17:10:34454 UDPSocketPosix* const socket_;
[email protected]a2798d92011-03-02 22:56:18455
456 DISALLOW_COPY_AND_ASSIGN(ReadWatcher);
457 };
458
Gabriel Charette19d2ae62018-04-10 14:10:58459 class WriteWatcher : public base::MessagePumpForIO::FdWatcher {
[email protected]a2798d92011-03-02 22:56:18460 public:
tfarina4eb7aad82015-09-14 17:10:34461 explicit WriteWatcher(UDPSocketPosix* socket) : socket_(socket) {}
[email protected]a2798d92011-03-02 22:56:18462
Gabriel Charette19d2ae62018-04-10 14:10:58463 // MessagePumpForIO::FdWatcher methods
[email protected]a2798d92011-03-02 22:56:18464
dchengb03027d2014-10-21 12:00:20465 void OnFileCanReadWithoutBlocking(int /* fd */) override {}
[email protected]a2798d92011-03-02 22:56:18466
dchengb03027d2014-10-21 12:00:20467 void OnFileCanWriteWithoutBlocking(int /* fd */) override;
[email protected]a2798d92011-03-02 22:56:18468
469 private:
tfarina4eb7aad82015-09-14 17:10:34470 UDPSocketPosix* const socket_;
[email protected]a2798d92011-03-02 22:56:18471
472 DISALLOW_COPY_AND_ASSIGN(WriteWatcher);
473 };
474
Brad Lassey3a814172018-04-26 03:30:21475 int InternalWriteAsync(CompletionOnceCallback callback,
Charles 'Buck' Krasic762317f2018-03-30 20:08:09476 const NetworkTrafficAnnotationTag& traffic_annotation);
477 bool WatchFileDescriptor();
478 void StopWatchingFileDescriptor();
479
[email protected]a2798d92011-03-02 22:56:18480 void DoReadCallback(int rv);
481 void DoWriteCallback(int rv);
482 void DidCompleteRead();
483 void DidCompleteWrite();
484
[email protected]8866f622011-10-18 20:08:10485 // Handles stats and logging. |result| is the number of bytes transferred, on
486 // success, or the net error code on failure. On success, LogRead takes in a
487 // sockaddr and its length, which are mandatory, while LogWrite takes in an
488 // optional IPEndPoint.
Charles 'Buck' Krasice70ff452017-08-14 22:11:44489 void LogRead(int result,
490 const char* bytes,
491 socklen_t addr_len,
492 const sockaddr* addr);
493 void LogWrite(int result, const char* bytes, const IPEndPoint* address);
[email protected]8866f622011-10-18 20:08:10494
[email protected]06043ae2011-03-16 00:00:21495 // Same as SendTo(), except that address is passed by pointer
496 // instead of by reference. It is called from Write() with |address|
Bartek Nowierski3253b672020-06-01 20:37:12497 // set to nullptr.
[email protected]06043ae2011-03-16 00:00:21498 int SendToOrWrite(IOBuffer* buf,
499 int buf_len,
500 const IPEndPoint* address,
Brad Lassey3a814172018-04-26 03:30:21501 CompletionOnceCallback callback);
[email protected]06043ae2011-03-16 00:00:21502
[email protected]8866f622011-10-18 20:08:10503 int InternalConnect(const IPEndPoint& address);
kapishnikov7f8dd1e2018-01-24 06:10:49504
505 // Reads data from a UDP socket. Depending whether the socket is connected or
506 // not, the method delegates the call to InternalRecvFromConnectedSocket()
507 // or InternalRecvFromNonConnectedSocket() respectively.
508 // For proper detection of truncated reads, the |buf_len| should always be
509 // one byte longer than the expected maximum packet length.
[email protected]06043ae2011-03-16 00:00:21510 int InternalRecvFrom(IOBuffer* buf, int buf_len, IPEndPoint* address);
kapishnikov7f8dd1e2018-01-24 06:10:49511
512 // A more efficient implementation of the InternalRecvFrom() method for
513 // reading data from connected sockets. Internally the method uses the read()
514 // system call.
515 int InternalRecvFromConnectedSocket(IOBuffer* buf,
516 int buf_len,
517 IPEndPoint* address);
518
519 // An implementation of the InternalRecvFrom() method for reading data
520 // from non-connected sockets. Internally the method uses the recvmsg()
521 // system call.
522 int InternalRecvFromNonConnectedSocket(IOBuffer* buf,
523 int buf_len,
524 IPEndPoint* address);
[email protected]06043ae2011-03-16 00:00:21525 int InternalSendTo(IOBuffer* buf, int buf_len, const IPEndPoint* address);
[email protected]a2798d92011-03-02 22:56:18526
[email protected]a1781d7b2012-07-16 11:52:34527 // Applies |socket_options_| to |socket_|. Should be called before
528 // Bind().
hidehiko17fac552014-12-08 06:02:17529 int SetMulticastOptions();
[email protected]5370c012011-06-29 03:47:04530 int DoBind(const IPEndPoint& address);
[email protected]acfe8e82013-12-12 14:12:56531 // Binds to a random port on |address|.
martijnd8dafab2016-03-14 18:28:49532 int RandomBind(const IPAddress& address);
[email protected]5370c012011-06-29 03:47:04533
Charles 'Buck' Krasic762317f2018-03-30 20:08:09534 // Helpers for |WriteAsync|
535 base::SequencedTaskRunner* GetTaskRunner();
536 void OnWriteAsyncTimerFired();
537 void LocalSendBuffers();
538 void PostSendBuffers();
539 int ResetLastAsyncResult();
540 int ResetWrittenBytes();
541
[email protected]a2798d92011-03-02 22:56:18542 int socket_;
sergeyu30ad5b32015-03-27 20:31:02543
Zhongyi Shi351b5442018-11-27 16:24:17544 // Hash of |socket_| to verify that it is not corrupted when calling close().
545 // Used to debug https://crbug.com/906005.
546 // TODO(crbug.com/906005): Remove this once the bug is fixed.
547 int socket_hash_;
548
[email protected]5f01ce22013-04-30 00:53:18549 int addr_family_;
hidehiko17fac552014-12-08 06:02:17550 bool is_connected_;
[email protected]a2798d92011-03-02 22:56:18551
[email protected]7be809df2012-08-07 17:00:48552 // Bitwise-or'd combination of SocketOptions. Specifies the set of
553 // options that should be applied to |socket_| before Bind().
[email protected]a1781d7b2012-07-16 11:52:34554 int socket_options_;
555
Yixin Wang3ae76ca2018-03-15 17:18:52556 // Flags passed to sendto().
557 int sendto_flags_;
558
[email protected]7b29dac2013-12-05 11:19:42559 // Multicast interface.
tfarinac40df1c2015-11-30 22:31:47560 uint32_t multicast_interface_;
[email protected]7b29dac2013-12-05 11:19:42561
hidehiko17fac552014-12-08 06:02:17562 // Multicast socket options cached for SetMulticastOption.
[email protected]5f01ce22013-04-30 00:53:18563 // Cannot be used after Bind().
564 int multicast_time_to_live_;
565
[email protected]5370c012011-06-29 03:47:04566 // How to do source port binding, used only when UDPSocket is part of
567 // UDPClientSocket, since UDPServerSocket provides Bind.
568 DatagramSocket::BindType bind_type_;
569
[email protected]a2798d92011-03-02 22:56:18570 // These are mutable since they're just cached copies to make
571 // GetPeerAddress/GetLocalAddress smarter.
danakja9850e12016-04-18 22:28:08572 mutable std::unique_ptr<IPEndPoint> local_address_;
573 mutable std::unique_ptr<IPEndPoint> remote_address_;
[email protected]a2798d92011-03-02 22:56:18574
tfarina4eb7aad82015-09-14 17:10:34575 // The socket's posix wrappers
Gabriel Charette19d2ae62018-04-10 14:10:58576 base::MessagePumpForIO::FdWatchController read_socket_watcher_;
577 base::MessagePumpForIO::FdWatchController write_socket_watcher_;
[email protected]a2798d92011-03-02 22:56:18578
579 // The corresponding watchers for reads and writes.
580 ReadWatcher read_watcher_;
581 WriteWatcher write_watcher_;
582
Charles 'Buck' Krasic762317f2018-03-30 20:08:09583 // Various bits to support |WriteAsync()|.
584 bool write_async_enabled_ = false;
585 bool write_batching_active_ = false;
586 bool write_multi_core_enabled_ = false;
587 int write_async_max_buffers_ = 16;
588 int written_bytes_ = 0;
589
590 int last_async_result_;
591 base::RepeatingTimer write_async_timer_;
592 bool write_async_timer_running_;
593 // Total writes in flight, including those |PostTask*|'d.
594 int write_async_outstanding_;
595
596 scoped_refptr<base::SequencedTaskRunner> task_runner_;
597
[email protected]43d4a0262011-03-09 19:26:04598 // The buffer used by InternalRead() to retry Read requests
[email protected]a2798d92011-03-02 22:56:18599 scoped_refptr<IOBuffer> read_buf_;
600 int read_buf_len_;
[email protected]43d4a0262011-03-09 19:26:04601 IPEndPoint* recv_from_address_;
[email protected]a2798d92011-03-02 22:56:18602
[email protected]43d4a0262011-03-09 19:26:04603 // The buffer used by InternalWrite() to retry Write requests
[email protected]a2798d92011-03-02 22:56:18604 scoped_refptr<IOBuffer> write_buf_;
605 int write_buf_len_;
danakja9850e12016-04-18 22:28:08606 std::unique_ptr<IPEndPoint> send_to_address_;
[email protected]a2798d92011-03-02 22:56:18607
608 // External callback; called when read is complete.
Brad Lassey3a814172018-04-26 03:30:21609 CompletionOnceCallback read_callback_;
[email protected]a2798d92011-03-02 22:56:18610
611 // External callback; called when write is complete.
Brad Lassey3a814172018-04-26 03:30:21612 CompletionOnceCallback write_callback_;
[email protected]a2798d92011-03-02 22:56:18613
tfarina42834112016-09-22 13:38:20614 NetLogWithSource net_log_;
[email protected]a2798d92011-03-02 22:56:18615
pauljensenf0d9535a2016-06-10 19:51:19616 // Network that this socket is bound to via BindToNetwork().
617 NetworkChangeNotifier::NetworkHandle bound_network_;
618
Charles 'Buck' Krasice70ff452017-08-14 22:11:44619 // These are used to lower the overhead updating activity monitor.
620 SentActivityMonitor sent_activity_monitor_;
621 ReceivedActivityMonitor received_activity_monitor_;
622
Paul Jensen0f49dec2017-12-12 23:39:58623 // Current socket tag if |socket_| is valid, otherwise the tag to apply when
624 // |socket_| is opened.
625 SocketTag tag_;
626
kapishnikov7f8dd1e2018-01-24 06:10:49627 // If set to true, the socket will use an optimized experimental code path.
628 // By default, the value is set to false. To use the optimization, the
629 // client of the socket has to opt-in by calling the
630 // enable_experimental_recv_optimization() method.
631 bool experimental_recv_optimization_enabled_;
632
gabd43afa12017-05-30 18:26:24633 THREAD_CHECKER(thread_checker_);
634
Charles 'Buck' Krasic762317f2018-03-30 20:08:09635 // Used for alternate writes that are posted for concurrent execution.
Jeremy Romand54000b22019-07-08 18:40:16636 base::WeakPtrFactory<UDPSocketPosix> weak_factory_{this};
Charles 'Buck' Krasic762317f2018-03-30 20:08:09637
tfarina4eb7aad82015-09-14 17:10:34638 DISALLOW_COPY_AND_ASSIGN(UDPSocketPosix);
[email protected]a2798d92011-03-02 22:56:18639};
640
641} // namespace net
642
tfarina5dd13c22016-11-16 12:08:26643#endif // NET_SOCKET_UDP_SOCKET_POSIX_H_