services.c revision 1c45ee92e2372f3c552744823143fb093fdbda9d
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#include <stddef.h>
18#include <stdlib.h>
19#include <stdio.h>
20#include <unistd.h>
21#include <string.h>
22#include <errno.h>
23
24#include "sysdeps.h"
25
26#define  TRACE_TAG  TRACE_SERVICES
27#include "adb.h"
28#include "file_sync_service.h"
29
30#if ADB_HOST
31#  ifndef HAVE_WINSOCK
32#    include <netinet/in.h>
33#    include <netdb.h>
34#    include <sys/ioctl.h>
35#  endif
36#else
37#  include <cutils/android_reboot.h>
38#endif
39
40typedef struct stinfo stinfo;
41
42struct stinfo {
43    void (*func)(int fd, void *cookie);
44    int fd;
45    void *cookie;
46};
47
48
49void *service_bootstrap_func(void *x)
50{
51    stinfo *sti = x;
52    sti->func(sti->fd, sti->cookie);
53    free(sti);
54    return 0;
55}
56
57#if !ADB_HOST
58
59void restart_root_service(int fd, void *cookie)
60{
61    char buf[100];
62    char value[PROPERTY_VALUE_MAX];
63
64    if (getuid() == 0) {
65        snprintf(buf, sizeof(buf), "adbd is already running as root\n");
66        writex(fd, buf, strlen(buf));
67        adb_close(fd);
68    } else {
69        property_get("ro.debuggable", value, "");
70        if (strcmp(value, "1") != 0) {
71            snprintf(buf, sizeof(buf), "adbd cannot run as root in production builds\n");
72            writex(fd, buf, strlen(buf));
73            adb_close(fd);
74            return;
75        }
76
77        property_set("service.adb.root", "1");
78        snprintf(buf, sizeof(buf), "restarting adbd as root\n");
79        writex(fd, buf, strlen(buf));
80        adb_close(fd);
81    }
82}
83
84void restart_tcp_service(int fd, void *cookie)
85{
86    char buf[100];
87    char value[PROPERTY_VALUE_MAX];
88    int port = (int)cookie;
89
90    if (port <= 0) {
91        snprintf(buf, sizeof(buf), "invalid port\n");
92        writex(fd, buf, strlen(buf));
93        adb_close(fd);
94        return;
95    }
96
97    snprintf(value, sizeof(value), "%d", port);
98    property_set("service.adb.tcp.port", value);
99    snprintf(buf, sizeof(buf), "restarting in TCP mode port: %d\n", port);
100    writex(fd, buf, strlen(buf));
101    adb_close(fd);
102}
103
104void restart_usb_service(int fd, void *cookie)
105{
106    char buf[100];
107
108    property_set("service.adb.tcp.port", "0");
109    snprintf(buf, sizeof(buf), "restarting in USB mode\n");
110    writex(fd, buf, strlen(buf));
111    adb_close(fd);
112}
113
114void reboot_service(int fd, void *arg)
115{
116    char buf[100];
117    char property_val[PROPERTY_VALUE_MAX];
118    int pid, ret;
119
120    sync();
121
122    /* Attempt to unmount the SD card first.
123     * No need to bother checking for errors.
124     */
125    pid = fork();
126    if (pid == 0) {
127        /* ask vdc to unmount it */
128        execl("/system/bin/vdc", "/system/bin/vdc", "volume", "unmount",
129                getenv("EXTERNAL_STORAGE"), "force", NULL);
130    } else if (pid > 0) {
131        /* wait until vdc succeeds or fails */
132        waitpid(pid, &ret, 0);
133    }
134
135    ret = snprintf(property_val, sizeof(property_val), "reboot,%s", (char *) arg);
136    if (ret >= (int) sizeof(property_val)) {
137        snprintf(buf, sizeof(buf), "reboot string too long. length=%d\n", ret);
138        writex(fd, buf, strlen(buf));
139        goto cleanup;
140    }
141
142    ret = property_set(ANDROID_RB_PROPERTY, property_val);
143    if (ret < 0) {
144        snprintf(buf, sizeof(buf), "reboot failed: %d\n", ret);
145        writex(fd, buf, strlen(buf));
146    }
147cleanup:
148    free(arg);
149    adb_close(fd);
150}
151
152#endif
153
154static int create_service_thread(void (*func)(int, void *), void *cookie)
155{
156    stinfo *sti;
157    adb_thread_t t;
158    int s[2];
159
160    if(adb_socketpair(s)) {
161        printf("cannot create service socket pair\n");
162        return -1;
163    }
164
165    sti = malloc(sizeof(stinfo));
166    if(sti == 0) fatal("cannot allocate stinfo");
167    sti->func = func;
168    sti->cookie = cookie;
169    sti->fd = s[1];
170
171    if(adb_thread_create( &t, service_bootstrap_func, sti)){
172        free(sti);
173        adb_close(s[0]);
174        adb_close(s[1]);
175        printf("cannot create service thread\n");
176        return -1;
177    }
178
179    D("service thread started, %d:%d\n",s[0], s[1]);
180    return s[0];
181}
182
183#if !ADB_HOST
184static int create_subprocess(const char *cmd, const char *arg0, const char *arg1, pid_t *pid)
185{
186#ifdef HAVE_WIN32_PROC
187    D("create_subprocess(cmd=%s, arg0=%s, arg1=%s)\n", cmd, arg0, arg1);
188    fprintf(stderr, "error: create_subprocess not implemented on Win32 (%s %s %s)\n", cmd, arg0, arg1);
189    return -1;
190#else /* !HAVE_WIN32_PROC */
191    char *devname;
192    int ptm;
193
194    ptm = unix_open("/dev/ptmx", O_RDWR); // | O_NOCTTY);
195    if(ptm < 0){
196        printf("[ cannot open /dev/ptmx - %s ]\n",strerror(errno));
197        return -1;
198    }
199    fcntl(ptm, F_SETFD, FD_CLOEXEC);
200
201    if(grantpt(ptm) || unlockpt(ptm) ||
202       ((devname = (char*) ptsname(ptm)) == 0)){
203        printf("[ trouble with /dev/ptmx - %s ]\n", strerror(errno));
204        adb_close(ptm);
205        return -1;
206    }
207
208    *pid = fork();
209    if(*pid < 0) {
210        printf("- fork failed: %s -\n", strerror(errno));
211        adb_close(ptm);
212        return -1;
213    }
214
215    if(*pid == 0){
216        int pts;
217
218        setsid();
219
220        pts = unix_open(devname, O_RDWR);
221        if(pts < 0) {
222            fprintf(stderr, "child failed to open pseudo-term slave: %s\n", devname);
223            exit(-1);
224        }
225
226        dup2(pts, 0);
227        dup2(pts, 1);
228        dup2(pts, 2);
229
230        adb_close(pts);
231        adb_close(ptm);
232
233        // set OOM adjustment to zero
234        char text[64];
235        snprintf(text, sizeof text, "/proc/%d/oom_adj", getpid());
236        int fd = adb_open(text, O_WRONLY);
237        if (fd >= 0) {
238            adb_write(fd, "0", 1);
239            adb_close(fd);
240        } else {
241           D("adb: unable to open %s\n", text);
242        }
243        execl(cmd, cmd, arg0, arg1, NULL);
244        fprintf(stderr, "- exec '%s' failed: %s (%d) -\n",
245                cmd, strerror(errno), errno);
246        exit(-1);
247    } else {
248        // Don't set child's OOM adjustment to zero.
249        // Let the child do it itself, as sometimes the parent starts
250        // running before the child has a /proc/pid/oom_adj.
251        // """adb: unable to open /proc/644/oom_adj""" seen in some logs.
252        return ptm;
253    }
254#endif /* !HAVE_WIN32_PROC */
255}
256#endif  /* !ABD_HOST */
257
258#if ADB_HOST
259#define SHELL_COMMAND "/bin/sh"
260#else
261#define SHELL_COMMAND "/system/bin/sh"
262#endif
263
264#if !ADB_HOST
265static void subproc_waiter_service(int fd, void *cookie)
266{
267    pid_t pid = (pid_t)cookie;
268
269    D("entered. fd=%d of pid=%d\n", fd, pid);
270    for (;;) {
271        int status;
272        pid_t p = waitpid(pid, &status, 0);
273        if (p == pid) {
274            D("fd=%d, post waitpid(pid=%d) status=%04x\n", fd, p, status);
275            if (WIFSIGNALED(status)) {
276                D("*** Killed by signal %d\n", WTERMSIG(status));
277                break;
278            } else if (!WIFEXITED(status)) {
279                D("*** Didn't exit!!. status %d\n", status);
280                break;
281            } else if (WEXITSTATUS(status) >= 0) {
282                D("*** Exit code %d\n", WEXITSTATUS(status));
283                break;
284            }
285         }
286    }
287    D("shell exited fd=%d of pid=%d err=%d\n", fd, pid, errno);
288    if (SHELL_EXIT_NOTIFY_FD >=0) {
289      int res;
290      res = writex(SHELL_EXIT_NOTIFY_FD, &fd, sizeof(fd));
291      D("notified shell exit via fd=%d for pid=%d res=%d errno=%d\n",
292        SHELL_EXIT_NOTIFY_FD, pid, res, errno);
293    }
294}
295
296static int create_subproc_thread(const char *name)
297{
298    stinfo *sti;
299    adb_thread_t t;
300    int ret_fd;
301    pid_t pid;
302    if(name) {
303        ret_fd = create_subprocess(SHELL_COMMAND, "-c", name, &pid);
304    } else {
305        ret_fd = create_subprocess(SHELL_COMMAND, "-", 0, &pid);
306    }
307    D("create_subprocess() ret_fd=%d pid=%d\n", ret_fd, pid);
308
309    sti = malloc(sizeof(stinfo));
310    if(sti == 0) fatal("cannot allocate stinfo");
311    sti->func = subproc_waiter_service;
312    sti->cookie = (void*)pid;
313    sti->fd = ret_fd;
314
315    if(adb_thread_create( &t, service_bootstrap_func, sti)){
316        free(sti);
317        adb_close(ret_fd);
318        printf("cannot create service thread\n");
319        return -1;
320    }
321
322    D("service thread started, fd=%d pid=%d\n",ret_fd, pid);
323    return ret_fd;
324}
325#endif
326
327int service_to_fd(const char *name)
328{
329    int ret = -1;
330
331    if(!strncmp(name, "tcp:", 4)) {
332        int port = atoi(name + 4);
333        name = strchr(name + 4, ':');
334        if(name == 0) {
335            ret = socket_loopback_client(port, SOCK_STREAM);
336            if (ret >= 0)
337                disable_tcp_nagle(ret);
338        } else {
339#if ADB_HOST
340            ret = socket_network_client(name + 1, port, SOCK_STREAM);
341#else
342            return -1;
343#endif
344        }
345#ifndef HAVE_WINSOCK   /* winsock doesn't implement unix domain sockets */
346    } else if(!strncmp(name, "local:", 6)) {
347        ret = socket_local_client(name + 6,
348                ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM);
349    } else if(!strncmp(name, "localreserved:", 14)) {
350        ret = socket_local_client(name + 14,
351                ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM);
352    } else if(!strncmp(name, "localabstract:", 14)) {
353        ret = socket_local_client(name + 14,
354                ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
355    } else if(!strncmp(name, "localfilesystem:", 16)) {
356        ret = socket_local_client(name + 16,
357                ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
358#endif
359#if !ADB_HOST
360    } else if(!strncmp("dev:", name, 4)) {
361        ret = unix_open(name + 4, O_RDWR);
362    } else if(!strncmp(name, "framebuffer:", 12)) {
363        ret = create_service_thread(framebuffer_service, 0);
364    } else if (!strncmp(name, "jdwp:", 5)) {
365        ret = create_jdwp_connection_fd(atoi(name+5));
366    } else if (!strncmp(name, "log:", 4)) {
367        ret = create_service_thread(log_service, get_log_file_path(name + 4));
368    } else if(!HOST && !strncmp(name, "shell:", 6)) {
369        if(name[6]) {
370            ret = create_subproc_thread(name + 6);
371        } else {
372            ret = create_subproc_thread(0);
373        }
374    } else if(!strncmp(name, "sync:", 5)) {
375        ret = create_service_thread(file_sync_service, NULL);
376    } else if(!strncmp(name, "remount:", 8)) {
377        ret = create_service_thread(remount_service, NULL);
378    } else if(!strncmp(name, "reboot:", 7)) {
379        void* arg = strdup(name + 7);
380        if(arg == 0) return -1;
381        ret = create_service_thread(reboot_service, arg);
382    } else if(!strncmp(name, "root:", 5)) {
383        ret = create_service_thread(restart_root_service, NULL);
384    } else if(!strncmp(name, "backup:", 7)) {
385        char* arg = strdup(name+7);
386        if (arg == NULL) return -1;
387        ret = backup_service(BACKUP, arg);
388    } else if(!strncmp(name, "restore:", 8)) {
389        ret = backup_service(RESTORE, NULL);
390    } else if(!strncmp(name, "tcpip:", 6)) {
391        int port;
392        if (sscanf(name + 6, "%d", &port) == 0) {
393            port = 0;
394        }
395        ret = create_service_thread(restart_tcp_service, (void *)port);
396    } else if(!strncmp(name, "usb:", 4)) {
397        ret = create_service_thread(restart_usb_service, NULL);
398#endif
399    }
400    if (ret >= 0) {
401        close_on_exec(ret);
402    }
403    return ret;
404}
405
406#if ADB_HOST
407struct state_info {
408    transport_type transport;
409    char* serial;
410    int state;
411};
412
413static void wait_for_state(int fd, void* cookie)
414{
415    struct state_info* sinfo = cookie;
416    char* err = "unknown error";
417
418    D("wait_for_state %d\n", sinfo->state);
419
420    atransport *t = acquire_one_transport(sinfo->state, sinfo->transport, sinfo->serial, &err);
421    if(t != 0) {
422        writex(fd, "OKAY", 4);
423    } else {
424        sendfailmsg(fd, err);
425    }
426
427    if (sinfo->serial)
428        free(sinfo->serial);
429    free(sinfo);
430    adb_close(fd);
431    D("wait_for_state is done\n");
432}
433
434static void connect_device(char* host, char* buffer, int buffer_size)
435{
436    int port, fd;
437    char* portstr = strchr(host, ':');
438    char hostbuf[100];
439    char serial[100];
440    int ret;
441
442    strncpy(hostbuf, host, sizeof(hostbuf) - 1);
443    if (portstr) {
444        if (portstr - host >= (ptrdiff_t)sizeof(hostbuf)) {
445            snprintf(buffer, buffer_size, "bad host name %s", host);
446            return;
447        }
448        // zero terminate the host at the point we found the colon
449        hostbuf[portstr - host] = 0;
450        if (sscanf(portstr + 1, "%d", &port) == 0) {
451            snprintf(buffer, buffer_size, "bad port number %s", portstr);
452            return;
453        }
454    } else {
455        port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
456    }
457
458    snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
459
460    fd = socket_network_client(hostbuf, port, SOCK_STREAM);
461    if (fd < 0) {
462        snprintf(buffer, buffer_size, "unable to connect to %s:%d", host, port);
463        return;
464    }
465
466    D("client: connected on remote on fd %d\n", fd);
467    close_on_exec(fd);
468    disable_tcp_nagle(fd);
469
470    ret = register_socket_transport(fd, serial, port, 0);
471    if (ret < 0) {
472        adb_close(fd);
473        snprintf(buffer, buffer_size, "already connected to %s", serial);
474    } else {
475        snprintf(buffer, buffer_size, "connected to %s", serial);
476    }
477}
478
479void connect_emulator(char* port_spec, char* buffer, int buffer_size)
480{
481    char* port_separator = strchr(port_spec, ',');
482    if (!port_separator) {
483        snprintf(buffer, buffer_size,
484                "unable to parse '%s' as <console port>,<adb port>",
485                port_spec);
486        return;
487    }
488
489    // Zero-terminate console port and make port_separator point to 2nd port.
490    *port_separator++ = 0;
491    int console_port = strtol(port_spec, NULL, 0);
492    int adb_port = strtol(port_separator, NULL, 0);
493    if (!(console_port > 0 && adb_port > 0)) {
494        *(port_separator - 1) = ',';
495        snprintf(buffer, buffer_size,
496                "Invalid port numbers: Expected positive numbers, got '%s'",
497                port_spec);
498        return;
499    }
500
501    /* Check if the emulator is already known.
502     * Note: There's a small but harmless race condition here: An emulator not
503     * present just yet could be registered by another invocation right
504     * after doing this check here. However, local_connect protects
505     * against double-registration too. From here, a better error message
506     * can be produced. In the case of the race condition, the very specific
507     * error message won't be shown, but the data doesn't get corrupted. */
508    atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
509    if (known_emulator != NULL) {
510        snprintf(buffer, buffer_size,
511                "Emulator on port %d already registered.", adb_port);
512        return;
513    }
514
515    /* Check if more emulators can be registered. Similar unproblematic
516     * race condition as above. */
517    int candidate_slot = get_available_local_transport_index();
518    if (candidate_slot < 0) {
519        snprintf(buffer, buffer_size, "Cannot accept more emulators.");
520        return;
521    }
522
523    /* Preconditions met, try to connect to the emulator. */
524    if (!local_connect_arbitrary_ports(console_port, adb_port)) {
525        snprintf(buffer, buffer_size,
526                "Connected to emulator on ports %d,%d", console_port, adb_port);
527    } else {
528        snprintf(buffer, buffer_size,
529                "Could not connect to emulator on ports %d,%d",
530                console_port, adb_port);
531    }
532}
533
534static void connect_service(int fd, void* cookie)
535{
536    char buf[4096];
537    char resp[4096];
538    char *host = cookie;
539
540    if (!strncmp(host, "emu:", 4)) {
541        connect_emulator(host + 4, buf, sizeof(buf));
542    } else {
543        connect_device(host, buf, sizeof(buf));
544    }
545
546    // Send response for emulator and device
547    snprintf(resp, sizeof(resp), "%04x%s",(unsigned)strlen(buf), buf);
548    writex(fd, resp, strlen(resp));
549    adb_close(fd);
550}
551#endif
552
553#if ADB_HOST
554asocket*  host_service_to_socket(const char*  name, const char *serial)
555{
556    if (!strcmp(name,"track-devices")) {
557        return create_device_tracker();
558    } else if (!strncmp(name, "wait-for-", strlen("wait-for-"))) {
559        struct state_info* sinfo = malloc(sizeof(struct state_info));
560
561        if (serial)
562            sinfo->serial = strdup(serial);
563        else
564            sinfo->serial = NULL;
565
566        name += strlen("wait-for-");
567
568        if (!strncmp(name, "local", strlen("local"))) {
569            sinfo->transport = kTransportLocal;
570            sinfo->state = CS_DEVICE;
571        } else if (!strncmp(name, "usb", strlen("usb"))) {
572            sinfo->transport = kTransportUsb;
573            sinfo->state = CS_DEVICE;
574        } else if (!strncmp(name, "any", strlen("any"))) {
575            sinfo->transport = kTransportAny;
576            sinfo->state = CS_DEVICE;
577        } else {
578            free(sinfo);
579            return NULL;
580        }
581
582        int fd = create_service_thread(wait_for_state, sinfo);
583        return create_local_socket(fd);
584    } else if (!strncmp(name, "connect:", 8)) {
585        const char *host = name + 8;
586        int fd = create_service_thread(connect_service, (void *)host);
587        return create_local_socket(fd);
588    }
589    return NULL;
590}
591#endif /* ADB_HOST */
592