1 //===-- Socket.cpp ----------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Host/Socket.h"
12 #include "lldb/Host/Config.h"
13 #include "lldb/Host/Host.h"
14 #include "lldb/Host/SocketAddress.h"
15 #include "lldb/Host/StringConvert.h"
16 #include "lldb/Host/common/TCPSocket.h"
17 #include "lldb/Host/common/UDPSocket.h"
18 #include "lldb/Utility/Log.h"
19 #include "lldb/Utility/RegularExpression.h"
21 #include "llvm/ADT/STLExtras.h"
23 #ifndef LLDB_DISABLE_POSIX
24 #include "lldb/Host/posix/DomainSocket.h"
26 #include <arpa/inet.h>
28 #include <netinet/in.h>
29 #include <netinet/tcp.h>
30 #include <sys/socket.h>
36 #include "lldb/Host/linux/AbstractSocket.h"
40 #include <arpa/inet.h>
41 #include <asm-generic/errno-base.h>
43 #include <linux/tcp.h>
45 #include <sys/syscall.h>
50 using namespace lldb_private;
53 typedef const char *set_socket_option_arg_type;
54 typedef char *get_socket_option_arg_type;
55 const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET;
56 #else // #if defined(_WIN32)
57 typedef const void *set_socket_option_arg_type;
58 typedef void *get_socket_option_arg_type;
59 const NativeSocket Socket::kInvalidSocketValue = -1;
60 #endif // #if defined(_WIN32)
64 bool IsInterrupted() {
66 return ::WSAGetLastError() == WSAEINTR;
68 return errno == EINTR;
73 Socket::Socket(SocketProtocol protocol, bool should_close,
74 bool child_processes_inherit)
75 : IOObject(eFDTypeSocket, should_close), m_protocol(protocol),
76 m_socket(kInvalidSocketValue),
77 m_child_processes_inherit(child_processes_inherit) {}
79 Socket::~Socket() { Close(); }
81 std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol,
82 bool child_processes_inherit,
86 std::unique_ptr<Socket> socket_up;
90 llvm::make_unique<TCPSocket>(true, child_processes_inherit);
94 llvm::make_unique<UDPSocket>(true, child_processes_inherit);
96 case ProtocolUnixDomain:
97 #ifndef LLDB_DISABLE_POSIX
99 llvm::make_unique<DomainSocket>(true, child_processes_inherit);
101 error.SetErrorString(
102 "Unix domain sockets are not supported on this platform.");
105 case ProtocolUnixAbstract:
108 llvm::make_unique<AbstractSocket>(child_processes_inherit);
110 error.SetErrorString(
111 "Abstract domain sockets are not supported on this platform.");
122 Status Socket::TcpConnect(llvm::StringRef host_and_port,
123 bool child_processes_inherit, Socket *&socket) {
124 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
126 log->Printf("Socket::%s (host/port = %s)", __FUNCTION__,
127 host_and_port.data());
130 std::unique_ptr<Socket> connect_socket(
131 Create(ProtocolTcp, child_processes_inherit, error));
135 error = connect_socket->Connect(host_and_port);
137 socket = connect_socket.release();
142 Status Socket::TcpListen(llvm::StringRef host_and_port,
143 bool child_processes_inherit, Socket *&socket,
144 Predicate<uint16_t> *predicate, int backlog) {
145 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
147 log->Printf("Socket::%s (%s)", __FUNCTION__, host_and_port.data());
150 std::string host_str;
151 std::string port_str;
152 int32_t port = INT32_MIN;
153 if (!DecodeHostAndPort(host_and_port, host_str, port_str, port, &error))
156 std::unique_ptr<TCPSocket> listen_socket(
157 new TCPSocket(true, child_processes_inherit));
161 error = listen_socket->Listen(host_and_port, backlog);
162 if (error.Success()) {
163 // We were asked to listen on port zero which means we
164 // must now read the actual port that was given to us
165 // as port zero is a special code for "find an open port
168 port = listen_socket->GetLocalPortNumber();
170 // Set the port predicate since when doing a listen://<host>:<port>
171 // it often needs to accept the incoming connection which is a blocking
172 // system call. Allowing access to the bound port using a predicate allows
173 // us to wait for the port predicate to be set to a non-zero value from
174 // another thread in an efficient manor.
176 predicate->SetValue(port, eBroadcastAlways);
177 socket = listen_socket.release();
183 Status Socket::UdpConnect(llvm::StringRef host_and_port,
184 bool child_processes_inherit, Socket *&socket) {
185 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
187 log->Printf("Socket::%s (host/port = %s)", __FUNCTION__,
188 host_and_port.data());
190 return UDPSocket::Connect(host_and_port, child_processes_inherit, socket);
193 Status Socket::UnixDomainConnect(llvm::StringRef name,
194 bool child_processes_inherit,
197 std::unique_ptr<Socket> connect_socket(
198 Create(ProtocolUnixDomain, child_processes_inherit, error));
202 error = connect_socket->Connect(name);
204 socket = connect_socket.release();
209 Status Socket::UnixDomainAccept(llvm::StringRef name,
210 bool child_processes_inherit, Socket *&socket) {
212 std::unique_ptr<Socket> listen_socket(
213 Create(ProtocolUnixDomain, child_processes_inherit, error));
217 error = listen_socket->Listen(name, 5);
221 error = listen_socket->Accept(socket);
225 Status Socket::UnixAbstractConnect(llvm::StringRef name,
226 bool child_processes_inherit,
229 std::unique_ptr<Socket> connect_socket(
230 Create(ProtocolUnixAbstract, child_processes_inherit, error));
234 error = connect_socket->Connect(name);
236 socket = connect_socket.release();
240 Status Socket::UnixAbstractAccept(llvm::StringRef name,
241 bool child_processes_inherit,
244 std::unique_ptr<Socket> listen_socket(
245 Create(ProtocolUnixAbstract, child_processes_inherit, error));
249 error = listen_socket->Listen(name, 5);
253 error = listen_socket->Accept(socket);
257 bool Socket::DecodeHostAndPort(llvm::StringRef host_and_port,
258 std::string &host_str, std::string &port_str,
259 int32_t &port, Status *error_ptr) {
260 static RegularExpression g_regex(
261 llvm::StringRef("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)"));
262 RegularExpression::Match regex_match(2);
263 if (g_regex.Execute(host_and_port, ®ex_match)) {
264 if (regex_match.GetMatchAtIndex(host_and_port.data(), 1, host_str) &&
265 regex_match.GetMatchAtIndex(host_and_port.data(), 2, port_str)) {
266 // IPv6 addresses are wrapped in [] when specified with ports
267 if (host_str.front() == '[' && host_str.back() == ']')
268 host_str = host_str.substr(1, host_str.size() - 2);
270 port = StringConvert::ToUInt32(port_str.c_str(), UINT32_MAX, 10, &ok);
271 if (ok && port <= UINT16_MAX) {
278 error_ptr->SetErrorStringWithFormat(
279 "invalid host:port specification: '%s'", host_and_port.data());
284 // If this was unsuccessful, then check if it's simply a signed 32-bit
285 // integer, representing
286 // a port with an empty host.
290 port = StringConvert::ToUInt32(host_and_port.data(), UINT32_MAX, 10, &ok);
291 if (ok && port < UINT16_MAX) {
292 port_str = host_and_port;
299 error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'",
300 host_and_port.data());
304 IOObject::WaitableHandle Socket::GetWaitableHandle() {
305 // TODO: On Windows, use WSAEventSelect
309 Status Socket::Read(void *buf, size_t &num_bytes) {
311 int bytes_received = 0;
313 bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0);
314 } while (bytes_received < 0 && IsInterrupted());
316 if (bytes_received < 0) {
320 num_bytes = bytes_received;
322 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
324 log->Printf("%p Socket::Read() (socket = %" PRIu64
325 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
327 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
328 static_cast<uint64_t>(num_bytes),
329 static_cast<int64_t>(bytes_received), error.AsCString());
335 Status Socket::Write(const void *buf, size_t &num_bytes) {
339 bytes_sent = Send(buf, num_bytes);
340 } while (bytes_sent < 0 && IsInterrupted());
342 if (bytes_sent < 0) {
346 num_bytes = bytes_sent;
348 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
350 log->Printf("%p Socket::Write() (socket = %" PRIu64
351 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
353 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
354 static_cast<uint64_t>(num_bytes),
355 static_cast<int64_t>(bytes_sent), error.AsCString());
361 Status Socket::PreDisconnect() {
366 Status Socket::Close() {
368 if (!IsValid() || !m_should_close_fd)
371 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
373 log->Printf("%p Socket::Close (fd = %i)", static_cast<void *>(this),
377 bool success = !!closesocket(m_socket);
379 bool success = !!::close(m_socket);
381 // A reference to a FD was passed in, set it to an invalid value
382 m_socket = kInvalidSocketValue;
390 int Socket::GetOption(int level, int option_name, int &option_value) {
391 get_socket_option_arg_type option_value_p =
392 reinterpret_cast<get_socket_option_arg_type>(&option_value);
393 socklen_t option_value_size = sizeof(int);
394 return ::getsockopt(m_socket, level, option_name, option_value_p,
398 int Socket::SetOption(int level, int option_name, int option_value) {
399 set_socket_option_arg_type option_value_p =
400 reinterpret_cast<get_socket_option_arg_type>(&option_value);
401 return ::setsockopt(m_socket, level, option_name, option_value_p,
402 sizeof(option_value));
405 size_t Socket::Send(const void *buf, const size_t num_bytes) {
406 return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0);
409 void Socket::SetLastError(Status &error) {
411 error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
413 error.SetErrorToErrno();
417 NativeSocket Socket::CreateSocket(const int domain, const int type,
419 bool child_processes_inherit, Status &error) {
421 auto socket_type = type;
423 if (!child_processes_inherit)
424 socket_type |= SOCK_CLOEXEC;
426 auto sock = ::socket(domain, socket_type, protocol);
427 if (sock == kInvalidSocketValue)
433 NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
435 bool child_processes_inherit, Status &error) {
437 #if defined(ANDROID_USE_ACCEPT_WORKAROUND)
439 // This enables static linking lldb-server to an API 21 libc, but still having
440 // it run on older devices. It is necessary because API 21 libc's
441 // implementation of accept() uses the accept4 syscall(), which is not
442 // available in older kernels. Using an older libc would fix this issue, but
443 // introduce other ones, as the old libraries were quite buggy.
444 int fd = syscall(__NR_accept, sockfd, addr, addrlen);
445 if (fd >= 0 && !child_processes_inherit) {
446 int flags = ::fcntl(fd, F_GETFD);
447 if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1)
453 #elif defined(SOCK_CLOEXEC)
455 if (!child_processes_inherit) {
456 flags |= SOCK_CLOEXEC;
458 NativeSocket fd = ::accept4(sockfd, addr, addrlen, flags);
460 NativeSocket fd = ::accept(sockfd, addr, addrlen);
462 if (fd == kInvalidSocketValue)