Socket.cpp revision 321369
1284345Ssjg//===-- Socket.cpp ----------------------------------------------*- C++ -*-===// 2284345Ssjg// 3284345Ssjg// The LLVM Compiler Infrastructure 4284345Ssjg// 5284345Ssjg// This file is distributed under the University of Illinois Open Source 6284345Ssjg// License. See LICENSE.TXT for details. 7284345Ssjg// 8284345Ssjg//===----------------------------------------------------------------------===// 9284345Ssjg 10284345Ssjg#include "lldb/Host/Socket.h" 11284345Ssjg 12284345Ssjg#include "lldb/Host/Config.h" 13284345Ssjg#include "lldb/Host/Host.h" 14284345Ssjg#include "lldb/Host/SocketAddress.h" 15284345Ssjg#include "lldb/Host/StringConvert.h" 16284345Ssjg#include "lldb/Host/common/TCPSocket.h" 17284345Ssjg#include "lldb/Host/common/UDPSocket.h" 18284345Ssjg#include "lldb/Utility/Log.h" 19284345Ssjg#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 164 // must now read the actual port that was given to us 165 // as port zero is a special code for "find an open port 166 // for me". 167 if (port == 0) 168 port = listen_socket->GetLocalPortNumber(); 169 170 // Set the port predicate since when doing a listen://<host>:<port> 171 // it often needs to accept the incoming connection which is a blocking 172 // system call. Allowing access to the bound port using a predicate allows 173 // us to wait for the port predicate to be set to a non-zero value from 174 // another thread in an efficient manor. 175 if (predicate) 176 predicate->SetValue(port, eBroadcastAlways); 177 socket = listen_socket.release(); 178 } 179 180 return error; 181} 182 183Status Socket::UdpConnect(llvm::StringRef host_and_port, 184 bool child_processes_inherit, Socket *&socket) { 185 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); 186 if (log) 187 log->Printf("Socket::%s (host/port = %s)", __FUNCTION__, 188 host_and_port.data()); 189 190 return UDPSocket::Connect(host_and_port, child_processes_inherit, socket); 191} 192 193Status Socket::UnixDomainConnect(llvm::StringRef name, 194 bool child_processes_inherit, 195 Socket *&socket) { 196 Status error; 197 std::unique_ptr<Socket> connect_socket( 198 Create(ProtocolUnixDomain, child_processes_inherit, error)); 199 if (error.Fail()) 200 return error; 201 202 error = connect_socket->Connect(name); 203 if (error.Success()) 204 socket = connect_socket.release(); 205 206 return error; 207} 208 209Status Socket::UnixDomainAccept(llvm::StringRef name, 210 bool child_processes_inherit, Socket *&socket) { 211 Status error; 212 std::unique_ptr<Socket> listen_socket( 213 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(socket); 222 return error; 223} 224 225Status Socket::UnixAbstractConnect(llvm::StringRef name, 226 bool child_processes_inherit, 227 Socket *&socket) { 228 Status error; 229 std::unique_ptr<Socket> connect_socket( 230 Create(ProtocolUnixAbstract, child_processes_inherit, error)); 231 if (error.Fail()) 232 return error; 233 234 error = connect_socket->Connect(name); 235 if (error.Success()) 236 socket = connect_socket.release(); 237 return error; 238} 239 240Status Socket::UnixAbstractAccept(llvm::StringRef name, 241 bool child_processes_inherit, 242 Socket *&socket) { 243 Status error; 244 std::unique_ptr<Socket> listen_socket( 245 Create(ProtocolUnixAbstract, child_processes_inherit, error)); 246 if (error.Fail()) 247 return error; 248 249 error = listen_socket->Listen(name, 5); 250 if (error.Fail()) 251 return error; 252 253 error = listen_socket->Accept(socket); 254 return error; 255} 256 257bool Socket::DecodeHostAndPort(llvm::StringRef host_and_port, 258 std::string &host_str, std::string &port_str, 259 int32_t &port, Status *error_ptr) { 260 static RegularExpression g_regex( 261 llvm::StringRef("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)")); 262 RegularExpression::Match regex_match(2); 263 if (g_regex.Execute(host_and_port, ®ex_match)) { 264 if (regex_match.GetMatchAtIndex(host_and_port.data(), 1, host_str) && 265 regex_match.GetMatchAtIndex(host_and_port.data(), 2, port_str)) { 266 // IPv6 addresses are wrapped in [] when specified with ports 267 if (host_str.front() == '[' && host_str.back() == ']') 268 host_str = host_str.substr(1, host_str.size() - 2); 269 bool ok = false; 270 port = StringConvert::ToUInt32(port_str.c_str(), UINT32_MAX, 10, &ok); 271 if (ok && port <= UINT16_MAX) { 272 if (error_ptr) 273 error_ptr->Clear(); 274 return true; 275 } 276 // port is too large 277 if (error_ptr) 278 error_ptr->SetErrorStringWithFormat( 279 "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 285 // integer, representing 286 // a port with an empty host. 287 host_str.clear(); 288 port_str.clear(); 289 bool ok = false; 290 port = StringConvert::ToUInt32(host_and_port.data(), UINT32_MAX, 10, &ok); 291 if (ok && port < UINT16_MAX) { 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'", 300 host_and_port.data()); 301 return false; 302} 303 304IOObject::WaitableHandle Socket::GetWaitableHandle() { 305 // TODO: On Windows, use WSAEventSelect 306 return m_socket; 307} 308 309Status Socket::Read(void *buf, size_t &num_bytes) { 310 Status error; 311 int bytes_received = 0; 312 do { 313 bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0); 314 } while (bytes_received < 0 && IsInterrupted()); 315 316 if (bytes_received < 0) { 317 SetLastError(error); 318 num_bytes = 0; 319 } else 320 num_bytes = bytes_received; 321 322 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION)); 323 if (log) { 324 log->Printf("%p Socket::Read() (socket = %" PRIu64 325 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 326 " (error = %s)", 327 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf, 328 static_cast<uint64_t>(num_bytes), 329 static_cast<int64_t>(bytes_received), error.AsCString()); 330 } 331 332 return error; 333} 334 335Status Socket::Write(const void *buf, size_t &num_bytes) { 336 Status error; 337 int bytes_sent = 0; 338 do { 339 bytes_sent = Send(buf, num_bytes); 340 } while (bytes_sent < 0 && IsInterrupted()); 341 342 if (bytes_sent < 0) { 343 SetLastError(error); 344 num_bytes = 0; 345 } else 346 num_bytes = bytes_sent; 347 348 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION)); 349 if (log) { 350 log->Printf("%p Socket::Write() (socket = %" PRIu64 351 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 352 " (error = %s)", 353 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf, 354 static_cast<uint64_t>(num_bytes), 355 static_cast<int64_t>(bytes_sent), error.AsCString()); 356 } 357 358 return error; 359} 360 361Status Socket::PreDisconnect() { 362 Status error; 363 return error; 364} 365 366Status Socket::Close() { 367 Status error; 368 if (!IsValid() || !m_should_close_fd) 369 return error; 370 371 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); 372 if (log) 373 log->Printf("%p Socket::Close (fd = %i)", static_cast<void *>(this), 374 m_socket); 375 376#if defined(_WIN32) 377 bool success = !!closesocket(m_socket); 378#else 379 bool success = !!::close(m_socket); 380#endif 381 // A reference to a FD was passed in, set it to an invalid value 382 m_socket = kInvalidSocketValue; 383 if (!success) { 384 SetLastError(error); 385 } 386 387 return error; 388} 389 390int Socket::GetOption(int level, int option_name, int &option_value) { 391 get_socket_option_arg_type option_value_p = 392 reinterpret_cast<get_socket_option_arg_type>(&option_value); 393 socklen_t option_value_size = sizeof(int); 394 return ::getsockopt(m_socket, level, option_name, option_value_p, 395 &option_value_size); 396} 397 398int Socket::SetOption(int level, int option_name, int option_value) { 399 set_socket_option_arg_type option_value_p = 400 reinterpret_cast<get_socket_option_arg_type>(&option_value); 401 return ::setsockopt(m_socket, level, option_name, option_value_p, 402 sizeof(option_value)); 403} 404 405size_t Socket::Send(const void *buf, const size_t num_bytes) { 406 return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0); 407} 408 409void Socket::SetLastError(Status &error) { 410#if defined(_WIN32) 411 error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32); 412#else 413 error.SetErrorToErrno(); 414#endif 415} 416 417NativeSocket Socket::CreateSocket(const int domain, const int type, 418 const int protocol, 419 bool child_processes_inherit, Status &error) { 420 error.Clear(); 421 auto socket_type = type; 422#ifdef SOCK_CLOEXEC 423 if (!child_processes_inherit) 424 socket_type |= SOCK_CLOEXEC; 425#endif 426 auto sock = ::socket(domain, socket_type, protocol); 427 if (sock == kInvalidSocketValue) 428 SetLastError(error); 429 430 return sock; 431} 432 433NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr, 434 socklen_t *addrlen, 435 bool child_processes_inherit, Status &error) { 436 error.Clear(); 437#if defined(ANDROID_USE_ACCEPT_WORKAROUND) 438 // Hack: 439 // This enables static linking lldb-server to an API 21 libc, but still having 440 // it run on older devices. It is necessary because API 21 libc's 441 // implementation of accept() uses the accept4 syscall(), which is not 442 // available in older kernels. Using an older libc would fix this issue, but 443 // introduce other ones, as the old libraries were quite buggy. 444 int fd = syscall(__NR_accept, sockfd, addr, addrlen); 445 if (fd >= 0 && !child_processes_inherit) { 446 int flags = ::fcntl(fd, F_GETFD); 447 if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1) 448 return fd; 449 SetLastError(error); 450 close(fd); 451 } 452 return fd; 453#elif defined(SOCK_CLOEXEC) 454 int flags = 0; 455 if (!child_processes_inherit) { 456 flags |= SOCK_CLOEXEC; 457 } 458 NativeSocket fd = ::accept4(sockfd, addr, addrlen, flags); 459#else 460 NativeSocket fd = ::accept(sockfd, addr, addrlen); 461#endif 462 if (fd == kInvalidSocketValue) 463 SetLastError(error); 464 return fd; 465} 466