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 namespace {
63 
64 bool IsInterrupted() {
65 #if defined(_WIN32)
66   return ::WSAGetLastError() == WSAEINTR;
67 #else
68   return errno == EINTR;
69 #endif
70 }
71 }
72 
73 Socket::Socket(SocketProtocol protocol, bool should_close,
74                bool child_processes_inherit)
75     : IOObject(eFDTypeSocket), m_protocol(protocol),
76       m_socket(kInvalidSocketValue),
77       m_child_processes_inherit(child_processes_inherit),
78       m_should_close_fd(should_close) {}
79 
80 Socket::~Socket() { Close(); }
81 
82 llvm::Error Socket::Initialize() {
83 #if defined(_WIN32)
84   auto wVersion = WINSOCK_VERSION;
85   WSADATA wsaData;
86   int err = ::WSAStartup(wVersion, &wsaData);
87   if (err == 0) {
88     if (wsaData.wVersion < wVersion) {
89       WSACleanup();
90       return llvm::make_error<llvm::StringError>(
91           "WSASock version is not expected.", llvm::inconvertibleErrorCode());
92     }
93   } else {
94     return llvm::errorCodeToError(llvm::mapWindowsError(::WSAGetLastError()));
95   }
96 #endif
97 
98   return llvm::Error::success();
99 }
100 
101 void Socket::Terminate() {
102 #if defined(_WIN32)
103   ::WSACleanup();
104 #endif
105 }
106 
107 std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol,
108                                        bool child_processes_inherit,
109                                        Status &error) {
110   error.Clear();
111 
112   std::unique_ptr<Socket> socket_up;
113   switch (protocol) {
114   case ProtocolTcp:
115     socket_up =
116         std::make_unique<TCPSocket>(true, child_processes_inherit);
117     break;
118   case ProtocolUdp:
119     socket_up =
120         std::make_unique<UDPSocket>(true, child_processes_inherit);
121     break;
122   case ProtocolUnixDomain:
123 #if LLDB_ENABLE_POSIX
124     socket_up =
125         std::make_unique<DomainSocket>(true, child_processes_inherit);
126 #else
127     error.SetErrorString(
128         "Unix domain sockets are not supported on this platform.");
129 #endif
130     break;
131   case ProtocolUnixAbstract:
132 #ifdef __linux__
133     socket_up =
134         std::make_unique<AbstractSocket>(child_processes_inherit);
135 #else
136     error.SetErrorString(
137         "Abstract domain sockets are not supported on this platform.");
138 #endif
139     break;
140   }
141 
142   if (error.Fail())
143     socket_up.reset();
144 
145   return socket_up;
146 }
147 
148 llvm::Expected<std::unique_ptr<Socket>>
149 Socket::TcpConnect(llvm::StringRef host_and_port,
150                    bool child_processes_inherit) {
151   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
152   LLDB_LOG(log, "host_and_port = {0}", host_and_port);
153 
154   Status error;
155   std::unique_ptr<Socket> connect_socket(
156       Create(ProtocolTcp, child_processes_inherit, error));
157   if (error.Fail())
158     return error.ToError();
159 
160   error = connect_socket->Connect(host_and_port);
161   if (error.Success())
162     return std::move(connect_socket);
163 
164   return error.ToError();
165 }
166 
167 llvm::Expected<std::unique_ptr<TCPSocket>>
168 Socket::TcpListen(llvm::StringRef host_and_port, bool child_processes_inherit,
169                   Predicate<uint16_t> *predicate, int backlog) {
170   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
171   LLDB_LOG(log, "host_and_port = {0}", host_and_port);
172 
173   std::string host_str;
174   std::string port_str;
175   uint16_t port;
176   if (llvm::Error decode_error =
177           DecodeHostAndPort(host_and_port, host_str, port_str, port))
178     return std::move(decode_error);
179 
180   std::unique_ptr<TCPSocket> listen_socket(
181       new TCPSocket(true, child_processes_inherit));
182 
183   Status error = listen_socket->Listen(host_and_port, backlog);
184   if (error.Fail())
185     return error.ToError();
186 
187   // We were asked to listen on port zero which means we must now read the
188   // actual port that was given to us as port zero is a special code for
189   // "find an open port for me".
190   if (port == 0)
191     port = listen_socket->GetLocalPortNumber();
192 
193   // Set the port predicate since when doing a listen://<host>:<port> it
194   // often needs to accept the incoming connection which is a blocking system
195   // call. Allowing access to the bound port using a predicate allows us to
196   // wait for the port predicate to be set to a non-zero value from another
197   // thread in an efficient manor.
198   if (predicate)
199     predicate->SetValue(port, eBroadcastAlways);
200   return std::move(listen_socket);
201 }
202 
203 llvm::Expected<std::unique_ptr<UDPSocket>>
204 Socket::UdpConnect(llvm::StringRef host_and_port,
205                    bool child_processes_inherit) {
206   return UDPSocket::Connect(host_and_port, child_processes_inherit);
207 }
208 
209 Status Socket::UnixDomainConnect(llvm::StringRef name,
210                                  bool child_processes_inherit,
211                                  Socket *&socket) {
212   Status error;
213   std::unique_ptr<Socket> connect_socket(
214       Create(ProtocolUnixDomain, child_processes_inherit, error));
215   if (error.Fail())
216     return error;
217 
218   error = connect_socket->Connect(name);
219   if (error.Success())
220     socket = connect_socket.release();
221 
222   return error;
223 }
224 
225 Status Socket::UnixDomainAccept(llvm::StringRef name,
226                                 bool child_processes_inherit, Socket *&socket) {
227   Status error;
228   std::unique_ptr<Socket> listen_socket(
229       Create(ProtocolUnixDomain, child_processes_inherit, error));
230   if (error.Fail())
231     return error;
232 
233   error = listen_socket->Listen(name, 5);
234   if (error.Fail())
235     return error;
236 
237   error = listen_socket->Accept(socket);
238   return error;
239 }
240 
241 Status Socket::UnixAbstractConnect(llvm::StringRef name,
242                                    bool child_processes_inherit,
243                                    Socket *&socket) {
244   Status error;
245   std::unique_ptr<Socket> connect_socket(
246       Create(ProtocolUnixAbstract, child_processes_inherit, error));
247   if (error.Fail())
248     return error;
249 
250   error = connect_socket->Connect(name);
251   if (error.Success())
252     socket = connect_socket.release();
253   return error;
254 }
255 
256 Status Socket::UnixAbstractAccept(llvm::StringRef name,
257                                   bool child_processes_inherit,
258                                   Socket *&socket) {
259   Status error;
260   std::unique_ptr<Socket> listen_socket(
261       Create(ProtocolUnixAbstract, child_processes_inherit, error));
262   if (error.Fail())
263     return error;
264 
265   error = listen_socket->Listen(name, 5);
266   if (error.Fail())
267     return error;
268 
269   error = listen_socket->Accept(socket);
270   return error;
271 }
272 
273 llvm::Error Socket::DecodeHostAndPort(llvm::StringRef host_and_port,
274                                       std::string &host_str,
275                                       std::string &port_str, uint16_t &port) {
276   static llvm::Regex g_regex("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)");
277   llvm::SmallVector<llvm::StringRef, 3> matches;
278   if (g_regex.match(host_and_port, &matches)) {
279     host_str = matches[1].str();
280     port_str = matches[2].str();
281     // IPv6 addresses are wrapped in [] when specified with ports
282     if (host_str.front() == '[' && host_str.back() == ']')
283       host_str = host_str.substr(1, host_str.size() - 2);
284     if (to_integer(matches[2], port, 10))
285       return llvm::Error::success();
286   } else {
287     // If this was unsuccessful, then check if it's simply a signed 32-bit
288     // integer, representing a port with an empty host.
289     host_str.clear();
290     port_str.clear();
291     if (to_integer(host_and_port, port, 10)) {
292       port_str = host_and_port.str();
293       return llvm::Error::success();
294     }
295   }
296 
297   return llvm::createStringError(llvm::inconvertibleErrorCode(),
298                                  "invalid host:port specification: '%s'",
299                                  host_and_port.str().c_str());
300 }
301 
302 IOObject::WaitableHandle Socket::GetWaitableHandle() {
303   // TODO: On Windows, use WSAEventSelect
304   return m_socket;
305 }
306 
307 Status Socket::Read(void *buf, size_t &num_bytes) {
308   Status error;
309   int bytes_received = 0;
310   do {
311     bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0);
312   } while (bytes_received < 0 && IsInterrupted());
313 
314   if (bytes_received < 0) {
315     SetLastError(error);
316     num_bytes = 0;
317   } else
318     num_bytes = bytes_received;
319 
320   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
321   if (log) {
322     LLDB_LOGF(log,
323               "%p Socket::Read() (socket = %" PRIu64
324               ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
325               " (error = %s)",
326               static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
327               static_cast<uint64_t>(num_bytes),
328               static_cast<int64_t>(bytes_received), error.AsCString());
329   }
330 
331   return error;
332 }
333 
334 Status Socket::Write(const void *buf, size_t &num_bytes) {
335   const size_t src_len = num_bytes;
336   Status error;
337   int bytes_sent = 0;
338   do {
339     bytes_sent = Send(buf, num_bytes);
340   } while (bytes_sent < 0 && IsInterrupted());
341 
342   if (bytes_sent < 0) {
343     SetLastError(error);
344     num_bytes = 0;
345   } else
346     num_bytes = bytes_sent;
347 
348   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
349   if (log) {
350     LLDB_LOGF(log,
351               "%p Socket::Write() (socket = %" PRIu64
352               ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
353               " (error = %s)",
354               static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
355               static_cast<uint64_t>(src_len),
356               static_cast<int64_t>(bytes_sent), error.AsCString());
357   }
358 
359   return error;
360 }
361 
362 Status Socket::PreDisconnect() {
363   Status error;
364   return error;
365 }
366 
367 Status Socket::Close() {
368   Status error;
369   if (!IsValid() || !m_should_close_fd)
370     return error;
371 
372   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
373   LLDB_LOGF(log, "%p Socket::Close (fd = %" PRIu64 ")",
374             static_cast<void *>(this), static_cast<uint64_t>(m_socket));
375 
376 #if defined(_WIN32)
377   bool success = !!closesocket(m_socket);
378 #else
379   bool success = !!::close(m_socket);
380 #endif
381   // A reference to a FD was passed in, set it to an invalid value
382   m_socket = kInvalidSocketValue;
383   if (!success) {
384     SetLastError(error);
385   }
386 
387   return error;
388 }
389 
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,
395                       &option_value_size);
396 }
397 
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));
403 }
404 
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);
407 }
408 
409 void Socket::SetLastError(Status &error) {
410 #if defined(_WIN32)
411   error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
412 #else
413   error.SetErrorToErrno();
414 #endif
415 }
416 
417 NativeSocket Socket::CreateSocket(const int domain, const int type,
418                                   const int protocol,
419                                   bool child_processes_inherit, Status &error) {
420   error.Clear();
421   auto socket_type = type;
422 #ifdef SOCK_CLOEXEC
423   if (!child_processes_inherit)
424     socket_type |= SOCK_CLOEXEC;
425 #endif
426   auto sock = ::socket(domain, socket_type, protocol);
427   if (sock == kInvalidSocketValue)
428     SetLastError(error);
429 
430   return sock;
431 }
432 
433 NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
434                                   socklen_t *addrlen,
435                                   bool child_processes_inherit, Status &error) {
436   error.Clear();
437 #if defined(ANDROID_USE_ACCEPT_WORKAROUND)
438   // Hack:
439   // This enables static linking lldb-server to an API 21 libc, but still
440   // having 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)
448       return fd;
449     SetLastError(error);
450     close(fd);
451   }
452   return fd;
453 #elif defined(SOCK_CLOEXEC) && defined(HAVE_ACCEPT4)
454   int flags = 0;
455   if (!child_processes_inherit) {
456     flags |= SOCK_CLOEXEC;
457   }
458   NativeSocket fd = llvm::sys::RetryAfterSignal(
459       static_cast<NativeSocket>(-1), ::accept4, sockfd, addr, addrlen, flags);
460 #else
461   NativeSocket fd = llvm::sys::RetryAfterSignal(
462       static_cast<NativeSocket>(-1), ::accept, sockfd, addr, addrlen);
463 #endif
464   if (fd == kInvalidSocketValue)
465     SetLastError(error);
466   return fd;
467 }
468