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