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 <android-base/errors.h>
27#include <android-base/file.h>
28#include <android-base/logging.h>
29#include <android-base/stringprintf.h>
30
31#include "adb.h"
32#include "adb_auth.h"
33#include "adb_listeners.h"
34#include "adb_utils.h"
35#include "transport.h"
36
37static std::string GetLogFilePath() {
38#if defined(_WIN32)
39    const char log_name[] = "adb.log";
40    WCHAR temp_path[MAX_PATH];
41
42    // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364992%28v=vs.85%29.aspx
43    DWORD nchars = GetTempPathW(arraysize(temp_path), temp_path);
44    if (nchars >= arraysize(temp_path) || nchars == 0) {
45        // If string truncation or some other error.
46        fatal("cannot retrieve temporary file path: %s\n",
47              android::base::SystemErrorCodeToString(GetLastError()).c_str());
48    }
49
50    std::string temp_path_utf8;
51    if (!android::base::WideToUTF8(temp_path, &temp_path_utf8)) {
52        fatal_errno("cannot convert temporary file path from UTF-16 to UTF-8");
53    }
54
55    return temp_path_utf8 + log_name;
56#else
57    const char* tmp_dir = getenv("TMPDIR");
58    if (tmp_dir == nullptr) tmp_dir = "/tmp";
59    return android::base::StringPrintf("%s/adb.%u.log", tmp_dir, getuid());
60#endif
61}
62
63static void setup_daemon_logging(void) {
64    const std::string log_file_path(GetLogFilePath());
65    int fd = unix_open(log_file_path.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0640);
66    if (fd == -1) {
67        fatal("cannot open '%s': %s", log_file_path.c_str(), strerror(errno));
68    }
69    if (dup2(fd, STDOUT_FILENO) == -1) {
70        fatal("cannot redirect stdout: %s", strerror(errno));
71    }
72    if (dup2(fd, STDERR_FILENO) == -1) {
73        fatal("cannot redirect stderr: %s", strerror(errno));
74    }
75    unix_close(fd);
76
77    fprintf(stderr, "--- adb starting (pid %d) ---\n", getpid());
78    LOG(INFO) << adb_version();
79}
80
81#if defined(_WIN32)
82static BOOL WINAPI ctrlc_handler(DWORD type) {
83    // TODO: Consider trying to kill a starting up adb server (if we're in
84    // launch_server) by calling GenerateConsoleCtrlEvent().
85    exit(STATUS_CONTROL_C_EXIT);
86    return TRUE;
87}
88#endif
89
90int adb_server_main(int is_daemon, int server_port, int ack_reply_fd) {
91#if defined(_WIN32)
92    // adb start-server starts us up with stdout and stderr hooked up to
93    // anonymous pipes. When the C Runtime sees this, it makes stderr and
94    // stdout buffered, but to improve the chance that error output is seen,
95    // unbuffer stdout and stderr just like if we were run at the console.
96    // This also keeps stderr unbuffered when it is redirected to adb.log.
97    if (is_daemon) {
98        if (setvbuf(stdout, NULL, _IONBF, 0) == -1) {
99            fatal("cannot make stdout unbuffered: %s", strerror(errno));
100        }
101        if (setvbuf(stderr, NULL, _IONBF, 0) == -1) {
102            fatal("cannot make stderr unbuffered: %s", strerror(errno));
103        }
104    }
105
106    SetConsoleCtrlHandler(ctrlc_handler, TRUE);
107#endif
108
109    init_transport_registration();
110
111    usb_init();
112    local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
113    adb_auth_init();
114
115    std::string error;
116    std::string local_name = android::base::StringPrintf("tcp:%d", server_port);
117    if (install_listener(local_name, "*smartsocket*", nullptr, 0, &error)) {
118        fatal("could not install *smartsocket* listener: %s", error.c_str());
119    }
120
121    // Inform our parent that we are up and running.
122    if (is_daemon) {
123        close_stdin();
124        setup_daemon_logging();
125
126#if !defined(_WIN32)
127        // Start a new session for the daemon. Do this here instead of after the fork so
128        // that a ctrl-c between the "starting server" and "done starting server" messages
129        // gets a chance to terminate the server.
130        if (setsid() == -1) {
131            fatal("setsid() failed: %s", strerror(errno));
132        }
133#endif
134
135        // Any error output written to stderr now goes to adb.log. We could
136        // keep around a copy of the stderr fd and use that to write any errors
137        // encountered by the following code, but that is probably overkill.
138#if defined(_WIN32)
139        const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd);
140        const CHAR ack[] = "OK\n";
141        const DWORD bytes_to_write = arraysize(ack) - 1;
142        DWORD written = 0;
143        if (!WriteFile(ack_reply_handle, ack, bytes_to_write, &written, NULL)) {
144            fatal("adb: cannot write ACK to handle 0x%p: %s", ack_reply_handle,
145                  android::base::SystemErrorCodeToString(GetLastError()).c_str());
146        }
147        if (written != bytes_to_write) {
148            fatal("adb: cannot write %lu bytes of ACK: only wrote %lu bytes",
149                  bytes_to_write, written);
150        }
151        CloseHandle(ack_reply_handle);
152#else
153        // TODO(danalbert): Can't use SendOkay because we're sending "OK\n", not
154        // "OKAY".
155        if (!android::base::WriteStringToFd("OK\n", ack_reply_fd)) {
156            fatal_errno("error writing ACK to fd %d", ack_reply_fd);
157        }
158        unix_close(ack_reply_fd);
159#endif
160    }
161
162    D("Event loop starting");
163    fdevent_loop();
164
165    return 0;
166}
167
168int main(int argc, char** argv) {
169    adb_sysdeps_init();
170    adb_trace_init(argv);
171    return adb_commandline(argc - 1, const_cast<const char**>(argv + 1));
172}
173