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