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