Socket.cpp revision 309124
1149871Sscottl//===-- Socket.cpp ----------------------------------------------*- C++ -*-===// 2149871Sscottl// 3136849Sscottl// The LLVM Compiler Infrastructure 4136849Sscottl// 5136849Sscottl// This file is distributed under the University of Illinois Open Source 6136849Sscottl// License. See LICENSE.TXT for details. 7136849Sscottl// 8136849Sscottl//===----------------------------------------------------------------------===// 9136849Sscottl 10136849Sscottl#include "lldb/Host/Socket.h" 11136849Sscottl 12136849Sscottl#include "lldb/Core/Log.h" 13136849Sscottl#include "lldb/Core/RegularExpression.h" 14136849Sscottl#include "lldb/Host/Config.h" 15136849Sscottl#include "lldb/Host/Host.h" 16136849Sscottl#include "lldb/Host/SocketAddress.h" 17136849Sscottl#include "lldb/Host/StringConvert.h" 18136849Sscottl#include "lldb/Host/TimeValue.h" 19136849Sscottl#include "lldb/Host/common/TCPSocket.h" 20136849Sscottl#include "lldb/Host/common/UDPSocket.h" 21136849Sscottl 22136849Sscottl#ifndef LLDB_DISABLE_POSIX 23136849Sscottl#include "lldb/Host/posix/DomainSocket.h" 24136849Sscottl 25136849Sscottl#include <arpa/inet.h> 26136849Sscottl#include <netdb.h> 27136849Sscottl#include <netinet/in.h> 28136849Sscottl#include <netinet/tcp.h> 29136849Sscottl#include <sys/socket.h> 30136849Sscottl#include <sys/un.h> 31153072Sru#endif 32136849Sscottl 33136849Sscottl#ifdef __linux__ 34136849Sscottl#include "lldb/Host/linux/AbstractSocket.h" 35136849Sscottl#endif 36136849Sscottl 37136849Sscottl#ifdef __ANDROID_NDK__ 38136849Sscottl#include <linux/tcp.h> 39149871Sscottl#include <bits/error_constants.h> 40149871Sscottl#include <asm-generic/errno-base.h> 41136849Sscottl#include <errno.h> 42149871Sscottl#include <arpa/inet.h> 43136849Sscottl#if defined(ANDROID_ARM_BUILD_STATIC) || defined(ANDROID_MIPS_BUILD_STATIC) 44136849Sscottl#include <unistd.h> 45136849Sscottl#include <sys/syscall.h> 46136849Sscottl#include <fcntl.h> 47136849Sscottl#endif // ANDROID_ARM_BUILD_STATIC || ANDROID_MIPS_BUILD_STATIC 48136849Sscottl#endif // __ANDROID_NDK__ 49149871Sscottl 50149871Sscottlusing namespace lldb; 51149871Sscottlusing namespace lldb_private; 52149871Sscottl 53149871Sscottl#if defined(_WIN32) 54149871Sscottltypedef const char * set_socket_option_arg_type; 55149871Sscottltypedef char * get_socket_option_arg_type; 56149871Sscottlconst NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET; 57136849Sscottl#else // #if defined(_WIN32) 58136849Sscottltypedef const void * set_socket_option_arg_type; 59136849Sscottltypedef void * get_socket_option_arg_type; 60136849Sscottlconst NativeSocket Socket::kInvalidSocketValue = -1; 61136849Sscottl#endif // #if defined(_WIN32) 62136849Sscottl 63136849Sscottlnamespace { 64149871Sscottl 65136849Sscottlbool IsInterrupted() 66136849Sscottl{ 67136849Sscottl#if defined(_WIN32) 68136849Sscottl return ::WSAGetLastError() == WSAEINTR; 69136849Sscottl#else 70136849Sscottl return errno == EINTR; 71149871Sscottl#endif 72149871Sscottl} 73149871Sscottl 74149871Sscottl} 75136849Sscottl 76149871SscottlSocket::Socket(NativeSocket socket, SocketProtocol protocol, bool should_close) 77149871Sscottl : IOObject(eFDTypeSocket, should_close) 78149871Sscottl , m_protocol(protocol) 79149871Sscottl , m_socket(socket) 80149871Sscottl{ 81149871Sscottl 82149871Sscottl} 83149871Sscottl 84149871SscottlSocket::~Socket() 85149871Sscottl{ 86136849Sscottl Close(); 87136849Sscottl} 88136849Sscottl 89136849Sscottlstd::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol, bool child_processes_inherit, Error &error) 90136849Sscottl{ 91136849Sscottl error.Clear(); 92136849Sscottl 93136849Sscottl std::unique_ptr<Socket> socket_up; 94136849Sscottl switch (protocol) 95136849Sscottl { 96136849Sscottl case ProtocolTcp: 97136849Sscottl socket_up.reset(new TCPSocket(child_processes_inherit, error)); 98149871Sscottl break; 99149871Sscottl case ProtocolUdp: 100149871Sscottl socket_up.reset(new UDPSocket(child_processes_inherit, error)); 101136849Sscottl break; 102136849Sscottl case ProtocolUnixDomain: 103136849Sscottl#ifndef LLDB_DISABLE_POSIX 104136849Sscottl socket_up.reset(new DomainSocket(child_processes_inherit, error)); 105136849Sscottl#else 106136849Sscottl error.SetErrorString("Unix domain sockets are not supported on this platform."); 107136849Sscottl#endif 108136849Sscottl break; 109136849Sscottl case ProtocolUnixAbstract: 110136849Sscottl#ifdef __linux__ 111136849Sscottl socket_up.reset(new AbstractSocket(child_processes_inherit, error)); 112136849Sscottl#else 113136849Sscottl error.SetErrorString("Abstract domain sockets are not supported on this platform."); 114136849Sscottl#endif 115149871Sscottl break; 116149871Sscottl } 117149871Sscottl 118136849Sscottl if (error.Fail()) 119136849Sscottl socket_up.reset(); 120136849Sscottl 121136849Sscottl return socket_up; 122136849Sscottl} 123136849Sscottl 124136849SscottlError Socket::TcpConnect(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&socket) 125136849Sscottl{ 126149871Sscottl Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION)); 127136849Sscottl if (log) 128136849Sscottl log->Printf ("Socket::%s (host/port = %s)", __FUNCTION__, host_and_port.data()); 129136849Sscottl 130136849Sscottl Error error; 131136849Sscottl std::unique_ptr<Socket> connect_socket(Create(ProtocolTcp, child_processes_inherit, error)); 132136849Sscottl if (error.Fail()) 133136849Sscottl return error; 134153072Sru 135149871Sscottl error = connect_socket->Connect(host_and_port); 136149871Sscottl if (error.Success()) 137149871Sscottl socket = connect_socket.release(); 138149871Sscottl 139136849Sscottl return error; 140136849Sscottl} 141136849Sscottl 142136849SscottlError 143136849SscottlSocket::TcpListen (llvm::StringRef host_and_port, 144149871Sscottl bool child_processes_inherit, 145136849Sscottl Socket *&socket, 146136849Sscottl Predicate<uint16_t>* predicate, 147136849Sscottl int backlog) 148136849Sscottl{ 149136849Sscottl Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION)); 150136849Sscottl if (log) 151136849Sscottl log->Printf ("Socket::%s (%s)", __FUNCTION__, host_and_port.data()); 152149871Sscottl 153 Error error; 154 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 160 std::unique_ptr<TCPSocket> listen_socket(new TCPSocket(child_processes_inherit, error)); 161 if (error.Fail()) 162 return error; 163 164 error = listen_socket->Listen(host_and_port, backlog); 165 if (error.Success()) 166 { 167 // 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) 172 port = listen_socket->GetLocalPortNumber(); 173 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) 180 predicate->SetValue (port, eBroadcastAlways); 181 socket = listen_socket.release(); 182 } 183 184 return error; 185} 186 187Error Socket::UdpConnect(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&send_socket, Socket *&recv_socket) 188{ 189 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION)); 190 if (log) 191 log->Printf ("Socket::%s (host/port = %s)", __FUNCTION__, host_and_port.data()); 192 193 return UDPSocket::Connect(host_and_port, child_processes_inherit, send_socket, recv_socket); 194} 195 196Error Socket::UnixDomainConnect(llvm::StringRef name, bool child_processes_inherit, Socket *&socket) 197{ 198 Error error; 199 std::unique_ptr<Socket> connect_socket(Create(ProtocolUnixDomain, child_processes_inherit, error)); 200 if (error.Fail()) 201 return error; 202 203 error = connect_socket->Connect(name); 204 if (error.Success()) 205 socket = connect_socket.release(); 206 207 return error; 208} 209 210Error Socket::UnixDomainAccept(llvm::StringRef name, bool child_processes_inherit, Socket *&socket) 211{ 212 Error error; 213 std::unique_ptr<Socket> listen_socket(Create(ProtocolUnixDomain, child_processes_inherit, error)); 214 if (error.Fail()) 215 return error; 216 217 error = listen_socket->Listen(name, 5); 218 if (error.Fail()) 219 return error; 220 221 error = listen_socket->Accept(name, child_processes_inherit, socket); 222 return error; 223} 224 225Error 226Socket::UnixAbstractConnect(llvm::StringRef name, bool child_processes_inherit, Socket *&socket) 227{ 228 Error error; 229 std::unique_ptr<Socket> connect_socket(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 239Error 240Socket::UnixAbstractAccept(llvm::StringRef name, bool child_processes_inherit, Socket *&socket) 241{ 242 Error error; 243 std::unique_ptr<Socket> listen_socket(Create(ProtocolUnixAbstract,child_processes_inherit, error)); 244 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); 252 return error; 253} 254 255bool 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(), ®ex_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 { 269 bool ok = false; 270 port = StringConvert::ToUInt32 (port_str.c_str(), UINT32_MAX, 10, &ok); 271 if (ok && port <= UINT16_MAX) 272 { 273 if (error_ptr) 274 error_ptr->Clear(); 275 return true; 276 } 277 // port is too large 278 if (error_ptr) 279 error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port.data()); 280 return false; 281 } 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(); 288 bool ok = false; 289 port = StringConvert::ToUInt32 (host_and_port.data(), UINT32_MAX, 10, &ok); 290 if (ok && port < UINT16_MAX) 291 { 292 port_str = host_and_port; 293 if (error_ptr) 294 error_ptr->Clear(); 295 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); 316 } while (bytes_received < 0 && IsInterrupted ()); 317 318 if (bytes_received < 0) 319 { 320 SetLastError (error); 321 num_bytes = 0; 322 } 323 else 324 num_bytes = bytes_received; 325 326 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION)); 327 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 { 347 bytes_sent = Send(buf, num_bytes); 348 } while (bytes_sent < 0 && IsInterrupted ()); 349 350 if (bytes_sent < 0) 351 { 352 SetLastError (error); 353 num_bytes = 0; 354 } 355 else 356 num_bytes = bytes_sent; 357 358 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION)); 359 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 { 398 SetLastError (error); 399 } 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); 409 return ::getsockopt(m_socket, level, option_name, option_value_p, &option_value_size); 410} 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); 415 return ::setsockopt(m_socket, level, option_name, option_value_p, sizeof(option_value)); 416} 417 418size_t Socket::Send(const void *buf, const size_t num_bytes) 419{ 420 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(); 460#if defined(ANDROID_ARM_BUILD_STATIC) || defined(ANDROID_MIPS_BUILD_STATIC) 461 // 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) 465 { 466 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); 471 } 472 return fd; 473#elif defined(SOCK_CLOEXEC) 474 int flags = 0; 475 if (!child_processes_inherit) { 476 flags |= SOCK_CLOEXEC; 477 } 478#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; 489} 490