1/*
2** Copyright 2008, 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 <sys/capability.h>
18#include <sys/prctl.h>
19#include <selinux/android.h>
20#include <selinux/avc.h>
21
22#include "installd.h"
23
24
25#define BUFFER_MAX    1024  /* input buffer for commands */
26#define TOKEN_MAX     8     /* max number of arguments in buffer */
27#define REPLY_MAX     256   /* largest reply allowed */
28
29static int do_ping(char **arg, char reply[REPLY_MAX])
30{
31    return 0;
32}
33
34static int do_install(char **arg, char reply[REPLY_MAX])
35{
36    return install(arg[0], atoi(arg[1]), atoi(arg[2]), arg[3]); /* pkgname, uid, gid, seinfo */
37}
38
39static int do_dexopt(char **arg, char reply[REPLY_MAX])
40{
41    /* apk_path, uid, is_public, pkgname, instruction_set, vm_safe_mode, should_relocate */
42    return dexopt(arg[0], atoi(arg[1]), atoi(arg[2]), arg[3], arg[4], atoi(arg[5]), 0);
43}
44
45static int do_mark_boot_complete(char **arg, char reply[REPLY_MAX])
46{
47    return mark_boot_complete(arg[0] /* instruction set */);
48}
49
50static int do_move_dex(char **arg, char reply[REPLY_MAX])
51{
52    return move_dex(arg[0], arg[1], arg[2]); /* src, dst, instruction_set */
53}
54
55static int do_rm_dex(char **arg, char reply[REPLY_MAX])
56{
57    return rm_dex(arg[0], arg[1]); /* pkgname, instruction_set */
58}
59
60static int do_remove(char **arg, char reply[REPLY_MAX])
61{
62    return uninstall(arg[0], atoi(arg[1])); /* pkgname, userid */
63}
64
65static int do_rename(char **arg, char reply[REPLY_MAX])
66{
67    return renamepkg(arg[0], arg[1]); /* oldpkgname, newpkgname */
68}
69
70static int do_fixuid(char **arg, char reply[REPLY_MAX])
71{
72    return fix_uid(arg[0], atoi(arg[1]), atoi(arg[2])); /* pkgname, uid, gid */
73}
74
75static int do_free_cache(char **arg, char reply[REPLY_MAX]) /* TODO int:free_size */
76{
77    return free_cache((int64_t)atoll(arg[0])); /* free_size */
78}
79
80static int do_rm_cache(char **arg, char reply[REPLY_MAX])
81{
82    return delete_cache(arg[0], atoi(arg[1])); /* pkgname, userid */
83}
84
85static int do_rm_code_cache(char **arg, char reply[REPLY_MAX])
86{
87    return delete_code_cache(arg[0], atoi(arg[1])); /* pkgname, userid */
88}
89
90static int do_get_size(char **arg, char reply[REPLY_MAX])
91{
92    int64_t codesize = 0;
93    int64_t datasize = 0;
94    int64_t cachesize = 0;
95    int64_t asecsize = 0;
96    int res = 0;
97
98        /* pkgdir, userid, apkpath */
99    res = get_size(arg[0], atoi(arg[1]), arg[2], arg[3], arg[4], arg[5],
100            arg[6], &codesize, &datasize, &cachesize, &asecsize);
101
102    /*
103     * Each int64_t can take up 22 characters printed out. Make sure it
104     * doesn't go over REPLY_MAX in the future.
105     */
106    snprintf(reply, REPLY_MAX, "%" PRId64 " %" PRId64 " %" PRId64 " %" PRId64,
107            codesize, datasize, cachesize, asecsize);
108    return res;
109}
110
111static int do_rm_user_data(char **arg, char reply[REPLY_MAX])
112{
113    return delete_user_data(arg[0], atoi(arg[1])); /* pkgname, userid */
114}
115
116static int do_mk_user_data(char **arg, char reply[REPLY_MAX])
117{
118    return make_user_data(arg[0], atoi(arg[1]), atoi(arg[2]), arg[3]);
119                             /* pkgname, uid, userid, seinfo */
120}
121
122static int do_mk_user_config(char **arg, char reply[REPLY_MAX])
123{
124    return make_user_config(atoi(arg[0])); /* userid */
125}
126
127static int do_rm_user(char **arg, char reply[REPLY_MAX])
128{
129    return delete_user(atoi(arg[0])); /* userid */
130}
131
132static int do_movefiles(char **arg, char reply[REPLY_MAX])
133{
134    return movefiles();
135}
136
137static int do_linklib(char **arg, char reply[REPLY_MAX])
138{
139    return linklib(arg[0], arg[1], atoi(arg[2]));
140}
141
142static int do_idmap(char **arg, char reply[REPLY_MAX])
143{
144    return idmap(arg[0], arg[1], atoi(arg[2]));
145}
146
147static int do_restorecon_data(char **arg, char reply[REPLY_MAX] __attribute__((unused)))
148{
149    return restorecon_data(arg[0], arg[1], atoi(arg[2]));
150                             /* pkgName, seinfo, uid*/
151}
152
153static int do_patchoat(char **arg, char reply[REPLY_MAX]) {
154    /* apk_path, uid, is_public, pkgname, instruction_set, vm_safe_mode, should_relocate */
155    return dexopt(arg[0], atoi(arg[1]), atoi(arg[2]), arg[3], arg[4], 0, 1);
156}
157
158struct cmdinfo {
159    const char *name;
160    unsigned numargs;
161    int (*func)(char **arg, char reply[REPLY_MAX]);
162};
163
164struct cmdinfo cmds[] = {
165    { "ping",                 0, do_ping },
166    { "install",              4, do_install },
167    { "dexopt",               6, do_dexopt },
168    { "markbootcomplete",     1, do_mark_boot_complete },
169    { "movedex",              3, do_move_dex },
170    { "rmdex",                2, do_rm_dex },
171    { "remove",               2, do_remove },
172    { "rename",               2, do_rename },
173    { "fixuid",               3, do_fixuid },
174    { "freecache",            1, do_free_cache },
175    { "rmcache",              2, do_rm_cache },
176    { "rmcodecache",          2, do_rm_code_cache },
177    { "getsize",              7, do_get_size },
178    { "rmuserdata",           2, do_rm_user_data },
179    { "movefiles",            0, do_movefiles },
180    { "linklib",              3, do_linklib },
181    { "mkuserdata",           4, do_mk_user_data },
182    { "mkuserconfig",         1, do_mk_user_config },
183    { "rmuser",               1, do_rm_user },
184    { "idmap",                3, do_idmap },
185    { "restorecondata",       3, do_restorecon_data },
186    { "patchoat",             5, do_patchoat },
187};
188
189static int readx(int s, void *_buf, int count)
190{
191    char *buf = _buf;
192    int n = 0, r;
193    if (count < 0) return -1;
194    while (n < count) {
195        r = read(s, buf + n, count - n);
196        if (r < 0) {
197            if (errno == EINTR) continue;
198            ALOGE("read error: %s\n", strerror(errno));
199            return -1;
200        }
201        if (r == 0) {
202            ALOGE("eof\n");
203            return -1; /* EOF */
204        }
205        n += r;
206    }
207    return 0;
208}
209
210static int writex(int s, const void *_buf, int count)
211{
212    const char *buf = _buf;
213    int n = 0, r;
214    if (count < 0) return -1;
215    while (n < count) {
216        r = write(s, buf + n, count - n);
217        if (r < 0) {
218            if (errno == EINTR) continue;
219            ALOGE("write error: %s\n", strerror(errno));
220            return -1;
221        }
222        n += r;
223    }
224    return 0;
225}
226
227
228/* Tokenize the command buffer, locate a matching command,
229 * ensure that the required number of arguments are provided,
230 * call the function(), return the result.
231 */
232static int execute(int s, char cmd[BUFFER_MAX])
233{
234    char reply[REPLY_MAX];
235    char *arg[TOKEN_MAX+1];
236    unsigned i;
237    unsigned n = 0;
238    unsigned short count;
239    int ret = -1;
240
241    // ALOGI("execute('%s')\n", cmd);
242
243        /* default reply is "" */
244    reply[0] = 0;
245
246        /* n is number of args (not counting arg[0]) */
247    arg[0] = cmd;
248    while (*cmd) {
249        if (isspace(*cmd)) {
250            *cmd++ = 0;
251            n++;
252            arg[n] = cmd;
253            if (n == TOKEN_MAX) {
254                ALOGE("too many arguments\n");
255                goto done;
256            }
257        }
258        cmd++;
259    }
260
261    for (i = 0; i < sizeof(cmds) / sizeof(cmds[0]); i++) {
262        if (!strcmp(cmds[i].name,arg[0])) {
263            if (n != cmds[i].numargs) {
264                ALOGE("%s requires %d arguments (%d given)\n",
265                     cmds[i].name, cmds[i].numargs, n);
266            } else {
267                ret = cmds[i].func(arg + 1, reply);
268            }
269            goto done;
270        }
271    }
272    ALOGE("unsupported command '%s'\n", arg[0]);
273
274done:
275    if (reply[0]) {
276        n = snprintf(cmd, BUFFER_MAX, "%d %s", ret, reply);
277    } else {
278        n = snprintf(cmd, BUFFER_MAX, "%d", ret);
279    }
280    if (n > BUFFER_MAX) n = BUFFER_MAX;
281    count = n;
282
283    // ALOGI("reply: '%s'\n", cmd);
284    if (writex(s, &count, sizeof(count))) return -1;
285    if (writex(s, cmd, count)) return -1;
286    return 0;
287}
288
289/**
290 * Initialize all the global variables that are used elsewhere. Returns 0 upon
291 * success and -1 on error.
292 */
293void free_globals() {
294    size_t i;
295
296    for (i = 0; i < android_system_dirs.count; i++) {
297        if (android_system_dirs.dirs[i].path != NULL) {
298            free(android_system_dirs.dirs[i].path);
299        }
300    }
301
302    free(android_system_dirs.dirs);
303}
304
305int initialize_globals() {
306    // Get the android data directory.
307    if (get_path_from_env(&android_data_dir, "ANDROID_DATA") < 0) {
308        return -1;
309    }
310
311    // Get the android app directory.
312    if (copy_and_append(&android_app_dir, &android_data_dir, APP_SUBDIR) < 0) {
313        return -1;
314    }
315
316    // Get the android protected app directory.
317    if (copy_and_append(&android_app_private_dir, &android_data_dir, PRIVATE_APP_SUBDIR) < 0) {
318        return -1;
319    }
320
321    // Get the android app native library directory.
322    if (copy_and_append(&android_app_lib_dir, &android_data_dir, APP_LIB_SUBDIR) < 0) {
323        return -1;
324    }
325
326    // Get the sd-card ASEC mount point.
327    if (get_path_from_env(&android_asec_dir, "ASEC_MOUNTPOINT") < 0) {
328        return -1;
329    }
330
331    // Get the android media directory.
332    if (copy_and_append(&android_media_dir, &android_data_dir, MEDIA_SUBDIR) < 0) {
333        return -1;
334    }
335
336    // Take note of the system and vendor directories.
337    android_system_dirs.count = 4;
338
339    android_system_dirs.dirs = calloc(android_system_dirs.count, sizeof(dir_rec_t));
340    if (android_system_dirs.dirs == NULL) {
341        ALOGE("Couldn't allocate array for dirs; aborting\n");
342        return -1;
343    }
344
345    dir_rec_t android_root_dir;
346    if (get_path_from_env(&android_root_dir, "ANDROID_ROOT") < 0) {
347        ALOGE("Missing ANDROID_ROOT; aborting\n");
348        return -1;
349    }
350
351    android_system_dirs.dirs[0].path = build_string2(android_root_dir.path, APP_SUBDIR);
352    android_system_dirs.dirs[0].len = strlen(android_system_dirs.dirs[0].path);
353
354    android_system_dirs.dirs[1].path = build_string2(android_root_dir.path, PRIV_APP_SUBDIR);
355    android_system_dirs.dirs[1].len = strlen(android_system_dirs.dirs[1].path);
356
357    android_system_dirs.dirs[2].path = "/vendor/app/";
358    android_system_dirs.dirs[2].len = strlen(android_system_dirs.dirs[2].path);
359
360    android_system_dirs.dirs[3].path = "/oem/app/";
361    android_system_dirs.dirs[3].len = strlen(android_system_dirs.dirs[3].path);
362
363    return 0;
364}
365
366int initialize_directories() {
367    int res = -1;
368
369    // Read current filesystem layout version to handle upgrade paths
370    char version_path[PATH_MAX];
371    snprintf(version_path, PATH_MAX, "%s.layout_version", android_data_dir.path);
372
373    int oldVersion;
374    if (fs_read_atomic_int(version_path, &oldVersion) == -1) {
375        oldVersion = 0;
376    }
377    int version = oldVersion;
378
379    // /data/user
380    char *user_data_dir = build_string2(android_data_dir.path, SECONDARY_USER_PREFIX);
381    // /data/data
382    char *legacy_data_dir = build_string2(android_data_dir.path, PRIMARY_USER_PREFIX);
383    // /data/user/0
384    char *primary_data_dir = build_string3(android_data_dir.path, SECONDARY_USER_PREFIX, "0");
385    if (!user_data_dir || !legacy_data_dir || !primary_data_dir) {
386        goto fail;
387    }
388
389    // Make the /data/user directory if necessary
390    if (access(user_data_dir, R_OK) < 0) {
391        if (mkdir(user_data_dir, 0711) < 0) {
392            goto fail;
393        }
394        if (chown(user_data_dir, AID_SYSTEM, AID_SYSTEM) < 0) {
395            goto fail;
396        }
397        if (chmod(user_data_dir, 0711) < 0) {
398            goto fail;
399        }
400    }
401    // Make the /data/user/0 symlink to /data/data if necessary
402    if (access(primary_data_dir, R_OK) < 0) {
403        if (symlink(legacy_data_dir, primary_data_dir)) {
404            goto fail;
405        }
406    }
407
408    if (version == 0) {
409        // Introducing multi-user, so migrate /data/media contents into /data/media/0
410        ALOGD("Upgrading /data/media for multi-user");
411
412        // Ensure /data/media
413        if (fs_prepare_dir(android_media_dir.path, 0770, AID_MEDIA_RW, AID_MEDIA_RW) == -1) {
414            goto fail;
415        }
416
417        // /data/media.tmp
418        char media_tmp_dir[PATH_MAX];
419        snprintf(media_tmp_dir, PATH_MAX, "%smedia.tmp", android_data_dir.path);
420
421        // Only copy when upgrade not already in progress
422        if (access(media_tmp_dir, F_OK) == -1) {
423            if (rename(android_media_dir.path, media_tmp_dir) == -1) {
424                ALOGE("Failed to move legacy media path: %s", strerror(errno));
425                goto fail;
426            }
427        }
428
429        // Create /data/media again
430        if (fs_prepare_dir(android_media_dir.path, 0770, AID_MEDIA_RW, AID_MEDIA_RW) == -1) {
431            goto fail;
432        }
433
434        if (selinux_android_restorecon(android_media_dir.path, 0)) {
435            goto fail;
436        }
437
438        // /data/media/0
439        char owner_media_dir[PATH_MAX];
440        snprintf(owner_media_dir, PATH_MAX, "%s0", android_media_dir.path);
441
442        // Move any owner data into place
443        if (access(media_tmp_dir, F_OK) == 0) {
444            if (rename(media_tmp_dir, owner_media_dir) == -1) {
445                ALOGE("Failed to move owner media path: %s", strerror(errno));
446                goto fail;
447            }
448        }
449
450        // Ensure media directories for any existing users
451        DIR *dir;
452        struct dirent *dirent;
453        char user_media_dir[PATH_MAX];
454
455        dir = opendir(user_data_dir);
456        if (dir != NULL) {
457            while ((dirent = readdir(dir))) {
458                if (dirent->d_type == DT_DIR) {
459                    const char *name = dirent->d_name;
460
461                    // skip "." and ".."
462                    if (name[0] == '.') {
463                        if (name[1] == 0) continue;
464                        if ((name[1] == '.') && (name[2] == 0)) continue;
465                    }
466
467                    // /data/media/<user_id>
468                    snprintf(user_media_dir, PATH_MAX, "%s%s", android_media_dir.path, name);
469                    if (fs_prepare_dir(user_media_dir, 0770, AID_MEDIA_RW, AID_MEDIA_RW) == -1) {
470                        goto fail;
471                    }
472                }
473            }
474            closedir(dir);
475        }
476
477        version = 1;
478    }
479
480    // /data/media/obb
481    char media_obb_dir[PATH_MAX];
482    snprintf(media_obb_dir, PATH_MAX, "%sobb", android_media_dir.path);
483
484    if (version == 1) {
485        // Introducing /data/media/obb for sharing OBB across users; migrate
486        // any existing OBB files from owner.
487        ALOGD("Upgrading to shared /data/media/obb");
488
489        // /data/media/0/Android/obb
490        char owner_obb_path[PATH_MAX];
491        snprintf(owner_obb_path, PATH_MAX, "%s0/Android/obb", android_media_dir.path);
492
493        // Only move if target doesn't already exist
494        if (access(media_obb_dir, F_OK) != 0 && access(owner_obb_path, F_OK) == 0) {
495            if (rename(owner_obb_path, media_obb_dir) == -1) {
496                ALOGE("Failed to move OBB from owner: %s", strerror(errno));
497                goto fail;
498            }
499        }
500
501        version = 2;
502    }
503
504    if (ensure_media_user_dirs(0) == -1) {
505        ALOGE("Failed to setup media for user 0");
506        goto fail;
507    }
508    if (fs_prepare_dir(media_obb_dir, 0770, AID_MEDIA_RW, AID_MEDIA_RW) == -1) {
509        goto fail;
510    }
511
512    if (ensure_config_user_dirs(0) == -1) {
513        ALOGE("Failed to setup misc for user 0");
514        goto fail;
515    }
516
517    if (version == 2) {
518        ALOGD("Upgrading to /data/misc/user directories");
519
520        char misc_dir[PATH_MAX];
521        snprintf(misc_dir, PATH_MAX, "%smisc", android_data_dir.path);
522
523        char keychain_added_dir[PATH_MAX];
524        snprintf(keychain_added_dir, PATH_MAX, "%s/keychain/cacerts-added", misc_dir);
525
526        char keychain_removed_dir[PATH_MAX];
527        snprintf(keychain_removed_dir, PATH_MAX, "%s/keychain/cacerts-removed", misc_dir);
528
529        DIR *dir;
530        struct dirent *dirent;
531        dir = opendir(user_data_dir);
532        if (dir != NULL) {
533            while ((dirent = readdir(dir))) {
534                const char *name = dirent->d_name;
535
536                // skip "." and ".."
537                if (name[0] == '.') {
538                    if (name[1] == 0) continue;
539                    if ((name[1] == '.') && (name[2] == 0)) continue;
540                }
541
542                uint32_t user_id = atoi(name);
543
544                // /data/misc/user/<user_id>
545                if (ensure_config_user_dirs(user_id) == -1) {
546                    goto fail;
547                }
548
549                char misc_added_dir[PATH_MAX];
550                snprintf(misc_added_dir, PATH_MAX, "%s/user/%s/cacerts-added", misc_dir, name);
551
552                char misc_removed_dir[PATH_MAX];
553                snprintf(misc_removed_dir, PATH_MAX, "%s/user/%s/cacerts-removed", misc_dir, name);
554
555                uid_t uid = multiuser_get_uid(user_id, AID_SYSTEM);
556                gid_t gid = uid;
557                if (access(keychain_added_dir, F_OK) == 0) {
558                    if (copy_dir_files(keychain_added_dir, misc_added_dir, uid, gid) != 0) {
559                        ALOGE("Some files failed to copy");
560                    }
561                }
562                if (access(keychain_removed_dir, F_OK) == 0) {
563                    if (copy_dir_files(keychain_removed_dir, misc_removed_dir, uid, gid) != 0) {
564                        ALOGE("Some files failed to copy");
565                    }
566                }
567            }
568            closedir(dir);
569
570            if (access(keychain_added_dir, F_OK) == 0) {
571                delete_dir_contents(keychain_added_dir, 1, 0);
572            }
573            if (access(keychain_removed_dir, F_OK) == 0) {
574                delete_dir_contents(keychain_removed_dir, 1, 0);
575            }
576        }
577
578        version = 3;
579    }
580
581    // Persist layout version if changed
582    if (version != oldVersion) {
583        if (fs_write_atomic_int(version_path, version) == -1) {
584            ALOGE("Failed to save version to %s: %s", version_path, strerror(errno));
585            goto fail;
586        }
587    }
588
589    // Success!
590    res = 0;
591
592fail:
593    free(user_data_dir);
594    free(legacy_data_dir);
595    free(primary_data_dir);
596    return res;
597}
598
599static void drop_privileges() {
600    if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
601        ALOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
602        exit(1);
603    }
604
605    if (setgid(AID_INSTALL) < 0) {
606        ALOGE("setgid() can't drop privileges; exiting.\n");
607        exit(1);
608    }
609
610    if (setuid(AID_INSTALL) < 0) {
611        ALOGE("setuid() can't drop privileges; exiting.\n");
612        exit(1);
613    }
614
615    struct __user_cap_header_struct capheader;
616    struct __user_cap_data_struct capdata[2];
617    memset(&capheader, 0, sizeof(capheader));
618    memset(&capdata, 0, sizeof(capdata));
619    capheader.version = _LINUX_CAPABILITY_VERSION_3;
620    capheader.pid = 0;
621
622    capdata[CAP_TO_INDEX(CAP_DAC_OVERRIDE)].permitted |= CAP_TO_MASK(CAP_DAC_OVERRIDE);
623    capdata[CAP_TO_INDEX(CAP_CHOWN)].permitted        |= CAP_TO_MASK(CAP_CHOWN);
624    capdata[CAP_TO_INDEX(CAP_SETUID)].permitted       |= CAP_TO_MASK(CAP_SETUID);
625    capdata[CAP_TO_INDEX(CAP_SETGID)].permitted       |= CAP_TO_MASK(CAP_SETGID);
626    capdata[CAP_TO_INDEX(CAP_FOWNER)].permitted       |= CAP_TO_MASK(CAP_FOWNER);
627
628    capdata[0].effective = capdata[0].permitted;
629    capdata[1].effective = capdata[1].permitted;
630    capdata[0].inheritable = 0;
631    capdata[1].inheritable = 0;
632
633    if (capset(&capheader, &capdata[0]) < 0) {
634        ALOGE("capset failed: %s\n", strerror(errno));
635        exit(1);
636    }
637}
638
639static int log_callback(int type, const char *fmt, ...) {
640    va_list ap;
641    int priority;
642
643    switch (type) {
644    case SELINUX_WARNING:
645        priority = ANDROID_LOG_WARN;
646        break;
647    case SELINUX_INFO:
648        priority = ANDROID_LOG_INFO;
649        break;
650    default:
651        priority = ANDROID_LOG_ERROR;
652        break;
653    }
654    va_start(ap, fmt);
655    LOG_PRI_VA(priority, "SELinux", fmt, ap);
656    va_end(ap);
657    return 0;
658}
659
660int main(const int argc, const char *argv[]) {
661    char buf[BUFFER_MAX];
662    struct sockaddr addr;
663    socklen_t alen;
664    int lsocket, s, count;
665    int selinux_enabled = (is_selinux_enabled() > 0);
666
667    ALOGI("installd firing up\n");
668
669    union selinux_callback cb;
670    cb.func_log = log_callback;
671    selinux_set_callback(SELINUX_CB_LOG, cb);
672
673    if (initialize_globals() < 0) {
674        ALOGE("Could not initialize globals; exiting.\n");
675        exit(1);
676    }
677
678    if (initialize_directories() < 0) {
679        ALOGE("Could not create directories; exiting.\n");
680        exit(1);
681    }
682
683    if (selinux_enabled && selinux_status_open(true) < 0) {
684        ALOGE("Could not open selinux status; exiting.\n");
685        exit(1);
686    }
687
688    drop_privileges();
689
690    lsocket = android_get_control_socket(SOCKET_PATH);
691    if (lsocket < 0) {
692        ALOGE("Failed to get socket from environment: %s\n", strerror(errno));
693        exit(1);
694    }
695    if (listen(lsocket, 5)) {
696        ALOGE("Listen on socket failed: %s\n", strerror(errno));
697        exit(1);
698    }
699    fcntl(lsocket, F_SETFD, FD_CLOEXEC);
700
701    for (;;) {
702        alen = sizeof(addr);
703        s = accept(lsocket, &addr, &alen);
704        if (s < 0) {
705            ALOGE("Accept failed: %s\n", strerror(errno));
706            continue;
707        }
708        fcntl(s, F_SETFD, FD_CLOEXEC);
709
710        ALOGI("new connection\n");
711        for (;;) {
712            unsigned short count;
713            if (readx(s, &count, sizeof(count))) {
714                ALOGE("failed to read size\n");
715                break;
716            }
717            if ((count < 1) || (count >= BUFFER_MAX)) {
718                ALOGE("invalid size %d\n", count);
719                break;
720            }
721            if (readx(s, buf, count)) {
722                ALOGE("failed to read command\n");
723                break;
724            }
725            buf[count] = 0;
726            if (selinux_enabled && selinux_status_updated() > 0) {
727                selinux_android_seapp_context_reload();
728            }
729            if (execute(s, buf)) break;
730        }
731        ALOGI("closing connection\n");
732        close(s);
733    }
734
735    return 0;
736}
737