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