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/FileSystem.h" 16 #include "lldb/Host/Host.h" 17 #include "lldb/Host/SocketAddress.h" 18 #include "lldb/Host/StringConvert.h" 19 #include "lldb/Host/TimeValue.h" 20 21 #ifdef __ANDROID_NDK__ 22 #include <linux/tcp.h> 23 #include <bits/error_constants.h> 24 #include <asm-generic/errno-base.h> 25 #include <errno.h> 26 #include <arpa/inet.h> 27 #if defined(ANDROID_ARM_BUILD_STATIC) 28 #include <unistd.h> 29 #include <sys/syscall.h> 30 #include <fcntl.h> 31 #endif // ANDROID_ARM_BUILD_STATIC 32 #endif // __ANDROID_NDK__ 33 34 #ifndef LLDB_DISABLE_POSIX 35 #include <arpa/inet.h> 36 #include <netdb.h> 37 #include <netinet/in.h> 38 #include <netinet/tcp.h> 39 #include <sys/socket.h> 40 #include <sys/un.h> 41 #endif 42 43 using namespace lldb; 44 using namespace lldb_private; 45 46 #if defined(_WIN32) 47 typedef const char * set_socket_option_arg_type; 48 typedef char * get_socket_option_arg_type; 49 const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET; 50 #else // #if defined(_WIN32) 51 typedef const void * set_socket_option_arg_type; 52 typedef void * get_socket_option_arg_type; 53 const NativeSocket Socket::kInvalidSocketValue = -1; 54 #endif // #if defined(_WIN32) 55 56 #ifdef __ANDROID__ 57 // Android does not have SUN_LEN 58 #ifndef SUN_LEN 59 #define SUN_LEN(ptr) ((size_t) (((struct sockaddr_un *) 0)->sun_path) + strlen((ptr)->sun_path)) 60 #endif 61 #endif // #ifdef __ANDROID__ 62 63 namespace { 64 65 NativeSocket CreateSocket(const int domain, const int type, const int protocol, bool child_processes_inherit) 66 { 67 auto socketType = type; 68 #ifdef SOCK_CLOEXEC 69 if (!child_processes_inherit) { 70 socketType |= SOCK_CLOEXEC; 71 } 72 #endif 73 return ::socket (domain, socketType, protocol); 74 } 75 76 NativeSocket Accept(NativeSocket sockfd, struct sockaddr *addr, socklen_t *addrlen, bool child_processes_inherit) 77 { 78 #if defined(ANDROID_ARM_BUILD_STATIC) 79 // Temporary workaround for statically linking Android lldb-server with the 80 // latest API. 81 int fd = syscall(__NR_accept, sockfd, addr, addrlen); 82 if (fd >= 0 && !child_processes_inherit) 83 { 84 int flags = ::fcntl(fd, F_GETFD); 85 if (flags == -1) 86 return -1; 87 if (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) 88 return -1; 89 } 90 return fd; 91 #elif defined(SOCK_CLOEXEC) 92 int flags = 0; 93 if (!child_processes_inherit) { 94 flags |= SOCK_CLOEXEC; 95 } 96 #if defined(__NetBSD__) 97 return ::paccept (sockfd, addr, addrlen, NULL, flags); 98 #else 99 return ::accept4 (sockfd, addr, addrlen, flags); 100 #endif 101 #else 102 return ::accept (sockfd, addr, addrlen); 103 #endif 104 } 105 106 void SetLastError(Error &error) 107 { 108 #if defined(_WIN32) 109 error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32); 110 #else 111 error.SetErrorToErrno(); 112 #endif 113 } 114 115 bool IsInterrupted() 116 { 117 #if defined(_WIN32) 118 return ::WSAGetLastError() == WSAEINTR; 119 #else 120 return errno == EINTR; 121 #endif 122 } 123 124 } 125 126 Socket::Socket(NativeSocket socket, SocketProtocol protocol, bool should_close) 127 : IOObject(eFDTypeSocket, should_close) 128 , m_protocol(protocol) 129 , m_socket(socket) 130 { 131 132 } 133 134 Socket::~Socket() 135 { 136 Close(); 137 } 138 139 Error Socket::TcpConnect(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&socket) 140 { 141 // Store the result in a unique_ptr in case we error out, the memory will get correctly freed. 142 std::unique_ptr<Socket> final_socket; 143 NativeSocket sock = kInvalidSocketValue; 144 Error error; 145 146 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION)); 147 if (log) 148 log->Printf ("Socket::TcpConnect (host/port = %s)", host_and_port.data()); 149 150 std::string host_str; 151 std::string port_str; 152 int32_t port = INT32_MIN; 153 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error)) 154 return error; 155 156 // Create the socket 157 sock = CreateSocket (AF_INET, SOCK_STREAM, IPPROTO_TCP, child_processes_inherit); 158 if (sock == kInvalidSocketValue) 159 { 160 SetLastError (error); 161 return error; 162 } 163 164 // Since they both refer to the same socket descriptor, arbitrarily choose the send socket to 165 // be the owner. 166 final_socket.reset(new Socket(sock, ProtocolTcp, true)); 167 168 // Enable local address reuse 169 final_socket->SetOption(SOL_SOCKET, SO_REUSEADDR, 1); 170 171 struct sockaddr_in sa; 172 ::memset (&sa, 0, sizeof (sa)); 173 sa.sin_family = AF_INET; 174 sa.sin_port = htons (port); 175 176 int inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr); 177 178 if (inet_pton_result <= 0) 179 { 180 struct hostent *host_entry = gethostbyname (host_str.c_str()); 181 if (host_entry) 182 host_str = ::inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list); 183 inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr); 184 if (inet_pton_result <= 0) 185 { 186 if (inet_pton_result == -1) 187 SetLastError(error); 188 else 189 error.SetErrorStringWithFormat("invalid host string: '%s'", host_str.c_str()); 190 191 return error; 192 } 193 } 194 195 if (-1 == ::connect (sock, (const struct sockaddr *)&sa, sizeof(sa))) 196 { 197 SetLastError (error); 198 return error; 199 } 200 201 // Keep our TCP packets coming without any delays. 202 final_socket->SetOption(IPPROTO_TCP, TCP_NODELAY, 1); 203 error.Clear(); 204 socket = final_socket.release(); 205 return error; 206 } 207 208 Error 209 Socket::TcpListen (llvm::StringRef host_and_port, 210 bool child_processes_inherit, 211 Socket *&socket, 212 Predicate<uint16_t>* predicate, 213 int backlog) 214 { 215 std::unique_ptr<Socket> listen_socket; 216 NativeSocket listen_sock = kInvalidSocketValue; 217 Error error; 218 219 const sa_family_t family = AF_INET; 220 const int socktype = SOCK_STREAM; 221 const int protocol = IPPROTO_TCP; 222 listen_sock = ::CreateSocket (family, socktype, protocol, child_processes_inherit); 223 if (listen_sock == kInvalidSocketValue) 224 { 225 SetLastError (error); 226 return error; 227 } 228 229 listen_socket.reset(new Socket(listen_sock, ProtocolTcp, true)); 230 231 // enable local address reuse 232 listen_socket->SetOption(SOL_SOCKET, SO_REUSEADDR, 1); 233 234 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION)); 235 if (log) 236 log->Printf ("Socket::TcpListen (%s)", host_and_port.data()); 237 238 std::string host_str; 239 std::string port_str; 240 int32_t port = INT32_MIN; 241 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error)) 242 return error; 243 244 SocketAddress bind_addr; 245 bool bind_addr_success = false; 246 247 // Only bind to the loopback address if we are expecting a connection from 248 // localhost to avoid any firewall issues. 249 if (host_str == "127.0.0.1") 250 bind_addr_success = bind_addr.SetToLocalhost (family, port); 251 else 252 bind_addr_success = bind_addr.SetToAnyAddress (family, port); 253 254 if (bind_addr_success) 255 { 256 int err = ::bind (listen_sock, bind_addr, bind_addr.GetLength()); 257 if (err == -1) 258 { 259 SetLastError (error); 260 return error; 261 } 262 263 err = ::listen (listen_sock, backlog); 264 if (err == -1) 265 { 266 SetLastError (error); 267 return error; 268 } 269 270 // We were asked to listen on port zero which means we 271 // must now read the actual port that was given to us 272 // as port zero is a special code for "find an open port 273 // for me". 274 if (port == 0) 275 port = listen_socket->GetLocalPortNumber(); 276 277 // Set the port predicate since when doing a listen://<host>:<port> 278 // it often needs to accept the incoming connection which is a blocking 279 // system call. Allowing access to the bound port using a predicate allows 280 // us to wait for the port predicate to be set to a non-zero value from 281 // another thread in an efficient manor. 282 if (predicate) 283 predicate->SetValue (port, eBroadcastAlways); 284 285 socket = listen_socket.release(); 286 } 287 288 return error; 289 } 290 291 Error Socket::BlockingAccept(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&socket) 292 { 293 Error error; 294 std::string host_str; 295 std::string port_str; 296 int32_t port; 297 if (!DecodeHostAndPort(host_and_port, host_str, port_str, port, &error)) 298 return error; 299 300 const sa_family_t family = AF_INET; 301 const int socktype = SOCK_STREAM; 302 const int protocol = IPPROTO_TCP; 303 SocketAddress listen_addr; 304 if (host_str.empty()) 305 listen_addr.SetToLocalhost(family, port); 306 else if (host_str.compare("*") == 0) 307 listen_addr.SetToAnyAddress(family, port); 308 else 309 { 310 if (!listen_addr.getaddrinfo(host_str.c_str(), port_str.c_str(), family, socktype, protocol)) 311 { 312 error.SetErrorStringWithFormat("unable to resolve hostname '%s'", host_str.c_str()); 313 return error; 314 } 315 } 316 317 bool accept_connection = false; 318 std::unique_ptr<Socket> accepted_socket; 319 320 // Loop until we are happy with our connection 321 while (!accept_connection) 322 { 323 struct sockaddr_in accept_addr; 324 ::memset (&accept_addr, 0, sizeof accept_addr); 325 #if !(defined (__linux__) || defined(_WIN32)) 326 accept_addr.sin_len = sizeof accept_addr; 327 #endif 328 socklen_t accept_addr_len = sizeof accept_addr; 329 330 int sock = Accept (this->GetNativeSocket(), 331 (struct sockaddr *)&accept_addr, 332 &accept_addr_len, 333 child_processes_inherit); 334 335 if (sock == kInvalidSocketValue) 336 { 337 SetLastError (error); 338 break; 339 } 340 341 bool is_same_addr = true; 342 #if !(defined(__linux__) || (defined(_WIN32))) 343 is_same_addr = (accept_addr_len == listen_addr.sockaddr_in().sin_len); 344 #endif 345 if (is_same_addr) 346 is_same_addr = (accept_addr.sin_addr.s_addr == listen_addr.sockaddr_in().sin_addr.s_addr); 347 348 if (is_same_addr || (listen_addr.sockaddr_in().sin_addr.s_addr == INADDR_ANY)) 349 { 350 accept_connection = true; 351 // Since both sockets have the same descriptor, arbitrarily choose the send 352 // socket to be the owner. 353 accepted_socket.reset(new Socket(sock, ProtocolTcp, true)); 354 } 355 else 356 { 357 const uint8_t *accept_ip = (const uint8_t *)&accept_addr.sin_addr.s_addr; 358 const uint8_t *listen_ip = (const uint8_t *)&listen_addr.sockaddr_in().sin_addr.s_addr; 359 ::fprintf (stderr, "error: rejecting incoming connection from %u.%u.%u.%u (expecting %u.%u.%u.%u)\n", 360 accept_ip[0], accept_ip[1], accept_ip[2], accept_ip[3], 361 listen_ip[0], listen_ip[1], listen_ip[2], listen_ip[3]); 362 accepted_socket.reset(); 363 } 364 } 365 366 if (!accepted_socket) 367 return error; 368 369 // Keep our TCP packets coming without any delays. 370 accepted_socket->SetOption (IPPROTO_TCP, TCP_NODELAY, 1); 371 error.Clear(); 372 socket = accepted_socket.release(); 373 return error; 374 375 } 376 377 Error Socket::UdpConnect(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&send_socket, Socket *&recv_socket) 378 { 379 std::unique_ptr<Socket> final_send_socket; 380 std::unique_ptr<Socket> final_recv_socket; 381 NativeSocket final_send_fd = kInvalidSocketValue; 382 NativeSocket final_recv_fd = kInvalidSocketValue; 383 384 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION)); 385 if (log) 386 log->Printf ("Socket::UdpConnect (host/port = %s)", host_and_port.data()); 387 388 Error error; 389 std::string host_str; 390 std::string port_str; 391 int32_t port = INT32_MIN; 392 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error)) 393 return error; 394 395 // Setup the receiving end of the UDP connection on this localhost 396 // on port zero. After we bind to port zero we can read the port. 397 final_recv_fd = ::CreateSocket (AF_INET, SOCK_DGRAM, 0, child_processes_inherit); 398 if (final_recv_fd == kInvalidSocketValue) 399 { 400 // Socket creation failed... 401 SetLastError (error); 402 } 403 else 404 { 405 final_recv_socket.reset(new Socket(final_recv_fd, ProtocolUdp, true)); 406 407 // Socket was created, now lets bind to the requested port 408 SocketAddress addr; 409 addr.SetToAnyAddress (AF_INET, 0); 410 411 if (::bind (final_recv_fd, addr, addr.GetLength()) == -1) 412 { 413 // Bind failed... 414 SetLastError (error); 415 } 416 } 417 418 assert(error.Fail() == !(final_recv_socket && final_recv_socket->IsValid())); 419 if (error.Fail()) 420 return error; 421 422 // At this point we have setup the receive port, now we need to 423 // setup the UDP send socket 424 425 struct addrinfo hints; 426 struct addrinfo *service_info_list = NULL; 427 428 ::memset (&hints, 0, sizeof(hints)); 429 hints.ai_family = AF_INET; 430 hints.ai_socktype = SOCK_DGRAM; 431 int err = ::getaddrinfo (host_str.c_str(), port_str.c_str(), &hints, &service_info_list); 432 if (err != 0) 433 { 434 error.SetErrorStringWithFormat("getaddrinfo(%s, %s, &hints, &info) returned error %i (%s)", 435 host_str.c_str(), 436 port_str.c_str(), 437 err, 438 gai_strerror(err)); 439 return error; 440 } 441 442 for (struct addrinfo *service_info_ptr = service_info_list; 443 service_info_ptr != NULL; 444 service_info_ptr = service_info_ptr->ai_next) 445 { 446 final_send_fd = ::CreateSocket (service_info_ptr->ai_family, 447 service_info_ptr->ai_socktype, 448 service_info_ptr->ai_protocol, 449 child_processes_inherit); 450 451 if (final_send_fd != kInvalidSocketValue) 452 { 453 final_send_socket.reset(new Socket(final_send_fd, ProtocolUdp, true)); 454 final_send_socket->m_udp_send_sockaddr = service_info_ptr; 455 break; 456 } 457 else 458 continue; 459 } 460 461 :: freeaddrinfo (service_info_list); 462 463 if (final_send_fd == kInvalidSocketValue) 464 { 465 SetLastError (error); 466 return error; 467 } 468 469 send_socket = final_send_socket.release(); 470 recv_socket = final_recv_socket.release(); 471 error.Clear(); 472 return error; 473 } 474 475 Error Socket::UnixDomainConnect(llvm::StringRef name, bool child_processes_inherit, Socket *&socket) 476 { 477 Error error; 478 #ifndef LLDB_DISABLE_POSIX 479 std::unique_ptr<Socket> final_socket; 480 481 // Open the socket that was passed in as an option 482 struct sockaddr_un saddr_un; 483 int fd = ::CreateSocket (AF_UNIX, SOCK_STREAM, 0, child_processes_inherit); 484 if (fd == kInvalidSocketValue) 485 { 486 SetLastError (error); 487 return error; 488 } 489 490 final_socket.reset(new Socket(fd, ProtocolUnixDomain, true)); 491 492 saddr_un.sun_family = AF_UNIX; 493 ::strncpy(saddr_un.sun_path, name.data(), sizeof(saddr_un.sun_path) - 1); 494 saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0'; 495 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) 496 saddr_un.sun_len = SUN_LEN (&saddr_un); 497 #endif 498 499 if (::connect (fd, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) < 0) 500 { 501 SetLastError (error); 502 return error; 503 } 504 505 socket = final_socket.release(); 506 #else 507 error.SetErrorString("Unix domain sockets are not supported on this platform."); 508 #endif 509 return error; 510 } 511 512 Error Socket::UnixDomainAccept(llvm::StringRef name, bool child_processes_inherit, Socket *&socket) 513 { 514 Error error; 515 #ifndef LLDB_DISABLE_POSIX 516 struct sockaddr_un saddr_un; 517 std::unique_ptr<Socket> listen_socket; 518 std::unique_ptr<Socket> final_socket; 519 NativeSocket listen_fd = kInvalidSocketValue; 520 NativeSocket socket_fd = kInvalidSocketValue; 521 522 listen_fd = ::CreateSocket (AF_UNIX, SOCK_STREAM, 0, child_processes_inherit); 523 if (listen_fd == kInvalidSocketValue) 524 { 525 SetLastError (error); 526 return error; 527 } 528 529 listen_socket.reset(new Socket(listen_fd, ProtocolUnixDomain, true)); 530 531 saddr_un.sun_family = AF_UNIX; 532 ::strncpy(saddr_un.sun_path, name.data(), sizeof(saddr_un.sun_path) - 1); 533 saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0'; 534 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) 535 saddr_un.sun_len = SUN_LEN (&saddr_un); 536 #endif 537 538 FileSystem::Unlink(FileSpec{name, true}); 539 bool success = false; 540 if (::bind (listen_fd, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) == 0) 541 { 542 if (::listen (listen_fd, 5) == 0) 543 { 544 socket_fd = Accept (listen_fd, NULL, 0, child_processes_inherit); 545 if (socket_fd > 0) 546 { 547 final_socket.reset(new Socket(socket_fd, ProtocolUnixDomain, true)); 548 success = true; 549 } 550 } 551 } 552 553 if (!success) 554 { 555 SetLastError (error); 556 return error; 557 } 558 // We are done with the listen port 559 listen_socket.reset(); 560 561 socket = final_socket.release(); 562 #else 563 error.SetErrorString("Unix domain sockets are not supported on this platform."); 564 #endif 565 return error; 566 } 567 568 bool 569 Socket::DecodeHostAndPort(llvm::StringRef host_and_port, 570 std::string &host_str, 571 std::string &port_str, 572 int32_t& port, 573 Error *error_ptr) 574 { 575 static RegularExpression g_regex ("([^:]+):([0-9]+)"); 576 RegularExpression::Match regex_match(2); 577 if (g_regex.Execute (host_and_port.data(), ®ex_match)) 578 { 579 if (regex_match.GetMatchAtIndex (host_and_port.data(), 1, host_str) && 580 regex_match.GetMatchAtIndex (host_and_port.data(), 2, port_str)) 581 { 582 bool ok = false; 583 port = StringConvert::ToUInt32 (port_str.c_str(), UINT32_MAX, 10, &ok); 584 if (ok && port < UINT16_MAX) 585 { 586 if (error_ptr) 587 error_ptr->Clear(); 588 return true; 589 } 590 // port is too large 591 if (error_ptr) 592 error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port.data()); 593 return false; 594 } 595 } 596 597 // If this was unsuccessful, then check if it's simply a signed 32-bit integer, representing 598 // a port with an empty host. 599 host_str.clear(); 600 port_str.clear(); 601 bool ok = false; 602 port = StringConvert::ToUInt32 (host_and_port.data(), UINT32_MAX, 10, &ok); 603 if (ok && port < UINT16_MAX) 604 { 605 port_str = host_and_port; 606 if (error_ptr) 607 error_ptr->Clear(); 608 return true; 609 } 610 611 if (error_ptr) 612 error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port.data()); 613 return false; 614 } 615 616 IOObject::WaitableHandle Socket::GetWaitableHandle() 617 { 618 // TODO: On Windows, use WSAEventSelect 619 return m_socket; 620 } 621 622 Error Socket::Read (void *buf, size_t &num_bytes) 623 { 624 Error error; 625 int bytes_received = 0; 626 do 627 { 628 bytes_received = ::recv (m_socket, static_cast<char *>(buf), num_bytes, 0); 629 } while (bytes_received < 0 && IsInterrupted ()); 630 631 if (bytes_received < 0) 632 { 633 SetLastError (error); 634 num_bytes = 0; 635 } 636 else 637 num_bytes = bytes_received; 638 639 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION)); 640 if (log) 641 { 642 log->Printf ("%p Socket::Read() (socket = %" PRIu64 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)", 643 static_cast<void*>(this), 644 static_cast<uint64_t>(m_socket), 645 buf, 646 static_cast<uint64_t>(num_bytes), 647 static_cast<int64_t>(bytes_received), 648 error.AsCString()); 649 } 650 651 return error; 652 } 653 654 Error Socket::Write (const void *buf, size_t &num_bytes) 655 { 656 Error error; 657 int bytes_sent = 0; 658 do 659 { 660 if (m_protocol == ProtocolUdp) 661 { 662 bytes_sent = ::sendto (m_socket, 663 static_cast<const char*>(buf), 664 num_bytes, 665 0, 666 m_udp_send_sockaddr, 667 m_udp_send_sockaddr.GetLength()); 668 } 669 else 670 bytes_sent = ::send (m_socket, static_cast<const char *>(buf), num_bytes, 0); 671 } while (bytes_sent < 0 && IsInterrupted ()); 672 673 if (bytes_sent < 0) 674 { 675 SetLastError (error); 676 num_bytes = 0; 677 } 678 else 679 num_bytes = bytes_sent; 680 681 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION)); 682 if (log) 683 { 684 log->Printf ("%p Socket::Write() (socket = %" PRIu64 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)", 685 static_cast<void*>(this), 686 static_cast<uint64_t>(m_socket), 687 buf, 688 static_cast<uint64_t>(num_bytes), 689 static_cast<int64_t>(bytes_sent), 690 error.AsCString()); 691 } 692 693 return error; 694 } 695 696 Error Socket::PreDisconnect() 697 { 698 Error error; 699 return error; 700 } 701 702 Error Socket::Close() 703 { 704 Error error; 705 if (!IsValid() || !m_should_close_fd) 706 return error; 707 708 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION)); 709 if (log) 710 log->Printf ("%p Socket::Close (fd = %i)", static_cast<void*>(this), m_socket); 711 712 #if defined(_WIN32) 713 bool success = !!closesocket(m_socket); 714 #else 715 bool success = !!::close (m_socket); 716 #endif 717 // A reference to a FD was passed in, set it to an invalid value 718 m_socket = kInvalidSocketValue; 719 if (!success) 720 { 721 SetLastError (error); 722 } 723 724 return error; 725 } 726 727 728 int Socket::GetOption(int level, int option_name, int &option_value) 729 { 730 get_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value); 731 socklen_t option_value_size = sizeof(int); 732 return ::getsockopt(m_socket, level, option_name, option_value_p, &option_value_size); 733 } 734 735 int Socket::SetOption(int level, int option_name, int option_value) 736 { 737 set_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value); 738 return ::setsockopt(m_socket, level, option_name, option_value_p, sizeof(option_value)); 739 } 740 741 uint16_t Socket::GetLocalPortNumber(const NativeSocket& socket) 742 { 743 // We bound to port zero, so we need to figure out which port we actually bound to 744 if (socket != kInvalidSocketValue) 745 { 746 SocketAddress sock_addr; 747 socklen_t sock_addr_len = sock_addr.GetMaxLength (); 748 if (::getsockname (socket, sock_addr, &sock_addr_len) == 0) 749 return sock_addr.GetPort (); 750 } 751 return 0; 752 } 753 754 // Return the port number that is being used by the socket. 755 uint16_t Socket::GetLocalPortNumber() const 756 { 757 return GetLocalPortNumber (m_socket); 758 } 759 760 std::string Socket::GetLocalIPAddress () const 761 { 762 // We bound to port zero, so we need to figure out which port we actually bound to 763 if (m_socket != kInvalidSocketValue) 764 { 765 SocketAddress sock_addr; 766 socklen_t sock_addr_len = sock_addr.GetMaxLength (); 767 if (::getsockname (m_socket, sock_addr, &sock_addr_len) == 0) 768 return sock_addr.GetIPAddress (); 769 } 770 return ""; 771 } 772 773 uint16_t Socket::GetRemotePortNumber () const 774 { 775 if (m_socket != kInvalidSocketValue) 776 { 777 SocketAddress sock_addr; 778 socklen_t sock_addr_len = sock_addr.GetMaxLength (); 779 if (::getpeername (m_socket, sock_addr, &sock_addr_len) == 0) 780 return sock_addr.GetPort (); 781 } 782 return 0; 783 } 784 785 std::string Socket::GetRemoteIPAddress () const 786 { 787 // We bound to port zero, so we need to figure out which port we actually bound to 788 if (m_socket != kInvalidSocketValue) 789 { 790 SocketAddress sock_addr; 791 socklen_t sock_addr_len = sock_addr.GetMaxLength (); 792 if (::getpeername (m_socket, sock_addr, &sock_addr_len) == 0) 793 return sock_addr.GetIPAddress (); 794 } 795 return ""; 796 } 797