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                   Predicate<uint16_t> *predicate, 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::string host_str;
171   std::string port_str;
172   uint16_t port;
173   if (llvm::Error decode_error =
174           DecodeHostAndPort(host_and_port, host_str, port_str, port))
175     return std::move(decode_error);
176 
177   std::unique_ptr<TCPSocket> listen_socket(
178       new TCPSocket(true, child_processes_inherit));
179 
180   Status error = listen_socket->Listen(host_and_port, backlog);
181   if (error.Fail())
182     return error.ToError();
183 
184   // We were asked to listen on port zero which means we must now read the
185   // actual port that was given to us as port zero is a special code for
186   // "find an open port for me".
187   if (port == 0)
188     port = listen_socket->GetLocalPortNumber();
189 
190   // Set the port predicate since when doing a listen://<host>:<port> it
191   // often needs to accept the incoming connection which is a blocking system
192   // call. Allowing access to the bound port using a predicate allows us to
193   // wait for the port predicate to be set to a non-zero value from another
194   // thread in an efficient manor.
195   if (predicate)
196     predicate->SetValue(port, eBroadcastAlways);
197   return std::move(listen_socket);
198 }
199 
200 llvm::Expected<std::unique_ptr<UDPSocket>>
201 Socket::UdpConnect(llvm::StringRef host_and_port,
202                    bool child_processes_inherit) {
203   return UDPSocket::Connect(host_and_port, child_processes_inherit);
204 }
205 
206 Status Socket::UnixDomainConnect(llvm::StringRef name,
207                                  bool child_processes_inherit,
208                                  Socket *&socket) {
209   Status error;
210   std::unique_ptr<Socket> connect_socket(
211       Create(ProtocolUnixDomain, child_processes_inherit, error));
212   if (error.Fail())
213     return error;
214 
215   error = connect_socket->Connect(name);
216   if (error.Success())
217     socket = connect_socket.release();
218 
219   return error;
220 }
221 
222 Status Socket::UnixDomainAccept(llvm::StringRef name,
223                                 bool child_processes_inherit, Socket *&socket) {
224   Status error;
225   std::unique_ptr<Socket> listen_socket(
226       Create(ProtocolUnixDomain, child_processes_inherit, error));
227   if (error.Fail())
228     return error;
229 
230   error = listen_socket->Listen(name, 5);
231   if (error.Fail())
232     return error;
233 
234   error = listen_socket->Accept(socket);
235   return error;
236 }
237 
238 Status Socket::UnixAbstractConnect(llvm::StringRef name,
239                                    bool child_processes_inherit,
240                                    Socket *&socket) {
241   Status error;
242   std::unique_ptr<Socket> connect_socket(
243       Create(ProtocolUnixAbstract, child_processes_inherit, error));
244   if (error.Fail())
245     return error;
246 
247   error = connect_socket->Connect(name);
248   if (error.Success())
249     socket = connect_socket.release();
250   return error;
251 }
252 
253 Status Socket::UnixAbstractAccept(llvm::StringRef name,
254                                   bool child_processes_inherit,
255                                   Socket *&socket) {
256   Status error;
257   std::unique_ptr<Socket> listen_socket(
258       Create(ProtocolUnixAbstract, child_processes_inherit, error));
259   if (error.Fail())
260     return error;
261 
262   error = listen_socket->Listen(name, 5);
263   if (error.Fail())
264     return error;
265 
266   error = listen_socket->Accept(socket);
267   return error;
268 }
269 
270 llvm::Error Socket::DecodeHostAndPort(llvm::StringRef host_and_port,
271                                       std::string &host_str,
272                                       std::string &port_str, uint16_t &port) {
273   static llvm::Regex g_regex("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)");
274   llvm::SmallVector<llvm::StringRef, 3> matches;
275   if (g_regex.match(host_and_port, &matches)) {
276     host_str = matches[1].str();
277     port_str = matches[2].str();
278     // IPv6 addresses are wrapped in [] when specified with ports
279     if (host_str.front() == '[' && host_str.back() == ']')
280       host_str = host_str.substr(1, host_str.size() - 2);
281     if (to_integer(matches[2], port, 10))
282       return llvm::Error::success();
283   } else {
284     // If this was unsuccessful, then check if it's simply a signed 32-bit
285     // integer, representing a port with an empty host.
286     host_str.clear();
287     port_str.clear();
288     if (to_integer(host_and_port, port, 10)) {
289       port_str = host_and_port.str();
290       return llvm::Error::success();
291     }
292   }
293 
294   return llvm::createStringError(llvm::inconvertibleErrorCode(),
295                                  "invalid host:port specification: '%s'",
296                                  host_and_port.str().c_str());
297 }
298 
299 IOObject::WaitableHandle Socket::GetWaitableHandle() {
300   // TODO: On Windows, use WSAEventSelect
301   return m_socket;
302 }
303 
304 Status Socket::Read(void *buf, size_t &num_bytes) {
305   Status error;
306   int bytes_received = 0;
307   do {
308     bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0);
309   } while (bytes_received < 0 && IsInterrupted());
310 
311   if (bytes_received < 0) {
312     SetLastError(error);
313     num_bytes = 0;
314   } else
315     num_bytes = bytes_received;
316 
317   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
318   if (log) {
319     LLDB_LOGF(log,
320               "%p Socket::Read() (socket = %" PRIu64
321               ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
322               " (error = %s)",
323               static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
324               static_cast<uint64_t>(num_bytes),
325               static_cast<int64_t>(bytes_received), error.AsCString());
326   }
327 
328   return error;
329 }
330 
331 Status Socket::Write(const void *buf, size_t &num_bytes) {
332   const size_t src_len = num_bytes;
333   Status error;
334   int bytes_sent = 0;
335   do {
336     bytes_sent = Send(buf, num_bytes);
337   } while (bytes_sent < 0 && IsInterrupted());
338 
339   if (bytes_sent < 0) {
340     SetLastError(error);
341     num_bytes = 0;
342   } else
343     num_bytes = bytes_sent;
344 
345   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
346   if (log) {
347     LLDB_LOGF(log,
348               "%p Socket::Write() (socket = %" PRIu64
349               ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
350               " (error = %s)",
351               static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
352               static_cast<uint64_t>(src_len),
353               static_cast<int64_t>(bytes_sent), error.AsCString());
354   }
355 
356   return error;
357 }
358 
359 Status Socket::PreDisconnect() {
360   Status error;
361   return error;
362 }
363 
364 Status Socket::Close() {
365   Status error;
366   if (!IsValid() || !m_should_close_fd)
367     return error;
368 
369   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
370   LLDB_LOGF(log, "%p Socket::Close (fd = %" PRIu64 ")",
371             static_cast<void *>(this), static_cast<uint64_t>(m_socket));
372 
373 #if defined(_WIN32)
374   bool success = !!closesocket(m_socket);
375 #else
376   bool success = !!::close(m_socket);
377 #endif
378   // A reference to a FD was passed in, set it to an invalid value
379   m_socket = kInvalidSocketValue;
380   if (!success) {
381     SetLastError(error);
382   }
383 
384   return error;
385 }
386 
387 int Socket::GetOption(int level, int option_name, int &option_value) {
388   get_socket_option_arg_type option_value_p =
389       reinterpret_cast<get_socket_option_arg_type>(&option_value);
390   socklen_t option_value_size = sizeof(int);
391   return ::getsockopt(m_socket, level, option_name, option_value_p,
392                       &option_value_size);
393 }
394 
395 int Socket::SetOption(int level, int option_name, int option_value) {
396   set_socket_option_arg_type option_value_p =
397       reinterpret_cast<get_socket_option_arg_type>(&option_value);
398   return ::setsockopt(m_socket, level, option_name, option_value_p,
399                       sizeof(option_value));
400 }
401 
402 size_t Socket::Send(const void *buf, const size_t num_bytes) {
403   return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0);
404 }
405 
406 void Socket::SetLastError(Status &error) {
407 #if defined(_WIN32)
408   error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
409 #else
410   error.SetErrorToErrno();
411 #endif
412 }
413 
414 NativeSocket Socket::CreateSocket(const int domain, const int type,
415                                   const int protocol,
416                                   bool child_processes_inherit, Status &error) {
417   error.Clear();
418   auto socket_type = type;
419 #ifdef SOCK_CLOEXEC
420   if (!child_processes_inherit)
421     socket_type |= SOCK_CLOEXEC;
422 #endif
423   auto sock = ::socket(domain, socket_type, protocol);
424   if (sock == kInvalidSocketValue)
425     SetLastError(error);
426 
427   return sock;
428 }
429 
430 NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
431                                   socklen_t *addrlen,
432                                   bool child_processes_inherit, Status &error) {
433   error.Clear();
434 #if defined(ANDROID_USE_ACCEPT_WORKAROUND)
435   // Hack:
436   // This enables static linking lldb-server to an API 21 libc, but still
437   // having it run on older devices. It is necessary because API 21 libc's
438   // implementation of accept() uses the accept4 syscall(), which is not
439   // available in older kernels. Using an older libc would fix this issue, but
440   // introduce other ones, as the old libraries were quite buggy.
441   int fd = syscall(__NR_accept, sockfd, addr, addrlen);
442   if (fd >= 0 && !child_processes_inherit) {
443     int flags = ::fcntl(fd, F_GETFD);
444     if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1)
445       return fd;
446     SetLastError(error);
447     close(fd);
448   }
449   return fd;
450 #elif defined(SOCK_CLOEXEC) && defined(HAVE_ACCEPT4)
451   int flags = 0;
452   if (!child_processes_inherit) {
453     flags |= SOCK_CLOEXEC;
454   }
455   NativeSocket fd = llvm::sys::RetryAfterSignal(
456       static_cast<NativeSocket>(-1), ::accept4, sockfd, addr, addrlen, flags);
457 #else
458   NativeSocket fd = llvm::sys::RetryAfterSignal(
459       static_cast<NativeSocket>(-1), ::accept, sockfd, addr, addrlen);
460 #endif
461   if (fd == kInvalidSocketValue)
462     SetLastError(error);
463   return fd;
464 }
465