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