1 //===-- Socket.cpp ----------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Host/Socket.h"
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/TimeValue.h"
19 #include "lldb/Interpreter/Args.h"
21 #ifndef LLDB_DISABLE_POSIX
22 #include <arpa/inet.h>
24 #include <netinet/in.h>
25 #include <netinet/tcp.h>
26 #include <sys/socket.h>
31 using namespace lldb_private;
34 typedef const char * set_socket_option_arg_type;
35 typedef char * get_socket_option_arg_type;
36 const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET;
37 #else // #if defined(_WIN32)
38 typedef const void * set_socket_option_arg_type;
39 typedef void * get_socket_option_arg_type;
40 const NativeSocket Socket::kInvalidSocketValue = -1;
41 #endif // #if defined(_WIN32)
43 Socket::Socket(NativeSocket socket, SocketProtocol protocol, bool should_close)
44 : IOObject(eFDTypeSocket, should_close)
45 , m_protocol(protocol)
56 Error Socket::TcpConnect(llvm::StringRef host_and_port, Socket *&socket)
58 // Store the result in a unique_ptr in case we error out, the memory will get correctly freed.
59 std::unique_ptr<Socket> final_socket;
60 NativeSocket sock = kInvalidSocketValue;
63 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_HOST));
65 log->Printf ("Socket::TcpConnect (host/port = %s)", host_and_port.data());
69 int32_t port = INT32_MIN;
70 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error))
74 sock = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
75 if (sock == kInvalidSocketValue)
77 // TODO: On Windows, use WSAGetLastError().
78 error.SetErrorToErrno();
82 // Since they both refer to the same socket descriptor, arbitrarily choose the send socket to
84 final_socket.reset(new Socket(sock, ProtocolTcp, true));
86 // Enable local address reuse
87 final_socket->SetOption(SOL_SOCKET, SO_REUSEADDR, 1);
89 struct sockaddr_in sa;
90 ::memset (&sa, 0, sizeof (sa));
91 sa.sin_family = AF_INET;
92 sa.sin_port = htons (port);
94 int inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
96 if (inet_pton_result <= 0)
98 struct hostent *host_entry = gethostbyname (host_str.c_str());
100 host_str = ::inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
101 inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
102 if (inet_pton_result <= 0)
104 // TODO: On Windows, use WSAGetLastError()
105 if (inet_pton_result == -1)
106 error.SetErrorToErrno();
108 error.SetErrorStringWithFormat("invalid host string: '%s'", host_str.c_str());
114 if (-1 == ::connect (sock, (const struct sockaddr *)&sa, sizeof(sa)))
116 // TODO: On Windows, use WSAGetLastError()
117 error.SetErrorToErrno();
121 // Keep our TCP packets coming without any delays.
122 final_socket->SetOption(IPPROTO_TCP, TCP_NODELAY, 1);
124 socket = final_socket.release();
128 Error Socket::TcpListen(llvm::StringRef host_and_port, Socket *&socket, Predicate<uint16_t>* predicate)
130 std::unique_ptr<Socket> listen_socket;
131 NativeSocket listen_sock = kInvalidSocketValue;
134 const sa_family_t family = AF_INET;
135 const int socktype = SOCK_STREAM;
136 const int protocol = IPPROTO_TCP;
137 listen_sock = ::socket (family, socktype, protocol);
138 if (listen_sock == kInvalidSocketValue)
140 error.SetErrorToErrno();
144 listen_socket.reset(new Socket(listen_sock, ProtocolTcp, true));
146 // enable local address reuse
147 listen_socket->SetOption(SOL_SOCKET, SO_REUSEADDR, 1);
149 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
151 log->Printf ("ConnectionFileDescriptor::SocketListen (%s)", host_and_port.data());
153 std::string host_str;
154 std::string port_str;
155 int32_t port = INT32_MIN;
156 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error))
159 SocketAddress anyaddr;
160 if (anyaddr.SetToAnyAddress (family, port))
162 int err = ::bind (listen_sock, anyaddr, anyaddr.GetLength());
165 // TODO: On Windows, use WSAGetLastError()
166 error.SetErrorToErrno();
170 err = ::listen (listen_sock, 1);
173 // TODO: On Windows, use WSAGetLastError()
174 error.SetErrorToErrno();
178 // We were asked to listen on port zero which means we
179 // must now read the actual port that was given to us
180 // as port zero is a special code for "find an open port
183 port = listen_socket->GetPortNumber();
185 // Set the port predicate since when doing a listen://<host>:<port>
186 // it often needs to accept the incoming connection which is a blocking
187 // system call. Allowing access to the bound port using a predicate allows
188 // us to wait for the port predicate to be set to a non-zero value from
189 // another thread in an efficient manor.
191 predicate->SetValue(port, eBroadcastAlways);
193 socket = listen_socket.release();
199 Error Socket::BlockingAccept(llvm::StringRef host_and_port, Socket *&socket)
202 std::string host_str;
203 std::string port_str;
205 if (!DecodeHostAndPort(host_and_port, host_str, port_str, port, &error))
208 const sa_family_t family = AF_INET;
209 const int socktype = SOCK_STREAM;
210 const int protocol = IPPROTO_TCP;
211 SocketAddress listen_addr;
212 if (host_str.empty())
213 listen_addr.SetToLocalhost(family, port);
214 else if (host_str.compare("*") == 0)
215 listen_addr.SetToAnyAddress(family, port);
218 if (!listen_addr.getaddrinfo(host_str.c_str(), port_str.c_str(), family, socktype, protocol))
220 error.SetErrorStringWithFormat("unable to resolve hostname '%s'", host_str.c_str());
225 bool accept_connection = false;
226 std::unique_ptr<Socket> accepted_socket;
228 // Loop until we are happy with our connection
229 while (!accept_connection)
231 struct sockaddr_in accept_addr;
232 ::memset (&accept_addr, 0, sizeof accept_addr);
233 #if !(defined (__linux__) || defined(_WIN32))
234 accept_addr.sin_len = sizeof accept_addr;
236 socklen_t accept_addr_len = sizeof accept_addr;
238 int sock = ::accept (this->GetNativeSocket(), (struct sockaddr *)&accept_addr, &accept_addr_len);
240 if (sock == kInvalidSocketValue)
242 // TODO: On Windows, use WSAGetLastError()
243 error.SetErrorToErrno();
247 bool is_same_addr = true;
248 #if !(defined(__linux__) || (defined(_WIN32)))
249 is_same_addr = (accept_addr_len == listen_addr.sockaddr_in().sin_len);
252 is_same_addr = (accept_addr.sin_addr.s_addr == listen_addr.sockaddr_in().sin_addr.s_addr);
254 if (is_same_addr || (listen_addr.sockaddr_in().sin_addr.s_addr == INADDR_ANY))
256 accept_connection = true;
257 // Since both sockets have the same descriptor, arbitrarily choose the send
258 // socket to be the owner.
259 accepted_socket.reset(new Socket(sock, ProtocolTcp, true));
263 const uint8_t *accept_ip = (const uint8_t *)&accept_addr.sin_addr.s_addr;
264 const uint8_t *listen_ip = (const uint8_t *)&listen_addr.sockaddr_in().sin_addr.s_addr;
265 ::fprintf (stderr, "error: rejecting incoming connection from %u.%u.%u.%u (expecting %u.%u.%u.%u)\n",
266 accept_ip[0], accept_ip[1], accept_ip[2], accept_ip[3],
267 listen_ip[0], listen_ip[1], listen_ip[2], listen_ip[3]);
268 accepted_socket.reset();
272 if (!accepted_socket)
275 // Keep our TCP packets coming without any delays.
276 accepted_socket->SetOption (IPPROTO_TCP, TCP_NODELAY, 1);
278 socket = accepted_socket.release();
283 Error Socket::UdpConnect(llvm::StringRef host_and_port, Socket *&send_socket, Socket *&recv_socket)
285 std::unique_ptr<Socket> final_send_socket;
286 std::unique_ptr<Socket> final_recv_socket;
287 NativeSocket final_send_fd = kInvalidSocketValue;
288 NativeSocket final_recv_fd = kInvalidSocketValue;
290 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
292 log->Printf ("Socket::UdpConnect (host/port = %s)", host_and_port.data());
295 std::string host_str;
296 std::string port_str;
297 int32_t port = INT32_MIN;
298 if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error))
301 // Setup the receiving end of the UDP connection on this localhost
302 // on port zero. After we bind to port zero we can read the port.
303 final_recv_fd = ::socket (AF_INET, SOCK_DGRAM, 0);
304 if (final_recv_fd == kInvalidSocketValue)
306 // Socket creation failed...
307 // TODO: On Windows, use WSAGetLastError().
308 error.SetErrorToErrno();
312 final_recv_socket.reset(new Socket(final_recv_fd, ProtocolUdp, true));
314 // Socket was created, now lets bind to the requested port
316 addr.SetToAnyAddress (AF_INET, 0);
318 if (::bind (final_recv_fd, addr, addr.GetLength()) == -1)
321 // TODO: On Windows use WSAGetLastError()
322 error.SetErrorToErrno();
326 assert(error.Fail() == !(final_recv_socket && final_recv_socket->IsValid()));
330 // At this point we have setup the receive port, now we need to
331 // setup the UDP send socket
333 struct addrinfo hints;
334 struct addrinfo *service_info_list = NULL;
336 ::memset (&hints, 0, sizeof(hints));
337 hints.ai_family = AF_INET;
338 hints.ai_socktype = SOCK_DGRAM;
339 int err = ::getaddrinfo (host_str.c_str(), port_str.c_str(), &hints, &service_info_list);
342 error.SetErrorStringWithFormat("getaddrinfo(%s, %s, &hints, &info) returned error %i (%s)",
350 for (struct addrinfo *service_info_ptr = service_info_list;
351 service_info_ptr != NULL;
352 service_info_ptr = service_info_ptr->ai_next)
354 final_send_fd = ::socket (service_info_ptr->ai_family,
355 service_info_ptr->ai_socktype,
356 service_info_ptr->ai_protocol);
358 if (final_send_fd != kInvalidSocketValue)
360 final_send_socket.reset(new Socket(final_send_fd, ProtocolUdp, true));
361 final_send_socket->m_udp_send_sockaddr = service_info_ptr;
368 :: freeaddrinfo (service_info_list);
370 if (final_send_fd == kInvalidSocketValue)
372 // TODO: On Windows, use WSAGetLastError().
373 error.SetErrorToErrno();
377 send_socket = final_send_socket.release();
378 recv_socket = final_recv_socket.release();
383 Error Socket::UnixDomainConnect(llvm::StringRef name, Socket *&socket)
386 #ifndef LLDB_DISABLE_POSIX
387 std::unique_ptr<Socket> final_socket;
389 // Open the socket that was passed in as an option
390 struct sockaddr_un saddr_un;
391 int fd = ::socket (AF_UNIX, SOCK_STREAM, 0);
392 if (fd == kInvalidSocketValue)
394 error.SetErrorToErrno();
398 final_socket.reset(new Socket(fd, ProtocolUnixDomain, true));
400 saddr_un.sun_family = AF_UNIX;
401 ::strncpy(saddr_un.sun_path, name.data(), sizeof(saddr_un.sun_path) - 1);
402 saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
403 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
404 saddr_un.sun_len = SUN_LEN (&saddr_un);
407 if (::connect (fd, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) < 0)
409 error.SetErrorToErrno();
413 socket = final_socket.release();
415 error.SetErrorString("Unix domain sockets are not supported on this platform.");
420 Error Socket::UnixDomainAccept(llvm::StringRef name, Socket *&socket)
423 #ifndef LLDB_DISABLE_POSIX
424 struct sockaddr_un saddr_un;
425 std::unique_ptr<Socket> listen_socket;
426 std::unique_ptr<Socket> final_socket;
427 NativeSocket listen_fd = kInvalidSocketValue;
428 NativeSocket socket_fd = kInvalidSocketValue;
430 listen_fd = ::socket (AF_UNIX, SOCK_STREAM, 0);
431 if (listen_fd == kInvalidSocketValue)
433 error.SetErrorToErrno();
437 listen_socket.reset(new Socket(listen_fd, ProtocolUnixDomain, true));
439 saddr_un.sun_family = AF_UNIX;
440 ::strncpy(saddr_un.sun_path, name.data(), sizeof(saddr_un.sun_path) - 1);
441 saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
442 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
443 saddr_un.sun_len = SUN_LEN (&saddr_un);
446 FileSystem::Unlink(name.data());
447 bool success = false;
448 if (::bind (listen_fd, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) == 0)
450 if (::listen (listen_fd, 5) == 0)
452 socket_fd = ::accept (listen_fd, NULL, 0);
455 final_socket.reset(new Socket(socket_fd, ProtocolUnixDomain, true));
463 error.SetErrorToErrno();
466 // We are done with the listen port
467 listen_socket.reset();
469 socket = final_socket.release();
471 error.SetErrorString("Unix domain sockets are not supported on this platform.");
477 Socket::DecodeHostAndPort(llvm::StringRef host_and_port,
478 std::string &host_str,
479 std::string &port_str,
483 static RegularExpression g_regex ("([^:]+):([0-9]+)");
484 RegularExpression::Match regex_match(2);
485 if (g_regex.Execute (host_and_port.data(), ®ex_match))
487 if (regex_match.GetMatchAtIndex (host_and_port.data(), 1, host_str) &&
488 regex_match.GetMatchAtIndex (host_and_port.data(), 2, port_str))
490 port = Args::StringToSInt32 (port_str.c_str(), INT32_MIN);
491 if (port != INT32_MIN)
500 // If this was unsuccessful, then check if it's simply a signed 32-bit integer, representing
501 // a port with an empty host.
504 port = Args::StringToSInt32(host_and_port.data(), INT32_MIN);
505 if (port != INT32_MIN)
507 port_str = host_and_port;
512 error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port.data());
516 IOObject::WaitableHandle Socket::GetWaitableHandle()
518 // TODO: On Windows, use WSAEventSelect
522 Error Socket::Read (void *buf, size_t &num_bytes)
525 int bytes_received = 0;
528 bytes_received = ::recv (m_socket, static_cast<char *>(buf), num_bytes, 0);
529 // TODO: Use WSAGetLastError on windows.
530 } while (bytes_received < 0 && errno == EINTR);
532 if (bytes_received < 0)
534 error.SetErrorToErrno();
538 num_bytes = bytes_received;
540 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_COMMUNICATION));
543 log->Printf ("%p Socket::Read() (socket = %" PRIu64 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
544 static_cast<void*>(this),
545 static_cast<uint64_t>(m_socket),
547 static_cast<uint64_t>(num_bytes),
548 static_cast<int64_t>(bytes_received),
555 Error Socket::Write (const void *buf, size_t &num_bytes)
561 if (m_protocol == ProtocolUdp)
563 bytes_sent = ::sendto (m_socket,
564 static_cast<const char*>(buf),
568 m_udp_send_sockaddr.GetLength());
571 bytes_sent = ::send (m_socket, static_cast<const char *>(buf), num_bytes, 0);
572 // TODO: Use WSAGetLastError on windows.
573 } while (bytes_sent < 0 && errno == EINTR);
577 // TODO: On Windows, use WSAGEtLastError.
578 error.SetErrorToErrno();
582 num_bytes = bytes_sent;
584 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_HOST));
587 log->Printf ("%p Socket::Write() (socket = %" PRIu64 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
588 static_cast<void*>(this),
589 static_cast<uint64_t>(m_socket),
591 static_cast<uint64_t>(num_bytes),
592 static_cast<int64_t>(bytes_sent),
599 Error Socket::PreDisconnect()
605 Error Socket::Close()
608 if (!IsValid() || !m_should_close_fd)
611 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
613 log->Printf ("%p Socket::Close (fd = %i)", static_cast<void*>(this), m_socket);
616 bool success = !!closesocket(m_socket);
618 bool success = !!::close (m_socket);
620 // A reference to a FD was passed in, set it to an invalid value
621 m_socket = kInvalidSocketValue;
624 // TODO: On Windows, use WSAGetLastError().
625 error.SetErrorToErrno();
632 int Socket::GetOption(int level, int option_name, int &option_value)
634 get_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
635 socklen_t option_value_size = sizeof(int);
636 return ::getsockopt(m_socket, level, option_name, option_value_p, &option_value_size);
639 int Socket::SetOption(int level, int option_name, int option_value)
641 set_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
642 return ::setsockopt(m_socket, level, option_name, option_value_p, sizeof(option_value));
645 uint16_t Socket::GetPortNumber(const NativeSocket& socket)
647 // We bound to port zero, so we need to figure out which port we actually bound to
650 SocketAddress sock_addr;
651 socklen_t sock_addr_len = sock_addr.GetMaxLength ();
652 if (::getsockname (socket, sock_addr, &sock_addr_len) == 0)
653 return sock_addr.GetPort ();
658 // Return the port number that is being used by the socket.
659 uint16_t Socket::GetPortNumber() const
661 return GetPortNumber(m_socket);