ConnectionFileDescriptor.cpp revision d5b3e3c662c967feb455a01f307c3f4bc318eec9
1//===-- ConnectionFileDescriptor.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/Core/ConnectionFileDescriptor.h" 11 12// C Includes 13#include <errno.h> 14#include <fcntl.h> 15#include <arpa/inet.h> 16#include <netdb.h> 17#include <netinet/in.h> 18#include <netinet/tcp.h> 19#include <sys/socket.h> 20#include <sys/un.h> 21#include <sys/types.h> 22#include <string.h> 23#include <stdlib.h> 24 25// C++ Includes 26// Other libraries and framework includes 27// Project includes 28#include "lldb/lldb-private-log.h" 29#include "lldb/Interpreter/Args.h" 30#include "lldb/Core/Communication.h" 31#include "lldb/Core/Log.h" 32#include "lldb/Core/RegularExpression.h" 33#include "lldb/Core/Timer.h" 34 35using namespace lldb; 36using namespace lldb_private; 37 38static bool 39DecodeHostAndPort (const char *host_and_port, 40 std::string &host_str, 41 std::string &port_str, 42 int32_t& port, 43 Error *error_ptr) 44{ 45 RegularExpression regex ("([^:]+):([0-9]+)"); 46 if (regex.Execute (host_and_port, 2)) 47 { 48 if (regex.GetMatchAtIndex (host_and_port, 1, host_str) && 49 regex.GetMatchAtIndex (host_and_port, 2, port_str)) 50 { 51 port = Args::StringToSInt32 (port_str.c_str(), INT32_MIN); 52 if (port != INT32_MIN) 53 { 54 if (error_ptr) 55 error_ptr->Clear(); 56 return true; 57 } 58 } 59 } 60 host_str.clear(); 61 port_str.clear(); 62 port = INT32_MIN; 63 if (error_ptr) 64 error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port); 65 return false; 66} 67 68ConnectionFileDescriptor::ConnectionFileDescriptor () : 69 Connection(), 70 m_fd_send (-1), 71 m_fd_recv (-1), 72 m_fd_send_type (eFDTypeFile), 73 m_fd_recv_type (eFDTypeFile), 74 m_udp_send_sockaddr (), 75 m_should_close_fd (false), 76 m_socket_timeout_usec(0) 77{ 78 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT)); 79 if (log) 80 log->Printf ("%p ConnectionFileDescriptor::ConnectionFileDescriptor ()", this); 81} 82 83ConnectionFileDescriptor::ConnectionFileDescriptor (int fd, bool owns_fd) : 84 Connection(), 85 m_fd_send (fd), 86 m_fd_recv (fd), 87 m_fd_send_type (eFDTypeFile), 88 m_fd_recv_type (eFDTypeFile), 89 m_udp_send_sockaddr (), 90 m_should_close_fd (owns_fd), 91 m_socket_timeout_usec(0) 92{ 93 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT)); 94 if (log) 95 log->Printf ("%p ConnectionFileDescriptor::ConnectionFileDescriptor (fd = %i, owns_fd = %i)", this, fd, owns_fd); 96} 97 98 99ConnectionFileDescriptor::~ConnectionFileDescriptor () 100{ 101 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION | LIBLLDB_LOG_OBJECT)); 102 if (log) 103 log->Printf ("%p ConnectionFileDescriptor::~ConnectionFileDescriptor ()", this); 104 Disconnect (NULL); 105} 106 107bool 108ConnectionFileDescriptor::IsConnected () const 109{ 110 return m_fd_send >= 0 || m_fd_recv >= 0; 111} 112 113ConnectionStatus 114ConnectionFileDescriptor::Connect (const char *s, Error *error_ptr) 115{ 116 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION)); 117 if (log) 118 log->Printf ("%p ConnectionFileDescriptor::Connect (url = '%s')", this, s); 119 120 if (s && s[0]) 121 { 122 char *end = NULL; 123 if (strstr(s, "listen://")) 124 { 125 // listen://HOST:PORT 126 unsigned long listen_port = ::strtoul(s + strlen("listen://"), &end, 0); 127 return SocketListen (listen_port, error_ptr); 128 } 129 else if (strstr(s, "unix-accept://")) 130 { 131 // unix://SOCKNAME 132 return NamedSocketAccept (s + strlen("unix-accept://"), error_ptr); 133 } 134 else if (strstr(s, "connect://")) 135 { 136 return ConnectTCP (s + strlen("connect://"), error_ptr); 137 } 138 else if (strstr(s, "tcp-connect://")) 139 { 140 return ConnectTCP (s + strlen("tcp-connect://"), error_ptr); 141 } 142 else if (strstr(s, "udp://")) 143 { 144 return ConnectUDP (s + strlen("udp://"), error_ptr); 145 } 146 else if (strstr(s, "fd://")) 147 { 148 // Just passing a native file descriptor within this current process 149 // that is already opened (possibly from a service or other source). 150 s += strlen ("fd://"); 151 bool success = false; 152 m_fd_send = m_fd_recv = Args::StringToSInt32 (s, -1, 0, &success); 153 154 if (success) 155 { 156 // We have what looks to be a valid file descriptor, but we 157 // should make it is. We currently are doing this by trying to 158 // get the flags from the file descriptor and making sure it 159 // isn't a bad fd. 160 errno = 0; 161 int flags = ::fcntl (m_fd_send, F_GETFL, 0); 162 if (flags == -1 || errno == EBADF) 163 { 164 if (error_ptr) 165 error_ptr->SetErrorStringWithFormat ("stale file descriptor: %s", s); 166 m_fd_send = m_fd_recv = -1; 167 return eConnectionStatusError; 168 } 169 else 170 { 171 // Try and get a socket option from this file descriptor to 172 // see if this is a socket and set m_is_socket accordingly. 173 int resuse; 174 bool is_socket = GetSocketOption (m_fd_send, SOL_SOCKET, SO_REUSEADDR, resuse) == 0; 175 if (is_socket) 176 m_fd_send_type = m_fd_recv_type = eFDTypeSocket; 177 m_should_close_fd = true; 178 return eConnectionStatusSuccess; 179 } 180 } 181 182 if (error_ptr) 183 error_ptr->SetErrorStringWithFormat ("invalid file descriptor: \"fd://%s\"", s); 184 m_fd_send = m_fd_recv = -1; 185 return eConnectionStatusError; 186 } 187 else if (strstr(s, "file://")) 188 { 189 // file:///PATH 190 const char *path = s + strlen("file://"); 191 m_fd_send = m_fd_recv = ::open (path, O_RDWR); 192 if (m_fd_send == -1) 193 { 194 if (error_ptr) 195 error_ptr->SetErrorToErrno(); 196 return eConnectionStatusError; 197 } 198 199 int flags = ::fcntl (m_fd_send, F_GETFL, 0); 200 if (flags >= 0) 201 { 202 if ((flags & O_NONBLOCK) == 0) 203 { 204 flags |= O_NONBLOCK; 205 ::fcntl (m_fd_send, F_SETFL, flags); 206 } 207 } 208 m_should_close_fd = true; 209 return eConnectionStatusSuccess; 210 } 211 if (error_ptr) 212 error_ptr->SetErrorStringWithFormat ("unsupported connection URL: '%s'", s); 213 return eConnectionStatusError; 214 } 215 if (error_ptr) 216 error_ptr->SetErrorString("invalid connect arguments"); 217 return eConnectionStatusError; 218} 219 220ConnectionStatus 221ConnectionFileDescriptor::Disconnect (Error *error_ptr) 222{ 223 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION)); 224 if (log) 225 log->Printf ("%p ConnectionFileDescriptor::Disconnect ()", this); 226 if (m_should_close_fd == false) 227 { 228 m_fd_send = m_fd_recv = -1; 229 return eConnectionStatusSuccess; 230 } 231 ConnectionStatus status = eConnectionStatusSuccess; 232 if (m_fd_send == m_fd_recv) 233 { 234 // Both file descriptors are the same, only close one 235 status = Close (m_fd_send, error_ptr); 236 m_fd_recv = -1; 237 } 238 else 239 { 240 // File descriptors are the different, close both if needed 241 if (m_fd_send >= 0) 242 status = Close (m_fd_send, error_ptr); 243 if (m_fd_recv >= 0) 244 { 245 ConnectionStatus recv_status = Close (m_fd_recv, error_ptr); 246 if (status == eConnectionStatusSuccess) 247 status = recv_status; 248 } 249 } 250 return status; 251} 252 253size_t 254ConnectionFileDescriptor::Read (void *dst, 255 size_t dst_len, 256 uint32_t timeout_usec, 257 ConnectionStatus &status, 258 Error *error_ptr) 259{ 260 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION)); 261 if (log) 262 log->Printf ("%p ConnectionFileDescriptor::Read () ::read (fd = %i, dst = %p, dst_len = %zu)...", 263 this, m_fd_recv, dst, dst_len); 264 265 ssize_t bytes_read = 0; 266 267 switch (m_fd_recv_type) 268 { 269 case eFDTypeFile: // Other FD requireing read/write 270 status = BytesAvailable (timeout_usec, error_ptr); 271 if (status == eConnectionStatusSuccess) 272 bytes_read = ::read (m_fd_recv, dst, dst_len); 273 break; 274 275 case eFDTypeSocket: // Socket requiring send/recv 276 if (SetSocketReceiveTimeout (timeout_usec)) 277 { 278 status = eConnectionStatusSuccess; 279 bytes_read = ::recv (m_fd_recv, dst, dst_len, 0); 280 } 281 break; 282 283 case eFDTypeSocketUDP: // Unconnected UDP socket requiring sendto/recvfrom 284 if (SetSocketReceiveTimeout (timeout_usec)) 285 { 286 status = eConnectionStatusSuccess; 287 SocketAddress from (m_udp_send_sockaddr); 288 socklen_t from_len = m_udp_send_sockaddr.GetLength(); 289 bytes_read = ::recvfrom (m_fd_recv, dst, dst_len, 0, (struct sockaddr *)&from, &from_len); 290 } 291 break; 292 } 293 294 if (status != eConnectionStatusSuccess) 295 return 0; 296 297 Error error; 298 if (bytes_read == 0) 299 { 300 error.Clear(); // End-of-file. Do not automatically close; pass along for the end-of-file handlers. 301 status = eConnectionStatusEndOfFile; 302 } 303 else if (bytes_read < 0) 304 { 305 error.SetErrorToErrno(); 306 } 307 else 308 { 309 error.Clear(); 310 } 311 312 if (log) 313 log->Printf ("%p ConnectionFileDescriptor::Read () ::read (fd = %i, dst = %p, dst_len = %zu) => %zi, error = %s", 314 this, 315 m_fd_recv, 316 dst, 317 dst_len, 318 bytes_read, 319 error.AsCString()); 320 321 if (error_ptr) 322 *error_ptr = error; 323 324 if (error.Fail()) 325 { 326 uint32_t error_value = error.GetError(); 327 switch (error_value) 328 { 329 case EAGAIN: // The file was marked for non-blocking I/O, and no data were ready to be read. 330 if (m_fd_recv_type == eFDTypeSocket || m_fd_recv_type == eFDTypeSocketUDP) 331 status = eConnectionStatusTimedOut; 332 else 333 status = eConnectionStatusSuccess; 334 return 0; 335 336 case EFAULT: // Buf points outside the allocated address space. 337 case EINTR: // A read from a slow device was interrupted before any data arrived by the delivery of a signal. 338 case EINVAL: // The pointer associated with fildes was negative. 339 case EIO: // An I/O error occurred while reading from the file system. 340 // The process group is orphaned. 341 // The file is a regular file, nbyte is greater than 0, 342 // the starting position is before the end-of-file, and 343 // the starting position is greater than or equal to the 344 // offset maximum established for the open file 345 // descriptor associated with fildes. 346 case EISDIR: // An attempt is made to read a directory. 347 case ENOBUFS: // An attempt to allocate a memory buffer fails. 348 case ENOMEM: // Insufficient memory is available. 349 status = eConnectionStatusError; 350 break; // Break to close.... 351 352 case ENOENT: // no such file or directory 353 case EBADF: // fildes is not a valid file or socket descriptor open for reading. 354 case ENXIO: // An action is requested of a device that does not exist.. 355 // A requested action cannot be performed by the device. 356 case ECONNRESET:// The connection is closed by the peer during a read attempt on a socket. 357 case ENOTCONN: // A read is attempted on an unconnected socket. 358 status = eConnectionStatusLostConnection; 359 break; // Break to close.... 360 361 case ETIMEDOUT: // A transmission timeout occurs during a read attempt on a socket. 362 status = eConnectionStatusTimedOut; 363 return 0; 364 } 365 366 Disconnect (NULL); 367 return 0; 368 } 369 return bytes_read; 370} 371 372size_t 373ConnectionFileDescriptor::Write (const void *src, size_t src_len, ConnectionStatus &status, Error *error_ptr) 374{ 375 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION)); 376 if (log) 377 log->Printf ("%p ConnectionFileDescriptor::Write (src = %p, src_len = %zu)", this, src, src_len); 378 379 if (!IsConnected ()) 380 { 381 if (error_ptr) 382 error_ptr->SetErrorString("not connected"); 383 status = eConnectionStatusNoConnection; 384 return 0; 385 } 386 387 388 Error error; 389 390 ssize_t bytes_sent = 0; 391 392 switch (m_fd_send_type) 393 { 394 case eFDTypeFile: // Other FD requireing read/write 395 bytes_sent = ::write (m_fd_send, src, src_len); 396 break; 397 398 case eFDTypeSocket: // Socket requiring send/recv 399 bytes_sent = ::send (m_fd_send, src, src_len, 0); 400 break; 401 402 case eFDTypeSocketUDP: // Unconnected UDP socket requiring sendto/recvfrom 403 assert (m_udp_send_sockaddr.GetFamily() != 0); 404 bytes_sent = ::sendto (m_fd_send, 405 src, 406 src_len, 407 0, 408 m_udp_send_sockaddr, 409 m_udp_send_sockaddr.GetLength()); 410 break; 411 } 412 413 if (bytes_sent < 0) 414 error.SetErrorToErrno (); 415 else 416 error.Clear (); 417 418 if (log) 419 { 420 switch (m_fd_send_type) 421 { 422 case eFDTypeFile: // Other FD requireing read/write 423 log->Printf ("%p ConnectionFileDescriptor::Write() ::write (fd = %i, src = %p, src_len = %zu) => %zi (error = %s)", 424 this, 425 m_fd_send, 426 src, 427 src_len, 428 bytes_sent, 429 error.AsCString()); 430 break; 431 432 case eFDTypeSocket: // Socket requiring send/recv 433 log->Printf ("%p ConnectionFileDescriptor::Write() ::send (socket = %i, src = %p, src_len = %zu, flags = 0) => %zi (error = %s)", 434 this, 435 m_fd_send, 436 src, 437 src_len, 438 bytes_sent, 439 error.AsCString()); 440 break; 441 442 case eFDTypeSocketUDP: // Unconnected UDP socket requiring sendto/recvfrom 443 log->Printf ("%p ConnectionFileDescriptor::Write() ::sendto (socket = %i, src = %p, src_len = %zu, flags = 0) => %zi (error = %s)", 444 this, 445 m_fd_send, 446 src, 447 src_len, 448 bytes_sent, 449 error.AsCString()); 450 break; 451 } 452 } 453 454 if (error_ptr) 455 *error_ptr = error; 456 457 if (error.Fail()) 458 { 459 switch (error.GetError()) 460 { 461 case EAGAIN: 462 case EINTR: 463 status = eConnectionStatusSuccess; 464 return 0; 465 466 case ECONNRESET:// The connection is closed by the peer during a read attempt on a socket. 467 case ENOTCONN: // A read is attempted on an unconnected socket. 468 status = eConnectionStatusLostConnection; 469 break; // Break to close.... 470 471 default: 472 status = eConnectionStatusError; 473 break; // Break to close.... 474 } 475 476 Disconnect (NULL); 477 return 0; 478 } 479 480 status = eConnectionStatusSuccess; 481 return bytes_sent; 482} 483 484ConnectionStatus 485ConnectionFileDescriptor::BytesAvailable (uint32_t timeout_usec, Error *error_ptr) 486{ 487 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION)); 488 if (log) 489 log->Printf("%p ConnectionFileDescriptor::BytesAvailable (timeout_usec = %u)", this, timeout_usec); 490 struct timeval *tv_ptr; 491 struct timeval tv; 492 if (timeout_usec == UINT32_MAX) 493 { 494 // Infinite wait... 495 tv_ptr = NULL; 496 } 497 else 498 { 499 TimeValue time_value; 500 time_value.OffsetWithMicroSeconds (timeout_usec); 501 tv = time_value.GetAsTimeVal(); 502 tv_ptr = &tv; 503 } 504 505 while (IsConnected()) 506 { 507 fd_set read_fds; 508 FD_ZERO (&read_fds); 509 FD_SET (m_fd_recv, &read_fds); 510 int nfds = m_fd_recv + 1; 511 512 Error error; 513 514 515 if (log) 516 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds = %i, fd = %i, NULL, NULL, timeout = %p)...", 517 this, nfds, m_fd_recv, tv_ptr); 518 519 const int num_set_fds = ::select (nfds, &read_fds, NULL, NULL, tv_ptr); 520 if (num_set_fds < 0) 521 error.SetErrorToErrno(); 522 else 523 error.Clear(); 524 525 if (log) 526 log->Printf("%p ConnectionFileDescriptor::BytesAvailable() ::select (nfds = %i, fd = %i, NULL, NULL, timeout = %p) => %d, error = %s", 527 this, nfds, m_fd_recv, tv_ptr, num_set_fds, error.AsCString()); 528 529 if (error_ptr) 530 *error_ptr = error; 531 532 if (error.Fail()) 533 { 534 switch (error.GetError()) 535 { 536 case EBADF: // One of the descriptor sets specified an invalid descriptor. 537 return eConnectionStatusLostConnection; 538 539 case EINVAL: // The specified time limit is invalid. One of its components is negative or too large. 540 default: // Other unknown error 541 return eConnectionStatusError; 542 543 case EAGAIN: // The kernel was (perhaps temporarily) unable to 544 // allocate the requested number of file descriptors, 545 // or we have non-blocking IO 546 case EINTR: // A signal was delivered before the time limit 547 // expired and before any of the selected events 548 // occurred. 549 break; // Lets keep reading to until we timeout 550 } 551 } 552 else if (num_set_fds == 0) 553 { 554 return eConnectionStatusTimedOut; 555 } 556 else if (num_set_fds > 0) 557 { 558 return eConnectionStatusSuccess; 559 } 560 } 561 562 if (error_ptr) 563 error_ptr->SetErrorString("not connected"); 564 return eConnectionStatusLostConnection; 565} 566 567ConnectionStatus 568ConnectionFileDescriptor::Close (int& fd, Error *error_ptr) 569{ 570 if (error_ptr) 571 error_ptr->Clear(); 572 bool success = true; 573 if (fd >= 0) 574 { 575 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION)); 576 if (log) 577 log->Printf ("%p ConnectionFileDescriptor::Close (fd = %i)", this,fd); 578 579 success = ::close (fd) == 0; 580 if (!success && error_ptr) 581 { 582 // Only set the error if we have been asked to since something else 583 // might have caused us to try and shut down the connection and may 584 // have already set the error. 585 error_ptr->SetErrorToErrno(); 586 } 587 fd = -1; 588 } 589 m_fd_send_type = m_fd_recv_type = eFDTypeFile; 590 if (success) 591 return eConnectionStatusSuccess; 592 else 593 return eConnectionStatusError; 594} 595 596ConnectionStatus 597ConnectionFileDescriptor::NamedSocketAccept (const char *socket_name, Error *error_ptr) 598{ 599 ConnectionStatus result = eConnectionStatusError; 600 struct sockaddr_un saddr_un; 601 602 m_fd_send_type = m_fd_recv_type = eFDTypeSocket; 603 604 int listen_socket = ::socket (AF_UNIX, SOCK_STREAM, 0); 605 if (listen_socket == -1) 606 { 607 if (error_ptr) 608 error_ptr->SetErrorToErrno(); 609 return eConnectionStatusError; 610 } 611 612 saddr_un.sun_family = AF_UNIX; 613 ::strncpy(saddr_un.sun_path, socket_name, sizeof(saddr_un.sun_path) - 1); 614 saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0'; 615#if defined(__APPLE__) || defined(__FreeBSD__) 616 saddr_un.sun_len = SUN_LEN (&saddr_un); 617#endif 618 619 if (::bind (listen_socket, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) == 0) 620 { 621 if (::listen (listen_socket, 5) == 0) 622 { 623 m_fd_send = m_fd_recv = ::accept (listen_socket, NULL, 0); 624 if (m_fd_send > 0) 625 { 626 m_should_close_fd = true; 627 628 if (error_ptr) 629 error_ptr->Clear(); 630 result = eConnectionStatusSuccess; 631 } 632 } 633 } 634 635 if (result != eConnectionStatusSuccess) 636 { 637 if (error_ptr) 638 error_ptr->SetErrorToErrno(); 639 } 640 // We are done with the listen port 641 Close (listen_socket, NULL); 642 return result; 643} 644 645ConnectionStatus 646ConnectionFileDescriptor::NamedSocketConnect (const char *socket_name, Error *error_ptr) 647{ 648 Disconnect (NULL); 649 m_fd_send_type = m_fd_recv_type = eFDTypeSocket; 650 651 // Open the socket that was passed in as an option 652 struct sockaddr_un saddr_un; 653 m_fd_send = m_fd_recv = ::socket (AF_UNIX, SOCK_STREAM, 0); 654 if (m_fd_send == -1) 655 { 656 if (error_ptr) 657 error_ptr->SetErrorToErrno(); 658 return eConnectionStatusError; 659 } 660 661 saddr_un.sun_family = AF_UNIX; 662 ::strncpy(saddr_un.sun_path, socket_name, sizeof(saddr_un.sun_path) - 1); 663 saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0'; 664#if defined(__APPLE__) || defined(__FreeBSD__) 665 saddr_un.sun_len = SUN_LEN (&saddr_un); 666#endif 667 668 if (::connect (m_fd_send, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) < 0) 669 { 670 if (error_ptr) 671 error_ptr->SetErrorToErrno(); 672 Disconnect (NULL); 673 return eConnectionStatusError; 674 } 675 if (error_ptr) 676 error_ptr->Clear(); 677 return eConnectionStatusSuccess; 678} 679 680ConnectionStatus 681ConnectionFileDescriptor::SocketListen (uint16_t listen_port_num, Error *error_ptr) 682{ 683 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION)); 684 if (log) 685 log->Printf ("%p ConnectionFileDescriptor::SocketListen (port = %i)", this, listen_port_num); 686 687 Disconnect (NULL); 688 m_fd_send_type = m_fd_recv_type = eFDTypeSocket; 689 int listen_port = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); 690 if (listen_port == -1) 691 { 692 if (error_ptr) 693 error_ptr->SetErrorToErrno(); 694 return eConnectionStatusError; 695 } 696 697 // enable local address reuse 698 SetSocketOption (listen_port, SOL_SOCKET, SO_REUSEADDR, 1); 699 700 SocketAddress localhost; 701 if (localhost.SetToLocalhost (AF_INET, listen_port_num)) 702 { 703 int err = ::bind (listen_port, localhost, localhost.GetLength()); 704 if (err == -1) 705 { 706 if (error_ptr) 707 error_ptr->SetErrorToErrno(); 708 Close (listen_port, NULL); 709 return eConnectionStatusError; 710 } 711 712 err = ::listen (listen_port, 1); 713 if (err == -1) 714 { 715 if (error_ptr) 716 error_ptr->SetErrorToErrno(); 717 Close (listen_port, NULL); 718 return eConnectionStatusError; 719 } 720 721 m_fd_send = m_fd_recv = ::accept (listen_port, NULL, 0); 722 if (m_fd_send == -1) 723 { 724 if (error_ptr) 725 error_ptr->SetErrorToErrno(); 726 Close (listen_port, NULL); 727 return eConnectionStatusError; 728 } 729 } 730 731 // We are done with the listen port 732 Close (listen_port, NULL); 733 734 m_should_close_fd = true; 735 736 // Keep our TCP packets coming without any delays. 737 SetSocketOption (m_fd_send, IPPROTO_TCP, TCP_NODELAY, 1); 738 if (error_ptr) 739 error_ptr->Clear(); 740 return eConnectionStatusSuccess; 741} 742 743ConnectionStatus 744ConnectionFileDescriptor::ConnectTCP (const char *host_and_port, Error *error_ptr) 745{ 746 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION)); 747 if (log) 748 log->Printf ("%p ConnectionFileDescriptor::ConnectTCP (host/port = %s)", this, host_and_port); 749 Disconnect (NULL); 750 751 m_fd_send_type = m_fd_recv_type = eFDTypeSocket; 752 std::string host_str; 753 std::string port_str; 754 int32_t port = INT32_MIN; 755 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, error_ptr)) 756 return eConnectionStatusError; 757 758 // Create the socket 759 m_fd_send = m_fd_recv = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); 760 if (m_fd_send == -1) 761 { 762 if (error_ptr) 763 error_ptr->SetErrorToErrno(); 764 return eConnectionStatusError; 765 } 766 767 m_should_close_fd = true; 768 769 // Enable local address reuse 770 SetSocketOption (m_fd_send, SOL_SOCKET, SO_REUSEADDR, 1); 771 772 struct sockaddr_in sa; 773 ::memset (&sa, 0, sizeof (sa)); 774 sa.sin_family = AF_INET; 775 sa.sin_port = htons (port); 776 777 int inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr); 778 779 if (inet_pton_result <= 0) 780 { 781 struct hostent *host_entry = gethostbyname (host_str.c_str()); 782 if (host_entry) 783 host_str = ::inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list); 784 inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr); 785 if (inet_pton_result <= 0) 786 { 787 788 if (error_ptr) 789 { 790 if (inet_pton_result == -1) 791 error_ptr->SetErrorToErrno(); 792 else 793 error_ptr->SetErrorStringWithFormat("invalid host string: '%s'", host_str.c_str()); 794 } 795 Disconnect (NULL); 796 797 return eConnectionStatusError; 798 } 799 } 800 801 if (-1 == ::connect (m_fd_send, (const struct sockaddr *)&sa, sizeof(sa))) 802 { 803 if (error_ptr) 804 error_ptr->SetErrorToErrno(); 805 Disconnect (NULL); 806 807 return eConnectionStatusError; 808 } 809 810 // Keep our TCP packets coming without any delays. 811 SetSocketOption (m_fd_send, IPPROTO_TCP, TCP_NODELAY, 1); 812 if (error_ptr) 813 error_ptr->Clear(); 814 return eConnectionStatusSuccess; 815} 816 817ConnectionStatus 818ConnectionFileDescriptor::ConnectUDP (const char *host_and_port, Error *error_ptr) 819{ 820 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION)); 821 if (log) 822 log->Printf ("%p ConnectionFileDescriptor::ConnectUDP (host/port = %s)", this, host_and_port); 823 Disconnect (NULL); 824 825 m_fd_send_type = m_fd_recv_type = eFDTypeSocketUDP; 826 827 std::string host_str; 828 std::string port_str; 829 int32_t port = INT32_MIN; 830 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, error_ptr)) 831 return eConnectionStatusError; 832 833 // Setup the receiving end of the UDP connection on this localhost 834 // on port zero. After we bind to port zero we can read the port. 835 m_fd_recv = ::socket (AF_INET, SOCK_DGRAM, 0); 836 if (m_fd_recv == -1) 837 { 838 // Socket creation failed... 839 if (error_ptr) 840 error_ptr->SetErrorToErrno(); 841 } 842 else 843 { 844 // Socket was created, now lets bind to the requested port 845 struct sockaddr_in sin; 846 ::memset (&sin, 0, sizeof(sin)); 847 sin.sin_len = sizeof(sin); 848 sin.sin_family = AF_INET; 849 sin.sin_port = 0; 850 sin.sin_addr.s_addr = htonl (INADDR_ANY); 851 852 if (::bind (m_fd_recv, (struct sockaddr *)&sin, sizeof(sin)) == -1) 853 { 854 // Bind failed... 855 if (error_ptr) 856 error_ptr->SetErrorToErrno(); 857 Disconnect (NULL); 858 } 859 } 860 861 if (m_fd_recv == -1) 862 return eConnectionStatusError; 863 864 // At this point we have setup the recieve port, now we need to 865 // setup the UDP send socket 866 867 struct addrinfo hints; 868 struct addrinfo *service_info_list = NULL; 869 870 ::memset (&hints, 0, sizeof(hints)); 871 hints.ai_family = AF_INET; 872 hints.ai_socktype = SOCK_DGRAM; 873 int err = ::getaddrinfo (host_str.c_str(), port_str.c_str(), &hints, &service_info_list); 874 if (err != 0) 875 { 876 if (error_ptr) 877 error_ptr->SetErrorStringWithFormat("getaddrinfo(%s, %s, &hints, &info) returned error %i (%s)", 878 host_str.c_str(), 879 port_str.c_str(), 880 err, 881 gai_strerror(err)); 882 Disconnect (NULL); 883 return eConnectionStatusError; 884 } 885 886 for (struct addrinfo *service_info_ptr = service_info_list; 887 service_info_ptr != NULL; 888 service_info_ptr = service_info_ptr->ai_next) 889 { 890 m_fd_send = ::socket (service_info_ptr->ai_family, 891 service_info_ptr->ai_socktype, 892 service_info_ptr->ai_protocol); 893 894 if (m_fd_send != -1) 895 { 896 m_udp_send_sockaddr = service_info_ptr; 897 break; 898 } 899 else 900 continue; 901 } 902 903 :: freeaddrinfo (service_info_list); 904 905 if (m_fd_send == -1) 906 { 907 Disconnect (NULL); 908 return eConnectionStatusError; 909 } 910 911 if (error_ptr) 912 error_ptr->Clear(); 913 914 m_should_close_fd = true; 915 return eConnectionStatusSuccess; 916} 917 918#if defined(__MINGW32__) || defined(__MINGW64__) 919typedef const char * set_socket_option_arg_type; 920typedef char * get_socket_option_arg_type; 921#else // #if defined(__MINGW32__) || defined(__MINGW64__) 922typedef const void * set_socket_option_arg_type; 923typedef void * get_socket_option_arg_type; 924#endif // #if defined(__MINGW32__) || defined(__MINGW64__) 925 926int 927ConnectionFileDescriptor::GetSocketOption(int fd, int level, int option_name, int &option_value) 928{ 929 get_socket_option_arg_type option_value_p = static_cast<get_socket_option_arg_type>(&option_value); 930 socklen_t option_value_size = sizeof(int); 931 return ::getsockopt(fd, level, option_name, option_value_p, &option_value_size); 932} 933 934int 935ConnectionFileDescriptor::SetSocketOption(int fd, int level, int option_name, int option_value) 936{ 937 set_socket_option_arg_type option_value_p = static_cast<get_socket_option_arg_type>(&option_value); 938 return ::setsockopt(fd, level, option_name, option_value_p, sizeof(option_value)); 939} 940 941bool 942ConnectionFileDescriptor::SetSocketReceiveTimeout (uint32_t timeout_usec) 943{ 944 switch (m_fd_recv_type) 945 { 946 case eFDTypeFile: // Other FD requireing read/write 947 break; 948 949 case eFDTypeSocket: // Socket requiring send/recv 950 case eFDTypeSocketUDP: // Unconnected UDP socket requiring sendto/recvfrom 951 { 952 // Check in case timeout for m_fd has already been set to this value 953 if (timeout_usec == m_socket_timeout_usec) 954 return true; 955 //printf ("ConnectionFileDescriptor::SetSocketReceiveTimeout (timeout_usec = %u)\n", timeout_usec); 956 957 struct timeval timeout; 958 timeout.tv_sec = timeout_usec / TimeValue::MicroSecPerSec; 959 timeout.tv_usec = timeout_usec % TimeValue::MicroSecPerSec; 960 if (::setsockopt (m_fd_recv, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == 0) 961 { 962 m_socket_timeout_usec = timeout_usec; 963 return true; 964 } 965 } 966 } 967 return false; 968} 969 970in_port_t 971ConnectionFileDescriptor::GetSocketPort (int fd) 972{ 973 // We bound to port zero, so we need to figure out which port we actually bound to 974 SocketAddress sock_addr; 975 socklen_t sock_addr_len = sock_addr.GetMaxLength (); 976 if (::getsockname (fd, sock_addr, &sock_addr_len) == 0) 977 return sock_addr.GetPort (); 978 979 return 0; 980} 981 982// If the read file descriptor is a socket, then return 983// the port number that is being used by the socket. 984in_port_t 985ConnectionFileDescriptor::GetReadPort () const 986{ 987 return ConnectionFileDescriptor::GetSocketPort (m_fd_recv); 988} 989 990// If the write file descriptor is a socket, then return 991// the port number that is being used by the socket. 992in_port_t 993ConnectionFileDescriptor::GetWritePort () const 994{ 995 return ConnectionFileDescriptor::GetSocketPort (m_fd_send); 996} 997 998 999