Home | History | Annotate | Download | only in adb
      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 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 <chrono>
     34 #include <condition_variable>
     35 #include <mutex>
     36 #include <string>
     37 #include <thread>
     38 #include <vector>
     39 
     40 #include <android-base/errors.h>
     41 #include <android-base/file.h>
     42 #include <android-base/logging.h>
     43 #include <android-base/macros.h>
     44 #include <android-base/parsenetaddress.h>
     45 #include <android-base/quick_exit.h>
     46 #include <android-base/stringprintf.h>
     47 #include <android-base/strings.h>
     48 
     49 #include "adb_auth.h"
     50 #include "adb_io.h"
     51 #include "adb_listeners.h"
     52 #include "adb_unique_fd.h"
     53 #include "adb_utils.h"
     54 #include "sysdeps/chrono.h"
     55 #include "transport.h"
     56 
     57 #if !ADB_HOST
     58 #include <sys/capability.h>
     59 #include <sys/mount.h>
     60 #include <android-base/properties.h>
     61 using namespace std::chrono_literals;
     62 #endif
     63 
     64 std::string adb_version() {
     65     // Don't change the format of this --- it's parsed by ddmlib.
     66     return android::base::StringPrintf(
     67         "Android Debug Bridge version %d.%d.%d\n"
     68         "Version %s\n"
     69         "Installed as %s\n",
     70         ADB_VERSION_MAJOR, ADB_VERSION_MINOR, ADB_SERVER_VERSION, ADB_VERSION,
     71         android::base::GetExecutablePath().c_str());
     72 }
     73 
     74 void fatal(const char *fmt, ...) {
     75     va_list ap;
     76     va_start(ap, fmt);
     77     char buf[1024];
     78     vsnprintf(buf, sizeof(buf), fmt, ap);
     79 
     80 #if ADB_HOST
     81     fprintf(stderr, "error: %s\n", buf);
     82 #else
     83     LOG(ERROR) << "error: " << buf;
     84 #endif
     85 
     86     va_end(ap);
     87     abort();
     88 }
     89 
     90 void fatal_errno(const char* fmt, ...) {
     91     int err = errno;
     92     va_list ap;
     93     va_start(ap, fmt);
     94     char buf[1024];
     95     vsnprintf(buf, sizeof(buf), fmt, ap);
     96 
     97 #if ADB_HOST
     98     fprintf(stderr, "error: %s: %s\n", buf, strerror(err));
     99 #else
    100     LOG(ERROR) << "error: " << buf << ": " << strerror(err);
    101 #endif
    102 
    103     va_end(ap);
    104     abort();
    105 }
    106 
    107 uint32_t calculate_apacket_checksum(const apacket* p) {
    108     const unsigned char* x = reinterpret_cast<const unsigned char*>(p->data);
    109     uint32_t sum = 0;
    110     size_t count = p->msg.data_length;
    111 
    112     while (count-- > 0) {
    113         sum += *x++;
    114     }
    115 
    116     return sum;
    117 }
    118 
    119 apacket* get_apacket(void)
    120 {
    121     apacket* p = reinterpret_cast<apacket*>(malloc(sizeof(apacket)));
    122     if (p == nullptr) {
    123       fatal("failed to allocate an apacket");
    124     }
    125 
    126     memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
    127     return p;
    128 }
    129 
    130 void put_apacket(apacket *p)
    131 {
    132     free(p);
    133 }
    134 
    135 void handle_online(atransport *t)
    136 {
    137     D("adb: online");
    138     t->online = 1;
    139 }
    140 
    141 void handle_offline(atransport *t)
    142 {
    143     D("adb: offline");
    144     //Close the associated usb
    145     t->online = 0;
    146 
    147     // This is necessary to avoid a race condition that occurred when a transport closes
    148     // while a client socket is still active.
    149     close_all_sockets(t);
    150 
    151     t->RunDisconnects();
    152 }
    153 
    154 #if DEBUG_PACKETS
    155 #define DUMPMAX 32
    156 void print_packet(const char *label, apacket *p)
    157 {
    158     char *tag;
    159     char *x;
    160     unsigned count;
    161 
    162     switch(p->msg.command){
    163     case A_SYNC: tag = "SYNC"; break;
    164     case A_CNXN: tag = "CNXN" ; break;
    165     case A_OPEN: tag = "OPEN"; break;
    166     case A_OKAY: tag = "OKAY"; break;
    167     case A_CLSE: tag = "CLSE"; break;
    168     case A_WRTE: tag = "WRTE"; break;
    169     case A_AUTH: tag = "AUTH"; break;
    170     default: tag = "????"; break;
    171     }
    172 
    173     fprintf(stderr, "%s: %s %08x %08x %04x \"",
    174             label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
    175     count = p->msg.data_length;
    176     x = (char*) p->data;
    177     if(count > DUMPMAX) {
    178         count = DUMPMAX;
    179         tag = "\n";
    180     } else {
    181         tag = "\"\n";
    182     }
    183     while(count-- > 0){
    184         if((*x >= ' ') && (*x < 127)) {
    185             fputc(*x, stderr);
    186         } else {
    187             fputc('.', stderr);
    188         }
    189         x++;
    190     }
    191     fputs(tag, stderr);
    192 }
    193 #endif
    194 
    195 static void send_ready(unsigned local, unsigned remote, atransport *t)
    196 {
    197     D("Calling send_ready");
    198     apacket *p = get_apacket();
    199     p->msg.command = A_OKAY;
    200     p->msg.arg0 = local;
    201     p->msg.arg1 = remote;
    202     send_packet(p, t);
    203 }
    204 
    205 static void send_close(unsigned local, unsigned remote, atransport *t)
    206 {
    207     D("Calling send_close");
    208     apacket *p = get_apacket();
    209     p->msg.command = A_CLSE;
    210     p->msg.arg0 = local;
    211     p->msg.arg1 = remote;
    212     send_packet(p, t);
    213 }
    214 
    215 std::string get_connection_string() {
    216     std::vector<std::string> connection_properties;
    217 
    218 #if !ADB_HOST
    219     static const char* cnxn_props[] = {
    220         "ro.product.name",
    221         "ro.product.model",
    222         "ro.product.device",
    223     };
    224 
    225     for (const auto& prop : cnxn_props) {
    226         std::string value = std::string(prop) + "=" + android::base::GetProperty(prop, "");
    227         connection_properties.push_back(value);
    228     }
    229 #endif
    230 
    231     connection_properties.push_back(android::base::StringPrintf(
    232         "features=%s", FeatureSetToString(supported_features()).c_str()));
    233 
    234     return android::base::StringPrintf(
    235         "%s::%s", adb_device_banner,
    236         android::base::Join(connection_properties, ';').c_str());
    237 }
    238 
    239 void send_connect(atransport* t) {
    240     D("Calling send_connect");
    241     apacket* cp = get_apacket();
    242     cp->msg.command = A_CNXN;
    243     cp->msg.arg0 = t->get_protocol_version();
    244     cp->msg.arg1 = t->get_max_payload();
    245 
    246     std::string connection_str = get_connection_string();
    247     // Connect and auth packets are limited to MAX_PAYLOAD_V1 because we don't
    248     // yet know how much data the other size is willing to accept.
    249     if (connection_str.length() > MAX_PAYLOAD_V1) {
    250         LOG(FATAL) << "Connection banner is too long (length = "
    251                    << connection_str.length() << ")";
    252     }
    253 
    254     memcpy(cp->data, connection_str.c_str(), connection_str.length());
    255     cp->msg.data_length = connection_str.length();
    256 
    257     send_packet(cp, t);
    258 }
    259 
    260 // qual_overwrite is used to overwrite a qualifier string.  dst is a
    261 // pointer to a char pointer.  It is assumed that if *dst is non-NULL, it
    262 // was malloc'ed and needs to freed.  *dst will be set to a dup of src.
    263 // TODO: switch to std::string for these atransport fields instead.
    264 static void qual_overwrite(char** dst, const std::string& src) {
    265     free(*dst);
    266     *dst = strdup(src.c_str());
    267 }
    268 
    269 void parse_banner(const std::string& banner, atransport* t) {
    270     D("parse_banner: %s", banner.c_str());
    271 
    272     // The format is something like:
    273     // "device::ro.product.name=x;ro.product.model=y;ro.product.device=z;".
    274     std::vector<std::string> pieces = android::base::Split(banner, ":");
    275 
    276     // Reset the features list or else if the server sends no features we may
    277     // keep the existing feature set (http://b/24405971).
    278     t->SetFeatures("");
    279 
    280     if (pieces.size() > 2) {
    281         const std::string& props = pieces[2];
    282         for (const auto& prop : android::base::Split(props, ";")) {
    283             // The list of properties was traditionally ;-terminated rather than ;-separated.
    284             if (prop.empty()) continue;
    285 
    286             std::vector<std::string> key_value = android::base::Split(prop, "=");
    287             if (key_value.size() != 2) continue;
    288 
    289             const std::string& key = key_value[0];
    290             const std::string& value = key_value[1];
    291             if (key == "ro.product.name") {
    292                 qual_overwrite(&t->product, value);
    293             } else if (key == "ro.product.model") {
    294                 qual_overwrite(&t->model, value);
    295             } else if (key == "ro.product.device") {
    296                 qual_overwrite(&t->device, value);
    297             } else if (key == "features") {
    298                 t->SetFeatures(value);
    299             }
    300         }
    301     }
    302 
    303     const std::string& type = pieces[0];
    304     if (type == "bootloader") {
    305         D("setting connection_state to kCsBootloader");
    306         t->SetConnectionState(kCsBootloader);
    307     } else if (type == "device") {
    308         D("setting connection_state to kCsDevice");
    309         t->SetConnectionState(kCsDevice);
    310     } else if (type == "recovery") {
    311         D("setting connection_state to kCsRecovery");
    312         t->SetConnectionState(kCsRecovery);
    313     } else if (type == "sideload") {
    314         D("setting connection_state to kCsSideload");
    315         t->SetConnectionState(kCsSideload);
    316     } else {
    317         D("setting connection_state to kCsHost");
    318         t->SetConnectionState(kCsHost);
    319     }
    320 }
    321 
    322 static void handle_new_connection(atransport* t, apacket* p) {
    323     if (t->GetConnectionState() != kCsOffline) {
    324         t->SetConnectionState(kCsOffline);
    325         handle_offline(t);
    326     }
    327 
    328     t->update_version(p->msg.arg0, p->msg.arg1);
    329     std::string banner(reinterpret_cast<const char*>(p->data),
    330                        p->msg.data_length);
    331     parse_banner(banner, t);
    332 
    333 #if ADB_HOST
    334     handle_online(t);
    335 #else
    336     if (!auth_required) {
    337         handle_online(t);
    338         send_connect(t);
    339     } else {
    340         send_auth_request(t);
    341     }
    342 #endif
    343 
    344     update_transports();
    345 }
    346 
    347 void handle_packet(apacket *p, atransport *t)
    348 {
    349     D("handle_packet() %c%c%c%c", ((char*) (&(p->msg.command)))[0],
    350             ((char*) (&(p->msg.command)))[1],
    351             ((char*) (&(p->msg.command)))[2],
    352             ((char*) (&(p->msg.command)))[3]);
    353     print_packet("recv", p);
    354 
    355     switch(p->msg.command){
    356     case A_SYNC:
    357         if (p->msg.arg0){
    358             send_packet(p, t);
    359 #if ADB_HOST
    360             send_connect(t);
    361 #endif
    362         } else {
    363             t->SetConnectionState(kCsOffline);
    364             handle_offline(t);
    365             send_packet(p, t);
    366         }
    367         return;
    368 
    369     case A_CNXN:  // CONNECT(version, maxdata, "system-id-string")
    370         handle_new_connection(t, p);
    371         break;
    372 
    373     case A_AUTH:
    374         switch (p->msg.arg0) {
    375 #if ADB_HOST
    376             case ADB_AUTH_TOKEN:
    377                 if (t->GetConnectionState() == kCsOffline) {
    378                     t->SetConnectionState(kCsUnauthorized);
    379                 }
    380                 send_auth_response(p->data, p->msg.data_length, t);
    381                 break;
    382 #else
    383             case ADB_AUTH_SIGNATURE:
    384                 if (adbd_auth_verify(t->token, sizeof(t->token), p->data, p->msg.data_length)) {
    385                     adbd_auth_verified(t);
    386                     t->failed_auth_attempts = 0;
    387                 } else {
    388                     if (t->failed_auth_attempts++ > 256) std::this_thread::sleep_for(1s);
    389                     send_auth_request(t);
    390                 }
    391                 break;
    392 
    393             case ADB_AUTH_RSAPUBLICKEY:
    394                 adbd_auth_confirm_key(p->data, p->msg.data_length, t);
    395                 break;
    396 #endif
    397             default:
    398                 t->SetConnectionState(kCsOffline);
    399                 handle_offline(t);
    400                 break;
    401         }
    402         break;
    403 
    404     case A_OPEN: /* OPEN(local-id, 0, "destination") */
    405         if (t->online && p->msg.arg0 != 0 && p->msg.arg1 == 0) {
    406             char *name = (char*) p->data;
    407             name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
    408             asocket* s = create_local_service_socket(name, t);
    409             if (s == nullptr) {
    410                 send_close(0, p->msg.arg0, t);
    411             } else {
    412                 s->peer = create_remote_socket(p->msg.arg0, t);
    413                 s->peer->peer = s;
    414                 send_ready(s->id, s->peer->id, t);
    415                 s->ready(s);
    416             }
    417         }
    418         break;
    419 
    420     case A_OKAY: /* READY(local-id, remote-id, "") */
    421         if (t->online && p->msg.arg0 != 0 && p->msg.arg1 != 0) {
    422             asocket* s = find_local_socket(p->msg.arg1, 0);
    423             if (s) {
    424                 if(s->peer == 0) {
    425                     /* On first READY message, create the connection. */
    426                     s->peer = create_remote_socket(p->msg.arg0, t);
    427                     s->peer->peer = s;
    428                     s->ready(s);
    429                 } else if (s->peer->id == p->msg.arg0) {
    430                     /* Other READY messages must use the same local-id */
    431                     s->ready(s);
    432                 } else {
    433                     D("Invalid A_OKAY(%d,%d), expected A_OKAY(%d,%d) on transport %s",
    434                       p->msg.arg0, p->msg.arg1, s->peer->id, p->msg.arg1, t->serial);
    435                 }
    436             } else {
    437                 // When receiving A_OKAY from device for A_OPEN request, the host server may
    438                 // have closed the local socket because of client disconnection. Then we need
    439                 // to send A_CLSE back to device to close the service on device.
    440                 send_close(p->msg.arg1, p->msg.arg0, t);
    441             }
    442         }
    443         break;
    444 
    445     case A_CLSE: /* CLOSE(local-id, remote-id, "") or CLOSE(0, remote-id, "") */
    446         if (t->online && p->msg.arg1 != 0) {
    447             asocket* s = find_local_socket(p->msg.arg1, p->msg.arg0);
    448             if (s) {
    449                 /* According to protocol.txt, p->msg.arg0 might be 0 to indicate
    450                  * a failed OPEN only. However, due to a bug in previous ADB
    451                  * versions, CLOSE(0, remote-id, "") was also used for normal
    452                  * CLOSE() operations.
    453                  *
    454                  * This is bad because it means a compromised adbd could
    455                  * send packets to close connections between the host and
    456                  * other devices. To avoid this, only allow this if the local
    457                  * socket has a peer on the same transport.
    458                  */
    459                 if (p->msg.arg0 == 0 && s->peer && s->peer->transport != t) {
    460                     D("Invalid A_CLSE(0, %u) from transport %s, expected transport %s",
    461                       p->msg.arg1, t->serial, s->peer->transport->serial);
    462                 } else {
    463                     s->close(s);
    464                 }
    465             }
    466         }
    467         break;
    468 
    469     case A_WRTE: /* WRITE(local-id, remote-id, <data>) */
    470         if (t->online && p->msg.arg0 != 0 && p->msg.arg1 != 0) {
    471             asocket* s = find_local_socket(p->msg.arg1, p->msg.arg0);
    472             if (s) {
    473                 unsigned rid = p->msg.arg0;
    474                 p->len = p->msg.data_length;
    475 
    476                 if (s->enqueue(s, p) == 0) {
    477                     D("Enqueue the socket");
    478                     send_ready(s->id, rid, t);
    479                 }
    480                 return;
    481             }
    482         }
    483         break;
    484 
    485     default:
    486         printf("handle_packet: what is %08x?!\n", p->msg.command);
    487     }
    488 
    489     put_apacket(p);
    490 }
    491 
    492 #if ADB_HOST
    493 
    494 #ifdef _WIN32
    495 
    496 // Try to make a handle non-inheritable and if there is an error, don't output
    497 // any error info, but leave GetLastError() for the caller to read. This is
    498 // convenient if the caller is expecting that this may fail and they'd like to
    499 // ignore such a failure.
    500 static bool _try_make_handle_noninheritable(HANDLE h) {
    501     if (h != INVALID_HANDLE_VALUE && h != NULL) {
    502         return SetHandleInformation(h, HANDLE_FLAG_INHERIT, 0) ? true : false;
    503     }
    504 
    505     return true;
    506 }
    507 
    508 // Try to make a handle non-inheritable with the expectation that this should
    509 // succeed, so if this fails, output error info.
    510 static bool _make_handle_noninheritable(HANDLE h) {
    511     if (!_try_make_handle_noninheritable(h)) {
    512         // Show the handle value to give us a clue in case we have problems
    513         // with pseudo-handle values.
    514         fprintf(stderr, "adb: cannot make handle 0x%p non-inheritable: %s\n", h,
    515                 android::base::SystemErrorCodeToString(GetLastError()).c_str());
    516         return false;
    517     }
    518 
    519     return true;
    520 }
    521 
    522 // Create anonymous pipe, preventing inheritance of the read pipe and setting
    523 // security of the write pipe to sa.
    524 static bool _create_anonymous_pipe(unique_handle* pipe_read_out,
    525                                    unique_handle* pipe_write_out,
    526                                    SECURITY_ATTRIBUTES* sa) {
    527     HANDLE pipe_read_raw = NULL;
    528     HANDLE pipe_write_raw = NULL;
    529     if (!CreatePipe(&pipe_read_raw, &pipe_write_raw, sa, 0)) {
    530         fprintf(stderr, "adb: CreatePipe failed: %s\n",
    531                 android::base::SystemErrorCodeToString(GetLastError()).c_str());
    532         return false;
    533     }
    534 
    535     unique_handle pipe_read(pipe_read_raw);
    536     pipe_read_raw = NULL;
    537     unique_handle pipe_write(pipe_write_raw);
    538     pipe_write_raw = NULL;
    539 
    540     if (!_make_handle_noninheritable(pipe_read.get())) {
    541         return false;
    542     }
    543 
    544     *pipe_read_out = std::move(pipe_read);
    545     *pipe_write_out = std::move(pipe_write);
    546 
    547     return true;
    548 }
    549 
    550 // Read from a pipe (that we take ownership of) and write the result to stdout/stderr. Return on
    551 // error or when the pipe is closed. Internally makes inheritable handles, so this should not be
    552 // called if subprocesses may be started concurrently.
    553 static unsigned _redirect_pipe_thread(HANDLE h, DWORD nStdHandle) {
    554     // Take ownership of the HANDLE and close when we're done.
    555     unique_handle   read_pipe(h);
    556     const char*     output_name = nStdHandle == STD_OUTPUT_HANDLE ? "stdout" : "stderr";
    557     const int       original_fd = fileno(nStdHandle == STD_OUTPUT_HANDLE ? stdout : stderr);
    558     std::unique_ptr<FILE, decltype(&fclose)> stream(nullptr, fclose);
    559 
    560     if (original_fd == -1) {
    561         fprintf(stderr, "adb: failed to get file descriptor for %s: %s\n", output_name,
    562                 strerror(errno));
    563         return EXIT_FAILURE;
    564     }
    565 
    566     // If fileno() is -2, stdout/stderr is not associated with an output stream, so we should read,
    567     // but don't write. Otherwise, make a FILE* identical to stdout/stderr except that it is in
    568     // binary mode with no CR/LR translation since we're reading raw.
    569     if (original_fd >= 0) {
    570         // This internally makes a duplicate file handle that is inheritable, so callers should not
    571         // call this function if subprocesses may be started concurrently.
    572         const int fd = dup(original_fd);
    573         if (fd == -1) {
    574             fprintf(stderr, "adb: failed to duplicate file descriptor for %s: %s\n", output_name,
    575                     strerror(errno));
    576             return EXIT_FAILURE;
    577         }
    578 
    579         // Note that although we call fdopen() below with a binary flag, it may not adhere to that
    580         // flag, so we have to set the mode manually.
    581         if (_setmode(fd, _O_BINARY) == -1) {
    582             fprintf(stderr, "adb: failed to set binary mode for duplicate of %s: %s\n", output_name,
    583                     strerror(errno));
    584             unix_close(fd);
    585             return EXIT_FAILURE;
    586         }
    587 
    588         stream.reset(fdopen(fd, "wb"));
    589         if (stream.get() == nullptr) {
    590             fprintf(stderr, "adb: failed to open duplicate stream for %s: %s\n", output_name,
    591                     strerror(errno));
    592             unix_close(fd);
    593             return EXIT_FAILURE;
    594         }
    595 
    596         // Unbuffer the stream because it will be buffered by default and we want subprocess output
    597         // to be shown immediately.
    598         if (setvbuf(stream.get(), NULL, _IONBF, 0) == -1) {
    599             fprintf(stderr, "adb: failed to unbuffer %s: %s\n", output_name, strerror(errno));
    600             return EXIT_FAILURE;
    601         }
    602 
    603         // fd will be closed when stream is closed.
    604     }
    605 
    606     while (true) {
    607         char    buf[64 * 1024];
    608         DWORD   bytes_read = 0;
    609         if (!ReadFile(read_pipe.get(), buf, sizeof(buf), &bytes_read, NULL)) {
    610             const DWORD err = GetLastError();
    611             // ERROR_BROKEN_PIPE is expected when the subprocess closes
    612             // the other end of the pipe.
    613             if (err == ERROR_BROKEN_PIPE) {
    614                 return EXIT_SUCCESS;
    615             } else {
    616                 fprintf(stderr, "adb: failed to read from %s: %s\n", output_name,
    617                         android::base::SystemErrorCodeToString(err).c_str());
    618                 return EXIT_FAILURE;
    619             }
    620         }
    621 
    622         // Don't try to write if our stdout/stderr was not setup by the parent process.
    623         if (stream) {
    624             // fwrite() actually calls adb_fwrite() which can write UTF-8 to the console.
    625             const size_t bytes_written = fwrite(buf, 1, bytes_read, stream.get());
    626             if (bytes_written != bytes_read) {
    627                 fprintf(stderr, "adb: error: only wrote %zu of %lu bytes to %s\n", bytes_written,
    628                         bytes_read, output_name);
    629                 return EXIT_FAILURE;
    630             }
    631         }
    632     }
    633 }
    634 
    635 static unsigned __stdcall _redirect_stdout_thread(HANDLE h) {
    636     adb_thread_setname("stdout redirect");
    637     return _redirect_pipe_thread(h, STD_OUTPUT_HANDLE);
    638 }
    639 
    640 static unsigned __stdcall _redirect_stderr_thread(HANDLE h) {
    641     adb_thread_setname("stderr redirect");
    642     return _redirect_pipe_thread(h, STD_ERROR_HANDLE);
    643 }
    644 
    645 #endif
    646 
    647 static void ReportServerStartupFailure(pid_t pid) {
    648     fprintf(stderr, "ADB server didn't ACK\n");
    649     fprintf(stderr, "Full server startup log: %s\n", GetLogFilePath().c_str());
    650     fprintf(stderr, "Server had pid: %d\n", pid);
    651 
    652     unique_fd fd(adb_open(GetLogFilePath().c_str(), O_RDONLY));
    653     if (fd == -1) return;
    654 
    655     // Let's not show more than 128KiB of log...
    656     adb_lseek(fd, -128 * 1024, SEEK_END);
    657     std::string content;
    658     if (!android::base::ReadFdToString(fd, &content)) return;
    659 
    660     std::string header = android::base::StringPrintf("--- adb starting (pid %d) ---", pid);
    661     std::vector<std::string> lines = android::base::Split(content, "\n");
    662     int i = lines.size() - 1;
    663     while (i >= 0 && lines[i] != header) --i;
    664     while (static_cast<size_t>(i) < lines.size()) fprintf(stderr, "%s\n", lines[i++].c_str());
    665 }
    666 
    667 int launch_server(const std::string& socket_spec) {
    668 #if defined(_WIN32)
    669     /* we need to start the server in the background                    */
    670     /* we create a PIPE that will be used to wait for the server's "OK" */
    671     /* message since the pipe handles must be inheritable, we use a     */
    672     /* security attribute                                               */
    673     SECURITY_ATTRIBUTES   sa;
    674     sa.nLength = sizeof(sa);
    675     sa.lpSecurityDescriptor = NULL;
    676     sa.bInheritHandle = TRUE;
    677 
    678     // Redirect stdin to Windows /dev/null. If we instead pass an original
    679     // stdin/stdout/stderr handle and it is a console handle, when the adb
    680     // server starts up, the C Runtime will see a console handle for a process
    681     // that isn't connected to a console and it will configure
    682     // stdin/stdout/stderr to be closed. At that point, freopen() could be used
    683     // to reopen stderr/out, but it would take more massaging to fixup the file
    684     // descriptor number that freopen() uses. It's simplest to avoid all of this
    685     // complexity by just redirecting stdin to `nul' and then the C Runtime acts
    686     // as expected.
    687     unique_handle   nul_read(CreateFileW(L"nul", GENERIC_READ,
    688             FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING,
    689             FILE_ATTRIBUTE_NORMAL, NULL));
    690     if (nul_read.get() == INVALID_HANDLE_VALUE) {
    691         fprintf(stderr, "adb: CreateFileW 'nul' failed: %s\n",
    692                 android::base::SystemErrorCodeToString(GetLastError()).c_str());
    693         return -1;
    694     }
    695 
    696     // Create pipes with non-inheritable read handle, inheritable write handle. We need to connect
    697     // the subprocess to pipes instead of just letting the subprocess inherit our existing
    698     // stdout/stderr handles because a DETACHED_PROCESS cannot write to a console that it is not
    699     // attached to.
    700     unique_handle   ack_read, ack_write;
    701     if (!_create_anonymous_pipe(&ack_read, &ack_write, &sa)) {
    702         return -1;
    703     }
    704     unique_handle   stdout_read, stdout_write;
    705     if (!_create_anonymous_pipe(&stdout_read, &stdout_write, &sa)) {
    706         return -1;
    707     }
    708     unique_handle   stderr_read, stderr_write;
    709     if (!_create_anonymous_pipe(&stderr_read, &stderr_write, &sa)) {
    710         return -1;
    711     }
    712 
    713     /* Some programs want to launch an adb command and collect its output by
    714      * calling CreateProcess with inheritable stdout/stderr handles, then
    715      * using read() to get its output. When this happens, the stdout/stderr
    716      * handles passed to the adb client process will also be inheritable.
    717      * When starting the adb server here, care must be taken to reset them
    718      * to non-inheritable.
    719      * Otherwise, something bad happens: even if the adb command completes,
    720      * the calling process is stuck while read()-ing from the stdout/stderr
    721      * descriptors, because they're connected to corresponding handles in the
    722      * adb server process (even if the latter never uses/writes to them).
    723      * Note that even if we don't pass these handles in the STARTUPINFO struct,
    724      * if they're marked inheritable, they're still inherited, requiring us to
    725      * deal with this.
    726      *
    727      * If we're still having problems with inheriting random handles in the
    728      * future, consider using PROC_THREAD_ATTRIBUTE_HANDLE_LIST to explicitly
    729      * specify which handles should be inherited: http://blogs.msdn.com/b/oldnewthing/archive/2011/12/16/10248328.aspx
    730      *
    731      * Older versions of Windows return console pseudo-handles that cannot be
    732      * made non-inheritable, so ignore those failures.
    733      */
    734     _try_make_handle_noninheritable(GetStdHandle(STD_INPUT_HANDLE));
    735     _try_make_handle_noninheritable(GetStdHandle(STD_OUTPUT_HANDLE));
    736     _try_make_handle_noninheritable(GetStdHandle(STD_ERROR_HANDLE));
    737 
    738     STARTUPINFOW    startup;
    739     ZeroMemory( &startup, sizeof(startup) );
    740     startup.cb = sizeof(startup);
    741     startup.hStdInput  = nul_read.get();
    742     startup.hStdOutput = stdout_write.get();
    743     startup.hStdError  = stderr_write.get();
    744     startup.dwFlags    = STARTF_USESTDHANDLES;
    745 
    746     // Verify that the pipe_write handle value can be passed on the command line
    747     // as %d and that the rest of adb code can pass it around in an int.
    748     const int ack_write_as_int = cast_handle_to_int(ack_write.get());
    749     if (cast_int_to_handle(ack_write_as_int) != ack_write.get()) {
    750         // If this fires, either handle values are larger than 32-bits or else
    751         // there is a bug in our casting.
    752         // https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203%28v=vs.85%29.aspx
    753         fprintf(stderr, "adb: cannot fit pipe handle value into 32-bits: 0x%p\n", ack_write.get());
    754         return -1;
    755     }
    756 
    757     // get path of current program
    758     WCHAR       program_path[MAX_PATH];
    759     const DWORD module_result = GetModuleFileNameW(NULL, program_path,
    760                                                    arraysize(program_path));
    761     if ((module_result >= arraysize(program_path)) || (module_result == 0)) {
    762         // String truncation or some other error.
    763         fprintf(stderr, "adb: cannot get executable path: %s\n",
    764                 android::base::SystemErrorCodeToString(GetLastError()).c_str());
    765         return -1;
    766     }
    767 
    768     WCHAR   args[64];
    769     snwprintf(args, arraysize(args), L"adb -L %s fork-server server --reply-fd %d",
    770               socket_spec.c_str(), ack_write_as_int);
    771 
    772     PROCESS_INFORMATION   pinfo;
    773     ZeroMemory(&pinfo, sizeof(pinfo));
    774 
    775     if (!CreateProcessW(
    776             program_path,                              /* program path  */
    777             args,
    778                                     /* the fork-server argument will set the
    779                                        debug = 2 in the child           */
    780             NULL,                   /* process handle is not inheritable */
    781             NULL,                    /* thread handle is not inheritable */
    782             TRUE,                          /* yes, inherit some handles */
    783             DETACHED_PROCESS, /* the new process doesn't have a console */
    784             NULL,                     /* use parent's environment block */
    785             NULL,                    /* use parent's starting directory */
    786             &startup,                 /* startup info, i.e. std handles */
    787             &pinfo )) {
    788         fprintf(stderr, "adb: CreateProcessW failed: %s\n",
    789                 android::base::SystemErrorCodeToString(GetLastError()).c_str());
    790         return -1;
    791     }
    792 
    793     unique_handle   process_handle(pinfo.hProcess);
    794     pinfo.hProcess = NULL;
    795 
    796     // Close handles that we no longer need to complete the rest.
    797     CloseHandle(pinfo.hThread);
    798     pinfo.hThread = NULL;
    799 
    800     nul_read.reset();
    801     ack_write.reset();
    802     stdout_write.reset();
    803     stderr_write.reset();
    804 
    805     // Start threads to read from subprocess stdout/stderr and write to ours to make subprocess
    806     // errors easier to diagnose. Note that the threads internally create inheritable handles, but
    807     // that is ok because we've already spawned the subprocess.
    808 
    809     // In the past, reading from a pipe before the child process's C Runtime
    810     // started up and called GetFileType() caused a hang: http://blogs.msdn.com/b/oldnewthing/archive/2011/12/02/10243553.aspx#10244216
    811     // This is reportedly fixed in Windows Vista: https://support.microsoft.com/en-us/kb/2009703
    812     // I was unable to reproduce the problem on Windows XP. It sounds like a
    813     // Windows Update may have fixed this: https://www.duckware.com/tech/peeknamedpipe.html
    814     unique_handle   stdout_thread(reinterpret_cast<HANDLE>(
    815             _beginthreadex(NULL, 0, _redirect_stdout_thread, stdout_read.get(),
    816                            0, NULL)));
    817     if (stdout_thread.get() == nullptr) {
    818         fprintf(stderr, "adb: cannot create thread: %s\n", strerror(errno));
    819         return -1;
    820     }
    821     stdout_read.release();  // Transfer ownership to new thread
    822 
    823     unique_handle   stderr_thread(reinterpret_cast<HANDLE>(
    824             _beginthreadex(NULL, 0, _redirect_stderr_thread, stderr_read.get(),
    825                            0, NULL)));
    826     if (stderr_thread.get() == nullptr) {
    827         fprintf(stderr, "adb: cannot create thread: %s\n", strerror(errno));
    828         return -1;
    829     }
    830     stderr_read.release();  // Transfer ownership to new thread
    831 
    832     bool    got_ack = false;
    833 
    834     // Wait for the "OK\n" message, for the pipe to be closed, or other error.
    835     {
    836         char    temp[3];
    837         DWORD   count = 0;
    838 
    839         if (ReadFile(ack_read.get(), temp, sizeof(temp), &count, NULL)) {
    840             const CHAR  expected[] = "OK\n";
    841             const DWORD expected_length = arraysize(expected) - 1;
    842             if (count == expected_length &&
    843                 memcmp(temp, expected, expected_length) == 0) {
    844                 got_ack = true;
    845             } else {
    846                 ReportServerStartupFailure(GetProcessId(process_handle.get()));
    847                 return -1;
    848             }
    849         } else {
    850             const DWORD err = GetLastError();
    851             // If the ACK was not written and the process exited, GetLastError()
    852             // is probably ERROR_BROKEN_PIPE, in which case that info is not
    853             // useful to the user.
    854             fprintf(stderr, "could not read ok from ADB Server%s\n",
    855                     err == ERROR_BROKEN_PIPE ? "" :
    856                     android::base::StringPrintf(": %s",
    857                             android::base::SystemErrorCodeToString(err).c_str()).c_str());
    858         }
    859     }
    860 
    861     // Always try to wait a bit for threads reading stdout/stderr to finish.
    862     // If the process started ok, it should close the pipes causing the threads
    863     // to finish. If the process had an error, it should exit, also causing
    864     // the pipes to be closed. In that case we want to read all of the output
    865     // and write it out so that the user can diagnose failures.
    866     const DWORD     thread_timeout_ms = 15 * 1000;
    867     const HANDLE    threads[] = { stdout_thread.get(), stderr_thread.get() };
    868     const DWORD     wait_result = WaitForMultipleObjects(arraysize(threads),
    869             threads, TRUE, thread_timeout_ms);
    870     if (wait_result == WAIT_TIMEOUT) {
    871         // Threads did not finish after waiting a little while. Perhaps the
    872         // server didn't close pipes, or it is hung.
    873         fprintf(stderr, "adb: timed out waiting for threads to finish reading from ADB server\n");
    874         // Process handles are signaled when the process exits, so if we wait
    875         // on the handle for 0 seconds and it returns 'timeout', that means that
    876         // the process is still running.
    877         if (WaitForSingleObject(process_handle.get(), 0) == WAIT_TIMEOUT) {
    878             // We could TerminateProcess(), but that seems somewhat presumptive.
    879             fprintf(stderr, "adb: server is running with process id %lu\n", pinfo.dwProcessId);
    880         }
    881         return -1;
    882     }
    883 
    884     if (wait_result != WAIT_OBJECT_0) {
    885         fprintf(stderr, "adb: unexpected result waiting for threads: %lu: %s\n", wait_result,
    886                 android::base::SystemErrorCodeToString(GetLastError()).c_str());
    887         return -1;
    888     }
    889 
    890     // For now ignore the thread exit codes and assume they worked properly.
    891 
    892     if (!got_ack) {
    893         return -1;
    894     }
    895 #else /* !defined(_WIN32) */
    896     // set up a pipe so the child can tell us when it is ready.
    897     // fd[0] will be parent's end, and the child will write on fd[1]
    898     int fd[2];
    899     if (pipe(fd)) {
    900         fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
    901         return -1;
    902     }
    903 
    904     std::string path = android::base::GetExecutablePath();
    905 
    906     pid_t pid = fork();
    907     if (pid < 0) return -1;
    908 
    909     if (pid == 0) {
    910         // child side of the fork
    911 
    912         adb_close(fd[0]);
    913 
    914         char reply_fd[30];
    915         snprintf(reply_fd, sizeof(reply_fd), "%d", fd[1]);
    916         // child process
    917         int result = execl(path.c_str(), "adb", "-L", socket_spec.c_str(), "fork-server", "server",
    918                            "--reply-fd", reply_fd, NULL);
    919         // this should not return
    920         fprintf(stderr, "adb: execl returned %d: %s\n", result, strerror(errno));
    921     } else {
    922         // parent side of the fork
    923         char temp[3] = {};
    924         // wait for the "OK\n" message
    925         adb_close(fd[1]);
    926         int ret = adb_read(fd[0], temp, 3);
    927         int saved_errno = errno;
    928         adb_close(fd[0]);
    929         if (ret < 0) {
    930             fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", saved_errno);
    931             return -1;
    932         }
    933         if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
    934             ReportServerStartupFailure(pid);
    935             return -1;
    936         }
    937     }
    938 #endif /* !defined(_WIN32) */
    939     return 0;
    940 }
    941 #endif /* ADB_HOST */
    942 
    943 // Try to handle a network forwarding request.
    944 // This returns 1 on success, 0 on failure, and -1 to indicate this is not
    945 // a forwarding-related request.
    946 int handle_forward_request(const char* service, TransportType type, const char* serial,
    947                            TransportId transport_id, int reply_fd) {
    948     if (!strcmp(service, "list-forward")) {
    949         // Create the list of forward redirections.
    950         std::string listeners = format_listeners();
    951 #if ADB_HOST
    952         SendOkay(reply_fd);
    953 #endif
    954         return SendProtocolString(reply_fd, listeners);
    955     }
    956 
    957     if (!strcmp(service, "killforward-all")) {
    958         remove_all_listeners();
    959 #if ADB_HOST
    960         /* On the host: 1st OKAY is connect, 2nd OKAY is status */
    961         SendOkay(reply_fd);
    962 #endif
    963         SendOkay(reply_fd);
    964         return 1;
    965     }
    966 
    967     if (!strncmp(service, "forward:", 8) || !strncmp(service, "killforward:", 12)) {
    968         // killforward:local
    969         // forward:(norebind:)?local;remote
    970         bool kill_forward = false;
    971         bool no_rebind = false;
    972         if (android::base::StartsWith(service, "killforward:")) {
    973             kill_forward = true;
    974             service += 12;
    975         } else {
    976             service += 8;   // skip past "forward:"
    977             if (android::base::StartsWith(service, "norebind:")) {
    978                 no_rebind = true;
    979                 service += 9;
    980             }
    981         }
    982 
    983         std::vector<std::string> pieces = android::base::Split(service, ";");
    984 
    985         if (kill_forward) {
    986             // Check killforward: parameter format: '<local>'
    987             if (pieces.size() != 1 || pieces[0].empty()) {
    988                 SendFail(reply_fd, android::base::StringPrintf("bad killforward: %s", service));
    989                 return 1;
    990             }
    991         } else {
    992             // Check forward: parameter format: '<local>;<remote>'
    993             if (pieces.size() != 2 || pieces[0].empty() || pieces[1].empty() || pieces[1][0] == '*') {
    994                 SendFail(reply_fd, android::base::StringPrintf("bad forward: %s", service));
    995                 return 1;
    996             }
    997         }
    998 
    999         std::string error_msg;
   1000         atransport* transport =
   1001             acquire_one_transport(type, serial, transport_id, nullptr, &error_msg);
   1002         if (!transport) {
   1003             SendFail(reply_fd, error_msg);
   1004             return 1;
   1005         }
   1006 
   1007         std::string error;
   1008         InstallStatus r;
   1009         int resolved_tcp_port = 0;
   1010         if (kill_forward) {
   1011             r = remove_listener(pieces[0].c_str(), transport);
   1012         } else {
   1013             r = install_listener(pieces[0], pieces[1].c_str(), transport, no_rebind,
   1014                                  &resolved_tcp_port, &error);
   1015         }
   1016         if (r == INSTALL_STATUS_OK) {
   1017 #if ADB_HOST
   1018             // On the host: 1st OKAY is connect, 2nd OKAY is status.
   1019             SendOkay(reply_fd);
   1020 #endif
   1021             SendOkay(reply_fd);
   1022 
   1023             // If a TCP port was resolved, send the actual port number back.
   1024             if (resolved_tcp_port != 0) {
   1025                 SendProtocolString(reply_fd, android::base::StringPrintf("%d", resolved_tcp_port));
   1026             }
   1027 
   1028             return 1;
   1029         }
   1030 
   1031         std::string message;
   1032         switch (r) {
   1033           case INSTALL_STATUS_OK: message = "success (!)"; break;
   1034           case INSTALL_STATUS_INTERNAL_ERROR: message = "internal error"; break;
   1035           case INSTALL_STATUS_CANNOT_BIND:
   1036             message = android::base::StringPrintf("cannot bind listener: %s",
   1037                                                   error.c_str());
   1038             break;
   1039           case INSTALL_STATUS_CANNOT_REBIND:
   1040             message = android::base::StringPrintf("cannot rebind existing socket");
   1041             break;
   1042           case INSTALL_STATUS_LISTENER_NOT_FOUND:
   1043             message = android::base::StringPrintf("listener '%s' not found", service);
   1044             break;
   1045         }
   1046         SendFail(reply_fd, message);
   1047         return 1;
   1048     }
   1049     return 0;
   1050 }
   1051 
   1052 #if ADB_HOST
   1053 static int SendOkay(int fd, const std::string& s) {
   1054     SendOkay(fd);
   1055     SendProtocolString(fd, s);
   1056     return 0;
   1057 }
   1058 
   1059 int handle_host_request(const char* service, TransportType type, const char* serial,
   1060                         TransportId transport_id, int reply_fd, asocket* s) {
   1061     if (strcmp(service, "kill") == 0) {
   1062         fprintf(stderr, "adb server killed by remote request\n");
   1063         fflush(stdout);
   1064 
   1065         // Send a reply even though we don't read it anymore, so that old versions
   1066         // of adb that do read it don't spew error messages.
   1067         SendOkay(reply_fd);
   1068 
   1069         // Rely on process exit to close the socket for us.
   1070         android::base::quick_exit(0);
   1071     }
   1072 
   1073     // "transport:" is used for switching transport with a specified serial number
   1074     // "transport-usb:" is used for switching transport to the only USB transport
   1075     // "transport-local:" is used for switching transport to the only local transport
   1076     // "transport-any:" is used for switching transport to the only transport
   1077     if (!strncmp(service, "transport", strlen("transport"))) {
   1078         TransportType type = kTransportAny;
   1079 
   1080         if (!strncmp(service, "transport-id:", strlen("transport-id:"))) {
   1081             service += strlen("transport-id:");
   1082             transport_id = strtoll(service, const_cast<char**>(&service), 10);
   1083             if (*service != '\0') {
   1084                 SendFail(reply_fd, "invalid transport id");
   1085                 return 1;
   1086             }
   1087         } else if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
   1088             type = kTransportUsb;
   1089         } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
   1090             type = kTransportLocal;
   1091         } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
   1092             type = kTransportAny;
   1093         } else if (!strncmp(service, "transport:", strlen("transport:"))) {
   1094             service += strlen("transport:");
   1095             serial = service;
   1096         }
   1097 
   1098         std::string error;
   1099         atransport* t = acquire_one_transport(type, serial, transport_id, nullptr, &error);
   1100         if (t != nullptr) {
   1101             s->transport = t;
   1102             SendOkay(reply_fd);
   1103         } else {
   1104             SendFail(reply_fd, error);
   1105         }
   1106         return 1;
   1107     }
   1108 
   1109     // return a list of all connected devices
   1110     if (!strncmp(service, "devices", 7)) {
   1111         bool long_listing = (strcmp(service+7, "-l") == 0);
   1112         if (long_listing || service[7] == 0) {
   1113             D("Getting device list...");
   1114             std::string device_list = list_transports(long_listing);
   1115             D("Sending device list...");
   1116             return SendOkay(reply_fd, device_list);
   1117         }
   1118         return 1;
   1119     }
   1120 
   1121     if (!strcmp(service, "reconnect-offline")) {
   1122         std::string response;
   1123         close_usb_devices([&response](const atransport* transport) {
   1124             switch (transport->GetConnectionState()) {
   1125                 case kCsOffline:
   1126                 case kCsUnauthorized:
   1127                     response += "reconnecting " + transport->serial_name() + "\n";
   1128                     return true;
   1129                 default:
   1130                     return false;
   1131             }
   1132         });
   1133         if (!response.empty()) {
   1134             response.resize(response.size() - 1);
   1135         }
   1136         SendOkay(reply_fd, response);
   1137         return 0;
   1138     }
   1139 
   1140     if (!strcmp(service, "features")) {
   1141         std::string error;
   1142         atransport* t = acquire_one_transport(type, serial, transport_id, nullptr, &error);
   1143         if (t != nullptr) {
   1144             SendOkay(reply_fd, FeatureSetToString(t->features()));
   1145         } else {
   1146             SendFail(reply_fd, error);
   1147         }
   1148         return 0;
   1149     }
   1150 
   1151     if (!strcmp(service, "host-features")) {
   1152         FeatureSet features = supported_features();
   1153         // Abuse features to report libusb status.
   1154         if (should_use_libusb()) {
   1155             features.insert(kFeatureLibusb);
   1156         }
   1157         features.insert(kFeaturePushSync);
   1158         SendOkay(reply_fd, FeatureSetToString(features));
   1159         return 0;
   1160     }
   1161 
   1162     // remove TCP transport
   1163     if (!strncmp(service, "disconnect:", 11)) {
   1164         const std::string address(service + 11);
   1165         if (address.empty()) {
   1166             kick_all_tcp_devices();
   1167             return SendOkay(reply_fd, "disconnected everything");
   1168         }
   1169 
   1170         std::string serial;
   1171         std::string host;
   1172         int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
   1173         std::string error;
   1174         if (!android::base::ParseNetAddress(address, &host, &port, &serial, &error)) {
   1175             return SendFail(reply_fd, android::base::StringPrintf("couldn't parse '%s': %s",
   1176                                                                   address.c_str(), error.c_str()));
   1177         }
   1178         atransport* t = find_transport(serial.c_str());
   1179         if (t == nullptr) {
   1180             return SendFail(reply_fd, android::base::StringPrintf("no such device '%s'",
   1181                                                                   serial.c_str()));
   1182         }
   1183         kick_transport(t);
   1184         return SendOkay(reply_fd, android::base::StringPrintf("disconnected %s", address.c_str()));
   1185     }
   1186 
   1187     // Returns our value for ADB_SERVER_VERSION.
   1188     if (!strcmp(service, "version")) {
   1189         return SendOkay(reply_fd, android::base::StringPrintf("%04x", ADB_SERVER_VERSION));
   1190     }
   1191 
   1192     // These always report "unknown" rather than the actual error, for scripts.
   1193     if (!strcmp(service, "get-serialno")) {
   1194         std::string error;
   1195         atransport* t = acquire_one_transport(type, serial, transport_id, nullptr, &error);
   1196         if (t) {
   1197             return SendOkay(reply_fd, t->serial ? t->serial : "unknown");
   1198         } else {
   1199             return SendFail(reply_fd, error);
   1200         }
   1201     }
   1202     if (!strcmp(service, "get-devpath")) {
   1203         std::string error;
   1204         atransport* t = acquire_one_transport(type, serial, transport_id, nullptr, &error);
   1205         if (t) {
   1206             return SendOkay(reply_fd, t->devpath ? t->devpath : "unknown");
   1207         } else {
   1208             return SendFail(reply_fd, error);
   1209         }
   1210     }
   1211     if (!strcmp(service, "get-state")) {
   1212         std::string error;
   1213         atransport* t = acquire_one_transport(type, serial, transport_id, nullptr, &error);
   1214         if (t) {
   1215             return SendOkay(reply_fd, t->connection_state_name());
   1216         } else {
   1217             return SendFail(reply_fd, error);
   1218         }
   1219     }
   1220 
   1221     // Indicates a new emulator instance has started.
   1222     if (!strncmp(service, "emulator:", 9)) {
   1223         int  port = atoi(service+9);
   1224         local_connect(port);
   1225         /* we don't even need to send a reply */
   1226         return 0;
   1227     }
   1228 
   1229     if (!strcmp(service, "reconnect")) {
   1230         std::string response;
   1231         atransport* t = acquire_one_transport(type, serial, transport_id, nullptr, &response, true);
   1232         if (t != nullptr) {
   1233             kick_transport(t);
   1234             response =
   1235                 "reconnecting " + t->serial_name() + " [" + t->connection_state_name() + "]\n";
   1236         }
   1237         return SendOkay(reply_fd, response);
   1238     }
   1239 
   1240     int ret = handle_forward_request(service, type, serial, transport_id, reply_fd);
   1241     if (ret >= 0)
   1242       return ret - 1;
   1243     return -1;
   1244 }
   1245 
   1246 static auto& init_mutex = *new std::mutex();
   1247 static auto& init_cv = *new std::condition_variable();
   1248 static bool device_scan_complete = false;
   1249 static bool transports_ready = false;
   1250 
   1251 void update_transport_status() {
   1252     bool result = iterate_transports([](const atransport* t) {
   1253         if (t->type == kTransportUsb && t->online != 1) {
   1254             return false;
   1255         }
   1256         return true;
   1257     });
   1258 
   1259     bool ready;
   1260     {
   1261         std::lock_guard<std::mutex> lock(init_mutex);
   1262         transports_ready = result;
   1263         ready = transports_ready && device_scan_complete;
   1264     }
   1265 
   1266     if (ready) {
   1267         init_cv.notify_all();
   1268     }
   1269 }
   1270 
   1271 void adb_notify_device_scan_complete() {
   1272     {
   1273         std::lock_guard<std::mutex> lock(init_mutex);
   1274         if (device_scan_complete) {
   1275             return;
   1276         }
   1277 
   1278         device_scan_complete = true;
   1279     }
   1280 
   1281     update_transport_status();
   1282 }
   1283 
   1284 void adb_wait_for_device_initialization() {
   1285     std::unique_lock<std::mutex> lock(init_mutex);
   1286     init_cv.wait_for(lock, 3s, []() { return device_scan_complete && transports_ready; });
   1287 }
   1288 
   1289 #endif  // ADB_HOST
   1290