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