1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef NET_SOCKET_UDP_SOCKET_POSIX_H_
6 #define NET_SOCKET_UDP_SOCKET_POSIX_H_
7 
8 #include <stdint.h>
9 #include <sys/socket.h>
10 #include <sys/types.h>
11 
12 #include <memory>
13 
14 #include "base/macros.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/message_loop/message_pump_for_io.h"
17 #include "base/threading/thread_checker.h"
18 #include "base/timer/timer.h"
19 #include "build/build_config.h"
20 #include "net/base/address_family.h"
21 #include "net/base/completion_once_callback.h"
22 #include "net/base/datagram_buffer.h"
23 #include "net/base/io_buffer.h"
24 #include "net/base/ip_endpoint.h"
25 #include "net/base/net_export.h"
26 #include "net/base/network_change_notifier.h"
27 #include "net/log/net_log_with_source.h"
28 #include "net/socket/datagram_socket.h"
29 #include "net/socket/diff_serv_code_point.h"
30 #include "net/socket/socket_descriptor.h"
31 #include "net/socket/socket_tag.h"
32 #include "net/socket/udp_socket_global_limits.h"
33 #include "net/traffic_annotation/network_traffic_annotation.h"
34 
35 #if defined(__ANDROID__) && defined(__aarch64__)
36 #define HAVE_SENDMMSG 1
37 #elif (defined(OS_LINUX) || defined(OS_BSD)) && !defined(OS_DRAGONFLY)
38 #define HAVE_SENDMMSG 1
39 #else
40 #define HAVE_SENDMMSG 0
41 #endif
42 
43 namespace net {
44 
45 class IPAddress;
46 class NetLog;
47 struct NetLogSource;
48 class SocketTag;
49 
50 // Sendresult is inspired by sendmmsg, but unlike sendmmsg it is not
51 // convenient to require that a positive |write_count| and a negative
52 // error code are mutually exclusive.
53 struct NET_EXPORT SendResult {
54   explicit SendResult();
55   ~SendResult();
56   SendResult(int rv, int write_count, DatagramBuffers buffers);
57   SendResult(SendResult& other) = delete;
58   SendResult& operator=(SendResult& other) = delete;
59   SendResult(SendResult&& other);
60   SendResult& operator=(SendResult&& other) = default;
61   int rv;
62   // number of successful writes.
63   int write_count;
64   DatagramBuffers buffers;
65 };
66 
67 // Don't delay writes more than this.
68 const base::TimeDelta kWriteAsyncMsThreshold =
69     base::TimeDelta::FromMilliseconds(1);
70 // Prefer local if number of writes is not more than this.
71 const int kWriteAsyncMinBuffersThreshold = 2;
72 // Don't allow more than this many outstanding async writes.
73 const int kWriteAsyncMaxBuffersThreshold = 16;
74 // PostTask immediately when unwritten buffers reaches this.
75 const int kWriteAsyncPostBuffersThreshold = kWriteAsyncMaxBuffersThreshold / 2;
76 // Don't unblock writer unless pending async writes are less than this.
77 const 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*.
82 class NET_EXPORT UDPSocketPosixSender
83     : public base::RefCountedThreadSafe<UDPSocketPosixSender> {
84  public:
85   UDPSocketPosixSender();
86 
87   SendResult SendBuffers(int fd, DatagramBuffers buffers);
88 
SetSendmmsgEnabled(bool enabled)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 
121 class NET_EXPORT UDPSocketPosix {
122  public:
123   // Performance helper for NetworkActivityMonitor, it batches
124   // throughput samples, subject to a byte limit threshold (64 KB) or
125   // timer (100 ms), whichever comes first.  The batching is subject
126   // to a minimum number of samples (2) required by NQE to update its
127   // throughput estimate.
128   class ActivityMonitor {
129    public:
ActivityMonitor()130     ActivityMonitor() : bytes_(0), increments_(0) {}
~ActivityMonitor()131     virtual ~ActivityMonitor() {}
132     // Provided by sent/received subclass.
133     // Update throughput, but batch to limit overhead of NetworkActivityMonitor.
134     void Increment(uint32_t bytes);
135     // For flushing cached values.
136     void OnClose();
137 
138    private:
139     virtual void NetworkActivityMonitorIncrement(uint32_t bytes) = 0;
140     void Update();
141     void OnTimerFired();
142 
143     uint32_t bytes_;
144     uint32_t increments_;
145     base::RepeatingTimer timer_;
146     DISALLOW_COPY_AND_ASSIGN(ActivityMonitor);
147   };
148 
149   class SentActivityMonitor : public ActivityMonitor {
150    public:
~SentActivityMonitor()151     ~SentActivityMonitor() override {}
152 
153    private:
154     void NetworkActivityMonitorIncrement(uint32_t bytes) override;
155   };
156 
157   class ReceivedActivityMonitor : public ActivityMonitor {
158    public:
~ReceivedActivityMonitor()159     ~ReceivedActivityMonitor() override {}
160 
161    private:
162     void NetworkActivityMonitorIncrement(uint32_t bytes) override;
163   };
164 
165   UDPSocketPosix(DatagramSocket::BindType bind_type,
166                  net::NetLog* net_log,
167                  const net::NetLogSource& source);
168   virtual ~UDPSocketPosix();
169 
170   // Opens the socket.
171   // Returns a net error code.
172   int Open(AddressFamily address_family);
173 
174   // Binds this socket to |network|. All data traffic on the socket will be sent
175   // and received via |network|. Must be called before Connect(). This call will
176   // fail if |network| has disconnected. Communication using this socket will
177   // fail if |network| disconnects.
178   // Returns a net error code.
179   int BindToNetwork(NetworkChangeNotifier::NetworkHandle network);
180 
181   // Connects the socket to connect with a certain |address|.
182   // Should be called after Open().
183   // Returns a net error code.
184   int Connect(const IPEndPoint& address);
185 
186   // Binds the address/port for this socket to |address|.  This is generally
187   // only used on a server. Should be called after Open().
188   // Returns a net error code.
189   int Bind(const IPEndPoint& address);
190 
191   // Closes the socket.
192   // TODO(rvargas, hidehiko): Disallow re-Open() after Close().
193   void Close();
194 
195   // Copies the remote udp address into |address| and returns a net error code.
196   int GetPeerAddress(IPEndPoint* address) const;
197 
198   // Copies the local udp address into |address| and returns a net error code.
199   // (similar to getsockname)
200   int GetLocalAddress(IPEndPoint* address) const;
201 
202   // IO:
203   // Multiple outstanding read requests are not supported.
204   // Full duplex mode (reading and writing at the same time) is supported
205 
206   // Reads from the socket.
207   // Only usable from the client-side of a UDP socket, after the socket
208   // has been connected.
209   int Read(IOBuffer* buf, int buf_len, CompletionOnceCallback callback);
210 
211   // Writes to the socket.
212   // Only usable from the client-side of a UDP socket, after the socket
213   // has been connected.
214   int Write(IOBuffer* buf,
215             int buf_len,
216             CompletionOnceCallback callback,
217             const NetworkTrafficAnnotationTag& traffic_annotation);
218 
219   // Refer to datagram_client_socket.h
220   int WriteAsync(DatagramBuffers buffers,
221                  CompletionOnceCallback callback,
222                  const NetworkTrafficAnnotationTag& traffic_annotation);
223   int WriteAsync(const char* buffer,
224                  size_t buf_len,
225                  CompletionOnceCallback callback,
226                  const NetworkTrafficAnnotationTag& traffic_annotation);
227 
228   DatagramBuffers GetUnwrittenBuffers();
229 
230   // Reads from a socket and receive sender address information.
231   // |buf| is the buffer to read data into.
232   // |buf_len| is the maximum amount of data to read.
233   // |address| is a buffer provided by the caller for receiving the sender
234   //   address information about the received data.  This buffer must be kept
235   //   alive by the caller until the callback is placed.
236   // |callback| is the callback on completion of the RecvFrom.
237   // Returns a net error code, or ERR_IO_PENDING if the IO is in progress.
238   // If ERR_IO_PENDING is returned, this socket takes a ref to |buf| to keep
239   // it alive until the data is received. However, the caller must keep
240   // |address| alive until the callback is called.
241   int RecvFrom(IOBuffer* buf,
242                int buf_len,
243                IPEndPoint* address,
244                CompletionOnceCallback callback);
245 
246   // Sends to a socket with a particular destination.
247   // |buf| is the buffer to send.
248   // |buf_len| is the number of bytes to send.
249   // |address| is the recipient address.
250   // |callback| is the user callback function to call on complete.
251   // Returns a net error code, or ERR_IO_PENDING if the IO is in progress.
252   // If ERR_IO_PENDING is returned, this socket copies |address| for
253   // asynchronous sending, and takes a ref to |buf| to keep it alive until the
254   // data is sent.
255   int SendTo(IOBuffer* buf,
256              int buf_len,
257              const IPEndPoint& address,
258              CompletionOnceCallback callback);
259 
260   // Sets the receive buffer size (in bytes) for the socket.
261   // Returns a net error code.
262   int SetReceiveBufferSize(int32_t size);
263 
264   // Sets the send buffer size (in bytes) for the socket.
265   // Returns a net error code.
266   int SetSendBufferSize(int32_t size);
267 
268   // Requests that packets sent by this socket not be fragment, either locally
269   // by the host, or by routers (via the DF bit in the IPv4 packet header).
270   // May not be supported by all platforms. Returns a return a network error
271   // code if there was a problem, but the socket will still be usable. Can not
272   // return ERR_IO_PENDING.
273   int SetDoNotFragment();
274 
275   // If |confirm| is true, then the MSG_CONFIRM flag will be passed to
276   // subsequent writes if it's supported by the platform.
277   void SetMsgConfirm(bool confirm);
278 
279   // Returns true if the socket is already connected or bound.
is_connected()280   bool is_connected() const { return is_connected_; }
281 
NetLog()282   const NetLogWithSource& NetLog() const { return net_log_; }
283 
284   // Call this to enable SO_REUSEADDR on the underlying socket.
285   // Should be called between Open() and Bind().
286   // Returns a net error code.
287   int AllowAddressReuse();
288 
289   // Call this to allow or disallow sending and receiving packets to and from
290   // broadcast addresses.
291   // Returns a net error code.
292   int SetBroadcast(bool broadcast);
293 
294   // Sets socket options to allow the socket to share the local address to which
295   // the socket will be bound with other processes and attempt to allow all such
296   // sockets to receive the same multicast messages. Returns a net error code.
297   //
298   // Ability and requirements for different sockets to receive the same messages
299   // varies between POSIX platforms.  For best results in allowing the messages
300   // to be shared, all sockets sharing the same address should join the same
301   // multicast group and interface. Also, the socket should listen to the
302   // specific multicast address rather than a wildcard address (e.g. 0.0.0.0).
303   //
304   // Should be called between Open() and Bind().
305   int AllowAddressSharingForMulticast();
306 
307   // Joins the multicast group.
308   // |group_address| is the group address to join, could be either
309   // an IPv4 or IPv6 address.
310   // Returns a net error code.
311   int JoinGroup(const IPAddress& group_address) const;
312 
313   // Leaves the multicast group.
314   // |group_address| is the group address to leave, could be either
315   // an IPv4 or IPv6 address. If the socket hasn't joined the group,
316   // it will be ignored.
317   // It's optional to leave the multicast group before destroying
318   // the socket. It will be done by the OS.
319   // Returns a net error code.
320   int LeaveGroup(const IPAddress& group_address) const;
321 
322   // Sets interface to use for multicast. If |interface_index| set to 0,
323   // default interface is used.
324   // Should be called before Bind().
325   // Returns a net error code.
326   int SetMulticastInterface(uint32_t interface_index);
327 
328   // Sets the time-to-live option for UDP packets sent to the multicast
329   // group address. The default value of this option is 1.
330   // Cannot be negative or more than 255.
331   // Should be called before Bind().
332   // Returns a net error code.
333   int SetMulticastTimeToLive(int time_to_live);
334 
335   // Sets the loopback flag for UDP socket. If this flag is true, the host
336   // will receive packets sent to the joined group from itself.
337   // The default value of this option is true.
338   // Should be called before Bind().
339   // Returns a net error code.
340   //
341   // Note: the behavior of |SetMulticastLoopbackMode| is slightly
342   // different between Windows and Unix-like systems. The inconsistency only
343   // happens when there are more than one applications on the same host
344   // joined to the same multicast group while having different settings on
345   // multicast loopback mode. On Windows, the applications with loopback off
346   // will not RECEIVE the loopback packets; while on Unix-like systems, the
347   // applications with loopback off will not SEND the loopback packets to
348   // other applications on the same host. See MSDN: http://goo.gl/6vqbj
349   int SetMulticastLoopbackMode(bool loopback);
350 
351   // Sets the differentiated services flags on outgoing packets. May not
352   // do anything on some platforms.
353   // Returns a net error code.
354   int SetDiffServCodePoint(DiffServCodePoint dscp);
355 
356   // Resets the thread to be used for thread-safety checks.
357   void DetachFromThread();
358 
359   // Apply |tag| to this socket.
360   void ApplySocketTag(const SocketTag& tag);
361 
SetWriteAsyncEnabled(bool enabled)362   void SetWriteAsyncEnabled(bool enabled) { write_async_enabled_ = enabled; }
WriteAsyncEnabled()363   bool WriteAsyncEnabled() { return write_async_enabled_; }
364 
365   void SetMaxPacketSize(size_t max_packet_size);
366 
SetWriteMultiCoreEnabled(bool enabled)367   void SetWriteMultiCoreEnabled(bool enabled) {
368     write_multi_core_enabled_ = enabled;
369   }
370 
SetSendmmsgEnabled(bool enabled)371   void SetSendmmsgEnabled(bool enabled) {
372     DCHECK(sender_ != nullptr);
373     sender_->SetSendmmsgEnabled(enabled);
374   }
375 
SetWriteBatchingActive(bool active)376   void SetWriteBatchingActive(bool active) { write_batching_active_ = active; }
377 
SetWriteAsyncMaxBuffers(int value)378   void SetWriteAsyncMaxBuffers(int value) {
379     LOG(INFO) << "SetWriteAsyncMaxBuffers: " << value;
380     write_async_max_buffers_ = value;
381   }
382 
383   // Enables experimental optimization. This method should be called
384   // before the socket is used to read data for the first time.
enable_experimental_recv_optimization()385   void enable_experimental_recv_optimization() {
386     DCHECK_EQ(kInvalidSocket, socket_);
387     experimental_recv_optimization_enabled_ = true;
388   }
389 
390  protected:
391   // WriteAsync batching etc. are to improve throughput of large high
392   // bandwidth uploads.
393 
394   // Watcher for WriteAsync paths.
395   class WriteAsyncWatcher : public base::MessagePumpForIO::FdWatcher {
396    public:
WriteAsyncWatcher(UDPSocketPosix * socket)397     explicit WriteAsyncWatcher(UDPSocketPosix* socket)
398         : socket_(socket), watching_(false) {}
399 
400     // MessagePumpForIO::FdWatcher methods
401 
OnFileCanReadWithoutBlocking(int)402     void OnFileCanReadWithoutBlocking(int /* fd */) override {}
403 
404     void OnFileCanWriteWithoutBlocking(int /* fd */) override;
405 
set_watching(bool watching)406     void set_watching(bool watching) { watching_ = watching; }
407 
watching()408     bool watching() { return watching_; }
409 
410    private:
411     UDPSocketPosix* const socket_;
412     bool watching_;
413 
414     DISALLOW_COPY_AND_ASSIGN(WriteAsyncWatcher);
415   };
416 
IncreaseWriteAsyncOutstanding(int increment)417   void IncreaseWriteAsyncOutstanding(int increment) {
418     write_async_outstanding_ += increment;
419   }
420 
421   virtual bool InternalWatchFileDescriptor();
422   virtual void InternalStopWatchingFileDescriptor();
423 
SetWriteCallback(CompletionOnceCallback callback)424   void SetWriteCallback(CompletionOnceCallback callback) {
425     write_callback_ = std::move(callback);
426   }
427 
428   void DidSendBuffers(SendResult buffers);
429   void FlushPending();
430 
431   std::unique_ptr<WriteAsyncWatcher> write_async_watcher_;
432   scoped_refptr<UDPSocketPosixSender> sender_;
433   std::unique_ptr<DatagramBufferPool> datagram_buffer_pool_;
434   // |WriteAsync| pending writes, does not include buffers that have
435   // been |PostTask*|'d.
436   DatagramBuffers pending_writes_;
437 
438  private:
439   enum SocketOptions {
440     SOCKET_OPTION_MULTICAST_LOOP = 1 << 0
441   };
442 
443   class ReadWatcher : public base::MessagePumpForIO::FdWatcher {
444    public:
ReadWatcher(UDPSocketPosix * socket)445     explicit ReadWatcher(UDPSocketPosix* socket) : socket_(socket) {}
446 
447     // MessagePumpForIO::FdWatcher methods
448 
449     void OnFileCanReadWithoutBlocking(int /* fd */) override;
450 
OnFileCanWriteWithoutBlocking(int)451     void OnFileCanWriteWithoutBlocking(int /* fd */) override {}
452 
453    private:
454     UDPSocketPosix* const socket_;
455 
456     DISALLOW_COPY_AND_ASSIGN(ReadWatcher);
457   };
458 
459   class WriteWatcher : public base::MessagePumpForIO::FdWatcher {
460    public:
WriteWatcher(UDPSocketPosix * socket)461     explicit WriteWatcher(UDPSocketPosix* socket) : socket_(socket) {}
462 
463     // MessagePumpForIO::FdWatcher methods
464 
OnFileCanReadWithoutBlocking(int)465     void OnFileCanReadWithoutBlocking(int /* fd */) override {}
466 
467     void OnFileCanWriteWithoutBlocking(int /* fd */) override;
468 
469    private:
470     UDPSocketPosix* const socket_;
471 
472     DISALLOW_COPY_AND_ASSIGN(WriteWatcher);
473   };
474 
475   int InternalWriteAsync(CompletionOnceCallback callback,
476                          const NetworkTrafficAnnotationTag& traffic_annotation);
477   bool WatchFileDescriptor();
478   void StopWatchingFileDescriptor();
479 
480   void DoReadCallback(int rv);
481   void DoWriteCallback(int rv);
482   void DidCompleteRead();
483   void DidCompleteWrite();
484 
485   // 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.
489   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);
494 
495   // Same as SendTo(), except that address is passed by pointer
496   // instead of by reference. It is called from Write() with |address|
497   // set to NULL.
498   int SendToOrWrite(IOBuffer* buf,
499                     int buf_len,
500                     const IPEndPoint* address,
501                     CompletionOnceCallback callback);
502 
503   int InternalConnect(const IPEndPoint& address);
504 
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.
510   int InternalRecvFrom(IOBuffer* buf, int buf_len, IPEndPoint* address);
511 
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);
525   int InternalSendTo(IOBuffer* buf, int buf_len, const IPEndPoint* address);
526 
527   // Applies |socket_options_| to |socket_|. Should be called before
528   // Bind().
529   int SetMulticastOptions();
530   int DoBind(const IPEndPoint& address);
531   // Binds to a random port on |address|.
532   int RandomBind(const IPAddress& address);
533 
534   // Helpers for |WriteAsync|
535   base::SequencedTaskRunner* GetTaskRunner();
536   void OnWriteAsyncTimerFired();
537   void LocalSendBuffers();
538   void PostSendBuffers();
539   int ResetLastAsyncResult();
540   int ResetWrittenBytes();
541 
542   int socket_;
543 
544   // 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 
549   int addr_family_;
550   bool is_connected_;
551 
552   // Bitwise-or'd combination of SocketOptions. Specifies the set of
553   // options that should be applied to |socket_| before Bind().
554   int socket_options_;
555 
556   // Flags passed to sendto().
557   int sendto_flags_;
558 
559   // Multicast interface.
560   uint32_t multicast_interface_;
561 
562   // Multicast socket options cached for SetMulticastOption.
563   // Cannot be used after Bind().
564   int multicast_time_to_live_;
565 
566   // 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 
570   // These are mutable since they're just cached copies to make
571   // GetPeerAddress/GetLocalAddress smarter.
572   mutable std::unique_ptr<IPEndPoint> local_address_;
573   mutable std::unique_ptr<IPEndPoint> remote_address_;
574 
575   // The socket's posix wrappers
576   base::MessagePumpForIO::FdWatchController read_socket_watcher_;
577   base::MessagePumpForIO::FdWatchController write_socket_watcher_;
578 
579   // The corresponding watchers for reads and writes.
580   ReadWatcher read_watcher_;
581   WriteWatcher write_watcher_;
582 
583   // 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 
598   // The buffer used by InternalRead() to retry Read requests
599   scoped_refptr<IOBuffer> read_buf_;
600   int read_buf_len_;
601   IPEndPoint* recv_from_address_;
602 
603   // The buffer used by InternalWrite() to retry Write requests
604   scoped_refptr<IOBuffer> write_buf_;
605   int write_buf_len_;
606   std::unique_ptr<IPEndPoint> send_to_address_;
607 
608   // External callback; called when read is complete.
609   CompletionOnceCallback read_callback_;
610 
611   // External callback; called when write is complete.
612   CompletionOnceCallback write_callback_;
613 
614   NetLogWithSource net_log_;
615 
616   // Network that this socket is bound to via BindToNetwork().
617   NetworkChangeNotifier::NetworkHandle bound_network_;
618 
619   // These are used to lower the overhead updating activity monitor.
620   SentActivityMonitor sent_activity_monitor_;
621   ReceivedActivityMonitor received_activity_monitor_;
622 
623   // Current socket tag if |socket_| is valid, otherwise the tag to apply when
624   // |socket_| is opened.
625   SocketTag tag_;
626 
627   // If set to true, the socket will use an optimized experimental code path.
628   // By default, the value is set to false. To use the optimization, the
629   // client of the socket has to opt-in by calling the
630   // enable_experimental_recv_optimization() method.
631   bool experimental_recv_optimization_enabled_;
632 
633   // Manages decrementing the global open UDP socket counter when this
634   // UDPSocket is destroyed.
635   OwnedUDPSocketCount owned_socket_count_;
636 
637   THREAD_CHECKER(thread_checker_);
638 
639   // Used for alternate writes that are posted for concurrent execution.
640   base::WeakPtrFactory<UDPSocketPosix> weak_factory_{this};
641 
642   DISALLOW_COPY_AND_ASSIGN(UDPSocketPosix);
643 };
644 
645 }  // namespace net
646 
647 #endif  // NET_SOCKET_UDP_SOCKET_POSIX_H_
648