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::Error Socket::DecodeHostAndPort(llvm::StringRef host_and_port,
187                                       std::string &host_str,
188                                       std::string &port_str, uint16_t &port) {
189   static llvm::Regex g_regex("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)");
190   llvm::SmallVector<llvm::StringRef, 3> matches;
191   if (g_regex.match(host_and_port, &matches)) {
192     host_str = matches[1].str();
193     port_str = matches[2].str();
194     // IPv6 addresses are wrapped in [] when specified with ports
195     if (host_str.front() == '[' && host_str.back() == ']')
196       host_str = host_str.substr(1, host_str.size() - 2);
197     if (to_integer(matches[2], port, 10))
198       return llvm::Error::success();
199   } else {
200     // If this was unsuccessful, then check if it's simply a signed 32-bit
201     // integer, representing a port with an empty host.
202     host_str.clear();
203     port_str.clear();
204     if (to_integer(host_and_port, port, 10)) {
205       port_str = host_and_port.str();
206       return llvm::Error::success();
207     }
208   }
209 
210   return llvm::createStringError(llvm::inconvertibleErrorCode(),
211                                  "invalid host:port specification: '%s'",
212                                  host_and_port.str().c_str());
213 }
214 
215 IOObject::WaitableHandle Socket::GetWaitableHandle() {
216   // TODO: On Windows, use WSAEventSelect
217   return m_socket;
218 }
219 
220 Status Socket::Read(void *buf, size_t &num_bytes) {
221   Status error;
222   int bytes_received = 0;
223   do {
224     bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0);
225   } while (bytes_received < 0 && IsInterrupted());
226 
227   if (bytes_received < 0) {
228     SetLastError(error);
229     num_bytes = 0;
230   } else
231     num_bytes = bytes_received;
232 
233   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
234   if (log) {
235     LLDB_LOGF(log,
236               "%p Socket::Read() (socket = %" PRIu64
237               ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
238               " (error = %s)",
239               static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
240               static_cast<uint64_t>(num_bytes),
241               static_cast<int64_t>(bytes_received), error.AsCString());
242   }
243 
244   return error;
245 }
246 
247 Status Socket::Write(const void *buf, size_t &num_bytes) {
248   const size_t src_len = num_bytes;
249   Status error;
250   int bytes_sent = 0;
251   do {
252     bytes_sent = Send(buf, num_bytes);
253   } while (bytes_sent < 0 && IsInterrupted());
254 
255   if (bytes_sent < 0) {
256     SetLastError(error);
257     num_bytes = 0;
258   } else
259     num_bytes = bytes_sent;
260 
261   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
262   if (log) {
263     LLDB_LOGF(log,
264               "%p Socket::Write() (socket = %" PRIu64
265               ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
266               " (error = %s)",
267               static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
268               static_cast<uint64_t>(src_len),
269               static_cast<int64_t>(bytes_sent), error.AsCString());
270   }
271 
272   return error;
273 }
274 
275 Status Socket::PreDisconnect() {
276   Status error;
277   return error;
278 }
279 
280 Status Socket::Close() {
281   Status error;
282   if (!IsValid() || !m_should_close_fd)
283     return error;
284 
285   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
286   LLDB_LOGF(log, "%p Socket::Close (fd = %" PRIu64 ")",
287             static_cast<void *>(this), static_cast<uint64_t>(m_socket));
288 
289 #if defined(_WIN32)
290   bool success = !!closesocket(m_socket);
291 #else
292   bool success = !!::close(m_socket);
293 #endif
294   // A reference to a FD was passed in, set it to an invalid value
295   m_socket = kInvalidSocketValue;
296   if (!success) {
297     SetLastError(error);
298   }
299 
300   return error;
301 }
302 
303 int Socket::GetOption(int level, int option_name, int &option_value) {
304   get_socket_option_arg_type option_value_p =
305       reinterpret_cast<get_socket_option_arg_type>(&option_value);
306   socklen_t option_value_size = sizeof(int);
307   return ::getsockopt(m_socket, level, option_name, option_value_p,
308                       &option_value_size);
309 }
310 
311 int Socket::SetOption(int level, int option_name, int option_value) {
312   set_socket_option_arg_type option_value_p =
313       reinterpret_cast<get_socket_option_arg_type>(&option_value);
314   return ::setsockopt(m_socket, level, option_name, option_value_p,
315                       sizeof(option_value));
316 }
317 
318 size_t Socket::Send(const void *buf, const size_t num_bytes) {
319   return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0);
320 }
321 
322 void Socket::SetLastError(Status &error) {
323 #if defined(_WIN32)
324   error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
325 #else
326   error.SetErrorToErrno();
327 #endif
328 }
329 
330 NativeSocket Socket::CreateSocket(const int domain, const int type,
331                                   const int protocol,
332                                   bool child_processes_inherit, Status &error) {
333   error.Clear();
334   auto socket_type = type;
335 #ifdef SOCK_CLOEXEC
336   if (!child_processes_inherit)
337     socket_type |= SOCK_CLOEXEC;
338 #endif
339   auto sock = ::socket(domain, socket_type, protocol);
340   if (sock == kInvalidSocketValue)
341     SetLastError(error);
342 
343   return sock;
344 }
345 
346 NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
347                                   socklen_t *addrlen,
348                                   bool child_processes_inherit, Status &error) {
349   error.Clear();
350 #if defined(ANDROID_USE_ACCEPT_WORKAROUND)
351   // Hack:
352   // This enables static linking lldb-server to an API 21 libc, but still
353   // having it run on older devices. It is necessary because API 21 libc's
354   // implementation of accept() uses the accept4 syscall(), which is not
355   // available in older kernels. Using an older libc would fix this issue, but
356   // introduce other ones, as the old libraries were quite buggy.
357   int fd = syscall(__NR_accept, sockfd, addr, addrlen);
358   if (fd >= 0 && !child_processes_inherit) {
359     int flags = ::fcntl(fd, F_GETFD);
360     if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1)
361       return fd;
362     SetLastError(error);
363     close(fd);
364   }
365   return fd;
366 #elif defined(SOCK_CLOEXEC) && defined(HAVE_ACCEPT4)
367   int flags = 0;
368   if (!child_processes_inherit) {
369     flags |= SOCK_CLOEXEC;
370   }
371   NativeSocket fd = llvm::sys::RetryAfterSignal(
372       static_cast<NativeSocket>(-1), ::accept4, sockfd, addr, addrlen, flags);
373 #else
374   NativeSocket fd = llvm::sys::RetryAfterSignal(
375       static_cast<NativeSocket>(-1), ::accept, sockfd, addr, addrlen);
376 #endif
377   if (fd == kInvalidSocketValue)
378     SetLastError(error);
379   return fd;
380 }
381