sync_socket_posix.cc 6.8 KB

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