blob: d3bd197a4d0e3573d0d801a9a7316f67b9233340 [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;
Jeff Sharkey63d0a062013-03-01 16:12:55 -080042import android.os.SystemClock;
Kenny Rootf5121a92011-08-10 16:23:32 -070043import android.provider.Settings;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080044import android.util.DisplayMetrics;
Jeff Sharkey63d0a062013-03-01 16:12:55 -080045import android.util.Log;
Kenny Root1ebd74a2011-08-03 15:09:44 -070046import android.util.Slog;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080047
Jeff Sharkey63d0a062013-03-01 16:12:55 -080048import com.android.internal.app.IMediaContainerService;
49import com.android.internal.content.NativeLibraryHelper;
50import com.android.internal.content.PackageHelper;
51
Kenny Rootf5121a92011-08-10 16:23:32 -070052import java.io.BufferedInputStream;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080053import java.io.File;
54import java.io.FileInputStream;
55import java.io.FileNotFoundException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080056import java.io.IOException;
57import java.io.InputStream;
Kenny Rootf5121a92011-08-10 16:23:32 -070058import java.io.OutputStream;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -070059import java.security.DigestException;
60import java.security.GeneralSecurityException;
61import java.security.InvalidAlgorithmParameterException;
62import java.security.InvalidKeyException;
63import java.security.NoSuchAlgorithmException;
64
65import javax.crypto.Cipher;
66import javax.crypto.CipherInputStream;
67import javax.crypto.Mac;
68import javax.crypto.NoSuchPaddingException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080069
Jeff Sharkey9cbe986a2012-04-22 18:56:43 -070070import libcore.io.ErrnoException;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -070071import libcore.io.IoUtils;
Jeff Sharkey9cbe986a2012-04-22 18:56:43 -070072import libcore.io.Libcore;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -070073import libcore.io.Streams;
Elliott Hughesbefd0b12013-07-09 14:46:18 -070074import libcore.io.StructStatVfs;
Jeff Sharkey9cbe986a2012-04-22 18:56:43 -070075
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080076/*
77 * This service copies a downloaded apk to a file passed in as
78 * a ParcelFileDescriptor or to a newly created container specified
79 * by parameters. The DownloadManager gives access to this process
80 * based on its uid. This process also needs the ACCESS_DOWNLOAD_MANAGER
81 * permission to access apks downloaded via the download manager.
82 */
Dianne Hackborne83cefce2010-02-04 17:38:14 -080083public class DefaultContainerService extends IntentService {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080084 private static final String TAG = "DefContainer";
Dianne Hackborn40e9f292012-11-27 19:12:23 -080085 private static final boolean localLOGV = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080086
Kenny Root85387d72010-08-26 10:13:11 -070087 private static final String LIB_DIR_NAME = "lib";
88
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080089 private IMediaContainerService.Stub mBinder = new IMediaContainerService.Stub() {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -070090 /**
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080091 * Creates a new container and copies resource there.
92 * @param paackageURI the uri of resource to be copied. Can be either
93 * a content uri or a file uri
Suchi Amalapurapu679bba32010-02-16 11:52:44 -080094 * @param cid the id of the secure container that should
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080095 * be used for creating a secure container into which the resource
96 * will be copied.
97 * @param key Refers to key used for encrypting the secure container
98 * @param resFileName Name of the target resource file(relative to newly
99 * created secure container)
100 * @return Returns the new cache path where the resource has been copied into
101 *
102 */
Kenny Root6dceb882012-04-12 14:23:49 -0700103 public String copyResourceToContainer(final Uri packageURI, final String cid,
104 final String key, final String resFileName, final String publicResFileName,
105 boolean isExternal, boolean isForwardLocked) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -0800106 if (packageURI == null || cid == null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800107 return null;
108 }
Kenny Root6dceb882012-04-12 14:23:49 -0700109
110 return copyResourceInner(packageURI, cid, key, resFileName, publicResFileName,
111 isExternal, isForwardLocked);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800112 }
113
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700114 /**
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800115 * Copy specified resource to output stream
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700116 *
Kenny Rootf5121a92011-08-10 16:23:32 -0700117 * @param packageURI the uri of resource to be copied. Should be a file
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700118 * uri
119 * @param encryptionParams parameters describing the encryption used for
120 * this file
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800121 * @param outStream Remote file descriptor to be used for copying
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700122 * @return returns status code according to those in
123 * {@link PackageManager}
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800124 */
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700125 public int copyResource(final Uri packageURI, ContainerEncryptionParams encryptionParams,
126 ParcelFileDescriptor outStream) {
Kenny Rootf5121a92011-08-10 16:23:32 -0700127 if (packageURI == null || outStream == null) {
128 return PackageManager.INSTALL_FAILED_INVALID_URI;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800129 }
Kenny Rootf5121a92011-08-10 16:23:32 -0700130
131 ParcelFileDescriptor.AutoCloseOutputStream autoOut
132 = new ParcelFileDescriptor.AutoCloseOutputStream(outStream);
133
134 try {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700135 copyFile(packageURI, autoOut, encryptionParams);
Kenny Rootf5121a92011-08-10 16:23:32 -0700136 return PackageManager.INSTALL_SUCCEEDED;
137 } catch (FileNotFoundException e) {
138 Slog.e(TAG, "Could not copy URI " + packageURI.toString() + " FNF: "
139 + e.getMessage());
140 return PackageManager.INSTALL_FAILED_INVALID_URI;
141 } catch (IOException e) {
142 Slog.e(TAG, "Could not copy URI " + packageURI.toString() + " IO: "
143 + e.getMessage());
144 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700145 } catch (DigestException e) {
146 Slog.e(TAG, "Could not copy URI " + packageURI.toString() + " Security: "
147 + e.getMessage());
148 return PackageManager.INSTALL_FAILED_INVALID_APK;
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);
296 eraseFiles(userEnv.getExternalStorageAppDataDirectory(item.packageName));
297 eraseFiles(userEnv.getExternalStorageAppMediaDirectory(item.packageName));
298 if (item.andCode) {
299 eraseFiles(userEnv.getExternalStorageAppObbDirectory(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
307 void eraseFiles(File path) {
308 if (path.isDirectory()) {
309 String[] files = path.list();
310 if (files != null) {
311 for (String file : files) {
312 eraseFiles(new File(path, file));
313 }
314 }
315 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800316 path.delete();
317 }
318
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800319 public IBinder onBind(Intent intent) {
320 return mBinder;
321 }
322
Kenny Root6dceb882012-04-12 14:23:49 -0700323 private String copyResourceInner(Uri packageURI, String newCid, String key, String resFileName,
324 String publicResFileName, boolean isExternal, boolean isForwardLocked) {
325
326 if (isExternal) {
327 // Make sure the sdcard is mounted.
328 String status = Environment.getExternalStorageState();
329 if (!status.equals(Environment.MEDIA_MOUNTED)) {
330 Slog.w(TAG, "Make sure sdcard is mounted.");
331 return null;
332 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800333 }
Kenny Root85387d72010-08-26 10:13:11 -0700334
335 // The .apk file
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800336 String codePath = packageURI.getPath();
Suchi Amalapurapu679bba32010-02-16 11:52:44 -0800337 File codeFile = new File(codePath);
Kenny Root85387d72010-08-26 10:13:11 -0700338
339 // Calculate size of container needed to hold base APK.
Kenny Root6dceb882012-04-12 14:23:49 -0700340 final int sizeMb;
Kenny Root1ebd74a2011-08-03 15:09:44 -0700341 try {
Kenny Root6dceb882012-04-12 14:23:49 -0700342 sizeMb = calculateContainerSize(codeFile, isForwardLocked);
343 } catch (IOException e) {
344 Slog.w(TAG, "Problem when trying to copy " + codeFile.getPath());
Kenny Root1ebd74a2011-08-03 15:09:44 -0700345 return null;
346 }
Kenny Root85387d72010-08-26 10:13:11 -0700347
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800348 // Create new container
Kenny Root6dceb882012-04-12 14:23:49 -0700349 final String newCachePath = PackageHelper.createSdDir(sizeMb, newCid, key, Process.myUid(),
350 isExternal);
351 if (newCachePath == null) {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700352 Slog.e(TAG, "Failed to create container " + newCid);
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800353 return null;
354 }
Kenny Root85387d72010-08-26 10:13:11 -0700355
Kenny Root1ebd74a2011-08-03 15:09:44 -0700356 if (localLOGV) {
357 Slog.i(TAG, "Created container for " + newCid + " at path : " + newCachePath);
358 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700359
Kenny Root1ebd74a2011-08-03 15:09:44 -0700360 final File resFile = new File(newCachePath, resFileName);
361 if (FileUtils.copyFile(new File(codePath), resFile)) {
362 if (localLOGV) {
363 Slog.i(TAG, "Copied " + codePath + " to " + resFile);
Kenny Root85387d72010-08-26 10:13:11 -0700364 }
Kenny Root1ebd74a2011-08-03 15:09:44 -0700365 } else {
366 Slog.e(TAG, "Failed to copy " + codePath + " to " + resFile);
367 // Clean up container
Kenny Root85387d72010-08-26 10:13:11 -0700368 PackageHelper.destroySdDir(newCid);
369 return null;
370 }
371
Kenny Rootbf023582012-05-02 16:56:15 -0700372 try {
373 Libcore.os.chmod(resFile.getAbsolutePath(), 0640);
374 } catch (ErrnoException e) {
375 Slog.e(TAG, "Could not chown APK: " + e.getMessage());
376 PackageHelper.destroySdDir(newCid);
377 return null;
378 }
379
Kenny Root6dceb882012-04-12 14:23:49 -0700380 if (isForwardLocked) {
381 File publicZipFile = new File(newCachePath, publicResFileName);
382 try {
383 PackageHelper.extractPublicFiles(resFile.getAbsolutePath(), publicZipFile);
384 if (localLOGV) {
385 Slog.i(TAG, "Copied resources to " + publicZipFile);
386 }
387 } catch (IOException e) {
388 Slog.e(TAG, "Could not chown public APK " + publicZipFile.getAbsolutePath() + ": "
389 + e.getMessage());
390 PackageHelper.destroySdDir(newCid);
391 return null;
392 }
393
394 try {
Kenny Root6dceb882012-04-12 14:23:49 -0700395 Libcore.os.chmod(publicZipFile.getAbsolutePath(), 0644);
396 } catch (ErrnoException e) {
Kenny Rootbf023582012-05-02 16:56:15 -0700397 Slog.e(TAG, "Could not chown public resource file: " + e.getMessage());
Kenny Root6dceb882012-04-12 14:23:49 -0700398 PackageHelper.destroySdDir(newCid);
399 return null;
400 }
401 }
402
Kenny Root1ebd74a2011-08-03 15:09:44 -0700403 final File sharedLibraryDir = new File(newCachePath, LIB_DIR_NAME);
404 if (sharedLibraryDir.mkdir()) {
405 int ret = NativeLibraryHelper.copyNativeBinariesIfNeededLI(codeFile, sharedLibraryDir);
406 if (ret != PackageManager.INSTALL_SUCCEEDED) {
407 Slog.e(TAG, "Could not copy native libraries to " + sharedLibraryDir.getPath());
408 PackageHelper.destroySdDir(newCid);
409 return null;
410 }
411 } else {
412 Slog.e(TAG, "Could not create native lib directory: " + sharedLibraryDir.getPath());
413 PackageHelper.destroySdDir(newCid);
414 return null;
415 }
416
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800417 if (!PackageHelper.finalizeSdDir(newCid)) {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700418 Slog.e(TAG, "Failed to finalize " + newCid + " at path " + newCachePath);
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800419 // Clean up container
420 PackageHelper.destroySdDir(newCid);
Kenny Root1ebd74a2011-08-03 15:09:44 -0700421 return null;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800422 }
Kenny Root1ebd74a2011-08-03 15:09:44 -0700423
424 if (localLOGV) {
425 Slog.i(TAG, "Finalized container " + newCid);
426 }
427
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800428 if (PackageHelper.isContainerMounted(newCid)) {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700429 if (localLOGV) {
430 Slog.i(TAG, "Unmounting " + newCid + " at path " + newCachePath);
431 }
432
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800433 // Force a gc to avoid being killed.
434 Runtime.getRuntime().gc();
435 PackageHelper.unMountSdDir(newCid);
436 } else {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700437 if (localLOGV) {
438 Slog.i(TAG, "Container " + newCid + " not mounted");
439 }
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -0800440 }
Kenny Root1ebd74a2011-08-03 15:09:44 -0700441
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800442 return newCachePath;
443 }
444
Kenny Rootf5121a92011-08-10 16:23:32 -0700445 private static void copyToFile(InputStream inputStream, OutputStream out) throws IOException {
446 byte[] buffer = new byte[16384];
447 int bytesRead;
448 while ((bytesRead = inputStream.read(buffer)) >= 0) {
449 out.write(buffer, 0, bytesRead);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800450 }
451 }
452
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700453 private void copyFile(Uri pPackageURI, OutputStream outStream,
454 ContainerEncryptionParams encryptionParams) throws FileNotFoundException, IOException,
455 DigestException {
456 String scheme = pPackageURI.getScheme();
457 InputStream inStream = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800458 try {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700459 if (scheme == null || scheme.equals("file")) {
460 final InputStream is = new FileInputStream(new File(pPackageURI.getPath()));
461 inStream = new BufferedInputStream(is);
462 } else if (scheme.equals("content")) {
463 final ParcelFileDescriptor fd;
464 try {
465 fd = getContentResolver().openFileDescriptor(pPackageURI, "r");
466 } catch (FileNotFoundException e) {
467 Slog.e(TAG, "Couldn't open file descriptor from download service. "
468 + "Failed with exception " + e);
469 throw e;
470 }
471
472 if (fd == null) {
473 Slog.e(TAG, "Provider returned no file descriptor for " +
474 pPackageURI.toString());
475 throw new FileNotFoundException("provider returned no file descriptor");
476 } else {
477 if (localLOGV) {
478 Slog.i(TAG, "Opened file descriptor from download service.");
479 }
480 inStream = new ParcelFileDescriptor.AutoCloseInputStream(fd);
481 }
482 } else {
483 Slog.e(TAG, "Package URI is not 'file:' or 'content:' - " + pPackageURI);
484 throw new FileNotFoundException("Package URI is not 'file:' or 'content:'");
485 }
486
487 /*
488 * If this resource is encrypted, get the decrypted stream version
489 * of it.
490 */
491 ApkContainer container = new ApkContainer(inStream, encryptionParams);
492
493 try {
494 /*
495 * We copy the source package file to a temp file and then
496 * rename it to the destination file in order to eliminate a
497 * window where the package directory scanner notices the new
498 * package file but it's not completely copied yet.
499 */
500 copyToFile(container.getInputStream(), outStream);
501
502 if (!container.isAuthenticated()) {
503 throw new DigestException();
504 }
505 } catch (GeneralSecurityException e) {
506 throw new DigestException("A problem occured copying the file.");
507 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800508 } finally {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700509 IoUtils.closeQuietly(inStream);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800510 }
511 }
512
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700513 private static class ApkContainer {
Kenny Root103d5302012-05-10 10:21:06 -0700514 private static final int MAX_AUTHENTICATED_DATA_SIZE = 16384;
515
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700516 private final InputStream mInStream;
Kenny Rootf5121a92011-08-10 16:23:32 -0700517
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700518 private MacAuthenticatedInputStream mAuthenticatedStream;
519
520 private byte[] mTag;
521
522 public ApkContainer(InputStream inStream, ContainerEncryptionParams encryptionParams)
523 throws IOException {
524 if (encryptionParams == null) {
525 mInStream = inStream;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800526 } else {
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700527 mInStream = getDecryptedStream(inStream, encryptionParams);
528 mTag = encryptionParams.getMacTag();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800529 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800530 }
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700531
532 public boolean isAuthenticated() {
533 if (mAuthenticatedStream == null) {
534 return true;
535 }
536
537 return mAuthenticatedStream.isTagEqual(mTag);
538 }
539
540 private Mac getMacInstance(ContainerEncryptionParams encryptionParams) throws IOException {
541 final Mac m;
542 try {
543 final String macAlgo = encryptionParams.getMacAlgorithm();
544
545 if (macAlgo != null) {
546 m = Mac.getInstance(macAlgo);
547 m.init(encryptionParams.getMacKey(), encryptionParams.getMacSpec());
548 } else {
549 m = null;
550 }
551
552 return m;
553 } catch (NoSuchAlgorithmException e) {
554 throw new IOException(e);
555 } catch (InvalidKeyException e) {
556 throw new IOException(e);
557 } catch (InvalidAlgorithmParameterException e) {
558 throw new IOException(e);
559 }
560 }
561
562 public InputStream getInputStream() {
563 return mInStream;
564 }
565
566 private InputStream getDecryptedStream(InputStream inStream,
567 ContainerEncryptionParams encryptionParams) throws IOException {
568 final Cipher c;
569 try {
570 c = Cipher.getInstance(encryptionParams.getEncryptionAlgorithm());
571 c.init(Cipher.DECRYPT_MODE, encryptionParams.getEncryptionKey(),
572 encryptionParams.getEncryptionSpec());
573 } catch (NoSuchAlgorithmException e) {
574 throw new IOException(e);
575 } catch (NoSuchPaddingException e) {
576 throw new IOException(e);
577 } catch (InvalidKeyException e) {
578 throw new IOException(e);
579 } catch (InvalidAlgorithmParameterException e) {
580 throw new IOException(e);
581 }
582
Kenny Root103d5302012-05-10 10:21:06 -0700583 final long encStart = encryptionParams.getEncryptedDataStart();
584 final long end = encryptionParams.getDataEnd();
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700585 if (end < encStart) {
586 throw new IOException("end <= encStart");
587 }
588
589 final Mac mac = getMacInstance(encryptionParams);
590 if (mac != null) {
Kenny Root103d5302012-05-10 10:21:06 -0700591 final long macStart = encryptionParams.getAuthenticatedDataStart();
592 if (macStart >= Integer.MAX_VALUE) {
593 throw new IOException("macStart >= Integer.MAX_VALUE");
594 }
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700595
Kenny Root103d5302012-05-10 10:21:06 -0700596 final long furtherOffset;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700597 if (macStart >= 0 && encStart >= 0 && macStart < encStart) {
598 /*
599 * If there is authenticated data at the beginning, read
600 * that into our MAC first.
601 */
Kenny Root103d5302012-05-10 10:21:06 -0700602 final long authenticatedLengthLong = encStart - macStart;
603 if (authenticatedLengthLong > MAX_AUTHENTICATED_DATA_SIZE) {
604 throw new IOException("authenticated data is too long");
605 }
606 final int authenticatedLength = (int) authenticatedLengthLong;
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700607
Kenny Root103d5302012-05-10 10:21:06 -0700608 final byte[] authenticatedData = new byte[(int) authenticatedLength];
609
610 Streams.readFully(inStream, authenticatedData, (int) macStart,
611 authenticatedLength);
Anonymous Cowardceb1b0b2012-04-24 10:35:16 -0700612 mac.update(authenticatedData, 0, authenticatedLength);
613
614 furtherOffset = 0;
615 } else {
616 /*
617 * No authenticated data at the beginning. Just skip the
618 * required number of bytes to the beginning of the stream.
619 */
620 if (encStart > 0) {
621 furtherOffset = encStart;
622 } else {
623 furtherOffset = 0;
624 }
625 }
626
627 /*
628 * If there is data at the end of the stream we want to ignore,
629 * wrap this in a LimitedLengthInputStream.
630 */
631 if (furtherOffset >= 0 && end > furtherOffset) {
632 inStream = new LimitedLengthInputStream(inStream, furtherOffset, end - encStart);
633 } else if (furtherOffset > 0) {
634 inStream.skip(furtherOffset);
635 }
636
637 mAuthenticatedStream = new MacAuthenticatedInputStream(inStream, mac);
638
639 inStream = mAuthenticatedStream;
640 } else {
641 if (encStart >= 0) {
642 if (end > encStart) {
643 inStream = new LimitedLengthInputStream(inStream, encStart, end - encStart);
644 } else {
645 inStream.skip(encStart);
646 }
647 }
648 }
649
650 return new CipherInputStream(inStream, c);
651 }
652
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800653 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800654
Kenny Root62e1b4e2011-03-14 17:13:39 -0700655 private static final int PREFER_INTERNAL = 1;
656 private static final int PREFER_EXTERNAL = 2;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800657
Kenny Root62e1b4e2011-03-14 17:13:39 -0700658 private int recommendAppInstallLocation(int installLocation, String archiveFilePath, int flags,
659 long threshold) {
660 int prefer;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700661 boolean checkBoth = false;
Kenny Root62e1b4e2011-03-14 17:13:39 -0700662
Kenny Root6dceb882012-04-12 14:23:49 -0700663 final boolean isForwardLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
664
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700665 check_inner : {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700666 /*
667 * Explicit install flags should override the manifest settings.
668 */
Kenny Root6dceb882012-04-12 14:23:49 -0700669 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700670 prefer = PREFER_INTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700671 break check_inner;
672 } else if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700673 prefer = PREFER_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700674 break check_inner;
675 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700676
677 /* No install flags. Check for manifest option. */
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700678 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700679 prefer = PREFER_INTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700680 break check_inner;
681 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700682 prefer = PREFER_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700683 checkBoth = true;
684 break check_inner;
685 } else if (installLocation == PackageInfo.INSTALL_LOCATION_AUTO) {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700686 // We default to preferring internal storage.
687 prefer = PREFER_INTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700688 checkBoth = true;
689 break check_inner;
690 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700691
Suchi Amalapurapu40e47252010-04-07 16:15:50 -0700692 // Pick user preference
Jeff Sharkey625239a2012-09-26 22:03:49 -0700693 int installPreference = Settings.Global.getInt(getApplicationContext()
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700694 .getContentResolver(),
Jeff Sharkey625239a2012-09-26 22:03:49 -0700695 Settings.Global.DEFAULT_INSTALL_LOCATION,
Suchi Amalapurapu40e47252010-04-07 16:15:50 -0700696 PackageHelper.APP_INSTALL_AUTO);
697 if (installPreference == PackageHelper.APP_INSTALL_INTERNAL) {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700698 prefer = PREFER_INTERNAL;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -0700699 break check_inner;
700 } else if (installPreference == PackageHelper.APP_INSTALL_EXTERNAL) {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700701 prefer = PREFER_EXTERNAL;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -0700702 break check_inner;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700703 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700704
705 /*
706 * Fall back to default policy of internal-only if nothing else is
707 * specified.
708 */
709 prefer = PREFER_INTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700710 }
711
Kenny Root62e1b4e2011-03-14 17:13:39 -0700712 final boolean emulated = Environment.isExternalStorageEmulated();
713
714 final File apkFile = new File(archiveFilePath);
715
716 boolean fitsOnInternal = false;
717 if (checkBoth || prefer == PREFER_INTERNAL) {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700718 try {
Kenny Root6dceb882012-04-12 14:23:49 -0700719 fitsOnInternal = isUnderInternalThreshold(apkFile, isForwardLocked, threshold);
720 } catch (IOException e) {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700721 return PackageHelper.RECOMMEND_FAILED_INVALID_URI;
722 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800723 }
724
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700725 boolean fitsOnSd = false;
Kenny Root62e1b4e2011-03-14 17:13:39 -0700726 if (!emulated && (checkBoth || prefer == PREFER_EXTERNAL)) {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700727 try {
Kenny Root6dceb882012-04-12 14:23:49 -0700728 fitsOnSd = isUnderExternalThreshold(apkFile, isForwardLocked);
729 } catch (IOException e) {
Kenny Root1ebd74a2011-08-03 15:09:44 -0700730 return PackageHelper.RECOMMEND_FAILED_INVALID_URI;
731 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700732 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700733
734 if (prefer == PREFER_INTERNAL) {
735 if (fitsOnInternal) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700736 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
737 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700738 } else if (!emulated && prefer == PREFER_EXTERNAL) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800739 if (fitsOnSd) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700740 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800741 }
742 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700743
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700744 if (checkBoth) {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700745 if (fitsOnInternal) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700746 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Kenny Root62e1b4e2011-03-14 17:13:39 -0700747 } else if (!emulated && fitsOnSd) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700748 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800749 }
750 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700751
752 /*
753 * If they requested to be on the external media by default, return that
754 * the media was unavailable. Otherwise, indicate there was insufficient
755 * storage space available.
756 */
757 if (!emulated && (checkBoth || prefer == PREFER_EXTERNAL)
758 && !Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700759 return PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE;
Kenny Root62e1b4e2011-03-14 17:13:39 -0700760 } else {
761 return PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800762 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800763 }
764
Kenny Root1ebd74a2011-08-03 15:09:44 -0700765 /**
766 * Measure a file to see if it fits within the free space threshold.
767 *
768 * @param apkFile file to check
769 * @param threshold byte threshold to compare against
770 * @return true if file fits under threshold
771 * @throws FileNotFoundException when APK does not exist
772 */
Kenny Root6dceb882012-04-12 14:23:49 -0700773 private boolean isUnderInternalThreshold(File apkFile, boolean isForwardLocked, long threshold)
774 throws IOException {
775 long size = apkFile.length();
Kenny Root1ebd74a2011-08-03 15:09:44 -0700776 if (size == 0 && !apkFile.exists()) {
777 throw new FileNotFoundException();
778 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800779
Kenny Root6dceb882012-04-12 14:23:49 -0700780 if (isForwardLocked) {
781 size += PackageHelper.extractPublicFiles(apkFile.getAbsolutePath(), null);
782 }
783
Kenny Root62e1b4e2011-03-14 17:13:39 -0700784 final StatFs internalStats = new StatFs(Environment.getDataDirectory().getPath());
785 final long availInternalSize = (long) internalStats.getAvailableBlocks()
786 * (long) internalStats.getBlockSize();
787
788 return (availInternalSize - size) > threshold;
789 }
790
791
Kenny Root1ebd74a2011-08-03 15:09:44 -0700792 /**
793 * Measure a file to see if it fits in the external free space.
794 *
795 * @param apkFile file to check
796 * @return true if file fits
797 * @throws IOException when file does not exist
798 */
Kenny Root6dceb882012-04-12 14:23:49 -0700799 private boolean isUnderExternalThreshold(File apkFile, boolean isForwardLocked)
800 throws IOException {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700801 if (Environment.isExternalStorageEmulated()) {
802 return false;
803 }
804
Kenny Root6dceb882012-04-12 14:23:49 -0700805 final int sizeMb = calculateContainerSize(apkFile, isForwardLocked);
Kenny Root62e1b4e2011-03-14 17:13:39 -0700806
807 final int availSdMb;
808 if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
Kenny Root61942c52011-08-15 12:46:04 -0700809 final StatFs sdStats = new StatFs(Environment.getExternalStorageDirectory().getPath());
810 final int blocksToMb = (1 << 20) / sdStats.getBlockSize();
811 availSdMb = sdStats.getAvailableBlocks() * blocksToMb;
Kenny Root62e1b4e2011-03-14 17:13:39 -0700812 } else {
813 availSdMb = -1;
814 }
815
816 return availSdMb > sizeMb;
817 }
818
819 /**
820 * Calculate the container size for an APK. Takes into account the
821 *
822 * @param apkFile file from which to calculate size
823 * @return size in megabytes (2^20 bytes)
Kenny Root6dceb882012-04-12 14:23:49 -0700824 * @throws IOException when there is a problem reading the file
Kenny Root62e1b4e2011-03-14 17:13:39 -0700825 */
Kenny Root6dceb882012-04-12 14:23:49 -0700826 private int calculateContainerSize(File apkFile, boolean forwardLocked) throws IOException {
Kenny Root62e1b4e2011-03-14 17:13:39 -0700827 // Calculate size of container needed to hold base APK.
828 long sizeBytes = apkFile.length();
Kenny Root1ebd74a2011-08-03 15:09:44 -0700829 if (sizeBytes == 0 && !apkFile.exists()) {
830 throw new FileNotFoundException();
831 }
Kenny Root62e1b4e2011-03-14 17:13:39 -0700832
833 // Check all the native files that need to be copied and add that to the
834 // container size.
Kenny Root66269ea2011-07-12 14:14:01 -0700835 sizeBytes += NativeLibraryHelper.sumNativeBinariesLI(apkFile);
Kenny Root62e1b4e2011-03-14 17:13:39 -0700836
Kenny Root6dceb882012-04-12 14:23:49 -0700837 if (forwardLocked) {
838 sizeBytes += PackageHelper.extractPublicFiles(apkFile.getPath(), null);
839 }
840
Kenny Root62e1b4e2011-03-14 17:13:39 -0700841 int sizeMb = (int) (sizeBytes >> 20);
842 if ((sizeBytes - (sizeMb * 1024 * 1024)) > 0) {
843 sizeMb++;
844 }
845
846 /*
847 * Add buffer size because we don't have a good way to determine the
848 * real FAT size. Your FAT size varies with how many directory entries
849 * you need, how big the whole filesystem is, and other such headaches.
850 */
851 sizeMb++;
852
853 return sizeMb;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800854 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800855}