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