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, 1, host_str) &&
263         regex_match.GetMatchAtIndex(host_and_port, 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   if (to_integer(host_and_port, port, 10) && port < UINT16_MAX) {
287     port_str = host_and_port;
288     if (error_ptr)
289       error_ptr->Clear();
290     return true;
291   }
292 
293   if (error_ptr)
294     error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'",
295                                         host_and_port.data());
296   return false;
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     log->Printf("%p Socket::Read() (socket = %" PRIu64
320                 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
321                 " (error = %s)",
322                 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
323                 static_cast<uint64_t>(num_bytes),
324                 static_cast<int64_t>(bytes_received), error.AsCString());
325   }
326 
327   return error;
328 }
329 
330 Status Socket::Write(const void *buf, size_t &num_bytes) {
331   Status error;
332   int bytes_sent = 0;
333   do {
334     bytes_sent = Send(buf, num_bytes);
335   } while (bytes_sent < 0 && IsInterrupted());
336 
337   if (bytes_sent < 0) {
338     SetLastError(error);
339     num_bytes = 0;
340   } else
341     num_bytes = bytes_sent;
342 
343   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
344   if (log) {
345     log->Printf("%p Socket::Write() (socket = %" PRIu64
346                 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
347                 " (error = %s)",
348                 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
349                 static_cast<uint64_t>(num_bytes),
350                 static_cast<int64_t>(bytes_sent), error.AsCString());
351   }
352 
353   return error;
354 }
355 
356 Status Socket::PreDisconnect() {
357   Status error;
358   return error;
359 }
360 
361 Status Socket::Close() {
362   Status error;
363   if (!IsValid() || !m_should_close_fd)
364     return error;
365 
366   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
367   if (log)
368     log->Printf("%p Socket::Close (fd = %i)", static_cast<void *>(this),
369                 m_socket);
370 
371 #if defined(_WIN32)
372   bool success = !!closesocket(m_socket);
373 #else
374   bool success = !!::close(m_socket);
375 #endif
376   // A reference to a FD was passed in, set it to an invalid value
377   m_socket = kInvalidSocketValue;
378   if (!success) {
379     SetLastError(error);
380   }
381 
382   return error;
383 }
384 
385 int Socket::GetOption(int level, int option_name, int &option_value) {
386   get_socket_option_arg_type option_value_p =
387       reinterpret_cast<get_socket_option_arg_type>(&option_value);
388   socklen_t option_value_size = sizeof(int);
389   return ::getsockopt(m_socket, level, option_name, option_value_p,
390                       &option_value_size);
391 }
392 
393 int Socket::SetOption(int level, int option_name, int option_value) {
394   set_socket_option_arg_type option_value_p =
395       reinterpret_cast<get_socket_option_arg_type>(&option_value);
396   return ::setsockopt(m_socket, level, option_name, option_value_p,
397                       sizeof(option_value));
398 }
399 
400 size_t Socket::Send(const void *buf, const size_t num_bytes) {
401   return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0);
402 }
403 
404 void Socket::SetLastError(Status &error) {
405 #if defined(_WIN32)
406   error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
407 #else
408   error.SetErrorToErrno();
409 #endif
410 }
411 
412 NativeSocket Socket::CreateSocket(const int domain, const int type,
413                                   const int protocol,
414                                   bool child_processes_inherit, Status &error) {
415   error.Clear();
416   auto socket_type = type;
417 #ifdef SOCK_CLOEXEC
418   if (!child_processes_inherit)
419     socket_type |= SOCK_CLOEXEC;
420 #endif
421   auto sock = ::socket(domain, socket_type, protocol);
422   if (sock == kInvalidSocketValue)
423     SetLastError(error);
424 
425   return sock;
426 }
427 
428 NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
429                                   socklen_t *addrlen,
430                                   bool child_processes_inherit, Status &error) {
431   error.Clear();
432 #if defined(ANDROID_USE_ACCEPT_WORKAROUND)
433   // Hack:
434   // This enables static linking lldb-server to an API 21 libc, but still
435   // having it run on older devices. It is necessary because API 21 libc's
436   // implementation of accept() uses the accept4 syscall(), which is not
437   // available in older kernels. Using an older libc would fix this issue, but
438   // introduce other ones, as the old libraries were quite buggy.
439   int fd = syscall(__NR_accept, sockfd, addr, addrlen);
440   if (fd >= 0 && !child_processes_inherit) {
441     int flags = ::fcntl(fd, F_GETFD);
442     if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1)
443       return fd;
444     SetLastError(error);
445     close(fd);
446   }
447   return fd;
448 #elif defined(SOCK_CLOEXEC) && defined(HAVE_ACCEPT4)
449   int flags = 0;
450   if (!child_processes_inherit) {
451     flags |= SOCK_CLOEXEC;
452   }
453   NativeSocket fd = ::accept4(sockfd, addr, addrlen, flags);
454 #else
455   NativeSocket fd = ::accept(sockfd, addr, addrlen);
456 #endif
457   if (fd == kInvalidSocketValue)
458     SetLastError(error);
459   return fd;
460 }
461