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 
22 #ifndef LLDB_DISABLE_POSIX
23 #include "lldb/Host/posix/DomainSocket.h"
24 
25 #include <arpa/inet.h>
26 #include <netdb.h>
27 #include <netinet/in.h>
28 #include <netinet/tcp.h>
29 #include <sys/socket.h>
30 #include <sys/un.h>
31 #include <unistd.h>
32 #endif
33 
34 #ifdef __linux__
35 #include "lldb/Host/linux/AbstractSocket.h"
36 #endif
37 
38 #ifdef __ANDROID__
39 #include <arpa/inet.h>
40 #include <asm-generic/errno-base.h>
41 #include <errno.h>
42 #include <linux/tcp.h>
43 #include <fcntl.h>
44 #include <sys/syscall.h>
45 #include <unistd.h>
46 #endif // __ANDROID__
47 
48 using namespace lldb;
49 using namespace lldb_private;
50 
51 #if defined(_WIN32)
52 typedef const char *set_socket_option_arg_type;
53 typedef char *get_socket_option_arg_type;
54 const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET;
55 #else  // #if defined(_WIN32)
56 typedef const void *set_socket_option_arg_type;
57 typedef void *get_socket_option_arg_type;
58 const NativeSocket Socket::kInvalidSocketValue = -1;
59 #endif // #if defined(_WIN32)
60 
61 namespace {
62 
63 bool IsInterrupted() {
64 #if defined(_WIN32)
65   return ::WSAGetLastError() == WSAEINTR;
66 #else
67   return errno == EINTR;
68 #endif
69 }
70 }
71 
72 Socket::Socket(SocketProtocol protocol, bool should_close,
73                bool child_processes_inherit)
74     : IOObject(eFDTypeSocket, should_close), m_protocol(protocol),
75       m_socket(kInvalidSocketValue),
76       m_child_processes_inherit(child_processes_inherit) {}
77 
78 Socket::~Socket() { Close(); }
79 
80 std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol,
81                                        bool child_processes_inherit,
82                                        Status &error) {
83   error.Clear();
84 
85   std::unique_ptr<Socket> socket_up;
86   switch (protocol) {
87   case ProtocolTcp:
88     socket_up =
89         llvm::make_unique<TCPSocket>(true, child_processes_inherit);
90     break;
91   case ProtocolUdp:
92     socket_up =
93         llvm::make_unique<UDPSocket>(true, child_processes_inherit);
94     break;
95   case ProtocolUnixDomain:
96 #ifndef LLDB_DISABLE_POSIX
97     socket_up =
98         llvm::make_unique<DomainSocket>(true, child_processes_inherit);
99 #else
100     error.SetErrorString(
101         "Unix domain sockets are not supported on this platform.");
102 #endif
103     break;
104   case ProtocolUnixAbstract:
105 #ifdef __linux__
106     socket_up =
107         llvm::make_unique<AbstractSocket>(child_processes_inherit);
108 #else
109     error.SetErrorString(
110         "Abstract domain sockets are not supported on this platform.");
111 #endif
112     break;
113   }
114 
115   if (error.Fail())
116     socket_up.reset();
117 
118   return socket_up;
119 }
120 
121 Status Socket::TcpConnect(llvm::StringRef host_and_port,
122                           bool child_processes_inherit, Socket *&socket) {
123   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
124   if (log)
125     log->Printf("Socket::%s (host/port = %s)", __FUNCTION__,
126                 host_and_port.data());
127 
128   Status error;
129   std::unique_ptr<Socket> connect_socket(
130       Create(ProtocolTcp, child_processes_inherit, error));
131   if (error.Fail())
132     return error;
133 
134   error = connect_socket->Connect(host_and_port);
135   if (error.Success())
136     socket = connect_socket.release();
137 
138   return error;
139 }
140 
141 Status Socket::TcpListen(llvm::StringRef host_and_port,
142                          bool child_processes_inherit, Socket *&socket,
143                          Predicate<uint16_t> *predicate, int backlog) {
144   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
145   if (log)
146     log->Printf("Socket::%s (%s)", __FUNCTION__, host_and_port.data());
147 
148   Status error;
149   std::string host_str;
150   std::string port_str;
151   int32_t port = INT32_MIN;
152   if (!DecodeHostAndPort(host_and_port, host_str, port_str, port, &error))
153     return error;
154 
155   std::unique_ptr<TCPSocket> listen_socket(
156       new TCPSocket(true, child_processes_inherit));
157   if (error.Fail())
158     return error;
159 
160   error = listen_socket->Listen(host_and_port, backlog);
161   if (error.Success()) {
162     // We were asked to listen on port zero which means we must now read the
163     // actual port that was given to us as port zero is a special code for
164     // "find an open port for me".
165     if (port == 0)
166       port = listen_socket->GetLocalPortNumber();
167 
168     // Set the port predicate since when doing a listen://<host>:<port> it
169     // often needs to accept the incoming connection which is a blocking system
170     // call. Allowing access to the bound port using a predicate allows us to
171     // wait for the port predicate to be set to a non-zero value from another
172     // thread in an efficient manor.
173     if (predicate)
174       predicate->SetValue(port, eBroadcastAlways);
175     socket = listen_socket.release();
176   }
177 
178   return error;
179 }
180 
181 Status Socket::UdpConnect(llvm::StringRef host_and_port,
182                           bool child_processes_inherit, Socket *&socket) {
183   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
184   if (log)
185     log->Printf("Socket::%s (host/port = %s)", __FUNCTION__,
186                 host_and_port.data());
187 
188   return UDPSocket::Connect(host_and_port, child_processes_inherit, socket);
189 }
190 
191 Status Socket::UnixDomainConnect(llvm::StringRef name,
192                                  bool child_processes_inherit,
193                                  Socket *&socket) {
194   Status error;
195   std::unique_ptr<Socket> connect_socket(
196       Create(ProtocolUnixDomain, child_processes_inherit, error));
197   if (error.Fail())
198     return error;
199 
200   error = connect_socket->Connect(name);
201   if (error.Success())
202     socket = connect_socket.release();
203 
204   return error;
205 }
206 
207 Status Socket::UnixDomainAccept(llvm::StringRef name,
208                                 bool child_processes_inherit, Socket *&socket) {
209   Status error;
210   std::unique_ptr<Socket> listen_socket(
211       Create(ProtocolUnixDomain, child_processes_inherit, error));
212   if (error.Fail())
213     return error;
214 
215   error = listen_socket->Listen(name, 5);
216   if (error.Fail())
217     return error;
218 
219   error = listen_socket->Accept(socket);
220   return error;
221 }
222 
223 Status Socket::UnixAbstractConnect(llvm::StringRef name,
224                                    bool child_processes_inherit,
225                                    Socket *&socket) {
226   Status error;
227   std::unique_ptr<Socket> connect_socket(
228       Create(ProtocolUnixAbstract, child_processes_inherit, error));
229   if (error.Fail())
230     return error;
231 
232   error = connect_socket->Connect(name);
233   if (error.Success())
234     socket = connect_socket.release();
235   return error;
236 }
237 
238 Status Socket::UnixAbstractAccept(llvm::StringRef name,
239                                   bool child_processes_inherit,
240                                   Socket *&socket) {
241   Status error;
242   std::unique_ptr<Socket> listen_socket(
243       Create(ProtocolUnixAbstract, child_processes_inherit, error));
244   if (error.Fail())
245     return error;
246 
247   error = listen_socket->Listen(name, 5);
248   if (error.Fail())
249     return error;
250 
251   error = listen_socket->Accept(socket);
252   return error;
253 }
254 
255 bool Socket::DecodeHostAndPort(llvm::StringRef host_and_port,
256                                std::string &host_str, std::string &port_str,
257                                int32_t &port, Status *error_ptr) {
258   static RegularExpression g_regex(
259       llvm::StringRef("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)"));
260   RegularExpression::Match regex_match(2);
261   if (g_regex.Execute(host_and_port, &regex_match)) {
262     if (regex_match.GetMatchAtIndex(host_and_port.data(), 1, host_str) &&
263         regex_match.GetMatchAtIndex(host_and_port.data(), 2, port_str)) {
264       // IPv6 addresses are wrapped in [] when specified with ports
265       if (host_str.front() == '[' && host_str.back() == ']')
266         host_str = host_str.substr(1, host_str.size() - 2);
267       bool ok = false;
268       port = StringConvert::ToUInt32(port_str.c_str(), UINT32_MAX, 10, &ok);
269       if (ok && port <= UINT16_MAX) {
270         if (error_ptr)
271           error_ptr->Clear();
272         return true;
273       }
274       // port is too large
275       if (error_ptr)
276         error_ptr->SetErrorStringWithFormat(
277             "invalid host:port specification: '%s'", host_and_port.data());
278       return false;
279     }
280   }
281 
282   // If this was unsuccessful, then check if it's simply a signed 32-bit
283   // integer, representing a port with an empty host.
284   host_str.clear();
285   port_str.clear();
286   bool ok = false;
287   port = StringConvert::ToUInt32(host_and_port.data(), UINT32_MAX, 10, &ok);
288   if (ok && port < UINT16_MAX) {
289     port_str = host_and_port;
290     if (error_ptr)
291       error_ptr->Clear();
292     return true;
293   }
294 
295   if (error_ptr)
296     error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'",
297                                         host_and_port.data());
298   return false;
299 }
300 
301 IOObject::WaitableHandle Socket::GetWaitableHandle() {
302   // TODO: On Windows, use WSAEventSelect
303   return m_socket;
304 }
305 
306 Status Socket::Read(void *buf, size_t &num_bytes) {
307   Status error;
308   int bytes_received = 0;
309   do {
310     bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0);
311   } while (bytes_received < 0 && IsInterrupted());
312 
313   if (bytes_received < 0) {
314     SetLastError(error);
315     num_bytes = 0;
316   } else
317     num_bytes = bytes_received;
318 
319   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
320   if (log) {
321     log->Printf("%p Socket::Read() (socket = %" PRIu64
322                 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
323                 " (error = %s)",
324                 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
325                 static_cast<uint64_t>(num_bytes),
326                 static_cast<int64_t>(bytes_received), error.AsCString());
327   }
328 
329   return error;
330 }
331 
332 Status Socket::Write(const void *buf, size_t &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     log->Printf("%p Socket::Write() (socket = %" PRIu64
348                 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
349                 " (error = %s)",
350                 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
351                 static_cast<uint64_t>(num_bytes),
352                 static_cast<int64_t>(bytes_sent), error.AsCString());
353   }
354 
355   return error;
356 }
357 
358 Status Socket::PreDisconnect() {
359   Status error;
360   return error;
361 }
362 
363 Status Socket::Close() {
364   Status error;
365   if (!IsValid() || !m_should_close_fd)
366     return error;
367 
368   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
369   if (log)
370     log->Printf("%p Socket::Close (fd = %i)", static_cast<void *>(this),
371                 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 = ::accept4(sockfd, addr, addrlen, flags);
456 #else
457   NativeSocket fd = ::accept(sockfd, addr, addrlen);
458 #endif
459   if (fd == kInvalidSocketValue)
460     SetLastError(error);
461   return fd;
462 }
463