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