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