DefaultContainerService.java revision aa183e2c9a279cb6aef7dc77855facfae795b6f8
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 directory) throws RemoteException {
169            return MeasurementUtils.measureDirectory(directory);
170        }
171    };
172
173    public DefaultContainerService() {
174        super("DefaultContainerService");
175        setIntentRedelivery(true);
176    }
177
178    @Override
179    protected void onHandleIntent(Intent intent) {
180        if (PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE.equals(intent.getAction())) {
181            IPackageManager pm = IPackageManager.Stub.asInterface(
182                    ServiceManager.getService("package"));
183            String pkg = null;
184            try {
185                while ((pkg=pm.nextPackageToClean(pkg)) != null) {
186                    eraseFiles(Environment.getExternalStorageAppDataDirectory(pkg));
187                    eraseFiles(Environment.getExternalStorageAppMediaDirectory(pkg));
188                }
189            } catch (RemoteException e) {
190            }
191        }
192    }
193
194    void eraseFiles(File path) {
195        if (path.isDirectory()) {
196            String[] files = path.list();
197            if (files != null) {
198                for (String file : files) {
199                    eraseFiles(new File(path, file));
200                }
201            }
202        }
203        path.delete();
204    }
205
206    public IBinder onBind(Intent intent) {
207        return mBinder;
208    }
209
210    private String copyResourceInner(Uri packageURI, String newCid, String key, String resFileName) {
211        // Make sure the sdcard is mounted.
212        String status = Environment.getExternalStorageState();
213        if (!status.equals(Environment.MEDIA_MOUNTED)) {
214            Log.w(TAG, "Make sure sdcard is mounted.");
215            return null;
216        }
217
218        // The .apk file
219        String codePath = packageURI.getPath();
220        File codeFile = new File(codePath);
221
222        // Calculate size of container needed to hold base APK.
223        long sizeBytes = codeFile.length();
224
225        // Check all the native files that need to be copied and add that to the container size.
226        ZipFile zipFile;
227        List<Pair<ZipEntry, String>> nativeFiles;
228        try {
229            zipFile = new ZipFile(codeFile);
230
231            nativeFiles = new LinkedList<Pair<ZipEntry, String>>();
232
233            NativeLibraryHelper.listPackageNativeBinariesLI(zipFile, nativeFiles);
234
235            final int N = nativeFiles.size();
236            for (int i = 0; i < N; i++) {
237                final Pair<ZipEntry, String> entry = nativeFiles.get(i);
238
239                /*
240                 * Note that PackageHelper.createSdDir adds a 1MB padding on
241                 * our claimed size, so we don't have to worry about block
242                 * alignment here.
243                 */
244                sizeBytes += entry.first.getSize();
245            }
246        } catch (ZipException e) {
247            Log.w(TAG, "Failed to extract data from package file", e);
248            return null;
249        } catch (IOException e) {
250            Log.w(TAG, "Failed to cache package shared libs", e);
251            return null;
252        }
253
254        // Create new container
255        String newCachePath = null;
256        if ((newCachePath = PackageHelper.createSdDir(sizeBytes, newCid, key, Process.myUid())) == null) {
257            Log.e(TAG, "Failed to create container " + newCid);
258            return null;
259        }
260        if (localLOGV)
261            Log.i(TAG, "Created container for " + newCid + " at path : " + newCachePath);
262        File resFile = new File(newCachePath, resFileName);
263        if (!FileUtils.copyFile(new File(codePath), resFile)) {
264            Log.e(TAG, "Failed to copy " + codePath + " to " + resFile);
265            // Clean up container
266            PackageHelper.destroySdDir(newCid);
267            return null;
268        }
269
270        try {
271            File sharedLibraryDir = new File(newCachePath, LIB_DIR_NAME);
272            sharedLibraryDir.mkdir();
273
274            final int N = nativeFiles.size();
275            for (int i = 0; i < N; i++) {
276                final Pair<ZipEntry, String> entry = nativeFiles.get(i);
277
278                InputStream is = zipFile.getInputStream(entry.first);
279                try {
280                    File destFile = new File(sharedLibraryDir, entry.second);
281                    if (!FileUtils.copyToFile(is, destFile)) {
282                        throw new IOException("Couldn't copy native binary "
283                                + entry.first.getName() + " to " + entry.second);
284                    }
285                } finally {
286                    is.close();
287                }
288            }
289        } catch (IOException e) {
290            Log.e(TAG, "Couldn't copy native file to container", e);
291            PackageHelper.destroySdDir(newCid);
292            return null;
293        }
294
295        if (localLOGV) Log.i(TAG, "Copied " + codePath + " to " + resFile);
296        if (!PackageHelper.finalizeSdDir(newCid)) {
297            Log.e(TAG, "Failed to finalize " + newCid + " at path " + newCachePath);
298            // Clean up container
299            PackageHelper.destroySdDir(newCid);
300        }
301        if (localLOGV) Log.i(TAG, "Finalized container " + newCid);
302        if (PackageHelper.isContainerMounted(newCid)) {
303            if (localLOGV) Log.i(TAG, "Unmounting " + newCid +
304                    " at path " + newCachePath);
305            // Force a gc to avoid being killed.
306            Runtime.getRuntime().gc();
307            PackageHelper.unMountSdDir(newCid);
308        } else {
309            if (localLOGV) Log.i(TAG, "Container " + newCid + " not mounted");
310        }
311        return newCachePath;
312    }
313
314    public static boolean copyToFile(InputStream inputStream, FileOutputStream out) {
315        try {
316            byte[] buffer = new byte[4096];
317            int bytesRead;
318            while ((bytesRead = inputStream.read(buffer)) >= 0) {
319                out.write(buffer, 0, bytesRead);
320            }
321            return true;
322        } catch (IOException e) {
323            Log.i(TAG, "Exception : " + e + " when copying file");
324            return false;
325        }
326    }
327
328    public static boolean copyToFile(File srcFile, FileOutputStream out) {
329        InputStream inputStream = null;
330        try {
331            inputStream = new FileInputStream(srcFile);
332            return copyToFile(inputStream, out);
333        } catch (IOException e) {
334            return false;
335        } finally {
336            try { if (inputStream != null) inputStream.close(); } catch (IOException e) {}
337        }
338    }
339
340    private  boolean copyFile(Uri pPackageURI, FileOutputStream outStream) {
341        String scheme = pPackageURI.getScheme();
342        if (scheme == null || scheme.equals("file")) {
343            final File srcPackageFile = new File(pPackageURI.getPath());
344            // We copy the source package file to a temp file and then rename it to the
345            // destination file in order to eliminate a window where the package directory
346            // scanner notices the new package file but it's not completely copied yet.
347            if (!copyToFile(srcPackageFile, outStream)) {
348                Log.e(TAG, "Couldn't copy file: " + srcPackageFile);
349                return false;
350            }
351        } else if (scheme.equals("content")) {
352            ParcelFileDescriptor fd = null;
353            try {
354                fd = getContentResolver().openFileDescriptor(pPackageURI, "r");
355            } catch (FileNotFoundException e) {
356                Log.e(TAG, "Couldn't open file descriptor from download service. Failed with exception " + e);
357                return false;
358            }
359            if (fd == null) {
360                Log.e(TAG, "Couldn't open file descriptor from download service (null).");
361                return false;
362            } else {
363                if (localLOGV) {
364                    Log.v(TAG, "Opened file descriptor from download service.");
365                }
366                ParcelFileDescriptor.AutoCloseInputStream
367                dlStream = new ParcelFileDescriptor.AutoCloseInputStream(fd);
368                // We copy the source package file to a temp file and then rename it to the
369                // destination file in order to eliminate a window where the package directory
370                // scanner notices the new package file but it's not completely copied yet.
371                if (!copyToFile(dlStream, outStream)) {
372                    Log.e(TAG, "Couldn't copy " + pPackageURI + " to temp file.");
373                    return false;
374                }
375            }
376        } else {
377            Log.e(TAG, "Package URI is not 'file:' or 'content:' - " + pPackageURI);
378            return false;
379        }
380        return true;
381    }
382
383    // Constants related to app heuristics
384    // No-installation limit for internal flash: 10% or less space available
385    private static final double LOW_NAND_FLASH_TRESHOLD = 0.1;
386
387    // SD-to-internal app size threshold: currently set to 1 MB
388    private static final long INSTALL_ON_SD_THRESHOLD = (1024 * 1024);
389    private static final int ERR_LOC = -1;
390
391    private int recommendAppInstallLocation(int installLocation,
392            String archiveFilePath, int flags) {
393        boolean checkInt = false;
394        boolean checkExt = false;
395        boolean checkBoth = false;
396        check_inner : {
397            // Check flags.
398            if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
399                // Check for forward locked app
400                checkInt = true;
401                break check_inner;
402            } else if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
403                // Explicit flag to install internally.
404                // Check internal storage and return
405                checkInt = true;
406                break check_inner;
407            } else if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
408                // Explicit flag to install externally.
409                // Check external storage and return
410                checkExt = true;
411                break check_inner;
412            }
413            // Check for manifest option
414            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
415                checkInt = true;
416                break check_inner;
417            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
418                checkExt = true;
419                checkBoth = true;
420                break check_inner;
421            } else if (installLocation == PackageInfo.INSTALL_LOCATION_AUTO) {
422                checkInt = true;
423                checkBoth = true;
424                break check_inner;
425            }
426            // Pick user preference
427            int installPreference = Settings.System.getInt(getApplicationContext()
428                    .getContentResolver(),
429                    Settings.Secure.DEFAULT_INSTALL_LOCATION,
430                    PackageHelper.APP_INSTALL_AUTO);
431            if (installPreference == PackageHelper.APP_INSTALL_INTERNAL) {
432                checkInt = true;
433                break check_inner;
434            } else if (installPreference == PackageHelper.APP_INSTALL_EXTERNAL) {
435                checkExt = true;
436                break check_inner;
437            }
438            // Fall back to default policy if nothing else is specified.
439            checkInt = true;
440        }
441
442        // Package size = code size + cache size + data size
443        // If code size > 1 MB, install on SD card.
444        // Else install on internal NAND flash, unless space on NAND is less than 10%
445        String status = Environment.getExternalStorageState();
446        long availSDSize = -1;
447        boolean mediaAvailable = false;
448        if (!Environment.isExternalStorageEmulated() && status.equals(Environment.MEDIA_MOUNTED)) {
449            StatFs sdStats = new StatFs(
450                    Environment.getExternalStorageDirectory().getPath());
451            availSDSize = (long)sdStats.getAvailableBlocks() *
452                    (long)sdStats.getBlockSize();
453            mediaAvailable = true;
454        }
455        StatFs internalStats = new StatFs(Environment.getDataDirectory().getPath());
456        long totalInternalSize = (long)internalStats.getBlockCount() *
457                (long)internalStats.getBlockSize();
458        long availInternalSize = (long)internalStats.getAvailableBlocks() *
459                (long)internalStats.getBlockSize();
460
461        double pctNandFree = (double)availInternalSize / (double)totalInternalSize;
462
463        File apkFile = new File(archiveFilePath);
464        long pkgLen = apkFile.length();
465
466        // To make final copy
467        long reqInstallSize = pkgLen;
468        // For dex files. Just ignore and fail when extracting. Max limit of 2Gig for now.
469        long reqInternalSize = 0;
470        boolean intThresholdOk = (pctNandFree >= LOW_NAND_FLASH_TRESHOLD);
471        boolean intAvailOk = ((reqInstallSize + reqInternalSize) < availInternalSize);
472        boolean fitsOnSd = false;
473        if (mediaAvailable && (reqInstallSize < availSDSize)) {
474            // If we do not have an internal size requirement
475            // don't do a threshold check.
476            if (reqInternalSize == 0) {
477                fitsOnSd = true;
478            } else if ((reqInternalSize < availInternalSize) && intThresholdOk) {
479                fitsOnSd = true;
480            }
481        }
482        boolean fitsOnInt = intThresholdOk && intAvailOk;
483        if (checkInt) {
484            // Check for internal memory availability
485            if (fitsOnInt) {
486                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
487            }
488        } else if (checkExt) {
489            if (fitsOnSd) {
490                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
491            }
492        }
493        if (checkBoth) {
494            // Check for internal first
495            if (fitsOnInt) {
496                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
497            }
498            // Check for external next
499            if (fitsOnSd) {
500                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
501            }
502        }
503        if ((checkExt || checkBoth) && !mediaAvailable) {
504            return PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE;
505        }
506        return PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
507    }
508
509    private boolean checkFreeStorageInner(boolean external, Uri packageURI) {
510        File apkFile = new File(packageURI.getPath());
511        long size = apkFile.length();
512        if (external) {
513            String status = Environment.getExternalStorageState();
514            long availSDSize = -1;
515            if (status.equals(Environment.MEDIA_MOUNTED)) {
516                StatFs sdStats = new StatFs(
517                        Environment.getExternalStorageDirectory().getPath());
518                availSDSize = (long)sdStats.getAvailableBlocks() *
519                (long)sdStats.getBlockSize();
520            }
521            return availSDSize > size;
522        }
523        StatFs internalStats = new StatFs(Environment.getDataDirectory().getPath());
524        long totalInternalSize = (long)internalStats.getBlockCount() *
525        (long)internalStats.getBlockSize();
526        long availInternalSize = (long)internalStats.getAvailableBlocks() *
527        (long)internalStats.getBlockSize();
528
529        double pctNandFree = (double)availInternalSize / (double)totalInternalSize;
530        // To make final copy
531        long reqInstallSize = size;
532        // For dex files. Just ignore and fail when extracting. Max limit of 2Gig for now.
533        long reqInternalSize = 0;
534        boolean intThresholdOk = (pctNandFree >= LOW_NAND_FLASH_TRESHOLD);
535        boolean intAvailOk = ((reqInstallSize + reqInternalSize) < availInternalSize);
536        return intThresholdOk && intAvailOk;
537    }
538}
539