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