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 #ifndef LLDB_DISABLE_POSIX
22 #include "lldb/Host/posix/DomainSocket.h"
23 
24 #include <arpa/inet.h>
25 #include <netdb.h>
26 #include <netinet/in.h>
27 #include <netinet/tcp.h>
28 #include <sys/socket.h>
29 #include <sys/un.h>
30 #endif
31 
32 #ifdef __linux__
33 #include "lldb/Host/linux/AbstractSocket.h"
34 #endif
35 
36 #ifdef __ANDROID__
37 #include <arpa/inet.h>
38 #include <asm-generic/errno-base.h>
39 #include <errno.h>
40 #include <linux/tcp.h>
41 #include <fcntl.h>
42 #include <sys/syscall.h>
43 #include <unistd.h>
44 #endif // __ANDROID__
45 
46 using namespace lldb;
47 using namespace lldb_private;
48 
49 #if defined(_WIN32)
50 typedef const char *set_socket_option_arg_type;
51 typedef char *get_socket_option_arg_type;
52 const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET;
53 #else  // #if defined(_WIN32)
54 typedef const void *set_socket_option_arg_type;
55 typedef void *get_socket_option_arg_type;
56 const NativeSocket Socket::kInvalidSocketValue = -1;
57 #endif // #if defined(_WIN32)
58 
59 namespace {
60 
61 bool IsInterrupted() {
62 #if defined(_WIN32)
63   return ::WSAGetLastError() == WSAEINTR;
64 #else
65   return errno == EINTR;
66 #endif
67 }
68 }
69 
70 Socket::Socket(NativeSocket socket, SocketProtocol protocol, bool should_close)
71     : IOObject(eFDTypeSocket, should_close), m_protocol(protocol),
72       m_socket(socket) {}
73 
74 Socket::~Socket() { Close(); }
75 
76 std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol,
77                                        bool child_processes_inherit,
78                                        Error &error) {
79   error.Clear();
80 
81   std::unique_ptr<Socket> socket_up;
82   switch (protocol) {
83   case ProtocolTcp:
84     socket_up.reset(new TCPSocket(child_processes_inherit, error));
85     break;
86   case ProtocolUdp:
87     socket_up.reset(new UDPSocket(child_processes_inherit, error));
88     break;
89   case ProtocolUnixDomain:
90 #ifndef LLDB_DISABLE_POSIX
91     socket_up.reset(new DomainSocket(child_processes_inherit, error));
92 #else
93     error.SetErrorString(
94         "Unix domain sockets are not supported on this platform.");
95 #endif
96     break;
97   case ProtocolUnixAbstract:
98 #ifdef __linux__
99     socket_up.reset(new AbstractSocket(child_processes_inherit, error));
100 #else
101     error.SetErrorString(
102         "Abstract domain sockets are not supported on this platform.");
103 #endif
104     break;
105   }
106 
107   if (error.Fail())
108     socket_up.reset();
109 
110   return socket_up;
111 }
112 
113 Error Socket::TcpConnect(llvm::StringRef host_and_port,
114                          bool child_processes_inherit, Socket *&socket) {
115   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
116   if (log)
117     log->Printf("Socket::%s (host/port = %s)", __FUNCTION__,
118                 host_and_port.data());
119 
120   Error error;
121   std::unique_ptr<Socket> connect_socket(
122       Create(ProtocolTcp, child_processes_inherit, error));
123   if (error.Fail())
124     return error;
125 
126   error = connect_socket->Connect(host_and_port);
127   if (error.Success())
128     socket = connect_socket.release();
129 
130   return error;
131 }
132 
133 Error Socket::TcpListen(llvm::StringRef host_and_port,
134                         bool child_processes_inherit, Socket *&socket,
135                         Predicate<uint16_t> *predicate, int backlog) {
136   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
137   if (log)
138     log->Printf("Socket::%s (%s)", __FUNCTION__, host_and_port.data());
139 
140   Error error;
141   std::string host_str;
142   std::string port_str;
143   int32_t port = INT32_MIN;
144   if (!DecodeHostAndPort(host_and_port, host_str, port_str, port, &error))
145     return error;
146 
147   std::unique_ptr<TCPSocket> listen_socket(
148       new TCPSocket(child_processes_inherit, error));
149   if (error.Fail())
150     return error;
151 
152   error = listen_socket->Listen(host_and_port, backlog);
153   if (error.Success()) {
154     // We were asked to listen on port zero which means we
155     // must now read the actual port that was given to us
156     // as port zero is a special code for "find an open port
157     // for me".
158     if (port == 0)
159       port = listen_socket->GetLocalPortNumber();
160 
161     // Set the port predicate since when doing a listen://<host>:<port>
162     // it often needs to accept the incoming connection which is a blocking
163     // system call. Allowing access to the bound port using a predicate allows
164     // us to wait for the port predicate to be set to a non-zero value from
165     // another thread in an efficient manor.
166     if (predicate)
167       predicate->SetValue(port, eBroadcastAlways);
168     socket = listen_socket.release();
169   }
170 
171   return error;
172 }
173 
174 Error Socket::UdpConnect(llvm::StringRef host_and_port,
175                          bool child_processes_inherit, Socket *&socket) {
176   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
177   if (log)
178     log->Printf("Socket::%s (host/port = %s)", __FUNCTION__,
179                 host_and_port.data());
180 
181   return UDPSocket::Connect(host_and_port, child_processes_inherit, socket);
182 }
183 
184 Error Socket::UnixDomainConnect(llvm::StringRef name,
185                                 bool child_processes_inherit, Socket *&socket) {
186   Error error;
187   std::unique_ptr<Socket> connect_socket(
188       Create(ProtocolUnixDomain, child_processes_inherit, error));
189   if (error.Fail())
190     return error;
191 
192   error = connect_socket->Connect(name);
193   if (error.Success())
194     socket = connect_socket.release();
195 
196   return error;
197 }
198 
199 Error Socket::UnixDomainAccept(llvm::StringRef name,
200                                bool child_processes_inherit, Socket *&socket) {
201   Error error;
202   std::unique_ptr<Socket> listen_socket(
203       Create(ProtocolUnixDomain, child_processes_inherit, error));
204   if (error.Fail())
205     return error;
206 
207   error = listen_socket->Listen(name, 5);
208   if (error.Fail())
209     return error;
210 
211   error = listen_socket->Accept(name, child_processes_inherit, socket);
212   return error;
213 }
214 
215 Error Socket::UnixAbstractConnect(llvm::StringRef name,
216                                   bool child_processes_inherit,
217                                   Socket *&socket) {
218   Error error;
219   std::unique_ptr<Socket> connect_socket(
220       Create(ProtocolUnixAbstract, child_processes_inherit, error));
221   if (error.Fail())
222     return error;
223 
224   error = connect_socket->Connect(name);
225   if (error.Success())
226     socket = connect_socket.release();
227   return error;
228 }
229 
230 Error Socket::UnixAbstractAccept(llvm::StringRef name,
231                                  bool child_processes_inherit,
232                                  Socket *&socket) {
233   Error error;
234   std::unique_ptr<Socket> listen_socket(
235       Create(ProtocolUnixAbstract, child_processes_inherit, error));
236   if (error.Fail())
237     return error;
238 
239   error = listen_socket->Listen(name, 5);
240   if (error.Fail())
241     return error;
242 
243   error = listen_socket->Accept(name, child_processes_inherit, socket);
244   return error;
245 }
246 
247 bool Socket::DecodeHostAndPort(llvm::StringRef host_and_port,
248                                std::string &host_str, std::string &port_str,
249                                int32_t &port, Error *error_ptr) {
250   static RegularExpression g_regex(llvm::StringRef("([^:]+):([0-9]+)"));
251   RegularExpression::Match regex_match(2);
252   if (g_regex.Execute(host_and_port, &regex_match)) {
253     if (regex_match.GetMatchAtIndex(host_and_port.data(), 1, host_str) &&
254         regex_match.GetMatchAtIndex(host_and_port.data(), 2, port_str)) {
255       bool ok = false;
256       port = StringConvert::ToUInt32(port_str.c_str(), UINT32_MAX, 10, &ok);
257       if (ok && port <= UINT16_MAX) {
258         if (error_ptr)
259           error_ptr->Clear();
260         return true;
261       }
262       // port is too large
263       if (error_ptr)
264         error_ptr->SetErrorStringWithFormat(
265             "invalid host:port specification: '%s'", host_and_port.data());
266       return false;
267     }
268   }
269 
270   // If this was unsuccessful, then check if it's simply a signed 32-bit
271   // integer, representing
272   // a port with an empty host.
273   host_str.clear();
274   port_str.clear();
275   bool ok = false;
276   port = StringConvert::ToUInt32(host_and_port.data(), UINT32_MAX, 10, &ok);
277   if (ok && port < UINT16_MAX) {
278     port_str = host_and_port;
279     if (error_ptr)
280       error_ptr->Clear();
281     return true;
282   }
283 
284   if (error_ptr)
285     error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'",
286                                         host_and_port.data());
287   return false;
288 }
289 
290 IOObject::WaitableHandle Socket::GetWaitableHandle() {
291   // TODO: On Windows, use WSAEventSelect
292   return m_socket;
293 }
294 
295 Error Socket::Read(void *buf, size_t &num_bytes) {
296   Error error;
297   int bytes_received = 0;
298   do {
299     bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0);
300   } while (bytes_received < 0 && IsInterrupted());
301 
302   if (bytes_received < 0) {
303     SetLastError(error);
304     num_bytes = 0;
305   } else
306     num_bytes = bytes_received;
307 
308   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
309   if (log) {
310     log->Printf("%p Socket::Read() (socket = %" PRIu64
311                 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
312                 " (error = %s)",
313                 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
314                 static_cast<uint64_t>(num_bytes),
315                 static_cast<int64_t>(bytes_received), error.AsCString());
316   }
317 
318   return error;
319 }
320 
321 Error Socket::Write(const void *buf, size_t &num_bytes) {
322   Error error;
323   int bytes_sent = 0;
324   do {
325     bytes_sent = Send(buf, num_bytes);
326   } while (bytes_sent < 0 && IsInterrupted());
327 
328   if (bytes_sent < 0) {
329     SetLastError(error);
330     num_bytes = 0;
331   } else
332     num_bytes = bytes_sent;
333 
334   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
335   if (log) {
336     log->Printf("%p Socket::Write() (socket = %" PRIu64
337                 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
338                 " (error = %s)",
339                 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
340                 static_cast<uint64_t>(num_bytes),
341                 static_cast<int64_t>(bytes_sent), error.AsCString());
342   }
343 
344   return error;
345 }
346 
347 Error Socket::PreDisconnect() {
348   Error error;
349   return error;
350 }
351 
352 Error Socket::Close() {
353   Error error;
354   if (!IsValid() || !m_should_close_fd)
355     return error;
356 
357   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
358   if (log)
359     log->Printf("%p Socket::Close (fd = %i)", static_cast<void *>(this),
360                 m_socket);
361 
362 #if defined(_WIN32)
363   bool success = !!closesocket(m_socket);
364 #else
365   bool success = !!::close(m_socket);
366 #endif
367   // A reference to a FD was passed in, set it to an invalid value
368   m_socket = kInvalidSocketValue;
369   if (!success) {
370     SetLastError(error);
371   }
372 
373   return error;
374 }
375 
376 int Socket::GetOption(int level, int option_name, int &option_value) {
377   get_socket_option_arg_type option_value_p =
378       reinterpret_cast<get_socket_option_arg_type>(&option_value);
379   socklen_t option_value_size = sizeof(int);
380   return ::getsockopt(m_socket, level, option_name, option_value_p,
381                       &option_value_size);
382 }
383 
384 int Socket::SetOption(int level, int option_name, int option_value) {
385   set_socket_option_arg_type option_value_p =
386       reinterpret_cast<get_socket_option_arg_type>(&option_value);
387   return ::setsockopt(m_socket, level, option_name, option_value_p,
388                       sizeof(option_value));
389 }
390 
391 size_t Socket::Send(const void *buf, const size_t num_bytes) {
392   return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0);
393 }
394 
395 void Socket::SetLastError(Error &error) {
396 #if defined(_WIN32)
397   error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
398 #else
399   error.SetErrorToErrno();
400 #endif
401 }
402 
403 NativeSocket Socket::CreateSocket(const int domain, const int type,
404                                   const int protocol,
405                                   bool child_processes_inherit, Error &error) {
406   error.Clear();
407   auto socketType = type;
408 #ifdef SOCK_CLOEXEC
409   if (!child_processes_inherit)
410     socketType |= SOCK_CLOEXEC;
411 #endif
412   auto sock = ::socket(domain, socketType, protocol);
413   if (sock == kInvalidSocketValue)
414     SetLastError(error);
415 
416   return sock;
417 }
418 
419 NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
420                                   socklen_t *addrlen,
421                                   bool child_processes_inherit, Error &error) {
422   error.Clear();
423 #if defined(ANDROID_USE_ACCEPT_WORKAROUND)
424   // Hack:
425   // This enables static linking lldb-server to an API 21 libc, but still having
426   // it run on older devices. It is necessary because API 21 libc's
427   // implementation of accept() uses the accept4 syscall(), which is not
428   // available in older kernels. Using an older libc would fix this issue, but
429   // introduce other ones, as the old libraries were quite buggy.
430   int fd = syscall(__NR_accept, sockfd, addr, addrlen);
431   if (fd >= 0 && !child_processes_inherit) {
432     int flags = ::fcntl(fd, F_GETFD);
433     if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1)
434       return fd;
435     SetLastError(error);
436     close(fd);
437   }
438   return fd;
439 #elif defined(SOCK_CLOEXEC)
440   int flags = 0;
441   if (!child_processes_inherit) {
442     flags |= SOCK_CLOEXEC;
443   }
444   NativeSocket fd = ::accept4(sockfd, addr, addrlen, flags);
445 #else
446   NativeSocket fd = ::accept(sockfd, addr, addrlen);
447 #endif
448   if (fd == kInvalidSocketValue)
449     SetLastError(error);
450   return fd;
451 }
452