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 <termios.h>
32 #include <unistd.h>
33 
34 #include <thread>
35 
36 #include <android-base/file.h>
37 #include <android-base/parseint.h>
38 #include <android-base/parsenetaddress.h>
39 #include <android-base/properties.h>
40 #include <android-base/stringprintf.h>
41 #include <android-base/strings.h>
42 #include <android-base/unique_fd.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/jdwp_service.h"
59 #include "daemon/logging.h"
60 #include "daemon/restart_service.h"
61 #include "daemon/shell_service.h"
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_looper([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 
reboot_device(const std::string & name)146 [[maybe_unused]] static unique_fd reboot_device(const std::string& name) {
147 #if defined(__ANDROID_RECOVERY__)
148     if (!__android_log_is_debuggable()) {
149         auto reboot_service = [name](unique_fd fd) {
150             std::string reboot_string = android::base::StringPrintf("reboot,%s", name.c_str());
151             if (!android::base::SetProperty(ANDROID_RB_PROPERTY, reboot_string)) {
152                 WriteFdFmt(fd.get(), "reboot (%s) failed\n", reboot_string.c_str());
153                 return;
154             }
155             while (true) pause();
156         };
157         return create_service_thread("reboot", reboot_service);
158     }
159 #endif
160     // Fall through
161     std::string cmd = "/system/bin/reboot ";
162     cmd += name;
163     return StartSubprocess(cmd, nullptr, SubprocessType::kRaw, SubprocessProtocol::kNone);
164 }
165 
166 struct ServiceSocket : public asocket {
167     ServiceSocket() = delete;
ServiceSocketServiceSocket168     explicit ServiceSocket(atransport* transport) {
169         CHECK(transport);
170         install_local_socket(this);
171         this->transport = transport;
172         this->enqueue = [](asocket* self, apacket::payload_type data) {
173             // TODO: This interface currently can't give any backpressure.
174             send_ready(self->id, self->peer->id, self->transport, data.size());
175             return static_cast<ServiceSocket*>(self)->Enqueue(std::move(data));
176         };
177         this->ready = [](asocket* self) { return static_cast<ServiceSocket*>(self)->Ready(); };
178         this->close = [](asocket* self) { return static_cast<ServiceSocket*>(self)->Close(); };
179     }
180     virtual ~ServiceSocket() = default;
181 
182     ServiceSocket(const ServiceSocket& copy) = delete;
183     ServiceSocket(ServiceSocket&& move) = delete;
184     ServiceSocket& operator=(const ServiceSocket& copy) = delete;
185     ServiceSocket& operator=(ServiceSocket&& move) = delete;
186 
EnqueueServiceSocket187     virtual int Enqueue(apacket::payload_type data) { return -1; }
ReadyServiceSocket188     virtual void Ready() {}
CloseServiceSocket189     virtual void Close() {
190         if (peer) {
191             peer->peer = nullptr;
192             if (peer->shutdown) {
193                 peer->shutdown(peer);
194             }
195             peer->close(peer);
196         }
197 
198         remove_socket(this);
199         delete this;
200     }
201 };
202 
203 struct SinkSocket : public ServiceSocket {
SinkSocketSinkSocket204     explicit SinkSocket(atransport* transport, size_t byte_count)
205         : ServiceSocket(transport), bytes_left_(byte_count) {
206         LOG(INFO) << "Creating new SinkSocket with capacity " << byte_count;
207     }
208 
~SinkSocketSinkSocket209     virtual ~SinkSocket() { LOG(INFO) << "SinkSocket destroyed"; }
210 
EnqueueSinkSocket211     virtual int Enqueue(apacket::payload_type data) override final {
212         if (bytes_left_ <= data.size()) {
213             // Done reading.
214             Close();
215             return -1;
216         }
217 
218         bytes_left_ -= data.size();
219         return 0;
220     }
221 
222     size_t bytes_left_;
223 };
224 
225 struct SourceSocket : public ServiceSocket {
SourceSocketSourceSocket226     explicit SourceSocket(atransport* transport, size_t byte_count)
227         : ServiceSocket(transport), bytes_left_(byte_count) {
228         LOG(INFO) << "Creating new SourceSocket with capacity " << byte_count;
229     }
230 
~SourceSocketSourceSocket231     virtual ~SourceSocket() { LOG(INFO) << "SourceSocket destroyed"; }
232 
ReadySourceSocket233     void Ready() {
234         size_t len = std::min(bytes_left_, get_max_payload());
235         if (len == 0) {
236             Close();
237             return;
238         }
239 
240         Block block(len);
241         memset(block.data(), 0, block.size());
242         peer->enqueue(peer, std::move(block));
243         bytes_left_ -= len;
244     }
245 
EnqueueSourceSocket246     int Enqueue(apacket::payload_type data) { return -1; }
247 
248     size_t bytes_left_;
249 };
250 
daemon_service_to_socket(std::string_view name,atransport * transport)251 asocket* daemon_service_to_socket(std::string_view name, atransport* transport) {
252     if (name == "jdwp") {
253         return create_jdwp_service_socket();
254     } else if (name == "track-jdwp") {
255         return create_jdwp_tracker_service_socket();
256     } else if (name == "track-app") {
257         return create_app_tracker_service_socket();
258     } else if (android::base::ConsumePrefix(&name, "sink:")) {
259         uint64_t byte_count = 0;
260         if (!ParseUint(&byte_count, name)) {
261             return nullptr;
262         }
263         return new SinkSocket(transport, byte_count);
264     } else if (android::base::ConsumePrefix(&name, "source:")) {
265         uint64_t byte_count = 0;
266         if (!ParseUint(&byte_count, name)) {
267             return nullptr;
268         }
269         return new SourceSocket(transport, byte_count);
270     }
271 
272     return nullptr;
273 }
274 
daemon_service_to_fd(std::string_view name,atransport * transport)275 unique_fd daemon_service_to_fd(std::string_view name, atransport* transport) {
276     ADB_LOG(Service) << "transport " << transport->serial_name() << " opening service " << name;
277 
278 #if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__)
279     if (name.starts_with("abb:") || name.starts_with("abb_exec:")) {
280         return execute_abb_command(name);
281     }
282 #endif
283 
284 #if defined(__ANDROID__)
285     if (name.starts_with("framebuffer:")) {
286         return create_service_thread("fb", framebuffer_service);
287     } else if (android::base::ConsumePrefix(&name, "remount:")) {
288         std::string cmd = "/system/bin/remount ";
289         cmd += name;
290         return StartSubprocess(cmd, nullptr, SubprocessType::kRaw, SubprocessProtocol::kNone);
291     } else if (android::base::ConsumePrefix(&name, "reboot:")) {
292         return reboot_device(std::string(name));
293     } else if (name.starts_with("root:")) {
294         return create_service_thread("root", restart_root_service);
295     } else if (name.starts_with("unroot:")) {
296         return create_service_thread("unroot", restart_unroot_service);
297     } else if (android::base::ConsumePrefix(&name, "backup:")) {
298         std::string cmd = "/system/bin/bu backup ";
299         cmd += name;
300         return StartSubprocess(cmd, nullptr, SubprocessType::kRaw, SubprocessProtocol::kNone);
301     } else if (name.starts_with("restore:")) {
302         return StartSubprocess("/system/bin/bu restore", nullptr, SubprocessType::kRaw,
303                                SubprocessProtocol::kNone);
304     } else if (name.starts_with("disable-verity:")) {
305         return StartSubprocess("/system/bin/disable-verity", nullptr, SubprocessType::kRaw,
306                                SubprocessProtocol::kNone);
307     } else if (name.starts_with("enable-verity:")) {
308         return StartSubprocess("/system/bin/enable-verity", nullptr, SubprocessType::kRaw,
309                                SubprocessProtocol::kNone);
310     } else if (android::base::ConsumePrefix(&name, "tcpip:")) {
311         std::string str(name);
312 
313         int port;
314         if (sscanf(str.c_str(), "%d", &port) != 1) {
315             return unique_fd{};
316         }
317         return create_service_thread("tcp",
318                                      std::bind(restart_tcp_service, std::placeholders::_1, port));
319     } else if (name.starts_with("usb:")) {
320         return create_service_thread("usb", restart_usb_service);
321     }
322 #endif
323 
324     if (android::base::ConsumePrefix(&name, "dev:")) {
325         return unique_fd{unix_open(name, O_RDWR | O_CLOEXEC)};
326     } else if (android::base::ConsumePrefix(&name, "dev-raw:")) {
327         android::base::unique_fd fd(unix_open(name, O_RDWR | O_CLOEXEC));
328         termios tattr;
329 
330         if (fd == -1) {
331             return unique_fd{};
332         }
333 
334         if (tcgetattr(fd.get(), &tattr) == -1) {
335             return unique_fd{};
336         }
337         cfmakeraw(&tattr);
338         if (tcsetattr(fd.get(), TCSADRAIN, &tattr) == -1) {
339             return unique_fd{};
340         }
341 
342         return fd;
343     } else if (android::base::ConsumePrefix(&name, "jdwp:")) {
344         pid_t pid;
345         if (!ParseUint(&pid, name)) {
346             return unique_fd{};
347         }
348         return create_jdwp_connection_fd(pid);
349     } else if (android::base::ConsumePrefix(&name, "shell")) {
350         return ShellService(name, transport);
351     } else if (android::base::ConsumePrefix(&name, "exec:")) {
352         return StartSubprocess(std::string(name), nullptr, SubprocessType::kRaw,
353                                SubprocessProtocol::kNone);
354     } else if (name.starts_with("sync:")) {
355         return create_service_thread("sync", file_sync_service);
356     } else if (android::base::ConsumePrefix(&name, "reverse:")) {
357         return reverse_service(name, transport);
358     } else if (name == "reconnect") {
359         return create_service_thread(
360                 "reconnect", std::bind(reconnect_service, std::placeholders::_1, transport));
361     } else if (name == "spin") {
362         return create_service_thread("spin", spin_service);
363     }
364 
365     return unique_fd{};
366 }
367