1 //===-- Socket.cpp ----------------------------------------------*- C++ -*-===//
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/StringConvert.h"
15 #include "lldb/Host/common/TCPSocket.h"
16 #include "lldb/Host/common/UDPSocket.h"
17 #include "lldb/Utility/Log.h"
18 #include "lldb/Utility/RegularExpression.h"
19 
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Support/Errno.h"
22 #include "llvm/Support/Error.h"
23 #include "llvm/Support/WindowsError.h"
24 
25 #ifndef LLDB_DISABLE_POSIX
26 #include "lldb/Host/posix/DomainSocket.h"
27 
28 #include <arpa/inet.h>
29 #include <netdb.h>
30 #include <netinet/in.h>
31 #include <netinet/tcp.h>
32 #include <sys/socket.h>
33 #include <sys/un.h>
34 #include <unistd.h>
35 #endif
36 
37 #ifdef __linux__
38 #include "lldb/Host/linux/AbstractSocket.h"
39 #endif
40 
41 #ifdef __ANDROID__
42 #include <arpa/inet.h>
43 #include <asm-generic/errno-base.h>
44 #include <errno.h>
45 #include <linux/tcp.h>
46 #include <fcntl.h>
47 #include <sys/syscall.h>
48 #include <unistd.h>
49 #endif // __ANDROID__
50 
51 using namespace lldb;
52 using namespace lldb_private;
53 
54 #if defined(_WIN32)
55 typedef const char *set_socket_option_arg_type;
56 typedef char *get_socket_option_arg_type;
57 const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET;
58 #else  // #if defined(_WIN32)
59 typedef const void *set_socket_option_arg_type;
60 typedef void *get_socket_option_arg_type;
61 const NativeSocket Socket::kInvalidSocketValue = -1;
62 #endif // #if defined(_WIN32)
63 
64 namespace {
65 
66 bool IsInterrupted() {
67 #if defined(_WIN32)
68   return ::WSAGetLastError() == WSAEINTR;
69 #else
70   return errno == EINTR;
71 #endif
72 }
73 }
74 
75 Socket::Socket(SocketProtocol protocol, bool should_close,
76                bool child_processes_inherit)
77     : IOObject(eFDTypeSocket, should_close), m_protocol(protocol),
78       m_socket(kInvalidSocketValue),
79       m_child_processes_inherit(child_processes_inherit) {}
80 
81 Socket::~Socket() { Close(); }
82 
83 llvm::Error Socket::Initialize() {
84 #if defined(_WIN32)
85   auto wVersion = WINSOCK_VERSION;
86   WSADATA wsaData;
87   int err = ::WSAStartup(wVersion, &wsaData);
88   if (err == 0) {
89     if (wsaData.wVersion < wVersion) {
90       WSACleanup();
91       return llvm::make_error<llvm::StringError>(
92           "WSASock version is not expected.", llvm::inconvertibleErrorCode());
93     }
94   } else {
95     return llvm::errorCodeToError(llvm::mapWindowsError(::WSAGetLastError()));
96   }
97 #endif
98 
99   return llvm::Error::success();
100 }
101 
102 void Socket::Terminate() {
103 #if defined(_WIN32)
104   ::WSACleanup();
105 #endif
106 }
107 
108 std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol,
109                                        bool child_processes_inherit,
110                                        Status &error) {
111   error.Clear();
112 
113   std::unique_ptr<Socket> socket_up;
114   switch (protocol) {
115   case ProtocolTcp:
116     socket_up =
117         llvm::make_unique<TCPSocket>(true, child_processes_inherit);
118     break;
119   case ProtocolUdp:
120     socket_up =
121         llvm::make_unique<UDPSocket>(true, child_processes_inherit);
122     break;
123   case ProtocolUnixDomain:
124 #ifndef LLDB_DISABLE_POSIX
125     socket_up =
126         llvm::make_unique<DomainSocket>(true, child_processes_inherit);
127 #else
128     error.SetErrorString(
129         "Unix domain sockets are not supported on this platform.");
130 #endif
131     break;
132   case ProtocolUnixAbstract:
133 #ifdef __linux__
134     socket_up =
135         llvm::make_unique<AbstractSocket>(child_processes_inherit);
136 #else
137     error.SetErrorString(
138         "Abstract domain sockets are not supported on this platform.");
139 #endif
140     break;
141   }
142 
143   if (error.Fail())
144     socket_up.reset();
145 
146   return socket_up;
147 }
148 
149 Status Socket::TcpConnect(llvm::StringRef host_and_port,
150                           bool child_processes_inherit, Socket *&socket) {
151   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
152   LLDB_LOGF(log, "Socket::%s (host/port = %s)", __FUNCTION__,
153             host_and_port.str().c_str());
154 
155   Status error;
156   std::unique_ptr<Socket> connect_socket(
157       Create(ProtocolTcp, child_processes_inherit, error));
158   if (error.Fail())
159     return error;
160 
161   error = connect_socket->Connect(host_and_port);
162   if (error.Success())
163     socket = connect_socket.release();
164 
165   return error;
166 }
167 
168 Status Socket::TcpListen(llvm::StringRef host_and_port,
169                          bool child_processes_inherit, Socket *&socket,
170                          Predicate<uint16_t> *predicate, int backlog) {
171   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
172   LLDB_LOGF(log, "Socket::%s (%s)", __FUNCTION__, host_and_port.str().c_str());
173 
174   Status error;
175   std::string host_str;
176   std::string port_str;
177   int32_t port = INT32_MIN;
178   if (!DecodeHostAndPort(host_and_port, host_str, port_str, port, &error))
179     return error;
180 
181   std::unique_ptr<TCPSocket> listen_socket(
182       new TCPSocket(true, child_processes_inherit));
183   if (error.Fail())
184     return error;
185 
186   error = listen_socket->Listen(host_and_port, backlog);
187   if (error.Success()) {
188     // We were asked to listen on port zero which means we must now read the
189     // actual port that was given to us as port zero is a special code for
190     // "find an open port for me".
191     if (port == 0)
192       port = listen_socket->GetLocalPortNumber();
193 
194     // Set the port predicate since when doing a listen://<host>:<port> it
195     // often needs to accept the incoming connection which is a blocking system
196     // call. Allowing access to the bound port using a predicate allows us to
197     // wait for the port predicate to be set to a non-zero value from another
198     // thread in an efficient manor.
199     if (predicate)
200       predicate->SetValue(port, eBroadcastAlways);
201     socket = listen_socket.release();
202   }
203 
204   return error;
205 }
206 
207 Status Socket::UdpConnect(llvm::StringRef host_and_port,
208                           bool child_processes_inherit, Socket *&socket) {
209   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
210   LLDB_LOGF(log, "Socket::%s (host/port = %s)", __FUNCTION__,
211             host_and_port.str().c_str());
212 
213   return UDPSocket::Connect(host_and_port, child_processes_inherit, socket);
214 }
215 
216 Status Socket::UnixDomainConnect(llvm::StringRef name,
217                                  bool child_processes_inherit,
218                                  Socket *&socket) {
219   Status error;
220   std::unique_ptr<Socket> connect_socket(
221       Create(ProtocolUnixDomain, child_processes_inherit, error));
222   if (error.Fail())
223     return error;
224 
225   error = connect_socket->Connect(name);
226   if (error.Success())
227     socket = connect_socket.release();
228 
229   return error;
230 }
231 
232 Status Socket::UnixDomainAccept(llvm::StringRef name,
233                                 bool child_processes_inherit, Socket *&socket) {
234   Status error;
235   std::unique_ptr<Socket> listen_socket(
236       Create(ProtocolUnixDomain, child_processes_inherit, error));
237   if (error.Fail())
238     return error;
239 
240   error = listen_socket->Listen(name, 5);
241   if (error.Fail())
242     return error;
243 
244   error = listen_socket->Accept(socket);
245   return error;
246 }
247 
248 Status Socket::UnixAbstractConnect(llvm::StringRef name,
249                                    bool child_processes_inherit,
250                                    Socket *&socket) {
251   Status error;
252   std::unique_ptr<Socket> connect_socket(
253       Create(ProtocolUnixAbstract, child_processes_inherit, error));
254   if (error.Fail())
255     return error;
256 
257   error = connect_socket->Connect(name);
258   if (error.Success())
259     socket = connect_socket.release();
260   return error;
261 }
262 
263 Status Socket::UnixAbstractAccept(llvm::StringRef name,
264                                   bool child_processes_inherit,
265                                   Socket *&socket) {
266   Status error;
267   std::unique_ptr<Socket> listen_socket(
268       Create(ProtocolUnixAbstract, child_processes_inherit, error));
269   if (error.Fail())
270     return error;
271 
272   error = listen_socket->Listen(name, 5);
273   if (error.Fail())
274     return error;
275 
276   error = listen_socket->Accept(socket);
277   return error;
278 }
279 
280 bool Socket::DecodeHostAndPort(llvm::StringRef host_and_port,
281                                std::string &host_str, std::string &port_str,
282                                int32_t &port, Status *error_ptr) {
283   static RegularExpression g_regex(
284       llvm::StringRef("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)"));
285   RegularExpression::Match regex_match(2);
286   if (g_regex.Execute(host_and_port, &regex_match)) {
287     if (regex_match.GetMatchAtIndex(host_and_port, 1, host_str) &&
288         regex_match.GetMatchAtIndex(host_and_port, 2, port_str)) {
289       // IPv6 addresses are wrapped in [] when specified with ports
290       if (host_str.front() == '[' && host_str.back() == ']')
291         host_str = host_str.substr(1, host_str.size() - 2);
292       bool ok = false;
293       port = StringConvert::ToUInt32(port_str.c_str(), UINT32_MAX, 10, &ok);
294       if (ok && port <= UINT16_MAX) {
295         if (error_ptr)
296           error_ptr->Clear();
297         return true;
298       }
299       // port is too large
300       if (error_ptr)
301         error_ptr->SetErrorStringWithFormat(
302             "invalid host:port specification: '%s'",
303             host_and_port.str().c_str());
304       return false;
305     }
306   }
307 
308   // If this was unsuccessful, then check if it's simply a signed 32-bit
309   // integer, representing a port with an empty host.
310   host_str.clear();
311   port_str.clear();
312   if (to_integer(host_and_port, port, 10) && port < UINT16_MAX) {
313     port_str = host_and_port;
314     if (error_ptr)
315       error_ptr->Clear();
316     return true;
317   }
318 
319   if (error_ptr)
320     error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'",
321                                         host_and_port.str().c_str());
322   return false;
323 }
324 
325 IOObject::WaitableHandle Socket::GetWaitableHandle() {
326   // TODO: On Windows, use WSAEventSelect
327   return m_socket;
328 }
329 
330 Status Socket::Read(void *buf, size_t &num_bytes) {
331   Status error;
332   int bytes_received = 0;
333   do {
334     bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0);
335   } while (bytes_received < 0 && IsInterrupted());
336 
337   if (bytes_received < 0) {
338     SetLastError(error);
339     num_bytes = 0;
340   } else
341     num_bytes = bytes_received;
342 
343   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
344   if (log) {
345     LLDB_LOGF(log,
346               "%p Socket::Read() (socket = %" PRIu64
347               ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
348               " (error = %s)",
349               static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
350               static_cast<uint64_t>(num_bytes),
351               static_cast<int64_t>(bytes_received), error.AsCString());
352   }
353 
354   return error;
355 }
356 
357 Status Socket::Write(const void *buf, size_t &num_bytes) {
358   Status error;
359   int bytes_sent = 0;
360   do {
361     bytes_sent = Send(buf, num_bytes);
362   } while (bytes_sent < 0 && IsInterrupted());
363 
364   if (bytes_sent < 0) {
365     SetLastError(error);
366     num_bytes = 0;
367   } else
368     num_bytes = bytes_sent;
369 
370   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
371   if (log) {
372     LLDB_LOGF(log,
373               "%p Socket::Write() (socket = %" PRIu64
374               ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
375               " (error = %s)",
376               static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
377               static_cast<uint64_t>(num_bytes),
378               static_cast<int64_t>(bytes_sent), error.AsCString());
379   }
380 
381   return error;
382 }
383 
384 Status Socket::PreDisconnect() {
385   Status error;
386   return error;
387 }
388 
389 Status Socket::Close() {
390   Status error;
391   if (!IsValid() || !m_should_close_fd)
392     return error;
393 
394   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
395   LLDB_LOGF(log, "%p Socket::Close (fd = %" PRIu64 ")",
396             static_cast<void *>(this), static_cast<uint64_t>(m_socket));
397 
398 #if defined(_WIN32)
399   bool success = !!closesocket(m_socket);
400 #else
401   bool success = !!::close(m_socket);
402 #endif
403   // A reference to a FD was passed in, set it to an invalid value
404   m_socket = kInvalidSocketValue;
405   if (!success) {
406     SetLastError(error);
407   }
408 
409   return error;
410 }
411 
412 int Socket::GetOption(int level, int option_name, int &option_value) {
413   get_socket_option_arg_type option_value_p =
414       reinterpret_cast<get_socket_option_arg_type>(&option_value);
415   socklen_t option_value_size = sizeof(int);
416   return ::getsockopt(m_socket, level, option_name, option_value_p,
417                       &option_value_size);
418 }
419 
420 int Socket::SetOption(int level, int option_name, int option_value) {
421   set_socket_option_arg_type option_value_p =
422       reinterpret_cast<get_socket_option_arg_type>(&option_value);
423   return ::setsockopt(m_socket, level, option_name, option_value_p,
424                       sizeof(option_value));
425 }
426 
427 size_t Socket::Send(const void *buf, const size_t num_bytes) {
428   return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0);
429 }
430 
431 void Socket::SetLastError(Status &error) {
432 #if defined(_WIN32)
433   error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
434 #else
435   error.SetErrorToErrno();
436 #endif
437 }
438 
439 NativeSocket Socket::CreateSocket(const int domain, const int type,
440                                   const int protocol,
441                                   bool child_processes_inherit, Status &error) {
442   error.Clear();
443   auto socket_type = type;
444 #ifdef SOCK_CLOEXEC
445   if (!child_processes_inherit)
446     socket_type |= SOCK_CLOEXEC;
447 #endif
448   auto sock = ::socket(domain, socket_type, protocol);
449   if (sock == kInvalidSocketValue)
450     SetLastError(error);
451 
452   return sock;
453 }
454 
455 NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
456                                   socklen_t *addrlen,
457                                   bool child_processes_inherit, Status &error) {
458   error.Clear();
459 #if defined(ANDROID_USE_ACCEPT_WORKAROUND)
460   // Hack:
461   // This enables static linking lldb-server to an API 21 libc, but still
462   // having it run on older devices. It is necessary because API 21 libc's
463   // implementation of accept() uses the accept4 syscall(), which is not
464   // available in older kernels. Using an older libc would fix this issue, but
465   // introduce other ones, as the old libraries were quite buggy.
466   int fd = syscall(__NR_accept, sockfd, addr, addrlen);
467   if (fd >= 0 && !child_processes_inherit) {
468     int flags = ::fcntl(fd, F_GETFD);
469     if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1)
470       return fd;
471     SetLastError(error);
472     close(fd);
473   }
474   return fd;
475 #elif defined(SOCK_CLOEXEC) && defined(HAVE_ACCEPT4)
476   int flags = 0;
477   if (!child_processes_inherit) {
478     flags |= SOCK_CLOEXEC;
479   }
480   NativeSocket fd = llvm::sys::RetryAfterSignal(-1, ::accept4,
481       sockfd, addr, addrlen, flags);
482 #else
483   NativeSocket fd = llvm::sys::RetryAfterSignal(-1, ::accept,
484       sockfd, addr, addrlen);
485 #endif
486   if (fd == kInvalidSocketValue)
487     SetLastError(error);
488   return fd;
489 }
490