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 <android-base/stringprintf.h> 29 #include <cutils/sockets.h> 30 31 #if !ADB_HOST 32 #include "cutils/properties.h" 33 #endif 34 35 #include "adb.h" 36 #include "adb_io.h" 37 #include "adb_utils.h" 38 39 #if ADB_HOST 40 41 // Android Wear has been using port 5601 in all of its documentation/tooling, 42 // but we search for emulators on ports [5554, 5555 + ADB_LOCAL_TRANSPORT_MAX]. 43 // Avoid stomping on their port by limiting the number of emulators that can be 44 // connected. 45 #define ADB_LOCAL_TRANSPORT_MAX 16 46 47 ADB_MUTEX_DEFINE(local_transports_lock); 48 49 /* we keep a list of opened transports. The atransport struct knows to which 50 * local transport it is connected. The list is used to detect when we're 51 * trying to connect twice to a given local transport. 52 */ 53 static atransport* local_transports[ ADB_LOCAL_TRANSPORT_MAX ]; 54 #endif /* ADB_HOST */ 55 56 static int remote_read(apacket *p, atransport *t) 57 { 58 if(!ReadFdExactly(t->sfd, &p->msg, sizeof(amessage))){ 59 D("remote local: read terminated (message)"); 60 return -1; 61 } 62 63 if(check_header(p, t)) { 64 D("bad header: terminated (data)"); 65 return -1; 66 } 67 68 if(!ReadFdExactly(t->sfd, p->data, p->msg.data_length)){ 69 D("remote local: terminated (data)"); 70 return -1; 71 } 72 73 if(check_data(p)) { 74 D("bad data: terminated (data)"); 75 return -1; 76 } 77 78 return 0; 79 } 80 81 static int remote_write(apacket *p, atransport *t) 82 { 83 int length = p->msg.data_length; 84 85 if(!WriteFdExactly(t->sfd, &p->msg, sizeof(amessage) + length)) { 86 D("remote local: write terminated"); 87 return -1; 88 } 89 90 return 0; 91 } 92 93 void local_connect(int port) { 94 std::string dummy; 95 local_connect_arbitrary_ports(port-1, port, &dummy); 96 } 97 98 int local_connect_arbitrary_ports(int console_port, int adb_port, std::string* error) { 99 int fd = -1; 100 101 #if ADB_HOST 102 if (find_emulator_transport_by_adb_port(adb_port) != nullptr || 103 find_emulator_transport_by_console_port(console_port) != nullptr) { 104 return -1; 105 } 106 107 const char *host = getenv("ADBHOST"); 108 if (host) { 109 fd = network_connect(host, adb_port, SOCK_STREAM, 0, error); 110 } 111 #endif 112 if (fd < 0) { 113 fd = network_loopback_client(adb_port, SOCK_STREAM, error); 114 } 115 116 if (fd >= 0) { 117 D("client: connected on remote on fd %d", fd); 118 close_on_exec(fd); 119 disable_tcp_nagle(fd); 120 std::string serial = getEmulatorSerialString(console_port); 121 if (register_socket_transport(fd, serial.c_str(), adb_port, 1) == 0) { 122 return 0; 123 } 124 adb_close(fd); 125 } 126 return -1; 127 } 128 129 #if ADB_HOST 130 static void client_socket_thread(void* x) { 131 adb_thread_setname("client_socket_thread"); 132 D("transport: client_socket_thread() starting"); 133 while (true) { 134 int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT; 135 int count = ADB_LOCAL_TRANSPORT_MAX; 136 137 // Try to connect to any number of running emulator instances. 138 for ( ; count > 0; count--, port += 2 ) { 139 local_connect(port); 140 } 141 sleep(1); 142 } 143 } 144 145 #else // ADB_HOST 146 147 static void server_socket_thread(void* arg) { 148 int serverfd, fd; 149 sockaddr_storage ss; 150 sockaddr *addrp = reinterpret_cast<sockaddr*>(&ss); 151 socklen_t alen; 152 int port = (int) (uintptr_t) arg; 153 154 adb_thread_setname("server socket"); 155 D("transport: server_socket_thread() starting"); 156 serverfd = -1; 157 for(;;) { 158 if(serverfd == -1) { 159 std::string error; 160 serverfd = network_inaddr_any_server(port, SOCK_STREAM, &error); 161 if(serverfd < 0) { 162 D("server: cannot bind socket yet: %s", error.c_str()); 163 adb_sleep_ms(1000); 164 continue; 165 } 166 close_on_exec(serverfd); 167 } 168 169 alen = sizeof(ss); 170 D("server: trying to get new connection from %d", port); 171 fd = adb_socket_accept(serverfd, addrp, &alen); 172 if(fd >= 0) { 173 D("server: new connection on fd %d", fd); 174 close_on_exec(fd); 175 disable_tcp_nagle(fd); 176 register_socket_transport(fd, "host", port, 1); 177 } 178 } 179 D("transport: server_socket_thread() exiting"); 180 } 181 182 /* This is relevant only for ADB daemon running inside the emulator. */ 183 /* 184 * Redefine open and write for qemu_pipe.h that contains inlined references 185 * to those routines. We will redifine them back after qemu_pipe.h inclusion. 186 */ 187 #undef open 188 #undef write 189 #define open adb_open 190 #define write adb_write 191 #include <hardware/qemu_pipe.h> 192 #undef open 193 #undef write 194 #define open ___xxx_open 195 #define write ___xxx_write 196 197 /* A worker thread that monitors host connections, and registers a transport for 198 * every new host connection. This thread replaces server_socket_thread on 199 * condition that adbd daemon runs inside the emulator, and emulator uses QEMUD 200 * pipe to communicate with adbd daemon inside the guest. This is done in order 201 * to provide more robust communication channel between ADB host and guest. The 202 * main issue with server_socket_thread approach is that it runs on top of TCP, 203 * and thus is sensitive to network disruptions. For instance, the 204 * ConnectionManager may decide to reset all network connections, in which case 205 * the connection between ADB host and guest will be lost. To make ADB traffic 206 * independent from the network, we use here 'adb' QEMUD service to transfer data 207 * between the host, and the guest. See external/qemu/android/adb-*.* that 208 * implements the emulator's side of the protocol. Another advantage of using 209 * QEMUD approach is that ADB will be up much sooner, since it doesn't depend 210 * anymore on network being set up. 211 * The guest side of the protocol contains the following phases: 212 * - Connect with adb QEMUD service. In this phase a handle to 'adb' QEMUD service 213 * is opened, and it becomes clear whether or not emulator supports that 214 * protocol. 215 * - Wait for the ADB host to create connection with the guest. This is done by 216 * sending an 'accept' request to the adb QEMUD service, and waiting on 217 * response. 218 * - When new ADB host connection is accepted, the connection with adb QEMUD 219 * service is registered as the transport, and a 'start' request is sent to the 220 * adb QEMUD service, indicating that the guest is ready to receive messages. 221 * Note that the guest will ignore messages sent down from the emulator before 222 * the transport registration is completed. That's why we need to send the 223 * 'start' request after the transport is registered. 224 */ 225 static void qemu_socket_thread(void* arg) { 226 /* 'accept' request to the adb QEMUD service. */ 227 static const char _accept_req[] = "accept"; 228 /* 'start' request to the adb QEMUD service. */ 229 static const char _start_req[] = "start"; 230 /* 'ok' reply from the adb QEMUD service. */ 231 static const char _ok_resp[] = "ok"; 232 233 const int port = (int) (uintptr_t) arg; 234 int fd; 235 char tmp[256]; 236 char con_name[32]; 237 238 adb_thread_setname("qemu socket"); 239 D("transport: qemu_socket_thread() starting"); 240 241 /* adb QEMUD service connection request. */ 242 snprintf(con_name, sizeof(con_name), "qemud:adb:%d", port); 243 244 /* Connect to the adb QEMUD service. */ 245 fd = qemu_pipe_open(con_name); 246 if (fd < 0) { 247 /* This could be an older version of the emulator, that doesn't 248 * implement adb QEMUD service. Fall back to the old TCP way. */ 249 D("adb service is not available. Falling back to TCP socket."); 250 adb_thread_create(server_socket_thread, arg); 251 return; 252 } 253 254 for(;;) { 255 /* 256 * Wait till the host creates a new connection. 257 */ 258 259 /* Send the 'accept' request. */ 260 if (WriteFdExactly(fd, _accept_req, strlen(_accept_req))) { 261 /* Wait for the response. In the response we expect 'ok' on success, 262 * or 'ko' on failure. */ 263 if (!ReadFdExactly(fd, tmp, 2) || memcmp(tmp, _ok_resp, 2)) { 264 D("Accepting ADB host connection has failed."); 265 adb_close(fd); 266 } else { 267 /* Host is connected. Register the transport, and start the 268 * exchange. */ 269 std::string serial = android::base::StringPrintf("host-%d", fd); 270 register_socket_transport(fd, serial.c_str(), port, 1); 271 if (!WriteFdExactly(fd, _start_req, strlen(_start_req))) { 272 adb_close(fd); 273 } 274 } 275 276 /* Prepare for accepting of the next ADB host connection. */ 277 fd = qemu_pipe_open(con_name); 278 if (fd < 0) { 279 D("adb service become unavailable."); 280 return; 281 } 282 } else { 283 D("Unable to send the '%s' request to ADB service.", _accept_req); 284 return; 285 } 286 } 287 D("transport: qemu_socket_thread() exiting"); 288 return; 289 } 290 #endif // !ADB_HOST 291 292 void local_init(int port) 293 { 294 adb_thread_func_t func; 295 const char* debug_name = ""; 296 297 #if ADB_HOST 298 func = client_socket_thread; 299 debug_name = "client"; 300 #else 301 /* For the adbd daemon in the system image we need to distinguish 302 * between the device, and the emulator. */ 303 char is_qemu[PROPERTY_VALUE_MAX]; 304 property_get("ro.kernel.qemu", is_qemu, ""); 305 if (!strcmp(is_qemu, "1")) { 306 /* Running inside the emulator: use QEMUD pipe as the transport. */ 307 func = qemu_socket_thread; 308 } else { 309 /* Running inside the device: use TCP socket as the transport. */ 310 func = server_socket_thread; 311 } 312 debug_name = "server"; 313 #endif // !ADB_HOST 314 315 D("transport: local %s init", debug_name); 316 if (!adb_thread_create(func, (void *) (uintptr_t) port)) { 317 fatal_errno("cannot create local socket %s thread", debug_name); 318 } 319 } 320 321 static void remote_kick(atransport *t) 322 { 323 int fd = t->sfd; 324 t->sfd = -1; 325 adb_shutdown(fd); 326 adb_close(fd); 327 328 #if ADB_HOST 329 int nn; 330 adb_mutex_lock( &local_transports_lock ); 331 for (nn = 0; nn < ADB_LOCAL_TRANSPORT_MAX; nn++) { 332 if (local_transports[nn] == t) { 333 local_transports[nn] = NULL; 334 break; 335 } 336 } 337 adb_mutex_unlock( &local_transports_lock ); 338 #endif 339 } 340 341 static void remote_close(atransport *t) 342 { 343 int fd = t->sfd; 344 if (fd != -1) { 345 t->sfd = -1; 346 adb_close(fd); 347 } 348 } 349 350 351 #if ADB_HOST 352 /* Only call this function if you already hold local_transports_lock. */ 353 atransport* find_emulator_transport_by_adb_port_locked(int adb_port) 354 { 355 int i; 356 for (i = 0; i < ADB_LOCAL_TRANSPORT_MAX; i++) { 357 if (local_transports[i] && local_transports[i]->adb_port == adb_port) { 358 return local_transports[i]; 359 } 360 } 361 return NULL; 362 } 363 364 std::string getEmulatorSerialString(int console_port) 365 { 366 return android::base::StringPrintf("emulator-%d", console_port); 367 } 368 369 atransport* find_emulator_transport_by_adb_port(int adb_port) 370 { 371 adb_mutex_lock( &local_transports_lock ); 372 atransport* result = find_emulator_transport_by_adb_port_locked(adb_port); 373 adb_mutex_unlock( &local_transports_lock ); 374 return result; 375 } 376 377 atransport* find_emulator_transport_by_console_port(int console_port) 378 { 379 return find_transport(getEmulatorSerialString(console_port).c_str()); 380 } 381 382 383 /* Only call this function if you already hold local_transports_lock. */ 384 int get_available_local_transport_index_locked() 385 { 386 int i; 387 for (i = 0; i < ADB_LOCAL_TRANSPORT_MAX; i++) { 388 if (local_transports[i] == NULL) { 389 return i; 390 } 391 } 392 return -1; 393 } 394 395 int get_available_local_transport_index() 396 { 397 adb_mutex_lock( &local_transports_lock ); 398 int result = get_available_local_transport_index_locked(); 399 adb_mutex_unlock( &local_transports_lock ); 400 return result; 401 } 402 #endif 403 404 int init_socket_transport(atransport *t, int s, int adb_port, int local) 405 { 406 int fail = 0; 407 408 t->SetKickFunction(remote_kick); 409 t->close = remote_close; 410 t->read_from_remote = remote_read; 411 t->write_to_remote = remote_write; 412 t->sfd = s; 413 t->sync_token = 1; 414 t->connection_state = kCsOffline; 415 t->type = kTransportLocal; 416 t->adb_port = 0; 417 418 #if ADB_HOST 419 if (local) { 420 adb_mutex_lock( &local_transports_lock ); 421 { 422 t->adb_port = adb_port; 423 atransport* existing_transport = 424 find_emulator_transport_by_adb_port_locked(adb_port); 425 int index = get_available_local_transport_index_locked(); 426 if (existing_transport != NULL) { 427 D("local transport for port %d already registered (%p)?", 428 adb_port, existing_transport); 429 fail = -1; 430 } else if (index < 0) { 431 // Too many emulators. 432 D("cannot register more emulators. Maximum is %d", 433 ADB_LOCAL_TRANSPORT_MAX); 434 fail = -1; 435 } else { 436 local_transports[index] = t; 437 } 438 } 439 adb_mutex_unlock( &local_transports_lock ); 440 } 441 #endif 442 return fail; 443 } 444