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