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