1/*
2 * Copyright (C) 2007 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 <stddef.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26
27#ifndef _WIN32
28#include <netdb.h>
29#include <netinet/in.h>
30#include <sys/ioctl.h>
31#include <unistd.h>
32#endif
33
34#include <thread>
35
36#include <android-base/file.h>
37#include <android-base/parsenetaddress.h>
38#include <android-base/stringprintf.h>
39#include <android-base/strings.h>
40#include <cutils/sockets.h>
41
42#if !ADB_HOST
43#include <android-base/properties.h>
44#include <bootloader_message/bootloader_message.h>
45#include <cutils/android_reboot.h>
46#include <log/log_properties.h>
47#endif
48
49#include "adb.h"
50#include "adb_io.h"
51#include "adb_utils.h"
52#include "file_sync_service.h"
53#include "remount_service.h"
54#include "services.h"
55#include "shell_service.h"
56#include "socket_spec.h"
57#include "sysdeps.h"
58#include "transport.h"
59
60struct stinfo {
61    const char* service_name;
62    void (*func)(int fd, void *cookie);
63    int fd;
64    void *cookie;
65};
66
67static void service_bootstrap_func(void* x) {
68    stinfo* sti = reinterpret_cast<stinfo*>(x);
69    adb_thread_setname(android::base::StringPrintf("%s svc %d", sti->service_name, sti->fd));
70    sti->func(sti->fd, sti->cookie);
71    free(sti);
72}
73
74#if !ADB_HOST
75
76void restart_root_service(int fd, void *cookie) {
77    if (getuid() == 0) {
78        WriteFdExactly(fd, "adbd is already running as root\n");
79        adb_close(fd);
80    } else {
81        if (!__android_log_is_debuggable()) {
82            WriteFdExactly(fd, "adbd cannot run as root in production builds\n");
83            adb_close(fd);
84            return;
85        }
86
87        android::base::SetProperty("service.adb.root", "1");
88        WriteFdExactly(fd, "restarting adbd as root\n");
89        adb_close(fd);
90    }
91}
92
93void restart_unroot_service(int fd, void *cookie) {
94    if (getuid() != 0) {
95        WriteFdExactly(fd, "adbd not running as root\n");
96        adb_close(fd);
97    } else {
98        android::base::SetProperty("service.adb.root", "0");
99        WriteFdExactly(fd, "restarting adbd as non root\n");
100        adb_close(fd);
101    }
102}
103
104void restart_tcp_service(int fd, void *cookie) {
105    int port = (int) (uintptr_t) cookie;
106    if (port <= 0) {
107        WriteFdFmt(fd, "invalid port %d\n", port);
108        adb_close(fd);
109        return;
110    }
111
112    android::base::SetProperty("service.adb.tcp.port", android::base::StringPrintf("%d", port));
113    WriteFdFmt(fd, "restarting in TCP mode port: %d\n", port);
114    adb_close(fd);
115}
116
117void restart_usb_service(int fd, void *cookie) {
118    android::base::SetProperty("service.adb.tcp.port", "0");
119    WriteFdExactly(fd, "restarting in USB mode\n");
120    adb_close(fd);
121}
122
123static bool reboot_service_impl(int fd, const char* arg) {
124    const char* reboot_arg = arg;
125    bool auto_reboot = false;
126
127    if (strcmp(reboot_arg, "sideload-auto-reboot") == 0) {
128        auto_reboot = true;
129        reboot_arg = "sideload";
130    }
131
132    // It reboots into sideload mode by setting "--sideload" or "--sideload_auto_reboot"
133    // in the command file.
134    if (strcmp(reboot_arg, "sideload") == 0) {
135        if (getuid() != 0) {
136            WriteFdExactly(fd, "'adb root' is required for 'adb reboot sideload'.\n");
137            return false;
138        }
139
140        const std::vector<std::string> options = {
141            auto_reboot ? "--sideload_auto_reboot" : "--sideload"
142        };
143        std::string err;
144        if (!write_bootloader_message(options, &err)) {
145            D("Failed to set bootloader message: %s", err.c_str());
146            return false;
147        }
148
149        reboot_arg = "recovery";
150    }
151
152    sync();
153
154    if (!reboot_arg || !reboot_arg[0]) reboot_arg = "adb";
155    std::string reboot_string = android::base::StringPrintf("reboot,%s", reboot_arg);
156    if (!android::base::SetProperty(ANDROID_RB_PROPERTY, reboot_string)) {
157        WriteFdFmt(fd, "reboot (%s) failed\n", reboot_string.c_str());
158        return false;
159    }
160
161    return true;
162}
163
164void reboot_service(int fd, void* arg) {
165    if (reboot_service_impl(fd, static_cast<const char*>(arg))) {
166        // Don't return early. Give the reboot command time to take effect
167        // to avoid messing up scripts which do "adb reboot && adb wait-for-device"
168        while (true) {
169            pause();
170        }
171    }
172
173    free(arg);
174    adb_close(fd);
175}
176
177static void reconnect_service(int fd, void* arg) {
178    WriteFdExactly(fd, "done");
179    adb_close(fd);
180    atransport* t = static_cast<atransport*>(arg);
181    kick_transport(t);
182}
183
184int reverse_service(const char* command, atransport* transport) {
185    int s[2];
186    if (adb_socketpair(s)) {
187        PLOG(ERROR) << "cannot create service socket pair.";
188        return -1;
189    }
190    VLOG(SERVICES) << "service socketpair: " << s[0] << ", " << s[1];
191    if (handle_forward_request(command, transport, s[1]) < 0) {
192        SendFail(s[1], "not a reverse forwarding command");
193    }
194    adb_close(s[1]);
195    return s[0];
196}
197
198// Shell service string can look like:
199//   shell[,arg1,arg2,...]:[command]
200static int ShellService(const std::string& args, const atransport* transport) {
201    size_t delimiter_index = args.find(':');
202    if (delimiter_index == std::string::npos) {
203        LOG(ERROR) << "No ':' found in shell service arguments: " << args;
204        return -1;
205    }
206
207    const std::string service_args = args.substr(0, delimiter_index);
208    const std::string command = args.substr(delimiter_index + 1);
209
210    // Defaults:
211    //   PTY for interactive, raw for non-interactive.
212    //   No protocol.
213    //   $TERM set to "dumb".
214    SubprocessType type(command.empty() ? SubprocessType::kPty
215                                        : SubprocessType::kRaw);
216    SubprocessProtocol protocol = SubprocessProtocol::kNone;
217    std::string terminal_type = "dumb";
218
219    for (const std::string& arg : android::base::Split(service_args, ",")) {
220        if (arg == kShellServiceArgRaw) {
221            type = SubprocessType::kRaw;
222        } else if (arg == kShellServiceArgPty) {
223            type = SubprocessType::kPty;
224        } else if (arg == kShellServiceArgShellProtocol) {
225            protocol = SubprocessProtocol::kShell;
226        } else if (android::base::StartsWith(arg, "TERM=")) {
227            terminal_type = arg.substr(5);
228        } else if (!arg.empty()) {
229            // This is not an error to allow for future expansion.
230            LOG(WARNING) << "Ignoring unknown shell service argument: " << arg;
231        }
232    }
233
234    return StartSubprocess(command.c_str(), terminal_type.c_str(), type, protocol);
235}
236
237#endif  // !ADB_HOST
238
239static int create_service_thread(const char* service_name, void (*func)(int, void*), void* cookie) {
240    int s[2];
241    if (adb_socketpair(s)) {
242        printf("cannot create service socket pair\n");
243        return -1;
244    }
245    D("socketpair: (%d,%d)", s[0], s[1]);
246
247#if !ADB_HOST
248    if (func == &file_sync_service) {
249        // Set file sync service socket to maximum size
250        int max_buf = LINUX_MAX_SOCKET_SIZE;
251        adb_setsockopt(s[0], SOL_SOCKET, SO_SNDBUF, &max_buf, sizeof(max_buf));
252        adb_setsockopt(s[1], SOL_SOCKET, SO_SNDBUF, &max_buf, sizeof(max_buf));
253    }
254#endif // !ADB_HOST
255
256    stinfo* sti = reinterpret_cast<stinfo*>(malloc(sizeof(stinfo)));
257    if (sti == nullptr) {
258        fatal("cannot allocate stinfo");
259    }
260    sti->service_name = service_name;
261    sti->func = func;
262    sti->cookie = cookie;
263    sti->fd = s[1];
264
265    std::thread(service_bootstrap_func, sti).detach();
266
267    D("service thread started, %d:%d",s[0], s[1]);
268    return s[0];
269}
270
271int service_to_fd(const char* name, atransport* transport) {
272    int ret = -1;
273
274    if (is_socket_spec(name)) {
275        std::string error;
276        ret = socket_spec_connect(name, &error);
277        if (ret < 0) {
278            LOG(ERROR) << "failed to connect to socket '" << name << "': " << error;
279        }
280#if !ADB_HOST
281    } else if(!strncmp("dev:", name, 4)) {
282        ret = unix_open(name + 4, O_RDWR | O_CLOEXEC);
283    } else if(!strncmp(name, "framebuffer:", 12)) {
284        ret = create_service_thread("fb", framebuffer_service, nullptr);
285    } else if (!strncmp(name, "jdwp:", 5)) {
286        ret = create_jdwp_connection_fd(atoi(name+5));
287    } else if(!strncmp(name, "shell", 5)) {
288        ret = ShellService(name + 5, transport);
289    } else if(!strncmp(name, "exec:", 5)) {
290        ret = StartSubprocess(name + 5, nullptr, SubprocessType::kRaw, SubprocessProtocol::kNone);
291    } else if(!strncmp(name, "sync:", 5)) {
292        ret = create_service_thread("sync", file_sync_service, nullptr);
293    } else if(!strncmp(name, "remount:", 8)) {
294        ret = create_service_thread("remount", remount_service, nullptr);
295    } else if(!strncmp(name, "reboot:", 7)) {
296        void* arg = strdup(name + 7);
297        if (arg == NULL) return -1;
298        ret = create_service_thread("reboot", reboot_service, arg);
299        if (ret < 0) free(arg);
300    } else if(!strncmp(name, "root:", 5)) {
301        ret = create_service_thread("root", restart_root_service, nullptr);
302    } else if(!strncmp(name, "unroot:", 7)) {
303        ret = create_service_thread("unroot", restart_unroot_service, nullptr);
304    } else if(!strncmp(name, "backup:", 7)) {
305        ret = StartSubprocess(android::base::StringPrintf("/system/bin/bu backup %s",
306                                                          (name + 7)).c_str(),
307                              nullptr, SubprocessType::kRaw, SubprocessProtocol::kNone);
308    } else if(!strncmp(name, "restore:", 8)) {
309        ret = StartSubprocess("/system/bin/bu restore", nullptr, SubprocessType::kRaw,
310                              SubprocessProtocol::kNone);
311    } else if(!strncmp(name, "tcpip:", 6)) {
312        int port;
313        if (sscanf(name + 6, "%d", &port) != 1) {
314            return -1;
315        }
316        ret = create_service_thread("tcp", restart_tcp_service, reinterpret_cast<void*>(port));
317    } else if(!strncmp(name, "usb:", 4)) {
318        ret = create_service_thread("usb", restart_usb_service, nullptr);
319    } else if (!strncmp(name, "reverse:", 8)) {
320        ret = reverse_service(name + 8, transport);
321    } else if(!strncmp(name, "disable-verity:", 15)) {
322        ret = create_service_thread("verity-on", set_verity_enabled_state_service,
323                                    reinterpret_cast<void*>(0));
324    } else if(!strncmp(name, "enable-verity:", 15)) {
325        ret = create_service_thread("verity-off", set_verity_enabled_state_service,
326                                    reinterpret_cast<void*>(1));
327    } else if (!strcmp(name, "reconnect")) {
328        ret = create_service_thread("reconnect", reconnect_service, transport);
329#endif
330    }
331    if (ret >= 0) {
332        close_on_exec(ret);
333    }
334    return ret;
335}
336
337#if ADB_HOST
338struct state_info {
339    TransportType transport_type;
340    std::string serial;
341    TransportId transport_id;
342    ConnectionState state;
343};
344
345static void wait_for_state(int fd, void* data) {
346    std::unique_ptr<state_info> sinfo(reinterpret_cast<state_info*>(data));
347
348    D("wait_for_state %d", sinfo->state);
349
350    while (true) {
351        bool is_ambiguous = false;
352        std::string error = "unknown error";
353        const char* serial = sinfo->serial.length() ? sinfo->serial.c_str() : NULL;
354        atransport* t = acquire_one_transport(sinfo->transport_type, serial, sinfo->transport_id,
355                                              &is_ambiguous, &error);
356        if (t != nullptr && (sinfo->state == kCsAny || sinfo->state == t->GetConnectionState())) {
357            SendOkay(fd);
358            break;
359        } else if (!is_ambiguous) {
360            adb_pollfd pfd = {.fd = fd, .events = POLLIN };
361            int rc = adb_poll(&pfd, 1, 1000);
362            if (rc < 0) {
363                SendFail(fd, error);
364                break;
365            } else if (rc > 0 && (pfd.revents & POLLHUP) != 0) {
366                // The other end of the socket is closed, probably because the other side was
367                // terminated, bail out.
368                break;
369            }
370
371            // Try again...
372        } else {
373            SendFail(fd, error);
374            break;
375        }
376    }
377
378    adb_close(fd);
379    D("wait_for_state is done");
380}
381
382void connect_emulator(const std::string& port_spec, std::string* response) {
383    std::vector<std::string> pieces = android::base::Split(port_spec, ",");
384    if (pieces.size() != 2) {
385        *response = android::base::StringPrintf("unable to parse '%s' as <console port>,<adb port>",
386                                                port_spec.c_str());
387        return;
388    }
389
390    int console_port = strtol(pieces[0].c_str(), NULL, 0);
391    int adb_port = strtol(pieces[1].c_str(), NULL, 0);
392    if (console_port <= 0 || adb_port <= 0) {
393        *response = android::base::StringPrintf("Invalid port numbers: %s", port_spec.c_str());
394        return;
395    }
396
397    // Check if the emulator is already known.
398    // Note: There's a small but harmless race condition here: An emulator not
399    // present just yet could be registered by another invocation right
400    // after doing this check here. However, local_connect protects
401    // against double-registration too. From here, a better error message
402    // can be produced. In the case of the race condition, the very specific
403    // error message won't be shown, but the data doesn't get corrupted.
404    atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
405    if (known_emulator != nullptr) {
406        *response = android::base::StringPrintf("Emulator already registered on port %d", adb_port);
407        return;
408    }
409
410    // Preconditions met, try to connect to the emulator.
411    std::string error;
412    if (!local_connect_arbitrary_ports(console_port, adb_port, &error)) {
413        *response = android::base::StringPrintf("Connected to emulator on ports %d,%d",
414                                                console_port, adb_port);
415    } else {
416        *response = android::base::StringPrintf("Could not connect to emulator on ports %d,%d: %s",
417                                                console_port, adb_port, error.c_str());
418    }
419}
420
421static void connect_service(int fd, void* data) {
422    char* host = reinterpret_cast<char*>(data);
423    std::string response;
424    if (!strncmp(host, "emu:", 4)) {
425        connect_emulator(host + 4, &response);
426    } else {
427        connect_device(host, &response);
428    }
429    free(host);
430
431    // Send response for emulator and device
432    SendProtocolString(fd, response);
433    adb_close(fd);
434}
435#endif
436
437#if ADB_HOST
438asocket* host_service_to_socket(const char* name, const char* serial, TransportId transport_id) {
439    if (!strcmp(name,"track-devices")) {
440        return create_device_tracker(false);
441    } else if (!strcmp(name, "track-devices-l")) {
442        return create_device_tracker(true);
443    } else if (android::base::StartsWith(name, "wait-for-")) {
444        name += strlen("wait-for-");
445
446        std::unique_ptr<state_info> sinfo(new state_info);
447        if (sinfo == nullptr) {
448            fprintf(stderr, "couldn't allocate state_info: %s", strerror(errno));
449            return nullptr;
450        }
451
452        if (serial) sinfo->serial = serial;
453        sinfo->transport_id = transport_id;
454
455        if (android::base::StartsWith(name, "local")) {
456            name += strlen("local");
457            sinfo->transport_type = kTransportLocal;
458        } else if (android::base::StartsWith(name, "usb")) {
459            name += strlen("usb");
460            sinfo->transport_type = kTransportUsb;
461        } else if (android::base::StartsWith(name, "any")) {
462            name += strlen("any");
463            sinfo->transport_type = kTransportAny;
464        } else {
465            return nullptr;
466        }
467
468        if (!strcmp(name, "-device")) {
469            sinfo->state = kCsDevice;
470        } else if (!strcmp(name, "-recovery")) {
471            sinfo->state = kCsRecovery;
472        } else if (!strcmp(name, "-sideload")) {
473            sinfo->state = kCsSideload;
474        } else if (!strcmp(name, "-bootloader")) {
475            sinfo->state = kCsBootloader;
476        } else if (!strcmp(name, "-any")) {
477            sinfo->state = kCsAny;
478        } else {
479            return nullptr;
480        }
481
482        int fd = create_service_thread("wait", wait_for_state, sinfo.get());
483        if (fd != -1) {
484            sinfo.release();
485        }
486        return create_local_socket(fd);
487    } else if (!strncmp(name, "connect:", 8)) {
488        char* host = strdup(name + 8);
489        int fd = create_service_thread("connect", connect_service, host);
490        if (fd == -1) {
491            free(host);
492        }
493        return create_local_socket(fd);
494    }
495    return NULL;
496}
497#endif /* ADB_HOST */
498