1 /* 2 * Copyright (C) 2007 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #define TRACE_TAG TRANSPORT 18 19 #include "sysdeps.h" 20 #include "transport.h" 21 22 #include <errno.h> 23 #include <stdio.h> 24 #include <stdlib.h> 25 #include <string.h> 26 #include <sys/types.h> 27 28 #include <condition_variable> 29 #include <mutex> 30 #include <thread> 31 #include <vector> 32 33 #include <android-base/parsenetaddress.h> 34 #include <android-base/stringprintf.h> 35 #include <cutils/sockets.h> 36 37 #if !ADB_HOST 38 #include <android-base/properties.h> 39 #endif 40 41 #include "adb.h" 42 #include "adb_io.h" 43 #include "adb_utils.h" 44 #include "sysdeps/chrono.h" 45 46 #if ADB_HOST 47 48 // Android Wear has been using port 5601 in all of its documentation/tooling, 49 // but we search for emulators on ports [5554, 5555 + ADB_LOCAL_TRANSPORT_MAX]. 50 // Avoid stomping on their port by limiting the number of emulators that can be 51 // connected. 52 #define ADB_LOCAL_TRANSPORT_MAX 16 53 54 static std::mutex& local_transports_lock = *new std::mutex(); 55 56 /* we keep a list of opened transports. The atransport struct knows to which 57 * local transport it is connected. The list is used to detect when we're 58 * trying to connect twice to a given local transport. 59 */ 60 static atransport* local_transports[ ADB_LOCAL_TRANSPORT_MAX ]; 61 #endif /* ADB_HOST */ 62 63 static int remote_read(apacket *p, atransport *t) 64 { 65 if(!ReadFdExactly(t->sfd, &p->msg, sizeof(amessage))){ 66 D("remote local: read terminated (message)"); 67 return -1; 68 } 69 70 if(check_header(p, t)) { 71 D("bad header: terminated (data)"); 72 return -1; 73 } 74 75 if(!ReadFdExactly(t->sfd, p->data, p->msg.data_length)){ 76 D("remote local: terminated (data)"); 77 return -1; 78 } 79 80 if(check_data(p)) { 81 D("bad data: terminated (data)"); 82 return -1; 83 } 84 85 return 0; 86 } 87 88 static int remote_write(apacket *p, atransport *t) 89 { 90 int length = p->msg.data_length; 91 92 if(!WriteFdExactly(t->sfd, &p->msg, sizeof(amessage) + length)) { 93 D("remote local: write terminated"); 94 return -1; 95 } 96 97 return 0; 98 } 99 100 bool local_connect(int port) { 101 std::string dummy; 102 return local_connect_arbitrary_ports(port-1, port, &dummy) == 0; 103 } 104 105 void connect_device(const std::string& address, std::string* response) { 106 if (address.empty()) { 107 *response = "empty address"; 108 return; 109 } 110 111 std::string serial; 112 std::string host; 113 int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT; 114 if (!android::base::ParseNetAddress(address, &host, &port, &serial, response)) { 115 return; 116 } 117 118 std::string error; 119 int fd = network_connect(host.c_str(), port, SOCK_STREAM, 10, &error); 120 if (fd == -1) { 121 *response = android::base::StringPrintf("unable to connect to %s: %s", 122 serial.c_str(), error.c_str()); 123 return; 124 } 125 126 D("client: connected %s remote on fd %d", serial.c_str(), fd); 127 close_on_exec(fd); 128 disable_tcp_nagle(fd); 129 130 // Send a TCP keepalive ping to the device every second so we can detect disconnects. 131 if (!set_tcp_keepalive(fd, 1)) { 132 D("warning: failed to configure TCP keepalives (%s)", strerror(errno)); 133 } 134 135 int ret = register_socket_transport(fd, serial.c_str(), port, 0); 136 if (ret < 0) { 137 adb_close(fd); 138 *response = android::base::StringPrintf("already connected to %s", serial.c_str()); 139 } else { 140 *response = android::base::StringPrintf("connected to %s", serial.c_str()); 141 } 142 } 143 144 145 int local_connect_arbitrary_ports(int console_port, int adb_port, std::string* error) { 146 int fd = -1; 147 148 #if ADB_HOST 149 if (find_emulator_transport_by_adb_port(adb_port) != nullptr || 150 find_emulator_transport_by_console_port(console_port) != nullptr) { 151 return -1; 152 } 153 154 const char *host = getenv("ADBHOST"); 155 if (host) { 156 fd = network_connect(host, adb_port, SOCK_STREAM, 0, error); 157 } 158 #endif 159 if (fd < 0) { 160 fd = network_loopback_client(adb_port, SOCK_STREAM, error); 161 } 162 163 if (fd >= 0) { 164 D("client: connected on remote on fd %d", fd); 165 close_on_exec(fd); 166 disable_tcp_nagle(fd); 167 std::string serial = getEmulatorSerialString(console_port); 168 if (register_socket_transport(fd, serial.c_str(), adb_port, 1) == 0) { 169 return 0; 170 } 171 adb_close(fd); 172 } 173 return -1; 174 } 175 176 #if ADB_HOST 177 178 static void PollAllLocalPortsForEmulator() { 179 int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT; 180 int count = ADB_LOCAL_TRANSPORT_MAX; 181 182 // Try to connect to any number of running emulator instances. 183 for ( ; count > 0; count--, port += 2 ) { 184 local_connect(port); 185 } 186 } 187 188 // Retry the disconnected local port for 60 times, and sleep 1 second between two retries. 189 constexpr uint32_t LOCAL_PORT_RETRY_COUNT = 60; 190 constexpr auto LOCAL_PORT_RETRY_INTERVAL = 1s; 191 192 struct RetryPort { 193 int port; 194 uint32_t retry_count; 195 }; 196 197 // Retry emulators just kicked. 198 static std::vector<RetryPort>& retry_ports = *new std::vector<RetryPort>; 199 std::mutex &retry_ports_lock = *new std::mutex; 200 std::condition_variable &retry_ports_cond = *new std::condition_variable; 201 202 static void client_socket_thread(void* x) { 203 adb_thread_setname("client_socket_thread"); 204 D("transport: client_socket_thread() starting"); 205 PollAllLocalPortsForEmulator(); 206 while (true) { 207 std::vector<RetryPort> ports; 208 // Collect retry ports. 209 { 210 std::unique_lock<std::mutex> lock(retry_ports_lock); 211 while (retry_ports.empty()) { 212 retry_ports_cond.wait(lock); 213 } 214 retry_ports.swap(ports); 215 } 216 // Sleep here instead of the end of loop, because if we immediately try to reconnect 217 // the emulator just kicked, the adbd on the emulator may not have time to remove the 218 // just kicked transport. 219 std::this_thread::sleep_for(LOCAL_PORT_RETRY_INTERVAL); 220 221 // Try connecting retry ports. 222 std::vector<RetryPort> next_ports; 223 for (auto& port : ports) { 224 VLOG(TRANSPORT) << "retry port " << port.port << ", last retry_count " 225 << port.retry_count; 226 if (local_connect(port.port)) { 227 VLOG(TRANSPORT) << "retry port " << port.port << " successfully"; 228 continue; 229 } 230 if (--port.retry_count > 0) { 231 next_ports.push_back(port); 232 } else { 233 VLOG(TRANSPORT) << "stop retrying port " << port.port; 234 } 235 } 236 237 // Copy back left retry ports. 238 { 239 std::unique_lock<std::mutex> lock(retry_ports_lock); 240 retry_ports.insert(retry_ports.end(), next_ports.begin(), next_ports.end()); 241 } 242 } 243 } 244 245 #else // ADB_HOST 246 247 static void server_socket_thread(void* arg) { 248 int serverfd, fd; 249 int port = (int) (uintptr_t) arg; 250 251 adb_thread_setname("server socket"); 252 D("transport: server_socket_thread() starting"); 253 serverfd = -1; 254 for(;;) { 255 if(serverfd == -1) { 256 std::string error; 257 serverfd = network_inaddr_any_server(port, SOCK_STREAM, &error); 258 if(serverfd < 0) { 259 D("server: cannot bind socket yet: %s", error.c_str()); 260 std::this_thread::sleep_for(1s); 261 continue; 262 } 263 close_on_exec(serverfd); 264 } 265 266 D("server: trying to get new connection from %d", port); 267 fd = adb_socket_accept(serverfd, nullptr, nullptr); 268 if(fd >= 0) { 269 D("server: new connection on fd %d", fd); 270 close_on_exec(fd); 271 disable_tcp_nagle(fd); 272 std::string serial = android::base::StringPrintf("host-%d", fd); 273 if (register_socket_transport(fd, serial.c_str(), port, 1) != 0) { 274 adb_close(fd); 275 } 276 } 277 } 278 D("transport: server_socket_thread() exiting"); 279 } 280 281 /* This is relevant only for ADB daemon running inside the emulator. */ 282 /* 283 * Redefine open and write for qemu_pipe.h that contains inlined references 284 * to those routines. We will redefine them back after qemu_pipe.h inclusion. 285 */ 286 #undef open 287 #undef read 288 #undef write 289 #define open adb_open 290 #define read adb_read 291 #define write adb_write 292 #include <system/qemu_pipe.h> 293 #undef open 294 #undef read 295 #undef write 296 #define open ___xxx_open 297 #define read ___xxx_read 298 #define write ___xxx_write 299 300 /* A worker thread that monitors host connections, and registers a transport for 301 * every new host connection. This thread replaces server_socket_thread on 302 * condition that adbd daemon runs inside the emulator, and emulator uses QEMUD 303 * pipe to communicate with adbd daemon inside the guest. This is done in order 304 * to provide more robust communication channel between ADB host and guest. The 305 * main issue with server_socket_thread approach is that it runs on top of TCP, 306 * and thus is sensitive to network disruptions. For instance, the 307 * ConnectionManager may decide to reset all network connections, in which case 308 * the connection between ADB host and guest will be lost. To make ADB traffic 309 * independent from the network, we use here 'adb' QEMUD service to transfer data 310 * between the host, and the guest. See external/qemu/android/adb-*.* that 311 * implements the emulator's side of the protocol. Another advantage of using 312 * QEMUD approach is that ADB will be up much sooner, since it doesn't depend 313 * anymore on network being set up. 314 * The guest side of the protocol contains the following phases: 315 * - Connect with adb QEMUD service. In this phase a handle to 'adb' QEMUD service 316 * is opened, and it becomes clear whether or not emulator supports that 317 * protocol. 318 * - Wait for the ADB host to create connection with the guest. This is done by 319 * sending an 'accept' request to the adb QEMUD service, and waiting on 320 * response. 321 * - When new ADB host connection is accepted, the connection with adb QEMUD 322 * service is registered as the transport, and a 'start' request is sent to the 323 * adb QEMUD service, indicating that the guest is ready to receive messages. 324 * Note that the guest will ignore messages sent down from the emulator before 325 * the transport registration is completed. That's why we need to send the 326 * 'start' request after the transport is registered. 327 */ 328 static void qemu_socket_thread(void* arg) { 329 /* 'accept' request to the adb QEMUD service. */ 330 static const char _accept_req[] = "accept"; 331 /* 'start' request to the adb QEMUD service. */ 332 static const char _start_req[] = "start"; 333 /* 'ok' reply from the adb QEMUD service. */ 334 static const char _ok_resp[] = "ok"; 335 336 const int port = (int) (uintptr_t) arg; 337 int fd; 338 char tmp[256]; 339 char con_name[32]; 340 341 adb_thread_setname("qemu socket"); 342 D("transport: qemu_socket_thread() starting"); 343 344 /* adb QEMUD service connection request. */ 345 snprintf(con_name, sizeof(con_name), "pipe:qemud:adb:%d", port); 346 347 /* Connect to the adb QEMUD service. */ 348 fd = qemu_pipe_open(con_name); 349 if (fd < 0) { 350 /* This could be an older version of the emulator, that doesn't 351 * implement adb QEMUD service. Fall back to the old TCP way. */ 352 D("adb service is not available. Falling back to TCP socket."); 353 adb_thread_create(server_socket_thread, arg); 354 return; 355 } 356 357 for(;;) { 358 /* 359 * Wait till the host creates a new connection. 360 */ 361 362 /* Send the 'accept' request. */ 363 if (WriteFdExactly(fd, _accept_req, strlen(_accept_req))) { 364 /* Wait for the response. In the response we expect 'ok' on success, 365 * or 'ko' on failure. */ 366 if (!ReadFdExactly(fd, tmp, 2) || memcmp(tmp, _ok_resp, 2)) { 367 D("Accepting ADB host connection has failed."); 368 adb_close(fd); 369 } else { 370 /* Host is connected. Register the transport, and start the 371 * exchange. */ 372 std::string serial = android::base::StringPrintf("host-%d", fd); 373 if (register_socket_transport(fd, serial.c_str(), port, 1) != 0 || 374 !WriteFdExactly(fd, _start_req, strlen(_start_req))) { 375 adb_close(fd); 376 } 377 } 378 379 /* Prepare for accepting of the next ADB host connection. */ 380 fd = qemu_pipe_open(con_name); 381 if (fd < 0) { 382 D("adb service become unavailable."); 383 return; 384 } 385 } else { 386 D("Unable to send the '%s' request to ADB service.", _accept_req); 387 return; 388 } 389 } 390 D("transport: qemu_socket_thread() exiting"); 391 return; 392 } 393 #endif // !ADB_HOST 394 395 void local_init(int port) 396 { 397 adb_thread_func_t func; 398 const char* debug_name = ""; 399 400 #if ADB_HOST 401 func = client_socket_thread; 402 debug_name = "client"; 403 #else 404 // For the adbd daemon in the system image we need to distinguish 405 // between the device, and the emulator. 406 if (android::base::GetBoolProperty("ro.kernel.qemu", false)) { 407 // Running inside the emulator: use QEMUD pipe as the transport. 408 func = qemu_socket_thread; 409 } else { 410 // Running inside the device: use TCP socket as the transport. 411 func = server_socket_thread; 412 } 413 debug_name = "server"; 414 #endif // !ADB_HOST 415 416 D("transport: local %s init", debug_name); 417 if (!adb_thread_create(func, (void *) (uintptr_t) port)) { 418 fatal_errno("cannot create local socket %s thread", debug_name); 419 } 420 } 421 422 static void remote_kick(atransport *t) 423 { 424 int fd = t->sfd; 425 t->sfd = -1; 426 adb_shutdown(fd); 427 adb_close(fd); 428 429 #if ADB_HOST 430 int nn; 431 std::lock_guard<std::mutex> lock(local_transports_lock); 432 for (nn = 0; nn < ADB_LOCAL_TRANSPORT_MAX; nn++) { 433 if (local_transports[nn] == t) { 434 local_transports[nn] = NULL; 435 break; 436 } 437 } 438 #endif 439 } 440 441 static void remote_close(atransport *t) 442 { 443 int fd = t->sfd; 444 if (fd != -1) { 445 t->sfd = -1; 446 adb_close(fd); 447 } 448 #if ADB_HOST 449 int local_port; 450 if (t->GetLocalPortForEmulator(&local_port)) { 451 VLOG(TRANSPORT) << "remote_close, local_port = " << local_port; 452 std::unique_lock<std::mutex> lock(retry_ports_lock); 453 RetryPort port; 454 port.port = local_port; 455 port.retry_count = LOCAL_PORT_RETRY_COUNT; 456 retry_ports.push_back(port); 457 retry_ports_cond.notify_one(); 458 } 459 #endif 460 } 461 462 463 #if ADB_HOST 464 /* Only call this function if you already hold local_transports_lock. */ 465 static atransport* find_emulator_transport_by_adb_port_locked(int adb_port) 466 { 467 int i; 468 for (i = 0; i < ADB_LOCAL_TRANSPORT_MAX; i++) { 469 int local_port; 470 if (local_transports[i] && local_transports[i]->GetLocalPortForEmulator(&local_port)) { 471 if (local_port == adb_port) { 472 return local_transports[i]; 473 } 474 } 475 } 476 return NULL; 477 } 478 479 std::string getEmulatorSerialString(int console_port) 480 { 481 return android::base::StringPrintf("emulator-%d", console_port); 482 } 483 484 atransport* find_emulator_transport_by_adb_port(int adb_port) 485 { 486 std::lock_guard<std::mutex> lock(local_transports_lock); 487 atransport* result = find_emulator_transport_by_adb_port_locked(adb_port); 488 return result; 489 } 490 491 atransport* find_emulator_transport_by_console_port(int console_port) 492 { 493 return find_transport(getEmulatorSerialString(console_port).c_str()); 494 } 495 496 497 /* Only call this function if you already hold local_transports_lock. */ 498 int get_available_local_transport_index_locked() 499 { 500 int i; 501 for (i = 0; i < ADB_LOCAL_TRANSPORT_MAX; i++) { 502 if (local_transports[i] == NULL) { 503 return i; 504 } 505 } 506 return -1; 507 } 508 509 int get_available_local_transport_index() 510 { 511 std::lock_guard<std::mutex> lock(local_transports_lock); 512 int result = get_available_local_transport_index_locked(); 513 return result; 514 } 515 #endif 516 517 int init_socket_transport(atransport *t, int s, int adb_port, int local) 518 { 519 int fail = 0; 520 521 t->SetKickFunction(remote_kick); 522 t->close = remote_close; 523 t->read_from_remote = remote_read; 524 t->write_to_remote = remote_write; 525 t->sfd = s; 526 t->sync_token = 1; 527 t->connection_state = kCsOffline; 528 t->type = kTransportLocal; 529 530 #if ADB_HOST 531 if (local) { 532 std::lock_guard<std::mutex> lock(local_transports_lock); 533 t->SetLocalPortForEmulator(adb_port); 534 atransport* existing_transport = find_emulator_transport_by_adb_port_locked(adb_port); 535 int index = get_available_local_transport_index_locked(); 536 if (existing_transport != NULL) { 537 D("local transport for port %d already registered (%p)?", adb_port, existing_transport); 538 fail = -1; 539 } else if (index < 0) { 540 // Too many emulators. 541 D("cannot register more emulators. Maximum is %d", ADB_LOCAL_TRANSPORT_MAX); 542 fail = -1; 543 } else { 544 local_transports[index] = t; 545 } 546 } 547 #endif 548 return fail; 549 } 550