Home | History | Annotate | Download | only in client
      1 /*
      2  * Copyright (C) 2015 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 
     21 #include <signal.h>
     22 #include <stdio.h>
     23 #include <stdlib.h>
     24 #include <unistd.h>
     25 
     26 #include <thread>
     27 
     28 #include <android-base/errors.h>
     29 #include <android-base/file.h>
     30 #include <android-base/logging.h>
     31 #include <android-base/stringprintf.h>
     32 
     33 #include "adb.h"
     34 #include "adb_auth.h"
     35 #include "adb_listeners.h"
     36 #include "adb_utils.h"
     37 #include "commandline.h"
     38 #include "sysdeps/chrono.h"
     39 #include "transport.h"
     40 
     41 static void setup_daemon_logging() {
     42     const std::string log_file_path(GetLogFilePath());
     43     int fd = unix_open(log_file_path.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0640);
     44     if (fd == -1) {
     45         fatal("cannot open '%s': %s", log_file_path.c_str(), strerror(errno));
     46     }
     47     if (dup2(fd, STDOUT_FILENO) == -1) {
     48         fatal("cannot redirect stdout: %s", strerror(errno));
     49     }
     50     if (dup2(fd, STDERR_FILENO) == -1) {
     51         fatal("cannot redirect stderr: %s", strerror(errno));
     52     }
     53     unix_close(fd);
     54 
     55     fprintf(stderr, "--- adb starting (pid %d) ---\n", getpid());
     56     LOG(INFO) << adb_version();
     57 }
     58 
     59 #if defined(_WIN32)
     60 static BOOL WINAPI ctrlc_handler(DWORD type) {
     61     // TODO: Consider trying to kill a starting up adb server (if we're in
     62     // launch_server) by calling GenerateConsoleCtrlEvent().
     63     exit(STATUS_CONTROL_C_EXIT);
     64     return TRUE;
     65 }
     66 #endif
     67 
     68 void adb_server_cleanup() {
     69     // Upon exit, we want to clean up in the following order:
     70     //   1. close_smartsockets, so that we don't get any new clients
     71     //   2. kick_all_transports, to avoid writing only part of a packet to a transport.
     72     //   3. usb_cleanup, to tear down the USB stack.
     73     close_smartsockets();
     74     kick_all_transports();
     75     usb_cleanup();
     76 }
     77 
     78 static void intentionally_leak() {
     79     void* p = ::operator new(1);
     80     // The analyzer is upset about this leaking. NOLINTNEXTLINE
     81     LOG(INFO) << "leaking pointer " << p;
     82 }
     83 
     84 int adb_server_main(int is_daemon, const std::string& socket_spec, int ack_reply_fd) {
     85 #if defined(_WIN32)
     86     // adb start-server starts us up with stdout and stderr hooked up to
     87     // anonymous pipes. When the C Runtime sees this, it makes stderr and
     88     // stdout buffered, but to improve the chance that error output is seen,
     89     // unbuffer stdout and stderr just like if we were run at the console.
     90     // This also keeps stderr unbuffered when it is redirected to adb.log.
     91     if (is_daemon) {
     92         if (setvbuf(stdout, NULL, _IONBF, 0) == -1) {
     93             fatal("cannot make stdout unbuffered: %s", strerror(errno));
     94         }
     95         if (setvbuf(stderr, NULL, _IONBF, 0) == -1) {
     96             fatal("cannot make stderr unbuffered: %s", strerror(errno));
     97         }
     98     }
     99 
    100     SetConsoleCtrlHandler(ctrlc_handler, TRUE);
    101 #else
    102     signal(SIGINT, [](int) {
    103         fdevent_run_on_main_thread([]() { exit(0); });
    104     });
    105 #endif
    106 
    107     char* leak = getenv("ADB_LEAK");
    108     if (leak && strcmp(leak, "1") == 0) {
    109         intentionally_leak();
    110     }
    111 
    112     if (is_daemon) {
    113         close_stdin();
    114         setup_daemon_logging();
    115     }
    116 
    117     atexit(adb_server_cleanup);
    118 
    119     init_transport_registration();
    120     init_mdns_transport_discovery();
    121 
    122     usb_init();
    123     local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
    124 
    125     std::string error;
    126 
    127     auto start = std::chrono::steady_clock::now();
    128 
    129     // If we told a previous adb server to quit because of version mismatch, we can get to this
    130     // point before it's finished exiting. Retry for a while to give it some time.
    131     while (install_listener(socket_spec, "*smartsocket*", nullptr, 0, nullptr, &error) !=
    132            INSTALL_STATUS_OK) {
    133         if (std::chrono::steady_clock::now() - start > 0.5s) {
    134             fatal("could not install *smartsocket* listener: %s", error.c_str());
    135         }
    136 
    137         std::this_thread::sleep_for(100ms);
    138     }
    139 
    140     adb_auth_init();
    141 
    142     if (is_daemon) {
    143 #if !defined(_WIN32)
    144         // Start a new session for the daemon. Do this here instead of after the fork so
    145         // that a ctrl-c between the "starting server" and "done starting server" messages
    146         // gets a chance to terminate the server.
    147         // setsid will fail with EPERM if it's already been a lead process of new session.
    148         // Ignore such error.
    149         if (setsid() == -1 && errno != EPERM) {
    150             fatal("setsid() failed: %s", strerror(errno));
    151         }
    152 #endif
    153 
    154         // Wait for the USB scan to complete before notifying the parent that we're up.
    155         // We need to perform this in a thread, because we would otherwise block the event loop.
    156         std::thread notify_thread([ack_reply_fd]() {
    157             adb_wait_for_device_initialization();
    158 
    159             // Any error output written to stderr now goes to adb.log. We could
    160             // keep around a copy of the stderr fd and use that to write any errors
    161             // encountered by the following code, but that is probably overkill.
    162 #if defined(_WIN32)
    163             const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd);
    164             const CHAR ack[] = "OK\n";
    165             const DWORD bytes_to_write = arraysize(ack) - 1;
    166             DWORD written = 0;
    167             if (!WriteFile(ack_reply_handle, ack, bytes_to_write, &written, NULL)) {
    168                 fatal("adb: cannot write ACK to handle 0x%p: %s", ack_reply_handle,
    169                       android::base::SystemErrorCodeToString(GetLastError()).c_str());
    170             }
    171             if (written != bytes_to_write) {
    172                 fatal("adb: cannot write %lu bytes of ACK: only wrote %lu bytes", bytes_to_write,
    173                       written);
    174             }
    175             CloseHandle(ack_reply_handle);
    176 #else
    177             // TODO(danalbert): Can't use SendOkay because we're sending "OK\n", not
    178             // "OKAY".
    179             if (!android::base::WriteStringToFd("OK\n", ack_reply_fd)) {
    180                 fatal_errno("error writing ACK to fd %d", ack_reply_fd);
    181             }
    182             unix_close(ack_reply_fd);
    183 #endif
    184         });
    185         notify_thread.detach();
    186     }
    187 
    188     D("Event loop starting");
    189     fdevent_loop();
    190 
    191     return 0;
    192 }
    193 
    194 int main(int argc, char** argv) {
    195     adb_trace_init(argv);
    196     return adb_commandline(argc - 1, const_cast<const char**>(argv + 1));
    197 }
    198