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