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_client.h"
36 #include "adb_listeners.h"
37 #include "adb_mdns.h"
38 #include "adb_utils.h"
39 #include "adb_wifi.h"
40 #include "client/usb.h"
41 #include "commandline.h"
42 #include "sysdeps/chrono.h"
43 #include "transport.h"
44
45 const char** __adb_argv;
46 const char** __adb_envp;
47
setup_daemon_logging()48 static void setup_daemon_logging() {
49 const std::string log_file_path(GetLogFilePath());
50 int fd = unix_open(log_file_path, O_WRONLY | O_CREAT | O_APPEND, 0640);
51 if (fd == -1) {
52 PLOG(FATAL) << "cannot open " << log_file_path;
53 }
54 if (dup2(fd, STDOUT_FILENO) == -1) {
55 PLOG(FATAL) << "cannot redirect stdout";
56 }
57 if (dup2(fd, STDERR_FILENO) == -1) {
58 PLOG(FATAL) << "cannot redirect stderr";
59 }
60 unix_close(fd);
61
62 fprintf(stderr, "--- adb starting (pid %d) ---\n", getpid());
63 LOG(INFO) << adb_version();
64 }
65
adb_server_cleanup()66 void adb_server_cleanup() {
67 // Upon exit, we want to clean up in the following order:
68 // 1. close_smartsockets, so that we don't get any new clients
69 // 2. kick_all_transports, to avoid writing only part of a packet to a transport.
70 // 3. usb_cleanup, to tear down the USB stack.
71 // 4. mdns_cleanup, to tear down mdns stack.
72 close_smartsockets();
73 kick_all_transports();
74 usb_cleanup();
75 mdns_cleanup();
76 }
77
intentionally_leak()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 // one_device: if null, server owns all devices, else server owns only
85 // device where atransport::MatchesTarget(one_device) is true.
adb_server_main(int is_daemon,const std::string & socket_spec,const char * one_device,int ack_reply_fd)86 int adb_server_main(int is_daemon, const std::string& socket_spec, const char* one_device,
87 int ack_reply_fd) {
88 #if defined(_WIN32)
89 // adb start-server starts us up with stdout and stderr hooked up to
90 // anonymous pipes. When the C Runtime sees this, it makes stderr and
91 // stdout buffered, but to improve the chance that error output is seen,
92 // unbuffer stdout and stderr just like if we were run at the console.
93 // This also keeps stderr unbuffered when it is redirected to adb.log.
94 if (is_daemon) {
95 if (setvbuf(stdout, nullptr, _IONBF, 0) == -1) {
96 PLOG(FATAL) << "cannot make stdout unbuffered";
97 }
98 if (setvbuf(stderr, nullptr, _IONBF, 0) == -1) {
99 PLOG(FATAL) << "cannot make stderr unbuffered";
100 }
101 }
102
103 // TODO: On Ctrl-C, consider trying to kill a starting up adb server (if we're in
104 // launch_server) by calling GenerateConsoleCtrlEvent().
105
106 // On Windows, SIGBREAK is when Ctrl-Break is pressed or the console window is closed. It should
107 // act like Ctrl-C.
108 signal(SIGBREAK, [](int) { raise(SIGINT); });
109 #endif
110 signal(SIGINT, [](int) { fdevent_run_on_looper([]() { exit(0); }); });
111
112 if (one_device) {
113 transport_set_one_device(one_device);
114 }
115
116 const char* reject_kill_server = getenv("ADB_REJECT_KILL_SERVER");
117 if (reject_kill_server && strcmp(reject_kill_server, "1") == 0) {
118 adb_set_reject_kill_server(true);
119 }
120
121 const char* leak = getenv("ADB_LEAK");
122 if (leak && strcmp(leak, "1") == 0) {
123 intentionally_leak();
124 }
125
126 if (is_daemon) {
127 close_stdin();
128 setup_daemon_logging();
129 }
130
131 atexit(adb_server_cleanup);
132
133 init_transport_registration();
134 init_reconnect_handler();
135
136 adb_wifi_init();
137 if (!getenv("ADB_MDNS") || strcmp(getenv("ADB_MDNS"), "0") != 0) {
138 init_mdns_transport_discovery();
139 }
140
141 if (!getenv("ADB_USB") || strcmp(getenv("ADB_USB"), "0") != 0) {
142 if (should_use_libusb()) {
143 libusb::usb_init();
144 } else {
145 usb_init();
146 }
147 } else {
148 adb_notify_device_scan_complete();
149 }
150
151 if (!getenv("ADB_EMU") || strcmp(getenv("ADB_EMU"), "0") != 0) {
152 local_init(android::base::StringPrintf("tcp:%d", DEFAULT_ADB_LOCAL_TRANSPORT_PORT));
153 }
154
155 std::string error;
156
157 auto start = std::chrono::steady_clock::now();
158
159 // If we told a previous adb server to quit because of version mismatch, we can get to this
160 // point before it's finished exiting. Retry for a while to give it some time. Don't actually
161 // accept any connections until adb_wait_for_device_initialization finishes below.
162 while (install_listener(socket_spec, "*smartsocket*", nullptr, INSTALL_LISTENER_DISABLED,
163 nullptr, &error) != INSTALL_STATUS_OK) {
164 if (std::chrono::steady_clock::now() - start > 0.5s) {
165 LOG(FATAL) << "could not install *smartsocket* listener: " << error;
166 }
167
168 std::this_thread::sleep_for(100ms);
169 }
170
171 adb_auth_init();
172
173 if (is_daemon) {
174 #if !defined(_WIN32)
175 // Start a new session for the daemon. Do this here instead of after the fork so
176 // that a ctrl-c between the "starting server" and "done starting server" messages
177 // gets a chance to terminate the server.
178 // setsid will fail with EPERM if it's already been a lead process of new session.
179 // Ignore such error.
180 if (setsid() == -1 && errno != EPERM) {
181 PLOG(FATAL) << "setsid() failed";
182 }
183 #endif
184 }
185
186 // Wait for the USB scan to complete before notifying the parent that we're up.
187 // We need to perform this in a thread, because we would otherwise block the event loop.
188 std::thread notify_thread([ack_reply_fd]() {
189 adb_wait_for_device_initialization();
190
191 if (ack_reply_fd >= 0) {
192 // Any error output written to stderr now goes to adb.log. We could
193 // keep around a copy of the stderr fd and use that to write any errors
194 // encountered by the following code, but that is probably overkill.
195 #if defined(_WIN32)
196 const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd);
197 const CHAR ack[] = "OK\n";
198 const DWORD bytes_to_write = arraysize(ack) - 1;
199 DWORD written = 0;
200 if (!WriteFile(ack_reply_handle, ack, bytes_to_write, &written, NULL)) {
201 LOG(FATAL) << "cannot write ACK to handle " << ack_reply_handle
202 << android::base::SystemErrorCodeToString(GetLastError());
203 }
204 if (written != bytes_to_write) {
205 LOG(FATAL) << "cannot write " << bytes_to_write << " bytes of ACK: only wrote "
206 << written << " bytes";
207 }
208 CloseHandle(ack_reply_handle);
209 #else
210 // TODO(danalbert): Can't use SendOkay because we're sending "OK\n", not
211 // "OKAY".
212 if (!android::base::WriteStringToFd("OK\n", ack_reply_fd)) {
213 PLOG(FATAL) << "error writing ACK to fd " << ack_reply_fd;
214 }
215 unix_close(ack_reply_fd);
216 #endif
217 }
218 // We don't accept() client connections until this point: this way, clients
219 // can't see wonky state early in startup even if they're connecting directly
220 // to the server instead of going through the adb program.
221 fdevent_run_on_looper([] { enable_server_sockets(); });
222 });
223 notify_thread.detach();
224
225 #if defined(__linux__)
226 // Write our location to .android/adb.$PORT, so that older clients can exec us.
227 std::string path;
228 if (!android::base::Readlink("/proc/self/exe", &path)) {
229 PLOG(ERROR) << "failed to readlink /proc/self/exe";
230 }
231
232 std::optional<std::string> server_executable_path = adb_get_server_executable_path();
233 if (server_executable_path) {
234 if (!android::base::WriteStringToFile(path, *server_executable_path)) {
235 PLOG(ERROR) << "failed to write server path to " << path;
236 }
237 }
238 #endif
239
240 D("Event loop starting");
241 fdevent_loop();
242 return 0;
243 }
244
main(int argc,char * argv[],char * envp[])245 int main(int argc, char* argv[], char* envp[]) {
246 __adb_argv = const_cast<const char**>(argv);
247 __adb_envp = const_cast<const char**>(envp);
248 adb_trace_init(argv);
249 return adb_commandline(argc - 1, const_cast<const char**>(argv + 1));
250 }
251