blob: 3182ddd3aeb9ea7ed32a1d63cc27e8bac4caefe3 [file] [log] [blame]
Josh Gao997cfac2018-07-25 18:15:52 -07001/*
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>
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -070029#include <sys/socket.h>
30#include <sys/un.h>
Josh Gao997cfac2018-07-25 18:15:52 -070031#include <unistd.h>
32
33#include <thread>
34
35#include <android-base/file.h>
Josh Gao6eb78822018-11-16 15:40:16 -080036#include <android-base/parseint.h>
Josh Gao997cfac2018-07-25 18:15:52 -070037#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 <bootloader_message/bootloader_message.h>
43#include <cutils/android_reboot.h>
44#include <cutils/sockets.h>
45#include <log/log_properties.h>
46
47#include "adb.h"
48#include "adb_io.h"
49#include "adb_unique_fd.h"
50#include "adb_utils.h"
51#include "services.h"
52#include "socket_spec.h"
53#include "sysdeps.h"
54#include "transport.h"
55
56#include "daemon/file_sync_service.h"
57#include "daemon/framebuffer_service.h"
58#include "daemon/remount_service.h"
59#include "daemon/set_verity_enable_state_service.h"
60#include "daemon/shell_service.h"
61
62void restart_root_service(unique_fd fd) {
63 if (getuid() == 0) {
64 WriteFdExactly(fd.get(), "adbd is already running as root\n");
65 return;
66 }
67 if (!__android_log_is_debuggable()) {
68 WriteFdExactly(fd.get(), "adbd cannot run as root in production builds\n");
69 return;
70 }
71
72 android::base::SetProperty("service.adb.root", "1");
73 WriteFdExactly(fd.get(), "restarting adbd as root\n");
74}
75
76void restart_unroot_service(unique_fd fd) {
77 if (getuid() != 0) {
78 WriteFdExactly(fd.get(), "adbd not running as root\n");
79 return;
80 }
81 android::base::SetProperty("service.adb.root", "0");
82 WriteFdExactly(fd.get(), "restarting adbd as non root\n");
83}
84
85void restart_tcp_service(unique_fd fd, int port) {
86 if (port <= 0) {
87 WriteFdFmt(fd.get(), "invalid port %d\n", port);
88 return;
89 }
90
91 android::base::SetProperty("service.adb.tcp.port", android::base::StringPrintf("%d", port));
92 WriteFdFmt(fd.get(), "restarting in TCP mode port: %d\n", port);
93}
94
95void restart_usb_service(unique_fd fd) {
96 android::base::SetProperty("service.adb.tcp.port", "0");
97 WriteFdExactly(fd.get(), "restarting in USB mode\n");
98}
99
Josh Gao6fb94612018-08-01 16:00:05 -0700100void reboot_service(unique_fd fd, const std::string& arg) {
Josh Gao997cfac2018-07-25 18:15:52 -0700101 std::string reboot_arg = arg;
Josh Gao997cfac2018-07-25 18:15:52 -0700102 sync();
103
104 if (reboot_arg.empty()) reboot_arg = "adb";
105 std::string reboot_string = android::base::StringPrintf("reboot,%s", reboot_arg.c_str());
Josh Gao6fb94612018-08-01 16:00:05 -0700106
Hridya Valsaraju54258262018-09-19 21:14:18 -0700107 if (reboot_arg == "fastboot" &&
Yifan Hong0e0f8182018-11-16 12:49:06 -0800108 android::base::GetBoolProperty("ro.boot.dynamic_partitions", false) &&
Hridya Valsaraju54258262018-09-19 21:14:18 -0700109 access("/dev/socket/recovery", F_OK) == 0) {
Hridya Valsaraju71fb82a2018-08-02 15:02:06 -0700110 LOG(INFO) << "Recovery specific reboot fastboot";
111 /*
112 * The socket is created to allow switching between recovery and
113 * fastboot.
114 */
115 android::base::unique_fd sock(socket(AF_UNIX, SOCK_STREAM, 0));
116 if (sock < 0) {
117 WriteFdFmt(fd, "reboot (%s) create\n", strerror(errno));
118 PLOG(ERROR) << "Creating recovery socket failed";
119 return;
120 }
121
122 sockaddr_un addr = {.sun_family = AF_UNIX};
123 strncpy(addr.sun_path, "/dev/socket/recovery", sizeof(addr.sun_path) - 1);
124 if (connect(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) == -1) {
125 WriteFdFmt(fd, "reboot (%s) connect\n", strerror(errno));
126 PLOG(ERROR) << "Couldn't connect to recovery socket";
127 return;
128 }
129 const char msg_switch_to_fastboot = 'f';
130 auto ret = adb_write(sock, &msg_switch_to_fastboot, sizeof(msg_switch_to_fastboot));
131 if (ret != sizeof(msg_switch_to_fastboot)) {
132 WriteFdFmt(fd, "reboot (%s) write\n", strerror(errno));
133 PLOG(ERROR) << "Couldn't write message to recovery socket to switch to fastboot";
134 return;
135 }
136 } else {
137 if (!android::base::SetProperty(ANDROID_RB_PROPERTY, reboot_string)) {
138 WriteFdFmt(fd.get(), "reboot (%s) failed\n", reboot_string.c_str());
139 return;
140 }
141 }
Josh Gao997cfac2018-07-25 18:15:52 -0700142 // Don't return early. Give the reboot command time to take effect
143 // to avoid messing up scripts which do "adb reboot && adb wait-for-device"
144 while (true) {
145 pause();
146 }
147}
148
149void reconnect_service(unique_fd fd, atransport* t) {
150 WriteFdExactly(fd.get(), "done");
151 kick_transport(t);
152}
153
154unique_fd reverse_service(const char* command, atransport* transport) {
155 int s[2];
156 if (adb_socketpair(s)) {
157 PLOG(ERROR) << "cannot create service socket pair.";
158 return unique_fd{};
159 }
160 VLOG(SERVICES) << "service socketpair: " << s[0] << ", " << s[1];
Josh Gao19062432018-07-30 18:49:03 -0700161 if (!handle_forward_request(command, transport, s[1])) {
Josh Gao997cfac2018-07-25 18:15:52 -0700162 SendFail(s[1], "not a reverse forwarding command");
163 }
164 adb_close(s[1]);
165 return unique_fd{s[0]};
166}
167
168// Shell service string can look like:
169// shell[,arg1,arg2,...]:[command]
170unique_fd ShellService(const std::string& args, const atransport* transport) {
171 size_t delimiter_index = args.find(':');
172 if (delimiter_index == std::string::npos) {
173 LOG(ERROR) << "No ':' found in shell service arguments: " << args;
174 return unique_fd{};
175 }
176
177 const std::string service_args = args.substr(0, delimiter_index);
178 const std::string command = args.substr(delimiter_index + 1);
179
180 // Defaults:
181 // PTY for interactive, raw for non-interactive.
182 // No protocol.
183 // $TERM set to "dumb".
184 SubprocessType type(command.empty() ? SubprocessType::kPty : SubprocessType::kRaw);
185 SubprocessProtocol protocol = SubprocessProtocol::kNone;
186 std::string terminal_type = "dumb";
187
188 for (const std::string& arg : android::base::Split(service_args, ",")) {
189 if (arg == kShellServiceArgRaw) {
190 type = SubprocessType::kRaw;
191 } else if (arg == kShellServiceArgPty) {
192 type = SubprocessType::kPty;
193 } else if (arg == kShellServiceArgShellProtocol) {
194 protocol = SubprocessProtocol::kShell;
195 } else if (android::base::StartsWith(arg, "TERM=")) {
196 terminal_type = arg.substr(5);
197 } else if (!arg.empty()) {
198 // This is not an error to allow for future expansion.
199 LOG(WARNING) << "Ignoring unknown shell service argument: " << arg;
200 }
201 }
202
203 return StartSubprocess(command.c_str(), terminal_type.c_str(), type, protocol);
204}
205
Josh Gao39c1f4b2018-10-05 17:09:07 -0700206static void spin_service(unique_fd fd) {
207 if (!__android_log_is_debuggable()) {
208 WriteFdExactly(fd.get(), "refusing to spin on non-debuggable build\n");
209 return;
210 }
211
212 // A service that creates an fdevent that's always pending, and then ignores it.
213 unique_fd pipe_read, pipe_write;
214 if (!Pipe(&pipe_read, &pipe_write)) {
215 WriteFdExactly(fd.get(), "failed to create pipe\n");
216 return;
217 }
218
219 fdevent_run_on_main_thread([fd = pipe_read.release()]() {
220 fdevent* fde = fdevent_create(fd, [](int, unsigned, void*) {}, nullptr);
221 fdevent_add(fde, FDE_READ);
222 });
223
224 WriteFdExactly(fd.get(), "spinning\n");
225}
226
Josh Gao6eb78822018-11-16 15:40:16 -0800227struct ServiceSocket : public asocket {
228 ServiceSocket() {
229 install_local_socket(this);
230 this->enqueue = [](asocket* self, apacket::payload_type data) {
231 return static_cast<ServiceSocket*>(self)->Enqueue(std::move(data));
232 };
233 this->ready = [](asocket* self) { return static_cast<ServiceSocket*>(self)->Ready(); };
234 this->close = [](asocket* self) { return static_cast<ServiceSocket*>(self)->Close(); };
235 }
236 virtual ~ServiceSocket() = default;
237
238 virtual int Enqueue(apacket::payload_type data) { return -1; }
239 virtual void Ready() {}
240 virtual void Close() {
241 if (peer) {
242 peer->peer = nullptr;
243 if (peer->shutdown) {
244 peer->shutdown(peer);
245 }
246 peer->close(peer);
247 }
248
249 remove_socket(this);
250 delete this;
251 }
252};
253
254struct SinkSocket : public ServiceSocket {
255 explicit SinkSocket(size_t byte_count) {
256 LOG(INFO) << "Creating new SinkSocket with capacity " << byte_count;
257 bytes_left_ = byte_count;
258 }
259
260 virtual ~SinkSocket() { LOG(INFO) << "SinkSocket destroyed"; }
261
262 virtual int Enqueue(apacket::payload_type data) override final {
263 if (bytes_left_ <= data.size()) {
264 // Done reading.
265 Close();
266 return -1;
267 }
268
269 bytes_left_ -= data.size();
270 return 0;
271 }
272
273 size_t bytes_left_;
274};
275
276struct SourceSocket : public ServiceSocket {
277 explicit SourceSocket(size_t byte_count) {
278 LOG(INFO) << "Creating new SourceSocket with capacity " << byte_count;
279 bytes_left_ = byte_count;
280 }
281
282 virtual ~SourceSocket() { LOG(INFO) << "SourceSocket destroyed"; }
283
284 void Ready() {
285 size_t len = std::min(bytes_left_, get_max_payload());
286 if (len == 0) {
287 Close();
288 return;
289 }
290
291 Block block(len);
292 memset(block.data(), 0, block.size());
293 peer->enqueue(peer, std::move(block));
294 bytes_left_ -= len;
295 }
296
297 int Enqueue(apacket::payload_type data) { return -1; }
298
299 size_t bytes_left_;
300};
301
302asocket* daemon_service_to_socket(std::string_view name) {
303 if (name == "jdwp") {
304 return create_jdwp_service_socket();
305 } else if (name == "track-jdwp") {
306 return create_jdwp_tracker_service_socket();
307 } else if (name.starts_with("sink:")) {
308 name.remove_prefix(strlen("sink:"));
309 uint64_t byte_count = 0;
310 if (!android::base::ParseUint(name.data(), &byte_count)) {
311 return nullptr;
312 }
313 return new SinkSocket(byte_count);
314 } else if (name.starts_with("source:")) {
315 name.remove_prefix(strlen("source:"));
316 uint64_t byte_count = 0;
317 if (!android::base::ParseUint(name.data(), &byte_count)) {
318 return nullptr;
319 }
320 return new SourceSocket(byte_count);
321 }
322
323 return nullptr;
324}
325
Josh Gao997cfac2018-07-25 18:15:52 -0700326unique_fd daemon_service_to_fd(const char* name, atransport* transport) {
327 if (!strncmp("dev:", name, 4)) {
328 return unique_fd{unix_open(name + 4, O_RDWR | O_CLOEXEC)};
329 } else if (!strncmp(name, "framebuffer:", 12)) {
330 return create_service_thread("fb", framebuffer_service);
331 } else if (!strncmp(name, "jdwp:", 5)) {
332 return create_jdwp_connection_fd(atoi(name + 5));
333 } else if (!strncmp(name, "shell", 5)) {
334 return ShellService(name + 5, transport);
335 } else if (!strncmp(name, "exec:", 5)) {
336 return StartSubprocess(name + 5, nullptr, SubprocessType::kRaw, SubprocessProtocol::kNone);
337 } else if (!strncmp(name, "sync:", 5)) {
338 return create_service_thread("sync", file_sync_service);
339 } else if (!strncmp(name, "remount:", 8)) {
340 std::string options(name + strlen("remount:"));
341 return create_service_thread("remount",
342 std::bind(remount_service, std::placeholders::_1, options));
343 } else if (!strncmp(name, "reboot:", 7)) {
344 std::string arg(name + strlen("reboot:"));
345 return create_service_thread("reboot",
346 std::bind(reboot_service, std::placeholders::_1, arg));
347 } else if (!strncmp(name, "root:", 5)) {
348 return create_service_thread("root", restart_root_service);
349 } else if (!strncmp(name, "unroot:", 7)) {
350 return create_service_thread("unroot", restart_unroot_service);
351 } else if (!strncmp(name, "backup:", 7)) {
352 return StartSubprocess(
353 android::base::StringPrintf("/system/bin/bu backup %s", (name + 7)).c_str(),
354 nullptr, SubprocessType::kRaw, SubprocessProtocol::kNone);
355 } else if (!strncmp(name, "restore:", 8)) {
356 return StartSubprocess("/system/bin/bu restore", nullptr, SubprocessType::kRaw,
357 SubprocessProtocol::kNone);
358 } else if (!strncmp(name, "tcpip:", 6)) {
359 int port;
360 if (sscanf(name + 6, "%d", &port) != 1) {
361 return unique_fd{};
362 }
363 return create_service_thread("tcp",
364 std::bind(restart_tcp_service, std::placeholders::_1, port));
365 } else if (!strncmp(name, "usb:", 4)) {
366 return create_service_thread("usb", restart_usb_service);
367 } else if (!strncmp(name, "reverse:", 8)) {
368 return reverse_service(name + 8, transport);
369 } else if (!strncmp(name, "disable-verity:", 15)) {
370 return create_service_thread("verity-on", std::bind(set_verity_enabled_state_service,
371 std::placeholders::_1, false));
372 } else if (!strncmp(name, "enable-verity:", 15)) {
373 return create_service_thread("verity-off", std::bind(set_verity_enabled_state_service,
374 std::placeholders::_1, true));
375 } else if (!strcmp(name, "reconnect")) {
376 return create_service_thread(
377 "reconnect", std::bind(reconnect_service, std::placeholders::_1, transport));
Josh Gao39c1f4b2018-10-05 17:09:07 -0700378 } else if (!strcmp(name, "spin")) {
379 return create_service_thread("spin", spin_service);
Josh Gao997cfac2018-07-25 18:15:52 -0700380 }
Josh Gao39c1f4b2018-10-05 17:09:07 -0700381
Josh Gao997cfac2018-07-25 18:15:52 -0700382 return unique_fd{};
383}