xref: /freebsd-src/contrib/llvm-project/lldb/source/Host/common/Socket.cpp (revision 4824e7fd18a1223177218d4aec1b3c6c5c4a444e)
1 //===-- Socket.cpp --------------------------------------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Host/Socket.h"
10 
11 #include "lldb/Host/Config.h"
12 #include "lldb/Host/Host.h"
13 #include "lldb/Host/SocketAddress.h"
14 #include "lldb/Host/common/TCPSocket.h"
15 #include "lldb/Host/common/UDPSocket.h"
16 #include "lldb/Utility/Log.h"
17 
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Support/Errno.h"
20 #include "llvm/Support/Error.h"
21 #include "llvm/Support/WindowsError.h"
22 
23 #if LLDB_ENABLE_POSIX
24 #include "lldb/Host/posix/DomainSocket.h"
25 
26 #include <arpa/inet.h>
27 #include <netdb.h>
28 #include <netinet/in.h>
29 #include <netinet/tcp.h>
30 #include <sys/socket.h>
31 #include <sys/un.h>
32 #include <unistd.h>
33 #endif
34 
35 #ifdef __linux__
36 #include "lldb/Host/linux/AbstractSocket.h"
37 #endif
38 
39 #ifdef __ANDROID__
40 #include <arpa/inet.h>
41 #include <asm-generic/errno-base.h>
42 #include <cerrno>
43 #include <fcntl.h>
44 #include <linux/tcp.h>
45 #include <sys/syscall.h>
46 #include <unistd.h>
47 #endif // __ANDROID__
48 
49 using namespace lldb;
50 using namespace lldb_private;
51 
52 #if defined(_WIN32)
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)
61 
62 static bool IsInterrupted() {
63 #if defined(_WIN32)
64   return ::WSAGetLastError() == WSAEINTR;
65 #else
66   return errno == EINTR;
67 #endif
68 }
69 
70 Socket::Socket(SocketProtocol protocol, bool should_close,
71                bool child_processes_inherit)
72     : IOObject(eFDTypeSocket), m_protocol(protocol),
73       m_socket(kInvalidSocketValue),
74       m_child_processes_inherit(child_processes_inherit),
75       m_should_close_fd(should_close) {}
76 
77 Socket::~Socket() { Close(); }
78 
79 llvm::Error Socket::Initialize() {
80 #if defined(_WIN32)
81   auto wVersion = WINSOCK_VERSION;
82   WSADATA wsaData;
83   int err = ::WSAStartup(wVersion, &wsaData);
84   if (err == 0) {
85     if (wsaData.wVersion < wVersion) {
86       WSACleanup();
87       return llvm::make_error<llvm::StringError>(
88           "WSASock version is not expected.", llvm::inconvertibleErrorCode());
89     }
90   } else {
91     return llvm::errorCodeToError(llvm::mapWindowsError(::WSAGetLastError()));
92   }
93 #endif
94 
95   return llvm::Error::success();
96 }
97 
98 void Socket::Terminate() {
99 #if defined(_WIN32)
100   ::WSACleanup();
101 #endif
102 }
103 
104 std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol,
105                                        bool child_processes_inherit,
106                                        Status &error) {
107   error.Clear();
108 
109   std::unique_ptr<Socket> socket_up;
110   switch (protocol) {
111   case ProtocolTcp:
112     socket_up =
113         std::make_unique<TCPSocket>(true, child_processes_inherit);
114     break;
115   case ProtocolUdp:
116     socket_up =
117         std::make_unique<UDPSocket>(true, child_processes_inherit);
118     break;
119   case ProtocolUnixDomain:
120 #if LLDB_ENABLE_POSIX
121     socket_up =
122         std::make_unique<DomainSocket>(true, child_processes_inherit);
123 #else
124     error.SetErrorString(
125         "Unix domain sockets are not supported on this platform.");
126 #endif
127     break;
128   case ProtocolUnixAbstract:
129 #ifdef __linux__
130     socket_up =
131         std::make_unique<AbstractSocket>(child_processes_inherit);
132 #else
133     error.SetErrorString(
134         "Abstract domain sockets are not supported on this platform.");
135 #endif
136     break;
137   }
138 
139   if (error.Fail())
140     socket_up.reset();
141 
142   return socket_up;
143 }
144 
145 llvm::Expected<std::unique_ptr<Socket>>
146 Socket::TcpConnect(llvm::StringRef host_and_port,
147                    bool child_processes_inherit) {
148   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
149   LLDB_LOG(log, "host_and_port = {0}", host_and_port);
150 
151   Status error;
152   std::unique_ptr<Socket> connect_socket(
153       Create(ProtocolTcp, child_processes_inherit, error));
154   if (error.Fail())
155     return error.ToError();
156 
157   error = connect_socket->Connect(host_and_port);
158   if (error.Success())
159     return std::move(connect_socket);
160 
161   return error.ToError();
162 }
163 
164 llvm::Expected<std::unique_ptr<TCPSocket>>
165 Socket::TcpListen(llvm::StringRef host_and_port, bool child_processes_inherit,
166                   int backlog) {
167   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
168   LLDB_LOG(log, "host_and_port = {0}", host_and_port);
169 
170   std::unique_ptr<TCPSocket> listen_socket(
171       new TCPSocket(true, child_processes_inherit));
172 
173   Status error = listen_socket->Listen(host_and_port, backlog);
174   if (error.Fail())
175     return error.ToError();
176 
177   return std::move(listen_socket);
178 }
179 
180 llvm::Expected<std::unique_ptr<UDPSocket>>
181 Socket::UdpConnect(llvm::StringRef host_and_port,
182                    bool child_processes_inherit) {
183   return UDPSocket::Connect(host_and_port, child_processes_inherit);
184 }
185 
186 llvm::Expected<Socket::HostAndPort> Socket::DecodeHostAndPort(llvm::StringRef host_and_port) {
187   static llvm::Regex g_regex("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)");
188   HostAndPort ret;
189   llvm::SmallVector<llvm::StringRef, 3> matches;
190   if (g_regex.match(host_and_port, &matches)) {
191     ret.hostname = matches[1].str();
192     // IPv6 addresses are wrapped in [] when specified with ports
193     if (ret.hostname.front() == '[' && ret.hostname.back() == ']')
194       ret.hostname = ret.hostname.substr(1, ret.hostname.size() - 2);
195     if (to_integer(matches[2], ret.port, 10))
196       return ret;
197   } else {
198     // If this was unsuccessful, then check if it's simply an unsigned 16-bit
199     // integer, representing a port with an empty host.
200     if (to_integer(host_and_port, ret.port, 10))
201       return ret;
202   }
203 
204   return llvm::createStringError(llvm::inconvertibleErrorCode(),
205                                  "invalid host:port specification: '%s'",
206                                  host_and_port.str().c_str());
207 }
208 
209 IOObject::WaitableHandle Socket::GetWaitableHandle() {
210   // TODO: On Windows, use WSAEventSelect
211   return m_socket;
212 }
213 
214 Status Socket::Read(void *buf, size_t &num_bytes) {
215   Status error;
216   int bytes_received = 0;
217   do {
218     bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0);
219   } while (bytes_received < 0 && IsInterrupted());
220 
221   if (bytes_received < 0) {
222     SetLastError(error);
223     num_bytes = 0;
224   } else
225     num_bytes = bytes_received;
226 
227   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
228   if (log) {
229     LLDB_LOGF(log,
230               "%p Socket::Read() (socket = %" PRIu64
231               ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
232               " (error = %s)",
233               static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
234               static_cast<uint64_t>(num_bytes),
235               static_cast<int64_t>(bytes_received), error.AsCString());
236   }
237 
238   return error;
239 }
240 
241 Status Socket::Write(const void *buf, size_t &num_bytes) {
242   const size_t src_len = num_bytes;
243   Status error;
244   int bytes_sent = 0;
245   do {
246     bytes_sent = Send(buf, num_bytes);
247   } while (bytes_sent < 0 && IsInterrupted());
248 
249   if (bytes_sent < 0) {
250     SetLastError(error);
251     num_bytes = 0;
252   } else
253     num_bytes = bytes_sent;
254 
255   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
256   if (log) {
257     LLDB_LOGF(log,
258               "%p Socket::Write() (socket = %" PRIu64
259               ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
260               " (error = %s)",
261               static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
262               static_cast<uint64_t>(src_len),
263               static_cast<int64_t>(bytes_sent), error.AsCString());
264   }
265 
266   return error;
267 }
268 
269 Status Socket::PreDisconnect() {
270   Status error;
271   return error;
272 }
273 
274 Status Socket::Close() {
275   Status error;
276   if (!IsValid() || !m_should_close_fd)
277     return error;
278 
279   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
280   LLDB_LOGF(log, "%p Socket::Close (fd = %" PRIu64 ")",
281             static_cast<void *>(this), static_cast<uint64_t>(m_socket));
282 
283 #if defined(_WIN32)
284   bool success = !!closesocket(m_socket);
285 #else
286   bool success = !!::close(m_socket);
287 #endif
288   // A reference to a FD was passed in, set it to an invalid value
289   m_socket = kInvalidSocketValue;
290   if (!success) {
291     SetLastError(error);
292   }
293 
294   return error;
295 }
296 
297 int Socket::GetOption(int level, int option_name, int &option_value) {
298   get_socket_option_arg_type option_value_p =
299       reinterpret_cast<get_socket_option_arg_type>(&option_value);
300   socklen_t option_value_size = sizeof(int);
301   return ::getsockopt(m_socket, level, option_name, option_value_p,
302                       &option_value_size);
303 }
304 
305 int Socket::SetOption(int level, int option_name, int option_value) {
306   set_socket_option_arg_type option_value_p =
307       reinterpret_cast<get_socket_option_arg_type>(&option_value);
308   return ::setsockopt(m_socket, level, option_name, option_value_p,
309                       sizeof(option_value));
310 }
311 
312 size_t Socket::Send(const void *buf, const size_t num_bytes) {
313   return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0);
314 }
315 
316 void Socket::SetLastError(Status &error) {
317 #if defined(_WIN32)
318   error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
319 #else
320   error.SetErrorToErrno();
321 #endif
322 }
323 
324 NativeSocket Socket::CreateSocket(const int domain, const int type,
325                                   const int protocol,
326                                   bool child_processes_inherit, Status &error) {
327   error.Clear();
328   auto socket_type = type;
329 #ifdef SOCK_CLOEXEC
330   if (!child_processes_inherit)
331     socket_type |= SOCK_CLOEXEC;
332 #endif
333   auto sock = ::socket(domain, socket_type, protocol);
334   if (sock == kInvalidSocketValue)
335     SetLastError(error);
336 
337   return sock;
338 }
339 
340 NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
341                                   socklen_t *addrlen,
342                                   bool child_processes_inherit, Status &error) {
343   error.Clear();
344 #if defined(ANDROID_USE_ACCEPT_WORKAROUND)
345   // Hack:
346   // This enables static linking lldb-server to an API 21 libc, but still
347   // having it run on older devices. It is necessary because API 21 libc's
348   // implementation of accept() uses the accept4 syscall(), which is not
349   // available in older kernels. Using an older libc would fix this issue, but
350   // introduce other ones, as the old libraries were quite buggy.
351   int fd = syscall(__NR_accept, sockfd, addr, addrlen);
352   if (fd >= 0 && !child_processes_inherit) {
353     int flags = ::fcntl(fd, F_GETFD);
354     if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1)
355       return fd;
356     SetLastError(error);
357     close(fd);
358   }
359   return fd;
360 #elif defined(SOCK_CLOEXEC) && defined(HAVE_ACCEPT4)
361   int flags = 0;
362   if (!child_processes_inherit) {
363     flags |= SOCK_CLOEXEC;
364   }
365   NativeSocket fd = llvm::sys::RetryAfterSignal(
366       static_cast<NativeSocket>(-1), ::accept4, sockfd, addr, addrlen, flags);
367 #else
368   NativeSocket fd = llvm::sys::RetryAfterSignal(
369       static_cast<NativeSocket>(-1), ::accept, sockfd, addr, addrlen);
370 #endif
371   if (fd == kInvalidSocketValue)
372     SetLastError(error);
373   return fd;
374 }
375 
376 llvm::raw_ostream &lldb_private::operator<<(llvm::raw_ostream &OS,
377                                             const Socket::HostAndPort &HP) {
378   return OS << '[' << HP.hostname << ']' << ':' << HP.port;
379 }
380