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