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/restart_service.h"
58 #include "daemon/set_verity_enable_state_service.h"
59 #include "daemon/shell_service.h"
60 
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_main_thread([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 
145 struct ServiceSocket : public asocket {
ServiceSocketServiceSocket146     ServiceSocket() {
147         install_local_socket(this);
148         this->enqueue = [](asocket* self, apacket::payload_type data) {
149             return static_cast<ServiceSocket*>(self)->Enqueue(std::move(data));
150         };
151         this->ready = [](asocket* self) { return static_cast<ServiceSocket*>(self)->Ready(); };
152         this->close = [](asocket* self) { return static_cast<ServiceSocket*>(self)->Close(); };
153     }
154     virtual ~ServiceSocket() = default;
155 
EnqueueServiceSocket156     virtual int Enqueue(apacket::payload_type data) { return -1; }
ReadyServiceSocket157     virtual void Ready() {}
CloseServiceSocket158     virtual void Close() {
159         if (peer) {
160             peer->peer = nullptr;
161             if (peer->shutdown) {
162                 peer->shutdown(peer);
163             }
164             peer->close(peer);
165         }
166 
167         remove_socket(this);
168         delete this;
169     }
170 };
171 
172 struct SinkSocket : public ServiceSocket {
SinkSocketSinkSocket173     explicit SinkSocket(size_t byte_count) {
174         LOG(INFO) << "Creating new SinkSocket with capacity " << byte_count;
175         bytes_left_ = byte_count;
176     }
177 
~SinkSocketSinkSocket178     virtual ~SinkSocket() { LOG(INFO) << "SinkSocket destroyed"; }
179 
EnqueueSinkSocket180     virtual int Enqueue(apacket::payload_type data) override final {
181         if (bytes_left_ <= data.size()) {
182             // Done reading.
183             Close();
184             return -1;
185         }
186 
187         bytes_left_ -= data.size();
188         return 0;
189     }
190 
191     size_t bytes_left_;
192 };
193 
194 struct SourceSocket : public ServiceSocket {
SourceSocketSourceSocket195     explicit SourceSocket(size_t byte_count) {
196         LOG(INFO) << "Creating new SourceSocket with capacity " << byte_count;
197         bytes_left_ = byte_count;
198     }
199 
~SourceSocketSourceSocket200     virtual ~SourceSocket() { LOG(INFO) << "SourceSocket destroyed"; }
201 
ReadySourceSocket202     void Ready() {
203         size_t len = std::min(bytes_left_, get_max_payload());
204         if (len == 0) {
205             Close();
206             return;
207         }
208 
209         Block block(len);
210         memset(block.data(), 0, block.size());
211         peer->enqueue(peer, std::move(block));
212         bytes_left_ -= len;
213     }
214 
EnqueueSourceSocket215     int Enqueue(apacket::payload_type data) { return -1; }
216 
217     size_t bytes_left_;
218 };
219 
daemon_service_to_socket(std::string_view name)220 asocket* daemon_service_to_socket(std::string_view name) {
221     if (name == "jdwp") {
222         return create_jdwp_service_socket();
223     } else if (name == "track-jdwp") {
224         return create_jdwp_tracker_service_socket();
225     } else if (android::base::ConsumePrefix(&name, "sink:")) {
226         uint64_t byte_count = 0;
227         if (!ParseUint(&byte_count, name)) {
228             return nullptr;
229         }
230         return new SinkSocket(byte_count);
231     } else if (android::base::ConsumePrefix(&name, "source:")) {
232         uint64_t byte_count = 0;
233         if (!ParseUint(&byte_count, name)) {
234             return nullptr;
235         }
236         return new SourceSocket(byte_count);
237     }
238 
239     return nullptr;
240 }
241 
daemon_service_to_fd(std::string_view name,atransport * transport)242 unique_fd daemon_service_to_fd(std::string_view name, atransport* transport) {
243 #if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__)
244     if (name.starts_with("abb:") || name.starts_with("abb_exec:")) {
245         return execute_abb_command(name);
246     }
247 #endif
248 
249 #if defined(__ANDROID__)
250     if (name.starts_with("framebuffer:")) {
251         return create_service_thread("fb", framebuffer_service);
252     } else if (android::base::ConsumePrefix(&name, "remount:")) {
253         std::string cmd = "/system/bin/remount ";
254         cmd += name;
255         return StartSubprocess(cmd, nullptr, SubprocessType::kRaw, SubprocessProtocol::kNone);
256     } else if (android::base::ConsumePrefix(&name, "reboot:")) {
257         std::string arg(name);
258         return create_service_thread("reboot",
259                                      std::bind(reboot_service, std::placeholders::_1, arg));
260     } else if (name.starts_with("root:")) {
261         return create_service_thread("root", restart_root_service);
262     } else if (name.starts_with("unroot:")) {
263         return create_service_thread("unroot", restart_unroot_service);
264     } else if (android::base::ConsumePrefix(&name, "backup:")) {
265         std::string cmd = "/system/bin/bu backup ";
266         cmd += name;
267         return StartSubprocess(cmd, nullptr, SubprocessType::kRaw, SubprocessProtocol::kNone);
268     } else if (name.starts_with("restore:")) {
269         return StartSubprocess("/system/bin/bu restore", nullptr, SubprocessType::kRaw,
270                                SubprocessProtocol::kNone);
271     } else if (name.starts_with("disable-verity:")) {
272         return create_service_thread("verity-on", std::bind(set_verity_enabled_state_service,
273                                                             std::placeholders::_1, false));
274     } else if (name.starts_with("enable-verity:")) {
275         return create_service_thread("verity-off", std::bind(set_verity_enabled_state_service,
276                                                              std::placeholders::_1, true));
277     } else if (android::base::ConsumePrefix(&name, "tcpip:")) {
278         std::string str(name);
279 
280         int port;
281         if (sscanf(str.c_str(), "%d", &port) != 1) {
282             return unique_fd{};
283         }
284         return create_service_thread("tcp",
285                                      std::bind(restart_tcp_service, std::placeholders::_1, port));
286     } else if (name.starts_with("usb:")) {
287         return create_service_thread("usb", restart_usb_service);
288     }
289 #endif
290 
291     if (android::base::ConsumePrefix(&name, "dev:")) {
292         return unique_fd{unix_open(name, O_RDWR | O_CLOEXEC)};
293     } else if (android::base::ConsumePrefix(&name, "jdwp:")) {
294         pid_t pid;
295         if (!ParseUint(&pid, name)) {
296             return unique_fd{};
297         }
298         return create_jdwp_connection_fd(pid);
299     } else if (android::base::ConsumePrefix(&name, "shell")) {
300         return ShellService(name, transport);
301     } else if (android::base::ConsumePrefix(&name, "exec:")) {
302         return StartSubprocess(std::string(name), nullptr, SubprocessType::kRaw,
303                                SubprocessProtocol::kNone);
304     } else if (name.starts_with("sync:")) {
305         return create_service_thread("sync", file_sync_service);
306     } else if (android::base::ConsumePrefix(&name, "reverse:")) {
307         return reverse_service(name, transport);
308     } else if (name == "reconnect") {
309         return create_service_thread(
310                 "reconnect", std::bind(reconnect_service, std::placeholders::_1, transport));
311     } else if (name == "spin") {
312         return create_service_thread("spin", spin_service);
313     }
314 
315     return unique_fd{};
316 }
317