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