DefaultContainerService.java revision 366949c2d934435ff9ef8082408ca36ff14a2241
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.content.Intent;
24import android.content.pm.IPackageManager;
25import android.content.pm.PackageInfo;
26import android.content.pm.PackageInfoLite;
27import android.content.pm.PackageManager;
28import android.content.pm.PackageParser;
29import android.content.res.ObbInfo;
30import android.content.res.ObbScanner;
31import android.net.Uri;
32import android.os.Environment;
33import android.os.IBinder;
34import android.os.ParcelFileDescriptor;
35import android.os.Process;
36import android.os.RemoteException;
37import android.os.ServiceManager;
38import android.os.StatFs;
39import android.app.IntentService;
40import android.util.DisplayMetrics;
41import android.util.Log;
42import android.util.Pair;
43
44import java.io.File;
45import java.io.FileInputStream;
46import java.io.FileNotFoundException;
47import java.io.FileOutputStream;
48import java.io.IOException;
49import java.io.InputStream;
50import java.util.LinkedList;
51import java.util.List;
52import java.util.zip.ZipEntry;
53import java.util.zip.ZipException;
54import java.util.zip.ZipFile;
55
56import android.os.FileUtils;
57import android.provider.Settings;
58
59/*
60 * This service copies a downloaded apk to a file passed in as
61 * a ParcelFileDescriptor or to a newly created container specified
62 * by parameters. The DownloadManager gives access to this process
63 * based on its uid. This process also needs the ACCESS_DOWNLOAD_MANAGER
64 * permission to access apks downloaded via the download manager.
65 */
66public class DefaultContainerService extends IntentService {
67    private static final String TAG = "DefContainer";
68    private static final boolean localLOGV = true;
69
70    private static final String LIB_DIR_NAME = "lib";
71
72    private IMediaContainerService.Stub mBinder = new IMediaContainerService.Stub() {
73        /*
74         * Creates a new container and copies resource there.
75         * @param paackageURI the uri of resource to be copied. Can be either
76         * a content uri or a file uri
77         * @param cid the id of the secure container that should
78         * be used for creating a secure container into which the resource
79         * will be copied.
80         * @param key Refers to key used for encrypting the secure container
81         * @param resFileName Name of the target resource file(relative to newly
82         * created secure container)
83         * @return Returns the new cache path where the resource has been copied into
84         *
85         */
86        public String copyResourceToContainer(final Uri packageURI,
87                final String cid,
88                final String key, final String resFileName) {
89            if (packageURI == null || cid == null) {
90                return null;
91            }
92            return copyResourceInner(packageURI, cid, key, resFileName);
93        }
94
95        /*
96         * Copy specified resource to output stream
97         * @param packageURI the uri of resource to be copied. Should be a
98         * file uri
99         * @param outStream Remote file descriptor to be used for copying
100         * @return Returns true if copy succeded or false otherwise.
101         */
102        public boolean copyResource(final Uri packageURI,
103                ParcelFileDescriptor outStream) {
104            if (packageURI == null ||  outStream == null) {
105                return false;
106            }
107            ParcelFileDescriptor.AutoCloseOutputStream
108            autoOut = new ParcelFileDescriptor.AutoCloseOutputStream(outStream);
109            return copyFile(packageURI, autoOut);
110        }
111
112        /*
113         * Determine the recommended install location for package
114         * specified by file uri location.
115         * @param fileUri the uri of resource to be copied. Should be a
116         * file uri
117         * @return Returns PackageInfoLite object containing
118         * the package info and recommended app location.
119         */
120        public PackageInfoLite getMinimalPackageInfo(final Uri fileUri, int flags) {
121            PackageInfoLite ret = new PackageInfoLite();
122            if (fileUri == null) {
123                Log.i(TAG, "Invalid package uri " + fileUri);
124                ret.recommendedInstallLocation = PackageHelper.RECOMMEND_FAILED_INVALID_APK;
125                return ret;
126            }
127            String scheme = fileUri.getScheme();
128            if (scheme != null && !scheme.equals("file")) {
129                Log.w(TAG, "Falling back to installing on internal storage only");
130                ret.recommendedInstallLocation = PackageHelper.RECOMMEND_INSTALL_INTERNAL;
131                return ret;
132            }
133            String archiveFilePath = fileUri.getPath();
134            PackageParser packageParser = new PackageParser(archiveFilePath);
135            File sourceFile = new File(archiveFilePath);
136            DisplayMetrics metrics = new DisplayMetrics();
137            metrics.setToDefaults();
138            PackageParser.PackageLite pkg = packageParser.parsePackageLite(
139                    archiveFilePath, 0);
140            // Nuke the parser reference right away and force a gc
141            packageParser = null;
142            Runtime.getRuntime().gc();
143            if (pkg == null) {
144                Log.w(TAG, "Failed to parse package");
145                ret.recommendedInstallLocation = PackageHelper.RECOMMEND_FAILED_INVALID_APK;
146                return ret;
147            }
148            ret.packageName = pkg.packageName;
149            ret.installLocation = pkg.installLocation;
150            ret.recommendedInstallLocation = recommendAppInstallLocation(pkg.installLocation, archiveFilePath, flags);
151            return ret;
152        }
153
154        public boolean checkFreeStorage(boolean external, Uri fileUri) {
155            return checkFreeStorageInner(external, fileUri);
156        }
157
158        public ObbInfo getObbInfo(String filename) {
159            try {
160                return ObbScanner.getObbInfo(filename);
161            } catch (IOException e) {
162                Log.d(TAG, "Couldn't get OBB info for " + filename);
163                return null;
164            }
165        }
166
167        @Override
168        public long calculateDirectorySize(String path) throws RemoteException {
169            final File directory = new File(path);
170            if (directory.exists() && directory.isDirectory()) {
171                return MeasurementUtils.measureDirectory(path);
172            } else {
173                return 0L;
174            }
175        }
176    };
177
178    public DefaultContainerService() {
179        super("DefaultContainerService");
180        setIntentRedelivery(true);
181    }
182
183    @Override
184    protected void onHandleIntent(Intent intent) {
185        if (PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE.equals(intent.getAction())) {
186            IPackageManager pm = IPackageManager.Stub.asInterface(
187                    ServiceManager.getService("package"));
188            String pkg = null;
189            try {
190                while ((pkg=pm.nextPackageToClean(pkg)) != null) {
191                    eraseFiles(Environment.getExternalStorageAppDataDirectory(pkg));
192                    eraseFiles(Environment.getExternalStorageAppMediaDirectory(pkg));
193                }
194            } catch (RemoteException e) {
195            }
196        }
197    }
198
199    void eraseFiles(File path) {
200        if (path.isDirectory()) {
201            String[] files = path.list();
202            if (files != null) {
203                for (String file : files) {
204                    eraseFiles(new File(path, file));
205                }
206            }
207        }
208        path.delete();
209    }
210
211    public IBinder onBind(Intent intent) {
212        return mBinder;
213    }
214
215    private String copyResourceInner(Uri packageURI, String newCid, String key, String resFileName) {
216        // Make sure the sdcard is mounted.
217        String status = Environment.getExternalStorageState();
218        if (!status.equals(Environment.MEDIA_MOUNTED)) {
219            Log.w(TAG, "Make sure sdcard is mounted.");
220            return null;
221        }
222
223        // The .apk file
224        String codePath = packageURI.getPath();
225        File codeFile = new File(codePath);
226
227        // Calculate size of container needed to hold base APK.
228        long sizeBytes = codeFile.length();
229
230        // Check all the native files that need to be copied and add that to the container size.
231        ZipFile zipFile;
232        List<Pair<ZipEntry, String>> nativeFiles;
233        try {
234            zipFile = new ZipFile(codeFile);
235
236            nativeFiles = new LinkedList<Pair<ZipEntry, String>>();
237
238            NativeLibraryHelper.listPackageNativeBinariesLI(zipFile, nativeFiles);
239
240            final int N = nativeFiles.size();
241            for (int i = 0; i < N; i++) {
242                final Pair<ZipEntry, String> entry = nativeFiles.get(i);
243
244                /*
245                 * Note that PackageHelper.createSdDir adds a 1MB padding on
246                 * our claimed size, so we don't have to worry about block
247                 * alignment here.
248                 */
249                sizeBytes += entry.first.getSize();
250            }
251        } catch (ZipException e) {
252            Log.w(TAG, "Failed to extract data from package file", e);
253            return null;
254        } catch (IOException e) {
255            Log.w(TAG, "Failed to cache package shared libs", e);
256            return null;
257        }
258
259        // Create new container
260        String newCachePath = null;
261        if ((newCachePath = PackageHelper.createSdDir(sizeBytes, newCid, key, Process.myUid())) == null) {
262            Log.e(TAG, "Failed to create container " + newCid);
263            return null;
264        }
265        if (localLOGV)
266            Log.i(TAG, "Created container for " + newCid + " at path : " + newCachePath);
267        File resFile = new File(newCachePath, resFileName);
268        if (!FileUtils.copyFile(new File(codePath), resFile)) {
269            Log.e(TAG, "Failed to copy " + codePath + " to " + resFile);
270            // Clean up container
271            PackageHelper.destroySdDir(newCid);
272            return null;
273        }
274
275        try {
276            File sharedLibraryDir = new File(newCachePath, LIB_DIR_NAME);
277            sharedLibraryDir.mkdir();
278
279            final int N = nativeFiles.size();
280            for (int i = 0; i < N; i++) {
281                final Pair<ZipEntry, String> entry = nativeFiles.get(i);
282
283                InputStream is = zipFile.getInputStream(entry.first);
284                try {
285                    File destFile = new File(sharedLibraryDir, entry.second);
286                    if (!FileUtils.copyToFile(is, destFile)) {
287                        throw new IOException("Couldn't copy native binary "
288                                + entry.first.getName() + " to " + entry.second);
289                    }
290                } finally {
291                    is.close();
292                }
293            }
294        } catch (IOException e) {
295            Log.e(TAG, "Couldn't copy native file to container", e);
296            PackageHelper.destroySdDir(newCid);
297            return null;
298        }
299
300        if (localLOGV) Log.i(TAG, "Copied " + codePath + " to " + resFile);
301        if (!PackageHelper.finalizeSdDir(newCid)) {
302            Log.e(TAG, "Failed to finalize " + newCid + " at path " + newCachePath);
303            // Clean up container
304            PackageHelper.destroySdDir(newCid);
305        }
306        if (localLOGV) Log.i(TAG, "Finalized container " + newCid);
307        if (PackageHelper.isContainerMounted(newCid)) {
308            if (localLOGV) Log.i(TAG, "Unmounting " + newCid +
309                    " at path " + newCachePath);
310            // Force a gc to avoid being killed.
311            Runtime.getRuntime().gc();
312            PackageHelper.unMountSdDir(newCid);
313        } else {
314            if (localLOGV) Log.i(TAG, "Container " + newCid + " not mounted");
315        }
316        return newCachePath;
317    }
318
319    public static boolean copyToFile(InputStream inputStream, FileOutputStream out) {
320        try {
321            byte[] buffer = new byte[4096];
322            int bytesRead;
323            while ((bytesRead = inputStream.read(buffer)) >= 0) {
324                out.write(buffer, 0, bytesRead);
325            }
326            return true;
327        } catch (IOException e) {
328            Log.i(TAG, "Exception : " + e + " when copying file");
329            return false;
330        }
331    }
332
333    public static boolean copyToFile(File srcFile, FileOutputStream out) {
334        InputStream inputStream = null;
335        try {
336            inputStream = new FileInputStream(srcFile);
337            return copyToFile(inputStream, out);
338        } catch (IOException e) {
339            return false;
340        } finally {
341            try { if (inputStream != null) inputStream.close(); } catch (IOException e) {}
342        }
343    }
344
345    private  boolean copyFile(Uri pPackageURI, FileOutputStream outStream) {
346        String scheme = pPackageURI.getScheme();
347        if (scheme == null || scheme.equals("file")) {
348            final File srcPackageFile = new File(pPackageURI.getPath());
349            // We copy the source package file to a temp file and then rename it to the
350            // destination file in order to eliminate a window where the package directory
351            // scanner notices the new package file but it's not completely copied yet.
352            if (!copyToFile(srcPackageFile, outStream)) {
353                Log.e(TAG, "Couldn't copy file: " + srcPackageFile);
354                return false;
355            }
356        } else if (scheme.equals("content")) {
357            ParcelFileDescriptor fd = null;
358            try {
359                fd = getContentResolver().openFileDescriptor(pPackageURI, "r");
360            } catch (FileNotFoundException e) {
361                Log.e(TAG, "Couldn't open file descriptor from download service. Failed with exception " + e);
362                return false;
363            }
364            if (fd == null) {
365                Log.e(TAG, "Couldn't open file descriptor from download service (null).");
366                return false;
367            } else {
368                if (localLOGV) {
369                    Log.v(TAG, "Opened file descriptor from download service.");
370                }
371                ParcelFileDescriptor.AutoCloseInputStream
372                dlStream = new ParcelFileDescriptor.AutoCloseInputStream(fd);
373                // We copy the source package file to a temp file and then rename it to the
374                // destination file in order to eliminate a window where the package directory
375                // scanner notices the new package file but it's not completely copied yet.
376                if (!copyToFile(dlStream, outStream)) {
377                    Log.e(TAG, "Couldn't copy " + pPackageURI + " to temp file.");
378                    return false;
379                }
380            }
381        } else {
382            Log.e(TAG, "Package URI is not 'file:' or 'content:' - " + pPackageURI);
383            return false;
384        }
385        return true;
386    }
387
388    // Constants related to app heuristics
389    // No-installation limit for internal flash: 10% or less space available
390    private static final double LOW_NAND_FLASH_TRESHOLD = 0.1;
391
392    // SD-to-internal app size threshold: currently set to 1 MB
393    private static final long INSTALL_ON_SD_THRESHOLD = (1024 * 1024);
394    private static final int ERR_LOC = -1;
395
396    private int recommendAppInstallLocation(int installLocation,
397            String archiveFilePath, int flags) {
398        boolean checkInt = false;
399        boolean checkExt = false;
400        boolean checkBoth = false;
401        check_inner : {
402            // Check flags.
403            if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
404                // Check for forward locked app
405                checkInt = true;
406                break check_inner;
407            } else if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
408                // Explicit flag to install internally.
409                // Check internal storage and return
410                checkInt = true;
411                break check_inner;
412            } else if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
413                // Explicit flag to install externally.
414                // Check external storage and return
415                checkExt = true;
416                break check_inner;
417            }
418            // Check for manifest option
419            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
420                checkInt = true;
421                break check_inner;
422            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
423                checkExt = true;
424                checkBoth = true;
425                break check_inner;
426            } else if (installLocation == PackageInfo.INSTALL_LOCATION_AUTO) {
427                checkInt = true;
428                checkBoth = true;
429                break check_inner;
430            }
431            // Pick user preference
432            int installPreference = Settings.System.getInt(getApplicationContext()
433                    .getContentResolver(),
434                    Settings.Secure.DEFAULT_INSTALL_LOCATION,
435                    PackageHelper.APP_INSTALL_AUTO);
436            if (installPreference == PackageHelper.APP_INSTALL_INTERNAL) {
437                checkInt = true;
438                break check_inner;
439            } else if (installPreference == PackageHelper.APP_INSTALL_EXTERNAL) {
440                checkExt = true;
441                break check_inner;
442            }
443            // Fall back to default policy if nothing else is specified.
444            checkInt = true;
445        }
446
447        // Package size = code size + cache size + data size
448        // If code size > 1 MB, install on SD card.
449        // Else install on internal NAND flash, unless space on NAND is less than 10%
450        String status = Environment.getExternalStorageState();
451        long availSDSize = -1;
452        boolean mediaAvailable = false;
453        if (!Environment.isExternalStorageEmulated() && status.equals(Environment.MEDIA_MOUNTED)) {
454            StatFs sdStats = new StatFs(
455                    Environment.getExternalStorageDirectory().getPath());
456            availSDSize = (long)sdStats.getAvailableBlocks() *
457                    (long)sdStats.getBlockSize();
458            mediaAvailable = true;
459        }
460        StatFs internalStats = new StatFs(Environment.getDataDirectory().getPath());
461        long totalInternalSize = (long)internalStats.getBlockCount() *
462                (long)internalStats.getBlockSize();
463        long availInternalSize = (long)internalStats.getAvailableBlocks() *
464                (long)internalStats.getBlockSize();
465
466        double pctNandFree = (double)availInternalSize / (double)totalInternalSize;
467
468        File apkFile = new File(archiveFilePath);
469        long pkgLen = apkFile.length();
470
471        // To make final copy
472        long reqInstallSize = pkgLen;
473        // For dex files. Just ignore and fail when extracting. Max limit of 2Gig for now.
474        long reqInternalSize = 0;
475        boolean intThresholdOk = (pctNandFree >= LOW_NAND_FLASH_TRESHOLD);
476        boolean intAvailOk = ((reqInstallSize + reqInternalSize) < availInternalSize);
477        boolean fitsOnSd = false;
478        if (mediaAvailable && (reqInstallSize < availSDSize)) {
479            // If we do not have an internal size requirement
480            // don't do a threshold check.
481            if (reqInternalSize == 0) {
482                fitsOnSd = true;
483            } else if ((reqInternalSize < availInternalSize) && intThresholdOk) {
484                fitsOnSd = true;
485            }
486        }
487        boolean fitsOnInt = intThresholdOk && intAvailOk;
488        if (checkInt) {
489            // Check for internal memory availability
490            if (fitsOnInt) {
491                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
492            }
493        } else if (checkExt) {
494            if (fitsOnSd) {
495                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
496            }
497        }
498        if (checkBoth) {
499            // Check for internal first
500            if (fitsOnInt) {
501                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
502            }
503            // Check for external next
504            if (fitsOnSd) {
505                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
506            }
507        }
508        if ((checkExt || checkBoth) && !mediaAvailable) {
509            return PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE;
510        }
511        return PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
512    }
513
514    private boolean checkFreeStorageInner(boolean external, Uri packageURI) {
515        File apkFile = new File(packageURI.getPath());
516        long size = apkFile.length();
517        if (external) {
518            String status = Environment.getExternalStorageState();
519            long availSDSize = -1;
520            if (status.equals(Environment.MEDIA_MOUNTED)) {
521                StatFs sdStats = new StatFs(
522                        Environment.getExternalStorageDirectory().getPath());
523                availSDSize = (long)sdStats.getAvailableBlocks() *
524                (long)sdStats.getBlockSize();
525            }
526            return availSDSize > size;
527        }
528        StatFs internalStats = new StatFs(Environment.getDataDirectory().getPath());
529        long totalInternalSize = (long)internalStats.getBlockCount() *
530        (long)internalStats.getBlockSize();
531        long availInternalSize = (long)internalStats.getAvailableBlocks() *
532        (long)internalStats.getBlockSize();
533
534        double pctNandFree = (double)availInternalSize / (double)totalInternalSize;
535        // To make final copy
536        long reqInstallSize = size;
537        // For dex files. Just ignore and fail when extracting. Max limit of 2Gig for now.
538        long reqInternalSize = 0;
539        boolean intThresholdOk = (pctNandFree >= LOW_NAND_FLASH_TRESHOLD);
540        boolean intAvailOk = ((reqInstallSize + reqInternalSize) < availInternalSize);
541        return intThresholdOk && intAvailOk;
542    }
543}
544