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 #define  TRACE_TAG   TRACE_ADB
     18 
     19 #include <stdio.h>
     20 #include <stdlib.h>
     21 #include <ctype.h>
     22 #include <stdarg.h>
     23 #include <errno.h>
     24 #include <stddef.h>
     25 #include <string.h>
     26 #include <time.h>
     27 #include <sys/time.h>
     28 #include <stdint.h>
     29 
     30 #include "sysdeps.h"
     31 #include "adb.h"
     32 #include "adb_auth.h"
     33 
     34 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
     35 
     36 #if !ADB_HOST
     37 #include <private/android_filesystem_config.h>
     38 #include <sys/capability.h>
     39 #include <linux/prctl.h>
     40 #include <sys/mount.h>
     41 #else
     42 #include "usb_vendors.h"
     43 #endif
     44 
     45 #if ADB_TRACE
     46 ADB_MUTEX_DEFINE( D_lock );
     47 #endif
     48 
     49 int HOST = 0;
     50 int gListenAll = 0;
     51 
     52 static int auth_enabled = 0;
     53 
     54 #if !ADB_HOST
     55 static const char *adb_device_banner = "device";
     56 #endif
     57 
     58 void fatal(const char *fmt, ...)
     59 {
     60     va_list ap;
     61     va_start(ap, fmt);
     62     fprintf(stderr, "error: ");
     63     vfprintf(stderr, fmt, ap);
     64     fprintf(stderr, "\n");
     65     va_end(ap);
     66     exit(-1);
     67 }
     68 
     69 void fatal_errno(const char *fmt, ...)
     70 {
     71     va_list ap;
     72     va_start(ap, fmt);
     73     fprintf(stderr, "error: %s: ", strerror(errno));
     74     vfprintf(stderr, fmt, ap);
     75     fprintf(stderr, "\n");
     76     va_end(ap);
     77     exit(-1);
     78 }
     79 
     80 int   adb_trace_mask;
     81 
     82 /* read a comma/space/colum/semi-column separated list of tags
     83  * from the ADB_TRACE environment variable and build the trace
     84  * mask from it. note that '1' and 'all' are special cases to
     85  * enable all tracing
     86  */
     87 void  adb_trace_init(void)
     88 {
     89     const char*  p = getenv("ADB_TRACE");
     90     const char*  q;
     91 
     92     static const struct {
     93         const char*  tag;
     94         int           flag;
     95     } tags[] = {
     96         { "1", 0 },
     97         { "all", 0 },
     98         { "adb", TRACE_ADB },
     99         { "sockets", TRACE_SOCKETS },
    100         { "packets", TRACE_PACKETS },
    101         { "rwx", TRACE_RWX },
    102         { "usb", TRACE_USB },
    103         { "sync", TRACE_SYNC },
    104         { "sysdeps", TRACE_SYSDEPS },
    105         { "transport", TRACE_TRANSPORT },
    106         { "jdwp", TRACE_JDWP },
    107         { "services", TRACE_SERVICES },
    108         { "auth", TRACE_AUTH },
    109         { NULL, 0 }
    110     };
    111 
    112     if (p == NULL)
    113             return;
    114 
    115     /* use a comma/column/semi-colum/space separated list */
    116     while (*p) {
    117         int  len, tagn;
    118 
    119         q = strpbrk(p, " ,:;");
    120         if (q == NULL) {
    121             q = p + strlen(p);
    122         }
    123         len = q - p;
    124 
    125         for (tagn = 0; tags[tagn].tag != NULL; tagn++)
    126         {
    127             int  taglen = strlen(tags[tagn].tag);
    128 
    129             if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
    130             {
    131                 int  flag = tags[tagn].flag;
    132                 if (flag == 0) {
    133                     adb_trace_mask = ~0;
    134                     return;
    135                 }
    136                 adb_trace_mask |= (1 << flag);
    137                 break;
    138             }
    139         }
    140         p = q;
    141         if (*p)
    142             p++;
    143     }
    144 }
    145 
    146 #if !ADB_HOST
    147 /*
    148  * Implements ADB tracing inside the emulator.
    149  */
    150 
    151 #include <stdarg.h>
    152 
    153 /*
    154  * Redefine open and write for qemu_pipe.h that contains inlined references
    155  * to those routines. We will redifine them back after qemu_pipe.h inclusion.
    156  */
    157 
    158 #undef open
    159 #undef write
    160 #define open    adb_open
    161 #define write   adb_write
    162 #include <hardware/qemu_pipe.h>
    163 #undef open
    164 #undef write
    165 #define open    ___xxx_open
    166 #define write   ___xxx_write
    167 
    168 /* A handle to adb-debug qemud service in the emulator. */
    169 int   adb_debug_qemu = -1;
    170 
    171 /* Initializes connection with the adb-debug qemud service in the emulator. */
    172 static int adb_qemu_trace_init(void)
    173 {
    174     char con_name[32];
    175 
    176     if (adb_debug_qemu >= 0) {
    177         return 0;
    178     }
    179 
    180     /* adb debugging QEMUD service connection request. */
    181     snprintf(con_name, sizeof(con_name), "qemud:adb-debug");
    182     adb_debug_qemu = qemu_pipe_open(con_name);
    183     return (adb_debug_qemu >= 0) ? 0 : -1;
    184 }
    185 
    186 void adb_qemu_trace(const char* fmt, ...)
    187 {
    188     va_list args;
    189     va_start(args, fmt);
    190     char msg[1024];
    191 
    192     if (adb_debug_qemu >= 0) {
    193         vsnprintf(msg, sizeof(msg), fmt, args);
    194         adb_write(adb_debug_qemu, msg, strlen(msg));
    195     }
    196 }
    197 #endif  /* !ADB_HOST */
    198 
    199 apacket *get_apacket(void)
    200 {
    201     apacket *p = malloc(sizeof(apacket));
    202     if(p == 0) fatal("failed to allocate an apacket");
    203     memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
    204     return p;
    205 }
    206 
    207 void put_apacket(apacket *p)
    208 {
    209     free(p);
    210 }
    211 
    212 void handle_online(atransport *t)
    213 {
    214     D("adb: online\n");
    215     t->online = 1;
    216 }
    217 
    218 void handle_offline(atransport *t)
    219 {
    220     D("adb: offline\n");
    221     //Close the associated usb
    222     t->online = 0;
    223     run_transport_disconnects(t);
    224 }
    225 
    226 #if DEBUG_PACKETS
    227 #define DUMPMAX 32
    228 void print_packet(const char *label, apacket *p)
    229 {
    230     char *tag;
    231     char *x;
    232     unsigned count;
    233 
    234     switch(p->msg.command){
    235     case A_SYNC: tag = "SYNC"; break;
    236     case A_CNXN: tag = "CNXN" ; break;
    237     case A_OPEN: tag = "OPEN"; break;
    238     case A_OKAY: tag = "OKAY"; break;
    239     case A_CLSE: tag = "CLSE"; break;
    240     case A_WRTE: tag = "WRTE"; break;
    241     case A_AUTH: tag = "AUTH"; break;
    242     default: tag = "????"; break;
    243     }
    244 
    245     fprintf(stderr, "%s: %s %08x %08x %04x \"",
    246             label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
    247     count = p->msg.data_length;
    248     x = (char*) p->data;
    249     if(count > DUMPMAX) {
    250         count = DUMPMAX;
    251         tag = "\n";
    252     } else {
    253         tag = "\"\n";
    254     }
    255     while(count-- > 0){
    256         if((*x >= ' ') && (*x < 127)) {
    257             fputc(*x, stderr);
    258         } else {
    259             fputc('.', stderr);
    260         }
    261         x++;
    262     }
    263     fputs(tag, stderr);
    264 }
    265 #endif
    266 
    267 static void send_ready(unsigned local, unsigned remote, atransport *t)
    268 {
    269     D("Calling send_ready \n");
    270     apacket *p = get_apacket();
    271     p->msg.command = A_OKAY;
    272     p->msg.arg0 = local;
    273     p->msg.arg1 = remote;
    274     send_packet(p, t);
    275 }
    276 
    277 static void send_close(unsigned local, unsigned remote, atransport *t)
    278 {
    279     D("Calling send_close \n");
    280     apacket *p = get_apacket();
    281     p->msg.command = A_CLSE;
    282     p->msg.arg0 = local;
    283     p->msg.arg1 = remote;
    284     send_packet(p, t);
    285 }
    286 
    287 static size_t fill_connect_data(char *buf, size_t bufsize)
    288 {
    289 #if ADB_HOST
    290     return snprintf(buf, bufsize, "host::") + 1;
    291 #else
    292     static const char *cnxn_props[] = {
    293         "ro.product.name",
    294         "ro.product.model",
    295         "ro.product.device",
    296     };
    297     static const int num_cnxn_props = ARRAY_SIZE(cnxn_props);
    298     int i;
    299     size_t remaining = bufsize;
    300     size_t len;
    301 
    302     len = snprintf(buf, remaining, "%s::", adb_device_banner);
    303     remaining -= len;
    304     buf += len;
    305     for (i = 0; i < num_cnxn_props; i++) {
    306         char value[PROPERTY_VALUE_MAX];
    307         property_get(cnxn_props[i], value, "");
    308         len = snprintf(buf, remaining, "%s=%s;", cnxn_props[i], value);
    309         remaining -= len;
    310         buf += len;
    311     }
    312 
    313     return bufsize - remaining + 1;
    314 #endif
    315 }
    316 
    317 static void send_connect(atransport *t)
    318 {
    319     D("Calling send_connect \n");
    320     apacket *cp = get_apacket();
    321     cp->msg.command = A_CNXN;
    322     cp->msg.arg0 = A_VERSION;
    323     cp->msg.arg1 = MAX_PAYLOAD;
    324     cp->msg.data_length = fill_connect_data((char *)cp->data,
    325                                             sizeof(cp->data));
    326     send_packet(cp, t);
    327 }
    328 
    329 void send_auth_request(atransport *t)
    330 {
    331     D("Calling send_auth_request\n");
    332     apacket *p;
    333     int ret;
    334 
    335     ret = adb_auth_generate_token(t->token, sizeof(t->token));
    336     if (ret != sizeof(t->token)) {
    337         D("Error generating token ret=%d\n", ret);
    338         return;
    339     }
    340 
    341     p = get_apacket();
    342     memcpy(p->data, t->token, ret);
    343     p->msg.command = A_AUTH;
    344     p->msg.arg0 = ADB_AUTH_TOKEN;
    345     p->msg.data_length = ret;
    346     send_packet(p, t);
    347 }
    348 
    349 static void send_auth_response(uint8_t *token, size_t token_size, atransport *t)
    350 {
    351     D("Calling send_auth_response\n");
    352     apacket *p = get_apacket();
    353     int ret;
    354 
    355     ret = adb_auth_sign(t->key, token, token_size, p->data);
    356     if (!ret) {
    357         D("Error signing the token\n");
    358         put_apacket(p);
    359         return;
    360     }
    361 
    362     p->msg.command = A_AUTH;
    363     p->msg.arg0 = ADB_AUTH_SIGNATURE;
    364     p->msg.data_length = ret;
    365     send_packet(p, t);
    366 }
    367 
    368 static void send_auth_publickey(atransport *t)
    369 {
    370     D("Calling send_auth_publickey\n");
    371     apacket *p = get_apacket();
    372     int ret;
    373 
    374     ret = adb_auth_get_userkey(p->data, sizeof(p->data));
    375     if (!ret) {
    376         D("Failed to get user public key\n");
    377         put_apacket(p);
    378         return;
    379     }
    380 
    381     p->msg.command = A_AUTH;
    382     p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
    383     p->msg.data_length = ret;
    384     send_packet(p, t);
    385 }
    386 
    387 void adb_auth_verified(atransport *t)
    388 {
    389     handle_online(t);
    390     send_connect(t);
    391 }
    392 
    393 static char *connection_state_name(atransport *t)
    394 {
    395     if (t == NULL) {
    396         return "unknown";
    397     }
    398 
    399     switch(t->connection_state) {
    400     case CS_BOOTLOADER:
    401         return "bootloader";
    402     case CS_DEVICE:
    403         return "device";
    404     case CS_OFFLINE:
    405         return "offline";
    406     case CS_UNAUTHORIZED:
    407         return "unauthorized";
    408     default:
    409         return "unknown";
    410     }
    411 }
    412 
    413 /* qual_overwrite is used to overwrite a qualifier string.  dst is a
    414  * pointer to a char pointer.  It is assumed that if *dst is non-NULL, it
    415  * was malloc'ed and needs to freed.  *dst will be set to a dup of src.
    416  */
    417 static void qual_overwrite(char **dst, const char *src)
    418 {
    419     if (!dst)
    420         return;
    421 
    422     free(*dst);
    423     *dst = NULL;
    424 
    425     if (!src || !*src)
    426         return;
    427 
    428     *dst = strdup(src);
    429 }
    430 
    431 void parse_banner(char *banner, atransport *t)
    432 {
    433     static const char *prop_seps = ";";
    434     static const char key_val_sep = '=';
    435     char *cp;
    436     char *type;
    437 
    438     D("parse_banner: %s\n", banner);
    439     type = banner;
    440     cp = strchr(type, ':');
    441     if (cp) {
    442         *cp++ = 0;
    443         /* Nothing is done with second field. */
    444         cp = strchr(cp, ':');
    445         if (cp) {
    446             char *save;
    447             char *key;
    448             key = adb_strtok_r(cp + 1, prop_seps, &save);
    449             while (key) {
    450                 cp = strchr(key, key_val_sep);
    451                 if (cp) {
    452                     *cp++ = '\0';
    453                     if (!strcmp(key, "ro.product.name"))
    454                         qual_overwrite(&t->product, cp);
    455                     else if (!strcmp(key, "ro.product.model"))
    456                         qual_overwrite(&t->model, cp);
    457                     else if (!strcmp(key, "ro.product.device"))
    458                         qual_overwrite(&t->device, cp);
    459                 }
    460                 key = adb_strtok_r(NULL, prop_seps, &save);
    461             }
    462         }
    463     }
    464 
    465     if(!strcmp(type, "bootloader")){
    466         D("setting connection_state to CS_BOOTLOADER\n");
    467         t->connection_state = CS_BOOTLOADER;
    468         update_transports();
    469         return;
    470     }
    471 
    472     if(!strcmp(type, "device")) {
    473         D("setting connection_state to CS_DEVICE\n");
    474         t->connection_state = CS_DEVICE;
    475         update_transports();
    476         return;
    477     }
    478 
    479     if(!strcmp(type, "recovery")) {
    480         D("setting connection_state to CS_RECOVERY\n");
    481         t->connection_state = CS_RECOVERY;
    482         update_transports();
    483         return;
    484     }
    485 
    486     if(!strcmp(type, "sideload")) {
    487         D("setting connection_state to CS_SIDELOAD\n");
    488         t->connection_state = CS_SIDELOAD;
    489         update_transports();
    490         return;
    491     }
    492 
    493     t->connection_state = CS_HOST;
    494 }
    495 
    496 void handle_packet(apacket *p, atransport *t)
    497 {
    498     asocket *s;
    499 
    500     D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
    501             ((char*) (&(p->msg.command)))[1],
    502             ((char*) (&(p->msg.command)))[2],
    503             ((char*) (&(p->msg.command)))[3]);
    504     print_packet("recv", p);
    505 
    506     switch(p->msg.command){
    507     case A_SYNC:
    508         if(p->msg.arg0){
    509             send_packet(p, t);
    510             if(HOST) send_connect(t);
    511         } else {
    512             t->connection_state = CS_OFFLINE;
    513             handle_offline(t);
    514             send_packet(p, t);
    515         }
    516         return;
    517 
    518     case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
    519             /* XXX verify version, etc */
    520         if(t->connection_state != CS_OFFLINE) {
    521             t->connection_state = CS_OFFLINE;
    522             handle_offline(t);
    523         }
    524 
    525         parse_banner((char*) p->data, t);
    526 
    527         if (HOST || !auth_enabled) {
    528             handle_online(t);
    529             if(!HOST) send_connect(t);
    530         } else {
    531             send_auth_request(t);
    532         }
    533         break;
    534 
    535     case A_AUTH:
    536         if (p->msg.arg0 == ADB_AUTH_TOKEN) {
    537             t->connection_state = CS_UNAUTHORIZED;
    538             t->key = adb_auth_nextkey(t->key);
    539             if (t->key) {
    540                 send_auth_response(p->data, p->msg.data_length, t);
    541             } else {
    542                 /* No more private keys to try, send the public key */
    543                 send_auth_publickey(t);
    544             }
    545         } else if (p->msg.arg0 == ADB_AUTH_SIGNATURE) {
    546             if (adb_auth_verify(t->token, p->data, p->msg.data_length)) {
    547                 adb_auth_verified(t);
    548                 t->failed_auth_attempts = 0;
    549             } else {
    550                 if (t->failed_auth_attempts++ > 10)
    551                     adb_sleep_ms(1000);
    552                 send_auth_request(t);
    553             }
    554         } else if (p->msg.arg0 == ADB_AUTH_RSAPUBLICKEY) {
    555             adb_auth_confirm_key(p->data, p->msg.data_length, t);
    556         }
    557         break;
    558 
    559     case A_OPEN: /* OPEN(local-id, 0, "destination") */
    560         if (t->online) {
    561             char *name = (char*) p->data;
    562             name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
    563             s = create_local_service_socket(name);
    564             if(s == 0) {
    565                 send_close(0, p->msg.arg0, t);
    566             } else {
    567                 s->peer = create_remote_socket(p->msg.arg0, t);
    568                 s->peer->peer = s;
    569                 send_ready(s->id, s->peer->id, t);
    570                 s->ready(s);
    571             }
    572         }
    573         break;
    574 
    575     case A_OKAY: /* READY(local-id, remote-id, "") */
    576         if (t->online) {
    577             if((s = find_local_socket(p->msg.arg1))) {
    578                 if(s->peer == 0) {
    579                     s->peer = create_remote_socket(p->msg.arg0, t);
    580                     s->peer->peer = s;
    581                 }
    582                 s->ready(s);
    583             }
    584         }
    585         break;
    586 
    587     case A_CLSE: /* CLOSE(local-id, remote-id, "") */
    588         if (t->online) {
    589             if((s = find_local_socket(p->msg.arg1))) {
    590                 s->close(s);
    591             }
    592         }
    593         break;
    594 
    595     case A_WRTE:
    596         if (t->online) {
    597             if((s = find_local_socket(p->msg.arg1))) {
    598                 unsigned rid = p->msg.arg0;
    599                 p->len = p->msg.data_length;
    600 
    601                 if(s->enqueue(s, p) == 0) {
    602                     D("Enqueue the socket\n");
    603                     send_ready(s->id, rid, t);
    604                 }
    605                 return;
    606             }
    607         }
    608         break;
    609 
    610     default:
    611         printf("handle_packet: what is %08x?!\n", p->msg.command);
    612     }
    613 
    614     put_apacket(p);
    615 }
    616 
    617 alistener listener_list = {
    618     .next = &listener_list,
    619     .prev = &listener_list,
    620 };
    621 
    622 static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
    623 {
    624     asocket *s;
    625 
    626     if(ev & FDE_READ) {
    627         struct sockaddr addr;
    628         socklen_t alen;
    629         int fd;
    630 
    631         alen = sizeof(addr);
    632         fd = adb_socket_accept(_fd, &addr, &alen);
    633         if(fd < 0) return;
    634 
    635         adb_socket_setbufsize(fd, CHUNK_SIZE);
    636 
    637         s = create_local_socket(fd);
    638         if(s) {
    639             connect_to_smartsocket(s);
    640             return;
    641         }
    642 
    643         adb_close(fd);
    644     }
    645 }
    646 
    647 static void listener_event_func(int _fd, unsigned ev, void *_l)
    648 {
    649     alistener *l = _l;
    650     asocket *s;
    651 
    652     if(ev & FDE_READ) {
    653         struct sockaddr addr;
    654         socklen_t alen;
    655         int fd;
    656 
    657         alen = sizeof(addr);
    658         fd = adb_socket_accept(_fd, &addr, &alen);
    659         if(fd < 0) return;
    660 
    661         s = create_local_socket(fd);
    662         if(s) {
    663             s->transport = l->transport;
    664             connect_to_remote(s, l->connect_to);
    665             return;
    666         }
    667 
    668         adb_close(fd);
    669     }
    670 }
    671 
    672 static void  free_listener(alistener*  l)
    673 {
    674     if (l->next) {
    675         l->next->prev = l->prev;
    676         l->prev->next = l->next;
    677         l->next = l->prev = l;
    678     }
    679 
    680     // closes the corresponding fd
    681     fdevent_remove(&l->fde);
    682 
    683     if (l->local_name)
    684         free((char*)l->local_name);
    685 
    686     if (l->connect_to)
    687         free((char*)l->connect_to);
    688 
    689     if (l->transport) {
    690         remove_transport_disconnect(l->transport, &l->disconnect);
    691     }
    692     free(l);
    693 }
    694 
    695 static void listener_disconnect(void*  _l, atransport*  t)
    696 {
    697     alistener*  l = _l;
    698 
    699     free_listener(l);
    700 }
    701 
    702 int local_name_to_fd(const char *name)
    703 {
    704     int port;
    705 
    706     if(!strncmp("tcp:", name, 4)){
    707         int  ret;
    708         port = atoi(name + 4);
    709 
    710         if (gListenAll > 0) {
    711             ret = socket_inaddr_any_server(port, SOCK_STREAM);
    712         } else {
    713             ret = socket_loopback_server(port, SOCK_STREAM);
    714         }
    715 
    716         return ret;
    717     }
    718 #ifndef HAVE_WIN32_IPC  /* no Unix-domain sockets on Win32 */
    719     // It's non-sensical to support the "reserved" space on the adb host side
    720     if(!strncmp(name, "local:", 6)) {
    721         return socket_local_server(name + 6,
    722                 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
    723     } else if(!strncmp(name, "localabstract:", 14)) {
    724         return socket_local_server(name + 14,
    725                 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
    726     } else if(!strncmp(name, "localfilesystem:", 16)) {
    727         return socket_local_server(name + 16,
    728                 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
    729     }
    730 
    731 #endif
    732     printf("unknown local portname '%s'\n", name);
    733     return -1;
    734 }
    735 
    736 // Write a single line describing a listener to a user-provided buffer.
    737 // Appends a trailing zero, even in case of truncation, but the function
    738 // returns the full line length.
    739 // If |buffer| is NULL, does not write but returns required size.
    740 static int format_listener(alistener* l, char* buffer, size_t buffer_len) {
    741     // Format is simply:
    742     //
    743     //  <device-serial> " " <local-name> " " <remote-name> "\n"
    744     //
    745     int local_len = strlen(l->local_name);
    746     int connect_len = strlen(l->connect_to);
    747     int serial_len = strlen(l->transport->serial);
    748 
    749     if (buffer != NULL) {
    750         snprintf(buffer, buffer_len, "%s %s %s\n",
    751                 l->transport->serial, l->local_name, l->connect_to);
    752     }
    753     // NOTE: snprintf() on Windows returns -1 in case of truncation, so
    754     // return the computed line length instead.
    755     return local_len + connect_len + serial_len + 3;
    756 }
    757 
    758 // Write the list of current listeners (network redirections) into a
    759 // user-provided buffer. Appends a trailing zero, even in case of
    760 // trunctaion, but return the full size in bytes.
    761 // If |buffer| is NULL, does not write but returns required size.
    762 static int format_listeners(char* buf, size_t buflen)
    763 {
    764     alistener* l;
    765     int result = 0;
    766     for (l = listener_list.next; l != &listener_list; l = l->next) {
    767         // Ignore special listeners like those for *smartsocket*
    768         if (l->connect_to[0] == '*')
    769           continue;
    770         int len = format_listener(l, buf, buflen);
    771         // Ensure there is space for the trailing zero.
    772         result += len;
    773         if (buf != NULL) {
    774           buf += len;
    775           buflen -= len;
    776           if (buflen <= 0)
    777               break;
    778         }
    779     }
    780     return result;
    781 }
    782 
    783 static int remove_listener(const char *local_name, atransport* transport)
    784 {
    785     alistener *l;
    786 
    787     for (l = listener_list.next; l != &listener_list; l = l->next) {
    788         if (!strcmp(local_name, l->local_name)) {
    789             listener_disconnect(l, l->transport);
    790             return 0;
    791         }
    792     }
    793     return -1;
    794 }
    795 
    796 static void remove_all_listeners(void)
    797 {
    798     alistener *l, *l_next;
    799     for (l = listener_list.next; l != &listener_list; l = l_next) {
    800         l_next = l->next;
    801         // Never remove smart sockets.
    802         if (l->connect_to[0] == '*')
    803             continue;
    804         listener_disconnect(l, l->transport);
    805     }
    806 }
    807 
    808 // error/status codes for install_listener.
    809 typedef enum {
    810   INSTALL_STATUS_OK = 0,
    811   INSTALL_STATUS_INTERNAL_ERROR = -1,
    812   INSTALL_STATUS_CANNOT_BIND = -2,
    813   INSTALL_STATUS_CANNOT_REBIND = -3,
    814 } install_status_t;
    815 
    816 static install_status_t install_listener(const char *local_name,
    817                                          const char *connect_to,
    818                                          atransport* transport,
    819                                          int no_rebind)
    820 {
    821     alistener *l;
    822 
    823     //printf("install_listener('%s','%s')\n", local_name, connect_to);
    824 
    825     for(l = listener_list.next; l != &listener_list; l = l->next){
    826         if(strcmp(local_name, l->local_name) == 0) {
    827             char *cto;
    828 
    829                 /* can't repurpose a smartsocket */
    830             if(l->connect_to[0] == '*') {
    831                 return INSTALL_STATUS_INTERNAL_ERROR;
    832             }
    833 
    834                 /* can't repurpose a listener if 'no_rebind' is true */
    835             if (no_rebind) {
    836                 return INSTALL_STATUS_CANNOT_REBIND;
    837             }
    838 
    839             cto = strdup(connect_to);
    840             if(cto == 0) {
    841                 return INSTALL_STATUS_INTERNAL_ERROR;
    842             }
    843 
    844             //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
    845             free((void*) l->connect_to);
    846             l->connect_to = cto;
    847             if (l->transport != transport) {
    848                 remove_transport_disconnect(l->transport, &l->disconnect);
    849                 l->transport = transport;
    850                 add_transport_disconnect(l->transport, &l->disconnect);
    851             }
    852             return INSTALL_STATUS_OK;
    853         }
    854     }
    855 
    856     if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
    857     if((l->local_name = strdup(local_name)) == 0) goto nomem;
    858     if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
    859 
    860 
    861     l->fd = local_name_to_fd(local_name);
    862     if(l->fd < 0) {
    863         free((void*) l->local_name);
    864         free((void*) l->connect_to);
    865         free(l);
    866         printf("cannot bind '%s'\n", local_name);
    867         return -2;
    868     }
    869 
    870     close_on_exec(l->fd);
    871     if(!strcmp(l->connect_to, "*smartsocket*")) {
    872         fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
    873     } else {
    874         fdevent_install(&l->fde, l->fd, listener_event_func, l);
    875     }
    876     fdevent_set(&l->fde, FDE_READ);
    877 
    878     l->next = &listener_list;
    879     l->prev = listener_list.prev;
    880     l->next->prev = l;
    881     l->prev->next = l;
    882     l->transport = transport;
    883 
    884     if (transport) {
    885         l->disconnect.opaque = l;
    886         l->disconnect.func   = listener_disconnect;
    887         add_transport_disconnect(transport, &l->disconnect);
    888     }
    889     return INSTALL_STATUS_OK;
    890 
    891 nomem:
    892     fatal("cannot allocate listener");
    893     return INSTALL_STATUS_INTERNAL_ERROR;
    894 }
    895 
    896 #ifdef HAVE_WIN32_PROC
    897 static BOOL WINAPI ctrlc_handler(DWORD type)
    898 {
    899     exit(STATUS_CONTROL_C_EXIT);
    900     return TRUE;
    901 }
    902 #endif
    903 
    904 static void adb_cleanup(void)
    905 {
    906     usb_cleanup();
    907 }
    908 
    909 void start_logging(void)
    910 {
    911 #ifdef HAVE_WIN32_PROC
    912     char    temp[ MAX_PATH ];
    913     FILE*   fnul;
    914     FILE*   flog;
    915 
    916     GetTempPath( sizeof(temp) - 8, temp );
    917     strcat( temp, "adb.log" );
    918 
    919     /* Win32 specific redirections */
    920     fnul = fopen( "NUL", "rt" );
    921     if (fnul != NULL)
    922         stdin[0] = fnul[0];
    923 
    924     flog = fopen( temp, "at" );
    925     if (flog == NULL)
    926         flog = fnul;
    927 
    928     setvbuf( flog, NULL, _IONBF, 0 );
    929 
    930     stdout[0] = flog[0];
    931     stderr[0] = flog[0];
    932     fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
    933 #else
    934     int fd;
    935 
    936     fd = unix_open("/dev/null", O_RDONLY);
    937     dup2(fd, 0);
    938     adb_close(fd);
    939 
    940     fd = unix_open("/tmp/adb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
    941     if(fd < 0) {
    942         fd = unix_open("/dev/null", O_WRONLY);
    943     }
    944     dup2(fd, 1);
    945     dup2(fd, 2);
    946     adb_close(fd);
    947     fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
    948 #endif
    949 }
    950 
    951 #if !ADB_HOST
    952 void start_device_log(void)
    953 {
    954     int fd;
    955     char    path[PATH_MAX];
    956     struct tm now;
    957     time_t t;
    958     char value[PROPERTY_VALUE_MAX];
    959 
    960     // read the trace mask from persistent property persist.adb.trace_mask
    961     // give up if the property is not set or cannot be parsed
    962     property_get("persist.adb.trace_mask", value, "");
    963     if (sscanf(value, "%x", &adb_trace_mask) != 1)
    964         return;
    965 
    966     adb_mkdir("/data/adb", 0775);
    967     tzset();
    968     time(&t);
    969     localtime_r(&t, &now);
    970     strftime(path, sizeof(path),
    971                 "/data/adb/adb-%Y-%m-%d-%H-%M-%S.txt",
    972                 &now);
    973     fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
    974     if (fd < 0)
    975         return;
    976 
    977     // redirect stdout and stderr to the log file
    978     dup2(fd, 1);
    979     dup2(fd, 2);
    980     fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
    981     adb_close(fd);
    982 
    983     fd = unix_open("/dev/null", O_RDONLY);
    984     dup2(fd, 0);
    985     adb_close(fd);
    986 }
    987 #endif
    988 
    989 #if ADB_HOST
    990 
    991 #ifdef WORKAROUND_BUG6558362
    992 #include <sched.h>
    993 #define AFFINITY_ENVVAR "ADB_CPU_AFFINITY_BUG6558362"
    994 void adb_set_affinity(void)
    995 {
    996    cpu_set_t cpu_set;
    997    const char* cpunum_str = getenv(AFFINITY_ENVVAR);
    998    char* strtol_res;
    999    int cpu_num;
   1000 
   1001    if (!cpunum_str || !*cpunum_str)
   1002        return;
   1003    cpu_num = strtol(cpunum_str, &strtol_res, 0);
   1004    if (*strtol_res != '\0')
   1005      fatal("bad number (%s) in env var %s. Expecting 0..n.\n", cpunum_str, AFFINITY_ENVVAR);
   1006 
   1007    sched_getaffinity(0, sizeof(cpu_set), &cpu_set);
   1008    D("orig cpu_set[0]=0x%08lx\n", cpu_set.__bits[0]);
   1009    CPU_ZERO(&cpu_set);
   1010    CPU_SET(cpu_num, &cpu_set);
   1011    sched_setaffinity(0, sizeof(cpu_set), &cpu_set);
   1012    sched_getaffinity(0, sizeof(cpu_set), &cpu_set);
   1013    D("new cpu_set[0]=0x%08lx\n", cpu_set.__bits[0]);
   1014 }
   1015 #endif
   1016 
   1017 int launch_server(int server_port)
   1018 {
   1019 #ifdef HAVE_WIN32_PROC
   1020     /* we need to start the server in the background                    */
   1021     /* we create a PIPE that will be used to wait for the server's "OK" */
   1022     /* message since the pipe handles must be inheritable, we use a     */
   1023     /* security attribute                                               */
   1024     HANDLE                pipe_read, pipe_write;
   1025     HANDLE                stdout_handle, stderr_handle;
   1026     SECURITY_ATTRIBUTES   sa;
   1027     STARTUPINFO           startup;
   1028     PROCESS_INFORMATION   pinfo;
   1029     char                  program_path[ MAX_PATH ];
   1030     int                   ret;
   1031 
   1032     sa.nLength = sizeof(sa);
   1033     sa.lpSecurityDescriptor = NULL;
   1034     sa.bInheritHandle = TRUE;
   1035 
   1036     /* create pipe, and ensure its read handle isn't inheritable */
   1037     ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
   1038     if (!ret) {
   1039         fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
   1040         return -1;
   1041     }
   1042 
   1043     SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
   1044 
   1045     /* Some programs want to launch an adb command and collect its output by
   1046      * calling CreateProcess with inheritable stdout/stderr handles, then
   1047      * using read() to get its output. When this happens, the stdout/stderr
   1048      * handles passed to the adb client process will also be inheritable.
   1049      * When starting the adb server here, care must be taken to reset them
   1050      * to non-inheritable.
   1051      * Otherwise, something bad happens: even if the adb command completes,
   1052      * the calling process is stuck while read()-ing from the stdout/stderr
   1053      * descriptors, because they're connected to corresponding handles in the
   1054      * adb server process (even if the latter never uses/writes to them).
   1055      */
   1056     stdout_handle = GetStdHandle( STD_OUTPUT_HANDLE );
   1057     stderr_handle = GetStdHandle( STD_ERROR_HANDLE );
   1058     if (stdout_handle != INVALID_HANDLE_VALUE) {
   1059         SetHandleInformation( stdout_handle, HANDLE_FLAG_INHERIT, 0 );
   1060     }
   1061     if (stderr_handle != INVALID_HANDLE_VALUE) {
   1062         SetHandleInformation( stderr_handle, HANDLE_FLAG_INHERIT, 0 );
   1063     }
   1064 
   1065     ZeroMemory( &startup, sizeof(startup) );
   1066     startup.cb = sizeof(startup);
   1067     startup.hStdInput  = GetStdHandle( STD_INPUT_HANDLE );
   1068     startup.hStdOutput = pipe_write;
   1069     startup.hStdError  = GetStdHandle( STD_ERROR_HANDLE );
   1070     startup.dwFlags    = STARTF_USESTDHANDLES;
   1071 
   1072     ZeroMemory( &pinfo, sizeof(pinfo) );
   1073 
   1074     /* get path of current program */
   1075     GetModuleFileName( NULL, program_path, sizeof(program_path) );
   1076 
   1077     ret = CreateProcess(
   1078             program_path,                              /* program path  */
   1079             "adb fork-server server",
   1080                                     /* the fork-server argument will set the
   1081                                        debug = 2 in the child           */
   1082             NULL,                   /* process handle is not inheritable */
   1083             NULL,                    /* thread handle is not inheritable */
   1084             TRUE,                          /* yes, inherit some handles */
   1085             DETACHED_PROCESS, /* the new process doesn't have a console */
   1086             NULL,                     /* use parent's environment block */
   1087             NULL,                    /* use parent's starting directory */
   1088             &startup,                 /* startup info, i.e. std handles */
   1089             &pinfo );
   1090 
   1091     CloseHandle( pipe_write );
   1092 
   1093     if (!ret) {
   1094         fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
   1095         CloseHandle( pipe_read );
   1096         return -1;
   1097     }
   1098 
   1099     CloseHandle( pinfo.hProcess );
   1100     CloseHandle( pinfo.hThread );
   1101 
   1102     /* wait for the "OK\n" message */
   1103     {
   1104         char  temp[3];
   1105         DWORD  count;
   1106 
   1107         ret = ReadFile( pipe_read, temp, 3, &count, NULL );
   1108         CloseHandle( pipe_read );
   1109         if ( !ret ) {
   1110             fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", GetLastError() );
   1111             return -1;
   1112         }
   1113         if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
   1114             fprintf(stderr, "ADB server didn't ACK\n" );
   1115             return -1;
   1116         }
   1117     }
   1118 #elif defined(HAVE_FORKEXEC)
   1119     char    path[PATH_MAX];
   1120     int     fd[2];
   1121 
   1122     // set up a pipe so the child can tell us when it is ready.
   1123     // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
   1124     if (pipe(fd)) {
   1125         fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
   1126         return -1;
   1127     }
   1128     get_my_path(path, PATH_MAX);
   1129     pid_t pid = fork();
   1130     if(pid < 0) return -1;
   1131 
   1132     if (pid == 0) {
   1133         // child side of the fork
   1134 
   1135         // redirect stderr to the pipe
   1136         // we use stderr instead of stdout due to stdout's buffering behavior.
   1137         adb_close(fd[0]);
   1138         dup2(fd[1], STDERR_FILENO);
   1139         adb_close(fd[1]);
   1140 
   1141         char str_port[30];
   1142         snprintf(str_port, sizeof(str_port), "%d",  server_port);
   1143         // child process
   1144         int result = execl(path, "adb", "-P", str_port, "fork-server", "server", NULL);
   1145         // this should not return
   1146         fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
   1147     } else  {
   1148         // parent side of the fork
   1149 
   1150         char  temp[3];
   1151 
   1152         temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
   1153         // wait for the "OK\n" message
   1154         adb_close(fd[1]);
   1155         int ret = adb_read(fd[0], temp, 3);
   1156         int saved_errno = errno;
   1157         adb_close(fd[0]);
   1158         if (ret < 0) {
   1159             fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", saved_errno);
   1160             return -1;
   1161         }
   1162         if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
   1163             fprintf(stderr, "ADB server didn't ACK\n" );
   1164             return -1;
   1165         }
   1166 
   1167         setsid();
   1168     }
   1169 #else
   1170 #error "cannot implement background server start on this platform"
   1171 #endif
   1172     return 0;
   1173 }
   1174 #endif
   1175 
   1176 /* Constructs a local name of form tcp:port.
   1177  * target_str points to the target string, it's content will be overwritten.
   1178  * target_size is the capacity of the target string.
   1179  * server_port is the port number to use for the local name.
   1180  */
   1181 void build_local_name(char* target_str, size_t target_size, int server_port)
   1182 {
   1183   snprintf(target_str, target_size, "tcp:%d", server_port);
   1184 }
   1185 
   1186 #if !ADB_HOST
   1187 
   1188 static void drop_capabilities_bounding_set_if_needed() {
   1189 #ifdef ALLOW_ADBD_ROOT
   1190     char value[PROPERTY_VALUE_MAX];
   1191     property_get("ro.debuggable", value, "");
   1192     if (strcmp(value, "1") == 0) {
   1193         return;
   1194     }
   1195 #endif
   1196     int i;
   1197     for (i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) {
   1198         if ((i == CAP_SETUID) || (i == CAP_SETGID)) {
   1199             // CAP_SETUID CAP_SETGID needed by /system/bin/run-as
   1200             continue;
   1201         }
   1202         int err = prctl(PR_CAPBSET_DROP, i, 0, 0, 0);
   1203 
   1204         // Some kernels don't have file capabilities compiled in, and
   1205         // prctl(PR_CAPBSET_DROP) returns EINVAL. Don't automatically
   1206         // die when we see such misconfigured kernels.
   1207         if ((err < 0) && (errno != EINVAL)) {
   1208             exit(1);
   1209         }
   1210     }
   1211 }
   1212 
   1213 static int should_drop_privileges() {
   1214 #ifndef ALLOW_ADBD_ROOT
   1215     return 1;
   1216 #else /* ALLOW_ADBD_ROOT */
   1217     int secure = 0;
   1218     char value[PROPERTY_VALUE_MAX];
   1219 
   1220    /* run adbd in secure mode if ro.secure is set and
   1221     ** we are not in the emulator
   1222     */
   1223     property_get("ro.kernel.qemu", value, "");
   1224     if (strcmp(value, "1") != 0) {
   1225         property_get("ro.secure", value, "1");
   1226         if (strcmp(value, "1") == 0) {
   1227             // don't run as root if ro.secure is set...
   1228             secure = 1;
   1229 
   1230             // ... except we allow running as root in userdebug builds if the
   1231             // service.adb.root property has been set by the "adb root" command
   1232             property_get("ro.debuggable", value, "");
   1233             if (strcmp(value, "1") == 0) {
   1234                 property_get("service.adb.root", value, "");
   1235                 if (strcmp(value, "1") == 0) {
   1236                     secure = 0;
   1237                 }
   1238             }
   1239         }
   1240     }
   1241     return secure;
   1242 #endif /* ALLOW_ADBD_ROOT */
   1243 }
   1244 #endif /* !ADB_HOST */
   1245 
   1246 int adb_main(int is_daemon, int server_port)
   1247 {
   1248 #if !ADB_HOST
   1249     int port;
   1250     char value[PROPERTY_VALUE_MAX];
   1251 
   1252     umask(000);
   1253 #endif
   1254 
   1255     atexit(adb_cleanup);
   1256 #ifdef HAVE_WIN32_PROC
   1257     SetConsoleCtrlHandler( ctrlc_handler, TRUE );
   1258 #elif defined(HAVE_FORKEXEC)
   1259     // No SIGCHLD. Let the service subproc handle its children.
   1260     signal(SIGPIPE, SIG_IGN);
   1261 #endif
   1262 
   1263     init_transport_registration();
   1264 
   1265 #if ADB_HOST
   1266     HOST = 1;
   1267 
   1268 #ifdef WORKAROUND_BUG6558362
   1269     if(is_daemon) adb_set_affinity();
   1270 #endif
   1271     usb_vendors_init();
   1272     usb_init();
   1273     local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
   1274     adb_auth_init();
   1275 
   1276     char local_name[30];
   1277     build_local_name(local_name, sizeof(local_name), server_port);
   1278     if(install_listener(local_name, "*smartsocket*", NULL, 0)) {
   1279         exit(1);
   1280     }
   1281 #else
   1282     property_get("ro.adb.secure", value, "0");
   1283     auth_enabled = !strcmp(value, "1");
   1284     if (auth_enabled)
   1285         adb_auth_init();
   1286 
   1287     // Our external storage path may be different than apps, since
   1288     // we aren't able to bind mount after dropping root.
   1289     const char* adb_external_storage = getenv("ADB_EXTERNAL_STORAGE");
   1290     if (NULL != adb_external_storage) {
   1291         setenv("EXTERNAL_STORAGE", adb_external_storage, 1);
   1292     } else {
   1293         D("Warning: ADB_EXTERNAL_STORAGE is not set.  Leaving EXTERNAL_STORAGE"
   1294           " unchanged.\n");
   1295     }
   1296 
   1297     /* don't listen on a port (default 5037) if running in secure mode */
   1298     /* don't run as root if we are running in secure mode */
   1299     if (should_drop_privileges()) {
   1300         struct __user_cap_header_struct header;
   1301         struct __user_cap_data_struct cap[2];
   1302 
   1303         if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
   1304             exit(1);
   1305         }
   1306 
   1307         drop_capabilities_bounding_set_if_needed();
   1308 
   1309         /* add extra groups:
   1310         ** AID_ADB to access the USB driver
   1311         ** AID_LOG to read system logs (adb logcat)
   1312         ** AID_INPUT to diagnose input issues (getevent)
   1313         ** AID_INET to diagnose network issues (netcfg, ping)
   1314         ** AID_GRAPHICS to access the frame buffer
   1315         ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
   1316         ** AID_SDCARD_R to allow reading from the SD card
   1317         ** AID_SDCARD_RW to allow writing to the SD card
   1318         ** AID_MOUNT to allow unmounting the SD card before rebooting
   1319         ** AID_NET_BW_STATS to read out qtaguid statistics
   1320         */
   1321         gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,
   1322                            AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
   1323                            AID_MOUNT, AID_NET_BW_STATS };
   1324         if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
   1325             exit(1);
   1326         }
   1327 
   1328         /* then switch user and group to "shell" */
   1329         if (setgid(AID_SHELL) != 0) {
   1330             exit(1);
   1331         }
   1332         if (setuid(AID_SHELL) != 0) {
   1333             exit(1);
   1334         }
   1335 
   1336         memset(&header, 0, sizeof(header));
   1337         memset(cap, 0, sizeof(cap));
   1338 
   1339         /* set CAP_SYS_BOOT capability, so "adb reboot" will succeed */
   1340         header.version = _LINUX_CAPABILITY_VERSION_3;
   1341         header.pid = 0;
   1342         cap[CAP_TO_INDEX(CAP_SYS_BOOT)].effective |= CAP_TO_MASK(CAP_SYS_BOOT);
   1343         cap[CAP_TO_INDEX(CAP_SYS_BOOT)].permitted |= CAP_TO_MASK(CAP_SYS_BOOT);
   1344         capset(&header, cap);
   1345 
   1346         D("Local port disabled\n");
   1347     } else {
   1348         char local_name[30];
   1349         build_local_name(local_name, sizeof(local_name), server_port);
   1350         if(install_listener(local_name, "*smartsocket*", NULL, 0)) {
   1351             exit(1);
   1352         }
   1353     }
   1354 
   1355     int usb = 0;
   1356     if (access(USB_ADB_PATH, F_OK) == 0 || access(USB_FFS_ADB_EP0, F_OK) == 0) {
   1357         // listen on USB
   1358         usb_init();
   1359         usb = 1;
   1360     }
   1361 
   1362     // If one of these properties is set, also listen on that port
   1363     // If one of the properties isn't set and we couldn't listen on usb,
   1364     // listen on the default port.
   1365     property_get("service.adb.tcp.port", value, "");
   1366     if (!value[0]) {
   1367         property_get("persist.adb.tcp.port", value, "");
   1368     }
   1369     if (sscanf(value, "%d", &port) == 1 && port > 0) {
   1370         printf("using port=%d\n", port);
   1371         // listen on TCP port specified by service.adb.tcp.port property
   1372         local_init(port);
   1373     } else if (!usb) {
   1374         // listen on default port
   1375         local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
   1376     }
   1377 
   1378     D("adb_main(): pre init_jdwp()\n");
   1379     init_jdwp();
   1380     D("adb_main(): post init_jdwp()\n");
   1381 #endif
   1382 
   1383     if (is_daemon)
   1384     {
   1385         // inform our parent that we are up and running.
   1386 #ifdef HAVE_WIN32_PROC
   1387         DWORD  count;
   1388         WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
   1389 #elif defined(HAVE_FORKEXEC)
   1390         fprintf(stderr, "OK\n");
   1391 #endif
   1392         start_logging();
   1393     }
   1394     D("Event loop starting\n");
   1395 
   1396     fdevent_loop();
   1397 
   1398     usb_cleanup();
   1399 
   1400     return 0;
   1401 }
   1402 
   1403 #if ADB_HOST
   1404 void connect_device(char* host, char* buffer, int buffer_size)
   1405 {
   1406     int port, fd;
   1407     char* portstr = strchr(host, ':');
   1408     char hostbuf[100];
   1409     char serial[100];
   1410 
   1411     strncpy(hostbuf, host, sizeof(hostbuf) - 1);
   1412     if (portstr) {
   1413         if (portstr - host >= (ptrdiff_t)sizeof(hostbuf)) {
   1414             snprintf(buffer, buffer_size, "bad host name %s", host);
   1415             return;
   1416         }
   1417         // zero terminate the host at the point we found the colon
   1418         hostbuf[portstr - host] = 0;
   1419         if (sscanf(portstr + 1, "%d", &port) == 0) {
   1420             snprintf(buffer, buffer_size, "bad port number %s", portstr);
   1421             return;
   1422         }
   1423     } else {
   1424         port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
   1425     }
   1426 
   1427     snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
   1428     if (find_transport(serial)) {
   1429         snprintf(buffer, buffer_size, "already connected to %s", serial);
   1430         return;
   1431     }
   1432 
   1433     fd = socket_network_client(hostbuf, port, SOCK_STREAM);
   1434     if (fd < 0) {
   1435         snprintf(buffer, buffer_size, "unable to connect to %s:%d", host, port);
   1436         return;
   1437     }
   1438 
   1439     D("client: connected on remote on fd %d\n", fd);
   1440     close_on_exec(fd);
   1441     disable_tcp_nagle(fd);
   1442     register_socket_transport(fd, serial, port, 0);
   1443     snprintf(buffer, buffer_size, "connected to %s", serial);
   1444 }
   1445 
   1446 void connect_emulator(char* port_spec, char* buffer, int buffer_size)
   1447 {
   1448     char* port_separator = strchr(port_spec, ',');
   1449     if (!port_separator) {
   1450         snprintf(buffer, buffer_size,
   1451                 "unable to parse '%s' as <console port>,<adb port>",
   1452                 port_spec);
   1453         return;
   1454     }
   1455 
   1456     // Zero-terminate console port and make port_separator point to 2nd port.
   1457     *port_separator++ = 0;
   1458     int console_port = strtol(port_spec, NULL, 0);
   1459     int adb_port = strtol(port_separator, NULL, 0);
   1460     if (!(console_port > 0 && adb_port > 0)) {
   1461         *(port_separator - 1) = ',';
   1462         snprintf(buffer, buffer_size,
   1463                 "Invalid port numbers: Expected positive numbers, got '%s'",
   1464                 port_spec);
   1465         return;
   1466     }
   1467 
   1468     /* Check if the emulator is already known.
   1469      * Note: There's a small but harmless race condition here: An emulator not
   1470      * present just yet could be registered by another invocation right
   1471      * after doing this check here. However, local_connect protects
   1472      * against double-registration too. From here, a better error message
   1473      * can be produced. In the case of the race condition, the very specific
   1474      * error message won't be shown, but the data doesn't get corrupted. */
   1475     atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
   1476     if (known_emulator != NULL) {
   1477         snprintf(buffer, buffer_size,
   1478                 "Emulator on port %d already registered.", adb_port);
   1479         return;
   1480     }
   1481 
   1482     /* Check if more emulators can be registered. Similar unproblematic
   1483      * race condition as above. */
   1484     int candidate_slot = get_available_local_transport_index();
   1485     if (candidate_slot < 0) {
   1486         snprintf(buffer, buffer_size, "Cannot accept more emulators.");
   1487         return;
   1488     }
   1489 
   1490     /* Preconditions met, try to connect to the emulator. */
   1491     if (!local_connect_arbitrary_ports(console_port, adb_port)) {
   1492         snprintf(buffer, buffer_size,
   1493                 "Connected to emulator on ports %d,%d", console_port, adb_port);
   1494     } else {
   1495         snprintf(buffer, buffer_size,
   1496                 "Could not connect to emulator on ports %d,%d",
   1497                 console_port, adb_port);
   1498     }
   1499 }
   1500 #endif
   1501 
   1502 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
   1503 {
   1504     atransport *transport = NULL;
   1505     char buf[4096];
   1506 
   1507     if(!strcmp(service, "kill")) {
   1508         fprintf(stderr,"adb server killed by remote request\n");
   1509         fflush(stdout);
   1510         adb_write(reply_fd, "OKAY", 4);
   1511         usb_cleanup();
   1512         exit(0);
   1513     }
   1514 
   1515 #if ADB_HOST
   1516     // "transport:" is used for switching transport with a specified serial number
   1517     // "transport-usb:" is used for switching transport to the only USB transport
   1518     // "transport-local:" is used for switching transport to the only local transport
   1519     // "transport-any:" is used for switching transport to the only transport
   1520     if (!strncmp(service, "transport", strlen("transport"))) {
   1521         char* error_string = "unknown failure";
   1522         transport_type type = kTransportAny;
   1523 
   1524         if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
   1525             type = kTransportUsb;
   1526         } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
   1527             type = kTransportLocal;
   1528         } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
   1529             type = kTransportAny;
   1530         } else if (!strncmp(service, "transport:", strlen("transport:"))) {
   1531             service += strlen("transport:");
   1532             serial = service;
   1533         }
   1534 
   1535         transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
   1536 
   1537         if (transport) {
   1538             s->transport = transport;
   1539             adb_write(reply_fd, "OKAY", 4);
   1540         } else {
   1541             sendfailmsg(reply_fd, error_string);
   1542         }
   1543         return 1;
   1544     }
   1545 
   1546     // return a list of all connected devices
   1547     if (!strncmp(service, "devices", 7)) {
   1548         char buffer[4096];
   1549         int use_long = !strcmp(service+7, "-l");
   1550         if (use_long || service[7] == 0) {
   1551             memset(buf, 0, sizeof(buf));
   1552             memset(buffer, 0, sizeof(buffer));
   1553             D("Getting device list \n");
   1554             list_transports(buffer, sizeof(buffer), use_long);
   1555             snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
   1556             D("Wrote device list \n");
   1557             writex(reply_fd, buf, strlen(buf));
   1558             return 0;
   1559         }
   1560     }
   1561 
   1562     // add a new TCP transport, device or emulator
   1563     if (!strncmp(service, "connect:", 8)) {
   1564         char buffer[4096];
   1565         char* host = service + 8;
   1566         if (!strncmp(host, "emu:", 4)) {
   1567             connect_emulator(host + 4, buffer, sizeof(buffer));
   1568         } else {
   1569             connect_device(host, buffer, sizeof(buffer));
   1570         }
   1571         // Send response for emulator and device
   1572         snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
   1573         writex(reply_fd, buf, strlen(buf));
   1574         return 0;
   1575     }
   1576 
   1577     // remove TCP transport
   1578     if (!strncmp(service, "disconnect:", 11)) {
   1579         char buffer[4096];
   1580         memset(buffer, 0, sizeof(buffer));
   1581         char* serial = service + 11;
   1582         if (serial[0] == 0) {
   1583             // disconnect from all TCP devices
   1584             unregister_all_tcp_transports();
   1585         } else {
   1586             char hostbuf[100];
   1587             // assume port 5555 if no port is specified
   1588             if (!strchr(serial, ':')) {
   1589                 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:5555", serial);
   1590                 serial = hostbuf;
   1591             }
   1592             atransport *t = find_transport(serial);
   1593 
   1594             if (t) {
   1595                 unregister_transport(t);
   1596             } else {
   1597                 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
   1598             }
   1599         }
   1600 
   1601         snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
   1602         writex(reply_fd, buf, strlen(buf));
   1603         return 0;
   1604     }
   1605 
   1606     // returns our value for ADB_SERVER_VERSION
   1607     if (!strcmp(service, "version")) {
   1608         char version[12];
   1609         snprintf(version, sizeof version, "%04x", ADB_SERVER_VERSION);
   1610         snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
   1611         writex(reply_fd, buf, strlen(buf));
   1612         return 0;
   1613     }
   1614 
   1615     if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
   1616         char *out = "unknown";
   1617          transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
   1618        if (transport && transport->serial) {
   1619             out = transport->serial;
   1620         }
   1621         snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
   1622         writex(reply_fd, buf, strlen(buf));
   1623         return 0;
   1624     }
   1625     if(!strncmp(service,"get-devpath",strlen("get-devpath"))) {
   1626         char *out = "unknown";
   1627          transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
   1628        if (transport && transport->devpath) {
   1629             out = transport->devpath;
   1630         }
   1631         snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
   1632         writex(reply_fd, buf, strlen(buf));
   1633         return 0;
   1634     }
   1635     // indicates a new emulator instance has started
   1636     if (!strncmp(service,"emulator:",9)) {
   1637         int  port = atoi(service+9);
   1638         local_connect(port);
   1639         /* we don't even need to send a reply */
   1640         return 0;
   1641     }
   1642 #endif // ADB_HOST
   1643 
   1644     if(!strcmp(service,"list-forward")) {
   1645         // Create the list of forward redirections.
   1646         char header[9];
   1647         int buffer_size = format_listeners(NULL, 0);
   1648         // Add one byte for the trailing zero.
   1649         char* buffer = malloc(buffer_size+1);
   1650         (void) format_listeners(buffer, buffer_size+1);
   1651         snprintf(header, sizeof header, "OKAY%04x", buffer_size);
   1652         writex(reply_fd, header, 8);
   1653         writex(reply_fd, buffer, buffer_size);
   1654         free(buffer);
   1655         return 0;
   1656     }
   1657 
   1658     if (!strcmp(service,"killforward-all")) {
   1659         remove_all_listeners();
   1660         adb_write(reply_fd, "OKAYOKAY", 8);
   1661         return 0;
   1662     }
   1663 
   1664     if(!strncmp(service,"forward:",8) ||
   1665        !strncmp(service,"killforward:",12)) {
   1666         char *local, *remote, *err;
   1667         int r;
   1668         atransport *transport;
   1669 
   1670         int createForward = strncmp(service,"kill",4);
   1671         int no_rebind = 0;
   1672 
   1673         local = strchr(service, ':') + 1;
   1674 
   1675         // Handle forward:norebind:<local>... here
   1676         if (createForward && !strncmp(local, "norebind:", 9)) {
   1677             no_rebind = 1;
   1678             local = strchr(local, ':') + 1;
   1679         }
   1680 
   1681         remote = strchr(local,';');
   1682 
   1683         if (createForward) {
   1684             // Check forward: parameter format: '<local>;<remote>'
   1685             if(remote == 0) {
   1686                 sendfailmsg(reply_fd, "malformed forward spec");
   1687                 return 0;
   1688             }
   1689 
   1690             *remote++ = 0;
   1691             if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
   1692                 sendfailmsg(reply_fd, "malformed forward spec");
   1693                 return 0;
   1694             }
   1695         } else {
   1696             // Check killforward: parameter format: '<local>'
   1697             if (local[0] == 0) {
   1698                 sendfailmsg(reply_fd, "malformed forward spec");
   1699                 return 0;
   1700             }
   1701         }
   1702 
   1703         transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
   1704         if (!transport) {
   1705             sendfailmsg(reply_fd, err);
   1706             return 0;
   1707         }
   1708 
   1709         if (createForward) {
   1710             r = install_listener(local, remote, transport, no_rebind);
   1711         } else {
   1712             r = remove_listener(local, transport);
   1713         }
   1714         if(r == 0) {
   1715                 /* 1st OKAY is connect, 2nd OKAY is status */
   1716             writex(reply_fd, "OKAYOKAY", 8);
   1717             return 0;
   1718         }
   1719 
   1720         if (createForward) {
   1721             const char* message;
   1722             switch (r) {
   1723               case INSTALL_STATUS_CANNOT_BIND:
   1724                 message = "cannot bind to socket";
   1725                 break;
   1726               case INSTALL_STATUS_CANNOT_REBIND:
   1727                 message = "cannot rebind existing socket";
   1728                 break;
   1729               default:
   1730                 message = "internal error";
   1731             }
   1732             sendfailmsg(reply_fd, message);
   1733         } else {
   1734             sendfailmsg(reply_fd, "cannot remove listener");
   1735         }
   1736         return 0;
   1737     }
   1738 
   1739     if(!strncmp(service,"get-state",strlen("get-state"))) {
   1740         transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
   1741         char *state = connection_state_name(transport);
   1742         snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
   1743         writex(reply_fd, buf, strlen(buf));
   1744         return 0;
   1745     }
   1746     return -1;
   1747 }
   1748 
   1749 #if !ADB_HOST
   1750 int recovery_mode = 0;
   1751 #endif
   1752 
   1753 int main(int argc, char **argv)
   1754 {
   1755 #if ADB_HOST
   1756     adb_sysdeps_init();
   1757     adb_trace_init();
   1758     D("Handling commandline()\n");
   1759     return adb_commandline(argc - 1, argv + 1);
   1760 #else
   1761     /* If adbd runs inside the emulator this will enable adb tracing via
   1762      * adb-debug qemud service in the emulator. */
   1763     adb_qemu_trace_init();
   1764     if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
   1765         adb_device_banner = "recovery";
   1766         recovery_mode = 1;
   1767     }
   1768 
   1769     start_device_log();
   1770     D("Handling main()\n");
   1771     return adb_main(0, DEFAULT_ADB_PORT);
   1772 #endif
   1773 }
   1774