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