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