2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define TRACE_TAG TRACE_SERVICES
29 #include <netinet/in.h>
30 #include <sys/ioctl.h>
34 #include <base/stringprintf.h>
37 #include "base/file.h"
38 #include "cutils/android_reboot.h"
39 #include "cutils/properties.h"
44 #include "file_sync_service.h"
45 #include "remount_service.h"
46 #include "transport.h"
49 void (*func)(int fd, void *cookie);
55 void *service_bootstrap_func(void *x)
57 stinfo* sti = reinterpret_cast<stinfo*>(x);
58 sti->func(sti->fd, sti->cookie);
65 void restart_root_service(int fd, void *cookie)
68 char value[PROPERTY_VALUE_MAX];
71 snprintf(buf, sizeof(buf), "adbd is already running as root\n");
72 WriteFdExactly(fd, buf, strlen(buf));
75 property_get("ro.debuggable", value, "");
76 if (strcmp(value, "1") != 0) {
77 snprintf(buf, sizeof(buf), "adbd cannot run as root in production builds\n");
78 WriteFdExactly(fd, buf, strlen(buf));
83 property_set("service.adb.root", "1");
84 snprintf(buf, sizeof(buf), "restarting adbd as root\n");
85 WriteFdExactly(fd, buf, strlen(buf));
90 void restart_unroot_service(int fd, void *cookie)
95 snprintf(buf, sizeof(buf), "adbd not running as root\n");
96 WriteFdExactly(fd, buf, strlen(buf));
99 property_set("service.adb.root", "0");
100 snprintf(buf, sizeof(buf), "restarting adbd as non root\n");
101 WriteFdExactly(fd, buf, strlen(buf));
106 void restart_tcp_service(int fd, void *cookie)
109 char value[PROPERTY_VALUE_MAX];
110 int port = (int) (uintptr_t) cookie;
113 snprintf(buf, sizeof(buf), "invalid port\n");
114 WriteFdExactly(fd, buf, strlen(buf));
119 snprintf(value, sizeof(value), "%d", port);
120 property_set("service.adb.tcp.port", value);
121 snprintf(buf, sizeof(buf), "restarting in TCP mode port: %d\n", port);
122 WriteFdExactly(fd, buf, strlen(buf));
126 void restart_usb_service(int fd, void *cookie)
130 property_set("service.adb.tcp.port", "0");
131 snprintf(buf, sizeof(buf), "restarting in USB mode\n");
132 WriteFdExactly(fd, buf, strlen(buf));
136 static bool reboot_service_impl(int fd, const char* arg) {
137 const char* reboot_arg = arg;
138 bool auto_reboot = false;
140 if (strcmp(reboot_arg, "sideload-auto-reboot") == 0) {
142 reboot_arg = "sideload";
146 // It reboots into sideload mode by setting "--sideload" or "--sideload_auto_reboot"
147 // in the command file.
148 if (strcmp(reboot_arg, "sideload") == 0) {
150 snprintf(buf, sizeof(buf), "'adb root' is required for 'adb reboot sideload'.\n");
151 WriteStringFully(fd, buf);
155 const char* const recovery_dir = "/cache/recovery";
156 const char* const command_file = "/cache/recovery/command";
157 // Ensure /cache/recovery exists.
158 if (adb_mkdir(recovery_dir, 0770) == -1 && errno != EEXIST) {
159 D("Failed to create directory '%s': %s\n", recovery_dir, strerror(errno));
163 bool write_status = android::base::WriteStringToFile(
164 auto_reboot ? "--sideload_auto_reboot" : "--sideload", command_file);
169 reboot_arg = "recovery";
174 char property_val[PROPERTY_VALUE_MAX];
175 int ret = snprintf(property_val, sizeof(property_val), "reboot,%s", reboot_arg);
176 if (ret >= static_cast<int>(sizeof(property_val))) {
177 snprintf(buf, sizeof(buf), "reboot string too long. length=%d\n", ret);
178 WriteStringFully(fd, buf);
182 ret = property_set(ANDROID_RB_PROPERTY, property_val);
184 snprintf(buf, sizeof(buf), "reboot failed: %d\n", ret);
185 WriteStringFully(fd, buf);
192 void reboot_service(int fd, void* arg)
194 if (reboot_service_impl(fd, static_cast<const char*>(arg))) {
195 // Don't return early. Give the reboot command time to take effect
196 // to avoid messing up scripts which do "adb reboot && adb wait-for-device"
206 void reverse_service(int fd, void* arg)
208 const char* command = reinterpret_cast<const char*>(arg);
210 if (handle_forward_request(command, kTransportAny, NULL, fd) < 0) {
211 sendfailmsg(fd, "not a reverse forwarding command");
219 static int create_service_thread(void (*func)(int, void *), void *cookie)
222 if (adb_socketpair(s)) {
223 printf("cannot create service socket pair\n");
226 D("socketpair: (%d,%d)", s[0], s[1]);
228 stinfo* sti = reinterpret_cast<stinfo*>(malloc(sizeof(stinfo)));
229 if (sti == nullptr) {
230 fatal("cannot allocate stinfo");
233 sti->cookie = cookie;
237 if (adb_thread_create(&t, service_bootstrap_func, sti)) {
241 printf("cannot create service thread\n");
245 D("service thread started, %d:%d\n",s[0], s[1]);
251 static void init_subproc_child()
255 // Set OOM score adjustment to prevent killing
256 int fd = adb_open("/proc/self/oom_score_adj", O_WRONLY | O_CLOEXEC);
258 adb_write(fd, "0", 1);
261 D("adb: unable to update oom_score_adj\n");
265 static int create_subproc_pty(const char *cmd, const char *arg0, const char *arg1, pid_t *pid)
267 D("create_subproc_pty(cmd=%s, arg0=%s, arg1=%s)\n", cmd, arg0, arg1);
269 fprintf(stderr, "error: create_subproc_pty not implemented on Win32 (%s %s %s)\n", cmd, arg0, arg1);
274 ptm = unix_open("/dev/ptmx", O_RDWR | O_CLOEXEC); // | O_NOCTTY);
276 printf("[ cannot open /dev/ptmx - %s ]\n",strerror(errno));
281 if(grantpt(ptm) || unlockpt(ptm) || ptsname_r(ptm, devname, sizeof(devname)) != 0) {
282 printf("[ trouble with /dev/ptmx - %s ]\n", strerror(errno));
289 printf("- fork failed: %s -\n", strerror(errno));
295 init_subproc_child();
297 int pts = unix_open(devname, O_RDWR | O_CLOEXEC);
299 fprintf(stderr, "child failed to open pseudo-term slave: %s\n", devname);
303 dup2(pts, STDIN_FILENO);
304 dup2(pts, STDOUT_FILENO);
305 dup2(pts, STDERR_FILENO);
310 execl(cmd, cmd, arg0, arg1, NULL);
311 fprintf(stderr, "- exec '%s' failed: %s (%d) -\n",
312 cmd, strerror(errno), errno);
317 #endif /* !defined(_WIN32) */
320 static int create_subproc_raw(const char *cmd, const char *arg0, const char *arg1, pid_t *pid)
322 D("create_subproc_raw(cmd=%s, arg0=%s, arg1=%s)\n", cmd, arg0, arg1);
324 fprintf(stderr, "error: create_subproc_raw not implemented on Win32 (%s %s %s)\n", cmd, arg0, arg1);
328 // 0 is parent socket, 1 is child socket
330 if (adb_socketpair(sv) < 0) {
331 printf("[ cannot create socket pair - %s ]\n", strerror(errno));
334 D("socketpair: (%d,%d)", sv[0], sv[1]);
338 printf("- fork failed: %s -\n", strerror(errno));
346 init_subproc_child();
348 dup2(sv[1], STDIN_FILENO);
349 dup2(sv[1], STDOUT_FILENO);
350 dup2(sv[1], STDERR_FILENO);
354 execl(cmd, cmd, arg0, arg1, NULL);
355 fprintf(stderr, "- exec '%s' failed: %s (%d) -\n",
356 cmd, strerror(errno), errno);
362 #endif /* !defined(_WIN32) */
364 #endif /* !ABD_HOST */
367 #define SHELL_COMMAND "/bin/sh"
369 #define SHELL_COMMAND "/system/bin/sh"
373 static void subproc_waiter_service(int fd, void *cookie)
375 pid_t pid = (pid_t) (uintptr_t) cookie;
377 D("entered. fd=%d of pid=%d\n", fd, pid);
380 pid_t p = waitpid(pid, &status, 0);
382 D("fd=%d, post waitpid(pid=%d) status=%04x\n", fd, p, status);
383 if (WIFSIGNALED(status)) {
384 D("*** Killed by signal %d\n", WTERMSIG(status));
386 } else if (!WIFEXITED(status)) {
387 D("*** Didn't exit!!. status %d\n", status);
389 } else if (WEXITSTATUS(status) >= 0) {
390 D("*** Exit code %d\n", WEXITSTATUS(status));
395 D("shell exited fd=%d of pid=%d err=%d\n", fd, pid, errno);
396 if (SHELL_EXIT_NOTIFY_FD >=0) {
398 res = WriteFdExactly(SHELL_EXIT_NOTIFY_FD, &fd, sizeof(fd)) ? 0 : -1;
399 D("notified shell exit via fd=%d for pid=%d res=%d errno=%d\n",
400 SHELL_EXIT_NOTIFY_FD, pid, res, errno);
404 static int create_subproc_thread(const char *name, const subproc_mode mode)
410 const char *arg0, *arg1;
411 if (name == 0 || *name == 0) {
412 arg0 = "-"; arg1 = 0;
414 arg0 = "-c"; arg1 = name;
419 ret_fd = create_subproc_pty(SHELL_COMMAND, arg0, arg1, &pid);
422 ret_fd = create_subproc_raw(SHELL_COMMAND, arg0, arg1, &pid);
425 fprintf(stderr, "invalid subproc_mode %d\n", mode);
428 D("create_subproc ret_fd=%d pid=%d\n", ret_fd, pid);
430 stinfo* sti = reinterpret_cast<stinfo*>(malloc(sizeof(stinfo)));
431 if(sti == 0) fatal("cannot allocate stinfo");
432 sti->func = subproc_waiter_service;
433 sti->cookie = (void*) (uintptr_t) pid;
436 if (adb_thread_create(&t, service_bootstrap_func, sti)) {
439 fprintf(stderr, "cannot create service thread\n");
443 D("service thread started, fd=%d pid=%d\n", ret_fd, pid);
448 int service_to_fd(const char *name)
452 if(!strncmp(name, "tcp:", 4)) {
453 int port = atoi(name + 4);
454 name = strchr(name + 4, ':');
456 ret = socket_loopback_client(port, SOCK_STREAM);
458 disable_tcp_nagle(ret);
461 ret = socket_network_client(name + 1, port, SOCK_STREAM);
466 #ifndef HAVE_WINSOCK /* winsock doesn't implement unix domain sockets */
467 } else if(!strncmp(name, "local:", 6)) {
468 ret = socket_local_client(name + 6,
469 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM);
470 } else if(!strncmp(name, "localreserved:", 14)) {
471 ret = socket_local_client(name + 14,
472 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM);
473 } else if(!strncmp(name, "localabstract:", 14)) {
474 ret = socket_local_client(name + 14,
475 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
476 } else if(!strncmp(name, "localfilesystem:", 16)) {
477 ret = socket_local_client(name + 16,
478 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
481 } else if(!strncmp("dev:", name, 4)) {
482 ret = unix_open(name + 4, O_RDWR | O_CLOEXEC);
483 } else if(!strncmp(name, "framebuffer:", 12)) {
484 ret = create_service_thread(framebuffer_service, 0);
485 } else if (!strncmp(name, "jdwp:", 5)) {
486 ret = create_jdwp_connection_fd(atoi(name+5));
487 } else if(!HOST && !strncmp(name, "shell:", 6)) {
488 ret = create_subproc_thread(name + 6, SUBPROC_PTY);
489 } else if(!HOST && !strncmp(name, "exec:", 5)) {
490 ret = create_subproc_thread(name + 5, SUBPROC_RAW);
491 } else if(!strncmp(name, "sync:", 5)) {
492 ret = create_service_thread(file_sync_service, NULL);
493 } else if(!strncmp(name, "remount:", 8)) {
494 ret = create_service_thread(remount_service, NULL);
495 } else if(!strncmp(name, "reboot:", 7)) {
496 void* arg = strdup(name + 7);
497 if (arg == NULL) return -1;
498 ret = create_service_thread(reboot_service, arg);
499 } else if(!strncmp(name, "root:", 5)) {
500 ret = create_service_thread(restart_root_service, NULL);
501 } else if(!strncmp(name, "unroot:", 7)) {
502 ret = create_service_thread(restart_unroot_service, NULL);
503 } else if(!strncmp(name, "backup:", 7)) {
504 ret = create_subproc_thread(android::base::StringPrintf("/system/bin/bu backup %s",
505 (name + 7)).c_str(), SUBPROC_RAW);
506 } else if(!strncmp(name, "restore:", 8)) {
507 ret = create_subproc_thread("/system/bin/bu restore", SUBPROC_RAW);
508 } else if(!strncmp(name, "tcpip:", 6)) {
510 if (sscanf(name + 6, "%d", &port) != 1) {
513 ret = create_service_thread(restart_tcp_service, (void *) (uintptr_t) port);
514 } else if(!strncmp(name, "usb:", 4)) {
515 ret = create_service_thread(restart_usb_service, NULL);
516 } else if (!strncmp(name, "reverse:", 8)) {
517 char* cookie = strdup(name + 8);
518 if (cookie == NULL) {
521 ret = create_service_thread(reverse_service, cookie);
526 } else if(!strncmp(name, "disable-verity:", 15)) {
527 ret = create_service_thread(set_verity_enabled_state_service, (void*)0);
528 } else if(!strncmp(name, "enable-verity:", 15)) {
529 ret = create_service_thread(set_verity_enabled_state_service, (void*)1);
540 transport_type transport;
545 static void wait_for_state(int fd, void* cookie)
547 state_info* sinfo = reinterpret_cast<state_info*>(cookie);
549 D("wait_for_state %d\n", sinfo->state);
551 std::string error_msg = "unknown error";
552 atransport* t = acquire_one_transport(sinfo->state, sinfo->transport, sinfo->serial, &error_msg);
554 WriteFdExactly(fd, "OKAY", 4);
556 sendfailmsg(fd, error_msg.c_str());
563 D("wait_for_state is done\n");
566 static void connect_device(char* host, char* buffer, int buffer_size)
569 char* portstr = strchr(host, ':');
574 strncpy(hostbuf, host, sizeof(hostbuf) - 1);
576 if (portstr - host >= (ptrdiff_t)sizeof(hostbuf)) {
577 snprintf(buffer, buffer_size, "bad host name %s", host);
580 // zero terminate the host at the point we found the colon
581 hostbuf[portstr - host] = 0;
582 if (sscanf(portstr + 1, "%d", &port) != 1) {
583 snprintf(buffer, buffer_size, "bad port number %s", portstr);
587 port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
590 snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
592 fd = socket_network_client_timeout(hostbuf, port, SOCK_STREAM, 10);
594 snprintf(buffer, buffer_size, "unable to connect to %s:%d", host, port);
598 D("client: connected on remote on fd %d\n", fd);
600 disable_tcp_nagle(fd);
602 ret = register_socket_transport(fd, serial, port, 0);
605 snprintf(buffer, buffer_size, "already connected to %s", serial);
607 snprintf(buffer, buffer_size, "connected to %s", serial);
611 void connect_emulator(char* port_spec, char* buffer, int buffer_size)
613 char* port_separator = strchr(port_spec, ',');
614 if (!port_separator) {
615 snprintf(buffer, buffer_size,
616 "unable to parse '%s' as <console port>,<adb port>",
621 // Zero-terminate console port and make port_separator point to 2nd port.
622 *port_separator++ = 0;
623 int console_port = strtol(port_spec, NULL, 0);
624 int adb_port = strtol(port_separator, NULL, 0);
625 if (!(console_port > 0 && adb_port > 0)) {
626 *(port_separator - 1) = ',';
627 snprintf(buffer, buffer_size,
628 "Invalid port numbers: Expected positive numbers, got '%s'",
633 /* Check if the emulator is already known.
634 * Note: There's a small but harmless race condition here: An emulator not
635 * present just yet could be registered by another invocation right
636 * after doing this check here. However, local_connect protects
637 * against double-registration too. From here, a better error message
638 * can be produced. In the case of the race condition, the very specific
639 * error message won't be shown, but the data doesn't get corrupted. */
640 atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
641 if (known_emulator != NULL) {
642 snprintf(buffer, buffer_size,
643 "Emulator on port %d already registered.", adb_port);
647 /* Check if more emulators can be registered. Similar unproblematic
648 * race condition as above. */
649 int candidate_slot = get_available_local_transport_index();
650 if (candidate_slot < 0) {
651 snprintf(buffer, buffer_size, "Cannot accept more emulators.");
655 /* Preconditions met, try to connect to the emulator. */
656 if (!local_connect_arbitrary_ports(console_port, adb_port)) {
657 snprintf(buffer, buffer_size,
658 "Connected to emulator on ports %d,%d", console_port, adb_port);
660 snprintf(buffer, buffer_size,
661 "Could not connect to emulator on ports %d,%d",
662 console_port, adb_port);
666 static void connect_service(int fd, void* cookie)
670 char *host = reinterpret_cast<char*>(cookie);
672 if (!strncmp(host, "emu:", 4)) {
673 connect_emulator(host + 4, buf, sizeof(buf));
675 connect_device(host, buf, sizeof(buf));
678 // Send response for emulator and device
679 snprintf(resp, sizeof(resp), "%04x%s",(unsigned)strlen(buf), buf);
680 WriteFdExactly(fd, resp, strlen(resp));
686 asocket* host_service_to_socket(const char* name, const char *serial)
688 if (!strcmp(name,"track-devices")) {
689 return create_device_tracker();
690 } else if (!strncmp(name, "wait-for-", strlen("wait-for-"))) {
691 auto sinfo = reinterpret_cast<state_info*>(malloc(sizeof(state_info)));
692 if (sinfo == nullptr) {
693 fprintf(stderr, "couldn't allocate state_info: %s", strerror(errno));
698 sinfo->serial = strdup(serial);
700 sinfo->serial = NULL;
702 name += strlen("wait-for-");
704 if (!strncmp(name, "local", strlen("local"))) {
705 sinfo->transport = kTransportLocal;
706 sinfo->state = CS_DEVICE;
707 } else if (!strncmp(name, "usb", strlen("usb"))) {
708 sinfo->transport = kTransportUsb;
709 sinfo->state = CS_DEVICE;
710 } else if (!strncmp(name, "any", strlen("any"))) {
711 sinfo->transport = kTransportAny;
712 sinfo->state = CS_DEVICE;
718 int fd = create_service_thread(wait_for_state, sinfo);
719 return create_local_socket(fd);
720 } else if (!strncmp(name, "connect:", 8)) {
721 const char *host = name + 8;
722 int fd = create_service_thread(connect_service, (void *)host);
723 return create_local_socket(fd);
727 #endif /* ADB_HOST */