1 /*
2 * Copyright (C) 2018 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 SERVICES
18
19 #include "sysdeps.h"
20
21 #include <errno.h>
22 #include <netdb.h>
23 #include <netinet/in.h>
24 #include <stddef.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/ioctl.h>
29 #include <sys/socket.h>
30 #include <sys/un.h>
31 #include <unistd.h>
32
33 #include <thread>
34
35 #include <android-base/file.h>
36 #include <android-base/parseint.h>
37 #include <android-base/parsenetaddress.h>
38 #include <android-base/properties.h>
39 #include <android-base/stringprintf.h>
40 #include <android-base/strings.h>
41 #include <android-base/unique_fd.h>
42 #include <cutils/android_reboot.h>
43 #include <cutils/sockets.h>
44 #include <log/log_properties.h>
45
46 #include "adb.h"
47 #include "adb_io.h"
48 #include "adb_unique_fd.h"
49 #include "adb_utils.h"
50 #include "services.h"
51 #include "socket_spec.h"
52 #include "sysdeps.h"
53 #include "transport.h"
54
55 #include "daemon/file_sync_service.h"
56 #include "daemon/framebuffer_service.h"
57 #include "daemon/jdwp_service.h"
58 #include "daemon/logging.h"
59 #include "daemon/restart_service.h"
60 #include "daemon/shell_service.h"
61
reconnect_service(unique_fd fd,atransport * t)62 void reconnect_service(unique_fd fd, atransport* t) {
63 WriteFdExactly(fd.get(), "done");
64 kick_transport(t);
65 }
66
reverse_service(std::string_view command,atransport * transport)67 unique_fd reverse_service(std::string_view command, atransport* transport) {
68 // TODO: Switch handle_forward_request to std::string_view.
69 std::string str(command);
70
71 int s[2];
72 if (adb_socketpair(s)) {
73 PLOG(ERROR) << "cannot create service socket pair.";
74 return unique_fd{};
75 }
76 VLOG(SERVICES) << "service socketpair: " << s[0] << ", " << s[1];
77 if (!handle_forward_request(str.c_str(), transport, s[1])) {
78 SendFail(s[1], "not a reverse forwarding command");
79 }
80 adb_close(s[1]);
81 return unique_fd{s[0]};
82 }
83
84 // Shell service string can look like:
85 // shell[,arg1,arg2,...]:[command]
ShellService(std::string_view args,const atransport * transport)86 unique_fd ShellService(std::string_view args, const atransport* transport) {
87 size_t delimiter_index = args.find(':');
88 if (delimiter_index == std::string::npos) {
89 LOG(ERROR) << "No ':' found in shell service arguments: " << args;
90 return unique_fd{};
91 }
92
93 // TODO: android::base::Split(const std::string_view&, ...)
94 std::string service_args(args.substr(0, delimiter_index));
95 std::string command(args.substr(delimiter_index + 1));
96
97 // Defaults:
98 // PTY for interactive, raw for non-interactive.
99 // No protocol.
100 // $TERM set to "dumb".
101 SubprocessType type(command.empty() ? SubprocessType::kPty : SubprocessType::kRaw);
102 SubprocessProtocol protocol = SubprocessProtocol::kNone;
103 std::string terminal_type = "dumb";
104
105 for (const std::string& arg : android::base::Split(service_args, ",")) {
106 if (arg == kShellServiceArgRaw) {
107 type = SubprocessType::kRaw;
108 } else if (arg == kShellServiceArgPty) {
109 type = SubprocessType::kPty;
110 } else if (arg == kShellServiceArgShellProtocol) {
111 protocol = SubprocessProtocol::kShell;
112 } else if (arg.starts_with("TERM=")) {
113 terminal_type = arg.substr(strlen("TERM="));
114 } else if (!arg.empty()) {
115 // This is not an error to allow for future expansion.
116 LOG(WARNING) << "Ignoring unknown shell service argument: " << arg;
117 }
118 }
119
120 return StartSubprocess(command, terminal_type.c_str(), type, protocol);
121 }
122
spin_service(unique_fd fd)123 static void spin_service(unique_fd fd) {
124 if (!__android_log_is_debuggable()) {
125 WriteFdExactly(fd.get(), "refusing to spin on non-debuggable build\n");
126 return;
127 }
128
129 // A service that creates an fdevent that's always pending, and then ignores it.
130 unique_fd pipe_read, pipe_write;
131 if (!Pipe(&pipe_read, &pipe_write)) {
132 WriteFdExactly(fd.get(), "failed to create pipe\n");
133 return;
134 }
135
136 fdevent_run_on_looper([fd = pipe_read.release()]() {
137 fdevent* fde = fdevent_create(
138 fd, [](int, unsigned, void*) {}, nullptr);
139 fdevent_add(fde, FDE_READ);
140 });
141
142 WriteFdExactly(fd.get(), "spinning\n");
143 }
144
reboot_device(const std::string & name)145 [[maybe_unused]] static unique_fd reboot_device(const std::string& name) {
146 #if defined(__ANDROID_RECOVERY__)
147 if (!__android_log_is_debuggable()) {
148 auto reboot_service = [name](unique_fd fd) {
149 std::string reboot_string = android::base::StringPrintf("reboot,%s", name.c_str());
150 if (!android::base::SetProperty(ANDROID_RB_PROPERTY, reboot_string)) {
151 WriteFdFmt(fd.get(), "reboot (%s) failed\n", reboot_string.c_str());
152 return;
153 }
154 while (true) pause();
155 };
156 return create_service_thread("reboot", reboot_service);
157 }
158 #endif
159 // Fall through
160 std::string cmd = "/system/bin/reboot ";
161 cmd += name;
162 return StartSubprocess(cmd, nullptr, SubprocessType::kRaw, SubprocessProtocol::kNone);
163 }
164
165 struct ServiceSocket : public asocket {
166 ServiceSocket() = delete;
ServiceSocketServiceSocket167 explicit ServiceSocket(atransport* transport) {
168 CHECK(transport);
169 install_local_socket(this);
170 this->transport = transport;
171 this->enqueue = [](asocket* self, apacket::payload_type data) {
172 // TODO: This interface currently can't give any backpressure.
173 send_ready(self->id, self->peer->id, self->transport, data.size());
174 return static_cast<ServiceSocket*>(self)->Enqueue(std::move(data));
175 };
176 this->ready = [](asocket* self) { return static_cast<ServiceSocket*>(self)->Ready(); };
177 this->close = [](asocket* self) { return static_cast<ServiceSocket*>(self)->Close(); };
178 }
179 virtual ~ServiceSocket() = default;
180
181 ServiceSocket(const ServiceSocket& copy) = delete;
182 ServiceSocket(ServiceSocket&& move) = delete;
183 ServiceSocket& operator=(const ServiceSocket& copy) = delete;
184 ServiceSocket& operator=(ServiceSocket&& move) = delete;
185
EnqueueServiceSocket186 virtual int Enqueue(apacket::payload_type data) { return -1; }
ReadyServiceSocket187 virtual void Ready() {}
CloseServiceSocket188 virtual void Close() {
189 if (peer) {
190 peer->peer = nullptr;
191 if (peer->shutdown) {
192 peer->shutdown(peer);
193 }
194 peer->close(peer);
195 }
196
197 remove_socket(this);
198 delete this;
199 }
200 };
201
202 struct SinkSocket : public ServiceSocket {
SinkSocketSinkSocket203 explicit SinkSocket(atransport* transport, size_t byte_count)
204 : ServiceSocket(transport), bytes_left_(byte_count) {
205 LOG(INFO) << "Creating new SinkSocket with capacity " << byte_count;
206 }
207
~SinkSocketSinkSocket208 virtual ~SinkSocket() { LOG(INFO) << "SinkSocket destroyed"; }
209
EnqueueSinkSocket210 virtual int Enqueue(apacket::payload_type data) override final {
211 if (bytes_left_ <= data.size()) {
212 // Done reading.
213 Close();
214 return -1;
215 }
216
217 bytes_left_ -= data.size();
218 return 0;
219 }
220
221 size_t bytes_left_;
222 };
223
224 struct SourceSocket : public ServiceSocket {
SourceSocketSourceSocket225 explicit SourceSocket(atransport* transport, size_t byte_count)
226 : ServiceSocket(transport), bytes_left_(byte_count) {
227 LOG(INFO) << "Creating new SourceSocket with capacity " << byte_count;
228 }
229
~SourceSocketSourceSocket230 virtual ~SourceSocket() { LOG(INFO) << "SourceSocket destroyed"; }
231
ReadySourceSocket232 void Ready() {
233 size_t len = std::min(bytes_left_, get_max_payload());
234 if (len == 0) {
235 Close();
236 return;
237 }
238
239 Block block(len);
240 memset(block.data(), 0, block.size());
241 peer->enqueue(peer, std::move(block));
242 bytes_left_ -= len;
243 }
244
EnqueueSourceSocket245 int Enqueue(apacket::payload_type data) { return -1; }
246
247 size_t bytes_left_;
248 };
249
daemon_service_to_socket(std::string_view name,atransport * transport)250 asocket* daemon_service_to_socket(std::string_view name, atransport* transport) {
251 if (name == "jdwp") {
252 return create_jdwp_service_socket();
253 } else if (name == "track-jdwp") {
254 return create_jdwp_tracker_service_socket();
255 } else if (name == "track-app") {
256 return create_app_tracker_service_socket();
257 } else if (android::base::ConsumePrefix(&name, "sink:")) {
258 uint64_t byte_count = 0;
259 if (!ParseUint(&byte_count, name)) {
260 return nullptr;
261 }
262 return new SinkSocket(transport, byte_count);
263 } else if (android::base::ConsumePrefix(&name, "source:")) {
264 uint64_t byte_count = 0;
265 if (!ParseUint(&byte_count, name)) {
266 return nullptr;
267 }
268 return new SourceSocket(transport, byte_count);
269 }
270
271 return nullptr;
272 }
273
daemon_service_to_fd(std::string_view name,atransport * transport)274 unique_fd daemon_service_to_fd(std::string_view name, atransport* transport) {
275 ADB_LOG(Service) << "transport " << transport->serial_name() << " opening service " << name;
276
277 #if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__)
278 if (name.starts_with("abb:") || name.starts_with("abb_exec:")) {
279 return execute_abb_command(name);
280 }
281 #endif
282
283 #if defined(__ANDROID__)
284 if (name.starts_with("framebuffer:")) {
285 return create_service_thread("fb", framebuffer_service);
286 } else if (android::base::ConsumePrefix(&name, "remount:")) {
287 std::string cmd = "/system/bin/remount ";
288 cmd += name;
289 return StartSubprocess(cmd, nullptr, SubprocessType::kRaw, SubprocessProtocol::kNone);
290 } else if (android::base::ConsumePrefix(&name, "reboot:")) {
291 return reboot_device(std::string(name));
292 } else if (name.starts_with("root:")) {
293 return create_service_thread("root", restart_root_service);
294 } else if (name.starts_with("unroot:")) {
295 return create_service_thread("unroot", restart_unroot_service);
296 } else if (android::base::ConsumePrefix(&name, "backup:")) {
297 std::string cmd = "/system/bin/bu backup ";
298 cmd += name;
299 return StartSubprocess(cmd, nullptr, SubprocessType::kRaw, SubprocessProtocol::kNone);
300 } else if (name.starts_with("restore:")) {
301 return StartSubprocess("/system/bin/bu restore", nullptr, SubprocessType::kRaw,
302 SubprocessProtocol::kNone);
303 } else if (name.starts_with("disable-verity:")) {
304 return StartSubprocess("/system/bin/disable-verity", nullptr, SubprocessType::kRaw,
305 SubprocessProtocol::kNone);
306 } else if (name.starts_with("enable-verity:")) {
307 return StartSubprocess("/system/bin/enable-verity", nullptr, SubprocessType::kRaw,
308 SubprocessProtocol::kNone);
309 } else if (android::base::ConsumePrefix(&name, "tcpip:")) {
310 std::string str(name);
311
312 int port;
313 if (sscanf(str.c_str(), "%d", &port) != 1) {
314 return unique_fd{};
315 }
316 return create_service_thread("tcp",
317 std::bind(restart_tcp_service, std::placeholders::_1, port));
318 } else if (name.starts_with("usb:")) {
319 return create_service_thread("usb", restart_usb_service);
320 }
321 #endif
322
323 if (android::base::ConsumePrefix(&name, "dev:")) {
324 return unique_fd{unix_open(name, O_RDWR | O_CLOEXEC)};
325 } else if (android::base::ConsumePrefix(&name, "jdwp:")) {
326 pid_t pid;
327 if (!ParseUint(&pid, name)) {
328 return unique_fd{};
329 }
330 return create_jdwp_connection_fd(pid);
331 } else if (android::base::ConsumePrefix(&name, "shell")) {
332 return ShellService(name, transport);
333 } else if (android::base::ConsumePrefix(&name, "exec:")) {
334 return StartSubprocess(std::string(name), nullptr, SubprocessType::kRaw,
335 SubprocessProtocol::kNone);
336 } else if (name.starts_with("sync:")) {
337 return create_service_thread("sync", file_sync_service);
338 } else if (android::base::ConsumePrefix(&name, "reverse:")) {
339 return reverse_service(name, transport);
340 } else if (name == "reconnect") {
341 return create_service_thread(
342 "reconnect", std::bind(reconnect_service, std::placeholders::_1, transport));
343 } else if (name == "spin") {
344 return create_service_thread("spin", spin_service);
345 }
346
347 return unique_fd{};
348 }
349