blob: b080e38f9c823ed42b20023330c7379d3ec3ee20 [file] [log] [blame]
Zachary Turner98688922014-08-06 18:16:26 +00001//===-- 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"
Vince Harron5275aaa2015-01-15 20:08:35 +000017#include "lldb/Host/StringConvert.h"
Zachary Turner98688922014-08-06 18:16:26 +000018#include "lldb/Host/TimeValue.h"
Oleksiy Vyalove98628c2015-10-15 23:54:09 +000019#include "lldb/Host/common/TCPSocket.h"
20#include "lldb/Host/common/UDPSocket.h"
21
22#ifndef LLDB_DISABLE_POSIX
23#include "lldb/Host/posix/DomainSocket.h"
24
25#include <arpa/inet.h>
26#include <netdb.h>
27#include <netinet/in.h>
28#include <netinet/tcp.h>
29#include <sys/socket.h>
30#include <sys/un.h>
31#endif
Zachary Turner98688922014-08-06 18:16:26 +000032
Shawn Best8da0bf32014-11-08 01:41:49 +000033#ifdef __ANDROID_NDK__
34#include <linux/tcp.h>
35#include <bits/error_constants.h>
36#include <asm-generic/errno-base.h>
37#include <errno.h>
38#include <arpa/inet.h>
Chaoren Line2716582015-07-15 19:22:12 +000039#if defined(ANDROID_ARM_BUILD_STATIC)
40#include <unistd.h>
41#include <sys/syscall.h>
Tamas Berghammer28753182015-07-16 12:35:04 +000042#include <fcntl.h>
Chaoren Line2716582015-07-15 19:22:12 +000043#endif // ANDROID_ARM_BUILD_STATIC
44#endif // __ANDROID_NDK__
Shawn Best8da0bf32014-11-08 01:41:49 +000045
Zachary Turner98688922014-08-06 18:16:26 +000046using namespace lldb;
47using namespace lldb_private;
48
49#if defined(_WIN32)
50typedef const char * set_socket_option_arg_type;
51typedef char * get_socket_option_arg_type;
52const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET;
53#else // #if defined(_WIN32)
54typedef const void * set_socket_option_arg_type;
55typedef void * get_socket_option_arg_type;
56const NativeSocket Socket::kInvalidSocketValue = -1;
57#endif // #if defined(_WIN32)
58
Oleksiy Vyalov477e42a2014-11-14 16:25:18 +000059namespace {
60
Oleksiy Vyalov4e1588c2015-04-10 02:31:37 +000061bool IsInterrupted()
62{
63#if defined(_WIN32)
64 return ::WSAGetLastError() == WSAEINTR;
65#else
66 return errno == EINTR;
67#endif
68}
69
Oleksiy Vyalov477e42a2014-11-14 16:25:18 +000070}
71
Zachary Turner98688922014-08-06 18:16:26 +000072Socket::Socket(NativeSocket socket, SocketProtocol protocol, bool should_close)
73 : IOObject(eFDTypeSocket, should_close)
74 , m_protocol(protocol)
75 , m_socket(socket)
76{
77
78}
79
80Socket::~Socket()
81{
82 Close();
83}
84
Oleksiy Vyalov477e42a2014-11-14 16:25:18 +000085Error Socket::TcpConnect(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&socket)
Zachary Turner98688922014-08-06 18:16:26 +000086{
Jason Molenda67e5ba32015-07-24 22:42:03 +000087 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION));
Zachary Turner98688922014-08-06 18:16:26 +000088 if (log)
Oleksiy Vyalove98628c2015-10-15 23:54:09 +000089 log->Printf ("Socket::%s (host/port = %s)", __FUNCTION__, host_and_port.data());
Zachary Turner98688922014-08-06 18:16:26 +000090
Oleksiy Vyalove98628c2015-10-15 23:54:09 +000091 Error error;
92 std::unique_ptr<TCPSocket> connect_socket(new TCPSocket(child_processes_inherit, error));
93 if (error.Fail())
Zachary Turner98688922014-08-06 18:16:26 +000094 return error;
95
Oleksiy Vyalove98628c2015-10-15 23:54:09 +000096 error = connect_socket->Connect(host_and_port);
97 if (error.Success())
98 socket = connect_socket.release();
Zachary Turner98688922014-08-06 18:16:26 +000099
Zachary Turner98688922014-08-06 18:16:26 +0000100 return error;
101}
102
Greg Claytonfceca9b2015-07-24 16:55:00 +0000103Error
104Socket::TcpListen (llvm::StringRef host_and_port,
105 bool child_processes_inherit,
106 Socket *&socket,
107 Predicate<uint16_t>* predicate,
108 int backlog)
Zachary Turner98688922014-08-06 18:16:26 +0000109{
Zachary Turner98688922014-08-06 18:16:26 +0000110 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
111 if (log)
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000112 log->Printf ("Socket::%s (%s)", __FUNCTION__, host_and_port.data());
Zachary Turner98688922014-08-06 18:16:26 +0000113
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000114 Error error;
Zachary Turner98688922014-08-06 18:16:26 +0000115 std::string host_str;
116 std::string port_str;
117 int32_t port = INT32_MIN;
118 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error))
119 return error;
120
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000121 std::unique_ptr<TCPSocket> listen_socket(new TCPSocket(child_processes_inherit, error));
122 if (error.Fail())
123 return error;
Greg Claytonfceca9b2015-07-24 16:55:00 +0000124
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000125 error = listen_socket->Listen(host_and_port, backlog);
126 if (error.Success())
Zachary Turner98688922014-08-06 18:16:26 +0000127 {
Zachary Turner98688922014-08-06 18:16:26 +0000128 // We were asked to listen on port zero which means we
129 // must now read the actual port that was given to us
130 // as port zero is a special code for "find an open port
131 // for me".
132 if (port == 0)
Vince Harron014bb7d2015-01-16 00:47:08 +0000133 port = listen_socket->GetLocalPortNumber();
Zachary Turner98688922014-08-06 18:16:26 +0000134
135 // Set the port predicate since when doing a listen://<host>:<port>
136 // it often needs to accept the incoming connection which is a blocking
137 // system call. Allowing access to the bound port using a predicate allows
138 // us to wait for the port predicate to be set to a non-zero value from
139 // another thread in an efficient manor.
140 if (predicate)
Vince Harron014bb7d2015-01-16 00:47:08 +0000141 predicate->SetValue (port, eBroadcastAlways);
Zachary Turner98688922014-08-06 18:16:26 +0000142 socket = listen_socket.release();
143 }
144
145 return error;
146}
147
Oleksiy Vyalov477e42a2014-11-14 16:25:18 +0000148Error Socket::UdpConnect(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&send_socket, Socket *&recv_socket)
Zachary Turner98688922014-08-06 18:16:26 +0000149{
Zachary Turner98688922014-08-06 18:16:26 +0000150 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
151 if (log)
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000152 log->Printf ("Socket::%s (host/port = %s)", __FUNCTION__, host_and_port.data());
Zachary Turner98688922014-08-06 18:16:26 +0000153
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000154 return UDPSocket::Connect(host_and_port, child_processes_inherit, send_socket, recv_socket);
Zachary Turner98688922014-08-06 18:16:26 +0000155}
156
Oleksiy Vyalov477e42a2014-11-14 16:25:18 +0000157Error Socket::UnixDomainConnect(llvm::StringRef name, bool child_processes_inherit, Socket *&socket)
Zachary Turner98688922014-08-06 18:16:26 +0000158{
159 Error error;
160#ifndef LLDB_DISABLE_POSIX
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000161 std::unique_ptr<DomainSocket> connect_socket(new DomainSocket(child_processes_inherit, error));
162 if (error.Fail())
Zachary Turner98688922014-08-06 18:16:26 +0000163 return error;
Zachary Turner98688922014-08-06 18:16:26 +0000164
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000165 error = connect_socket->Connect(name);
166 if (error.Success())
167 socket = connect_socket.release();
Zachary Turner98688922014-08-06 18:16:26 +0000168#else
169 error.SetErrorString("Unix domain sockets are not supported on this platform.");
170#endif
171 return error;
172}
173
Oleksiy Vyalov477e42a2014-11-14 16:25:18 +0000174Error Socket::UnixDomainAccept(llvm::StringRef name, bool child_processes_inherit, Socket *&socket)
Zachary Turner98688922014-08-06 18:16:26 +0000175{
176 Error error;
177#ifndef LLDB_DISABLE_POSIX
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000178 std::unique_ptr<DomainSocket> listen_socket(new DomainSocket(child_processes_inherit, error));
179 if (error.Fail())
Zachary Turner98688922014-08-06 18:16:26 +0000180 return error;
Zachary Turner98688922014-08-06 18:16:26 +0000181
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000182 error = listen_socket->Listen(name, 5);
183 if (error.Fail())
Zachary Turner98688922014-08-06 18:16:26 +0000184 return error;
Zachary Turner98688922014-08-06 18:16:26 +0000185
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000186 error = listen_socket->Accept(name, child_processes_inherit, socket);
Zachary Turner98688922014-08-06 18:16:26 +0000187#else
188 error.SetErrorString("Unix domain sockets are not supported on this platform.");
189#endif
190 return error;
191}
192
193bool
194Socket::DecodeHostAndPort(llvm::StringRef host_and_port,
195 std::string &host_str,
196 std::string &port_str,
197 int32_t& port,
198 Error *error_ptr)
199{
200 static RegularExpression g_regex ("([^:]+):([0-9]+)");
201 RegularExpression::Match regex_match(2);
202 if (g_regex.Execute (host_and_port.data(), &regex_match))
203 {
204 if (regex_match.GetMatchAtIndex (host_and_port.data(), 1, host_str) &&
205 regex_match.GetMatchAtIndex (host_and_port.data(), 2, port_str))
206 {
Vince Harron014bb7d2015-01-16 00:47:08 +0000207 bool ok = false;
208 port = StringConvert::ToUInt32 (port_str.c_str(), UINT32_MAX, 10, &ok);
209 if (ok && port < UINT16_MAX)
Zachary Turner98688922014-08-06 18:16:26 +0000210 {
211 if (error_ptr)
212 error_ptr->Clear();
213 return true;
214 }
Vince Harron014bb7d2015-01-16 00:47:08 +0000215 // port is too large
216 if (error_ptr)
217 error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port.data());
218 return false;
Zachary Turner98688922014-08-06 18:16:26 +0000219 }
220 }
221
222 // If this was unsuccessful, then check if it's simply a signed 32-bit integer, representing
223 // a port with an empty host.
224 host_str.clear();
225 port_str.clear();
Vince Harron014bb7d2015-01-16 00:47:08 +0000226 bool ok = false;
227 port = StringConvert::ToUInt32 (host_and_port.data(), UINT32_MAX, 10, &ok);
228 if (ok && port < UINT16_MAX)
Zachary Turner98688922014-08-06 18:16:26 +0000229 {
230 port_str = host_and_port;
Vince Harron014bb7d2015-01-16 00:47:08 +0000231 if (error_ptr)
232 error_ptr->Clear();
Zachary Turner98688922014-08-06 18:16:26 +0000233 return true;
234 }
235
236 if (error_ptr)
237 error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port.data());
238 return false;
239}
240
241IOObject::WaitableHandle Socket::GetWaitableHandle()
242{
243 // TODO: On Windows, use WSAEventSelect
244 return m_socket;
245}
246
247Error Socket::Read (void *buf, size_t &num_bytes)
248{
249 Error error;
250 int bytes_received = 0;
251 do
252 {
253 bytes_received = ::recv (m_socket, static_cast<char *>(buf), num_bytes, 0);
Oleksiy Vyalov4e1588c2015-04-10 02:31:37 +0000254 } while (bytes_received < 0 && IsInterrupted ());
Zachary Turner98688922014-08-06 18:16:26 +0000255
256 if (bytes_received < 0)
257 {
Oleksiy Vyalov4e1588c2015-04-10 02:31:37 +0000258 SetLastError (error);
Zachary Turner98688922014-08-06 18:16:26 +0000259 num_bytes = 0;
260 }
261 else
262 num_bytes = bytes_received;
263
Jason Molenda67e5ba32015-07-24 22:42:03 +0000264 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION));
Zachary Turner98688922014-08-06 18:16:26 +0000265 if (log)
266 {
267 log->Printf ("%p Socket::Read() (socket = %" PRIu64 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
268 static_cast<void*>(this),
269 static_cast<uint64_t>(m_socket),
270 buf,
271 static_cast<uint64_t>(num_bytes),
272 static_cast<int64_t>(bytes_received),
273 error.AsCString());
274 }
275
276 return error;
277}
278
279Error Socket::Write (const void *buf, size_t &num_bytes)
280{
281 Error error;
282 int bytes_sent = 0;
283 do
284 {
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000285 bytes_sent = Send(buf, num_bytes);
Oleksiy Vyalov4e1588c2015-04-10 02:31:37 +0000286 } while (bytes_sent < 0 && IsInterrupted ());
Zachary Turner98688922014-08-06 18:16:26 +0000287
288 if (bytes_sent < 0)
289 {
Oleksiy Vyalov4e1588c2015-04-10 02:31:37 +0000290 SetLastError (error);
Zachary Turner98688922014-08-06 18:16:26 +0000291 num_bytes = 0;
292 }
293 else
294 num_bytes = bytes_sent;
295
Jason Molenda67e5ba32015-07-24 22:42:03 +0000296 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION));
Zachary Turner98688922014-08-06 18:16:26 +0000297 if (log)
298 {
299 log->Printf ("%p Socket::Write() (socket = %" PRIu64 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
300 static_cast<void*>(this),
301 static_cast<uint64_t>(m_socket),
302 buf,
303 static_cast<uint64_t>(num_bytes),
304 static_cast<int64_t>(bytes_sent),
305 error.AsCString());
306 }
307
308 return error;
309}
310
311Error Socket::PreDisconnect()
312{
313 Error error;
314 return error;
315}
316
317Error Socket::Close()
318{
319 Error error;
320 if (!IsValid() || !m_should_close_fd)
321 return error;
322
323 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
324 if (log)
325 log->Printf ("%p Socket::Close (fd = %i)", static_cast<void*>(this), m_socket);
326
327#if defined(_WIN32)
328 bool success = !!closesocket(m_socket);
329#else
330 bool success = !!::close (m_socket);
331#endif
332 // A reference to a FD was passed in, set it to an invalid value
333 m_socket = kInvalidSocketValue;
334 if (!success)
335 {
Oleksiy Vyalov4e1588c2015-04-10 02:31:37 +0000336 SetLastError (error);
Zachary Turner98688922014-08-06 18:16:26 +0000337 }
338
339 return error;
340}
341
342
343int Socket::GetOption(int level, int option_name, int &option_value)
344{
345 get_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
346 socklen_t option_value_size = sizeof(int);
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000347 return ::getsockopt(m_socket, level, option_name, option_value_p, &option_value_size);
Zachary Turner98688922014-08-06 18:16:26 +0000348}
349
350int Socket::SetOption(int level, int option_name, int option_value)
351{
352 set_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000353 return ::setsockopt(m_socket, level, option_name, option_value_p, sizeof(option_value));
Zachary Turner98688922014-08-06 18:16:26 +0000354}
355
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000356size_t Socket::Send(const void *buf, const size_t num_bytes)
Zachary Turner98688922014-08-06 18:16:26 +0000357{
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000358 return ::send (m_socket, static_cast<const char *>(buf), num_bytes, 0);
359}
360
361void Socket::SetLastError(Error &error)
362{
363#if defined(_WIN32)
364 error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
365#else
366 error.SetErrorToErrno();
367#endif
368}
369
370NativeSocket
371Socket::CreateSocket(const int domain,
372 const int type,
373 const int protocol,
374 bool child_processes_inherit,
375 Error& error)
376{
377 error.Clear();
378 auto socketType = type;
379#ifdef SOCK_CLOEXEC
380 if (!child_processes_inherit)
381 socketType |= SOCK_CLOEXEC;
382#endif
383 auto sock = ::socket (domain, socketType, protocol);
384 if (sock == kInvalidSocketValue)
385 SetLastError(error);
386
387 return sock;
388}
389
390NativeSocket
391Socket::AcceptSocket(NativeSocket sockfd,
392 struct sockaddr *addr,
393 socklen_t *addrlen,
394 bool child_processes_inherit,
395 Error& error)
396{
397 error.Clear();
398#if defined(ANDROID_ARM_BUILD_STATIC)
399 // Temporary workaround for statically linking Android lldb-server with the
400 // latest API.
401 int fd = syscall(__NR_accept, sockfd, addr, addrlen);
402 if (fd >= 0 && !child_processes_inherit)
Zachary Turner98688922014-08-06 18:16:26 +0000403 {
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000404 int flags = ::fcntl(fd, F_GETFD);
405 if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1)
406 return fd;
407 SetLastError(error);
408 close(fd);
Zachary Turner98688922014-08-06 18:16:26 +0000409 }
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000410 return fd;
411#elif defined(SOCK_CLOEXEC)
412 int flags = 0;
413 if (!child_processes_inherit) {
414 flags |= SOCK_CLOEXEC;
Vince Harron014bb7d2015-01-16 00:47:08 +0000415 }
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000416#if defined(__NetBSD__)
417 NativeSocket fd = ::paccept (sockfd, addr, addrlen, nullptr, flags);
418#else
419 NativeSocket fd = ::accept4 (sockfd, addr, addrlen, flags);
420#endif
421#else
422 NativeSocket fd = ::accept (sockfd, addr, addrlen);
423#endif
424 if (fd == kInvalidSocketValue)
425 SetLastError(error);
426 return fd;
Vince Harron014bb7d2015-01-16 00:47:08 +0000427}