1 //===-- TcpSocket.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/common/TCPSocket.h"
12 #include "lldb/Core/Log.h"
13 #include "lldb/Host/Config.h"
15 #ifndef LLDB_DISABLE_POSIX
16 #include <arpa/inet.h>
17 #include <netinet/tcp.h>
18 #include <sys/socket.h>
22 using namespace lldb_private;
26 const int kDomain = AF_INET;
27 const int kType = SOCK_STREAM;
31 TCPSocket::TCPSocket(NativeSocket socket, bool should_close)
32 : Socket(socket, ProtocolTcp, should_close)
37 TCPSocket::TCPSocket(bool child_processes_inherit, Error &error)
38 : TCPSocket(CreateSocket(kDomain, kType, IPPROTO_TCP, child_processes_inherit, error), true)
43 // Return the port number that is being used by the socket.
45 TCPSocket::GetLocalPortNumber() const
47 if (m_socket != kInvalidSocketValue)
49 SocketAddress sock_addr;
50 socklen_t sock_addr_len = sock_addr.GetMaxLength ();
51 if (::getsockname (m_socket, sock_addr, &sock_addr_len) == 0)
52 return sock_addr.GetPort ();
58 TCPSocket::GetLocalIPAddress() const
60 // We bound to port zero, so we need to figure out which port we actually bound to
61 if (m_socket != kInvalidSocketValue)
63 SocketAddress sock_addr;
64 socklen_t sock_addr_len = sock_addr.GetMaxLength ();
65 if (::getsockname (m_socket, sock_addr, &sock_addr_len) == 0)
66 return sock_addr.GetIPAddress ();
72 TCPSocket::GetRemotePortNumber() const
74 if (m_socket != kInvalidSocketValue)
76 SocketAddress sock_addr;
77 socklen_t sock_addr_len = sock_addr.GetMaxLength ();
78 if (::getpeername (m_socket, sock_addr, &sock_addr_len) == 0)
79 return sock_addr.GetPort ();
85 TCPSocket::GetRemoteIPAddress () const
87 // We bound to port zero, so we need to figure out which port we actually bound to
88 if (m_socket != kInvalidSocketValue)
90 SocketAddress sock_addr;
91 socklen_t sock_addr_len = sock_addr.GetMaxLength ();
92 if (::getpeername (m_socket, sock_addr, &sock_addr_len) == 0)
93 return sock_addr.GetIPAddress ();
99 TCPSocket::Connect(llvm::StringRef name)
101 if (m_socket == kInvalidSocketValue)
102 return Error("Invalid socket");
104 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION));
106 log->Printf ("TCPSocket::%s (host/port = %s)", __FUNCTION__, name.data());
109 std::string host_str;
110 std::string port_str;
111 int32_t port = INT32_MIN;
112 if (!DecodeHostAndPort (name, host_str, port_str, port, &error))
115 struct sockaddr_in sa;
116 ::memset (&sa, 0, sizeof (sa));
117 sa.sin_family = kDomain;
118 sa.sin_port = htons (port);
120 int inet_pton_result = ::inet_pton (kDomain, host_str.c_str(), &sa.sin_addr);
122 if (inet_pton_result <= 0)
124 struct hostent *host_entry = gethostbyname (host_str.c_str());
126 host_str = ::inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
127 inet_pton_result = ::inet_pton (kDomain, host_str.c_str(), &sa.sin_addr);
128 if (inet_pton_result <= 0)
130 if (inet_pton_result == -1)
133 error.SetErrorStringWithFormat("invalid host string: '%s'", host_str.c_str());
139 if (-1 == ::connect (GetNativeSocket(), (const struct sockaddr *)&sa, sizeof(sa)))
141 SetLastError (error);
145 // Keep our TCP packets coming without any delays.
152 TCPSocket::Listen(llvm::StringRef name, int backlog)
156 // enable local address reuse
157 SetOptionReuseAddress();
159 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
161 log->Printf ("TCPSocket::%s (%s)", __FUNCTION__, name.data());
163 std::string host_str;
164 std::string port_str;
165 int32_t port = INT32_MIN;
166 if (!DecodeHostAndPort (name, host_str, port_str, port, &error))
169 SocketAddress bind_addr;
171 // Only bind to the loopback address if we are expecting a connection from
172 // localhost to avoid any firewall issues.
173 const bool bind_addr_success = (host_str == "127.0.0.1") ?
174 bind_addr.SetToLocalhost (kDomain, port) :
175 bind_addr.SetToAnyAddress (kDomain, port);
177 if (!bind_addr_success)
179 error.SetErrorString("Failed to bind port");
183 int err = ::bind (GetNativeSocket(), bind_addr, bind_addr.GetLength());
185 err = ::listen (GetNativeSocket(), backlog);
188 SetLastError (error);
194 TCPSocket::Accept(llvm::StringRef name, bool child_processes_inherit, Socket *&conn_socket)
197 std::string host_str;
198 std::string port_str;
200 if (!DecodeHostAndPort(name, host_str, port_str, port, &error))
203 const sa_family_t family = kDomain;
204 const int socktype = kType;
205 const int protocol = IPPROTO_TCP;
206 SocketAddress listen_addr;
207 if (host_str.empty())
208 listen_addr.SetToLocalhost(family, port);
209 else if (host_str.compare("*") == 0)
210 listen_addr.SetToAnyAddress(family, port);
213 if (!listen_addr.getaddrinfo(host_str.c_str(), port_str.c_str(), family, socktype, protocol))
215 error.SetErrorStringWithFormat("unable to resolve hostname '%s'", host_str.c_str());
220 bool accept_connection = false;
221 std::unique_ptr<TCPSocket> accepted_socket;
223 // Loop until we are happy with our connection
224 while (!accept_connection)
226 struct sockaddr_in accept_addr;
227 ::memset (&accept_addr, 0, sizeof accept_addr);
228 #if !(defined (__linux__) || defined(_WIN32))
229 accept_addr.sin_len = sizeof accept_addr;
231 socklen_t accept_addr_len = sizeof accept_addr;
233 int sock = AcceptSocket (GetNativeSocket(),
234 (struct sockaddr *)&accept_addr,
236 child_processes_inherit,
242 bool is_same_addr = true;
243 #if !(defined(__linux__) || (defined(_WIN32)))
244 is_same_addr = (accept_addr_len == listen_addr.sockaddr_in().sin_len);
247 is_same_addr = (accept_addr.sin_addr.s_addr == listen_addr.sockaddr_in().sin_addr.s_addr);
249 if (is_same_addr || (listen_addr.sockaddr_in().sin_addr.s_addr == INADDR_ANY))
251 accept_connection = true;
252 accepted_socket.reset(new TCPSocket(sock, true));
256 const uint8_t *accept_ip = (const uint8_t *)&accept_addr.sin_addr.s_addr;
257 const uint8_t *listen_ip = (const uint8_t *)&listen_addr.sockaddr_in().sin_addr.s_addr;
258 ::fprintf (stderr, "error: rejecting incoming connection from %u.%u.%u.%u (expecting %u.%u.%u.%u)\n",
259 accept_ip[0], accept_ip[1], accept_ip[2], accept_ip[3],
260 listen_ip[0], listen_ip[1], listen_ip[2], listen_ip[3]);
261 accepted_socket.reset();
265 if (!accepted_socket)
268 // Keep our TCP packets coming without any delays.
269 accepted_socket->SetOptionNoDelay();
271 conn_socket = accepted_socket.release();
276 TCPSocket::SetOptionNoDelay()
278 return SetOption (IPPROTO_TCP, TCP_NODELAY, 1);
282 TCPSocket::SetOptionReuseAddress()
284 return SetOption(SOL_SOCKET, SO_REUSEADDR, 1);