Upload upstream chromium 108.0.5359.1
[platform/framework/web/chromium-efl.git] / base / sync_socket_posix.cc
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 #include "base/sync_socket.h"
6
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <limits.h>
10 #include <poll.h>
11 #include <stddef.h>
12 #include <stdio.h>
13 #include <sys/ioctl.h>
14 #include <sys/socket.h>
15 #include <sys/types.h>
16
17 #include "base/check_op.h"
18 #include "base/containers/span.h"
19 #include "base/files/file_util.h"
20 #include "base/numerics/safe_conversions.h"
21 #include "base/threading/scoped_blocking_call.h"
22 #include "build/build_config.h"
23
24 #if BUILDFLAG(IS_SOLARIS)
25 #include <sys/filio.h>
26 #endif
27
28 namespace base {
29
30 namespace {
31 // To avoid users sending negative message lengths to Send/Receive
32 // we clamp message lengths, which are size_t, to no more than INT_MAX.
33 const size_t kMaxMessageLength = static_cast<size_t>(INT_MAX);
34
35 // Writes |length| of |buffer| into |handle|.  Returns the number of bytes
36 // written or zero on error.  |length| must be greater than 0.
37 size_t SendHelper(SyncSocket::Handle handle,
38                   const void* buffer,
39                   size_t length) {
40   DCHECK_GT(length, 0u);
41   DCHECK_LE(length, kMaxMessageLength);
42   DCHECK_NE(handle, SyncSocket::kInvalidHandle);
43   return WriteFileDescriptor(
44              handle, make_span(static_cast<const uint8_t*>(buffer), length))
45              ? length
46              : 0;
47 }
48
49 }  // namespace
50
51 // static
52 bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
53   DCHECK_NE(socket_a, socket_b);
54   DCHECK(!socket_a->IsValid());
55   DCHECK(!socket_b->IsValid());
56
57 #if BUILDFLAG(IS_APPLE)
58   int nosigpipe = 1;
59 #endif  // BUILDFLAG(IS_APPLE)
60
61   ScopedHandle handles[2];
62
63   {
64     Handle raw_handles[2] = {kInvalidHandle, kInvalidHandle};
65     if (socketpair(AF_UNIX, SOCK_STREAM, 0, raw_handles) != 0) {
66       return false;
67     }
68     handles[0].reset(raw_handles[0]);
69     handles[1].reset(raw_handles[1]);
70   }
71
72 #if BUILDFLAG(IS_APPLE)
73   // On OSX an attempt to read or write to a closed socket may generate a
74   // SIGPIPE rather than returning -1.  setsockopt will shut this off.
75   if (0 != setsockopt(handles[0].get(), SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe,
76                       sizeof(nosigpipe)) ||
77       0 != setsockopt(handles[1].get(), SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe,
78                       sizeof(nosigpipe))) {
79     return false;
80   }
81 #endif
82
83   // Copy the handles out for successful return.
84   socket_a->handle_ = std::move(handles[0]);
85   socket_b->handle_ = std::move(handles[1]);
86
87   return true;
88 }
89
90 void SyncSocket::Close() {
91   handle_.reset();
92 }
93
94 size_t SyncSocket::Send(const void* buffer, size_t length) {
95   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
96   return SendHelper(handle(), buffer, length);
97 }
98
99 size_t SyncSocket::Receive(void* buffer, size_t length) {
100   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
101   DCHECK_GT(length, 0u);
102   DCHECK_LE(length, kMaxMessageLength);
103   DCHECK(IsValid());
104   char* charbuffer = static_cast<char*>(buffer);
105   if (ReadFromFD(handle(), charbuffer, length))
106     return length;
107   return 0;
108 }
109
110 size_t SyncSocket::ReceiveWithTimeout(void* buffer,
111                                       size_t length,
112                                       TimeDelta timeout) {
113   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
114   DCHECK_GT(length, 0u);
115   DCHECK_LE(length, kMaxMessageLength);
116   DCHECK(IsValid());
117
118   // Only timeouts greater than zero and less than one second are allowed.
119   DCHECK_GT(timeout.InMicroseconds(), 0);
120   DCHECK_LT(timeout.InMicroseconds(), Seconds(1).InMicroseconds());
121
122   // Track the start time so we can reduce the timeout as data is read.
123   TimeTicks start_time = TimeTicks::Now();
124   const TimeTicks finish_time = start_time + timeout;
125
126   struct pollfd pollfd;
127   pollfd.fd = handle();
128   pollfd.events = POLLIN;
129   pollfd.revents = 0;
130
131   size_t bytes_read_total = 0;
132   while (bytes_read_total < length) {
133     const TimeDelta this_timeout = finish_time - TimeTicks::Now();
134     const int timeout_ms =
135         static_cast<int>(this_timeout.InMillisecondsRoundedUp());
136     if (timeout_ms <= 0)
137       break;
138     const int poll_result = poll(&pollfd, 1, timeout_ms);
139     // Handle EINTR manually since we need to update the timeout value.
140     if (poll_result == -1 && errno == EINTR)
141       continue;
142     // Return if other type of error or a timeout.
143     if (poll_result <= 0)
144       return bytes_read_total;
145
146     // poll() only tells us that data is ready for reading, not how much.  We
147     // must Peek() for the amount ready for reading to avoid blocking.
148     // At hang up (POLLHUP), the write end has been closed and there might still
149     // be data to be read.
150     // No special handling is needed for error (POLLERR); we can let any of the
151     // following operations fail and handle it there.
152     DCHECK(pollfd.revents & (POLLIN | POLLHUP | POLLERR)) << pollfd.revents;
153     const size_t bytes_to_read = std::min(Peek(), length - bytes_read_total);
154
155     // There may be zero bytes to read if the socket at the other end closed.
156     if (!bytes_to_read)
157       return bytes_read_total;
158
159     const size_t bytes_received =
160         Receive(static_cast<char*>(buffer) + bytes_read_total, bytes_to_read);
161     bytes_read_total += bytes_received;
162     if (bytes_received != bytes_to_read)
163       return bytes_read_total;
164   }
165
166   return bytes_read_total;
167 }
168
169 size_t SyncSocket::Peek() {
170   DCHECK(IsValid());
171   int number_chars = 0;
172   if (ioctl(handle_.get(), FIONREAD, &number_chars) == -1) {
173     // If there is an error in ioctl, signal that the channel would block.
174     return 0;
175   }
176   return checked_cast<size_t>(number_chars);
177 }
178
179 bool SyncSocket::IsValid() const {
180   return handle_.is_valid();
181 }
182
183 SyncSocket::Handle SyncSocket::handle() const {
184   return handle_.get();
185 }
186
187 SyncSocket::Handle SyncSocket::Release() {
188   return handle_.release();
189 }
190
191 bool CancelableSyncSocket::Shutdown() {
192   DCHECK(IsValid());
193   return HANDLE_EINTR(shutdown(handle(), SHUT_RDWR)) >= 0;
194 }
195
196 size_t CancelableSyncSocket::Send(const void* buffer, size_t length) {
197   DCHECK_GT(length, 0u);
198   DCHECK_LE(length, kMaxMessageLength);
199   DCHECK(IsValid());
200
201   const int flags = fcntl(handle(), F_GETFL);
202   if (flags != -1 && (flags & O_NONBLOCK) == 0) {
203     // Set the socket to non-blocking mode for sending if its original mode
204     // is blocking.
205     fcntl(handle(), F_SETFL, flags | O_NONBLOCK);
206   }
207
208   const size_t len = SendHelper(handle(), buffer, length);
209
210   if (flags != -1 && (flags & O_NONBLOCK) == 0) {
211     // Restore the original flags.
212     fcntl(handle(), F_SETFL, flags);
213   }
214
215   return len;
216 }
217
218 // static
219 bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
220                                       CancelableSyncSocket* socket_b) {
221   return SyncSocket::CreatePair(socket_a, socket_b);
222 }
223
224 }  // namespace base