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"
17 #include <arpa/inet.h>
21 #include <netinet/in.h>
22 #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. */
33 bool ResolveIPV4HostName(const char *hostname, in_addr_t &addr) {
34 if (hostname == NULL || hostname[0] == '\0' ||
35 strcmp(hostname, "localhost") == 0 ||
36 strcmp(hostname, "127.0.0.1") == 0) {
37 addr = htonl(INADDR_LOOPBACK);
39 } else if (strcmp(hostname, "*") == 0) {
40 addr = htonl(INADDR_ANY);
43 // See if an IP address was specified as numbers
44 int inet_pton_result = ::inet_pton(AF_INET, hostname, &addr);
46 if (inet_pton_result == 1)
49 struct hostent *host_entry = gethostbyname(hostname);
52 ::inet_ntoa(*(struct in_addr *)*host_entry->h_addr_list));
53 inet_pton_result = ::inet_pton(AF_INET, ip_str.c_str(), &addr);
54 if (inet_pton_result == 1)
61 rnb_err_t RNBSocket::Listen(const char *listen_host, uint16_t port,
62 PortBoundCallback callback,
63 const void *callback_baton) {
64 // DNBLogThreadedIf(LOG_RNB_COMM, "%8u RNBSocket::%s called",
65 // (uint32_t)m_timer.ElapsedMicroSeconds(true), __FUNCTION__);
66 // Disconnect without saving errno
69 // Now figure out the hostname that will be attaching and palce it into
70 struct sockaddr_in listen_addr;
71 ::memset(&listen_addr, 0, sizeof listen_addr);
72 listen_addr.sin_len = sizeof listen_addr;
73 listen_addr.sin_family = AF_INET;
74 listen_addr.sin_port = htons(port);
75 listen_addr.sin_addr.s_addr = INADDR_ANY;
77 if (!ResolveIPV4HostName(listen_host, listen_addr.sin_addr.s_addr)) {
78 DNBLogThreaded("error: failed to resolve connecting host '%s'",
84 int listen_fd = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
86 err.SetError(errno, DNBError::POSIX);
88 if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM))
89 err.LogThreaded("::socket ( domain = AF_INET, type = SOCK_STREAM, protocol "
90 "= IPPROTO_TCP ) => socket = %i",
96 // enable local address reuse
97 SetSocketOption(listen_fd, SOL_SOCKET, SO_REUSEADDR, 1);
99 struct sockaddr_in sa;
100 ::memset(&sa, 0, sizeof sa);
101 sa.sin_len = sizeof sa;
102 sa.sin_family = AF_INET;
103 sa.sin_port = htons(port);
104 sa.sin_addr.s_addr = INADDR_ANY; // Let incoming connections bind to any host
105 // network interface (this is NOT who can
107 int error = ::bind(listen_fd, (struct sockaddr *)&sa, sizeof(sa));
109 err.SetError(errno, DNBError::POSIX);
111 if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM))
113 "::bind ( socket = %i, (struct sockaddr *) &sa, sizeof(sa)) )",
117 ClosePort(listen_fd, false);
121 error = ::listen(listen_fd, 5);
123 err.SetError(errno, DNBError::POSIX);
125 if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM))
126 err.LogThreaded("::listen ( socket = %i, backlog = 1 )", listen_fd);
129 ClosePort(listen_fd, false);
134 // We were asked to listen on port zero which means we
135 // must now read the actual port that was given to us
136 // as port zero is a special code for "find an open port
139 socklen_t sa_len = sizeof(sa);
140 if (getsockname(listen_fd, (struct sockaddr *)&sa, &sa_len) == 0) {
141 port = ntohs(sa.sin_port);
142 callback(callback_baton, port);
145 callback(callback_baton, port);
149 struct sockaddr_in accept_addr;
150 ::memset(&accept_addr, 0, sizeof accept_addr);
151 accept_addr.sin_len = sizeof accept_addr;
153 bool accept_connection = false;
155 // Loop until we are happy with our connection
156 while (!accept_connection) {
157 socklen_t accept_addr_len = sizeof accept_addr;
159 ::accept(listen_fd, (struct sockaddr *)&accept_addr, &accept_addr_len);
162 err.SetError(errno, DNBError::POSIX);
164 if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM))
166 "::accept ( socket = %i, address = %p, address_len = %u )", listen_fd,
167 &accept_addr, accept_addr_len);
172 if (listen_addr.sin_addr.s_addr == INADDR_ANY)
173 accept_connection = true;
175 if (accept_addr_len == listen_addr.sin_len &&
176 accept_addr.sin_addr.s_addr == listen_addr.sin_addr.s_addr) {
177 accept_connection = true;
181 const uint8_t *accept_ip =
182 (const uint8_t *)&accept_addr.sin_addr.s_addr;
183 const uint8_t *listen_ip =
184 (const uint8_t *)&listen_addr.sin_addr.s_addr;
185 ::fprintf(stderr, "error: rejecting incoming connection from "
186 "%u.%u.%u.%u (expecting %u.%u.%u.%u)\n",
187 accept_ip[0], accept_ip[1], accept_ip[2], accept_ip[3],
188 listen_ip[0], listen_ip[1], listen_ip[2], listen_ip[3]);
189 DNBLogThreaded("error: rejecting connection from %u.%u.%u.%u "
190 "(expecting %u.%u.%u.%u)",
191 accept_ip[0], accept_ip[1], accept_ip[2], accept_ip[3],
192 listen_ip[0], listen_ip[1], listen_ip[2], listen_ip[3]);
197 ClosePort(listen_fd, false);
202 // Keep our TCP packets coming without any delays.
203 SetSocketOption(m_fd, IPPROTO_TCP, TCP_NODELAY, 1);
209 rnb_err_t RNBSocket::Connect(const char *host, uint16_t port) {
213 m_fd = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
217 // Enable local address reuse
218 SetSocketOption(m_fd, SOL_SOCKET, SO_REUSEADDR, 1);
220 struct sockaddr_in sa;
221 ::memset(&sa, 0, sizeof(sa));
222 sa.sin_family = AF_INET;
223 sa.sin_port = htons(port);
225 if (!ResolveIPV4HostName(host, sa.sin_addr.s_addr)) {
226 DNBLogThreaded("error: failed to resolve host '%s'", host);
231 if (-1 == ::connect(m_fd, (const struct sockaddr *)&sa, sizeof(sa))) {
236 // Keep our TCP packets coming without any delays.
237 SetSocketOption(m_fd, IPPROTO_TCP, TCP_NODELAY, 1);
241 rnb_err_t RNBSocket::useFD(int fd) {
243 DNBLogThreadedIf(LOG_RNB_COMM, "Bad file descriptor passed in.");
252 rnb_err_t RNBSocket::ConnectToService() {
253 DNBLog("Connecting to com.apple.%s service...", DEBUGSERVER_PROGRAM_NAME);
254 // Disconnect from any previous connections
256 if (::secure_lockdown_checkin(&m_ld_conn, NULL, NULL) != kLDESuccess) {
257 DNBLogThreadedIf(LOG_RNB_COMM,
258 "::secure_lockdown_checkin(&m_fd, NULL, NULL) failed");
260 return rnb_not_connected;
262 m_fd = ::lockdown_get_socket(m_ld_conn);
264 DNBLogThreadedIf(LOG_RNB_COMM, "::lockdown_get_socket() failed");
265 return rnb_not_connected;
267 m_fd_from_lockdown = true;
272 rnb_err_t RNBSocket::OpenFile(const char *path) {
274 m_fd = open(path, O_RDWR);
276 err.SetError(errno, DNBError::POSIX);
277 err.LogThreaded("can't open file '%s'", path);
278 return rnb_not_connected;
280 struct termios stdin_termios;
282 if (::tcgetattr(m_fd, &stdin_termios) == 0) {
283 stdin_termios.c_lflag &= ~ECHO; // Turn off echoing
284 stdin_termios.c_lflag &= ~ICANON; // Get one char at a time
285 ::tcsetattr(m_fd, TCSANOW, &stdin_termios);
291 int RNBSocket::SetSocketOption(int fd, int level, int option_name,
293 return ::setsockopt(fd, level, option_name, &option_value,
294 sizeof(option_value));
297 rnb_err_t RNBSocket::Disconnect(bool save_errno) {
299 if (m_fd_from_lockdown) {
300 m_fd_from_lockdown = false;
302 lockdown_disconnect(m_ld_conn);
306 return ClosePort(m_fd, save_errno);
309 rnb_err_t RNBSocket::Read(std::string &p) {
313 // Note that BUF is on the stack so we must be careful to keep any
314 // writes to BUF from overflowing or we'll have security issues.
319 // DNBLogThreadedIf(LOG_RNB_COMM, "%8u RNBSocket::%s calling read()",
320 // (uint32_t)m_timer.ElapsedMicroSeconds(true), __FUNCTION__);
322 ssize_t bytesread = read(m_fd, buf, sizeof(buf));
324 err.SetError(errno, DNBError::POSIX);
326 p.append(buf, bytesread);
328 if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM))
329 err.LogThreaded("::read ( %i, %p, %llu ) => %i", m_fd, buf, sizeof(buf),
330 (uint64_t)bytesread);
332 // Our port went away - we have to mark this so IsConnected will return the
334 if (bytesread == 0) {
336 return rnb_not_connected;
337 } else if (bytesread == -1) {
341 // Strip spaces from the end of the buffer
342 while (!p.empty() && isspace(p[p.size() - 1]))
343 p.erase(p.size() - 1);
345 // Most data in the debugserver packets valid printable characters...
346 DNBLogThreadedIf(LOG_RNB_COMM, "read: %s", p.c_str());
350 rnb_err_t RNBSocket::Write(const void *buffer, size_t length) {
355 ssize_t bytessent = write(m_fd, buffer, length);
357 err.SetError(errno, DNBError::POSIX);
359 if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM))
360 err.LogThreaded("::write ( socket = %i, buffer = %p, length = %llu) => %i",
361 m_fd, buffer, length, (uint64_t)bytessent);
366 if ((size_t)bytessent != length)
370 LOG_RNB_PACKETS, "putpkt: %*s", (int)length,
372 buffer); // All data is string based in debugserver, so this is safe
373 DNBLogThreadedIf(LOG_RNB_COMM, "sent: %*s", (int)length, (char *)buffer);
378 rnb_err_t RNBSocket::ClosePort(int &fd, bool save_errno) {
382 close_err = close(fd);
385 return close_err != 0 ? rnb_err : rnb_success;