blob: 3ffb8bf8351d6d1cc23612b7211335a4117a886c [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 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.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Tom Taylord4a47292009-12-21 13:59:18 -080021import com.android.common.FastXmlSerializer;
22import com.android.common.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023
24import org.xmlpull.v1.XmlPullParser;
25import org.xmlpull.v1.XmlPullParserException;
26import org.xmlpull.v1.XmlSerializer;
27
28import android.app.ActivityManagerNative;
29import android.app.IActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070034import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080035import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070036import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.content.pm.ActivityInfo;
38import android.content.pm.ApplicationInfo;
39import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070040import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.pm.IPackageDataObserver;
42import android.content.pm.IPackageDeleteObserver;
43import android.content.pm.IPackageInstallObserver;
44import android.content.pm.IPackageManager;
45import android.content.pm.IPackageStatsObserver;
46import android.content.pm.InstrumentationInfo;
47import android.content.pm.PackageInfo;
48import android.content.pm.PackageManager;
49import android.content.pm.PackageStats;
50import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
51import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
52import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
53import static android.content.pm.PackageManager.PKG_INSTALL_COMPLETE;
54import static android.content.pm.PackageManager.PKG_INSTALL_INCOMPLETE;
55import android.content.pm.PackageParser;
56import android.content.pm.PermissionInfo;
57import android.content.pm.PermissionGroupInfo;
58import android.content.pm.ProviderInfo;
59import android.content.pm.ResolveInfo;
60import android.content.pm.ServiceInfo;
61import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.net.Uri;
63import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070064import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.os.Bundle;
66import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080067import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070068import android.os.Looper;
69import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.os.Parcel;
71import android.os.RemoteException;
72import android.os.Environment;
73import android.os.FileObserver;
74import android.os.FileUtils;
75import android.os.Handler;
76import android.os.ParcelFileDescriptor;
77import android.os.Process;
78import android.os.ServiceManager;
79import android.os.SystemClock;
80import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080081import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.util.*;
83import android.view.Display;
84import android.view.WindowManager;
85
86import java.io.File;
87import java.io.FileDescriptor;
88import java.io.FileInputStream;
89import java.io.FileNotFoundException;
90import java.io.FileOutputStream;
91import java.io.FileReader;
92import java.io.FilenameFilter;
93import java.io.IOException;
94import java.io.InputStream;
95import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -080096import java.security.NoSuchAlgorithmException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import java.util.ArrayList;
98import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -070099import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import java.util.Collections;
101import java.util.Comparator;
102import java.util.Enumeration;
103import java.util.HashMap;
104import java.util.HashSet;
105import java.util.Iterator;
106import java.util.List;
107import java.util.Map;
108import java.util.Set;
109import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800110import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import java.util.zip.ZipFile;
112import java.util.zip.ZipOutputStream;
113
114class PackageManagerService extends IPackageManager.Stub {
115 private static final String TAG = "PackageManager";
116 private static final boolean DEBUG_SETTINGS = false;
117 private static final boolean DEBUG_PREFERRED = false;
118
119 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
120 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400121 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 private static final int FIRST_APPLICATION_UID =
123 Process.FIRST_APPLICATION_UID;
124 private static final int MAX_APPLICATION_UIDS = 1000;
125
126 private static final boolean SHOW_INFO = false;
127
128 private static final boolean GET_CERTIFICATES = true;
129
Oscar Montemayora8529f62009-11-18 10:14:20 -0800130 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 private static final int REMOVE_EVENTS =
133 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
134 private static final int ADD_EVENTS =
135 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
136
137 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
138
139 static final int SCAN_MONITOR = 1<<0;
140 static final int SCAN_NO_DEX = 1<<1;
141 static final int SCAN_FORCE_DEX = 1<<2;
142 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800143 static final int SCAN_NEW_INSTALL = 1<<4;
144 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
146 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
147 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700148 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149
Dianne Hackborn851a5412009-05-08 12:06:44 -0700150 final int mSdkVersion = Build.VERSION.SDK_INT;
151 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
152 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 final Context mContext;
155 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700156 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 final DisplayMetrics mMetrics;
158 final int mDefParseFlags;
159 final String[] mSeparateProcesses;
160
161 // This is where all application persistent data goes.
162 final File mAppDataDir;
163
Oscar Montemayora8529f62009-11-18 10:14:20 -0800164 // If Encrypted File System feature is enabled, all application persistent data
165 // should go here instead.
166 final File mSecureAppDataDir;
167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 // This is the object monitoring the framework dir.
169 final FileObserver mFrameworkInstallObserver;
170
171 // This is the object monitoring the system app dir.
172 final FileObserver mSystemInstallObserver;
173
174 // This is the object monitoring mAppInstallDir.
175 final FileObserver mAppInstallObserver;
176
177 // This is the object monitoring mDrmAppPrivateInstallDir.
178 final FileObserver mDrmAppInstallObserver;
179
180 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
181 // LOCK HELD. Can be called with mInstallLock held.
182 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 final File mFrameworkDir;
185 final File mSystemAppDir;
186 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700187 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
189 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
190 // apps.
191 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 // Lock for state used when installing and doing other long running
196 // operations. Methods that must be called with this lock held have
197 // the prefix "LI".
198 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 // These are the directories in the 3rd party applications installed dir
201 // that we have currently loaded packages from. Keys are the application's
202 // installed zip file (absolute codePath), and values are Package.
203 final HashMap<String, PackageParser.Package> mAppDirs =
204 new HashMap<String, PackageParser.Package>();
205
206 // Information for the parser to write more useful error messages.
207 File mScanningPath;
208 int mLastScanError;
209
210 final int[] mOutPermissions = new int[3];
211
212 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 // Keys are String (package name), values are Package. This also serves
215 // as the lock for the global state. Methods that must be called with
216 // this lock held have the prefix "LP".
217 final HashMap<String, PackageParser.Package> mPackages =
218 new HashMap<String, PackageParser.Package>();
219
220 final Settings mSettings;
221 boolean mRestoredSettings;
222 boolean mReportedUidError;
223
224 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
225 int[] mGlobalGids;
226
227 // These are the built-in uid -> permission mappings that were read from the
228 // etc/permissions.xml file.
229 final SparseArray<HashSet<String>> mSystemPermissions =
230 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 // These are the built-in shared libraries that were read from the
233 // etc/permissions.xml file.
234 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800235
Dianne Hackborn49237342009-08-27 20:08:01 -0700236 // Temporary for building the final shared libraries for an .apk.
237 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800238
Dianne Hackborn49237342009-08-27 20:08:01 -0700239 // These are the features this devices supports that were read from the
240 // etc/permissions.xml file.
241 final HashMap<String, FeatureInfo> mAvailableFeatures =
242 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 // All available activities, for your resolving pleasure.
245 final ActivityIntentResolver mActivities =
246 new ActivityIntentResolver();
247
248 // All available receivers, for your resolving pleasure.
249 final ActivityIntentResolver mReceivers =
250 new ActivityIntentResolver();
251
252 // All available services, for your resolving pleasure.
253 final ServiceIntentResolver mServices = new ServiceIntentResolver();
254
255 // Keys are String (provider class name), values are Provider.
256 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
257 new HashMap<ComponentName, PackageParser.Provider>();
258
259 // Mapping from provider base names (first directory in content URI codePath)
260 // to the provider information.
261 final HashMap<String, PackageParser.Provider> mProviders =
262 new HashMap<String, PackageParser.Provider>();
263
264 // Mapping from instrumentation class names to info about them.
265 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
266 new HashMap<ComponentName, PackageParser.Instrumentation>();
267
268 // Mapping from permission names to info about them.
269 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
270 new HashMap<String, PackageParser.PermissionGroup>();
271
Dianne Hackborn854060af2009-07-09 18:14:31 -0700272 // Broadcast actions that are only available to the system.
273 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 boolean mSystemReady;
276 boolean mSafeMode;
277 boolean mHasSystemUidErrors;
278
279 ApplicationInfo mAndroidApplication;
280 final ActivityInfo mResolveActivity = new ActivityInfo();
281 final ResolveInfo mResolveInfo = new ResolveInfo();
282 ComponentName mResolveComponentName;
283 PackageParser.Package mPlatformPackage;
284
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700285 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800286 final HashMap<String, ArrayList<String>> mPendingBroadcasts
287 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700288 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800289 static final int MCS_BOUND = 3;
290 static final int END_COPY = 4;
291 static final int INIT_COPY = 5;
292 static final int MCS_UNBIND = 6;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700293 // Delay time in millisecs
294 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800295 private ServiceConnection mDefContainerConn = new ServiceConnection() {
296 public void onServiceConnected(ComponentName name, IBinder service) {
297 IMediaContainerService imcs =
298 IMediaContainerService.Stub.asInterface(service);
299 Message msg = mHandler.obtainMessage(MCS_BOUND, imcs);
300 mHandler.sendMessage(msg);
301 }
302
303 public void onServiceDisconnected(ComponentName name) {
304 }
305 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700306
307 class PackageHandler extends Handler {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800308 final ArrayList<InstallArgs> mPendingInstalls =
309 new ArrayList<InstallArgs>();
310 // Service Connection to remote media container service to copy
311 // package uri's from external media onto secure containers
312 // or internal storage.
313 private IMediaContainerService mContainerService = null;
314
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700315 PackageHandler(Looper looper) {
316 super(looper);
317 }
318 public void handleMessage(Message msg) {
319 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800320 case INIT_COPY: {
321 InstallArgs args = (InstallArgs) msg.obj;
322 args.createCopyFile();
323 Intent service = new Intent().setComponent(new ComponentName(
324 "com.android.defcontainer",
325 "com.android.defcontainer.DefaultContainerService"));
326 if (mContainerService != null) {
327 // No need to add to pending list. Use remote stub directly
328 handleStartCopy(args);
329 } else {
330 if (mContext.bindService(service, mDefContainerConn,
331 Context.BIND_AUTO_CREATE)) {
332 mPendingInstalls.add(args);
333 } else {
334 Log.e(TAG, "Failed to bind to media container service");
335 // Indicate install failure TODO add new error code
336 processPendingInstall(args,
337 PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800338 }
339 }
340 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800341 }
342 case MCS_BOUND: {
343 // Initialize mContainerService if needed.
344 if (msg.obj != null) {
345 mContainerService = (IMediaContainerService) msg.obj;
346 }
347 if (mPendingInstalls.size() > 0) {
348 InstallArgs args = mPendingInstalls.remove(0);
349 if (args != null) {
350 handleStartCopy(args);
351 }
352 }
353 break;
354 }
355 case MCS_UNBIND : {
356 if (mPendingInstalls.size() == 0) {
357 mContext.unbindService(mDefContainerConn);
358 mContainerService = null;
359 }
360 break;
361 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700362 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800363 String packages[];
364 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700365 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700366 int uids[];
367 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800368 if (mPendingBroadcasts == null) {
369 return;
370 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700371 size = mPendingBroadcasts.size();
372 if (size <= 0) {
373 // Nothing to be done. Just return
374 return;
375 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800376 packages = new String[size];
377 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700378 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800379 Iterator<HashMap.Entry<String, ArrayList<String>>>
380 it = mPendingBroadcasts.entrySet().iterator();
381 int i = 0;
382 while (it.hasNext() && i < size) {
383 HashMap.Entry<String, ArrayList<String>> ent = it.next();
384 packages[i] = ent.getKey();
385 components[i] = ent.getValue();
386 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700387 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800388 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700389 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800390 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700391 mPendingBroadcasts.clear();
392 }
393 // Send broadcasts
394 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800395 sendPackageChangedBroadcast(packages[i], true,
396 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700397 }
398 break;
399 }
400 }
401 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800402
403 // Utility method to initiate copying apk via media
404 // container service.
405 private void handleStartCopy(InstallArgs args) {
406 int ret = PackageManager.INSTALL_SUCCEEDED;
407 if (mContainerService == null) {
408 // Install error
409 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
410 } else {
411 ret = args.copyApk(mContainerService);
412 }
413 mHandler.sendEmptyMessage(MCS_UNBIND);
414 processPendingInstall(args, ret);
415 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700416 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800417
418 static boolean installOnSd(int flags) {
419 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
420 ((flags & PackageManager.INSTALL_ON_SDCARD) == 0)) {
421 return false;
422 }
423 return true;
424 }
425
426 static boolean isFwdLocked(int flags) {
427 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
428 return true;
429 }
430 return false;
431 }
432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 public static final IPackageManager main(Context context, boolean factoryTest) {
434 PackageManagerService m = new PackageManagerService(context, factoryTest);
435 ServiceManager.addService("package", m);
436 return m;
437 }
438
439 static String[] splitString(String str, char sep) {
440 int count = 1;
441 int i = 0;
442 while ((i=str.indexOf(sep, i)) >= 0) {
443 count++;
444 i++;
445 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 String[] res = new String[count];
448 i=0;
449 count = 0;
450 int lastI=0;
451 while ((i=str.indexOf(sep, i)) >= 0) {
452 res[count] = str.substring(lastI, i);
453 count++;
454 i++;
455 lastI = i;
456 }
457 res[count] = str.substring(lastI, str.length());
458 return res;
459 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800462 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465 if (mSdkVersion <= 0) {
466 Log.w(TAG, "**** ro.build.version.sdk not set!");
467 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 mContext = context;
470 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700471 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 mMetrics = new DisplayMetrics();
473 mSettings = new Settings();
474 mSettings.addSharedUserLP("android.uid.system",
475 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
476 mSettings.addSharedUserLP("android.uid.phone",
477 MULTIPLE_APPLICATION_UIDS
478 ? RADIO_UID : FIRST_APPLICATION_UID,
479 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400480 mSettings.addSharedUserLP("android.uid.log",
481 MULTIPLE_APPLICATION_UIDS
482 ? LOG_UID : FIRST_APPLICATION_UID,
483 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484
485 String separateProcesses = SystemProperties.get("debug.separate_processes");
486 if (separateProcesses != null && separateProcesses.length() > 0) {
487 if ("*".equals(separateProcesses)) {
488 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
489 mSeparateProcesses = null;
490 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
491 } else {
492 mDefParseFlags = 0;
493 mSeparateProcesses = separateProcesses.split(",");
494 Log.w(TAG, "Running with debug.separate_processes: "
495 + separateProcesses);
496 }
497 } else {
498 mDefParseFlags = 0;
499 mSeparateProcesses = null;
500 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 Installer installer = new Installer();
503 // Little hacky thing to check if installd is here, to determine
504 // whether we are running on the simulator and thus need to take
505 // care of building the /data file structure ourself.
506 // (apparently the sim now has a working installer)
507 if (installer.ping() && Process.supportsProcesses()) {
508 mInstaller = installer;
509 } else {
510 mInstaller = null;
511 }
512
513 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
514 Display d = wm.getDefaultDisplay();
515 d.getMetrics(mMetrics);
516
517 synchronized (mInstallLock) {
518 synchronized (mPackages) {
519 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700520 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 File dataDir = Environment.getDataDirectory();
523 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800524 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
526
527 if (mInstaller == null) {
528 // Make sure these dirs exist, when we are running in
529 // the simulator.
530 // Make a wide-open directory for random misc stuff.
531 File miscDir = new File(dataDir, "misc");
532 miscDir.mkdirs();
533 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800534 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 mDrmAppPrivateInstallDir.mkdirs();
536 }
537
538 readPermissions();
539
540 mRestoredSettings = mSettings.readLP();
541 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800542
543 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800545
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800546 // Set flag to monitor and not change apk file paths when
547 // scanning install directories.
548 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700549 if (mNoDexOpt) {
550 Log.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800551 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700552 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700557 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700560 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 /**
563 * Out of paranoia, ensure that everything in the boot class
564 * path has been dexed.
565 */
566 String bootClassPath = System.getProperty("java.boot.class.path");
567 if (bootClassPath != null) {
568 String[] paths = splitString(bootClassPath, ':');
569 for (int i=0; i<paths.length; i++) {
570 try {
571 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
572 libFiles.add(paths[i]);
573 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700574 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 }
576 } catch (FileNotFoundException e) {
577 Log.w(TAG, "Boot class path not found: " + paths[i]);
578 } catch (IOException e) {
579 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
580 }
581 }
582 } else {
583 Log.w(TAG, "No BOOTCLASSPATH found!");
584 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 /**
587 * Also ensure all external libraries have had dexopt run on them.
588 */
589 if (mSharedLibraries.size() > 0) {
590 Iterator<String> libs = mSharedLibraries.values().iterator();
591 while (libs.hasNext()) {
592 String lib = libs.next();
593 try {
594 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
595 libFiles.add(lib);
596 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700597 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 }
599 } catch (FileNotFoundException e) {
600 Log.w(TAG, "Library not found: " + lib);
601 } catch (IOException e) {
602 Log.w(TAG, "Exception reading library: " + lib, e);
603 }
604 }
605 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 // Gross hack for now: we know this file doesn't contain any
608 // code, so don't dexopt it to avoid the resulting log spew.
609 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 /**
612 * And there are a number of commands implemented in Java, which
613 * we currently need to do the dexopt on so that they can be
614 * run from a non-root shell.
615 */
616 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700617 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 for (int i=0; i<frameworkFiles.length; i++) {
619 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
620 String path = libPath.getPath();
621 // Skip the file if we alrady did it.
622 if (libFiles.contains(path)) {
623 continue;
624 }
625 // Skip the file if it is not a type we want to dexopt.
626 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
627 continue;
628 }
629 try {
630 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
631 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700632 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 }
634 } catch (FileNotFoundException e) {
635 Log.w(TAG, "Jar not found: " + path);
636 } catch (IOException e) {
637 Log.w(TAG, "Exception reading jar: " + path, e);
638 }
639 }
640 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800641
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700642 if (didDexOpt) {
643 // If we had to do a dexopt of one of the previous
644 // things, then something on the system has changed.
645 // Consider this significant, and wipe away all other
646 // existing dexopt files to ensure we don't leave any
647 // dangling around.
648 String[] files = mDalvikCacheDir.list();
649 if (files != null) {
650 for (int i=0; i<files.length; i++) {
651 String fn = files[i];
652 if (fn.startsWith("data@app@")
653 || fn.startsWith("data@app-private@")) {
654 Log.i(TAG, "Pruning dalvik file: " + fn);
655 (new File(mDalvikCacheDir, fn)).delete();
656 }
657 }
658 }
659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 mFrameworkInstallObserver = new AppDirObserver(
663 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
664 mFrameworkInstallObserver.startWatching();
665 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800666 scanMode | SCAN_NO_DEX);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
668 mSystemInstallObserver = new AppDirObserver(
669 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
670 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800671 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 mAppInstallDir = new File(dataDir, "app");
673 if (mInstaller == null) {
674 // Make sure these dirs exist, when we are running in
675 // the simulator.
676 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
677 }
678 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800679 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 //clean up list
681 for(int i = 0; i < deletePkgsList.size(); i++) {
682 //clean up here
683 cleanupInstallFailedPackage(deletePkgsList.get(i));
684 }
685 //delete tmp files
686 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800687
688 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 SystemClock.uptimeMillis());
690 mAppInstallObserver = new AppDirObserver(
691 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
692 mAppInstallObserver.startWatching();
693 scanDirLI(mAppInstallDir, 0, scanMode);
694
695 mDrmAppInstallObserver = new AppDirObserver(
696 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
697 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800698 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800700 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 SystemClock.uptimeMillis());
702 Log.i(TAG, "Time to scan packages: "
703 + ((SystemClock.uptimeMillis()-startTime)/1000f)
704 + " seconds");
705
706 updatePermissionsLP();
707
708 mSettings.writeLP();
709
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800710 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 // Now after opening every single application zip, make sure they
714 // are all flushed. Not really needed, but keeps things nice and
715 // tidy.
716 Runtime.getRuntime().gc();
717 } // synchronized (mPackages)
718 } // synchronized (mInstallLock)
719 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 @Override
722 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
723 throws RemoteException {
724 try {
725 return super.onTransact(code, data, reply, flags);
726 } catch (RuntimeException e) {
727 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
728 Log.e(TAG, "Package Manager Crash", e);
729 }
730 throw e;
731 }
732 }
733
Dianne Hackborne6620b22010-01-22 14:46:21 -0800734 void cleanupInstallFailedPackage(PackageSetting ps) {
735 Log.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800737 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
738 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 if (retCode < 0) {
740 Log.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800741 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 }
743 } else {
744 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800745 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 File dataDir = new File(pkg.applicationInfo.dataDir);
747 dataDir.delete();
748 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800749 if (ps.codePath != null) {
750 if (!ps.codePath.delete()) {
751 Log.w(TAG, "Unable to remove old code file: " + ps.codePath);
752 }
753 }
754 if (ps.resourcePath != null) {
755 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
756 Log.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
757 }
758 }
759 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 }
761
762 void readPermissions() {
763 // Read permissions from .../etc/permission directory.
764 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
765 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
766 Log.w(TAG, "No directory " + libraryDir + ", skipping");
767 return;
768 }
769 if (!libraryDir.canRead()) {
770 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
771 return;
772 }
773
774 // Iterate over the files in the directory and scan .xml files
775 for (File f : libraryDir.listFiles()) {
776 // We'll read platform.xml last
777 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
778 continue;
779 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 if (!f.getPath().endsWith(".xml")) {
782 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
783 continue;
784 }
785 if (!f.canRead()) {
786 Log.w(TAG, "Permissions library file " + f + " cannot be read");
787 continue;
788 }
789
790 readPermissionsFromXml(f);
791 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
794 final File permFile = new File(Environment.getRootDirectory(),
795 "etc/permissions/platform.xml");
796 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800797
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700798 StringBuilder sb = new StringBuilder(128);
799 sb.append("Libs:");
800 Iterator<String> it = mSharedLibraries.keySet().iterator();
801 while (it.hasNext()) {
802 sb.append(' ');
803 String name = it.next();
804 sb.append(name);
805 sb.append(':');
806 sb.append(mSharedLibraries.get(name));
807 }
808 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800809
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700810 sb.setLength(0);
811 sb.append("Features:");
812 it = mAvailableFeatures.keySet().iterator();
813 while (it.hasNext()) {
814 sb.append(' ');
815 sb.append(it.next());
816 }
817 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800819
820 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 FileReader permReader = null;
822 try {
823 permReader = new FileReader(permFile);
824 } catch (FileNotFoundException e) {
825 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
826 return;
827 }
828
829 try {
830 XmlPullParser parser = Xml.newPullParser();
831 parser.setInput(permReader);
832
833 XmlUtils.beginDocument(parser, "permissions");
834
835 while (true) {
836 XmlUtils.nextElement(parser);
837 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
838 break;
839 }
840
841 String name = parser.getName();
842 if ("group".equals(name)) {
843 String gidStr = parser.getAttributeValue(null, "gid");
844 if (gidStr != null) {
845 int gid = Integer.parseInt(gidStr);
846 mGlobalGids = appendInt(mGlobalGids, gid);
847 } else {
848 Log.w(TAG, "<group> without gid at "
849 + parser.getPositionDescription());
850 }
851
852 XmlUtils.skipCurrentTag(parser);
853 continue;
854 } else if ("permission".equals(name)) {
855 String perm = parser.getAttributeValue(null, "name");
856 if (perm == null) {
857 Log.w(TAG, "<permission> without name at "
858 + parser.getPositionDescription());
859 XmlUtils.skipCurrentTag(parser);
860 continue;
861 }
862 perm = perm.intern();
863 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 } else if ("assign-permission".equals(name)) {
866 String perm = parser.getAttributeValue(null, "name");
867 if (perm == null) {
868 Log.w(TAG, "<assign-permission> without name at "
869 + parser.getPositionDescription());
870 XmlUtils.skipCurrentTag(parser);
871 continue;
872 }
873 String uidStr = parser.getAttributeValue(null, "uid");
874 if (uidStr == null) {
875 Log.w(TAG, "<assign-permission> without uid at "
876 + parser.getPositionDescription());
877 XmlUtils.skipCurrentTag(parser);
878 continue;
879 }
880 int uid = Process.getUidForName(uidStr);
881 if (uid < 0) {
882 Log.w(TAG, "<assign-permission> with unknown uid \""
883 + uidStr + "\" at "
884 + parser.getPositionDescription());
885 XmlUtils.skipCurrentTag(parser);
886 continue;
887 }
888 perm = perm.intern();
889 HashSet<String> perms = mSystemPermissions.get(uid);
890 if (perms == null) {
891 perms = new HashSet<String>();
892 mSystemPermissions.put(uid, perms);
893 }
894 perms.add(perm);
895 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 } else if ("library".equals(name)) {
898 String lname = parser.getAttributeValue(null, "name");
899 String lfile = parser.getAttributeValue(null, "file");
900 if (lname == null) {
901 Log.w(TAG, "<library> without name at "
902 + parser.getPositionDescription());
903 } else if (lfile == null) {
904 Log.w(TAG, "<library> without file at "
905 + parser.getPositionDescription());
906 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700907 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -0700908 mSharedLibraries.put(lname, lfile);
909 }
910 XmlUtils.skipCurrentTag(parser);
911 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800912
Dianne Hackborn49237342009-08-27 20:08:01 -0700913 } else if ("feature".equals(name)) {
914 String fname = parser.getAttributeValue(null, "name");
915 if (fname == null) {
916 Log.w(TAG, "<feature> without name at "
917 + parser.getPositionDescription());
918 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700919 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -0700920 FeatureInfo fi = new FeatureInfo();
921 fi.name = fname;
922 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 }
924 XmlUtils.skipCurrentTag(parser);
925 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 } else {
928 XmlUtils.skipCurrentTag(parser);
929 continue;
930 }
931
932 }
933 } catch (XmlPullParserException e) {
934 Log.w(TAG, "Got execption parsing permissions.", e);
935 } catch (IOException e) {
936 Log.w(TAG, "Got execption parsing permissions.", e);
937 }
938 }
939
940 void readPermission(XmlPullParser parser, String name)
941 throws IOException, XmlPullParserException {
942
943 name = name.intern();
944
945 BasePermission bp = mSettings.mPermissions.get(name);
946 if (bp == null) {
947 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
948 mSettings.mPermissions.put(name, bp);
949 }
950 int outerDepth = parser.getDepth();
951 int type;
952 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
953 && (type != XmlPullParser.END_TAG
954 || parser.getDepth() > outerDepth)) {
955 if (type == XmlPullParser.END_TAG
956 || type == XmlPullParser.TEXT) {
957 continue;
958 }
959
960 String tagName = parser.getName();
961 if ("group".equals(tagName)) {
962 String gidStr = parser.getAttributeValue(null, "gid");
963 if (gidStr != null) {
964 int gid = Process.getGidForName(gidStr);
965 bp.gids = appendInt(bp.gids, gid);
966 } else {
967 Log.w(TAG, "<group> without gid at "
968 + parser.getPositionDescription());
969 }
970 }
971 XmlUtils.skipCurrentTag(parser);
972 }
973 }
974
975 static int[] appendInt(int[] cur, int val) {
976 if (cur == null) {
977 return new int[] { val };
978 }
979 final int N = cur.length;
980 for (int i=0; i<N; i++) {
981 if (cur[i] == val) {
982 return cur;
983 }
984 }
985 int[] ret = new int[N+1];
986 System.arraycopy(cur, 0, ret, 0, N);
987 ret[N] = val;
988 return ret;
989 }
990
991 static int[] appendInts(int[] cur, int[] add) {
992 if (add == null) return cur;
993 if (cur == null) return add;
994 final int N = add.length;
995 for (int i=0; i<N; i++) {
996 cur = appendInt(cur, add[i]);
997 }
998 return cur;
999 }
1000
1001 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001002 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1003 // The package has been uninstalled but has retained data and resources.
1004 return PackageParser.generatePackageInfo(p, null, flags);
1005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 final PackageSetting ps = (PackageSetting)p.mExtras;
1007 if (ps == null) {
1008 return null;
1009 }
1010 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1011 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1012 }
1013
1014 public PackageInfo getPackageInfo(String packageName, int flags) {
1015 synchronized (mPackages) {
1016 PackageParser.Package p = mPackages.get(packageName);
1017 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001018 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 + ": " + p);
1020 if (p != null) {
1021 return generatePackageInfo(p, flags);
1022 }
1023 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1024 return generatePackageInfoFromSettingsLP(packageName, flags);
1025 }
1026 }
1027 return null;
1028 }
1029
1030 public int getPackageUid(String packageName) {
1031 synchronized (mPackages) {
1032 PackageParser.Package p = mPackages.get(packageName);
1033 if(p != null) {
1034 return p.applicationInfo.uid;
1035 }
1036 PackageSetting ps = mSettings.mPackages.get(packageName);
1037 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1038 return -1;
1039 }
1040 p = ps.pkg;
1041 return p != null ? p.applicationInfo.uid : -1;
1042 }
1043 }
1044
1045 public int[] getPackageGids(String packageName) {
1046 synchronized (mPackages) {
1047 PackageParser.Package p = mPackages.get(packageName);
1048 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001049 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 + ": " + p);
1051 if (p != null) {
1052 final PackageSetting ps = (PackageSetting)p.mExtras;
1053 final SharedUserSetting suid = ps.sharedUser;
1054 return suid != null ? suid.gids : ps.gids;
1055 }
1056 }
1057 // stupid thing to indicate an error.
1058 return new int[0];
1059 }
1060
1061 public PermissionInfo getPermissionInfo(String name, int flags) {
1062 synchronized (mPackages) {
1063 final BasePermission p = mSettings.mPermissions.get(name);
1064 if (p != null && p.perm != null) {
1065 return PackageParser.generatePermissionInfo(p.perm, flags);
1066 }
1067 return null;
1068 }
1069 }
1070
1071 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1072 synchronized (mPackages) {
1073 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1074 for (BasePermission p : mSettings.mPermissions.values()) {
1075 if (group == null) {
1076 if (p.perm.info.group == null) {
1077 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1078 }
1079 } else {
1080 if (group.equals(p.perm.info.group)) {
1081 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1082 }
1083 }
1084 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 if (out.size() > 0) {
1087 return out;
1088 }
1089 return mPermissionGroups.containsKey(group) ? out : null;
1090 }
1091 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1094 synchronized (mPackages) {
1095 return PackageParser.generatePermissionGroupInfo(
1096 mPermissionGroups.get(name), flags);
1097 }
1098 }
1099
1100 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1101 synchronized (mPackages) {
1102 final int N = mPermissionGroups.size();
1103 ArrayList<PermissionGroupInfo> out
1104 = new ArrayList<PermissionGroupInfo>(N);
1105 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1106 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1107 }
1108 return out;
1109 }
1110 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1113 PackageSetting ps = mSettings.mPackages.get(packageName);
1114 if(ps != null) {
1115 if(ps.pkg == null) {
1116 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1117 if(pInfo != null) {
1118 return pInfo.applicationInfo;
1119 }
1120 return null;
1121 }
1122 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1123 }
1124 return null;
1125 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1128 PackageSetting ps = mSettings.mPackages.get(packageName);
1129 if(ps != null) {
1130 if(ps.pkg == null) {
1131 ps.pkg = new PackageParser.Package(packageName);
1132 ps.pkg.applicationInfo.packageName = packageName;
1133 }
1134 return generatePackageInfo(ps.pkg, flags);
1135 }
1136 return null;
1137 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1140 synchronized (mPackages) {
1141 PackageParser.Package p = mPackages.get(packageName);
1142 if (Config.LOGV) Log.v(
1143 TAG, "getApplicationInfo " + packageName
1144 + ": " + p);
1145 if (p != null) {
1146 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001147 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 }
1149 if ("android".equals(packageName)||"system".equals(packageName)) {
1150 return mAndroidApplication;
1151 }
1152 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1153 return generateApplicationInfoFromSettingsLP(packageName, flags);
1154 }
1155 }
1156 return null;
1157 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001158
1159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1161 mContext.enforceCallingOrSelfPermission(
1162 android.Manifest.permission.CLEAR_APP_CACHE, null);
1163 // Queue up an async operation since clearing cache may take a little while.
1164 mHandler.post(new Runnable() {
1165 public void run() {
1166 mHandler.removeCallbacks(this);
1167 int retCode = -1;
1168 if (mInstaller != null) {
1169 retCode = mInstaller.freeCache(freeStorageSize);
1170 if (retCode < 0) {
1171 Log.w(TAG, "Couldn't clear application caches");
1172 }
1173 } //end if mInstaller
1174 if (observer != null) {
1175 try {
1176 observer.onRemoveCompleted(null, (retCode >= 0));
1177 } catch (RemoteException e) {
1178 Log.w(TAG, "RemoveException when invoking call back");
1179 }
1180 }
1181 }
1182 });
1183 }
1184
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001185 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001186 mContext.enforceCallingOrSelfPermission(
1187 android.Manifest.permission.CLEAR_APP_CACHE, null);
1188 // Queue up an async operation since clearing cache may take a little while.
1189 mHandler.post(new Runnable() {
1190 public void run() {
1191 mHandler.removeCallbacks(this);
1192 int retCode = -1;
1193 if (mInstaller != null) {
1194 retCode = mInstaller.freeCache(freeStorageSize);
1195 if (retCode < 0) {
1196 Log.w(TAG, "Couldn't clear application caches");
1197 }
1198 }
1199 if(pi != null) {
1200 try {
1201 // Callback via pending intent
1202 int code = (retCode >= 0) ? 1 : 0;
1203 pi.sendIntent(null, code, null,
1204 null, null);
1205 } catch (SendIntentException e1) {
1206 Log.i(TAG, "Failed to send pending intent");
1207 }
1208 }
1209 }
1210 });
1211 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1214 synchronized (mPackages) {
1215 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001216
1217 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001219 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 }
1221 if (mResolveComponentName.equals(component)) {
1222 return mResolveActivity;
1223 }
1224 }
1225 return null;
1226 }
1227
1228 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1229 synchronized (mPackages) {
1230 PackageParser.Activity a = mReceivers.mActivities.get(component);
1231 if (Config.LOGV) Log.v(
1232 TAG, "getReceiverInfo " + component + ": " + a);
1233 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1234 return PackageParser.generateActivityInfo(a, flags);
1235 }
1236 }
1237 return null;
1238 }
1239
1240 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1241 synchronized (mPackages) {
1242 PackageParser.Service s = mServices.mServices.get(component);
1243 if (Config.LOGV) Log.v(
1244 TAG, "getServiceInfo " + component + ": " + s);
1245 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1246 return PackageParser.generateServiceInfo(s, flags);
1247 }
1248 }
1249 return null;
1250 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 public String[] getSystemSharedLibraryNames() {
1253 Set<String> libSet;
1254 synchronized (mPackages) {
1255 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001256 int size = libSet.size();
1257 if (size > 0) {
1258 String[] libs = new String[size];
1259 libSet.toArray(libs);
1260 return libs;
1261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001263 return null;
1264 }
1265
1266 public FeatureInfo[] getSystemAvailableFeatures() {
1267 Collection<FeatureInfo> featSet;
1268 synchronized (mPackages) {
1269 featSet = mAvailableFeatures.values();
1270 int size = featSet.size();
1271 if (size > 0) {
1272 FeatureInfo[] features = new FeatureInfo[size+1];
1273 featSet.toArray(features);
1274 FeatureInfo fi = new FeatureInfo();
1275 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1276 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1277 features[size] = fi;
1278 return features;
1279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 }
1281 return null;
1282 }
1283
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001284 public boolean hasSystemFeature(String name) {
1285 synchronized (mPackages) {
1286 return mAvailableFeatures.containsKey(name);
1287 }
1288 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 public int checkPermission(String permName, String pkgName) {
1291 synchronized (mPackages) {
1292 PackageParser.Package p = mPackages.get(pkgName);
1293 if (p != null && p.mExtras != null) {
1294 PackageSetting ps = (PackageSetting)p.mExtras;
1295 if (ps.sharedUser != null) {
1296 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1297 return PackageManager.PERMISSION_GRANTED;
1298 }
1299 } else if (ps.grantedPermissions.contains(permName)) {
1300 return PackageManager.PERMISSION_GRANTED;
1301 }
1302 }
1303 }
1304 return PackageManager.PERMISSION_DENIED;
1305 }
1306
1307 public int checkUidPermission(String permName, int uid) {
1308 synchronized (mPackages) {
1309 Object obj = mSettings.getUserIdLP(uid);
1310 if (obj != null) {
1311 if (obj instanceof SharedUserSetting) {
1312 SharedUserSetting sus = (SharedUserSetting)obj;
1313 if (sus.grantedPermissions.contains(permName)) {
1314 return PackageManager.PERMISSION_GRANTED;
1315 }
1316 } else if (obj instanceof PackageSetting) {
1317 PackageSetting ps = (PackageSetting)obj;
1318 if (ps.grantedPermissions.contains(permName)) {
1319 return PackageManager.PERMISSION_GRANTED;
1320 }
1321 }
1322 } else {
1323 HashSet<String> perms = mSystemPermissions.get(uid);
1324 if (perms != null && perms.contains(permName)) {
1325 return PackageManager.PERMISSION_GRANTED;
1326 }
1327 }
1328 }
1329 return PackageManager.PERMISSION_DENIED;
1330 }
1331
1332 private BasePermission findPermissionTreeLP(String permName) {
1333 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1334 if (permName.startsWith(bp.name) &&
1335 permName.length() > bp.name.length() &&
1336 permName.charAt(bp.name.length()) == '.') {
1337 return bp;
1338 }
1339 }
1340 return null;
1341 }
1342
1343 private BasePermission checkPermissionTreeLP(String permName) {
1344 if (permName != null) {
1345 BasePermission bp = findPermissionTreeLP(permName);
1346 if (bp != null) {
1347 if (bp.uid == Binder.getCallingUid()) {
1348 return bp;
1349 }
1350 throw new SecurityException("Calling uid "
1351 + Binder.getCallingUid()
1352 + " is not allowed to add to permission tree "
1353 + bp.name + " owned by uid " + bp.uid);
1354 }
1355 }
1356 throw new SecurityException("No permission tree found for " + permName);
1357 }
1358
1359 public boolean addPermission(PermissionInfo info) {
1360 synchronized (mPackages) {
1361 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1362 throw new SecurityException("Label must be specified in permission");
1363 }
1364 BasePermission tree = checkPermissionTreeLP(info.name);
1365 BasePermission bp = mSettings.mPermissions.get(info.name);
1366 boolean added = bp == null;
1367 if (added) {
1368 bp = new BasePermission(info.name, tree.sourcePackage,
1369 BasePermission.TYPE_DYNAMIC);
1370 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1371 throw new SecurityException(
1372 "Not allowed to modify non-dynamic permission "
1373 + info.name);
1374 }
1375 bp.perm = new PackageParser.Permission(tree.perm.owner,
1376 new PermissionInfo(info));
1377 bp.perm.info.packageName = tree.perm.info.packageName;
1378 bp.uid = tree.uid;
1379 if (added) {
1380 mSettings.mPermissions.put(info.name, bp);
1381 }
1382 mSettings.writeLP();
1383 return added;
1384 }
1385 }
1386
1387 public void removePermission(String name) {
1388 synchronized (mPackages) {
1389 checkPermissionTreeLP(name);
1390 BasePermission bp = mSettings.mPermissions.get(name);
1391 if (bp != null) {
1392 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1393 throw new SecurityException(
1394 "Not allowed to modify non-dynamic permission "
1395 + name);
1396 }
1397 mSettings.mPermissions.remove(name);
1398 mSettings.writeLP();
1399 }
1400 }
1401 }
1402
Dianne Hackborn854060af2009-07-09 18:14:31 -07001403 public boolean isProtectedBroadcast(String actionName) {
1404 synchronized (mPackages) {
1405 return mProtectedBroadcasts.contains(actionName);
1406 }
1407 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 public int checkSignatures(String pkg1, String pkg2) {
1410 synchronized (mPackages) {
1411 PackageParser.Package p1 = mPackages.get(pkg1);
1412 PackageParser.Package p2 = mPackages.get(pkg2);
1413 if (p1 == null || p1.mExtras == null
1414 || p2 == null || p2.mExtras == null) {
1415 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1416 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001417 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 }
1419 }
1420
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001421 public int checkUidSignatures(int uid1, int uid2) {
1422 synchronized (mPackages) {
1423 Signature[] s1;
1424 Signature[] s2;
1425 Object obj = mSettings.getUserIdLP(uid1);
1426 if (obj != null) {
1427 if (obj instanceof SharedUserSetting) {
1428 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1429 } else if (obj instanceof PackageSetting) {
1430 s1 = ((PackageSetting)obj).signatures.mSignatures;
1431 } else {
1432 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1433 }
1434 } else {
1435 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1436 }
1437 obj = mSettings.getUserIdLP(uid2);
1438 if (obj != null) {
1439 if (obj instanceof SharedUserSetting) {
1440 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1441 } else if (obj instanceof PackageSetting) {
1442 s2 = ((PackageSetting)obj).signatures.mSignatures;
1443 } else {
1444 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1445 }
1446 } else {
1447 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1448 }
1449 return checkSignaturesLP(s1, s2);
1450 }
1451 }
1452
1453 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1454 if (s1 == null) {
1455 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1457 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1458 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001459 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1461 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001462 final int N1 = s1.length;
1463 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 for (int i=0; i<N1; i++) {
1465 boolean match = false;
1466 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001467 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 match = true;
1469 break;
1470 }
1471 }
1472 if (!match) {
1473 return PackageManager.SIGNATURE_NO_MATCH;
1474 }
1475 }
1476 return PackageManager.SIGNATURE_MATCH;
1477 }
1478
1479 public String[] getPackagesForUid(int uid) {
1480 synchronized (mPackages) {
1481 Object obj = mSettings.getUserIdLP(uid);
1482 if (obj instanceof SharedUserSetting) {
1483 SharedUserSetting sus = (SharedUserSetting)obj;
1484 final int N = sus.packages.size();
1485 String[] res = new String[N];
1486 Iterator<PackageSetting> it = sus.packages.iterator();
1487 int i=0;
1488 while (it.hasNext()) {
1489 res[i++] = it.next().name;
1490 }
1491 return res;
1492 } else if (obj instanceof PackageSetting) {
1493 PackageSetting ps = (PackageSetting)obj;
1494 return new String[] { ps.name };
1495 }
1496 }
1497 return null;
1498 }
1499
1500 public String getNameForUid(int uid) {
1501 synchronized (mPackages) {
1502 Object obj = mSettings.getUserIdLP(uid);
1503 if (obj instanceof SharedUserSetting) {
1504 SharedUserSetting sus = (SharedUserSetting)obj;
1505 return sus.name + ":" + sus.userId;
1506 } else if (obj instanceof PackageSetting) {
1507 PackageSetting ps = (PackageSetting)obj;
1508 return ps.name;
1509 }
1510 }
1511 return null;
1512 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 public int getUidForSharedUser(String sharedUserName) {
1515 if(sharedUserName == null) {
1516 return -1;
1517 }
1518 synchronized (mPackages) {
1519 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1520 if(suid == null) {
1521 return -1;
1522 }
1523 return suid.userId;
1524 }
1525 }
1526
1527 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1528 int flags) {
1529 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001530 return chooseBestActivity(intent, resolvedType, flags, query);
1531 }
1532
Mihai Predaeae850c2009-05-13 10:13:48 +02001533 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1534 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 if (query != null) {
1536 final int N = query.size();
1537 if (N == 1) {
1538 return query.get(0);
1539 } else if (N > 1) {
1540 // If there is more than one activity with the same priority,
1541 // then let the user decide between them.
1542 ResolveInfo r0 = query.get(0);
1543 ResolveInfo r1 = query.get(1);
1544 if (false) {
1545 System.out.println(r0.activityInfo.name +
1546 "=" + r0.priority + " vs " +
1547 r1.activityInfo.name +
1548 "=" + r1.priority);
1549 }
1550 // If the first activity has a higher priority, or a different
1551 // default, then it is always desireable to pick it.
1552 if (r0.priority != r1.priority
1553 || r0.preferredOrder != r1.preferredOrder
1554 || r0.isDefault != r1.isDefault) {
1555 return query.get(0);
1556 }
1557 // If we have saved a preference for a preferred activity for
1558 // this Intent, use that.
1559 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1560 flags, query, r0.priority);
1561 if (ri != null) {
1562 return ri;
1563 }
1564 return mResolveInfo;
1565 }
1566 }
1567 return null;
1568 }
1569
1570 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1571 int flags, List<ResolveInfo> query, int priority) {
1572 synchronized (mPackages) {
1573 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1574 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001575 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1577 if (prefs != null && prefs.size() > 0) {
1578 // First figure out how good the original match set is.
1579 // We will only allow preferred activities that came
1580 // from the same match quality.
1581 int match = 0;
1582 final int N = query.size();
1583 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1584 for (int j=0; j<N; j++) {
1585 ResolveInfo ri = query.get(j);
1586 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1587 + ": 0x" + Integer.toHexString(match));
1588 if (ri.match > match) match = ri.match;
1589 }
1590 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1591 + Integer.toHexString(match));
1592 match &= IntentFilter.MATCH_CATEGORY_MASK;
1593 final int M = prefs.size();
1594 for (int i=0; i<M; i++) {
1595 PreferredActivity pa = prefs.get(i);
1596 if (pa.mMatch != match) {
1597 continue;
1598 }
1599 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1600 if (DEBUG_PREFERRED) {
1601 Log.v(TAG, "Got preferred activity:");
1602 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1603 }
1604 if (ai != null) {
1605 for (int j=0; j<N; j++) {
1606 ResolveInfo ri = query.get(j);
1607 if (!ri.activityInfo.applicationInfo.packageName
1608 .equals(ai.applicationInfo.packageName)) {
1609 continue;
1610 }
1611 if (!ri.activityInfo.name.equals(ai.name)) {
1612 continue;
1613 }
1614
1615 // Okay we found a previously set preferred app.
1616 // If the result set is different from when this
1617 // was created, we need to clear it and re-ask the
1618 // user their preference.
1619 if (!pa.sameSet(query, priority)) {
1620 Log.i(TAG, "Result set changed, dropping preferred activity for "
1621 + intent + " type " + resolvedType);
1622 mSettings.mPreferredActivities.removeFilter(pa);
1623 return null;
1624 }
1625
1626 // Yay!
1627 return ri;
1628 }
1629 }
1630 }
1631 }
1632 }
1633 return null;
1634 }
1635
1636 public List<ResolveInfo> queryIntentActivities(Intent intent,
1637 String resolvedType, int flags) {
1638 ComponentName comp = intent.getComponent();
1639 if (comp != null) {
1640 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1641 ActivityInfo ai = getActivityInfo(comp, flags);
1642 if (ai != null) {
1643 ResolveInfo ri = new ResolveInfo();
1644 ri.activityInfo = ai;
1645 list.add(ri);
1646 }
1647 return list;
1648 }
1649
1650 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001651 String pkgName = intent.getPackage();
1652 if (pkgName == null) {
1653 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1654 resolvedType, flags);
1655 }
1656 PackageParser.Package pkg = mPackages.get(pkgName);
1657 if (pkg != null) {
1658 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1659 resolvedType, flags, pkg.activities);
1660 }
1661 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 }
1663 }
1664
1665 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1666 Intent[] specifics, String[] specificTypes, Intent intent,
1667 String resolvedType, int flags) {
1668 final String resultsAction = intent.getAction();
1669
1670 List<ResolveInfo> results = queryIntentActivities(
1671 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1672 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1673
1674 int specificsPos = 0;
1675 int N;
1676
1677 // todo: note that the algorithm used here is O(N^2). This
1678 // isn't a problem in our current environment, but if we start running
1679 // into situations where we have more than 5 or 10 matches then this
1680 // should probably be changed to something smarter...
1681
1682 // First we go through and resolve each of the specific items
1683 // that were supplied, taking care of removing any corresponding
1684 // duplicate items in the generic resolve list.
1685 if (specifics != null) {
1686 for (int i=0; i<specifics.length; i++) {
1687 final Intent sintent = specifics[i];
1688 if (sintent == null) {
1689 continue;
1690 }
1691
1692 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1693 String action = sintent.getAction();
1694 if (resultsAction != null && resultsAction.equals(action)) {
1695 // If this action was explicitly requested, then don't
1696 // remove things that have it.
1697 action = null;
1698 }
1699 ComponentName comp = sintent.getComponent();
1700 ResolveInfo ri = null;
1701 ActivityInfo ai = null;
1702 if (comp == null) {
1703 ri = resolveIntent(
1704 sintent,
1705 specificTypes != null ? specificTypes[i] : null,
1706 flags);
1707 if (ri == null) {
1708 continue;
1709 }
1710 if (ri == mResolveInfo) {
1711 // ACK! Must do something better with this.
1712 }
1713 ai = ri.activityInfo;
1714 comp = new ComponentName(ai.applicationInfo.packageName,
1715 ai.name);
1716 } else {
1717 ai = getActivityInfo(comp, flags);
1718 if (ai == null) {
1719 continue;
1720 }
1721 }
1722
1723 // Look for any generic query activities that are duplicates
1724 // of this specific one, and remove them from the results.
1725 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1726 N = results.size();
1727 int j;
1728 for (j=specificsPos; j<N; j++) {
1729 ResolveInfo sri = results.get(j);
1730 if ((sri.activityInfo.name.equals(comp.getClassName())
1731 && sri.activityInfo.applicationInfo.packageName.equals(
1732 comp.getPackageName()))
1733 || (action != null && sri.filter.matchAction(action))) {
1734 results.remove(j);
1735 if (Config.LOGV) Log.v(
1736 TAG, "Removing duplicate item from " + j
1737 + " due to specific " + specificsPos);
1738 if (ri == null) {
1739 ri = sri;
1740 }
1741 j--;
1742 N--;
1743 }
1744 }
1745
1746 // Add this specific item to its proper place.
1747 if (ri == null) {
1748 ri = new ResolveInfo();
1749 ri.activityInfo = ai;
1750 }
1751 results.add(specificsPos, ri);
1752 ri.specificIndex = i;
1753 specificsPos++;
1754 }
1755 }
1756
1757 // Now we go through the remaining generic results and remove any
1758 // duplicate actions that are found here.
1759 N = results.size();
1760 for (int i=specificsPos; i<N-1; i++) {
1761 final ResolveInfo rii = results.get(i);
1762 if (rii.filter == null) {
1763 continue;
1764 }
1765
1766 // Iterate over all of the actions of this result's intent
1767 // filter... typically this should be just one.
1768 final Iterator<String> it = rii.filter.actionsIterator();
1769 if (it == null) {
1770 continue;
1771 }
1772 while (it.hasNext()) {
1773 final String action = it.next();
1774 if (resultsAction != null && resultsAction.equals(action)) {
1775 // If this action was explicitly requested, then don't
1776 // remove things that have it.
1777 continue;
1778 }
1779 for (int j=i+1; j<N; j++) {
1780 final ResolveInfo rij = results.get(j);
1781 if (rij.filter != null && rij.filter.hasAction(action)) {
1782 results.remove(j);
1783 if (Config.LOGV) Log.v(
1784 TAG, "Removing duplicate item from " + j
1785 + " due to action " + action + " at " + i);
1786 j--;
1787 N--;
1788 }
1789 }
1790 }
1791
1792 // If the caller didn't request filter information, drop it now
1793 // so we don't have to marshall/unmarshall it.
1794 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1795 rii.filter = null;
1796 }
1797 }
1798
1799 // Filter out the caller activity if so requested.
1800 if (caller != null) {
1801 N = results.size();
1802 for (int i=0; i<N; i++) {
1803 ActivityInfo ainfo = results.get(i).activityInfo;
1804 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1805 && caller.getClassName().equals(ainfo.name)) {
1806 results.remove(i);
1807 break;
1808 }
1809 }
1810 }
1811
1812 // If the caller didn't request filter information,
1813 // drop them now so we don't have to
1814 // marshall/unmarshall it.
1815 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1816 N = results.size();
1817 for (int i=0; i<N; i++) {
1818 results.get(i).filter = null;
1819 }
1820 }
1821
1822 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1823 return results;
1824 }
1825
1826 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1827 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001828 ComponentName comp = intent.getComponent();
1829 if (comp != null) {
1830 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1831 ActivityInfo ai = getReceiverInfo(comp, flags);
1832 if (ai != null) {
1833 ResolveInfo ri = new ResolveInfo();
1834 ri.activityInfo = ai;
1835 list.add(ri);
1836 }
1837 return list;
1838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001841 String pkgName = intent.getPackage();
1842 if (pkgName == null) {
1843 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1844 resolvedType, flags);
1845 }
1846 PackageParser.Package pkg = mPackages.get(pkgName);
1847 if (pkg != null) {
1848 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1849 resolvedType, flags, pkg.receivers);
1850 }
1851 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 }
1853 }
1854
1855 public ResolveInfo resolveService(Intent intent, String resolvedType,
1856 int flags) {
1857 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1858 flags);
1859 if (query != null) {
1860 if (query.size() >= 1) {
1861 // If there is more than one service with the same priority,
1862 // just arbitrarily pick the first one.
1863 return query.get(0);
1864 }
1865 }
1866 return null;
1867 }
1868
1869 public List<ResolveInfo> queryIntentServices(Intent intent,
1870 String resolvedType, int flags) {
1871 ComponentName comp = intent.getComponent();
1872 if (comp != null) {
1873 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1874 ServiceInfo si = getServiceInfo(comp, flags);
1875 if (si != null) {
1876 ResolveInfo ri = new ResolveInfo();
1877 ri.serviceInfo = si;
1878 list.add(ri);
1879 }
1880 return list;
1881 }
1882
1883 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001884 String pkgName = intent.getPackage();
1885 if (pkgName == null) {
1886 return (List<ResolveInfo>)mServices.queryIntent(intent,
1887 resolvedType, flags);
1888 }
1889 PackageParser.Package pkg = mPackages.get(pkgName);
1890 if (pkg != null) {
1891 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
1892 resolvedType, flags, pkg.services);
1893 }
1894 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 }
1896 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 public List<PackageInfo> getInstalledPackages(int flags) {
1899 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
1900
1901 synchronized (mPackages) {
1902 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1903 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1904 while (i.hasNext()) {
1905 final PackageSetting ps = i.next();
1906 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
1907 if(psPkg != null) {
1908 finalList.add(psPkg);
1909 }
1910 }
1911 }
1912 else {
1913 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1914 while (i.hasNext()) {
1915 final PackageParser.Package p = i.next();
1916 if (p.applicationInfo != null) {
1917 PackageInfo pi = generatePackageInfo(p, flags);
1918 if(pi != null) {
1919 finalList.add(pi);
1920 }
1921 }
1922 }
1923 }
1924 }
1925 return finalList;
1926 }
1927
1928 public List<ApplicationInfo> getInstalledApplications(int flags) {
1929 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1930 synchronized(mPackages) {
1931 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1932 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1933 while (i.hasNext()) {
1934 final PackageSetting ps = i.next();
1935 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
1936 if(ai != null) {
1937 finalList.add(ai);
1938 }
1939 }
1940 }
1941 else {
1942 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1943 while (i.hasNext()) {
1944 final PackageParser.Package p = i.next();
1945 if (p.applicationInfo != null) {
1946 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
1947 if(ai != null) {
1948 finalList.add(ai);
1949 }
1950 }
1951 }
1952 }
1953 }
1954 return finalList;
1955 }
1956
1957 public List<ApplicationInfo> getPersistentApplications(int flags) {
1958 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1959
1960 synchronized (mPackages) {
1961 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1962 while (i.hasNext()) {
1963 PackageParser.Package p = i.next();
1964 if (p.applicationInfo != null
1965 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
1966 && (!mSafeMode || (p.applicationInfo.flags
1967 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1968 finalList.add(p.applicationInfo);
1969 }
1970 }
1971 }
1972
1973 return finalList;
1974 }
1975
1976 public ProviderInfo resolveContentProvider(String name, int flags) {
1977 synchronized (mPackages) {
1978 final PackageParser.Provider provider = mProviders.get(name);
1979 return provider != null
1980 && mSettings.isEnabledLP(provider.info, flags)
1981 && (!mSafeMode || (provider.info.applicationInfo.flags
1982 &ApplicationInfo.FLAG_SYSTEM) != 0)
1983 ? PackageParser.generateProviderInfo(provider, flags)
1984 : null;
1985 }
1986 }
1987
Fred Quintana718d8a22009-04-29 17:53:20 -07001988 /**
1989 * @deprecated
1990 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 public void querySyncProviders(List outNames, List outInfo) {
1992 synchronized (mPackages) {
1993 Iterator<Map.Entry<String, PackageParser.Provider>> i
1994 = mProviders.entrySet().iterator();
1995
1996 while (i.hasNext()) {
1997 Map.Entry<String, PackageParser.Provider> entry = i.next();
1998 PackageParser.Provider p = entry.getValue();
1999
2000 if (p.syncable
2001 && (!mSafeMode || (p.info.applicationInfo.flags
2002 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2003 outNames.add(entry.getKey());
2004 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2005 }
2006 }
2007 }
2008 }
2009
2010 public List<ProviderInfo> queryContentProviders(String processName,
2011 int uid, int flags) {
2012 ArrayList<ProviderInfo> finalList = null;
2013
2014 synchronized (mPackages) {
2015 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2016 while (i.hasNext()) {
2017 PackageParser.Provider p = i.next();
2018 if (p.info.authority != null
2019 && (processName == null ||
2020 (p.info.processName.equals(processName)
2021 && p.info.applicationInfo.uid == uid))
2022 && mSettings.isEnabledLP(p.info, flags)
2023 && (!mSafeMode || (p.info.applicationInfo.flags
2024 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2025 if (finalList == null) {
2026 finalList = new ArrayList<ProviderInfo>(3);
2027 }
2028 finalList.add(PackageParser.generateProviderInfo(p,
2029 flags));
2030 }
2031 }
2032 }
2033
2034 if (finalList != null) {
2035 Collections.sort(finalList, mProviderInitOrderSorter);
2036 }
2037
2038 return finalList;
2039 }
2040
2041 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2042 int flags) {
2043 synchronized (mPackages) {
2044 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2045 return PackageParser.generateInstrumentationInfo(i, flags);
2046 }
2047 }
2048
2049 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2050 int flags) {
2051 ArrayList<InstrumentationInfo> finalList =
2052 new ArrayList<InstrumentationInfo>();
2053
2054 synchronized (mPackages) {
2055 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2056 while (i.hasNext()) {
2057 PackageParser.Instrumentation p = i.next();
2058 if (targetPackage == null
2059 || targetPackage.equals(p.info.targetPackage)) {
2060 finalList.add(PackageParser.generateInstrumentationInfo(p,
2061 flags));
2062 }
2063 }
2064 }
2065
2066 return finalList;
2067 }
2068
2069 private void scanDirLI(File dir, int flags, int scanMode) {
2070 Log.d(TAG, "Scanning app dir " + dir);
2071
2072 String[] files = dir.list();
2073
2074 int i;
2075 for (i=0; i<files.length; i++) {
2076 File file = new File(dir, files[i]);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002077 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
2079 }
2080 }
2081
2082 private static void reportSettingsProblem(int priority, String msg) {
2083 try {
2084 File dataDir = Environment.getDataDirectory();
2085 File systemDir = new File(dataDir, "system");
2086 File fname = new File(systemDir, "uiderrors.txt");
2087 FileOutputStream out = new FileOutputStream(fname, true);
2088 PrintWriter pw = new PrintWriter(out);
2089 pw.println(msg);
2090 pw.close();
2091 FileUtils.setPermissions(
2092 fname.toString(),
2093 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2094 -1, -1);
2095 } catch (java.io.IOException e) {
2096 }
2097 Log.println(priority, TAG, msg);
2098 }
2099
2100 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2101 PackageParser.Package pkg, File srcFile, int parseFlags) {
2102 if (GET_CERTIFICATES) {
2103 if (ps == null || !ps.codePath.equals(srcFile)
2104 || ps.getTimeStamp() != srcFile.lastModified()) {
2105 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2106 if (!pp.collectCertificates(pkg, parseFlags)) {
2107 mLastScanError = pp.getParseError();
2108 return false;
2109 }
2110 }
2111 }
2112 return true;
2113 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 /*
2116 * Scan a package and return the newly parsed package.
2117 * Returns null in case of errors and the error code is stored in mLastScanError
2118 */
2119 private PackageParser.Package scanPackageLI(File scanFile,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002120 int parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 int scanMode) {
2122 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002123 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002125 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002128 scanPath,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002129 mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 if (pkg == null) {
2131 mLastScanError = pp.getParseError();
2132 return null;
2133 }
2134 PackageSetting ps;
2135 PackageSetting updatedPkg;
2136 synchronized (mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002137 ps = mSettings.peekPackageLP(pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 updatedPkg = mSettings.mDisabledSysPackages.get(pkg.packageName);
2139 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002140 // Verify certificates first
2141 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2142 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2143 return null;
2144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 if (updatedPkg != null) {
2146 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2147 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2148 }
2149 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2150 // Check for updated system applications here
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002151 if ((ps != null) && (!ps.codePath.equals(scanFile))) {
2152 if (pkg.mVersionCode < ps.versionCode) {
2153 // The system package has been updated and the code path does not match
2154 // Ignore entry. Just return
2155 Log.w(TAG, "Package:" + pkg.packageName +
2156 " has been updated. Ignoring the one from path:"+scanFile);
2157 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2158 return null;
2159 } else {
2160 // Delete the older apk pointed to by ps
2161 // At this point, its safely assumed that package installation for
2162 // apps in system partition will go through. If not there won't be a working
2163 // version of the app
2164 synchronized (mPackages) {
2165 // Just remove the loaded entries from package lists.
2166 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002167 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002168 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2169 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002170 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002172 }
2173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 // The apk is forward locked (not public) if its code and resources
2175 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002176 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002178 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002179 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002180
2181 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2182 if (ps != null && ps.resourcePathString != null) {
2183 pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
2184 } else {
2185 // Should not happen at all. Just log an error.
2186 Log.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
2187 }
2188 } else {
2189 pkg.applicationInfo.publicSourceDir = pkg.mScanPath;
2190 }
2191 pkg.applicationInfo.sourceDir = pkg.mScanPath;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002192 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002193 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002194 }
2195
2196 private static String fixProcessName(String defProcessName,
2197 String processName, int uid) {
2198 if (processName == null) {
2199 return defProcessName;
2200 }
2201 return processName;
2202 }
2203
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002204 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2206 if (pkg.mSignatures != null) {
2207 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2208 updateSignature)) {
2209 Log.e(TAG, "Package " + pkg.packageName
2210 + " signatures do not match the previously installed version; ignoring!");
2211 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2212 return false;
2213 }
2214
2215 if (pkgSetting.sharedUser != null) {
2216 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2217 pkg.mSignatures, updateSignature)) {
2218 Log.e(TAG, "Package " + pkg.packageName
2219 + " has no signatures that match those in shared user "
2220 + pkgSetting.sharedUser.name + "; ignoring!");
2221 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2222 return false;
2223 }
2224 }
2225 } else {
2226 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2227 }
2228 return true;
2229 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002230
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002231 public boolean performDexOpt(String packageName) {
2232 if (!mNoDexOpt) {
2233 return false;
2234 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002235
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002236 PackageParser.Package p;
2237 synchronized (mPackages) {
2238 p = mPackages.get(packageName);
2239 if (p == null || p.mDidDexOpt) {
2240 return false;
2241 }
2242 }
2243 synchronized (mInstallLock) {
2244 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2245 }
2246 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002247
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002248 static final int DEX_OPT_SKIPPED = 0;
2249 static final int DEX_OPT_PERFORMED = 1;
2250 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002251
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002252 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2253 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002254 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002255 String path = pkg.mScanPath;
2256 int ret = 0;
2257 try {
2258 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002259 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002260 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002261 pkg.mDidDexOpt = true;
2262 performed = true;
2263 }
2264 } catch (FileNotFoundException e) {
2265 Log.w(TAG, "Apk not found for dexopt: " + path);
2266 ret = -1;
2267 } catch (IOException e) {
2268 Log.w(TAG, "Exception reading apk: " + path, e);
2269 ret = -1;
2270 }
2271 if (ret < 0) {
2272 //error from installer
2273 return DEX_OPT_FAILED;
2274 }
2275 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002276
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002277 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2278 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002279
2280 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2281 return Environment.isEncryptedFilesystemEnabled() &&
2282 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2283 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 private PackageParser.Package scanPackageLI(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002286 PackageParser.Package pkg, int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002287 File scanFile = new File(pkg.mScanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 mScanningPath = scanFile;
2289 if (pkg == null) {
2290 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2291 return null;
2292 }
2293
2294 final String pkgName = pkg.applicationInfo.packageName;
2295 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2296 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2297 }
2298
2299 if (pkgName.equals("android")) {
2300 synchronized (mPackages) {
2301 if (mAndroidApplication != null) {
2302 Log.w(TAG, "*************************************************");
2303 Log.w(TAG, "Core android package being redefined. Skipping.");
2304 Log.w(TAG, " file=" + mScanningPath);
2305 Log.w(TAG, "*************************************************");
2306 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2307 return null;
2308 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 // Set up information for our fall-back user intent resolution
2311 // activity.
2312 mPlatformPackage = pkg;
2313 pkg.mVersionCode = mSdkVersion;
2314 mAndroidApplication = pkg.applicationInfo;
2315 mResolveActivity.applicationInfo = mAndroidApplication;
2316 mResolveActivity.name = ResolverActivity.class.getName();
2317 mResolveActivity.packageName = mAndroidApplication.packageName;
2318 mResolveActivity.processName = mAndroidApplication.processName;
2319 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2320 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2321 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2322 mResolveActivity.exported = true;
2323 mResolveActivity.enabled = true;
2324 mResolveInfo.activityInfo = mResolveActivity;
2325 mResolveInfo.priority = 0;
2326 mResolveInfo.preferredOrder = 0;
2327 mResolveInfo.match = 0;
2328 mResolveComponentName = new ComponentName(
2329 mAndroidApplication.packageName, mResolveActivity.name);
2330 }
2331 }
2332
2333 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
2334 TAG, "Scanning package " + pkgName);
2335 if (mPackages.containsKey(pkgName) || mSharedLibraries.containsKey(pkgName)) {
2336 Log.w(TAG, "*************************************************");
2337 Log.w(TAG, "Application package " + pkgName
2338 + " already installed. Skipping duplicate.");
2339 Log.w(TAG, "*************************************************");
2340 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2341 return null;
2342 }
2343
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002344 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002345 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2346 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 SharedUserSetting suid = null;
2349 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 synchronized (mPackages) {
2354 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002355 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2356 if (mTmpSharedLibraries == null ||
2357 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2358 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2359 }
2360 int num = 0;
2361 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2362 for (int i=0; i<N; i++) {
2363 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 if (file == null) {
2365 Log.e(TAG, "Package " + pkg.packageName
2366 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002367 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2369 return null;
2370 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002371 mTmpSharedLibraries[num] = file;
2372 num++;
2373 }
2374 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2375 for (int i=0; i<N; i++) {
2376 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2377 if (file == null) {
2378 Log.w(TAG, "Package " + pkg.packageName
2379 + " desires unavailable shared library "
2380 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2381 } else {
2382 mTmpSharedLibraries[num] = file;
2383 num++;
2384 }
2385 }
2386 if (num > 0) {
2387 pkg.usesLibraryFiles = new String[num];
2388 System.arraycopy(mTmpSharedLibraries, 0,
2389 pkg.usesLibraryFiles, 0, num);
2390 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002391
Dianne Hackborn49237342009-08-27 20:08:01 -07002392 if (pkg.reqFeatures != null) {
2393 N = pkg.reqFeatures.size();
2394 for (int i=0; i<N; i++) {
2395 FeatureInfo fi = pkg.reqFeatures.get(i);
2396 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2397 // Don't care.
2398 continue;
2399 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002400
Dianne Hackborn49237342009-08-27 20:08:01 -07002401 if (fi.name != null) {
2402 if (mAvailableFeatures.get(fi.name) == null) {
2403 Log.e(TAG, "Package " + pkg.packageName
2404 + " requires unavailable feature "
2405 + fi.name + "; failing!");
2406 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2407 return null;
2408 }
2409 }
2410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 }
2412 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 if (pkg.mSharedUserId != null) {
2415 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2416 pkg.applicationInfo.flags, true);
2417 if (suid == null) {
2418 Log.w(TAG, "Creating application package " + pkgName
2419 + " for shared user failed");
2420 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2421 return null;
2422 }
2423 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2424 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2425 + suid.userId + "): packages=" + suid.packages);
2426 }
2427 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002428
2429 // Just create the setting, don't add it yet. For already existing packages
2430 // the PkgSetting exists already and doesn't have to be created.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 pkgSetting = mSettings.getPackageLP(pkg, suid, destCodeFile,
2432 destResourceFile, pkg.applicationInfo.flags, true, false);
2433 if (pkgSetting == null) {
2434 Log.w(TAG, "Creating application package " + pkgName + " failed");
2435 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2436 return null;
2437 }
2438 if(mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
2439 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2440 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 pkg.applicationInfo.uid = pkgSetting.userId;
2443 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002444
2445 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2447 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2448 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2449 return null;
2450 }
2451 // The signature has changed, but this package is in the system
2452 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002453 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 // However... if this package is part of a shared user, but it
2455 // doesn't match the signature of the shared user, let's fail.
2456 // What this means is that you can't change the signatures
2457 // associated with an overall shared user, which doesn't seem all
2458 // that unreasonable.
2459 if (pkgSetting.sharedUser != null) {
2460 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2461 pkg.mSignatures, false)) {
2462 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2463 return null;
2464 }
2465 }
2466 removeExisting = true;
2467 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002468
The Android Open Source Project10592532009-03-18 17:39:46 -07002469 // Verify that this new package doesn't have any content providers
2470 // that conflict with existing packages. Only do this if the
2471 // package isn't already installed, since we don't want to break
2472 // things that are installed.
2473 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2474 int N = pkg.providers.size();
2475 int i;
2476 for (i=0; i<N; i++) {
2477 PackageParser.Provider p = pkg.providers.get(i);
2478 String names[] = p.info.authority.split(";");
2479 for (int j = 0; j < names.length; j++) {
2480 if (mProviders.containsKey(names[j])) {
2481 PackageParser.Provider other = mProviders.get(names[j]);
2482 Log.w(TAG, "Can't install because provider name " + names[j] +
2483 " (in package " + pkg.applicationInfo.packageName +
2484 ") is already used by "
2485 + ((other != null && other.component != null)
2486 ? other.component.getPackageName() : "?"));
2487 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2488 return null;
2489 }
2490 }
2491 }
2492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 }
2494
2495 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002496 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002498 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 if (ret != 0) {
2500 String msg = "System package " + pkg.packageName
2501 + " could not have data directory erased after signature change.";
2502 reportSettingsProblem(Log.WARN, msg);
2503 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2504 return null;
2505 }
2506 }
2507 Log.w(TAG, "System package " + pkg.packageName
2508 + " signature changed: existing data removed.");
2509 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2510 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 long scanFileTime = scanFile.lastModified();
2513 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2514 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2515 pkg.applicationInfo.processName = fixProcessName(
2516 pkg.applicationInfo.packageName,
2517 pkg.applicationInfo.processName,
2518 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519
2520 File dataPath;
2521 if (mPlatformPackage == pkg) {
2522 // The system package is special.
2523 dataPath = new File (Environment.getDataDirectory(), "system");
2524 pkg.applicationInfo.dataDir = dataPath.getPath();
2525 } else {
2526 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002527 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2528 if (useEncryptedFSDir) {
2529 dataPath = new File(mSecureAppDataDir, pkgName);
2530 } else {
2531 dataPath = new File(mAppDataDir, pkgName);
2532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 if (dataPath.exists()) {
2534 mOutPermissions[1] = 0;
2535 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2536 if (mOutPermissions[1] == pkg.applicationInfo.uid
2537 || !Process.supportsProcesses()) {
2538 pkg.applicationInfo.dataDir = dataPath.getPath();
2539 } else {
2540 boolean recovered = false;
2541 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2542 // If this is a system app, we can at least delete its
2543 // current data so the application will still work.
2544 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002545 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 if(ret >= 0) {
2547 // Old data gone!
2548 String msg = "System package " + pkg.packageName
2549 + " has changed from uid: "
2550 + mOutPermissions[1] + " to "
2551 + pkg.applicationInfo.uid + "; old data erased";
2552 reportSettingsProblem(Log.WARN, msg);
2553 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002556 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557 pkg.applicationInfo.uid);
2558 if (ret == -1) {
2559 // Ack should not happen!
2560 msg = "System package " + pkg.packageName
2561 + " could not have data directory re-created after delete.";
2562 reportSettingsProblem(Log.WARN, msg);
2563 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2564 return null;
2565 }
2566 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 if (!recovered) {
2569 mHasSystemUidErrors = true;
2570 }
2571 }
2572 if (!recovered) {
2573 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2574 + pkg.applicationInfo.uid + "/fs_"
2575 + mOutPermissions[1];
2576 String msg = "Package " + pkg.packageName
2577 + " has mismatched uid: "
2578 + mOutPermissions[1] + " on disk, "
2579 + pkg.applicationInfo.uid + " in settings";
2580 synchronized (mPackages) {
2581 if (!mReportedUidError) {
2582 mReportedUidError = true;
2583 msg = msg + "; read messages:\n"
2584 + mSettings.getReadMessagesLP();
2585 }
2586 reportSettingsProblem(Log.ERROR, msg);
2587 }
2588 }
2589 }
2590 pkg.applicationInfo.dataDir = dataPath.getPath();
2591 } else {
2592 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2593 Log.v(TAG, "Want this data dir: " + dataPath);
2594 //invoke installer to do the actual installation
2595 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002596 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597 pkg.applicationInfo.uid);
2598 if(ret < 0) {
2599 // Error from installer
2600 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2601 return null;
2602 }
2603 } else {
2604 dataPath.mkdirs();
2605 if (dataPath.exists()) {
2606 FileUtils.setPermissions(
2607 dataPath.toString(),
2608 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2609 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2610 }
2611 }
2612 if (dataPath.exists()) {
2613 pkg.applicationInfo.dataDir = dataPath.getPath();
2614 } else {
2615 Log.w(TAG, "Unable to create data directory: " + dataPath);
2616 pkg.applicationInfo.dataDir = null;
2617 }
2618 }
2619 }
2620
2621 // Perform shared library installation and dex validation and
2622 // optimization, if this is not a system app.
2623 if (mInstaller != null) {
2624 String path = scanFile.getPath();
2625 if (scanFileNewer) {
2626 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002627 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2628 if (err != PackageManager.INSTALL_SUCCEEDED) {
2629 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 return null;
2631 }
2632 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002633 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002634
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002635 if ((scanMode&SCAN_NO_DEX) == 0) {
2636 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2638 return null;
2639 }
2640 }
2641 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643 if (mFactoryTest && pkg.requestedPermissions.contains(
2644 android.Manifest.permission.FACTORY_TEST)) {
2645 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2646 }
2647
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002648 // We don't expect installation to fail beyond this point,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 if ((scanMode&SCAN_MONITOR) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 mAppDirs.put(pkg.mPath, pkg);
2651 }
2652
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002653 // Request the ActivityManager to kill the process(only for existing packages)
2654 // so that we do not end up in a confused state while the user is still using the older
2655 // version of the application while the new one gets installed.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002656 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING ) != 0) {
2657 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002658 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002659 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002663 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002665 mPackages.put(pkg.applicationInfo.packageName, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 int N = pkg.providers.size();
2667 StringBuilder r = null;
2668 int i;
2669 for (i=0; i<N; i++) {
2670 PackageParser.Provider p = pkg.providers.get(i);
2671 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2672 p.info.processName, pkg.applicationInfo.uid);
2673 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2674 p.info.name), p);
2675 p.syncable = p.info.isSyncable;
2676 String names[] = p.info.authority.split(";");
2677 p.info.authority = null;
2678 for (int j = 0; j < names.length; j++) {
2679 if (j == 1 && p.syncable) {
2680 // We only want the first authority for a provider to possibly be
2681 // syncable, so if we already added this provider using a different
2682 // authority clear the syncable flag. We copy the provider before
2683 // changing it because the mProviders object contains a reference
2684 // to a provider that we don't want to change.
2685 // Only do this for the second authority since the resulting provider
2686 // object can be the same for all future authorities for this provider.
2687 p = new PackageParser.Provider(p);
2688 p.syncable = false;
2689 }
2690 if (!mProviders.containsKey(names[j])) {
2691 mProviders.put(names[j], p);
2692 if (p.info.authority == null) {
2693 p.info.authority = names[j];
2694 } else {
2695 p.info.authority = p.info.authority + ";" + names[j];
2696 }
2697 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
2698 Log.d(TAG, "Registered content provider: " + names[j] +
2699 ", className = " + p.info.name +
2700 ", isSyncable = " + p.info.isSyncable);
2701 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07002702 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 Log.w(TAG, "Skipping provider name " + names[j] +
2704 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07002705 "): name already used by "
2706 + ((other != null && other.component != null)
2707 ? other.component.getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 }
2709 }
2710 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2711 if (r == null) {
2712 r = new StringBuilder(256);
2713 } else {
2714 r.append(' ');
2715 }
2716 r.append(p.info.name);
2717 }
2718 }
2719 if (r != null) {
2720 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2721 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 N = pkg.services.size();
2724 r = null;
2725 for (i=0; i<N; i++) {
2726 PackageParser.Service s = pkg.services.get(i);
2727 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
2728 s.info.processName, pkg.applicationInfo.uid);
2729 mServices.addService(s);
2730 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2731 if (r == null) {
2732 r = new StringBuilder(256);
2733 } else {
2734 r.append(' ');
2735 }
2736 r.append(s.info.name);
2737 }
2738 }
2739 if (r != null) {
2740 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2741 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002743 N = pkg.receivers.size();
2744 r = null;
2745 for (i=0; i<N; i++) {
2746 PackageParser.Activity a = pkg.receivers.get(i);
2747 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2748 a.info.processName, pkg.applicationInfo.uid);
2749 mReceivers.addActivity(a, "receiver");
2750 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2751 if (r == null) {
2752 r = new StringBuilder(256);
2753 } else {
2754 r.append(' ');
2755 }
2756 r.append(a.info.name);
2757 }
2758 }
2759 if (r != null) {
2760 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2761 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 N = pkg.activities.size();
2764 r = null;
2765 for (i=0; i<N; i++) {
2766 PackageParser.Activity a = pkg.activities.get(i);
2767 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2768 a.info.processName, pkg.applicationInfo.uid);
2769 mActivities.addActivity(a, "activity");
2770 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2771 if (r == null) {
2772 r = new StringBuilder(256);
2773 } else {
2774 r.append(' ');
2775 }
2776 r.append(a.info.name);
2777 }
2778 }
2779 if (r != null) {
2780 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
2781 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 N = pkg.permissionGroups.size();
2784 r = null;
2785 for (i=0; i<N; i++) {
2786 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
2787 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
2788 if (cur == null) {
2789 mPermissionGroups.put(pg.info.name, pg);
2790 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2791 if (r == null) {
2792 r = new StringBuilder(256);
2793 } else {
2794 r.append(' ');
2795 }
2796 r.append(pg.info.name);
2797 }
2798 } else {
2799 Log.w(TAG, "Permission group " + pg.info.name + " from package "
2800 + pg.info.packageName + " ignored: original from "
2801 + cur.info.packageName);
2802 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2803 if (r == null) {
2804 r = new StringBuilder(256);
2805 } else {
2806 r.append(' ');
2807 }
2808 r.append("DUP:");
2809 r.append(pg.info.name);
2810 }
2811 }
2812 }
2813 if (r != null) {
2814 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
2815 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 N = pkg.permissions.size();
2818 r = null;
2819 for (i=0; i<N; i++) {
2820 PackageParser.Permission p = pkg.permissions.get(i);
2821 HashMap<String, BasePermission> permissionMap =
2822 p.tree ? mSettings.mPermissionTrees
2823 : mSettings.mPermissions;
2824 p.group = mPermissionGroups.get(p.info.group);
2825 if (p.info.group == null || p.group != null) {
2826 BasePermission bp = permissionMap.get(p.info.name);
2827 if (bp == null) {
2828 bp = new BasePermission(p.info.name, p.info.packageName,
2829 BasePermission.TYPE_NORMAL);
2830 permissionMap.put(p.info.name, bp);
2831 }
2832 if (bp.perm == null) {
2833 if (bp.sourcePackage == null
2834 || bp.sourcePackage.equals(p.info.packageName)) {
2835 BasePermission tree = findPermissionTreeLP(p.info.name);
2836 if (tree == null
2837 || tree.sourcePackage.equals(p.info.packageName)) {
2838 bp.perm = p;
2839 bp.uid = pkg.applicationInfo.uid;
2840 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2841 if (r == null) {
2842 r = new StringBuilder(256);
2843 } else {
2844 r.append(' ');
2845 }
2846 r.append(p.info.name);
2847 }
2848 } else {
2849 Log.w(TAG, "Permission " + p.info.name + " from package "
2850 + p.info.packageName + " ignored: base tree "
2851 + tree.name + " is from package "
2852 + tree.sourcePackage);
2853 }
2854 } else {
2855 Log.w(TAG, "Permission " + p.info.name + " from package "
2856 + p.info.packageName + " ignored: original from "
2857 + bp.sourcePackage);
2858 }
2859 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2860 if (r == null) {
2861 r = new StringBuilder(256);
2862 } else {
2863 r.append(' ');
2864 }
2865 r.append("DUP:");
2866 r.append(p.info.name);
2867 }
2868 } else {
2869 Log.w(TAG, "Permission " + p.info.name + " from package "
2870 + p.info.packageName + " ignored: no group "
2871 + p.group);
2872 }
2873 }
2874 if (r != null) {
2875 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
2876 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878 N = pkg.instrumentation.size();
2879 r = null;
2880 for (i=0; i<N; i++) {
2881 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
2882 a.info.packageName = pkg.applicationInfo.packageName;
2883 a.info.sourceDir = pkg.applicationInfo.sourceDir;
2884 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
2885 a.info.dataDir = pkg.applicationInfo.dataDir;
2886 mInstrumentation.put(a.component, a);
2887 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2888 if (r == null) {
2889 r = new StringBuilder(256);
2890 } else {
2891 r.append(' ');
2892 }
2893 r.append(a.info.name);
2894 }
2895 }
2896 if (r != null) {
2897 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
2898 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002899
Dianne Hackborn854060af2009-07-09 18:14:31 -07002900 if (pkg.protectedBroadcasts != null) {
2901 N = pkg.protectedBroadcasts.size();
2902 for (i=0; i<N; i++) {
2903 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
2904 }
2905 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 pkgSetting.setTimeStamp(scanFileTime);
2908 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 return pkg;
2911 }
2912
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002913 private void killApplication(String pkgName, int uid) {
2914 // Request the ActivityManager to kill the process(only for existing packages)
2915 // so that we do not end up in a confused state while the user is still using the older
2916 // version of the application while the new one gets installed.
2917 IActivityManager am = ActivityManagerNative.getDefault();
2918 if (am != null) {
2919 try {
2920 am.killApplicationWithUid(pkgName, uid);
2921 } catch (RemoteException e) {
2922 }
2923 }
2924 }
2925
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002926 // The following constants are returned by cachePackageSharedLibsForAbiLI
2927 // to indicate if native shared libraries were found in the package.
2928 // Values are:
2929 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
2930 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
2931 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
2932 // in package (and not installed)
2933 //
2934 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
2935 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
2936 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002938 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
2939 // and automatically copy them to /data/data/<appname>/lib if present.
2940 //
2941 // NOTE: this method may throw an IOException if the library cannot
2942 // be copied to its final destination, e.g. if there isn't enough
2943 // room left on the data partition, or a ZipException if the package
2944 // file is malformed.
2945 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08002946 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
2947 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002948 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
2949 final String apkLib = "lib/";
2950 final int apkLibLen = apkLib.length();
2951 final int cpuAbiLen = cpuAbi.length();
2952 final String libPrefix = "lib";
2953 final int libPrefixLen = libPrefix.length();
2954 final String libSuffix = ".so";
2955 final int libSuffixLen = libSuffix.length();
2956 boolean hasNativeLibraries = false;
2957 boolean installedNativeLibraries = false;
2958
2959 // the minimum length of a valid native shared library of the form
2960 // lib/<something>/lib<name>.so.
2961 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
2962
2963 ZipFile zipFile = new ZipFile(scanFile);
2964 Enumeration<ZipEntry> entries =
2965 (Enumeration<ZipEntry>) zipFile.entries();
2966
2967 while (entries.hasMoreElements()) {
2968 ZipEntry entry = entries.nextElement();
2969 // skip directories
2970 if (entry.isDirectory()) {
2971 continue;
2972 }
2973 String entryName = entry.getName();
2974
2975 // check that the entry looks like lib/<something>/lib<name>.so
2976 // here, but don't check the ABI just yet.
2977 //
2978 // - must be sufficiently long
2979 // - must end with libSuffix, i.e. ".so"
2980 // - must start with apkLib, i.e. "lib/"
2981 if (entryName.length() < minEntryLen ||
2982 !entryName.endsWith(libSuffix) ||
2983 !entryName.startsWith(apkLib) ) {
2984 continue;
2985 }
2986
2987 // file name must start with libPrefix, i.e. "lib"
2988 int lastSlash = entryName.lastIndexOf('/');
2989
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002990 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002991 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
2992 continue;
2993 }
2994
2995 hasNativeLibraries = true;
2996
2997 // check the cpuAbi now, between lib/ and /lib<name>.so
2998 //
2999 if (lastSlash != apkLibLen + cpuAbiLen ||
3000 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3001 continue;
3002
3003 // extract the library file name, ensure it doesn't contain
3004 // weird characters. we're guaranteed here that it doesn't contain
3005 // a directory separator though.
3006 String libFileName = entryName.substring(lastSlash+1);
3007 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3008 continue;
3009 }
3010
3011 installedNativeLibraries = true;
3012
3013 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3014 File.separator + libFileName;
3015 File sharedLibraryFile = new File(sharedLibraryFilePath);
3016 if (! sharedLibraryFile.exists() ||
3017 sharedLibraryFile.length() != entry.getSize() ||
3018 sharedLibraryFile.lastModified() != entry.getTime()) {
3019 if (Config.LOGD) {
3020 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003022 if (mInstaller == null) {
3023 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003024 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003025 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003026 sharedLibraryFile);
3027 }
3028 }
3029 if (!hasNativeLibraries)
3030 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3031
3032 if (!installedNativeLibraries)
3033 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3034
3035 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3036 }
3037
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003038 // Find the gdbserver executable program in a package at
3039 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3040 //
3041 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3042 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3043 //
3044 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3045 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3046 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3047 final String GDBSERVER = "gdbserver";
3048 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3049
3050 ZipFile zipFile = new ZipFile(scanFile);
3051 Enumeration<ZipEntry> entries =
3052 (Enumeration<ZipEntry>) zipFile.entries();
3053
3054 while (entries.hasMoreElements()) {
3055 ZipEntry entry = entries.nextElement();
3056 // skip directories
3057 if (entry.isDirectory()) {
3058 continue;
3059 }
3060 String entryName = entry.getName();
3061
3062 if (!entryName.equals(apkGdbServerPath)) {
3063 continue;
3064 }
3065
3066 String installGdbServerPath = installGdbServerDir.getPath() +
3067 "/" + GDBSERVER;
3068 File installGdbServerFile = new File(installGdbServerPath);
3069 if (! installGdbServerFile.exists() ||
3070 installGdbServerFile.length() != entry.getSize() ||
3071 installGdbServerFile.lastModified() != entry.getTime()) {
3072 if (Config.LOGD) {
3073 Log.d(TAG, "Caching gdbserver " + entry.getName());
3074 }
3075 if (mInstaller == null) {
3076 installGdbServerDir.mkdir();
3077 }
3078 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3079 installGdbServerFile);
3080 }
3081 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3082 }
3083 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3084 }
3085
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003086 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3087 // and copy them to /data/data/<appname>/lib.
3088 //
3089 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3090 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3091 // one if ro.product.cpu.abi2 is defined.
3092 //
3093 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3094 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003095 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003096 try {
3097 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3098
3099 // some architectures are capable of supporting several CPU ABIs
3100 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3101 // this is indicated by the definition of the ro.product.cpu.abi2
3102 // system property.
3103 //
3104 // only scan the package twice in case of ABI mismatch
3105 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003106 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003107 if (cpuAbi2 != null) {
3108 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003109 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003110
3111 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
3112 Log.w(TAG,"Native ABI mismatch from package file");
3113 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003114 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003115
3116 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3117 cpuAbi = cpuAbi2;
3118 }
3119 }
3120
3121 // for debuggable packages, also extract gdbserver from lib/<abi>
3122 // into /data/data/<appname>/lib too.
3123 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3124 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3125 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3126 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3127 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003129 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003130 } catch (ZipException e) {
3131 Log.w(TAG, "Failed to extract data from package file", e);
3132 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003133 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07003134 Log.w(TAG, "Failed to cache package shared libs", e);
3135 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003137 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 }
3139
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003140 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003142 File binaryDir,
3143 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 InputStream inputStream = zipFile.getInputStream(entry);
3145 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003146 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003148 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003149 // now need to be left as world readable and owned by the system.
3150 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3151 ! tempFile.setLastModified(entry.getTime()) ||
3152 FileUtils.setPermissions(tempFilePath,
3153 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003154 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003155 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003156 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157 // Failed to properly write file.
3158 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003159 throw new IOException("Couldn't create cached binary "
3160 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003161 }
3162 } finally {
3163 inputStream.close();
3164 }
3165 }
3166
3167 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3168 if (chatty && Config.LOGD) Log.d(
3169 TAG, "Removing package " + pkg.applicationInfo.packageName );
3170
3171 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174 mPackages.remove(pkg.applicationInfo.packageName);
3175 if (pkg.mPath != null) {
3176 mAppDirs.remove(pkg.mPath);
3177 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 PackageSetting ps = (PackageSetting)pkg.mExtras;
3180 if (ps != null && ps.sharedUser != null) {
3181 // XXX don't do this until the data is removed.
3182 if (false) {
3183 ps.sharedUser.packages.remove(ps);
3184 if (ps.sharedUser.packages.size() == 0) {
3185 // Remove.
3186 }
3187 }
3188 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 int N = pkg.providers.size();
3191 StringBuilder r = null;
3192 int i;
3193 for (i=0; i<N; i++) {
3194 PackageParser.Provider p = pkg.providers.get(i);
3195 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3196 p.info.name));
3197 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 /* The is another ContentProvider with this authority when
3200 * this app was installed so this authority is null,
3201 * Ignore it as we don't have to unregister the provider.
3202 */
3203 continue;
3204 }
3205 String names[] = p.info.authority.split(";");
3206 for (int j = 0; j < names.length; j++) {
3207 if (mProviders.get(names[j]) == p) {
3208 mProviders.remove(names[j]);
3209 if (chatty && Config.LOGD) Log.d(
3210 TAG, "Unregistered content provider: " + names[j] +
3211 ", className = " + p.info.name +
3212 ", isSyncable = " + p.info.isSyncable);
3213 }
3214 }
3215 if (chatty) {
3216 if (r == null) {
3217 r = new StringBuilder(256);
3218 } else {
3219 r.append(' ');
3220 }
3221 r.append(p.info.name);
3222 }
3223 }
3224 if (r != null) {
3225 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3226 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 N = pkg.services.size();
3229 r = null;
3230 for (i=0; i<N; i++) {
3231 PackageParser.Service s = pkg.services.get(i);
3232 mServices.removeService(s);
3233 if (chatty) {
3234 if (r == null) {
3235 r = new StringBuilder(256);
3236 } else {
3237 r.append(' ');
3238 }
3239 r.append(s.info.name);
3240 }
3241 }
3242 if (r != null) {
3243 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3244 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 N = pkg.receivers.size();
3247 r = null;
3248 for (i=0; i<N; i++) {
3249 PackageParser.Activity a = pkg.receivers.get(i);
3250 mReceivers.removeActivity(a, "receiver");
3251 if (chatty) {
3252 if (r == null) {
3253 r = new StringBuilder(256);
3254 } else {
3255 r.append(' ');
3256 }
3257 r.append(a.info.name);
3258 }
3259 }
3260 if (r != null) {
3261 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3262 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264 N = pkg.activities.size();
3265 r = null;
3266 for (i=0; i<N; i++) {
3267 PackageParser.Activity a = pkg.activities.get(i);
3268 mActivities.removeActivity(a, "activity");
3269 if (chatty) {
3270 if (r == null) {
3271 r = new StringBuilder(256);
3272 } else {
3273 r.append(' ');
3274 }
3275 r.append(a.info.name);
3276 }
3277 }
3278 if (r != null) {
3279 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3280 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 N = pkg.permissions.size();
3283 r = null;
3284 for (i=0; i<N; i++) {
3285 PackageParser.Permission p = pkg.permissions.get(i);
3286 boolean tree = false;
3287 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3288 if (bp == null) {
3289 tree = true;
3290 bp = mSettings.mPermissionTrees.get(p.info.name);
3291 }
3292 if (bp != null && bp.perm == p) {
3293 if (bp.type != BasePermission.TYPE_BUILTIN) {
3294 if (tree) {
3295 mSettings.mPermissionTrees.remove(p.info.name);
3296 } else {
3297 mSettings.mPermissions.remove(p.info.name);
3298 }
3299 } else {
3300 bp.perm = null;
3301 }
3302 if (chatty) {
3303 if (r == null) {
3304 r = new StringBuilder(256);
3305 } else {
3306 r.append(' ');
3307 }
3308 r.append(p.info.name);
3309 }
3310 }
3311 }
3312 if (r != null) {
3313 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3314 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 N = pkg.instrumentation.size();
3317 r = null;
3318 for (i=0; i<N; i++) {
3319 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3320 mInstrumentation.remove(a.component);
3321 if (chatty) {
3322 if (r == null) {
3323 r = new StringBuilder(256);
3324 } else {
3325 r.append(' ');
3326 }
3327 r.append(a.info.name);
3328 }
3329 }
3330 if (r != null) {
3331 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3332 }
3333 }
3334 }
3335
3336 private static final boolean isPackageFilename(String name) {
3337 return name != null && name.endsWith(".apk");
3338 }
3339
3340 private void updatePermissionsLP() {
3341 // Make sure there are no dangling permission trees.
3342 Iterator<BasePermission> it = mSettings.mPermissionTrees
3343 .values().iterator();
3344 while (it.hasNext()) {
3345 BasePermission bp = it.next();
3346 if (bp.perm == null) {
3347 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3348 + " from package " + bp.sourcePackage);
3349 it.remove();
3350 }
3351 }
3352
3353 // Make sure all dynamic permissions have been assigned to a package,
3354 // and make sure there are no dangling permissions.
3355 it = mSettings.mPermissions.values().iterator();
3356 while (it.hasNext()) {
3357 BasePermission bp = it.next();
3358 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3359 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3360 + bp.name + " pkg=" + bp.sourcePackage
3361 + " info=" + bp.pendingInfo);
3362 if (bp.perm == null && bp.pendingInfo != null) {
3363 BasePermission tree = findPermissionTreeLP(bp.name);
3364 if (tree != null) {
3365 bp.perm = new PackageParser.Permission(tree.perm.owner,
3366 new PermissionInfo(bp.pendingInfo));
3367 bp.perm.info.packageName = tree.perm.info.packageName;
3368 bp.perm.info.name = bp.name;
3369 bp.uid = tree.uid;
3370 }
3371 }
3372 }
3373 if (bp.perm == null) {
3374 Log.w(TAG, "Removing dangling permission: " + bp.name
3375 + " from package " + bp.sourcePackage);
3376 it.remove();
3377 }
3378 }
3379
3380 // Now update the permissions for all packages, in particular
3381 // replace the granted permissions of the system packages.
3382 for (PackageParser.Package pkg : mPackages.values()) {
3383 grantPermissionsLP(pkg, false);
3384 }
3385 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3388 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3389 if (ps == null) {
3390 return;
3391 }
3392 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3393 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 if (replace) {
3396 ps.permissionsFixed = false;
3397 if (gp == ps) {
3398 gp.grantedPermissions.clear();
3399 gp.gids = mGlobalGids;
3400 }
3401 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 if (gp.gids == null) {
3404 gp.gids = mGlobalGids;
3405 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003407 final int N = pkg.requestedPermissions.size();
3408 for (int i=0; i<N; i++) {
3409 String name = pkg.requestedPermissions.get(i);
3410 BasePermission bp = mSettings.mPermissions.get(name);
3411 PackageParser.Permission p = bp != null ? bp.perm : null;
3412 if (false) {
3413 if (gp != ps) {
3414 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3415 + ": " + p);
3416 }
3417 }
3418 if (p != null) {
3419 final String perm = p.info.name;
3420 boolean allowed;
3421 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3422 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3423 allowed = true;
3424 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3425 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003426 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003428 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003429 == PackageManager.SIGNATURE_MATCH);
3430 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3431 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3432 // For updated system applications, the signatureOrSystem permission
3433 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003434 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3436 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3437 if(sysPs.grantedPermissions.contains(perm)) {
3438 allowed = true;
3439 } else {
3440 allowed = false;
3441 }
3442 } else {
3443 allowed = true;
3444 }
3445 }
3446 }
3447 } else {
3448 allowed = false;
3449 }
3450 if (false) {
3451 if (gp != ps) {
3452 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3453 }
3454 }
3455 if (allowed) {
3456 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3457 && ps.permissionsFixed) {
3458 // If this is an existing, non-system package, then
3459 // we can't add any new permissions to it.
3460 if (!gp.loadedPermissions.contains(perm)) {
3461 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003462 // Except... if this is a permission that was added
3463 // to the platform (note: need to only do this when
3464 // updating the platform).
3465 final int NP = PackageParser.NEW_PERMISSIONS.length;
3466 for (int ip=0; ip<NP; ip++) {
3467 final PackageParser.NewPermissionInfo npi
3468 = PackageParser.NEW_PERMISSIONS[ip];
3469 if (npi.name.equals(perm)
3470 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3471 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003472 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003473 + pkg.packageName);
3474 break;
3475 }
3476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003477 }
3478 }
3479 if (allowed) {
3480 if (!gp.grantedPermissions.contains(perm)) {
3481 addedPermission = true;
3482 gp.grantedPermissions.add(perm);
3483 gp.gids = appendInts(gp.gids, bp.gids);
3484 }
3485 } else {
3486 Log.w(TAG, "Not granting permission " + perm
3487 + " to package " + pkg.packageName
3488 + " because it was previously installed without");
3489 }
3490 } else {
3491 Log.w(TAG, "Not granting permission " + perm
3492 + " to package " + pkg.packageName
3493 + " (protectionLevel=" + p.info.protectionLevel
3494 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3495 + ")");
3496 }
3497 } else {
3498 Log.w(TAG, "Unknown permission " + name
3499 + " in package " + pkg.packageName);
3500 }
3501 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003503 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003504 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3505 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 // This is the first that we have heard about this package, so the
3507 // permissions we have now selected are fixed until explicitly
3508 // changed.
3509 ps.permissionsFixed = true;
3510 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3511 }
3512 }
3513
3514 private final class ActivityIntentResolver
3515 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003516 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003517 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003518 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003519 }
3520
Mihai Preda074edef2009-05-18 17:13:31 +02003521 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003522 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003523 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003524 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3525 }
3526
Mihai Predaeae850c2009-05-13 10:13:48 +02003527 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3528 ArrayList<PackageParser.Activity> packageActivities) {
3529 if (packageActivities == null) {
3530 return null;
3531 }
3532 mFlags = flags;
3533 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3534 int N = packageActivities.size();
3535 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3536 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003537
3538 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003539 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003540 intentFilters = packageActivities.get(i).intents;
3541 if (intentFilters != null && intentFilters.size() > 0) {
3542 listCut.add(intentFilters);
3543 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003544 }
3545 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3546 }
3547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003548 public final void addActivity(PackageParser.Activity a, String type) {
3549 mActivities.put(a.component, a);
3550 if (SHOW_INFO || Config.LOGV) Log.v(
3551 TAG, " " + type + " " +
3552 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3553 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3554 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003555 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3557 if (SHOW_INFO || Config.LOGV) {
3558 Log.v(TAG, " IntentFilter:");
3559 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3560 }
3561 if (!intent.debugCheck()) {
3562 Log.w(TAG, "==> For Activity " + a.info.name);
3563 }
3564 addFilter(intent);
3565 }
3566 }
3567
3568 public final void removeActivity(PackageParser.Activity a, String type) {
3569 mActivities.remove(a.component);
3570 if (SHOW_INFO || Config.LOGV) Log.v(
3571 TAG, " " + type + " " +
3572 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3573 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3574 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003575 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003576 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3577 if (SHOW_INFO || Config.LOGV) {
3578 Log.v(TAG, " IntentFilter:");
3579 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3580 }
3581 removeFilter(intent);
3582 }
3583 }
3584
3585 @Override
3586 protected boolean allowFilterResult(
3587 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3588 ActivityInfo filterAi = filter.activity.info;
3589 for (int i=dest.size()-1; i>=0; i--) {
3590 ActivityInfo destAi = dest.get(i).activityInfo;
3591 if (destAi.name == filterAi.name
3592 && destAi.packageName == filterAi.packageName) {
3593 return false;
3594 }
3595 }
3596 return true;
3597 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003599 @Override
3600 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3601 int match) {
3602 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3603 return null;
3604 }
3605 final PackageParser.Activity activity = info.activity;
3606 if (mSafeMode && (activity.info.applicationInfo.flags
3607 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3608 return null;
3609 }
3610 final ResolveInfo res = new ResolveInfo();
3611 res.activityInfo = PackageParser.generateActivityInfo(activity,
3612 mFlags);
3613 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3614 res.filter = info;
3615 }
3616 res.priority = info.getPriority();
3617 res.preferredOrder = activity.owner.mPreferredOrder;
3618 //System.out.println("Result: " + res.activityInfo.className +
3619 // " = " + res.priority);
3620 res.match = match;
3621 res.isDefault = info.hasDefault;
3622 res.labelRes = info.labelRes;
3623 res.nonLocalizedLabel = info.nonLocalizedLabel;
3624 res.icon = info.icon;
3625 return res;
3626 }
3627
3628 @Override
3629 protected void sortResults(List<ResolveInfo> results) {
3630 Collections.sort(results, mResolvePrioritySorter);
3631 }
3632
3633 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003634 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003636 out.print(prefix); out.print(
3637 Integer.toHexString(System.identityHashCode(filter.activity)));
3638 out.print(' ');
3639 out.println(filter.activity.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003640 }
3641
3642// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3643// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3644// final List<ResolveInfo> retList = Lists.newArrayList();
3645// while (i.hasNext()) {
3646// final ResolveInfo resolveInfo = i.next();
3647// if (isEnabledLP(resolveInfo.activityInfo)) {
3648// retList.add(resolveInfo);
3649// }
3650// }
3651// return retList;
3652// }
3653
3654 // Keys are String (activity class name), values are Activity.
3655 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3656 = new HashMap<ComponentName, PackageParser.Activity>();
3657 private int mFlags;
3658 }
3659
3660 private final class ServiceIntentResolver
3661 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003662 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003663 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003664 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003665 }
3666
Mihai Preda074edef2009-05-18 17:13:31 +02003667 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003669 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3671 }
3672
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003673 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3674 ArrayList<PackageParser.Service> packageServices) {
3675 if (packageServices == null) {
3676 return null;
3677 }
3678 mFlags = flags;
3679 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3680 int N = packageServices.size();
3681 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3682 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3683
3684 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3685 for (int i = 0; i < N; ++i) {
3686 intentFilters = packageServices.get(i).intents;
3687 if (intentFilters != null && intentFilters.size() > 0) {
3688 listCut.add(intentFilters);
3689 }
3690 }
3691 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3692 }
3693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 public final void addService(PackageParser.Service s) {
3695 mServices.put(s.component, s);
3696 if (SHOW_INFO || Config.LOGV) Log.v(
3697 TAG, " " + (s.info.nonLocalizedLabel != null
3698 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3699 if (SHOW_INFO || Config.LOGV) Log.v(
3700 TAG, " Class=" + s.info.name);
3701 int NI = s.intents.size();
3702 int j;
3703 for (j=0; j<NI; j++) {
3704 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3705 if (SHOW_INFO || Config.LOGV) {
3706 Log.v(TAG, " IntentFilter:");
3707 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3708 }
3709 if (!intent.debugCheck()) {
3710 Log.w(TAG, "==> For Service " + s.info.name);
3711 }
3712 addFilter(intent);
3713 }
3714 }
3715
3716 public final void removeService(PackageParser.Service s) {
3717 mServices.remove(s.component);
3718 if (SHOW_INFO || Config.LOGV) Log.v(
3719 TAG, " " + (s.info.nonLocalizedLabel != null
3720 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3721 if (SHOW_INFO || Config.LOGV) Log.v(
3722 TAG, " Class=" + s.info.name);
3723 int NI = s.intents.size();
3724 int j;
3725 for (j=0; j<NI; j++) {
3726 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3727 if (SHOW_INFO || Config.LOGV) {
3728 Log.v(TAG, " IntentFilter:");
3729 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3730 }
3731 removeFilter(intent);
3732 }
3733 }
3734
3735 @Override
3736 protected boolean allowFilterResult(
3737 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3738 ServiceInfo filterSi = filter.service.info;
3739 for (int i=dest.size()-1; i>=0; i--) {
3740 ServiceInfo destAi = dest.get(i).serviceInfo;
3741 if (destAi.name == filterSi.name
3742 && destAi.packageName == filterSi.packageName) {
3743 return false;
3744 }
3745 }
3746 return true;
3747 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 @Override
3750 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
3751 int match) {
3752 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
3753 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
3754 return null;
3755 }
3756 final PackageParser.Service service = info.service;
3757 if (mSafeMode && (service.info.applicationInfo.flags
3758 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3759 return null;
3760 }
3761 final ResolveInfo res = new ResolveInfo();
3762 res.serviceInfo = PackageParser.generateServiceInfo(service,
3763 mFlags);
3764 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3765 res.filter = filter;
3766 }
3767 res.priority = info.getPriority();
3768 res.preferredOrder = service.owner.mPreferredOrder;
3769 //System.out.println("Result: " + res.activityInfo.className +
3770 // " = " + res.priority);
3771 res.match = match;
3772 res.isDefault = info.hasDefault;
3773 res.labelRes = info.labelRes;
3774 res.nonLocalizedLabel = info.nonLocalizedLabel;
3775 res.icon = info.icon;
3776 return res;
3777 }
3778
3779 @Override
3780 protected void sortResults(List<ResolveInfo> results) {
3781 Collections.sort(results, mResolvePrioritySorter);
3782 }
3783
3784 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003785 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003786 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003787 out.print(prefix); out.print(
3788 Integer.toHexString(System.identityHashCode(filter.service)));
3789 out.print(' ');
3790 out.println(filter.service.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791 }
3792
3793// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3794// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3795// final List<ResolveInfo> retList = Lists.newArrayList();
3796// while (i.hasNext()) {
3797// final ResolveInfo resolveInfo = (ResolveInfo) i;
3798// if (isEnabledLP(resolveInfo.serviceInfo)) {
3799// retList.add(resolveInfo);
3800// }
3801// }
3802// return retList;
3803// }
3804
3805 // Keys are String (activity class name), values are Activity.
3806 private final HashMap<ComponentName, PackageParser.Service> mServices
3807 = new HashMap<ComponentName, PackageParser.Service>();
3808 private int mFlags;
3809 };
3810
3811 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
3812 new Comparator<ResolveInfo>() {
3813 public int compare(ResolveInfo r1, ResolveInfo r2) {
3814 int v1 = r1.priority;
3815 int v2 = r2.priority;
3816 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
3817 if (v1 != v2) {
3818 return (v1 > v2) ? -1 : 1;
3819 }
3820 v1 = r1.preferredOrder;
3821 v2 = r2.preferredOrder;
3822 if (v1 != v2) {
3823 return (v1 > v2) ? -1 : 1;
3824 }
3825 if (r1.isDefault != r2.isDefault) {
3826 return r1.isDefault ? -1 : 1;
3827 }
3828 v1 = r1.match;
3829 v2 = r2.match;
3830 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
3831 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3832 }
3833 };
3834
3835 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
3836 new Comparator<ProviderInfo>() {
3837 public int compare(ProviderInfo p1, ProviderInfo p2) {
3838 final int v1 = p1.initOrder;
3839 final int v2 = p2.initOrder;
3840 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3841 }
3842 };
3843
3844 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
3845 IActivityManager am = ActivityManagerNative.getDefault();
3846 if (am != null) {
3847 try {
3848 final Intent intent = new Intent(action,
3849 pkg != null ? Uri.fromParts("package", pkg, null) : null);
3850 if (extras != null) {
3851 intent.putExtras(extras);
3852 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07003853 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 am.broadcastIntent(
3855 null, intent,
3856 null, null, 0, null, null, null, false, false);
3857 } catch (RemoteException ex) {
3858 }
3859 }
3860 }
3861
3862 private final class AppDirObserver extends FileObserver {
3863 public AppDirObserver(String path, int mask, boolean isrom) {
3864 super(path, mask);
3865 mRootDir = path;
3866 mIsRom = isrom;
3867 }
3868
3869 public void onEvent(int event, String path) {
3870 String removedPackage = null;
3871 int removedUid = -1;
3872 String addedPackage = null;
3873 int addedUid = -1;
3874
3875 synchronized (mInstallLock) {
3876 String fullPathStr = null;
3877 File fullPath = null;
3878 if (path != null) {
3879 fullPath = new File(mRootDir, path);
3880 fullPathStr = fullPath.getPath();
3881 }
3882
3883 if (Config.LOGV) Log.v(
3884 TAG, "File " + fullPathStr + " changed: "
3885 + Integer.toHexString(event));
3886
3887 if (!isPackageFilename(path)) {
3888 if (Config.LOGV) Log.v(
3889 TAG, "Ignoring change of non-package file: " + fullPathStr);
3890 return;
3891 }
3892
3893 if ((event&REMOVE_EVENTS) != 0) {
3894 synchronized (mInstallLock) {
3895 PackageParser.Package p = mAppDirs.get(fullPathStr);
3896 if (p != null) {
3897 removePackageLI(p, true);
3898 removedPackage = p.applicationInfo.packageName;
3899 removedUid = p.applicationInfo.uid;
3900 }
3901 }
3902 }
3903
3904 if ((event&ADD_EVENTS) != 0) {
3905 PackageParser.Package p = mAppDirs.get(fullPathStr);
3906 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003907 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
3909 PackageParser.PARSE_CHATTY |
3910 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08003911 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 if (p != null) {
3913 synchronized (mPackages) {
3914 grantPermissionsLP(p, false);
3915 }
3916 addedPackage = p.applicationInfo.packageName;
3917 addedUid = p.applicationInfo.uid;
3918 }
3919 }
3920 }
3921
3922 synchronized (mPackages) {
3923 mSettings.writeLP();
3924 }
3925 }
3926
3927 if (removedPackage != null) {
3928 Bundle extras = new Bundle(1);
3929 extras.putInt(Intent.EXTRA_UID, removedUid);
3930 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
3931 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
3932 }
3933 if (addedPackage != null) {
3934 Bundle extras = new Bundle(1);
3935 extras.putInt(Intent.EXTRA_UID, addedUid);
3936 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
3937 }
3938 }
3939
3940 private final String mRootDir;
3941 private final boolean mIsRom;
3942 }
Jacek Surazski65e13172009-04-28 15:26:38 +02003943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003944 /* Called when a downloaded package installation has been confirmed by the user */
3945 public void installPackage(
3946 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02003947 installPackage(packageURI, observer, flags, null);
3948 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003949
Jacek Surazski65e13172009-04-28 15:26:38 +02003950 /* Called when a downloaded package installation has been confirmed by the user */
3951 public void installPackage(
3952 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
3953 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 mContext.enforceCallingOrSelfPermission(
3955 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003956
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003957 Message msg = mHandler.obtainMessage(INIT_COPY);
3958 msg.obj = createInstallArgs(packageURI, observer, flags, installerPackageName);
3959 mHandler.sendMessage(msg);
3960 }
3961
3962 private InstallArgs createInstallArgs(Uri packageURI, IPackageInstallObserver observer,
3963 int flags, String installerPackageName) {
3964 if (installOnSd(flags)) {
3965 return new SdInstallArgs(packageURI, observer, flags,
3966 installerPackageName);
3967 } else {
3968 return new FileInstallArgs(packageURI, observer, flags,
3969 installerPackageName);
3970 }
3971 }
3972
3973 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
3974 if (installOnSd(flags)) {
3975 return new SdInstallArgs(fullCodePath, fullResourcePath);
3976 } else {
3977 return new FileInstallArgs(fullCodePath, fullResourcePath);
3978 }
3979 }
3980
3981 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 // Queue up an async operation since the package installation may take a little while.
3983 mHandler.post(new Runnable() {
3984 public void run() {
3985 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003986 // Result object to be returned
3987 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003988 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003989 res.uid = -1;
3990 res.pkg = null;
3991 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003992 args.doPreInstall(res.returnCode);
3993 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003994 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003995 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003996 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003997 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003999 if (args.observer != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004001 args.observer.packageInstalled(res.name, res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 } catch (RemoteException e) {
4003 Log.i(TAG, "Observer no longer exists.");
4004 }
4005 }
4006 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
4007 // call appears in the synchronized block above.
4008 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4009 res.removedInfo.sendBroadcast(false, true);
4010 Bundle extras = new Bundle(1);
4011 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07004012 final boolean update = res.removedInfo.removedPackage != null;
4013 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4015 }
4016 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
4017 res.pkg.applicationInfo.packageName,
4018 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07004019 if (update) {
4020 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
4021 res.pkg.applicationInfo.packageName,
4022 extras);
4023 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004024 if (res.removedInfo.args != null) {
4025 // Remove the replaced package's older resources safely now
4026 synchronized (mInstallLock) {
4027 res.removedInfo.args.cleanUpResourcesLI();
4028 }
4029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 }
4031 Runtime.getRuntime().gc();
4032 }
4033 });
4034 }
4035
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004036 static abstract class InstallArgs {
4037 final IPackageInstallObserver observer;
4038 final int flags;
4039 final Uri packageURI;
4040 final String installerPackageName;
4041
4042 InstallArgs(Uri packageURI,
4043 IPackageInstallObserver observer, int flags,
4044 String installerPackageName) {
4045 this.packageURI = packageURI;
4046 this.flags = flags;
4047 this.observer = observer;
4048 this.installerPackageName = installerPackageName;
4049 }
4050
4051 abstract void createCopyFile();
4052 abstract int copyApk(IMediaContainerService imcs);
4053 abstract void doPreInstall(int status);
4054 abstract boolean doRename(int status, String pkgName, String oldCodePath);
4055 abstract void doPostInstall(int status);
4056 abstract String getCodePath();
4057 abstract String getResourcePath();
4058 // Need installer lock especially for dex file removal.
4059 abstract void cleanUpResourcesLI();
4060 }
4061
4062 class FileInstallArgs extends InstallArgs {
4063 File installDir;
4064 String codeFileName;
4065 String resourceFileName;
4066
4067 FileInstallArgs(Uri packageURI,
4068 IPackageInstallObserver observer, int flags,
4069 String installerPackageName) {
4070 super(packageURI, observer, flags, installerPackageName);
4071 }
4072
4073 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4074 super(null, null, 0, null);
4075 File codeFile = new File(fullCodePath);
4076 installDir = codeFile.getParentFile();
4077 codeFileName = fullCodePath;
4078 resourceFileName = fullResourcePath;
4079 }
4080
4081 void createCopyFile() {
4082 boolean fwdLocked = isFwdLocked(flags);
4083 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4084 codeFileName = createTempPackageFile(installDir).getPath();
4085 resourceFileName = getResourcePathFromCodePath();
4086 }
4087
4088 String getCodePath() {
4089 return codeFileName;
4090 }
4091
4092 int copyApk(IMediaContainerService imcs) {
4093 // Get a ParcelFileDescriptor to write to the output file
4094 File codeFile = new File(codeFileName);
4095 ParcelFileDescriptor out = null;
4096 try {
4097 out = ParcelFileDescriptor.open(codeFile,
4098 ParcelFileDescriptor.MODE_READ_WRITE);
4099 } catch (FileNotFoundException e) {
4100 Log.e(TAG, "Failed to create file descritpor for : " + codeFileName);
4101 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4102 }
4103 // Copy the resource now
4104 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4105 try {
4106 if (imcs.copyResource(packageURI, out)) {
4107 ret = PackageManager.INSTALL_SUCCEEDED;
4108 }
4109 } catch (RemoteException e) {
4110 } finally {
4111 try { if (out != null) out.close(); } catch (IOException e) {}
4112 }
4113 return ret;
4114 }
4115
4116 void doPreInstall(int status) {
4117 if (status != PackageManager.INSTALL_SUCCEEDED) {
4118 cleanUp();
4119 }
4120 }
4121
4122 boolean doRename(int status, final String pkgName, String oldCodePath) {
4123 if (status != PackageManager.INSTALL_SUCCEEDED) {
4124 cleanUp();
4125 return false;
4126 } else {
4127 // Rename based on packageName
4128 File codeFile = new File(getCodePath());
4129 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4130 File desFile = new File(installDir, apkName + ".apk");
4131 if (!codeFile.renameTo(desFile)) {
4132 return false;
4133 }
4134 // Reset paths since the file has been renamed.
4135 codeFileName = desFile.getPath();
4136 resourceFileName = getResourcePathFromCodePath();
4137 // Set permissions
4138 if (!setPermissions(pkgName)) {
4139 // Failed setting permissions.
4140 return false;
4141 }
4142 return true;
4143 }
4144 }
4145
4146 void doPostInstall(int status) {
4147 if (status != PackageManager.INSTALL_SUCCEEDED) {
4148 cleanUp();
4149 }
4150 }
4151
4152 String getResourcePath() {
4153 return resourceFileName;
4154 }
4155
4156 String getResourcePathFromCodePath() {
4157 String codePath = getCodePath();
4158 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4159 String apkNameOnly = getApkName(codePath);
4160 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4161 } else {
4162 return codePath;
4163 }
4164 }
4165
4166 private boolean cleanUp() {
4167 boolean ret = true;
4168 String sourceDir = getCodePath();
4169 String publicSourceDir = getResourcePath();
4170 if (sourceDir != null) {
4171 File sourceFile = new File(sourceDir);
4172 if (!sourceFile.exists()) {
4173 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4174 ret = false;
4175 }
4176 // Delete application's code and resources
4177 sourceFile.delete();
4178 }
4179 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4180 final File publicSourceFile = new File(publicSourceDir);
4181 if (!publicSourceFile.exists()) {
4182 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4183 }
4184 if (publicSourceFile.exists()) {
4185 publicSourceFile.delete();
4186 }
4187 }
4188 return ret;
4189 }
4190
4191 void cleanUpResourcesLI() {
4192 String sourceDir = getCodePath();
4193 if (cleanUp() && mInstaller != null) {
4194 int retCode = mInstaller.rmdex(sourceDir);
4195 if (retCode < 0) {
4196 Log.w(TAG, "Couldn't remove dex file for package: "
4197 + " at location "
4198 + sourceDir + ", retcode=" + retCode);
4199 // we don't consider this to be a failure of the core package deletion
4200 }
4201 }
4202 }
4203
4204 private boolean setPermissions(String pkgName) {
4205 // TODO Do this in a more elegant way later on. for now just a hack
4206 if (!isFwdLocked(flags)) {
4207 final int filePermissions =
4208 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4209 |FileUtils.S_IROTH;
4210 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4211 if (retCode != 0) {
4212 Log.e(TAG, "Couldn't set new package file permissions for " +
4213 getCodePath()
4214 + ". The return code was: " + retCode);
4215 // TODO Define new internal error
4216 return false;
4217 }
4218 return true;
4219 }
4220 return true;
4221 }
4222 }
4223
4224 class SdInstallArgs extends InstallArgs {
4225 String cid;
4226 String cachePath;
4227 static final String RES_FILE_NAME = "pkg.apk";
4228
4229 SdInstallArgs(Uri packageURI,
4230 IPackageInstallObserver observer, int flags,
4231 String installerPackageName) {
4232 super(packageURI, observer, flags, installerPackageName);
4233 }
4234
4235 SdInstallArgs(String fullCodePath, String fullResourcePath) {
4236 super(null, null, 0, null);
4237 // Extract cid from fullCodePath
4238 int eidx = fullCodePath.lastIndexOf("/");
4239 String subStr1 = fullCodePath.substring(0, eidx);
4240 int sidx = subStr1.lastIndexOf("/");
4241 cid = subStr1.substring(sidx+1, eidx);
4242 cachePath = subStr1;
4243 }
4244
4245 void createCopyFile() {
4246 cid = getTempContainerId();
4247 }
4248
4249 int copyApk(IMediaContainerService imcs) {
4250 try {
4251 cachePath = imcs.copyResourceToContainer(
4252 packageURI, cid,
4253 getEncryptKey(), RES_FILE_NAME);
4254 } catch (RemoteException e) {
4255 }
4256
4257 if (cachePath != null) {
4258 // Mount container once its created with system_uid
4259 cachePath = mountSdDir(cid, Process.SYSTEM_UID);
4260 }
4261 if (cachePath == null) {
4262 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
4263 } else {
4264 return PackageManager.INSTALL_SUCCEEDED;
4265 }
4266 }
4267
4268 @Override
4269 String getCodePath() {
4270 return cachePath + "/" + RES_FILE_NAME;
4271 }
4272
4273 @Override
4274 String getResourcePath() {
4275 return cachePath + "/" + RES_FILE_NAME;
4276 }
4277
4278 void doPreInstall(int status) {
4279 if (status != PackageManager.INSTALL_SUCCEEDED) {
4280 // Destroy container
4281 destroySdDir(cid);
4282 }
4283 }
4284
4285 boolean doRename(int status, final String pkgName,
4286 String oldCodePath) {
4287 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
4288 // STOPSHIP TEMPORARY HACK FOR RENAME
4289 // Create new container at newCachePath
4290 String codePath = getCodePath();
4291 String newCachePath = null;
4292 final int CREATE_FAILED = 1;
4293 final int COPY_FAILED = 3;
4294 final int FINALIZE_FAILED = 5;
4295 final int PASS = 7;
4296 int errCode = CREATE_FAILED;
4297 if ((newCachePath = createSdDir(new File(codePath), newCacheId)) != null) {
4298 errCode = COPY_FAILED;
4299 // Copy file from codePath
4300 if (FileUtils.copyFile(new File(codePath), new File(newCachePath, RES_FILE_NAME))) {
4301 errCode = FINALIZE_FAILED;
4302 if (finalizeSdDir(newCacheId)) {
4303 errCode = PASS;
4304 }
4305 }
4306 }
4307 // Print error based on errCode
4308 String errMsg = "";
4309 switch (errCode) {
4310 case CREATE_FAILED:
4311 errMsg = "CREATE_FAILED";
4312 break;
4313 case COPY_FAILED:
4314 errMsg = "COPY_FAILED";
4315 destroySdDir(newCacheId);
4316 break;
4317 case FINALIZE_FAILED:
4318 errMsg = "FINALIZE_FAILED";
4319 destroySdDir(newCacheId);
4320 break;
4321 default:
4322 errMsg = "PASS";
4323 break;
4324 }
4325 // Destroy the temporary container
4326 destroySdDir(cid);
4327 Log.i(TAG, "Status: " + errMsg);
4328 if (errCode != PASS) {
4329 return false;
4330 }
4331 cid = newCacheId;
4332 cachePath = newCachePath;
4333
4334 return true;
4335 }
4336
4337 void doPostInstall(int status) {
4338 if (status != PackageManager.INSTALL_SUCCEEDED) {
4339 cleanUp();
4340 } else {
4341 // Unmount container
4342 // Rename and remount based on package name and new uid
4343 }
4344 }
4345
4346 private void cleanUp() {
4347 // Destroy secure container
4348 destroySdDir(cid);
4349 }
4350
4351 void cleanUpResourcesLI() {
4352 String sourceFile = getCodePath();
4353 // Remove dex file
4354 if (mInstaller != null) {
4355 int retCode = mInstaller.rmdex(sourceFile.toString());
4356 if (retCode < 0) {
4357 Log.w(TAG, "Couldn't remove dex file for package: "
4358 + " at location "
4359 + sourceFile.toString() + ", retcode=" + retCode);
4360 // we don't consider this to be a failure of the core package deletion
4361 }
4362 }
4363 cleanUp();
4364 }
4365 };
4366
4367 // Utility method used to create code paths based on package name and available index.
4368 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
4369 String idxStr = "";
4370 int idx = 1;
4371 if (oldCodePath != null) {
4372 int eidx = -1;
4373 if (suffix != null) {
4374 eidx = oldCodePath.indexOf(suffix);
4375 }
4376 if (eidx == -1) {
4377 eidx = oldCodePath.length();
4378 }
4379 int sidx = oldCodePath.indexOf(prefix);
4380 if (sidx == -1) {
4381 sidx = 0;
4382 }
4383 String subStr = oldCodePath.substring(sidx + prefix.length(), eidx);
4384 if (subStr != null) {
4385 if (subStr.startsWith("-")) {
4386 subStr = subStr.substring(1);
4387 }
4388 try {
4389 idx = Integer.parseInt(subStr);
4390 if (idx <= 1) {
4391 idx++;
4392 } else {
4393 idx--;
4394 }
4395 } catch(NumberFormatException e) {
4396 }
4397 }
4398 }
4399 idxStr = "-" + Integer.toString(idx);
4400 return prefix + idxStr;
4401 }
4402
4403 // Utility method that returns the relative package path with respect
4404 // to the installation directory. Like say for /data/data/com.test-1.apk
4405 // string com.test-1 is returned.
4406 static String getApkName(String codePath) {
4407 if (codePath == null) {
4408 return null;
4409 }
4410 int sidx = codePath.lastIndexOf("/");
4411 int eidx = codePath.lastIndexOf(".");
4412 if (eidx == -1) {
4413 eidx = codePath.length();
4414 } else if (eidx == 0) {
4415 Log.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
4416 return null;
4417 }
4418 return codePath.substring(sidx+1, eidx);
4419 }
4420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004421 class PackageInstalledInfo {
4422 String name;
4423 int uid;
4424 PackageParser.Package pkg;
4425 int returnCode;
4426 PackageRemovedInfo removedInfo;
4427 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004429 /*
4430 * Install a non-existing package.
4431 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004432 private void installNewPackageLI(PackageParser.Package pkg,
4433 int parseFlags,
4434 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004435 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004436 // Remember this for later, in case we need to rollback this install
Oscar Montemayora8529f62009-11-18 10:14:20 -08004437 boolean dataDirExists;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004438 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08004439
4440 if (useEncryptedFilesystemForPackage(pkg)) {
4441 dataDirExists = (new File(mSecureAppDataDir, pkgName)).exists();
4442 } else {
4443 dataDirExists = (new File(mAppDataDir, pkgName)).exists();
4444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445 res.name = pkgName;
4446 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004447 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004448 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004449 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004450 + " without first uninstalling.");
4451 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4452 return;
4453 }
4454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004455 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004456 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004457 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004458 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004459 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4460 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4461 }
4462 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004463 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004464 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004465 res);
4466 // delete the partially installed application. the data directory will have to be
4467 // restored if it was already existing
4468 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4469 // remove package from internal structures. Note that we want deletePackageX to
4470 // delete the package data and cache directories that it created in
4471 // scanPackageLocked, unless those directories existed before we even tried to
4472 // install.
4473 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004474 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004475 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
4476 res.removedInfo);
4477 }
4478 }
4479 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004480
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004481 private void replacePackageLI(PackageParser.Package pkg,
4482 int parseFlags,
4483 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004484 String installerPackageName, PackageInstalledInfo res) {
4485
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004486 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004487 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004488 // First find the old package info and check signatures
4489 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004490 oldPackage = mPackages.get(pkgName);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004491 if(checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
4492 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004493 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
4494 return;
4495 }
4496 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004497 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004498 if(sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004499 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004500 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004501 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502 }
4503 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004505 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004506 PackageParser.Package pkg,
4507 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004508 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004509 PackageParser.Package newPackage = null;
4510 String pkgName = deletedPackage.packageName;
4511 boolean deletedPkg = true;
4512 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004513
Jacek Surazski65e13172009-04-28 15:26:38 +02004514 String oldInstallerPackageName = null;
4515 synchronized (mPackages) {
4516 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
4517 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004518
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004519 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004521 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004522 res.removedInfo)) {
4523 // If the existing package was'nt successfully deleted
4524 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4525 deletedPkg = false;
4526 } else {
4527 // Successfully deleted the old package. Now proceed with re-installation
4528 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004529 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004530 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004531 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004532 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4533 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08004534 }
4535 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004536 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004537 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004538 res);
4539 updatedSettings = true;
4540 }
4541 }
4542
4543 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4544 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004545 // were keeping around in case we needed them (see below) can now be deleted.
4546 // This info will be set on the res.removedInfo to clean up later on as post
4547 // install action.
4548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004549 //update signature on the new package setting
4550 //this should always succeed, since we checked the
4551 //signature earlier.
4552 synchronized(mPackages) {
4553 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
4554 parseFlags, true);
4555 }
4556 } else {
4557 // remove package from internal structures. Note that we want deletePackageX to
4558 // delete the package data and cache directories that it created in
4559 // scanPackageLocked, unless those directories existed before we even tried to
4560 // install.
4561 if(updatedSettings) {
4562 deletePackageLI(
4563 pkgName, true,
4564 PackageManager.DONT_DELETE_DATA,
4565 res.removedInfo);
4566 }
4567 // Since we failed to install the new package we need to restore the old
4568 // package that we deleted.
4569 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004570 File restoreFile = new File(deletedPackage.mPath);
4571 if (restoreFile == null) {
4572 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
4573 return;
4574 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004575 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
4576 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004577 // Parse old package
4578 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
4579 scanPackageLI(restoreFile, parseFlags, scanMode);
4580 synchronized (mPackages) {
4581 grantPermissionsLP(deletedPackage, false);
4582 mSettings.writeLP();
4583 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004584 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4585 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
4586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004587 }
4588 }
4589 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004591 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004592 PackageParser.Package pkg,
4593 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004594 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004595 PackageParser.Package newPackage = null;
4596 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004597 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004598 PackageParser.PARSE_IS_SYSTEM;
4599 String packageName = deletedPackage.packageName;
4600 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4601 if (packageName == null) {
4602 Log.w(TAG, "Attempt to delete null packageName.");
4603 return;
4604 }
4605 PackageParser.Package oldPkg;
4606 PackageSetting oldPkgSetting;
4607 synchronized (mPackages) {
4608 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004609 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004610 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
4611 (oldPkgSetting == null)) {
4612 Log.w(TAG, "Could'nt find package:"+packageName+" information");
4613 return;
4614 }
4615 }
4616 res.removedInfo.uid = oldPkg.applicationInfo.uid;
4617 res.removedInfo.removedPackage = packageName;
4618 // Remove existing system package
4619 removePackageLI(oldPkg, true);
4620 synchronized (mPackages) {
4621 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
4622 }
4623
4624 // Successfully disabled the old package. Now proceed with re-installation
4625 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4626 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004627 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004628 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004629 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004630 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4631 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4632 }
4633 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004634 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004635 updatedSettings = true;
4636 }
4637
4638 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4639 //update signature on the new package setting
4640 //this should always succeed, since we checked the
4641 //signature earlier.
4642 synchronized(mPackages) {
4643 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
4644 parseFlags, true);
4645 }
4646 } else {
4647 // Re installation failed. Restore old information
4648 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07004649 if (newPackage != null) {
4650 removePackageLI(newPackage, true);
4651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004652 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004653 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004654 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07004655 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004656 // Restore the old system information in Settings
4657 synchronized(mPackages) {
4658 if(updatedSettings) {
4659 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02004660 mSettings.setInstallerPackageName(packageName,
4661 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004662 }
4663 mSettings.writeLP();
4664 }
4665 }
4666 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004667
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004668 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004669 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004670 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004671 synchronized (mPackages) {
4672 //write settings. the installStatus will be incomplete at this stage.
4673 //note that the new package setting would have already been
4674 //added to mPackages. It hasn't been persisted yet.
4675 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
4676 mSettings.writeLP();
4677 }
4678
4679 int retCode = 0;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004680 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4681 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004683 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004684 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4685 return;
4686 }
4687 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004688 res.returnCode = setPermissionsLI(newPackage);
4689 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4690 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004691 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004692 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004693 }
4694 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4695 if (mInstaller != null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004696 mInstaller.rmdex(newPackage.mScanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004697 }
4698 }
4699
4700 synchronized (mPackages) {
4701 grantPermissionsLP(newPackage, true);
4702 res.name = pkgName;
4703 res.uid = newPackage.applicationInfo.uid;
4704 res.pkg = newPackage;
4705 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02004706 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004707 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4708 //to update install status
4709 mSettings.writeLP();
4710 }
4711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004712
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004713 private void installPackageLI(InstallArgs args,
4714 boolean newInstall, PackageInstalledInfo res) {
4715 int pFlags = args.flags;
4716 String installerPackageName = args.installerPackageName;
4717 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004718 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
4719 boolean onSd = ((pFlags & PackageManager.INSTALL_ON_SDCARD) != 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004720 boolean replacingExistingPackage = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004721 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
4722 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004723 // Result object to be returned
4724 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4725
4726 main_flow: try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004727 // Retrieve PackageSettings and parse package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004728 int parseFlags = PackageParser.PARSE_CHATTY |
4729 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
4730 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004731 parseFlags |= mDefParseFlags;
4732 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
4733 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004734 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004735 null, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004736 if (pkg == null) {
4737 res.returnCode = pp.getParseError();
4738 break main_flow;
4739 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004740 String pkgName = res.name = pkg.packageName;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004741 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
4742 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
4743 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
4744 break main_flow;
4745 }
4746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004747 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
4748 res.returnCode = pp.getParseError();
4749 break main_flow;
4750 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004751
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004752 // Get rid of all references to package scan path via parser.
4753 pp = null;
4754 String oldCodePath = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004755 synchronized (mPackages) {
4756 //check if installing already existing package
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004757 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004758 && mPackages.containsKey(pkgName)) {
4759 replacingExistingPackage = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004760 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004761 }
4762 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004763
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004764 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
4765 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4766 break main_flow;
4767 }
4768 // TODO rename pkg.mScanPath In scanPackageLI let it just set values based on mScanPath
4769 pkg.applicationInfo.sourceDir = pkg.mScanPath= pkg.mPath = args.getCodePath();
4770 pkg.applicationInfo.publicSourceDir = args.getResourcePath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004771 if(replacingExistingPackage) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004772 replacePackageLI(pkg, parseFlags, scanMode,
4773 installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004774 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004775 installNewPackageLI(pkg, parseFlags, scanMode,
4776 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004777 }
4778 } finally {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004779 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004781 }
4782 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004783
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004784 private int setPermissionsLI(PackageParser.Package newPackage) {
4785 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004786 int retCode = 0;
4787 // TODO Gross hack but fix later. Ideally move this to be a post installation
4788 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004789 if ((newPackage.applicationInfo.flags
4790 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
4791 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004792 try {
4793 extractPublicFiles(newPackage, destResourceFile);
4794 } catch (IOException e) {
4795 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
4796 " forward-locked app.");
4797 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4798 } finally {
4799 //TODO clean up the extracted public files
4800 }
4801 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004802 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004803 newPackage.applicationInfo.uid);
4804 } else {
4805 final int filePermissions =
4806 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004807 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004808 newPackage.applicationInfo.uid);
4809 }
4810 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004811 // The permissions on the resource file was set when it was copied for
4812 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004813 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004815 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004816 Log.e(TAG, "Couldn't set new package file permissions for " +
4817 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004818 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004819 // TODO Define new internal error
4820 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004821 }
4822 return PackageManager.INSTALL_SUCCEEDED;
4823 }
4824
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004825 private boolean isForwardLocked(PackageParser.Package pkg) {
4826 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004827 }
4828
4829 private void extractPublicFiles(PackageParser.Package newPackage,
4830 File publicZipFile) throws IOException {
4831 final ZipOutputStream publicZipOutStream =
4832 new ZipOutputStream(new FileOutputStream(publicZipFile));
4833 final ZipFile privateZip = new ZipFile(newPackage.mPath);
4834
4835 // Copy manifest, resources.arsc and res directory to public zip
4836
4837 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
4838 while (privateZipEntries.hasMoreElements()) {
4839 final ZipEntry zipEntry = privateZipEntries.nextElement();
4840 final String zipEntryName = zipEntry.getName();
4841 if ("AndroidManifest.xml".equals(zipEntryName)
4842 || "resources.arsc".equals(zipEntryName)
4843 || zipEntryName.startsWith("res/")) {
4844 try {
4845 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
4846 } catch (IOException e) {
4847 try {
4848 publicZipOutStream.close();
4849 throw e;
4850 } finally {
4851 publicZipFile.delete();
4852 }
4853 }
4854 }
4855 }
4856
4857 publicZipOutStream.close();
4858 FileUtils.setPermissions(
4859 publicZipFile.getAbsolutePath(),
4860 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
4861 -1, -1);
4862 }
4863
4864 private static void copyZipEntry(ZipEntry zipEntry,
4865 ZipFile inZipFile,
4866 ZipOutputStream outZipStream) throws IOException {
4867 byte[] buffer = new byte[4096];
4868 int num;
4869
4870 ZipEntry newEntry;
4871 if (zipEntry.getMethod() == ZipEntry.STORED) {
4872 // Preserve the STORED method of the input entry.
4873 newEntry = new ZipEntry(zipEntry);
4874 } else {
4875 // Create a new entry so that the compressed len is recomputed.
4876 newEntry = new ZipEntry(zipEntry.getName());
4877 }
4878 outZipStream.putNextEntry(newEntry);
4879
4880 InputStream data = inZipFile.getInputStream(zipEntry);
4881 while ((num = data.read(buffer)) > 0) {
4882 outZipStream.write(buffer, 0, num);
4883 }
4884 outZipStream.flush();
4885 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004887 private void deleteTempPackageFiles() {
4888 FilenameFilter filter = new FilenameFilter() {
4889 public boolean accept(File dir, String name) {
4890 return name.startsWith("vmdl") && name.endsWith(".tmp");
4891 }
4892 };
4893 String tmpFilesList[] = mAppInstallDir.list(filter);
4894 if(tmpFilesList == null) {
4895 return;
4896 }
4897 for(int i = 0; i < tmpFilesList.length; i++) {
4898 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
4899 tmpFile.delete();
4900 }
4901 }
4902
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004903 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004904 File tmpPackageFile;
4905 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004906 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004907 } catch (IOException e) {
4908 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
4909 return null;
4910 }
4911 try {
4912 FileUtils.setPermissions(
4913 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
4914 -1, -1);
4915 } catch (IOException e) {
4916 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
4917 return null;
4918 }
4919 return tmpPackageFile;
4920 }
4921
4922 public void deletePackage(final String packageName,
4923 final IPackageDeleteObserver observer,
4924 final int flags) {
4925 mContext.enforceCallingOrSelfPermission(
4926 android.Manifest.permission.DELETE_PACKAGES, null);
4927 // Queue up an async operation since the package deletion may take a little while.
4928 mHandler.post(new Runnable() {
4929 public void run() {
4930 mHandler.removeCallbacks(this);
4931 final boolean succeded = deletePackageX(packageName, true, true, flags);
4932 if (observer != null) {
4933 try {
4934 observer.packageDeleted(succeded);
4935 } catch (RemoteException e) {
4936 Log.i(TAG, "Observer no longer exists.");
4937 } //end catch
4938 } //end if
4939 } //end run
4940 });
4941 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004943 /**
4944 * This method is an internal method that could be get invoked either
4945 * to delete an installed package or to clean up a failed installation.
4946 * After deleting an installed package, a broadcast is sent to notify any
4947 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004948 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004949 * installation wouldn't have sent the initial broadcast either
4950 * The key steps in deleting a package are
4951 * deleting the package information in internal structures like mPackages,
4952 * deleting the packages base directories through installd
4953 * updating mSettings to reflect current status
4954 * persisting settings for later use
4955 * sending a broadcast if necessary
4956 */
4957
4958 private boolean deletePackageX(String packageName, boolean sendBroadCast,
4959 boolean deleteCodeAndResources, int flags) {
4960 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07004961 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004962
4963 synchronized (mInstallLock) {
4964 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
4965 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004967 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07004968 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
4969 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
4970
4971 // If the removed package was a system update, the old system packaged
4972 // was re-enabled; we need to broadcast this information
4973 if (systemUpdate) {
4974 Bundle extras = new Bundle(1);
4975 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
4976 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4977
4978 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
4979 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
4980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004981 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004982 // Delete the resources here after sending the broadcast to let
4983 // other processes clean up before deleting resources.
4984 synchronized (mInstallLock) {
4985 if (info.args != null) {
4986 info.args.cleanUpResourcesLI();
4987 }
4988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004989 return res;
4990 }
4991
4992 static class PackageRemovedInfo {
4993 String removedPackage;
4994 int uid = -1;
4995 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07004996 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004997 // Clean up resources deleted packages.
4998 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07004999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005000 void sendBroadcast(boolean fullRemove, boolean replacing) {
5001 Bundle extras = new Bundle(1);
5002 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5003 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5004 if (replacing) {
5005 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5006 }
5007 if (removedPackage != null) {
5008 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5009 }
5010 if (removedUid >= 0) {
5011 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5012 }
5013 }
5014 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005016 /*
5017 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5018 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005019 * make sure this flag is set for partially installed apps. If not its meaningless to
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005020 * delete a partially installed application.
5021 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005022 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005023 int flags) {
5024 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005025 if (outInfo != null) {
5026 outInfo.removedPackage = packageName;
5027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005028 removePackageLI(p, true);
5029 // Retrieve object to delete permissions for shared user later on
5030 PackageSetting deletedPs;
5031 synchronized (mPackages) {
5032 deletedPs = mSettings.mPackages.get(packageName);
5033 }
5034 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005035 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005036 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005037 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005038 if (retCode < 0) {
5039 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
5040 + packageName + ", retcode=" + retCode);
5041 // we don't consider this to be a failure of the core package deletion
5042 }
5043 } else {
5044 //for emulator
5045 PackageParser.Package pkg = mPackages.get(packageName);
5046 File dataDir = new File(pkg.applicationInfo.dataDir);
5047 dataDir.delete();
5048 }
5049 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005050 if (outInfo != null) {
5051 outInfo.removedUid = mSettings.removePackageLP(packageName);
5052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005053 }
5054 }
5055 synchronized (mPackages) {
5056 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5057 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005058 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005059 }
5060 // Save settings now
5061 mSettings.writeLP ();
5062 }
5063 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005065 /*
5066 * Tries to delete system package.
5067 */
5068 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005069 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005070 ApplicationInfo applicationInfo = p.applicationInfo;
5071 //applicable for non-partially installed applications only
5072 if (applicationInfo == null) {
5073 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5074 return false;
5075 }
5076 PackageSetting ps = null;
5077 // Confirm if the system package has been updated
5078 // An updated system app can be deleted. This will also have to restore
5079 // the system pkg from system partition
5080 synchronized (mPackages) {
5081 ps = mSettings.getDisabledSystemPkg(p.packageName);
5082 }
5083 if (ps == null) {
5084 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
5085 return false;
5086 } else {
5087 Log.i(TAG, "Deleting system pkg from data partition");
5088 }
5089 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005090 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005091 boolean deleteCodeAndResources = false;
5092 if (ps.versionCode < p.mVersionCode) {
5093 // Delete code and resources for downgrades
5094 deleteCodeAndResources = true;
5095 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5096 flags &= ~PackageManager.DONT_DELETE_DATA;
5097 }
5098 } else {
5099 // Preserve data by setting flag
5100 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5101 flags |= PackageManager.DONT_DELETE_DATA;
5102 }
5103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005104 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5105 if (!ret) {
5106 return false;
5107 }
5108 synchronized (mPackages) {
5109 // Reinstate the old system package
5110 mSettings.enableSystemPackageLP(p.packageName);
5111 }
5112 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005113 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005114 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005115 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005117 if (newPkg == null) {
5118 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
5119 return false;
5120 }
5121 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005122 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005123 mSettings.writeLP();
5124 }
5125 return true;
5126 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005128 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5129 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5130 ApplicationInfo applicationInfo = p.applicationInfo;
5131 if (applicationInfo == null) {
5132 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5133 return false;
5134 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005135 if (outInfo != null) {
5136 outInfo.uid = applicationInfo.uid;
5137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005138
5139 // Delete package data from internal structures and also remove data if flag is set
5140 removePackageDataLI(p, outInfo, flags);
5141
5142 // Delete application code and resources
5143 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005144 // TODO can pick up from PackageSettings as well
5145 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD)!=0) ?
5146 PackageManager.INSTALL_ON_SDCARD : 0;
5147 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
5148 PackageManager.INSTALL_FORWARD_LOCK : 0;
5149 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005150 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005151 }
5152 return true;
5153 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005155 /*
5156 * This method handles package deletion in general
5157 */
5158 private boolean deletePackageLI(String packageName,
5159 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5160 if (packageName == null) {
5161 Log.w(TAG, "Attempt to delete null packageName.");
5162 return false;
5163 }
5164 PackageParser.Package p;
5165 boolean dataOnly = false;
5166 synchronized (mPackages) {
5167 p = mPackages.get(packageName);
5168 if (p == null) {
5169 //this retrieves partially installed apps
5170 dataOnly = true;
5171 PackageSetting ps = mSettings.mPackages.get(packageName);
5172 if (ps == null) {
5173 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5174 return false;
5175 }
5176 p = ps.pkg;
5177 }
5178 }
5179 if (p == null) {
5180 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5181 return false;
5182 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005184 if (dataOnly) {
5185 // Delete application data first
5186 removePackageDataLI(p, outInfo, flags);
5187 return true;
5188 }
5189 // At this point the package should have ApplicationInfo associated with it
5190 if (p.applicationInfo == null) {
5191 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5192 return false;
5193 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005194 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005195 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5196 Log.i(TAG, "Removing system package:"+p.packageName);
5197 // When an updated system application is deleted we delete the existing resources as well and
5198 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005199 ret = deleteSystemPackageLI(p, flags, outInfo);
5200 } else {
5201 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005202 // Kill application pre-emptively especially for apps on sd.
5203 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005204 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005205 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005206 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005207 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005209 public void clearApplicationUserData(final String packageName,
5210 final IPackageDataObserver observer) {
5211 mContext.enforceCallingOrSelfPermission(
5212 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
5213 // Queue up an async operation since the package deletion may take a little while.
5214 mHandler.post(new Runnable() {
5215 public void run() {
5216 mHandler.removeCallbacks(this);
5217 final boolean succeeded;
5218 synchronized (mInstallLock) {
5219 succeeded = clearApplicationUserDataLI(packageName);
5220 }
5221 if (succeeded) {
5222 // invoke DeviceStorageMonitor's update method to clear any notifications
5223 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
5224 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
5225 if (dsm != null) {
5226 dsm.updateMemory();
5227 }
5228 }
5229 if(observer != null) {
5230 try {
5231 observer.onRemoveCompleted(packageName, succeeded);
5232 } catch (RemoteException e) {
5233 Log.i(TAG, "Observer no longer exists.");
5234 }
5235 } //end if observer
5236 } //end run
5237 });
5238 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005240 private boolean clearApplicationUserDataLI(String packageName) {
5241 if (packageName == null) {
5242 Log.w(TAG, "Attempt to delete null packageName.");
5243 return false;
5244 }
5245 PackageParser.Package p;
5246 boolean dataOnly = false;
5247 synchronized (mPackages) {
5248 p = mPackages.get(packageName);
5249 if(p == null) {
5250 dataOnly = true;
5251 PackageSetting ps = mSettings.mPackages.get(packageName);
5252 if((ps == null) || (ps.pkg == null)) {
5253 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5254 return false;
5255 }
5256 p = ps.pkg;
5257 }
5258 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005259 boolean useEncryptedFSDir = false;
5260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005261 if(!dataOnly) {
5262 //need to check this only for fully installed applications
5263 if (p == null) {
5264 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5265 return false;
5266 }
5267 final ApplicationInfo applicationInfo = p.applicationInfo;
5268 if (applicationInfo == null) {
5269 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5270 return false;
5271 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005272 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005273 }
5274 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005275 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005276 if (retCode < 0) {
5277 Log.w(TAG, "Couldn't remove cache files for package: "
5278 + packageName);
5279 return false;
5280 }
5281 }
5282 return true;
5283 }
5284
5285 public void deleteApplicationCacheFiles(final String packageName,
5286 final IPackageDataObserver observer) {
5287 mContext.enforceCallingOrSelfPermission(
5288 android.Manifest.permission.DELETE_CACHE_FILES, null);
5289 // Queue up an async operation since the package deletion may take a little while.
5290 mHandler.post(new Runnable() {
5291 public void run() {
5292 mHandler.removeCallbacks(this);
5293 final boolean succeded;
5294 synchronized (mInstallLock) {
5295 succeded = deleteApplicationCacheFilesLI(packageName);
5296 }
5297 if(observer != null) {
5298 try {
5299 observer.onRemoveCompleted(packageName, succeded);
5300 } catch (RemoteException e) {
5301 Log.i(TAG, "Observer no longer exists.");
5302 }
5303 } //end if observer
5304 } //end run
5305 });
5306 }
5307
5308 private boolean deleteApplicationCacheFilesLI(String packageName) {
5309 if (packageName == null) {
5310 Log.w(TAG, "Attempt to delete null packageName.");
5311 return false;
5312 }
5313 PackageParser.Package p;
5314 synchronized (mPackages) {
5315 p = mPackages.get(packageName);
5316 }
5317 if (p == null) {
5318 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5319 return false;
5320 }
5321 final ApplicationInfo applicationInfo = p.applicationInfo;
5322 if (applicationInfo == null) {
5323 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5324 return false;
5325 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005326 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005327 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005328 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005329 if (retCode < 0) {
5330 Log.w(TAG, "Couldn't remove cache files for package: "
5331 + packageName);
5332 return false;
5333 }
5334 }
5335 return true;
5336 }
5337
5338 public void getPackageSizeInfo(final String packageName,
5339 final IPackageStatsObserver observer) {
5340 mContext.enforceCallingOrSelfPermission(
5341 android.Manifest.permission.GET_PACKAGE_SIZE, null);
5342 // Queue up an async operation since the package deletion may take a little while.
5343 mHandler.post(new Runnable() {
5344 public void run() {
5345 mHandler.removeCallbacks(this);
5346 PackageStats lStats = new PackageStats(packageName);
5347 final boolean succeded;
5348 synchronized (mInstallLock) {
5349 succeded = getPackageSizeInfoLI(packageName, lStats);
5350 }
5351 if(observer != null) {
5352 try {
5353 observer.onGetStatsCompleted(lStats, succeded);
5354 } catch (RemoteException e) {
5355 Log.i(TAG, "Observer no longer exists.");
5356 }
5357 } //end if observer
5358 } //end run
5359 });
5360 }
5361
5362 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
5363 if (packageName == null) {
5364 Log.w(TAG, "Attempt to get size of null packageName.");
5365 return false;
5366 }
5367 PackageParser.Package p;
5368 boolean dataOnly = false;
5369 synchronized (mPackages) {
5370 p = mPackages.get(packageName);
5371 if(p == null) {
5372 dataOnly = true;
5373 PackageSetting ps = mSettings.mPackages.get(packageName);
5374 if((ps == null) || (ps.pkg == null)) {
5375 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5376 return false;
5377 }
5378 p = ps.pkg;
5379 }
5380 }
5381 String publicSrcDir = null;
5382 if(!dataOnly) {
5383 final ApplicationInfo applicationInfo = p.applicationInfo;
5384 if (applicationInfo == null) {
5385 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5386 return false;
5387 }
5388 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
5389 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005390 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005391 if (mInstaller != null) {
5392 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08005393 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005394 if (res < 0) {
5395 return false;
5396 } else {
5397 return true;
5398 }
5399 }
5400 return true;
5401 }
5402
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005404 public void addPackageToPreferred(String packageName) {
5405 mContext.enforceCallingOrSelfPermission(
5406 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005407 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005408 }
5409
5410 public void removePackageFromPreferred(String packageName) {
5411 mContext.enforceCallingOrSelfPermission(
5412 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005413 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005414 }
5415
5416 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005417 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005418 }
5419
5420 public void addPreferredActivity(IntentFilter filter, int match,
5421 ComponentName[] set, ComponentName activity) {
5422 mContext.enforceCallingOrSelfPermission(
5423 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5424
5425 synchronized (mPackages) {
5426 Log.i(TAG, "Adding preferred activity " + activity + ":");
5427 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5428 mSettings.mPreferredActivities.addFilter(
5429 new PreferredActivity(filter, match, set, activity));
5430 mSettings.writeLP();
5431 }
5432 }
5433
Satish Sampath8dbe6122009-06-02 23:35:54 +01005434 public void replacePreferredActivity(IntentFilter filter, int match,
5435 ComponentName[] set, ComponentName activity) {
5436 mContext.enforceCallingOrSelfPermission(
5437 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5438 if (filter.countActions() != 1) {
5439 throw new IllegalArgumentException(
5440 "replacePreferredActivity expects filter to have only 1 action.");
5441 }
5442 if (filter.countCategories() != 1) {
5443 throw new IllegalArgumentException(
5444 "replacePreferredActivity expects filter to have only 1 category.");
5445 }
5446 if (filter.countDataAuthorities() != 0
5447 || filter.countDataPaths() != 0
5448 || filter.countDataSchemes() != 0
5449 || filter.countDataTypes() != 0) {
5450 throw new IllegalArgumentException(
5451 "replacePreferredActivity expects filter to have no data authorities, " +
5452 "paths, schemes or types.");
5453 }
5454 synchronized (mPackages) {
5455 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5456 String action = filter.getAction(0);
5457 String category = filter.getCategory(0);
5458 while (it.hasNext()) {
5459 PreferredActivity pa = it.next();
5460 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
5461 it.remove();
5462 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
5463 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5464 }
5465 }
5466 addPreferredActivity(filter, match, set, activity);
5467 }
5468 }
5469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005470 public void clearPackagePreferredActivities(String packageName) {
5471 mContext.enforceCallingOrSelfPermission(
5472 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5473
5474 synchronized (mPackages) {
5475 if (clearPackagePreferredActivitiesLP(packageName)) {
5476 mSettings.writeLP();
5477 }
5478 }
5479 }
5480
5481 boolean clearPackagePreferredActivitiesLP(String packageName) {
5482 boolean changed = false;
5483 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5484 while (it.hasNext()) {
5485 PreferredActivity pa = it.next();
5486 if (pa.mActivity.getPackageName().equals(packageName)) {
5487 it.remove();
5488 changed = true;
5489 }
5490 }
5491 return changed;
5492 }
5493
5494 public int getPreferredActivities(List<IntentFilter> outFilters,
5495 List<ComponentName> outActivities, String packageName) {
5496
5497 int num = 0;
5498 synchronized (mPackages) {
5499 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5500 while (it.hasNext()) {
5501 PreferredActivity pa = it.next();
5502 if (packageName == null
5503 || pa.mActivity.getPackageName().equals(packageName)) {
5504 if (outFilters != null) {
5505 outFilters.add(new IntentFilter(pa));
5506 }
5507 if (outActivities != null) {
5508 outActivities.add(pa.mActivity);
5509 }
5510 }
5511 }
5512 }
5513
5514 return num;
5515 }
5516
5517 public void setApplicationEnabledSetting(String appPackageName,
5518 int newState, int flags) {
5519 setEnabledSetting(appPackageName, null, newState, flags);
5520 }
5521
5522 public void setComponentEnabledSetting(ComponentName componentName,
5523 int newState, int flags) {
5524 setEnabledSetting(componentName.getPackageName(),
5525 componentName.getClassName(), newState, flags);
5526 }
5527
5528 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005529 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
5531 || newState == COMPONENT_ENABLED_STATE_ENABLED
5532 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
5533 throw new IllegalArgumentException("Invalid new component state: "
5534 + newState);
5535 }
5536 PackageSetting pkgSetting;
5537 final int uid = Binder.getCallingUid();
5538 final int permission = mContext.checkCallingPermission(
5539 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
5540 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005541 boolean sendNow = false;
5542 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005543 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005544 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005545 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005546 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005547 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005548 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005549 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005550 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005551 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005552 }
5553 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005554 "Unknown component: " + packageName
5555 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005556 }
5557 if (!allowedByPermission && (uid != pkgSetting.userId)) {
5558 throw new SecurityException(
5559 "Permission Denial: attempt to change component state from pid="
5560 + Binder.getCallingPid()
5561 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
5562 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005563 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005564 // We're dealing with an application/package level state change
5565 pkgSetting.enabled = newState;
5566 } else {
5567 // We're dealing with a component level state change
5568 switch (newState) {
5569 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005570 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005571 break;
5572 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005573 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005574 break;
5575 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005576 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 break;
5578 default:
5579 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005580 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005581 }
5582 }
5583 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005584 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005585 components = mPendingBroadcasts.get(packageName);
5586 boolean newPackage = components == null;
5587 if (newPackage) {
5588 components = new ArrayList<String>();
5589 }
5590 if (!components.contains(componentName)) {
5591 components.add(componentName);
5592 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005593 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
5594 sendNow = true;
5595 // Purge entry from pending broadcast list if another one exists already
5596 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005597 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005598 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005599 if (newPackage) {
5600 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005601 }
5602 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
5603 // Schedule a message
5604 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
5605 }
5606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005607 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609 long callingId = Binder.clearCallingIdentity();
5610 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005611 if (sendNow) {
5612 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005613 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005615 } finally {
5616 Binder.restoreCallingIdentity(callingId);
5617 }
5618 }
5619
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005620 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005621 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
5622 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
5623 + " components=" + componentNames);
5624 Bundle extras = new Bundle(4);
5625 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
5626 String nameList[] = new String[componentNames.size()];
5627 componentNames.toArray(nameList);
5628 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005629 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
5630 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005631 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005632 }
5633
Jacek Surazski65e13172009-04-28 15:26:38 +02005634 public String getInstallerPackageName(String packageName) {
5635 synchronized (mPackages) {
5636 PackageSetting pkg = mSettings.mPackages.get(packageName);
5637 if (pkg == null) {
5638 throw new IllegalArgumentException("Unknown package: " + packageName);
5639 }
5640 return pkg.installerPackageName;
5641 }
5642 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005644 public int getApplicationEnabledSetting(String appPackageName) {
5645 synchronized (mPackages) {
5646 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
5647 if (pkg == null) {
5648 throw new IllegalArgumentException("Unknown package: " + appPackageName);
5649 }
5650 return pkg.enabled;
5651 }
5652 }
5653
5654 public int getComponentEnabledSetting(ComponentName componentName) {
5655 synchronized (mPackages) {
5656 final String packageNameStr = componentName.getPackageName();
5657 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
5658 if (pkg == null) {
5659 throw new IllegalArgumentException("Unknown component: " + componentName);
5660 }
5661 final String classNameStr = componentName.getClassName();
5662 return pkg.currentEnabledStateLP(classNameStr);
5663 }
5664 }
5665
5666 public void enterSafeMode() {
5667 if (!mSystemReady) {
5668 mSafeMode = true;
5669 }
5670 }
5671
5672 public void systemReady() {
5673 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005674
5675 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005676 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005677 mContext.getContentResolver(),
5678 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005679 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005680 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005681 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005683 }
5684
5685 public boolean isSafeMode() {
5686 return mSafeMode;
5687 }
5688
5689 public boolean hasSystemUidErrors() {
5690 return mHasSystemUidErrors;
5691 }
5692
5693 static String arrayToString(int[] array) {
5694 StringBuffer buf = new StringBuffer(128);
5695 buf.append('[');
5696 if (array != null) {
5697 for (int i=0; i<array.length; i++) {
5698 if (i > 0) buf.append(", ");
5699 buf.append(array[i]);
5700 }
5701 }
5702 buf.append(']');
5703 return buf.toString();
5704 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005706 @Override
5707 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
5708 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5709 != PackageManager.PERMISSION_GRANTED) {
5710 pw.println("Permission Denial: can't dump ActivityManager from from pid="
5711 + Binder.getCallingPid()
5712 + ", uid=" + Binder.getCallingUid()
5713 + " without permission "
5714 + android.Manifest.permission.DUMP);
5715 return;
5716 }
5717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005718 synchronized (mPackages) {
5719 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005720 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 pw.println(" ");
5722 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005723 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 pw.println(" ");
5725 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005726 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005727 pw.println(" ");
5728 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005729 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005731 pw.println("Permissions:");
5732 {
5733 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005734 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
5735 pw.print(Integer.toHexString(System.identityHashCode(p)));
5736 pw.println("):");
5737 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
5738 pw.print(" uid="); pw.print(p.uid);
5739 pw.print(" gids="); pw.print(arrayToString(p.gids));
5740 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005741 }
5742 }
5743 pw.println(" ");
5744 pw.println("Packages:");
5745 {
5746 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005747 pw.print(" Package ["); pw.print(ps.name); pw.print("] (");
5748 pw.print(Integer.toHexString(System.identityHashCode(ps)));
5749 pw.println("):");
5750 pw.print(" userId="); pw.print(ps.userId);
5751 pw.print(" gids="); pw.println(arrayToString(ps.gids));
5752 pw.print(" sharedUser="); pw.println(ps.sharedUser);
5753 pw.print(" pkg="); pw.println(ps.pkg);
5754 pw.print(" codePath="); pw.println(ps.codePathString);
5755 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005756 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005757 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005758 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005759 pw.print(" supportsScreens=[");
5760 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005761 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005762 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005763 if (!first) pw.print(", ");
5764 first = false;
5765 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005766 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005767 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005768 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005769 if (!first) pw.print(", ");
5770 first = false;
5771 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005772 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005773 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005774 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005775 if (!first) pw.print(", ");
5776 first = false;
5777 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005778 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005779 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005780 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005781 if (!first) pw.print(", ");
5782 first = false;
5783 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005784 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005785 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005786 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
5787 if (!first) pw.print(", ");
5788 first = false;
5789 pw.print("anyDensity");
5790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005791 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005792 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005793 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
5794 pw.print(" signatures="); pw.println(ps.signatures);
5795 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
5796 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
5797 pw.print(" installStatus="); pw.print(ps.installStatus);
5798 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 if (ps.disabledComponents.size() > 0) {
5800 pw.println(" disabledComponents:");
5801 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005802 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005803 }
5804 }
5805 if (ps.enabledComponents.size() > 0) {
5806 pw.println(" enabledComponents:");
5807 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005808 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005809 }
5810 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005811 if (ps.grantedPermissions.size() > 0) {
5812 pw.println(" grantedPermissions:");
5813 for (String s : ps.grantedPermissions) {
5814 pw.print(" "); pw.println(s);
5815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005817 if (ps.loadedPermissions.size() > 0) {
5818 pw.println(" loadedPermissions:");
5819 for (String s : ps.loadedPermissions) {
5820 pw.print(" "); pw.println(s);
5821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 }
5823 }
5824 }
5825 pw.println(" ");
5826 pw.println("Shared Users:");
5827 {
5828 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005829 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
5830 pw.print(Integer.toHexString(System.identityHashCode(su)));
5831 pw.println("):");
5832 pw.print(" userId="); pw.print(su.userId);
5833 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005834 pw.println(" grantedPermissions:");
5835 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005836 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005837 }
5838 pw.println(" loadedPermissions:");
5839 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005840 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005841 }
5842 }
5843 }
5844 pw.println(" ");
5845 pw.println("Settings parse messages:");
5846 pw.println(mSettings.mReadMessages.toString());
5847 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05005848
5849 synchronized (mProviders) {
5850 pw.println(" ");
5851 pw.println("Registered ContentProviders:");
5852 for (PackageParser.Provider p : mProviders.values()) {
5853 pw.println(" ["); pw.println(p.info.authority); pw.println("]: ");
5854 pw.println(p.toString());
5855 }
5856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005857 }
5858
5859 static final class BasePermission {
5860 final static int TYPE_NORMAL = 0;
5861 final static int TYPE_BUILTIN = 1;
5862 final static int TYPE_DYNAMIC = 2;
5863
5864 final String name;
5865 final String sourcePackage;
5866 final int type;
5867 PackageParser.Permission perm;
5868 PermissionInfo pendingInfo;
5869 int uid;
5870 int[] gids;
5871
5872 BasePermission(String _name, String _sourcePackage, int _type) {
5873 name = _name;
5874 sourcePackage = _sourcePackage;
5875 type = _type;
5876 }
5877 }
5878
5879 static class PackageSignatures {
5880 private Signature[] mSignatures;
5881
5882 PackageSignatures(Signature[] sigs) {
5883 assignSignatures(sigs);
5884 }
5885
5886 PackageSignatures() {
5887 }
5888
5889 void writeXml(XmlSerializer serializer, String tagName,
5890 ArrayList<Signature> pastSignatures) throws IOException {
5891 if (mSignatures == null) {
5892 return;
5893 }
5894 serializer.startTag(null, tagName);
5895 serializer.attribute(null, "count",
5896 Integer.toString(mSignatures.length));
5897 for (int i=0; i<mSignatures.length; i++) {
5898 serializer.startTag(null, "cert");
5899 final Signature sig = mSignatures[i];
5900 final int sigHash = sig.hashCode();
5901 final int numPast = pastSignatures.size();
5902 int j;
5903 for (j=0; j<numPast; j++) {
5904 Signature pastSig = pastSignatures.get(j);
5905 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
5906 serializer.attribute(null, "index", Integer.toString(j));
5907 break;
5908 }
5909 }
5910 if (j >= numPast) {
5911 pastSignatures.add(sig);
5912 serializer.attribute(null, "index", Integer.toString(numPast));
5913 serializer.attribute(null, "key", sig.toCharsString());
5914 }
5915 serializer.endTag(null, "cert");
5916 }
5917 serializer.endTag(null, tagName);
5918 }
5919
5920 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
5921 throws IOException, XmlPullParserException {
5922 String countStr = parser.getAttributeValue(null, "count");
5923 if (countStr == null) {
5924 reportSettingsProblem(Log.WARN,
5925 "Error in package manager settings: <signatures> has"
5926 + " no count at " + parser.getPositionDescription());
5927 XmlUtils.skipCurrentTag(parser);
5928 }
5929 final int count = Integer.parseInt(countStr);
5930 mSignatures = new Signature[count];
5931 int pos = 0;
5932
5933 int outerDepth = parser.getDepth();
5934 int type;
5935 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5936 && (type != XmlPullParser.END_TAG
5937 || parser.getDepth() > outerDepth)) {
5938 if (type == XmlPullParser.END_TAG
5939 || type == XmlPullParser.TEXT) {
5940 continue;
5941 }
5942
5943 String tagName = parser.getName();
5944 if (tagName.equals("cert")) {
5945 if (pos < count) {
5946 String index = parser.getAttributeValue(null, "index");
5947 if (index != null) {
5948 try {
5949 int idx = Integer.parseInt(index);
5950 String key = parser.getAttributeValue(null, "key");
5951 if (key == null) {
5952 if (idx >= 0 && idx < pastSignatures.size()) {
5953 Signature sig = pastSignatures.get(idx);
5954 if (sig != null) {
5955 mSignatures[pos] = pastSignatures.get(idx);
5956 pos++;
5957 } else {
5958 reportSettingsProblem(Log.WARN,
5959 "Error in package manager settings: <cert> "
5960 + "index " + index + " is not defined at "
5961 + parser.getPositionDescription());
5962 }
5963 } else {
5964 reportSettingsProblem(Log.WARN,
5965 "Error in package manager settings: <cert> "
5966 + "index " + index + " is out of bounds at "
5967 + parser.getPositionDescription());
5968 }
5969 } else {
5970 while (pastSignatures.size() <= idx) {
5971 pastSignatures.add(null);
5972 }
5973 Signature sig = new Signature(key);
5974 pastSignatures.set(idx, sig);
5975 mSignatures[pos] = sig;
5976 pos++;
5977 }
5978 } catch (NumberFormatException e) {
5979 reportSettingsProblem(Log.WARN,
5980 "Error in package manager settings: <cert> "
5981 + "index " + index + " is not a number at "
5982 + parser.getPositionDescription());
5983 }
5984 } else {
5985 reportSettingsProblem(Log.WARN,
5986 "Error in package manager settings: <cert> has"
5987 + " no index at " + parser.getPositionDescription());
5988 }
5989 } else {
5990 reportSettingsProblem(Log.WARN,
5991 "Error in package manager settings: too "
5992 + "many <cert> tags, expected " + count
5993 + " at " + parser.getPositionDescription());
5994 }
5995 } else {
5996 reportSettingsProblem(Log.WARN,
5997 "Unknown element under <cert>: "
5998 + parser.getName());
5999 }
6000 XmlUtils.skipCurrentTag(parser);
6001 }
6002
6003 if (pos < count) {
6004 // Should never happen -- there is an error in the written
6005 // settings -- but if it does we don't want to generate
6006 // a bad array.
6007 Signature[] newSigs = new Signature[pos];
6008 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6009 mSignatures = newSigs;
6010 }
6011 }
6012
6013 /**
6014 * If any of the given 'sigs' is contained in the existing signatures,
6015 * then completely replace the current signatures with the ones in
6016 * 'sigs'. This is used for updating an existing package to a newly
6017 * installed version.
6018 */
6019 boolean updateSignatures(Signature[] sigs, boolean update) {
6020 if (mSignatures == null) {
6021 if (update) {
6022 assignSignatures(sigs);
6023 }
6024 return true;
6025 }
6026 if (sigs == null) {
6027 return false;
6028 }
6029
6030 for (int i=0; i<sigs.length; i++) {
6031 Signature sig = sigs[i];
6032 for (int j=0; j<mSignatures.length; j++) {
6033 if (mSignatures[j].equals(sig)) {
6034 if (update) {
6035 assignSignatures(sigs);
6036 }
6037 return true;
6038 }
6039 }
6040 }
6041 return false;
6042 }
6043
6044 /**
6045 * If any of the given 'sigs' is contained in the existing signatures,
6046 * then add in any new signatures found in 'sigs'. This is used for
6047 * including a new package into an existing shared user id.
6048 */
6049 boolean mergeSignatures(Signature[] sigs, boolean update) {
6050 if (mSignatures == null) {
6051 if (update) {
6052 assignSignatures(sigs);
6053 }
6054 return true;
6055 }
6056 if (sigs == null) {
6057 return false;
6058 }
6059
6060 Signature[] added = null;
6061 int addedCount = 0;
6062 boolean haveMatch = false;
6063 for (int i=0; i<sigs.length; i++) {
6064 Signature sig = sigs[i];
6065 boolean found = false;
6066 for (int j=0; j<mSignatures.length; j++) {
6067 if (mSignatures[j].equals(sig)) {
6068 found = true;
6069 haveMatch = true;
6070 break;
6071 }
6072 }
6073
6074 if (!found) {
6075 if (added == null) {
6076 added = new Signature[sigs.length];
6077 }
6078 added[i] = sig;
6079 addedCount++;
6080 }
6081 }
6082
6083 if (!haveMatch) {
6084 // Nothing matched -- reject the new signatures.
6085 return false;
6086 }
6087 if (added == null) {
6088 // Completely matched -- nothing else to do.
6089 return true;
6090 }
6091
6092 // Add additional signatures in.
6093 if (update) {
6094 Signature[] total = new Signature[addedCount+mSignatures.length];
6095 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
6096 int j = mSignatures.length;
6097 for (int i=0; i<added.length; i++) {
6098 if (added[i] != null) {
6099 total[j] = added[i];
6100 j++;
6101 }
6102 }
6103 mSignatures = total;
6104 }
6105 return true;
6106 }
6107
6108 private void assignSignatures(Signature[] sigs) {
6109 if (sigs == null) {
6110 mSignatures = null;
6111 return;
6112 }
6113 mSignatures = new Signature[sigs.length];
6114 for (int i=0; i<sigs.length; i++) {
6115 mSignatures[i] = sigs[i];
6116 }
6117 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006119 @Override
6120 public String toString() {
6121 StringBuffer buf = new StringBuffer(128);
6122 buf.append("PackageSignatures{");
6123 buf.append(Integer.toHexString(System.identityHashCode(this)));
6124 buf.append(" [");
6125 if (mSignatures != null) {
6126 for (int i=0; i<mSignatures.length; i++) {
6127 if (i > 0) buf.append(", ");
6128 buf.append(Integer.toHexString(
6129 System.identityHashCode(mSignatures[i])));
6130 }
6131 }
6132 buf.append("]}");
6133 return buf.toString();
6134 }
6135 }
6136
6137 static class PreferredActivity extends IntentFilter {
6138 final int mMatch;
6139 final String[] mSetPackages;
6140 final String[] mSetClasses;
6141 final String[] mSetComponents;
6142 final ComponentName mActivity;
6143 final String mShortActivity;
6144 String mParseError;
6145
6146 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
6147 ComponentName activity) {
6148 super(filter);
6149 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
6150 mActivity = activity;
6151 mShortActivity = activity.flattenToShortString();
6152 mParseError = null;
6153 if (set != null) {
6154 final int N = set.length;
6155 String[] myPackages = new String[N];
6156 String[] myClasses = new String[N];
6157 String[] myComponents = new String[N];
6158 for (int i=0; i<N; i++) {
6159 ComponentName cn = set[i];
6160 if (cn == null) {
6161 mSetPackages = null;
6162 mSetClasses = null;
6163 mSetComponents = null;
6164 return;
6165 }
6166 myPackages[i] = cn.getPackageName().intern();
6167 myClasses[i] = cn.getClassName().intern();
6168 myComponents[i] = cn.flattenToShortString().intern();
6169 }
6170 mSetPackages = myPackages;
6171 mSetClasses = myClasses;
6172 mSetComponents = myComponents;
6173 } else {
6174 mSetPackages = null;
6175 mSetClasses = null;
6176 mSetComponents = null;
6177 }
6178 }
6179
6180 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
6181 IOException {
6182 mShortActivity = parser.getAttributeValue(null, "name");
6183 mActivity = ComponentName.unflattenFromString(mShortActivity);
6184 if (mActivity == null) {
6185 mParseError = "Bad activity name " + mShortActivity;
6186 }
6187 String matchStr = parser.getAttributeValue(null, "match");
6188 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
6189 String setCountStr = parser.getAttributeValue(null, "set");
6190 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
6191
6192 String[] myPackages = setCount > 0 ? new String[setCount] : null;
6193 String[] myClasses = setCount > 0 ? new String[setCount] : null;
6194 String[] myComponents = setCount > 0 ? new String[setCount] : null;
6195
6196 int setPos = 0;
6197
6198 int outerDepth = parser.getDepth();
6199 int type;
6200 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6201 && (type != XmlPullParser.END_TAG
6202 || parser.getDepth() > outerDepth)) {
6203 if (type == XmlPullParser.END_TAG
6204 || type == XmlPullParser.TEXT) {
6205 continue;
6206 }
6207
6208 String tagName = parser.getName();
6209 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
6210 // + parser.getDepth() + " tag=" + tagName);
6211 if (tagName.equals("set")) {
6212 String name = parser.getAttributeValue(null, "name");
6213 if (name == null) {
6214 if (mParseError == null) {
6215 mParseError = "No name in set tag in preferred activity "
6216 + mShortActivity;
6217 }
6218 } else if (setPos >= setCount) {
6219 if (mParseError == null) {
6220 mParseError = "Too many set tags in preferred activity "
6221 + mShortActivity;
6222 }
6223 } else {
6224 ComponentName cn = ComponentName.unflattenFromString(name);
6225 if (cn == null) {
6226 if (mParseError == null) {
6227 mParseError = "Bad set name " + name + " in preferred activity "
6228 + mShortActivity;
6229 }
6230 } else {
6231 myPackages[setPos] = cn.getPackageName();
6232 myClasses[setPos] = cn.getClassName();
6233 myComponents[setPos] = name;
6234 setPos++;
6235 }
6236 }
6237 XmlUtils.skipCurrentTag(parser);
6238 } else if (tagName.equals("filter")) {
6239 //Log.i(TAG, "Starting to parse filter...");
6240 readFromXml(parser);
6241 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
6242 // + parser.getDepth() + " tag=" + parser.getName());
6243 } else {
6244 reportSettingsProblem(Log.WARN,
6245 "Unknown element under <preferred-activities>: "
6246 + parser.getName());
6247 XmlUtils.skipCurrentTag(parser);
6248 }
6249 }
6250
6251 if (setPos != setCount) {
6252 if (mParseError == null) {
6253 mParseError = "Not enough set tags (expected " + setCount
6254 + " but found " + setPos + ") in " + mShortActivity;
6255 }
6256 }
6257
6258 mSetPackages = myPackages;
6259 mSetClasses = myClasses;
6260 mSetComponents = myComponents;
6261 }
6262
6263 public void writeToXml(XmlSerializer serializer) throws IOException {
6264 final int NS = mSetClasses != null ? mSetClasses.length : 0;
6265 serializer.attribute(null, "name", mShortActivity);
6266 serializer.attribute(null, "match", Integer.toHexString(mMatch));
6267 serializer.attribute(null, "set", Integer.toString(NS));
6268 for (int s=0; s<NS; s++) {
6269 serializer.startTag(null, "set");
6270 serializer.attribute(null, "name", mSetComponents[s]);
6271 serializer.endTag(null, "set");
6272 }
6273 serializer.startTag(null, "filter");
6274 super.writeToXml(serializer);
6275 serializer.endTag(null, "filter");
6276 }
6277
6278 boolean sameSet(List<ResolveInfo> query, int priority) {
6279 if (mSetPackages == null) return false;
6280 final int NQ = query.size();
6281 final int NS = mSetPackages.length;
6282 int numMatch = 0;
6283 for (int i=0; i<NQ; i++) {
6284 ResolveInfo ri = query.get(i);
6285 if (ri.priority != priority) continue;
6286 ActivityInfo ai = ri.activityInfo;
6287 boolean good = false;
6288 for (int j=0; j<NS; j++) {
6289 if (mSetPackages[j].equals(ai.packageName)
6290 && mSetClasses[j].equals(ai.name)) {
6291 numMatch++;
6292 good = true;
6293 break;
6294 }
6295 }
6296 if (!good) return false;
6297 }
6298 return numMatch == NS;
6299 }
6300 }
6301
6302 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006303 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 HashSet<String> grantedPermissions = new HashSet<String>();
6306 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006308 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006310 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08006311 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
6312 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
6313 (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006314 }
6315 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006317 /**
6318 * Settings base class for pending and resolved classes.
6319 */
6320 static class PackageSettingBase extends GrantedPermissions {
6321 final String name;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006322 File codePath;
6323 String codePathString;
6324 File resourcePath;
6325 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006326 private long timeStamp;
6327 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006328 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329
6330 PackageSignatures signatures = new PackageSignatures();
6331
6332 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 /* Explicitly disabled components */
6335 HashSet<String> disabledComponents = new HashSet<String>(0);
6336 /* Explicitly enabled components */
6337 HashSet<String> enabledComponents = new HashSet<String>(0);
6338 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6339 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006340
Jacek Surazski65e13172009-04-28 15:26:38 +02006341 /* package name of the app that installed this package */
6342 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006343
6344 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006345 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006346 super(pkgFlags);
6347 this.name = name;
6348 this.codePath = codePath;
6349 this.codePathString = codePath.toString();
6350 this.resourcePath = resourcePath;
6351 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006352 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006353 }
6354
Jacek Surazski65e13172009-04-28 15:26:38 +02006355 public void setInstallerPackageName(String packageName) {
6356 installerPackageName = packageName;
6357 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006358
Jacek Surazski65e13172009-04-28 15:26:38 +02006359 String getInstallerPackageName() {
6360 return installerPackageName;
6361 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 public void setInstallStatus(int newStatus) {
6364 installStatus = newStatus;
6365 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 public int getInstallStatus() {
6368 return installStatus;
6369 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006371 public void setTimeStamp(long newStamp) {
6372 if (newStamp != timeStamp) {
6373 timeStamp = newStamp;
6374 timeStampString = Long.toString(newStamp);
6375 }
6376 }
6377
6378 public void setTimeStamp(long newStamp, String newStampStr) {
6379 timeStamp = newStamp;
6380 timeStampString = newStampStr;
6381 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006383 public long getTimeStamp() {
6384 return timeStamp;
6385 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006387 public String getTimeStampStr() {
6388 return timeStampString;
6389 }
6390
6391 public void copyFrom(PackageSettingBase base) {
6392 grantedPermissions = base.grantedPermissions;
6393 gids = base.gids;
6394 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006396 timeStamp = base.timeStamp;
6397 timeStampString = base.timeStampString;
6398 signatures = base.signatures;
6399 permissionsFixed = base.permissionsFixed;
6400 disabledComponents = base.disabledComponents;
6401 enabledComponents = base.enabledComponents;
6402 enabled = base.enabled;
6403 installStatus = base.installStatus;
6404 }
6405
6406 void enableComponentLP(String componentClassName) {
6407 disabledComponents.remove(componentClassName);
6408 enabledComponents.add(componentClassName);
6409 }
6410
6411 void disableComponentLP(String componentClassName) {
6412 enabledComponents.remove(componentClassName);
6413 disabledComponents.add(componentClassName);
6414 }
6415
6416 void restoreComponentLP(String componentClassName) {
6417 enabledComponents.remove(componentClassName);
6418 disabledComponents.remove(componentClassName);
6419 }
6420
6421 int currentEnabledStateLP(String componentName) {
6422 if (enabledComponents.contains(componentName)) {
6423 return COMPONENT_ENABLED_STATE_ENABLED;
6424 } else if (disabledComponents.contains(componentName)) {
6425 return COMPONENT_ENABLED_STATE_DISABLED;
6426 } else {
6427 return COMPONENT_ENABLED_STATE_DEFAULT;
6428 }
6429 }
6430 }
6431
6432 /**
6433 * Settings data for a particular package we know about.
6434 */
6435 static final class PackageSetting extends PackageSettingBase {
6436 int userId;
6437 PackageParser.Package pkg;
6438 SharedUserSetting sharedUser;
6439
6440 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006441 int pVersionCode, int pkgFlags) {
6442 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006443 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445 @Override
6446 public String toString() {
6447 return "PackageSetting{"
6448 + Integer.toHexString(System.identityHashCode(this))
6449 + " " + name + "/" + userId + "}";
6450 }
6451 }
6452
6453 /**
6454 * Settings data for a particular shared user ID we know about.
6455 */
6456 static final class SharedUserSetting extends GrantedPermissions {
6457 final String name;
6458 int userId;
6459 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
6460 final PackageSignatures signatures = new PackageSignatures();
6461
6462 SharedUserSetting(String _name, int _pkgFlags) {
6463 super(_pkgFlags);
6464 name = _name;
6465 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 @Override
6468 public String toString() {
6469 return "SharedUserSetting{"
6470 + Integer.toHexString(System.identityHashCode(this))
6471 + " " + name + "/" + userId + "}";
6472 }
6473 }
6474
6475 /**
6476 * Holds information about dynamic settings.
6477 */
6478 private static final class Settings {
6479 private final File mSettingsFilename;
6480 private final File mBackupSettingsFilename;
6481 private final HashMap<String, PackageSetting> mPackages =
6482 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006483 // List of replaced system applications
6484 final HashMap<String, PackageSetting> mDisabledSysPackages =
6485 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 // The user's preferred activities associated with particular intent
6488 // filters.
6489 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
6490 new IntentResolver<PreferredActivity, PreferredActivity>() {
6491 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006492 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006493 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006494 out.print(prefix); out.print(
6495 Integer.toHexString(System.identityHashCode(filter)));
6496 out.print(' ');
6497 out.print(filter.mActivity.flattenToShortString());
6498 out.print(" match=0x");
6499 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006500 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006501 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006502 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006503 out.print(prefix); out.print(" ");
6504 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006505 }
6506 }
6507 }
6508 };
6509 private final HashMap<String, SharedUserSetting> mSharedUsers =
6510 new HashMap<String, SharedUserSetting>();
6511 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
6512 private final SparseArray<Object> mOtherUserIds =
6513 new SparseArray<Object>();
6514
6515 // For reading/writing settings file.
6516 private final ArrayList<Signature> mPastSignatures =
6517 new ArrayList<Signature>();
6518
6519 // Mapping from permission names to info about them.
6520 final HashMap<String, BasePermission> mPermissions =
6521 new HashMap<String, BasePermission>();
6522
6523 // Mapping from permission tree names to info about them.
6524 final HashMap<String, BasePermission> mPermissionTrees =
6525 new HashMap<String, BasePermission>();
6526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006527 private final StringBuilder mReadMessages = new StringBuilder();
6528
6529 private static final class PendingPackage extends PackageSettingBase {
6530 final int sharedId;
6531
6532 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006533 int sharedId, int pVersionCode, int pkgFlags) {
6534 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006535 this.sharedId = sharedId;
6536 }
6537 }
6538 private final ArrayList<PendingPackage> mPendingPackages
6539 = new ArrayList<PendingPackage>();
6540
6541 Settings() {
6542 File dataDir = Environment.getDataDirectory();
6543 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08006544 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
6545 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006546 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08006547 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006548 FileUtils.setPermissions(systemDir.toString(),
6549 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6550 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6551 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08006552 FileUtils.setPermissions(systemSecureDir.toString(),
6553 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6554 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6555 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006556 mSettingsFilename = new File(systemDir, "packages.xml");
6557 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
6558 }
6559
6560 PackageSetting getPackageLP(PackageParser.Package pkg,
6561 SharedUserSetting sharedUser, File codePath, File resourcePath,
6562 int pkgFlags, boolean create, boolean add) {
6563 final String name = pkg.packageName;
6564 PackageSetting p = getPackageLP(name, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006565 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006566 return p;
6567 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006568
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006569 PackageSetting peekPackageLP(String name) {
6570 return mPackages.get(name);
6571 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006572 PackageSetting p = mPackages.get(name);
6573 if (p != null && p.codePath.getPath().equals(codePath)) {
6574 return p;
6575 }
6576 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006577 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006578 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006580 void setInstallStatus(String pkgName, int status) {
6581 PackageSetting p = mPackages.get(pkgName);
6582 if(p != null) {
6583 if(p.getInstallStatus() != status) {
6584 p.setInstallStatus(status);
6585 }
6586 }
6587 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006588
Jacek Surazski65e13172009-04-28 15:26:38 +02006589 void setInstallerPackageName(String pkgName,
6590 String installerPkgName) {
6591 PackageSetting p = mPackages.get(pkgName);
6592 if(p != null) {
6593 p.setInstallerPackageName(installerPkgName);
6594 }
6595 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006596
Jacek Surazski65e13172009-04-28 15:26:38 +02006597 String getInstallerPackageName(String pkgName) {
6598 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006599 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02006600 }
6601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006602 int getInstallStatus(String pkgName) {
6603 PackageSetting p = mPackages.get(pkgName);
6604 if(p != null) {
6605 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006607 return -1;
6608 }
6609
6610 SharedUserSetting getSharedUserLP(String name,
6611 int pkgFlags, boolean create) {
6612 SharedUserSetting s = mSharedUsers.get(name);
6613 if (s == null) {
6614 if (!create) {
6615 return null;
6616 }
6617 s = new SharedUserSetting(name, pkgFlags);
6618 if (MULTIPLE_APPLICATION_UIDS) {
6619 s.userId = newUserIdLP(s);
6620 } else {
6621 s.userId = FIRST_APPLICATION_UID;
6622 }
6623 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
6624 // < 0 means we couldn't assign a userid; fall out and return
6625 // s, which is currently null
6626 if (s.userId >= 0) {
6627 mSharedUsers.put(name, s);
6628 }
6629 }
6630
6631 return s;
6632 }
6633
6634 int disableSystemPackageLP(String name) {
6635 PackageSetting p = mPackages.get(name);
6636 if(p == null) {
6637 Log.w(TAG, "Package:"+name+" is not an installed package");
6638 return -1;
6639 }
6640 PackageSetting dp = mDisabledSysPackages.get(name);
6641 // always make sure the system package code and resource paths dont change
6642 if(dp == null) {
6643 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6644 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6645 }
6646 mDisabledSysPackages.put(name, p);
6647 }
6648 return removePackageLP(name);
6649 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006651 PackageSetting enableSystemPackageLP(String name) {
6652 PackageSetting p = mDisabledSysPackages.get(name);
6653 if(p == null) {
6654 Log.w(TAG, "Package:"+name+" is not disabled");
6655 return null;
6656 }
6657 // Reset flag in ApplicationInfo object
6658 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6659 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6660 }
6661 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006662 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 mDisabledSysPackages.remove(name);
6664 return ret;
6665 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006668 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669 PackageSetting p = mPackages.get(name);
6670 if (p != null) {
6671 if (p.userId == uid) {
6672 return p;
6673 }
6674 reportSettingsProblem(Log.ERROR,
6675 "Adding duplicate package, keeping first: " + name);
6676 return null;
6677 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006678 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006679 p.userId = uid;
6680 if (addUserIdLP(uid, p, name)) {
6681 mPackages.put(name, p);
6682 return p;
6683 }
6684 return null;
6685 }
6686
6687 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
6688 SharedUserSetting s = mSharedUsers.get(name);
6689 if (s != null) {
6690 if (s.userId == uid) {
6691 return s;
6692 }
6693 reportSettingsProblem(Log.ERROR,
6694 "Adding duplicate shared user, keeping first: " + name);
6695 return null;
6696 }
6697 s = new SharedUserSetting(name, pkgFlags);
6698 s.userId = uid;
6699 if (addUserIdLP(uid, s, name)) {
6700 mSharedUsers.put(name, s);
6701 return s;
6702 }
6703 return null;
6704 }
6705
6706 private PackageSetting getPackageLP(String name,
6707 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006708 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006709 PackageSetting p = mPackages.get(name);
6710 if (p != null) {
6711 if (!p.codePath.equals(codePath)) {
6712 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006713 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006714 // This is an updated system app with versions in both system
6715 // and data partition. Just let the most recent version
6716 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006717 Log.w(TAG, "Trying to update system app code path from " +
6718 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006719 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006720 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07006721 reportSettingsProblem(Log.WARN,
6722 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006723 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006725 }
6726 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006727 reportSettingsProblem(Log.WARN,
6728 "Package " + name + " shared user changed from "
6729 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
6730 + " to "
6731 + (sharedUser != null ? sharedUser.name : "<nothing>")
6732 + "; replacing with new");
6733 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006734 } else {
6735 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6736 // If what we are scanning is a system package, then
6737 // make it so, regardless of whether it was previously
6738 // installed only in the data partition.
6739 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006741 }
6742 }
6743 if (p == null) {
6744 // Create a new PackageSettings entry. this can end up here because
6745 // of code path mismatch or user id mismatch of an updated system partition
6746 if (!create) {
6747 return null;
6748 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006749 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006750 p.setTimeStamp(codePath.lastModified());
Dianne Hackborn5d6d7732009-05-13 18:09:56 -07006751 p.sharedUser = sharedUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006752 if (sharedUser != null) {
6753 p.userId = sharedUser.userId;
6754 } else if (MULTIPLE_APPLICATION_UIDS) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006755 // Clone the setting here for disabled system packages
6756 PackageSetting dis = mDisabledSysPackages.get(name);
6757 if (dis != null) {
6758 // For disabled packages a new setting is created
6759 // from the existing user id. This still has to be
6760 // added to list of user id's
6761 // Copy signatures from previous setting
6762 if (dis.signatures.mSignatures != null) {
6763 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
6764 }
6765 p.userId = dis.userId;
6766 // Clone permissions
6767 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
6768 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
6769 // Clone component info
6770 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
6771 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
6772 // Add new setting to list of user ids
6773 addUserIdLP(p.userId, p, name);
6774 } else {
6775 // Assign new user id
6776 p.userId = newUserIdLP(p);
6777 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006778 } else {
6779 p.userId = FIRST_APPLICATION_UID;
6780 }
6781 if (p.userId < 0) {
6782 reportSettingsProblem(Log.WARN,
6783 "Package " + name + " could not be assigned a valid uid");
6784 return null;
6785 }
6786 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006787 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006788 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006789 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006790 }
6791 }
6792 return p;
6793 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006794
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006795 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006796 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006797 String codePath = pkg.applicationInfo.sourceDir;
6798 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006799 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006800 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006801 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006802 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006803 p.codePath = new File(codePath);
6804 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006805 }
6806 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006807 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006808 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006809 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006810 p.resourcePath = new File(resourcePath);
6811 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006812 }
6813 // Update version code if needed
6814 if (pkg.mVersionCode != p.versionCode) {
6815 p.versionCode = pkg.mVersionCode;
6816 }
6817 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
6818 }
6819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006820 // Utility method that adds a PackageSetting to mPackages and
6821 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006822 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006823 SharedUserSetting sharedUser) {
6824 mPackages.put(name, p);
6825 if (sharedUser != null) {
6826 if (p.sharedUser != null && p.sharedUser != sharedUser) {
6827 reportSettingsProblem(Log.ERROR,
6828 "Package " + p.name + " was user "
6829 + p.sharedUser + " but is now " + sharedUser
6830 + "; I am not changing its files so it will probably fail!");
6831 p.sharedUser.packages.remove(p);
6832 } else if (p.userId != sharedUser.userId) {
6833 reportSettingsProblem(Log.ERROR,
6834 "Package " + p.name + " was user id " + p.userId
6835 + " but is now user " + sharedUser
6836 + " with id " + sharedUser.userId
6837 + "; I am not changing its files so it will probably fail!");
6838 }
6839
6840 sharedUser.packages.add(p);
6841 p.sharedUser = sharedUser;
6842 p.userId = sharedUser.userId;
6843 }
6844 }
6845
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006846 /*
6847 * Update the shared user setting when a package using
6848 * specifying the shared user id is removed. The gids
6849 * associated with each permission of the deleted package
6850 * are removed from the shared user's gid list only if its
6851 * not in use by other permissions of packages in the
6852 * shared user setting.
6853 */
6854 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006855 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
6856 Log.i(TAG, "Trying to update info for null package. Just ignoring");
6857 return;
6858 }
6859 // No sharedUserId
6860 if (deletedPs.sharedUser == null) {
6861 return;
6862 }
6863 SharedUserSetting sus = deletedPs.sharedUser;
6864 // Update permissions
6865 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
6866 boolean used = false;
6867 if (!sus.grantedPermissions.contains (eachPerm)) {
6868 continue;
6869 }
6870 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07006871 if (pkg.pkg != null &&
6872 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
6873 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006874 used = true;
6875 break;
6876 }
6877 }
6878 if (!used) {
6879 // can safely delete this permission from list
6880 sus.grantedPermissions.remove(eachPerm);
6881 sus.loadedPermissions.remove(eachPerm);
6882 }
6883 }
6884 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006885 int newGids[] = globalGids;
6886 for (String eachPerm : sus.grantedPermissions) {
6887 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07006888 if (bp != null) {
6889 newGids = appendInts(newGids, bp.gids);
6890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006891 }
6892 sus.gids = newGids;
6893 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006895 private int removePackageLP(String name) {
6896 PackageSetting p = mPackages.get(name);
6897 if (p != null) {
6898 mPackages.remove(name);
6899 if (p.sharedUser != null) {
6900 p.sharedUser.packages.remove(p);
6901 if (p.sharedUser.packages.size() == 0) {
6902 mSharedUsers.remove(p.sharedUser.name);
6903 removeUserIdLP(p.sharedUser.userId);
6904 return p.sharedUser.userId;
6905 }
6906 } else {
6907 removeUserIdLP(p.userId);
6908 return p.userId;
6909 }
6910 }
6911 return -1;
6912 }
6913
6914 private boolean addUserIdLP(int uid, Object obj, Object name) {
6915 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
6916 return false;
6917 }
6918
6919 if (uid >= FIRST_APPLICATION_UID) {
6920 int N = mUserIds.size();
6921 final int index = uid - FIRST_APPLICATION_UID;
6922 while (index >= N) {
6923 mUserIds.add(null);
6924 N++;
6925 }
6926 if (mUserIds.get(index) != null) {
6927 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006928 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006929 + " name=" + name);
6930 return false;
6931 }
6932 mUserIds.set(index, obj);
6933 } else {
6934 if (mOtherUserIds.get(uid) != null) {
6935 reportSettingsProblem(Log.ERROR,
6936 "Adding duplicate shared id: " + uid
6937 + " name=" + name);
6938 return false;
6939 }
6940 mOtherUserIds.put(uid, obj);
6941 }
6942 return true;
6943 }
6944
6945 public Object getUserIdLP(int uid) {
6946 if (uid >= FIRST_APPLICATION_UID) {
6947 int N = mUserIds.size();
6948 final int index = uid - FIRST_APPLICATION_UID;
6949 return index < N ? mUserIds.get(index) : null;
6950 } else {
6951 return mOtherUserIds.get(uid);
6952 }
6953 }
6954
6955 private void removeUserIdLP(int uid) {
6956 if (uid >= FIRST_APPLICATION_UID) {
6957 int N = mUserIds.size();
6958 final int index = uid - FIRST_APPLICATION_UID;
6959 if (index < N) mUserIds.set(index, null);
6960 } else {
6961 mOtherUserIds.remove(uid);
6962 }
6963 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006965 void writeLP() {
6966 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
6967
6968 // Keep the old settings around until we know the new ones have
6969 // been successfully written.
6970 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07006971 // Presence of backup settings file indicates that we failed
6972 // to persist settings earlier. So preserve the older
6973 // backup for future reference since the current settings
6974 // might have been corrupted.
6975 if (!mBackupSettingsFilename.exists()) {
6976 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
6977 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
6978 return;
6979 }
6980 } else {
6981 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07006982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006983 }
6984
6985 mPastSignatures.clear();
6986
6987 try {
6988 FileOutputStream str = new FileOutputStream(mSettingsFilename);
6989
6990 //XmlSerializer serializer = XmlUtils.serializerInstance();
6991 XmlSerializer serializer = new FastXmlSerializer();
6992 serializer.setOutput(str, "utf-8");
6993 serializer.startDocument(null, true);
6994 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
6995
6996 serializer.startTag(null, "packages");
6997
6998 serializer.startTag(null, "permission-trees");
6999 for (BasePermission bp : mPermissionTrees.values()) {
7000 writePermission(serializer, bp);
7001 }
7002 serializer.endTag(null, "permission-trees");
7003
7004 serializer.startTag(null, "permissions");
7005 for (BasePermission bp : mPermissions.values()) {
7006 writePermission(serializer, bp);
7007 }
7008 serializer.endTag(null, "permissions");
7009
7010 for (PackageSetting pkg : mPackages.values()) {
7011 writePackage(serializer, pkg);
7012 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007014 for (PackageSetting pkg : mDisabledSysPackages.values()) {
7015 writeDisabledSysPackage(serializer, pkg);
7016 }
7017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007018 serializer.startTag(null, "preferred-activities");
7019 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
7020 serializer.startTag(null, "item");
7021 pa.writeToXml(serializer);
7022 serializer.endTag(null, "item");
7023 }
7024 serializer.endTag(null, "preferred-activities");
7025
7026 for (SharedUserSetting usr : mSharedUsers.values()) {
7027 serializer.startTag(null, "shared-user");
7028 serializer.attribute(null, "name", usr.name);
7029 serializer.attribute(null, "userId",
7030 Integer.toString(usr.userId));
7031 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
7032 serializer.startTag(null, "perms");
7033 for (String name : usr.grantedPermissions) {
7034 serializer.startTag(null, "item");
7035 serializer.attribute(null, "name", name);
7036 serializer.endTag(null, "item");
7037 }
7038 serializer.endTag(null, "perms");
7039 serializer.endTag(null, "shared-user");
7040 }
7041
7042 serializer.endTag(null, "packages");
7043
7044 serializer.endDocument();
7045
7046 str.flush();
7047 str.close();
7048
7049 // New settings successfully written, old ones are no longer
7050 // needed.
7051 mBackupSettingsFilename.delete();
7052 FileUtils.setPermissions(mSettingsFilename.toString(),
7053 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7054 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7055 |FileUtils.S_IROTH,
7056 -1, -1);
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007057 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007058
7059 } catch(XmlPullParserException e) {
7060 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007061 } catch(java.io.IOException e) {
7062 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007063 }
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007064 // Clean up partially written file
7065 if (mSettingsFilename.exists()) {
7066 if (!mSettingsFilename.delete()) {
7067 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
7068 }
7069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007070 //Debug.stopMethodTracing();
7071 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007072
7073 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007074 throws java.io.IOException {
7075 serializer.startTag(null, "updated-package");
7076 serializer.attribute(null, "name", pkg.name);
7077 serializer.attribute(null, "codePath", pkg.codePathString);
7078 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007079 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007080 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7081 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7082 }
7083 if (pkg.sharedUser == null) {
7084 serializer.attribute(null, "userId",
7085 Integer.toString(pkg.userId));
7086 } else {
7087 serializer.attribute(null, "sharedUserId",
7088 Integer.toString(pkg.userId));
7089 }
7090 serializer.startTag(null, "perms");
7091 if (pkg.sharedUser == null) {
7092 // If this is a shared user, the permissions will
7093 // be written there. We still need to write an
7094 // empty permissions list so permissionsFixed will
7095 // be set.
7096 for (final String name : pkg.grantedPermissions) {
7097 BasePermission bp = mPermissions.get(name);
7098 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
7099 // We only need to write signature or system permissions but this wont
7100 // match the semantics of grantedPermissions. So write all permissions.
7101 serializer.startTag(null, "item");
7102 serializer.attribute(null, "name", name);
7103 serializer.endTag(null, "item");
7104 }
7105 }
7106 }
7107 serializer.endTag(null, "perms");
7108 serializer.endTag(null, "updated-package");
7109 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007110
7111 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007112 throws java.io.IOException {
7113 serializer.startTag(null, "package");
7114 serializer.attribute(null, "name", pkg.name);
7115 serializer.attribute(null, "codePath", pkg.codePathString);
7116 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7117 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7118 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007119 serializer.attribute(null, "flags",
7120 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007121 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007122 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007123 if (pkg.sharedUser == null) {
7124 serializer.attribute(null, "userId",
7125 Integer.toString(pkg.userId));
7126 } else {
7127 serializer.attribute(null, "sharedUserId",
7128 Integer.toString(pkg.userId));
7129 }
7130 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
7131 serializer.attribute(null, "enabled",
7132 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
7133 ? "true" : "false");
7134 }
7135 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
7136 serializer.attribute(null, "installStatus", "false");
7137 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007138 if (pkg.installerPackageName != null) {
7139 serializer.attribute(null, "installer", pkg.installerPackageName);
7140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007141 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
7142 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7143 serializer.startTag(null, "perms");
7144 if (pkg.sharedUser == null) {
7145 // If this is a shared user, the permissions will
7146 // be written there. We still need to write an
7147 // empty permissions list so permissionsFixed will
7148 // be set.
7149 for (final String name : pkg.grantedPermissions) {
7150 serializer.startTag(null, "item");
7151 serializer.attribute(null, "name", name);
7152 serializer.endTag(null, "item");
7153 }
7154 }
7155 serializer.endTag(null, "perms");
7156 }
7157 if (pkg.disabledComponents.size() > 0) {
7158 serializer.startTag(null, "disabled-components");
7159 for (final String name : pkg.disabledComponents) {
7160 serializer.startTag(null, "item");
7161 serializer.attribute(null, "name", name);
7162 serializer.endTag(null, "item");
7163 }
7164 serializer.endTag(null, "disabled-components");
7165 }
7166 if (pkg.enabledComponents.size() > 0) {
7167 serializer.startTag(null, "enabled-components");
7168 for (final String name : pkg.enabledComponents) {
7169 serializer.startTag(null, "item");
7170 serializer.attribute(null, "name", name);
7171 serializer.endTag(null, "item");
7172 }
7173 serializer.endTag(null, "enabled-components");
7174 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007176 serializer.endTag(null, "package");
7177 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007179 void writePermission(XmlSerializer serializer, BasePermission bp)
7180 throws XmlPullParserException, java.io.IOException {
7181 if (bp.type != BasePermission.TYPE_BUILTIN
7182 && bp.sourcePackage != null) {
7183 serializer.startTag(null, "item");
7184 serializer.attribute(null, "name", bp.name);
7185 serializer.attribute(null, "package", bp.sourcePackage);
7186 if (DEBUG_SETTINGS) Log.v(TAG,
7187 "Writing perm: name=" + bp.name + " type=" + bp.type);
7188 if (bp.type == BasePermission.TYPE_DYNAMIC) {
7189 PermissionInfo pi = bp.perm != null ? bp.perm.info
7190 : bp.pendingInfo;
7191 if (pi != null) {
7192 serializer.attribute(null, "type", "dynamic");
7193 if (pi.icon != 0) {
7194 serializer.attribute(null, "icon",
7195 Integer.toString(pi.icon));
7196 }
7197 if (pi.nonLocalizedLabel != null) {
7198 serializer.attribute(null, "label",
7199 pi.nonLocalizedLabel.toString());
7200 }
7201 if (pi.protectionLevel !=
7202 PermissionInfo.PROTECTION_NORMAL) {
7203 serializer.attribute(null, "protection",
7204 Integer.toString(pi.protectionLevel));
7205 }
7206 }
7207 }
7208 serializer.endTag(null, "item");
7209 }
7210 }
7211
7212 String getReadMessagesLP() {
7213 return mReadMessages.toString();
7214 }
7215
Oscar Montemayora8529f62009-11-18 10:14:20 -08007216 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007217 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
7218 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007219 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007220 while(its.hasNext()) {
7221 String key = its.next();
7222 PackageSetting ps = mPackages.get(key);
7223 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08007224 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007225 }
7226 }
7227 return ret;
7228 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007230 boolean readLP() {
7231 FileInputStream str = null;
7232 if (mBackupSettingsFilename.exists()) {
7233 try {
7234 str = new FileInputStream(mBackupSettingsFilename);
7235 mReadMessages.append("Reading from backup settings file\n");
7236 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007237 if (mSettingsFilename.exists()) {
7238 // If both the backup and settings file exist, we
7239 // ignore the settings since it might have been
7240 // corrupted.
7241 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
7242 mSettingsFilename.delete();
7243 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007244 } catch (java.io.IOException e) {
7245 // We'll try for the normal settings file.
7246 }
7247 }
7248
7249 mPastSignatures.clear();
7250
7251 try {
7252 if (str == null) {
7253 if (!mSettingsFilename.exists()) {
7254 mReadMessages.append("No settings file found\n");
7255 Log.i(TAG, "No current settings file!");
7256 return false;
7257 }
7258 str = new FileInputStream(mSettingsFilename);
7259 }
7260 XmlPullParser parser = Xml.newPullParser();
7261 parser.setInput(str, null);
7262
7263 int type;
7264 while ((type=parser.next()) != XmlPullParser.START_TAG
7265 && type != XmlPullParser.END_DOCUMENT) {
7266 ;
7267 }
7268
7269 if (type != XmlPullParser.START_TAG) {
7270 mReadMessages.append("No start tag found in settings file\n");
7271 Log.e(TAG, "No start tag found in package manager settings");
7272 return false;
7273 }
7274
7275 int outerDepth = parser.getDepth();
7276 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7277 && (type != XmlPullParser.END_TAG
7278 || parser.getDepth() > outerDepth)) {
7279 if (type == XmlPullParser.END_TAG
7280 || type == XmlPullParser.TEXT) {
7281 continue;
7282 }
7283
7284 String tagName = parser.getName();
7285 if (tagName.equals("package")) {
7286 readPackageLP(parser);
7287 } else if (tagName.equals("permissions")) {
7288 readPermissionsLP(mPermissions, parser);
7289 } else if (tagName.equals("permission-trees")) {
7290 readPermissionsLP(mPermissionTrees, parser);
7291 } else if (tagName.equals("shared-user")) {
7292 readSharedUserLP(parser);
7293 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08007294 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007295 } else if (tagName.equals("preferred-activities")) {
7296 readPreferredActivitiesLP(parser);
7297 } else if(tagName.equals("updated-package")) {
7298 readDisabledSysPackageLP(parser);
7299 } else {
7300 Log.w(TAG, "Unknown element under <packages>: "
7301 + parser.getName());
7302 XmlUtils.skipCurrentTag(parser);
7303 }
7304 }
7305
7306 str.close();
7307
7308 } catch(XmlPullParserException e) {
7309 mReadMessages.append("Error reading: " + e.toString());
7310 Log.e(TAG, "Error reading package manager settings", e);
7311
7312 } catch(java.io.IOException e) {
7313 mReadMessages.append("Error reading: " + e.toString());
7314 Log.e(TAG, "Error reading package manager settings", e);
7315
7316 }
7317
7318 int N = mPendingPackages.size();
7319 for (int i=0; i<N; i++) {
7320 final PendingPackage pp = mPendingPackages.get(i);
7321 Object idObj = getUserIdLP(pp.sharedId);
7322 if (idObj != null && idObj instanceof SharedUserSetting) {
7323 PackageSetting p = getPackageLP(pp.name,
7324 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007325 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007326 if (p == null) {
7327 Log.w(TAG, "Unable to create application package for "
7328 + pp.name);
7329 continue;
7330 }
7331 p.copyFrom(pp);
7332 } else if (idObj != null) {
7333 String msg = "Bad package setting: package " + pp.name
7334 + " has shared uid " + pp.sharedId
7335 + " that is not a shared uid\n";
7336 mReadMessages.append(msg);
7337 Log.e(TAG, msg);
7338 } else {
7339 String msg = "Bad package setting: package " + pp.name
7340 + " has shared uid " + pp.sharedId
7341 + " that is not defined\n";
7342 mReadMessages.append(msg);
7343 Log.e(TAG, msg);
7344 }
7345 }
7346 mPendingPackages.clear();
7347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007348 mReadMessages.append("Read completed successfully: "
7349 + mPackages.size() + " packages, "
7350 + mSharedUsers.size() + " shared uids\n");
7351
7352 return true;
7353 }
7354
7355 private int readInt(XmlPullParser parser, String ns, String name,
7356 int defValue) {
7357 String v = parser.getAttributeValue(ns, name);
7358 try {
7359 if (v == null) {
7360 return defValue;
7361 }
7362 return Integer.parseInt(v);
7363 } catch (NumberFormatException e) {
7364 reportSettingsProblem(Log.WARN,
7365 "Error in package manager settings: attribute " +
7366 name + " has bad integer value " + v + " at "
7367 + parser.getPositionDescription());
7368 }
7369 return defValue;
7370 }
7371
7372 private void readPermissionsLP(HashMap<String, BasePermission> out,
7373 XmlPullParser parser)
7374 throws IOException, XmlPullParserException {
7375 int outerDepth = parser.getDepth();
7376 int type;
7377 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7378 && (type != XmlPullParser.END_TAG
7379 || parser.getDepth() > outerDepth)) {
7380 if (type == XmlPullParser.END_TAG
7381 || type == XmlPullParser.TEXT) {
7382 continue;
7383 }
7384
7385 String tagName = parser.getName();
7386 if (tagName.equals("item")) {
7387 String name = parser.getAttributeValue(null, "name");
7388 String sourcePackage = parser.getAttributeValue(null, "package");
7389 String ptype = parser.getAttributeValue(null, "type");
7390 if (name != null && sourcePackage != null) {
7391 boolean dynamic = "dynamic".equals(ptype);
7392 BasePermission bp = new BasePermission(name, sourcePackage,
7393 dynamic
7394 ? BasePermission.TYPE_DYNAMIC
7395 : BasePermission.TYPE_NORMAL);
7396 if (dynamic) {
7397 PermissionInfo pi = new PermissionInfo();
7398 pi.packageName = sourcePackage.intern();
7399 pi.name = name.intern();
7400 pi.icon = readInt(parser, null, "icon", 0);
7401 pi.nonLocalizedLabel = parser.getAttributeValue(
7402 null, "label");
7403 pi.protectionLevel = readInt(parser, null, "protection",
7404 PermissionInfo.PROTECTION_NORMAL);
7405 bp.pendingInfo = pi;
7406 }
7407 out.put(bp.name, bp);
7408 } else {
7409 reportSettingsProblem(Log.WARN,
7410 "Error in package manager settings: permissions has"
7411 + " no name at " + parser.getPositionDescription());
7412 }
7413 } else {
7414 reportSettingsProblem(Log.WARN,
7415 "Unknown element reading permissions: "
7416 + parser.getName() + " at "
7417 + parser.getPositionDescription());
7418 }
7419 XmlUtils.skipCurrentTag(parser);
7420 }
7421 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007423 private void readDisabledSysPackageLP(XmlPullParser parser)
7424 throws XmlPullParserException, IOException {
7425 String name = parser.getAttributeValue(null, "name");
7426 String codePathStr = parser.getAttributeValue(null, "codePath");
7427 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
7428 if(resourcePathStr == null) {
7429 resourcePathStr = codePathStr;
7430 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007431 String version = parser.getAttributeValue(null, "version");
7432 int versionCode = 0;
7433 if (version != null) {
7434 try {
7435 versionCode = Integer.parseInt(version);
7436 } catch (NumberFormatException e) {
7437 }
7438 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007440 int pkgFlags = 0;
7441 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007442 PackageSetting ps = new PackageSetting(name,
7443 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007444 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007445 String timeStampStr = parser.getAttributeValue(null, "ts");
7446 if (timeStampStr != null) {
7447 try {
7448 long timeStamp = Long.parseLong(timeStampStr);
7449 ps.setTimeStamp(timeStamp, timeStampStr);
7450 } catch (NumberFormatException e) {
7451 }
7452 }
7453 String idStr = parser.getAttributeValue(null, "userId");
7454 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
7455 if(ps.userId <= 0) {
7456 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7457 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
7458 }
7459 int outerDepth = parser.getDepth();
7460 int type;
7461 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7462 && (type != XmlPullParser.END_TAG
7463 || parser.getDepth() > outerDepth)) {
7464 if (type == XmlPullParser.END_TAG
7465 || type == XmlPullParser.TEXT) {
7466 continue;
7467 }
7468
7469 String tagName = parser.getName();
7470 if (tagName.equals("perms")) {
7471 readGrantedPermissionsLP(parser,
7472 ps.grantedPermissions);
7473 } else {
7474 reportSettingsProblem(Log.WARN,
7475 "Unknown element under <updated-package>: "
7476 + parser.getName());
7477 XmlUtils.skipCurrentTag(parser);
7478 }
7479 }
7480 mDisabledSysPackages.put(name, ps);
7481 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007483 private void readPackageLP(XmlPullParser parser)
7484 throws XmlPullParserException, IOException {
7485 String name = null;
7486 String idStr = null;
7487 String sharedIdStr = null;
7488 String codePathStr = null;
7489 String resourcePathStr = null;
7490 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02007491 String installerPackageName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007492 int pkgFlags = 0;
7493 String timeStampStr;
7494 long timeStamp = 0;
7495 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007496 String version = null;
7497 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007498 try {
7499 name = parser.getAttributeValue(null, "name");
7500 idStr = parser.getAttributeValue(null, "userId");
7501 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7502 codePathStr = parser.getAttributeValue(null, "codePath");
7503 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007504 version = parser.getAttributeValue(null, "version");
7505 if (version != null) {
7506 try {
7507 versionCode = Integer.parseInt(version);
7508 } catch (NumberFormatException e) {
7509 }
7510 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007511 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007512
7513 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007514 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007515 try {
7516 pkgFlags = Integer.parseInt(systemStr);
7517 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007518 }
7519 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007520 // For backward compatibility
7521 systemStr = parser.getAttributeValue(null, "system");
7522 if (systemStr != null) {
7523 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
7524 } else {
7525 // Old settings that don't specify system... just treat
7526 // them as system, good enough.
7527 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007529 }
7530 timeStampStr = parser.getAttributeValue(null, "ts");
7531 if (timeStampStr != null) {
7532 try {
7533 timeStamp = Long.parseLong(timeStampStr);
7534 } catch (NumberFormatException e) {
7535 }
7536 }
7537 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
7538 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
7539 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7540 if (resourcePathStr == null) {
7541 resourcePathStr = codePathStr;
7542 }
7543 if (name == null) {
7544 reportSettingsProblem(Log.WARN,
7545 "Error in package manager settings: <package> has no name at "
7546 + parser.getPositionDescription());
7547 } else if (codePathStr == null) {
7548 reportSettingsProblem(Log.WARN,
7549 "Error in package manager settings: <package> has no codePath at "
7550 + parser.getPositionDescription());
7551 } else if (userId > 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007552 packageSetting = addPackageLP(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007553 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007554 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7555 + ": userId=" + userId + " pkg=" + packageSetting);
7556 if (packageSetting == null) {
7557 reportSettingsProblem(Log.ERROR,
7558 "Failure adding uid " + userId
7559 + " while parsing settings at "
7560 + parser.getPositionDescription());
7561 } else {
7562 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7563 }
7564 } else if (sharedIdStr != null) {
7565 userId = sharedIdStr != null
7566 ? Integer.parseInt(sharedIdStr) : 0;
7567 if (userId > 0) {
7568 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007569 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007570 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7571 mPendingPackages.add((PendingPackage) packageSetting);
7572 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7573 + ": sharedUserId=" + userId + " pkg="
7574 + packageSetting);
7575 } else {
7576 reportSettingsProblem(Log.WARN,
7577 "Error in package manager settings: package "
7578 + name + " has bad sharedId " + sharedIdStr
7579 + " at " + parser.getPositionDescription());
7580 }
7581 } else {
7582 reportSettingsProblem(Log.WARN,
7583 "Error in package manager settings: package "
7584 + name + " has bad userId " + idStr + " at "
7585 + parser.getPositionDescription());
7586 }
7587 } catch (NumberFormatException e) {
7588 reportSettingsProblem(Log.WARN,
7589 "Error in package manager settings: package "
7590 + name + " has bad userId " + idStr + " at "
7591 + parser.getPositionDescription());
7592 }
7593 if (packageSetting != null) {
Jacek Surazski65e13172009-04-28 15:26:38 +02007594 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007595 final String enabledStr = parser.getAttributeValue(null, "enabled");
7596 if (enabledStr != null) {
7597 if (enabledStr.equalsIgnoreCase("true")) {
7598 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
7599 } else if (enabledStr.equalsIgnoreCase("false")) {
7600 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
7601 } else if (enabledStr.equalsIgnoreCase("default")) {
7602 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7603 } else {
7604 reportSettingsProblem(Log.WARN,
7605 "Error in package manager settings: package "
7606 + name + " has bad enabled value: " + idStr
7607 + " at " + parser.getPositionDescription());
7608 }
7609 } else {
7610 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7611 }
7612 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
7613 if (installStatusStr != null) {
7614 if (installStatusStr.equalsIgnoreCase("false")) {
7615 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
7616 } else {
7617 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
7618 }
7619 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007621 int outerDepth = parser.getDepth();
7622 int type;
7623 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7624 && (type != XmlPullParser.END_TAG
7625 || parser.getDepth() > outerDepth)) {
7626 if (type == XmlPullParser.END_TAG
7627 || type == XmlPullParser.TEXT) {
7628 continue;
7629 }
7630
7631 String tagName = parser.getName();
7632 if (tagName.equals("disabled-components")) {
7633 readDisabledComponentsLP(packageSetting, parser);
7634 } else if (tagName.equals("enabled-components")) {
7635 readEnabledComponentsLP(packageSetting, parser);
7636 } else if (tagName.equals("sigs")) {
7637 packageSetting.signatures.readXml(parser, mPastSignatures);
7638 } else if (tagName.equals("perms")) {
7639 readGrantedPermissionsLP(parser,
7640 packageSetting.loadedPermissions);
7641 packageSetting.permissionsFixed = true;
7642 } else {
7643 reportSettingsProblem(Log.WARN,
7644 "Unknown element under <package>: "
7645 + parser.getName());
7646 XmlUtils.skipCurrentTag(parser);
7647 }
7648 }
7649 } else {
7650 XmlUtils.skipCurrentTag(parser);
7651 }
7652 }
7653
7654 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
7655 XmlPullParser parser)
7656 throws IOException, XmlPullParserException {
7657 int outerDepth = parser.getDepth();
7658 int type;
7659 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7660 && (type != XmlPullParser.END_TAG
7661 || parser.getDepth() > outerDepth)) {
7662 if (type == XmlPullParser.END_TAG
7663 || type == XmlPullParser.TEXT) {
7664 continue;
7665 }
7666
7667 String tagName = parser.getName();
7668 if (tagName.equals("item")) {
7669 String name = parser.getAttributeValue(null, "name");
7670 if (name != null) {
7671 packageSetting.disabledComponents.add(name.intern());
7672 } else {
7673 reportSettingsProblem(Log.WARN,
7674 "Error in package manager settings: <disabled-components> has"
7675 + " no name at " + parser.getPositionDescription());
7676 }
7677 } else {
7678 reportSettingsProblem(Log.WARN,
7679 "Unknown element under <disabled-components>: "
7680 + parser.getName());
7681 }
7682 XmlUtils.skipCurrentTag(parser);
7683 }
7684 }
7685
7686 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
7687 XmlPullParser parser)
7688 throws IOException, XmlPullParserException {
7689 int outerDepth = parser.getDepth();
7690 int type;
7691 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7692 && (type != XmlPullParser.END_TAG
7693 || parser.getDepth() > outerDepth)) {
7694 if (type == XmlPullParser.END_TAG
7695 || type == XmlPullParser.TEXT) {
7696 continue;
7697 }
7698
7699 String tagName = parser.getName();
7700 if (tagName.equals("item")) {
7701 String name = parser.getAttributeValue(null, "name");
7702 if (name != null) {
7703 packageSetting.enabledComponents.add(name.intern());
7704 } else {
7705 reportSettingsProblem(Log.WARN,
7706 "Error in package manager settings: <enabled-components> has"
7707 + " no name at " + parser.getPositionDescription());
7708 }
7709 } else {
7710 reportSettingsProblem(Log.WARN,
7711 "Unknown element under <enabled-components>: "
7712 + parser.getName());
7713 }
7714 XmlUtils.skipCurrentTag(parser);
7715 }
7716 }
7717
7718 private void readSharedUserLP(XmlPullParser parser)
7719 throws XmlPullParserException, IOException {
7720 String name = null;
7721 String idStr = null;
7722 int pkgFlags = 0;
7723 SharedUserSetting su = null;
7724 try {
7725 name = parser.getAttributeValue(null, "name");
7726 idStr = parser.getAttributeValue(null, "userId");
7727 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7728 if ("true".equals(parser.getAttributeValue(null, "system"))) {
7729 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7730 }
7731 if (name == null) {
7732 reportSettingsProblem(Log.WARN,
7733 "Error in package manager settings: <shared-user> has no name at "
7734 + parser.getPositionDescription());
7735 } else if (userId == 0) {
7736 reportSettingsProblem(Log.WARN,
7737 "Error in package manager settings: shared-user "
7738 + name + " has bad userId " + idStr + " at "
7739 + parser.getPositionDescription());
7740 } else {
7741 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
7742 reportSettingsProblem(Log.ERROR,
7743 "Occurred while parsing settings at "
7744 + parser.getPositionDescription());
7745 }
7746 }
7747 } catch (NumberFormatException e) {
7748 reportSettingsProblem(Log.WARN,
7749 "Error in package manager settings: package "
7750 + name + " has bad userId " + idStr + " at "
7751 + parser.getPositionDescription());
7752 };
7753
7754 if (su != null) {
7755 int outerDepth = parser.getDepth();
7756 int type;
7757 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7758 && (type != XmlPullParser.END_TAG
7759 || parser.getDepth() > outerDepth)) {
7760 if (type == XmlPullParser.END_TAG
7761 || type == XmlPullParser.TEXT) {
7762 continue;
7763 }
7764
7765 String tagName = parser.getName();
7766 if (tagName.equals("sigs")) {
7767 su.signatures.readXml(parser, mPastSignatures);
7768 } else if (tagName.equals("perms")) {
7769 readGrantedPermissionsLP(parser, su.loadedPermissions);
7770 } else {
7771 reportSettingsProblem(Log.WARN,
7772 "Unknown element under <shared-user>: "
7773 + parser.getName());
7774 XmlUtils.skipCurrentTag(parser);
7775 }
7776 }
7777
7778 } else {
7779 XmlUtils.skipCurrentTag(parser);
7780 }
7781 }
7782
7783 private void readGrantedPermissionsLP(XmlPullParser parser,
7784 HashSet<String> outPerms) throws IOException, XmlPullParserException {
7785 int outerDepth = parser.getDepth();
7786 int type;
7787 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7788 && (type != XmlPullParser.END_TAG
7789 || parser.getDepth() > outerDepth)) {
7790 if (type == XmlPullParser.END_TAG
7791 || type == XmlPullParser.TEXT) {
7792 continue;
7793 }
7794
7795 String tagName = parser.getName();
7796 if (tagName.equals("item")) {
7797 String name = parser.getAttributeValue(null, "name");
7798 if (name != null) {
7799 outPerms.add(name.intern());
7800 } else {
7801 reportSettingsProblem(Log.WARN,
7802 "Error in package manager settings: <perms> has"
7803 + " no name at " + parser.getPositionDescription());
7804 }
7805 } else {
7806 reportSettingsProblem(Log.WARN,
7807 "Unknown element under <perms>: "
7808 + parser.getName());
7809 }
7810 XmlUtils.skipCurrentTag(parser);
7811 }
7812 }
7813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007814 private void readPreferredActivitiesLP(XmlPullParser parser)
7815 throws XmlPullParserException, IOException {
7816 int outerDepth = parser.getDepth();
7817 int type;
7818 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7819 && (type != XmlPullParser.END_TAG
7820 || parser.getDepth() > outerDepth)) {
7821 if (type == XmlPullParser.END_TAG
7822 || type == XmlPullParser.TEXT) {
7823 continue;
7824 }
7825
7826 String tagName = parser.getName();
7827 if (tagName.equals("item")) {
7828 PreferredActivity pa = new PreferredActivity(parser);
7829 if (pa.mParseError == null) {
7830 mPreferredActivities.addFilter(pa);
7831 } else {
7832 reportSettingsProblem(Log.WARN,
7833 "Error in package manager settings: <preferred-activity> "
7834 + pa.mParseError + " at "
7835 + parser.getPositionDescription());
7836 }
7837 } else {
7838 reportSettingsProblem(Log.WARN,
7839 "Unknown element under <preferred-activities>: "
7840 + parser.getName());
7841 XmlUtils.skipCurrentTag(parser);
7842 }
7843 }
7844 }
7845
7846 // Returns -1 if we could not find an available UserId to assign
7847 private int newUserIdLP(Object obj) {
7848 // Let's be stupidly inefficient for now...
7849 final int N = mUserIds.size();
7850 for (int i=0; i<N; i++) {
7851 if (mUserIds.get(i) == null) {
7852 mUserIds.set(i, obj);
7853 return FIRST_APPLICATION_UID + i;
7854 }
7855 }
7856
7857 // None left?
7858 if (N >= MAX_APPLICATION_UIDS) {
7859 return -1;
7860 }
7861
7862 mUserIds.add(obj);
7863 return FIRST_APPLICATION_UID + N;
7864 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007866 public PackageSetting getDisabledSystemPkg(String name) {
7867 synchronized(mPackages) {
7868 PackageSetting ps = mDisabledSysPackages.get(name);
7869 return ps;
7870 }
7871 }
7872
7873 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
7874 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
7875 if (Config.LOGV) {
7876 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
7877 + " componentName = " + componentInfo.name);
7878 Log.v(TAG, "enabledComponents: "
7879 + Arrays.toString(packageSettings.enabledComponents.toArray()));
7880 Log.v(TAG, "disabledComponents: "
7881 + Arrays.toString(packageSettings.disabledComponents.toArray()));
7882 }
7883 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
7884 || ((componentInfo.enabled
7885 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
7886 || (componentInfo.applicationInfo.enabled
7887 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
7888 && !packageSettings.disabledComponents.contains(componentInfo.name))
7889 || packageSettings.enabledComponents.contains(componentInfo.name));
7890 }
7891 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007892
7893 // ------- apps on sdcard specific code -------
7894 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08007895 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08007896 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007897 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007898 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007899
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007900
7901 static MountService getMountService() {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007902 return (MountService) ServiceManager.getService("mount");
7903 }
7904
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007905 private String getEncryptKey() {
7906 try {
7907 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
7908 if (sdEncKey == null) {
7909 sdEncKey = SystemKeyStore.getInstance().
7910 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
7911 if (sdEncKey == null) {
7912 Log.e(TAG, "Failed to create encryption keys");
7913 return null;
7914 }
7915 }
7916 return sdEncKey;
7917 } catch (NoSuchAlgorithmException nsae) {
7918 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
7919 return null;
7920 }
7921 }
7922
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007923 private String createSdDir(File tmpPackageFile, String pkgName) {
7924 // Create mount point via MountService
7925 MountService mountService = getMountService();
7926 long len = tmpPackageFile.length();
7927 int mbLen = (int) (len/(1024*1024));
7928 if ((len - (mbLen * 1024 * 1024)) > 0) {
7929 mbLen++;
7930 }
7931 if (DEBUG_SD_INSTALL) Log.i(TAG, "mbLen="+mbLen);
7932 String cachePath = null;
Oscar Montemayord02546b2010-01-14 16:38:40 -08007933 String sdEncKey;
7934 try {
7935 sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
7936 if (sdEncKey == null) {
7937 sdEncKey = SystemKeyStore.getInstance().
7938 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
7939 if (sdEncKey == null) {
7940 Log.e(TAG, "Failed to create encryption keys for package: " + pkgName + ".");
7941 return null;
7942 }
7943 }
7944 } catch (NoSuchAlgorithmException nsae) {
7945 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
7946 return null;
7947 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007948 try {
7949 cachePath = mountService.createSecureContainer(pkgName,
7950 mbLen,
Oscar Montemayord02546b2010-01-14 16:38:40 -08007951 "vfat", sdEncKey, Process.SYSTEM_UID);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007952 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install " + pkgName + ", cachePath =" + cachePath);
7953 return cachePath;
7954 } catch(IllegalStateException e) {
7955 Log.e(TAG, "Failed to create storage on sdcard with exception: " + e);
7956 }
7957 // TODO just fail here and let the user delete later on.
7958 try {
7959 mountService.destroySecureContainer(pkgName);
7960 if (DEBUG_SD_INSTALL) Log.i(TAG, "Destroying cache for " + pkgName + ", cachePath =" + cachePath);
7961 } catch(IllegalStateException e) {
7962 Log.e(TAG, "Failed to destroy existing cache: " + e);
7963 return null;
7964 }
7965 try {
7966 cachePath = mountService.createSecureContainer(pkgName,
7967 mbLen,
Oscar Montemayord02546b2010-01-14 16:38:40 -08007968 "vfat", sdEncKey, Process.SYSTEM_UID);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007969 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install again " + pkgName + ", cachePath =" + cachePath);
7970 return cachePath;
7971 } catch(IllegalStateException e) {
7972 Log.e(TAG, "Failed to create storage on sdcard with exception: " + e);
7973 return null;
7974 }
7975 }
7976
7977 private String mountSdDir(String pkgName, int ownerUid) {
Oscar Montemayord02546b2010-01-14 16:38:40 -08007978 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
7979 if (sdEncKey == null) {
7980 Log.e(TAG, "Failed to retrieve encryption keys to mount package code: " + pkgName + ".");
7981 return null;
7982 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007983 try {
Oscar Montemayord02546b2010-01-14 16:38:40 -08007984 return getMountService().mountSecureContainer(pkgName, sdEncKey, ownerUid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007985 } catch (IllegalStateException e) {
7986 Log.i(TAG, "Failed to mount container for pkg : " + pkgName + " exception : " + e);
7987 }
7988 return null;
7989 }
7990
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007991 private boolean unMountSdDir(String pkgName) {
7992 // STOPSHIP unmount directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007993 try {
7994 getMountService().unmountSecureContainer(pkgName);
7995 return true;
7996 } catch (IllegalStateException e) {
7997 Log.e(TAG, "Failed to unmount : " + pkgName + " with exception " + e);
7998 }
7999 return false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008000 }
8001
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008002 private String getSdDir(String pkgName) {
8003 String cachePath = null;
8004 try {
8005 cachePath = getMountService().getSecureContainerPath(pkgName);
8006 } catch (IllegalStateException e) {
8007 Log.e(TAG, "Failed to retrieve secure container path for pkg : " + pkgName + " with exception " + e);
8008 }
8009 return cachePath;
8010 }
8011
8012 private boolean finalizeSdDir(String pkgName) {
8013 try {
8014 getMountService().finalizeSecureContainer(pkgName);
8015 return true;
8016 } catch (IllegalStateException e) {
8017 Log.i(TAG, "Failed to destroy container for pkg : " + pkgName);
8018 return false;
8019 }
8020 }
8021
8022 private boolean destroySdDir(String pkgName) {
8023 try {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008024 // We need to destroy right away
8025 getMountService().destroySecureContainer(pkgName);
8026 return true;
8027 } catch (IllegalStateException e) {
8028 Log.i(TAG, "Failed to destroy container for pkg : " + pkgName);
8029 return false;
8030 }
8031 }
8032
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008033 static String[] getSecureContainerList() {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008034 try {
8035 return getMountService().getSecureContainerList();
8036 } catch (IllegalStateException e) {
8037 Log.i(TAG, "Failed to getSecureContainerList");
8038 }
8039 return null;
8040 }
8041
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008042 static String getTempContainerId() {
8043 String prefix = "smdl1tmp";
8044 int tmpIdx = 1;
8045 String list[] = getSecureContainerList();
8046 if (list != null) {
8047 int idx = 0;
8048 int idList[] = new int[MAX_CONTAINERS];
8049 boolean neverFound = true;
8050 for (String name : list) {
8051 // Ignore null entries
8052 if (name == null) {
8053 continue;
8054 }
8055 int sidx = name.indexOf(prefix);
8056 if (sidx == -1) {
8057 // Not a temp file. just ignore
8058 continue;
8059 }
8060 String subStr = name.substring(sidx + prefix.length());
8061 idList[idx] = -1;
8062 if (subStr != null) {
8063 try {
8064 int cid = Integer.parseInt(subStr);
8065 idList[idx++] = cid;
8066 neverFound = false;
8067 } catch (NumberFormatException e) {
8068 }
8069 }
8070 }
8071 if (!neverFound) {
8072 // Sort idList
8073 Arrays.sort(idList);
8074 for (int j = 1; j <= idList.length; j++) {
8075 if (idList[j-1] != j) {
8076 tmpIdx = j;
8077 break;
8078 }
8079 }
8080 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008081 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008082 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008083 }
8084
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008085 public void updateExternalMediaStatus(final boolean mediaStatus) {
8086 if (mediaStatus == mMediaMounted) {
8087 return;
8088 }
8089 mMediaMounted = mediaStatus;
8090 // Queue up an async operation since the package installation may take a little while.
8091 mHandler.post(new Runnable() {
8092 public void run() {
8093 mHandler.removeCallbacks(this);
8094 final String list[] = getSecureContainerList();
8095 if (list == null || list.length == 0) {
8096 return;
8097 }
8098 for (int i = 0; i < list.length; i++) {
8099 String mountPkg = list[i];
8100 // TODO compare with default package
8101 synchronized (mPackages) {
8102 PackageSetting ps = mSettings.mPackages.get(mountPkg);
8103 if (ps != null && (ps.pkgFlags & ApplicationInfo.FLAG_ON_SDCARD) != 0) {
8104 if (mediaStatus) {
8105 String pkgPath = getSdDir(mountPkg);
8106 if (pkgPath == null) {
8107 continue;
8108 }
8109 pkgPath = ps.codePathString;
8110 int parseFlags = PackageParser.PARSE_CHATTY |
8111 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
8112 PackageParser pp = new PackageParser(pkgPath);
8113 pp.setSeparateProcesses(mSeparateProcesses);
8114 final PackageParser.Package pkg = pp.parsePackage(new File(pkgPath),
8115 null, mMetrics, parseFlags);
8116 if (pkg == null) {
8117 Log.w(TAG, "Failed to install package : " + mountPkg + " from sd card");
8118 continue;
8119 }
8120 int scanMode = SCAN_MONITOR;
8121 // Scan the package
8122 if (scanPackageLI(pkg, parseFlags, scanMode) != null) {
8123 // Grant permissions
8124 grantPermissionsLP(pkg, false);
8125 // Persist settings
8126 mSettings.writeLP();
8127 } else {
8128 Log.i(TAG, "Failed to install package: " + mountPkg + " from sdcard");
8129 }
8130 } else {
8131 // Delete package
8132 PackageRemovedInfo outInfo = new PackageRemovedInfo();
8133 boolean res = deletePackageLI(mountPkg, false, PackageManager.DONT_DELETE_DATA, outInfo);
8134 if (!res) {
8135 Log.e(TAG, "Failed to delete pkg from sdcard : " + mountPkg);
8136 }
8137 }
8138 }
8139 }
8140 }
8141 }
8142 });
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008144}