adb.c revision fd96db17b7f07eb6615af01fd1908b74383bf04b
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 <string.h>
25#include <time.h>
26#include <sys/time.h>
27
28#include "sysdeps.h"
29#include "adb.h"
30
31#if !ADB_HOST
32#include <private/android_filesystem_config.h>
33#include <linux/capability.h>
34#include <linux/prctl.h>
35#else
36#include "usb_vendors.h"
37#endif
38
39#if ADB_TRACE
40ADB_MUTEX_DEFINE( D_lock );
41#endif
42
43int HOST = 0;
44
45static const char *adb_device_banner = "device";
46
47void fatal(const char *fmt, ...)
48{
49    va_list ap;
50    va_start(ap, fmt);
51    fprintf(stderr, "error: ");
52    vfprintf(stderr, fmt, ap);
53    fprintf(stderr, "\n");
54    va_end(ap);
55    exit(-1);
56}
57
58void fatal_errno(const char *fmt, ...)
59{
60    va_list ap;
61    va_start(ap, fmt);
62    fprintf(stderr, "error: %s: ", strerror(errno));
63    vfprintf(stderr, fmt, ap);
64    fprintf(stderr, "\n");
65    va_end(ap);
66    exit(-1);
67}
68
69int   adb_trace_mask;
70
71/* read a comma/space/colum/semi-column separated list of tags
72 * from the ADB_TRACE environment variable and build the trace
73 * mask from it. note that '1' and 'all' are special cases to
74 * enable all tracing
75 */
76void  adb_trace_init(void)
77{
78    const char*  p = getenv("ADB_TRACE");
79    const char*  q;
80
81    static const struct {
82        const char*  tag;
83        int           flag;
84    } tags[] = {
85        { "1", 0 },
86        { "all", 0 },
87        { "adb", TRACE_ADB },
88        { "sockets", TRACE_SOCKETS },
89        { "packets", TRACE_PACKETS },
90        { "rwx", TRACE_RWX },
91        { "usb", TRACE_USB },
92        { "sync", TRACE_SYNC },
93        { "sysdeps", TRACE_SYSDEPS },
94        { "transport", TRACE_TRANSPORT },
95        { "jdwp", TRACE_JDWP },
96        { "services", TRACE_SERVICES },
97        { NULL, 0 }
98    };
99
100    if (p == NULL)
101            return;
102
103    /* use a comma/column/semi-colum/space separated list */
104    while (*p) {
105        int  len, tagn;
106
107        q = strpbrk(p, " ,:;");
108        if (q == NULL) {
109            q = p + strlen(p);
110        }
111        len = q - p;
112
113        for (tagn = 0; tags[tagn].tag != NULL; tagn++)
114        {
115            int  taglen = strlen(tags[tagn].tag);
116
117            if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
118            {
119                int  flag = tags[tagn].flag;
120                if (flag == 0) {
121                    adb_trace_mask = ~0;
122                    return;
123                }
124                adb_trace_mask |= (1 << flag);
125                break;
126            }
127        }
128        p = q;
129        if (*p)
130            p++;
131    }
132}
133
134#if !ADB_HOST
135/*
136 * Implements ADB tracing inside the emulator.
137 */
138
139#include <stdarg.h>
140
141/*
142 * Redefine open and write for qemu_pipe.h that contains inlined references
143 * to those routines. We will redifine them back after qemu_pipe.h inclusion.
144 */
145
146#undef open
147#undef write
148#define open    adb_open
149#define write   adb_write
150#include <hardware/qemu_pipe.h>
151#undef open
152#undef write
153#define open    ___xxx_open
154#define write   ___xxx_write
155
156/* A handle to adb-debug qemud service in the emulator. */
157int   adb_debug_qemu = -1;
158
159/* Initializes connection with the adb-debug qemud service in the emulator. */
160static int adb_qemu_trace_init(void)
161{
162    char con_name[32];
163
164    if (adb_debug_qemu >= 0) {
165        return 0;
166    }
167
168    /* adb debugging QEMUD service connection request. */
169    snprintf(con_name, sizeof(con_name), "qemud:adb-debug");
170    adb_debug_qemu = qemu_pipe_open(con_name);
171    return (adb_debug_qemu >= 0) ? 0 : -1;
172}
173
174void adb_qemu_trace(const char* fmt, ...)
175{
176    va_list args;
177    va_start(args, fmt);
178    char msg[1024];
179
180    if (adb_debug_qemu >= 0) {
181        vsnprintf(msg, sizeof(msg), fmt, args);
182        adb_write(adb_debug_qemu, msg, strlen(msg));
183    }
184}
185#endif  /* !ADB_HOST */
186
187apacket *get_apacket(void)
188{
189    apacket *p = malloc(sizeof(apacket));
190    if(p == 0) fatal("failed to allocate an apacket");
191    memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
192    return p;
193}
194
195void put_apacket(apacket *p)
196{
197    free(p);
198}
199
200void handle_online(void)
201{
202    D("adb: online\n");
203}
204
205void handle_offline(atransport *t)
206{
207    D("adb: offline\n");
208    //Close the associated usb
209    run_transport_disconnects(t);
210}
211
212#if TRACE_PACKETS
213#define DUMPMAX 32
214void print_packet(const char *label, apacket *p)
215{
216    char *tag;
217    char *x;
218    unsigned count;
219
220    switch(p->msg.command){
221    case A_SYNC: tag = "SYNC"; break;
222    case A_CNXN: tag = "CNXN" ; break;
223    case A_OPEN: tag = "OPEN"; break;
224    case A_OKAY: tag = "OKAY"; break;
225    case A_CLSE: tag = "CLSE"; break;
226    case A_WRTE: tag = "WRTE"; break;
227    default: tag = "????"; break;
228    }
229
230    fprintf(stderr, "%s: %s %08x %08x %04x \"",
231            label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
232    count = p->msg.data_length;
233    x = (char*) p->data;
234    if(count > DUMPMAX) {
235        count = DUMPMAX;
236        tag = "\n";
237    } else {
238        tag = "\"\n";
239    }
240    while(count-- > 0){
241        if((*x >= ' ') && (*x < 127)) {
242            fputc(*x, stderr);
243        } else {
244            fputc('.', stderr);
245        }
246        x++;
247    }
248    fprintf(stderr, tag);
249}
250#endif
251
252static void send_ready(unsigned local, unsigned remote, atransport *t)
253{
254    D("Calling send_ready \n");
255    apacket *p = get_apacket();
256    p->msg.command = A_OKAY;
257    p->msg.arg0 = local;
258    p->msg.arg1 = remote;
259    send_packet(p, t);
260}
261
262static void send_close(unsigned local, unsigned remote, atransport *t)
263{
264    D("Calling send_close \n");
265    apacket *p = get_apacket();
266    p->msg.command = A_CLSE;
267    p->msg.arg0 = local;
268    p->msg.arg1 = remote;
269    send_packet(p, t);
270}
271
272static void send_connect(atransport *t)
273{
274    D("Calling send_connect \n");
275    apacket *cp = get_apacket();
276    cp->msg.command = A_CNXN;
277    cp->msg.arg0 = A_VERSION;
278    cp->msg.arg1 = MAX_PAYLOAD;
279    snprintf((char*) cp->data, sizeof cp->data, "%s::",
280            HOST ? "host" : adb_device_banner);
281    cp->msg.data_length = strlen((char*) cp->data) + 1;
282    send_packet(cp, t);
283#if ADB_HOST
284        /* XXX why sleep here? */
285    // allow the device some time to respond to the connect message
286    adb_sleep_ms(1000);
287#endif
288}
289
290static char *connection_state_name(atransport *t)
291{
292    if (t == NULL) {
293        return "unknown";
294    }
295
296    switch(t->connection_state) {
297    case CS_BOOTLOADER:
298        return "bootloader";
299    case CS_DEVICE:
300        return "device";
301    case CS_OFFLINE:
302        return "offline";
303    default:
304        return "unknown";
305    }
306}
307
308void parse_banner(char *banner, atransport *t)
309{
310    char *type, *product, *end;
311
312    D("parse_banner: %s\n", banner);
313    type = banner;
314    product = strchr(type, ':');
315    if(product) {
316        *product++ = 0;
317    } else {
318        product = "";
319    }
320
321        /* remove trailing ':' */
322    end = strchr(product, ':');
323    if(end) *end = 0;
324
325        /* save product name in device structure */
326    if (t->product == NULL) {
327        t->product = strdup(product);
328    } else if (strcmp(product, t->product) != 0) {
329        free(t->product);
330        t->product = strdup(product);
331    }
332
333    if(!strcmp(type, "bootloader")){
334        D("setting connection_state to CS_BOOTLOADER\n");
335        t->connection_state = CS_BOOTLOADER;
336        update_transports();
337        return;
338    }
339
340    if(!strcmp(type, "device")) {
341        D("setting connection_state to CS_DEVICE\n");
342        t->connection_state = CS_DEVICE;
343        update_transports();
344        return;
345    }
346
347    if(!strcmp(type, "recovery")) {
348        D("setting connection_state to CS_RECOVERY\n");
349        t->connection_state = CS_RECOVERY;
350        update_transports();
351        return;
352    }
353
354    if(!strcmp(type, "sideload")) {
355        D("setting connection_state to CS_SIDELOAD\n");
356        t->connection_state = CS_SIDELOAD;
357        update_transports();
358        return;
359    }
360
361    t->connection_state = CS_HOST;
362}
363
364void handle_packet(apacket *p, atransport *t)
365{
366    asocket *s;
367
368    D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
369            ((char*) (&(p->msg.command)))[1],
370            ((char*) (&(p->msg.command)))[2],
371            ((char*) (&(p->msg.command)))[3]);
372    print_packet("recv", p);
373
374    switch(p->msg.command){
375    case A_SYNC:
376        if(p->msg.arg0){
377            send_packet(p, t);
378            if(HOST) send_connect(t);
379        } else {
380            t->connection_state = CS_OFFLINE;
381            handle_offline(t);
382            send_packet(p, t);
383        }
384        return;
385
386    case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
387            /* XXX verify version, etc */
388        if(t->connection_state != CS_OFFLINE) {
389            t->connection_state = CS_OFFLINE;
390            handle_offline(t);
391        }
392        parse_banner((char*) p->data, t);
393        handle_online();
394        if(!HOST) send_connect(t);
395        break;
396
397    case A_OPEN: /* OPEN(local-id, 0, "destination") */
398        if(t->connection_state != CS_OFFLINE) {
399            char *name = (char*) p->data;
400            name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
401            s = create_local_service_socket(name);
402            if(s == 0) {
403                send_close(0, p->msg.arg0, t);
404            } else {
405                s->peer = create_remote_socket(p->msg.arg0, t);
406                s->peer->peer = s;
407                send_ready(s->id, s->peer->id, t);
408                s->ready(s);
409            }
410        }
411        break;
412
413    case A_OKAY: /* READY(local-id, remote-id, "") */
414        if(t->connection_state != CS_OFFLINE) {
415            if((s = find_local_socket(p->msg.arg1))) {
416                if(s->peer == 0) {
417                    s->peer = create_remote_socket(p->msg.arg0, t);
418                    s->peer->peer = s;
419                }
420                s->ready(s);
421            }
422        }
423        break;
424
425    case A_CLSE: /* CLOSE(local-id, remote-id, "") */
426        if(t->connection_state != CS_OFFLINE) {
427            if((s = find_local_socket(p->msg.arg1))) {
428                s->close(s);
429            }
430        }
431        break;
432
433    case A_WRTE:
434        if(t->connection_state != CS_OFFLINE) {
435            if((s = find_local_socket(p->msg.arg1))) {
436                unsigned rid = p->msg.arg0;
437                p->len = p->msg.data_length;
438
439                if(s->enqueue(s, p) == 0) {
440                    D("Enqueue the socket\n");
441                    send_ready(s->id, rid, t);
442                }
443                return;
444            }
445        }
446        break;
447
448    default:
449        printf("handle_packet: what is %08x?!\n", p->msg.command);
450    }
451
452    put_apacket(p);
453}
454
455alistener listener_list = {
456    .next = &listener_list,
457    .prev = &listener_list,
458};
459
460static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
461{
462    asocket *s;
463
464    if(ev & FDE_READ) {
465        struct sockaddr addr;
466        socklen_t alen;
467        int fd;
468
469        alen = sizeof(addr);
470        fd = adb_socket_accept(_fd, &addr, &alen);
471        if(fd < 0) return;
472
473        adb_socket_setbufsize(fd, CHUNK_SIZE);
474
475        s = create_local_socket(fd);
476        if(s) {
477            connect_to_smartsocket(s);
478            return;
479        }
480
481        adb_close(fd);
482    }
483}
484
485static void listener_event_func(int _fd, unsigned ev, void *_l)
486{
487    alistener *l = _l;
488    asocket *s;
489
490    if(ev & FDE_READ) {
491        struct sockaddr addr;
492        socklen_t alen;
493        int fd;
494
495        alen = sizeof(addr);
496        fd = adb_socket_accept(_fd, &addr, &alen);
497        if(fd < 0) return;
498
499        s = create_local_socket(fd);
500        if(s) {
501            s->transport = l->transport;
502            connect_to_remote(s, l->connect_to);
503            return;
504        }
505
506        adb_close(fd);
507    }
508}
509
510static void  free_listener(alistener*  l)
511{
512    if (l->next) {
513        l->next->prev = l->prev;
514        l->prev->next = l->next;
515        l->next = l->prev = l;
516    }
517
518    // closes the corresponding fd
519    fdevent_remove(&l->fde);
520
521    if (l->local_name)
522        free((char*)l->local_name);
523
524    if (l->connect_to)
525        free((char*)l->connect_to);
526
527    if (l->transport) {
528        remove_transport_disconnect(l->transport, &l->disconnect);
529    }
530    free(l);
531}
532
533static void listener_disconnect(void*  _l, atransport*  t)
534{
535    alistener*  l = _l;
536
537    free_listener(l);
538}
539
540int local_name_to_fd(const char *name)
541{
542    int port;
543
544    if(!strncmp("tcp:", name, 4)){
545        int  ret;
546        port = atoi(name + 4);
547        ret = socket_loopback_server(port, SOCK_STREAM);
548        return ret;
549    }
550#ifndef HAVE_WIN32_IPC  /* no Unix-domain sockets on Win32 */
551    // It's non-sensical to support the "reserved" space on the adb host side
552    if(!strncmp(name, "local:", 6)) {
553        return socket_local_server(name + 6,
554                ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
555    } else if(!strncmp(name, "localabstract:", 14)) {
556        return socket_local_server(name + 14,
557                ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
558    } else if(!strncmp(name, "localfilesystem:", 16)) {
559        return socket_local_server(name + 16,
560                ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
561    }
562
563#endif
564    printf("unknown local portname '%s'\n", name);
565    return -1;
566}
567
568static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
569{
570    alistener *l;
571
572    for (l = listener_list.next; l != &listener_list; l = l->next) {
573        if (!strcmp(local_name, l->local_name) &&
574            !strcmp(connect_to, l->connect_to) &&
575            l->transport && l->transport == transport) {
576
577            listener_disconnect(l, transport);
578            return 0;
579        }
580    }
581
582    return -1;
583}
584
585static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
586{
587    alistener *l;
588
589    //printf("install_listener('%s','%s')\n", local_name, connect_to);
590
591    for(l = listener_list.next; l != &listener_list; l = l->next){
592        if(strcmp(local_name, l->local_name) == 0) {
593            char *cto;
594
595                /* can't repurpose a smartsocket */
596            if(l->connect_to[0] == '*') {
597                return -1;
598            }
599
600            cto = strdup(connect_to);
601            if(cto == 0) {
602                return -1;
603            }
604
605            //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
606            free((void*) l->connect_to);
607            l->connect_to = cto;
608            if (l->transport != transport) {
609                remove_transport_disconnect(l->transport, &l->disconnect);
610                l->transport = transport;
611                add_transport_disconnect(l->transport, &l->disconnect);
612            }
613            return 0;
614        }
615    }
616
617    if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
618    if((l->local_name = strdup(local_name)) == 0) goto nomem;
619    if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
620
621
622    l->fd = local_name_to_fd(local_name);
623    if(l->fd < 0) {
624        free((void*) l->local_name);
625        free((void*) l->connect_to);
626        free(l);
627        printf("cannot bind '%s'\n", local_name);
628        return -2;
629    }
630
631    close_on_exec(l->fd);
632    if(!strcmp(l->connect_to, "*smartsocket*")) {
633        fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
634    } else {
635        fdevent_install(&l->fde, l->fd, listener_event_func, l);
636    }
637    fdevent_set(&l->fde, FDE_READ);
638
639    l->next = &listener_list;
640    l->prev = listener_list.prev;
641    l->next->prev = l;
642    l->prev->next = l;
643    l->transport = transport;
644
645    if (transport) {
646        l->disconnect.opaque = l;
647        l->disconnect.func   = listener_disconnect;
648        add_transport_disconnect(transport, &l->disconnect);
649    }
650    return 0;
651
652nomem:
653    fatal("cannot allocate listener");
654    return 0;
655}
656
657#ifdef HAVE_WIN32_PROC
658static BOOL WINAPI ctrlc_handler(DWORD type)
659{
660    exit(STATUS_CONTROL_C_EXIT);
661    return TRUE;
662}
663#endif
664
665static void adb_cleanup(void)
666{
667    usb_cleanup();
668}
669
670void start_logging(void)
671{
672#ifdef HAVE_WIN32_PROC
673    char    temp[ MAX_PATH ];
674    FILE*   fnul;
675    FILE*   flog;
676
677    GetTempPath( sizeof(temp) - 8, temp );
678    strcat( temp, "adb.log" );
679
680    /* Win32 specific redirections */
681    fnul = fopen( "NUL", "rt" );
682    if (fnul != NULL)
683        stdin[0] = fnul[0];
684
685    flog = fopen( temp, "at" );
686    if (flog == NULL)
687        flog = fnul;
688
689    setvbuf( flog, NULL, _IONBF, 0 );
690
691    stdout[0] = flog[0];
692    stderr[0] = flog[0];
693    fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
694#else
695    int fd;
696
697    fd = unix_open("/dev/null", O_RDONLY);
698    dup2(fd, 0);
699    adb_close(fd);
700
701    fd = unix_open("/tmp/adb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
702    if(fd < 0) {
703        fd = unix_open("/dev/null", O_WRONLY);
704    }
705    dup2(fd, 1);
706    dup2(fd, 2);
707    adb_close(fd);
708    fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
709#endif
710}
711
712#if !ADB_HOST
713void start_device_log(void)
714{
715    int fd;
716    char    path[PATH_MAX];
717    struct tm now;
718    time_t t;
719    char value[PROPERTY_VALUE_MAX];
720
721    // read the trace mask from persistent property persist.adb.trace_mask
722    // give up if the property is not set or cannot be parsed
723    property_get("persist.adb.trace_mask", value, "");
724    if (sscanf(value, "%x", &adb_trace_mask) != 1)
725        return;
726
727    adb_mkdir("/data/adb", 0775);
728    tzset();
729    time(&t);
730    localtime_r(&t, &now);
731    strftime(path, sizeof(path),
732                "/data/adb/adb-%Y-%m-%d-%H-%M-%S.txt",
733                &now);
734    fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
735    if (fd < 0)
736        return;
737
738    // redirect stdout and stderr to the log file
739    dup2(fd, 1);
740    dup2(fd, 2);
741    fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
742    adb_close(fd);
743
744    fd = unix_open("/dev/null", O_RDONLY);
745    dup2(fd, 0);
746    adb_close(fd);
747}
748#endif
749
750#if ADB_HOST
751int launch_server(int server_port)
752{
753#ifdef HAVE_WIN32_PROC
754    /* we need to start the server in the background                    */
755    /* we create a PIPE that will be used to wait for the server's "OK" */
756    /* message since the pipe handles must be inheritable, we use a     */
757    /* security attribute                                               */
758    HANDLE                pipe_read, pipe_write;
759    SECURITY_ATTRIBUTES   sa;
760    STARTUPINFO           startup;
761    PROCESS_INFORMATION   pinfo;
762    char                  program_path[ MAX_PATH ];
763    int                   ret;
764
765    sa.nLength = sizeof(sa);
766    sa.lpSecurityDescriptor = NULL;
767    sa.bInheritHandle = TRUE;
768
769    /* create pipe, and ensure its read handle isn't inheritable */
770    ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
771    if (!ret) {
772        fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
773        return -1;
774    }
775
776    SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
777
778    ZeroMemory( &startup, sizeof(startup) );
779    startup.cb = sizeof(startup);
780    startup.hStdInput  = GetStdHandle( STD_INPUT_HANDLE );
781    startup.hStdOutput = pipe_write;
782    startup.hStdError  = GetStdHandle( STD_ERROR_HANDLE );
783    startup.dwFlags    = STARTF_USESTDHANDLES;
784
785    ZeroMemory( &pinfo, sizeof(pinfo) );
786
787    /* get path of current program */
788    GetModuleFileName( NULL, program_path, sizeof(program_path) );
789
790    ret = CreateProcess(
791            program_path,                              /* program path  */
792            "adb fork-server server",
793                                    /* the fork-server argument will set the
794                                       debug = 2 in the child           */
795            NULL,                   /* process handle is not inheritable */
796            NULL,                    /* thread handle is not inheritable */
797            TRUE,                          /* yes, inherit some handles */
798            DETACHED_PROCESS, /* the new process doesn't have a console */
799            NULL,                     /* use parent's environment block */
800            NULL,                    /* use parent's starting directory */
801            &startup,                 /* startup info, i.e. std handles */
802            &pinfo );
803
804    CloseHandle( pipe_write );
805
806    if (!ret) {
807        fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
808        CloseHandle( pipe_read );
809        return -1;
810    }
811
812    CloseHandle( pinfo.hProcess );
813    CloseHandle( pinfo.hThread );
814
815    /* wait for the "OK\n" message */
816    {
817        char  temp[3];
818        DWORD  count;
819
820        ret = ReadFile( pipe_read, temp, 3, &count, NULL );
821        CloseHandle( pipe_read );
822        if ( !ret ) {
823            fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", GetLastError() );
824            return -1;
825        }
826        if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
827            fprintf(stderr, "ADB server didn't ACK\n" );
828            return -1;
829        }
830    }
831#elif defined(HAVE_FORKEXEC)
832    char    path[PATH_MAX];
833    int     fd[2];
834
835    // set up a pipe so the child can tell us when it is ready.
836    // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
837    if (pipe(fd)) {
838        fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
839        return -1;
840    }
841    get_my_path(path, PATH_MAX);
842    pid_t pid = fork();
843    if(pid < 0) return -1;
844
845    if (pid == 0) {
846        // child side of the fork
847
848        // redirect stderr to the pipe
849        // we use stderr instead of stdout due to stdout's buffering behavior.
850        adb_close(fd[0]);
851        dup2(fd[1], STDERR_FILENO);
852        adb_close(fd[1]);
853
854        // child process
855        int result = execl(path, "adb", "fork-server", "server", NULL);
856        // this should not return
857        fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
858    } else  {
859        // parent side of the fork
860
861        char  temp[3];
862
863        temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
864        // wait for the "OK\n" message
865        adb_close(fd[1]);
866        int ret = adb_read(fd[0], temp, 3);
867        int saved_errno = errno;
868        adb_close(fd[0]);
869        if (ret < 0) {
870            fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", saved_errno);
871            return -1;
872        }
873        if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
874            fprintf(stderr, "ADB server didn't ACK\n" );
875            return -1;
876        }
877
878        setsid();
879    }
880#else
881#error "cannot implement background server start on this platform"
882#endif
883    return 0;
884}
885#endif
886
887/* Constructs a local name of form tcp:port.
888 * target_str points to the target string, it's content will be overwritten.
889 * target_size is the capacity of the target string.
890 * server_port is the port number to use for the local name.
891 */
892void build_local_name(char* target_str, size_t target_size, int server_port)
893{
894  snprintf(target_str, target_size, "tcp:%d", server_port);
895}
896
897#if !ADB_HOST
898static int should_drop_privileges() {
899#ifndef ALLOW_ADBD_ROOT
900    return 1;
901#else /* ALLOW_ADBD_ROOT */
902    int secure = 0;
903    char value[PROPERTY_VALUE_MAX];
904
905   /* run adbd in secure mode if ro.secure is set and
906    ** we are not in the emulator
907    */
908    property_get("ro.kernel.qemu", value, "");
909    if (strcmp(value, "1") != 0) {
910        property_get("ro.secure", value, "1");
911        if (strcmp(value, "1") == 0) {
912            // don't run as root if ro.secure is set...
913            secure = 1;
914
915            // ... except we allow running as root in userdebug builds if the
916            // service.adb.root property has been set by the "adb root" command
917            property_get("ro.debuggable", value, "");
918            if (strcmp(value, "1") == 0) {
919                property_get("service.adb.root", value, "");
920                if (strcmp(value, "1") == 0) {
921                    secure = 0;
922                }
923            }
924        }
925    }
926    return secure;
927#endif /* ALLOW_ADBD_ROOT */
928}
929#endif /* !ADB_HOST */
930
931int adb_main(int is_daemon, int server_port)
932{
933#if !ADB_HOST
934    int port;
935    char value[PROPERTY_VALUE_MAX];
936
937    umask(000);
938#endif
939
940    atexit(adb_cleanup);
941#ifdef HAVE_WIN32_PROC
942    SetConsoleCtrlHandler( ctrlc_handler, TRUE );
943#elif defined(HAVE_FORKEXEC)
944    // No SIGCHLD. Let the service subproc handle its children.
945    signal(SIGPIPE, SIG_IGN);
946#endif
947
948    init_transport_registration();
949
950
951#if ADB_HOST
952    HOST = 1;
953    usb_vendors_init();
954    usb_init();
955    local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
956
957    char local_name[30];
958    build_local_name(local_name, sizeof(local_name), server_port);
959    if(install_listener(local_name, "*smartsocket*", NULL)) {
960        exit(1);
961    }
962#else
963
964    /* don't listen on a port (default 5037) if running in secure mode */
965    /* don't run as root if we are running in secure mode */
966    if (should_drop_privileges()) {
967        struct __user_cap_header_struct header;
968        struct __user_cap_data_struct cap;
969
970        if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
971            exit(1);
972        }
973
974        /* add extra groups:
975        ** AID_ADB to access the USB driver
976        ** AID_LOG to read system logs (adb logcat)
977        ** AID_INPUT to diagnose input issues (getevent)
978        ** AID_INET to diagnose network issues (netcfg, ping)
979        ** AID_GRAPHICS to access the frame buffer
980        ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
981        ** AID_SDCARD_R to allow reading from the SD card
982        ** AID_SDCARD_RW to allow writing to the SD card
983        ** AID_MOUNT to allow unmounting the SD card before rebooting
984        ** AID_NET_BW_STATS to read out qtaguid statistics
985        */
986        gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,
987                           AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
988                           AID_MOUNT, AID_NET_BW_STATS };
989        if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
990            exit(1);
991        }
992
993        /* then switch user and group to "shell" */
994        if (setgid(AID_SHELL) != 0) {
995            exit(1);
996        }
997        if (setuid(AID_SHELL) != 0) {
998            exit(1);
999        }
1000
1001        /* set CAP_SYS_BOOT capability, so "adb reboot" will succeed */
1002        header.version = _LINUX_CAPABILITY_VERSION;
1003        header.pid = 0;
1004        cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
1005        cap.inheritable = 0;
1006        capset(&header, &cap);
1007
1008        D("Local port disabled\n");
1009    } else {
1010        char local_name[30];
1011        build_local_name(local_name, sizeof(local_name), server_port);
1012        if(install_listener(local_name, "*smartsocket*", NULL)) {
1013            exit(1);
1014        }
1015    }
1016
1017        /* for the device, start the usb transport if the
1018        ** android usb device exists and the "service.adb.tcp.port" and
1019        ** "persist.adb.tcp.port" properties are not set.
1020        ** Otherwise start the network transport.
1021        */
1022    property_get("service.adb.tcp.port", value, "");
1023    if (!value[0])
1024        property_get("persist.adb.tcp.port", value, "");
1025    if (sscanf(value, "%d", &port) == 1 && port > 0) {
1026        // listen on TCP port specified by service.adb.tcp.port property
1027        local_init(port);
1028    } else if (access(USB_ADB_PATH, F_OK) == 0 ||
1029               access(USB_FFS_ADB_EP0, 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 >= 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