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