blob: 5fe0d8cf65fc5c92338310d4575e498a97ddc591 [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"
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
Sean McAllister41695562020-08-20 02:11:0938#elif defined(OS_LINUX) || defined(OS_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.
69const base::TimeDelta kWriteAsyncMsThreshold =
70 base::TimeDelta::FromMilliseconds(1);
71// Prefer local if number of writes is not more than this.
72const int kWriteAsyncMinBuffersThreshold = 2;
73// Don't allow more than this many outstanding async writes.
74const int kWriteAsyncMaxBuffersThreshold = 16;
75// PostTask immediately when unwritten buffers reaches this.
76const int kWriteAsyncPostBuffersThreshold = kWriteAsyncMaxBuffersThreshold / 2;
77// Don't unblock writer unless pending async writes are less than this.
78const int kWriteAsyncCallbackBuffersThreshold = kWriteAsyncMaxBuffersThreshold;
79
80// To allow mock |Send|/|Sendmsg| in testing. This has to be
81// reference counted thread safe because |SendBuffers| and
82// |SendmmsgBuffers| may be invoked in another thread via PostTask*.
83class NET_EXPORT UDPSocketPosixSender
84 : public base::RefCountedThreadSafe<UDPSocketPosixSender> {
85 public:
Eric Orth7141dbc2018-10-26 20:10:2486 UDPSocketPosixSender();
Charles 'Buck' Krasic762317f2018-03-30 20:08:0987
88 SendResult SendBuffers(int fd, DatagramBuffers buffers);
89
90 void SetSendmmsgEnabled(bool enabled) {
91#if HAVE_SENDMMSG
92 sendmmsg_enabled_ = enabled;
93#endif
94 }
95
96 protected:
97 friend class base::RefCountedThreadSafe<UDPSocketPosixSender>;
98
99 virtual ~UDPSocketPosixSender();
100 virtual ssize_t Send(int sockfd,
101 const void* buf,
102 size_t len,
103 int flags) const;
104#if HAVE_SENDMMSG
105 virtual int Sendmmsg(int sockfd,
106 struct mmsghdr* msgvec,
107 unsigned int vlen,
108 unsigned int flags) const;
109#endif
110
111 SendResult InternalSendBuffers(int fd, DatagramBuffers buffers) const;
112#if HAVE_SENDMMSG
113 SendResult InternalSendmmsgBuffers(int fd, DatagramBuffers buffers) const;
114#endif
115
116 private:
117 UDPSocketPosixSender(const UDPSocketPosixSender&) = delete;
118 UDPSocketPosixSender& operator=(const UDPSocketPosixSender&) = delete;
119 bool sendmmsg_enabled_;
120};
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:
Francois Doray5146d2f02021-03-30 18:11:57131 ReceivedActivityMonitor() : bytes_(0), increments_(0) {}
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
147 uint32_t bytes_;
148 uint32_t increments_;
149 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);
tfarina4eb7aad82015-09-14 17:10:34155 virtual ~UDPSocketPosix();
[email protected]a2798d92011-03-02 22:56:18156
hidehiko17fac552014-12-08 06:02:17157 // Opens the socket.
158 // Returns a net error code.
159 int Open(AddressFamily address_family);
160
pauljensenbe5bc3232015-10-05 20:39:27161 // Binds this socket to |network|. All data traffic on the socket will be sent
162 // and received via |network|. Must be called before Connect(). This call will
163 // fail if |network| has disconnected. Communication using this socket will
164 // fail if |network| disconnects.
165 // Returns a net error code.
166 int BindToNetwork(NetworkChangeNotifier::NetworkHandle network);
167
hidehiko17fac552014-12-08 06:02:17168 // Connects the socket to connect with a certain |address|.
169 // Should be called after Open().
[email protected]a2798d92011-03-02 22:56:18170 // Returns a net error code.
[email protected]43d4a0262011-03-09 19:26:04171 int Connect(const IPEndPoint& address);
[email protected]a2798d92011-03-02 22:56:18172
hidehiko17fac552014-12-08 06:02:17173 // Binds the address/port for this socket to |address|. This is generally
174 // only used on a server. Should be called after Open().
[email protected]a2798d92011-03-02 22:56:18175 // Returns a net error code.
[email protected]43d4a0262011-03-09 19:26:04176 int Bind(const IPEndPoint& address);
[email protected]a2798d92011-03-02 22:56:18177
hidehiko17fac552014-12-08 06:02:17178 // Closes the socket.
179 // TODO(rvargas, hidehiko): Disallow re-Open() after Close().
[email protected]a2798d92011-03-02 22:56:18180 void Close();
181
hidehiko17fac552014-12-08 06:02:17182 // Copies the remote udp address into |address| and returns a net error code.
[email protected]43d4a0262011-03-09 19:26:04183 int GetPeerAddress(IPEndPoint* address) const;
[email protected]a2798d92011-03-02 22:56:18184
hidehiko17fac552014-12-08 06:02:17185 // Copies the local udp address into |address| and returns a net error code.
[email protected]a2798d92011-03-02 22:56:18186 // (similar to getsockname)
[email protected]43d4a0262011-03-09 19:26:04187 int GetLocalAddress(IPEndPoint* address) const;
[email protected]a2798d92011-03-02 22:56:18188
189 // IO:
190 // Multiple outstanding read requests are not supported.
191 // Full duplex mode (reading and writing at the same time) is supported
192
hidehiko17fac552014-12-08 06:02:17193 // Reads from the socket.
[email protected]a2798d92011-03-02 22:56:18194 // Only usable from the client-side of a UDP socket, after the socket
195 // has been connected.
Brad Lassey3a814172018-04-26 03:30:21196 int Read(IOBuffer* buf, int buf_len, CompletionOnceCallback callback);
[email protected]a2798d92011-03-02 22:56:18197
hidehiko17fac552014-12-08 06:02:17198 // Writes to the socket.
[email protected]a2798d92011-03-02 22:56:18199 // Only usable from the client-side of a UDP socket, after the socket
200 // has been connected.
[email protected]a2b2cfc2017-12-06 09:06:08201 int Write(IOBuffer* buf,
202 int buf_len,
Brad Lassey3a814172018-04-26 03:30:21203 CompletionOnceCallback callback,
[email protected]cda4b7b2017-12-20 06:04:43204 const NetworkTrafficAnnotationTag& traffic_annotation);
[email protected]a2798d92011-03-02 22:56:18205
Charles 'Buck' Krasic762317f2018-03-30 20:08:09206 // Refer to datagram_client_socket.h
207 int WriteAsync(DatagramBuffers buffers,
Brad Lassey3a814172018-04-26 03:30:21208 CompletionOnceCallback callback,
Charles 'Buck' Krasic762317f2018-03-30 20:08:09209 const NetworkTrafficAnnotationTag& traffic_annotation);
210 int WriteAsync(const char* buffer,
211 size_t buf_len,
Brad Lassey3a814172018-04-26 03:30:21212 CompletionOnceCallback callback,
Charles 'Buck' Krasic762317f2018-03-30 20:08:09213 const NetworkTrafficAnnotationTag& traffic_annotation);
214
215 DatagramBuffers GetUnwrittenBuffers();
216
hidehiko17fac552014-12-08 06:02:17217 // Reads from a socket and receive sender address information.
[email protected]a2798d92011-03-02 22:56:18218 // |buf| is the buffer to read data into.
219 // |buf_len| is the maximum amount of data to read.
220 // |address| is a buffer provided by the caller for receiving the sender
221 // address information about the received data. This buffer must be kept
222 // alive by the caller until the callback is placed.
[email protected]73c5b692014-07-01 12:43:41223 // |callback| is the callback on completion of the RecvFrom.
[email protected]a2798d92011-03-02 22:56:18224 // Returns a net error code, or ERR_IO_PENDING if the IO is in progress.
Matthew Denton111df5ad2018-10-19 20:39:25225 // If ERR_IO_PENDING is returned, this socket takes a ref to |buf| to keep
226 // it alive until the data is received. However, the caller must keep
227 // |address| alive until the callback is called.
[email protected]a2798d92011-03-02 22:56:18228 int RecvFrom(IOBuffer* buf,
229 int buf_len,
[email protected]43d4a0262011-03-09 19:26:04230 IPEndPoint* address,
Brad Lassey3a814172018-04-26 03:30:21231 CompletionOnceCallback callback);
[email protected]a2798d92011-03-02 22:56:18232
hidehiko17fac552014-12-08 06:02:17233 // Sends to a socket with a particular destination.
tfarina39524dd2016-02-19 10:52:10234 // |buf| is the buffer to send.
235 // |buf_len| is the number of bytes to send.
[email protected]a2798d92011-03-02 22:56:18236 // |address| is the recipient address.
[email protected]a2798d92011-03-02 22:56:18237 // |callback| is the user callback function to call on complete.
238 // Returns a net error code, or ERR_IO_PENDING if the IO is in progress.
Matthew Denton111df5ad2018-10-19 20:39:25239 // If ERR_IO_PENDING is returned, this socket copies |address| for
240 // asynchronous sending, and takes a ref to |buf| to keep it alive until the
241 // data is sent.
[email protected]a2798d92011-03-02 22:56:18242 int SendTo(IOBuffer* buf,
243 int buf_len,
[email protected]43d4a0262011-03-09 19:26:04244 const IPEndPoint& address,
Brad Lassey3a814172018-04-26 03:30:21245 CompletionOnceCallback callback);
[email protected]a2798d92011-03-02 22:56:18246
hidehiko17fac552014-12-08 06:02:17247 // Sets the receive buffer size (in bytes) for the socket.
248 // Returns a net error code.
tfarinac40df1c2015-11-30 22:31:47249 int SetReceiveBufferSize(int32_t size);
[email protected]df31da42011-10-18 01:44:40250
hidehiko17fac552014-12-08 06:02:17251 // Sets the send buffer size (in bytes) for the socket.
252 // Returns a net error code.
tfarinac40df1c2015-11-30 22:31:47253 int SetSendBufferSize(int32_t size);
[email protected]df31da42011-10-18 01:44:40254
rchff006a12016-08-24 23:56:31255 // Requests that packets sent by this socket not be fragment, either locally
256 // by the host, or by routers (via the DF bit in the IPv4 packet header).
257 // May not be supported by all platforms. Returns a return a network error
258 // code if there was a problem, but the socket will still be usable. Can not
259 // return ERR_IO_PENDING.
260 int SetDoNotFragment();
261
Yixin Wang3ae76ca2018-03-15 17:18:52262 // If |confirm| is true, then the MSG_CONFIRM flag will be passed to
263 // subsequent writes if it's supported by the platform.
264 void SetMsgConfirm(bool confirm);
265
[email protected]a2798d92011-03-02 22:56:18266 // Returns true if the socket is already connected or bound.
hidehiko17fac552014-12-08 06:02:17267 bool is_connected() const { return is_connected_; }
[email protected]a2798d92011-03-02 22:56:18268
tfarina42834112016-09-22 13:38:20269 const NetLogWithSource& NetLog() const { return net_log_; }
[email protected]eaf10dc2011-07-18 21:47:35270
tfarina6f2f3beb2017-04-19 11:53:14271 // Call this to enable SO_REUSEADDR on the underlying socket.
272 // Should be called between Open() and Bind().
hidehiko17fac552014-12-08 06:02:17273 // Returns a net error code.
274 int AllowAddressReuse();
[email protected]a1781d7b2012-07-16 11:52:34275
tfarina6f2f3beb2017-04-19 11:53:14276 // Call this to allow or disallow sending and receiving packets to and from
277 // broadcast addresses.
hidehiko17fac552014-12-08 06:02:17278 // Returns a net error code.
279 int SetBroadcast(bool broadcast);
[email protected]a1781d7b2012-07-16 11:52:34280
Eric Orth7141dbc2018-10-26 20:10:24281 // Sets socket options to allow the socket to share the local address to which
282 // the socket will be bound with other processes and attempt to allow all such
283 // sockets to receive the same multicast messages. Returns a net error code.
284 //
285 // Ability and requirements for different sockets to receive the same messages
286 // varies between POSIX platforms. For best results in allowing the messages
287 // to be shared, all sockets sharing the same address should join the same
288 // multicast group and interface. Also, the socket should listen to the
289 // specific multicast address rather than a wildcard address (e.g. 0.0.0.0).
290 //
291 // Should be called between Open() and Bind().
292 int AllowAddressSharingForMulticast();
293
hidehiko17fac552014-12-08 06:02:17294 // Joins the multicast group.
[email protected]5f01ce22013-04-30 00:53:18295 // |group_address| is the group address to join, could be either
296 // an IPv4 or IPv6 address.
hidehiko17fac552014-12-08 06:02:17297 // Returns a net error code.
martijnd8dafab2016-03-14 18:28:49298 int JoinGroup(const IPAddress& group_address) const;
[email protected]5f01ce22013-04-30 00:53:18299
hidehiko17fac552014-12-08 06:02:17300 // Leaves the multicast group.
[email protected]5f01ce22013-04-30 00:53:18301 // |group_address| is the group address to leave, could be either
302 // an IPv4 or IPv6 address. If the socket hasn't joined the group,
303 // it will be ignored.
304 // It's optional to leave the multicast group before destroying
305 // the socket. It will be done by the OS.
hidehiko17fac552014-12-08 06:02:17306 // Returns a net error code.
martijnd8dafab2016-03-14 18:28:49307 int LeaveGroup(const IPAddress& group_address) const;
[email protected]5f01ce22013-04-30 00:53:18308
hidehiko17fac552014-12-08 06:02:17309 // Sets interface to use for multicast. If |interface_index| set to 0,
310 // default interface is used.
[email protected]7b29dac2013-12-05 11:19:42311 // Should be called before Bind().
hidehiko17fac552014-12-08 06:02:17312 // Returns a net error code.
tfarinac40df1c2015-11-30 22:31:47313 int SetMulticastInterface(uint32_t interface_index);
[email protected]7b29dac2013-12-05 11:19:42314
hidehiko17fac552014-12-08 06:02:17315 // Sets the time-to-live option for UDP packets sent to the multicast
[email protected]5f01ce22013-04-30 00:53:18316 // group address. The default value of this option is 1.
317 // Cannot be negative or more than 255.
318 // Should be called before Bind().
hidehiko17fac552014-12-08 06:02:17319 // Returns a net error code.
[email protected]5f01ce22013-04-30 00:53:18320 int SetMulticastTimeToLive(int time_to_live);
321
hidehiko17fac552014-12-08 06:02:17322 // Sets the loopback flag for UDP socket. If this flag is true, the host
[email protected]5f01ce22013-04-30 00:53:18323 // will receive packets sent to the joined group from itself.
324 // The default value of this option is true.
325 // Should be called before Bind().
hidehiko17fac552014-12-08 06:02:17326 // Returns a net error code.
[email protected]5f01ce22013-04-30 00:53:18327 //
328 // Note: the behavior of |SetMulticastLoopbackMode| is slightly
329 // different between Windows and Unix-like systems. The inconsistency only
330 // happens when there are more than one applications on the same host
331 // joined to the same multicast group while having different settings on
332 // multicast loopback mode. On Windows, the applications with loopback off
333 // will not RECEIVE the loopback packets; while on Unix-like systems, the
334 // applications with loopback off will not SEND the loopback packets to
335 // other applications on the same host. See MSDN: http://goo.gl/6vqbj
336 int SetMulticastLoopbackMode(bool loopback);
337
hidehiko17fac552014-12-08 06:02:17338 // Sets the differentiated services flags on outgoing packets. May not
[email protected]a8a442b32013-10-22 00:34:41339 // do anything on some platforms.
hidehiko17fac552014-12-08 06:02:17340 // Returns a net error code.
[email protected]a8a442b32013-10-22 00:34:41341 int SetDiffServCodePoint(DiffServCodePoint dscp);
342
[email protected]1901dbcb2014-03-10 07:18:37343 // Resets the thread to be used for thread-safety checks.
344 void DetachFromThread();
345
Paul Jensen0f49dec2017-12-12 23:39:58346 // Apply |tag| to this socket.
347 void ApplySocketTag(const SocketTag& tag);
348
Charles 'Buck' Krasic762317f2018-03-30 20:08:09349 void SetWriteAsyncEnabled(bool enabled) { write_async_enabled_ = enabled; }
350 bool WriteAsyncEnabled() { return write_async_enabled_; }
351
352 void SetMaxPacketSize(size_t max_packet_size);
353
354 void SetWriteMultiCoreEnabled(bool enabled) {
355 write_multi_core_enabled_ = enabled;
356 }
357
358 void SetSendmmsgEnabled(bool enabled) {
359 DCHECK(sender_ != nullptr);
360 sender_->SetSendmmsgEnabled(enabled);
361 }
362
363 void SetWriteBatchingActive(bool active) { write_batching_active_ = active; }
364
365 void SetWriteAsyncMaxBuffers(int value) {
366 LOG(INFO) << "SetWriteAsyncMaxBuffers: " << value;
367 write_async_max_buffers_ = value;
368 }
369
kapishnikov7f8dd1e2018-01-24 06:10:49370 // Enables experimental optimization. This method should be called
371 // before the socket is used to read data for the first time.
372 void enable_experimental_recv_optimization() {
373 DCHECK_EQ(kInvalidSocket, socket_);
374 experimental_recv_optimization_enabled_ = true;
Eric Orth7141dbc2018-10-26 20:10:24375 }
kapishnikov7f8dd1e2018-01-24 06:10:49376
Yu Suca37f3c2020-10-09 20:02:23377 // Sets iOS Network Service Type for option SO_NET_SERVICE_TYPE.
378 int SetIOSNetworkServiceType(int ios_network_service_type);
379
Charles 'Buck' Krasic762317f2018-03-30 20:08:09380 protected:
381 // WriteAsync batching etc. are to improve throughput of large high
382 // bandwidth uploads.
383
384 // Watcher for WriteAsync paths.
Gabriel Charette19d2ae62018-04-10 14:10:58385 class WriteAsyncWatcher : public base::MessagePumpForIO::FdWatcher {
Charles 'Buck' Krasic762317f2018-03-30 20:08:09386 public:
387 explicit WriteAsyncWatcher(UDPSocketPosix* socket)
388 : socket_(socket), watching_(false) {}
389
Gabriel Charette19d2ae62018-04-10 14:10:58390 // MessagePumpForIO::FdWatcher methods
Charles 'Buck' Krasic762317f2018-03-30 20:08:09391
392 void OnFileCanReadWithoutBlocking(int /* fd */) override {}
393
394 void OnFileCanWriteWithoutBlocking(int /* fd */) override;
395
396 void set_watching(bool watching) { watching_ = watching; }
397
398 bool watching() { return watching_; }
399
400 private:
401 UDPSocketPosix* const socket_;
402 bool watching_;
403
404 DISALLOW_COPY_AND_ASSIGN(WriteAsyncWatcher);
405 };
406
407 void IncreaseWriteAsyncOutstanding(int increment) {
408 write_async_outstanding_ += increment;
409 }
410
411 virtual bool InternalWatchFileDescriptor();
412 virtual void InternalStopWatchingFileDescriptor();
413
Brad Lassey3a814172018-04-26 03:30:21414 void SetWriteCallback(CompletionOnceCallback callback) {
Charles 'Buck' Krasic762317f2018-03-30 20:08:09415 write_callback_ = std::move(callback);
416 }
417
418 void DidSendBuffers(SendResult buffers);
419 void FlushPending();
420
421 std::unique_ptr<WriteAsyncWatcher> write_async_watcher_;
422 scoped_refptr<UDPSocketPosixSender> sender_;
423 std::unique_ptr<DatagramBufferPool> datagram_buffer_pool_;
424 // |WriteAsync| pending writes, does not include buffers that have
425 // been |PostTask*|'d.
426 DatagramBuffers pending_writes_;
427
[email protected]a2798d92011-03-02 22:56:18428 private:
[email protected]a1781d7b2012-07-16 11:52:34429 enum SocketOptions {
hidehiko17fac552014-12-08 06:02:17430 SOCKET_OPTION_MULTICAST_LOOP = 1 << 0
[email protected]a1781d7b2012-07-16 11:52:34431 };
432
Gabriel Charette19d2ae62018-04-10 14:10:58433 class ReadWatcher : public base::MessagePumpForIO::FdWatcher {
[email protected]a2798d92011-03-02 22:56:18434 public:
tfarina4eb7aad82015-09-14 17:10:34435 explicit ReadWatcher(UDPSocketPosix* socket) : socket_(socket) {}
[email protected]a2798d92011-03-02 22:56:18436
Gabriel Charette19d2ae62018-04-10 14:10:58437 // MessagePumpForIO::FdWatcher methods
[email protected]a2798d92011-03-02 22:56:18438
dchengb03027d2014-10-21 12:00:20439 void OnFileCanReadWithoutBlocking(int /* fd */) override;
[email protected]a2798d92011-03-02 22:56:18440
dchengb03027d2014-10-21 12:00:20441 void OnFileCanWriteWithoutBlocking(int /* fd */) override {}
[email protected]a2798d92011-03-02 22:56:18442
443 private:
tfarina4eb7aad82015-09-14 17:10:34444 UDPSocketPosix* const socket_;
[email protected]a2798d92011-03-02 22:56:18445
446 DISALLOW_COPY_AND_ASSIGN(ReadWatcher);
447 };
448
Gabriel Charette19d2ae62018-04-10 14:10:58449 class WriteWatcher : public base::MessagePumpForIO::FdWatcher {
[email protected]a2798d92011-03-02 22:56:18450 public:
tfarina4eb7aad82015-09-14 17:10:34451 explicit WriteWatcher(UDPSocketPosix* socket) : socket_(socket) {}
[email protected]a2798d92011-03-02 22:56:18452
Gabriel Charette19d2ae62018-04-10 14:10:58453 // MessagePumpForIO::FdWatcher methods
[email protected]a2798d92011-03-02 22:56:18454
dchengb03027d2014-10-21 12:00:20455 void OnFileCanReadWithoutBlocking(int /* fd */) override {}
[email protected]a2798d92011-03-02 22:56:18456
dchengb03027d2014-10-21 12:00:20457 void OnFileCanWriteWithoutBlocking(int /* fd */) override;
[email protected]a2798d92011-03-02 22:56:18458
459 private:
tfarina4eb7aad82015-09-14 17:10:34460 UDPSocketPosix* const socket_;
[email protected]a2798d92011-03-02 22:56:18461
462 DISALLOW_COPY_AND_ASSIGN(WriteWatcher);
463 };
464
Brad Lassey3a814172018-04-26 03:30:21465 int InternalWriteAsync(CompletionOnceCallback callback,
Charles 'Buck' Krasic762317f2018-03-30 20:08:09466 const NetworkTrafficAnnotationTag& traffic_annotation);
467 bool WatchFileDescriptor();
468 void StopWatchingFileDescriptor();
469
[email protected]a2798d92011-03-02 22:56:18470 void DoReadCallback(int rv);
471 void DoWriteCallback(int rv);
472 void DidCompleteRead();
473 void DidCompleteWrite();
474
[email protected]8866f622011-10-18 20:08:10475 // Handles stats and logging. |result| is the number of bytes transferred, on
476 // success, or the net error code on failure. On success, LogRead takes in a
477 // sockaddr and its length, which are mandatory, while LogWrite takes in an
478 // optional IPEndPoint.
Charles 'Buck' Krasice70ff452017-08-14 22:11:44479 void LogRead(int result,
480 const char* bytes,
481 socklen_t addr_len,
482 const sockaddr* addr);
483 void LogWrite(int result, const char* bytes, const IPEndPoint* address);
[email protected]8866f622011-10-18 20:08:10484
[email protected]06043ae2011-03-16 00:00:21485 // Same as SendTo(), except that address is passed by pointer
486 // instead of by reference. It is called from Write() with |address|
Bartek Nowierski3253b672020-06-01 20:37:12487 // set to nullptr.
[email protected]06043ae2011-03-16 00:00:21488 int SendToOrWrite(IOBuffer* buf,
489 int buf_len,
490 const IPEndPoint* address,
Brad Lassey3a814172018-04-26 03:30:21491 CompletionOnceCallback callback);
[email protected]06043ae2011-03-16 00:00:21492
[email protected]8866f622011-10-18 20:08:10493 int InternalConnect(const IPEndPoint& address);
kapishnikov7f8dd1e2018-01-24 06:10:49494
495 // Reads data from a UDP socket. Depending whether the socket is connected or
496 // not, the method delegates the call to InternalRecvFromConnectedSocket()
497 // or InternalRecvFromNonConnectedSocket() respectively.
498 // For proper detection of truncated reads, the |buf_len| should always be
499 // one byte longer than the expected maximum packet length.
[email protected]06043ae2011-03-16 00:00:21500 int InternalRecvFrom(IOBuffer* buf, int buf_len, IPEndPoint* address);
kapishnikov7f8dd1e2018-01-24 06:10:49501
502 // A more efficient implementation of the InternalRecvFrom() method for
503 // reading data from connected sockets. Internally the method uses the read()
504 // system call.
505 int InternalRecvFromConnectedSocket(IOBuffer* buf,
506 int buf_len,
507 IPEndPoint* address);
508
509 // An implementation of the InternalRecvFrom() method for reading data
510 // from non-connected sockets. Internally the method uses the recvmsg()
511 // system call.
512 int InternalRecvFromNonConnectedSocket(IOBuffer* buf,
513 int buf_len,
514 IPEndPoint* address);
[email protected]06043ae2011-03-16 00:00:21515 int InternalSendTo(IOBuffer* buf, int buf_len, const IPEndPoint* address);
[email protected]a2798d92011-03-02 22:56:18516
[email protected]a1781d7b2012-07-16 11:52:34517 // Applies |socket_options_| to |socket_|. Should be called before
518 // Bind().
hidehiko17fac552014-12-08 06:02:17519 int SetMulticastOptions();
[email protected]5370c012011-06-29 03:47:04520 int DoBind(const IPEndPoint& address);
[email protected]acfe8e82013-12-12 14:12:56521 // Binds to a random port on |address|.
martijnd8dafab2016-03-14 18:28:49522 int RandomBind(const IPAddress& address);
[email protected]5370c012011-06-29 03:47:04523
Charles 'Buck' Krasic762317f2018-03-30 20:08:09524 // Helpers for |WriteAsync|
525 base::SequencedTaskRunner* GetTaskRunner();
526 void OnWriteAsyncTimerFired();
527 void LocalSendBuffers();
528 void PostSendBuffers();
529 int ResetLastAsyncResult();
530 int ResetWrittenBytes();
531
[email protected]a2798d92011-03-02 22:56:18532 int socket_;
sergeyu30ad5b32015-03-27 20:31:02533
Zhongyi Shi351b5442018-11-27 16:24:17534 // Hash of |socket_| to verify that it is not corrupted when calling close().
535 // Used to debug https://crbug.com/906005.
536 // TODO(crbug.com/906005): Remove this once the bug is fixed.
537 int socket_hash_;
538
[email protected]5f01ce22013-04-30 00:53:18539 int addr_family_;
hidehiko17fac552014-12-08 06:02:17540 bool is_connected_;
[email protected]a2798d92011-03-02 22:56:18541
[email protected]7be809df2012-08-07 17:00:48542 // Bitwise-or'd combination of SocketOptions. Specifies the set of
543 // options that should be applied to |socket_| before Bind().
[email protected]a1781d7b2012-07-16 11:52:34544 int socket_options_;
545
Yixin Wang3ae76ca2018-03-15 17:18:52546 // Flags passed to sendto().
547 int sendto_flags_;
548
[email protected]7b29dac2013-12-05 11:19:42549 // Multicast interface.
tfarinac40df1c2015-11-30 22:31:47550 uint32_t multicast_interface_;
[email protected]7b29dac2013-12-05 11:19:42551
hidehiko17fac552014-12-08 06:02:17552 // Multicast socket options cached for SetMulticastOption.
[email protected]5f01ce22013-04-30 00:53:18553 // Cannot be used after Bind().
554 int multicast_time_to_live_;
555
[email protected]5370c012011-06-29 03:47:04556 // How to do source port binding, used only when UDPSocket is part of
557 // UDPClientSocket, since UDPServerSocket provides Bind.
558 DatagramSocket::BindType bind_type_;
559
[email protected]a2798d92011-03-02 22:56:18560 // These are mutable since they're just cached copies to make
561 // GetPeerAddress/GetLocalAddress smarter.
danakja9850e12016-04-18 22:28:08562 mutable std::unique_ptr<IPEndPoint> local_address_;
563 mutable std::unique_ptr<IPEndPoint> remote_address_;
[email protected]a2798d92011-03-02 22:56:18564
tfarina4eb7aad82015-09-14 17:10:34565 // The socket's posix wrappers
Gabriel Charette19d2ae62018-04-10 14:10:58566 base::MessagePumpForIO::FdWatchController read_socket_watcher_;
567 base::MessagePumpForIO::FdWatchController write_socket_watcher_;
[email protected]a2798d92011-03-02 22:56:18568
569 // The corresponding watchers for reads and writes.
570 ReadWatcher read_watcher_;
571 WriteWatcher write_watcher_;
572
Charles 'Buck' Krasic762317f2018-03-30 20:08:09573 // Various bits to support |WriteAsync()|.
574 bool write_async_enabled_ = false;
575 bool write_batching_active_ = false;
576 bool write_multi_core_enabled_ = false;
577 int write_async_max_buffers_ = 16;
578 int written_bytes_ = 0;
579
580 int last_async_result_;
581 base::RepeatingTimer write_async_timer_;
582 bool write_async_timer_running_;
583 // Total writes in flight, including those |PostTask*|'d.
584 int write_async_outstanding_;
585
586 scoped_refptr<base::SequencedTaskRunner> task_runner_;
587
[email protected]43d4a0262011-03-09 19:26:04588 // The buffer used by InternalRead() to retry Read requests
[email protected]a2798d92011-03-02 22:56:18589 scoped_refptr<IOBuffer> read_buf_;
590 int read_buf_len_;
[email protected]43d4a0262011-03-09 19:26:04591 IPEndPoint* recv_from_address_;
[email protected]a2798d92011-03-02 22:56:18592
[email protected]43d4a0262011-03-09 19:26:04593 // The buffer used by InternalWrite() to retry Write requests
[email protected]a2798d92011-03-02 22:56:18594 scoped_refptr<IOBuffer> write_buf_;
595 int write_buf_len_;
danakja9850e12016-04-18 22:28:08596 std::unique_ptr<IPEndPoint> send_to_address_;
[email protected]a2798d92011-03-02 22:56:18597
598 // External callback; called when read is complete.
Brad Lassey3a814172018-04-26 03:30:21599 CompletionOnceCallback read_callback_;
[email protected]a2798d92011-03-02 22:56:18600
601 // External callback; called when write is complete.
Brad Lassey3a814172018-04-26 03:30:21602 CompletionOnceCallback write_callback_;
[email protected]a2798d92011-03-02 22:56:18603
tfarina42834112016-09-22 13:38:20604 NetLogWithSource net_log_;
[email protected]a2798d92011-03-02 22:56:18605
pauljensenf0d9535a2016-06-10 19:51:19606 // Network that this socket is bound to via BindToNetwork().
607 NetworkChangeNotifier::NetworkHandle bound_network_;
608
Francois Doray32ad3672021-04-15 15:37:39609 // Whether net::activity_monitor should be updated every time bytes are
610 // received, without batching through |received_activity_monitor_|. This is
611 // initialized with the state of the "UdpSocketPosixAlwaysUpdateBytesReceived"
612 // feature. It is cached to avoid accessing the FeatureList every time bytes
613 // are received.
614 const bool always_update_bytes_received_;
615
Francois Doray5146d2f02021-03-30 18:11:57616 // Used to lower the overhead updating activity monitor.
Charles 'Buck' Krasice70ff452017-08-14 22:11:44617 ReceivedActivityMonitor received_activity_monitor_;
618
Paul Jensen0f49dec2017-12-12 23:39:58619 // Current socket tag if |socket_| is valid, otherwise the tag to apply when
620 // |socket_| is opened.
621 SocketTag tag_;
622
kapishnikov7f8dd1e2018-01-24 06:10:49623 // If set to true, the socket will use an optimized experimental code path.
624 // By default, the value is set to false. To use the optimization, the
625 // client of the socket has to opt-in by calling the
626 // enable_experimental_recv_optimization() method.
627 bool experimental_recv_optimization_enabled_;
628
Eric Roman5a841922020-08-13 01:28:25629 // Manages decrementing the global open UDP socket counter when this
630 // UDPSocket is destroyed.
631 OwnedUDPSocketCount owned_socket_count_;
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_