• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
SendHelper(SyncSocket::Handle handle,span<const uint8_t> data)37 size_t SendHelper(SyncSocket::Handle handle, span<const uint8_t> data) {
38   CHECK_LE(data.size(), kMaxMessageLength);
39   DCHECK_NE(handle, SyncSocket::kInvalidHandle);
40   return WriteFileDescriptor(handle, data) ? data.size() : 0;
41 }
42 
43 }  // namespace
44 
45 // static
CreatePair(SyncSocket * socket_a,SyncSocket * socket_b)46 bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
47   DCHECK_NE(socket_a, socket_b);
48   DCHECK(!socket_a->IsValid());
49   DCHECK(!socket_b->IsValid());
50 
51 #if BUILDFLAG(IS_APPLE)
52   int nosigpipe = 1;
53 #endif  // BUILDFLAG(IS_APPLE)
54 
55   ScopedHandle handles[2];
56 
57   {
58     Handle raw_handles[2] = {kInvalidHandle, kInvalidHandle};
59     if (socketpair(AF_UNIX, SOCK_STREAM, 0, raw_handles) != 0) {
60       return false;
61     }
62     handles[0].reset(raw_handles[0]);
63     handles[1].reset(raw_handles[1]);
64   }
65 
66 #if BUILDFLAG(IS_APPLE)
67   // On OSX an attempt to read or write to a closed socket may generate a
68   // SIGPIPE rather than returning -1.  setsockopt will shut this off.
69   if (0 != setsockopt(handles[0].get(), SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe,
70                       sizeof(nosigpipe)) ||
71       0 != setsockopt(handles[1].get(), SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe,
72                       sizeof(nosigpipe))) {
73     return false;
74   }
75 #endif
76 
77   // Copy the handles out for successful return.
78   socket_a->handle_ = std::move(handles[0]);
79   socket_b->handle_ = std::move(handles[1]);
80 
81   return true;
82 }
83 
Close()84 void SyncSocket::Close() {
85   handle_.reset();
86 }
87 
Send(span<const uint8_t> data)88 size_t SyncSocket::Send(span<const uint8_t> data) {
89   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
90   return SendHelper(handle(), data);
91 }
92 
Receive(span<uint8_t> buffer)93 size_t SyncSocket::Receive(span<uint8_t> buffer) {
94   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
95   CHECK_LE(buffer.size(), kMaxMessageLength);
96   DCHECK(IsValid());
97   if (ReadFromFD(handle(), as_writable_chars(buffer))) {
98     return buffer.size();
99   }
100   return 0;
101 }
102 
ReceiveWithTimeout(span<uint8_t> buffer,TimeDelta timeout)103 size_t SyncSocket::ReceiveWithTimeout(span<uint8_t> buffer, TimeDelta timeout) {
104   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
105   CHECK_LE(buffer.size(), kMaxMessageLength);
106   DCHECK(IsValid());
107 
108   // Only timeouts greater than zero and less than one second are allowed.
109   DCHECK_GT(timeout.InMicroseconds(), 0);
110   DCHECK_LT(timeout.InMicroseconds(), Seconds(1).InMicroseconds());
111 
112   // Track the start time so we can reduce the timeout as data is read.
113   TimeTicks start_time = TimeTicks::Now();
114   const TimeTicks finish_time = start_time + timeout;
115 
116   struct pollfd pollfd;
117   pollfd.fd = handle();
118   pollfd.events = POLLIN;
119   pollfd.revents = 0;
120 
121   size_t bytes_read_total = 0;
122   while (!buffer.empty()) {
123     const TimeDelta this_timeout = finish_time - TimeTicks::Now();
124     const int timeout_ms =
125         static_cast<int>(this_timeout.InMillisecondsRoundedUp());
126     if (timeout_ms <= 0)
127       break;
128     const int poll_result = poll(&pollfd, 1, timeout_ms);
129     // Handle EINTR manually since we need to update the timeout value.
130     if (poll_result == -1 && errno == EINTR)
131       continue;
132     // Return if other type of error or a timeout.
133     if (poll_result <= 0)
134       return bytes_read_total;
135 
136     // poll() only tells us that data is ready for reading, not how much.  We
137     // must Peek() for the amount ready for reading to avoid blocking.
138     // At hang up (POLLHUP), the write end has been closed and there might still
139     // be data to be read.
140     // No special handling is needed for error (POLLERR); we can let any of the
141     // following operations fail and handle it there.
142     DCHECK(pollfd.revents & (POLLIN | POLLHUP | POLLERR)) << pollfd.revents;
143     const size_t bytes_to_read = std::min(Peek(), buffer.size());
144 
145     // There may be zero bytes to read if the socket at the other end closed.
146     if (!bytes_to_read)
147       return bytes_read_total;
148 
149     const size_t bytes_received = Receive(buffer.subspan(0u, bytes_to_read));
150     bytes_read_total += bytes_received;
151     buffer = buffer.subspan(bytes_received);
152     if (bytes_received != bytes_to_read)
153       return bytes_read_total;
154   }
155 
156   return bytes_read_total;
157 }
158 
Peek()159 size_t SyncSocket::Peek() {
160   DCHECK(IsValid());
161   int number_chars = 0;
162   if (ioctl(handle_.get(), FIONREAD, &number_chars) == -1) {
163     // If there is an error in ioctl, signal that the channel would block.
164     return 0;
165   }
166   return checked_cast<size_t>(number_chars);
167 }
168 
IsValid() const169 bool SyncSocket::IsValid() const {
170   return handle_.is_valid();
171 }
172 
handle() const173 SyncSocket::Handle SyncSocket::handle() const {
174   return handle_.get();
175 }
176 
Release()177 SyncSocket::Handle SyncSocket::Release() {
178   return handle_.release();
179 }
180 
Shutdown()181 bool CancelableSyncSocket::Shutdown() {
182   DCHECK(IsValid());
183   return HANDLE_EINTR(shutdown(handle(), SHUT_RDWR)) >= 0;
184 }
185 
Send(span<const uint8_t> data)186 size_t CancelableSyncSocket::Send(span<const uint8_t> data) {
187   CHECK_LE(data.size(), kMaxMessageLength);
188   DCHECK(IsValid());
189 
190   const int flags = fcntl(handle(), F_GETFL);
191   if (flags != -1 && (flags & O_NONBLOCK) == 0) {
192     // Set the socket to non-blocking mode for sending if its original mode
193     // is blocking.
194     fcntl(handle(), F_SETFL, flags | O_NONBLOCK);
195   }
196 
197   const size_t len = SendHelper(handle(), data);
198 
199   if (flags != -1 && (flags & O_NONBLOCK) == 0) {
200     // Restore the original flags.
201     fcntl(handle(), F_SETFL, flags);
202   }
203 
204   return len;
205 }
206 
207 // static
CreatePair(CancelableSyncSocket * socket_a,CancelableSyncSocket * socket_b)208 bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
209                                       CancelableSyncSocket* socket_b) {
210   return SyncSocket::CreatePair(socket_a, socket_b);
211 }
212 
213 }  // namespace base
214