adb.cpp revision 0156589846117bccb2fbec6b3141cc21bc86c638
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 "sysdeps.h"
20#include "adb.h"
21
22#include <ctype.h>
23#include <errno.h>
24#include <stdarg.h>
25#include <stddef.h>
26#include <stdint.h>
27#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
30#include <sys/time.h>
31#include <time.h>
32
33#include <string>
34
35#include <base/stringprintf.h>
36#include <base/strings.h>
37
38#include "adb_auth.h"
39#include "adb_io.h"
40#include "adb_listeners.h"
41#include "transport.h"
42
43#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
44
45#if !ADB_HOST
46#include <cutils/properties.h>
47#include <sys/capability.h>
48#include <sys/mount.h>
49#endif
50
51#if ADB_TRACE
52ADB_MUTEX_DEFINE( D_lock );
53#endif
54
55int HOST = 0;
56
57#if !ADB_HOST
58const char *adb_device_banner = "device";
59#endif
60
61void fatal(const char *fmt, ...)
62{
63    va_list ap;
64    va_start(ap, fmt);
65    fprintf(stderr, "error: ");
66    vfprintf(stderr, fmt, ap);
67    fprintf(stderr, "\n");
68    va_end(ap);
69    exit(-1);
70}
71
72void fatal_errno(const char *fmt, ...)
73{
74    va_list ap;
75    va_start(ap, fmt);
76    fprintf(stderr, "error: %s: ", strerror(errno));
77    vfprintf(stderr, fmt, ap);
78    fprintf(stderr, "\n");
79    va_end(ap);
80    exit(-1);
81}
82
83#if !ADB_HOST
84void start_device_log(void) {
85    struct tm now;
86    time_t t;
87    tzset();
88    time(&t);
89    localtime_r(&t, &now);
90
91    char timestamp[PATH_MAX];
92    strftime(timestamp, sizeof(timestamp), "%Y-%m-%d-%H-%M-%S", &now);
93
94    char path[PATH_MAX];
95    snprintf(path, sizeof(path), "/data/adb/adb-%s-%d", timestamp, getpid());
96
97    int fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0640);
98    if (fd == -1) {
99        return;
100    }
101
102    // redirect stdout and stderr to the log file
103    dup2(fd, STDOUT_FILENO);
104    dup2(fd, STDERR_FILENO);
105    fprintf(stderr, "--- adb starting (pid %d) ---\n", getpid());
106    adb_close(fd);
107}
108#endif
109
110int adb_trace_mask;
111
112std::string get_trace_setting_from_env() {
113    const char* setting = getenv("ADB_TRACE");
114    if (setting == nullptr) {
115        setting = "";
116    }
117
118    return std::string(setting);
119}
120
121#if !ADB_HOST
122std::string get_trace_setting_from_prop() {
123    char buf[PROPERTY_VALUE_MAX];
124    property_get("persist.adb.trace_mask", buf, "");
125    return std::string(buf);
126}
127#endif
128
129std::string get_trace_setting() {
130#if ADB_HOST
131    return get_trace_setting_from_env();
132#else
133    return get_trace_setting_from_prop();
134#endif
135}
136
137// Split the comma/space/colum/semi-column separated list of tags from the trace
138// setting and build the trace mask from it. note that '1' and 'all' are special
139// cases to enable all tracing.
140//
141// adb's trace setting comes from the ADB_TRACE environment variable, whereas
142// adbd's comes from the system property persist.adb.trace_mask.
143void adb_trace_init() {
144    const std::string trace_setting = get_trace_setting();
145
146    static const struct {
147        const char*  tag;
148        int           flag;
149    } tags[] = {
150        { "1", 0 },
151        { "all", 0 },
152        { "adb", TRACE_ADB },
153        { "sockets", TRACE_SOCKETS },
154        { "packets", TRACE_PACKETS },
155        { "rwx", TRACE_RWX },
156        { "usb", TRACE_USB },
157        { "sync", TRACE_SYNC },
158        { "sysdeps", TRACE_SYSDEPS },
159        { "transport", TRACE_TRANSPORT },
160        { "jdwp", TRACE_JDWP },
161        { "services", TRACE_SERVICES },
162        { "auth", TRACE_AUTH },
163        { NULL, 0 }
164    };
165
166    if (trace_setting.empty()) {
167        return;
168    }
169
170    // Use a comma/colon/semi-colon/space separated list
171    const char* p = trace_setting.c_str();
172    while (*p) {
173        int  len, tagn;
174
175        const char* q = strpbrk(p, " ,:;");
176        if (q == NULL) {
177            q = p + strlen(p);
178        }
179        len = q - p;
180
181        for (tagn = 0; tags[tagn].tag != NULL; tagn++) {
182            int  taglen = strlen(tags[tagn].tag);
183
184            if (len == taglen && !memcmp(tags[tagn].tag, p, len)) {
185                int  flag = tags[tagn].flag;
186                if (flag == 0) {
187                    adb_trace_mask = ~0;
188                    return;
189                }
190                adb_trace_mask |= (1 << flag);
191                break;
192            }
193        }
194        p = q;
195        if (*p)
196            p++;
197    }
198
199#if !ADB_HOST
200    start_device_log();
201#endif
202}
203
204apacket* get_apacket(void)
205{
206    apacket* p = reinterpret_cast<apacket*>(malloc(sizeof(apacket)));
207    if (p == nullptr) {
208      fatal("failed to allocate an apacket");
209    }
210
211    memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
212    return p;
213}
214
215void put_apacket(apacket *p)
216{
217    free(p);
218}
219
220void handle_online(atransport *t)
221{
222    D("adb: online\n");
223    t->online = 1;
224}
225
226void handle_offline(atransport *t)
227{
228    D("adb: offline\n");
229    //Close the associated usb
230    t->online = 0;
231    run_transport_disconnects(t);
232}
233
234#if DEBUG_PACKETS
235#define DUMPMAX 32
236void print_packet(const char *label, apacket *p)
237{
238    char *tag;
239    char *x;
240    unsigned count;
241
242    switch(p->msg.command){
243    case A_SYNC: tag = "SYNC"; break;
244    case A_CNXN: tag = "CNXN" ; break;
245    case A_OPEN: tag = "OPEN"; break;
246    case A_OKAY: tag = "OKAY"; break;
247    case A_CLSE: tag = "CLSE"; break;
248    case A_WRTE: tag = "WRTE"; break;
249    case A_AUTH: tag = "AUTH"; break;
250    default: tag = "????"; break;
251    }
252
253    fprintf(stderr, "%s: %s %08x %08x %04x \"",
254            label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
255    count = p->msg.data_length;
256    x = (char*) p->data;
257    if(count > DUMPMAX) {
258        count = DUMPMAX;
259        tag = "\n";
260    } else {
261        tag = "\"\n";
262    }
263    while(count-- > 0){
264        if((*x >= ' ') && (*x < 127)) {
265            fputc(*x, stderr);
266        } else {
267            fputc('.', stderr);
268        }
269        x++;
270    }
271    fputs(tag, stderr);
272}
273#endif
274
275static void send_ready(unsigned local, unsigned remote, atransport *t)
276{
277    D("Calling send_ready \n");
278    apacket *p = get_apacket();
279    p->msg.command = A_OKAY;
280    p->msg.arg0 = local;
281    p->msg.arg1 = remote;
282    send_packet(p, t);
283}
284
285static void send_close(unsigned local, unsigned remote, atransport *t)
286{
287    D("Calling send_close \n");
288    apacket *p = get_apacket();
289    p->msg.command = A_CLSE;
290    p->msg.arg0 = local;
291    p->msg.arg1 = remote;
292    send_packet(p, t);
293}
294
295static size_t fill_connect_data(char *buf, size_t bufsize)
296{
297#if ADB_HOST
298    return snprintf(buf, bufsize, "host::") + 1;
299#else
300    static const char *cnxn_props[] = {
301        "ro.product.name",
302        "ro.product.model",
303        "ro.product.device",
304    };
305    static const int num_cnxn_props = ARRAY_SIZE(cnxn_props);
306    int i;
307    size_t remaining = bufsize;
308    size_t len;
309
310    len = snprintf(buf, remaining, "%s::", adb_device_banner);
311    remaining -= len;
312    buf += len;
313    for (i = 0; i < num_cnxn_props; i++) {
314        char value[PROPERTY_VALUE_MAX];
315        property_get(cnxn_props[i], value, "");
316        len = snprintf(buf, remaining, "%s=%s;", cnxn_props[i], value);
317        remaining -= len;
318        buf += len;
319    }
320
321    return bufsize - remaining + 1;
322#endif
323}
324
325#if !ADB_HOST
326static void send_msg_with_header(int fd, const char* msg, size_t msglen) {
327    char header[5];
328    if (msglen > 0xffff)
329        msglen = 0xffff;
330    snprintf(header, sizeof(header), "%04x", (unsigned)msglen);
331    WriteFdExactly(fd, header, 4);
332    WriteFdExactly(fd, msg, msglen);
333}
334#endif
335
336#if ADB_HOST
337static void send_msg_with_okay(int fd, const char* msg, size_t msglen) {
338    char header[9];
339    if (msglen > 0xffff)
340        msglen = 0xffff;
341    snprintf(header, sizeof(header), "OKAY%04x", (unsigned)msglen);
342    WriteFdExactly(fd, header, 8);
343    WriteFdExactly(fd, msg, msglen);
344}
345#endif // ADB_HOST
346
347void send_connect(atransport *t)
348{
349    D("Calling send_connect \n");
350    apacket *cp = get_apacket();
351    cp->msg.command = A_CNXN;
352    cp->msg.arg0 = A_VERSION;
353    cp->msg.arg1 = MAX_PAYLOAD;
354    cp->msg.data_length = fill_connect_data((char *)cp->data,
355                                            sizeof(cp->data));
356    send_packet(cp, t);
357}
358
359#if ADB_HOST
360static const char* connection_state_name(atransport *t)
361{
362    if (t == NULL) {
363        return "unknown";
364    }
365
366    switch(t->connection_state) {
367    case CS_BOOTLOADER:
368        return "bootloader";
369    case CS_DEVICE:
370        return "device";
371    case CS_RECOVERY:
372        return "recovery";
373    case CS_SIDELOAD:
374        return "sideload";
375    case CS_OFFLINE:
376        return "offline";
377    case CS_UNAUTHORIZED:
378        return "unauthorized";
379    default:
380        return "unknown";
381    }
382}
383#endif // ADB_HOST
384
385// qual_overwrite is used to overwrite a qualifier string.  dst is a
386// pointer to a char pointer.  It is assumed that if *dst is non-NULL, it
387// was malloc'ed and needs to freed.  *dst will be set to a dup of src.
388// TODO: switch to std::string for these atransport fields instead.
389static void qual_overwrite(char** dst, const std::string& src) {
390    free(*dst);
391    *dst = strdup(src.c_str());
392}
393
394void parse_banner(const char* banner, atransport* t) {
395    D("parse_banner: %s\n", banner);
396
397    // The format is something like:
398    // "device::ro.product.name=x;ro.product.model=y;ro.product.device=z;".
399    std::vector<std::string> pieces = android::base::Split(banner, ":");
400
401    if (pieces.size() > 2) {
402        const std::string& props = pieces[2];
403        for (auto& prop : android::base::Split(props, ";")) {
404            // The list of properties was traditionally ;-terminated rather than ;-separated.
405            if (prop.empty()) continue;
406
407            std::vector<std::string> key_value = android::base::Split(prop, "=");
408            if (key_value.size() != 2) continue;
409
410            const std::string& key = key_value[0];
411            const std::string& value = key_value[1];
412            if (key == "ro.product.name") {
413                qual_overwrite(&t->product, value);
414            } else if (key == "ro.product.model") {
415                qual_overwrite(&t->model, value);
416            } else if (key == "ro.product.device") {
417                qual_overwrite(&t->device, value);
418            }
419        }
420    }
421
422    const std::string& type = pieces[0];
423    if (type == "bootloader") {
424        D("setting connection_state to CS_BOOTLOADER\n");
425        t->connection_state = CS_BOOTLOADER;
426        update_transports();
427    } else if (type == "device") {
428        D("setting connection_state to CS_DEVICE\n");
429        t->connection_state = CS_DEVICE;
430        update_transports();
431    } else if (type == "recovery") {
432        D("setting connection_state to CS_RECOVERY\n");
433        t->connection_state = CS_RECOVERY;
434        update_transports();
435    } else if (type == "sideload") {
436        D("setting connection_state to CS_SIDELOAD\n");
437        t->connection_state = CS_SIDELOAD;
438        update_transports();
439    } else {
440        D("setting connection_state to CS_HOST\n");
441        t->connection_state = CS_HOST;
442    }
443}
444
445void handle_packet(apacket *p, atransport *t)
446{
447    asocket *s;
448
449    D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
450            ((char*) (&(p->msg.command)))[1],
451            ((char*) (&(p->msg.command)))[2],
452            ((char*) (&(p->msg.command)))[3]);
453    print_packet("recv", p);
454
455    switch(p->msg.command){
456    case A_SYNC:
457        if(p->msg.arg0){
458            send_packet(p, t);
459            if(HOST) send_connect(t);
460        } else {
461            t->connection_state = CS_OFFLINE;
462            handle_offline(t);
463            send_packet(p, t);
464        }
465        return;
466
467    case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
468            /* XXX verify version, etc */
469        if(t->connection_state != CS_OFFLINE) {
470            t->connection_state = CS_OFFLINE;
471            handle_offline(t);
472        }
473
474        parse_banner(reinterpret_cast<const char*>(p->data), t);
475
476        if (HOST || !auth_enabled) {
477            handle_online(t);
478            if(!HOST) send_connect(t);
479        } else {
480            send_auth_request(t);
481        }
482        break;
483
484    case A_AUTH:
485        if (p->msg.arg0 == ADB_AUTH_TOKEN) {
486            t->connection_state = CS_UNAUTHORIZED;
487            t->key = adb_auth_nextkey(t->key);
488            if (t->key) {
489                send_auth_response(p->data, p->msg.data_length, t);
490            } else {
491                /* No more private keys to try, send the public key */
492                send_auth_publickey(t);
493            }
494        } else if (p->msg.arg0 == ADB_AUTH_SIGNATURE) {
495            if (adb_auth_verify(t->token, p->data, p->msg.data_length)) {
496                adb_auth_verified(t);
497                t->failed_auth_attempts = 0;
498            } else {
499                if (t->failed_auth_attempts++ > 10)
500                    adb_sleep_ms(1000);
501                send_auth_request(t);
502            }
503        } else if (p->msg.arg0 == ADB_AUTH_RSAPUBLICKEY) {
504            adb_auth_confirm_key(p->data, p->msg.data_length, t);
505        }
506        break;
507
508    case A_OPEN: /* OPEN(local-id, 0, "destination") */
509        if (t->online && p->msg.arg0 != 0 && p->msg.arg1 == 0) {
510            char *name = (char*) p->data;
511            name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
512            s = create_local_service_socket(name);
513            if(s == 0) {
514                send_close(0, p->msg.arg0, t);
515            } else {
516                s->peer = create_remote_socket(p->msg.arg0, t);
517                s->peer->peer = s;
518                send_ready(s->id, s->peer->id, t);
519                s->ready(s);
520            }
521        }
522        break;
523
524    case A_OKAY: /* READY(local-id, remote-id, "") */
525        if (t->online && p->msg.arg0 != 0 && p->msg.arg1 != 0) {
526            if((s = find_local_socket(p->msg.arg1, 0))) {
527                if(s->peer == 0) {
528                    /* On first READY message, create the connection. */
529                    s->peer = create_remote_socket(p->msg.arg0, t);
530                    s->peer->peer = s;
531                    s->ready(s);
532                } else if (s->peer->id == p->msg.arg0) {
533                    /* Other READY messages must use the same local-id */
534                    s->ready(s);
535                } else {
536                    D("Invalid A_OKAY(%d,%d), expected A_OKAY(%d,%d) on transport %s\n",
537                      p->msg.arg0, p->msg.arg1, s->peer->id, p->msg.arg1, t->serial);
538                }
539            }
540        }
541        break;
542
543    case A_CLSE: /* CLOSE(local-id, remote-id, "") or CLOSE(0, remote-id, "") */
544        if (t->online && p->msg.arg1 != 0) {
545            if((s = find_local_socket(p->msg.arg1, p->msg.arg0))) {
546                /* According to protocol.txt, p->msg.arg0 might be 0 to indicate
547                 * a failed OPEN only. However, due to a bug in previous ADB
548                 * versions, CLOSE(0, remote-id, "") was also used for normal
549                 * CLOSE() operations.
550                 *
551                 * This is bad because it means a compromised adbd could
552                 * send packets to close connections between the host and
553                 * other devices. To avoid this, only allow this if the local
554                 * socket has a peer on the same transport.
555                 */
556                if (p->msg.arg0 == 0 && s->peer && s->peer->transport != t) {
557                    D("Invalid A_CLSE(0, %u) from transport %s, expected transport %s\n",
558                      p->msg.arg1, t->serial, s->peer->transport->serial);
559                } else {
560                    s->close(s);
561                }
562            }
563        }
564        break;
565
566    case A_WRTE: /* WRITE(local-id, remote-id, <data>) */
567        if (t->online && p->msg.arg0 != 0 && p->msg.arg1 != 0) {
568            if((s = find_local_socket(p->msg.arg1, p->msg.arg0))) {
569                unsigned rid = p->msg.arg0;
570                p->len = p->msg.data_length;
571
572                if(s->enqueue(s, p) == 0) {
573                    D("Enqueue the socket\n");
574                    send_ready(s->id, rid, t);
575                }
576                return;
577            }
578        }
579        break;
580
581    default:
582        printf("handle_packet: what is %08x?!\n", p->msg.command);
583    }
584
585    put_apacket(p);
586}
587
588#if ADB_HOST
589
590int launch_server(int server_port)
591{
592#if defined(_WIN32)
593    /* we need to start the server in the background                    */
594    /* we create a PIPE that will be used to wait for the server's "OK" */
595    /* message since the pipe handles must be inheritable, we use a     */
596    /* security attribute                                               */
597    HANDLE                pipe_read, pipe_write;
598    HANDLE                stdout_handle, stderr_handle;
599    SECURITY_ATTRIBUTES   sa;
600    STARTUPINFO           startup;
601    PROCESS_INFORMATION   pinfo;
602    char                  program_path[ MAX_PATH ];
603    int                   ret;
604
605    sa.nLength = sizeof(sa);
606    sa.lpSecurityDescriptor = NULL;
607    sa.bInheritHandle = TRUE;
608
609    /* create pipe, and ensure its read handle isn't inheritable */
610    ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
611    if (!ret) {
612        fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
613        return -1;
614    }
615
616    SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
617
618    /* Some programs want to launch an adb command and collect its output by
619     * calling CreateProcess with inheritable stdout/stderr handles, then
620     * using read() to get its output. When this happens, the stdout/stderr
621     * handles passed to the adb client process will also be inheritable.
622     * When starting the adb server here, care must be taken to reset them
623     * to non-inheritable.
624     * Otherwise, something bad happens: even if the adb command completes,
625     * the calling process is stuck while read()-ing from the stdout/stderr
626     * descriptors, because they're connected to corresponding handles in the
627     * adb server process (even if the latter never uses/writes to them).
628     */
629    stdout_handle = GetStdHandle( STD_OUTPUT_HANDLE );
630    stderr_handle = GetStdHandle( STD_ERROR_HANDLE );
631    if (stdout_handle != INVALID_HANDLE_VALUE) {
632        SetHandleInformation( stdout_handle, HANDLE_FLAG_INHERIT, 0 );
633    }
634    if (stderr_handle != INVALID_HANDLE_VALUE) {
635        SetHandleInformation( stderr_handle, HANDLE_FLAG_INHERIT, 0 );
636    }
637
638    ZeroMemory( &startup, sizeof(startup) );
639    startup.cb = sizeof(startup);
640    startup.hStdInput  = GetStdHandle( STD_INPUT_HANDLE );
641    startup.hStdOutput = pipe_write;
642    startup.hStdError  = GetStdHandle( STD_ERROR_HANDLE );
643    startup.dwFlags    = STARTF_USESTDHANDLES;
644
645    ZeroMemory( &pinfo, sizeof(pinfo) );
646
647    /* get path of current program */
648    GetModuleFileName( NULL, program_path, sizeof(program_path) );
649    char args[64];
650    snprintf(args, sizeof(args), "adb -P %d fork-server server",  server_port);
651    ret = CreateProcess(
652            program_path,                              /* program path  */
653            args,
654                                    /* the fork-server argument will set the
655                                       debug = 2 in the child           */
656            NULL,                   /* process handle is not inheritable */
657            NULL,                    /* thread handle is not inheritable */
658            TRUE,                          /* yes, inherit some handles */
659            DETACHED_PROCESS, /* the new process doesn't have a console */
660            NULL,                     /* use parent's environment block */
661            NULL,                    /* use parent's starting directory */
662            &startup,                 /* startup info, i.e. std handles */
663            &pinfo );
664
665    CloseHandle( pipe_write );
666
667    if (!ret) {
668        fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
669        CloseHandle( pipe_read );
670        return -1;
671    }
672
673    CloseHandle( pinfo.hProcess );
674    CloseHandle( pinfo.hThread );
675
676    /* wait for the "OK\n" message */
677    {
678        char  temp[3];
679        DWORD  count;
680
681        ret = ReadFile( pipe_read, temp, 3, &count, NULL );
682        CloseHandle( pipe_read );
683        if ( !ret ) {
684            fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", GetLastError() );
685            return -1;
686        }
687        if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
688            fprintf(stderr, "ADB server didn't ACK\n" );
689            return -1;
690        }
691    }
692#else /* !defined(_WIN32) */
693    char    path[PATH_MAX];
694    int     fd[2];
695
696    // set up a pipe so the child can tell us when it is ready.
697    // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
698    if (pipe(fd)) {
699        fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
700        return -1;
701    }
702    get_my_path(path, PATH_MAX);
703    pid_t pid = fork();
704    if(pid < 0) return -1;
705
706    if (pid == 0) {
707        // child side of the fork
708
709        // redirect stderr to the pipe
710        // we use stderr instead of stdout due to stdout's buffering behavior.
711        adb_close(fd[0]);
712        dup2(fd[1], STDERR_FILENO);
713        adb_close(fd[1]);
714
715        char str_port[30];
716        snprintf(str_port, sizeof(str_port), "%d",  server_port);
717        // child process
718        int result = execl(path, "adb", "-P", str_port, "fork-server", "server", NULL);
719        // this should not return
720        fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
721    } else  {
722        // parent side of the fork
723
724        char  temp[3];
725
726        temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
727        // wait for the "OK\n" message
728        adb_close(fd[1]);
729        int ret = adb_read(fd[0], temp, 3);
730        int saved_errno = errno;
731        adb_close(fd[0]);
732        if (ret < 0) {
733            fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", saved_errno);
734            return -1;
735        }
736        if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
737            fprintf(stderr, "ADB server didn't ACK\n" );
738            return -1;
739        }
740
741        setsid();
742    }
743#endif /* !defined(_WIN32) */
744    return 0;
745}
746#endif /* ADB_HOST */
747
748// Try to handle a network forwarding request.
749// This returns 1 on success, 0 on failure, and -1 to indicate this is not
750// a forwarding-related request.
751int handle_forward_request(const char* service, transport_type ttype, char* serial, int reply_fd)
752{
753    if (!strcmp(service, "list-forward")) {
754        // Create the list of forward redirections.
755        int buffer_size = format_listeners(NULL, 0);
756        // Add one byte for the trailing zero.
757        char* buffer = reinterpret_cast<char*>(malloc(buffer_size + 1));
758        if (buffer == nullptr) {
759            sendfailmsg(reply_fd, "not enough memory");
760            return 1;
761        }
762        (void) format_listeners(buffer, buffer_size + 1);
763#if ADB_HOST
764        send_msg_with_okay(reply_fd, buffer, buffer_size);
765#else
766        send_msg_with_header(reply_fd, buffer, buffer_size);
767#endif
768        free(buffer);
769        return 1;
770    }
771
772    if (!strcmp(service, "killforward-all")) {
773        remove_all_listeners();
774#if ADB_HOST
775        /* On the host: 1st OKAY is connect, 2nd OKAY is status */
776        adb_write(reply_fd, "OKAY", 4);
777#endif
778        adb_write(reply_fd, "OKAY", 4);
779        return 1;
780    }
781
782    if (!strncmp(service, "forward:",8) ||
783        !strncmp(service, "killforward:",12)) {
784        char *local, *remote;
785        atransport *transport;
786
787        int createForward = strncmp(service, "kill", 4);
788        int no_rebind = 0;
789
790        local = strchr(service, ':') + 1;
791
792        // Handle forward:norebind:<local>... here
793        if (createForward && !strncmp(local, "norebind:", 9)) {
794            no_rebind = 1;
795            local = strchr(local, ':') + 1;
796        }
797
798        remote = strchr(local,';');
799
800        if (createForward) {
801            // Check forward: parameter format: '<local>;<remote>'
802            if(remote == 0) {
803                sendfailmsg(reply_fd, "malformed forward spec");
804                return 1;
805            }
806
807            *remote++ = 0;
808            if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')) {
809                sendfailmsg(reply_fd, "malformed forward spec");
810                return 1;
811            }
812        } else {
813            // Check killforward: parameter format: '<local>'
814            if (local[0] == 0) {
815                sendfailmsg(reply_fd, "malformed forward spec");
816                return 1;
817            }
818        }
819
820        std::string error_msg;
821        transport = acquire_one_transport(CS_ANY, ttype, serial, &error_msg);
822        if (!transport) {
823            sendfailmsg(reply_fd, error_msg.c_str());
824            return 1;
825        }
826
827        install_status_t r;
828        if (createForward) {
829            r = install_listener(local, remote, transport, no_rebind);
830        } else {
831            r = remove_listener(local, transport);
832        }
833        if (r == INSTALL_STATUS_OK) {
834#if ADB_HOST
835            /* On the host: 1st OKAY is connect, 2nd OKAY is status */
836            WriteFdExactly(reply_fd, "OKAY", 4);
837#endif
838            WriteFdExactly(reply_fd, "OKAY", 4);
839            return 1;
840        }
841
842        std::string message;
843        switch (r) {
844          case INSTALL_STATUS_OK: message = " "; break;
845          case INSTALL_STATUS_INTERNAL_ERROR: message = "internal error"; break;
846          case INSTALL_STATUS_CANNOT_BIND:
847            message = android::base::StringPrintf("cannot bind to socket: %s", strerror(errno));
848            break;
849          case INSTALL_STATUS_CANNOT_REBIND:
850            message = android::base::StringPrintf("cannot rebind existing socket: %s", strerror(errno));
851            break;
852          case INSTALL_STATUS_LISTENER_NOT_FOUND: message = "listener not found"; break;
853        }
854        sendfailmsg(reply_fd, message.c_str());
855        return 1;
856    }
857    return 0;
858}
859
860int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
861{
862    if(!strcmp(service, "kill")) {
863        fprintf(stderr,"adb server killed by remote request\n");
864        fflush(stdout);
865        adb_write(reply_fd, "OKAY", 4);
866        usb_cleanup();
867        exit(0);
868    }
869
870#if ADB_HOST
871    atransport *transport = NULL;
872    // "transport:" is used for switching transport with a specified serial number
873    // "transport-usb:" is used for switching transport to the only USB transport
874    // "transport-local:" is used for switching transport to the only local transport
875    // "transport-any:" is used for switching transport to the only transport
876    if (!strncmp(service, "transport", strlen("transport"))) {
877        transport_type type = kTransportAny;
878
879        if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
880            type = kTransportUsb;
881        } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
882            type = kTransportLocal;
883        } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
884            type = kTransportAny;
885        } else if (!strncmp(service, "transport:", strlen("transport:"))) {
886            service += strlen("transport:");
887            serial = service;
888        }
889
890        std::string error_msg = "unknown failure";
891        transport = acquire_one_transport(CS_ANY, type, serial, &error_msg);
892
893        if (transport) {
894            s->transport = transport;
895            adb_write(reply_fd, "OKAY", 4);
896        } else {
897            sendfailmsg(reply_fd, error_msg.c_str());
898        }
899        return 1;
900    }
901
902    // return a list of all connected devices
903    if (!strncmp(service, "devices", 7)) {
904        char buffer[4096];
905        int use_long = !strcmp(service+7, "-l");
906        if (use_long || service[7] == 0) {
907            memset(buffer, 0, sizeof(buffer));
908            D("Getting device list \n");
909            list_transports(buffer, sizeof(buffer), use_long);
910            D("Wrote device list \n");
911            send_msg_with_okay(reply_fd, buffer, strlen(buffer));
912            return 0;
913        }
914    }
915
916    // remove TCP transport
917    if (!strncmp(service, "disconnect:", 11)) {
918        char buffer[4096];
919        memset(buffer, 0, sizeof(buffer));
920        char* serial = service + 11;
921        if (serial[0] == 0) {
922            // disconnect from all TCP devices
923            unregister_all_tcp_transports();
924        } else {
925            char hostbuf[100];
926            // assume port 5555 if no port is specified
927            if (!strchr(serial, ':')) {
928                snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:5555", serial);
929                serial = hostbuf;
930            }
931            atransport *t = find_transport(serial);
932
933            if (t) {
934                unregister_transport(t);
935            } else {
936                snprintf(buffer, sizeof(buffer), "No such device %s", serial);
937            }
938        }
939
940        send_msg_with_okay(reply_fd, buffer, strlen(buffer));
941        return 0;
942    }
943
944    // returns our value for ADB_SERVER_VERSION
945    if (!strcmp(service, "version")) {
946        char version[12];
947        snprintf(version, sizeof version, "%04x", ADB_SERVER_VERSION);
948        send_msg_with_okay(reply_fd, version, strlen(version));
949        return 0;
950    }
951
952    if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
953        const char *out = "unknown";
954        transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
955        if (transport && transport->serial) {
956            out = transport->serial;
957        }
958        send_msg_with_okay(reply_fd, out, strlen(out));
959        return 0;
960    }
961    if(!strncmp(service,"get-devpath",strlen("get-devpath"))) {
962        const char *out = "unknown";
963        transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
964        if (transport && transport->devpath) {
965            out = transport->devpath;
966        }
967        send_msg_with_okay(reply_fd, out, strlen(out));
968        return 0;
969    }
970    // indicates a new emulator instance has started
971    if (!strncmp(service,"emulator:",9)) {
972        int  port = atoi(service+9);
973        local_connect(port);
974        /* we don't even need to send a reply */
975        return 0;
976    }
977
978    if(!strncmp(service,"get-state",strlen("get-state"))) {
979        transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
980        const char *state = connection_state_name(transport);
981        send_msg_with_okay(reply_fd, state, strlen(state));
982        return 0;
983    }
984#endif // ADB_HOST
985
986    int ret = handle_forward_request(service, ttype, serial, reply_fd);
987    if (ret >= 0)
988      return ret - 1;
989    return -1;
990}
991