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