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/sockets.h>
43 #include <log/log_properties.h>
44
45 #include "adb.h"
46 #include "adb_io.h"
47 #include "adb_unique_fd.h"
48 #include "adb_utils.h"
49 #include "services.h"
50 #include "socket_spec.h"
51 #include "sysdeps.h"
52 #include "transport.h"
53
54 #include "daemon/file_sync_service.h"
55 #include "daemon/framebuffer_service.h"
56 #include "daemon/reboot_service.h"
57 #include "daemon/remount_service.h"
58 #include "daemon/restart_service.h"
59 #include "daemon/set_verity_enable_state_service.h"
60 #include "daemon/shell_service.h"
61
62
reconnect_service(unique_fd fd,atransport * t)63 void reconnect_service(unique_fd fd, atransport* t) {
64 WriteFdExactly(fd.get(), "done");
65 kick_transport(t);
66 }
67
reverse_service(std::string_view command,atransport * transport)68 unique_fd reverse_service(std::string_view command, atransport* transport) {
69 // TODO: Switch handle_forward_request to std::string_view.
70 std::string str(command);
71
72 int s[2];
73 if (adb_socketpair(s)) {
74 PLOG(ERROR) << "cannot create service socket pair.";
75 return unique_fd{};
76 }
77 VLOG(SERVICES) << "service socketpair: " << s[0] << ", " << s[1];
78 if (!handle_forward_request(str.c_str(), transport, s[1])) {
79 SendFail(s[1], "not a reverse forwarding command");
80 }
81 adb_close(s[1]);
82 return unique_fd{s[0]};
83 }
84
85 // Shell service string can look like:
86 // shell[,arg1,arg2,...]:[command]
ShellService(std::string_view args,const atransport * transport)87 unique_fd ShellService(std::string_view args, const atransport* transport) {
88 size_t delimiter_index = args.find(':');
89 if (delimiter_index == std::string::npos) {
90 LOG(ERROR) << "No ':' found in shell service arguments: " << args;
91 return unique_fd{};
92 }
93
94 // TODO: android::base::Split(const std::string_view&, ...)
95 std::string service_args(args.substr(0, delimiter_index));
96 std::string command(args.substr(delimiter_index + 1));
97
98 // Defaults:
99 // PTY for interactive, raw for non-interactive.
100 // No protocol.
101 // $TERM set to "dumb".
102 SubprocessType type(command.empty() ? SubprocessType::kPty : SubprocessType::kRaw);
103 SubprocessProtocol protocol = SubprocessProtocol::kNone;
104 std::string terminal_type = "dumb";
105
106 for (const std::string& arg : android::base::Split(service_args, ",")) {
107 if (arg == kShellServiceArgRaw) {
108 type = SubprocessType::kRaw;
109 } else if (arg == kShellServiceArgPty) {
110 type = SubprocessType::kPty;
111 } else if (arg == kShellServiceArgShellProtocol) {
112 protocol = SubprocessProtocol::kShell;
113 } else if (arg.starts_with("TERM=")) {
114 terminal_type = arg.substr(strlen("TERM="));
115 } else if (!arg.empty()) {
116 // This is not an error to allow for future expansion.
117 LOG(WARNING) << "Ignoring unknown shell service argument: " << arg;
118 }
119 }
120
121 return StartSubprocess(command, terminal_type.c_str(), type, protocol);
122 }
123
spin_service(unique_fd fd)124 static void spin_service(unique_fd fd) {
125 if (!__android_log_is_debuggable()) {
126 WriteFdExactly(fd.get(), "refusing to spin on non-debuggable build\n");
127 return;
128 }
129
130 // A service that creates an fdevent that's always pending, and then ignores it.
131 unique_fd pipe_read, pipe_write;
132 if (!Pipe(&pipe_read, &pipe_write)) {
133 WriteFdExactly(fd.get(), "failed to create pipe\n");
134 return;
135 }
136
137 fdevent_run_on_main_thread([fd = pipe_read.release()]() {
138 fdevent* fde = fdevent_create(
139 fd, [](int, unsigned, void*) {}, nullptr);
140 fdevent_add(fde, FDE_READ);
141 });
142
143 WriteFdExactly(fd.get(), "spinning\n");
144 }
145
146 struct ServiceSocket : public asocket {
ServiceSocketServiceSocket147 ServiceSocket() {
148 install_local_socket(this);
149 this->enqueue = [](asocket* self, apacket::payload_type data) {
150 return static_cast<ServiceSocket*>(self)->Enqueue(std::move(data));
151 };
152 this->ready = [](asocket* self) { return static_cast<ServiceSocket*>(self)->Ready(); };
153 this->close = [](asocket* self) { return static_cast<ServiceSocket*>(self)->Close(); };
154 }
155 virtual ~ServiceSocket() = default;
156
EnqueueServiceSocket157 virtual int Enqueue(apacket::payload_type data) { return -1; }
ReadyServiceSocket158 virtual void Ready() {}
CloseServiceSocket159 virtual void Close() {
160 if (peer) {
161 peer->peer = nullptr;
162 if (peer->shutdown) {
163 peer->shutdown(peer);
164 }
165 peer->close(peer);
166 }
167
168 remove_socket(this);
169 delete this;
170 }
171 };
172
173 struct SinkSocket : public ServiceSocket {
SinkSocketSinkSocket174 explicit SinkSocket(size_t byte_count) {
175 LOG(INFO) << "Creating new SinkSocket with capacity " << byte_count;
176 bytes_left_ = byte_count;
177 }
178
~SinkSocketSinkSocket179 virtual ~SinkSocket() { LOG(INFO) << "SinkSocket destroyed"; }
180
EnqueueSinkSocket181 virtual int Enqueue(apacket::payload_type data) override final {
182 if (bytes_left_ <= data.size()) {
183 // Done reading.
184 Close();
185 return -1;
186 }
187
188 bytes_left_ -= data.size();
189 return 0;
190 }
191
192 size_t bytes_left_;
193 };
194
195 struct SourceSocket : public ServiceSocket {
SourceSocketSourceSocket196 explicit SourceSocket(size_t byte_count) {
197 LOG(INFO) << "Creating new SourceSocket with capacity " << byte_count;
198 bytes_left_ = byte_count;
199 }
200
~SourceSocketSourceSocket201 virtual ~SourceSocket() { LOG(INFO) << "SourceSocket destroyed"; }
202
ReadySourceSocket203 void Ready() {
204 size_t len = std::min(bytes_left_, get_max_payload());
205 if (len == 0) {
206 Close();
207 return;
208 }
209
210 Block block(len);
211 memset(block.data(), 0, block.size());
212 peer->enqueue(peer, std::move(block));
213 bytes_left_ -= len;
214 }
215
EnqueueSourceSocket216 int Enqueue(apacket::payload_type data) { return -1; }
217
218 size_t bytes_left_;
219 };
220
daemon_service_to_socket(std::string_view name)221 asocket* daemon_service_to_socket(std::string_view name) {
222 if (name == "jdwp") {
223 return create_jdwp_service_socket();
224 } else if (name == "track-jdwp") {
225 return create_jdwp_tracker_service_socket();
226 } else if (ConsumePrefix(&name, "sink:")) {
227 uint64_t byte_count = 0;
228 if (!ParseUint(&byte_count, name)) {
229 return nullptr;
230 }
231 return new SinkSocket(byte_count);
232 } else if (ConsumePrefix(&name, "source:")) {
233 uint64_t byte_count = 0;
234 if (!ParseUint(&byte_count, name)) {
235 return nullptr;
236 }
237 return new SourceSocket(byte_count);
238 }
239
240 return nullptr;
241 }
242
daemon_service_to_fd(std::string_view name,atransport * transport)243 unique_fd daemon_service_to_fd(std::string_view name, atransport* transport) {
244 #if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__)
245 if (name.starts_with("abb:") || name.starts_with("abb_exec:")) {
246 return execute_abb_command(name);
247 }
248 #endif
249
250 #if defined(__ANDROID__)
251 if (name.starts_with("framebuffer:")) {
252 return create_service_thread("fb", framebuffer_service);
253 } else if (ConsumePrefix(&name, "remount:")) {
254 std::string arg(name);
255 return create_service_thread("remount",
256 std::bind(remount_service, std::placeholders::_1, arg));
257 } else if (ConsumePrefix(&name, "reboot:")) {
258 std::string arg(name);
259 return create_service_thread("reboot",
260 std::bind(reboot_service, std::placeholders::_1, arg));
261 } else if (name.starts_with("root:")) {
262 return create_service_thread("root", restart_root_service);
263 } else if (name.starts_with("unroot:")) {
264 return create_service_thread("unroot", restart_unroot_service);
265 } else if (ConsumePrefix(&name, "backup:")) {
266 std::string cmd = "/system/bin/bu backup ";
267 cmd += name;
268 return StartSubprocess(cmd, nullptr, SubprocessType::kRaw, SubprocessProtocol::kNone);
269 } else if (name.starts_with("restore:")) {
270 return StartSubprocess("/system/bin/bu restore", nullptr, SubprocessType::kRaw,
271 SubprocessProtocol::kNone);
272 } else if (name.starts_with("disable-verity:")) {
273 return create_service_thread("verity-on", std::bind(set_verity_enabled_state_service,
274 std::placeholders::_1, false));
275 } else if (name.starts_with("enable-verity:")) {
276 return create_service_thread("verity-off", std::bind(set_verity_enabled_state_service,
277 std::placeholders::_1, true));
278 } else if (ConsumePrefix(&name, "tcpip:")) {
279 std::string str(name);
280
281 int port;
282 if (sscanf(str.c_str(), "%d", &port) != 1) {
283 return unique_fd{};
284 }
285 return create_service_thread("tcp",
286 std::bind(restart_tcp_service, std::placeholders::_1, port));
287 } else if (name.starts_with("usb:")) {
288 return create_service_thread("usb", restart_usb_service);
289 }
290 #endif
291
292 if (ConsumePrefix(&name, "dev:")) {
293 return unique_fd{unix_open(name, O_RDWR | O_CLOEXEC)};
294 } else if (ConsumePrefix(&name, "jdwp:")) {
295 pid_t pid;
296 if (!ParseUint(&pid, name)) {
297 return unique_fd{};
298 }
299 return create_jdwp_connection_fd(pid);
300 } else if (ConsumePrefix(&name, "shell")) {
301 return ShellService(name, transport);
302 } else if (ConsumePrefix(&name, "exec:")) {
303 return StartSubprocess(std::string(name), nullptr, SubprocessType::kRaw,
304 SubprocessProtocol::kNone);
305 } else if (name.starts_with("sync:")) {
306 return create_service_thread("sync", file_sync_service);
307 } else if (ConsumePrefix(&name, "reverse:")) {
308 return reverse_service(name, transport);
309 } else if (name == "reconnect") {
310 return create_service_thread(
311 "reconnect", std::bind(reconnect_service, std::placeholders::_1, transport));
312 } else if (name == "spin") {
313 return create_service_thread("spin", spin_service);
314 }
315
316 return unique_fd{};
317 }
318