]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Host/common/Socket.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Host / common / Socket.cpp
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   if (log)
153     log->Printf("Socket::%s (host/port = %s)", __FUNCTION__,
154                 host_and_port.str().c_str());
155
156   Status error;
157   std::unique_ptr<Socket> connect_socket(
158       Create(ProtocolTcp, child_processes_inherit, error));
159   if (error.Fail())
160     return error;
161
162   error = connect_socket->Connect(host_and_port);
163   if (error.Success())
164     socket = connect_socket.release();
165
166   return error;
167 }
168
169 Status Socket::TcpListen(llvm::StringRef host_and_port,
170                          bool child_processes_inherit, Socket *&socket,
171                          Predicate<uint16_t> *predicate, int backlog) {
172   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
173   if (log)
174     log->Printf("Socket::%s (%s)", __FUNCTION__, host_and_port.str().c_str());
175
176   Status error;
177   std::string host_str;
178   std::string port_str;
179   int32_t port = INT32_MIN;
180   if (!DecodeHostAndPort(host_and_port, host_str, port_str, port, &error))
181     return error;
182
183   std::unique_ptr<TCPSocket> listen_socket(
184       new TCPSocket(true, child_processes_inherit));
185   if (error.Fail())
186     return error;
187
188   error = listen_socket->Listen(host_and_port, backlog);
189   if (error.Success()) {
190     // We were asked to listen on port zero which means we must now read the
191     // actual port that was given to us as port zero is a special code for
192     // "find an open port for me".
193     if (port == 0)
194       port = listen_socket->GetLocalPortNumber();
195
196     // Set the port predicate since when doing a listen://<host>:<port> it
197     // often needs to accept the incoming connection which is a blocking system
198     // call. Allowing access to the bound port using a predicate allows us to
199     // wait for the port predicate to be set to a non-zero value from another
200     // thread in an efficient manor.
201     if (predicate)
202       predicate->SetValue(port, eBroadcastAlways);
203     socket = listen_socket.release();
204   }
205
206   return error;
207 }
208
209 Status Socket::UdpConnect(llvm::StringRef host_and_port,
210                           bool child_processes_inherit, Socket *&socket) {
211   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
212   if (log)
213     log->Printf("Socket::%s (host/port = %s)", __FUNCTION__,
214                 host_and_port.str().c_str());
215
216   return UDPSocket::Connect(host_and_port, child_processes_inherit, socket);
217 }
218
219 Status Socket::UnixDomainConnect(llvm::StringRef name,
220                                  bool child_processes_inherit,
221                                  Socket *&socket) {
222   Status error;
223   std::unique_ptr<Socket> connect_socket(
224       Create(ProtocolUnixDomain, child_processes_inherit, error));
225   if (error.Fail())
226     return error;
227
228   error = connect_socket->Connect(name);
229   if (error.Success())
230     socket = connect_socket.release();
231
232   return error;
233 }
234
235 Status Socket::UnixDomainAccept(llvm::StringRef name,
236                                 bool child_processes_inherit, Socket *&socket) {
237   Status error;
238   std::unique_ptr<Socket> listen_socket(
239       Create(ProtocolUnixDomain, child_processes_inherit, error));
240   if (error.Fail())
241     return error;
242
243   error = listen_socket->Listen(name, 5);
244   if (error.Fail())
245     return error;
246
247   error = listen_socket->Accept(socket);
248   return error;
249 }
250
251 Status Socket::UnixAbstractConnect(llvm::StringRef name,
252                                    bool child_processes_inherit,
253                                    Socket *&socket) {
254   Status error;
255   std::unique_ptr<Socket> connect_socket(
256       Create(ProtocolUnixAbstract, child_processes_inherit, error));
257   if (error.Fail())
258     return error;
259
260   error = connect_socket->Connect(name);
261   if (error.Success())
262     socket = connect_socket.release();
263   return error;
264 }
265
266 Status Socket::UnixAbstractAccept(llvm::StringRef name,
267                                   bool child_processes_inherit,
268                                   Socket *&socket) {
269   Status error;
270   std::unique_ptr<Socket> listen_socket(
271       Create(ProtocolUnixAbstract, child_processes_inherit, error));
272   if (error.Fail())
273     return error;
274
275   error = listen_socket->Listen(name, 5);
276   if (error.Fail())
277     return error;
278
279   error = listen_socket->Accept(socket);
280   return error;
281 }
282
283 bool Socket::DecodeHostAndPort(llvm::StringRef host_and_port,
284                                std::string &host_str, std::string &port_str,
285                                int32_t &port, Status *error_ptr) {
286   static RegularExpression g_regex(
287       llvm::StringRef("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)"));
288   RegularExpression::Match regex_match(2);
289   if (g_regex.Execute(host_and_port, &regex_match)) {
290     if (regex_match.GetMatchAtIndex(host_and_port, 1, host_str) &&
291         regex_match.GetMatchAtIndex(host_and_port, 2, port_str)) {
292       // IPv6 addresses are wrapped in [] when specified with ports
293       if (host_str.front() == '[' && host_str.back() == ']')
294         host_str = host_str.substr(1, host_str.size() - 2);
295       bool ok = false;
296       port = StringConvert::ToUInt32(port_str.c_str(), UINT32_MAX, 10, &ok);
297       if (ok && port <= UINT16_MAX) {
298         if (error_ptr)
299           error_ptr->Clear();
300         return true;
301       }
302       // port is too large
303       if (error_ptr)
304         error_ptr->SetErrorStringWithFormat(
305             "invalid host:port specification: '%s'",
306             host_and_port.str().c_str());
307       return false;
308     }
309   }
310
311   // If this was unsuccessful, then check if it's simply a signed 32-bit
312   // integer, representing a port with an empty host.
313   host_str.clear();
314   port_str.clear();
315   if (to_integer(host_and_port, port, 10) && port < UINT16_MAX) {
316     port_str = host_and_port;
317     if (error_ptr)
318       error_ptr->Clear();
319     return true;
320   }
321
322   if (error_ptr)
323     error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'",
324                                         host_and_port.str().c_str());
325   return false;
326 }
327
328 IOObject::WaitableHandle Socket::GetWaitableHandle() {
329   // TODO: On Windows, use WSAEventSelect
330   return m_socket;
331 }
332
333 Status Socket::Read(void *buf, size_t &num_bytes) {
334   Status error;
335   int bytes_received = 0;
336   do {
337     bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0);
338   } while (bytes_received < 0 && IsInterrupted());
339
340   if (bytes_received < 0) {
341     SetLastError(error);
342     num_bytes = 0;
343   } else
344     num_bytes = bytes_received;
345
346   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
347   if (log) {
348     log->Printf("%p Socket::Read() (socket = %" PRIu64
349                 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
350                 " (error = %s)",
351                 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
352                 static_cast<uint64_t>(num_bytes),
353                 static_cast<int64_t>(bytes_received), error.AsCString());
354   }
355
356   return error;
357 }
358
359 Status Socket::Write(const void *buf, size_t &num_bytes) {
360   Status error;
361   int bytes_sent = 0;
362   do {
363     bytes_sent = Send(buf, num_bytes);
364   } while (bytes_sent < 0 && IsInterrupted());
365
366   if (bytes_sent < 0) {
367     SetLastError(error);
368     num_bytes = 0;
369   } else
370     num_bytes = bytes_sent;
371
372   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
373   if (log) {
374     log->Printf("%p Socket::Write() (socket = %" PRIu64
375                 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
376                 " (error = %s)",
377                 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
378                 static_cast<uint64_t>(num_bytes),
379                 static_cast<int64_t>(bytes_sent), error.AsCString());
380   }
381
382   return error;
383 }
384
385 Status Socket::PreDisconnect() {
386   Status error;
387   return error;
388 }
389
390 Status Socket::Close() {
391   Status error;
392   if (!IsValid() || !m_should_close_fd)
393     return error;
394
395   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
396   if (log)
397     log->Printf("%p Socket::Close (fd = %" PRIu64 ")",
398                 static_cast<void *>(this), static_cast<uint64_t>(m_socket));
399
400 #if defined(_WIN32)
401   bool success = !!closesocket(m_socket);
402 #else
403   bool success = !!::close(m_socket);
404 #endif
405   // A reference to a FD was passed in, set it to an invalid value
406   m_socket = kInvalidSocketValue;
407   if (!success) {
408     SetLastError(error);
409   }
410
411   return error;
412 }
413
414 int Socket::GetOption(int level, int option_name, int &option_value) {
415   get_socket_option_arg_type option_value_p =
416       reinterpret_cast<get_socket_option_arg_type>(&option_value);
417   socklen_t option_value_size = sizeof(int);
418   return ::getsockopt(m_socket, level, option_name, option_value_p,
419                       &option_value_size);
420 }
421
422 int Socket::SetOption(int level, int option_name, int option_value) {
423   set_socket_option_arg_type option_value_p =
424       reinterpret_cast<get_socket_option_arg_type>(&option_value);
425   return ::setsockopt(m_socket, level, option_name, option_value_p,
426                       sizeof(option_value));
427 }
428
429 size_t Socket::Send(const void *buf, const size_t num_bytes) {
430   return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0);
431 }
432
433 void Socket::SetLastError(Status &error) {
434 #if defined(_WIN32)
435   error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
436 #else
437   error.SetErrorToErrno();
438 #endif
439 }
440
441 NativeSocket Socket::CreateSocket(const int domain, const int type,
442                                   const int protocol,
443                                   bool child_processes_inherit, Status &error) {
444   error.Clear();
445   auto socket_type = type;
446 #ifdef SOCK_CLOEXEC
447   if (!child_processes_inherit)
448     socket_type |= SOCK_CLOEXEC;
449 #endif
450   auto sock = ::socket(domain, socket_type, protocol);
451   if (sock == kInvalidSocketValue)
452     SetLastError(error);
453
454   return sock;
455 }
456
457 NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
458                                   socklen_t *addrlen,
459                                   bool child_processes_inherit, Status &error) {
460   error.Clear();
461 #if defined(ANDROID_USE_ACCEPT_WORKAROUND)
462   // Hack:
463   // This enables static linking lldb-server to an API 21 libc, but still
464   // having it run on older devices. It is necessary because API 21 libc's
465   // implementation of accept() uses the accept4 syscall(), which is not
466   // available in older kernels. Using an older libc would fix this issue, but
467   // introduce other ones, as the old libraries were quite buggy.
468   int fd = syscall(__NR_accept, sockfd, addr, addrlen);
469   if (fd >= 0 && !child_processes_inherit) {
470     int flags = ::fcntl(fd, F_GETFD);
471     if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1)
472       return fd;
473     SetLastError(error);
474     close(fd);
475   }
476   return fd;
477 #elif defined(SOCK_CLOEXEC) && defined(HAVE_ACCEPT4)
478   int flags = 0;
479   if (!child_processes_inherit) {
480     flags |= SOCK_CLOEXEC;
481   }
482   NativeSocket fd = llvm::sys::RetryAfterSignal(-1, ::accept4,
483       sockfd, addr, addrlen, flags);
484 #else
485   NativeSocket fd = llvm::sys::RetryAfterSignal(-1, ::accept,
486       sockfd, addr, addrlen);
487 #endif
488   if (fd == kInvalidSocketValue)
489     SetLastError(error);
490   return fd;
491 }