1 //===-- RNBSocket.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 // Created by Greg Clayton on 12/12/07.
12 //===----------------------------------------------------------------------===//
14 #include "RNBSocket.h"
15 #include <arpa/inet.h>
19 #include <netinet/in.h>
20 #include <netinet/tcp.h>
29 /* Once we have a RNBSocket object with a port # specified,
30 this function is called to wait for an incoming connection.
31 This function blocks while waiting for that connection. */
34 ResolveIPV4HostName (const char *hostname, in_addr_t &addr)
36 if (hostname == NULL ||
37 hostname[0] == '\0' ||
38 strcmp(hostname, "localhost") == 0 ||
39 strcmp(hostname, "127.0.0.1") == 0)
41 addr = htonl (INADDR_LOOPBACK);
44 else if (strcmp(hostname, "*") == 0)
46 addr = htonl (INADDR_ANY);
51 // See if an IP address was specified as numbers
52 int inet_pton_result = ::inet_pton (AF_INET, hostname, &addr);
54 if (inet_pton_result == 1)
57 struct hostent *host_entry = gethostbyname (hostname);
60 std::string ip_str (::inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list));
61 inet_pton_result = ::inet_pton (AF_INET, ip_str.c_str(), &addr);
62 if (inet_pton_result == 1)
70 RNBSocket::Listen (const char *listen_host, uint16_t port, PortBoundCallback callback, const void *callback_baton)
72 //DNBLogThreadedIf(LOG_RNB_COMM, "%8u RNBSocket::%s called", (uint32_t)m_timer.ElapsedMicroSeconds(true), __FUNCTION__);
73 // Disconnect without saving errno
76 // Now figure out the hostname that will be attaching and palce it into
77 struct sockaddr_in listen_addr;
78 ::memset (&listen_addr, 0, sizeof listen_addr);
79 listen_addr.sin_len = sizeof listen_addr;
80 listen_addr.sin_family = AF_INET;
81 listen_addr.sin_port = htons (port);
82 listen_addr.sin_addr.s_addr = INADDR_ANY;
84 if (!ResolveIPV4HostName(listen_host, listen_addr.sin_addr.s_addr))
86 DNBLogThreaded("error: failed to resolve connecting host '%s'", listen_host);
91 int listen_fd = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
93 err.SetError(errno, DNBError::POSIX);
95 if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM))
96 err.LogThreaded("::socket ( domain = AF_INET, type = SOCK_STREAM, protocol = IPPROTO_TCP ) => socket = %i", listen_fd);
101 // enable local address reuse
102 SetSocketOption (listen_fd, SOL_SOCKET, SO_REUSEADDR, 1);
104 struct sockaddr_in sa;
105 ::memset (&sa, 0, sizeof sa);
106 sa.sin_len = sizeof sa;
107 sa.sin_family = AF_INET;
108 sa.sin_port = htons (port);
109 sa.sin_addr.s_addr = INADDR_ANY; // Let incoming connections bind to any host network interface (this is NOT who can connect to us)
110 int error = ::bind (listen_fd, (struct sockaddr *) &sa, sizeof(sa));
112 err.SetError(errno, DNBError::POSIX);
114 if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM))
115 err.LogThreaded("::bind ( socket = %i, (struct sockaddr *) &sa, sizeof(sa)) )", listen_fd);
119 ClosePort (listen_fd, false);
123 error = ::listen (listen_fd, 5);
125 err.SetError(errno, DNBError::POSIX);
127 if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM))
128 err.LogThreaded("::listen ( socket = %i, backlog = 1 )", listen_fd);
132 ClosePort (listen_fd, false);
138 // We were asked to listen on port zero which means we
139 // must now read the actual port that was given to us
140 // as port zero is a special code for "find an open port
144 socklen_t sa_len = sizeof (sa);
145 if (getsockname(listen_fd, (struct sockaddr *)&sa, &sa_len) == 0)
147 port = ntohs (sa.sin_port);
148 callback (callback_baton, port);
153 callback (callback_baton, port);
157 struct sockaddr_in accept_addr;
158 ::memset (&accept_addr, 0, sizeof accept_addr);
159 accept_addr.sin_len = sizeof accept_addr;
161 bool accept_connection = false;
163 // Loop until we are happy with our connection
164 while (!accept_connection)
166 socklen_t accept_addr_len = sizeof accept_addr;
167 m_fd = ::accept (listen_fd, (struct sockaddr *)&accept_addr, &accept_addr_len);
170 err.SetError(errno, DNBError::POSIX);
172 if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM))
173 err.LogThreaded("::accept ( socket = %i, address = %p, address_len = %u )", listen_fd, &accept_addr, accept_addr_len);
178 if (listen_addr.sin_addr.s_addr == INADDR_ANY)
179 accept_connection = true;
182 if (accept_addr_len == listen_addr.sin_len &&
183 accept_addr.sin_addr.s_addr == listen_addr.sin_addr.s_addr)
185 accept_connection = true;
191 const uint8_t *accept_ip = (const uint8_t *)&accept_addr.sin_addr.s_addr;
192 const uint8_t *listen_ip = (const uint8_t *)&listen_addr.sin_addr.s_addr;
194 "error: rejecting incoming connection from %u.%u.%u.%u (expecting %u.%u.%u.%u)\n",
195 accept_ip[0], accept_ip[1], accept_ip[2], accept_ip[3],
196 listen_ip[0], listen_ip[1], listen_ip[2], listen_ip[3]);
197 DNBLogThreaded ("error: rejecting connection from %u.%u.%u.%u (expecting %u.%u.%u.%u)",
198 accept_ip[0], accept_ip[1], accept_ip[2], accept_ip[3],
199 listen_ip[0], listen_ip[1], listen_ip[2], listen_ip[3]);
204 ClosePort (listen_fd, false);
212 // Keep our TCP packets coming without any delays.
213 SetSocketOption (m_fd, IPPROTO_TCP, TCP_NODELAY, 1);
220 RNBSocket::Connect (const char *host, uint16_t port)
225 m_fd = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
229 // Enable local address reuse
230 SetSocketOption (m_fd, SOL_SOCKET, SO_REUSEADDR, 1);
232 struct sockaddr_in sa;
233 ::memset (&sa, 0, sizeof (sa));
234 sa.sin_family = AF_INET;
235 sa.sin_port = htons (port);
237 if (!ResolveIPV4HostName(host, sa.sin_addr.s_addr))
239 DNBLogThreaded("error: failed to resolve host '%s'", host);
244 if (-1 == ::connect (m_fd, (const struct sockaddr *)&sa, sizeof(sa)))
250 // Keep our TCP packets coming without any delays.
251 SetSocketOption (m_fd, IPPROTO_TCP, TCP_NODELAY, 1);
256 RNBSocket::useFD(int fd)
259 DNBLogThreadedIf(LOG_RNB_COMM, "Bad file descriptor passed in.");
269 RNBSocket::ConnectToService()
271 DNBLog("Connecting to com.apple.%s service...", DEBUGSERVER_PROGRAM_NAME);
272 // Disconnect from any previous connections
274 if (::secure_lockdown_checkin (&m_ld_conn, NULL, NULL) != kLDESuccess)
276 DNBLogThreadedIf(LOG_RNB_COMM, "::secure_lockdown_checkin(&m_fd, NULL, NULL) failed");
278 return rnb_not_connected;
280 m_fd = ::lockdown_get_socket (m_ld_conn);
283 DNBLogThreadedIf(LOG_RNB_COMM, "::lockdown_get_socket() failed");
284 return rnb_not_connected;
286 m_fd_from_lockdown = true;
292 RNBSocket::OpenFile (const char *path)
295 m_fd = open (path, O_RDWR);
298 err.SetError(errno, DNBError::POSIX);
299 err.LogThreaded ("can't open file '%s'", path);
300 return rnb_not_connected;
304 struct termios stdin_termios;
306 if (::tcgetattr (m_fd, &stdin_termios) == 0)
308 stdin_termios.c_lflag &= ~ECHO; // Turn off echoing
309 stdin_termios.c_lflag &= ~ICANON; // Get one char at a time
310 ::tcsetattr (m_fd, TCSANOW, &stdin_termios);
317 RNBSocket::SetSocketOption(int fd, int level, int option_name, int option_value)
319 return ::setsockopt(fd, level, option_name, &option_value, sizeof(option_value));
323 RNBSocket::Disconnect (bool save_errno)
326 if (m_fd_from_lockdown)
328 m_fd_from_lockdown = false;
330 lockdown_disconnect (m_ld_conn);
334 return ClosePort (m_fd, save_errno);
339 RNBSocket::Read (std::string &p)
344 // Note that BUF is on the stack so we must be careful to keep any
345 // writes to BUF from overflowing or we'll have security issues.
350 //DNBLogThreadedIf(LOG_RNB_COMM, "%8u RNBSocket::%s calling read()", (uint32_t)m_timer.ElapsedMicroSeconds(true), __FUNCTION__);
352 ssize_t bytesread = read (m_fd, buf, sizeof (buf));
354 err.SetError(errno, DNBError::POSIX);
356 p.append(buf, bytesread);
358 if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM))
359 err.LogThreaded("::read ( %i, %p, %llu ) => %i", m_fd, buf, sizeof (buf), (uint64_t)bytesread);
361 // Our port went away - we have to mark this so IsConnected will return the truth.
365 return rnb_not_connected;
367 else if (bytesread == -1)
372 // Strip spaces from the end of the buffer
373 while (!p.empty() && isspace (p[p.size() - 1]))
374 p.erase (p.size () - 1);
376 // Most data in the debugserver packets valid printable characters...
377 DNBLogThreadedIf(LOG_RNB_COMM, "read: %s", p.c_str());
382 RNBSocket::Write (const void *buffer, size_t length)
388 ssize_t bytessent = write (m_fd, buffer, length);
390 err.SetError(errno, DNBError::POSIX);
392 if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM))
393 err.LogThreaded("::write ( socket = %i, buffer = %p, length = %llu) => %i", m_fd, buffer, length, (uint64_t)bytessent);
398 if ((size_t)bytessent != length)
401 DNBLogThreadedIf(LOG_RNB_PACKETS, "putpkt: %*s", (int)length, (char *)buffer); // All data is string based in debugserver, so this is safe
402 DNBLogThreadedIf(LOG_RNB_COMM, "sent: %*s", (int)length, (char *)buffer);
409 RNBSocket::ClosePort (int& fd, bool save_errno)
415 close_err = close (fd);
418 return close_err != 0 ? rnb_err : rnb_success;