xref: /aosp_15_r20/external/cronet/base/sync_socket.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 The Chromium Authors
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 BASE_SYNC_SOCKET_H_
6 #define BASE_SYNC_SOCKET_H_
7 
8 // A socket abstraction used for sending and receiving plain
9 // data.  Because the receiving is blocking, they can be used to perform
10 // rudimentary cross-process synchronization with low latency.
11 
12 #include <stddef.h>
13 
14 #include "base/base_export.h"
15 #include "base/containers/span.h"
16 #include "base/files/platform_file.h"
17 #include "base/synchronization/waitable_event.h"
18 #include "base/time/time.h"
19 #include "build/build_config.h"
20 
21 #if BUILDFLAG(IS_WIN)
22 #include <windows.h>
23 #endif
24 #include <sys/types.h>
25 
26 namespace base {
27 
28 class BASE_EXPORT SyncSocket {
29  public:
30   using Handle = PlatformFile;
31   using ScopedHandle = ScopedPlatformFile;
32   static const Handle kInvalidHandle;
33 
34   SyncSocket();
35 
36   // Creates a SyncSocket from a Handle.
37   explicit SyncSocket(Handle handle);
38   explicit SyncSocket(ScopedHandle handle);
39   SyncSocket(const SyncSocket&) = delete;
40   SyncSocket& operator=(const SyncSocket&) = delete;
41   virtual ~SyncSocket();
42 
43   // Initializes and connects a pair of sockets.
44   // |socket_a| and |socket_b| must not hold a valid handle.  Upon successful
45   // return, the sockets will both be valid and connected.
46   static bool CreatePair(SyncSocket* socket_a, SyncSocket* socket_b);
47 
48   // Closes the SyncSocket.
49   virtual void Close();
50 
51   // Sends the message to the remote peer of the SyncSocket.
52   // Note it is not safe to send messages from the same socket handle by
53   // multiple threads simultaneously.
54   // `data` must be non-empty.
55   // Returns the number of bytes sent, or 0 upon failure.
56   virtual size_t Send(span<const uint8_t> data);
57   // Same as above, but with the following parameters:
58   // `buffer` is a pointer to the data to send.
59   // `length` is the length of the data to send (must be non-zero).
60   // TODO(https://crbug.com/1490484): Migrate callers to the span version.
61   virtual size_t Send(const void* buffer, size_t length);
62 
63   // Receives a message from an SyncSocket.
64   // The data will be received in `buffer`, which must be non-empty.
65   // Returns the number of bytes received, or 0 upon failure.
66   virtual size_t Receive(span<uint8_t> buffer);
67   // Same as above, but with the following parameters:
68   // `buffer` is a pointer to the buffer to receive data.
69   // `length` is the number of bytes of data to receive (must be non-zero).
70   // TODO(https://crbug.com/1490484): Migrate callers to the span version.
71   virtual size_t Receive(void* buffer, size_t length);
72 
73   // Same as Receive() but only blocks for data until `timeout` has elapsed or
74   // `buffer` is exhausted. Currently only timeouts less than one second are
75   // allowed. Returns the number of bytes read.
76   virtual size_t ReceiveWithTimeout(span<uint8_t> buffer, TimeDelta timeout);
77   // TODO(https://crbug.com/1490484): Migrate callers to the span version.
78   virtual size_t ReceiveWithTimeout(void* buffer,
79                                     size_t length,
80                                     TimeDelta timeout);
81 
82   // Returns the number of bytes available. If non-zero, Receive() will not
83   // not block when called.
84   virtual size_t Peek();
85 
86   // Returns true if the Handle is valid, and false if it is not.
87   bool IsValid() const;
88 
89   // Extracts the contained handle.  Used for transferring between
90   // processes.
91   Handle handle() const;
92 
93   // Extracts and takes ownership of the contained handle.
94   Handle Release();
95   ScopedHandle Take();
96 
97  protected:
98   ScopedHandle handle_;
99 };
100 
101 // Derives from SyncSocket and adds support for shutting down the socket from
102 // another thread while a blocking Receive or Send is being done from the
103 // thread that owns the socket.
104 class BASE_EXPORT CancelableSyncSocket : public SyncSocket {
105  public:
106   CancelableSyncSocket();
107   explicit CancelableSyncSocket(Handle handle);
108   explicit CancelableSyncSocket(ScopedHandle handle);
109   CancelableSyncSocket(const CancelableSyncSocket&) = delete;
110   CancelableSyncSocket& operator=(const CancelableSyncSocket&) = delete;
111   ~CancelableSyncSocket() override = default;
112 
113   // Initializes a pair of cancelable sockets.  See documentation for
114   // SyncSocket::CreatePair for more details.
115   static bool CreatePair(CancelableSyncSocket* socket_a,
116                          CancelableSyncSocket* socket_b);
117 
118   // A way to shut down a socket even if another thread is currently performing
119   // a blocking Receive or Send.
120   bool Shutdown();
121 
122 #if BUILDFLAG(IS_WIN)
123   // Since the Linux and Mac implementations actually use a socket, shutting
124   // them down from another thread is pretty simple - we can just call
125   // shutdown().  However, the Windows implementation relies on named pipes
126   // and there isn't a way to cancel a blocking synchronous Read that is
127   // supported on <Vista. So, for Windows only, we override these
128   // SyncSocket methods in order to support shutting down the 'socket'.
129   void Close() override;
130   size_t Receive(span<uint8_t> buffer) override;
131   // TODO(https://crbug.com/1490484): Migrate callers to the span version.
132   size_t Receive(void* buffer, size_t length) override;
133   size_t ReceiveWithTimeout(span<uint8_t> buffer, TimeDelta timeout) override;
134   // TODO(https://crbug.com/1490484): Migrate callers to the span version.
135   size_t ReceiveWithTimeout(void* buffer,
136                             size_t length,
137                             TimeDelta timeout) override;
138 #endif
139 
140   // Send() is overridden to catch cases where the remote end is not responding
141   // and we fill the local socket buffer. When `data` is full, this
142   // implementation of Send() will not block indefinitely as
143   // SyncSocket::Send will, but instead return 0, as no bytes could be sent.
144   // Note that the socket will not be closed in this case.
145   size_t Send(span<const uint8_t> data) override;
146   // TODO(https://crbug.com/1490484): Migrate callers to the span version.
147   size_t Send(const void* buffer, size_t length) override;
148 
149  private:
150 #if BUILDFLAG(IS_WIN)
151   WaitableEvent shutdown_event_;
152   WaitableEvent file_operation_;
153 #endif
154 };
155 
156 }  // namespace base
157 
158 #endif  // BASE_SYNC_SOCKET_H_
159