installd.cpp revision c1e93e7d746e07791b0667c80ad43a407c515fa8
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 <fcntl.h>
18#include <selinux/android.h>
19#include <selinux/avc.h>
20#include <sys/capability.h>
21#include <sys/fsuid.h>
22#include <sys/prctl.h>
23#include <sys/socket.h>
24#include <sys/stat.h>
25
26#include <android-base/logging.h>
27#include <cutils/fs.h>
28#include <cutils/log.h>               // TODO: Move everything to base::logging.
29#include <cutils/properties.h>
30#include <cutils/sockets.h>
31#include <private/android_filesystem_config.h>
32
33#include <commands.h>
34#include <globals.h>
35#include <installd_constants.h>
36#include <installd_deps.h>  // Need to fill in requirements of commands.
37#include <utils.h>
38
39#ifndef LOG_TAG
40#define LOG_TAG "installd"
41#endif
42#define SOCKET_PATH "installd"
43
44#define BUFFER_MAX    1024  /* input buffer for commands */
45#define TOKEN_MAX     16    /* max number of arguments in buffer */
46#define REPLY_MAX     256   /* largest reply allowed */
47
48namespace android {
49namespace installd {
50
51// Check that installd-deps sizes match cutils sizes.
52static_assert(kPropertyKeyMax == PROPERTY_KEY_MAX, "Size mismatch.");
53static_assert(kPropertyValueMax == PROPERTY_VALUE_MAX, "Size mismatch.");
54
55////////////////////////
56// Plug-in functions. //
57////////////////////////
58
59int get_property(const char *key, char *value, const char *default_value) {
60    return property_get(key, value, default_value);
61}
62
63// Compute the output path of
64bool calculate_oat_file_path(char path[PKG_PATH_MAX],
65                             const char *oat_dir,
66                             const char *apk_path,
67                             const char *instruction_set) {
68    const char *file_name_start;
69    const char *file_name_end;
70
71    file_name_start = strrchr(apk_path, '/');
72    if (file_name_start == NULL) {
73        ALOGE("apk_path '%s' has no '/'s in it\n", apk_path);
74        return false;
75    }
76    file_name_end = strrchr(apk_path, '.');
77    if (file_name_end < file_name_start) {
78        ALOGE("apk_path '%s' has no extension\n", apk_path);
79        return false;
80    }
81
82    // Calculate file_name
83    int file_name_len = file_name_end - file_name_start - 1;
84    char file_name[file_name_len + 1];
85    memcpy(file_name, file_name_start + 1, file_name_len);
86    file_name[file_name_len] = '\0';
87
88    // <apk_parent_dir>/oat/<isa>/<file_name>.odex
89    snprintf(path, PKG_PATH_MAX, "%s/%s/%s.odex", oat_dir, instruction_set, file_name);
90    return true;
91}
92
93/*
94 * Computes the odex file for the given apk_path and instruction_set.
95 * /system/framework/whatever.jar -> /system/framework/oat/<isa>/whatever.odex
96 *
97 * Returns false if it failed to determine the odex file path.
98 */
99bool calculate_odex_file_path(char path[PKG_PATH_MAX],
100                              const char *apk_path,
101                              const char *instruction_set) {
102    if (strlen(apk_path) + strlen("oat/") + strlen(instruction_set)
103            + strlen("/") + strlen("odex") + 1 > PKG_PATH_MAX) {
104        ALOGE("apk_path '%s' may be too long to form odex file path.\n", apk_path);
105        return false;
106    }
107
108    strcpy(path, apk_path);
109    char *end = strrchr(path, '/');
110    if (end == NULL) {
111        ALOGE("apk_path '%s' has no '/'s in it?!\n", apk_path);
112        return false;
113    }
114    const char *apk_end = apk_path + (end - path); // strrchr(apk_path, '/');
115
116    strcpy(end + 1, "oat/");       // path = /system/framework/oat/\0
117    strcat(path, instruction_set); // path = /system/framework/oat/<isa>\0
118    strcat(path, apk_end);         // path = /system/framework/oat/<isa>/whatever.jar\0
119    end = strrchr(path, '.');
120    if (end == NULL) {
121        ALOGE("apk_path '%s' has no extension.\n", apk_path);
122        return false;
123    }
124    strcpy(end + 1, "odex");
125    return true;
126}
127
128bool create_cache_path(char path[PKG_PATH_MAX],
129                       const char *src,
130                       const char *instruction_set) {
131    /* demand that we are an absolute path */
132    if ((src == nullptr) || (src[0] != '/') || strstr(src,"..")) {
133        return false;
134    }
135
136    size_t srclen = strlen(src);
137
138    if (srclen > PKG_PATH_MAX) {        // XXX: PKG_NAME_MAX?
139        return false;
140    }
141
142    size_t dstlen =
143        android_data_dir.len +
144        strlen(DALVIK_CACHE) +
145        1 +
146        strlen(instruction_set) +
147        srclen +
148        strlen(DALVIK_CACHE_POSTFIX) + 2;
149
150    if (dstlen > PKG_PATH_MAX) {
151        return false;
152    }
153
154    sprintf(path,"%s%s/%s/%s",
155            android_data_dir.path,
156            DALVIK_CACHE,
157            instruction_set,
158            src + 1 /* skip the leading / */);
159
160    char* tmp =
161            path +
162            android_data_dir.len +
163            strlen(DALVIK_CACHE) +
164            1 +
165            strlen(instruction_set) + 1;
166
167    for(; *tmp; tmp++) {
168        if (*tmp == '/') {
169            *tmp = '@';
170        }
171    }
172
173    strcat(path, DALVIK_CACHE_POSTFIX);
174    return true;
175}
176
177
178static char* parse_null(char* arg) {
179    if (strcmp(arg, "!") == 0) {
180        return nullptr;
181    } else {
182        return arg;
183    }
184}
185
186static int do_ping(char **arg ATTRIBUTE_UNUSED, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
187{
188    return 0;
189}
190
191// We use otapreopt_chroot to get into the chroot.
192static constexpr const char* kOtaPreopt = "/system/bin/otapreopt_chroot";
193
194static int do_ota_dexopt(const char* args[DEXOPT_PARAM_COUNT],
195                         char reply[REPLY_MAX] ATTRIBUTE_UNUSED) {
196    // Time to fork and run otapreopt.
197
198    // Check that the tool exists.
199    struct stat s;
200    if (stat(kOtaPreopt, &s) != 0) {
201        LOG(ERROR) << "Otapreopt chroot tool not found.";
202        return -1;
203    }
204
205    pid_t pid = fork();
206    if (pid == 0) {
207        const char* argv[1 + DEXOPT_PARAM_COUNT + 1];
208        argv[0] = kOtaPreopt;
209
210        for (size_t i = 0; i < DEXOPT_PARAM_COUNT; ++i) {
211            argv[i + 1] = args[i];
212        }
213
214        argv[DEXOPT_PARAM_COUNT + 1] = nullptr;
215
216        execv(argv[0], (char * const *)argv);
217        PLOG(ERROR) << "execv(OTAPREOPT_CHROOT) failed";
218        exit(99);
219    } else {
220        int res = wait_child(pid);
221        if (res == 0) {
222            ALOGV("DexInv: --- END OTAPREOPT (success) ---\n");
223        } else {
224            ALOGE("DexInv: --- END OTAPREOPT --- status=0x%04x, process failed\n", res);
225        }
226        return res;
227    }
228}
229
230static int do_regular_dexopt(const char* args[DEXOPT_PARAM_COUNT],
231                             char reply[REPLY_MAX] ATTRIBUTE_UNUSED) {
232    return dexopt(args);
233}
234
235using DexoptFn = int (*)(const char* args[DEXOPT_PARAM_COUNT],
236                         char reply[REPLY_MAX]);
237
238static int do_dexopt(char **arg, char reply[REPLY_MAX])
239{
240    const char* args[DEXOPT_PARAM_COUNT];
241    for (size_t i = 0; i < DEXOPT_PARAM_COUNT; ++i) {
242        CHECK(arg[i] != nullptr);
243        args[i] = arg[i];
244    }
245
246    int dexopt_flags = atoi(arg[6]);
247    DexoptFn dexopt_fn;
248    if ((dexopt_flags & DEXOPT_OTA) != 0) {
249        dexopt_fn = do_ota_dexopt;
250    } else {
251        dexopt_fn = do_regular_dexopt;
252    }
253    return dexopt_fn(args, reply);
254}
255
256static int do_merge_profiles(char **arg, char reply[REPLY_MAX])
257{
258    uid_t uid = static_cast<uid_t>(atoi(arg[0]));
259    const char* pkgname = arg[1];
260    if (merge_profiles(uid, pkgname)) {
261        strncpy(reply, "true", REPLY_MAX);
262    } else {
263        strncpy(reply, "false", REPLY_MAX);
264    }
265    return 0;
266}
267
268static int do_dump_profiles(char **arg, char reply[REPLY_MAX])
269{
270    uid_t uid = static_cast<uid_t>(atoi(arg[0]));
271    const char* pkgname = arg[1];
272    const char* dex_files = arg[2];
273    if (dump_profile(uid, pkgname, dex_files)) {
274        strncpy(reply, "true", REPLY_MAX);
275    } else {
276        strncpy(reply, "false", REPLY_MAX);
277    }
278    return 0;
279}
280
281static int do_mark_boot_complete(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
282{
283    return mark_boot_complete(arg[0] /* instruction set */);
284}
285
286static int do_rm_dex(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
287{
288    return rm_dex(arg[0], arg[1]); /* pkgname, instruction_set */
289}
290
291static int do_free_cache(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED) /* TODO int:free_size */
292{
293    return free_cache(parse_null(arg[0]), (int64_t)atoll(arg[1])); /* uuid, free_size */
294}
295
296static int do_get_app_size(char **arg, char reply[REPLY_MAX]) {
297    int64_t codesize = 0;
298    int64_t datasize = 0;
299    int64_t cachesize = 0;
300    int64_t asecsize = 0;
301    int res = 0;
302
303    /* const char *uuid, const char *pkgname, int userid, int flags, ino_t ce_data_inode,
304            const char* code_path */
305    res = get_app_size(parse_null(arg[0]), arg[1], atoi(arg[2]), atoi(arg[3]), atol(arg[4]),
306            arg[5], &codesize, &datasize, &cachesize, &asecsize);
307
308    /*
309     * Each int64_t can take up 22 characters printed out. Make sure it
310     * doesn't go over REPLY_MAX in the future.
311     */
312    snprintf(reply, REPLY_MAX, "%" PRId64 " %" PRId64 " %" PRId64 " %" PRId64,
313            codesize, datasize, cachesize, asecsize);
314    return res;
315}
316
317static int do_linklib(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
318{
319    return linklib(parse_null(arg[0]), arg[1], arg[2], atoi(arg[3]));
320}
321
322static int do_idmap(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
323{
324    return idmap(arg[0], arg[1], atoi(arg[2]));
325}
326
327static int do_create_oat_dir(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
328{
329    /* oat_dir, instruction_set */
330    return create_oat_dir(arg[0], arg[1]);
331}
332
333static int do_rm_package_dir(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
334{
335    /* oat_dir */
336    return rm_package_dir(arg[0]);
337}
338
339static int do_clear_app_profiles(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
340{
341    /* package_name */
342    return clear_app_profiles(arg[0]);
343}
344
345static int do_destroy_app_profiles(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
346{
347    /* package_name */
348    return destroy_app_profiles(arg[0]);
349}
350
351static int do_link_file(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED)
352{
353    /* relative_path, from_base, to_base */
354    return link_file(arg[0], arg[1], arg[2]);
355}
356
357static int do_move_ab(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED) {
358    // apk_path, instruction_set, oat_dir
359    return move_ab(arg[0], arg[1], arg[2]);
360}
361
362static int do_delete_odex(char **arg, char reply[REPLY_MAX] ATTRIBUTE_UNUSED) {
363    // apk_path, instruction_set, oat_dir
364    return delete_odex(arg[0], arg[1], arg[2]) ? 0 : -1;
365}
366
367struct cmdinfo {
368    const char *name;
369    unsigned numargs;
370    int (*func)(char **arg, char reply[REPLY_MAX]);
371};
372
373struct cmdinfo cmds[] = {
374    { "ping",                 0, do_ping },
375    { "get_app_size",         6, do_get_app_size },
376    { "dexopt",              10, do_dexopt },
377    { "markbootcomplete",     1, do_mark_boot_complete },
378    { "rmdex",                2, do_rm_dex },
379    { "freecache",            2, do_free_cache },
380    { "linklib",              4, do_linklib },
381    { "idmap",                3, do_idmap },
382    { "createoatdir",         2, do_create_oat_dir },
383    { "rmpackagedir",         1, do_rm_package_dir },
384    { "clear_app_profiles",   1, do_clear_app_profiles },
385    { "destroy_app_profiles", 1, do_destroy_app_profiles },
386    { "linkfile",             3, do_link_file },
387    { "move_ab",              3, do_move_ab },
388    { "merge_profiles",       2, do_merge_profiles },
389    { "dump_profiles",        3, do_dump_profiles },
390    { "delete_odex",          3, do_delete_odex },
391};
392
393static int readx(int s, void *_buf, int count)
394{
395    char *buf = (char *) _buf;
396    int n = 0, r;
397    if (count < 0) return -1;
398    while (n < count) {
399        r = read(s, buf + n, count - n);
400        if (r < 0) {
401            if (errno == EINTR) continue;
402            ALOGE("read error: %s\n", strerror(errno));
403            return -1;
404        }
405        if (r == 0) {
406            ALOGE("eof\n");
407            return -1; /* EOF */
408        }
409        n += r;
410    }
411    return 0;
412}
413
414static int writex(int s, const void *_buf, int count)
415{
416    const char *buf = (const char *) _buf;
417    int n = 0, r;
418    if (count < 0) return -1;
419    while (n < count) {
420        r = write(s, buf + n, count - n);
421        if (r < 0) {
422            if (errno == EINTR) continue;
423            ALOGE("write error: %s\n", strerror(errno));
424            return -1;
425        }
426        n += r;
427    }
428    return 0;
429}
430
431
432/* Tokenize the command buffer, locate a matching command,
433 * ensure that the required number of arguments are provided,
434 * call the function(), return the result.
435 */
436static int execute(int s, char cmd[BUFFER_MAX])
437{
438    char reply[REPLY_MAX];
439    char *arg[TOKEN_MAX+1];
440    unsigned i;
441    unsigned n = 0;
442    unsigned short count;
443    int ret = -1;
444
445    // ALOGI("execute('%s')\n", cmd);
446
447        /* default reply is "" */
448    reply[0] = 0;
449
450        /* n is number of args (not counting arg[0]) */
451    arg[0] = cmd;
452    while (*cmd) {
453        if (isspace(*cmd)) {
454            *cmd++ = 0;
455            n++;
456            arg[n] = cmd;
457            if (n == TOKEN_MAX) {
458                ALOGE("too many arguments\n");
459                goto done;
460            }
461        }
462        if (*cmd) {
463          cmd++;
464        }
465    }
466
467    for (i = 0; i < sizeof(cmds) / sizeof(cmds[0]); i++) {
468        if (!strcmp(cmds[i].name,arg[0])) {
469            if (n != cmds[i].numargs) {
470                ALOGE("%s requires %d arguments (%d given)\n",
471                     cmds[i].name, cmds[i].numargs, n);
472            } else {
473                ret = cmds[i].func(arg + 1, reply);
474            }
475            goto done;
476        }
477    }
478    ALOGE("unsupported command '%s'\n", arg[0]);
479
480done:
481    if (reply[0]) {
482        n = snprintf(cmd, BUFFER_MAX, "%d %s", ret, reply);
483    } else {
484        n = snprintf(cmd, BUFFER_MAX, "%d", ret);
485    }
486    if (n > BUFFER_MAX) n = BUFFER_MAX;
487    count = n;
488
489    // ALOGI("reply: '%s'\n", cmd);
490    if (writex(s, &count, sizeof(count))) return -1;
491    if (writex(s, cmd, count)) return -1;
492    return 0;
493}
494
495static bool initialize_globals() {
496    const char* data_path = getenv("ANDROID_DATA");
497    if (data_path == nullptr) {
498        ALOGE("Could not find ANDROID_DATA");
499        return false;
500    }
501    const char* root_path = getenv("ANDROID_ROOT");
502    if (root_path == nullptr) {
503        ALOGE("Could not find ANDROID_ROOT");
504        return false;
505    }
506
507    return init_globals_from_data_and_root(data_path, root_path);
508}
509
510static int initialize_directories() {
511    int res = -1;
512
513    // Read current filesystem layout version to handle upgrade paths
514    char version_path[PATH_MAX];
515    snprintf(version_path, PATH_MAX, "%s.layout_version", android_data_dir.path);
516
517    int oldVersion;
518    if (fs_read_atomic_int(version_path, &oldVersion) == -1) {
519        oldVersion = 0;
520    }
521    int version = oldVersion;
522
523    if (version < 2) {
524        SLOGD("Assuming that device has multi-user storage layout; upgrade no longer supported");
525        version = 2;
526    }
527
528    if (ensure_config_user_dirs(0) == -1) {
529        ALOGE("Failed to setup misc for user 0");
530        goto fail;
531    }
532
533    if (version == 2) {
534        ALOGD("Upgrading to /data/misc/user directories");
535
536        char misc_dir[PATH_MAX];
537        snprintf(misc_dir, PATH_MAX, "%smisc", android_data_dir.path);
538
539        char keychain_added_dir[PATH_MAX];
540        snprintf(keychain_added_dir, PATH_MAX, "%s/keychain/cacerts-added", misc_dir);
541
542        char keychain_removed_dir[PATH_MAX];
543        snprintf(keychain_removed_dir, PATH_MAX, "%s/keychain/cacerts-removed", misc_dir);
544
545        DIR *dir;
546        struct dirent *dirent;
547        dir = opendir("/data/user");
548        if (dir != NULL) {
549            while ((dirent = readdir(dir))) {
550                const char *name = dirent->d_name;
551
552                // skip "." and ".."
553                if (name[0] == '.') {
554                    if (name[1] == 0) continue;
555                    if ((name[1] == '.') && (name[2] == 0)) continue;
556                }
557
558                uint32_t user_id = atoi(name);
559
560                // /data/misc/user/<user_id>
561                if (ensure_config_user_dirs(user_id) == -1) {
562                    goto fail;
563                }
564
565                char misc_added_dir[PATH_MAX];
566                snprintf(misc_added_dir, PATH_MAX, "%s/user/%s/cacerts-added", misc_dir, name);
567
568                char misc_removed_dir[PATH_MAX];
569                snprintf(misc_removed_dir, PATH_MAX, "%s/user/%s/cacerts-removed", misc_dir, name);
570
571                uid_t uid = multiuser_get_uid(user_id, AID_SYSTEM);
572                gid_t gid = uid;
573                if (access(keychain_added_dir, F_OK) == 0) {
574                    if (copy_dir_files(keychain_added_dir, misc_added_dir, uid, gid) != 0) {
575                        ALOGE("Some files failed to copy");
576                    }
577                }
578                if (access(keychain_removed_dir, F_OK) == 0) {
579                    if (copy_dir_files(keychain_removed_dir, misc_removed_dir, uid, gid) != 0) {
580                        ALOGE("Some files failed to copy");
581                    }
582                }
583            }
584            closedir(dir);
585
586            if (access(keychain_added_dir, F_OK) == 0) {
587                delete_dir_contents(keychain_added_dir, 1, 0);
588            }
589            if (access(keychain_removed_dir, F_OK) == 0) {
590                delete_dir_contents(keychain_removed_dir, 1, 0);
591            }
592        }
593
594        version = 3;
595    }
596
597    // Persist layout version if changed
598    if (version != oldVersion) {
599        if (fs_write_atomic_int(version_path, version) == -1) {
600            ALOGE("Failed to save version to %s: %s", version_path, strerror(errno));
601            goto fail;
602        }
603    }
604
605    // Success!
606    res = 0;
607
608fail:
609    return res;
610}
611
612static int log_callback(int type, const char *fmt, ...) {
613    va_list ap;
614    int priority;
615
616    switch (type) {
617    case SELINUX_WARNING:
618        priority = ANDROID_LOG_WARN;
619        break;
620    case SELINUX_INFO:
621        priority = ANDROID_LOG_INFO;
622        break;
623    default:
624        priority = ANDROID_LOG_ERROR;
625        break;
626    }
627    va_start(ap, fmt);
628    LOG_PRI_VA(priority, "SELinux", fmt, ap);
629    va_end(ap);
630    return 0;
631}
632
633static int installd_main(const int argc ATTRIBUTE_UNUSED, char *argv[]) {
634    char buf[BUFFER_MAX];
635    struct sockaddr addr;
636    socklen_t alen;
637    int lsocket, s, ret;
638    int selinux_enabled = (is_selinux_enabled() > 0);
639
640    setenv("ANDROID_LOG_TAGS", "*:v", 1);
641    android::base::InitLogging(argv);
642
643    ALOGI("installd firing up\n");
644
645    union selinux_callback cb;
646    cb.func_log = log_callback;
647    selinux_set_callback(SELINUX_CB_LOG, cb);
648
649    if (!initialize_globals()) {
650        ALOGE("Could not initialize globals; exiting.\n");
651        exit(1);
652    }
653
654    if (initialize_directories() < 0) {
655        ALOGE("Could not create directories; exiting.\n");
656        exit(1);
657    }
658
659    if (selinux_enabled && selinux_status_open(true) < 0) {
660        ALOGE("Could not open selinux status; exiting.\n");
661        exit(1);
662    }
663
664    if ((ret = InstalldNativeService::start()) != android::OK) {
665        ALOGE("Unable to start InstalldNativeService: %d", ret);
666        exit(1);
667    }
668
669    lsocket = android_get_control_socket(SOCKET_PATH);
670    if (lsocket < 0) {
671        ALOGE("Failed to get socket from environment: %s\n", strerror(errno));
672        exit(1);
673    }
674    if (listen(lsocket, 5)) {
675        ALOGE("Listen on socket failed: %s\n", strerror(errno));
676        exit(1);
677    }
678    fcntl(lsocket, F_SETFD, FD_CLOEXEC);
679
680    for (;;) {
681        alen = sizeof(addr);
682        s = accept(lsocket, &addr, &alen);
683        if (s < 0) {
684            ALOGE("Accept failed: %s\n", strerror(errno));
685            continue;
686        }
687        fcntl(s, F_SETFD, FD_CLOEXEC);
688
689        ALOGI("new connection\n");
690        for (;;) {
691            unsigned short count;
692            if (readx(s, &count, sizeof(count))) {
693                ALOGE("failed to read size\n");
694                break;
695            }
696            if ((count < 1) || (count >= BUFFER_MAX)) {
697                ALOGE("invalid size %d\n", count);
698                break;
699            }
700            if (readx(s, buf, count)) {
701                ALOGE("failed to read command\n");
702                break;
703            }
704            buf[count] = 0;
705            if (selinux_enabled && selinux_status_updated() > 0) {
706                selinux_android_seapp_context_reload();
707            }
708            if (execute(s, buf)) break;
709        }
710        ALOGI("closing connection\n");
711        close(s);
712    }
713
714    return 0;
715}
716
717}  // namespace installd
718}  // namespace android
719
720int main(const int argc, char *argv[]) {
721    return android::installd::installd_main(argc, argv);
722}
723