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