Socket.cpp revision 341825
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#include <unistd.h>
33#endif
34
35#ifdef __linux__
36#include "lldb/Host/linux/AbstractSocket.h"
37#endif
38
39#ifdef __ANDROID__
40#include <arpa/inet.h>
41#include <asm-generic/errno-base.h>
42#include <errno.h>
43#include <linux/tcp.h>
44#include <fcntl.h>
45#include <sys/syscall.h>
46#include <unistd.h>
47#endif // __ANDROID__
48
49using namespace lldb;
50using namespace lldb_private;
51
52#if defined(_WIN32)
53typedef const char *set_socket_option_arg_type;
54typedef char *get_socket_option_arg_type;
55const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET;
56#else  // #if defined(_WIN32)
57typedef const void *set_socket_option_arg_type;
58typedef void *get_socket_option_arg_type;
59const NativeSocket Socket::kInvalidSocketValue = -1;
60#endif // #if defined(_WIN32)
61
62namespace {
63
64bool IsInterrupted() {
65#if defined(_WIN32)
66  return ::WSAGetLastError() == WSAEINTR;
67#else
68  return errno == EINTR;
69#endif
70}
71}
72
73Socket::Socket(SocketProtocol protocol, bool should_close,
74               bool child_processes_inherit)
75    : IOObject(eFDTypeSocket, should_close), m_protocol(protocol),
76      m_socket(kInvalidSocketValue),
77      m_child_processes_inherit(child_processes_inherit) {}
78
79Socket::~Socket() { Close(); }
80
81std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol,
82                                       bool child_processes_inherit,
83                                       Status &error) {
84  error.Clear();
85
86  std::unique_ptr<Socket> socket_up;
87  switch (protocol) {
88  case ProtocolTcp:
89    socket_up =
90        llvm::make_unique<TCPSocket>(true, child_processes_inherit);
91    break;
92  case ProtocolUdp:
93    socket_up =
94        llvm::make_unique<UDPSocket>(true, child_processes_inherit);
95    break;
96  case ProtocolUnixDomain:
97#ifndef LLDB_DISABLE_POSIX
98    socket_up =
99        llvm::make_unique<DomainSocket>(true, child_processes_inherit);
100#else
101    error.SetErrorString(
102        "Unix domain sockets are not supported on this platform.");
103#endif
104    break;
105  case ProtocolUnixAbstract:
106#ifdef __linux__
107    socket_up =
108        llvm::make_unique<AbstractSocket>(child_processes_inherit);
109#else
110    error.SetErrorString(
111        "Abstract domain sockets are not supported on this platform.");
112#endif
113    break;
114  }
115
116  if (error.Fail())
117    socket_up.reset();
118
119  return socket_up;
120}
121
122Status Socket::TcpConnect(llvm::StringRef host_and_port,
123                          bool child_processes_inherit, Socket *&socket) {
124  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
125  if (log)
126    log->Printf("Socket::%s (host/port = %s)", __FUNCTION__,
127                host_and_port.data());
128
129  Status error;
130  std::unique_ptr<Socket> connect_socket(
131      Create(ProtocolTcp, child_processes_inherit, error));
132  if (error.Fail())
133    return error;
134
135  error = connect_socket->Connect(host_and_port);
136  if (error.Success())
137    socket = connect_socket.release();
138
139  return error;
140}
141
142Status Socket::TcpListen(llvm::StringRef host_and_port,
143                         bool child_processes_inherit, Socket *&socket,
144                         Predicate<uint16_t> *predicate, int backlog) {
145  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
146  if (log)
147    log->Printf("Socket::%s (%s)", __FUNCTION__, host_and_port.data());
148
149  Status error;
150  std::string host_str;
151  std::string port_str;
152  int32_t port = INT32_MIN;
153  if (!DecodeHostAndPort(host_and_port, host_str, port_str, port, &error))
154    return error;
155
156  std::unique_ptr<TCPSocket> listen_socket(
157      new TCPSocket(true, child_processes_inherit));
158  if (error.Fail())
159    return error;
160
161  error = listen_socket->Listen(host_and_port, backlog);
162  if (error.Success()) {
163    // We were asked to listen on port zero which means we must now read the
164    // actual port that was given to us as port zero is a special code for
165    // "find an open port for me".
166    if (port == 0)
167      port = listen_socket->GetLocalPortNumber();
168
169    // Set the port predicate since when doing a listen://<host>:<port> it
170    // often needs to accept the incoming connection which is a blocking system
171    // call. Allowing access to the bound port using a predicate allows us to
172    // wait for the port predicate to be set to a non-zero value from another
173    // 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
182Status 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
192Status 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
208Status 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
224Status 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
239Status 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
256bool 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 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
302IOObject::WaitableHandle Socket::GetWaitableHandle() {
303  // TODO: On Windows, use WSAEventSelect
304  return m_socket;
305}
306
307Status Socket::Read(void *buf, size_t &num_bytes) {
308  Status 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
333Status Socket::Write(const void *buf, size_t &num_bytes) {
334  Status 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
359Status Socket::PreDisconnect() {
360  Status error;
361  return error;
362}
363
364Status Socket::Close() {
365  Status 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
388int 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
396int 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
403size_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
407void Socket::SetLastError(Status &error) {
408#if defined(_WIN32)
409  error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
410#else
411  error.SetErrorToErrno();
412#endif
413}
414
415NativeSocket Socket::CreateSocket(const int domain, const int type,
416                                  const int protocol,
417                                  bool child_processes_inherit, Status &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
431NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
432                                  socklen_t *addrlen,
433                                  bool child_processes_inherit, Status &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
438  // having 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) && defined(HAVE_ACCEPT4)
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