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