blob: 351c3057d8ef4dc3c994683306fa59d108e31672 [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
Tsuyoshi Horo2ec06e002022-06-09 01:38:5987 UDPSocketPosixSender(const UDPSocketPosixSender&) = delete;
88 UDPSocketPosixSender& operator=(const UDPSocketPosixSender&) = delete;
89
Charles 'Buck' Krasic762317f2018-03-30 20:08:0990 SendResult SendBuffers(int fd, DatagramBuffers buffers);
91
92 void SetSendmmsgEnabled(bool enabled) {
93#if HAVE_SENDMMSG
94 sendmmsg_enabled_ = enabled;
95#endif
96 }
97
98 protected:
99 friend class base::RefCountedThreadSafe<UDPSocketPosixSender>;
100
101 virtual ~UDPSocketPosixSender();
102 virtual ssize_t Send(int sockfd,
103 const void* buf,
104 size_t len,
105 int flags) const;
106#if HAVE_SENDMMSG
107 virtual int Sendmmsg(int sockfd,
108 struct mmsghdr* msgvec,
109 unsigned int vlen,
110 unsigned int flags) const;
111#endif
112
113 SendResult InternalSendBuffers(int fd, DatagramBuffers buffers) const;
114#if HAVE_SENDMMSG
115 SendResult InternalSendmmsgBuffers(int fd, DatagramBuffers buffers) const;
116#endif
117
118 private:
Tsuyoshi Horo2ec06e002022-06-09 01:38:59119 bool sendmmsg_enabled_ = false;
Charles 'Buck' Krasic762317f2018-03-30 20:08:09120};
121
gabd43afa12017-05-30 18:26:24122class NET_EXPORT UDPSocketPosix {
[email protected]a2798d92011-03-02 22:56:18123 public:
Francois Doray32ad3672021-04-15 15:37:39124 // Performance helper for net::activity_monitor, it batches
Charles 'Buck' Krasice70ff452017-08-14 22:11:44125 // throughput samples, subject to a byte limit threshold (64 KB) or
126 // timer (100 ms), whichever comes first. The batching is subject
127 // to a minimum number of samples (2) required by NQE to update its
128 // throughput estimate.
Francois Doray5146d2f02021-03-30 18:11:57129 class ReceivedActivityMonitor {
Charles 'Buck' Krasice70ff452017-08-14 22:11:44130 public:
Tsuyoshi Horo2ec06e002022-06-09 01:38:59131 ReceivedActivityMonitor() = default;
Peter Boström293b1342021-09-22 17:31:43132
133 ReceivedActivityMonitor(const ReceivedActivityMonitor&) = delete;
134 ReceivedActivityMonitor& operator=(const ReceivedActivityMonitor&) = delete;
135
Francois Doray5146d2f02021-03-30 18:11:57136 ~ReceivedActivityMonitor() = default;
Charles 'Buck' Krasice70ff452017-08-14 22:11:44137 // Provided by sent/received subclass.
Francois Doray32ad3672021-04-15 15:37:39138 // Update throughput, but batch to limit overhead of net::activity_monitor.
Charles 'Buck' Krasice70ff452017-08-14 22:11:44139 void Increment(uint32_t bytes);
140 // For flushing cached values.
141 void OnClose();
142
143 private:
Charles 'Buck' Krasice70ff452017-08-14 22:11:44144 void Update();
145 void OnTimerFired();
146
Tsuyoshi Horo2ec06e002022-06-09 01:38:59147 uint32_t bytes_ = 0;
148 uint32_t increments_ = 0;
Charles 'Buck' Krasice70ff452017-08-14 22:11:44149 base::RepeatingTimer timer_;
Charles 'Buck' Krasice70ff452017-08-14 22:11:44150 };
151
tfarina4eb7aad82015-09-14 17:10:34152 UDPSocketPosix(DatagramSocket::BindType bind_type,
tfarina4eb7aad82015-09-14 17:10:34153 net::NetLog* net_log,
mikecironef22f9812016-10-04 03:40:19154 const net::NetLogSource& source);
Peter Boström407869b2021-10-07 04:42:48155
156 UDPSocketPosix(const UDPSocketPosix&) = delete;
157 UDPSocketPosix& operator=(const UDPSocketPosix&) = delete;
158
tfarina4eb7aad82015-09-14 17:10:34159 virtual ~UDPSocketPosix();
[email protected]a2798d92011-03-02 22:56:18160
hidehiko17fac552014-12-08 06:02:17161 // Opens the socket.
162 // Returns a net error code.
163 int Open(AddressFamily address_family);
164
pauljensenbe5bc3232015-10-05 20:39:27165 // Binds this socket to |network|. All data traffic on the socket will be sent
166 // and received via |network|. Must be called before Connect(). This call will
167 // fail if |network| has disconnected. Communication using this socket will
168 // fail if |network| disconnects.
169 // Returns a net error code.
170 int BindToNetwork(NetworkChangeNotifier::NetworkHandle network);
171
hidehiko17fac552014-12-08 06:02:17172 // Connects the socket to connect with a certain |address|.
173 // Should be called after Open().
[email protected]a2798d92011-03-02 22:56:18174 // Returns a net error code.
[email protected]43d4a0262011-03-09 19:26:04175 int Connect(const IPEndPoint& address);
[email protected]a2798d92011-03-02 22:56:18176
hidehiko17fac552014-12-08 06:02:17177 // Binds the address/port for this socket to |address|. This is generally
178 // only used on a server. Should be called after Open().
[email protected]a2798d92011-03-02 22:56:18179 // Returns a net error code.
[email protected]43d4a0262011-03-09 19:26:04180 int Bind(const IPEndPoint& address);
[email protected]a2798d92011-03-02 22:56:18181
hidehiko17fac552014-12-08 06:02:17182 // Closes the socket.
183 // TODO(rvargas, hidehiko): Disallow re-Open() after Close().
[email protected]a2798d92011-03-02 22:56:18184 void Close();
185
hidehiko17fac552014-12-08 06:02:17186 // Copies the remote udp address into |address| and returns a net error code.
[email protected]43d4a0262011-03-09 19:26:04187 int GetPeerAddress(IPEndPoint* address) const;
[email protected]a2798d92011-03-02 22:56:18188
hidehiko17fac552014-12-08 06:02:17189 // Copies the local udp address into |address| and returns a net error code.
[email protected]a2798d92011-03-02 22:56:18190 // (similar to getsockname)
[email protected]43d4a0262011-03-09 19:26:04191 int GetLocalAddress(IPEndPoint* address) const;
[email protected]a2798d92011-03-02 22:56:18192
193 // IO:
194 // Multiple outstanding read requests are not supported.
195 // Full duplex mode (reading and writing at the same time) is supported
196
hidehiko17fac552014-12-08 06:02:17197 // Reads from the socket.
[email protected]a2798d92011-03-02 22:56:18198 // Only usable from the client-side of a UDP socket, after the socket
199 // has been connected.
Brad Lassey3a814172018-04-26 03:30:21200 int Read(IOBuffer* buf, int buf_len, CompletionOnceCallback callback);
[email protected]a2798d92011-03-02 22:56:18201
hidehiko17fac552014-12-08 06:02:17202 // Writes to the socket.
[email protected]a2798d92011-03-02 22:56:18203 // Only usable from the client-side of a UDP socket, after the socket
204 // has been connected.
[email protected]a2b2cfc2017-12-06 09:06:08205 int Write(IOBuffer* buf,
206 int buf_len,
Brad Lassey3a814172018-04-26 03:30:21207 CompletionOnceCallback callback,
[email protected]cda4b7b2017-12-20 06:04:43208 const NetworkTrafficAnnotationTag& traffic_annotation);
[email protected]a2798d92011-03-02 22:56:18209
Charles 'Buck' Krasic762317f2018-03-30 20:08:09210 // Refer to datagram_client_socket.h
211 int WriteAsync(DatagramBuffers buffers,
Brad Lassey3a814172018-04-26 03:30:21212 CompletionOnceCallback callback,
Charles 'Buck' Krasic762317f2018-03-30 20:08:09213 const NetworkTrafficAnnotationTag& traffic_annotation);
214 int WriteAsync(const char* buffer,
215 size_t buf_len,
Brad Lassey3a814172018-04-26 03:30:21216 CompletionOnceCallback callback,
Charles 'Buck' Krasic762317f2018-03-30 20:08:09217 const NetworkTrafficAnnotationTag& traffic_annotation);
218
219 DatagramBuffers GetUnwrittenBuffers();
220
hidehiko17fac552014-12-08 06:02:17221 // Reads from a socket and receive sender address information.
[email protected]a2798d92011-03-02 22:56:18222 // |buf| is the buffer to read data into.
223 // |buf_len| is the maximum amount of data to read.
224 // |address| is a buffer provided by the caller for receiving the sender
225 // address information about the received data. This buffer must be kept
226 // alive by the caller until the callback is placed.
[email protected]73c5b692014-07-01 12:43:41227 // |callback| is the callback on completion of the RecvFrom.
[email protected]a2798d92011-03-02 22:56:18228 // Returns a net error code, or ERR_IO_PENDING if the IO is in progress.
Matthew Denton111df5ad2018-10-19 20:39:25229 // If ERR_IO_PENDING is returned, this socket takes a ref to |buf| to keep
230 // it alive until the data is received. However, the caller must keep
231 // |address| alive until the callback is called.
[email protected]a2798d92011-03-02 22:56:18232 int RecvFrom(IOBuffer* buf,
233 int buf_len,
[email protected]43d4a0262011-03-09 19:26:04234 IPEndPoint* address,
Brad Lassey3a814172018-04-26 03:30:21235 CompletionOnceCallback callback);
[email protected]a2798d92011-03-02 22:56:18236
hidehiko17fac552014-12-08 06:02:17237 // Sends to a socket with a particular destination.
tfarina39524dd2016-02-19 10:52:10238 // |buf| is the buffer to send.
239 // |buf_len| is the number of bytes to send.
[email protected]a2798d92011-03-02 22:56:18240 // |address| is the recipient address.
[email protected]a2798d92011-03-02 22:56:18241 // |callback| is the user callback function to call on complete.
242 // Returns a net error code, or ERR_IO_PENDING if the IO is in progress.
Matthew Denton111df5ad2018-10-19 20:39:25243 // If ERR_IO_PENDING is returned, this socket copies |address| for
244 // asynchronous sending, and takes a ref to |buf| to keep it alive until the
245 // data is sent.
[email protected]a2798d92011-03-02 22:56:18246 int SendTo(IOBuffer* buf,
247 int buf_len,
[email protected]43d4a0262011-03-09 19:26:04248 const IPEndPoint& address,
Brad Lassey3a814172018-04-26 03:30:21249 CompletionOnceCallback callback);
[email protected]a2798d92011-03-02 22:56:18250
hidehiko17fac552014-12-08 06:02:17251 // Sets the receive buffer size (in bytes) for the socket.
252 // Returns a net error code.
tfarinac40df1c2015-11-30 22:31:47253 int SetReceiveBufferSize(int32_t size);
[email protected]df31da42011-10-18 01:44:40254
hidehiko17fac552014-12-08 06:02:17255 // Sets the send buffer size (in bytes) for the socket.
256 // Returns a net error code.
tfarinac40df1c2015-11-30 22:31:47257 int SetSendBufferSize(int32_t size);
[email protected]df31da42011-10-18 01:44:40258
rchff006a12016-08-24 23:56:31259 // Requests that packets sent by this socket not be fragment, either locally
260 // by the host, or by routers (via the DF bit in the IPv4 packet header).
Momoka Yamamoto3f916b82022-02-10 18:26:52261 // May not be supported by all platforms. Returns a network error code if
262 // there was a problem, but the socket will still be usable. Can not
rchff006a12016-08-24 23:56:31263 // return ERR_IO_PENDING.
264 int SetDoNotFragment();
265
Yixin Wang3ae76ca2018-03-15 17:18:52266 // If |confirm| is true, then the MSG_CONFIRM flag will be passed to
267 // subsequent writes if it's supported by the platform.
268 void SetMsgConfirm(bool confirm);
269
[email protected]a2798d92011-03-02 22:56:18270 // Returns true if the socket is already connected or bound.
hidehiko17fac552014-12-08 06:02:17271 bool is_connected() const { return is_connected_; }
[email protected]a2798d92011-03-02 22:56:18272
tfarina42834112016-09-22 13:38:20273 const NetLogWithSource& NetLog() const { return net_log_; }
[email protected]eaf10dc2011-07-18 21:47:35274
tfarina6f2f3beb2017-04-19 11:53:14275 // Call this to enable SO_REUSEADDR on the underlying socket.
276 // Should be called between Open() and Bind().
hidehiko17fac552014-12-08 06:02:17277 // Returns a net error code.
278 int AllowAddressReuse();
[email protected]a1781d7b2012-07-16 11:52:34279
tfarina6f2f3beb2017-04-19 11:53:14280 // Call this to allow or disallow sending and receiving packets to and from
281 // broadcast addresses.
hidehiko17fac552014-12-08 06:02:17282 // Returns a net error code.
283 int SetBroadcast(bool broadcast);
[email protected]a1781d7b2012-07-16 11:52:34284
Eric Orth7141dbc2018-10-26 20:10:24285 // Sets socket options to allow the socket to share the local address to which
286 // the socket will be bound with other processes and attempt to allow all such
287 // sockets to receive the same multicast messages. Returns a net error code.
288 //
289 // Ability and requirements for different sockets to receive the same messages
290 // varies between POSIX platforms. For best results in allowing the messages
291 // to be shared, all sockets sharing the same address should join the same
292 // multicast group and interface. Also, the socket should listen to the
293 // specific multicast address rather than a wildcard address (e.g. 0.0.0.0).
294 //
295 // Should be called between Open() and Bind().
296 int AllowAddressSharingForMulticast();
297
hidehiko17fac552014-12-08 06:02:17298 // Joins the multicast group.
[email protected]5f01ce22013-04-30 00:53:18299 // |group_address| is the group address to join, could be either
300 // an IPv4 or IPv6 address.
hidehiko17fac552014-12-08 06:02:17301 // Returns a net error code.
martijnd8dafab2016-03-14 18:28:49302 int JoinGroup(const IPAddress& group_address) const;
[email protected]5f01ce22013-04-30 00:53:18303
hidehiko17fac552014-12-08 06:02:17304 // Leaves the multicast group.
[email protected]5f01ce22013-04-30 00:53:18305 // |group_address| is the group address to leave, could be either
306 // an IPv4 or IPv6 address. If the socket hasn't joined the group,
307 // it will be ignored.
308 // It's optional to leave the multicast group before destroying
309 // the socket. It will be done by the OS.
hidehiko17fac552014-12-08 06:02:17310 // Returns a net error code.
martijnd8dafab2016-03-14 18:28:49311 int LeaveGroup(const IPAddress& group_address) const;
[email protected]5f01ce22013-04-30 00:53:18312
hidehiko17fac552014-12-08 06:02:17313 // Sets interface to use for multicast. If |interface_index| set to 0,
314 // default interface is used.
[email protected]7b29dac2013-12-05 11:19:42315 // Should be called before Bind().
hidehiko17fac552014-12-08 06:02:17316 // Returns a net error code.
tfarinac40df1c2015-11-30 22:31:47317 int SetMulticastInterface(uint32_t interface_index);
[email protected]7b29dac2013-12-05 11:19:42318
hidehiko17fac552014-12-08 06:02:17319 // Sets the time-to-live option for UDP packets sent to the multicast
[email protected]5f01ce22013-04-30 00:53:18320 // group address. The default value of this option is 1.
321 // Cannot be negative or more than 255.
322 // Should be called before Bind().
hidehiko17fac552014-12-08 06:02:17323 // Returns a net error code.
[email protected]5f01ce22013-04-30 00:53:18324 int SetMulticastTimeToLive(int time_to_live);
325
hidehiko17fac552014-12-08 06:02:17326 // Sets the loopback flag for UDP socket. If this flag is true, the host
[email protected]5f01ce22013-04-30 00:53:18327 // will receive packets sent to the joined group from itself.
328 // The default value of this option is true.
329 // Should be called before Bind().
hidehiko17fac552014-12-08 06:02:17330 // Returns a net error code.
[email protected]5f01ce22013-04-30 00:53:18331 //
332 // Note: the behavior of |SetMulticastLoopbackMode| is slightly
333 // different between Windows and Unix-like systems. The inconsistency only
334 // happens when there are more than one applications on the same host
335 // joined to the same multicast group while having different settings on
336 // multicast loopback mode. On Windows, the applications with loopback off
337 // will not RECEIVE the loopback packets; while on Unix-like systems, the
338 // applications with loopback off will not SEND the loopback packets to
339 // other applications on the same host. See MSDN: http://goo.gl/6vqbj
340 int SetMulticastLoopbackMode(bool loopback);
341
hidehiko17fac552014-12-08 06:02:17342 // Sets the differentiated services flags on outgoing packets. May not
[email protected]a8a442b32013-10-22 00:34:41343 // do anything on some platforms.
hidehiko17fac552014-12-08 06:02:17344 // Returns a net error code.
[email protected]a8a442b32013-10-22 00:34:41345 int SetDiffServCodePoint(DiffServCodePoint dscp);
346
Stefano Duo157e10c22022-01-25 12:58:34347 // Exposes the underlying socket descriptor for testing its state. Does not
348 // release ownership of the descriptor.
349 SocketDescriptor SocketDescriptorForTesting() const { return socket_; }
350
[email protected]1901dbcb2014-03-10 07:18:37351 // Resets the thread to be used for thread-safety checks.
352 void DetachFromThread();
353
Paul Jensen0f49dec2017-12-12 23:39:58354 // Apply |tag| to this socket.
355 void ApplySocketTag(const SocketTag& tag);
356
Charles 'Buck' Krasic762317f2018-03-30 20:08:09357 void SetWriteAsyncEnabled(bool enabled) { write_async_enabled_ = enabled; }
358 bool WriteAsyncEnabled() { return write_async_enabled_; }
359
360 void SetMaxPacketSize(size_t max_packet_size);
361
362 void SetWriteMultiCoreEnabled(bool enabled) {
363 write_multi_core_enabled_ = enabled;
364 }
365
366 void SetSendmmsgEnabled(bool enabled) {
367 DCHECK(sender_ != nullptr);
368 sender_->SetSendmmsgEnabled(enabled);
369 }
370
371 void SetWriteBatchingActive(bool active) { write_batching_active_ = active; }
372
373 void SetWriteAsyncMaxBuffers(int value) {
374 LOG(INFO) << "SetWriteAsyncMaxBuffers: " << value;
375 write_async_max_buffers_ = value;
376 }
377
kapishnikov7f8dd1e2018-01-24 06:10:49378 // Enables experimental optimization. This method should be called
379 // before the socket is used to read data for the first time.
380 void enable_experimental_recv_optimization() {
381 DCHECK_EQ(kInvalidSocket, socket_);
382 experimental_recv_optimization_enabled_ = true;
Eric Orth7141dbc2018-10-26 20:10:24383 }
kapishnikov7f8dd1e2018-01-24 06:10:49384
Yu Suca37f3c2020-10-09 20:02:23385 // Sets iOS Network Service Type for option SO_NET_SERVICE_TYPE.
386 int SetIOSNetworkServiceType(int ios_network_service_type);
387
Charles 'Buck' Krasic762317f2018-03-30 20:08:09388 protected:
389 // WriteAsync batching etc. are to improve throughput of large high
390 // bandwidth uploads.
391
392 // Watcher for WriteAsync paths.
Gabriel Charette19d2ae62018-04-10 14:10:58393 class WriteAsyncWatcher : public base::MessagePumpForIO::FdWatcher {
Charles 'Buck' Krasic762317f2018-03-30 20:08:09394 public:
Tsuyoshi Horo2ec06e002022-06-09 01:38:59395 explicit WriteAsyncWatcher(UDPSocketPosix* socket) : socket_(socket) {}
Charles 'Buck' Krasic762317f2018-03-30 20:08:09396
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_;
Tsuyoshi Horo2ec06e002022-06-09 01:38:59412 bool watching_ = false;
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.
Tsuyoshi Horo2ec06e002022-06-09 01:38:59547 int socket_hash_ = 0;
Zhongyi Shi351b5442018-11-27 16:24:17548
Tsuyoshi Horo2ec06e002022-06-09 01:38:59549 int addr_family_ = 0;
550 bool is_connected_ = false;
[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().
Tsuyoshi Horo2ec06e002022-06-09 01:38:59554 int socket_options_ = SOCKET_OPTION_MULTICAST_LOOP;
[email protected]a1781d7b2012-07-16 11:52:34555
Yixin Wang3ae76ca2018-03-15 17:18:52556 // Flags passed to sendto().
Tsuyoshi Horo2ec06e002022-06-09 01:38:59557 int sendto_flags_ = 0;
Yixin Wang3ae76ca2018-03-15 17:18:52558
[email protected]7b29dac2013-12-05 11:19:42559 // Multicast interface.
Tsuyoshi Horo2ec06e002022-06-09 01:38:59560 uint32_t multicast_interface_ = 0;
[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().
Tsuyoshi Horo2ec06e002022-06-09 01:38:59564 int multicast_time_to_live_ = 1;
[email protected]5f01ce22013-04-30 00:53:18565
[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
Tsuyoshi Horo2ec06e002022-06-09 01:38:59590 int last_async_result_ = 0;
Charles 'Buck' Krasic762317f2018-03-30 20:08:09591 base::RepeatingTimer write_async_timer_;
Tsuyoshi Horo2ec06e002022-06-09 01:38:59592 bool write_async_timer_running_ = false;
Charles 'Buck' Krasic762317f2018-03-30 20:08:09593 // Total writes in flight, including those |PostTask*|'d.
Tsuyoshi Horo2ec06e002022-06-09 01:38:59594 int write_async_outstanding_ = 0;
Charles 'Buck' Krasic762317f2018-03-30 20:08:09595
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_;
Tsuyoshi Horo2ec06e002022-06-09 01:38:59600 int read_buf_len_ = 0;
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_;
Tsuyoshi Horo2ec06e002022-06-09 01:38:59605 int write_buf_len_ = 0;
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.
Tsuyoshi Horo2ec06e002022-06-09 01:38:59637 bool experimental_recv_optimization_enabled_ = false;
kapishnikov7f8dd1e2018-01-24 06:10:49638
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_