• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <linux/capability.h>
18 #include "installd.h"
19 #include <diskusage/dirsize.h>
20 
21 #ifdef HAVE_SELINUX
22 #include <selinux/android.h>
23 #endif
24 
25 /* Directory records that are used in execution of commands. */
26 dir_rec_t android_data_dir;
27 dir_rec_t android_asec_dir;
28 dir_rec_t android_app_dir;
29 dir_rec_t android_app_private_dir;
30 dir_rec_t android_app_lib_dir;
31 dir_rec_t android_media_dir;
32 dir_rec_array_t android_system_dirs;
33 
install(const char * pkgname,uid_t uid,gid_t gid)34 int install(const char *pkgname, uid_t uid, gid_t gid)
35 {
36     char pkgdir[PKG_PATH_MAX];
37     char libsymlink[PKG_PATH_MAX];
38     char applibdir[PKG_PATH_MAX];
39     struct stat libStat;
40 
41     if ((uid < AID_SYSTEM) || (gid < AID_SYSTEM)) {
42         ALOGE("invalid uid/gid: %d %d\n", uid, gid);
43         return -1;
44     }
45 
46     if (create_pkg_path(pkgdir, pkgname, PKG_DIR_POSTFIX, 0)) {
47         ALOGE("cannot create package path\n");
48         return -1;
49     }
50 
51     if (create_pkg_path(libsymlink, pkgname, PKG_LIB_POSTFIX, 0)) {
52         ALOGE("cannot create package lib symlink origin path\n");
53         return -1;
54     }
55 
56     if (create_pkg_path_in_dir(applibdir, &android_app_lib_dir, pkgname, PKG_DIR_POSTFIX)) {
57         ALOGE("cannot create package lib symlink dest path\n");
58         return -1;
59     }
60 
61     if (mkdir(pkgdir, 0751) < 0) {
62         ALOGE("cannot create dir '%s': %s\n", pkgdir, strerror(errno));
63         return -1;
64     }
65     if (chmod(pkgdir, 0751) < 0) {
66         ALOGE("cannot chmod dir '%s': %s\n", pkgdir, strerror(errno));
67         unlink(pkgdir);
68         return -1;
69     }
70 
71     if (lstat(libsymlink, &libStat) < 0) {
72         if (errno != ENOENT) {
73             ALOGE("couldn't stat lib dir: %s\n", strerror(errno));
74             return -1;
75         }
76     } else {
77         if (S_ISDIR(libStat.st_mode)) {
78             if (delete_dir_contents(libsymlink, 1, 0) < 0) {
79                 ALOGE("couldn't delete lib directory during install for: %s", libsymlink);
80                 return -1;
81             }
82         } else if (S_ISLNK(libStat.st_mode)) {
83             if (unlink(libsymlink) < 0) {
84                 ALOGE("couldn't unlink lib directory during install for: %s", libsymlink);
85                 return -1;
86             }
87         }
88     }
89 
90     if (symlink(applibdir, libsymlink) < 0) {
91         ALOGE("couldn't symlink directory '%s' -> '%s': %s\n", libsymlink, applibdir,
92                 strerror(errno));
93         unlink(pkgdir);
94         return -1;
95     }
96 
97 #ifdef HAVE_SELINUX
98     if (selinux_android_setfilecon(pkgdir, pkgname, uid) < 0) {
99         ALOGE("cannot setfilecon dir '%s': %s\n", pkgdir, strerror(errno));
100         unlink(libsymlink);
101         unlink(pkgdir);
102         return -1;
103     }
104 #endif
105 
106     if (chown(pkgdir, uid, gid) < 0) {
107         ALOGE("cannot chown dir '%s': %s\n", pkgdir, strerror(errno));
108         unlink(libsymlink);
109         unlink(pkgdir);
110         return -1;
111     }
112 
113     return 0;
114 }
115 
uninstall(const char * pkgname,uid_t persona)116 int uninstall(const char *pkgname, uid_t persona)
117 {
118     char pkgdir[PKG_PATH_MAX];
119 
120     if (create_pkg_path(pkgdir, pkgname, PKG_DIR_POSTFIX, persona))
121         return -1;
122 
123     /* delete contents AND directory, no exceptions */
124     return delete_dir_contents(pkgdir, 1, NULL);
125 }
126 
renamepkg(const char * oldpkgname,const char * newpkgname)127 int renamepkg(const char *oldpkgname, const char *newpkgname)
128 {
129     char oldpkgdir[PKG_PATH_MAX];
130     char newpkgdir[PKG_PATH_MAX];
131 
132     if (create_pkg_path(oldpkgdir, oldpkgname, PKG_DIR_POSTFIX, 0))
133         return -1;
134     if (create_pkg_path(newpkgdir, newpkgname, PKG_DIR_POSTFIX, 0))
135         return -1;
136 
137     if (rename(oldpkgdir, newpkgdir) < 0) {
138         ALOGE("cannot rename dir '%s' to '%s': %s\n", oldpkgdir, newpkgdir, strerror(errno));
139         return -errno;
140     }
141     return 0;
142 }
143 
fix_uid(const char * pkgname,uid_t uid,gid_t gid)144 int fix_uid(const char *pkgname, uid_t uid, gid_t gid)
145 {
146     char pkgdir[PKG_PATH_MAX];
147     struct stat s;
148     int rc = 0;
149 
150     if ((uid < AID_SYSTEM) || (gid < AID_SYSTEM)) {
151         ALOGE("invalid uid/gid: %d %d\n", uid, gid);
152         return -1;
153     }
154 
155     if (create_pkg_path(pkgdir, pkgname, PKG_DIR_POSTFIX, 0)) {
156         ALOGE("cannot create package path\n");
157         return -1;
158     }
159 
160     if (stat(pkgdir, &s) < 0) return -1;
161 
162     if (s.st_uid != 0 || s.st_gid != 0) {
163         ALOGE("fixing uid of non-root pkg: %s %lu %lu\n", pkgdir, s.st_uid, s.st_gid);
164         return -1;
165     }
166 
167     if (chmod(pkgdir, 0751) < 0) {
168         ALOGE("cannot chmod dir '%s': %s\n", pkgdir, strerror(errno));
169         unlink(pkgdir);
170         return -errno;
171     }
172     if (chown(pkgdir, uid, gid) < 0) {
173         ALOGE("cannot chown dir '%s': %s\n", pkgdir, strerror(errno));
174         unlink(pkgdir);
175         return -errno;
176     }
177 
178     return 0;
179 }
180 
delete_user_data(const char * pkgname,uid_t persona)181 int delete_user_data(const char *pkgname, uid_t persona)
182 {
183     char pkgdir[PKG_PATH_MAX];
184 
185     if (create_pkg_path(pkgdir, pkgname, PKG_DIR_POSTFIX, persona))
186         return -1;
187 
188     /* delete contents, excluding "lib", but not the directory itself */
189     return delete_dir_contents(pkgdir, 0, "lib");
190 }
191 
make_user_data(const char * pkgname,uid_t uid,uid_t persona)192 int make_user_data(const char *pkgname, uid_t uid, uid_t persona)
193 {
194     char pkgdir[PKG_PATH_MAX];
195     char applibdir[PKG_PATH_MAX];
196     char libsymlink[PKG_PATH_MAX];
197     struct stat libStat;
198 
199     // Create the data dir for the package
200     if (create_pkg_path(pkgdir, pkgname, PKG_DIR_POSTFIX, persona)) {
201         return -1;
202     }
203     if (create_pkg_path(libsymlink, pkgname, PKG_LIB_POSTFIX, persona)) {
204         ALOGE("cannot create package lib symlink origin path\n");
205         return -1;
206     }
207     if (create_pkg_path_in_dir(applibdir, &android_app_lib_dir, pkgname, PKG_DIR_POSTFIX)) {
208         ALOGE("cannot create package lib symlink dest path\n");
209         return -1;
210     }
211 
212     if (mkdir(pkgdir, 0751) < 0) {
213         ALOGE("cannot create dir '%s': %s\n", pkgdir, strerror(errno));
214         return -errno;
215     }
216     if (chmod(pkgdir, 0751) < 0) {
217         ALOGE("cannot chmod dir '%s': %s\n", pkgdir, strerror(errno));
218         unlink(pkgdir);
219         return -errno;
220     }
221 
222     if (lstat(libsymlink, &libStat) < 0) {
223         if (errno != ENOENT) {
224             ALOGE("couldn't stat lib dir for non-primary: %s\n", strerror(errno));
225             unlink(pkgdir);
226             return -1;
227         }
228     } else {
229         if (S_ISDIR(libStat.st_mode)) {
230             if (delete_dir_contents(libsymlink, 1, 0) < 0) {
231                 ALOGE("couldn't delete lib directory during install for non-primary: %s",
232                         libsymlink);
233                 unlink(pkgdir);
234                 return -1;
235             }
236         } else if (S_ISLNK(libStat.st_mode)) {
237             if (unlink(libsymlink) < 0) {
238                 ALOGE("couldn't unlink lib directory during install for non-primary: %s",
239                         libsymlink);
240                 unlink(pkgdir);
241                 return -1;
242             }
243         }
244     }
245 
246     if (symlink(applibdir, libsymlink) < 0) {
247         ALOGE("couldn't symlink directory for non-primary '%s' -> '%s': %s\n", libsymlink,
248                 applibdir, strerror(errno));
249         unlink(pkgdir);
250         return -1;
251     }
252 
253     if (chown(pkgdir, uid, uid) < 0) {
254         ALOGE("cannot chown dir '%s': %s\n", pkgdir, strerror(errno));
255         unlink(libsymlink);
256         unlink(pkgdir);
257         return -errno;
258     }
259 
260 #ifdef HAVE_SELINUX
261     if (selinux_android_setfilecon(pkgdir, pkgname, uid) < 0) {
262         ALOGE("cannot setfilecon dir '%s': %s\n", pkgdir, strerror(errno));
263         unlink(libsymlink);
264         unlink(pkgdir);
265         return -errno;
266     }
267 #endif
268 
269     return 0;
270 }
271 
delete_persona(uid_t persona)272 int delete_persona(uid_t persona)
273 {
274     char data_path[PKG_PATH_MAX];
275     if (create_persona_path(data_path, persona)) {
276         return -1;
277     }
278     if (delete_dir_contents(data_path, 1, NULL)) {
279         return -1;
280     }
281 
282     char media_path[PATH_MAX];
283     if (create_persona_media_path(media_path, (userid_t) persona) == -1) {
284         return -1;
285     }
286     if (delete_dir_contents(media_path, 1, NULL) == -1) {
287         return -1;
288     }
289 
290     return 0;
291 }
292 
clone_persona_data(uid_t src_persona,uid_t target_persona,int copy)293 int clone_persona_data(uid_t src_persona, uid_t target_persona, int copy)
294 {
295     char src_data_dir[PKG_PATH_MAX];
296     char pkg_path[PKG_PATH_MAX];
297     DIR *d;
298     struct dirent *de;
299     struct stat s;
300     uid_t uid;
301 
302     if (create_persona_path(src_data_dir, src_persona)) {
303         return -1;
304     }
305 
306     d = opendir(src_data_dir);
307     if (d != NULL) {
308         while ((de = readdir(d))) {
309             const char *name = de->d_name;
310 
311             if (de->d_type == DT_DIR) {
312                 int subfd;
313                     /* always skip "." and ".." */
314                 if (name[0] == '.') {
315                     if (name[1] == 0) continue;
316                     if ((name[1] == '.') && (name[2] == 0)) continue;
317                 }
318                 /* Create the full path to the package's data dir */
319                 create_pkg_path(pkg_path, name, PKG_DIR_POSTFIX, src_persona);
320                 /* Get the file stat */
321                 if (stat(pkg_path, &s) < 0) continue;
322                 /* Get the uid of the package */
323                 ALOGI("Adding datadir for uid = %lu\n", s.st_uid);
324                 uid = (uid_t) s.st_uid % PER_USER_RANGE;
325                 /* Create the directory for the target */
326                 make_user_data(name, uid + target_persona * PER_USER_RANGE,
327                                target_persona);
328             }
329         }
330         closedir(d);
331     }
332 
333     if (ensure_media_user_dirs((userid_t) target_persona) == -1) {
334         return -1;
335     }
336 
337     return 0;
338 }
339 
delete_cache(const char * pkgname,uid_t persona)340 int delete_cache(const char *pkgname, uid_t persona)
341 {
342     char cachedir[PKG_PATH_MAX];
343 
344     if (create_pkg_path(cachedir, pkgname, CACHE_DIR_POSTFIX, persona))
345         return -1;
346 
347         /* delete contents, not the directory, no exceptions */
348     return delete_dir_contents(cachedir, 0, 0);
349 }
350 
351 /* Try to ensure free_size bytes of storage are available.
352  * Returns 0 on success.
353  * This is rather simple-minded because doing a full LRU would
354  * be potentially memory-intensive, and without atime it would
355  * also require that apps constantly modify file metadata even
356  * when just reading from the cache, which is pretty awful.
357  */
free_cache(int64_t free_size)358 int free_cache(int64_t free_size)
359 {
360     cache_t* cache;
361     int64_t avail;
362     DIR *d;
363     struct dirent *de;
364     char tmpdir[PATH_MAX];
365     char *dirpos;
366 
367     avail = data_disk_free();
368     if (avail < 0) return -1;
369 
370     ALOGI("free_cache(%" PRId64 ") avail %" PRId64 "\n", free_size, avail);
371     if (avail >= free_size) return 0;
372 
373     cache = start_cache_collection();
374 
375     // Collect cache files for primary user.
376     if (create_persona_path(tmpdir, 0) == 0) {
377         //ALOGI("adding cache files from %s\n", tmpdir);
378         add_cache_files(cache, tmpdir, "cache");
379     }
380 
381     // Search for other users and add any cache files from them.
382     snprintf(tmpdir, sizeof(tmpdir), "%s%s", android_data_dir.path,
383             SECONDARY_USER_PREFIX);
384     dirpos = tmpdir + strlen(tmpdir);
385     d = opendir(tmpdir);
386     if (d != NULL) {
387         while ((de = readdir(d))) {
388             if (de->d_type == DT_DIR) {
389                 const char *name = de->d_name;
390                     /* always skip "." and ".." */
391                 if (name[0] == '.') {
392                     if (name[1] == 0) continue;
393                     if ((name[1] == '.') && (name[2] == 0)) continue;
394                 }
395                 if ((strlen(name)+(dirpos-tmpdir)) < (sizeof(tmpdir)-1)) {
396                     strcpy(dirpos, name);
397                     //ALOGI("adding cache files from %s\n", tmpdir);
398                     add_cache_files(cache, tmpdir, "cache");
399                 } else {
400                     ALOGW("Path exceeds limit: %s%s", tmpdir, name);
401                 }
402             }
403         }
404         closedir(d);
405     }
406 
407     // Collect cache files on external storage for all users (if it is mounted as part
408     // of the internal storage).
409     strcpy(tmpdir, android_media_dir.path);
410     dirpos = tmpdir + strlen(tmpdir);
411     d = opendir(tmpdir);
412     if (d != NULL) {
413         while ((de = readdir(d))) {
414             if (de->d_type == DT_DIR) {
415                 const char *name = de->d_name;
416                     /* skip any dir that doesn't start with a number, so not a user */
417                 if (name[0] < '0' || name[0] > '9') {
418                     continue;
419                 }
420                 if ((strlen(name)+(dirpos-tmpdir)) < (sizeof(tmpdir)-1)) {
421                     strcpy(dirpos, name);
422                     if (lookup_media_dir(tmpdir, "Android") == 0
423                             && lookup_media_dir(tmpdir, "data") == 0) {
424                         //ALOGI("adding cache files from %s\n", tmpdir);
425                         add_cache_files(cache, tmpdir, "cache");
426                     }
427                 } else {
428                     ALOGW("Path exceeds limit: %s%s", tmpdir, name);
429                 }
430             }
431         }
432         closedir(d);
433     }
434 
435     clear_cache_files(cache, free_size);
436     finish_cache_collection(cache);
437 
438     return data_disk_free() >= free_size ? 0 : -1;
439 }
440 
move_dex(const char * src,const char * dst)441 int move_dex(const char *src, const char *dst)
442 {
443     char src_dex[PKG_PATH_MAX];
444     char dst_dex[PKG_PATH_MAX];
445 
446     if (validate_apk_path(src)) return -1;
447     if (validate_apk_path(dst)) return -1;
448 
449     if (create_cache_path(src_dex, src)) return -1;
450     if (create_cache_path(dst_dex, dst)) return -1;
451 
452     ALOGV("move %s -> %s\n", src_dex, dst_dex);
453     if (rename(src_dex, dst_dex) < 0) {
454         ALOGE("Couldn't move %s: %s\n", src_dex, strerror(errno));
455         return -1;
456     } else {
457         return 0;
458     }
459 }
460 
rm_dex(const char * path)461 int rm_dex(const char *path)
462 {
463     char dex_path[PKG_PATH_MAX];
464 
465     if (validate_apk_path(path)) return -1;
466     if (create_cache_path(dex_path, path)) return -1;
467 
468     ALOGV("unlink %s\n", dex_path);
469     if (unlink(dex_path) < 0) {
470         ALOGE("Couldn't unlink %s: %s\n", dex_path, strerror(errno));
471         return -1;
472     } else {
473         return 0;
474     }
475 }
476 
get_size(const char * pkgname,int persona,const char * apkpath,const char * fwdlock_apkpath,const char * asecpath,int64_t * _codesize,int64_t * _datasize,int64_t * _cachesize,int64_t * _asecsize)477 int get_size(const char *pkgname, int persona, const char *apkpath,
478              const char *fwdlock_apkpath, const char *asecpath,
479              int64_t *_codesize, int64_t *_datasize, int64_t *_cachesize,
480              int64_t* _asecsize)
481 {
482     DIR *d;
483     int dfd;
484     struct dirent *de;
485     struct stat s;
486     char path[PKG_PATH_MAX];
487 
488     int64_t codesize = 0;
489     int64_t datasize = 0;
490     int64_t cachesize = 0;
491     int64_t asecsize = 0;
492 
493         /* count the source apk as code -- but only if it's not
494          * on the /system partition and its not on the sdcard.
495          */
496     if (validate_system_app_path(apkpath) &&
497             strncmp(apkpath, android_asec_dir.path, android_asec_dir.len) != 0) {
498         if (stat(apkpath, &s) == 0) {
499             codesize += stat_size(&s);
500         }
501     }
502         /* count the forward locked apk as code if it is given
503          */
504     if (fwdlock_apkpath != NULL && fwdlock_apkpath[0] != '!') {
505         if (stat(fwdlock_apkpath, &s) == 0) {
506             codesize += stat_size(&s);
507         }
508     }
509         /* count the cached dexfile as code */
510     if (!create_cache_path(path, apkpath)) {
511         if (stat(path, &s) == 0) {
512             codesize += stat_size(&s);
513         }
514     }
515 
516         /* add in size of any libraries */
517     if (!create_pkg_path_in_dir(path, &android_app_lib_dir, pkgname, PKG_DIR_POSTFIX)) {
518         d = opendir(path);
519         if (d != NULL) {
520             dfd = dirfd(d);
521             codesize += calculate_dir_size(dfd);
522             closedir(d);
523         }
524     }
525 
526         /* compute asec size if it is given
527          */
528     if (asecpath != NULL && asecpath[0] != '!') {
529         if (stat(asecpath, &s) == 0) {
530             asecsize += stat_size(&s);
531         }
532     }
533 
534     if (create_pkg_path(path, pkgname, PKG_DIR_POSTFIX, persona)) {
535         goto done;
536     }
537 
538     d = opendir(path);
539     if (d == NULL) {
540         goto done;
541     }
542     dfd = dirfd(d);
543 
544     /* most stuff in the pkgdir is data, except for the "cache"
545      * directory and below, which is cache, and the "lib" directory
546      * and below, which is code...
547      */
548     while ((de = readdir(d))) {
549         const char *name = de->d_name;
550 
551         if (de->d_type == DT_DIR) {
552             int subfd;
553             int64_t statsize = 0;
554             int64_t dirsize = 0;
555                 /* always skip "." and ".." */
556             if (name[0] == '.') {
557                 if (name[1] == 0) continue;
558                 if ((name[1] == '.') && (name[2] == 0)) continue;
559             }
560             if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
561                 statsize = stat_size(&s);
562             }
563             subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
564             if (subfd >= 0) {
565                 dirsize = calculate_dir_size(subfd);
566             }
567             if(!strcmp(name,"lib")) {
568                 codesize += dirsize + statsize;
569             } else if(!strcmp(name,"cache")) {
570                 cachesize += dirsize + statsize;
571             } else {
572                 datasize += dirsize + statsize;
573             }
574         } else if (de->d_type == DT_LNK && !strcmp(name,"lib")) {
575             // This is the symbolic link to the application's library
576             // code.  We'll count this as code instead of data, since
577             // it is not something that the app creates.
578             if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
579                 codesize += stat_size(&s);
580             }
581         } else {
582             if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
583                 datasize += stat_size(&s);
584             }
585         }
586     }
587     closedir(d);
588 done:
589     *_codesize = codesize;
590     *_datasize = datasize;
591     *_cachesize = cachesize;
592     *_asecsize = asecsize;
593     return 0;
594 }
595 
596 
597 /* a simpler version of dexOptGenerateCacheFileName() */
create_cache_path(char path[PKG_PATH_MAX],const char * src)598 int create_cache_path(char path[PKG_PATH_MAX], const char *src)
599 {
600     char *tmp;
601     int srclen;
602     int dstlen;
603 
604     srclen = strlen(src);
605 
606         /* demand that we are an absolute path */
607     if ((src == 0) || (src[0] != '/') || strstr(src,"..")) {
608         return -1;
609     }
610 
611     if (srclen > PKG_PATH_MAX) {        // XXX: PKG_NAME_MAX?
612         return -1;
613     }
614 
615     dstlen = srclen + strlen(DALVIK_CACHE_PREFIX) +
616         strlen(DALVIK_CACHE_POSTFIX) + 1;
617 
618     if (dstlen > PKG_PATH_MAX) {
619         return -1;
620     }
621 
622     sprintf(path,"%s%s%s",
623             DALVIK_CACHE_PREFIX,
624             src + 1, /* skip the leading / */
625             DALVIK_CACHE_POSTFIX);
626 
627     for(tmp = path + strlen(DALVIK_CACHE_PREFIX); *tmp; tmp++) {
628         if (*tmp == '/') {
629             *tmp = '@';
630         }
631     }
632 
633     return 0;
634 }
635 
run_dexopt(int zip_fd,int odex_fd,const char * input_file_name,const char * dexopt_flags)636 static void run_dexopt(int zip_fd, int odex_fd, const char* input_file_name,
637     const char* dexopt_flags)
638 {
639     static const char* DEX_OPT_BIN = "/system/bin/dexopt";
640     static const int MAX_INT_LEN = 12;      // '-'+10dig+'\0' -OR- 0x+8dig
641     char zip_num[MAX_INT_LEN];
642     char odex_num[MAX_INT_LEN];
643 
644     sprintf(zip_num, "%d", zip_fd);
645     sprintf(odex_num, "%d", odex_fd);
646 
647     execl(DEX_OPT_BIN, DEX_OPT_BIN, "--zip", zip_num, odex_num, input_file_name,
648         dexopt_flags, (char*) NULL);
649     ALOGE("execl(%s) failed: %s\n", DEX_OPT_BIN, strerror(errno));
650 }
651 
wait_dexopt(pid_t pid,const char * apk_path)652 static int wait_dexopt(pid_t pid, const char* apk_path)
653 {
654     int status;
655     pid_t got_pid;
656 
657     /*
658      * Wait for the optimization process to finish.
659      */
660     while (1) {
661         got_pid = waitpid(pid, &status, 0);
662         if (got_pid == -1 && errno == EINTR) {
663             printf("waitpid interrupted, retrying\n");
664         } else {
665             break;
666         }
667     }
668     if (got_pid != pid) {
669         ALOGW("waitpid failed: wanted %d, got %d: %s\n",
670             (int) pid, (int) got_pid, strerror(errno));
671         return 1;
672     }
673 
674     if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
675         ALOGV("DexInv: --- END '%s' (success) ---\n", apk_path);
676         return 0;
677     } else {
678         ALOGW("DexInv: --- END '%s' --- status=0x%04x, process failed\n",
679             apk_path, status);
680         return status;      /* always nonzero */
681     }
682 }
683 
dexopt(const char * apk_path,uid_t uid,int is_public)684 int dexopt(const char *apk_path, uid_t uid, int is_public)
685 {
686     struct utimbuf ut;
687     struct stat apk_stat, dex_stat;
688     char dex_path[PKG_PATH_MAX];
689     char dexopt_flags[PROPERTY_VALUE_MAX];
690     char *end;
691     int res, zip_fd=-1, odex_fd=-1;
692 
693         /* Before anything else: is there a .odex file?  If so, we have
694          * pre-optimized the apk and there is nothing to do here.
695          */
696     if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
697         return -1;
698     }
699 
700     /* platform-specific flags affecting optimization and verification */
701     property_get("dalvik.vm.dexopt-flags", dexopt_flags, "");
702 
703     strcpy(dex_path, apk_path);
704     end = strrchr(dex_path, '.');
705     if (end != NULL) {
706         strcpy(end, ".odex");
707         if (stat(dex_path, &dex_stat) == 0) {
708             return 0;
709         }
710     }
711 
712     if (create_cache_path(dex_path, apk_path)) {
713         return -1;
714     }
715 
716     memset(&apk_stat, 0, sizeof(apk_stat));
717     stat(apk_path, &apk_stat);
718 
719     zip_fd = open(apk_path, O_RDONLY, 0);
720     if (zip_fd < 0) {
721         ALOGE("dexopt cannot open '%s' for input\n", apk_path);
722         return -1;
723     }
724 
725     unlink(dex_path);
726     odex_fd = open(dex_path, O_RDWR | O_CREAT | O_EXCL, 0644);
727     if (odex_fd < 0) {
728         ALOGE("dexopt cannot open '%s' for output\n", dex_path);
729         goto fail;
730     }
731     if (fchmod(odex_fd,
732                S_IRUSR|S_IWUSR|S_IRGRP |
733                (is_public ? S_IROTH : 0)) < 0) {
734         ALOGE("dexopt cannot chmod '%s'\n", dex_path);
735         goto fail;
736     }
737     if (fchown(odex_fd, AID_SYSTEM, uid) < 0) {
738         ALOGE("dexopt cannot chown '%s'\n", dex_path);
739         goto fail;
740     }
741 
742     ALOGV("DexInv: --- BEGIN '%s' ---\n", apk_path);
743 
744     pid_t pid;
745     pid = fork();
746     if (pid == 0) {
747         /* child -- drop privileges before continuing */
748         if (setgid(uid) != 0) {
749             ALOGE("setgid(%d) failed during dexopt\n", uid);
750             exit(64);
751         }
752         if (setuid(uid) != 0) {
753             ALOGE("setuid(%d) during dexopt\n", uid);
754             exit(65);
755         }
756         // drop capabilities
757         struct __user_cap_header_struct capheader;
758         struct __user_cap_data_struct capdata[2];
759         memset(&capheader, 0, sizeof(capheader));
760         memset(&capdata, 0, sizeof(capdata));
761         capheader.version = _LINUX_CAPABILITY_VERSION_3;
762         if (capset(&capheader, &capdata[0]) < 0) {
763             ALOGE("capset failed: %s\n", strerror(errno));
764             exit(66);
765         }
766         if (flock(odex_fd, LOCK_EX | LOCK_NB) != 0) {
767             ALOGE("flock(%s) failed: %s\n", dex_path, strerror(errno));
768             exit(67);
769         }
770 
771         run_dexopt(zip_fd, odex_fd, apk_path, dexopt_flags);
772         exit(68);   /* only get here on exec failure */
773     } else {
774         res = wait_dexopt(pid, apk_path);
775         if (res != 0) {
776             ALOGE("dexopt failed on '%s' res = %d\n", dex_path, res);
777             goto fail;
778         }
779     }
780 
781     ut.actime = apk_stat.st_atime;
782     ut.modtime = apk_stat.st_mtime;
783     utime(dex_path, &ut);
784 
785     close(odex_fd);
786     close(zip_fd);
787     return 0;
788 
789 fail:
790     if (odex_fd >= 0) {
791         close(odex_fd);
792         unlink(dex_path);
793     }
794     if (zip_fd >= 0) {
795         close(zip_fd);
796     }
797     return -1;
798 }
799 
mkinnerdirs(char * path,int basepos,mode_t mode,int uid,int gid,struct stat * statbuf)800 void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
801         struct stat* statbuf)
802 {
803     while (path[basepos] != 0) {
804         if (path[basepos] == '/') {
805             path[basepos] = 0;
806             if (lstat(path, statbuf) < 0) {
807                 ALOGV("Making directory: %s\n", path);
808                 if (mkdir(path, mode) == 0) {
809                     chown(path, uid, gid);
810                 } else {
811                     ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
812                 }
813             }
814             path[basepos] = '/';
815             basepos++;
816         }
817         basepos++;
818     }
819 }
820 
movefileordir(char * srcpath,char * dstpath,int dstbasepos,int dstuid,int dstgid,struct stat * statbuf)821 int movefileordir(char* srcpath, char* dstpath, int dstbasepos,
822         int dstuid, int dstgid, struct stat* statbuf)
823 {
824     DIR *d;
825     struct dirent *de;
826     int res;
827 
828     int srcend = strlen(srcpath);
829     int dstend = strlen(dstpath);
830 
831     if (lstat(srcpath, statbuf) < 0) {
832         ALOGW("Unable to stat %s: %s\n", srcpath, strerror(errno));
833         return 1;
834     }
835 
836     if ((statbuf->st_mode&S_IFDIR) == 0) {
837         mkinnerdirs(dstpath, dstbasepos, S_IRWXU|S_IRWXG|S_IXOTH,
838                 dstuid, dstgid, statbuf);
839         ALOGV("Renaming %s to %s (uid %d)\n", srcpath, dstpath, dstuid);
840         if (rename(srcpath, dstpath) >= 0) {
841             if (chown(dstpath, dstuid, dstgid) < 0) {
842                 ALOGE("cannot chown %s: %s\n", dstpath, strerror(errno));
843                 unlink(dstpath);
844                 return 1;
845             }
846         } else {
847             ALOGW("Unable to rename %s to %s: %s\n",
848                 srcpath, dstpath, strerror(errno));
849             return 1;
850         }
851         return 0;
852     }
853 
854     d = opendir(srcpath);
855     if (d == NULL) {
856         ALOGW("Unable to opendir %s: %s\n", srcpath, strerror(errno));
857         return 1;
858     }
859 
860     res = 0;
861 
862     while ((de = readdir(d))) {
863         const char *name = de->d_name;
864             /* always skip "." and ".." */
865         if (name[0] == '.') {
866             if (name[1] == 0) continue;
867             if ((name[1] == '.') && (name[2] == 0)) continue;
868         }
869 
870         if ((srcend+strlen(name)) >= (PKG_PATH_MAX-2)) {
871             ALOGW("Source path too long; skipping: %s/%s\n", srcpath, name);
872             continue;
873         }
874 
875         if ((dstend+strlen(name)) >= (PKG_PATH_MAX-2)) {
876             ALOGW("Destination path too long; skipping: %s/%s\n", dstpath, name);
877             continue;
878         }
879 
880         srcpath[srcend] = dstpath[dstend] = '/';
881         strcpy(srcpath+srcend+1, name);
882         strcpy(dstpath+dstend+1, name);
883 
884         if (movefileordir(srcpath, dstpath, dstbasepos, dstuid, dstgid, statbuf) != 0) {
885             res = 1;
886         }
887 
888         // Note: we will be leaving empty directories behind in srcpath,
889         // but that is okay, the package manager will be erasing all of the
890         // data associated with .apks that disappear.
891 
892         srcpath[srcend] = dstpath[dstend] = 0;
893     }
894 
895     closedir(d);
896     return res;
897 }
898 
movefiles()899 int movefiles()
900 {
901     DIR *d;
902     int dfd, subfd;
903     struct dirent *de;
904     struct stat s;
905     char buf[PKG_PATH_MAX+1];
906     int bufp, bufe, bufi, readlen;
907 
908     char srcpkg[PKG_NAME_MAX];
909     char dstpkg[PKG_NAME_MAX];
910     char srcpath[PKG_PATH_MAX];
911     char dstpath[PKG_PATH_MAX];
912     int dstuid=-1, dstgid=-1;
913     int hasspace;
914 
915     d = opendir(UPDATE_COMMANDS_DIR_PREFIX);
916     if (d == NULL) {
917         goto done;
918     }
919     dfd = dirfd(d);
920 
921         /* Iterate through all files in the directory, executing the
922          * file movements requested there-in.
923          */
924     while ((de = readdir(d))) {
925         const char *name = de->d_name;
926 
927         if (de->d_type == DT_DIR) {
928             continue;
929         } else {
930             subfd = openat(dfd, name, O_RDONLY);
931             if (subfd < 0) {
932                 ALOGW("Unable to open update commands at %s%s\n",
933                         UPDATE_COMMANDS_DIR_PREFIX, name);
934                 continue;
935             }
936 
937             bufp = 0;
938             bufe = 0;
939             buf[PKG_PATH_MAX] = 0;
940             srcpkg[0] = dstpkg[0] = 0;
941             while (1) {
942                 bufi = bufp;
943                 while (bufi < bufe && buf[bufi] != '\n') {
944                     bufi++;
945                 }
946                 if (bufi < bufe) {
947                     buf[bufi] = 0;
948                     ALOGV("Processing line: %s\n", buf+bufp);
949                     hasspace = 0;
950                     while (bufp < bufi && isspace(buf[bufp])) {
951                         hasspace = 1;
952                         bufp++;
953                     }
954                     if (buf[bufp] == '#' || bufp == bufi) {
955                         // skip comments and empty lines.
956                     } else if (hasspace) {
957                         if (dstpkg[0] == 0) {
958                             ALOGW("Path before package line in %s%s: %s\n",
959                                     UPDATE_COMMANDS_DIR_PREFIX, name, buf+bufp);
960                         } else if (srcpkg[0] == 0) {
961                             // Skip -- source package no longer exists.
962                         } else {
963                             ALOGV("Move file: %s (from %s to %s)\n", buf+bufp, srcpkg, dstpkg);
964                             if (!create_move_path(srcpath, srcpkg, buf+bufp, 0) &&
965                                     !create_move_path(dstpath, dstpkg, buf+bufp, 0)) {
966                                 movefileordir(srcpath, dstpath,
967                                         strlen(dstpath)-strlen(buf+bufp),
968                                         dstuid, dstgid, &s);
969                             }
970                         }
971                     } else {
972                         char* div = strchr(buf+bufp, ':');
973                         if (div == NULL) {
974                             ALOGW("Bad package spec in %s%s; no ':' sep: %s\n",
975                                     UPDATE_COMMANDS_DIR_PREFIX, name, buf+bufp);
976                         } else {
977                             *div = 0;
978                             div++;
979                             if (strlen(buf+bufp) < PKG_NAME_MAX) {
980                                 strcpy(dstpkg, buf+bufp);
981                             } else {
982                                 srcpkg[0] = dstpkg[0] = 0;
983                                 ALOGW("Package name too long in %s%s: %s\n",
984                                         UPDATE_COMMANDS_DIR_PREFIX, name, buf+bufp);
985                             }
986                             if (strlen(div) < PKG_NAME_MAX) {
987                                 strcpy(srcpkg, div);
988                             } else {
989                                 srcpkg[0] = dstpkg[0] = 0;
990                                 ALOGW("Package name too long in %s%s: %s\n",
991                                         UPDATE_COMMANDS_DIR_PREFIX, name, div);
992                             }
993                             if (srcpkg[0] != 0) {
994                                 if (!create_pkg_path(srcpath, srcpkg, PKG_DIR_POSTFIX, 0)) {
995                                     if (lstat(srcpath, &s) < 0) {
996                                         // Package no longer exists -- skip.
997                                         srcpkg[0] = 0;
998                                     }
999                                 } else {
1000                                     srcpkg[0] = 0;
1001                                     ALOGW("Can't create path %s in %s%s\n",
1002                                             div, UPDATE_COMMANDS_DIR_PREFIX, name);
1003                                 }
1004                                 if (srcpkg[0] != 0) {
1005                                     if (!create_pkg_path(dstpath, dstpkg, PKG_DIR_POSTFIX, 0)) {
1006                                         if (lstat(dstpath, &s) == 0) {
1007                                             dstuid = s.st_uid;
1008                                             dstgid = s.st_gid;
1009                                         } else {
1010                                             // Destination package doesn't
1011                                             // exist...  due to original-package,
1012                                             // this is normal, so don't be
1013                                             // noisy about it.
1014                                             srcpkg[0] = 0;
1015                                         }
1016                                     } else {
1017                                         srcpkg[0] = 0;
1018                                         ALOGW("Can't create path %s in %s%s\n",
1019                                                 div, UPDATE_COMMANDS_DIR_PREFIX, name);
1020                                     }
1021                                 }
1022                                 ALOGV("Transfering from %s to %s: uid=%d\n",
1023                                     srcpkg, dstpkg, dstuid);
1024                             }
1025                         }
1026                     }
1027                     bufp = bufi+1;
1028                 } else {
1029                     if (bufp == 0) {
1030                         if (bufp < bufe) {
1031                             ALOGW("Line too long in %s%s, skipping: %s\n",
1032                                     UPDATE_COMMANDS_DIR_PREFIX, name, buf);
1033                         }
1034                     } else if (bufp < bufe) {
1035                         memcpy(buf, buf+bufp, bufe-bufp);
1036                         bufe -= bufp;
1037                         bufp = 0;
1038                     }
1039                     readlen = read(subfd, buf+bufe, PKG_PATH_MAX-bufe);
1040                     if (readlen < 0) {
1041                         ALOGW("Failure reading update commands in %s%s: %s\n",
1042                                 UPDATE_COMMANDS_DIR_PREFIX, name, strerror(errno));
1043                         break;
1044                     } else if (readlen == 0) {
1045                         break;
1046                     }
1047                     bufe += readlen;
1048                     buf[bufe] = 0;
1049                     ALOGV("Read buf: %s\n", buf);
1050                 }
1051             }
1052             close(subfd);
1053         }
1054     }
1055     closedir(d);
1056 done:
1057     return 0;
1058 }
1059 
linklib(const char * pkgname,const char * asecLibDir,int userId)1060 int linklib(const char* pkgname, const char* asecLibDir, int userId)
1061 {
1062     char pkgdir[PKG_PATH_MAX];
1063     char libsymlink[PKG_PATH_MAX];
1064     struct stat s, libStat;
1065     int rc = 0;
1066 
1067     if (create_pkg_path(pkgdir, pkgname, PKG_DIR_POSTFIX, userId)) {
1068         ALOGE("cannot create package path\n");
1069         return -1;
1070     }
1071     if (create_pkg_path(libsymlink, pkgname, PKG_LIB_POSTFIX, userId)) {
1072         ALOGE("cannot create package lib symlink origin path\n");
1073         return -1;
1074     }
1075 
1076     if (stat(pkgdir, &s) < 0) return -1;
1077 
1078     if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
1079         ALOGE("failed to chown '%s': %s\n", pkgdir, strerror(errno));
1080         return -1;
1081     }
1082 
1083     if (chmod(pkgdir, 0700) < 0) {
1084         ALOGE("linklib() 1: failed to chmod '%s': %s\n", pkgdir, strerror(errno));
1085         rc = -1;
1086         goto out;
1087     }
1088 
1089     if (lstat(libsymlink, &libStat) < 0) {
1090         if (errno != ENOENT) {
1091             ALOGE("couldn't stat lib dir: %s\n", strerror(errno));
1092             rc = -1;
1093             goto out;
1094         }
1095     } else {
1096         if (S_ISDIR(libStat.st_mode)) {
1097             if (delete_dir_contents(libsymlink, 1, 0) < 0) {
1098                 rc = -1;
1099                 goto out;
1100             }
1101         } else if (S_ISLNK(libStat.st_mode)) {
1102             if (unlink(libsymlink) < 0) {
1103                 ALOGE("couldn't unlink lib dir: %s\n", strerror(errno));
1104                 rc = -1;
1105                 goto out;
1106             }
1107         }
1108     }
1109 
1110     if (symlink(asecLibDir, libsymlink) < 0) {
1111         ALOGE("couldn't symlink directory '%s' -> '%s': %s\n", libsymlink, asecLibDir,
1112                 strerror(errno));
1113         rc = -errno;
1114         goto out;
1115     }
1116 
1117 out:
1118     if (chmod(pkgdir, s.st_mode) < 0) {
1119         ALOGE("linklib() 2: failed to chmod '%s': %s\n", pkgdir, strerror(errno));
1120         rc = -errno;
1121     }
1122 
1123     if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
1124         ALOGE("failed to chown '%s' : %s\n", pkgdir, strerror(errno));
1125         return -errno;
1126     }
1127 
1128     return rc;
1129 }
1130