1 //===-- Socket.cpp ----------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/Host/Socket.h"
11 
12 #include "lldb/Host/Config.h"
13 #include "lldb/Host/Host.h"
14 #include "lldb/Host/SocketAddress.h"
15 #include "lldb/Host/StringConvert.h"
16 #include "lldb/Host/common/TCPSocket.h"
17 #include "lldb/Host/common/UDPSocket.h"
18 #include "lldb/Utility/Log.h"
19 #include "lldb/Utility/RegularExpression.h"
20 
21 #include "llvm/ADT/STLExtras.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 #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                                        Error &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 Error 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   Error 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 Error 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   Error 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
163     // must now read the actual port that was given to us
164     // as port zero is a special code for "find an open port
165     // for me".
166     if (port == 0)
167       port = listen_socket->GetLocalPortNumber();
168 
169     // Set the port predicate since when doing a listen://<host>:<port>
170     // it often needs to accept the incoming connection which is a blocking
171     // system call. Allowing access to the bound port using a predicate allows
172     // us to wait for the port predicate to be set to a non-zero value from
173     // another 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 Error 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 Error Socket::UnixDomainConnect(llvm::StringRef name,
193                                 bool child_processes_inherit, Socket *&socket) {
194   Error 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 Error Socket::UnixDomainAccept(llvm::StringRef name,
208                                bool child_processes_inherit, Socket *&socket) {
209   Error 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 Error Socket::UnixAbstractConnect(llvm::StringRef name,
224                                   bool child_processes_inherit,
225                                   Socket *&socket) {
226   Error 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 Error Socket::UnixAbstractAccept(llvm::StringRef name,
239                                  bool child_processes_inherit,
240                                  Socket *&socket) {
241   Error 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, Error *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
284   // a port with an empty host.
285   host_str.clear();
286   port_str.clear();
287   bool ok = false;
288   port = StringConvert::ToUInt32(host_and_port.data(), UINT32_MAX, 10, &ok);
289   if (ok && port < UINT16_MAX) {
290     port_str = host_and_port;
291     if (error_ptr)
292       error_ptr->Clear();
293     return true;
294   }
295 
296   if (error_ptr)
297     error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'",
298                                         host_and_port.data());
299   return false;
300 }
301 
302 IOObject::WaitableHandle Socket::GetWaitableHandle() {
303   // TODO: On Windows, use WSAEventSelect
304   return m_socket;
305 }
306 
307 Error Socket::Read(void *buf, size_t &num_bytes) {
308   Error error;
309   int bytes_received = 0;
310   do {
311     bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0);
312   } while (bytes_received < 0 && IsInterrupted());
313 
314   if (bytes_received < 0) {
315     SetLastError(error);
316     num_bytes = 0;
317   } else
318     num_bytes = bytes_received;
319 
320   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
321   if (log) {
322     log->Printf("%p Socket::Read() (socket = %" PRIu64
323                 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
324                 " (error = %s)",
325                 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
326                 static_cast<uint64_t>(num_bytes),
327                 static_cast<int64_t>(bytes_received), error.AsCString());
328   }
329 
330   return error;
331 }
332 
333 Error Socket::Write(const void *buf, size_t &num_bytes) {
334   Error error;
335   int bytes_sent = 0;
336   do {
337     bytes_sent = Send(buf, num_bytes);
338   } while (bytes_sent < 0 && IsInterrupted());
339 
340   if (bytes_sent < 0) {
341     SetLastError(error);
342     num_bytes = 0;
343   } else
344     num_bytes = bytes_sent;
345 
346   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
347   if (log) {
348     log->Printf("%p Socket::Write() (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_sent), error.AsCString());
354   }
355 
356   return error;
357 }
358 
359 Error Socket::PreDisconnect() {
360   Error error;
361   return error;
362 }
363 
364 Error Socket::Close() {
365   Error error;
366   if (!IsValid() || !m_should_close_fd)
367     return error;
368 
369   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
370   if (log)
371     log->Printf("%p Socket::Close (fd = %i)", static_cast<void *>(this),
372                 m_socket);
373 
374 #if defined(_WIN32)
375   bool success = !!closesocket(m_socket);
376 #else
377   bool success = !!::close(m_socket);
378 #endif
379   // A reference to a FD was passed in, set it to an invalid value
380   m_socket = kInvalidSocketValue;
381   if (!success) {
382     SetLastError(error);
383   }
384 
385   return error;
386 }
387 
388 int Socket::GetOption(int level, int option_name, int &option_value) {
389   get_socket_option_arg_type option_value_p =
390       reinterpret_cast<get_socket_option_arg_type>(&option_value);
391   socklen_t option_value_size = sizeof(int);
392   return ::getsockopt(m_socket, level, option_name, option_value_p,
393                       &option_value_size);
394 }
395 
396 int Socket::SetOption(int level, int option_name, int option_value) {
397   set_socket_option_arg_type option_value_p =
398       reinterpret_cast<get_socket_option_arg_type>(&option_value);
399   return ::setsockopt(m_socket, level, option_name, option_value_p,
400                       sizeof(option_value));
401 }
402 
403 size_t Socket::Send(const void *buf, const size_t num_bytes) {
404   return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0);
405 }
406 
407 void Socket::SetLastError(Error &error) {
408 #if defined(_WIN32)
409   error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
410 #else
411   error.SetErrorToErrno();
412 #endif
413 }
414 
415 NativeSocket Socket::CreateSocket(const int domain, const int type,
416                                   const int protocol,
417                                   bool child_processes_inherit, Error &error) {
418   error.Clear();
419   auto socket_type = type;
420 #ifdef SOCK_CLOEXEC
421   if (!child_processes_inherit)
422     socket_type |= SOCK_CLOEXEC;
423 #endif
424   auto sock = ::socket(domain, socket_type, protocol);
425   if (sock == kInvalidSocketValue)
426     SetLastError(error);
427 
428   return sock;
429 }
430 
431 NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
432                                   socklen_t *addrlen,
433                                   bool child_processes_inherit, Error &error) {
434   error.Clear();
435 #if defined(ANDROID_USE_ACCEPT_WORKAROUND)
436   // Hack:
437   // This enables static linking lldb-server to an API 21 libc, but still having
438   // it run on older devices. It is necessary because API 21 libc's
439   // implementation of accept() uses the accept4 syscall(), which is not
440   // available in older kernels. Using an older libc would fix this issue, but
441   // introduce other ones, as the old libraries were quite buggy.
442   int fd = syscall(__NR_accept, sockfd, addr, addrlen);
443   if (fd >= 0 && !child_processes_inherit) {
444     int flags = ::fcntl(fd, F_GETFD);
445     if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1)
446       return fd;
447     SetLastError(error);
448     close(fd);
449   }
450   return fd;
451 #elif defined(SOCK_CLOEXEC)
452   int flags = 0;
453   if (!child_processes_inherit) {
454     flags |= SOCK_CLOEXEC;
455   }
456   NativeSocket fd = ::accept4(sockfd, addr, addrlen, flags);
457 #else
458   NativeSocket fd = ::accept(sockfd, addr, addrlen);
459 #endif
460   if (fd == kInvalidSocketValue)
461     SetLastError(error);
462   return fd;
463 }
464