Home | History | Annotate | Download | only in adb
      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)
     30 static 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 
     50 ADB_MUTEX_DEFINE( local_transports_lock );
     51 
     52 static atransport*  local_transports[ ADB_LOCAL_TRANSPORT_MAX ];
     53 #endif /* ADB_HOST */
     54 
     55 static 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 
     86 static 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 
    105 int local_connect(int port) {
    106     return local_connect_arbitrary_ports(port-1, port);
    107 }
    108 
    109 int 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 
    136 static 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 
    154 static 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 /* This is relevant only for ADB daemon running inside the emulator. */
    189 #if !ADB_HOST
    190 /*
    191  * Redefine open and write for qemu_pipe.h that contains inlined references
    192  * to those routines. We will redifine them back after qemu_pipe.h inclusion.
    193  */
    194 #undef open
    195 #undef write
    196 #define open    adb_open
    197 #define write   adb_write
    198 #include <hardware/qemu_pipe.h>
    199 #undef open
    200 #undef write
    201 #define open    ___xxx_open
    202 #define write   ___xxx_write
    203 
    204 /* A worker thread that monitors host connections, and registers a transport for
    205  * every new host connection. This thread replaces server_socket_thread on
    206  * condition that adbd daemon runs inside the emulator, and emulator uses QEMUD
    207  * pipe to communicate with adbd daemon inside the guest. This is done in order
    208  * to provide more robust communication channel between ADB host and guest. The
    209  * main issue with server_socket_thread approach is that it runs on top of TCP,
    210  * and thus is sensitive to network disruptions. For instance, the
    211  * ConnectionManager may decide to reset all network connections, in which case
    212  * the connection between ADB host and guest will be lost. To make ADB traffic
    213  * independent from the network, we use here 'adb' QEMUD service to transfer data
    214  * between the host, and the guest. See external/qemu/android/adb-*.* that
    215  * implements the emulator's side of the protocol. Another advantage of using
    216  * QEMUD approach is that ADB will be up much sooner, since it doesn't depend
    217  * anymore on network being set up.
    218  * The guest side of the protocol contains the following phases:
    219  * - Connect with adb QEMUD service. In this phase a handle to 'adb' QEMUD service
    220  *   is opened, and it becomes clear whether or not emulator supports that
    221  *   protocol.
    222  * - Wait for the ADB host to create connection with the guest. This is done by
    223  *   sending an 'accept' request to the adb QEMUD service, and waiting on
    224  *   response.
    225  * - When new ADB host connection is accepted, the connection with adb QEMUD
    226  *   service is registered as the transport, and a 'start' request is sent to the
    227  *   adb QEMUD service, indicating that the guest is ready to receive messages.
    228  *   Note that the guest will ignore messages sent down from the emulator before
    229  *   the transport registration is completed. That's why we need to send the
    230  *   'start' request after the transport is registered.
    231  */
    232 static void *qemu_socket_thread(void * arg)
    233 {
    234 /* 'accept' request to the adb QEMUD service. */
    235 static const char _accept_req[] = "accept";
    236 /* 'start' request to the adb QEMUD service. */
    237 static const char _start_req[]  = "start";
    238 /* 'ok' reply from the adb QEMUD service. */
    239 static const char _ok_resp[]    = "ok";
    240 
    241     const int port = (int)arg;
    242     int res, fd;
    243     char tmp[256];
    244     char con_name[32];
    245 
    246     D("transport: qemu_socket_thread() starting\n");
    247 
    248     /* adb QEMUD service connection request. */
    249     snprintf(con_name, sizeof(con_name), "qemud:adb:%d", port);
    250 
    251     /* Connect to the adb QEMUD service. */
    252     fd = qemu_pipe_open(con_name);
    253     if (fd < 0) {
    254         /* This could be an older version of the emulator, that doesn't
    255          * implement adb QEMUD service. Fall back to the old TCP way. */
    256         adb_thread_t thr;
    257         D("adb service is not available. Falling back to TCP socket.\n");
    258         adb_thread_create(&thr, server_socket_thread, arg);
    259         return 0;
    260     }
    261 
    262     for(;;) {
    263         /*
    264          * Wait till the host creates a new connection.
    265          */
    266 
    267         /* Send the 'accept' request. */
    268         res = adb_write(fd, _accept_req, strlen(_accept_req));
    269         if (res == strlen(_accept_req)) {
    270             /* Wait for the response. In the response we expect 'ok' on success,
    271              * or 'ko' on failure. */
    272             res = adb_read(fd, tmp, sizeof(tmp));
    273             if (res != 2 || memcmp(tmp, _ok_resp, 2)) {
    274                 D("Accepting ADB host connection has failed.\n");
    275                 adb_close(fd);
    276             } else {
    277                 /* Host is connected. Register the transport, and start the
    278                  * exchange. */
    279                 register_socket_transport(fd, "host", port, 1);
    280                 adb_write(fd, _start_req, strlen(_start_req));
    281             }
    282 
    283             /* Prepare for accepting of the next ADB host connection. */
    284             fd = qemu_pipe_open(con_name);
    285             if (fd < 0) {
    286                 D("adb service become unavailable.\n");
    287                 return 0;
    288             }
    289         } else {
    290             D("Unable to send the '%s' request to ADB service.\n", _accept_req);
    291             return 0;
    292         }
    293     }
    294     D("transport: qemu_socket_thread() exiting\n");
    295     return 0;
    296 }
    297 #endif  // !ADB_HOST
    298 
    299 void local_init(int port)
    300 {
    301     adb_thread_t thr;
    302     void* (*func)(void *);
    303 
    304     if(HOST) {
    305         func = client_socket_thread;
    306     } else {
    307 #if ADB_HOST
    308         func = server_socket_thread;
    309 #else
    310         /* For the adbd daemon in the system image we need to distinguish
    311          * between the device, and the emulator. */
    312         char is_qemu[PROPERTY_VALUE_MAX];
    313         property_get("ro.kernel.qemu", is_qemu, "");
    314         if (!strcmp(is_qemu, "1")) {
    315             /* Running inside the emulator: use QEMUD pipe as the transport. */
    316             func = qemu_socket_thread;
    317         } else {
    318             /* Running inside the device: use TCP socket as the transport. */
    319             func = server_socket_thread;
    320         }
    321 #endif // !ADB_HOST
    322     }
    323 
    324     D("transport: local %s init\n", HOST ? "client" : "server");
    325 
    326     if(adb_thread_create(&thr, func, (void *)port)) {
    327         fatal_errno("cannot create local socket %s thread",
    328                     HOST ? "client" : "server");
    329     }
    330 }
    331 
    332 static void remote_kick(atransport *t)
    333 {
    334     int fd = t->sfd;
    335     t->sfd = -1;
    336     adb_shutdown(fd);
    337     adb_close(fd);
    338 
    339 #if ADB_HOST
    340     if(HOST) {
    341         int  nn;
    342         adb_mutex_lock( &local_transports_lock );
    343         for (nn = 0; nn < ADB_LOCAL_TRANSPORT_MAX; nn++) {
    344             if (local_transports[nn] == t) {
    345                 local_transports[nn] = NULL;
    346                 break;
    347             }
    348         }
    349         adb_mutex_unlock( &local_transports_lock );
    350     }
    351 #endif
    352 }
    353 
    354 static void remote_close(atransport *t)
    355 {
    356     adb_close(t->fd);
    357 }
    358 
    359 
    360 #if ADB_HOST
    361 /* Only call this function if you already hold local_transports_lock. */
    362 atransport* find_emulator_transport_by_adb_port_locked(int adb_port)
    363 {
    364     int i;
    365     for (i = 0; i < ADB_LOCAL_TRANSPORT_MAX; i++) {
    366         if (local_transports[i] && local_transports[i]->adb_port == adb_port) {
    367             return local_transports[i];
    368         }
    369     }
    370     return NULL;
    371 }
    372 
    373 atransport* find_emulator_transport_by_adb_port(int adb_port)
    374 {
    375     adb_mutex_lock( &local_transports_lock );
    376     atransport* result = find_emulator_transport_by_adb_port_locked(adb_port);
    377     adb_mutex_unlock( &local_transports_lock );
    378     return result;
    379 }
    380 
    381 /* Only call this function if you already hold local_transports_lock. */
    382 int get_available_local_transport_index_locked()
    383 {
    384     int i;
    385     for (i = 0; i < ADB_LOCAL_TRANSPORT_MAX; i++) {
    386         if (local_transports[i] == NULL) {
    387             return i;
    388         }
    389     }
    390     return -1;
    391 }
    392 
    393 int get_available_local_transport_index()
    394 {
    395     adb_mutex_lock( &local_transports_lock );
    396     int result = get_available_local_transport_index_locked();
    397     adb_mutex_unlock( &local_transports_lock );
    398     return result;
    399 }
    400 #endif
    401 
    402 int init_socket_transport(atransport *t, int s, int adb_port, int local)
    403 {
    404     int  fail = 0;
    405 
    406     t->kick = remote_kick;
    407     t->close = remote_close;
    408     t->read_from_remote = remote_read;
    409     t->write_to_remote = remote_write;
    410     t->sfd = s;
    411     t->sync_token = 1;
    412     t->connection_state = CS_OFFLINE;
    413     t->type = kTransportLocal;
    414     t->adb_port = 0;
    415 
    416 #if ADB_HOST
    417     if (HOST && local) {
    418         adb_mutex_lock( &local_transports_lock );
    419         {
    420             t->adb_port = adb_port;
    421             atransport* existing_transport =
    422                     find_emulator_transport_by_adb_port_locked(adb_port);
    423             int index = get_available_local_transport_index_locked();
    424             if (existing_transport != NULL) {
    425                 D("local transport for port %d already registered (%p)?\n",
    426                 adb_port, existing_transport);
    427                 fail = -1;
    428             } else if (index < 0) {
    429                 // Too many emulators.
    430                 D("cannot register more emulators. Maximum is %d\n",
    431                         ADB_LOCAL_TRANSPORT_MAX);
    432                 fail = -1;
    433             } else {
    434                 local_transports[index] = t;
    435             }
    436        }
    437        adb_mutex_unlock( &local_transports_lock );
    438     }
    439 #endif
    440     return fail;
    441 }
    442