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