DefaultContainerService.java revision 6431d11cd420536aaa9d93ae510a3151ccc4df1d
1/*
2 * Copyright (C) 2010 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
17package com.android.defcontainer;
18
19import android.app.IntentService;
20import android.content.Intent;
21import android.content.pm.ContainerEncryptionParams;
22import android.content.pm.IPackageManager;
23import android.content.pm.LimitedLengthInputStream;
24import android.content.pm.MacAuthenticatedInputStream;
25import android.content.pm.PackageCleanItem;
26import android.content.pm.PackageInfo;
27import android.content.pm.PackageInfoLite;
28import android.content.pm.PackageManager;
29import android.content.pm.PackageParser;
30import android.content.res.ObbInfo;
31import android.content.res.ObbScanner;
32import android.net.Uri;
33import android.os.Build;
34import android.os.Environment;
35import android.os.Environment.UserEnvironment;
36import android.os.FileUtils;
37import android.os.IBinder;
38import android.os.ParcelFileDescriptor;
39import android.os.Process;
40import android.os.RemoteException;
41import android.os.ServiceManager;
42import android.os.StatFs;
43import android.provider.Settings;
44import android.system.ErrnoException;
45import android.system.Os;
46import android.system.StructStatVfs;
47import android.util.DisplayMetrics;
48import android.util.Slog;
49
50import com.android.internal.app.IMediaContainerService;
51import com.android.internal.content.NativeLibraryHelper;
52import com.android.internal.content.PackageHelper;
53
54import java.io.BufferedInputStream;
55import java.io.File;
56import java.io.FileInputStream;
57import java.io.FileNotFoundException;
58import java.io.IOException;
59import java.io.InputStream;
60import java.io.OutputStream;
61import java.security.DigestException;
62import java.security.GeneralSecurityException;
63import java.security.InvalidAlgorithmParameterException;
64import java.security.InvalidKeyException;
65import java.security.NoSuchAlgorithmException;
66
67import javax.crypto.Cipher;
68import javax.crypto.CipherInputStream;
69import javax.crypto.Mac;
70import javax.crypto.NoSuchPaddingException;
71
72import libcore.io.IoUtils;
73import libcore.io.Streams;
74
75/*
76 * This service copies a downloaded apk to a file passed in as
77 * a ParcelFileDescriptor or to a newly created container specified
78 * by parameters. The DownloadManager gives access to this process
79 * based on its uid. This process also needs the ACCESS_DOWNLOAD_MANAGER
80 * permission to access apks downloaded via the download manager.
81 */
82public class DefaultContainerService extends IntentService {
83    private static final String TAG = "DefContainer";
84    private static final boolean localLOGV = false;
85
86    private static final String LIB_DIR_NAME = "lib";
87
88    private IMediaContainerService.Stub mBinder = new IMediaContainerService.Stub() {
89        /**
90         * Creates a new container and copies resource there.
91         * @param paackageURI the uri of resource to be copied. Can be either
92         * a content uri or a file uri
93         * @param cid the id of the secure container that should
94         * be used for creating a secure container into which the resource
95         * will be copied.
96         * @param key Refers to key used for encrypting the secure container
97         * @param resFileName Name of the target resource file(relative to newly
98         * created secure container)
99         * @return Returns the new cache path where the resource has been copied into
100         *
101         */
102        public String copyResourceToContainer(final Uri packageURI, final String cid,
103                final String key, final String resFileName, final String publicResFileName,
104                boolean isExternal, boolean isForwardLocked, String abiOverride) {
105            if (packageURI == null || cid == null) {
106                return null;
107            }
108
109            return copyResourceInner(packageURI, cid, key, resFileName, publicResFileName,
110                    isExternal, isForwardLocked, abiOverride);
111        }
112
113        /**
114         * Copy specified resource to output stream
115         *
116         * @param packageURI the uri of resource to be copied. Should be a file
117         *            uri
118         * @param encryptionParams parameters describing the encryption used for
119         *            this file
120         * @param outStream Remote file descriptor to be used for copying
121         * @return returns status code according to those in
122         *         {@link PackageManager}
123         */
124        public int copyResource(final Uri packageURI, ContainerEncryptionParams encryptionParams,
125                ParcelFileDescriptor outStream) {
126            if (packageURI == null || outStream == null) {
127                return PackageManager.INSTALL_FAILED_INVALID_URI;
128            }
129
130            ParcelFileDescriptor.AutoCloseOutputStream autoOut
131                    = new ParcelFileDescriptor.AutoCloseOutputStream(outStream);
132
133            try {
134                copyFile(packageURI, autoOut, encryptionParams);
135                return PackageManager.INSTALL_SUCCEEDED;
136            } catch (FileNotFoundException e) {
137                Slog.e(TAG, "Could not copy URI " + packageURI.toString() + " FNF: "
138                        + e.getMessage());
139                return PackageManager.INSTALL_FAILED_INVALID_URI;
140            } catch (IOException e) {
141                Slog.e(TAG, "Could not copy URI " + packageURI.toString() + " IO: "
142                        + e.getMessage());
143                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
144            } catch (DigestException e) {
145                Slog.e(TAG, "Could not copy URI " + packageURI.toString() + " Security: "
146                                + e.getMessage());
147                return PackageManager.INSTALL_FAILED_INVALID_APK;
148            } finally {
149                IoUtils.closeQuietly(autoOut);
150            }
151        }
152
153        /**
154         * Determine the recommended install location for package
155         * specified by file uri location.
156         *
157         * @return Returns PackageInfoLite object containing
158         * the package info and recommended app location.
159         */
160        public PackageInfoLite getMinimalPackageInfo(final String packagePath, int flags,
161                long threshold, String abiOverride) {
162            PackageInfoLite ret = new PackageInfoLite();
163
164            if (packagePath == null) {
165                Slog.i(TAG, "Invalid package file " + packagePath);
166                ret.recommendedInstallLocation = PackageHelper.RECOMMEND_FAILED_INVALID_APK;
167                return ret;
168            }
169
170            DisplayMetrics metrics = new DisplayMetrics();
171            metrics.setToDefaults();
172
173            PackageParser.PackageLite pkg = PackageParser.parsePackageLite(packagePath, 0);
174            if (pkg == null) {
175                Slog.w(TAG, "Failed to parse package");
176
177                final File apkFile = new File(packagePath);
178                if (!apkFile.exists()) {
179                    ret.recommendedInstallLocation = PackageHelper.RECOMMEND_FAILED_INVALID_URI;
180                } else {
181                    ret.recommendedInstallLocation = PackageHelper.RECOMMEND_FAILED_INVALID_APK;
182                }
183
184                return ret;
185            }
186
187            ret.packageName = pkg.packageName;
188            ret.versionCode = pkg.versionCode;
189            ret.installLocation = pkg.installLocation;
190            ret.verifiers = pkg.verifiers;
191
192            ret.recommendedInstallLocation = recommendAppInstallLocation(pkg.installLocation,
193                    packagePath, flags, threshold, abiOverride);
194
195            return ret;
196        }
197
198        @Override
199        public boolean checkInternalFreeStorage(Uri packageUri, boolean isForwardLocked,
200                long threshold) throws RemoteException {
201            final File apkFile = new File(packageUri.getPath());
202            try {
203                return isUnderInternalThreshold(apkFile, isForwardLocked, threshold);
204            } catch (IOException e) {
205                return true;
206            }
207        }
208
209        @Override
210        public boolean checkExternalFreeStorage(Uri packageUri, boolean isForwardLocked,
211                String abiOverride) throws RemoteException {
212            final File apkFile = new File(packageUri.getPath());
213            try {
214                return isUnderExternalThreshold(apkFile, isForwardLocked, abiOverride);
215            } catch (IOException e) {
216                return true;
217            }
218        }
219
220        public ObbInfo getObbInfo(String filename) {
221            try {
222                return ObbScanner.getObbInfo(filename);
223            } catch (IOException e) {
224                Slog.d(TAG, "Couldn't get OBB info for " + filename);
225                return null;
226            }
227        }
228
229        @Override
230        public long calculateDirectorySize(String path) throws RemoteException {
231            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
232
233            final File dir = Environment.maybeTranslateEmulatedPathToInternal(new File(path));
234            if (dir.exists() && dir.isDirectory()) {
235                final String targetPath = dir.getAbsolutePath();
236                return MeasurementUtils.measureDirectory(targetPath);
237            } else {
238                return 0L;
239            }
240        }
241
242        @Override
243        public long[] getFileSystemStats(String path) {
244            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
245
246            try {
247                final StructStatVfs stat = Os.statvfs(path);
248                final long totalSize = stat.f_blocks * stat.f_bsize;
249                final long availSize = stat.f_bavail * stat.f_bsize;
250                return new long[] { totalSize, availSize };
251            } catch (ErrnoException e) {
252                throw new IllegalStateException(e);
253            }
254        }
255
256        @Override
257        public void clearDirectory(String path) throws RemoteException {
258            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
259
260            final File directory = new File(path);
261            if (directory.exists() && directory.isDirectory()) {
262                eraseFiles(directory);
263            }
264        }
265
266        @Override
267        public long calculateInstalledSize(String packagePath, boolean isForwardLocked,
268                String abiOverride) throws RemoteException {
269            final File packageFile = new File(packagePath);
270            try {
271                return calculateContainerSize(packageFile, isForwardLocked, abiOverride) * 1024 * 1024;
272            } catch (IOException e) {
273                /*
274                 * Okay, something failed, so let's just estimate it to be 2x
275                 * the file size. Note this will be 0 if the file doesn't exist.
276                 */
277                return packageFile.length() * 2;
278            }
279        }
280    };
281
282    public DefaultContainerService() {
283        super("DefaultContainerService");
284        setIntentRedelivery(true);
285    }
286
287    @Override
288    protected void onHandleIntent(Intent intent) {
289        if (PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE.equals(intent.getAction())) {
290            final IPackageManager pm = IPackageManager.Stub.asInterface(
291                    ServiceManager.getService("package"));
292            PackageCleanItem item = null;
293            try {
294                while ((item = pm.nextPackageToClean(item)) != null) {
295                    final UserEnvironment userEnv = new UserEnvironment(item.userId);
296                    eraseFiles(userEnv.buildExternalStorageAppDataDirs(item.packageName));
297                    eraseFiles(userEnv.buildExternalStorageAppMediaDirs(item.packageName));
298                    if (item.andCode) {
299                        eraseFiles(userEnv.buildExternalStorageAppObbDirs(item.packageName));
300                    }
301                }
302            } catch (RemoteException e) {
303            }
304        }
305    }
306
307    void eraseFiles(File[] paths) {
308        for (File path : paths) {
309            eraseFiles(path);
310        }
311    }
312
313    void eraseFiles(File path) {
314        if (path.isDirectory()) {
315            String[] files = path.list();
316            if (files != null) {
317                for (String file : files) {
318                    eraseFiles(new File(path, file));
319                }
320            }
321        }
322        path.delete();
323    }
324
325    public IBinder onBind(Intent intent) {
326        return mBinder;
327    }
328
329    private String copyResourceInner(Uri packageURI, String newCid, String key, String resFileName,
330            String publicResFileName, boolean isExternal, boolean isForwardLocked,
331            String abiOverride) {
332
333        if (isExternal) {
334            // Make sure the sdcard is mounted.
335            String status = Environment.getExternalStorageState();
336            if (!status.equals(Environment.MEDIA_MOUNTED)) {
337                Slog.w(TAG, "Make sure sdcard is mounted.");
338                return null;
339            }
340        }
341
342        // The .apk file
343        String codePath = packageURI.getPath();
344        File codeFile = new File(codePath);
345        String[] abiList = (abiOverride != null) ? new String[] { abiOverride }
346                : Build.SUPPORTED_ABIS;
347        NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(codePath);
348        final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
349
350        // Calculate size of container needed to hold base APK.
351        final int sizeMb;
352        try {
353            sizeMb = calculateContainerSize(handle, codeFile, abi, isForwardLocked);
354        } catch (IOException e) {
355            Slog.w(TAG, "Problem when trying to copy " + codeFile.getPath());
356            return null;
357        }
358
359        // Create new container
360        final String newCachePath = PackageHelper.createSdDir(sizeMb, newCid, key, Process.myUid(),
361                isExternal);
362        if (newCachePath == null) {
363            Slog.e(TAG, "Failed to create container " + newCid);
364            return null;
365        }
366
367        if (localLOGV) {
368            Slog.i(TAG, "Created container for " + newCid + " at path : " + newCachePath);
369        }
370
371        final File resFile = new File(newCachePath, resFileName);
372        if (FileUtils.copyFile(new File(codePath), resFile)) {
373            if (localLOGV) {
374                Slog.i(TAG, "Copied " + codePath + " to " + resFile);
375            }
376        } else {
377            Slog.e(TAG, "Failed to copy " + codePath + " to " + resFile);
378            // Clean up container
379            PackageHelper.destroySdDir(newCid);
380            return null;
381        }
382
383        try {
384            Os.chmod(resFile.getAbsolutePath(), 0640);
385        } catch (ErrnoException e) {
386            Slog.e(TAG, "Could not chown APK: " + e.getMessage());
387            PackageHelper.destroySdDir(newCid);
388            return null;
389        }
390
391        if (isForwardLocked) {
392            File publicZipFile = new File(newCachePath, publicResFileName);
393            try {
394                PackageHelper.extractPublicFiles(resFile.getAbsolutePath(), publicZipFile);
395                if (localLOGV) {
396                    Slog.i(TAG, "Copied resources to " + publicZipFile);
397                }
398            } catch (IOException e) {
399                Slog.e(TAG, "Could not chown public APK " + publicZipFile.getAbsolutePath() + ": "
400                        + e.getMessage());
401                PackageHelper.destroySdDir(newCid);
402                return null;
403            }
404
405            try {
406                Os.chmod(publicZipFile.getAbsolutePath(), 0644);
407            } catch (ErrnoException e) {
408                Slog.e(TAG, "Could not chown public resource file: " + e.getMessage());
409                PackageHelper.destroySdDir(newCid);
410                return null;
411            }
412        }
413
414        final File sharedLibraryDir = new File(newCachePath, LIB_DIR_NAME);
415        if (sharedLibraryDir.mkdir()) {
416            int ret = PackageManager.INSTALL_SUCCEEDED;
417            if (abi >= 0) {
418                ret = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
419                        sharedLibraryDir, abiList[abi]);
420            } else if (abi != PackageManager.NO_NATIVE_LIBRARIES) {
421                ret = abi;
422            }
423
424            if (ret != PackageManager.INSTALL_SUCCEEDED) {
425                Slog.e(TAG, "Could not copy native libraries to " + sharedLibraryDir.getPath());
426                PackageHelper.destroySdDir(newCid);
427                return null;
428            }
429        } else {
430            Slog.e(TAG, "Could not create native lib directory: " + sharedLibraryDir.getPath());
431            PackageHelper.destroySdDir(newCid);
432            return null;
433        }
434
435        if (!PackageHelper.finalizeSdDir(newCid)) {
436            Slog.e(TAG, "Failed to finalize " + newCid + " at path " + newCachePath);
437            // Clean up container
438            PackageHelper.destroySdDir(newCid);
439            return null;
440        }
441
442        if (localLOGV) {
443            Slog.i(TAG, "Finalized container " + newCid);
444        }
445
446        if (PackageHelper.isContainerMounted(newCid)) {
447            if (localLOGV) {
448                Slog.i(TAG, "Unmounting " + newCid + " at path " + newCachePath);
449            }
450
451            // Force a gc to avoid being killed.
452            Runtime.getRuntime().gc();
453            PackageHelper.unMountSdDir(newCid);
454        } else {
455            if (localLOGV) {
456                Slog.i(TAG, "Container " + newCid + " not mounted");
457            }
458        }
459
460        return newCachePath;
461    }
462
463    private static void copyToFile(InputStream inputStream, OutputStream out) throws IOException {
464        byte[] buffer = new byte[16384];
465        int bytesRead;
466        while ((bytesRead = inputStream.read(buffer)) >= 0) {
467            out.write(buffer, 0, bytesRead);
468        }
469    }
470
471    private void copyFile(Uri pPackageURI, OutputStream outStream,
472            ContainerEncryptionParams encryptionParams) throws FileNotFoundException, IOException,
473            DigestException {
474        String scheme = pPackageURI.getScheme();
475        InputStream inStream = null;
476        try {
477            if (scheme == null || scheme.equals("file")) {
478                final InputStream is = new FileInputStream(new File(pPackageURI.getPath()));
479                inStream = new BufferedInputStream(is);
480            } else if (scheme.equals("content")) {
481                final ParcelFileDescriptor fd;
482                try {
483                    fd = getContentResolver().openFileDescriptor(pPackageURI, "r");
484                } catch (FileNotFoundException e) {
485                    Slog.e(TAG, "Couldn't open file descriptor from download service. "
486                            + "Failed with exception " + e);
487                    throw e;
488                }
489
490                if (fd == null) {
491                    Slog.e(TAG, "Provider returned no file descriptor for " +
492                            pPackageURI.toString());
493                    throw new FileNotFoundException("provider returned no file descriptor");
494                } else {
495                    if (localLOGV) {
496                        Slog.i(TAG, "Opened file descriptor from download service.");
497                    }
498                    inStream = new ParcelFileDescriptor.AutoCloseInputStream(fd);
499                }
500            } else {
501                Slog.e(TAG, "Package URI is not 'file:' or 'content:' - " + pPackageURI);
502                throw new FileNotFoundException("Package URI is not 'file:' or 'content:'");
503            }
504
505            /*
506             * If this resource is encrypted, get the decrypted stream version
507             * of it.
508             */
509            ApkContainer container = new ApkContainer(inStream, encryptionParams);
510
511            try {
512                /*
513                 * We copy the source package file to a temp file and then
514                 * rename it to the destination file in order to eliminate a
515                 * window where the package directory scanner notices the new
516                 * package file but it's not completely copied yet.
517                 */
518                copyToFile(container.getInputStream(), outStream);
519
520                if (!container.isAuthenticated()) {
521                    throw new DigestException();
522                }
523            } catch (GeneralSecurityException e) {
524                throw new DigestException("A problem occured copying the file.");
525            }
526        } finally {
527            IoUtils.closeQuietly(inStream);
528        }
529    }
530
531    private static class ApkContainer {
532        private static final int MAX_AUTHENTICATED_DATA_SIZE = 16384;
533
534        private final InputStream mInStream;
535
536        private MacAuthenticatedInputStream mAuthenticatedStream;
537
538        private byte[] mTag;
539
540        public ApkContainer(InputStream inStream, ContainerEncryptionParams encryptionParams)
541                throws IOException {
542            if (encryptionParams == null) {
543                mInStream = inStream;
544            } else {
545                mInStream = getDecryptedStream(inStream, encryptionParams);
546                mTag = encryptionParams.getMacTag();
547            }
548        }
549
550        public boolean isAuthenticated() {
551            if (mAuthenticatedStream == null) {
552                return true;
553            }
554
555            return mAuthenticatedStream.isTagEqual(mTag);
556        }
557
558        private Mac getMacInstance(ContainerEncryptionParams encryptionParams) throws IOException {
559            final Mac m;
560            try {
561                final String macAlgo = encryptionParams.getMacAlgorithm();
562
563                if (macAlgo != null) {
564                    m = Mac.getInstance(macAlgo);
565                    m.init(encryptionParams.getMacKey(), encryptionParams.getMacSpec());
566                } else {
567                    m = null;
568                }
569
570                return m;
571            } catch (NoSuchAlgorithmException e) {
572                throw new IOException(e);
573            } catch (InvalidKeyException e) {
574                throw new IOException(e);
575            } catch (InvalidAlgorithmParameterException e) {
576                throw new IOException(e);
577            }
578        }
579
580        public InputStream getInputStream() {
581            return mInStream;
582        }
583
584        private InputStream getDecryptedStream(InputStream inStream,
585                ContainerEncryptionParams encryptionParams) throws IOException {
586            final Cipher c;
587            try {
588                c = Cipher.getInstance(encryptionParams.getEncryptionAlgorithm());
589                c.init(Cipher.DECRYPT_MODE, encryptionParams.getEncryptionKey(),
590                        encryptionParams.getEncryptionSpec());
591            } catch (NoSuchAlgorithmException e) {
592                throw new IOException(e);
593            } catch (NoSuchPaddingException e) {
594                throw new IOException(e);
595            } catch (InvalidKeyException e) {
596                throw new IOException(e);
597            } catch (InvalidAlgorithmParameterException e) {
598                throw new IOException(e);
599            }
600
601            final long encStart = encryptionParams.getEncryptedDataStart();
602            final long end = encryptionParams.getDataEnd();
603            if (end < encStart) {
604                throw new IOException("end <= encStart");
605            }
606
607            final Mac mac = getMacInstance(encryptionParams);
608            if (mac != null) {
609                final long macStart = encryptionParams.getAuthenticatedDataStart();
610                if (macStart >= Integer.MAX_VALUE) {
611                    throw new IOException("macStart >= Integer.MAX_VALUE");
612                }
613
614                final long furtherOffset;
615                if (macStart >= 0 && encStart >= 0 && macStart < encStart) {
616                    /*
617                     * If there is authenticated data at the beginning, read
618                     * that into our MAC first.
619                     */
620                    final long authenticatedLengthLong = encStart - macStart;
621                    if (authenticatedLengthLong > MAX_AUTHENTICATED_DATA_SIZE) {
622                        throw new IOException("authenticated data is too long");
623                    }
624                    final int authenticatedLength = (int) authenticatedLengthLong;
625
626                    final byte[] authenticatedData = new byte[(int) authenticatedLength];
627
628                    Streams.readFully(inStream, authenticatedData, (int) macStart,
629                            authenticatedLength);
630                    mac.update(authenticatedData, 0, authenticatedLength);
631
632                    furtherOffset = 0;
633                } else {
634                    /*
635                     * No authenticated data at the beginning. Just skip the
636                     * required number of bytes to the beginning of the stream.
637                     */
638                    if (encStart > 0) {
639                        furtherOffset = encStart;
640                    } else {
641                        furtherOffset = 0;
642                    }
643                }
644
645                /*
646                 * If there is data at the end of the stream we want to ignore,
647                 * wrap this in a LimitedLengthInputStream.
648                 */
649                if (furtherOffset >= 0 && end > furtherOffset) {
650                    inStream = new LimitedLengthInputStream(inStream, furtherOffset, end - encStart);
651                } else if (furtherOffset > 0) {
652                    inStream.skip(furtherOffset);
653                }
654
655                mAuthenticatedStream = new MacAuthenticatedInputStream(inStream, mac);
656
657                inStream = mAuthenticatedStream;
658            } else {
659                if (encStart >= 0) {
660                    if (end > encStart) {
661                        inStream = new LimitedLengthInputStream(inStream, encStart, end - encStart);
662                    } else {
663                        inStream.skip(encStart);
664                    }
665                }
666            }
667
668            return new CipherInputStream(inStream, c);
669        }
670
671    }
672
673    private static final int PREFER_INTERNAL = 1;
674    private static final int PREFER_EXTERNAL = 2;
675
676    private int recommendAppInstallLocation(int installLocation, String archiveFilePath, int flags,
677            long threshold, String abiOverride) {
678        int prefer;
679        boolean checkBoth = false;
680
681        final boolean isForwardLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
682
683        check_inner : {
684            /*
685             * Explicit install flags should override the manifest settings.
686             */
687            if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
688                prefer = PREFER_INTERNAL;
689                break check_inner;
690            } else if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
691                prefer = PREFER_EXTERNAL;
692                break check_inner;
693            }
694
695            /* No install flags. Check for manifest option. */
696            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
697                prefer = PREFER_INTERNAL;
698                break check_inner;
699            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
700                prefer = PREFER_EXTERNAL;
701                checkBoth = true;
702                break check_inner;
703            } else if (installLocation == PackageInfo.INSTALL_LOCATION_AUTO) {
704                // We default to preferring internal storage.
705                prefer = PREFER_INTERNAL;
706                checkBoth = true;
707                break check_inner;
708            }
709
710            // Pick user preference
711            int installPreference = Settings.Global.getInt(getApplicationContext()
712                    .getContentResolver(),
713                    Settings.Global.DEFAULT_INSTALL_LOCATION,
714                    PackageHelper.APP_INSTALL_AUTO);
715            if (installPreference == PackageHelper.APP_INSTALL_INTERNAL) {
716                prefer = PREFER_INTERNAL;
717                break check_inner;
718            } else if (installPreference == PackageHelper.APP_INSTALL_EXTERNAL) {
719                prefer = PREFER_EXTERNAL;
720                break check_inner;
721            }
722
723            /*
724             * Fall back to default policy of internal-only if nothing else is
725             * specified.
726             */
727            prefer = PREFER_INTERNAL;
728        }
729
730        final boolean emulated = Environment.isExternalStorageEmulated();
731
732        final File apkFile = new File(archiveFilePath);
733
734        boolean fitsOnInternal = false;
735        if (checkBoth || prefer == PREFER_INTERNAL) {
736            try {
737                fitsOnInternal = isUnderInternalThreshold(apkFile, isForwardLocked, threshold);
738            } catch (IOException e) {
739                return PackageHelper.RECOMMEND_FAILED_INVALID_URI;
740            }
741        }
742
743        boolean fitsOnSd = false;
744        if (!emulated && (checkBoth || prefer == PREFER_EXTERNAL)) {
745            try {
746                fitsOnSd = isUnderExternalThreshold(apkFile, isForwardLocked, abiOverride);
747            } catch (IOException e) {
748                return PackageHelper.RECOMMEND_FAILED_INVALID_URI;
749            }
750        }
751
752        if (prefer == PREFER_INTERNAL) {
753            if (fitsOnInternal) {
754                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
755            }
756        } else if (!emulated && prefer == PREFER_EXTERNAL) {
757            if (fitsOnSd) {
758                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
759            }
760        }
761
762        if (checkBoth) {
763            if (fitsOnInternal) {
764                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
765            } else if (!emulated && fitsOnSd) {
766                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
767            }
768        }
769
770        /*
771         * If they requested to be on the external media by default, return that
772         * the media was unavailable. Otherwise, indicate there was insufficient
773         * storage space available.
774         */
775        if (!emulated && (checkBoth || prefer == PREFER_EXTERNAL)
776                && !Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
777            return PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE;
778        } else {
779            return PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
780        }
781    }
782
783    /**
784     * Measure a file to see if it fits within the free space threshold.
785     *
786     * @param apkFile file to check
787     * @param threshold byte threshold to compare against
788     * @return true if file fits under threshold
789     * @throws FileNotFoundException when APK does not exist
790     */
791    private boolean isUnderInternalThreshold(File apkFile, boolean isForwardLocked, long threshold)
792            throws IOException {
793        long size = apkFile.length();
794        if (size == 0 && !apkFile.exists()) {
795            throw new FileNotFoundException();
796        }
797
798        if (isForwardLocked) {
799            size += PackageHelper.extractPublicFiles(apkFile.getAbsolutePath(), null);
800        }
801
802        final StatFs internalStats = new StatFs(Environment.getDataDirectory().getPath());
803        final long availInternalSize = (long) internalStats.getAvailableBlocks()
804                * (long) internalStats.getBlockSize();
805
806        return (availInternalSize - size) > threshold;
807    }
808
809
810    /**
811     * Measure a file to see if it fits in the external free space.
812     *
813     * @param apkFile file to check
814     * @return true if file fits
815     * @throws IOException when file does not exist
816     */
817    private boolean isUnderExternalThreshold(File apkFile, boolean isForwardLocked, String abiOverride)
818            throws IOException {
819        if (Environment.isExternalStorageEmulated()) {
820            return false;
821        }
822
823        final int sizeMb = calculateContainerSize(apkFile, isForwardLocked, abiOverride);
824
825        final int availSdMb;
826        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
827            final StatFs sdStats = new StatFs(Environment.getExternalStorageDirectory().getPath());
828            final int blocksToMb = (1 << 20) / sdStats.getBlockSize();
829            availSdMb = sdStats.getAvailableBlocks() * blocksToMb;
830        } else {
831            availSdMb = -1;
832        }
833
834        return availSdMb > sizeMb;
835    }
836
837    private int calculateContainerSize(File apkFile, boolean forwardLocked,
838            String abiOverride) throws IOException {
839        NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(apkFile);
840        final int abi = NativeLibraryHelper.findSupportedAbi(handle,
841                (abiOverride != null) ? new String[] { abiOverride } : Build.SUPPORTED_ABIS);
842
843        try {
844            return calculateContainerSize(handle, apkFile, abi, forwardLocked);
845        } finally {
846            handle.close();
847        }
848    }
849
850    /**
851     * Calculate the container size for an APK. Takes into account the
852     *
853     * @param apkFile file from which to calculate size
854     * @return size in megabytes (2^20 bytes)
855     * @throws IOException when there is a problem reading the file
856     */
857    private int calculateContainerSize(NativeLibraryHelper.ApkHandle apkHandle,
858            File apkFile, int abiIndex, boolean forwardLocked) throws IOException {
859        // Calculate size of container needed to hold base APK.
860        long sizeBytes = apkFile.length();
861        if (sizeBytes == 0 && !apkFile.exists()) {
862            throw new FileNotFoundException();
863        }
864
865        // Check all the native files that need to be copied and add that to the
866        // container size.
867        if (abiIndex >= 0) {
868            sizeBytes += NativeLibraryHelper.sumNativeBinariesLI(apkHandle,
869                    Build.SUPPORTED_ABIS[abiIndex]);
870        }
871
872        if (forwardLocked) {
873            sizeBytes += PackageHelper.extractPublicFiles(apkFile.getPath(), null);
874        }
875
876        int sizeMb = (int) (sizeBytes >> 20);
877        if ((sizeBytes - (sizeMb * 1024 * 1024)) > 0) {
878            sizeMb++;
879        }
880
881        /*
882         * Add buffer size because we don't have a good way to determine the
883         * real FAT size. Your FAT size varies with how many directory entries
884         * you need, how big the whole filesystem is, and other such headaches.
885         */
886        sizeMb++;
887
888        return sizeMb;
889    }
890}
891