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