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