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