commands.c revision d705fd2b0aca3f57168934f2ea8c351ef249f829
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 "installd.h"
18
19int install(const char *pkgname, int encrypted_fs_flag, uid_t uid, gid_t gid)
20{
21    char pkgdir[PKG_PATH_MAX];
22    char libdir[PKG_PATH_MAX];
23
24    if ((uid < AID_SYSTEM) || (gid < AID_SYSTEM)) {
25        LOGE("invalid uid/gid: %d %d\n", uid, gid);
26        return -1;
27
28    }
29
30    if (encrypted_fs_flag == USE_UNENCRYPTED_FS) {
31        if (create_pkg_path(pkgdir, PKG_DIR_PREFIX, pkgname, PKG_DIR_POSTFIX))
32            return -1;
33        if (create_pkg_path(libdir, PKG_LIB_PREFIX, pkgname, PKG_LIB_POSTFIX))
34            return -1;
35    } else {
36        if (create_pkg_path(pkgdir, PKG_SEC_DIR_PREFIX, pkgname, PKG_DIR_POSTFIX))
37            return -1;
38        if (create_pkg_path(libdir, PKG_SEC_LIB_PREFIX, pkgname, PKG_LIB_POSTFIX))
39            return -1;
40    }
41
42    if (mkdir(pkgdir, 0751) < 0) {
43        LOGE("cannot create dir '%s': %s\n", pkgdir, strerror(errno));
44        return -errno;
45    }
46    if (chown(pkgdir, uid, gid) < 0) {
47        LOGE("cannot chown dir '%s': %s\n", pkgdir, strerror(errno));
48        unlink(pkgdir);
49        return -errno;
50    }
51    if (mkdir(libdir, 0755) < 0) {
52        LOGE("cannot create dir '%s': %s\n", libdir, strerror(errno));
53        unlink(pkgdir);
54        return -errno;
55    }
56    if (chown(libdir, AID_SYSTEM, AID_SYSTEM) < 0) {
57        LOGE("cannot chown dir '%s': %s\n", libdir, strerror(errno));
58        unlink(libdir);
59        unlink(pkgdir);
60        return -errno;
61    }
62    return 0;
63}
64
65int uninstall(const char *pkgname, int encrypted_fs_flag)
66{
67    char pkgdir[PKG_PATH_MAX];
68
69    if (encrypted_fs_flag == USE_UNENCRYPTED_FS) {
70        if (create_pkg_path(pkgdir, PKG_DIR_PREFIX, pkgname, PKG_DIR_POSTFIX))
71            return -1;
72    } else {
73        if (create_pkg_path(pkgdir, PKG_SEC_DIR_PREFIX, pkgname, PKG_DIR_POSTFIX))
74            return -1;
75    }
76
77        /* delete contents AND directory, no exceptions */
78    return delete_dir_contents(pkgdir, 1, 0);
79}
80
81int renamepkg(const char *oldpkgname, const char *newpkgname, int encrypted_fs_flag)
82{
83    char oldpkgdir[PKG_PATH_MAX];
84    char newpkgdir[PKG_PATH_MAX];
85
86    if (encrypted_fs_flag == USE_UNENCRYPTED_FS) {
87        if (create_pkg_path(oldpkgdir, PKG_DIR_PREFIX, oldpkgname, PKG_DIR_POSTFIX))
88            return -1;
89        if (create_pkg_path(newpkgdir, PKG_DIR_PREFIX, newpkgname, PKG_DIR_POSTFIX))
90            return -1;
91    } else {
92        if (create_pkg_path(oldpkgdir, PKG_SEC_DIR_PREFIX, oldpkgname, PKG_DIR_POSTFIX))
93            return -1;
94        if (create_pkg_path(newpkgdir, PKG_SEC_DIR_PREFIX, newpkgname, PKG_DIR_POSTFIX))
95            return -1;
96    }
97
98    if (rename(oldpkgdir, newpkgdir) < 0) {
99        LOGE("cannot rename dir '%s' to '%s': %s\n", oldpkgdir, newpkgdir, strerror(errno));
100        return -errno;
101    }
102    return 0;
103}
104
105int delete_user_data(const char *pkgname, int encrypted_fs_flag)
106{
107    char pkgdir[PKG_PATH_MAX];
108
109    if (encrypted_fs_flag == USE_UNENCRYPTED_FS) {
110        if (create_pkg_path(pkgdir, PKG_DIR_PREFIX, pkgname, PKG_DIR_POSTFIX))
111            return -1;
112    } else {
113        if (create_pkg_path(pkgdir, PKG_SEC_DIR_PREFIX, pkgname, PKG_DIR_POSTFIX))
114            return -1;
115    }
116
117        /* delete contents, excluding "lib", but not the directory itself */
118    return delete_dir_contents(pkgdir, 0, "lib");
119}
120
121int delete_cache(const char *pkgname, int encrypted_fs_flag)
122{
123    char cachedir[PKG_PATH_MAX];
124
125    if (encrypted_fs_flag == USE_UNENCRYPTED_FS) {
126        if (create_pkg_path(cachedir, CACHE_DIR_PREFIX, pkgname, CACHE_DIR_POSTFIX))
127            return -1;
128    } else {
129        if (create_pkg_path(cachedir, CACHE_SEC_DIR_PREFIX, pkgname, CACHE_DIR_POSTFIX))
130            return -1;
131    }
132
133        /* delete contents, not the directory, no exceptions */
134    return delete_dir_contents(cachedir, 0, 0);
135}
136
137/* TODO(oam): depending on use case (ecryptfs or dmcrypt)
138 * change implementation
139 */
140static int disk_free()
141{
142    struct statfs sfs;
143    if (statfs(PKG_DIR_PREFIX, &sfs) == 0) {
144        return sfs.f_bavail * sfs.f_bsize;
145    } else {
146        return -1;
147    }
148}
149
150/* Try to ensure free_size bytes of storage are available.
151 * Returns 0 on success.
152 * This is rather simple-minded because doing a full LRU would
153 * be potentially memory-intensive, and without atime it would
154 * also require that apps constantly modify file metadata even
155 * when just reading from the cache, which is pretty awful.
156 */
157int free_cache(int free_size)
158{
159    const char *name;
160    int dfd, subfd;
161    DIR *d;
162    struct dirent *de;
163    int avail;
164
165    avail = disk_free();
166    if (avail < 0) return -1;
167
168    LOGI("free_cache(%d) avail %d\n", free_size, avail);
169    if (avail >= free_size) return 0;
170
171    /* First try encrypted dir */
172    d = opendir(PKG_SEC_DIR_PREFIX);
173    if (d == NULL) {
174        LOGE("cannot open %s\n", PKG_SEC_DIR_PREFIX);
175    } else {
176        dfd = dirfd(d);
177
178        while ((de = readdir(d))) {
179           if (de->d_type != DT_DIR) continue;
180           name = de->d_name;
181
182            /* always skip "." and ".." */
183            if (name[0] == '.') {
184                if (name[1] == 0) continue;
185                if ((name[1] == '.') && (name[2] == 0)) continue;
186            }
187
188            subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
189            if (subfd < 0) continue;
190
191            delete_dir_contents_fd(subfd, "cache");
192            close(subfd);
193
194            avail = disk_free();
195            if (avail >= free_size) {
196                closedir(d);
197                return 0;
198            }
199        }
200        closedir(d);
201    }
202
203    /* Next try unencrypted dir... */
204    d = opendir(PKG_DIR_PREFIX);
205    if (d == NULL) {
206        LOGE("cannot open %s\n", PKG_DIR_PREFIX);
207        return -1;
208    }
209    dfd = dirfd(d);
210
211    while ((de = readdir(d))) {
212        if (de->d_type != DT_DIR) continue;
213        name = de->d_name;
214
215        /* always skip "." and ".." */
216        if (name[0] == '.') {
217            if (name[1] == 0) continue;
218            if ((name[1] == '.') && (name[2] == 0)) continue;
219        }
220
221        subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
222        if (subfd < 0) continue;
223
224        delete_dir_contents_fd(subfd, "cache");
225        close(subfd);
226
227        avail = disk_free();
228        if (avail >= free_size) {
229            closedir(d);
230            return 0;
231        }
232    }
233    closedir(d);
234
235    /* Fail case - not possible to free space */
236    return -1;
237}
238
239/* used by move_dex, rm_dex, etc to ensure that the provided paths
240 * don't point anywhere other than at the APK_DIR_PREFIX
241 */
242static int is_valid_apk_path(const char *path)
243{
244    int len = strlen(APK_DIR_PREFIX);
245int nosubdircheck = 0;
246    if (strncmp(path, APK_DIR_PREFIX, len)) {
247        len = strlen(PROTECTED_DIR_PREFIX);
248        if (strncmp(path, PROTECTED_DIR_PREFIX, len)) {
249            len = strlen(SDCARD_DIR_PREFIX);
250            if (strncmp(path, SDCARD_DIR_PREFIX, len)) {
251                LOGE("invalid apk path '%s' (bad prefix)\n", path);
252                return 0;
253            } else {
254                nosubdircheck = 1;
255            }
256        }
257    }
258    if ((nosubdircheck != 1) && strchr(path + len, '/')) {
259        LOGE("invalid apk path '%s' (subdir?)\n", path);
260        return 0;
261    }
262    if (path[len] == '.') {
263        LOGE("invalid apk path '%s' (trickery)\n", path);
264        return 0;
265    }
266    return 1;
267}
268
269int move_dex(const char *src, const char *dst)
270{
271    char src_dex[PKG_PATH_MAX];
272    char dst_dex[PKG_PATH_MAX];
273
274    if (!is_valid_apk_path(src)) return -1;
275    if (!is_valid_apk_path(dst)) return -1;
276
277    if (create_cache_path(src_dex, src)) return -1;
278    if (create_cache_path(dst_dex, dst)) return -1;
279
280    LOGI("move %s -> %s\n", src_dex, dst_dex);
281    if (rename(src_dex, dst_dex) < 0) {
282        return -1;
283    } else {
284        return 0;
285    }
286}
287
288int rm_dex(const char *path)
289{
290    char dex_path[PKG_PATH_MAX];
291
292    if (!is_valid_apk_path(path)) return -1;
293    if (create_cache_path(dex_path, path)) return -1;
294
295    LOGI("unlink %s\n", dex_path);
296    if (unlink(dex_path) < 0) {
297        return -1;
298    } else {
299        return 0;
300    }
301}
302
303int protect(char *pkgname, gid_t gid)
304{
305    struct stat s;
306    char pkgpath[PKG_PATH_MAX];
307
308    if (gid < AID_SYSTEM) return -1;
309
310    if (create_pkg_path(pkgpath, PROTECTED_DIR_PREFIX, pkgname, ".apk"))
311        return -1;
312
313    if (stat(pkgpath, &s) < 0) return -1;
314
315    if (chown(pkgpath, s.st_uid, gid) < 0) {
316        LOGE("failed to chgrp '%s': %s\n", pkgpath, strerror(errno));
317        return -1;
318    }
319
320    if (chmod(pkgpath, S_IRUSR|S_IWUSR|S_IRGRP) < 0) {
321        LOGE("failed to chmod '%s': %s\n", pkgpath, strerror(errno));
322        return -1;
323    }
324
325    return 0;
326}
327
328static int stat_size(struct stat *s)
329{
330    int blksize = s->st_blksize;
331    int size = s->st_size;
332
333    if (blksize) {
334            /* round up to filesystem block size */
335        size = (size + blksize - 1) & (~(blksize - 1));
336    }
337
338    return size;
339}
340
341static int calculate_dir_size(int dfd)
342{
343    int size = 0;
344    struct stat s;
345    DIR *d;
346    struct dirent *de;
347
348    d = fdopendir(dfd);
349    if (d == NULL) {
350        close(dfd);
351        return 0;
352    }
353
354    while ((de = readdir(d))) {
355        const char *name = de->d_name;
356        if (de->d_type == DT_DIR) {
357            int subfd;
358                /* always skip "." and ".." */
359            if (name[0] == '.') {
360                if (name[1] == 0) continue;
361                if ((name[1] == '.') && (name[2] == 0)) continue;
362            }
363            subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
364            if (subfd >= 0) {
365                size += calculate_dir_size(subfd);
366            }
367        } else {
368            if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
369                size += stat_size(&s);
370            }
371        }
372    }
373    closedir(d);
374    return size;
375}
376
377int get_size(const char *pkgname, const char *apkpath,
378             const char *fwdlock_apkpath,
379             int *_codesize, int *_datasize, int *_cachesize, int encrypted_fs_flag)
380{
381    DIR *d;
382    int dfd;
383    struct dirent *de;
384    struct stat s;
385    char path[PKG_PATH_MAX];
386
387    int codesize = 0;
388    int datasize = 0;
389    int cachesize = 0;
390
391        /* count the source apk as code -- but only if it's not
392         * on the /system partition
393         */
394    if (strncmp(apkpath, "/system", 7) != 0) {
395        if (stat(apkpath, &s) == 0) {
396            codesize += stat_size(&s);
397        }
398    }
399        /* count the forward locked apk as code if it is given
400         */
401    if (fwdlock_apkpath != NULL && fwdlock_apkpath[0] != '!') {
402        if (stat(fwdlock_apkpath, &s) == 0) {
403            codesize += stat_size(&s);
404        }
405    }
406
407
408        /* count the cached dexfile as code */
409    if (!create_cache_path(path, apkpath)) {
410        if (stat(path, &s) == 0) {
411            codesize += stat_size(&s);
412        }
413    }
414
415    if (encrypted_fs_flag == 0) {
416        if (create_pkg_path(path, PKG_DIR_PREFIX, pkgname, PKG_DIR_POSTFIX)) {
417            goto done;
418        }
419    } else {
420        if (create_pkg_path(path, PKG_SEC_DIR_PREFIX, pkgname, PKG_DIR_POSTFIX)) {
421            goto done;
422        }
423    }
424
425    d = opendir(path);
426    if (d == NULL) {
427        goto done;
428    }
429    dfd = dirfd(d);
430
431        /* most stuff in the pkgdir is data, except for the "cache"
432         * directory and below, which is cache, and the "lib" directory
433         * and below, which is code...
434         */
435    while ((de = readdir(d))) {
436        const char *name = de->d_name;
437
438        if (de->d_type == DT_DIR) {
439            int subfd;
440                /* always skip "." and ".." */
441            if (name[0] == '.') {
442                if (name[1] == 0) continue;
443                if ((name[1] == '.') && (name[2] == 0)) continue;
444            }
445            subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
446            if (subfd >= 0) {
447                int size = calculate_dir_size(subfd);
448                if (!strcmp(name,"lib")) {
449                    codesize += size;
450                } else if(!strcmp(name,"cache")) {
451                    cachesize += size;
452                } else {
453                    datasize += size;
454                }
455            }
456        } else {
457            if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
458                datasize += stat_size(&s);
459            }
460        }
461    }
462    closedir(d);
463done:
464    *_codesize = codesize;
465    *_datasize = datasize;
466    *_cachesize = cachesize;
467    return 0;
468}
469
470
471/* a simpler version of dexOptGenerateCacheFileName() */
472int create_cache_path(char path[PKG_PATH_MAX], const char *src)
473{
474    char *tmp;
475    int srclen;
476    int dstlen;
477
478    srclen = strlen(src);
479
480        /* demand that we are an absolute path */
481    if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
482        return -1;
483    }
484
485    if (srclen > PKG_PATH_MAX) {        // XXX: PKG_NAME_MAX?
486        return -1;
487    }
488
489    dstlen = srclen + strlen(DALVIK_CACHE_PREFIX) +
490        strlen(DALVIK_CACHE_POSTFIX) + 1;
491
492    if (dstlen > PKG_PATH_MAX) {
493        return -1;
494    }
495
496    sprintf(path,"%s%s%s",
497            DALVIK_CACHE_PREFIX,
498            src + 1, /* skip the leading / */
499            DALVIK_CACHE_POSTFIX);
500
501    for(tmp = path + strlen(DALVIK_CACHE_PREFIX); *tmp; tmp++) {
502        if (*tmp == '/') {
503            *tmp = '@';
504        }
505    }
506
507    return 0;
508}
509
510static void run_dexopt(int zip_fd, int odex_fd, const char* input_file_name,
511    const char* dexopt_flags)
512{
513    static const char* DEX_OPT_BIN = "/system/bin/dexopt";
514    static const int MAX_INT_LEN = 12;      // '-'+10dig+'\0' -OR- 0x+8dig
515    char zip_num[MAX_INT_LEN];
516    char odex_num[MAX_INT_LEN];
517
518    sprintf(zip_num, "%d", zip_fd);
519    sprintf(odex_num, "%d", odex_fd);
520
521    execl(DEX_OPT_BIN, DEX_OPT_BIN, "--zip", zip_num, odex_num, input_file_name,
522        dexopt_flags, (char*) NULL);
523    LOGE("execl(%s) failed: %s\n", DEX_OPT_BIN, strerror(errno));
524}
525
526static int wait_dexopt(pid_t pid, const char* apk_path)
527{
528    int status;
529    pid_t got_pid;
530
531    /*
532     * Wait for the optimization process to finish.
533     */
534    while (1) {
535        got_pid = waitpid(pid, &status, 0);
536        if (got_pid == -1 && errno == EINTR) {
537            printf("waitpid interrupted, retrying\n");
538        } else {
539            break;
540        }
541    }
542    if (got_pid != pid) {
543        LOGW("waitpid failed: wanted %d, got %d: %s\n",
544            (int) pid, (int) got_pid, strerror(errno));
545        return 1;
546    }
547
548    if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
549        LOGD("DexInv: --- END '%s' (success) ---\n", apk_path);
550        return 0;
551    } else {
552        LOGW("DexInv: --- END '%s' --- status=0x%04x, process failed\n",
553            apk_path, status);
554        return status;      /* always nonzero */
555    }
556}
557
558int dexopt(const char *apk_path, uid_t uid, int is_public)
559{
560    struct utimbuf ut;
561    struct stat apk_stat, dex_stat;
562    char dex_path[PKG_PATH_MAX];
563    char dexopt_flags[PROPERTY_VALUE_MAX];
564    char *end;
565    int res, zip_fd=-1, odex_fd=-1;
566
567        /* Before anything else: is there a .odex file?  If so, we have
568         * pre-optimized the apk and there is nothing to do here.
569         */
570    if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
571        return -1;
572    }
573
574    /* platform-specific flags affecting optimization and verification */
575    property_get("dalvik.vm.dexopt-flags", dexopt_flags, "");
576
577    strcpy(dex_path, apk_path);
578    end = strrchr(dex_path, '.');
579    if (end != NULL) {
580        strcpy(end, ".odex");
581        if (stat(dex_path, &dex_stat) == 0) {
582            return 0;
583        }
584    }
585
586    if (create_cache_path(dex_path, apk_path)) {
587        return -1;
588    }
589
590    memset(&apk_stat, 0, sizeof(apk_stat));
591    stat(apk_path, &apk_stat);
592
593    zip_fd = open(apk_path, O_RDONLY, 0);
594    if (zip_fd < 0) {
595        LOGE("dexopt cannot open '%s' for input\n", apk_path);
596        return -1;
597    }
598
599    unlink(dex_path);
600    odex_fd = open(dex_path, O_RDWR | O_CREAT | O_EXCL, 0644);
601    if (odex_fd < 0) {
602        LOGE("dexopt cannot open '%s' for output\n", dex_path);
603        goto fail;
604    }
605    if (fchown(odex_fd, AID_SYSTEM, uid) < 0) {
606        LOGE("dexopt cannot chown '%s'\n", dex_path);
607        goto fail;
608    }
609    if (fchmod(odex_fd,
610               S_IRUSR|S_IWUSR|S_IRGRP |
611               (is_public ? S_IROTH : 0)) < 0) {
612        LOGE("dexopt cannot chmod '%s'\n", dex_path);
613        goto fail;
614    }
615
616    LOGD("DexInv: --- BEGIN '%s' ---\n", apk_path);
617
618    pid_t pid;
619    pid = fork();
620    if (pid == 0) {
621        /* child -- drop privileges before continuing */
622        if (setgid(uid) != 0) {
623            LOGE("setgid(%d) failed during dexopt\n", uid);
624            exit(64);
625        }
626        if (setuid(uid) != 0) {
627            LOGE("setuid(%d) during dexopt\n", uid);
628            exit(65);
629        }
630        if (flock(odex_fd, LOCK_EX | LOCK_NB) != 0) {
631            LOGE("flock(%s) failed: %s\n", dex_path, strerror(errno));
632            exit(66);
633        }
634
635        run_dexopt(zip_fd, odex_fd, apk_path, dexopt_flags);
636        exit(67);   /* only get here on exec failure */
637    } else {
638        res = wait_dexopt(pid, apk_path);
639        if (res != 0) {
640            LOGE("dexopt failed on '%s' res = %d\n", dex_path, res);
641            goto fail;
642        }
643    }
644
645    ut.actime = apk_stat.st_atime;
646    ut.modtime = apk_stat.st_mtime;
647    utime(dex_path, &ut);
648
649    close(odex_fd);
650    close(zip_fd);
651    return 0;
652
653fail:
654    if (odex_fd >= 0) {
655        close(odex_fd);
656        unlink(dex_path);
657    }
658    if (zip_fd >= 0) {
659        close(zip_fd);
660    }
661    return -1;
662}
663
664int create_move_path(char path[PKG_PATH_MAX],
665    const char* prefix,
666    const char* pkgname,
667    const char* leaf)
668{
669    if ((strlen(prefix) + strlen(pkgname) + strlen(leaf) + 1) >= PKG_PATH_MAX) {
670        return -1;
671    }
672
673    sprintf(path, "%s%s/%s", prefix, pkgname, leaf);
674    return 0;
675}
676
677void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid)
678{
679    while (path[basepos] != 0) {
680        if (path[basepos] == '/') {
681            path[basepos] = 0;
682            LOGI("Making directory: %s\n", path);
683            if (mkdir(path, mode) == 0) {
684                chown(path, uid, gid);
685            }
686            path[basepos] = '/';
687            basepos++;
688        }
689        basepos++;
690    }
691}
692
693int movefileordir(char* srcpath, char* dstpath, int dstuid, int dstgid,
694        struct stat* statbuf)
695{
696    DIR *d;
697    struct dirent *de;
698    int res;
699
700    int srcend = strlen(srcpath);
701    int dstend = strlen(dstpath);
702
703    if (lstat(srcpath, statbuf) < 0) {
704        LOGW("Unable to stat %s: %s\n", srcpath, strerror(errno));
705        return 1;
706    }
707
708    if ((statbuf->st_mode&S_IFDIR) == 0) {
709        LOGI("Renaming %s to %s (uid %d)\n", srcpath, dstpath, dstuid);
710        mkinnerdirs(dstpath, dstend-1, S_IRWXU|S_IRWXG|S_IXOTH, dstuid, dstgid);
711        if (rename(srcpath, dstpath) >= 0) {
712            if (chown(dstpath, dstuid, dstgid) < 0) {
713                LOGE("cannot chown %s: %s\n", dstpath, strerror(errno));
714                unlink(dstpath);
715                return 1;
716            }
717        } else {
718            LOGW("Unable to rename %s to %s: %s\n",
719                srcpath, dstpath, strerror(errno));
720            return 1;
721        }
722        return 0;
723    }
724
725    d = opendir(srcpath);
726    if (d == NULL) {
727        LOGW("Unable to opendir %s: %s\n", srcpath, strerror(errno));
728        return 1;
729    }
730
731    res = 0;
732
733    while ((de = readdir(d))) {
734        const char *name = de->d_name;
735            /* always skip "." and ".." */
736        if (name[0] == '.') {
737            if (name[1] == 0) continue;
738            if ((name[1] == '.') && (name[2] == 0)) continue;
739        }
740
741        if ((srcend+strlen(name)) >= (PKG_PATH_MAX-2)) {
742            LOGW("Source path too long; skipping: %s/%s\n", srcpath, name);
743            continue;
744        }
745
746        if ((dstend+strlen(name)) >= (PKG_PATH_MAX-2)) {
747            LOGW("Destination path too long; skipping: %s/%s\n", dstpath, name);
748            continue;
749        }
750
751        srcpath[srcend] = dstpath[dstend] = '/';
752        strcpy(srcpath+srcend+1, name);
753        strcpy(dstpath+dstend+1, name);
754
755        if (movefileordir(srcpath, dstpath, dstuid, dstgid, statbuf) != 0) {
756            res = 1;
757        }
758
759        // Note: we will be leaving empty directories behind in srcpath,
760        // but that is okay, the package manager will be erasing all of the
761        // data associated with .apks that disappear.
762
763        srcpath[srcend] = dstpath[dstend] = 0;
764    }
765
766    closedir(d);
767    return res;
768}
769
770int movefiles()
771{
772    DIR *d;
773    int dfd, subfd;
774    struct dirent *de;
775    struct stat s;
776    char buf[PKG_PATH_MAX+1];
777    int bufp, bufe, bufi, readlen;
778
779    char srcpkg[PKG_NAME_MAX];
780    char dstpkg[PKG_NAME_MAX];
781    char srcpath[PKG_PATH_MAX];
782    char dstpath[PKG_PATH_MAX];
783    int dstuid=-1, dstgid=-1;
784    int hasspace;
785
786    d = opendir(UPDATE_COMMANDS_DIR_PREFIX);
787    if (d == NULL) {
788        goto done;
789    }
790    dfd = dirfd(d);
791
792        /* Iterate through all files in the directory, executing the
793         * file movements requested there-in.
794         */
795    while ((de = readdir(d))) {
796        const char *name = de->d_name;
797
798        if (de->d_type == DT_DIR) {
799            continue;
800        } else {
801            subfd = openat(dfd, name, O_RDONLY);
802            if (subfd < 0) {
803                LOGW("Unable to open update commands at %s%s\n",
804                        UPDATE_COMMANDS_DIR_PREFIX, name);
805                continue;
806            }
807
808            bufp = 0;
809            bufe = 0;
810            buf[PKG_PATH_MAX] = 0;
811            srcpkg[0] = dstpkg[0] = 0;
812            while (1) {
813                bufi = bufp;
814                while (bufi < bufe && buf[bufi] != '\n') {
815                    bufi++;
816                }
817                if (bufi < bufe) {
818                    buf[bufi] = 0;
819                    LOGV("Processing line: %s\n", buf+bufp);
820                    hasspace = 0;
821                    while (bufp < bufi && isspace(buf[bufp])) {
822                        hasspace = 1;
823                        bufp++;
824                    }
825                    if (buf[bufp] == '#' || bufp == bufi) {
826                        // skip comments and empty lines.
827                    } else if (hasspace) {
828                        if (dstpkg[0] == 0) {
829                            LOGW("Path before package line in %s%s: %s\n",
830                                    UPDATE_COMMANDS_DIR_PREFIX, name, buf+bufp);
831                        } else if (srcpkg[0] == 0) {
832                            // Skip -- source package no longer exists.
833                        } else {
834                            LOGV("Move file: %s (from %s to %s)\n", buf+bufp, srcpkg, dstpkg);
835                            if (!create_move_path(srcpath, PKG_DIR_PREFIX, srcpkg, buf+bufp) &&
836                                    !create_move_path(dstpath, PKG_DIR_PREFIX, dstpkg, buf+bufp)) {
837                                movefileordir(srcpath, dstpath, dstuid, dstgid, &s);
838                            }
839                        }
840                    } else {
841                        char* div = strchr(buf+bufp, ':');
842                        if (div == NULL) {
843                            LOGW("Bad package spec in %s%s; no ':' sep: %s\n",
844                                    UPDATE_COMMANDS_DIR_PREFIX, name, buf+bufp);
845                        } else {
846                            *div = 0;
847                            div++;
848                            if (strlen(buf+bufp) < PKG_NAME_MAX) {
849                                strcpy(dstpkg, buf+bufp);
850                            } else {
851                                srcpkg[0] = dstpkg[0] = 0;
852                                LOGW("Package name too long in %s%s: %s\n",
853                                        UPDATE_COMMANDS_DIR_PREFIX, name, buf+bufp);
854                            }
855                            if (strlen(div) < PKG_NAME_MAX) {
856                                strcpy(srcpkg, div);
857                            } else {
858                                srcpkg[0] = dstpkg[0] = 0;
859                                LOGW("Package name too long in %s%s: %s\n",
860                                        UPDATE_COMMANDS_DIR_PREFIX, name, div);
861                            }
862                            if (srcpkg[0] != 0) {
863                                if (!create_pkg_path(srcpath, PKG_DIR_PREFIX, srcpkg,
864                                        PKG_DIR_POSTFIX)) {
865                                    if (lstat(srcpath, &s) < 0) {
866                                        // Package no longer exists -- skip.
867                                        srcpkg[0] = 0;
868                                    }
869                                } else {
870                                    srcpkg[0] = 0;
871                                    LOGW("Can't create path %s in %s%s\n",
872                                            div, UPDATE_COMMANDS_DIR_PREFIX, name);
873                                }
874                                if (srcpkg[0] != 0) {
875                                    if (!create_pkg_path(dstpath, PKG_DIR_PREFIX, dstpkg,
876                                            PKG_DIR_POSTFIX)) {
877                                        if (lstat(dstpath, &s) == 0) {
878                                            dstuid = s.st_uid;
879                                            dstgid = s.st_gid;
880                                        } else {
881                                            // Destination package doesn't
882                                            // exist...  due to original-package,
883                                            // this is normal, so don't be
884                                            // noisy about it.
885                                            srcpkg[0] = 0;
886                                        }
887                                    } else {
888                                        srcpkg[0] = 0;
889                                        LOGW("Can't create path %s in %s%s\n",
890                                                div, UPDATE_COMMANDS_DIR_PREFIX, name);
891                                    }
892                                }
893                                LOGV("Transfering from %s to %s: uid=%d\n",
894                                    srcpkg, dstpkg, dstuid);
895                            }
896                        }
897                    }
898                    bufp = bufi+1;
899                } else {
900                    if (bufp == 0) {
901                        if (bufp < bufe) {
902                            LOGW("Line too long in %s%s, skipping: %s\n",
903                                    UPDATE_COMMANDS_DIR_PREFIX, name, buf);
904                        }
905                    } else if (bufp < bufe) {
906                        memcpy(buf, buf+bufp, bufe-bufp);
907                        bufe -= bufp;
908                        bufp = 0;
909                    }
910                    readlen = read(subfd, buf+bufe, PKG_PATH_MAX-bufe);
911                    if (readlen < 0) {
912                        LOGW("Failure reading update commands in %s%s: %s\n",
913                                UPDATE_COMMANDS_DIR_PREFIX, name, strerror(errno));
914                        break;
915                    } else if (readlen == 0) {
916                        break;
917                    }
918                    bufe += readlen;
919                    buf[bufe] = 0;
920                    LOGV("Read buf: %s\n", buf);
921                }
922            }
923            close(subfd);
924        }
925    }
926    closedir(d);
927done:
928    return 0;
929}
930