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/common/TCPSocket.h" 15 #include "lldb/Host/common/UDPSocket.h" 16 #include "lldb/Utility/Log.h" 17 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/Support/Errno.h" 20 #include "llvm/Support/Error.h" 21 #include "llvm/Support/WindowsError.h" 22 23 #if LLDB_ENABLE_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 <cerrno> 43 #include <fcntl.h> 44 #include <linux/tcp.h> 45 #include <sys/syscall.h> 46 #include <unistd.h> 47 #endif // __ANDROID__ 48 49 using namespace lldb; 50 using namespace lldb_private; 51 52 #if defined(_WIN32) 53 typedef const char *set_socket_option_arg_type; 54 typedef char *get_socket_option_arg_type; 55 const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET; 56 #else // #if defined(_WIN32) 57 typedef const void *set_socket_option_arg_type; 58 typedef void *get_socket_option_arg_type; 59 const NativeSocket Socket::kInvalidSocketValue = -1; 60 #endif // #if defined(_WIN32) 61 62 static bool IsInterrupted() { 63 #if defined(_WIN32) 64 return ::WSAGetLastError() == WSAEINTR; 65 #else 66 return errno == EINTR; 67 #endif 68 } 69 70 Socket::Socket(SocketProtocol protocol, bool should_close, 71 bool child_processes_inherit) 72 : IOObject(eFDTypeSocket), m_protocol(protocol), 73 m_socket(kInvalidSocketValue), 74 m_child_processes_inherit(child_processes_inherit), 75 m_should_close_fd(should_close) {} 76 77 Socket::~Socket() { Close(); } 78 79 llvm::Error Socket::Initialize() { 80 #if defined(_WIN32) 81 auto wVersion = WINSOCK_VERSION; 82 WSADATA wsaData; 83 int err = ::WSAStartup(wVersion, &wsaData); 84 if (err == 0) { 85 if (wsaData.wVersion < wVersion) { 86 WSACleanup(); 87 return llvm::make_error<llvm::StringError>( 88 "WSASock version is not expected.", llvm::inconvertibleErrorCode()); 89 } 90 } else { 91 return llvm::errorCodeToError(llvm::mapWindowsError(::WSAGetLastError())); 92 } 93 #endif 94 95 return llvm::Error::success(); 96 } 97 98 void Socket::Terminate() { 99 #if defined(_WIN32) 100 ::WSACleanup(); 101 #endif 102 } 103 104 std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol, 105 bool child_processes_inherit, 106 Status &error) { 107 error.Clear(); 108 109 std::unique_ptr<Socket> socket_up; 110 switch (protocol) { 111 case ProtocolTcp: 112 socket_up = 113 std::make_unique<TCPSocket>(true, child_processes_inherit); 114 break; 115 case ProtocolUdp: 116 socket_up = 117 std::make_unique<UDPSocket>(true, child_processes_inherit); 118 break; 119 case ProtocolUnixDomain: 120 #if LLDB_ENABLE_POSIX 121 socket_up = 122 std::make_unique<DomainSocket>(true, child_processes_inherit); 123 #else 124 error.SetErrorString( 125 "Unix domain sockets are not supported on this platform."); 126 #endif 127 break; 128 case ProtocolUnixAbstract: 129 #ifdef __linux__ 130 socket_up = 131 std::make_unique<AbstractSocket>(child_processes_inherit); 132 #else 133 error.SetErrorString( 134 "Abstract domain sockets are not supported on this platform."); 135 #endif 136 break; 137 } 138 139 if (error.Fail()) 140 socket_up.reset(); 141 142 return socket_up; 143 } 144 145 llvm::Expected<std::unique_ptr<Socket>> 146 Socket::TcpConnect(llvm::StringRef host_and_port, 147 bool child_processes_inherit) { 148 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); 149 LLDB_LOG(log, "host_and_port = {0}", host_and_port); 150 151 Status error; 152 std::unique_ptr<Socket> connect_socket( 153 Create(ProtocolTcp, child_processes_inherit, error)); 154 if (error.Fail()) 155 return error.ToError(); 156 157 error = connect_socket->Connect(host_and_port); 158 if (error.Success()) 159 return std::move(connect_socket); 160 161 return error.ToError(); 162 } 163 164 llvm::Expected<std::unique_ptr<TCPSocket>> 165 Socket::TcpListen(llvm::StringRef host_and_port, bool child_processes_inherit, 166 int backlog) { 167 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); 168 LLDB_LOG(log, "host_and_port = {0}", host_and_port); 169 170 std::unique_ptr<TCPSocket> listen_socket( 171 new TCPSocket(true, child_processes_inherit)); 172 173 Status error = listen_socket->Listen(host_and_port, backlog); 174 if (error.Fail()) 175 return error.ToError(); 176 177 return std::move(listen_socket); 178 } 179 180 llvm::Expected<std::unique_ptr<UDPSocket>> 181 Socket::UdpConnect(llvm::StringRef host_and_port, 182 bool child_processes_inherit) { 183 return UDPSocket::Connect(host_and_port, child_processes_inherit); 184 } 185 186 Status Socket::UnixDomainConnect(llvm::StringRef name, 187 bool child_processes_inherit, 188 Socket *&socket) { 189 Status error; 190 std::unique_ptr<Socket> connect_socket( 191 Create(ProtocolUnixDomain, child_processes_inherit, error)); 192 if (error.Fail()) 193 return error; 194 195 error = connect_socket->Connect(name); 196 if (error.Success()) 197 socket = connect_socket.release(); 198 199 return error; 200 } 201 202 Status Socket::UnixDomainAccept(llvm::StringRef name, 203 bool child_processes_inherit, Socket *&socket) { 204 Status error; 205 std::unique_ptr<Socket> listen_socket( 206 Create(ProtocolUnixDomain, child_processes_inherit, error)); 207 if (error.Fail()) 208 return error; 209 210 error = listen_socket->Listen(name, 5); 211 if (error.Fail()) 212 return error; 213 214 error = listen_socket->Accept(socket); 215 return error; 216 } 217 218 Status Socket::UnixAbstractConnect(llvm::StringRef name, 219 bool child_processes_inherit, 220 Socket *&socket) { 221 Status error; 222 std::unique_ptr<Socket> connect_socket( 223 Create(ProtocolUnixAbstract, child_processes_inherit, error)); 224 if (error.Fail()) 225 return error; 226 227 error = connect_socket->Connect(name); 228 if (error.Success()) 229 socket = connect_socket.release(); 230 return error; 231 } 232 233 Status Socket::UnixAbstractAccept(llvm::StringRef name, 234 bool child_processes_inherit, 235 Socket *&socket) { 236 Status error; 237 std::unique_ptr<Socket> listen_socket( 238 Create(ProtocolUnixAbstract, child_processes_inherit, error)); 239 if (error.Fail()) 240 return error; 241 242 error = listen_socket->Listen(name, 5); 243 if (error.Fail()) 244 return error; 245 246 error = listen_socket->Accept(socket); 247 return error; 248 } 249 250 llvm::Expected<Socket::HostAndPort> Socket::DecodeHostAndPort(llvm::StringRef host_and_port) { 251 static llvm::Regex g_regex("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)"); 252 HostAndPort ret; 253 llvm::SmallVector<llvm::StringRef, 3> matches; 254 if (g_regex.match(host_and_port, &matches)) { 255 ret.hostname = matches[1].str(); 256 // IPv6 addresses are wrapped in [] when specified with ports 257 if (ret.hostname.front() == '[' && ret.hostname.back() == ']') 258 ret.hostname = ret.hostname.substr(1, ret.hostname.size() - 2); 259 if (to_integer(matches[2], ret.port, 10)) 260 return ret; 261 } else { 262 // If this was unsuccessful, then check if it's simply an unsigned 16-bit 263 // integer, representing a port with an empty host. 264 if (to_integer(host_and_port, ret.port, 10)) 265 return ret; 266 } 267 268 return llvm::createStringError(llvm::inconvertibleErrorCode(), 269 "invalid host:port specification: '%s'", 270 host_and_port.str().c_str()); 271 } 272 273 IOObject::WaitableHandle Socket::GetWaitableHandle() { 274 // TODO: On Windows, use WSAEventSelect 275 return m_socket; 276 } 277 278 Status Socket::Read(void *buf, size_t &num_bytes) { 279 Status error; 280 int bytes_received = 0; 281 do { 282 bytes_received = ::recv(m_socket, static_cast<char *>(buf), num_bytes, 0); 283 } while (bytes_received < 0 && IsInterrupted()); 284 285 if (bytes_received < 0) { 286 SetLastError(error); 287 num_bytes = 0; 288 } else 289 num_bytes = bytes_received; 290 291 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION)); 292 if (log) { 293 LLDB_LOGF(log, 294 "%p Socket::Read() (socket = %" PRIu64 295 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 296 " (error = %s)", 297 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf, 298 static_cast<uint64_t>(num_bytes), 299 static_cast<int64_t>(bytes_received), error.AsCString()); 300 } 301 302 return error; 303 } 304 305 Status Socket::Write(const void *buf, size_t &num_bytes) { 306 const size_t src_len = num_bytes; 307 Status error; 308 int bytes_sent = 0; 309 do { 310 bytes_sent = Send(buf, num_bytes); 311 } while (bytes_sent < 0 && IsInterrupted()); 312 313 if (bytes_sent < 0) { 314 SetLastError(error); 315 num_bytes = 0; 316 } else 317 num_bytes = bytes_sent; 318 319 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION)); 320 if (log) { 321 LLDB_LOGF(log, 322 "%p Socket::Write() (socket = %" PRIu64 323 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 324 " (error = %s)", 325 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf, 326 static_cast<uint64_t>(src_len), 327 static_cast<int64_t>(bytes_sent), error.AsCString()); 328 } 329 330 return error; 331 } 332 333 Status Socket::PreDisconnect() { 334 Status error; 335 return error; 336 } 337 338 Status Socket::Close() { 339 Status error; 340 if (!IsValid() || !m_should_close_fd) 341 return error; 342 343 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); 344 LLDB_LOGF(log, "%p Socket::Close (fd = %" PRIu64 ")", 345 static_cast<void *>(this), static_cast<uint64_t>(m_socket)); 346 347 #if defined(_WIN32) 348 bool success = !!closesocket(m_socket); 349 #else 350 bool success = !!::close(m_socket); 351 #endif 352 // A reference to a FD was passed in, set it to an invalid value 353 m_socket = kInvalidSocketValue; 354 if (!success) { 355 SetLastError(error); 356 } 357 358 return error; 359 } 360 361 int Socket::GetOption(int level, int option_name, int &option_value) { 362 get_socket_option_arg_type option_value_p = 363 reinterpret_cast<get_socket_option_arg_type>(&option_value); 364 socklen_t option_value_size = sizeof(int); 365 return ::getsockopt(m_socket, level, option_name, option_value_p, 366 &option_value_size); 367 } 368 369 int Socket::SetOption(int level, int option_name, int option_value) { 370 set_socket_option_arg_type option_value_p = 371 reinterpret_cast<get_socket_option_arg_type>(&option_value); 372 return ::setsockopt(m_socket, level, option_name, option_value_p, 373 sizeof(option_value)); 374 } 375 376 size_t Socket::Send(const void *buf, const size_t num_bytes) { 377 return ::send(m_socket, static_cast<const char *>(buf), num_bytes, 0); 378 } 379 380 void Socket::SetLastError(Status &error) { 381 #if defined(_WIN32) 382 error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32); 383 #else 384 error.SetErrorToErrno(); 385 #endif 386 } 387 388 NativeSocket Socket::CreateSocket(const int domain, const int type, 389 const int protocol, 390 bool child_processes_inherit, Status &error) { 391 error.Clear(); 392 auto socket_type = type; 393 #ifdef SOCK_CLOEXEC 394 if (!child_processes_inherit) 395 socket_type |= SOCK_CLOEXEC; 396 #endif 397 auto sock = ::socket(domain, socket_type, protocol); 398 if (sock == kInvalidSocketValue) 399 SetLastError(error); 400 401 return sock; 402 } 403 404 NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr, 405 socklen_t *addrlen, 406 bool child_processes_inherit, Status &error) { 407 error.Clear(); 408 #if defined(ANDROID_USE_ACCEPT_WORKAROUND) 409 // Hack: 410 // This enables static linking lldb-server to an API 21 libc, but still 411 // having it run on older devices. It is necessary because API 21 libc's 412 // implementation of accept() uses the accept4 syscall(), which is not 413 // available in older kernels. Using an older libc would fix this issue, but 414 // introduce other ones, as the old libraries were quite buggy. 415 int fd = syscall(__NR_accept, sockfd, addr, addrlen); 416 if (fd >= 0 && !child_processes_inherit) { 417 int flags = ::fcntl(fd, F_GETFD); 418 if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1) 419 return fd; 420 SetLastError(error); 421 close(fd); 422 } 423 return fd; 424 #elif defined(SOCK_CLOEXEC) && defined(HAVE_ACCEPT4) 425 int flags = 0; 426 if (!child_processes_inherit) { 427 flags |= SOCK_CLOEXEC; 428 } 429 NativeSocket fd = llvm::sys::RetryAfterSignal( 430 static_cast<NativeSocket>(-1), ::accept4, sockfd, addr, addrlen, flags); 431 #else 432 NativeSocket fd = llvm::sys::RetryAfterSignal( 433 static_cast<NativeSocket>(-1), ::accept, sockfd, addr, addrlen); 434 #endif 435 if (fd == kInvalidSocketValue) 436 SetLastError(error); 437 return fd; 438 } 439 440 llvm::raw_ostream &lldb_private::operator<<(llvm::raw_ostream &OS, 441 const Socket::HostAndPort &HP) { 442 return OS << '[' << HP.hostname << ']' << ':' << HP.port; 443 } 444