blob: ea049ae6933e415ef433d71efffba0b6a890ecdf [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
Oleksiy Vyalov179c51e2015-10-22 17:50:33 +000033#ifdef __linux__
34#include "lldb/Host/linux/AbstractSocket.h"
35#endif
36
Shawn Best8da0bf32014-11-08 01:41:49 +000037#ifdef __ANDROID_NDK__
38#include <linux/tcp.h>
39#include <bits/error_constants.h>
40#include <asm-generic/errno-base.h>
41#include <errno.h>
42#include <arpa/inet.h>
Chaoren Lin33942822015-10-27 19:17:35 +000043#if defined(ANDROID_ARM_BUILD_STATIC) || defined(ANDROID_MIPS_BUILD_STATIC)
Chaoren Line2716582015-07-15 19:22:12 +000044#include <unistd.h>
45#include <sys/syscall.h>
Tamas Berghammer28753182015-07-16 12:35:04 +000046#include <fcntl.h>
Chaoren Lin33942822015-10-27 19:17:35 +000047#endif // ANDROID_ARM_BUILD_STATIC || ANDROID_MIPS_BUILD_STATIC
Chaoren Line2716582015-07-15 19:22:12 +000048#endif // __ANDROID_NDK__
Shawn Best8da0bf32014-11-08 01:41:49 +000049
Zachary Turner98688922014-08-06 18:16:26 +000050using namespace lldb;
51using namespace lldb_private;
52
53#if defined(_WIN32)
54typedef const char * set_socket_option_arg_type;
55typedef char * get_socket_option_arg_type;
56const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET;
57#else // #if defined(_WIN32)
58typedef const void * set_socket_option_arg_type;
59typedef void * get_socket_option_arg_type;
60const NativeSocket Socket::kInvalidSocketValue = -1;
61#endif // #if defined(_WIN32)
62
Oleksiy Vyalov477e42a2014-11-14 16:25:18 +000063namespace {
64
Oleksiy Vyalov4e1588c2015-04-10 02:31:37 +000065bool IsInterrupted()
66{
67#if defined(_WIN32)
68 return ::WSAGetLastError() == WSAEINTR;
69#else
70 return errno == EINTR;
71#endif
72}
73
Oleksiy Vyalov477e42a2014-11-14 16:25:18 +000074}
75
Zachary Turner98688922014-08-06 18:16:26 +000076Socket::Socket(NativeSocket socket, SocketProtocol protocol, bool should_close)
77 : IOObject(eFDTypeSocket, should_close)
78 , m_protocol(protocol)
79 , m_socket(socket)
80{
81
82}
83
84Socket::~Socket()
85{
86 Close();
87}
88
Oleksiy Vyalovdb4d9862015-10-27 17:32:01 +000089std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol, bool child_processes_inherit, Error &error)
90{
91 error.Clear();
92
93 std::unique_ptr<Socket> socket_up;
94 switch (protocol)
95 {
96 case ProtocolTcp:
97 socket_up.reset(new TCPSocket(child_processes_inherit, error));
98 break;
99 case ProtocolUdp:
100 socket_up.reset(new UDPSocket(child_processes_inherit, error));
101 break;
102 case ProtocolUnixDomain:
103#ifndef LLDB_DISABLE_POSIX
104 socket_up.reset(new DomainSocket(child_processes_inherit, error));
105#else
106 error.SetErrorString("Unix domain sockets are not supported on this platform.");
107#endif
108 break;
109 case ProtocolUnixAbstract:
110#ifdef __linux__
111 socket_up.reset(new AbstractSocket(child_processes_inherit, error));
112#else
113 error.SetErrorString("Abstract domain sockets are not supported on this platform.");
114#endif
115 break;
116 }
117
118 if (error.Fail())
119 socket_up.reset();
120
121 return socket_up;
122}
123
Oleksiy Vyalov477e42a2014-11-14 16:25:18 +0000124Error Socket::TcpConnect(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&socket)
Zachary Turner98688922014-08-06 18:16:26 +0000125{
Jason Molenda67e5ba32015-07-24 22:42:03 +0000126 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION));
Zachary Turner98688922014-08-06 18:16:26 +0000127 if (log)
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000128 log->Printf ("Socket::%s (host/port = %s)", __FUNCTION__, host_and_port.data());
Zachary Turner98688922014-08-06 18:16:26 +0000129
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000130 Error error;
Oleksiy Vyalovdb4d9862015-10-27 17:32:01 +0000131 std::unique_ptr<Socket> connect_socket(Create(ProtocolTcp, child_processes_inherit, error));
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000132 if (error.Fail())
Zachary Turner98688922014-08-06 18:16:26 +0000133 return error;
134
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000135 error = connect_socket->Connect(host_and_port);
136 if (error.Success())
137 socket = connect_socket.release();
Zachary Turner98688922014-08-06 18:16:26 +0000138
Zachary Turner98688922014-08-06 18:16:26 +0000139 return error;
140}
141
Greg Claytonfceca9b2015-07-24 16:55:00 +0000142Error
143Socket::TcpListen (llvm::StringRef host_and_port,
144 bool child_processes_inherit,
145 Socket *&socket,
146 Predicate<uint16_t>* predicate,
147 int backlog)
Zachary Turner98688922014-08-06 18:16:26 +0000148{
Zachary Turner98688922014-08-06 18:16:26 +0000149 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
150 if (log)
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000151 log->Printf ("Socket::%s (%s)", __FUNCTION__, host_and_port.data());
Zachary Turner98688922014-08-06 18:16:26 +0000152
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000153 Error error;
Zachary Turner98688922014-08-06 18:16:26 +0000154 std::string host_str;
155 std::string port_str;
156 int32_t port = INT32_MIN;
157 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error))
158 return error;
159
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000160 std::unique_ptr<TCPSocket> listen_socket(new TCPSocket(child_processes_inherit, error));
161 if (error.Fail())
162 return error;
Greg Claytonfceca9b2015-07-24 16:55:00 +0000163
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000164 error = listen_socket->Listen(host_and_port, backlog);
165 if (error.Success())
Zachary Turner98688922014-08-06 18:16:26 +0000166 {
Zachary Turner98688922014-08-06 18:16:26 +0000167 // We were asked to listen on port zero which means we
168 // must now read the actual port that was given to us
169 // as port zero is a special code for "find an open port
170 // for me".
171 if (port == 0)
Vince Harron014bb7d2015-01-16 00:47:08 +0000172 port = listen_socket->GetLocalPortNumber();
Zachary Turner98688922014-08-06 18:16:26 +0000173
174 // Set the port predicate since when doing a listen://<host>:<port>
175 // it often needs to accept the incoming connection which is a blocking
176 // system call. Allowing access to the bound port using a predicate allows
177 // us to wait for the port predicate to be set to a non-zero value from
178 // another thread in an efficient manor.
179 if (predicate)
Vince Harron014bb7d2015-01-16 00:47:08 +0000180 predicate->SetValue (port, eBroadcastAlways);
Zachary Turner98688922014-08-06 18:16:26 +0000181 socket = listen_socket.release();
182 }
183
184 return error;
185}
186
Oleksiy Vyalov477e42a2014-11-14 16:25:18 +0000187Error Socket::UdpConnect(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&send_socket, Socket *&recv_socket)
Zachary Turner98688922014-08-06 18:16:26 +0000188{
Zachary Turner98688922014-08-06 18:16:26 +0000189 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
190 if (log)
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000191 log->Printf ("Socket::%s (host/port = %s)", __FUNCTION__, host_and_port.data());
Zachary Turner98688922014-08-06 18:16:26 +0000192
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000193 return UDPSocket::Connect(host_and_port, child_processes_inherit, send_socket, recv_socket);
Zachary Turner98688922014-08-06 18:16:26 +0000194}
195
Oleksiy Vyalov477e42a2014-11-14 16:25:18 +0000196Error Socket::UnixDomainConnect(llvm::StringRef name, bool child_processes_inherit, Socket *&socket)
Zachary Turner98688922014-08-06 18:16:26 +0000197{
198 Error error;
Oleksiy Vyalovdb4d9862015-10-27 17:32:01 +0000199 std::unique_ptr<Socket> connect_socket(Create(ProtocolUnixDomain, child_processes_inherit, error));
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000200 if (error.Fail())
Zachary Turner98688922014-08-06 18:16:26 +0000201 return error;
Zachary Turner98688922014-08-06 18:16:26 +0000202
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000203 error = connect_socket->Connect(name);
204 if (error.Success())
205 socket = connect_socket.release();
Oleksiy Vyalovdb4d9862015-10-27 17:32:01 +0000206
Zachary Turner98688922014-08-06 18:16:26 +0000207 return error;
208}
209
Oleksiy Vyalov477e42a2014-11-14 16:25:18 +0000210Error Socket::UnixDomainAccept(llvm::StringRef name, bool child_processes_inherit, Socket *&socket)
Zachary Turner98688922014-08-06 18:16:26 +0000211{
212 Error error;
Oleksiy Vyalovdb4d9862015-10-27 17:32:01 +0000213 std::unique_ptr<Socket> listen_socket(Create(ProtocolUnixDomain, child_processes_inherit, error));
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000214 if (error.Fail())
Zachary Turner98688922014-08-06 18:16:26 +0000215 return error;
Zachary Turner98688922014-08-06 18:16:26 +0000216
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000217 error = listen_socket->Listen(name, 5);
218 if (error.Fail())
Zachary Turner98688922014-08-06 18:16:26 +0000219 return error;
Zachary Turner98688922014-08-06 18:16:26 +0000220
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000221 error = listen_socket->Accept(name, child_processes_inherit, socket);
Zachary Turner98688922014-08-06 18:16:26 +0000222 return error;
223}
224
Oleksiy Vyalov179c51e2015-10-22 17:50:33 +0000225Error
226Socket::UnixAbstractConnect(llvm::StringRef name, bool child_processes_inherit, Socket *&socket)
227{
228 Error error;
Oleksiy Vyalovdb4d9862015-10-27 17:32:01 +0000229 std::unique_ptr<Socket> connect_socket(Create(ProtocolUnixAbstract, child_processes_inherit, error));
Oleksiy Vyalov179c51e2015-10-22 17:50:33 +0000230 if (error.Fail())
231 return error;
232
233 error = connect_socket->Connect(name);
234 if (error.Success())
235 socket = connect_socket.release();
Oleksiy Vyalov179c51e2015-10-22 17:50:33 +0000236 return error;
237}
238
239Error
240Socket::UnixAbstractAccept(llvm::StringRef name, bool child_processes_inherit, Socket *&socket)
241{
242 Error error;
Oleksiy Vyalovdb4d9862015-10-27 17:32:01 +0000243 std::unique_ptr<Socket> listen_socket(Create(ProtocolUnixAbstract,child_processes_inherit, error));
Oleksiy Vyalov179c51e2015-10-22 17:50:33 +0000244 if (error.Fail())
245 return error;
246
247 error = listen_socket->Listen(name, 5);
248 if (error.Fail())
249 return error;
250
251 error = listen_socket->Accept(name, child_processes_inherit, socket);
Oleksiy Vyalov179c51e2015-10-22 17:50:33 +0000252 return error;
253}
254
Zachary Turner98688922014-08-06 18:16:26 +0000255bool
256Socket::DecodeHostAndPort(llvm::StringRef host_and_port,
257 std::string &host_str,
258 std::string &port_str,
259 int32_t& port,
260 Error *error_ptr)
261{
262 static RegularExpression g_regex ("([^:]+):([0-9]+)");
263 RegularExpression::Match regex_match(2);
264 if (g_regex.Execute (host_and_port.data(), &regex_match))
265 {
266 if (regex_match.GetMatchAtIndex (host_and_port.data(), 1, host_str) &&
267 regex_match.GetMatchAtIndex (host_and_port.data(), 2, port_str))
268 {
Vince Harron014bb7d2015-01-16 00:47:08 +0000269 bool ok = false;
270 port = StringConvert::ToUInt32 (port_str.c_str(), UINT32_MAX, 10, &ok);
Pavel Labath1b58f5c2016-02-03 11:12:23 +0000271 if (ok && port <= UINT16_MAX)
Zachary Turner98688922014-08-06 18:16:26 +0000272 {
273 if (error_ptr)
274 error_ptr->Clear();
275 return true;
276 }
Vince Harron014bb7d2015-01-16 00:47:08 +0000277 // port is too large
278 if (error_ptr)
279 error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port.data());
280 return false;
Zachary Turner98688922014-08-06 18:16:26 +0000281 }
282 }
283
284 // If this was unsuccessful, then check if it's simply a signed 32-bit integer, representing
285 // a port with an empty host.
286 host_str.clear();
287 port_str.clear();
Vince Harron014bb7d2015-01-16 00:47:08 +0000288 bool ok = false;
289 port = StringConvert::ToUInt32 (host_and_port.data(), UINT32_MAX, 10, &ok);
290 if (ok && port < UINT16_MAX)
Zachary Turner98688922014-08-06 18:16:26 +0000291 {
292 port_str = host_and_port;
Vince Harron014bb7d2015-01-16 00:47:08 +0000293 if (error_ptr)
294 error_ptr->Clear();
Zachary Turner98688922014-08-06 18:16:26 +0000295 return true;
296 }
297
298 if (error_ptr)
299 error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port.data());
300 return false;
301}
302
303IOObject::WaitableHandle Socket::GetWaitableHandle()
304{
305 // TODO: On Windows, use WSAEventSelect
306 return m_socket;
307}
308
309Error Socket::Read (void *buf, size_t &num_bytes)
310{
311 Error error;
312 int bytes_received = 0;
313 do
314 {
315 bytes_received = ::recv (m_socket, static_cast<char *>(buf), num_bytes, 0);
Oleksiy Vyalov4e1588c2015-04-10 02:31:37 +0000316 } while (bytes_received < 0 && IsInterrupted ());
Zachary Turner98688922014-08-06 18:16:26 +0000317
318 if (bytes_received < 0)
319 {
Oleksiy Vyalov4e1588c2015-04-10 02:31:37 +0000320 SetLastError (error);
Zachary Turner98688922014-08-06 18:16:26 +0000321 num_bytes = 0;
322 }
323 else
324 num_bytes = bytes_received;
325
Jason Molenda67e5ba32015-07-24 22:42:03 +0000326 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION));
Zachary Turner98688922014-08-06 18:16:26 +0000327 if (log)
328 {
329 log->Printf ("%p Socket::Read() (socket = %" PRIu64 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
330 static_cast<void*>(this),
331 static_cast<uint64_t>(m_socket),
332 buf,
333 static_cast<uint64_t>(num_bytes),
334 static_cast<int64_t>(bytes_received),
335 error.AsCString());
336 }
337
338 return error;
339}
340
341Error Socket::Write (const void *buf, size_t &num_bytes)
342{
343 Error error;
344 int bytes_sent = 0;
345 do
346 {
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000347 bytes_sent = Send(buf, num_bytes);
Oleksiy Vyalov4e1588c2015-04-10 02:31:37 +0000348 } while (bytes_sent < 0 && IsInterrupted ());
Zachary Turner98688922014-08-06 18:16:26 +0000349
350 if (bytes_sent < 0)
351 {
Oleksiy Vyalov4e1588c2015-04-10 02:31:37 +0000352 SetLastError (error);
Zachary Turner98688922014-08-06 18:16:26 +0000353 num_bytes = 0;
354 }
355 else
356 num_bytes = bytes_sent;
357
Jason Molenda67e5ba32015-07-24 22:42:03 +0000358 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION));
Zachary Turner98688922014-08-06 18:16:26 +0000359 if (log)
360 {
361 log->Printf ("%p Socket::Write() (socket = %" PRIu64 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
362 static_cast<void*>(this),
363 static_cast<uint64_t>(m_socket),
364 buf,
365 static_cast<uint64_t>(num_bytes),
366 static_cast<int64_t>(bytes_sent),
367 error.AsCString());
368 }
369
370 return error;
371}
372
373Error Socket::PreDisconnect()
374{
375 Error error;
376 return error;
377}
378
379Error Socket::Close()
380{
381 Error error;
382 if (!IsValid() || !m_should_close_fd)
383 return error;
384
385 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
386 if (log)
387 log->Printf ("%p Socket::Close (fd = %i)", static_cast<void*>(this), m_socket);
388
389#if defined(_WIN32)
390 bool success = !!closesocket(m_socket);
391#else
392 bool success = !!::close (m_socket);
393#endif
394 // A reference to a FD was passed in, set it to an invalid value
395 m_socket = kInvalidSocketValue;
396 if (!success)
397 {
Oleksiy Vyalov4e1588c2015-04-10 02:31:37 +0000398 SetLastError (error);
Zachary Turner98688922014-08-06 18:16:26 +0000399 }
400
401 return error;
402}
403
404
405int Socket::GetOption(int level, int option_name, int &option_value)
406{
407 get_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
408 socklen_t option_value_size = sizeof(int);
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000409 return ::getsockopt(m_socket, level, option_name, option_value_p, &option_value_size);
Zachary Turner98688922014-08-06 18:16:26 +0000410}
411
412int Socket::SetOption(int level, int option_name, int option_value)
413{
414 set_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000415 return ::setsockopt(m_socket, level, option_name, option_value_p, sizeof(option_value));
Zachary Turner98688922014-08-06 18:16:26 +0000416}
417
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000418size_t Socket::Send(const void *buf, const size_t num_bytes)
Zachary Turner98688922014-08-06 18:16:26 +0000419{
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000420 return ::send (m_socket, static_cast<const char *>(buf), num_bytes, 0);
421}
422
423void Socket::SetLastError(Error &error)
424{
425#if defined(_WIN32)
426 error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
427#else
428 error.SetErrorToErrno();
429#endif
430}
431
432NativeSocket
433Socket::CreateSocket(const int domain,
434 const int type,
435 const int protocol,
436 bool child_processes_inherit,
437 Error& error)
438{
439 error.Clear();
440 auto socketType = type;
441#ifdef SOCK_CLOEXEC
442 if (!child_processes_inherit)
443 socketType |= SOCK_CLOEXEC;
444#endif
445 auto sock = ::socket (domain, socketType, protocol);
446 if (sock == kInvalidSocketValue)
447 SetLastError(error);
448
449 return sock;
450}
451
452NativeSocket
453Socket::AcceptSocket(NativeSocket sockfd,
454 struct sockaddr *addr,
455 socklen_t *addrlen,
456 bool child_processes_inherit,
457 Error& error)
458{
459 error.Clear();
Chaoren Lin33942822015-10-27 19:17:35 +0000460#if defined(ANDROID_ARM_BUILD_STATIC) || defined(ANDROID_MIPS_BUILD_STATIC)
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000461 // Temporary workaround for statically linking Android lldb-server with the
462 // latest API.
463 int fd = syscall(__NR_accept, sockfd, addr, addrlen);
464 if (fd >= 0 && !child_processes_inherit)
Zachary Turner98688922014-08-06 18:16:26 +0000465 {
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000466 int flags = ::fcntl(fd, F_GETFD);
467 if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1)
468 return fd;
469 SetLastError(error);
470 close(fd);
Zachary Turner98688922014-08-06 18:16:26 +0000471 }
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000472 return fd;
473#elif defined(SOCK_CLOEXEC)
474 int flags = 0;
475 if (!child_processes_inherit) {
476 flags |= SOCK_CLOEXEC;
Vince Harron014bb7d2015-01-16 00:47:08 +0000477 }
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000478#if defined(__NetBSD__)
479 NativeSocket fd = ::paccept (sockfd, addr, addrlen, nullptr, flags);
480#else
481 NativeSocket fd = ::accept4 (sockfd, addr, addrlen, flags);
482#endif
483#else
484 NativeSocket fd = ::accept (sockfd, addr, addrlen);
485#endif
486 if (fd == kInvalidSocketValue)
487 SetLastError(error);
488 return fd;
Vince Harron014bb7d2015-01-16 00:47:08 +0000489}