ConnectionFileDescriptor.cpp revision ac304e4cbd1005210661720d5f2232f85b08c195
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 struct sockaddr_in sa; 701 ::memset (&sa, 0, sizeof sa); 702 sa.sin_family = AF_INET; 703 sa.sin_port = htons (listen_port_num); 704 sa.sin_addr.s_addr = htonl (INADDR_ANY); 705 706 int err = ::bind (listen_port, (struct sockaddr *) &sa, sizeof(sa)); 707 if (err == -1) 708 { 709 if (error_ptr) 710 error_ptr->SetErrorToErrno(); 711 Close (listen_port, NULL); 712 return eConnectionStatusError; 713 } 714 715 err = ::listen (listen_port, 1); 716 if (err == -1) 717 { 718 if (error_ptr) 719 error_ptr->SetErrorToErrno(); 720 Close (listen_port, NULL); 721 return eConnectionStatusError; 722 } 723 724 m_fd_send = m_fd_recv = ::accept (listen_port, NULL, 0); 725 if (m_fd_send == -1) 726 { 727 if (error_ptr) 728 error_ptr->SetErrorToErrno(); 729 Close (listen_port, NULL); 730 return eConnectionStatusError; 731 } 732 733 // We are done with the listen port 734 Close (listen_port, NULL); 735 736 m_should_close_fd = true; 737 738 // Keep our TCP packets coming without any delays. 739 SetSocketOption (m_fd_send, IPPROTO_TCP, TCP_NODELAY, 1); 740 if (error_ptr) 741 error_ptr->Clear(); 742 return eConnectionStatusSuccess; 743} 744 745ConnectionStatus 746ConnectionFileDescriptor::ConnectTCP (const char *host_and_port, Error *error_ptr) 747{ 748 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION)); 749 if (log) 750 log->Printf ("%p ConnectionFileDescriptor::ConnectTCP (host/port = %s)", this, host_and_port); 751 Disconnect (NULL); 752 753 m_fd_send_type = m_fd_recv_type = eFDTypeSocket; 754 std::string host_str; 755 std::string port_str; 756 int32_t port = INT32_MIN; 757 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, error_ptr)) 758 return eConnectionStatusError; 759 760 // Create the socket 761 m_fd_send = m_fd_recv = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); 762 if (m_fd_send == -1) 763 { 764 if (error_ptr) 765 error_ptr->SetErrorToErrno(); 766 return eConnectionStatusError; 767 } 768 769 m_should_close_fd = true; 770 771 // Enable local address reuse 772 SetSocketOption (m_fd_send, SOL_SOCKET, SO_REUSEADDR, 1); 773 774 struct sockaddr_in sa; 775 ::memset (&sa, 0, sizeof (sa)); 776 sa.sin_family = AF_INET; 777 sa.sin_port = htons (port); 778 779 int inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr); 780 781 if (inet_pton_result <= 0) 782 { 783 struct hostent *host_entry = gethostbyname (host_str.c_str()); 784 if (host_entry) 785 host_str = ::inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list); 786 inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr); 787 if (inet_pton_result <= 0) 788 { 789 790 if (error_ptr) 791 { 792 if (inet_pton_result == -1) 793 error_ptr->SetErrorToErrno(); 794 else 795 error_ptr->SetErrorStringWithFormat("invalid host string: '%s'", host_str.c_str()); 796 } 797 Disconnect (NULL); 798 799 return eConnectionStatusError; 800 } 801 } 802 803 if (-1 == ::connect (m_fd_send, (const struct sockaddr *)&sa, sizeof(sa))) 804 { 805 if (error_ptr) 806 error_ptr->SetErrorToErrno(); 807 Disconnect (NULL); 808 809 return eConnectionStatusError; 810 } 811 812 // Keep our TCP packets coming without any delays. 813 SetSocketOption (m_fd_send, IPPROTO_TCP, TCP_NODELAY, 1); 814 if (error_ptr) 815 error_ptr->Clear(); 816 return eConnectionStatusSuccess; 817} 818 819ConnectionStatus 820ConnectionFileDescriptor::ConnectUDP (const char *host_and_port, Error *error_ptr) 821{ 822 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION)); 823 if (log) 824 log->Printf ("%p ConnectionFileDescriptor::ConnectUDP (host/port = %s)", this, host_and_port); 825 Disconnect (NULL); 826 827 m_fd_send_type = m_fd_recv_type = eFDTypeSocketUDP; 828 829 std::string host_str; 830 std::string port_str; 831 int32_t port = INT32_MIN; 832 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, error_ptr)) 833 return eConnectionStatusError; 834 835 // Setup the receiving end of the UDP connection on this localhost 836 // on port zero. After we bind to port zero we can read the port. 837 m_fd_recv = ::socket (AF_INET, SOCK_DGRAM, 0); 838 if (m_fd_recv == -1) 839 { 840 // Socket creation failed... 841 if (error_ptr) 842 error_ptr->SetErrorToErrno(); 843 } 844 else 845 { 846 // Socket was created, now lets bind to the requested port 847 struct sockaddr_in sin; 848 ::memset (&sin, 0, sizeof(sin)); 849 sin.sin_len = sizeof(sin); 850 sin.sin_family = AF_INET; 851 sin.sin_port = 0; 852 sin.sin_addr.s_addr = htonl (INADDR_ANY); 853 854 if (::bind (m_fd_recv, (struct sockaddr *)&sin, sizeof(sin)) == -1) 855 { 856 // Bind failed... 857 if (error_ptr) 858 error_ptr->SetErrorToErrno(); 859 Disconnect (NULL); 860 } 861 } 862 863 if (m_fd_recv == -1) 864 return eConnectionStatusError; 865 866 // At this point we have setup the recieve port, now we need to 867 // setup the UDP send socket 868 869 struct addrinfo hints; 870 struct addrinfo *service_info_list = NULL; 871 872 ::memset (&hints, 0, sizeof(hints)); 873 hints.ai_family = AF_INET; 874 hints.ai_socktype = SOCK_DGRAM; 875 int err = ::getaddrinfo (host_str.c_str(), port_str.c_str(), &hints, &service_info_list); 876 if (err != 0) 877 { 878 if (error_ptr) 879 error_ptr->SetErrorStringWithFormat("getaddrinfo(%s, %s, &hints, &info) returned error %i (%s)", 880 host_str.c_str(), 881 port_str.c_str(), 882 err, 883 gai_strerror(err)); 884 Disconnect (NULL); 885 return eConnectionStatusError; 886 } 887 888 for (struct addrinfo *service_info_ptr = service_info_list; 889 service_info_ptr != NULL; 890 service_info_ptr = service_info_ptr->ai_next) 891 { 892 m_fd_send = ::socket (service_info_ptr->ai_family, 893 service_info_ptr->ai_socktype, 894 service_info_ptr->ai_protocol); 895 896 if (m_fd_send != -1) 897 { 898 m_udp_send_sockaddr = service_info_ptr; 899 break; 900 } 901 else 902 continue; 903 } 904 905 :: freeaddrinfo (service_info_list); 906 907 if (m_fd_send == -1) 908 { 909 Disconnect (NULL); 910 return eConnectionStatusError; 911 } 912 913 if (error_ptr) 914 error_ptr->Clear(); 915 916 m_should_close_fd = true; 917 return eConnectionStatusSuccess; 918} 919 920#if defined(__MINGW32__) || defined(__MINGW64__) 921typedef const char * set_socket_option_arg_type; 922typedef char * get_socket_option_arg_type; 923#else // #if defined(__MINGW32__) || defined(__MINGW64__) 924typedef const void * set_socket_option_arg_type; 925typedef void * get_socket_option_arg_type; 926#endif // #if defined(__MINGW32__) || defined(__MINGW64__) 927 928int 929ConnectionFileDescriptor::GetSocketOption(int fd, int level, int option_name, int &option_value) 930{ 931 get_socket_option_arg_type option_value_p = static_cast<get_socket_option_arg_type>(&option_value); 932 socklen_t option_value_size = sizeof(int); 933 return ::getsockopt(fd, level, option_name, option_value_p, &option_value_size); 934} 935 936int 937ConnectionFileDescriptor::SetSocketOption(int fd, int level, int option_name, int option_value) 938{ 939 set_socket_option_arg_type option_value_p = static_cast<get_socket_option_arg_type>(&option_value); 940 return ::setsockopt(fd, level, option_name, option_value_p, sizeof(option_value)); 941} 942 943bool 944ConnectionFileDescriptor::SetSocketReceiveTimeout (uint32_t timeout_usec) 945{ 946 switch (m_fd_recv_type) 947 { 948 case eFDTypeFile: // Other FD requireing read/write 949 break; 950 951 case eFDTypeSocket: // Socket requiring send/recv 952 case eFDTypeSocketUDP: // Unconnected UDP socket requiring sendto/recvfrom 953 { 954 // Check in case timeout for m_fd has already been set to this value 955 if (timeout_usec == m_socket_timeout_usec) 956 return true; 957 //printf ("ConnectionFileDescriptor::SetSocketReceiveTimeout (timeout_usec = %u)\n", timeout_usec); 958 959 struct timeval timeout; 960 timeout.tv_sec = timeout_usec / TimeValue::MicroSecPerSec; 961 timeout.tv_usec = timeout_usec % TimeValue::MicroSecPerSec; 962 if (::setsockopt (m_fd_recv, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == 0) 963 { 964 m_socket_timeout_usec = timeout_usec; 965 return true; 966 } 967 } 968 } 969 return false; 970} 971 972in_port_t 973ConnectionFileDescriptor::GetSocketPort (int fd) 974{ 975 // We bound to port zero, so we need to figure out which port we actually bound to 976 SocketAddress sock_addr; 977 socklen_t sock_addr_len = sock_addr.GetMaxLength (); 978 if (::getsockname (fd, sock_addr, &sock_addr_len) == 0) 979 return sock_addr.GetPort (); 980 981 return 0; 982} 983 984// If the read file descriptor is a socket, then return 985// the port number that is being used by the socket. 986in_port_t 987ConnectionFileDescriptor::GetReadPort () const 988{ 989 return ConnectionFileDescriptor::GetSocketPort (m_fd_recv); 990} 991 992// If the write file descriptor is a socket, then return 993// the port number that is being used by the socket. 994in_port_t 995ConnectionFileDescriptor::GetWritePort () const 996{ 997 return ConnectionFileDescriptor::GetSocketPort (m_fd_send); 998} 999 1000 1001