transport_local.cpp revision 0e2c19465964d27f6da0e5d23c329b7892d41204
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 TRACE_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 <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)\n");
55        return -1;
56    }
57
58    if(check_header(p, t)) {
59        D("bad header: terminated (data)\n");
60        return -1;
61    }
62
63    if(!ReadFdExactly(t->sfd, p->data, p->msg.data_length)){
64        D("remote local: terminated (data)\n");
65        return -1;
66    }
67
68    if(check_data(p)) {
69        D("bad data: terminated (data)\n");
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\n");
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\n", 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
124static void *client_socket_thread(void *x)
125{
126#if ADB_HOST
127    D("transport: client_socket_thread() starting\n");
128    while (true) {
129        int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
130        int count = ADB_LOCAL_TRANSPORT_MAX;
131
132        // Try to connect to any number of running emulator instances.
133        for ( ; count > 0; count--, port += 2 ) {
134            local_connect(port);
135        }
136        sleep(1);
137    }
138#endif
139    return 0;
140}
141
142static void *server_socket_thread(void * arg)
143{
144    int serverfd, fd;
145    struct sockaddr addr;
146    socklen_t alen;
147    int port = (int) (uintptr_t) arg;
148
149    D("transport: server_socket_thread() starting\n");
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\n", error.c_str());
157                adb_sleep_ms(1000);
158                continue;
159            }
160            close_on_exec(serverfd);
161        }
162
163        alen = sizeof(addr);
164        D("server: trying to get new connection from %d\n", port);
165        fd = adb_socket_accept(serverfd, &addr, &alen);
166        if(fd >= 0) {
167            D("server: new connection on fd %d\n", 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\n");
174    return 0;
175}
176
177/* This is relevant only for ADB daemon running inside the emulator. */
178#if !ADB_HOST
179/*
180 * Redefine open and write for qemu_pipe.h that contains inlined references
181 * to those routines. We will redifine them back after qemu_pipe.h inclusion.
182 */
183#undef open
184#undef write
185#define open    adb_open
186#define write   adb_write
187#include <hardware/qemu_pipe.h>
188#undef open
189#undef write
190#define open    ___xxx_open
191#define write   ___xxx_write
192
193/* A worker thread that monitors host connections, and registers a transport for
194 * every new host connection. This thread replaces server_socket_thread on
195 * condition that adbd daemon runs inside the emulator, and emulator uses QEMUD
196 * pipe to communicate with adbd daemon inside the guest. This is done in order
197 * to provide more robust communication channel between ADB host and guest. The
198 * main issue with server_socket_thread approach is that it runs on top of TCP,
199 * and thus is sensitive to network disruptions. For instance, the
200 * ConnectionManager may decide to reset all network connections, in which case
201 * the connection between ADB host and guest will be lost. To make ADB traffic
202 * independent from the network, we use here 'adb' QEMUD service to transfer data
203 * between the host, and the guest. See external/qemu/android/adb-*.* that
204 * implements the emulator's side of the protocol. Another advantage of using
205 * QEMUD approach is that ADB will be up much sooner, since it doesn't depend
206 * anymore on network being set up.
207 * The guest side of the protocol contains the following phases:
208 * - Connect with adb QEMUD service. In this phase a handle to 'adb' QEMUD service
209 *   is opened, and it becomes clear whether or not emulator supports that
210 *   protocol.
211 * - Wait for the ADB host to create connection with the guest. This is done by
212 *   sending an 'accept' request to the adb QEMUD service, and waiting on
213 *   response.
214 * - When new ADB host connection is accepted, the connection with adb QEMUD
215 *   service is registered as the transport, and a 'start' request is sent to the
216 *   adb QEMUD service, indicating that the guest is ready to receive messages.
217 *   Note that the guest will ignore messages sent down from the emulator before
218 *   the transport registration is completed. That's why we need to send the
219 *   'start' request after the transport is registered.
220 */
221static void *qemu_socket_thread(void * arg)
222{
223/* 'accept' request to the adb QEMUD service. */
224static const char _accept_req[] = "accept";
225/* 'start' request to the adb QEMUD service. */
226static const char _start_req[]  = "start";
227/* 'ok' reply from the adb QEMUD service. */
228static const char _ok_resp[]    = "ok";
229
230    const int port = (int) (uintptr_t) arg;
231    int res, fd;
232    char tmp[256];
233    char con_name[32];
234
235    D("transport: qemu_socket_thread() starting\n");
236
237    /* adb QEMUD service connection request. */
238    snprintf(con_name, sizeof(con_name), "qemud:adb:%d", port);
239
240    /* Connect to the adb QEMUD service. */
241    fd = qemu_pipe_open(con_name);
242    if (fd < 0) {
243        /* This could be an older version of the emulator, that doesn't
244         * implement adb QEMUD service. Fall back to the old TCP way. */
245        D("adb service is not available. Falling back to TCP socket.\n");
246        adb_thread_create(server_socket_thread, arg);
247        return 0;
248    }
249
250    for(;;) {
251        /*
252         * Wait till the host creates a new connection.
253         */
254
255        /* Send the 'accept' request. */
256        res = adb_write(fd, _accept_req, strlen(_accept_req));
257        if ((size_t)res == strlen(_accept_req)) {
258            /* Wait for the response. In the response we expect 'ok' on success,
259             * or 'ko' on failure. */
260            res = adb_read(fd, tmp, sizeof(tmp));
261            if (res != 2 || memcmp(tmp, _ok_resp, 2)) {
262                D("Accepting ADB host connection has failed.\n");
263                adb_close(fd);
264            } else {
265                /* Host is connected. Register the transport, and start the
266                 * exchange. */
267                register_socket_transport(fd, "host", port, 1);
268                adb_write(fd, _start_req, strlen(_start_req));
269            }
270
271            /* Prepare for accepting of the next ADB host connection. */
272            fd = qemu_pipe_open(con_name);
273            if (fd < 0) {
274                D("adb service become unavailable.\n");
275                return 0;
276            }
277        } else {
278            D("Unable to send the '%s' request to ADB service.\n", _accept_req);
279            return 0;
280        }
281    }
282    D("transport: qemu_socket_thread() exiting\n");
283    return 0;
284}
285#endif  // !ADB_HOST
286
287void local_init(int port)
288{
289    void* (*func)(void *);
290
291    if(HOST) {
292        func = client_socket_thread;
293    } else {
294#if ADB_HOST
295        func = server_socket_thread;
296#else
297        /* For the adbd daemon in the system image we need to distinguish
298         * between the device, and the emulator. */
299        char is_qemu[PROPERTY_VALUE_MAX];
300        property_get("ro.kernel.qemu", is_qemu, "");
301        if (!strcmp(is_qemu, "1")) {
302            /* Running inside the emulator: use QEMUD pipe as the transport. */
303            func = qemu_socket_thread;
304        } else {
305            /* Running inside the device: use TCP socket as the transport. */
306            func = server_socket_thread;
307        }
308#endif // !ADB_HOST
309    }
310
311    D("transport: local %s init\n", HOST ? "client" : "server");
312
313    if (!adb_thread_create(func, (void *) (uintptr_t) port)) {
314        fatal_errno("cannot create local socket %s thread", HOST ? "client" : "server");
315    }
316}
317
318static void remote_kick(atransport *t)
319{
320    int fd = t->sfd;
321    t->sfd = -1;
322    adb_shutdown(fd);
323    adb_close(fd);
324
325#if ADB_HOST
326    if(HOST) {
327        int  nn;
328        adb_mutex_lock( &local_transports_lock );
329        for (nn = 0; nn < ADB_LOCAL_TRANSPORT_MAX; nn++) {
330            if (local_transports[nn] == t) {
331                local_transports[nn] = NULL;
332                break;
333            }
334        }
335        adb_mutex_unlock( &local_transports_lock );
336    }
337#endif
338}
339
340static 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. */
352atransport* 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
363atransport* 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. */
372int 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
383int 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
392int init_socket_transport(atransport *t, int s, int adb_port, int local)
393{
394    int  fail = 0;
395
396    t->kick = 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 (HOST && 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)?\n",
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\n",
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