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