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