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