blob: f68d1a9f2f55960a6c2d270bd5359a0b3625fcf8 [file] [log] [blame]
Kenny Root15a4d2f2010-03-11 18:20:12 -08001/*
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
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080017package com.android.defcontainer;
18
Kenny Rootf5121a92011-08-10 16:23:32 -070019import android.app.IntentService;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080020import android.content.Intent;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -070021import android.content.pm.ContainerEncryptionParams;
Dianne Hackborne83cefce2010-02-04 17:38:14 -080022import android.content.pm.IPackageManager;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -070023import android.content.pm.LimitedLengthInputStream;
Jeff Sharkey63d0a062013-03-01 16:12:55 -080024import android.content.pm.MacAuthenticatedInputStream;
Dianne Hackborn7767eac2012-08-23 18:25:40 -070025import android.content.pm.PackageCleanItem;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080026import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080027import android.content.pm.PackageInfoLite;
Dianne Hackborne83cefce2010-02-04 17:38:14 -080028import android.content.pm.PackageManager;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080029import android.content.pm.PackageParser;
Kenny Roota02b8b02010-08-05 16:14:17 -070030import android.content.res.ObbInfo;
31import android.content.res.ObbScanner;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080032import android.net.Uri;
Dianne Hackborne83cefce2010-02-04 17:38:14 -080033import android.os.Environment;
Jeff Sharkey752cd922012-09-23 16:25:12 -070034import android.os.Environment.UserEnvironment;
Kenny Rootf5121a92011-08-10 16:23:32 -070035import android.os.FileUtils;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080036import android.os.IBinder;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080037import android.os.ParcelFileDescriptor;
38import android.os.Process;
39import android.os.RemoteException;
40import android.os.ServiceManager;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080041import android.os.StatFs;
Kenny Rootf5121a92011-08-10 16:23:32 -070042import android.provider.Settings;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080043import android.util.DisplayMetrics;
Kenny Root1ebd74a2011-08-03 15:09:44 -070044import android.util.Slog;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080045
Jeff Sharkey63d0a062013-03-01 16:12:55 -080046import com.android.internal.app.IMediaContainerService;
47import com.android.internal.content.NativeLibraryHelper;
48import com.android.internal.content.PackageHelper;
49
Kenny Rootf5121a92011-08-10 16:23:32 -070050import java.io.BufferedInputStream;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080051import java.io.File;
52import java.io.FileInputStream;
53import java.io.FileNotFoundException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080054import java.io.IOException;
55import java.io.InputStream;
Kenny Rootf5121a92011-08-10 16:23:32 -070056import java.io.OutputStream;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -070057import 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;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080067
Jeff Sharkey9cbe986a2012-04-22 18:56:43 -070068import libcore.io.ErrnoException;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -070069import libcore.io.IoUtils;
Jeff Sharkey9cbe986a2012-04-22 18:56:43 -070070import libcore.io.Libcore;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -070071import libcore.io.Streams;
Elliott Hughesbefd0b12013-07-09 14:46:18 -070072import libcore.io.StructStatVfs;
Jeff Sharkey9cbe986a2012-04-22 18:56:43 -070073
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080074/*
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 */
Dianne Hackborne83cefce2010-02-04 17:38:14 -080081public class DefaultContainerService extends IntentService {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080082 private static final String TAG = "DefContainer";
Dianne Hackborn40e9f292012-11-27 19:12:23 -080083 private static final boolean localLOGV = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080084
Kenny Root85387d72010-08-26 10:13:11 -070085 private static final String LIB_DIR_NAME = "lib";
86
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080087 private IMediaContainerService.Stub mBinder = new IMediaContainerService.Stub() {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -070088 /**
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080089 * 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
Suchi Amalapurapu679bba32010-02-16 11:52:44 -080092 * @param cid the id of the secure container that should
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080093 * 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 */
Kenny Root6dceb882012-04-12 14:23:49 -0700101 public String copyResourceToContainer(final Uri packageURI, final String cid,
102 final String key, final String resFileName, final String publicResFileName,
103 boolean isExternal, boolean isForwardLocked) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -0800104 if (packageURI == null || cid == null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800105 return null;
106 }
Kenny Root6dceb882012-04-12 14:23:49 -0700107
108 return copyResourceInner(packageURI, cid, key, resFileName, publicResFileName,
109 isExternal, isForwardLocked);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800110 }
111
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700112 /**
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800113 * Copy specified resource to output stream
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700114 *
Kenny Rootf5121a92011-08-10 16:23:32 -0700115 * @param packageURI the uri of resource to be copied. Should be a file
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700116 * uri
117 * @param encryptionParams parameters describing the encryption used for
118 * this file
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800119 * @param outStream Remote file descriptor to be used for copying
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700120 * @return returns status code according to those in
121 * {@link PackageManager}
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800122 */
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700123 public int copyResource(final Uri packageURI, ContainerEncryptionParams encryptionParams,
124 ParcelFileDescriptor outStream) {
Kenny Rootf5121a92011-08-10 16:23:32 -0700125 if (packageURI == null || outStream == null) {
126 return PackageManager.INSTALL_FAILED_INVALID_URI;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800127 }
Kenny Rootf5121a92011-08-10 16:23:32 -0700128
129 ParcelFileDescriptor.AutoCloseOutputStream autoOut
130 = new ParcelFileDescriptor.AutoCloseOutputStream(outStream);
131
132 try {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700133 copyFile(packageURI, autoOut, encryptionParams);
Kenny Rootf5121a92011-08-10 16:23:32 -0700134 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;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700143 } catch (DigestException e) {
144 Slog.e(TAG, "Could not copy URI " + packageURI.toString() + " Security: "
145 + e.getMessage());
146 return PackageManager.INSTALL_FAILED_INVALID_APK;
Jeff Sharkey5adb34f2013-04-25 11:35:12 -0700147 } finally {
148 IoUtils.closeQuietly(autoOut);
Kenny Rootf5121a92011-08-10 16:23:32 -0700149 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800150 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800151
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700152 /**
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800153 * Determine the recommended install location for package
154 * specified by file uri location.
155 * @param fileUri the uri of resource to be copied. Should be a
156 * file uri
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800157 * @return Returns PackageInfoLite object containing
158 * the package info and recommended app location.
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800159 */
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700160 public PackageInfoLite getMinimalPackageInfo(final String packagePath, int flags,
161 long threshold) {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800162 PackageInfoLite ret = new PackageInfoLite();
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700163
164 if (packagePath == null) {
165 Slog.i(TAG, "Invalid package file " + packagePath);
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800166 ret.recommendedInstallLocation = PackageHelper.RECOMMEND_FAILED_INVALID_APK;
167 return ret;
Suchi Amalapurapu3602f762010-03-03 17:29:33 -0800168 }
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700169
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800170 DisplayMetrics metrics = new DisplayMetrics();
171 metrics.setToDefaults();
Kenny Root1ebd74a2011-08-03 15:09:44 -0700172
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700173 PackageParser.PackageLite pkg = PackageParser.parsePackageLite(packagePath, 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800174 if (pkg == null) {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700175 Slog.w(TAG, "Failed to parse package");
176
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700177 final File apkFile = new File(packagePath);
Kenny Root1ebd74a2011-08-03 15:09:44 -0700178 if (!apkFile.exists()) {
179 ret.recommendedInstallLocation = PackageHelper.RECOMMEND_FAILED_INVALID_URI;
180 } else {
181 ret.recommendedInstallLocation = PackageHelper.RECOMMEND_FAILED_INVALID_APK;
182 }
183
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800184 return ret;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800185 }
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700186
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800187 ret.packageName = pkg.packageName;
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700188 ret.versionCode = pkg.versionCode;
Kenny Root930d3af2010-07-30 16:52:29 -0700189 ret.installLocation = pkg.installLocation;
Kenny Root05ca4c92011-09-15 10:36:25 -0700190 ret.verifiers = pkg.verifiers;
Kenny Root1ebd74a2011-08-03 15:09:44 -0700191
Kenny Root62e1b4e2011-03-14 17:13:39 -0700192 ret.recommendedInstallLocation = recommendAppInstallLocation(pkg.installLocation,
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700193 packagePath, flags, threshold);
Kenny Root1ebd74a2011-08-03 15:09:44 -0700194
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800195 return ret;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800196 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800197
Kenny Root62e1b4e2011-03-14 17:13:39 -0700198 @Override
Kenny Root6dceb882012-04-12 14:23:49 -0700199 public boolean checkInternalFreeStorage(Uri packageUri, boolean isForwardLocked,
200 long threshold) throws RemoteException {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700201 final File apkFile = new File(packageUri.getPath());
Kenny Root1ebd74a2011-08-03 15:09:44 -0700202 try {
Kenny Root6dceb882012-04-12 14:23:49 -0700203 return isUnderInternalThreshold(apkFile, isForwardLocked, threshold);
204 } catch (IOException e) {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700205 return true;
206 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700207 }
208
209 @Override
Kenny Root6dceb882012-04-12 14:23:49 -0700210 public boolean checkExternalFreeStorage(Uri packageUri, boolean isForwardLocked)
211 throws RemoteException {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700212 final File apkFile = new File(packageUri.getPath());
Kenny Root1ebd74a2011-08-03 15:09:44 -0700213 try {
Kenny Root6dceb882012-04-12 14:23:49 -0700214 return isUnderExternalThreshold(apkFile, isForwardLocked);
215 } catch (IOException e) {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700216 return true;
217 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800218 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700219
220 public ObbInfo getObbInfo(String filename) {
Kenny Root05105f72010-09-22 17:29:43 -0700221 try {
222 return ObbScanner.getObbInfo(filename);
223 } catch (IOException e) {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700224 Slog.d(TAG, "Couldn't get OBB info for " + filename);
Kenny Root05105f72010-09-22 17:29:43 -0700225 return null;
226 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700227 }
Kenny Rootaa183e22010-12-02 18:00:38 -0800228
229 @Override
Kenny Root366949c2011-01-14 17:18:14 -0800230 public long calculateDirectorySize(String path) throws RemoteException {
Kenny Roota69b7eb2012-05-14 14:47:06 -0700231 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
232
Jeff Sharkey63d0a062013-03-01 16:12:55 -0800233 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);
Kenny Root366949c2011-01-14 17:18:14 -0800237 } else {
238 return 0L;
239 }
Kenny Rootaa183e22010-12-02 18:00:38 -0800240 }
Jeff Sharkey9cbe986a2012-04-22 18:56:43 -0700241
242 @Override
243 public long[] getFileSystemStats(String path) {
Kenny Roota69b7eb2012-05-14 14:47:06 -0700244 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
245
Jeff Sharkey9cbe986a2012-04-22 18:56:43 -0700246 try {
Elliott Hughesbefd0b12013-07-09 14:46:18 -0700247 final StructStatVfs stat = Libcore.os.statvfs(path);
Jeff Sharkey9cbe986a2012-04-22 18:56:43 -0700248 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 }
Dianne Hackborn183ce022012-06-29 15:00:21 -0700255
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 }
Kenny Rootcea37432012-10-18 14:57:33 -0700265
266 @Override
267 public long calculateInstalledSize(String packagePath, boolean isForwardLocked)
268 throws RemoteException {
269 final File packageFile = new File(packagePath);
270 try {
271 return calculateContainerSize(packageFile, isForwardLocked) * 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 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800280 };
281
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800282 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())) {
Jeff Sharkey752cd922012-09-23 16:25:12 -0700290 final IPackageManager pm = IPackageManager.Stub.asInterface(
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800291 ServiceManager.getService("package"));
Jeff Sharkey752cd922012-09-23 16:25:12 -0700292 PackageCleanItem item = null;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800293 try {
Jeff Sharkey752cd922012-09-23 16:25:12 -0700294 while ((item = pm.nextPackageToClean(item)) != null) {
295 final UserEnvironment userEnv = new UserEnvironment(item.userId);
Jeff Sharkey7f392de2013-08-11 17:42:17 -0700296 eraseFiles(userEnv.buildExternalStorageAppDataDirs(item.packageName));
297 eraseFiles(userEnv.buildExternalStorageAppMediaDirs(item.packageName));
Jeff Sharkey752cd922012-09-23 16:25:12 -0700298 if (item.andCode) {
Jeff Sharkey7f392de2013-08-11 17:42:17 -0700299 eraseFiles(userEnv.buildExternalStorageAppObbDirs(item.packageName));
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700300 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800301 }
302 } catch (RemoteException e) {
303 }
304 }
305 }
306
Jeff Sharkey7f392de2013-08-11 17:42:17 -0700307 void eraseFiles(File[] paths) {
308 for (File path : paths) {
309 eraseFiles(path);
310 }
311 }
312
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800313 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 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800322 path.delete();
323 }
324
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800325 public IBinder onBind(Intent intent) {
326 return mBinder;
327 }
328
Kenny Root6dceb882012-04-12 14:23:49 -0700329 private String copyResourceInner(Uri packageURI, String newCid, String key, String resFileName,
330 String publicResFileName, boolean isExternal, boolean isForwardLocked) {
331
332 if (isExternal) {
333 // Make sure the sdcard is mounted.
334 String status = Environment.getExternalStorageState();
335 if (!status.equals(Environment.MEDIA_MOUNTED)) {
336 Slog.w(TAG, "Make sure sdcard is mounted.");
337 return null;
338 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800339 }
Kenny Root85387d72010-08-26 10:13:11 -0700340
341 // The .apk file
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800342 String codePath = packageURI.getPath();
Suchi Amalapurapu679bba32010-02-16 11:52:44 -0800343 File codeFile = new File(codePath);
Kenny Root85387d72010-08-26 10:13:11 -0700344
345 // Calculate size of container needed to hold base APK.
Kenny Root6dceb882012-04-12 14:23:49 -0700346 final int sizeMb;
Kenny Root1ebd74a2011-08-03 15:09:44 -0700347 try {
Kenny Root6dceb882012-04-12 14:23:49 -0700348 sizeMb = calculateContainerSize(codeFile, isForwardLocked);
349 } catch (IOException e) {
350 Slog.w(TAG, "Problem when trying to copy " + codeFile.getPath());
Kenny Root1ebd74a2011-08-03 15:09:44 -0700351 return null;
352 }
Kenny Root85387d72010-08-26 10:13:11 -0700353
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800354 // Create new container
Kenny Root6dceb882012-04-12 14:23:49 -0700355 final String newCachePath = PackageHelper.createSdDir(sizeMb, newCid, key, Process.myUid(),
356 isExternal);
357 if (newCachePath == null) {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700358 Slog.e(TAG, "Failed to create container " + newCid);
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800359 return null;
360 }
Kenny Root85387d72010-08-26 10:13:11 -0700361
Kenny Root1ebd74a2011-08-03 15:09:44 -0700362 if (localLOGV) {
363 Slog.i(TAG, "Created container for " + newCid + " at path : " + newCachePath);
364 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700365
Kenny Root1ebd74a2011-08-03 15:09:44 -0700366 final File resFile = new File(newCachePath, resFileName);
367 if (FileUtils.copyFile(new File(codePath), resFile)) {
368 if (localLOGV) {
369 Slog.i(TAG, "Copied " + codePath + " to " + resFile);
Kenny Root85387d72010-08-26 10:13:11 -0700370 }
Kenny Root1ebd74a2011-08-03 15:09:44 -0700371 } else {
372 Slog.e(TAG, "Failed to copy " + codePath + " to " + resFile);
373 // Clean up container
Kenny Root85387d72010-08-26 10:13:11 -0700374 PackageHelper.destroySdDir(newCid);
375 return null;
376 }
377
Kenny Rootbf023582012-05-02 16:56:15 -0700378 try {
379 Libcore.os.chmod(resFile.getAbsolutePath(), 0640);
380 } catch (ErrnoException e) {
381 Slog.e(TAG, "Could not chown APK: " + e.getMessage());
382 PackageHelper.destroySdDir(newCid);
383 return null;
384 }
385
Kenny Root6dceb882012-04-12 14:23:49 -0700386 if (isForwardLocked) {
387 File publicZipFile = new File(newCachePath, publicResFileName);
388 try {
389 PackageHelper.extractPublicFiles(resFile.getAbsolutePath(), publicZipFile);
390 if (localLOGV) {
391 Slog.i(TAG, "Copied resources to " + publicZipFile);
392 }
393 } catch (IOException e) {
394 Slog.e(TAG, "Could not chown public APK " + publicZipFile.getAbsolutePath() + ": "
395 + e.getMessage());
396 PackageHelper.destroySdDir(newCid);
397 return null;
398 }
399
400 try {
Kenny Root6dceb882012-04-12 14:23:49 -0700401 Libcore.os.chmod(publicZipFile.getAbsolutePath(), 0644);
402 } catch (ErrnoException e) {
Kenny Rootbf023582012-05-02 16:56:15 -0700403 Slog.e(TAG, "Could not chown public resource file: " + e.getMessage());
Kenny Root6dceb882012-04-12 14:23:49 -0700404 PackageHelper.destroySdDir(newCid);
405 return null;
406 }
407 }
408
Kenny Root1ebd74a2011-08-03 15:09:44 -0700409 final File sharedLibraryDir = new File(newCachePath, LIB_DIR_NAME);
410 if (sharedLibraryDir.mkdir()) {
411 int ret = NativeLibraryHelper.copyNativeBinariesIfNeededLI(codeFile, sharedLibraryDir);
412 if (ret != PackageManager.INSTALL_SUCCEEDED) {
413 Slog.e(TAG, "Could not copy native libraries to " + sharedLibraryDir.getPath());
414 PackageHelper.destroySdDir(newCid);
415 return null;
416 }
417 } else {
418 Slog.e(TAG, "Could not create native lib directory: " + sharedLibraryDir.getPath());
419 PackageHelper.destroySdDir(newCid);
420 return null;
421 }
422
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800423 if (!PackageHelper.finalizeSdDir(newCid)) {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700424 Slog.e(TAG, "Failed to finalize " + newCid + " at path " + newCachePath);
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800425 // Clean up container
426 PackageHelper.destroySdDir(newCid);
Kenny Root1ebd74a2011-08-03 15:09:44 -0700427 return null;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800428 }
Kenny Root1ebd74a2011-08-03 15:09:44 -0700429
430 if (localLOGV) {
431 Slog.i(TAG, "Finalized container " + newCid);
432 }
433
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800434 if (PackageHelper.isContainerMounted(newCid)) {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700435 if (localLOGV) {
436 Slog.i(TAG, "Unmounting " + newCid + " at path " + newCachePath);
437 }
438
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800439 // Force a gc to avoid being killed.
440 Runtime.getRuntime().gc();
441 PackageHelper.unMountSdDir(newCid);
442 } else {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700443 if (localLOGV) {
444 Slog.i(TAG, "Container " + newCid + " not mounted");
445 }
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800446 }
Kenny Root1ebd74a2011-08-03 15:09:44 -0700447
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800448 return newCachePath;
449 }
450
Kenny Rootf5121a92011-08-10 16:23:32 -0700451 private static void copyToFile(InputStream inputStream, OutputStream out) throws IOException {
452 byte[] buffer = new byte[16384];
453 int bytesRead;
454 while ((bytesRead = inputStream.read(buffer)) >= 0) {
455 out.write(buffer, 0, bytesRead);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800456 }
457 }
458
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700459 private void copyFile(Uri pPackageURI, OutputStream outStream,
460 ContainerEncryptionParams encryptionParams) throws FileNotFoundException, IOException,
461 DigestException {
462 String scheme = pPackageURI.getScheme();
463 InputStream inStream = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800464 try {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700465 if (scheme == null || scheme.equals("file")) {
466 final InputStream is = new FileInputStream(new File(pPackageURI.getPath()));
467 inStream = new BufferedInputStream(is);
468 } else if (scheme.equals("content")) {
469 final ParcelFileDescriptor fd;
470 try {
471 fd = getContentResolver().openFileDescriptor(pPackageURI, "r");
472 } catch (FileNotFoundException e) {
473 Slog.e(TAG, "Couldn't open file descriptor from download service. "
474 + "Failed with exception " + e);
475 throw e;
476 }
477
478 if (fd == null) {
479 Slog.e(TAG, "Provider returned no file descriptor for " +
480 pPackageURI.toString());
481 throw new FileNotFoundException("provider returned no file descriptor");
482 } else {
483 if (localLOGV) {
484 Slog.i(TAG, "Opened file descriptor from download service.");
485 }
486 inStream = new ParcelFileDescriptor.AutoCloseInputStream(fd);
487 }
488 } else {
489 Slog.e(TAG, "Package URI is not 'file:' or 'content:' - " + pPackageURI);
490 throw new FileNotFoundException("Package URI is not 'file:' or 'content:'");
491 }
492
493 /*
494 * If this resource is encrypted, get the decrypted stream version
495 * of it.
496 */
497 ApkContainer container = new ApkContainer(inStream, encryptionParams);
498
499 try {
500 /*
501 * We copy the source package file to a temp file and then
502 * rename it to the destination file in order to eliminate a
503 * window where the package directory scanner notices the new
504 * package file but it's not completely copied yet.
505 */
506 copyToFile(container.getInputStream(), outStream);
507
508 if (!container.isAuthenticated()) {
509 throw new DigestException();
510 }
511 } catch (GeneralSecurityException e) {
512 throw new DigestException("A problem occured copying the file.");
513 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800514 } finally {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700515 IoUtils.closeQuietly(inStream);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800516 }
517 }
518
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700519 private static class ApkContainer {
Kenny Root103d5302012-05-10 10:21:06 -0700520 private static final int MAX_AUTHENTICATED_DATA_SIZE = 16384;
521
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700522 private final InputStream mInStream;
Kenny Rootf5121a92011-08-10 16:23:32 -0700523
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700524 private MacAuthenticatedInputStream mAuthenticatedStream;
525
526 private byte[] mTag;
527
528 public ApkContainer(InputStream inStream, ContainerEncryptionParams encryptionParams)
529 throws IOException {
530 if (encryptionParams == null) {
531 mInStream = inStream;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800532 } else {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700533 mInStream = getDecryptedStream(inStream, encryptionParams);
534 mTag = encryptionParams.getMacTag();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800535 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800536 }
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700537
538 public boolean isAuthenticated() {
539 if (mAuthenticatedStream == null) {
540 return true;
541 }
542
543 return mAuthenticatedStream.isTagEqual(mTag);
544 }
545
546 private Mac getMacInstance(ContainerEncryptionParams encryptionParams) throws IOException {
547 final Mac m;
548 try {
549 final String macAlgo = encryptionParams.getMacAlgorithm();
550
551 if (macAlgo != null) {
552 m = Mac.getInstance(macAlgo);
553 m.init(encryptionParams.getMacKey(), encryptionParams.getMacSpec());
554 } else {
555 m = null;
556 }
557
558 return m;
559 } catch (NoSuchAlgorithmException e) {
560 throw new IOException(e);
561 } catch (InvalidKeyException e) {
562 throw new IOException(e);
563 } catch (InvalidAlgorithmParameterException e) {
564 throw new IOException(e);
565 }
566 }
567
568 public InputStream getInputStream() {
569 return mInStream;
570 }
571
572 private InputStream getDecryptedStream(InputStream inStream,
573 ContainerEncryptionParams encryptionParams) throws IOException {
574 final Cipher c;
575 try {
576 c = Cipher.getInstance(encryptionParams.getEncryptionAlgorithm());
577 c.init(Cipher.DECRYPT_MODE, encryptionParams.getEncryptionKey(),
578 encryptionParams.getEncryptionSpec());
579 } catch (NoSuchAlgorithmException e) {
580 throw new IOException(e);
581 } catch (NoSuchPaddingException e) {
582 throw new IOException(e);
583 } catch (InvalidKeyException e) {
584 throw new IOException(e);
585 } catch (InvalidAlgorithmParameterException e) {
586 throw new IOException(e);
587 }
588
Kenny Root103d5302012-05-10 10:21:06 -0700589 final long encStart = encryptionParams.getEncryptedDataStart();
590 final long end = encryptionParams.getDataEnd();
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700591 if (end < encStart) {
592 throw new IOException("end <= encStart");
593 }
594
595 final Mac mac = getMacInstance(encryptionParams);
596 if (mac != null) {
Kenny Root103d5302012-05-10 10:21:06 -0700597 final long macStart = encryptionParams.getAuthenticatedDataStart();
598 if (macStart >= Integer.MAX_VALUE) {
599 throw new IOException("macStart >= Integer.MAX_VALUE");
600 }
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700601
Kenny Root103d5302012-05-10 10:21:06 -0700602 final long furtherOffset;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700603 if (macStart >= 0 && encStart >= 0 && macStart < encStart) {
604 /*
605 * If there is authenticated data at the beginning, read
606 * that into our MAC first.
607 */
Kenny Root103d5302012-05-10 10:21:06 -0700608 final long authenticatedLengthLong = encStart - macStart;
609 if (authenticatedLengthLong > MAX_AUTHENTICATED_DATA_SIZE) {
610 throw new IOException("authenticated data is too long");
611 }
612 final int authenticatedLength = (int) authenticatedLengthLong;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700613
Kenny Root103d5302012-05-10 10:21:06 -0700614 final byte[] authenticatedData = new byte[(int) authenticatedLength];
615
616 Streams.readFully(inStream, authenticatedData, (int) macStart,
617 authenticatedLength);
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700618 mac.update(authenticatedData, 0, authenticatedLength);
619
620 furtherOffset = 0;
621 } else {
622 /*
623 * No authenticated data at the beginning. Just skip the
624 * required number of bytes to the beginning of the stream.
625 */
626 if (encStart > 0) {
627 furtherOffset = encStart;
628 } else {
629 furtherOffset = 0;
630 }
631 }
632
633 /*
634 * If there is data at the end of the stream we want to ignore,
635 * wrap this in a LimitedLengthInputStream.
636 */
637 if (furtherOffset >= 0 && end > furtherOffset) {
638 inStream = new LimitedLengthInputStream(inStream, furtherOffset, end - encStart);
639 } else if (furtherOffset > 0) {
640 inStream.skip(furtherOffset);
641 }
642
643 mAuthenticatedStream = new MacAuthenticatedInputStream(inStream, mac);
644
645 inStream = mAuthenticatedStream;
646 } else {
647 if (encStart >= 0) {
648 if (end > encStart) {
649 inStream = new LimitedLengthInputStream(inStream, encStart, end - encStart);
650 } else {
651 inStream.skip(encStart);
652 }
653 }
654 }
655
656 return new CipherInputStream(inStream, c);
657 }
658
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800659 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800660
Kenny Root62e1b4e2011-03-14 17:13:39 -0700661 private static final int PREFER_INTERNAL = 1;
662 private static final int PREFER_EXTERNAL = 2;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800663
Kenny Root62e1b4e2011-03-14 17:13:39 -0700664 private int recommendAppInstallLocation(int installLocation, String archiveFilePath, int flags,
665 long threshold) {
666 int prefer;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700667 boolean checkBoth = false;
Kenny Root62e1b4e2011-03-14 17:13:39 -0700668
Kenny Root6dceb882012-04-12 14:23:49 -0700669 final boolean isForwardLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
670
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700671 check_inner : {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700672 /*
673 * Explicit install flags should override the manifest settings.
674 */
Kenny Root6dceb882012-04-12 14:23:49 -0700675 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700676 prefer = PREFER_INTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700677 break check_inner;
678 } else if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700679 prefer = PREFER_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700680 break check_inner;
681 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700682
683 /* No install flags. Check for manifest option. */
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700684 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700685 prefer = PREFER_INTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700686 break check_inner;
687 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700688 prefer = PREFER_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700689 checkBoth = true;
690 break check_inner;
691 } else if (installLocation == PackageInfo.INSTALL_LOCATION_AUTO) {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700692 // We default to preferring internal storage.
693 prefer = PREFER_INTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700694 checkBoth = true;
695 break check_inner;
696 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700697
Suchi Amalapurapu40e47252010-04-07 16:15:50 -0700698 // Pick user preference
Jeff Sharkey625239a2012-09-26 22:03:49 -0700699 int installPreference = Settings.Global.getInt(getApplicationContext()
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700700 .getContentResolver(),
Jeff Sharkey625239a2012-09-26 22:03:49 -0700701 Settings.Global.DEFAULT_INSTALL_LOCATION,
Suchi Amalapurapu40e47252010-04-07 16:15:50 -0700702 PackageHelper.APP_INSTALL_AUTO);
703 if (installPreference == PackageHelper.APP_INSTALL_INTERNAL) {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700704 prefer = PREFER_INTERNAL;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -0700705 break check_inner;
706 } else if (installPreference == PackageHelper.APP_INSTALL_EXTERNAL) {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700707 prefer = PREFER_EXTERNAL;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -0700708 break check_inner;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700709 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700710
711 /*
712 * Fall back to default policy of internal-only if nothing else is
713 * specified.
714 */
715 prefer = PREFER_INTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700716 }
717
Kenny Root62e1b4e2011-03-14 17:13:39 -0700718 final boolean emulated = Environment.isExternalStorageEmulated();
719
720 final File apkFile = new File(archiveFilePath);
721
722 boolean fitsOnInternal = false;
723 if (checkBoth || prefer == PREFER_INTERNAL) {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700724 try {
Kenny Root6dceb882012-04-12 14:23:49 -0700725 fitsOnInternal = isUnderInternalThreshold(apkFile, isForwardLocked, threshold);
726 } catch (IOException e) {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700727 return PackageHelper.RECOMMEND_FAILED_INVALID_URI;
728 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800729 }
730
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700731 boolean fitsOnSd = false;
Kenny Root62e1b4e2011-03-14 17:13:39 -0700732 if (!emulated && (checkBoth || prefer == PREFER_EXTERNAL)) {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700733 try {
Kenny Root6dceb882012-04-12 14:23:49 -0700734 fitsOnSd = isUnderExternalThreshold(apkFile, isForwardLocked);
735 } catch (IOException e) {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700736 return PackageHelper.RECOMMEND_FAILED_INVALID_URI;
737 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700738 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700739
740 if (prefer == PREFER_INTERNAL) {
741 if (fitsOnInternal) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700742 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
743 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700744 } else if (!emulated && prefer == PREFER_EXTERNAL) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800745 if (fitsOnSd) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700746 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800747 }
748 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700749
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700750 if (checkBoth) {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700751 if (fitsOnInternal) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700752 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Kenny Root62e1b4e2011-03-14 17:13:39 -0700753 } else if (!emulated && fitsOnSd) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700754 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800755 }
756 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700757
758 /*
759 * If they requested to be on the external media by default, return that
760 * the media was unavailable. Otherwise, indicate there was insufficient
761 * storage space available.
762 */
763 if (!emulated && (checkBoth || prefer == PREFER_EXTERNAL)
764 && !Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700765 return PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE;
Kenny Root62e1b4e2011-03-14 17:13:39 -0700766 } else {
767 return PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800768 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800769 }
770
Kenny Root1ebd74a2011-08-03 15:09:44 -0700771 /**
772 * Measure a file to see if it fits within the free space threshold.
773 *
774 * @param apkFile file to check
775 * @param threshold byte threshold to compare against
776 * @return true if file fits under threshold
777 * @throws FileNotFoundException when APK does not exist
778 */
Kenny Root6dceb882012-04-12 14:23:49 -0700779 private boolean isUnderInternalThreshold(File apkFile, boolean isForwardLocked, long threshold)
780 throws IOException {
781 long size = apkFile.length();
Kenny Root1ebd74a2011-08-03 15:09:44 -0700782 if (size == 0 && !apkFile.exists()) {
783 throw new FileNotFoundException();
784 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800785
Kenny Root6dceb882012-04-12 14:23:49 -0700786 if (isForwardLocked) {
787 size += PackageHelper.extractPublicFiles(apkFile.getAbsolutePath(), null);
788 }
789
Kenny Root62e1b4e2011-03-14 17:13:39 -0700790 final StatFs internalStats = new StatFs(Environment.getDataDirectory().getPath());
791 final long availInternalSize = (long) internalStats.getAvailableBlocks()
792 * (long) internalStats.getBlockSize();
793
794 return (availInternalSize - size) > threshold;
795 }
796
797
Kenny Root1ebd74a2011-08-03 15:09:44 -0700798 /**
799 * Measure a file to see if it fits in the external free space.
800 *
801 * @param apkFile file to check
802 * @return true if file fits
803 * @throws IOException when file does not exist
804 */
Kenny Root6dceb882012-04-12 14:23:49 -0700805 private boolean isUnderExternalThreshold(File apkFile, boolean isForwardLocked)
806 throws IOException {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700807 if (Environment.isExternalStorageEmulated()) {
808 return false;
809 }
810
Kenny Root6dceb882012-04-12 14:23:49 -0700811 final int sizeMb = calculateContainerSize(apkFile, isForwardLocked);
Kenny Root62e1b4e2011-03-14 17:13:39 -0700812
813 final int availSdMb;
814 if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
Kenny Root61942c52011-08-15 12:46:04 -0700815 final StatFs sdStats = new StatFs(Environment.getExternalStorageDirectory().getPath());
816 final int blocksToMb = (1 << 20) / sdStats.getBlockSize();
817 availSdMb = sdStats.getAvailableBlocks() * blocksToMb;
Kenny Root62e1b4e2011-03-14 17:13:39 -0700818 } else {
819 availSdMb = -1;
820 }
821
822 return availSdMb > sizeMb;
823 }
824
825 /**
826 * Calculate the container size for an APK. Takes into account the
827 *
828 * @param apkFile file from which to calculate size
829 * @return size in megabytes (2^20 bytes)
Kenny Root6dceb882012-04-12 14:23:49 -0700830 * @throws IOException when there is a problem reading the file
Kenny Root62e1b4e2011-03-14 17:13:39 -0700831 */
Kenny Root6dceb882012-04-12 14:23:49 -0700832 private int calculateContainerSize(File apkFile, boolean forwardLocked) throws IOException {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700833 // Calculate size of container needed to hold base APK.
834 long sizeBytes = apkFile.length();
Kenny Root1ebd74a2011-08-03 15:09:44 -0700835 if (sizeBytes == 0 && !apkFile.exists()) {
836 throw new FileNotFoundException();
837 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700838
839 // Check all the native files that need to be copied and add that to the
840 // container size.
Kenny Root66269ea2011-07-12 14:14:01 -0700841 sizeBytes += NativeLibraryHelper.sumNativeBinariesLI(apkFile);
Kenny Root62e1b4e2011-03-14 17:13:39 -0700842
Kenny Root6dceb882012-04-12 14:23:49 -0700843 if (forwardLocked) {
844 sizeBytes += PackageHelper.extractPublicFiles(apkFile.getPath(), null);
845 }
846
Kenny Root62e1b4e2011-03-14 17:13:39 -0700847 int sizeMb = (int) (sizeBytes >> 20);
848 if ((sizeBytes - (sizeMb * 1024 * 1024)) > 0) {
849 sizeMb++;
850 }
851
852 /*
853 * Add buffer size because we don't have a good way to determine the
854 * real FAT size. Your FAT size varies with how many directory entries
855 * you need, how big the whole filesystem is, and other such headaches.
856 */
857 sizeMb++;
858
859 return sizeMb;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800860 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800861}