1 //===-- Socket.cpp ----------------------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Host/Socket.h"
11 #include "lldb/Host/Config.h"
12 #include "lldb/Host/Host.h"
13 #include "lldb/Host/SocketAddress.h"
14 #include "lldb/Host/StringConvert.h"
15 #include "lldb/Host/common/TCPSocket.h"
16 #include "lldb/Host/common/UDPSocket.h"
17 #include "lldb/Utility/Log.h"
18 #include "lldb/Utility/RegularExpression.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Support/Errno.h"
22 #include "llvm/Support/Error.h"
23 #include "llvm/Support/WindowsError.h"
25 #ifndef LLDB_DISABLE_POSIX
26 #include "lldb/Host/posix/DomainSocket.h"
28 #include <arpa/inet.h>
30 #include <netinet/in.h>
31 #include <netinet/tcp.h>
32 #include <sys/socket.h>
38 #include "lldb/Host/linux/AbstractSocket.h"
42 #include <arpa/inet.h>
43 #include <asm-generic/errno-base.h>
45 #include <linux/tcp.h>
47 #include <sys/syscall.h>
52 using namespace lldb_private;
55 typedef const char *set_socket_option_arg_type;
56 typedef char *get_socket_option_arg_type;
57 const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET;
58 #else // #if defined(_WIN32)
59 typedef const void *set_socket_option_arg_type;
60 typedef void *get_socket_option_arg_type;
61 const NativeSocket Socket::kInvalidSocketValue = -1;
62 #endif // #if defined(_WIN32)
66 bool IsInterrupted() {
68 return ::WSAGetLastError() == WSAEINTR;
70 return errno == EINTR;
75 Socket::Socket(SocketProtocol protocol, bool should_close,
76 bool child_processes_inherit)
77 : IOObject(eFDTypeSocket, should_close), m_protocol(protocol),
78 m_socket(kInvalidSocketValue),
79 m_child_processes_inherit(child_processes_inherit) {}
81 Socket::~Socket() { Close(); }
83 llvm::Error Socket::Initialize() {
85 auto wVersion = WINSOCK_VERSION;
87 int err = ::WSAStartup(wVersion, &wsaData);
89 if (wsaData.wVersion < wVersion) {
91 return llvm::make_error<llvm::StringError>(
92 "WSASock version is not expected.", llvm::inconvertibleErrorCode());
95 return llvm::errorCodeToError(llvm::mapWindowsError(::WSAGetLastError()));
99 return llvm::Error::success();
102 void Socket::Terminate() {
108 std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol,
109 bool child_processes_inherit,
113 std::unique_ptr<Socket> socket_up;
117 llvm::make_unique<TCPSocket>(true, child_processes_inherit);
121 llvm::make_unique<UDPSocket>(true, child_processes_inherit);
123 case ProtocolUnixDomain:
124 #ifndef LLDB_DISABLE_POSIX
126 llvm::make_unique<DomainSocket>(true, child_processes_inherit);
128 error.SetErrorString(
129 "Unix domain sockets are not supported on this platform.");
132 case ProtocolUnixAbstract:
135 llvm::make_unique<AbstractSocket>(child_processes_inherit);
137 error.SetErrorString(
138 "Abstract domain sockets are not supported on this platform.");
149 Status Socket::TcpConnect(llvm::StringRef host_and_port,
150 bool child_processes_inherit, Socket *&socket) {
151 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
153 log->Printf("Socket::%s (host/port = %s)", __FUNCTION__,
154 host_and_port.str().c_str());
157 std::unique_ptr<Socket> connect_socket(
158 Create(ProtocolTcp, child_processes_inherit, error));
162 error = connect_socket->Connect(host_and_port);
164 socket = connect_socket.release();
169 Status Socket::TcpListen(llvm::StringRef host_and_port,
170 bool child_processes_inherit, Socket *&socket,
171 Predicate<uint16_t> *predicate, int backlog) {
172 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
174 log->Printf("Socket::%s (%s)", __FUNCTION__, host_and_port.str().c_str());
177 std::string host_str;
178 std::string port_str;
179 int32_t port = INT32_MIN;
180 if (!DecodeHostAndPort(host_and_port, host_str, port_str, port, &error))
183 std::unique_ptr<TCPSocket> listen_socket(
184 new TCPSocket(true, child_processes_inherit));
188 error = listen_socket->Listen(host_and_port, backlog);
189 if (error.Success()) {
190 // We were asked to listen on port zero which means we must now read the
191 // actual port that was given to us as port zero is a special code for
192 // "find an open port for me".
194 port = listen_socket->GetLocalPortNumber();
196 // Set the port predicate since when doing a listen://<host>:<port> it
197 // often needs to accept the incoming connection which is a blocking system
198 // call. Allowing access to the bound port using a predicate allows us to
199 // wait for the port predicate to be set to a non-zero value from another
200 // thread in an efficient manor.
202 predicate->SetValue(port, eBroadcastAlways);
203 socket = listen_socket.release();
209 Status Socket::UdpConnect(llvm::StringRef host_and_port,
210 bool child_processes_inherit, Socket *&socket) {
211 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
213 log->Printf("Socket::%s (host/port = %s)", __FUNCTION__,
214 host_and_port.str().c_str());
216 return UDPSocket::Connect(host_and_port, child_processes_inherit, socket);
219 Status Socket::UnixDomainConnect(llvm::StringRef name,
220 bool child_processes_inherit,
223 std::unique_ptr<Socket> connect_socket(
224 Create(ProtocolUnixDomain, child_processes_inherit, error));
228 error = connect_socket->Connect(name);
230 socket = connect_socket.release();
235 Status Socket::UnixDomainAccept(llvm::StringRef name,
236 bool child_processes_inherit, Socket *&socket) {
238 std::unique_ptr<Socket> listen_socket(
239 Create(ProtocolUnixDomain, child_processes_inherit, error));
243 error = listen_socket->Listen(name, 5);
247 error = listen_socket->Accept(socket);
251 Status Socket::UnixAbstractConnect(llvm::StringRef name,
252 bool child_processes_inherit,
255 std::unique_ptr<Socket> connect_socket(
256 Create(ProtocolUnixAbstract, child_processes_inherit, error));
260 error = connect_socket->Connect(name);
262 socket = connect_socket.release();
266 Status Socket::UnixAbstractAccept(llvm::StringRef name,
267 bool child_processes_inherit,
270 std::unique_ptr<Socket> listen_socket(
271 Create(ProtocolUnixAbstract, child_processes_inherit, error));
275 error = listen_socket->Listen(name, 5);
279 error = listen_socket->Accept(socket);
283 bool Socket::DecodeHostAndPort(llvm::StringRef host_and_port,
284 std::string &host_str, std::string &port_str,
285 int32_t &port, Status *error_ptr) {
286 static RegularExpression g_regex(
287 llvm::StringRef("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)"));
288 RegularExpression::Match regex_match(2);
289 if (g_regex.Execute(host_and_port, ®ex_match)) {
290 if (regex_match.GetMatchAtIndex(host_and_port, 1, host_str) &&
291 regex_match.GetMatchAtIndex(host_and_port, 2, port_str)) {
292 // IPv6 addresses are wrapped in [] when specified with ports
293 if (host_str.front() == '[' && host_str.back() == ']')
294 host_str = host_str.substr(1, host_str.size() - 2);
296 port = StringConvert::ToUInt32(port_str.c_str(), UINT32_MAX, 10, &ok);
297 if (ok && port <= UINT16_MAX) {
304 error_ptr->SetErrorStringWithFormat(
305 "invalid host:port specification: '%s'",
306 host_and_port.str().c_str());
311 // If this was unsuccessful, then check if it's simply a signed 32-bit
312 // integer, representing a port with an empty host.
315 if (to_integer(host_and_port, port, 10) && port < UINT16_MAX) {
316 port_str = host_and_port;
323 error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'",
324 host_and_port.str().c_str());
328 IOObject::WaitableHandle Socket::GetWaitableHandle() {
329 // TODO: On Windows, use WSAEventSelect
333 Status Socket::Read(void *buf, size_t &num_bytes) {
335 int bytes_received = 0;
337 bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0);
338 } while (bytes_received < 0 && IsInterrupted());
340 if (bytes_received < 0) {
344 num_bytes = bytes_received;
346 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
348 log->Printf("%p Socket::Read() (socket = %" PRIu64
349 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
351 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
352 static_cast<uint64_t>(num_bytes),
353 static_cast<int64_t>(bytes_received), error.AsCString());
359 Status Socket::Write(const void *buf, size_t &num_bytes) {
363 bytes_sent = Send(buf, num_bytes);
364 } while (bytes_sent < 0 && IsInterrupted());
366 if (bytes_sent < 0) {
370 num_bytes = bytes_sent;
372 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
374 log->Printf("%p Socket::Write() (socket = %" PRIu64
375 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
377 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
378 static_cast<uint64_t>(num_bytes),
379 static_cast<int64_t>(bytes_sent), error.AsCString());
385 Status Socket::PreDisconnect() {
390 Status Socket::Close() {
392 if (!IsValid() || !m_should_close_fd)
395 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
397 log->Printf("%p Socket::Close (fd = %" PRIu64 ")",
398 static_cast<void *>(this), static_cast<uint64_t>(m_socket));
401 bool success = !!closesocket(m_socket);
403 bool success = !!::close(m_socket);
405 // A reference to a FD was passed in, set it to an invalid value
406 m_socket = kInvalidSocketValue;
414 int Socket::GetOption(int level, int option_name, int &option_value) {
415 get_socket_option_arg_type option_value_p =
416 reinterpret_cast<get_socket_option_arg_type>(&option_value);
417 socklen_t option_value_size = sizeof(int);
418 return ::getsockopt(m_socket, level, option_name, option_value_p,
422 int Socket::SetOption(int level, int option_name, int option_value) {
423 set_socket_option_arg_type option_value_p =
424 reinterpret_cast<get_socket_option_arg_type>(&option_value);
425 return ::setsockopt(m_socket, level, option_name, option_value_p,
426 sizeof(option_value));
429 size_t Socket::Send(const void *buf, const size_t num_bytes) {
430 return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0);
433 void Socket::SetLastError(Status &error) {
435 error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
437 error.SetErrorToErrno();
441 NativeSocket Socket::CreateSocket(const int domain, const int type,
443 bool child_processes_inherit, Status &error) {
445 auto socket_type = type;
447 if (!child_processes_inherit)
448 socket_type |= SOCK_CLOEXEC;
450 auto sock = ::socket(domain, socket_type, protocol);
451 if (sock == kInvalidSocketValue)
457 NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
459 bool child_processes_inherit, Status &error) {
461 #if defined(ANDROID_USE_ACCEPT_WORKAROUND)
463 // This enables static linking lldb-server to an API 21 libc, but still
464 // having it run on older devices. It is necessary because API 21 libc's
465 // implementation of accept() uses the accept4 syscall(), which is not
466 // available in older kernels. Using an older libc would fix this issue, but
467 // introduce other ones, as the old libraries were quite buggy.
468 int fd = syscall(__NR_accept, sockfd, addr, addrlen);
469 if (fd >= 0 && !child_processes_inherit) {
470 int flags = ::fcntl(fd, F_GETFD);
471 if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1)
477 #elif defined(SOCK_CLOEXEC) && defined(HAVE_ACCEPT4)
479 if (!child_processes_inherit) {
480 flags |= SOCK_CLOEXEC;
482 NativeSocket fd = llvm::sys::RetryAfterSignal(-1, ::accept4,
483 sockfd, addr, addrlen, flags);
485 NativeSocket fd = llvm::sys::RetryAfterSignal(-1, ::accept,
486 sockfd, addr, addrlen);
488 if (fd == kInvalidSocketValue)