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/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" 17 #include "lldb/Host/StringConvert.h" 18 #include "lldb/Host/TimeValue.h" 19 #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 32 33 #ifdef __linux__ 34 #include "lldb/Host/linux/AbstractSocket.h" 35 #endif 36 37 #ifdef __ANDROID_NDK__ 38 #include <arpa/inet.h> 39 #include <asm-generic/errno-base.h> 40 #include <bits/error_constants.h> 41 #include <errno.h> 42 #include <linux/tcp.h> 43 #if defined(ANDROID_ARM_BUILD_STATIC) || defined(ANDROID_MIPS_BUILD_STATIC) 44 #include <fcntl.h> 45 #include <sys/syscall.h> 46 #include <unistd.h> 47 #endif // ANDROID_ARM_BUILD_STATIC || ANDROID_MIPS_BUILD_STATIC 48 #endif // __ANDROID_NDK__ 49 50 using namespace lldb; 51 using namespace lldb_private; 52 53 #if defined(_WIN32) 54 typedef const char *set_socket_option_arg_type; 55 typedef char *get_socket_option_arg_type; 56 const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET; 57 #else // #if defined(_WIN32) 58 typedef const void *set_socket_option_arg_type; 59 typedef void *get_socket_option_arg_type; 60 const NativeSocket Socket::kInvalidSocketValue = -1; 61 #endif // #if defined(_WIN32) 62 63 namespace { 64 65 bool IsInterrupted() { 66 #if defined(_WIN32) 67 return ::WSAGetLastError() == WSAEINTR; 68 #else 69 return errno == EINTR; 70 #endif 71 } 72 } 73 74 Socket::Socket(NativeSocket socket, SocketProtocol protocol, bool should_close) 75 : IOObject(eFDTypeSocket, should_close), m_protocol(protocol), 76 m_socket(socket) {} 77 78 Socket::~Socket() { Close(); } 79 80 std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol, 81 bool child_processes_inherit, 82 Error &error) { 83 error.Clear(); 84 85 std::unique_ptr<Socket> socket_up; 86 switch (protocol) { 87 case ProtocolTcp: 88 socket_up.reset(new TCPSocket(child_processes_inherit, error)); 89 break; 90 case ProtocolUdp: 91 socket_up.reset(new UDPSocket(child_processes_inherit, error)); 92 break; 93 case ProtocolUnixDomain: 94 #ifndef LLDB_DISABLE_POSIX 95 socket_up.reset(new DomainSocket(child_processes_inherit, error)); 96 #else 97 error.SetErrorString( 98 "Unix domain sockets are not supported on this platform."); 99 #endif 100 break; 101 case ProtocolUnixAbstract: 102 #ifdef __linux__ 103 socket_up.reset(new AbstractSocket(child_processes_inherit, error)); 104 #else 105 error.SetErrorString( 106 "Abstract domain sockets are not supported on this platform."); 107 #endif 108 break; 109 } 110 111 if (error.Fail()) 112 socket_up.reset(); 113 114 return socket_up; 115 } 116 117 Error Socket::TcpConnect(llvm::StringRef host_and_port, 118 bool child_processes_inherit, Socket *&socket) { 119 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION)); 120 if (log) 121 log->Printf("Socket::%s (host/port = %s)", __FUNCTION__, 122 host_and_port.data()); 123 124 Error error; 125 std::unique_ptr<Socket> connect_socket( 126 Create(ProtocolTcp, child_processes_inherit, error)); 127 if (error.Fail()) 128 return error; 129 130 error = connect_socket->Connect(host_and_port); 131 if (error.Success()) 132 socket = connect_socket.release(); 133 134 return error; 135 } 136 137 Error Socket::TcpListen(llvm::StringRef host_and_port, 138 bool child_processes_inherit, Socket *&socket, 139 Predicate<uint16_t> *predicate, int backlog) { 140 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); 141 if (log) 142 log->Printf("Socket::%s (%s)", __FUNCTION__, host_and_port.data()); 143 144 Error error; 145 std::string host_str; 146 std::string port_str; 147 int32_t port = INT32_MIN; 148 if (!DecodeHostAndPort(host_and_port, host_str, port_str, port, &error)) 149 return error; 150 151 std::unique_ptr<TCPSocket> listen_socket( 152 new TCPSocket(child_processes_inherit, error)); 153 if (error.Fail()) 154 return error; 155 156 error = listen_socket->Listen(host_and_port, backlog); 157 if (error.Success()) { 158 // We were asked to listen on port zero which means we 159 // must now read the actual port that was given to us 160 // as port zero is a special code for "find an open port 161 // for me". 162 if (port == 0) 163 port = listen_socket->GetLocalPortNumber(); 164 165 // Set the port predicate since when doing a listen://<host>:<port> 166 // it often needs to accept the incoming connection which is a blocking 167 // system call. Allowing access to the bound port using a predicate allows 168 // us to wait for the port predicate to be set to a non-zero value from 169 // another thread in an efficient manor. 170 if (predicate) 171 predicate->SetValue(port, eBroadcastAlways); 172 socket = listen_socket.release(); 173 } 174 175 return error; 176 } 177 178 Error Socket::UdpConnect(llvm::StringRef host_and_port, 179 bool child_processes_inherit, Socket *&send_socket, 180 Socket *&recv_socket) { 181 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); 182 if (log) 183 log->Printf("Socket::%s (host/port = %s)", __FUNCTION__, 184 host_and_port.data()); 185 186 return UDPSocket::Connect(host_and_port, child_processes_inherit, send_socket, 187 recv_socket); 188 } 189 190 Error Socket::UnixDomainConnect(llvm::StringRef name, 191 bool child_processes_inherit, Socket *&socket) { 192 Error error; 193 std::unique_ptr<Socket> connect_socket( 194 Create(ProtocolUnixDomain, child_processes_inherit, error)); 195 if (error.Fail()) 196 return error; 197 198 error = connect_socket->Connect(name); 199 if (error.Success()) 200 socket = connect_socket.release(); 201 202 return error; 203 } 204 205 Error Socket::UnixDomainAccept(llvm::StringRef name, 206 bool child_processes_inherit, Socket *&socket) { 207 Error error; 208 std::unique_ptr<Socket> listen_socket( 209 Create(ProtocolUnixDomain, child_processes_inherit, error)); 210 if (error.Fail()) 211 return error; 212 213 error = listen_socket->Listen(name, 5); 214 if (error.Fail()) 215 return error; 216 217 error = listen_socket->Accept(name, child_processes_inherit, socket); 218 return error; 219 } 220 221 Error Socket::UnixAbstractConnect(llvm::StringRef name, 222 bool child_processes_inherit, 223 Socket *&socket) { 224 Error error; 225 std::unique_ptr<Socket> connect_socket( 226 Create(ProtocolUnixAbstract, child_processes_inherit, error)); 227 if (error.Fail()) 228 return error; 229 230 error = connect_socket->Connect(name); 231 if (error.Success()) 232 socket = connect_socket.release(); 233 return error; 234 } 235 236 Error Socket::UnixAbstractAccept(llvm::StringRef name, 237 bool child_processes_inherit, 238 Socket *&socket) { 239 Error error; 240 std::unique_ptr<Socket> listen_socket( 241 Create(ProtocolUnixAbstract, child_processes_inherit, error)); 242 if (error.Fail()) 243 return error; 244 245 error = listen_socket->Listen(name, 5); 246 if (error.Fail()) 247 return error; 248 249 error = listen_socket->Accept(name, child_processes_inherit, socket); 250 return error; 251 } 252 253 bool Socket::DecodeHostAndPort(llvm::StringRef host_and_port, 254 std::string &host_str, std::string &port_str, 255 int32_t &port, Error *error_ptr) { 256 static RegularExpression g_regex(llvm::StringRef("([^:]+):([0-9]+)")); 257 RegularExpression::Match regex_match(2); 258 if (g_regex.Execute(host_and_port, ®ex_match)) { 259 if (regex_match.GetMatchAtIndex(host_and_port.data(), 1, host_str) && 260 regex_match.GetMatchAtIndex(host_and_port.data(), 2, port_str)) { 261 bool ok = false; 262 port = StringConvert::ToUInt32(port_str.c_str(), UINT32_MAX, 10, &ok); 263 if (ok && port <= UINT16_MAX) { 264 if (error_ptr) 265 error_ptr->Clear(); 266 return true; 267 } 268 // port is too large 269 if (error_ptr) 270 error_ptr->SetErrorStringWithFormat( 271 "invalid host:port specification: '%s'", host_and_port.data()); 272 return false; 273 } 274 } 275 276 // If this was unsuccessful, then check if it's simply a signed 32-bit 277 // integer, representing 278 // a port with an empty host. 279 host_str.clear(); 280 port_str.clear(); 281 bool ok = false; 282 port = StringConvert::ToUInt32(host_and_port.data(), UINT32_MAX, 10, &ok); 283 if (ok && port < UINT16_MAX) { 284 port_str = host_and_port; 285 if (error_ptr) 286 error_ptr->Clear(); 287 return true; 288 } 289 290 if (error_ptr) 291 error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", 292 host_and_port.data()); 293 return false; 294 } 295 296 IOObject::WaitableHandle Socket::GetWaitableHandle() { 297 // TODO: On Windows, use WSAEventSelect 298 return m_socket; 299 } 300 301 Error Socket::Read(void *buf, size_t &num_bytes) { 302 Error error; 303 int bytes_received = 0; 304 do { 305 bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0); 306 } while (bytes_received < 0 && IsInterrupted()); 307 308 if (bytes_received < 0) { 309 SetLastError(error); 310 num_bytes = 0; 311 } else 312 num_bytes = bytes_received; 313 314 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION)); 315 if (log) { 316 log->Printf("%p Socket::Read() (socket = %" PRIu64 317 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 318 " (error = %s)", 319 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf, 320 static_cast<uint64_t>(num_bytes), 321 static_cast<int64_t>(bytes_received), error.AsCString()); 322 } 323 324 return error; 325 } 326 327 Error Socket::Write(const void *buf, size_t &num_bytes) { 328 Error error; 329 int bytes_sent = 0; 330 do { 331 bytes_sent = Send(buf, num_bytes); 332 } while (bytes_sent < 0 && IsInterrupted()); 333 334 if (bytes_sent < 0) { 335 SetLastError(error); 336 num_bytes = 0; 337 } else 338 num_bytes = bytes_sent; 339 340 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION)); 341 if (log) { 342 log->Printf("%p Socket::Write() (socket = %" PRIu64 343 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 344 " (error = %s)", 345 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf, 346 static_cast<uint64_t>(num_bytes), 347 static_cast<int64_t>(bytes_sent), error.AsCString()); 348 } 349 350 return error; 351 } 352 353 Error Socket::PreDisconnect() { 354 Error error; 355 return error; 356 } 357 358 Error Socket::Close() { 359 Error error; 360 if (!IsValid() || !m_should_close_fd) 361 return error; 362 363 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); 364 if (log) 365 log->Printf("%p Socket::Close (fd = %i)", static_cast<void *>(this), 366 m_socket); 367 368 #if defined(_WIN32) 369 bool success = !!closesocket(m_socket); 370 #else 371 bool success = !!::close(m_socket); 372 #endif 373 // A reference to a FD was passed in, set it to an invalid value 374 m_socket = kInvalidSocketValue; 375 if (!success) { 376 SetLastError(error); 377 } 378 379 return error; 380 } 381 382 int Socket::GetOption(int level, int option_name, int &option_value) { 383 get_socket_option_arg_type option_value_p = 384 reinterpret_cast<get_socket_option_arg_type>(&option_value); 385 socklen_t option_value_size = sizeof(int); 386 return ::getsockopt(m_socket, level, option_name, option_value_p, 387 &option_value_size); 388 } 389 390 int Socket::SetOption(int level, int option_name, int option_value) { 391 set_socket_option_arg_type option_value_p = 392 reinterpret_cast<get_socket_option_arg_type>(&option_value); 393 return ::setsockopt(m_socket, level, option_name, option_value_p, 394 sizeof(option_value)); 395 } 396 397 size_t Socket::Send(const void *buf, const size_t num_bytes) { 398 return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0); 399 } 400 401 void Socket::SetLastError(Error &error) { 402 #if defined(_WIN32) 403 error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32); 404 #else 405 error.SetErrorToErrno(); 406 #endif 407 } 408 409 NativeSocket Socket::CreateSocket(const int domain, const int type, 410 const int protocol, 411 bool child_processes_inherit, Error &error) { 412 error.Clear(); 413 auto socketType = type; 414 #ifdef SOCK_CLOEXEC 415 if (!child_processes_inherit) 416 socketType |= SOCK_CLOEXEC; 417 #endif 418 auto sock = ::socket(domain, socketType, protocol); 419 if (sock == kInvalidSocketValue) 420 SetLastError(error); 421 422 return sock; 423 } 424 425 NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr, 426 socklen_t *addrlen, 427 bool child_processes_inherit, Error &error) { 428 error.Clear(); 429 #if defined(ANDROID_ARM_BUILD_STATIC) || defined(ANDROID_MIPS_BUILD_STATIC) 430 // Temporary workaround for statically linking Android lldb-server with the 431 // latest API. 432 int fd = syscall(__NR_accept, sockfd, addr, addrlen); 433 if (fd >= 0 && !child_processes_inherit) { 434 int flags = ::fcntl(fd, F_GETFD); 435 if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1) 436 return fd; 437 SetLastError(error); 438 close(fd); 439 } 440 return fd; 441 #elif defined(SOCK_CLOEXEC) 442 int flags = 0; 443 if (!child_processes_inherit) { 444 flags |= SOCK_CLOEXEC; 445 } 446 #if defined(__NetBSD__) 447 NativeSocket fd = ::paccept(sockfd, addr, addrlen, nullptr, flags); 448 #else 449 NativeSocket fd = ::accept4(sockfd, addr, addrlen, flags); 450 #endif 451 #else 452 NativeSocket fd = ::accept(sockfd, addr, addrlen); 453 #endif 454 if (fd == kInvalidSocketValue) 455 SetLastError(error); 456 return fd; 457 } 458