blob: 9bd2e6d0cb0130b8eebbe2e87da85452d3de3a08 [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"
Keishi Hattori0e45c022021-11-27 09:25:5215#include "base/memory/raw_ptr.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"
Eric Roman5a841922020-08-13 01:28:2533#include "net/socket/udp_socket_global_limits.h"
[email protected]a2b2cfc2017-12-06 09:06:0834#include "net/traffic_annotation/network_traffic_annotation.h"
[email protected]a2798d92011-03-02 22:56:1835
Charles 'Buck' Krasic762317f2018-03-30 20:08:0936#if defined(__ANDROID__) && defined(__aarch64__)
37#define HAVE_SENDMMSG 1
Xiaohan Wang2a6845b2022-01-08 04:40:5738#elif BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
Charles 'Buck' Krasic762317f2018-03-30 20:08:0939#define HAVE_SENDMMSG 1
40#else
41#define HAVE_SENDMMSG 0
42#endif
43
[email protected]a2798d92011-03-02 22:56:1844namespace net {
45
martijnd8dafab2016-03-14 18:28:4946class IPAddress;
mikecironef22f9812016-10-04 03:40:1947class NetLog;
48struct NetLogSource;
Paul Jensen0f49dec2017-12-12 23:39:5849class SocketTag;
martijnd8dafab2016-03-14 18:28:4950
Charles 'Buck' Krasic762317f2018-03-30 20:08:0951// Sendresult is inspired by sendmmsg, but unlike sendmmsg it is not
52// convenient to require that a positive |write_count| and a negative
53// error code are mutually exclusive.
54struct NET_EXPORT SendResult {
55 explicit SendResult();
56 ~SendResult();
57 SendResult(int rv, int write_count, DatagramBuffers buffers);
58 SendResult(SendResult& other) = delete;
59 SendResult& operator=(SendResult& other) = delete;
60 SendResult(SendResult&& other);
61 SendResult& operator=(SendResult&& other) = default;
62 int rv;
63 // number of successful writes.
64 int write_count;
65 DatagramBuffers buffers;
66};
67
68// Don't delay writes more than this.
Peter Kastinge5a38ed2021-10-02 03:06:3569const base::TimeDelta kWriteAsyncMsThreshold = base::Milliseconds(1);
Charles 'Buck' Krasic762317f2018-03-30 20:08:0970// 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:
Francois Doray32ad3672021-04-15 15:37:39123 // Performance helper for net::activity_monitor, it batches
Charles 'Buck' Krasice70ff452017-08-14 22:11:44124 // 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.
Francois Doray5146d2f02021-03-30 18:11:57128 class ReceivedActivityMonitor {
Charles 'Buck' Krasice70ff452017-08-14 22:11:44129 public:
Francois Doray5146d2f02021-03-30 18:11:57130 ReceivedActivityMonitor() : bytes_(0), increments_(0) {}
Peter Boström293b1342021-09-22 17:31:43131
132 ReceivedActivityMonitor(const ReceivedActivityMonitor&) = delete;
133 ReceivedActivityMonitor& operator=(const ReceivedActivityMonitor&) = delete;
134
Francois Doray5146d2f02021-03-30 18:11:57135 ~ReceivedActivityMonitor() = default;
Charles 'Buck' Krasice70ff452017-08-14 22:11:44136 // Provided by sent/received subclass.
Francois Doray32ad3672021-04-15 15:37:39137 // Update throughput, but batch to limit overhead of net::activity_monitor.
Charles 'Buck' Krasice70ff452017-08-14 22:11:44138 void Increment(uint32_t bytes);
139 // For flushing cached values.
140 void OnClose();
141
142 private:
Charles 'Buck' Krasice70ff452017-08-14 22:11:44143 void Update();
144 void OnTimerFired();
145
146 uint32_t bytes_;
147 uint32_t increments_;
148 base::RepeatingTimer timer_;
Charles 'Buck' Krasice70ff452017-08-14 22:11:44149 };
150
tfarina4eb7aad82015-09-14 17:10:34151 UDPSocketPosix(DatagramSocket::BindType bind_type,
tfarina4eb7aad82015-09-14 17:10:34152 net::NetLog* net_log,
mikecironef22f9812016-10-04 03:40:19153 const net::NetLogSource& source);
Peter Boström407869b2021-10-07 04:42:48154
155 UDPSocketPosix(const UDPSocketPosix&) = delete;
156 UDPSocketPosix& operator=(const UDPSocketPosix&) = delete;
157
tfarina4eb7aad82015-09-14 17:10:34158 virtual ~UDPSocketPosix();
[email protected]a2798d92011-03-02 22:56:18159
hidehiko17fac552014-12-08 06:02:17160 // Opens the socket.
161 // Returns a net error code.
162 int Open(AddressFamily address_family);
163
pauljensenbe5bc3232015-10-05 20:39:27164 // Binds this socket to |network|. All data traffic on the socket will be sent
165 // and received via |network|. Must be called before Connect(). This call will
166 // fail if |network| has disconnected. Communication using this socket will
167 // fail if |network| disconnects.
168 // Returns a net error code.
169 int BindToNetwork(NetworkChangeNotifier::NetworkHandle network);
170
hidehiko17fac552014-12-08 06:02:17171 // Connects the socket to connect with a certain |address|.
172 // Should be called after Open().
[email protected]a2798d92011-03-02 22:56:18173 // Returns a net error code.
[email protected]43d4a0262011-03-09 19:26:04174 int Connect(const IPEndPoint& address);
[email protected]a2798d92011-03-02 22:56:18175
hidehiko17fac552014-12-08 06:02:17176 // Binds the address/port for this socket to |address|. This is generally
177 // only used on a server. Should be called after Open().
[email protected]a2798d92011-03-02 22:56:18178 // Returns a net error code.
[email protected]43d4a0262011-03-09 19:26:04179 int Bind(const IPEndPoint& address);
[email protected]a2798d92011-03-02 22:56:18180
hidehiko17fac552014-12-08 06:02:17181 // Closes the socket.
182 // TODO(rvargas, hidehiko): Disallow re-Open() after Close().
[email protected]a2798d92011-03-02 22:56:18183 void Close();
184
hidehiko17fac552014-12-08 06:02:17185 // Copies the remote udp address into |address| and returns a net error code.
[email protected]43d4a0262011-03-09 19:26:04186 int GetPeerAddress(IPEndPoint* address) const;
[email protected]a2798d92011-03-02 22:56:18187
hidehiko17fac552014-12-08 06:02:17188 // Copies the local udp address into |address| and returns a net error code.
[email protected]a2798d92011-03-02 22:56:18189 // (similar to getsockname)
[email protected]43d4a0262011-03-09 19:26:04190 int GetLocalAddress(IPEndPoint* address) const;
[email protected]a2798d92011-03-02 22:56:18191
192 // IO:
193 // Multiple outstanding read requests are not supported.
194 // Full duplex mode (reading and writing at the same time) is supported
195
hidehiko17fac552014-12-08 06:02:17196 // Reads from the socket.
[email protected]a2798d92011-03-02 22:56:18197 // Only usable from the client-side of a UDP socket, after the socket
198 // has been connected.
Brad Lassey3a814172018-04-26 03:30:21199 int Read(IOBuffer* buf, int buf_len, CompletionOnceCallback callback);
[email protected]a2798d92011-03-02 22:56:18200
hidehiko17fac552014-12-08 06:02:17201 // Writes to the socket.
[email protected]a2798d92011-03-02 22:56:18202 // Only usable from the client-side of a UDP socket, after the socket
203 // has been connected.
[email protected]a2b2cfc2017-12-06 09:06:08204 int Write(IOBuffer* buf,
205 int buf_len,
Brad Lassey3a814172018-04-26 03:30:21206 CompletionOnceCallback callback,
[email protected]cda4b7b2017-12-20 06:04:43207 const NetworkTrafficAnnotationTag& traffic_annotation);
[email protected]a2798d92011-03-02 22:56:18208
Charles 'Buck' Krasic762317f2018-03-30 20:08:09209 // Refer to datagram_client_socket.h
210 int WriteAsync(DatagramBuffers buffers,
Brad Lassey3a814172018-04-26 03:30:21211 CompletionOnceCallback callback,
Charles 'Buck' Krasic762317f2018-03-30 20:08:09212 const NetworkTrafficAnnotationTag& traffic_annotation);
213 int WriteAsync(const char* buffer,
214 size_t buf_len,
Brad Lassey3a814172018-04-26 03:30:21215 CompletionOnceCallback callback,
Charles 'Buck' Krasic762317f2018-03-30 20:08:09216 const NetworkTrafficAnnotationTag& traffic_annotation);
217
218 DatagramBuffers GetUnwrittenBuffers();
219
hidehiko17fac552014-12-08 06:02:17220 // Reads from a socket and receive sender address information.
[email protected]a2798d92011-03-02 22:56:18221 // |buf| is the buffer to read data into.
222 // |buf_len| is the maximum amount of data to read.
223 // |address| is a buffer provided by the caller for receiving the sender
224 // address information about the received data. This buffer must be kept
225 // alive by the caller until the callback is placed.
[email protected]73c5b692014-07-01 12:43:41226 // |callback| is the callback on completion of the RecvFrom.
[email protected]a2798d92011-03-02 22:56:18227 // Returns a net error code, or ERR_IO_PENDING if the IO is in progress.
Matthew Denton111df5ad2018-10-19 20:39:25228 // If ERR_IO_PENDING is returned, this socket takes a ref to |buf| to keep
229 // it alive until the data is received. However, the caller must keep
230 // |address| alive until the callback is called.
[email protected]a2798d92011-03-02 22:56:18231 int RecvFrom(IOBuffer* buf,
232 int buf_len,
[email protected]43d4a0262011-03-09 19:26:04233 IPEndPoint* address,
Brad Lassey3a814172018-04-26 03:30:21234 CompletionOnceCallback callback);
[email protected]a2798d92011-03-02 22:56:18235
hidehiko17fac552014-12-08 06:02:17236 // Sends to a socket with a particular destination.
tfarina39524dd2016-02-19 10:52:10237 // |buf| is the buffer to send.
238 // |buf_len| is the number of bytes to send.
[email protected]a2798d92011-03-02 22:56:18239 // |address| is the recipient address.
[email protected]a2798d92011-03-02 22:56:18240 // |callback| is the user callback function to call on complete.
241 // Returns a net error code, or ERR_IO_PENDING if the IO is in progress.
Matthew Denton111df5ad2018-10-19 20:39:25242 // If ERR_IO_PENDING is returned, this socket copies |address| for
243 // asynchronous sending, and takes a ref to |buf| to keep it alive until the
244 // data is sent.
[email protected]a2798d92011-03-02 22:56:18245 int SendTo(IOBuffer* buf,
246 int buf_len,
[email protected]43d4a0262011-03-09 19:26:04247 const IPEndPoint& address,
Brad Lassey3a814172018-04-26 03:30:21248 CompletionOnceCallback callback);
[email protected]a2798d92011-03-02 22:56:18249
hidehiko17fac552014-12-08 06:02:17250 // Sets the receive buffer size (in bytes) for the socket.
251 // Returns a net error code.
tfarinac40df1c2015-11-30 22:31:47252 int SetReceiveBufferSize(int32_t size);
[email protected]df31da42011-10-18 01:44:40253
hidehiko17fac552014-12-08 06:02:17254 // Sets the send buffer size (in bytes) for the socket.
255 // Returns a net error code.
tfarinac40df1c2015-11-30 22:31:47256 int SetSendBufferSize(int32_t size);
[email protected]df31da42011-10-18 01:44:40257
rchff006a12016-08-24 23:56:31258 // Requests that packets sent by this socket not be fragment, either locally
259 // by the host, or by routers (via the DF bit in the IPv4 packet header).
Momoka Yamamoto3f916b82022-02-10 18:26:52260 // May not be supported by all platforms. Returns a network error code if
261 // there was a problem, but the socket will still be usable. Can not
rchff006a12016-08-24 23:56:31262 // return ERR_IO_PENDING.
263 int SetDoNotFragment();
264
Yixin Wang3ae76ca2018-03-15 17:18:52265 // If |confirm| is true, then the MSG_CONFIRM flag will be passed to
266 // subsequent writes if it's supported by the platform.
267 void SetMsgConfirm(bool confirm);
268
[email protected]a2798d92011-03-02 22:56:18269 // Returns true if the socket is already connected or bound.
hidehiko17fac552014-12-08 06:02:17270 bool is_connected() const { return is_connected_; }
[email protected]a2798d92011-03-02 22:56:18271
tfarina42834112016-09-22 13:38:20272 const NetLogWithSource& NetLog() const { return net_log_; }
[email protected]eaf10dc2011-07-18 21:47:35273
tfarina6f2f3beb2017-04-19 11:53:14274 // Call this to enable SO_REUSEADDR on the underlying socket.
275 // Should be called between Open() and Bind().
hidehiko17fac552014-12-08 06:02:17276 // Returns a net error code.
277 int AllowAddressReuse();
[email protected]a1781d7b2012-07-16 11:52:34278
tfarina6f2f3beb2017-04-19 11:53:14279 // Call this to allow or disallow sending and receiving packets to and from
280 // broadcast addresses.
hidehiko17fac552014-12-08 06:02:17281 // Returns a net error code.
282 int SetBroadcast(bool broadcast);
[email protected]a1781d7b2012-07-16 11:52:34283
Eric Orth7141dbc2018-10-26 20:10:24284 // Sets socket options to allow the socket to share the local address to which
285 // the socket will be bound with other processes and attempt to allow all such
286 // sockets to receive the same multicast messages. Returns a net error code.
287 //
288 // Ability and requirements for different sockets to receive the same messages
289 // varies between POSIX platforms. For best results in allowing the messages
290 // to be shared, all sockets sharing the same address should join the same
291 // multicast group and interface. Also, the socket should listen to the
292 // specific multicast address rather than a wildcard address (e.g. 0.0.0.0).
293 //
294 // Should be called between Open() and Bind().
295 int AllowAddressSharingForMulticast();
296
hidehiko17fac552014-12-08 06:02:17297 // Joins the multicast group.
[email protected]5f01ce22013-04-30 00:53:18298 // |group_address| is the group address to join, could be either
299 // an IPv4 or IPv6 address.
hidehiko17fac552014-12-08 06:02:17300 // Returns a net error code.
martijnd8dafab2016-03-14 18:28:49301 int JoinGroup(const IPAddress& group_address) const;
[email protected]5f01ce22013-04-30 00:53:18302
hidehiko17fac552014-12-08 06:02:17303 // Leaves the multicast group.
[email protected]5f01ce22013-04-30 00:53:18304 // |group_address| is the group address to leave, could be either
305 // an IPv4 or IPv6 address. If the socket hasn't joined the group,
306 // it will be ignored.
307 // It's optional to leave the multicast group before destroying
308 // the socket. It will be done by the OS.
hidehiko17fac552014-12-08 06:02:17309 // Returns a net error code.
martijnd8dafab2016-03-14 18:28:49310 int LeaveGroup(const IPAddress& group_address) const;
[email protected]5f01ce22013-04-30 00:53:18311
hidehiko17fac552014-12-08 06:02:17312 // Sets interface to use for multicast. If |interface_index| set to 0,
313 // default interface is used.
[email protected]7b29dac2013-12-05 11:19:42314 // Should be called before Bind().
hidehiko17fac552014-12-08 06:02:17315 // Returns a net error code.
tfarinac40df1c2015-11-30 22:31:47316 int SetMulticastInterface(uint32_t interface_index);
[email protected]7b29dac2013-12-05 11:19:42317
hidehiko17fac552014-12-08 06:02:17318 // Sets the time-to-live option for UDP packets sent to the multicast
[email protected]5f01ce22013-04-30 00:53:18319 // group address. The default value of this option is 1.
320 // Cannot be negative or more than 255.
321 // Should be called before Bind().
hidehiko17fac552014-12-08 06:02:17322 // Returns a net error code.
[email protected]5f01ce22013-04-30 00:53:18323 int SetMulticastTimeToLive(int time_to_live);
324
hidehiko17fac552014-12-08 06:02:17325 // Sets the loopback flag for UDP socket. If this flag is true, the host
[email protected]5f01ce22013-04-30 00:53:18326 // will receive packets sent to the joined group from itself.
327 // The default value of this option is true.
328 // Should be called before Bind().
hidehiko17fac552014-12-08 06:02:17329 // Returns a net error code.
[email protected]5f01ce22013-04-30 00:53:18330 //
331 // Note: the behavior of |SetMulticastLoopbackMode| is slightly
332 // different between Windows and Unix-like systems. The inconsistency only
333 // happens when there are more than one applications on the same host
334 // joined to the same multicast group while having different settings on
335 // multicast loopback mode. On Windows, the applications with loopback off
336 // will not RECEIVE the loopback packets; while on Unix-like systems, the
337 // applications with loopback off will not SEND the loopback packets to
338 // other applications on the same host. See MSDN: http://goo.gl/6vqbj
339 int SetMulticastLoopbackMode(bool loopback);
340
hidehiko17fac552014-12-08 06:02:17341 // Sets the differentiated services flags on outgoing packets. May not
[email protected]a8a442b32013-10-22 00:34:41342 // do anything on some platforms.
hidehiko17fac552014-12-08 06:02:17343 // Returns a net error code.
[email protected]a8a442b32013-10-22 00:34:41344 int SetDiffServCodePoint(DiffServCodePoint dscp);
345
Stefano Duo157e10c22022-01-25 12:58:34346 // Exposes the underlying socket descriptor for testing its state. Does not
347 // release ownership of the descriptor.
348 SocketDescriptor SocketDescriptorForTesting() const { return socket_; }
349
[email protected]1901dbcb2014-03-10 07:18:37350 // Resets the thread to be used for thread-safety checks.
351 void DetachFromThread();
352
Paul Jensen0f49dec2017-12-12 23:39:58353 // Apply |tag| to this socket.
354 void ApplySocketTag(const SocketTag& tag);
355
Charles 'Buck' Krasic762317f2018-03-30 20:08:09356 void SetWriteAsyncEnabled(bool enabled) { write_async_enabled_ = enabled; }
357 bool WriteAsyncEnabled() { return write_async_enabled_; }
358
359 void SetMaxPacketSize(size_t max_packet_size);
360
361 void SetWriteMultiCoreEnabled(bool enabled) {
362 write_multi_core_enabled_ = enabled;
363 }
364
365 void SetSendmmsgEnabled(bool enabled) {
366 DCHECK(sender_ != nullptr);
367 sender_->SetSendmmsgEnabled(enabled);
368 }
369
370 void SetWriteBatchingActive(bool active) { write_batching_active_ = active; }
371
372 void SetWriteAsyncMaxBuffers(int value) {
373 LOG(INFO) << "SetWriteAsyncMaxBuffers: " << value;
374 write_async_max_buffers_ = value;
375 }
376
kapishnikov7f8dd1e2018-01-24 06:10:49377 // Enables experimental optimization. This method should be called
378 // before the socket is used to read data for the first time.
379 void enable_experimental_recv_optimization() {
380 DCHECK_EQ(kInvalidSocket, socket_);
381 experimental_recv_optimization_enabled_ = true;
Eric Orth7141dbc2018-10-26 20:10:24382 }
kapishnikov7f8dd1e2018-01-24 06:10:49383
Yu Suca37f3c2020-10-09 20:02:23384 // Sets iOS Network Service Type for option SO_NET_SERVICE_TYPE.
385 int SetIOSNetworkServiceType(int ios_network_service_type);
386
Charles 'Buck' Krasic762317f2018-03-30 20:08:09387 protected:
388 // WriteAsync batching etc. are to improve throughput of large high
389 // bandwidth uploads.
390
391 // Watcher for WriteAsync paths.
Gabriel Charette19d2ae62018-04-10 14:10:58392 class WriteAsyncWatcher : public base::MessagePumpForIO::FdWatcher {
Charles 'Buck' Krasic762317f2018-03-30 20:08:09393 public:
394 explicit WriteAsyncWatcher(UDPSocketPosix* socket)
395 : socket_(socket), watching_(false) {}
396
Peter Boström407869b2021-10-07 04:42:48397 WriteAsyncWatcher(const WriteAsyncWatcher&) = delete;
398 WriteAsyncWatcher& operator=(const WriteAsyncWatcher&) = delete;
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:
Keishi Hattori0e45c022021-11-27 09:25:52411 const raw_ptr<UDPSocketPosix> socket_;
Charles 'Buck' Krasic762317f2018-03-30 20:08:09412 bool watching_;
Charles 'Buck' Krasic762317f2018-03-30 20:08:09413 };
414
415 void IncreaseWriteAsyncOutstanding(int increment) {
416 write_async_outstanding_ += increment;
417 }
418
419 virtual bool InternalWatchFileDescriptor();
420 virtual void InternalStopWatchingFileDescriptor();
421
Brad Lassey3a814172018-04-26 03:30:21422 void SetWriteCallback(CompletionOnceCallback callback) {
Charles 'Buck' Krasic762317f2018-03-30 20:08:09423 write_callback_ = std::move(callback);
424 }
425
426 void DidSendBuffers(SendResult buffers);
427 void FlushPending();
428
429 std::unique_ptr<WriteAsyncWatcher> write_async_watcher_;
430 scoped_refptr<UDPSocketPosixSender> sender_;
431 std::unique_ptr<DatagramBufferPool> datagram_buffer_pool_;
432 // |WriteAsync| pending writes, does not include buffers that have
433 // been |PostTask*|'d.
434 DatagramBuffers pending_writes_;
435
[email protected]a2798d92011-03-02 22:56:18436 private:
[email protected]a1781d7b2012-07-16 11:52:34437 enum SocketOptions {
hidehiko17fac552014-12-08 06:02:17438 SOCKET_OPTION_MULTICAST_LOOP = 1 << 0
[email protected]a1781d7b2012-07-16 11:52:34439 };
440
Gabriel Charette19d2ae62018-04-10 14:10:58441 class ReadWatcher : public base::MessagePumpForIO::FdWatcher {
[email protected]a2798d92011-03-02 22:56:18442 public:
tfarina4eb7aad82015-09-14 17:10:34443 explicit ReadWatcher(UDPSocketPosix* socket) : socket_(socket) {}
[email protected]a2798d92011-03-02 22:56:18444
Peter Boström407869b2021-10-07 04:42:48445 ReadWatcher(const ReadWatcher&) = delete;
446 ReadWatcher& operator=(const ReadWatcher&) = delete;
447
Gabriel Charette19d2ae62018-04-10 14:10:58448 // MessagePumpForIO::FdWatcher methods
[email protected]a2798d92011-03-02 22:56:18449
dchengb03027d2014-10-21 12:00:20450 void OnFileCanReadWithoutBlocking(int /* fd */) override;
[email protected]a2798d92011-03-02 22:56:18451
dchengb03027d2014-10-21 12:00:20452 void OnFileCanWriteWithoutBlocking(int /* fd */) override {}
[email protected]a2798d92011-03-02 22:56:18453
454 private:
Keishi Hattori0e45c022021-11-27 09:25:52455 const raw_ptr<UDPSocketPosix> socket_;
[email protected]a2798d92011-03-02 22:56:18456 };
457
Gabriel Charette19d2ae62018-04-10 14:10:58458 class WriteWatcher : public base::MessagePumpForIO::FdWatcher {
[email protected]a2798d92011-03-02 22:56:18459 public:
tfarina4eb7aad82015-09-14 17:10:34460 explicit WriteWatcher(UDPSocketPosix* socket) : socket_(socket) {}
[email protected]a2798d92011-03-02 22:56:18461
Peter Boström407869b2021-10-07 04:42:48462 WriteWatcher(const WriteWatcher&) = delete;
463 WriteWatcher& operator=(const WriteWatcher&) = delete;
464
Gabriel Charette19d2ae62018-04-10 14:10:58465 // MessagePumpForIO::FdWatcher methods
[email protected]a2798d92011-03-02 22:56:18466
dchengb03027d2014-10-21 12:00:20467 void OnFileCanReadWithoutBlocking(int /* fd */) override {}
[email protected]a2798d92011-03-02 22:56:18468
dchengb03027d2014-10-21 12:00:20469 void OnFileCanWriteWithoutBlocking(int /* fd */) override;
[email protected]a2798d92011-03-02 22:56:18470
471 private:
Keishi Hattori0e45c022021-11-27 09:25:52472 const raw_ptr<UDPSocketPosix> socket_;
[email protected]a2798d92011-03-02 22:56:18473 };
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_;
Keishi Hattori0e45c022021-11-27 09:25:52601 raw_ptr<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
Francois Doray32ad3672021-04-15 15:37:39619 // Whether net::activity_monitor should be updated every time bytes are
620 // received, without batching through |received_activity_monitor_|. This is
621 // initialized with the state of the "UdpSocketPosixAlwaysUpdateBytesReceived"
622 // feature. It is cached to avoid accessing the FeatureList every time bytes
623 // are received.
624 const bool always_update_bytes_received_;
625
Francois Doray5146d2f02021-03-30 18:11:57626 // Used to lower the overhead updating activity monitor.
Charles 'Buck' Krasice70ff452017-08-14 22:11:44627 ReceivedActivityMonitor received_activity_monitor_;
628
Paul Jensen0f49dec2017-12-12 23:39:58629 // Current socket tag if |socket_| is valid, otherwise the tag to apply when
630 // |socket_| is opened.
631 SocketTag tag_;
632
kapishnikov7f8dd1e2018-01-24 06:10:49633 // If set to true, the socket will use an optimized experimental code path.
634 // By default, the value is set to false. To use the optimization, the
635 // client of the socket has to opt-in by calling the
636 // enable_experimental_recv_optimization() method.
637 bool experimental_recv_optimization_enabled_;
638
Eric Roman5a841922020-08-13 01:28:25639 // Manages decrementing the global open UDP socket counter when this
640 // UDPSocket is destroyed.
641 OwnedUDPSocketCount owned_socket_count_;
642
gabd43afa12017-05-30 18:26:24643 THREAD_CHECKER(thread_checker_);
644
Charles 'Buck' Krasic762317f2018-03-30 20:08:09645 // Used for alternate writes that are posted for concurrent execution.
Jeremy Romand54000b22019-07-08 18:40:16646 base::WeakPtrFactory<UDPSocketPosix> weak_factory_{this};
[email protected]a2798d92011-03-02 22:56:18647};
648
649} // namespace net
650
tfarina5dd13c22016-11-16 12:08:26651#endif // NET_SOCKET_UDP_SOCKET_POSIX_H_