1 //===-- RNBSocket.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 // Created by Greg Clayton on 12/12/07. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "RNBSocket.h" 15 #include <arpa/inet.h> 16 #include <errno.h> 17 #include <fcntl.h> 18 #include <netdb.h> 19 #include <netinet/in.h> 20 #include <netinet/tcp.h> 21 #include <termios.h> 22 #include "DNBLog.h" 23 #include "DNBError.h" 24 25 #ifdef WITH_LOCKDOWN 26 #include "lockdown.h" 27 #endif 28 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. */ 32 33 bool 34 ResolveIPV4HostName (const char *hostname, in_addr_t &addr) 35 { 36 if (hostname == NULL || 37 hostname[0] == '\0' || 38 strcmp(hostname, "localhost") == 0 || 39 strcmp(hostname, "127.0.0.1") == 0) 40 { 41 addr = htonl (INADDR_LOOPBACK); 42 return true; 43 } 44 else if (strcmp(hostname, "*") == 0) 45 { 46 addr = htonl (INADDR_ANY); 47 return true; 48 } 49 else 50 { 51 // See if an IP address was specified as numbers 52 int inet_pton_result = ::inet_pton (AF_INET, hostname, &addr); 53 54 if (inet_pton_result == 1) 55 return true; 56 57 struct hostent *host_entry = gethostbyname (hostname); 58 if (host_entry) 59 { 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) 63 return true; 64 } 65 } 66 return false; 67 } 68 69 rnb_err_t 70 RNBSocket::Listen (const char *listen_host, in_port_t port, PortBoundCallback callback, const void *callback_baton) 71 { 72 //DNBLogThreadedIf(LOG_RNB_COMM, "%8u RNBSocket::%s called", (uint32_t)m_timer.ElapsedMicroSeconds(true), __FUNCTION__); 73 // Disconnect without saving errno 74 Disconnect (false); 75 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; 83 84 if (!ResolveIPV4HostName(listen_host, listen_addr.sin_addr.s_addr)) 85 { 86 DNBLogThreaded("error: failed to resolve connecting host '%s'", listen_host); 87 return rnb_err; 88 } 89 90 DNBError err; 91 int listen_fd = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); 92 if (listen_fd == -1) 93 err.SetError(errno, DNBError::POSIX); 94 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); 97 98 if (err.Fail()) 99 return rnb_err; 100 101 // enable local address reuse 102 SetSocketOption (listen_fd, SOL_SOCKET, SO_REUSEADDR, 1); 103 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)); 111 if (error == -1) 112 err.SetError(errno, DNBError::POSIX); 113 114 if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM)) 115 err.LogThreaded("::bind ( socket = %i, (struct sockaddr *) &sa, sizeof(sa)) )", listen_fd); 116 117 if (err.Fail()) 118 { 119 ClosePort (listen_fd, false); 120 return rnb_err; 121 } 122 123 error = ::listen (listen_fd, 5); 124 if (error == -1) 125 err.SetError(errno, DNBError::POSIX); 126 127 if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM)) 128 err.LogThreaded("::listen ( socket = %i, backlog = 1 )", listen_fd); 129 130 if (err.Fail()) 131 { 132 ClosePort (listen_fd, false); 133 return rnb_err; 134 } 135 136 if (callback) 137 { 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 141 // for me". 142 if (port == 0) 143 { 144 socklen_t sa_len = sizeof (sa); 145 if (getsockname(listen_fd, (struct sockaddr *)&sa, &sa_len) == 0) 146 { 147 port = ntohs (sa.sin_port); 148 callback (callback_baton, port); 149 } 150 } 151 else 152 { 153 callback (callback_baton, port); 154 } 155 } 156 157 struct sockaddr_in accept_addr; 158 ::memset (&accept_addr, 0, sizeof accept_addr); 159 accept_addr.sin_len = sizeof accept_addr; 160 161 bool accept_connection = false; 162 163 // Loop until we are happy with our connection 164 while (!accept_connection) 165 { 166 socklen_t accept_addr_len = sizeof accept_addr; 167 m_fd = ::accept (listen_fd, (struct sockaddr *)&accept_addr, &accept_addr_len); 168 169 if (m_fd == -1) 170 err.SetError(errno, DNBError::POSIX); 171 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); 174 175 if (err.Fail()) 176 break; 177 178 if (listen_addr.sin_addr.s_addr == INADDR_ANY) 179 accept_connection = true; 180 else 181 { 182 if (accept_addr_len == listen_addr.sin_len && 183 accept_addr.sin_addr.s_addr == listen_addr.sin_addr.s_addr) 184 { 185 accept_connection = true; 186 } 187 else 188 { 189 ::close (m_fd); 190 m_fd = -1; 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; 193 ::fprintf (stderr, 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]); 200 } 201 } 202 } 203 204 ClosePort (listen_fd, false); 205 206 if (err.Fail()) 207 { 208 return rnb_err; 209 } 210 else 211 { 212 // Keep our TCP packets coming without any delays. 213 SetSocketOption (m_fd, IPPROTO_TCP, TCP_NODELAY, 1); 214 } 215 216 return rnb_success; 217 } 218 219 rnb_err_t 220 RNBSocket::Connect (const char *host, uint16_t port) 221 { 222 Disconnect (false); 223 224 // Create the socket 225 m_fd = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); 226 if (m_fd == -1) 227 return rnb_err; 228 229 // Enable local address reuse 230 SetSocketOption (m_fd, SOL_SOCKET, SO_REUSEADDR, 1); 231 232 struct sockaddr_in sa; 233 ::memset (&sa, 0, sizeof (sa)); 234 sa.sin_family = AF_INET; 235 sa.sin_port = htons (port); 236 237 if (!ResolveIPV4HostName(host, sa.sin_addr.s_addr)) 238 { 239 DNBLogThreaded("error: failed to resolve host '%s'", host); 240 Disconnect (false); 241 return rnb_err; 242 } 243 244 if (-1 == ::connect (m_fd, (const struct sockaddr *)&sa, sizeof(sa))) 245 { 246 Disconnect (false); 247 return rnb_err; 248 } 249 250 // Keep our TCP packets coming without any delays. 251 SetSocketOption (m_fd, IPPROTO_TCP, TCP_NODELAY, 1); 252 return rnb_success; 253 } 254 255 rnb_err_t 256 RNBSocket::useFD(int fd) 257 { 258 if (fd < 0) { 259 DNBLogThreadedIf(LOG_RNB_COMM, "Bad file descriptor passed in."); 260 return rnb_err; 261 } 262 263 m_fd = fd; 264 return rnb_success; 265 } 266 267 #ifdef WITH_LOCKDOWN 268 rnb_err_t 269 RNBSocket::ConnectToService() 270 { 271 DNBLog("Connecting to com.apple.%s service...", DEBUGSERVER_PROGRAM_NAME); 272 // Disconnect from any previous connections 273 Disconnect(false); 274 if (::secure_lockdown_checkin (&m_ld_conn, NULL, NULL) != kLDESuccess) 275 { 276 DNBLogThreadedIf(LOG_RNB_COMM, "::secure_lockdown_checkin(&m_fd, NULL, NULL) failed"); 277 m_fd = -1; 278 return rnb_not_connected; 279 } 280 m_fd = ::lockdown_get_socket (m_ld_conn); 281 if (m_fd == -1) 282 { 283 DNBLogThreadedIf(LOG_RNB_COMM, "::lockdown_get_socket() failed"); 284 return rnb_not_connected; 285 } 286 m_fd_from_lockdown = true; 287 return rnb_success; 288 } 289 #endif 290 291 rnb_err_t 292 RNBSocket::OpenFile (const char *path) 293 { 294 DNBError err; 295 m_fd = open (path, O_RDWR); 296 if (m_fd == -1) 297 { 298 err.SetError(errno, DNBError::POSIX); 299 err.LogThreaded ("can't open file '%s'", path); 300 return rnb_not_connected; 301 } 302 else 303 { 304 struct termios stdin_termios; 305 306 if (::tcgetattr (m_fd, &stdin_termios) == 0) 307 { 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); 311 } 312 } 313 return rnb_success; 314 } 315 316 int 317 RNBSocket::SetSocketOption(int fd, int level, int option_name, int option_value) 318 { 319 return ::setsockopt(fd, level, option_name, &option_value, sizeof(option_value)); 320 } 321 322 rnb_err_t 323 RNBSocket::Disconnect (bool save_errno) 324 { 325 #ifdef WITH_LOCKDOWN 326 if (m_fd_from_lockdown) 327 { 328 m_fd_from_lockdown = false; 329 m_fd = -1; 330 lockdown_disconnect (m_ld_conn); 331 return rnb_success; 332 } 333 #endif 334 return ClosePort (m_fd, save_errno); 335 } 336 337 338 rnb_err_t 339 RNBSocket::Read (std::string &p) 340 { 341 char buf[1024]; 342 p.clear(); 343 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. 346 347 if (m_fd == -1) 348 return rnb_err; 349 350 //DNBLogThreadedIf(LOG_RNB_COMM, "%8u RNBSocket::%s calling read()", (uint32_t)m_timer.ElapsedMicroSeconds(true), __FUNCTION__); 351 DNBError err; 352 int bytesread = read (m_fd, buf, sizeof (buf)); 353 if (bytesread <= 0) 354 err.SetError(errno, DNBError::POSIX); 355 else 356 p.append(buf, bytesread); 357 358 if (err.Fail() || DNBLogCheckLogBit(LOG_RNB_COMM)) 359 err.LogThreaded("::read ( %i, %p, %llu ) => %i", m_fd, buf, sizeof (buf), (uint64_t)bytesread); 360 361 // Our port went away - we have to mark this so IsConnected will return the truth. 362 if (bytesread == 0) 363 { 364 m_fd = -1; 365 return rnb_not_connected; 366 } 367 else if (bytesread == -1) 368 { 369 m_fd = -1; 370 return rnb_err; 371 } 372 // Strip spaces from the end of the buffer 373 while (!p.empty() && isspace (p[p.size() - 1])) 374 p.erase (p.size () - 1); 375 376 // Most data in the debugserver packets valid printable characters... 377 DNBLogThreadedIf(LOG_RNB_COMM, "read: %s", p.c_str()); 378 return rnb_success; 379 } 380 381 rnb_err_t 382 RNBSocket::Write (const void *buffer, size_t length) 383 { 384 if (m_fd == -1) 385 return rnb_err; 386 387 DNBError err; 388 int bytessent = write (m_fd, buffer, length); 389 if (bytessent < 0) 390 err.SetError(errno, DNBError::POSIX); 391 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); 394 395 if (bytessent < 0) 396 return rnb_err; 397 398 if (bytessent != length) 399 return rnb_err; 400 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); 403 404 return rnb_success; 405 } 406 407 408 rnb_err_t 409 RNBSocket::ClosePort (int& fd, bool save_errno) 410 { 411 int close_err = 0; 412 if (fd > 0) 413 { 414 errno = 0; 415 close_err = close (fd); 416 fd = -1; 417 } 418 return close_err != 0 ? rnb_err : rnb_success; 419 } 420 421 422