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