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 must now read the
164 // actual port that was given to us as port zero is a special code for
165 // "find an open port for me".
167 port = listen_socket->GetLocalPortNumber();
169 // Set the port predicate since when doing a listen://<host>:<port> it
170 // often needs to accept the incoming connection which is a blocking system
171 // call. Allowing access to the bound port using a predicate allows us to
172 // wait for the port predicate to be set to a non-zero value from another
173 // thread in an efficient manor.
175 predicate->SetValue(port, eBroadcastAlways);
176 socket = listen_socket.release();
182 Status Socket::UdpConnect(llvm::StringRef host_and_port,
183 bool child_processes_inherit, Socket *&socket) {
184 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
186 log->Printf("Socket::%s (host/port = %s)", __FUNCTION__,
187 host_and_port.data());
189 return UDPSocket::Connect(host_and_port, child_processes_inherit, socket);
192 Status Socket::UnixDomainConnect(llvm::StringRef name,
193 bool child_processes_inherit,
196 std::unique_ptr<Socket> connect_socket(
197 Create(ProtocolUnixDomain, child_processes_inherit, error));
201 error = connect_socket->Connect(name);
203 socket = connect_socket.release();
208 Status Socket::UnixDomainAccept(llvm::StringRef name,
209 bool child_processes_inherit, Socket *&socket) {
211 std::unique_ptr<Socket> listen_socket(
212 Create(ProtocolUnixDomain, child_processes_inherit, error));
216 error = listen_socket->Listen(name, 5);
220 error = listen_socket->Accept(socket);
224 Status Socket::UnixAbstractConnect(llvm::StringRef name,
225 bool child_processes_inherit,
228 std::unique_ptr<Socket> connect_socket(
229 Create(ProtocolUnixAbstract, child_processes_inherit, error));
233 error = connect_socket->Connect(name);
235 socket = connect_socket.release();
239 Status Socket::UnixAbstractAccept(llvm::StringRef name,
240 bool child_processes_inherit,
243 std::unique_ptr<Socket> listen_socket(
244 Create(ProtocolUnixAbstract, child_processes_inherit, error));
248 error = listen_socket->Listen(name, 5);
252 error = listen_socket->Accept(socket);
256 bool Socket::DecodeHostAndPort(llvm::StringRef host_and_port,
257 std::string &host_str, std::string &port_str,
258 int32_t &port, Status *error_ptr) {
259 static RegularExpression g_regex(
260 llvm::StringRef("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)"));
261 RegularExpression::Match regex_match(2);
262 if (g_regex.Execute(host_and_port, ®ex_match)) {
263 if (regex_match.GetMatchAtIndex(host_and_port.data(), 1, host_str) &&
264 regex_match.GetMatchAtIndex(host_and_port.data(), 2, port_str)) {
265 // IPv6 addresses are wrapped in [] when specified with ports
266 if (host_str.front() == '[' && host_str.back() == ']')
267 host_str = host_str.substr(1, host_str.size() - 2);
269 port = StringConvert::ToUInt32(port_str.c_str(), UINT32_MAX, 10, &ok);
270 if (ok && port <= UINT16_MAX) {
277 error_ptr->SetErrorStringWithFormat(
278 "invalid host:port specification: '%s'", host_and_port.data());
283 // If this was unsuccessful, then check if it's simply a signed 32-bit
284 // integer, representing a port with an empty host.
288 port = StringConvert::ToUInt32(host_and_port.data(), UINT32_MAX, 10, &ok);
289 if (ok && port < UINT16_MAX) {
290 port_str = host_and_port;
297 error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'",
298 host_and_port.data());
302 IOObject::WaitableHandle Socket::GetWaitableHandle() {
303 // TODO: On Windows, use WSAEventSelect
307 Status Socket::Read(void *buf, size_t &num_bytes) {
309 int bytes_received = 0;
311 bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0);
312 } while (bytes_received < 0 && IsInterrupted());
314 if (bytes_received < 0) {
318 num_bytes = bytes_received;
320 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
322 log->Printf("%p Socket::Read() (socket = %" PRIu64
323 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
325 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
326 static_cast<uint64_t>(num_bytes),
327 static_cast<int64_t>(bytes_received), error.AsCString());
333 Status Socket::Write(const void *buf, size_t &num_bytes) {
337 bytes_sent = Send(buf, num_bytes);
338 } while (bytes_sent < 0 && IsInterrupted());
340 if (bytes_sent < 0) {
344 num_bytes = bytes_sent;
346 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
348 log->Printf("%p Socket::Write() (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_sent), error.AsCString());
359 Status Socket::PreDisconnect() {
364 Status Socket::Close() {
366 if (!IsValid() || !m_should_close_fd)
369 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
371 log->Printf("%p Socket::Close (fd = %i)", static_cast<void *>(this),
375 bool success = !!closesocket(m_socket);
377 bool success = !!::close(m_socket);
379 // A reference to a FD was passed in, set it to an invalid value
380 m_socket = kInvalidSocketValue;
388 int Socket::GetOption(int level, int option_name, int &option_value) {
389 get_socket_option_arg_type option_value_p =
390 reinterpret_cast<get_socket_option_arg_type>(&option_value);
391 socklen_t option_value_size = sizeof(int);
392 return ::getsockopt(m_socket, level, option_name, option_value_p,
396 int Socket::SetOption(int level, int option_name, int option_value) {
397 set_socket_option_arg_type option_value_p =
398 reinterpret_cast<get_socket_option_arg_type>(&option_value);
399 return ::setsockopt(m_socket, level, option_name, option_value_p,
400 sizeof(option_value));
403 size_t Socket::Send(const void *buf, const size_t num_bytes) {
404 return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0);
407 void Socket::SetLastError(Status &error) {
409 error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
411 error.SetErrorToErrno();
415 NativeSocket Socket::CreateSocket(const int domain, const int type,
417 bool child_processes_inherit, Status &error) {
419 auto socket_type = type;
421 if (!child_processes_inherit)
422 socket_type |= SOCK_CLOEXEC;
424 auto sock = ::socket(domain, socket_type, protocol);
425 if (sock == kInvalidSocketValue)
431 NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
433 bool child_processes_inherit, Status &error) {
435 #if defined(ANDROID_USE_ACCEPT_WORKAROUND)
437 // This enables static linking lldb-server to an API 21 libc, but still
438 // having it run on older devices. It is necessary because API 21 libc's
439 // implementation of accept() uses the accept4 syscall(), which is not
440 // available in older kernels. Using an older libc would fix this issue, but
441 // introduce other ones, as the old libraries were quite buggy.
442 int fd = syscall(__NR_accept, sockfd, addr, addrlen);
443 if (fd >= 0 && !child_processes_inherit) {
444 int flags = ::fcntl(fd, F_GETFD);
445 if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1)
451 #elif defined(SOCK_CLOEXEC) && defined(HAVE_ACCEPT4)
453 if (!child_processes_inherit) {
454 flags |= SOCK_CLOEXEC;
456 NativeSocket fd = ::accept4(sockfd, addr, addrlen, flags);
458 NativeSocket fd = ::accept(sockfd, addr, addrlen);
460 if (fd == kInvalidSocketValue)